from django.http import HttpResponse, HttpResponseServerError
from django.views.generic import TemplateView, View

import json

from rdflib import Graph, RDFS, URIRef, Literal

from utils import JSONResponseMixin, get_env
from services import FASTService, VIVOService

#Setup a triple store
# from backend import SQLiteBackend
# tstore =SQLiteBackend()
from backend import VivoBackend
ep = get_env('ENDPOINT')
tstore = VivoBackend(ep)

from backend import D, VIVO, RDF
from display import organization, person

class ResourceView(View):
    """
    Handle edits posted by the rich text and tagging widgets..
    """
    def post(self, *args, **kwargs):
        posted = self.request.POST
        edit = json.loads(posted.get('edit'))
        if edit.get('type') == 'ck':
            add_stmts = edit['add']
            add_g = tstore.make_edit_graph(add_stmts)
            subtract_g = tstore.get_subtract_graph(add_stmts)
        elif edit.get('type') in [u'multi-tag']:
            add_stmts = edit.get('add')
            if (add_stmts is not None) and (add_stmts != {}):
                add_g = Graph()
                if add_stmts['object'] == u'new':
                    uri, g = tstore.create_resource(
                        add_stmts['range'],
                        add_stmts['text']
                    )
                    add_g += g
                    add_stmts['object'] = uri
                else:
                    #Make sure we have the text for the added KW
                    obj_uri = URIRef(add_stmts['object'])
                    add_g.add((obj_uri, RDFS.label, Literal(add_stmts['text'])))
                    #Add type.
                    atype = tstore.get_prop_from_abbrv(add_stmts['range'])
                    add_g.add((obj_uri, RDF.type, atype))

                add_g += tstore.make_edit_graph(add_stmts)
            else:
                add_g = Graph()
            remove_stmts = edit.get('subtract')
            if remove_stmts is not None:
                subtract_g = tstore.make_edit_graph(remove_stmts)
            else:
                subtract_g = Graph()
        else:
            return HttpResponseServerError("Edit failed.  Edit type not recognized.")

        done = tstore.add_remove(add_g, subtract_g)
        if done is True:
            return HttpResponse('', 200 )
        else:
            return HttpResponseServerError("Edit failed.")

        return HttpResponseServerError("Edit failed.")

class BasePropertyView(View):

    def get_place_research_areas(self, uri):
        rq = """
        select ?ra ?label
        where {
            ?uri vivo:hasResearchArea ?ra .
            ?ra a schema:Place .
            ?ra rdfs:label ?label .
        }
        """
        out = []
        for row in tstore.graph.query(rq, initBindings={'uri': uri}):
            d = {}
            d['uri'] = row.ra.toPython()
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

class IndexView(TemplateView, ResourceView):
    template_name = 'index.html'

    def get_groups(self):
        rq = """
        select ?org ?label
        where {
            ?org a foaf:Group .
            ?org rdfs:label ?label .
        }
        ORDER BY ?label
        """
        out = []
        for row in tstore.graph.query(rq):
            d = {}
            d['uri'] = row.org.toPython().split('/')[-1]
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

    def get_organizations(self):
        rq = """
        select ?org ?label
        where {
            ?org a foaf:Organization .
            ?org rdfs:label ?label .
        }
        ORDER BY ?label
        LIMIT 10
        """
        out = []
        for row in tstore.graph.query(rq):
            d = {}
            d['uri'] = row.org.toPython().split('/')[-1]
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

    def get_faculty(self):
        rq = """
        select ?fac ?label
        where {
            ?fac a vivo:FacultyMember .
            ?fac rdfs:label ?label .
        }
        ORDER BY ?label
        LIMIT 10
        """
        out = []
        for row in tstore.graph.query(rq):
            d = {}
            d['uri'] = row.fac.toPython().split('/')[-1]
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        url = self.request.resolver_match.url_name
        if url == u'index':
            context['name'] = 'Index'
            orgs = self.get_organizations()
            faculty = self.get_faculty()
            context['orgs']  = orgs
            context['people'] = faculty
        elif url == u'people':
            context['name'] = 'People'
            faculty = self.get_faculty()
            context['people'] = faculty
        elif url == u'organizations':
            context['name'] = 'Organizations'
            orgs = self.get_organizations()
            groups = self.get_groups()
            orgs += groups
            context['orgs'] = orgs
        return context

class PersonView(TemplateView, ResourceView, BasePropertyView):
    template_name = 'person.html'

    def get_research_areas(self, uri):
        rq = """
        select ?ra ?label
        where {
            ?uri vivo:hasResearchArea ?ra .
            ?ra rdfs:label ?label .
            FILTER NOT EXISTS {?ra a schema:Place }
        }
        """
        out = []
        for row in tstore.graph.query(rq, initBindings={'uri': uri}):
            d = {}
            d['uri'] = row.ra.toPython()
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

    def get_affiliations(self, uri):
        rq = """
        select ?org ?label
        where {
            ?uri schema:affiliation ?org .
            ?org rdfs:label ?label .
        }
        """
        out = []
        for row in tstore.graph.query(rq, initBindings={'uri': uri}):
            d = {}
            d['uri'] = row.org.toPython()
            d['id'] = d['uri']
            d['text'] = row.label.toPython()
            out.append(d)
        return out

    def get_collaborators(self, uri):
        rq = """
        select ?collab ?name
        where {
            ?uri vivo:hasCollaborator ?collab .
            ?collab rdfs:label ?name .
        }"""
        out = []
        for row in tstore.graph.query(rq, initBindings={'uri': uri}):
            d = {}
            d['uri'] = row.collab.toPython()
            d['id'] = d['uri']
            d['text'] = row.name.toPython()
            out.append(d)
        return out

    def get_details(self, uri):
        #Get the name, title and other non-editable details.
        rq = """
        CONSTRUCT {
            ?fac d:name ?label .
            ?fac d:title ?title .
            ?org d:org ?orgName .
            ?collab d:collabName ?collabName .
        }
        where {
            ?fac rdfs:label ?label
            OPTIONAL {
                #Property paths are real slow.
                ?fac obo:ARG_2000028 ?vc .
                ?vc vcard:hasTitle ?t .
                ?t vcard:title ?title .
            }
            OPTIONAL {
                ?position a vivo:Position ;
                          vivo:relates ?fac ;
                          vivo:relates ?org .
                ?org a foaf:Organization.
                ?org rdfs:label ?orgName .
            }
        }
        """
        data = tstore.graph.query(rq, initBindings={'fac': uri})
        g = data.graph
        return {
            'name': g.value(subject=uri, predicate=D['name']),
            'title': g.value(subject=uri, predicate=D['title']),
            'orgs': [{'id' : o.org.toPython().replace(D, ''), 'name': o.name} for o in g.query('select ?org ?name where { ?org d:org ?name}')],
        }

    def get_context_data(self, local_name=None, **kwargs):
        context = super(PersonView, self).get_context_data(**kwargs)
        uri = D[local_name]
        details = self.get_details(uri)
        context['uri'] = uri
        context['local_name'] = uri
        #In production, this will need to be refactored because each call
        #to graph generates a SPARQL query.
        profile = {
            'overview': tstore.graph.value(subject=uri, predicate=VIVO.overview),
            'researchOverview': tstore.graph.value(subject=uri, predicate=VIVO.researchOverview),
            'teachingOverview': tstore.graph.value(subject=uri, predicate=VIVO.teachingOverview),
        }
        profile.update(details)
        prepared_sections = []
        for section in person:
            if section['id'] == 'researchArea':
                section['data'] = json.dumps(self.get_research_areas(uri))
            elif section['id'] == 'placeResearchArea':
                section['data'] = json.dumps(self.get_place_research_areas(uri))
            elif section['id'] == 'affiliations':
                section['data'] = json.dumps(self.get_affiliations(uri))
            elif section['id'] == 'collaborators':
                section['data'] = json.dumps(self.get_collaborators(uri))
            else:
                section['data'] = profile.get(section['id'])
            prepared_sections.append(section)
        context['sections']  = prepared_sections
        context['profile'] = profile
        return context

class OrganizationView(TemplateView, ResourceView, BasePropertyView):
    template_name = 'organization.html'

    def get_context_data(self, local_name=None, **kwargs):
        context = {}
        uri = D[local_name]
        context['uri'] = uri
        context['name'] = tstore.graph.value(subject=uri, predicate=RDFS.label)
        profile = {
            'overview': tstore.graph.value(subject=uri, predicate=VIVO.overview),
        }
        prepared_sections = []
        for section in organization:
            if section['id'] == 'researchArea':
                section['data'] = json.dumps(self.get_research_areas(uri))
            elif section['id'] == 'placeResearchArea':
                section['data'] = json.dumps(self.get_place_research_areas(uri))
            else:
                section['data'] = profile.get(section['id'])
            prepared_sections.append(section)
        context['sections']  = prepared_sections
        context['profile'] = profile
        return context

#
# - Services for autcomplete widgets
#

class JSONServiceView(View, JSONResponseMixin):
    def render_to_response(self, context):
        return JSONResponseMixin.render_to_response(self, context)

class FASTTopicAutocompleteView(JSONServiceView):

    def get(self, request, *args, **kwargs):
        fs = FASTService()
        #topics
        index = 'suggest50'
        context = {}
        query = self.request.GET.get('query')
        out = fs.get(query, index)
        context['results'] = out
        return self.render_to_response(context)

