import csv

from django.core.management.base import BaseCommand

from ...models import *

# Usage example: python manage.py import_from_csv IA "<filename.csv>"

class Command(BaseCommand):
    help = "Load polling location data from a spreadsheet"

    def add_arguments(self, parser):
        parser.add_argument("state_code")
        parser.add_argument("file")

    def handle(self, *args, **options):
        state_code = options["state_code"]
        file_name = options["file"]
        lid = 1
        reader = csv.DictReader(open(file_name))
        for row in reader:
            print(row)
            precinct, created = Precinct.objects.get_or_create(
                van_precinct_id=row.get("Precinct ID"),
                state_code=state_code,
                county=row.get("County"),
                precinct_code=row.get("Precinct Code"),
            )
            precinct.save()

            polling_location = PollingLocation(
                location_id=lid,
                location_name=row.get("Location Name"),
                address=row.get("Street Address"),
                city=row.get("City"),
                state_code=state_code,
                zip=row.get("Zip Code"),
            )
            polling_location.save()

            ptpl = PrecinctToPollingLocation(
                precinct=precinct,
                state_code=state_code,
                distance=1.0,
                location=polling_location,
            )
            ptpl.save()
            lid += 1


from collections import namedtuple

#: Wrapper class for values that don't have to be quoted.
atom = namedtuple("atom", ("value",))

#: The set of characters that must be escaped before being sent as
#: Redis strings.
escapes = {
    ord(b"\0"): rb"\x00",
    ord(b"\n"): rb"\n",
    ord(b"\r"): rb"\r",
    ord(b"\\"): rb"\\",
    ord(b'"'): rb'\"',
}

def serialize(x):
    """Serialize `x` so that it can safely be sent to Redis.

    Parameters:
      x(object): The value to serialize.

    Returns:
      bytes: The serialized value.
    """
    if isinstance(x, atom):
        return x.value
    elif isinstance(x, bytes):
        return quote(x)
    elif isinstance(x, str):
        return quote(x.encode("utf-8"))
    elif isinstance(x, (float, int)):
        return str(x).encode("ascii")
    else:
        return serialize(str(x))

def quote(bs):
    return b'"' + bytes(escape(bs)) + b'"'

def escape(bs):
    for c in bs:
        if c in escapes:
            yield from escapes[c]
        else:
            yield c


from pathlib import Path

import pandas as pd

from lmentry.constants import HOMOPHONES_PATH
from lmentry.scorers.homophone_scorer import HomophoneScorer
from lmentry.tasks.task import LMentryTask

class Homophones(LMentryTask):

    scorer_cls = HomophoneScorer

    def __init__(self, name="homophones"):
        super().__init__(name)
        self.canonical_template = "Q: Which word sounds like the word \"{query}\", \"{word1}\" or \"{word2}\"?\nA:"
        self.second_template = "Q: Of the two words \"{word1}\" and \"{word2}\", which one sounds more like \"{query}\"?\nA:"
        self.third_template = "Q: Which is a homophone of the word \"{query}\", \"{word1}\" or \"{word2}\"?\nA:"
        self.all_templates = [self.canonical_template, self.second_template, self.third_template]
        self.parameter_names = ["query", "answer", "distractor"]

    def create_data(self, homophones_path: Path = None, task_data_path: Path = None):

        homophones_path = homophones_path or HOMOPHONES_PATH
        homophones_data = pd.read_csv(homophones_path)

        examples = {}
        for template_id, template in enumerate(self.all_templates):
            for _, row in homophones_data.iterrows():
                query = row["word"]
                homophone = row["homophone"]
                for distractor_name in ("easy1", "easy2", "semantic1", "semantic2"):
                    distractor = row[distractor_name]
                    for answer_index in (0, 1):
                        word1 = homophone if answer_index == 0 else distractor
                        word2 = distractor if answer_index == 0 else homophone

                        input_ = template.format(query=query, word1=word1, word2=word2)

                        # create the metadata
                        metadata = dict()
                        metadata["query"] = query
                        metadata["answer"] = homophone
                        metadata["distractor"] = distractor
                        metadata["distractor_type"] = distractor_name[:-1]
                        metadata["answer_index"] = answer_index
                        metadata["template_id"] = template_id

                        # create the example
                        example = dict()
                        example["input"] = input_
                        example["metadata"] = metadata
                        examples[str(len(examples) + 1)] = example

        # create the shared settings
        settings = dict()
        settings["canary"] = self.canary_string
        settings["name"] = self.name
        settings["num_examples_per_template"] = int(len(examples) / len(self.all_templates))
        settings["input_templates"] = self.all_templates

        # build the task_data
        task_data = dict()
        task_data["settings"] = settings
        task_data["examples"] = examples

        # save the data
        self.save_task_data(task_data, task_data_path)

if __name__ == '__main__':
    task = Homophones()


#!/usr/bin/env python
# coding: utf-8

# In[1]:

from PyQt5 import QtCore, QtGui, QtWidgets, Qt
import datetime

from clsOneOfFour import *
from clsClearTranslator import *

