from argparse import ArgumentParser
from os import _exit
from os.path import exists, join

def main():
    arguments = ArgumentParser(description="A tool to check if there's any issue missing")
    arguments.add_argument("master_list", action='store', type=str)
    arguments.add_argument("data_dir", action='store', type=str)
    parsed = arguments.parse_args()
    try:
        lines = []
        with open(parsed.master_list, "r", encoding="utf-8") as read_file:
            lines = [x.strip() for x in read_file.readlines()]
        transtable = str.maketrans("-", "\\")
        for line in lines:
            new = line.translate(transtable)
            issue_path = join(parsed.data_dir, new)
            if not exists(issue_path):
               f = open(join("./data", "missing_issues_two.txt"), "a", encoding="utf-8")
               f.write("{}\n".format(issue_path))
               f.close()
        return 0
    except KeyboardInterrupt:
        return 131

if __name__ == "__main__":
    _exit(main())


import logging

from sportorg.models.result.result_checker import ResultChecker, ResultCheckerException
from sportorg.models.memory import race, Person, Result, ResultSportident

class ResultSportidentGeneration:
    def __init__(self, result: ResultSportident):
        assert result, Result
        self._result = result
        self._person = None
        self.assign_chip_reading = race().get_setting('sportident_assign_chip_reading', 'off')
        self.repeated_reading = race().get_setting('sportident_repeated_reading', 'rewrite')

    def _add_result_to_race(self):
        race().add_result(self._result)

    def _has_result(self):
        for result in race().results:
            if result is None:
                continue
            if result == self._result:
                return True
        return False

    def _find_person_by_result(self):
        if self._person is not None:
            return True
        for person in race().persons:
            if person.sportident_card is not None and person.sportident_card == self._result.sportident_card:
                self._person = person
                return True

        return False

    def _has_sportident_card(self):
        for result in race().results:
            if result is None:
                continue
            if result.sportident_card == self._result.sportident_card:
                return True
        return False

    def add_result(self):
        if self._has_result():
            return
        if self.assign_chip_reading == 'always':
            pass  # bib
        self._add_result()

    def check_splits(self):
        if self._find_person_by_result():
            return ResultChecker(self._person).check_result(self._result)
        return False

    def _no_person(self):
        if self.assign_chip_reading == 'off':
            self._add_result_to_race()
        elif self.assign_chip_reading == 'only_unknown_members':
            # bib
            self._add_result()

    def _add_result(self):
        if isinstance(self._result.person, Person):
            self._find_person_by_result()
            try:
                ResultChecker.calculate_penalty(self._result)
                ResultChecker.checking(self._result)
            except ResultCheckerException as e:
                logging.error(str(e))

            self._add_result_to_race()

            logging.info('Sportident {}'.format(self._result))
            logging.debug(self._result.status)
        else:
            if self._find_person_by_result():
                self._result.person = self._person
                self._add_result()
            else:
                self._no_person()


import sys
input = sys.stdin.readline
N = int(input())
lst = list(map(int, input().split()))

dp = [10**10]
for i in lst:
    if i < dp[-1]:
        dp.append(i)
    else:
        left, right = 0, len(dp)-1
        while dp[left] > i  :
            mid = (left+right)//2
            if i < dp[mid]:
                left = mid + 1
            else:
                right = mid - 1
        dp[left] = max(dp[left], i)

print(len(dp)-1)


import datetime

x = input().split()
a = int(x[0])
b = int(x[1])
c = int(x[2])

date_my = datetime.date( a, b, c)
delta = datetime.timedelta(days = int(input()))

now_date = date_my + delta

print(now_date.year, now_date.month, now_date.day)


from flask import Flask, flash, render_template, redirect, url_for, request
from flask import current_app, Blueprint
from flask_login import current_user, login_user, logout_user, login_required
from .forms import AdminUserForm, AdminTestUserForm, RoleForm
from .models import User, Event, ActivityType, Role, RoleIds, db
from flask_images import Images
from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict
from wtforms import SelectField
from functools import wraps
import sys
import os

import sqlalchemy.exc
import sqlalchemy_utils

blueprint = Blueprint('administration', __name__, url_prefix='/administration')

################################################################
# Decorator
################################################################

def admin_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_admin():
            flash('Méthode non autorisée.', 'error')
            return redirect(url_for('event.index'))
        return func(*args, **kwargs)
    return decorated_view

################################################################
# ADMINISTRATION
################################################################

@blueprint.route('/', methods=['GET', 'POST'])
@login_required
@admin_required
def administration():
    if not current_user.is_admin():
        flash('Vous n\'êtes pas administrateur.')
        return redirect(url_for('index'))

    users = User.query.all()

    return render_template('administration.html',
                           conf=current_app.config,
                           users=users)

@blueprint.route('/users/add', methods=['GET', 'POST'])
@blueprint.route('/users/<user_id>', methods=['GET', 'POST'])
@login_required
@admin_required
def manage_user(user_id=None):
    user = User() if user_id is None else User.query.get(user_id)

    # If we are operating on a 'normal' user, restrict fields
    # Else allow editing everything
    FormClass = AdminUserForm
    if user.is_test or user_id == None:
        FormClass = AdminTestUserForm

    form = FormClass() if user_id is None else FormClass(obj=user)
    action = 'Ajout' if user_id is None else 'Édition'

    if not form.validate_on_submit():
        return render_template('basicform.html',
                               conf=current_app.config,
                               form=form,
                               title="{} d'utilisateur".format(action))

    # Do not touch password if user does not want to change it
    if hasattr(form, 'password') and form.password.data == '':
        delattr(form , 'password')

    form.populate_obj(user)
    # Commit this object will create the id if it
    # is a user creation
    if user_id == None:
        db.session.add(user)
        db.session.commit()

    # Save avatar into ight UploadSet
    if form.remove_avatar and form.remove_avatar.data:
        user.delete_avatar()
    user.save_avatar(FormClass().avatar_file.data)

    db.session.add(user)
    db.session.commit()

    return redirect(url_for('administration.administration'))

@blueprint.route('/users/<user_id>/delete', methods=['POST'])
@login_required
@admin_required
def delete_user(user_id):
    flash('Suppression d\'utilisateur non implémentée. ID ' + user_id, 'error')
    return redirect(url_for('administration.administration'))

@blueprint.route('/user/<user_id>/roles', methods=['GET', 'POST'])
@login_required
@admin_required
def add_user_role(user_id):

    user = User.query.filter_by(id=user_id).first()
    if user is None:
        flash('Utilisateur inexistant', 'error')
        return redirect(url_for('administration.administration'))

    form = RoleForm()
    if not form.is_submitted():
        return render_template('user_roles.html',
                               conf=current_app.config,
                               user=user,
                               form=form,
                               title="Roles utilisateur")

    role = Role()
    form.populate_obj(role)
    role_id = RoleIds(int(role.role_id))

    if role_id.relates_to_activity():
        role.activity_type = ActivityType.query.filter_by(
            id=form.activity_type_id.data).first()
        role_exists = user.has_role_for_activity(
            [role_id], role.activity_type.id)
    else:
        role.activity_type = None
        role_exists = user.has_role([role_id])

    if role_exists:
        flash("Role déjà associé à l'utilisateur", 'error')
    else:
        user.roles.append(role)
        db.session.add(role)
        db.session.commit()

    form = RoleForm()
    return render_template('user_roles.html',
                           conf=current_app.config,
                           user=user,
                           form=form,
                           title='Roles utilisateur')

@blueprint.route('/roles/<user_id>/delete', methods=['POST'])
@login_required
@admin_required
def remove_user_role(user_id):
    role = Role.query.filter_by(id=user_id).first()
    if role is None:
        flash('Role inexistant', 'error')
        return redirect(url_for('administration.administration'))

    user = role.user

    if user == current_user and role.role_id == RoleIds.Administrator:
        flash('Rétrogradation impossible', 'error')
    else:
        db.session.delete(role)
        db.session.commit()

    form = RoleForm()
    return render_template('user_roles.html',
                           conf=current_app.config,
                           user=user,
                           form=form,
                           title='Roles utilisateur')

# init: Setup activity types (if db is ready)

def init_activity_types():
    try:
        for (id, atype) in current_app.config['TYPES'].items():
            activity_type = ActivityType.query.get(id)
            if activity_type == None:
                activity_type = ActivityType(id=id)

            activity_type.name=atype['name']
            activity_type.short=atype['short']
            db.session.add(activity_type)

        db.session.commit()

    except sqlalchemy.exc.OperationalError:
        print('WARN: Cannot configure activity types: db is not available')


# bottom-up DP
# reference: https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/286753/C%2B%2B-with-picture
class Solution:
    def minScoreTriangulation(self, A: List[int]) -> int:
        N = len(A)
        dp = [[0 for _ in range(N)] for _ in range(N)]
        for d in range(2, N):
            for i in range(0, N-d):
                j = i + d
                dp[i][j] = float('inf')
                for k in range(i+1, j):
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[j] * A[k])
        return dp[0][N - 1]


"""
慕课视频: CNN-MNIST
配置tensorboard

"""

import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("mnist_data", one_hot=True,
                                  source_url="http://yann.lecun.com/exdb/mnist/")  # 55000张，28*28像素

# None表示张量(Tensor)的第一个维度可以是任何长度
# 除以255是为了做归一化(Normalization)，把灰度值从[0, 255]变成[0, 1]区间
# 归一话可以让之后的优化器(optimizer)更快更好地找到误差最小值
input_x = tf.placeholder(dtype=tf.float32, shape=[None, 28 * 28]) / 255  # 输入。是一个28*28的图片。
output_y = tf.placeholder(dtype=tf.int32, shape=[None, 10])  # 输出：10个数字的预测

# -1表示自动推导维度大小。让计算机根据其他维度的值和总的元素大小来推导出-1的地方的维度应该是多少
input_x_images = tf.reshape(input_x, [-1, 28, 28, 1])  # 改变形状之后的输入

# 测试数据，从测试数据集里选取3000个手写数字的图片和对应标签
test_x = mnist.test.images[:3000]  # 图片
test_y = mnist.test.labels[:3000]  # 标签

# 构建卷积神经网络
# 卷积层
conv_1 = tf.layers.conv2d(inputs=input_x_images,  # 形状[28, 28, 1]
                          filters=32,  # 32个过滤器，输出的深度(depth=32)
                          kernel_size=[5, 5],  # 过滤器的二维平面大小 5*5
                          strides=1,  # 步长
                          padding='same',  # 补零方案: same表示输出的大小不变，因此需要在外围补零两圈
                          activation=tf.nn.relu  # 激活函数：relu
                          )  # 输出形状[28, 28, 32]

# 池化层(pooling): 亚采样
pool_1 = tf.layers.max_pooling2d(inputs=conv_1,  # 形状[28, 28, 32]
                                 pool_size=[2, 2],  # 过滤器在二维的大小是2*2
                                 strides=2,  # 步长2
                                 name="first_pooling"
                                 )  # 输出形状[14, 14, 32]

# 卷积层
conv_2 = tf.layers.conv2d(inputs=pool_1,  # 形状：14*14*32
                          filters=64,  # 64个过滤器，输出的深度(depth=64)
                          kernel_size=[5, 5],  # 过滤器的二维平面大小
                          strides=1,  # 步长
                          padding='same',  # 补零方案:same, 表示输出的大小不变，因此需要在外围补零两圈
                          activation=tf.nn.relu  # 激活函数：relu
                          )  # 输出形状[14, 14, 64]

# 池化层: 亚采样
pool_2 = tf.layers.max_pooling2d(inputs=conv_2,  # 形状[14, 14, 64]
                                 pool_size=[2, 2],  # 过滤器在二维的大小是2*2
                                 strides=2,  # 步长2
                                 )  # 输出形状[7, 7, 64]