class FASTPlaceAutocompleteView(JSONServiceView):
    def get(self, request, *args, **kwargs):
        fs = FASTService()
        #locations/geograph
        index = 'suggest51'
        context = {}
        query = self.request.GET.get('query')
        out = fs.get(query, index)
        context['results'] = out
        return self.render_to_response(context)

class FASTOrganizationAutocompleteView(JSONServiceView):
    def get(self, request, *args, **kwargs):
        fs = FASTService()
        context = {}
        #organizations
        index = 'suggest10'
        query = self.request.GET.get('query')
        out = fs.get(query, index)
        context['results'] = out
        return self.render_to_response(context)

class VIVOCollaboratorsAutocompleteView(JSONServiceView):
    def get(self, request, *args, **kwargs):
        #fellow faculty members.
        context = {}
        vs = VIVOService()
        query = self.request.GET.get('query')
        out = vs.get(query, VIVO['FacultyMember'].toPython())
        context['results'] = out
        return self.render_to_response(context)


test = "<color:(0, 0, 0)>hjsfjhskd<size: 20   >lfasdasdasda<size:23123;super_offset:3; italic:True>sdasdasda</>dasdhsj</>kdfhkls</aaa>"
tags = {""}

styles = {"int": ["size", "sub_offset", "super_offset", "word_spacing", "letter_spacing", "leading"], "bool": ["italic", "bold", "underline", "shadow", "super", "sub"], "intlist": ["color", "background", "shadow_offset", "shadow_color"], "string": ["font"]}

def process_style(style):
    temp = style.replace(" ", "")
    temp = temp.split(";")
    final = {}
    for x in temp:
        split_text = x.split(":")
        if split_text[0] in styles["int"]:
            final[split_text[0]] = int(split_text[1])
        elif split_text[0] in styles["bool"]:
            final[split_text[0]] = bool(split_text[1])
        elif split_text[0] in styles["string"]:
            final[split_text[0]] = split_text[1]
        elif split_text[0] in styles["intlist"]:
            final[split_text[0]] = [int(x) for x in split_text[1][1:-1].split(",")]
    return final

def append(levels, lst, item):
    temp = lst
    for level in levels:
        temp = temp[level]
    temp.append(item)
    return(len(temp))

style = []
text = []
final = []
current_index = 0
state = "between_tags"
close = False
levels = []

temp_final = []

for char in test:
    if state == "inside_tags":
        text.append(char)
        if char == ">":
            state = "between_tags"
            temp_final.append("".join(text))
            text = []
    elif state == "between_tags":
        if char == "<":
            state = "inside_tags"
            temp_final.append("".join(text))
            text = []
        text.append(char)
print(temp_final)

for char in test:
    if state == "inside_tags":
        if char == ">":
            state = "between_tags"
            final_style = process_style("".join(style))
            if final_style != {}:
                append(levels, final, final_style)
            style = []
        elif char == "/":
            try:
                levels.pop()
            except:
                pass
        else:
            style.append(char)
    elif state == "between_tags":
        if char == "<":
            state = "inside_tags"
            if text != []:
                append(levels, final, "".join(text))
            levels.append(append(levels, final, []) - 1)
            text = []
        else:
            text.append(char)
print(final)


import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

## READ DATA
df = pd.read_csv("../data/USDJPY_1M_3Y.csv")
print(df.head())

## CREATE VWAP
df['VxC'] = df['Volume'] * df['Close']
vwap_steps = 20
vwaps = [x for x in range(5,100,15)]

for vwap_steps in vwaps:
    print('Creating vwap{}'.format(vwap_steps))
    df['vwap{}'.format(vwap_steps)] = 0
    for i in range(vwap_steps, df.shape[0] + 1):
        df.loc[i - 1,'vwap{}'.format(vwap_steps)] = df.loc[i-vwap_steps:i,'VxC'].sum() / df.loc[i-vwap_steps:i,'Volume'].sum()
        if(i % 100000 == 0):
            print(i)

df = df[vwaps[-1] - 1:]
df.drop('VxC', axis = 1)
df.reset_index(drop=True, inplace=True)
print(df.head())
print(df.tail())

## SAVE MODEL
print('Saving model')
file_name = '../data/USDJPY_1M_vwap.csv'
df.to_csv(file_name, index = False)


from flask import Flask, render_template, redirect
from form import TaskForm
from config import Config

app = Flask(
  'app',
  template_folder='templates'
)
app.config.from_object(Config)

my_list = []
def add_to_list(task):
  my_list.append(task)
  print(my_list)

@app.route('/')
def hello_world():
  return render_template('basic.html')

@app.route('/todo', methods=['GET','POST'])
def todo():
  form = TaskForm()
  if form.is_submitted():
    print("made it")
    add_to_list(form.task.data)
    return redirect('/mylist')
  return render_template('todo.html', form=form)

@app.route('/mylist')
def mylist():
  return render_template('mylist.html', my_list=my_list)

app.run(host='0.0.0.0', port=8080)


from Application import Application
from Database import Database
import Director
from pygame import *

def main():
    db = Database()
    db['screen_width'] = 800
    db['screen_height'] = 450
    db['locomotive_img'] = "locomotive.png"
    db['rails_img'] = "ClickerBg.png"
    db['font'] = "F77-Minecraft.ttf"
    app = Application("MyApp")
    app.create_window(db['screen_width'], db['screen_height'], "ClickerGame")
    return app.run()

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import random

digits = [x for x in range(10)]
random.shuffle(digits)
conceived = digits[:4]
if conceived[0] == 0:
    conceived[0] = conceived[1]
    conceived[1] = 0
print('Игра "Быки и Коровы"')
while True:
    guessed = int(input("Введите число: "))
    if not 999 < guessed < 10000:
        print("Число от 1000 до 9999")
        print("Число от 1000 до 9999")
        continue
    testing = [int(x) for x in str(guessed)]
    if testing == conceived:
        print("Вы выиграли!")
        print("Это было", conceived)
        break
    for n, d in enumerate(testing):
        if d == conceived[n]:
            print("Б", end="")
        elif d in conceived:
            print("К", end="")
        else:
            print(d, end="")
    print()


import os

CURRENT_DIRECTORY = os.path.dirname(__file__)
os.chdir(CURRENT_DIRECTORY)
import numpy as np

def read_input_lines():
    with open('input.txt', 'r') as fh:
        return [x.strip() for x in fh.readlines()]

def read_input_text():
    with open('input.txt', 'r') as fh:
        return fh.read().strip()

def part_a():
    ints = [int(x) for x in read_input_lines()] # ints are not unique and rotation values are large
    ints = [int(x) for x in """1
2
-3
3
-2
0
4""".split("\n")]
    originalix2pos = np.arange(0,len(ints))

    for i in range(len(ints)):
        num, pos = ints[i],originalix2pos[i]
        new_pos = (pos + num) % len(ints)
        print(i, num, pos,  new_pos)

        effective_move = num % len(ints)
        new_pos_unbounded = pos + effective_move

        range_unbounded = np.arange(pos+1,new_pos_unbounded + 1 ) if new_pos_unbounded > pos else np.arange(new_pos_unbounded,pos)
        range_bounded = range_unbounded % len(ints)
        originalix2pos[range_bounded] += (-1 if num > 0 else 1)
        originalix2pos[i] = new_pos
        originalix2pos %= len(ints)

        print([ints[i] for i in sorted(range(len(ints)), key = lambda x: originalix2pos[x])])

    print(len(set(originalix2pos.values())))
    zeroix = originalix2pos[ints.index(0)]
    print(sum(ints[k] for k,v in originalix2pos.items() if v in [(zeroix+x)% len(ints) for x in [1000,2000,3000]]))

part_a()
def part_b():
    pass


"""
    Name: Nnamdi Ajoku
    Language: Python

    Description: Given a string s, find the first non-repeating character in it and return
    its index. If it does not exist, return -1.

"""

def firstUniqChar(s):

    track = {}
    for i in range(len(s)):
        if s[i] not in track:
            track[s[i]] = i
        else:
            track[s[i]] = -1

    count = 0
    for k,v in track.items():
        count += 1
        if v != -1:
            return track[k]
            break

        elif v == -1 and count == len(track):
            return v


"""Retriever implementation which provides a NetVLAD global image descriptor to suggest potential image pairs.
Note: Similarity computation based off of Paul-Edouard Sarlin's HLOC:
Reference: https://github.com/cvg/Hierarchical-Localization/blob/master/hloc/pairs_from_retrieval.py
https://openaccess.thecvf.com/content_cvpr_2016/papers/Arandjelovic_NetVLAD_CNN_Architecture_CVPR_2016_paper.pdf
Authors: John Lambert
"""
import math
import os
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Tuple

import matplotlib.pyplot as plt
import numpy as np
import torch

import gtsfm.utils.logger as logger_utils
from gtsfm.retriever.retriever_base import RetrieverBase, ImageMatchingRegime

logger = logger_utils.get_logger()
MAX_NUM_IMAGES = 10000

@dataclass
class SubBlockSimilarityResult:
    i_start: int
    i_end: int
    j_start: int
    j_end: int
    subblock: torch.Tensor