class Ui_FormTestSetup(object):
    def setupUi(self, FormTestSetup):
        FormTestSetup.setObjectName("FormTestSetup")
        FormTestSetup.resize(400, 433)
        self.spinBoxCount = QtWidgets.QSpinBox(FormTestSetup)
        self.spinBoxCount.setGeometry(QtCore.QRect(20, 238, 101, 22))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.spinBoxCount.setFont(font)
        self.spinBoxCount.setMinimum(3)
        self.spinBoxCount.setSingleStep(1)
        self.spinBoxCount.setObjectName("spinBoxCount")
        self.rbtnForward = QtWidgets.QRadioButton(FormTestSetup)
        self.rbtnForward.setGeometry(QtCore.QRect(50, 110, 82, 17))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.rbtnForward.setFont(font)
        self.rbtnForward.setObjectName("rbtnForward")
        self.rbtnReverse = QtWidgets.QRadioButton(FormTestSetup)
        self.rbtnReverse.setGeometry(QtCore.QRect(50, 150, 82, 17))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.rbtnReverse.setFont(font)
        self.rbtnReverse.setObjectName("rbtnReverse")
        self.btnBack = QtWidgets.QPushButton(FormTestSetup)
        self.btnBack.setGeometry(QtCore.QRect(320, 390, 75, 23))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.btnBack.setFont(font)
        self.btnBack.setObjectName("btnBack")
        self.btnOK = QtWidgets.QPushButton(FormTestSetup)
        self.btnOK.setGeometry(QtCore.QRect(220, 390, 75, 23))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.btnOK.setFont(font)
        self.btnOK.setObjectName("btnOK")
        self.label = QtWidgets.QLabel(FormTestSetup)
        self.label.setGeometry(QtCore.QRect(130, 10, 181, 21))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(14)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.label_3 = QtWidgets.QLabel(FormTestSetup)
        self.label_3.setGeometry(QtCore.QRect(20, 200, 251, 31))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.spinBoxTime = QtWidgets.QSpinBox(FormTestSetup)
        self.spinBoxTime.setGeometry(QtCore.QRect(20, 330, 101, 22))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.spinBoxTime.setFont(font)
        self.spinBoxTime.setMinimum(1)
        self.spinBoxTime.setMaximum(60)
        self.spinBoxTime.setSingleStep(2)
        self.spinBoxTime.setProperty("value", 10)
        self.spinBoxTime.setObjectName("spinBoxTime")
        self.checkBox = QtWidgets.QCheckBox(FormTestSetup)
        self.checkBox.setGeometry(QtCore.QRect(20, 296, 161, 21))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.checkBox.setFont(font)
        self.checkBox.setObjectName("checkBox")
        self.label_4 = QtWidgets.QLabel(FormTestSetup)
        self.label_4.setGeometry(QtCore.QRect(20, 70, 251, 31))
        font = QtGui.QFont()
        font.setFamily("Microsoft YaHei UI")
        font.setPointSize(11)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")

        self.retranslateUi(FormTestSetup)
        QtCore.QMetaObject.connectSlotsByName(FormTestSetup)

    def retranslateUi(self, FormTestSetup):
        _translate = QtCore.QCoreApplication.translate
        FormTestSetup.setWindowTitle(_translate("FormTestSetup", "Form"))
        self.rbtnForward.setText(_translate("FormTestSetup", "Forward"))
        self.rbtnReverse.setText(_translate("FormTestSetup", "Reverse"))
        self.btnBack.setText(_translate("FormTestSetup", "Back"))
        self.btnOK.setText(_translate("FormTestSetup", "OK"))
        self.label.setText(_translate("FormTestSetup", "Test setup"))
        self.label_3.setText(_translate("FormTestSetup", "Number of questions in the test:"))
        self.checkBox.setText(_translate("FormTestSetup", "Set response time"))
        self.label_4.setText(_translate("FormTestSetup", "Translation direction:"))

class TestSetup(QtWidgets.QWidget):
    def __init__(self, root, test_type='oof', parent=None):
        QtWidgets.QWidget.__init__(self, parent)
        self.ui = Ui_FormTestSetup()
        self.ui.setupUi(self)
        self.main = root
        self.df = root.df
        self.test_type = test_type
        self.directForward = True
        self.initUI()

    def initUI(self):
        self.rbtn_group = QtWidgets.QButtonGroup()
        self.rbtn_group.addButton(self.ui.rbtnForward)
        self.rbtn_group.addButton(self.ui.rbtnReverse)
        self.rbtn_group.buttonClicked.connect(self.rbtn_checked)

        self.ui.rbtnForward.setChecked(True)
        self.ui.spinBoxCount.setMaximum(len(self.df)-4)
        self.ui.btnOK.clicked.connect(self.go_ok)
        self.ui.btnBack.clicked.connect(self.close)
        self.show()

    def rbtn_checked(self, btn):
        if btn == self.ui.rbtnForward:
            self.directForward = True
        else:
            self.directForward = False

    def go_ok(self):
        if self.ui.checkBox.isChecked():
            self.time_is_set = True
            self.timer_val = self.ui.spinBoxTime.value()
        else:
            self.time_is_set = False
            self.timer_val = 0
        self.count = int(self.ui.spinBoxCount.value())
        if self.test_type == 'oof':
            self.tester = OneOfFour(self)
        elif self.test_type == 'ct':
            self.tester = ClearTranslator(self)
        else:
            raise ValueError(f'Invalid test cipher: {self.test_type}')
        self.close()


#!/usr/bin/env python3

import sys
import argparse as ap
import chemprop

# to make chemprop work with --proparg_combinat/--proparg_stereo,
# patch ${CONDA_PREFIX}/lib/python3.8/site-packages/chemprop/rdkit.py
# with cgr_proparg_patch.txt

def argparse():
    parser = ap.ArgumentParser()
    g1 = parser.add_mutually_exclusive_group(required=True)
    g1.add_argument('--true', action='store_true', help='use true atom mapping')
    g1.add_argument('--random', action='store_true', help='use random atom mapping')
    g1.add_argument('--rxnmapper', action='store_true', help='use atom mapping from rxnmapper')
    g1.add_argument('--nomapping', action='store_true', help='use without atom mapping')
    g2 = parser.add_mutually_exclusive_group(required=True)
    g2.add_argument('-c', '--cyclo', action='store_true', help='use Cyclo-23-TS dataset')
    g2.add_argument('-g', '--gdb', action='store_true', help='use GDB7-22-TS dataset')
    g2.add_argument('-p', '--proparg', action='store_true', help='use Proparg-21-TS dataset with SMILES from xyz')
    g2.add_argument('--proparg_combinat', action='store_true', help='use Proparg-21-TS dataset with fragment-based SMILES')
    g2.add_argument('--proparg_stereo', action='store_true', help='use Proparg-21-TS dataset with stereochemistry-enriched fragment-based SMILES')
    parser.add_argument('--withH', action='store_true', help='use explicit H')
    args = parser.parse_args()
    return parser, args