# 平坦化 flat
flat = tf.reshape(pool_2, shape=[-1, 7 * 7 * 64])  # 形状：7*7*64

# 全连接层: 1024个神经元的全连接层
dense = tf.layers.dense(inputs=flat,
                        units=1024,
                        activation=tf.nn.relu
                        )

# dropout: 丢弃50%，即rate=0.5
dropout = tf.layers.dropout(inputs=dense,
                            rate=0.5
                            )

# 全连接层: 构建10个神经元的全连接层，这里不用激活函数来做非线性化了
logits = tf.layers.dense(inputs=dropout,
                         units=10
                         )  # 输出形状：1*1*10

# 计算误差（计算cross entropy（交叉熵），再用sotfmax计算百分比的概率）
loss = tf.losses.softmax_cross_entropy(onehot_labels=output_y,
                                       logits=logits
                                       )

# 用Adam优化器来最小化误差，学习率0.001
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

# 精度。计算预测值和实际标签的匹配程度。返回(accuracy, update_op), 会创建两个局部变量。
accuracy = tf.metrics.accuracy(labels=tf.argmax(output_y, axis=1),
                               predictions=tf.argmax(logits, axis=1),
                               )[1]
tf.summary.scalar("optimizer", accuracy)
tf.summary.histogram("histogram", accuracy)

# 创建会话
sess = tf.Session()

# tensorboard
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter("./logs", sess.graph)

# 初始化变量：要初始化全局和局部两种变量
init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init)

for i in range(2000):
    batch = mnist.train.next_batch(50)  # 从训练数据集里取下一个'50个样本'
    summary, train_loss, train_op_ = sess.run([merged, loss, train_op], feed_dict={input_x: batch[0], output_y: batch[1]})
    train_writer.add_summary(summary)

    if i % 100 == 0:
        test_accuracy = sess.run([accuracy], feed_dict={input_x: test_x, output_y: test_y})
        print("step={}, train-loss={}, test-accoutacy={}".format(i, train_loss, test_accuracy))

# 测试： 打印20个预测值和真实值的对
test_output = sess.run(logits, {input_x: test_x[:20]})
inferred_y = np.argmax(test_output, 1)

print(inferred_y, '推测的数字')  # 推测的数字
print(np.argmax(test_y[:20], 1), '真实的数字')  # 真实的数字

# 关闭会话
sess.close()


import boto3
import json
import pickle
from tag import Tag

def lambda_handler(event, context):

    s3 = boto3.resource('s3')
    book = event['queryStringParameters']['book']

    tag_type = 'secondary'

    book_headers = None

    if tag_type=='primary':
        book_headers = book+'_primary.json'
    else:
        book_headers = book+'_secondary.json'

    print(book_headers)

    data = json.loads(s3.Bucket("pdfheaders").Object(book_headers).get()['Body'].read())
    # json_data = json_data.decode('utf8')

    print('type',type(data))

    wordMap = {}

    stack = []

    for header in data:

        fontS = header.find("h")
        headS = header.find(">")
        posS = header.find("{")
        posE = header.find("}")
        blockS = posS+header[posS:].find("-")
        heading = header[headS+1:posS]

        fontSize = int(header[fontS+1:headS])
        text = header[headS+1:posS]
        start_page = int(header[posS+1:blockS])
        start_block = int(header[blockS+1:posE])
        text = text.strip()
        heading = heading.strip()
        if(len(text)==0):
            continue
        tag = Tag(text,fontSize,start_page,start_block,0,0)

        if stack:
            # Remove paragraphs from stack with headers having lesser font
            while stack and stack[-1].fontSize>=fontSize:
                # print('Popping',stack[-1].text)
                rm_tag = stack.pop()
                rm_tag.end_page = start_page
                rm_tag.end_block = start_block-1 # is -1 when heading on new page

            if stack:
                if heading not in wordMap.keys():
                    wordMap[heading] = tag
                else:
                    tag.text = stack[-1].text+' '+heading
                    wordMap[stack[-1].text+' '+heading] = tag
                stack[-1].child.append(tag)
                # print(tag.text,' child of ',stack[-1].text)

        stack.append(tag)

    # put wordMap into s3 bucket 'pdftags'
    with open("/tmp/"+book+".pickle", 'wb') as out:
        pickle.dump(wordMap, out, protocol=pickle.HIGHEST_PROTOCOL)
        out.close()
    s3.Bucket("pdftags").upload_file("/tmp/"+book+".pickle", book+'.pickle')

    return {
        'statusCode': 200,
        'body': json.dumps(tag_type+' tags generated for '+book)
    }


"""
Trust Anchor Interface
"""
# (c) 2015-2018 Microchip Technology Inc. and its subsidiaries.
#
# Subject to your compliance with these terms, you may use Microchip software
# and any derivatives exclusively with Microchip products. It is your
# responsibility to comply with third party license terms applicable to your
# use of third party software (including open source software) that may
# accompany Microchip software.
#
# THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
# EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
# WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
# PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT,
# SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE
# OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF
# MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE
# FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL
# LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED
# THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR
# THIS SOFTWARE.

from ctypes import c_uint8, byref, create_string_buffer, c_uint16, c_size_t, POINTER, cast, Array
from .status import Status
from .library import get_cryptoauthlib, AtcaReference, AtcaStructure, AtcaUnion, create_byte_buffer

class ta_handle_properties_public_key(AtcaStructure):
    """
    Class: 0
    """
    _fields_ = [
        ('Path_Length', c_uint8),
        ('Secure_Boot', c_uint8, 1),
        ('Root', c_uint8, 2),
        ('CRL_Sign', c_uint8, 1),
        ('Special_Only', c_uint8, 1),
        ('Reserved', c_uint8, 3)
    ]
    _pack_ = 1

class ta_handle_properties_private_key(AtcaStructure):
    """
    Class 1:
    """
    _fields_ = [
        ('Pub_Key', c_uint8),
        ('Session', c_uint8, 1),
        ('Key_Gen', c_uint8, 1),
        ('Sign_Use', c_uint8, 2),
        ('Agree_Use', c_uint8, 2),
        ('Reserved', c_uint8, 2)
    ]
    _pack_ = 1

class ta_handle_properties_symmetric_key(AtcaStructure):
    """
    Class 2
    """
    _fields_ = [
        ('Granted_Rights', c_uint8),
        ('Sym_Usage', c_uint8, 2),
        ('Session_Use', c_uint8, 3),
        ('Key_Group_OK', c_uint8, 1),
        ('Reserved', c_uint8, 2)
    ]
    _pack_ = 1

class ta_handle_properties_data(AtcaStructure):
    """
    Class 3
    """
    _fields_ = [
        ('Size', c_uint16, 12),
        ('Template', c_uint16, 1),
        ('Reserved', c_uint16, 3)
    ]
    _pack_ = 1

class ta_handle_properties_certificate(AtcaStructure):
    """
    Class 4
    """
    _fields_ = [
        ('Granted_Rights', c_uint8),
        ('Secure_Boot', c_uint8, 1),
        ('CA_OK', c_uint8, 1),
        ('CA_Parent', c_uint8, 1),
        ('CRL_Sign', c_uint8, 1),
        ('Special_Only', c_uint8, 1),
        ('Reserved', c_uint8, 3)
    ]
    _pack_ = 1

class ta_handle_properties_key_group(AtcaStructure):
    """
    Class 6
    """
    _fields_ = [
        ('Num_Keys', c_uint8, 5),
        ('Handles', c_uint8, 1),
        ('Reserved0', c_uint8, 2),
        ('Reserved1', c_uint8)
    ]
    _pack_ = 1

class ta_handle_properties_crl(AtcaStructure):
    _fields_ = [
        ('Num_Digests', c_uint8),
        ('Reserved', c_uint8)
    ]
    _pack_ = 1

class ta_element_attributes_properties(AtcaUnion):
    _fields_ = [
        ('public', ta_handle_properties_public_key),
        ('private', ta_handle_properties_private_key),
        ('symmetric', ta_handle_properties_symmetric_key),
        ('data', ta_handle_properties_data),
        ('certificate', ta_handle_properties_certificate),
        ('key_group', ta_handle_properties_key_group),
        ('crl', ta_handle_properties_crl)
    ]
    _pack_ = 1

class ta_element_attributes_t(AtcaStructure):
    _fields_ = [
        ('Class', c_uint8, 3),
        ('Key_Type', c_uint8, 4),
        ('Alg_Mode', c_uint8, 1),
        ('Property', ta_element_attributes_properties),
        ('Usage_Key', c_uint8),
        ('Write_Key', c_uint8),
        ('Read_Key', c_uint8),
        ('Usage_Perm', c_uint8, 2),
        ('Write_Perm', c_uint8, 2),
        ('Read_Perm', c_uint8, 2),
        ('Delete_Perm', c_uint8, 2),
        ('Use_Count', c_uint8, 2),
        ('Reserved0', c_uint8, 1),
        ('Exportable', c_uint8, 1),
        ('Lockable', c_uint8, 1),
        ('Access_Limit', c_uint8, 2),
        ('Reserved1', c_uint8, 1)
    ]
    _pack_ = 1

def talib_handle_init_public_key(attributes, key_type, alg_mode, secure_boot_enable, root_key_enable):
    return get_cryptoauthlib().talib_handle_init_public_key(byref(attributes), key_type, alg_mode, secure_boot_enable,
                                                            root_key_enable)

def talib_handle_init_private_key(attributes, key_type, alg_mode, sign_use, key_agreement_use):
    return get_cryptoauthlib().talib_handle_init_private_key(byref(attributes), key_type, alg_mode, sign_use,
                                                             key_agreement_use)

def talib_handle_init_symmetric_key(attributes, key_type, sym_usage):
    return get_cryptoauthlib().talib_handle_init_symmetric_key(byref(attributes), key_type, sym_usage)

def talib_handle_init_data(attributes, data_size):
    return get_cryptoauthlib().talib_handle_init_data(byref(attributes), data_size)

def talib_handle_init_extracated_certificate(attributes, key_type, alg_mode, secure_boot_use, intermediate_ca_enable):
    return get_cryptoauthlib().talib_handle_init_extracated_certificate(byref(attributes), key_type, alg_mode,
                                                                        secure_boot_use, intermediate_ca_enable)

def talib_handle_init_fast_crypto_key_group(attributes, key_type, num_keys, handles):
    return get_cryptoauthlib().talib_handle_init_fast_crypto_key_group(byref(attributes), key_type, num_keys, handles)

def talib_handle_set_permissions(attributes, usage_perm, write_perm, read_perm, delete_perm):
    return get_cryptoauthlib().talib_handle_set_permissions(byref(attributes), usage_perm, write_perm, read_perm,
                                                            delete_perm)

def talib_handle_set_usage_permission(attributes, usage_perm):
    return get_cryptoauthlib().talib_handle_set_usage_permission(byref(attributes), usage_perm)

def talib_handle_set_write_permission(attributes, write_perm):
    return get_cryptoauthlib().talib_handle_set_write_permission(byref(attributes), write_perm)

def talib_handle_set_read_permission(attributes, read_perm):
    return get_cryptoauthlib().talib_handle_set_read_permission(byref(attributes), read_perm)

def talib_handle_set_delete_permission(attributes, delete_perm):
    return get_cryptoauthlib().talib_handle_set_delete_permission(byref(attributes), delete_perm)

def talib_create(device, mode, details, handle_in, handle_config, handle_out):
    if not isinstance(handle_out, AtcaReference):
        status = Status.ATCA_BAD_PARAM
    else:
        c_handle_out = c_uint16(handle_out.value)
        status = get_cryptoauthlib().talib_create(device, details, handle_in, byref(handle_config), byref(c_handle_out))
        handle_out.value = c_handle_out.value
    return status