class NetVLADRetriever(RetrieverBase):
    def __init__(self, num_matched: int, min_score: float = 0.1, blocksize: int = 50) -> None:
        """
        Args:
            num_matched: Number of K potential matches to provide per query. These are the top "K" matches per query.
            min_score: Minimum allowed similarity score to accept a match.
            blocksize: Size of matching sub-blocks when creating similarity matrix.
        """
        super().__init__(matching_regime=ImageMatchingRegime.RETRIEVAL)
        self._num_matched = num_matched
        self._blocksize = blocksize
        self._min_score = min_score

    def __repr__(self) -> str:
        return f"""
        NetVLADRetriever:
            Num. frames matched: {self._num_matched}
            Block size: {self._blocksize}
            Minimum score: {self._min_score}
        """

    def get_image_pairs(
        self,
        global_descriptors: Optional[List[np.ndarray]],
        image_fnames: List[str],
        plots_output_dir: Optional[Path] = None,
    ) -> List[Tuple[int, int]]:
        """Compute potential image pairs.

        Args:
            global_descriptors: the global descriptors for the retriever, if needed.
            image_fnames: file names of the images
            plots_output_dir: Directory to save plots to. If None, plots are not saved.

        Returns:
            List of (i1,i2) image pairs.
        """
        if global_descriptors is None:
            raise ValueError("Global descriptors need to be provided")
        sim = self.compute_similarity_matrix(global_descriptors)
        return self.compute_pairs_from_similarity_matrix(
            sim=sim, image_fnames=image_fnames, plots_output_dir=plots_output_dir
        )

    def compute_similarity_matrix(self, global_descriptors: List[np.ndarray]) -> torch.tensor:
        """Compute a similarity matrix between all pairs of images.
        We use block matching, to avoid excessive memory usage.
        We cannot fit more than 50x50 sized block into memory, on a 16 GB RAM machine.
        A similar blocked exhaustive matching implementation can be found in COLMAP:
        https://github.com/colmap/colmap/blob/dev/src/feature/matching.cc#L899

        Args:
            global_descriptors: global descriptors, one per image.

        Returns:
            Similarity matrix as tensor of shape (num_images, num_images).
        """
        num_images = len(global_descriptors)
        if num_images > MAX_NUM_IMAGES:
            raise RuntimeError("Cannot construct similarity matrix of this size.")

        subblock_results: List[SubBlockSimilarityResult] = []
        num_blocks = math.ceil(num_images / self._blocksize)

        # TODO(Ayush, John): do we still need to do subblock computations?
        for block_i in range(num_blocks):
            for block_j in range(block_i, num_blocks):
                subblock_results.append(
                    self._compute_similarity_subblock(
                        global_descriptors=global_descriptors, block_i=block_i, block_j=block_j
                    )
                )

        sim = self._aggregate_subblocks(subblock_results=subblock_results, num_images=num_images)
        return sim

    def _compute_similarity_subblock(self, global_descriptors: List[np.ndarray], block_i: int, block_j: int):
        """Compute a sub-block of an global descriptor based similarity matrix.
        Args:
            global_descriptors: global descriptors, one per image.
            block_i: row index of sub-block.
            block_j: column index of sub-block.
        Returns:
            sub-block similarity result.
        """
        num_images = len(global_descriptors)
        device = "cuda" if torch.cuda.is_available() else "cpu"
        num_blocks = math.ceil(num_images / self._blocksize)
        # only compute the upper triangular portion of the similarity matrix.
        logger.info("Computing matching block (%d/%d,%d/%d)", block_i, num_blocks - 1, block_j, num_blocks - 1)
        i_start = block_i * self._blocksize
        i_end = (block_i + 1) * self._blocksize
        i_end = min(i_end, num_images)
        j_start = block_j * self._blocksize
        j_end = (block_j + 1) * self._blocksize
        j_end = min(j_end, num_images)
        # Form (K,D) for K images.
        block_i_query_descs = torch.from_numpy(np.array(global_descriptors[i_start:i_end]))
        block_j_query_descs = torch.from_numpy(np.array(global_descriptors[j_start:j_end]))
        # Einsum equivalent to (img_descs @ img_descs.T)
        sim_block = torch.einsum("id,jd->ij", block_i_query_descs.to(device), block_j_query_descs.to(device))
        return SubBlockSimilarityResult(i_start=i_start, i_end=i_end, j_start=j_start, j_end=j_end, subblock=sim_block)

    def _aggregate_subblocks(self, subblock_results: List[SubBlockSimilarityResult], num_images: int) -> torch.Tensor:
        """Aggregate results from many independently computed sub-blocks of the similarity matrix into a single matrix.

        Args:
            subblock_results: Metadata and results of similarity matrix sub-block computation.
            num_images: Number of images to compare for matching.

        Returns:
            sim: Tensor of shape (num_images, num_images) representing similarity matrix.
        """
        sim = torch.zeros((num_images, num_images))
        for sr in subblock_results:
            sim[sr.i_start : sr.i_end, sr.j_start : sr.j_end] = sr.subblock
        return sim

    def compute_pairs_from_similarity_matrix(
        self, sim: torch.Tensor, image_fnames: List[str], plots_output_dir: Optional[Path] = None
    ) -> List[Tuple[int, int]]:
        """

        Args:
            sim: Tensor of shape (num_images, num_images) representing similarity matrix.
            image_fnames: the names of the images
            plots_output_dir: Directory to save plots to. If None, plots are not saved.

        Returns:
            pair_indices: (i1,i2) image pairs.
        """
        num_images = len(image_fnames)
        # Avoid self-matching and disallow lower triangular portion
        is_invalid_mat = ~np.triu(np.ones((num_images, num_images), dtype=bool))
        np.fill_diagonal(a=is_invalid_mat, val=True)
        pairs = pairs_from_score_matrix(
            sim, invalid=is_invalid_mat, num_select=self._num_matched, min_score=self._min_score
        )
        named_pairs = [(image_fnames[i], image_fnames[j]) for i, j in pairs]
        if plots_output_dir:
            os.makedirs(plots_output_dir, exist_ok=True)
            # Save image of similarity matrix.
            plt.imshow(np.triu(sim.detach().cpu().numpy()))
            plt.title("Image Similarity Matrix")
            plt.savefig(str(plots_output_dir / "netvlad_similarity_matrix.jpg"), dpi=500)
            plt.close("all")
            # Save values in similarity matrix.
            np.savetxt(
                fname=str(plots_output_dir / "netvlad_similarity_matrix.txt"),
                X=sim.detach().cpu().numpy(),
                fmt="%.2f",
                delimiter=",",
            )

            # Save named pairs and scores.
            with open(plots_output_dir / "netvlad_named_pairs.txt", "w") as fid:
                for _named_pair, _pair_ind in zip(named_pairs, pairs):
                    fid.write("%.4f %s %s\n" % (sim[_pair_ind[0], _pair_ind[1]], _named_pair[0], _named_pair[1]))

        logger.info("Found %d pairs from the NetVLAD Retriever.", len(pairs))
        return pairs

def pairs_from_score_matrix(
    scores: torch.Tensor, invalid: np.array, num_select: int, min_score: Optional[float] = None
) -> List[Tuple[int, int]]:
    """Identify image pairs from a score matrix.

    Note: Similarity computation here is based off of Paul-Edouard Sarlin's HLOC:
    Reference: https://github.com/cvg/Hierarchical-Localization/blob/master/hloc/pairs_from_retrieval.py

    Args:
        scores: (K1,K2) for matching K1 images against K2 images.
        invalid: (K1,K2) boolean array indicating invalid match pairs (e.g. self-matches).
        num_select: Number of matches to select, per query.
        min_score: Minimum allowed similarity score.

    Returns:
        pairs: Tuples representing pairs (i1,i2) of images.
    """
    N = scores.shape[0]
    # if there are only N images to choose from, selecting more than N is not allowed
    num_select = min(num_select, N)
    assert scores.shape == invalid.shape
    invalid = torch.from_numpy(invalid).to(scores.device)
    if min_score is not None:
        # logical OR.
        invalid |= scores < min_score
    scores.masked_fill_(invalid, float("-inf"))
    topk = torch.topk(scores, k=num_select, dim=1)
    indices = topk.indices.cpu().numpy()
    valid = topk.values.isfinite().cpu().numpy()
    pairs = []
    for i, j in zip(*np.where(valid)):
        pairs.append((i, indices[i, j]))
    return pairs


import taichi as ti
import numpy as np
import argparse
from ray_tracing_models import Ray, Camera, Hittable_list, Sphere, PI, random_in_unit_sphere, refract, reflect, reflectance, random_unit_vector
ti.init(arch=ti.gpu)

# Canvas
aspect_ratio = 1.0
image_width = 800
image_height = int(image_width / aspect_ratio)
canvas = ti.Vector.field(3, dtype=ti.f32, shape=(image_width, image_height))

# Rendering parameters
samples_per_pixel = 4
max_depth = 10
sample_on_unit_sphere_surface = True

@ti.kernel
def render():
    for i, j in canvas:
        u = (i + ti.random()) / image_width
        v = (j + ti.random()) / image_height
        color = ti.Vector([0.0, 0.0, 0.0])
        for n in range(samples_per_pixel):
            ray = camera.get_ray(u, v)
            color += ray_color(ray)
        color /= samples_per_pixel
        canvas[i, j] += color