if __name__ == "__main__":

    parser, args = argparse()
    if args.cyclo:
        data_path = '../../data/cyclo/full_dataset.csv'
        target_columns = 'G_act'
    elif args.gdb:
        data_path = '../../data/gdb7-22-ts/ccsdtf12_dz.csv'
        target_columns = 'dE0'
    elif args.proparg:
        data_path = '../../data/proparg/data.csv'
        target_columns = "Eafw"
    elif args.proparg_combinat:
        data_path = '../../data/proparg/data_fixarom_smiles.csv'
        target_columns = "Eafw"
    elif args.proparg_stereo:
        data_path = '../../data/proparg/data_fixarom_smiles_stereo.csv'
        target_columns = "Eafw"

    if args.random:
        smiles_columns = 'rxn_smiles_random'
    elif args.rxnmapper:
        smiles_columns = 'rxn_smiles_rxnmapper'
    elif args.nomapping:
        if args.proparg or args.proparg_combinat or args.proparg_stereo:
            smiles_columns = 'rxn_smiles'
        else:
            smiles_columns = 'rxn_smiles_nomapping'
    elif args.true:
        if args.proparg or args.proparg_combinat or args.proparg_stereo:
            smiles_columns = 'rxn_smiles_mapped'
        else:
            smiles_columns = 'rxn_smiles'

    arguments = [
        "--data_path", data_path,
        "--dataset_type",  "regression",
        "--target_columns", target_columns,
        "--smiles_columns", smiles_columns,
        "--metric", "mae",
        "--dropout", "0.05",
        "--epochs", "300",
        "--reaction",
        "--num_folds",  "10",
        "--batch_size", "50",
        "--save_dir", "./"]
    if args.withH:
        arguments.append('--explicit_h')

    args_chemprop = chemprop.args.TrainArgs().parse_args(arguments)
    mean_score, std_score = chemprop.train.cross_validate(args=args_chemprop, train_func=chemprop.train.run_training)
    print("Mean score", mean_score, "std_score", std_score)


from django.conf.urls import url
from . import views           # This line is new!
urlpatterns = [
    url(r'^$', views.index),
    url(r'^register$', views.register),
    url(r'^login$', views.login),
    url(r'^books$', views.user),
    url(r'^books/add$', views.add),
    url(r'^books/add_review$', views.add_review),
    url(r'^books/create$', views.create),
    url(r'^logout$', views.logout),
    url(r'^books/(\d+)', views.book),
    url(r'^users/(\d+)', views.profile)
]


import math
n = int(input()) # 시험장의 개수
people = list(map(int, input().split()))
master_available, vice_available = map(int, input().split())
answer = 0
for i in range(n):
    people[i] -= master_available
    if people[i] < 0:
        people[i] = 0
    answer += 1
for i in range(n):
    answer += math.ceil(people[i] / vice_available)
print(answer)


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  #warning message won't appear when run app

    db.init_app(app) # Initialiaze sqlite database

    login_manager = LoginManager() # Create a Login Manager instance
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app) # configure it for login

    from models import User
    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    from auth import auth as auth_blueprint
    from main import main as main_blueprint

    app.register_blueprint(auth_blueprint)
    app.register_blueprint(main_blueprint)

    return app


from dataset.reddit_user_dataset import RedditUserDataset
from dataset.reddit_user_dataset import convert_timeframes_to_model_input
from utils.feature_computing import Embedder
import pickle as pkl
import random
import gzip
import time
import os
from os import listdir
from utils.file_sort import path_sort
from argparse import ArgumentParser
import numpy as np
from os.path import isfile, join
import json
from utils.utils import *
import torch

parser = ArgumentParser()
parser.add_argument("--base_dataset", dest="base_dataset_path", required=True, type=str)
parser.add_argument("--source_frames", dest="source_frames_path", required=True, type=str)
parser.add_argument("--sample_dir", dest="sample_dir", required=True, type=str)
parser.add_argument("--n_users", dest="n_users", default=300, type=int)
parser.add_argument("--n_train_samples", dest="n_train_samples", default=800, type=int)
parser.add_argument("--n_val_samples", dest="n_val_samples", default=200, type=int)
parser.add_argument("--n_test_samples", dest="n_test_samples", default=1, type=int)
parser.add_argument("--threshold", dest="threshold", default=0.8, type=float)
parser.add_argument("--percentage", dest="percentage", default=1, type=float)
parser.add_argument("--root_seed", dest="root_seed", default=1337, type=int)

parser.add_argument("--train_min_index", dest="train_min_index", default=0, type=int)
parser.add_argument("--train_max_index", dest="train_max_index", default=1, type=int)
parser.add_argument("--val_min_index", dest="val_min_index", default=0, type=int)
parser.add_argument("--val_max_index", dest="val_max_index", default=1, type=int)
parser.add_argument("--test_min_index", dest="test_min_index", default=0, type=int)
parser.add_argument("--test_max_index", dest="test_max_index", default=1, type=int)

parser.add_argument("--user_ids", dest="user_ids", required=False, type=str, default="../data/reddit_dataset/user_splits/")
parser.add_argument("--random_features", dest="random_features", required=False, default=False, type=str2bool)