def talib_create_element(device, handle_config, handle_out):
    if not isinstance(handle_out, AtcaReference):
        status = Status.ATCA_BAD_PARAM
    else:
        c_handle_out = c_uint16(handle_out.value)
        status = get_cryptoauthlib().talib_create_element(device, handle_config, byref(c_handle_out))
        handle_out.value = c_handle_out.value
    return status

def talib_create_element_with_handle(device, handle_in, handle_config):
    return get_cryptoauthlib().talib_create_element_with_handle(device, handle_in, byref(handle_config))

def talib_create_ephemeral_element_with_handle(device, details, handle_in, handle_config):
    return get_cryptoauthlib().talib_create_ephemeral_element_with_handle(device, details, handle_in,
                                                                          byref(handle_config))

def talib_create_hmac_element(device, key_size, handle_config, handle_out):
    if not isinstance(handle_out, AtcaReference):
        status = Status.ATCA_BAD_PARAM
    else:
        c_handle_out = c_uint16(handle_out.value)
        status = get_cryptoauthlib().talib_create_hmac_element(device, key_size, byref(handle_config),
                                                               byref(c_handle_out))
        handle_out.value = c_handle_out.value
    return status

def talib_create_hmac_element_with_handle(device, key_size, handle_in, handle_config):
    return get_cryptoauthlib().talib_create_hmac_element_with_handle(device, key_size, handle_in, byref(handle_config))

def talib_delete_handle(device, handle):
    return get_cryptoauthlib().talib_delete_handle(device, handle)

def talib_is_handle_valid(device, target_handle, is_valid):
    if not isinstance(is_valid, AtcaReference):
        status = Status.ATCA_BAD_PARAM
    else:
        c_is_valid = c_uint8(is_valid.value)
        status = get_cryptoauthlib().talib_is_handle_valid(device, target_handle, byref(c_is_valid))
        is_valid.value = c_is_valid.value
    return status

def talib_info(device, revision):
    """
    Used to get the device revision number. (DevRev)

    Args:
        revision            8-byte bytearray receiving the revision number
                            from the device. (Expects bytearray)

    Returns:
        Status code
    """
    c_revision = create_string_buffer(8)
    if not isinstance(revision, bytearray):
        status = Status.ATCA_BAD_PARAM
    else:
        status = get_cryptoauthlib().talib_info(device, c_revision)
        revision[0:] = bytes(c_revision.raw)
    return status

def talib_info_get_handle_info(device, target_handle, handle_info):
    if not isinstance(handle_info, ta_element_attributes_t):
        status = Status.ATCA_BAD_PARAM
    else:
        info_array = create_string_buffer(9)
        status = get_cryptoauthlib().talib_info_get_handle_info(device, target_handle, info_array)
        handle_info.update_from_buffer(info_array)
    return status

#ATCA_STATUS talib_info_get_handle_info(ATCADevice device, uint32_t target_handle, uint8_t handle_info[STATIC_ARRAY TA_HANDLE_INFO_SIZE]);

def talib_info_get_handles_array(device, handles):
    if not isinstance(handles, list):
        status = Status.ATCA_BAD_PARAM
    else:
        results = (c_uint16*100)()
        count = c_size_t(100)
        status = get_cryptoauthlib().talib_info_get_handles_array(device, cast(results, POINTER(c_uint16)), byref(count))
        handles[0:] = results[:count.value]
    return status

#ATCA_STATUS talib_info_get_handle_size(ATCADevice device, uint32_t target_handle, size_t* out_size);

def talib_write_element(device, handle, length, data):
    status = get_cryptoauthlib().talib_write_element(device, handle, length, bytes(data))

    return status

def talib_auth_generate_nonce(device, handle, options, i_nonce):
    cbuf = create_string_buffer(16)
    cbuf[0:] = i_nonce[0:16]
    status = get_cryptoauthlib().talib_auth_generate_nonce(device, handle, options, cbuf)
    i_nonce[0:] = cbuf[:len(cbuf)]
    return status

def talib_auth_startup(device, handle, alg_id, max_cmd, key_len, key, i_nonce, r_nonce):
    status = get_cryptoauthlib().talib_auth_startup(device, handle, alg_id, max_cmd, key_len, key,
                                                    create_byte_buffer(i_nonce), create_byte_buffer(r_nonce))
    return status

def talib_auth_terminate(device):
    return get_cryptoauthlib().talib_auth_terminate(device)

# Make module import * safe - keep at the end of the file
__all__ = ['ta_element_attributes_t']
__all__ += [x for x in dir() if x.startswith(__name__.split('.')[-1])]


#--------------------------------------------------------------
# JobOptions for user setting in SCTCalib/SCTCalibWriteSvc
# - Minimum inputs to run each algorithm
#--------------------------------------------------------------

#--------------------------------------------------------------
# RunNumber and number of events
#--------------------------------------------------------------
RunNumber = 364214
EvtMax    = -1

#--------------------------------------------------------------
# Geometry and Conditons Tag
# - If empty, one tag is automatically chosen in topOptions
#--------------------------------------------------------------
GeometryTag   = '' # empty in default
ConditionsTag = '' # empty in default

#--------------------------------------------------------------
# Global flags and beam flag
#--------------------------------------------------------------
DataSource = 'data'       # 'data' or 'geant4'
beamType   = 'cosmics' # 'cosmics', 'singlebeam' or 'collisions'

#------------------------------------------------------------
# Flags for input
# - TrkVal/BS : NoisyStrips, HV, DeadChip, DeadStrip
# - HIST      : NoiseOccupancy, RawOccupancy, Efficiency, BSErrorDB, LorentzAngle
#------------------------------------------------------------
ReadBS         = True
#------------------------------------------------------------
# Algorithm turned on
# - Set only one flag to True and others to False
#------------------------------------------------------------
#--- Algs using TrkVal or BS
DoNoisyStrip     = False
DoNoisyLB        = False
DoHV             = False
DoDeadStrip      = False
DoDeadChip       = True
#--- Algs using HIST
DoNoiseOccupancy = False
DoRawOccupancy   = False
DoEfficiency     = False
DoBSErrorDB      = False
DoLorentzAngle   = False

#------------------------------------------------------------
# Default setup for specific flags in SCTCalib
# - This default is for NoisyStrips
#------------------------------------------------------------
UseDCS           = False
UseConfiguration = True
UseCalibration   = True
UseMajority      = True
UseBSError       = False
DoHitMaps        = True
ReadHitMaps      = True # True = 2 steps of HitMap production and analysis, False = simultaneous production and analysis
DoBSErrors       = False

#------------------------------------------------------------
# Properties in SCTCalib
#------------------------------------------------------------
#--- local DB
WriteToCool = True

# hitmaps
LbsPerWindow           = 30

#--- Noisy strips
NoisyUpdate            = False     # True = Write out difference from the existing data, False = Write out all
NoisyWriteAllModules   = True
NoisyMinStat           = 10000     # 50000 (enough), 10000 (still possible), 5000 (for commissioning)
NoisyStripAll          = True      # True = All noisy strips into DB, False = Only newly found strips
NoisyStripThrDef       = True      # True = Offline, False = Calib
NoisyStripThrOffline   = 1.500E-2  # Threshold in Offline
NoisyStripThrOnline    = 1.500E-3  # Threshold in Online/Calibration (TBD)
NoisyWaferFinder       = True      # True = turn on noisy wafer criteria, False = turn off
NoisyWaferWrite        = True      # True = include noisy wafer, False = do not include
NoisyWaferAllStrips    = False     # True = write out all strips, False = only noisy strips
NoisyWaferThrBarrel    = 1.000E-3
NoisyWaferThrECA       = 1.000E-3
NoisyWaferThrECC       = 1.000E-3
NoisyWaferFraction     = 0.500
NoisyChipFraction      = 0.500
NoisyUploadTest        = True      #only false during the first few runs
NoisyModuleAverageInDB = -1.
NoisyStripLastRunInDB  = -999
NoisyStripAverageInDB  = -999.
NoisyModuleList        = 5000
NoisyModuleDiff        = 0.500
NoisyStripDiff         = 5120

#--- Dead strips/chips
DeadStripMinStat      = 0
DeadStripMinStatBusy  = 200000
DeadChipMinStat       = 0
DeadStripSignificance = 10
DeadChipSignificance  = 10
BusyThr4DeadFinding   = 1E-4
NoisyThr4DeadFinding  = 1.500E-3
DeadChipUploadTest    = True
DeadStripUploadTest   = True

#--- HIST
NoiseOccupancyTriggerAware = True
NoiseOccupancyMinStat = 5000
RawOccupancyMinStat   = 5000
EfficiencyMinStat     = 5000
BSErrorDBMinStat      = 5000
LorentzAngleMinStat   = 5000

#--- Lorentz Angle Debug Mode
LorentzAngleDebugMode = True

#--------------------------------------------------------------
# Tags for local DB and XML files in SCTCalib/SCTCalibWriteSvc
#--------------------------------------------------------------
TagID4NoisyStrips    = 'SctDerivedMonitoring-RUN2-UPD4-005' # UPD4, open IOV for BLK
TagID4DeadStrips     = 'SctDerivedDeadStrips-003-00'
TagID4DeadChips      = 'SctDerivedDeadChips-003-00'
TagID4NoiseOccupancy = 'SctDerivedNoiseOccupancy-003-01'
TagID4RawOccupancy   = 'SctDerivedRawOccupancy-003-00'
TagID4Efficiency     = 'SctDerivedEfficiency-003-00'
TagID4BSErrors       = 'SctDerivedBSErrorsRun2-001-00'
TagID4LorentzAngle   = 'SctDerivedLorentzAngleRun2_v2-001-00'

#--------------------------------------------------------------
# A list of GeometryTags
# - One tag is chosen in topOptions from magnet current info
#--------------------------------------------------------------
GeometryTagSTF = 'ATLAS-R2-2015-03-00-00'    # Solenoid=ON,  BarrelToroid=ON
GeometryTagNTF = 'ATLAS-R2-2015-03-00-00'    # Solenoid=ON,  BarrelToroid=OFF
GeometryTagNSF = 'ATLAS-R2-2015-03-00-00'    # Solenoid=OFF, BarrelToroid=ON
GeometryTagNF  = 'ATLAS-R2-2015-03-00-00'    # Solenoid=OFF, BarrelToroid=OFF
GeometryTagMC  = 'ATLAS-R2-2015-03-00-00'    # MC

#--------------------------------------------------------------
# A list of ConditionsTags
# - One tag is chosen in topOptions from magnet current info
#--------------------------------------------------------------
#--- MC
ConditionsTagMC  = 'OFLCOND-DR-BS7T-ANom-00' # digi+rec for MC09 - Nominal
#--- BLK : bulk production
ConditionsTagSTF = 'CONDBR2-ES1PA-2016-03'    # Solenoid=ON,  BarrelToroid=ON
ConditionsTagNTF = 'CONDBR2-ES1PA-2016-03'    # Solenoid=ON,  BarrelToroid=OFF
ConditionsTagNSF = 'CONDBR2-ES1PA-2016-03'    # Solenoid=OFF, BarrelToroid=ON
ConditionsTagNF  = 'CONDBR2-ES1PA-2016-03'    # Solenoid=OFF, BarrelToroid=OFF

#--------------------------------------------------------------
# Read /SCT/Derived/Monotoring in COOL
NoisyReadNumRuns = 5   # Used in a criteria for upload of NoisyStrips
TagID4NoisyUploadTest = 'SctDerivedMonitoring-RUN2-UPD4-005'