# Path tracing
@ti.func
def ray_color(ray):
    color_buffer = ti.Vector([0.0, 0.0, 0.0])
    brightness = ti.Vector([1.0, 1.0, 1.0])
    scattered_origin = ray.origin
    scattered_direction = ray.direction
    p_RR = 0.8
    for n in range(max_depth):
        if ti.random() > p_RR:
            break
        is_hit, hit_point, hit_point_normal, front_face, material, color = scene.hit(Ray(scattered_origin, scattered_direction))
        if is_hit:
            if material == 0:
                color_buffer = color * brightness
                break
            else:
                # Diffuse
                if material == 1:
                    target = hit_point + hit_point_normal
                    if sample_on_unit_sphere_surface:
                        target += random_unit_vector()
                    else:
                        target += random_in_unit_sphere()
                    scattered_direction = target - hit_point
                    scattered_origin = hit_point
                    brightness *= color
                # Metal and Fuzz Metal
                elif material == 2 or material == 4:
                    fuzz = 0.0
                    if material == 4:
                        fuzz = 0.4
                    scattered_direction = reflect(scattered_direction.normalized(),
                                                  hit_point_normal)
                    if sample_on_unit_sphere_surface:
                        scattered_direction += fuzz * random_unit_vector()
                    else:
                        scattered_direction += fuzz * random_in_unit_sphere()
                    scattered_origin = hit_point
                    if scattered_direction.dot(hit_point_normal) < 0:
                        break
                    else:
                        brightness *= color
                # Dielectric
                elif material == 3:
                    refraction_ratio = 1.5
                    if front_face:
                        refraction_ratio = 1 / refraction_ratio
                    cos_theta = ti.min(-scattered_direction.normalized().dot(hit_point_normal), 1.0)
                    sin_theta = ti.sqrt(1 - cos_theta * cos_theta)
                    # total internal reflection
                    if refraction_ratio * sin_theta > 1.0 or reflectance(cos_theta, refraction_ratio) > ti.random():
                        scattered_direction = reflect(scattered_direction.normalized(), hit_point_normal)
                    else:
                        scattered_direction = refract(scattered_direction.normalized(), hit_point_normal, refraction_ratio)
                    scattered_origin = hit_point
                    brightness *= color
                brightness /= p_RR
    return color_buffer

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Naive Ray Tracing')
    parser.add_argument(
        '--max_depth', type=int, default=10, help='max depth (default: 10)')
    parser.add_argument(
        '--samples_per_pixel', type=int, default=4, help='samples_per_pixel  (default: 4)')
    parser.add_argument(
        '--samples_in_unit_sphere', action='store_true', help='whether sample in a unit sphere')
    args = parser.parse_args()

    max_depth = args.max_depth
    samples_per_pixel = args.samples_per_pixel
    sample_on_unit_sphere_surface = not args.samples_in_unit_sphere
    scene = Hittable_list()

    # Light source
    scene.add(Sphere(center=ti.Vector([0, 5.4, -1]), radius=3.0, material=0, color=ti.Vector([10.0, 10.0, 10.0])))
    # Ground
    scene.add(Sphere(center=ti.Vector([0, -100.5, -1]), radius=100.0, material=1, color=ti.Vector([0.8, 0.8, 0.8])))
    # ceiling
    scene.add(Sphere(center=ti.Vector([0, 102.5, -1]), radius=100.0, material=1, color=ti.Vector([0.8, 0.8, 0.8])))
    # back wall
    scene.add(Sphere(center=ti.Vector([0, 1, 101]), radius=100.0, material=1, color=ti.Vector([0.8, 0.8, 0.8])))
    # right wall
    scene.add(Sphere(center=ti.Vector([-101.5, 0, -1]), radius=100.0, material=1, color=ti.Vector([0.6, 0.0, 0.0])))
    # left wall
    scene.add(Sphere(center=ti.Vector([101.5, 0, -1]), radius=100.0, material=1, color=ti.Vector([0.0, 0.6, 0.0])))

    # Diffuse ball
    scene.add(Sphere(center=ti.Vector([0, -0.2, -1.5]), radius=0.3, material=1, color=ti.Vector([0.8, 0.3, 0.3])))
    # Metal ball
    scene.add(Sphere(center=ti.Vector([-0.8, 0.2, -1]), radius=0.7, material=2, color=ti.Vector([0.6, 0.8, 0.8])))
    # Glass ball
    scene.add(Sphere(center=ti.Vector([0.7, 0, -0.5]), radius=0.5, material=3, color=ti.Vector([1.0, 1.0, 1.0])))
    # Metal ball-2
    scene.add(Sphere(center=ti.Vector([0.6, -0.3, -2.0]), radius=0.2, material=4, color=ti.Vector([0.8, 0.6, 0.2])))

    camera = Camera()
    gui = ti.GUI("Ray Tracing", res=(image_width, image_height))
    canvas.fill(0)
    cnt = 0
    while gui.running:
        render()
        cnt += 1
        gui.set_image(np.sqrt(canvas.to_numpy() / cnt))
        gui.show()


import discord
from redbot.core import Config, checks, commands
from redbot.core.utils.menus import menu, commands, DEFAULT_CONTROLS
import asyncio
import logging

from .boorucore import BooruCore

class Boorualias:

    @commands.command()
    @commands.guild_only()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def neko(self, ctx, *, tag=""):
        """Neko images"""

        tag_default = " neko"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "nekos_nsfw_neko", "nekos_sfw_neko"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def anal(self, ctx, *, tag=""):
        """Anal images"""

        tag_default = " anal"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "anal", "nekos_nsfw_anal"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def ass(self, ctx, *, tag=""):
        """Ass images"""

        tag_default = " ass"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "ass", "obutts"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def bdsm(self, ctx, *, tag=""):
        """Bdsm images"""

        tag_default = " bdsm"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "bdsm", "nekos_nsfw_bdsm", "nekos_nsfw_femdom"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def boobs(self, ctx, *, tag=""):
        """Boobs images"""

        tag_default = " boobs"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "boobs", "oboobs", "nekos_nsfw_boobs"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def cumon(self, ctx, *, tag=""):
        """Cum_on images"""

        tag_default = " cum_on_*"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "cumshots", "nekos_nsfw_cum"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def yaoi(self, ctx, *, tag=""):
        """Yaoi images"""

        tag_default = " yaoi"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "gay"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def lesbian(self, ctx, *, tag=""):
        """Lesbian images"""

        tag_default = " lesbian yuri"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "lesbian", "nekos_nsfw_yuri"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def milf(self, ctx, *, tag=""):
        """Milf images"""

        tag_default = " milf"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "safe", "milf"]

        await self.generic_alias_booru(ctx, boards, tag)

    @commands.command()
    @commands.guild_only()
    @commands.is_nsfw()
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def oral(self, ctx, *, tag=""):
        """Oral images"""

        tag_default = " oral"
        tag += tag_default
        boards = ["dan", "gel", "kon", "yan", "cunnilingus", "blowjob", "deepthroat", "nekos_nsfw_blowjob", "nekos_nsfw_cunnilingus"]

        await self.generic_alias_booru(ctx, boards, tag)