if __name__ == '__main__':
    args = parser.parse_args()
    base_dataset = RedditUserDataset.load_from_file(args.base_dataset_path, compression='gzip')

    # Build ground truth
    ground_truth = {}
    for _, row in base_dataset.data_frame.iterrows():
        ground_truth[row['user_id']] = row['fake_news_spreader']

    source_frame_dir = args.source_frames_path
    target_dir = args.sample_dir

    print("Running model dataloader with target dir {}".format(target_dir))

    if not os.path.exists(os.path.join(target_dir, 'train_samples/')):
        os.makedirs(os.path.join(target_dir, 'train_samples/'))
    if not os.path.exists(os.path.join(target_dir, 'val_samples/')):
        os.makedirs(os.path.join(target_dir, 'val_samples/'))
    if not os.path.exists(os.path.join(target_dir, 'test_samples/')):
        os.makedirs(os.path.join(target_dir, 'test_samples/'))

    train_min_index = args.train_min_index
    train_max_index = args.train_max_index
    val_min_index = args.val_min_index
    val_max_index = args.val_max_index
    test_min_index = args.test_min_index
    test_max_index = args.test_max_index
    n_users = args.n_users
    n_train_samples = args.n_train_samples
    n_val_samples = args.n_val_samples
    n_test_samples = args.n_test_samples
    threshold = args.threshold
    percentage = args.percentage
    ROOT_SEED = args.root_seed

    source_graph_descriptor = pkl.load(
        gzip.open(os.path.join(args.source_frames_path, 'source_graph_descriptor.data'), 'rb'))

    doc_embedding_file_path = [source_graph_descriptor['embedding_file_path']]
    embed_type = source_graph_descriptor['embed_type']
    doc_embedding_file_header = 'embedding_file'
    embed_mode = source_graph_descriptor['embed_mode']

    if 'dim' in source_graph_descriptor:
        dim = source_graph_descriptor['dim']
    else:
        dim = 768

    if 'merge_liwc' in source_graph_descriptor:
        merge_liwc = source_graph_descriptor['merge_liwc']
        if merge_liwc:
            print("Merging with LIWC")
            doc_embedding_file_path.append('../data/embeddings/psycho/' )

    dataset_descriptor = {}
    dataset_descriptor['n_users'] = n_users
    dataset_descriptor['n_train_samples'] = n_train_samples
    dataset_descriptor['n_val_samples'] = n_val_samples
    dataset_descriptor['n_test_samples'] = n_test_samples
    dataset_descriptor['threshold'] = threshold
    dataset_descriptor['percentage'] = percentage
    dataset_descriptor['root_seed'] = ROOT_SEED
    dataset_descriptor['base_dataset'] = args.base_dataset_path
    dataset_descriptor['source_frames'] = args.source_frames_path
    dataset_descriptor['embed_mode'] = embed_mode
    dataset_descriptor['time_splits'] = [[train_min_index, train_max_index],
                                        [val_min_index, val_max_index],
                                        [test_min_index, test_max_index]]
    dataset_descriptor['doc_embedding_file_path'] = doc_embedding_file_path
    dataset_descriptor['doc_embedding_file_header'] = doc_embedding_file_header
    dataset_descriptor['user_ids'] = args.user_ids

    json.dump(dataset_descriptor, open(os.path.join(target_dir, 'dataset_descriptor.json'), 'w'))

    random.seed(ROOT_SEED)
    np.random.seed(ROOT_SEED)
    sampling_seeds = [int(random.uniform(0, 1000000)) for i in range(n_train_samples + n_test_samples + n_val_samples)]

    embedder = Embedder(doc_embedding_file_path, embed_type, dim)

    timeframed_dataset = []

    for graph in path_sort(
            [join(source_frame_dir, f) for f in listdir(source_frame_dir) if isfile(join(source_frame_dir, f))]):
        if "source_graph_descriptor.data" in graph:
            continue
        print(graph)
        timeframe_ds = RedditUserDataset.load_from_instance_file(graph)
        timeframe_ds.shorten_similarity_triplet_list(threshold)
        timeframed_dataset.append(timeframe_ds)
        doc_sum = 0
        users = 0
        for index, row in RedditUserDataset.load_from_instance_file(graph).data_frame.iterrows():
            users += 1

    # Split user
    train_ids = read_userids('train_ids.txt', args.user_ids)
    val_ids = read_userids('val_ids.txt', args.user_ids)
    test_ids = read_userids('test_ids.txt', args.user_ids)
    print(len(train_ids))
    print(len(val_ids))
    print(len(test_ids))

    # Validating the splits
    for uid in train_ids:
        if uid in val_ids:
            raise Exception("Invalid split!")
        if uid in test_ids:
            raise Exception("Invalid split")

    for uid in val_ids:
        if uid in test_ids:
            raise Exception("Invalid split!")

    train_sample_frame = base_dataset.filter_user_ids(train_ids, inplace=False).data_frame
    print(len(train_sample_frame))
    val_sample_frame = base_dataset.filter_user_ids(val_ids, inplace=False).data_frame
    print(len(val_sample_frame))
    test_sample_frame = base_dataset.filter_user_ids(test_ids, inplace=False).data_frame
    print(len(test_sample_frame))

    precomputed_features = {}
    not_embedded_users = set()
    for _, row in base_dataset.data_frame.iterrows():
        precomputed_features[row['user_id']] = []

    if not args.random_features:
        for time_index, frame in enumerate(timeframed_dataset):
            print('Precomputing features for timeframe...')
            feature_map, current_not_emb_users = frame.compute_features(embedder, time_index=time_index, embed_mode=embed_mode)
            not_embedded_users.update(current_not_emb_users)

            for index, feature in feature_map.items():
                if index in precomputed_features.keys():
                    precomputed_features[index].append(feature_map[index])
    else:
        for frame in timeframed_dataset:
            print('Precomputing random features...')
            for _, row in frame.data_frame.iterrows():
                precomputed_features[row['user_id']].append(torch.tensor(np.random.uniform(low=-1.5, high=1.5, size=dim)))

    print("Could not embed {} users".format(len(not_embedded_users)))
    seed_counter = -1

    train_sample_frame = train_sample_frame[~train_sample_frame['user_id'].isin(not_embedded_users)]
    val_sample_frame = val_sample_frame[~val_sample_frame['user_id'].isin(not_embedded_users)]
    test_sample_frame = test_sample_frame[~test_sample_frame['user_id'].isin(not_embedded_users)]

    start = time.time()
    for n in range(n_train_samples):
        seed_counter += 1
        sample_ids = train_sample_frame.sample(n=n_users, random_state=sampling_seeds[seed_counter])['user_id']
        sample_frames = [frame.filter_user_ids(sample_ids, inplace=False) for frame in timeframed_dataset]

        start_frame = train_min_index
        train_window = train_max_index - train_min_index
        print(start_frame)
        print(start_frame + train_window)
        sample_frames = sample_frames[start_frame:start_frame + train_window]

        sample_frames = [
            tf.build_graph_column_precomputed(threshold=threshold, percentage=percentage, inplace=False).data_frame for
            _, tf in
            enumerate(sample_frames)]

        sample = convert_timeframes_to_model_input(sample_frames, {k: v[start_frame:start_frame + train_window] for k, v in
                                                                precomputed_features.items()}, ground_truth, dim)
        sample.print_shapes()
        pkl.dump(sample, gzip.open(os.path.join(target_dir, 'train_samples/') + 'sample_' + str(n) + '.data', 'wb'))

    end = time.time()
    print("Elapsed time:" + str(end - start))

    start = time.time()
    for n in range(n_val_samples):
        seed_counter += 1
        sample_ids = val_sample_frame.sample(n=n_users, random_state=sampling_seeds[seed_counter])['user_id']
        sample_frames = [frame.filter_user_ids(sample_ids, inplace=False) for frame in timeframed_dataset]

        start_frame = val_min_index
        val_window = val_max_index - val_min_index

        print(start_frame)
        print(start_frame + val_window)

        sample_frames = sample_frames[start_frame:start_frame + val_window]

        sample_frames = [
            tf.build_graph_column_precomputed(threshold=threshold, percentage=percentage, inplace=False).data_frame for
            index, tf in
            enumerate(sample_frames)]

        sample = convert_timeframes_to_model_input(sample_frames, {k: v[start_frame:start_frame + val_window] for k, v in
                                                                precomputed_features.items()}, ground_truth, dim)
        sample.print_shapes()
        pkl.dump(sample, gzip.open(os.path.join(target_dir, 'val_samples/') + 'sample_' + str(n) + '.data', 'wb'))
    end = time.time()
    print("Elapsed time:" + str(end - start))

    start = time.time()
    sample_ids = list(set(test_sample_frame['user_id'].values).intersection(set(embedder.test_users)))

    print(f'Amount of test users {len(sample_ids)}')
    for n in range(n_test_samples):
        seed_counter += 1
        sample_frames = [frame.filter_user_ids(sample_ids, inplace=False) for frame in timeframed_dataset]

        start_frame = test_min_index
        test_window = test_max_index - test_min_index

        print(start_frame)
        print(start_frame + test_window)
        sample_frames = sample_frames[start_frame:]
        sample_frames = [
            tf.build_graph_column_precomputed(threshold=threshold, percentage=percentage, inplace=False).data_frame for
            index, tf in
            enumerate(sample_frames)]

        sample = convert_timeframes_to_model_input(sample_frames, {k: v[start_frame:] for k, v in
                                                                precomputed_features.items()}, ground_truth, dim)
        sample.print_shapes()
        pkl.dump(sample, gzip.open(os.path.join(target_dir, 'test_samples/') + 'sample_' + str(n) + '.data', 'wb'))

    end = time.time()
    print("Elapsed time:" + str(end - start))

    dataset_descriptor['source_frame_descriptor'] = source_graph_descriptor

    for key, val in dataset_descriptor.items():
        if isinstance(val, dict):
            dataset_descriptor[key] = {k: convert_value(v) for k,v in val.items()}
        else:
            dataset_descriptor[key] = val

    json.dump(dataset_descriptor, open(os.path.join(target_dir, 'dataset_descriptor.json'), 'w'))