"""
Copyright (c) Facebook, Inc. and its affiliates.

This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""

"""
Definition of PyTorch "Dataset" that iterates through compressed videos
and return compressed representations (I-frames, motion vectors,
or residuals) for training or testing.
"""

import os
import os.path
import random

import numpy as np
import torch
import torch.utils.data as data

from coviar import get_num_frames
from coviar import load
from transforms import color_aug
from PIL import Image
from skimage.measure import block_reduce
from scipy import interpolate

import logging
logging.basicConfig(level=logging.DEBUG)

GOP_SIZE = 12

# '/projects/eventnet/dataset/HMDB51/fb/TSN_input/'

def video_path_to_flow_path(flow_root, video_path):
    # example:
    tmp = video_path.split('/')
    return os.path.join(flow_root, tmp[-2], tmp[-1][:-4])

def clip_and_scale(img, size):
    return (img * (127.5 / size)).astype(np.int32)

def get_seg_range(n, num_segments, seg, representation):
    if representation in ['residual', 'mv', 'flow']:
        n -= 1

    seg_size = float(n - 1) / num_segments
    seg_begin = int(np.round(seg_size * seg))
    seg_end = int(np.round(seg_size * (seg+1)))
    if seg_end == seg_begin:
        seg_end = seg_begin + 1

    if representation in ['residual', 'mv', 'flow']:
        # Exclude the 0-th frame, because it's an I-frmae.
        return seg_begin + 1, seg_end + 1

    return seg_begin, seg_end

def get_gop_pos(frame_idx, representation):
    """given frame idx to find the group idx and the position inside a group"""
    gop_index = frame_idx // GOP_SIZE
    gop_pos = frame_idx % GOP_SIZE
    if representation in ['residual', 'mv', 'flow']:
        if gop_pos == 0:    # use the previous frame's residual and MV if it's iframe
            gop_index -= 1
            gop_pos = GOP_SIZE - 1
    else:
        gop_pos = 0 # indeed find the iframe rather than rgb frame in the middle of GOP
    return gop_index, gop_pos

class CoviarDataSet(data.Dataset):
    def __init__(self, data_root, flow_root, data_name,
                 video_list,
                 representation,
                 new_length,
                 flow_ds_factor,
                 upsample_interp,
                 transform,
                 num_segments,
                 is_train,
                 accumulate,
                 gop,
                 mv_minmaxnorm=0,
                 viz=False,
                 flow_folder='tvl1'):

        self._data_root = data_root
        self._data_name = data_name
        self._flow_root = flow_root
        self._num_segments = num_segments
        self._representation = representation
        self._new_length = new_length
        self._flow_ds_factor = flow_ds_factor
        self._upsample_interp = upsample_interp
        self._mv_minmaxnorm = mv_minmaxnorm
        self._transform = transform
        self._is_train = is_train
        self._accumulate = accumulate
        self._viz = viz
        self._flow_folder = flow_folder
        global GOP_SIZE
        GOP_SIZE = gop

        self._input_mean = torch.from_numpy(
            np.array([0.485, 0.456, 0.406]).reshape((1, 3, 1, 1))).float()
        self._input_std = torch.from_numpy(
            np.array([0.229, 0.224, 0.225]).reshape((1, 3, 1, 1))).float()

        self._load_list(video_list)

    def _load_list(self, video_list):
        self._video_list = []
        with open(video_list, 'r') as f:
            for line in f:
                video, _, label = line.strip().split()
                video_path = os.path.join(self._data_root, video[:-4] + '.mp4')
                flow_path = video_path_to_flow_path(self._flow_root, video_path)
                self._video_list.append((
                    video_path,
                    int(label),
                    min(get_num_frames(video_path),len(os.listdir(flow_path))/3)))

        print('%d videos loaded.' % len(self._video_list))

    def _get_train_frame_index(self, num_frames, seg):
        # Compute the range of the segment.
        seg_begin, seg_end = get_seg_range(num_frames, self._num_segments, seg,
                                                 representation=self._representation)

        # Sample one frame from the segment.
        v_frame_idx = random.randint(seg_begin, seg_end - 1)
        return get_gop_pos(v_frame_idx, self._representation)

    def _get_test_frame_index(self, num_frames, seg):
        if self._representation in ['mv', 'residual', 'flow']:
            num_frames -= 1

        seg_size = float(num_frames - 1) / self._num_segments
        v_frame_idx = int(np.round(seg_size * (seg + 0.5)))

        if self._representation in ['mv', 'residual', 'flow']:
            v_frame_idx += 1

        return get_gop_pos(v_frame_idx, self._representation)

    def __getitem__(self, index):

        if self._representation == 'mv':
            representation_idx = 1
        elif self._representation == 'residual':
            representation_idx = 2
        else:
            representation_idx = 0

        if self._is_train:
            video_path, label, num_frames = random.choice(self._video_list)
        else:
            video_path, label, num_frames = self._video_list[index]

        frames = []
        idx_first = -99999
        for seg in range(self._num_segments):

            if self._is_train:
                gop_index, gop_pos = self._get_train_frame_index(num_frames, seg)
            else:
                gop_index, gop_pos = self._get_test_frame_index(num_frames, seg)

            flow_path = video_path_to_flow_path(self._flow_root, video_path)
            if self._flow_folder == 'tvl1':
                flow_tmpl = 'flow_{0}_{1:05d}.jpg'
            if self._flow_folder[0:3] == 'PWC':
                flow_tmpl = 'flow_{0}_{1:05d}.png'
            idx = gop_index * GOP_SIZE + gop_pos + 1
            if idx_first == -99999:
                idx_first = idx
            # read the corresponding pre-computed optical flow along x and y dimension
            x_img = np.array(Image.open(os.path.join(flow_path, flow_tmpl.format('x', idx))).convert('L'))
            y_img = np.array(Image.open(os.path.join(flow_path, flow_tmpl.format('y', idx))).convert('L'))
            flow = np.stack([x_img, y_img], axis=-1)
            if flow is None:
                print('Error: loading flow %s failed.' % video_path)

            # load MV and data pre-processing
            mv = load(video_path, gop_index, gop_pos, representation_idx, self._accumulate)

            if mv is None:
                print('Error: loading video %s failed.' % video_path)
                mv = np.zeros((256, 256, 2)) if self._representation == 'mv' else np.zeros((256, 256, 3))
            else:
                if self._representation == 'mv':
                    if self._mv_minmaxnorm == 1:
                        mv = clip_and_scale(mv, 20)   # scale values from +-20 to +-127.5
                    mv += 128
                    mv = (np.minimum(np.maximum(mv, 0), 255)).astype(np.uint8)
                elif self._representation == 'residual':
                    mv += 128
                    mv = (np.minimum(np.maximum(mv, 0), 255)).astype(np.uint8)

            if self._representation == 'iframe':
                mv = color_aug(mv)

                # BGR to RGB. (PyTorch uses RGB according to doc.)
                mv = mv[..., ::-1]

            # load residual and data pre-processing
            residual = load(video_path, gop_index, gop_pos, 2, self._accumulate)
            residual += 128
            residual = (np.minimum(np.maximum(residual, 0), 255)).astype(np.uint8)

            frames.append(np.concatenate((flow, mv, residual), axis=2))

        frames = self._transform(frames)

        frames = np.array(frames)
        frames = np.transpose(frames, (0, 3, 1, 2))
        # print('frames shape in dataloader:')
        # print(frames.shape)  # (num_crops*num_segments, 5, 224, 224)

        # split input into input_mv and input_flow
        input_flow = frames[:, 0:2, :, :]
        input_mv = frames[:, 2:4, :, :]
        input_residual = frames[:, 4:, :, :]

        if self._flow_ds_factor is not 0:
            # downsample to make OF blocky
            factor = self._flow_ds_factor
            w_max = input_flow.shape[2]
            h_max = input_flow.shape[3]
            input_flow = block_reduce(input_flow, block_size=(1, 1, factor, factor), func=np.mean)
            # resize to original size by repeating or interpolation
            if self._upsample_interp is False:
                input_flow = input_flow.repeat(factor, axis=2).repeat(factor, axis=3)
            else:
                # interpolate along certain dimension? only interp1d can do so
                w_max_ds = input_flow.shape[2]
                h_max_ds = input_flow.shape[3]
                f_out = interpolate.interp1d(np.linspace(0, 1, w_max_ds), input_flow, kind='linear', axis=2)
                input_flow = f_out(np.linspace(0, 1, w_max_ds * factor))
                f_out = interpolate.interp1d(np.linspace(0, 1, h_max_ds), input_flow, kind='linear', axis=3)
                input_flow = f_out(np.linspace(0, 1, h_max_ds * factor))
            input_flow = input_flow[:, :, :w_max, :h_max]

        """load data from numpy to torch and pre-processing"""
        # print('input_flow shape in dataloader:')
        # print(input_flow.shape)  # (num_crops*num_segments, 2, 224, 224)
        input_flow = torch.from_numpy(input_flow).float() / 255.0
        input_mv = torch.from_numpy(input_mv).float() / 255.0
        input_residual = torch.from_numpy(input_residual).float() / 255.0
        # print('input_flow after torch shape in dataloader:')
        # print(input_flow.shape)  # torch.Size([num_crops*num_segments, 2, 224, 224])

        if self._representation == 'iframe':
            input_mv = (input_mv - self._input_mean) / self._input_std
        elif self._representation == 'mv':
            input_mv = (input_mv - 0.5) / torch.mean(self._input_std)

        input_flow = (input_flow - 0.5) / torch.mean(self._input_std)
        input_residual = (input_residual - 0.5) / self._input_std

        # print('Input flow shape %s:' % str(input_flow.shape))  # torch.Size([1, num_crops*num_segments, 2, 224, 224])
        # print('Input mv shape %s:' % str(input_mv.shape))
        # print('Input residual shape %s:' % str(input_residual.shape))
        # print('Input mv scope min %s:' % str(input_mv.min()))
        # print('Input mv scope max %s:' % str(input_mv.max()))
        # print('Input flow scope min %s:' % str(input_flow.min()))
        # print('Input flow scope max %s:' % str(input_flow.max()))
        if (self._viz == True) and (self._is_train == False):
            classname = flow_path.split('/')[-2]
            img_tmpl = 'img_{:05d}.jpg'
            # idx is the index of the first frame/segment of the current video
            return input_flow, input_mv, input_residual, label, os.path.join(flow_path, img_tmpl.format(idx_first)), classname
        else:
            return input_flow, input_mv, input_residual, label

    def __len__(self):
        return len(self._video_list)


import random

def countNeg(list):
    count = 0
    for i in list:
        if i < 0:
            count = count + 1
    return count

lst = []
for i in range(100):
    lst.append(random.randint(-1000, 1000))

print(countNeg(lst))


'''
Name   :   Login
Usage  :   Get Resource for Login screen
Description : This code is used to Login into Intuglo Logistics and interacts with the logins and config tables.
'''

import falcon
import json
import pymysql
from SessionManagement import createSession
from DatabaseConnection import *
from memcacheResource import MemcacheFunctions
import traceback
import sys
import bcrypt

class LoginResource__v1__(object):
    def on_get(self, req, resp, user, password):
        try:
            database_connection = get_db_connection()
            cursor = database_connection.cursor()
            cursor.execute("SELECT password from logins where email = '"+user+"' ")
            row = cursor.fetchone()
            if(cursor.rowcount>0):
                status = bcrypt.checkpw(password.encode('utf-8'),row['password'])
                if status:
                    cursor.execute("SELECT logins.login_id,logins.is_active,logins.is_on_boarded, logins.merchant_id,logistic_providers.supplier_id,\
                    logistic_providers.supplier_name,customers.customer_name, customers.customer_id,custom_agent.agent_name,customers.cart_id,\
                    custom_agent.custom_agent_id,admin_profile.admin_name,admin_profile.admin_id,logins.user_type\
                        FROM logins\
                        LEFT JOIN logistic_providers ON  logins.login_id = logistic_providers.login_id\
                        LEFT JOIN customers ON logins.login_id = customers.login_id\
                        LEFT JOIN custom_agent ON logins.login_id = custom_agent.login_id\
                        LEFT JOIN admin_profile ON logins.login_id = admin_profile.login_id\
                        WHERE logins.email = '"+user+"'")

                    row = cursor.fetchall()
                    UserDetails=list(row)
                    NewDict = dict()
                    for k,v in UserDetails[0].items():
                        if v is not None:
                            NewDict[k] = v
                    if(NewDict['is_active']==1):
                        SessionID = createSession(user)
                        resp.status = falcon.HTTP_200
                        login_id = str(NewDict['login_id'])
                        MemcacheFunctions.mc.set(login_id,SessionID,300)
                        NewDict['SessionID'] = SessionID
                        if (NewDict['user_type'] is 1):
                            NewDict['UserID'] = NewDict.pop('supplier_id')
                            NewDict['UserName'] = NewDict.pop('supplier_name')
                        elif (NewDict['user_type'] is 2):
                            NewDict['UserID'] = NewDict.pop('customer_id')
                            NewDict['UserName'] = NewDict.pop('customer_name')
                            if 'cart_id' in NewDict:
                                old_cart_id = NewDict['cart_id']
                                cursor.execute("select cart_status from carts where cart_id = "+str(NewDict['cart_id'])+"")
                                cart_info = cursor.fetchone()
                                if cursor.rowcount > 0:
                                    if cart_info['cart_status'] == 'PAID':
                                        database_connection.begin()
                                        cursor.execute("insert into carts(login_id) VALUES ("+str(NewDict['login_id'])+")")
                                        cart_id = cursor.lastrowid
                                        NewDict['cart_id'] = cart_id
                                        cursor.execute("update customers set cart_id = "+str(cart_id)+" where cart_id = "+str(old_cart_id)+"")
                                        database_connection.commit()
                            else:
                                cursor.execute("insert into carts(login_id) VALUES ("+str(NewDict['login_id'])+")")
                                database_connection.commit()
                                cart_id = cursor.lastrowid
                                NewDict['cart_id'] = cart_id
                                cursor.execute("update customers set cart_id = "+str(cart_id)+" where customer_id = "+str(NewDict['UserID'])+"")
                                database_connection.commit()
                        elif (NewDict['user_type'] is 3):
                            NewDict['UserID'] = NewDict.pop('custom_agent_id')
                            NewDict['UserName'] = NewDict.pop('agent_name')
                        elif (NewDict['user_type'] is 0):
                            NewDict['UserID'] = NewDict.pop('admin_id')
                            NewDict['UserName'] = NewDict.pop('admin_name')
                        result_json = json.dumps(NewDict, sort_keys=True)
                        resp.body = (result_json)
                    else:
                        resp.status = falcon.HTTP_200
                        Err = {"Reason": "Your account is not active"}
                        result_json = json.dumps(Err)
                        resp.body = (result_json)
                else:
                    resp.status = falcon.HTTP_401
                    Error = {"Error Message": "Your email or password is incorrect."}
                    jsonresult = json.dumps(Error)
                    resp.body = (jsonresult)
            else:
                resp.status = falcon.HTTP_204
                Error = {"Error Message": "Email is not found. Please Sign Up."}
                jsonresult = json.dumps(Error)
                resp.body = (jsonresult)

        except ValueError as err:
            raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args)
        except pymysql.IntegrityError as err:
            raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args)
        except Exception as err:
            raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args)
        finally:
            cursor.close()
            database_connection.close()


from django.db import models
from django.contrib.auth.models import AbstractUser
from .grade_sheet import SubjectGrade, SubjectGradePoint
from django.utils import timezone

from django.db.models import Avg, Count, Min, Sum

STD_CLASS = (
    ('6', 'Six'),
    ('7', 'Seven'),
    ('8', 'Eight'),
    ('9', 'Nine'),
    ('10', 'Ten'),
)

STD_GENDER = (
    ('MALE', 'Male'),
    ('FEMALE', 'Female'),
)

STD_GROUP = (
        ('S', 'Science'),
        ('B', 'Business Studies'),
        ('H', 'Humatics'),
        ('G', 'General')
)

REGULAR = 'R'
OPTIONAL = 'O'

SUBJECT_TYPE_CHOICE = (
        (REGULAR, 'REGULAR'),
        (OPTIONAL, 'OPTIONAL')
)

class CustomUser(AbstractUser):
    name=models.CharField('Full Name',max_length=100)

class StdCommon(models.Model):
    pub_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)

class SubjectTecher(StdCommon):
    teacher_name=models.CharField('Teacher Name', max_length=100)
    teach_phone_number=models.IntegerField('Mobile Number')
    teach_major_subject=models.CharField('Subject Name: ', max_length=100)

    def __str__(self):
        return self.teacher_name

class StdSubject(StdCommon):

    subject_name = models.CharField('Subject Name', max_length=100)
    teacher=models.ForeignKey(SubjectTecher, on_delete=models.CASCADE, related_name='teacher')
    subject_group = models.CharField(
        'Subject Group', choices=STD_GROUP, default='G', max_length=10)

    subject_code=models.CharField('Subject Code', max_length=10)
    subjet_class = models.CharField(
        'Subject Class', max_length=2, choices=STD_CLASS, default='6')
    subject_type = models.CharField(
        'Subject Type', max_length=1, default=REGULAR, choices=SUBJECT_TYPE_CHOICE)
    subject_full_marks = models.DecimalField(
        'Full Marks', max_digits=5, decimal_places=2, default=100)
    subject_pass_marks = models.DecimalField(
        'Pass Marks', max_digits=5, decimal_places=2, default=33)

    subject_form_searh_name=models.CharField('Subject Search Form name', max_length=500, blank=True, null=True)

    def __str__(self):
        return self.subject_name+' Class '+self.subjet_class+' '+' '+self.subject_type+' Code '+self.subject_code

    def save(self, *args, **kwargs):
        subject_form_searh_name=self.subject_name+' Class '+self.subjet_class+' '+' '+self.subject_type+' Code '+self.subject_code

        self.subject_form_searh_name=subject_form_searh_name

        super(StdSubject, self).save(*args, **kwargs) # Call the real save() method

    class Meta:
        verbose_name = ("Subject")
        verbose_name_plural = ("Subject")
        ordering = ['subject_code']

class StudentInfo(StdCommon):

    std_name = models.CharField('Student Name',max_length=100, help_text='Type only student Full Name like as Nazmul Islam or Nazrul Islam', blank=True, null=True)
    std_class = models.CharField('Student Class',max_length=2, choices=STD_CLASS, default=6, help_text='Select a class')
    std_roll = models.IntegerField('Roll Number',help_text='Type Student Roll Number (Only Number)')
    std_group=models.CharField('Group', choices=STD_GROUP, max_length=1, default='G')
    std_gender=models.CharField('Gender', max_length=10, choices=STD_GENDER, default='MALE')
    #std_subjects = models.ManyToManyField(StdSubject)

    std_total_marks = models.FloatField('Total Marks', default=0, blank=True, null=True)

    std_gpa = models.CharField('GPA', max_length=50,default='F', blank=True, null=True)

    std_grade_point_total_sum=models.FloatField('Total Avg Number per Subject', blank=True, null=True) # toal grade point sum

    std_grade_point_total_subject_avg = models.FloatField(
        'Total GPA', blank=True, null=True) #avg gradepoint

    std_fail_subject=models.IntegerField('Fail Subject', blank=True, null=True)

    school_rank=models.IntegerField('Student Rank in School',default=0, blank=True, null=True)
    class_rank = models.IntegerField(
        'Student Rank in Class', default=0, blank=True, null=True)

    def __str__(self):
        return self.std_name

    class Meta:
            verbose_name = ("Student Detail")
            verbose_name_plural = ("Student Detail's")
            ordering = ['std_roll']

    def total_marks_sum(self):
        std_id = self.id
        x = Marks.objects.filter(std_name=std_id).aggregate(
            total_number=Sum('subject_marks')).get('total_number', 0)

        return x

    def save(self, *args, **kwargs):

        std_id = self.id
        fail_sub = 0
        std_result='Pass'

        total_number = Marks.objects.filter(std_name=std_id).aggregate(
            total_number=Sum('subject_marks')).get('total_number', 0)

        subject_grade = ((Marks.objects.filter(std_name=std_id, subject_gradepoint__gte=1).aggregate(sp=Sum('subject_gradepoint')).get('sp', 0)))

        self.std_total_marks = total_number

        if subject_grade is None:
            subject_grade=0

        self.std_grade_point_total_sum = subject_grade

        subject_grade_f = Marks.objects.filter(std_name=std_id, subject_name__subject_type__startswith='R')

        try:
            class_rank_new = Rank.objects.get(std=self.id)
            self.class_rank = class_rank_new.class_rank
            self.school_rank = class_rank_new.school_rank
        except :
            self.class_rank = 0
            self.school_rank = 0

        for i in subject_grade_f:

            if 'F' == i.subject_gpa:
                fail_sub = fail_sub+1

            std_result = 'Fail ' +str(fail_sub)+' Subject'

        self.std_gpa = std_result

        self.std_fail_subject=fail_sub

        if fail_sub >= 1:
            self.std_grade_point_total_subject_avg=0

        else:
            if self.std_class == '6' or self.std_class == '7':
                self.std_grade_point_total_subject_avg ='%2f' % (subject_grade/7)
            elif self.std_class == '8':
                self.std_grade_point_total_subject_avg ='%2f' % (subject_grade/7)

            elif self.std_class == '9' or self.std_class == '10':
                self.std_grade_point_total_subject_avg = '%2f' % (subject_grade/9)

        super(StudentInfo, self).save(*args, **kwargs) # Call the real save() method

class Marks(StdCommon):
    std_name = models.ForeignKey(
        StudentInfo, on_delete=models.CASCADE)
    subject_name = models.ForeignKey(StdSubject, on_delete=models.CASCADE)
    subject_marks=models.DecimalField(max_digits=5, decimal_places=2, help_text='Please give proper number')

    subject_gradepoint=models.DecimalField('Grade Point', max_digits=3, decimal_places=1, blank=True, null=True, help_text="Please keep blank")
    subject_gpa = models.CharField('Subject GPA', max_length=5, blank=True, null=True, help_text="Please keep blank")

    '''
    def __str__(self):
        return self.std_name.std_name+' Class: '+str(self.std_name.std_class)+' Roll: '+str(self.std_name.std_roll) +' ' + self.subject_name.subject_name +' '+str(self.subject_marks)
    '''
    def __str__(self):
        x ='%.f' % self.subject_marks
        return x+' - '+self.subject_name.subject_name

    class Meta:
        verbose_name = ("Mark Details")
        verbose_name_plural = ("Result Sheet Details")
        ordering = ['subject_name']

    def subject_grade(self):
        grade = SubjectGrade(self.subject_marks,self.subject_name.subject_full_marks).subgrade()
        return grade

    def subject_grade_point(self):
        grade = SubjectGradePoint( self.subject_marks, self.subject_name.subject_full_marks).subgrade()
        return grade

    def save(self, *args, **kwargs):
        grade_point = SubjectGradePoint(self.subject_marks, self.subject_name.subject_full_marks).subgrade()
        gpa = SubjectGrade(self.subject_marks,self.subject_name.subject_full_marks).subgrade()

        if self.subject_name.subject_type =='O':

            if self.subject_marks >= ((self.subject_name.subject_full_marks/100)*50) and self.subject_marks <= self.subject_name.subject_full_marks:
                subject_opt_grade_point = grade_point-2

                self.subject_gradepoint = subject_opt_grade_point
                self.subject_gpa = gpa

            elif self.subject_marks >= ((self.subject_name.subject_full_marks/100)*33) and self.subject_marks < ((self.subject_name.subject_full_marks/100)*50):
                self.subject_gradepoint = 0
                self.subject_gpa=gpa

            elif self.subject_marks < ((self.subject_name.subject_full_marks/100)*33):
                self.subject_gradepoint = 0
                self.subject_gpa = gpa

        elif self.subject_name.subject_type == 'R':
            self.subject_gradepoint = grade_point
            self.subject_gpa = gpa

        super().save(*args, **kwargs)

class Rank(models.Model):
    std = models.ForeignKey(StudentInfo, related_name='std', on_delete=models.CASCADE)

    total_marks = models.DecimalField(
        max_digits=5, decimal_places=2, help_text='Please give proper number', default=0, blank=True, null=True)
    total_gpa = models.DecimalField(
        max_digits=5, decimal_places=2, help_text='Please give proper number', default=0, blank=True, null=True)
    class_rank = models.IntegerField(default=0, blank=True, null=True)
    school_rank=models.IntegerField('All School Rank', default=0, blank=True, null=True)

    def __str__(self):
        return 'Name: %s |  Marks: %s | Class Rank %s | School Rank %s' % (self.std, self.total_marks, self.class_rank, self.school_rank)

    class Meta:
            verbose_name = ("Rank")
            verbose_name_plural = ("Rank")
            ordering = ['class_rank']


'''
Created on Apr 8, 2019

@author: smaiya
'''

"""
logistic regression
 objective: argmin (beta) (sum_i(sum_j(xij*betas_j) - yi)^2)
 d/dbeta_j(loss function) = 0
 yi
 xis for each data bit
 sum(xi^2*beta_i) beta_1 proporational to the snr_i
  pilot bits -- known bits sent by network and known power
  using these pilot bits...we estimate the snr_i