"""
机器人的运动范围
地上有一个m行n列的方格，从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动，它每次可以向左、右、上、下
移动一格（不能移动到方格外），也不能进入行坐标和列坐标的数位之和大于k的格子。例如，当k为18时，机器人能够进入方格 [35, 37]
因为3+5+3+7=18。但它不能进入方格 [35, 38]，因为3+5+3+8=19。请问该机器人能够到达多少个格子？
示例 1：
输入：m = 2, n = 3, k = 1
输出：3

示例 2：
输入：m = 3, n = 1, k = 0
输出：1

提示：
1 <= n,m <= 100
0 <= k <= 20
来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
# 这个题目，我先想到的是，注意，比如坐标为（9，9)时，如果m=n=10,且 k = 8这种的话，那么(9,9),(9,10),(10,9)都不能访问，但是
# （10，10）是可以访问的，但是访问不到，被挡住了哦。
# 初步看了第一感觉就是深度优先或者广度优先

import numpy as np
from typing import List
def visit(x:int, y:int, k:int, jvzhen:List[List[int]], m:int, n:int) -> int:
	ans = 0
	step_dict = {0:[-1,0],1:[1,0],2:[0,-1],3:[0,1]}  # 对应上下左右
	for i in range(4):
		loc_x = x
		loc_y = y
		if (loc_x+step_dict[i][0])>=0 and (loc_x+step_dict[i][0])<m and (loc_y+step_dict[i][1])>=0 and (loc_y+step_dict[i][1])<n:
			num = sum([int(a) for a in str(loc_x + step_dict[i][0])])+sum([int(b) for b in str(loc_y+step_dict[i][1])])
			if num<=k and jvzhen[loc_x + step_dict[i][0]][loc_y+step_dict[i][1]] == 0:
				ans +=1
				loc_x = loc_x + step_dict[i][0]
				loc_y = loc_y + step_dict[i][1]
				jvzhen[loc_x][loc_y] = 1
				ans += visit(loc_x,loc_y,k,jvzhen,m,n)
	return ans

class Solution:
	def movingCount(self, m: int, n: int, k: int) -> int:
		jvzhen = np.zeros((m,n)).astype(int)
		jvzhen[0][0] = 1
		ans = visit(0,0,k,jvzhen,m,n)
		return ans+1

solu = Solution()
ans = solu.movingCount(3,1,0)
print(ans)

names=['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',
        'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
        'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
        'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',
        'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
        'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
        'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
        'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
        'hair drier', 'toothbrush']
print(len(names))


"""
JADN Definition BaseModel
Customized from `jadnschema.schema.baseModel.BaseModel`
"""
from copy import deepcopy
from enum import Enum
from typing import Any, ClassVar
from pydantic import create_model  # pylint: disable=no-name-in-module
from pydantic.main import ModelMetaclass  # pylint: disable=no-name-in-module
from .options import Options
from .field import getFieldSchema, getFieldType
from ..consts import SELECTOR_TYPES, STRUCTURED_TYPES, FIELD_TYPES
from ..baseModel import BaseModel
from ...utils import classproperty, ellipsis_str
__pdoc__ = {
    "DefinitionBase.name": "The definition's valid schema name",
    "DefinitionBase.description": "The definition's description",
    "DefinitionBase.data_type": "The definition's base datatype"
}

class DefinitionMeta(ModelMetaclass):
    def __new__(mcs, name, bases, attrs, **kwargs):  # pylint: disable=bad-classmethod-argument
        base_opts = [b.__options__ for b in reversed(bases) if issubclass(b, BaseModel) and b != BaseModel]
        opts = Options(
            *base_opts,
            attrs.pop("__options__", None), attrs.pop("Options", None),
            kwargs.pop("__options__", None), kwargs.pop("Options", None),
            getattr(mcs, "__options__", None), getattr(mcs, "Options", None),
        )
        new_namespace = {
            **attrs,
            **kwargs,
            "__options__": opts,
        }
        cls = super().__new__(mcs, name, bases, new_namespace)  # pylint: disable=too-many-function-args
        base_names = [b.__name__ for b in bases]
        for idx, (field, opts) in enumerate(cls.__fields__.items()):
            if field != "__root__":
                opts.field_info.extra["parent"] = cls
                field_opts = opts.field_info.extra["options"]
                field_opts.setdefault("name", f"{name}.{opts.alias}")
                field_opts.setdefault("data_type", getFieldType(opts))
                opts.field_info.extra.setdefault("id", idx)
                if not opts.required and field_opts.minc != 0 and "Choice" not in base_names:
                    field_opts.minc = 0
        return cls

class DefinitionBase(BaseModel, metaclass=DefinitionMeta):  # pylint: disable=invalid-metaclass
    __options__: ClassVar[Options]

    def __str__(self):
        cls = self.__class__
        mro = [c for c in cls.__mro__ if not c.__name__ == cls.__name__][0]
        data = self.json(exclude_none=True)
        return f"{self.name}({mro.__name__}: {ellipsis_str(data)})"

    # Pydantic overrides
    @classmethod
    def schema(cls) -> list:
        """
        Format the definition to valid JADN schema format
        :return: formatted JADN
        """
        mro = [c for c in cls.__mro__ if not c.__name__ == cls.__name__][0]
        schema = [cls.name, mro.__name__, cls.__options__.schema(), (cls.__doc__ or "").strip()]
        if cls.__fields__ and "__root__" not in cls.__fields__:
            fields = []
            for opt in cls.__fields__.values():
                fields.append(getFieldSchema(opt))
            schema.append(fields)
        return schema

    # Custom Methods
    @classmethod
    def is_enum(cls) -> bool:
        """
        Determine if the definition is an enumerated type
        :return: True/False if the definition is an enumerated type
        """
        for base in cls.__mro__:
            if base.__name__ == "Enumerated":
                return True
        return False

    @classmethod
    def is_structure(cls) -> bool:
        """
        Determine if the definition is a structure type
        `Array`, `ArrayOf`, `Map`, `MapOf`, & `Record` are structure types
        :return: True/False if the definition is a structure type
        """
        for base in cls.__mro__:
            if base.__name__ in STRUCTURED_TYPES:
                return True
        return False

    @classmethod
    def is_selector(cls) -> bool:
        """
        Determine if the definition is a selector type
        `Enumerated` & `Choice` are selector types
        :return: True/False if the definition is a selector type
        """
        for base in cls.__mro__:
            if base.__name__ in SELECTOR_TYPES:
                return True
        return False

    @classmethod
    def has_fields(cls) -> bool:
        """
        Determine if the definition has fields
        `Enumerated`, `Choice`, `Array`, `Map`, & `Record` should have defined fields
        :return: True/False if the definition has fields
        """
        for base in cls.__mro__:
            if base.__name__ in FIELD_TYPES:
                return True
        return False

    # Helpers
    @classmethod
    def expandCompact(cls, value: Any) -> Any:
        if isinstance(value, dict) and cls.__fields__:
            rtn = {}
            for field in cls.__fields__.values():
                f_id = field.field_info.extra["id"]
                if f_id in value:
                    rtn[field.alias] = field.type_.expandCompact(value[f_id])
            return rtn
        return value

    @classproperty
    def name(cls) -> str:  # pylint: disable=no-self-argument
        """The definition's valid schema name"""
        return cls.__options__.name or cls.__name__

    @classproperty
    def description(cls) -> str:  # pylint: disable=no-self-argument
        """The definition's description"""
        return cls.__doc__

    @classproperty
    def data_type(cls) -> str:  # pylint: disable=no-self-argument
        """The definition's base datatype"""
        return cls.__options__.data_type

    @classmethod
    def enumerated(cls) -> "Enumerated":  # pylint: disable=no-self-argument
        """
        Convert the given class to an 'Enumerated' class if applicable
        :return: converted Enumerated class object
        """
        if cls.data_type in ("Binary", "Boolean", "Integer", "Number", "Null", "String"):
            raise TypeError(f"{cls.name} cannot be extended as an enumerated type")

        if cls.data_type == "Enumerated":  # pylint: disable=comparison-with-callable
            return cls

        from .structures import Enumerated  # pylint: disable=import-outside-toplevel
        name = f"Enum-{cls.name}"
        values = {}
        for k, v in cls.__fields__.items():
            values[k] = deepcopy(v.field_info)
            values[k].default = k

        cls_kwargs = dict(
            __name__=name,
            __doc__=f"Derived Enumerated from {cls.name}",
            __enums__=Enum("__enums__", values),
            __options__=Options(cls.__options__, name=name)
        )
        return create_model(name, __base__=Enumerated, __cls_kwargs__=cls_kwargs)

    class Config:
        arbitrary_types_allowed = True
        orm_mode = True


import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score

def Train(x_train, y_train, x_test, y_test):
    clf = Perceptron(random_state=241)
    clf.fit(x_train, y_train.ravel())
    predictions = clf.predict(x_test)
    return accuracy_score(y_test, predictions)

data_train = pd.read_csv('perceptron-train.csv',header=None)
x_train = data_train.iloc[0:, 1:3]
y_train = data_train.iloc[0:, 0:1]

print(data_train.head())
print(x_train.head())
print(y_train.head())

data_test = pd.read_csv('perceptron-test.csv',header=None)
x_test = data_test.iloc[0:, 1:3]
y_test = data_test.iloc[0:, 0:1]

score_without_scaling = Train(
    x_train.as_matrix(),
    y_train.as_matrix(),
    x_test.as_matrix(),
    y_test.as_matrix())

print(
    "Before scaling",
    score_without_scaling)

scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(
    x_train.as_matrix())
print(x_train.head())
#print(x_train_scaled.head())
x_test_scaled = scaler.transform(
    x_test.as_matrix())

score_with_scaling = Train(
    x_train_scaled,
    y_train.as_matrix(),
    x_test_scaled,
    y_test.as_matrix())

print(
    "After scaling",
    score_with_scaling)

print(
    "Diff",
    round(
        score_with_scaling - score_without_scaling,
        3))


import torch