"""Criacao da tabela especialidade

Revision ID: 73ed255af28f
Revises:
Create Date: 2020-05-06 20:08:07.320767

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '73ed255af28f'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    op.create_table('especialidade',
        sa.Column('id', sa.Integer(), nullable=False),
        sa.Column('descricao', sa.Unicode(length=80), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('descricao')
    )

def downgrade():
    op.drop_table('especialidade')


from Identity.settings.base import *

# Apps list
THIRD_PARTY_APPS = [
    'oauth2_provider',
    'corsheaders',
    'rest_framework'
]
SERVICE_APPS = [
    "oauth2",
    "users"
]
INSTALLED_APPS += THIRD_PARTY_APPS + SERVICE_APPS

# Auth config
AUTH_USER_MODEL = 'users.User'
LOGIN_URL = 'users:sign-in'
LOGOUT_URL = 'users:sign-out'
SESSION_COOKIE_AGE = 3600 * 24 * 3

# oauth provider app model
OAUTH2_PROVIDER_APPLICATION_MODEL = 'oauth2.Application'


#!/usr/bin/python

import networkx as nx
from networkx.algorithms import clique, bipartite

def planar(input_struct):

    G = nx.Graph()
    G.add_nodes_from(input_struct.get("nodes"))
    G.add_weighted_edges_from(input_struct.get("edges"))

    G_first_set = nx.Graph()
    G.add_nodes_from(input_struct.get("first_set_nodes"))
    G.add_weighted_edges_from(input_struct.get("first_set_edges"))
    choice = input_struct.get("choice")

    # check if graph is planar
    is_planar, _ = nx.check_planarity(G)

    # user choice
    if choice:
        if is_planar == True:
            # if choice is true and graph was planar
            display(Markdown("Corretto !"))
            #print("Corretto il grafo è planare, fornire un planar embedding")
        else:
            # if choice is true and graph was not planar
            display(Markdown("Soluzione errata"))
            #print("Soluzione errata")
    else:
        if is_planar == False:
        # if choice is flase and graph was not planar

            if G_first_set.number_of_nodes() == 6:

                # check k_33 graph with bipartition
                bip_first_set = bipartite.is_bipartite(G_first_set)
                if bip_first_set:
                    display(Markdown("Controesempio corretto"))
                    #print("Controesempio corretto")
                else:
                    display(Markdown("Non è un K 3 3"))
                    #print("Non è un K 3 3")

            elif G_first_set.number_of_nodes() == 5:
                # check k 5 with clique

                clique = nx.find_cliques(G_first_set)
                sorted_list = sorted(clique, key=len)

                if len(sorted_list[len(sorted_list)-1]) == 5:
                    display(Markdown("Controesempio corretto"))
                    #print("Controesempio corretto")
                else:
                    display(Markdown("Non è un K 5"))
                    #print("Non è un K 5")
            else:
                # wrong counterexample
                display(Markdown("Controesempio non valido"))
                #print("Controesempio non valido")
        else:
            # if choice is flase and graph was planar
            display(Markdown("Soluzione errata"))
            #print("Soluzione errata")


from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import undetected_chromedriver as uc
import googleapiclient.discovery
import requests

from urllib.parse import urlsplit, quote_plus, urljoin
from bs4 import BeautifulSoup
import re

import os
import time
import random

# Selenium functions
def make_driver(proxy=None, load_images=False, config=True):
    options = uc.ChromeOptions()
    if proxy:
        options.add_argument(f"--proxy-server={proxy}")
    if not load_images:
        prefs = {"profile.managed_default_content_settings.images": 2}
        options.add_experimental_option("prefs", prefs)
    driver = uc.Chrome(options=options, use_subprocess=True)
    if config:
        input("You have started an Undetected Chromedriver!\nTake a minute to configure the browser before scraping.\n") # Install ublock origin or other plugins
    return driver

def fill_form(driver, text, element, by = By.ID, timeout=10, human=False):
    input = WebDriverWait(driver, timeout).until( \
        EC.presence_of_element_located((by, element)))
    input.clear()
    if human: # Imitate human behavior)
        time.sleep(random.uniform(0.3, 1))
        for letter in text:
            input.send_keys(letter)
            time.sleep(random.uniform(0.1, 0.75))
    else:
        input.send_keys(text)

def click_item(driver, element, by = By.ID, timeout=10, multi=False):
    WebDriverWait(driver, timeout).until( \
        EC.element_to_be_clickable((by, element)))
    if multi:
        btn = driver.find_elements(by, element)
        for b in btn:
            driver.execute_script("arguments[0].click();", b)
    else:
        btn = driver.find_element(by, element)
        driver.execute_script("arguments[0].click();", btn)

def get_element_text(driver, element, by = By.ID, timeout=10):
    WebDriverWait(driver, timeout).until( \
        EC.presence_of_element_located((by, element)))
    ele = driver.find_element(by, element)
    return ele.text

def check_loaded(driver, element, by=By.ID, timeout=10):
    WebDriverWait(driver, timeout).until( \
            EC.presence_of_element_located((by, element)))

def get_element(driver, element, by = By.ID, timeout=10):
    WebDriverWait(driver, timeout).until( \
        EC.presence_of_element_located((by, element)))
    ele = driver.find_element(by, element)
    return ele

def get_elements(driver, element, by = By.ID, timeout=10):
    WebDriverWait(driver, timeout).until( \
        EC.presence_of_element_located((by, element)))
    ele = driver.find_elements(by, element)
    return ele

# Instagram functions
def instagram_login(driver, my_username, my_password):
    driver.get("https://instagram.com/login")
    fill_form(driver, my_username, "input[name='username']", By.CSS_SELECTOR, human=True)
    time.sleep(random.uniform(0.1, 0.3))
    fill_form(driver, my_password, "input[name='password']", By.CSS_SELECTOR, human=True)
    time.sleep(random.uniform(0.1, 0.3))
    click_item(driver, "button[type='submit']", By.CSS_SELECTOR)
    time.sleep(random.uniform(0.1, 0.3))
    click_item(driver, "div[class='_ac8f'] > button[class='_acan _acao _acas']", By.CSS_SELECTOR)

def get_instagram_user_info(driver, username):
    print(f"getting profile data for {username}")
    driver.get(f"https://instastories.watch/en/{username}/")
    soup = BeautifulSoup(driver.page_source)
    try:
        stats = [tag.text for tag in soup.select("ul.fIYNp > li")]
        n_posts, n_followers, n_following = [s for s in stats]
        title = soup.select_one("h1.ArEj5").text
        bio = soup.select_one("p.T5HPc").text
    except AttributeError:
        print("Could not get user stats! Maybe they are a private account.")
        n_posts, n_followers, n_following, title, bio = ["private" for p in range(1,6)]
    return {
        "username": username,
        "title": title,
        "bio": bio,
        "n_posts": n_posts,
        "n_followers": n_followers,
        "n_following": n_following
    }

def get_instagram_user_posts(driver, username, n=10):
    print(f"getting posts for {username}")
    driver.get(f"https://pixwox.com/profile/{username}")
    soup = BeautifulSoup(driver.page_source)
    atags = soup.select("a[class='cover_link']")
    try:
        hrefs = [a.attrs["href"] for a in atags]
    except AttributeError:
        print("Could not get user posts! Maybe they are a private account.")
        return None
    links = [urljoin("https://pixwox.com", href) for href in hrefs]
    posts = []
    for i, link in enumerate(links): # Try grequests
        if i >= n:
            break
        driver.get(link)
        soup = BeautifulSoup(driver.page_source)
        wrapper = soup.select_one("div[class='view_w']")
        caption = wrapper.select_one("img").attrs["alt"]
        comments = []
        try:
            comment_divs = soup.select("div[class=comment_w]")
            for c in comment_divs:
                comment = {
                    "username": c.select_one("div[class='username'] > a").text.replace("@", ""),
                    "comment": c.select_one("div[class='sum']").text
                }
                comments.append(comment)
        except AttributeError:
            pass
        posts.append({
            "post": link,
            "likes": soup.select_one("div[class='count_item count_item_like cf'] > span[class='num']").text,
            "caption": caption,
            "media": wrapper.select_one("a").attrs["href"],
            "mentions": re.findall(r"@\w+", caption),
            "hashtags": re.findall(r"#\w+", caption),
            "comments": comments
        })
    return posts

def get_follower_list(driver, username, n=300):
    driver.get(f"https://www.instagram.com/{username}/followers/")
    time.sleep(random.uniform(1,4))
    scroll = """
        scrollingDiv = document.querySelector("div._aano");
        scrollingDiv.scrollTop = scrollingDiv.scrollHeight * {};
    """
    followers = set()
    while len(followers) < n:
        print(f"got {len(followers)} followers from {username}")
        driver.execute_script(scroll.format(random.uniform(0.99, 0.999))) # Random scroll length
        time.sleep(random.uniform(1,4)) # Random scroll pause
        follower_div = get_element(driver, "div._aano", By.CSS_SELECTOR).get_attribute("outerHTML")
        soup = BeautifulSoup(follower_div)
        follower_names = [s.text for s in soup.select("span[class='_aacl _aaco _aacw _aacx _aad7 _aade']")]
        print(follower_names)
        followers.update(follower_names)
    return list(followers)

class YoutubeChannel():
    def __init__(self, api_key, channel):
        self.driver = make_driver()
        self.channel = channel
        self.channel_id = self.get_channel_id(channel)
        self.data = self.get_channel_data(api_key, n_videos=10)
        self.driver.quit()

    def get_channel_id(self, channel):
        r = requests.get(f"https://youtube.com/c/{channel}")
        soup = BeautifulSoup(r.text)
        href = soup.select_one("link[itemprop='url']").attrs["href"]
        return href.split("/")[-1]

    def get_video_id(self, n=10):
        self.driver.get(f"https://www.youtube.com/c/{self.channel}/videos")
        soup = BeautifulSoup(self.driver.page_source)
        hrefs = [a.attrs["href"] for a in soup.select("a[id=video-title]")]
        ids = []
        for href in hrefs[0:n]:
            if "/shorts" in href:
                ids.append(href.split("/")[-1])
            else:
                ids.append(href.split("=")[-1])
        return ids

    def get_video_comments(self, api_key, video_id):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
        youtube = googleapiclient.discovery.build(
            "youtube", "v3", developerKey=api_key
        )
        request = youtube.commentThreads().list(
            part="snippet",
            videoId=video_id
        )
        response = request.execute()
        return response

    def get_video_data(self, api_key, video_id):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
        youtube = googleapiclient.discovery.build(
            "youtube", "v3", developerKey=api_key
        )
        request = youtube.videos().list(
            part="statistics,localizations,snippet,statistics,status,topicDetails,recordingDetails",
            id=video_id
        )
        response = request.execute()
        try:
            comments = self.get_video_comments(api_key, video_id)
            n_comments = len(comments["items"])
        except:
            comments = None
            n_comments = None
        return {
            "title": response["items"][0]["snippet"]["title"],
            "description": response["items"][0]["snippet"]["description"],
            "date_published": response["items"][0]["snippet"]["publishedAt"],
            "channel": response["items"][0]["snippet"]["channelTitle"],
            "n_views": response["items"][0]["statistics"]["viewCount"],
            "n_likes": response["items"][0]["statistics"]["likeCount"],
            "n_favorites": response["items"][0]["statistics"]["favoriteCount"],
            "n_comments": n_comments,
            "comments": comments
        }

    def get_channel_data(self, api_key, n_videos=10):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
        youtube = googleapiclient.discovery.build(
            "youtube", "v3", developerKey=api_key
        )
        request = youtube.channels().list(
            part="statistics,contentOwnerDetails,localizations,snippet,statistics,status,topicDetails,brandingSettings",
            id=self.channel_id
        )
        response = request.execute()
        keywords = response["items"][0]["brandingSettings"]["channel"]["keywords"]
        videos = self.get_video_id(n_videos)
        return {
            "title": response["items"][0]["snippet"]["title"],
            "description": re.sub(r"\\", "", re.sub(r"\n+", " ", response["items"][0]["snippet"]["description"])),
            "custom_url": response["items"][0]["snippet"]["customUrl"],
            "published_date": response["items"][0]["snippet"]["publishedAt"],
            "view_count": response["items"][0]["statistics"]["viewCount"],
            "n_subscribers": response["items"][0]["statistics"]["subscriberCount"],
            "hidden_sub_count": response["items"][0]["statistics"]["hiddenSubscriberCount"],
            "video_count": response["items"][0]["statistics"]["videoCount"],
            "topic_categories": response["items"][0]["topicDetails"]["topicCategories"],
            "country": response["items"][0]["brandingSettings"]["channel"]["country"],
            "keywords": keywords,
            "videos": [self.get_video_data(api_key, video) for video in videos]
        }


import distro, math, numpy

def _solver(stats):
    (mu,) = distro.extractStats(stats, [distro.Stat.Mu])
    return (round(mu),)

distro.register(
    name        = 'Chi_Squared',
    domain      = distro.Domain.Continuous,
    params      = ('k',),
    paramSolver = _solver,
    cdf         = lambda x, k : 0, #not implemented
    sample      = lambda k: numpy.random.chisquare(k),
    fittingFns  = {
        distro.Stat.Sig2: lambda k : 2*k,
        distro.Stat.Skew: lambda k : math.sqrt(8./k),
        distro.Stat.Kurt: lambda k : 12./k+3
    }
)


#!/usr/bin/python3

import sys
import os
import subprocess
import concurrent.futures

def convert(f):
    *base, ext = f.split(".")
    base = ".".join(base)
    print(base, ext)
    os.mkfifo(base+".raw")
    subprocess.Popen(['dump-gnash', '-1', '-D', base+'.raw', f])
    subprocess.call(['gst-launch-1.0 -e filesrc location={} ! videoparse format=rgbx width=1024 height=576 framerate=24000/1000 ! videoconvert ! video/x-raw,format=NV12,framerate=24/1 ! vaapiencode_h264 tune=high-compression ! matroskamux name=mux ! filesink location={}'.format(base+'.raw',base+'.mkv')], shell=True)
    os.unlink(base+".raw")

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_to_url = {executor.submit(convert, f): f for f in os.listdir(".") if f.endswith(".swf")}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('.', end='')
            sys.stdout.flush()
    print()


# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import print_function

from functools import wraps

import sys
import math
import inspect

from bxemu.core import PortfolioManager
from bxemu.basic import Tick, Order, Trade
from bxemu.strategy import StrategyTemplate
from bxemu.constant import *

class BacktestAccount(PortfolioManager):

    def __init__(self, name):
        super(BacktestAccount, self).__init__(name)

    def preOrderCheck(fn):
        """
        先要做下单前的检查，检查通过才可以下单
        """
        @wraps(fn)
        def wrap(*args, **kwargs):
            """
            1.只能在策略里面调用
            2.下单数是否超过了持仓数
            """
            stack = inspect.stack()
            has = False
            for s in stack:
                if s[0].f_code.co_name == "onTick":
                    has = True
                    break
            if not has:
                raise Exception("placeOrder方法只能在策略里面被调用")
            #=======================================================
            curClass = stack[1][0].f_locals["self"].__class__
            has = False
            for c in inspect.getmro(curClass):
                if c == StrategyTemplate:
                    has = True
                    break
            if not has:
                raise Exception("placeOrder方法只能在策略里面被调用")
            #=======================================================
            self, side, price, size = args
            assert side == DIRECTION_BUY or side == DIRECTION_SELL
            assert price > 0 and price <= 1000000
            assert size > 0 and size < 10000000
            #=======================================================
            return fn(*args, **kwargs)
        return wrap

    @preOrderCheck
    def placeOrder(self, side, price, size):
        order = Order.create(side, price, size, ORDER_TYPE_LIMIT, self.lastQuoteTime)
        self.strategy.onOrder(order)
        #尝试成交
        self._deal(order, TRADE_TYPE_TAKER)
        return order.orderId

    def cancelOrder(self, orderId):
        #先要更新保证金占用
        if sys.version_info.major == 2:
            l = filter(lambda order:order.orderId==orderId, self.orderBook)
        else:
            l = list(filter(lambda order:order.orderId==orderId, self.orderBook))
        order = l[0]
        order.left = 0
        order.status = "Canceled"
        self.strategy.onOrder(order)

    def cancelAllOfOrders(self):
        for order in self.orderBook[:]:
            self.cancelOrder(order.orderId)

    def _deal(self, order, tradeType):
        if (order.side == DIRECTION_SELL and order.price <= self.lastFillPrice) or\
           (order.side == DIRECTION_BUY and order.price >= self.lastFillPrice):
            #获取本次可以成交的数量
            tradeVol = self._obtainTransactionVolume(order.left)
            #判断是否允许成交(比如说一成交就会导致仓位爆仓的情况就不允许成交)
            if self._allowTrade(order, tradeVol, self.lastFillPrice, self.lastMarkPrice, tradeType):
                #可以成交
                order.left -= tradeVol  #更新订单的已成交数量
                trade = Trade.create(order.side, tradeVol, self.lastFillPrice, order.type, order.size, order.left, order.price, order.orderId, tradeType, self.lastQuoteTime)
                self.strategy.onTrade(trade)
            else:   #不允许成交,取消这个订单
                order.left = 0
                order.status = "Trade not allowed, order canceled"
                self.strategy.onOrder(order)

    def _makeTrade(self):
        """
        撮合交易
        """
        for order in self.orderBook[:]:
            self._deal(order, TRADE_TYPE_MAKER)

    def processQuote(self, tupleQuote):
        """
        调用_makeTrade撮合订单
        调用策略的onTick
        """
        self.lastMarkPrice, self.lastFillPrice, self.lastQuoteTime = tupleQuote
        #
        self._makeTrade()
        #
        tick = Tick.create(self.lastMarkPrice, self.lastFillPrice, self.lastQuoteTime)
        self.strategy.onTick(tick)


from datetime import datetime

from django.http import HttpResponse

from ridesharing_fcm.tasks import send_message_helper, update_token

def update_firebase_token(request):
    """
    Update Firebase ID for device with device_id

    :param request: POST {'id', 'token'}, 'token' is new token
    """
    new_token, user_id = request.POST['token'], request.POST['id']
    update_token.delay(user_id, new_token)
    return HttpResponse('ok')

def send_message_immediately(request):
    """
    Send message to one user immediately

    :param request: GET {'id', 'title', 'body'}
    """
    user_id = request.GET['id']
    title, message = request.GET['title'], request.GET['message']
    send_message_helper.delay(user_id=user_id, title=title, message=message)
    return HttpResponse('ok')

def send_message_datetime(request):
    """
    Send message at given time. Time is timestamp
    :param request: GET {'id', 'title', 'message', 'timestamp'}
    """
    user_id, timestamp = request.GET['id'], request.GET['timestamp']
    time = datetime.fromtimestamp(int(float(timestamp)))
    title, message = request.GET['title'], request.GET['message']
    send_message_helper.apply_async((user_id, title, message), eta=time)
    return HttpResponse('ok')


import  cv2
import numpy as np

img = cv2.imread('e:\\1394506194911.jpg')
# 默认是浅拷贝
img2 = img
# 深拷贝
img3 = img.copy()
img[10:100,10:100] = [0,0,255]

cv2.imshow('img',img)
cv2.imshow('img2',img2)
cv2.imshow('img3',img3)
cv2.waitKey(0)


# ------------------------------------------------ main script ---------------------------------------------------------
# import the necessary packages
from reader import extract_digit
from reader import find_puzzle
from keras.utils import img_to_array
from keras.models import load_model
from solver import solve
import numpy as np
import argparse
import imutils
import cv2

# ----------------------------------------------------------------------------------------------------------------------
# read in arguments
# ----------------------------------------------------------------------------------------------------------------------
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=True, help="path to trained digit classifier")
ap.add_argument("-i", "--image", required=True, help="path to input Sudoku puzzle image")
ap.add_argument("-d", "--debug", required=False, type=int, help="print intermediate steps in puzzle recognition")
args = vars(ap.parse_args())

# ----------------------------------------------------------------------------------------------------------------------
# read puzzle from image, classify digits in cells then print solution:
# ----------------------------------------------------------------------------------------------------------------------
# load the digit classifier from disk
print("[INFO] loading digit classifier...")
model = load_model(args["model"])

# read the image
image = cv2.imread(args["image"])
image = imutils.resize(image, width=600)

# find the puzzle in the image and the size of each cell
(puzzleImage, warped) = find_puzzle(image, debug=args["debug"] > 0)
stepR = warped.shape[0] // 9
stepC = warped.shape[1] // 9

# build the sudoku board:
puzzle = [[0 for i in range(0, 9)] for j in range(0, 9)]
for c in range(0, 9):
    for r in range(0, 9):

        # find cell and extract digit:
        cell = warped[(r*stepR):((r+1)*stepR), (c*stepC):((c+1)*stepC)]
        digit = extract_digit(cell, debug=args["debug"] > 0)

        # if the cell has a digit apply the classifier and save the result:
        if digit is not None:
            roi = cv2.resize(digit, (28, 28))
            roi = roi.astype("float") / 255.0
            roi = img_to_array(roi)
            roi = np.expand_dims(roi, axis=0)
            puzzle[r][c] = model.predict(roi).argmax(axis=1)[0]
            print(puzzle[r][c])

# solve and print
solved_puzzle = solve(puzzle)
[print(r) for r in solved_puzzle]


import json
#import os
import pygame as pg
from . import constants
from . import settings

CAPTION = "MissilyMissileCommand"

pg.init()

pg.display.set_caption(CAPTION)
pg.display.set_mode(constants.SCREEN_SIZE)

pg.mouse.set_visible(False)

def load_highscores():
    try:
        with open(str(constants.HIGHSCORE_PATH), 'r') as score_file:
            settings.high_scores = json.load(score_file)
    except FileNotFoundError:
        with open(str(constants.HIGHSCORE_PATH), 'w') as score_file:
            json.dump(settings.high_scores, score_file)
        load_highscores()
load_highscores()

def load_settings():
    try:
        with open(str(constants.SETTINGS_PATH), 'r') as settings_file:
            the_settings = json.load(settings_file)
            for k, v in the_settings.items():
                exec("settings.{var} = {val}".format(var=k, val=v))
    except FileNotFoundError:
        pass #Use sane defaults
load_settings()


from django.urls import path,include
from .views import paginaprincipal, listarProducto, modificarProducto, agregarProducto, eliminarProducto,administracion,lista,muestraProducto,categoria,carrito,offline,listarCategorias,modificarCategoria,eliminarCategoria,tiendas
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('', paginaprincipal,name="loby"),
    path('listar/', listarProducto, name="listar"),
    path('agregar/', agregarProducto, name='agregar'),
    path('modificar/<int:id_producto>', modificarProducto, name='modificar'),
    path('eliminar/<int:id_producto>', eliminarProducto, name='eliminar'),
    path('administracion/',administracion, name='admin'),
    path('lista/<id>',lista, name='lista'),
    path('productos/<int:id_producto>',muestraProducto, name='muestraProducto'),
    path('categoria/',categoria,name='categoria'),
    path('carrito/',carrito,name='carrito'),
    path('offline/',offline,name='offline'),
    path('listacategorias/',listarCategorias,name='listacategorias'),
    path('modificarcategoria/<int:id>',modificarCategoria,name='modificarcategoria'),
    path('eliminarcategoria/<int:id>',eliminarCategoria,name='eliminarcategoria'),
    path('tiendas/',tiendas,name='tiendas')
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
    document_root=settings.MEDIA_ROOT
    )