"""

"""
Given two sparse matrices A and B, return the result of multiplication of A and B.
You may assume that A's column number is equal to B's row number.
A = mxn -- ~x elements x<<mxn
B = nxp -- ~y elements y<<nxp
Multiplication ~ O(x+y)
"""
#Operations(rawA, rawB).multiply()

class Operations(object):
    def __init__(self, rawA, rawB):
        self.sparseA = self.sparse_matrix(rawA)
        self.sparseB = self.sparse_matrix(rawB)
        self.m = len(rawA)
        self.n = len(rawA[0])
        self.p = len(rawB[0])

    def sparse_matrix(self, matrix):
        sparse_matrix = {}
        num_cols = len(matrix[0])
        for row_idx, row in enumerate(matrix):
            for col_idx, element in enumerate(row):
                if (element!=0):
                    sparse_matrix[col_idx+row_idx*num_cols] = element
        return sparse_matrix

    def multiply(self):
        output = {}
        for i in range(self.m):
            for j in range(self.p):
                # mth row of sparseA and pth column of sparseB
                for k in range(self.n):
                    mult_cell = 0
                    if (self.sparseA[k+i*self.n] and self.sparseB[j+k*self.n]):
                        mult_cell+= (self.sparseA[k+i*self.n] * self.sparseB[j+k*self.n])
                if mult_cell!=0:
                    output[j+i*self.m] = mult_cell

        for idxA, valA in self.sparseA.items():

            for idxB, valB in self.sparseB.items():
                for k in range(self.n):
                    mult_cell = 0
                    # Check if idxA and idxB are applicable to k
                    if (idxA):
                        mult_cell+=valA*valB

        return output


# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations

# -------------------------------------------------------------------------
# This is a sample controller
# - index is the default action of any application
# - user is required for authentication and authorization
# - download is for downloading files uploaded in the db (does streaming)
# -------------------------------------------------------------------------
import re
import random

stoplist = [
    "",
    "The", "the",
    "is", "an",
    "to", "at",
    "of", "in",
    "and",
]

def index():
    """
    example action using the internationalization operator T and flash
    rendered by views/default/index.html or views/generic.html

    if you need a simple wiki simply replace the two lines below with:
    return auth.wiki()
    """
    if auth.user_id is not None: ()
    trl_list = []
    i = 0
    for row in db().select(db.trailer_metadata.ALL, orderby='<random>', limitby=(0, 30)):
        trl_list.append(row)
        i += 1
    movie_list = []
    j = 0
    for row in db().select(db.movie_metadata.ALL, orderby='<random>', limitby=(0, 30)):
        movie_list.append(row)
        j += 1
    randm1 = []
    randm2 = []
    randm3 = []
    for x in range(0, 3):
        randm1.append(movie_list[random.randint(0, j - 1)])
        randm2.append(movie_list[random.randint(0, j - 1)])
        randm3.append(movie_list[random.randint(0, j - 1)])
    randt = trl_list[random.randint(0, i - 1)]
    genre = ['Action', 'Adventure', 'Fantasy', 'Sci-Fi', 'Thriller', 'Documentary', 'Romance', 'Animation', 'Comedy',
             'Family', 'Musical', 'Mystery', 'Western', 'Drama', 'History', 'Sport', 'Crime', 'Horror', 'War',
             'Biography', 'Music', 'Game-Show', 'Reality-TV', 'News', 'Short', 'Film-Noir']
    return dict(trl=trl_list, rant=randt, ranm1=randm1, ranm2=randm2, ranm3=randm3, genres=genre)

@auth.requires_login()
def preferences():
    """
    Suggests movie, add like movie to database, dislike movie to database:
    """
    rows = db().select(db.movie_metadata.ALL, orderby='<random>', limitby=(0, 50))
    return dict(rows=rows)

def page():
    key = request.args[0]
    movie = db(db.movie_metadata.movie_id == key).select()
    return dict(rows=movie)

def post():
    search = request.vars.key_terms
    key = search.split()
    rows = db(db.movie_metadata.movie_title.contains(key) or
             db.movie_metadata.director_name.contains(key) or
             db.movie_metadata.title_year.contains(key) or
             db.movie_metadata.content_rating.contains(key) or
             db.movie_metadata.imdb_score.contains(key) or
             db.movie_metadata.genres.contains(key) or
             db.movie_metadata.plot_keywords.contains(key) or
             db.movie_metadata.synopsis.contains(key) or
             db.movie_metadata.color.contains(key) or
             db.movie_metadata.country.contains(key) or
             db.movie_metadata.movie_language.contains(key) or
             db.movie_metadata.actor_1_name.contains(key) or
             db.movie_metadata.actor_2_name.contains(key) or
             db.movie_metadata.actor_3_name.contains(key) or
             db.movie_metadata.plot_keywords.contains(key) or
             db.movie_metadata.synopsis.contains(key)).select()
    return dict(rows=rows)

def user():
    """
    exposes:
    http://..../[app]/default/user/login
    http://..../[app]/default/user/logout
    http://..../[app]/default/user/register
    http://..../[app]/default/user/profile
    http://..../[app]/default/user/retrieve_password
    http://..../[app]/default/user/change_password
    http://..../[app]/default/user/bulk_register
    use @auth.requires_login()
        @auth.requires_membership('group name')
        @auth.requires_permission('read','table name',record_id)
    to decorate functions that need access control
    also notice there is http://..../[app]/appadmin/manage/auth to allow administrator to manage users
    """
    # Redirects user to users preference page
    auth.settings.login_next = URL('default', 'preferences')
    return dict(form=auth())

@cache.action()
def download():
    """
    allows downloading of uploaded files
    http://..../[app]/default/download/[filename]
    """
    return response.download(request, db)

def call():
    """
    exposes services. for example:
    http://..../[app]/default/call/jsonrpc
    decorate with @services.jsonrpc the functions to expose
    supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
    """
    return service()

def directors():
    return dict()

def genres():
    genre = request.args[0]
    rows = db(db.movie_metadata.genres.contains(genre)).select()
    return dict(rows=rows)

def popular():
    rows = db(db.movie_metadata.movie_facebook_likes).select(limitby=(0, 100),
                                                             orderby=~db.movie_metadata.movie_facebook_likes)
    return dict(rows=rows)

def top():
    rows = db(db.movie_metadata.imdb_score).select(limitby=(0, 100), orderby=~db.movie_metadata.imdb_score)
    return dict(rows=rows)

def get_movies():
    search_string = request.vars.q.strip()
    rows = db().select(db.movie_metadata.ALL, limitby=(0, 100))
    movie_list = []
    sublist = []
    title_list = []
    original_list = []

    #Starting algorithm, start by finding all words with a size greater than 2
    for r in rows:
        append_list = re.findall(r'[A-z0-9][A-z0-9]+', r.movie_title)
        if len(append_list):
            title_list.append(append_list)
            original_list.append(r.movie_title)

    i = 0
    removal = 0

    #each title in the title is another title
    for title in title_list:
        k = 0

        #this code changes all words to lower case if not already, makes the word non-plural. No I can't actually
        #tell if it's plural, but as long as I apply the same technique to incoming search terms the result is the same
        for word in title:
            title[k] = word.lower()
            if title[k][-1] == 's' and title[k][-2] != 's':
                title[k] = title[k][:-1]
            k+=1

        s_word = 0
        removal = 0

        #This code removes useless words that can't be used as keywords. The funny stuff with the while loop is because
        #of the array removal causing shenanagins
        while s_word < len(title):
            for stop_word in stoplist:
                if title[s_word] == stop_word:
                    title.remove(title[s_word])
                    removal = 1
            if removal:
                removal = 0
            else:
                s_word += 1

    #This code starts both the query parsing as well as the scoring algorithm
    #good shit right here
    if request.vars.q.strip():
        high_list = []
        high_original = []

        #parse the search terms using the same methods as the titles to ensure compaitbility
        search_list = [x for x in re.findall(r'[A-z0-9][A-z0-9]+', request.vars.q)]

        i = 0
        for word in search_list:
            search_list[i] = word.lower()
            if search_list[i][-1] == 's' and search_list[i][-2] != 's':
                search_list[i] = search_list[i][:-1]
            i += 1

        s_word = 0
        removal = 0
        # This code removes useless words that can't be used as keywords, just like the one before
        while s_word < len(search_list):
            for stop_word in stoplist:
                if search_list[s_word] == stop_word:
                    search_list.remove(search_list[s_word])
                    removal = 1
            if removal:
                removal = 0
            else:
                s_word += 1

        highest_score = 0
        index = 0
        for list in title_list:
            search_match = 0
            for title_word in list:
                for search_word in search_list:
                    if search_word == title_word:
                        search_match += 1

            # This is the actual algorithm,
            # score =        [# of matched words]              [# of matched words]
            #              -------------------------   +  ------------------------------
            #              2 x [# of searched words]      2 x [# of words in movie title]
            search_score = float(search_match) / (len(search_list) * 2) + float(search_match) / (len(list) * 2)

            #Scorekeeping
            if search_score > highest_score:
                #print(original_list[index])
                sublist = []
                sublist.append(original_list[index])
                sublist.append(search_score)
                high_original = [sublist] + high_original
                sublist = []

                highest_score = search_score
            elif search_score > 0.3:
                #print(original_list[index])
                sublist = []
                sublist.append(original_list[index])
                sublist.append(search_score)
                high_original.append(sublist)
            sublist = []
            index += 1
            #end for loop
        for item in high_original:
            sublist = []
            r = db(db.movie_metadata.movie_title == item[0]).select().first()
            sublist.append(r.movie_title)
            sublist.append(r.director_name)
            sublist.append(r.imdb_score)
            sublist.append(r.genres)
            sublist.append(r.synopsis)
            sublist.append(r.content_rating)
            sublist.append(r.movie_poster_link)
            sublist.append(r.movie_imdb_link)
            sublist.append(r.movie_trailer_link)

            movie_list.append(sublist)

    else:
        for r in rows:
            #append items to the list of lists of lists of lists of lists of lists
            sublist.append(r.movie_title)
            sublist.append(r.director_name)
            sublist.append(r.imdb_score)
            sublist.append(r.genres)
            sublist.append(r.synopsis)
            sublist.append(r.content_rating)
            sublist.append(r.movie_poster_link)
            sublist.append(r.movie_imdb_link)
            sublist.append(r.movie_trailer_link)

            movie_list.append(sublist)
            sublist = []

    return response.json(dict(movie_list=movie_list))

def movies():
    return dict()

def query():
    return dict()


"""
ID: xknxkn1
LANG: PYTHON3
TASK: crypt1
"""

f=open("crypt1.in",'r')

N=int(f.readline().strip())
dsetstr=f.readline().strip().split(" ")
dset=list(map(int,dsetstr))
dset.sort()
dsetstr=list(map(str,dset))
print("N,dsetstr,dset",N,dsetstr,dset)

allgood=[]
line1=[0,0,0,0]
line2=[0,0]
line3=[0,0,0,0]
line4=[0,0,0,0]
line5=[0,0,0,0]

def charinset(charstr,charset):
    chars=list(charstr)
    for char in chars:
        if char not in charset:
            return False
    return True

def goodmultple(line1,line2):
    global allgood
    l1str="".join(list(map(str,line1)))
    l2str="".join(list(map(str,line2)))
#    print(l1str+"x"+l2str)
    l1int=int(l1str)
    l2int=int(l2str)
    l3int=l1int*line2[1]
    l3str=str(l3int)
    if len(l3str)>3:
#        print("l3>3")
        return 3
    if charinset(l3str,dsetstr)==False:
        return 1
    l4int=l1int*line2[0]
    l4str=str(l4int)
    if len(l4str)>3:
#        print("l4>3")
        return 4
    if charinset(l4str,dsetstr)==False:
        return 1
    l5int=l1int*l2int
    l5str=str(l5int)

 #   print(l5str)
    if len(l5str)>4:
 #       print("len5>5")
        return 5
    if charinset(l5str,dsetstr)==False:
        return 1

 #   print("good")
#   print("\n"+" "+l1str+"\n"+"   "+l2str+"\n"+"-----"+"\n"+" "+l3str+"   "+"\n"+""+l4str+"\n"+"....."+"\n"+l5str)
    allgood.append(l1str+" "+l2str)
    return 0

line1=[2,2,2]
line2=[2,2]

line1s=[]
for i in range(N):
    for j in range(N):
        for k in range(N):
                line1[0]=dset[i]
                line1[1]=dset[j]
                line1[2]=dset[k]
#                print(line1)
                line1s.append(line1.copy())

line2s=[]
for i in range(N):
    for j in range(N):
        line2[0]=dset[i]
        line2[1]=dset[j]
#        print(line2)
        line2s.append(line2.copy())

#print("line1s",line1s)
#print("line2s",line2s)

def searchall():
    ress=[]
    for i in range(len(line1s)):
        for j in range(len(line2s)):
            line1=line1s[i]
            line2=line2s[j]
            res=goodmultple(line1,line2)
            if res == 0:
                ress.append([line1,line2])
            elif res == 1:
                continue
    return ress

ress=searchall()
result=len(ress)
#print(ress)
outstr=str(result)+"\n"
with open("crypt1.out",'w') as fw:
    print(outstr)
    fw.write(outstr)


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

from msrest.serialization import Model

class MountVolumes(Model):
    """Details of volumes to mount on the cluster.

    :param azure_file_shares: Azure File Share setup configuration. References
     to Azure File Shares that are to be mounted to the cluster nodes.
    :type azure_file_shares: list of :class:`AzureFileShareReference
     <azure.mgmt.batchai.models.AzureFileShareReference>`
    :param azure_blob_file_systems: Azure Blob FileSystem setup configuration.
     References to Azure Blob FUSE that are to be mounted to the cluster nodes.
    :type azure_blob_file_systems: list of
     :class:`AzureBlobFileSystemReference
     <azure.mgmt.batchai.models.AzureBlobFileSystemReference>`
    :param file_servers: References to a list of file servers that are mounted
     to the cluster node.
    :type file_servers: list of :class:`FileServerReference
     <azure.mgmt.batchai.models.FileServerReference>`
    :param unmanaged_file_systems: References to a list of file servers that
     are mounted to the cluster node.
    :type unmanaged_file_systems: list of :class:`UnmanagedFileSystemReference
     <azure.mgmt.batchai.models.UnmanagedFileSystemReference>`
    """

    _attribute_map = {
        'azure_file_shares': {'key': 'azureFileShares', 'type': '[AzureFileShareReference]'},
        'azure_blob_file_systems': {'key': 'azureBlobFileSystems', 'type': '[AzureBlobFileSystemReference]'},
        'file_servers': {'key': 'fileServers', 'type': '[FileServerReference]'},
        'unmanaged_file_systems': {'key': 'unmanagedFileSystems', 'type': '[UnmanagedFileSystemReference]'},
    }

    def __init__(self, azure_file_shares=None, azure_blob_file_systems=None, file_servers=None, unmanaged_file_systems=None):
        self.azure_file_shares = azure_file_shares
        self.azure_blob_file_systems = azure_blob_file_systems
        self.file_servers = file_servers
        self.unmanaged_file_systems = unmanaged_file_systems


from django.contrib import admin
from dashboard.models import *
# from clientlabel.models import ClientFileLabel
# from polymorphic.admin import PolymorphicInlineSupportMixin, StackedPolymorphicInline

@admin.register(TopLevelAccount)
class TopLevelAccountAdmin(admin.ModelAdmin):
    list_display = ['id','name']
    search_field = ['name']

# class ClientFileLabelInline(StackedPolymorphicInline):
#     model = ClientFileLabel

# @admin.register(Client)
# class ClientAdmin(admin.ModelAdmin):
# # class ClientAdmin(PolymorphicInlineSupportMixin,admin.ModelAdmin):
#     list_display = ['first', 'last', 'status',
#                     'preparer','reviewer',
#                     # 'esign', 'efile', 'deliver_portal',
#                     # 'nondeliver_date_start',
#                     # 'nondeliver_date_end'
#                     ]
#     search_field = ['first']
    # inlines = (ClientFileLabelInline)

@admin.register(ProjectFileLabel)
# class ProjectFileLabelAdmin(ClientAdmin):
class ProjectFileLabelAdmin(admin.ModelAdmin):
    # def get_list_display(self, request):
    #     return self.list_display
    list_display = ['project', 'client',
                    # 'status',
                    # 'preparer','reviewer',
                    'esign', 'efile', 'deliver_portal',
                    'nondeliver_date_start',
                    'nondeliver_date_end'
                    ]
    list_filter = ['client','esign']
    # search_field = ['project']

class ProjectFileLabelInline(admin.TabularInline):
    model = ProjectFileLabel

class ClientAdmin(admin.ModelAdmin):
    inlines = [
        ProjectFileLabelInline,
    ]

class ProjectAdmin(admin.ModelAdmin):
    inlines = [
        ProjectFileLabelInline,
    ]

# class ProjectFileLabelAdmin(admin.ModelAdmin):
#     inlines = [
#         ProjectInline,
#     ]
#     exclude = ('clients',)

admin.site.register(Project,ProjectAdmin)
# admin.site.register(ProjectFileLabel,ProjectFileLabelAdmin)
admin.site.register(Client,ClientAdmin)
# @admin.register(Project)
# class ProjectAdmin(admin.ModelAdmin):
#     # def get_list_display(self, request):
#     #     return self.list_display + ('first', 'last')
#     list_display = ['type','tax_year']
# admin.site.register(Project)
# @admin.register(ClientFileLabel)
# class ClientFileLabelAdmin(admin.ModelAdmin):
#     list_display = [
#                     'esign', 'efile', 'deliver_portal',
#                     'nondeliver_date_start',
#                     'nondeliver_date_end',
#                     ]

# Register your models here.
# admin.site.register(Client)
admin.site.register(Preparer)
admin.site.register(Reviewer)
admin.site.register(ProjectStatus)


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

from .game.core import Game
from .utils.package_io import all_cards

__author__ = 'fyabc'

def main():
    AllCards = all_cards()

    game = Game()

    print(AllCards)

if __name__ == '__main__':
    main()


#  Linked List Cycle 2

#  Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
#
#  Follow up:
#  Can you solve it without using extra space?

#  Solution:
#    Step 1: Fast-Slow pointer, if fast pointer reach end, return None. Otherwise, go to Step 2
#    Step 2: Fast-Slow pointer continue move. The circle length is the steps it took to meet agian.
#    Step 3: Front move "cicle length" steps. Then tail start to move.
#    Step 4: They will met when front reach the cicle begin node again.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @return a list node
    def detectCycle(self, head):
        if not head or head.next == head:
            return head
        # Verify the Circle Exist
        fast = head.next
        slow = head
        while fast and fast.next:
            if fast == slow:
                break
            fast = fast.next.next
            slow = slow.next

        if not (fast and fast.next):
            return None

        # Find the length of the circle
        fast = fast.next
        length = 1
        while fast != slow:
            fast = fast.next.next
            slow = slow.next
            length += 1

        fast = head
        slow = head
        while length:
            fast = fast.next
            length -= 1
        while fast != slow:
            fast = fast.next
            slow = slow.next

        return fast


# coding:utf-8
import datetime
from django import forms

from website.models import Person
from common.validators import dni_validator, alphanumeric_validator, phone_validator
from dateutil import relativedelta

class PersonAuthForm(forms.Form):
    document = forms.CharField(max_length=8, strip=True, validators=[dni_validator], required=True)
    birth_date = forms.DateField(input_formats=['%Y-%m-%d'], required=True, localize=False)

    def clean_birth_date(self):
        birth_date = self.cleaned_data.get('birth_date')
        if birth_date:
            age = relativedelta.relativedelta(datetime.datetime.now().date(), birth_date)

            if age.years < 18:
                raise forms.ValidationError(
                    u'Debes ser mayor de edad para poder participar.'
                )
        return birth_date

    def clean(self):
        birth_date = self.cleaned_data.get('birth_date')
        document = self.cleaned_data.get('document')

        if document and birth_date:
            person = Person.objects.filter(document=document).filter(birth_date=birth_date)
            if not person.exists():
                person = Person.objects.filter(document=document)
                if person.exists():
                    raise forms.ValidationError(
                        u'¡La fecha de nacimiento no coincide con el DNI ingresado!'
                    )

class PersonForm(forms.Form):

    document = forms.CharField(
        max_length=8,
        strip=True,
        validators=[dni_validator],
        required=True
    )

    birth_date = forms.DateField(
        input_formats=['%Y-%m-%d'],
        required=True,
        localize=False
    )

    name = forms.CharField(
        max_length=30,
        validators=[alphanumeric_validator],
        strip=True,
        required=True,
    )

    last_name = forms.CharField(
        max_length=30,
        validators=[alphanumeric_validator],
        strip=True,
        required=True,
    )

    email = forms.EmailField(required=True)

    gender = forms.CharField(
        max_length=1,
        label=u'Género',
        required=True
    )

    phone = forms.CharField(
        label=u'Celular',
        required=False,
        validators=[phone_validator]
    )

    country = forms.CharField(
        max_length=50,
        label=u'País',
        required=True
    )

    state = forms.CharField(
        max_length=50,
        label=u'Departamento',
        required=True
    )

    city = forms.CharField(
        max_length=50,
        label=u'Provincia',
        required=True
    )

    optin = forms.BooleanField(
        label=u'Recibir Boletines',
        required=False
    )

    terms = forms.BooleanField(
        label=u'Términos y condiciones',
        required=True
    )


'''
Created on 09-Dec-2015

@author: krishna
'''

from SinglyLinkedList import Node

class Stack(object):
    '''
    Last in first out
    '''

    def __init__(self, top=Node()):
        '''
        Constructor
        '''
        self.data_list = []
        self.top = top
        if top != None:
            self.data_list.append(top.data)

    def pop(self):
        '''
        deletes top and returns it
        '''

        if self.top != None:
            self.data_list.remove(self.top.data)
            top_value = self.top.data
            self.top = self.top.next
            if self.top != None:
                self.top.prev = None
            return top_value
        return None

    def push(self, data):
        '''
        creates a node for this data and add it to the top of the stack
        '''

        self.data_list.append(data)
        new_top = Node(data)
        new_top.next = self.top
        if self.top != None:
            self.top.prev = new_top
        self.top = new_top

    def peek(self):
        '''
        returns the data stored in top node of the stack
        '''

        if self.top != None:
            return self.top.data
        return None


#!/usr/bin/env python
'''
Created on Dec 20, 2015

@author: ppremkum
'''
#importing required modules into this file
from AutomationController import JiraTestController
from PresentationController import TestReportViewer, GenerateDropDownHtml, CompareResults, PlotGraph, PurgeResults
import argparse

#Help Function, which describes about the usage.
def help_func():
    print("===================================================================")
    print ("%s <option> <args>")
    print ("<option takes ExecuteTests/QueryResults/GenerateReport as an argument>")
    print ("<args are specific to the option selected>")
    print ("<ExecuteTests> -p 'projectName' -s 'scope' -r 'range'")
    print ("<QueryResults> -p 'projectName' -s 'scope' -sd 'startDate' -ed 'endDate'")
    print ("<CompareResults> -p 'projectName' -s 'scope' -sd 'startDate' -ed 'endDate'")
    print ("<PlotGraph> -p 'projectName' -s 'scope' -sd 'startDate' -ed 'endDate'")
    print ("<GenerateReport> -f 'csvFile'")
    print ("<PurgeResults> -p 'projectName' -s 'scope' -sd 'startDate' -ed 'endDate'")
    print("===================================================================")

'''This function parses and return arguments passed in'''
# Assign description to the help doc
parser = argparse.ArgumentParser(description='Script retrieves and executes the jira testcases or queries for test results or generates test reports')

# Add arguments
parser.add_argument('-o', '--option', type=str, help=help_func(), required=True)
parser.add_argument('-a', '--args', help='Arguments corresponding to the option selected', required=True, type=str)
arguments = parser.parse_args()
# Assign args to variables
option = arguments.option
args = arguments.args

print ("Arguments Passed are:",args)
try:
    if option == "ExecuteTests":
        # This will execute the tests and updates the results based on arguments.
        JiraTestController.main(args)
    elif option == "QueryResults":
        # This will fetch the results based on arguments and creates CSV file with the results.
        TestReportViewer.main(args)
    elif option == "GenerateReport":
        #Generates html report from a given search criteria.
        GenerateDropDownHtml.main(args)
    elif option == "CompareResults":
        #Compares the results between runs based on search criteria.
        CompareResults.main(args)
    elif option == "PlotGraph":
        #Generates graph from the results based on search criteria.
        PlotGraph.main(args)
    elif option == "PurgeResults":
        #Purges(Deletes permanently) the previous results based on search criteria(startDate and endDate).
        PurgeResults.main(args)
    else:
        print ("Invalid option mentioned")
        help_func()
except Exception as e:
    import traceback
    import sys
    print("Error occured while running the command:",option)
    print("Exception occured is:")
    traceback.print_exc()
    sys.exit(1)


#!/usr/bin/env python310

import json
import itertools

SKILL = "Mining"

materials = ["Rune Essence", "Copper", "Tin", "Iron", "Coal", "Silver", "Gold", "Mithril", "Adamantite", "Runite", "Dragonite"]

mastery_item = [
    "Mastery Level",
    SKILL,
    "",
    "CURRENT_ITEM",
    "99",
    [["Start Skill", SKILL, "NEXT_ITEM", "", ""]],
]

def itemize(*args):
    if len(args) == 3:
        return [" ".join((x, y, z)) for (x, y, z) in itertools.product(*args)]
    return [" ".join((x, y)) for (x, y) in itertools.product(*args)]

def generate_list(itemlist):
    mastery_list = []
    # Iterate through each pair
    for grouping in itertools.pairwise(itemlist):
        mastery_list.append(
            [
                "Mastery Level",
                SKILL,
                "",
                grouping[0],
                "99",
                [["Start Skill", SKILL, grouping[1], "", ""]],
            ]
        )
    return mastery_list

mastery_list = []
itemlist = []
itemlist.extend(["Rune Essence"])
itemlist.extend([x + " Ore" for x in materials if "Essence" not in x])

# Manually add the starting point
mastery_list.append(
    ["Idle", "", "", "", "", [["Start Skill", SKILL, itemlist[0], "", ""]]]
)

# Generate the rest of the lists
mastery_list.extend(generate_list(itemlist))

# Manually add the final agility
mastery_list.append(
    [
        "Mastery Level",
        SKILL,
        "",
        itemlist[-1],
        "99",
        [["Start Skill", "Agility", "", "", ""]],
    ]
)

with open(f"{SKILL.lower()}_mastery.txt", "w") as f:
    json.dump(mastery_list, f, sort_keys=False, indent=2)


# -*- coding: utf-8 -*-
# Author:jiang
# 2020/10/27 14:35
downloadnum=9 # 设置 downloadnum=False全量下载
storynums=30 #下载的故事个数 storynum=Fasle 全量下载
indexnum=2
from util.log import logger as logging
from threading import Thread,Lock
import time
# from mysql.storyMysql import getStoryNum, getDownLoadUrl, getStoryTitle,getAllStoryText,getStoryText
from util.getStoryContentUrl import getStoryContentUrl
from util.downLoadStory import downLoadStory
from util.storyWriteTxt import storyWriteTxt
# from mysql.allStoryUrlMysql import getSrotyUrl
from mysql.mySQL import MySQL
from util.getStoryIndex import get_story_urlsnew
db=MySQL()
def main():
    storynos=db.getDownLoadSrotyNo(storynums)
    if len(storynos)==False:
        storyUrls=db.getStoryIndex(indexnum)
        logging.info(storyUrls)
        for i in storyUrls:
            get_story_urlsnew(i)
        # threads=[]
        # starttime=time.time()
        # for i in storyUrls:
        #     t=Thread(target=get_story_urlsnew,args=[i])
        #     t.start()
        #     threads.append(t)
        # for i in threads:
        #     t.join()
        # endtime=time.time()
        # print('Cost {} seconds'.format(endtime-starttime))

    for storyno in storynos:
        newdownLoadUrl=[]
        storytitle=db.getStoryTitle(storyno)
        downloadUrl=db.getStoryDownLoadUrl(storyno)#获取需要下载小说的链接地址
        alreadyDownloadUrl=db.getAreadyStoryDownLoadUrl(storyno) #获取已下载小说的链接地址
        #i:http://m.xsqishu.com/book/54/82868.html
        if len(downloadUrl)==0:#如果该小说没有存入链接地址，重新获取
            msg="没有- -<"+storytitle+">- -的下载地址,重新获取"
            logging.info(msg)
            data=db.getSrotyDownUrl(storyno) #downloadnum需要下载的个数
            #data数据类型  #i[0] storyno,i[1]下载地址，i[2]标题
            urls=getStoryContentUrl(data[0],data[1])
            if len(urls)==0:
                msg="小说- - -<"+storytitle+">- - -暂未提供下载"
                logging.info(msg)
            else:
                newdownLoadUrl=urls
        elif len(downloadUrl)==len(alreadyDownloadUrl):
            msg="小说- - -"+storytitle+"- - -未更新"
            logging.info(msg)
        else:
            newdownLoadUrl=(set(downloadUrl).difference(set(alreadyDownloadUrl)))
        logging.info(newdownLoadUrl)
        downLoadStory(storyno,newdownLoadUrl)
        # for storyno,urls in urls_dict.items():
        # #     if downloadnum:
        # #         url = urls[0:downloadnum]
        # #     else:
        # #         url = urls
        # #     logging.info(url)
        #     #url=['http://m.xsqishu.com/book/100/82862/1.html', 'http://m.xsqishu.com/book/100/82862/2.html']
        #     storytitle=db.getStoryTitle(storyno)
        #     count_num = db.getStorySumChapter_Num(storyno) #获取该小说所有章节之和
        #     logging.info("len(url)")
        #     logging.info(len(url))
        #     logging.info("count_num")
        #     logging.info(count_num)
        #     if len(url)==0:
        #         msg="小说- - -"+storytitle+"- - -暂未提供下载"
        #         logging.info(msg)
        #     else:
        #         if count_num == len(url):
        #             msg="小说- - -"+storytitle+"- - -未更新"
        #             logging.info(msg)
        #         if count_num < len(url):
        #             logging.info("------------")
        #             logging.info(url)
        #             downLoadUrl = db.getDownLoadUrl(url)
        #             downLoadStory(storyno,downLoadUrl)
        #             storyWriteTxt(storyno)
        #         # dict = getAllStoryText()  # 获取全量小说
        #         # if dict:
        #         #     storyWriteTxt(dict,storyno,flag=0)
        #         # dict = getStoryText(downLoadUrl)  # 获取增量小说
        #         # if dict:
        #         #     storyWriteTxt(dict,storyno,flag=1)
if __name__ == '__main__':
    main()

    ###爬取过程中中断后写入txt出现问题


from datetime import datetime, timedelta
import os
from airflow import DAG
from airflow.operators.postgres_operator import PostgresOperator
from airflow.operators.dummy_operator import DummyOperator
from helpers.sql_queries import SqlQueries

default_args = {
    'owner': 'udacity',
    'start_date': datetime(2018, 11, 12, 0, 0, 0, 0),
    'end_date': datetime(2018, 11, 15, 0, 0, 0, 0),
    'depends_on_past': False,
    'email': ['nicolas.zabel@evhr.net'],
    'email_on_failure': False,
    'email_on_retry': False,
    'retries': 0,
    'retry_delay': timedelta(minutes=5)
}

dag = DAG('ddl_songs_and_events',
          default_args=default_args,
          description='Create tables in Redshift with Airflow',
          max_active_runs = 1
        )

start_operator = DummyOperator(task_id='Begin_execution',  dag=dag)

create_staging_songs = PostgresOperator(
    task_id = "create_staging_songs",
    postgres_conn_id = "redshift",
    dag = dag,
    sql = SqlQueries.create_queries['staging_songs']
)

create_staging_events = PostgresOperator(
    task_id = "create_staging_events",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['staging_events']
)

create_songplays = PostgresOperator(
    task_id = "create_songplays",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['songplays']
)

create_users = PostgresOperator(
    task_id = "create_users",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['users']
)

create_artists = PostgresOperator(
    task_id = "create_artists",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['artists']
)

create_songs = PostgresOperator(
    task_id = "create_songs",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['songs']
)

create_time = PostgresOperator(
    task_id = "create_time",
    postgres_conn_id = "redshift",
    dag = dag,
    sql= SqlQueries.create_queries['time']
)

end_operator = DummyOperator(task_id='Stop_execution',  dag=dag)

start_operator >> [create_staging_events, create_staging_songs, create_users, create_artists, create_songs, create_time, create_songplays] >> end_operator