class GECO():

    def __init__(self, goal, step_size, alpha=0.99, beta_init=1.0,
                 beta_min=1e-10, speedup=None):
        self.err_ema = None
        self.goal = goal
        self.step_size = step_size
        self.alpha = alpha
        self.beta = torch.tensor(beta_init)
        self.beta_min = torch.tensor(beta_min)
        self.beta_max = torch.tensor(1e10)
        self.speedup = speedup

    def to_cuda(self):
        self.beta = self.beta.cuda()
        if self.err_ema is not None:
            self.err_ema = self.err_ema.cuda()

    def loss(self, err, kld):
        # Compute loss with current beta
        loss = err + self.beta * kld
        # Update beta without computing / backpropping gradients
        with torch.no_grad():
            if self.err_ema is None:
                self.err_ema = err
            else:
                self.err_ema = (1.0-self.alpha)*err + self.alpha*self.err_ema
            constraint = (self.goal - self.err_ema)
            if self.speedup is not None and constraint.item() > 0:
                factor = torch.exp(self.speedup * self.step_size * constraint)
            else:
                factor = torch.exp(self.step_size * constraint)
            self.beta = (factor * self.beta).clamp(self.beta_min, self.beta_max)
        # Return loss
        return loss


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   713.py
@Contact :   huanghoward@foxmail.com
@Modify Time :    2022/5/5 11:31
------------
"""

class Solution(object):
    def numSubarrayProductLessThanK(self, nums, k):
        left=0
        prob = 1
        ans = 0
        for i,n in enumerate(nums):
            prob = prob*n
            while prob>=k:

                prob = prob/nums[left]
                left += 1
            ans += i+1-left
            print(ans)
        return ans

if __name__ == '__main__':
    s = Solution()
    s.numSubarrayProductLessThanK([10,5,2,6],100)


def isTidy(s):
  for i in range(len(s) - 1):
    if s[i + 1] < s[i]:
      return False
  return True

T = int(input())

for i in range(T):
  N = int(input())
  S = str(N)

  while not isTidy(S):
    for j in range(len(S) - 1):
      if S[j + 1] < S[j]:
        tmp = list(S)
        tmp[j] = str(int(S[j]) - 1)
        for k in range(j + 1, len(S)):
          tmp[k] = str(9)
        S = "".join(tmp)
    tmp = list(S)

    if S[0] == '0':
      S = S[1:len(S)]

  print("Case #" + str(i + 1) + ": " + S)


import sys
sys.setrecursionlimit(200001)
input = sys.stdin.readline

def dfs(idx, o):
    global ans

    order[idx] = o
    visit[idx] = num

    if not visit[friendOf[idx]]: dfs(friendOf[idx], o+1)
    elif visit[friendOf[idx]] == num: ans += o - order[friendOf[idx]] + 1

answer = []
tc = int(input())
for _ in range(tc):

    n = int(input())

    friendOf = [0]+list(map(int, input().split()))
    visit = [0]*(n+1)
    order = [0]*(n+1)

    num = 1
    ans = 0

    for i in range(1, n+1):
        if not visit[i]:
            dfs(i, 1)
            num += 1

    answer.append(str(n - ans))
print("\n".join(answer))


from django.urls import path, include
from .views import all_products, product_detail, add_product, delete_product, edit_product

urlpatterns = [
    path('', all_products, name='products'),
    path('<product_id>', product_detail, name='product_detail'),
    path('manage/', add_product, name='add_product'),
    path('manage/edit/<product_id>/', edit_product, name='edit_product'),
    path('manage/delete/<product_id>/', delete_product, name='delete_product'),
]


#!/usr/bin/python3
# -*- coding: utf-8 -*

# Photobooth version 1

# Pour info, la taille de l'écran 7 pouces est de 640x480.

import RPi.GPIO as GPIO
import time #Utile pour le sime.sleep pour mettre en pause le programme
from datetime import datetime #Utile pour générer le nom de la photo selon la date du jour. Voir ligne 106. Doc : https://docs.python.org/fr/3.6/library/datetime.html
from PIL import Image #PIL sert à ouvrir, manipuler, sauveguarder des images
import pygame
from pygame.locals import *
import os

#-- Import et création d'un fichier de log --#
import logging
logging.basicConfig(filename='FichierDeLogs.log', encoding='utf-8', level=logging.DEBUG)
logging.info('This message should go the the file')

#--------------------------------------------#

import logging #Utile pour logguer tous les évènements

GPIO.setmode(GPIO.BCM) #Attention au choix du port ; référez-vous au site https://fr.pinout.xyz/
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP)

pygame.init()
infoObject = pygame.display.Info() #pygame.display.Info sert a creer un objet d'information video destine a l'affichage. Il prend pour proprietes ce qu'il trouvera dans current-h et current_y qui sont des attributs de .display.info.  Voir https://devdocs.io/pygame/ref/display#pygame.display.Info
screen = pygame.display.set_mode((infoObject.current_w,infoObject.current_h), pygame.FULLSCREEN)
screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
background = pygame.Surface(screen.get_size())  # Create the background object ; pygame.Surface va creer un nouvel objet image avec la taille pour arguments. Screen est une variable-
background = background.convert()  # Convert it to a background - Pour que le format de pixel soit identique entre le fond et le background

screenPicture = pygame.display.set_mode((infoObject.current_w,infoObject.current_h), pygame.FULLSCREEN)  # Full screen - Idem c la variable screen
backgroundPicture = pygame.Surface(screenPicture.get_size())  # Create the background object
backgroundPicture = background.convert()  # Convert it to a background - Pour que le format de pixel soit identique entre le fond et le background
#screen = pygame.display.set_mode((0,0),pygame.RESIZABLE)
width, height = screen.get_size()
rectScreen = screen.get_rect()
pygame.mouse.set_visible (False)
BUTTON_PIN = 25

#Ppygame.mixer.init()
#son = pygame.mixer.Sound('/home/pi/Photomaton/son.wav')
#canal = son.play()

def PrisePhoto(NomPhoto): #prendre une photo avec Raspistill
    command = "sudo raspistill -t 2000 -w 1200 -h 675 -o "+ NomPhoto +" -q 100" #prend une photo après 5sec de largeur 1200 et hauteur 675 de qualité 100
    os.system(command)

def AfficherPhoto(NomPhoto): # affiche NomPhoto
    print("loading image: " + NomPhoto)
    background = pygame.image.load(NomPhoto);
    background.convert_alpha()
    background = pygame.transform.scale(background,(width,height))
    screen.blit(background,(0,0),(0,0,width,height))
    pygame.display.flip()

def decompte():
  AfficherTexte("Attention")
  time.sleep(1)
  AfficherTexte("--> Photo dans 5 secondes")
  time.sleep(1)

def AfficherTexte(message): # pour pouvoir afficher des messages sur un fond noir
    screen.fill(pygame.Color(0,0,0))
    font = pygame.font.SysFont("verdana", 30, bold=1)
    textsurface = font.render(message, 1, pygame.Color(255,255,255))
  #  textpos = text.get_rect()
  #  textpos.centerx = background.get_rect().centerx
  #  textpos.centery = background.get_rect().centery

  #  if(ImageShowed):
  #      backgroundPicture.blit(text, textpos)
  #  else:
  #      background.blit(text, textpos)

    #screen.blit(textsurface,(240,240)) # Position x et y du texte
    #pygame.display.update()

def AfficherTexteTransparent(message): # pour pouvoir afficher des messages en conservant le fond
    font = pygame.font.SysFont("verdana", 30, bold=1)
    textsurface = font.render(message, 1, pygame.Color(255,255,255))
    screen.blit(textsurface,(35,40))
    pygame.display.update()

def AfficherTexteAccueil(message): # Afficher un Texte sur l'image d'accueil (ou à la place)
    font = pygame.font.SysFont("verdana", 30, bold=1)
    textsurface = font.render(message, 1, pygame.Color(100,150,200))
    screen.blit(textsurface,(35,40))
    pygame.display.update()

def Evenement(): #Est en charge de retourner TRUE ou FALSE
    global pygame

    RienNeSePasse = True #initialisation de la variable RienNeSePasse a TRUE. Il n'y a pas d'evenement, rien ne se passe.
    while RienNeSePasse: #tant qu'il n'y a pas d'evenement.... Tant que RienNeSePasse est au statut defini au-dessus
            input_state = GPIO.input(BUTTON_PIN) #...alors on va lire (GPIO.input()) le PIN (variable BUTTON_PIN initialisé à 25 au début). Correspond a TRUE. La variable input_state correspond a le lecture de l'entree BUTTON_PIN (25). Voir https://deusyss.developpez.com/tutoriels/RaspberryPi/PythonEtLeGpio/#LIII-A
            if input_state == False: #Si l'etat change (appui sur le bouton)...
                    RienNeSePasse = False #Alors on indique cette variable change.
                    return #On retourne l'etat
            for event in pygame.event.get(): #pygame.event.get() va lire les evenements en attente dans la queue ainsi que les y retirer.
                    if event.type == pygame.KEYDOWN: #Si dans la queue il y a un appui sur une touche du clavier...
                        if event.key == pygame.K_ESCAPE: #...et qu'il s'agit de la touche echap...
                            pygame.quit() #...alors on quitte le programme https://www.pygame.org/docs/ref/key.html#comment_pygame_key_name
                        if event.key == pygame.K_DOWN: #Toutefois s'il y a un appuisur la fleche du bas
                            RienNeSePasse = False #Alors on change l'etat et donc on attend 0.2s
                            return #On retourne l'etat
            time.sleep(0.2)

# Début du programme #

if (os.path.isdir("/home/pi/Desktop/photos") == False): # si le dossier pour stocker les photos n'existe pas
    os.mkdir("/home/pi/Desktop/photos")                  # alors on crée le dossier (sur le bureau)
    os.chmod("/home/pi/Desktop/photos",0o777)            # et on change les droits pour pouvoir effacer des photos

#AfficherTexteAccueil("Installez-vous et appuyez sur le bouton pour prendre une photo")

while True : #boucle jusqu'a interruption
    print ("\n attente boucle \n ")
    screensize = screen.get_rect() #Je veux récupérer la taille de l'écran...
    print ("L'écran fait", screensize) #...afin de l'afficher dans la console

     #On affiche la photo d'accueil
    AfficherPhoto("/home/pi/Photobooth/images/appuyezbouton.jpg")

     #on attend que le bouton soit pressé
    Evenement()
     # on a appuyé sur le bouton...
     #on lance le décompte
    decompte()
    pygame.display.flip()
     #on génère le nom de la photo avec heure_min_sec
    date_today = datetime.now()
    nom_image = date_today.strftime('%d-%m-%Y_%Hh-%Mm-%Ss') #Voir strftime de la doc https://docs.python.org/fr/3.6/library/datetime.html#strftime-strptime-behavior
     #on déclenche la prise de photo
    chemin_photo = '/home/pi/Desktop/photos/'+nom_image+'.jpeg'
    PrisePhoto(chemin_photo) #Déclenchement de la prise de photo
    AfficherTexte("--> Merci ! <--")
    time.sleep(1)
     #On affiche la photo...
    AfficherPhoto(chemin_photo)
     #...et par dessus on affiche un message
    AfficherTexteTransparent("OK ; voici ce qui est dans la boite ...")
    time.sleep(2) #Ajout d'un temps d'affichage afin de repartir sur l'accueil ensuite
    pygame.display.flip()
     #on recommence en rechargeant l'écran d'accueil
    #AfficherPhoto("/home/pi/Photobooth/images/appuyezbouton.jpg")
    #pygame.mixer.init()
    #son = pygame.mixer.Sound('/home/pi/Photomaton/son.wav')
    #canal = son.play()

    #if (GPIO.input(25) == 0): #si le bouton est encore enfoncé (son etat sera 0)
          #print ("Ho ; bouton  appuyé !!! Je dois sortir ; c'est le chef qui l'a dit !") #Va afficher ça dans la console
          #break # alors on sort du while

    #for event in pygame.event.get(): #pygame.event.get() va lire les evenements en attente dans la queue ainsi que les y retirer.
        #if event.type == pygame.KEYDOWN: #Si dans la queue il y a un appui sur la fleche du bas sur le clavier alors on attends 0.2s (fin de la fonction)
            #if event.key == pygame.K_ESCAPE: #Mais si il y a un appui sur la touche echap https://www.pygame.org/docs/ref/key.html#comment_pygame_key_name
                #print("Appui sur Echap, fin du programme")
                #pygame.quit() #Alors on quitte le programme

GPIO.cleanup()           # reinitialisation GPIO lors d'une sortie normale


# A - Rightmost
# https://atcoder.jp/contests/abc276/tasks/abc276_a

s = list(input())
idx = -1

for i in range(len(s)):
    char = s[i]
    if char == "a":
        idx = i

if idx == -1:
    print(-1)
else:
    print(idx + 1)


import dtlz
import random
import math
import hve
import sys
import sk

class candidate:
    num_objs = 10

    def __init__(self, decs):
        self.decs = decs
        self.fitness = None
        self.dom_count = 0

    # Calculate fitness of this candidate based on passed in fitness_family
    def calc_fitness(self, fitness_family):
        self.fitness = fitness_family(self.decs, self.num_objs, len(self.decs))
        return

    # Binary domination
    def __gt__(self, other):
        better = any([x < y for x,y in zip(self.fitness, other.fitness)])
        worse = any([x > y for x,y in zip(self.fitness, other.fitness)])
        return better and not worse

    def __repr__(self):
        return ",".join([str(x) for x in self.decs])

# Population is a collection of candidates and has the GA operations
class population:
    num_candidates = 10;
    fitness_family = None
    prob_mut = 0.05
    num_decs = 2

    def __init__(self, num_candidates = 10, fitness_family = dtlz.dtlz1):
        self.candidates = []
        self.num_candidates = num_candidates
        self.fitness_family = fitness_family

    # Initialize first generation
    def randomize(self):
        for i in range(self.num_candidates):
            can = candidate([])
            for j in range(self.num_decs):
                can.decs.append(random.random())
            can.calc_fitness(self.fitness_family)
            self.candidates.append(can)
        self.ap_binary_dom()

    # Cross over using random cross over point
    def crossover(self, candidate1, candidate2):
        crossover_point = random.randrange(0, self.num_decs)
        decs1 = []
        decs2 = []
        for i in range(0, crossover_point):
            decs1.append(candidate1.decs[i])
            decs2.append(candidate2.decs[i])
        for i in range(crossover_point, self.num_decs):
            decs1.append(candidate2.decs[i])
            decs2.append(candidate1.decs[i])
        can1 = candidate(decs1)
        can1.calc_fitness(self.fitness_family)
        can2 = candidate(decs2)
        can2.calc_fitness(self.fitness_family)
        return [can1, can2]

    def select(self):
        return self.weighted_wheel()

    # Mutate every bit with random probably
    def mutate(self, candidate):
        for i in range(0, self.num_decs):
            if random.random() < self.prob_mut:
                candidate.decs[i] = random.random()
        return

    def __repr__(self):
        return ",".join([can.__repr__() for can in self.candidates])

    # All pairs binary domination, dom_count is the number of other candidates a candidate dominates
    def ap_binary_dom(self):
        candidates = self.candidates
        n = self.num_candidates

        for i in range(0, n):
            for j in range(0, n):
                if i == j:
                    continue
                if candidates[i] > candidates[j]:
                    candidates[i].dom_count += 1

    # weighted wheel technique of selection based on dom_count
    def weighted_wheel(self):
        sumTemp = sum([x.dom_count for x in self.candidates])
        if sumTemp == 0:
            return self.candidates[random.randint(0, self.num_candidates-1)]
        rand = random.random()*sumTemp
        sumT = 0
        for i in range(0, self.num_candidates):
            sumT += self.candidates[i].dom_count
            if rand < sumT:
                return self.candidates[i]

# This class drives the GA algorithm
class GA:
    fitness_family = None
    num_candidates = 100

    def __init__(self, num_candidates = 10, fitness_family = dtlz.dtlz1, num_objs =10, num_decs = 2, prob_mut=0.05):
        self.generations = []
        self.current_generation = 0
        self.num_candidates = num_candidates
        self.fitness_family = fitness_family
        candidate.num_objs = num_objs
        population.num_decs = num_decs
        population.prob_mut = prob_mut
        return

    def randomize(self):
        gen1 = population(self.num_candidates, self.fitness_family)
        gen1.randomize()
        self.generations.append(gen1)
        return

    def next(self):
        curr_pop = self.generations[self.current_generation];
        next_pop = population(self.num_candidates, self.fitness_family)
        for i in range(0, self.num_candidates, 2):
            can1 = curr_pop.select()
            can2 = curr_pop.select()
            [crs1, crs2] = curr_pop.crossover(can1, can2)
            curr_pop.mutate(crs1)
            curr_pop.mutate(crs2)
            next_pop.candidates.append(crs1)
            next_pop.candidates.append(crs2)
        next_pop.ap_binary_dom()
        self.generations.append(next_pop)
        self.current_generation += 1
        return

    def hvdata(self, hveCurr):
        hveCurr.add_data(self.generations[self.current_generation])

    def calc_a12(self):
        if self.current_generation % 100 != 99 or self.current_generation < 199:
            return 0
        gen1 = []
        gen2 = []
        for i in range(self.current_generation-199, self.current_generation-99):
            gen1 += self.generations[i].candidates
        for i in range(self.current_generation-99, self.current_generation+1):
            gen2 += self.generations[i].candidates
        sum1 = [sum(c.fitness) for c in gen1]
        sum2 = [sum(c.fitness) for c in gen2]
        a12 = sk.a12(sum1, sum2)
        return 1 if a12 > 0.56 else 0

    def run(self, num_generations=1000):
        self.randomize()
        hveCurr = hve.HVE()
        num_lives = 5
        for i in range(0, num_generations):
            self.next()
            self.hvdata(hveCurr)
            num_lives -= self.calc_a12()
            if num_lives == 0:
                break
        return hveCurr.pareto_last()

objs = [2,4,6,8]
decs = [10,20,40]
fitness_family = [dtlz.dtlz1, dtlz.dtlz3, dtlz.dtlz5, dtlz.dtlz7]
ff_names = ["dtlz1", "dtlz3", "dtlz5", "dtlz7"]

def run_all():
    for num_objs in objs:
        for num_decs in decs:
            for f in range(0, len(fitness_family)):
                ff = fitness_family[f]
                fname = ff_names[f]
                sys.stderr.write("{0}-{1}-{2}\n".format(fname, num_objs, num_decs))
                filedes = open("data/ga-{0}-{1}-{2}.txt".format(fname, num_objs, num_decs), 'w')
                run_one_n_times(num_candidates=100, fitness_family=ff, num_objs=num_objs, num_decs=num_decs, num_generations=1000, filedes=filedes)
                filedes.close()

def run_one_n_times(num_candidates, fitness_family, num_objs, num_decs, num_generations, filedes, num_runs=20):
    results = []
    for i in range(0, num_runs):
        sys.stderr.write("Run " + str(i) + "\n")
        ga = GA(num_candidates, fitness_family, num_objs, num_decs)
        hve_res = ga.run(num_generations)
        results.append(hve_res)

    hyper_vols = [res.hyper_vol for res in results]
    filedes.write("Hypervolume: " + str(hyper_vols) + "\n")
    filedes.write("Spread: " + str([str(res.spread) for res in results]) + "\n")

    avg = sum(hyper_vols) / len(hyper_vols)
    hmax = max(hyper_vols)
    hmin = min(hyper_vols)
    dev = max([hmax-avg,avg-hmin])
    filedes.write("Hypervolume Deviation: " + str(avg) + "+-" + str(dev) + "\n")

### Scripts

### Run one instance of GA 20 times. Results are collected in the file ga.txt
#filedes = open("ga.txt", 'w')
#run_one_n_times(num_candidates=25, fitness_family=dtlz.dtlz1, num_objs=2, num_decs=10, num_generations=150, filedes=filedes, num_runs=20)

#### Run one instance of GA
#ga = GA(num_candidates=100, fitness_family=dtlz.dtlz1, num_objs=2, num_decs=10, prob_mut=0.05)
#hve1 = ga.run(num_generations=1000)
#print "Hyper volume: " + str(hve1.hyper_vol)
#print "Spread: " + str(hve1.spread)

### Run all instances of GA 20 times (warning: this takes hours)
#run_all()


def solution(m, n, board):
    answer = 0

    # 회전
    newboard = rotate90(m,n,board)

    while 1:
        # 사라지는 블럭이 있는지
        flag = False

        # 사라질 블럭 체크하는 테이블
        check = [ [True for _ in range(m)] for _ in range(n)]

        for r in range(n-1):
            for c in range(m-1):
                # 2*2 블럭 찾은 경우
                if newboard[r][c] != '*' and newboard[r][c] == newboard[r+1][c] == newboard[r][c+1] == newboard[r+1][c+1]:
                    # 사라질 블럭 체크
                    check[r][c] = check[r+1][c] = check[r][c+1] = check[r+1][c+1] = False
                    flag = True

        for r in range(n):
            # 블럭 사라진 뒤에 로우 구하기
            newRow = ['*' for _ in range(m)]
            idx = 0
            # 왼쪽부터 채워 나감 -> 90도 돌려서 가능
            for c in range(m):
                if check[r][c]:
                    newRow[idx] = newboard[r][c]
                    idx = idx + 1
                else :
                    # 사라지는 블럭 합산
                    answer = answer + 1

            newboard[r] = newRow

        # 하나도 안사라지는 경우 break
        if not flag :
            break

    return answer

def rotate90(row,columm,board):
    ret = [[0] * row for _ in range(columm)]
    for r in range(row):
        for c in range(columm):
            ret[c][row-1-r] = board[r][c]
    return ret

def printTable(board):
    for i in board:
        for j in i:
            print(j,end='')
        print('')

print(solution(7, 2, ["AA", "BB", "AA", "BB", "ZZ", "ZZ", "CC"]))
print(solution(4 , 5, ["AAAAA","AUUUA","AUUAA","AAAAA"] ))
print(solution(6 , 6, ["AABBFF","AAAFFF","VAAFFV","AABBFF","AACCFF","VVCCFF" ] ))


from decimal import Decimal
from django.conf import settings
from django.shortcuts import get_object_or_404
from products.models import Product

def bag_contents(request):
    """
    Context processor
    Returns context dictionary of data for the shopping bag
    The function is avaliable accross all the templates
    """

    # setting up vars
    # list of dicts containing item_id, quantitiy and the product obj
    bag_items = []
    total = 0
    product_count = 0
    # get the var if it exists or assign empty dict
    bag = request.session.get('bag', {})

    # using bag items to calc the total, items and product_count
    # item_id is the key and quantity is its value
    for item_id, quantity in bag.items():
        # checks that the item is not found for the bag if its been deleted
        if Product.objects.filter(pk=item_id).exists():
            # get the product
            product = Product.objects.get(pk=item_id)
            total += quantity * product.price
            product_count += quantity
            bag_items.append({
                'item_id': item_id,
                'quantity': quantity,
                'product': product,
                'sub_total': (product.price * quantity)
            })

    if total < settings.FREE_DELIVERY_THRESHOLD:
        # decimal is more accurate than float for rounding
        delivery = total * Decimal(settings.STANDARD_DELIVERY_PERCENTAGE / 100)

        # to show the user how much more they need to spend for free delivery
        free_delivery_delta = settings.FREE_DELIVERY_THRESHOLD - total
    else:
        delivery = 0
        free_delivery_delta = 0

    grand_total = total + delivery

    context = {
        'bag_items': bag_items,
        'product_count': product_count,
        'total': total,
        'delivery': delivery,
        'grand_total': grand_total,
        'free_delivery_delta': free_delivery_delta,
        'free_delivery_threshold': settings.FREE_DELIVERY_THRESHOLD,
    }

    return context


from ...base.time_evolution import TimeEvolution
from ...base.utils import allclose
from ..initializer import Allocator, Initializer
from ..registers import Registers
from ..transformer import TimeEvolveTransformer

class TestAllocator:
    """
    Allocatorクラスと付随するメソッドのテスト
        * 以下のロジックはテストしない
            * ただ値を代入するだけのロジック
            * すでにテスト済みの値を代入するロジック
            * 既存オブジェクトを出力するだけのロジック
    """

    def test_for_success_allocator_allocate(
        self, dict_for_test_success_allocator_allocate
    ):
        """allocateメソッドの正常系テスト"""
        dict_for_test = dict_for_test_success_allocator_allocate

        qubit_count = dict_for_test["qubit_count"]
        register_count = dict_for_test["register_count"]
        qubits = dict_for_test["qubits"]
        registers = Registers(register_count)
        for index in range(len(dict_for_test["registers"])):
            if dict_for_test["registers"][index] is not None:
                registers.put(index, dict_for_test["registers"][index])

        state = Allocator(qubit_count, register_count).allocate()
        assert allclose(qubits.matrix, state.qubits.matrix)
        for index in range(register_count):
            assert state.registers.get(index) == registers.get(index)

class TestInitializer:
    """
    Initializerクラスと付随するメソッドのテスト
        * 以下のロジックはテストしない
            * ただ値を代入するだけのロジック
            * すでにテスト済みの値を代入するロジック
            * 既存オブジェクトを出力するだけのロジック
    """

    def test_for_success_initializer_initialize(
        self, dict_for_test_success_initializer_initialize
    ):
        """initializeメソッドの正常系テスト"""
        dict_for_test = dict_for_test_success_initializer_initialize

        qubit_count = dict_for_test["qubit_count"]
        register_count = dict_for_test["register_count"]
        qubits = dict_for_test["qubits"]
        registers = Registers(register_count)
        for index in range(len(dict_for_test["registers"])):
            if dict_for_test["registers"][index] is not None:
                registers.put(index, dict_for_test["registers"][index])
        time_evolutions = [
            TimeEvolveTransformer(TimeEvolution(dict_for_test["unitary"]))
        ]

        allocator = Allocator(qubit_count, register_count)
        initializer = Initializer(allocator, time_evolutions)
        state = initializer.initialize()
        assert allclose(qubits.matrix, state.qubits.matrix)
        for index in range(register_count):
            assert state.registers.get(index) == registers.get(index)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Jaap.nl scraping - main script
By dr.Pep
"""

# Built-in/Generic imports

# Libs
# import time
# import numpy as np
from datetime import date, datetime
import pandas as pd
import logging
import os, uuid, sys
# from azure.storage.blob import BlockBlobService, PublicAccess, ContentSettings

# Own modules

import ScrapeJaap
from MyConstants import * # This way you get the constants without filename as prefix

# Authorship
__author__ = 'dr.Pep'
__copyright__ = 'Copyright 2019, dr.Pep'
__credits__ = 'Thanks to the magnificent Py4e and PCC'
__licence__ = 'All rights reserved'
__version__ = '0.0.1'
__maintainer__ = 'dr.Pep'
__email__ = 'python@vdlaan.eu'
__status__ = 'In development'

# Set up logging
logging.basicConfig(filename = LOGDATA + LOGFILE,
                    level = logging.DEBUG)
logging.info('Running script MainJaap.py | Time stamp: ' + datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
logging.info('Website to be scraped: ' + str(URL))
logging.info('Number of pages: ' + str(MAXPAGE))

# Scrape all summary pages
for p in range(MAXPAGE):
    # Log where we are
    # logging.info('Scraping summary page ' + str(p+1))
    # Read page
    df_houses_read = ScrapeJaap.read_summary_page(URL,p+1)
    if p == 0:
        df_houses_summary = df_houses_read
    else:
        df_houses_summary = pd.concat(
            [df_houses_summary,df_houses_read],
            ignore_index=True,
            sort =False
        )

# Write summary to file
df_houses_summary.to_csv(PROJECTDATA + SUMMARYFILE,index=False,header=True)

logging.info('Summaries of all ' + str(len(df_houses_summary)) + ' houses have been written to file!')

# Scrape all detail pages
for i in df_houses_summary.index:
    # Start with logging where we are
    # logging.info('Scraping detail page '+ str(i))

    # Read the page with details
    df_detail_read = ScrapeJaap.read_house_detail_page(
        df_houses_summary['link'][i],
        df_houses_summary['pricetype'][i],
        df_houses_summary['id'][i]
    )

    # Some error handling - when page cannot be read
    if type(df_detail_read) == bool:
        logging.warning(
            'Index:' + str(i)
            + ' | Address:' + str(df_houses_summary['address'][i])
            + ' | ID:'+ str(df_houses_summary['id'][i]) + ' | Scraping failed'
        )
        continue

    # Put the scraped data into a data frame
    if i == 0:
        df_houses_detail = df_detail_read
    else:
        df_houses_detail= pd.concat(
            [df_houses_detail,df_detail_read],
            ignore_index=True,
            sort =False
        )

# Write data frame with all house details to file
df_houses_detail.to_csv(PROJECTDATA + DETAILFILE,index=False,header=True)

# Log our success
logging.info('Details of '+str(len(df_houses_detail))+' houses have been written to file!')

# Write Summary and Detail files to blobs
# THE BELOW DOES NOT WORK WITHOUT SAS TOKEN (currently empty)
#
# blob_service = BlockBlobService(account_name = ACCOUNT_NAME, account_key = None, sas_token = SAS_TOKEN)
#
# blob_service.create_blob_from_path(
#     CONTAINER_NAME,
#     LOGFILE,
#     RAWDATA + LOGFILE)
# blob_service.create_blob_from_path(
#     CONTAINER_NAME,
#     SUMMARYFILE,
#     PROJECTDATA + SUMMARYFILE)
# blob_service.create_blob_from_path(
#     CONTAINER_NAME,
#     DETAILFILE,
#     PROJECTDATA + DETAILFILE)