from FRGCTemplate import *
from LFWTemplate import *
from BosphorusTemplate import *
from baseClasses.BiometricProcessing import *
from scipy.interpolate import interp2d
from helper.functions import fitPlane

class AngularFeatureExtraction(BiometricProcessing):

    def __init__(self, database,generateImages=True):
        self.databases = database
        self.methodName = 'Angular'
        self.generateImagesTrainig = generateImages
        self.sigmoid_table = {}
        super().__init__()

    def generateCode(self, image, center):
        idxs = [
            (center[0] - 1, center[1] - 1),
            (center[0] - 1, center[1]),
            (center[0] - 1, center[1] + 1),
            (center[0], center[1] + 1),
            (center[0] + 1, center[1] + 1),
            (center[0] + 1, center[1]),
            (center[0] + 1, center[1] - 1),
            (center[0], center[1] - 1)
        ]
        points = []
        for i in idxs:
            points.append([i[0], i[1], image[i[0]][i[1]]])

        return round(self.getAnglePlaneAxis(np.array(points + [[center[0],center[1],image[center[0]][center[1]]]])))

    def generateImagePoints(self, image, centerIndex):
        pointsImage = []
        for x in range(image.shape[0]):
            for y in range(image.shape[1]):
                pointsImage.append([y-centerIndex[1],(x*-1)+centerIndex[0],image[x,y]])
        return np.array(pointsImage)

    def getByPosition(self,x,y,image):
        for i in image:
            if i[0] == x and i[1] == y:
                return i

        else:
            return None

    def get_pixel2d(self,image,rows,cols,r,c,cval):
        if (r<0) or (r>=rows) or (c<0) or (c >= cols):
            return cval
        else:
            return image[r][c]

    def getAnglePlaneAxis(self,x):
        if type(x) is not np.ndarray:
            x = np.array(x)

        c, z = fitPlane(x)
        normals = []
        for i in range(len(x) - 2):
            v1 = x[-1] - np.array(x[i,:2].tolist() + [z[i]])
            v2 = x[-1] - np.array(x[i+1,:2].tolist() + [z[i+1]])
            normals.append(np.cross(v1,v2))

        finalNormal = np.mean(np.array(normals),axis=0)
        finalNormal = finalNormal / np.linalg.norm(finalNormal)
        cosAngleZ = np.dot(finalNormal, np.array([0, 0, 1]))
        return cosAngleZ

    def generateCodePR(self, image, center, xPositions, yPositions):
        image = np.ascontiguousarray(image, dtype=np.double)
        xPositions = xPositions + center[0]
        yPositions = yPositions + center[1]
        idxs = np.array([x for x in zip(xPositions,yPositions)])
        idxs = idxs[-3:].tolist() + idxs[0:-3].tolist()
        points = []
        for i in idxs:
            if (not i[0].is_integer() or not i[1].is_integer()):
                xidxs = [math.floor(i[0]), math.ceil(i[0])]
                yidxs = [math.floor(i[1]), math.ceil(i[1])]

                imageDataBil = np.array([
                    (xidxs[0], yidxs[0], image[xidxs[0]][yidxs[0]]),
                    (xidxs[0], yidxs[1], image[xidxs[0]][yidxs[1]]),
                    (xidxs[1], yidxs[0], image[xidxs[1]][yidxs[0]]),
                    (xidxs[1], yidxs[1], image[xidxs[1]][yidxs[1]])
                ])
                nFunc = interp2d(imageDataBil[:,0],imageDataBil[:,1],imageDataBil[:,2])
                nv = nFunc(i[0], i[1])[0]
                points.append([i[0], i[1], nv])
            else:
                points.append([i[0], i[1], image[int(i[0])][int(i[1])]])

        angle = self.getAnglePlaneAxis(np.array(points + [[center[0],center[1],image[center[0]][center[1]]]]))
        subraction = np.histogram(angle, bins=256, range=[-1, 1])[0]
        return np.argwhere(subraction == 1)[0][0]

    def generateImageDescriptor(self, image, p=8, r=1, typeLBP='original', template=None):
        if typeLBP == 'pr':
            xPositions = np.round(- r * np.sin(2 * np.pi * np.arange(p, dtype=np.double) / p),5)
            yPositions = np.round(r * np.cos(2 * np.pi * np.arange(p, dtype=np.double) / p),5)

        for i in range(r, image.shape[0] - r):
            for j in range(r, image.shape[1] - r):
                resultCode = None
                if typeLBP == 'original':
                    resultCode = self.generateCode(image[i - 1:i + 2, j - 1:j + 2], np.array([1, 1]))
                elif typeLBP == 'pr':
                    resultCode = self.generateCodePR(image[i - r:i + (r + 1), j - r:j + (r + 1)], np.array([r, r]), xPositions,yPositions)

                if not template is None:
                    template.layersChar[i][j] = resultCode

    def setupTemplate(self, template):
        return template

    def cleanupTemplate(self, template):
        if (type(template) is not FRGCTemplate) and (type(template) is not BosphorusTemplate) and (len(template.image) > 0):
            template.layersChar = np.zeros((len(template.image), len(template.image[0])))
            template.image = im.fromarray(np.array(template.image, dtype=np.uint8))
            template.image = template.image.rotate(-180)
            template.save(True)
        return template

    def featureExtraction(self, points=None, radius=None, paralelCalling=False,forceImage=True,procs=10):
        self.quantityItensProcessing = sum([len(d.templates) for d in self.databases])
        self.feitos = 0
        if paralelCalling:
            poolCalling = Pool(processes=procs)
            for database in self.databases:
                dataForParCal = [{'template': t, 'points': points, 'radius': radius, 'forceImage' : forceImage} for t in database.templates]
                responses = poolCalling.map(unwrap_self_f_feature, zip([self] * len(dataForParCal), dataForParCal))
        else:
            for database in self.databases:
                for template in database.templates:
                    dataForParCal = {'points': points, 'radius': radius, 'template': template, 'forceImage' : forceImage}
                    a, template.features = self.doFeatureExtraction(dataForParCal)

    def progessNumber(self):
        self.feitos += 1
        print("%d completed from %d" % (self.feitos,self.quantityItensProcessing))

    def localcall(self,parameters):
        template = parameters['template']
        if parameters['forceImage'] or not template.isFileExists(self.fullPathGallFile,'png'):
            print(template.rawRepr)
            points = parameters['points']
            radius = parameters['radius']
            imgCroped = np.asarray(template.image).astype(np.int64)
            if template.layersChar is None:
                template.layersChar = np.full((imgCroped.shape[0], imgCroped.shape[1]),255)

            if (not points is None) and (not radius is None):
                self.generateImageDescriptor(imgCroped, p=points, r=radius,typeLBP='pr',template=template)
            else:
                self.generateImageDescriptor(imgCroped,template=template)

            if self.generateImagesTrainig:
                template.saveImageTraining(False, self.fullPathGallFile)

            return None, None
        else:
            return None, None


#!/usr/bin/env python
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
# -*- coding: UTF-8 -*-

"""
Simple Bot to reply to Telegram messages.

First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.

Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

import logging
from decimal import Decimal
import json
import httpx
from telegram import Update, ForceReply, InlineKeyboardMarkup, InlineKeyboardButton, ParseMode
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from telegram.utils.helpers import escape_markdown
import time
from web3 import Web3

def loadConfig():
    with open("./config.json","r") as f:
        load_dict = json.load(f)
    return load_dict

config = loadConfig()
BOTAPIKEY =  config['bot_api_key']
CHANNEL = config['channel_id']
KEY = config['information_key']

def string_to_hash(string):
    return Web3.keccak(string)

# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)

content_send = {}

def getMessages():
    messages = []
    url = "https://www.maitanbang.com/api/news/index?key=" + KEY
    result = httpx.get(url, timeout = 10)
    result_json = json.loads(result.text)
    if result_json['code'] != 200:
        return messages
    datas = result_json['data']
    for data in datas:
        content = data['content']
        hash_byte = string_to_hash(content)
        if hash_byte in content_send.keys():
            messages.append(content)
            content_send[hash_byte] = int(time.time())
    # messages = ["【Optimism：以太坊合并时不会暂停网络，资产仅可提取到PoS链上】MarsBit消息，以太坊二层扩容网络 Optimism 在其社交平台表示，以太坊合并将不会对 Optimism 网络造成影响，不会暂停网络，存取款可照常进行。一旦合并触发，Optimism 的运营将完全转移到以太坊 PoS 链上，Optimism 上的资产也将只能提取到 PoS 链上。"]
    return messages

def main() -> None:
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    updater = Updater(token=BOTAPIKEY)

    # Get the dispatcher to register handlers
    dispatcher = updater.dispatcher

    # on non command i.e message - echo the message on Telegram
    # dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, auto_check_token))
    while True:
        try:
            messages = getMessages()
            for message in messages:
                updater.bot.send_message(chat_id = CHANNEL, text = message, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
                time.sleep(2)
        except Exception as err:
            logger.error(err)
            continue

        now = int(time.time())
        for key, val in content_send.items():
            if now - val > 86400:
                content_send.pop(key)

        time.sleep(60)

    # Start the Bot
    updater.start_polling(10)

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()

if __name__ == '__main__':
    main()


import discord
import json
import pymongo
import sys

sys.path.insert(1, "/bot/")

from settings import MONGO_CONNECT
from discord.ext import commands
from requests_futures.sessions import FuturesSession

INSUFF_ARGS = "Insufficient arguments!"
NO_UNDERSTAND = "I do not understand what you are asking me to do."

mongo_client = pymongo.MongoClient(MONGO_CONNECT)
db = mongo_client.Auric_Oasis

def setup(bot):
    """
        Add this cog to the given bot
    """

    bot.add_cog(DailyAlertCog(bot))

def tupToSentence(tup):
    """
        Takes a tuple, converts it to a string
    """

    words = len(tup)
    sentence = ""

    for i in range(words):

        sentence += tup[i]

        if (i < words):
            sentence += ' '

    return sentence

def get_id(daily_achieves, daily):
    """
        Returns the key/index corresponding to the given
        daily achieve
    """

    for i_d, val in daily_achieves.items():
        if daily == val:
            return i_d

def obtain_description(achieve_id):

    session = FuturesSession()

    request = session.get("https://api.guildwars2.com/v2/achievements/" + str(achieve_id))
    request_result = request.result()

    result = json.loads(request_result.text)

    return result['requirement']

class DailyAlertCog(commands.Cog):
    """
        Currently a WiP
    """

    @commands.command(name="daily-alert", help=" - Series of commands relating to the addition or removal of dailies to be alerted to!", pass_context = True)
    async def daily(self, ctx, *args):
        """
            Collection of commands specific for 'daily-alert'
        """

        creator = "Goose"
        exalted = discord.utils.get(ctx.guild.roles, name="Exalted")
        ascended = discord.utils.get(ctx.guild.roles, name="Ascended")

        if ((exalted in ctx.author.roles) or (ascended in ctx.author.roles) or (ctx.author.name == creator)):

            if (args):

                # Obtaining daily achieves info
                dailyAchieves_doc = db.daily_achievements.find_one({"Title" : "List of Daily Achievements"})
                daily_list = dailyAchieves_doc["achievements"]

                # Obtaining watchlist info
                watchlist_doc = db.daily_achievements.find_one({"Title" : "Daily Watchlist"})
                watchlist = watchlist_doc["watchlist"]

                # Obtaining info on roles and notify
                roles_doc = db.roles.find_one({"Title" : "Auric Oasis Roles"})
                roles_list = roles_doc["roles"]
                notify_list = roles_doc["notify_list"]

                # Clears the watchlist
                if (args[0] == "clear-list"):

                    # Checks to see if the watchlist is empty or not
                    if (not watchlist):
                        await ctx.send("There is no Watchlist to clear!")
                        return

                    watchlist.clear()

                    db.daily_achievements.update_one({"Title" : "Daily Watchlist"}, {"$set": {"watchlist" : watchlist}})

                    await ctx.send("Daily Watchlist has been cleared!")

                # If it is not present, inserts the daily to the watchlist
                elif (args[0] == "add-daily"):

                    if (len(args) < 2):
                        await ctx.send(INSUFF_ARGS)
                        return

                    dailyToAdd = "Daily " + tupToSentence(args[1:])
                    dailyToAdd = dailyToAdd.strip()

                    # Check to see if the achieve is valid
                    if (dailyToAdd not in daily_list.values()):
                        await ctx.send("Cannot recognize this achievement!")
                        return

                    # Makes sure no repeat is being added to the watchlist
                    if (dailyToAdd not in watchlist):

                        watchlist.append(dailyToAdd)
                        db.daily_achievements.update_one({"Title" : "Daily Watchlist"}, {"$set": {"watchlist": watchlist}})

                        await ctx.send("%s has been added to the Watchlist!" % (dailyToAdd))
                        return
                    else:
                        await ctx.send("Daily is already being monitored!")
                        return

                elif (args[0] == "remove-daily"):

                    if (len(args) < 2):
                        await ctx.send(INSUFF_ARGS)
                        return

                    dailyToRemove = "Daily " + tupToSentence(args[1:])
                    dailyToRemove = dailyToRemove.strip()

                    # Check to see if the achieve is valid
                    if (dailyToRemove not in daily_list.values()):
                        await ctx.send("Cannot recognize this achievement!")

                    if (watchlist):

                        # Makes sure the achieve exists in the watchlist
                        if (dailyToRemove in watchlist):

                            watchlist.remove(dailyToRemove)
                            db.daily_achievements.update_one({"Title" : "Daily Watchlist"}, {"$set": {"watchlist": watchlist}})

                            await ctx.send("%s has been removed from the Watchlist!" % (dailyToRemove))
                            return
                        else:
                            await ctx.send("This daily is not in the watchlist!")
                            return

                    else:
                        await ctx.send("Nothing to remove from the watchlist!")
                        return

                # Displays the watchlist
                elif (args[0] == "display-watchlist"):

                    response = "Here is the list of dailies I am currently keeping track of..."
                    embed_msg = discord.Embed(color=0xffee05)

                    for entry in watchlist:

                        daily_id = get_id(daily_list, entry)

                        embed_msg.add_field(
                            name=entry,
                            value=obtain_description(daily_id),
                            inline=False
                        )

                    await ctx.send(response, embed=embed_msg)
                    return

                # Adds a role to the notify list
                elif (args[0] == "add-notify"):

                    if (len(args) < 2):
                        await ctx.send(INSUFF_ARGS)
                        return

                    roleToAdd = tupToSentence(args[1:])
                    roleToAdd = roleToAdd.strip()

                    # Makes sure role is valid within the guild, and not in the notify list
                    if ((roleToAdd in roles_list.values()) and (roleToAdd not in notify_list)):

                        notify_list.append(roleToAdd)
                        db.roles.update_one({"Title" : "Auric Oasis Roles"}, {"$set": {"notify_list" : notify_list}})

                        await ctx.send("%s has been added to the notify list!" % (roleToAdd))
                        return

                    else:
                        await ctx.send("Role either does not exist in the guild, or has already been added!")
                        return

                elif (args[0] == "remove-notify"):

                    if (len(args) < 2):
                        await ctx.send(INSUFF_ARGS)
                        return

                    if (notify_list):

                        roleToRemove = tupToSentence(args[1:])
                        roleToRemove = roleToRemove.strip()

                        # Makes sure role is valid within the guild, and in the notify list
                        if ((roleToRemove in roles_list.values()) and (roleToRemove in notify_list)):

                            notify_list.remove(roleToRemove)
                            db.roles.update_one({"Title" : "Auric Oasis Roles"}, {"$set": {"notify_list" : notify_list}})

                            await ctx.send("%s has been removed from the notify list!" % (roleToRemove))
                            return

                        else:
                            await ctx.send("Role either does not exist in the guild, or is not in the notify list!")
                            return

                    else:
                        await ctx.send("Nothing to remove from the notify list!")
                        return

                elif (args[0] == "display-notify"):

                    response = "Here is the list of roles I am tasked to notify..."
                    embed_msg = discord.Embed(color=0xffee05)

                    for role in notify_list:

                        role_name = get_id(roles_list, role)

                        embed_msg.add_field(
                            name=role_name,
                            value='\u200b',
                            inline=False
                        )

                    await ctx.send(response, embed=embed_msg)
                    return

                else:
                    await ctx.send("I do not understand what you are asking me to do!")
                    return

            else:
                await ctx.send(INSUFF_ARGS)
                return

        else:
            await ctx.send("My apologies, but you are not authorized to issue this command.")


import gc
import numpy as np
import pandas as pd

from preprocessing.config_preproc import PreprocConfig as CFG

cat_features = CFG.cat_features
use_cols = ['customer_ID', 'P_2'] + cat_features
print('Reading and concatenating data to calc last cat means')

df_train = pd.read_parquet(CFG.train_feature_file, columns=use_cols)
df_train['dset'] = 'train'
df_train = df_train.groupby('customer_ID').tail(1)

df_test = pd.read_parquet(CFG.test_feature_file, columns=use_cols)
df_test['dset'] = 'test'
df_test = df_test.groupby('customer_ID').tail(1)

# concatenation to extract additional P2 information from test
df_comb = pd.concat([df_train, df_test]).reset_index(drop=True)
print(f'Combined shape: {df_comb.shape}')

del df_train, df_test
gc.collect()

cat_P2_means = {}

for cat in cat_features:
    cat_P2_means[cat] = df_comb.groupby(cat)['P_2'].mean()

del df_comb
gc.collect()

use_cols = ['customer_ID']
for cat in cat_features:
    use_cols += [f'{cat}_{i}' for i in range(0, CFG.max_n_statement)]

print('Mapping last cat means to full flattened cats')
df_train = pd.read_parquet(CFG.output_dir + 'train_flattened_full.parquet', columns=use_cols)
df_test = pd.read_parquet(CFG.output_dir + 'test_flattened_full.parquet', columns=use_cols)

for cat in cat_features:
    for i in range(0, CFG.max_n_statement):
        df_train[f'{cat}_{i}_P2_mean'] = df_train[f'{cat}_{i}'].map(cat_P2_means[cat])
        df_train = df_train.drop(columns=[f'{cat}_{i}'])
        df_test[f'{cat}_{i}_P2_mean'] = df_test[f'{cat}_{i}'].map(cat_P2_means[cat])
        df_test = df_test.drop(columns=[f'{cat}_{i}'])

df_train.to_parquet(CFG.output_dir + 'train_full_flat_cat_p2_encoded_features.parquet')
df_test.to_parquet(CFG.output_dir + 'test_full_flat_cat_p2_encoded_features.parquet')


import cv2
import numpy as np
import sys
from time import time

def rectcenter(rect):
    (x,y,w,h) = rect
    return (x+w/2,y+h/2)

def distance(c1, c2):
    return np.hypot(c1[0]-c2[0],c1[1]-c2[1])

cv2.namedWindow("preview")
cv2.namedWindow("preview2")
cv2.namedWindow("previewblob")
vc = cv2.VideoCapture(int(sys.argv[1]))
vc2 = cv2.VideoCapture(int(sys.argv[2]))
vc.set(3,int(sys.argv[3]))
vc.set(4,int(sys.argv[4]))
rw = vc.get(3)
rh = vc.get(4)
# print(vc.get(3))
# print(vc.get(4))

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

if vc2.isOpened(): # try to get the first frame
    rval2, frame2 = vc2.read()
else:
    rval2 = False

# Setup SimpleBlobDetector parameters.
params = cv2.SimpleBlobDetector_Params()

# Change thresholds
params.minThreshold = 5;
params.maxThreshold = 50;

# Filter by Area.
params.filterByArea = True
params.minArea = 1
params.maxArea = 3

# Filter by Circularity
params.filterByCircularity = True
params.minCircularity = 0.7

# Filter by Convexity
params.filterByConvexity = True
params.minConvexity = 0.88

# Filter by Inertia
params.filterByInertia = True
params.minInertiaRatio = 0.01
detector = cv2.SimpleBlobDetector_create(params)
reye_cascade = cv2.CascadeClassifier('haarcascade_righteye_2splits.xml')
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
face = None
flost = 0

kernel = np.ones((5,5),np.uint8)

ptime = time()
nf = 0
thresh1 = 70
thresh2 = 135
record = False
while rval and rval2:
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray4 = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray4, 1.3, 5)
    for f in faces:
        if face is not None:
            # print("Face: " + str(distance(f,face)))
            if not (1 < distance(f,face) < 20):
                continue
        face = f
        flost = 0
    if flost < 5 and face is not None:
        (x,y,w,h) = face
        cv2.rectangle(frame2,(x,y),(x+w,y+h),(255,0,0),2)
    else:
        face = None

    gray3 = 255-gray

    gray2 = thresh1-gray
    # gray2 = cv2.equalizeHist(gray2)
    gray2 = cv2.erode(gray2,kernel)
    gray2 = cv2.GaussianBlur(gray2, (5,5), 6, 6)
    # gray2 = cv2.dilate(gray2,kernel)
    # blah,gray2 = cv2.threshold(gray2,thresh2,255,cv2.THRESH_BINARY)
    # gray2 = cv2.GaussianBlur(gray2, (5,5), 3, 3)

    eyes = reye_cascade.detectMultiScale(gray)
    # for e in eyes:
    #     (ex,ey,ew,eh) = e
    #     cv2.rectangle(frame,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
    #     roi_gray = gray2[ey:ey+eh, ex:ex+ew]
    #     roi_color = frame[ey:ey+eh, ex:ex+ew]
    roi_gray = gray2
    rows = roi_gray.shape[0]
    circles = cv2.HoughCircles(roi_gray, cv2.HOUGH_GRADIENT, 1, rows / 4,
                           param1=200, param2=10,
                           minRadius=10, maxRadius=20)
    center = None
    if circles is not None:
        circles = np.uint16(np.around(circles))
        for i in circles[0, :]:
            center = (i[0], i[1])
            # print(distance(center,rectcenter(e)))
            if distance(center,rectcenter((0,rh/3,rw,rh))) > 200:
                continue
            # circle center
            cv2.circle(roi_gray, center, 1, (0, 100, 100), 3)
            # circle outline
            radius = i[2]
            cv2.circle(roi_gray, center, radius, (100, 0, 100), 3)

    blobframe = None
    keypoints = detector.detect(gray3)

    blobframe = cv2.drawKeypoints(gray3, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

    cv2.imshow("preview", gray2)
    cv2.imshow("preview2", frame2)
    if blobframe is not None:
        cv2.imshow("previewblob",blobframe)

    if record and face is not None and center is not None and blobframe is not None:
        (x,y,w,h) = face
        (px,py) = center
        if len(keypoints) > 4:
            keypoints = keypoints[0:4]
        else:
            keypoints = keypoints+(4-len(keypoints))*[cv2.KeyPoint(2,-1,-1)]
        print(','.join([str(x),str(y),str(px),str(py)]+[str(x.pt[0]) for x in keypoints]+[str(x.pt[1]) for x in keypoints]))

    nf = nf + 1
    if time() - ptime > 5:
        # print(str(nf/(time()-ptime)))
        ptime = time()
        nf = 0
    rval, frame = vc.read()
    rval2, frame2 = vc2.read()
    key = cv2.waitKey(20)
    if key != -1:
    #     print(key)
        print("1: " + str(thresh1))
        print("2: " + str(thresh2))
    if key == 27: # exit on ESC
        break
    elif key == 32:
        # cv2.imwrite('testimage.png',frame);
        record = not record
    elif key == 104:
        thresh1 = thresh1 + 5
    elif key == 106:
        thresh1 = thresh1 - 5
    elif key == 107:
        thresh2 = thresh2 + 5
    elif key == 108:
        thresh2 = thresh2 - 5

cv2.destroyWindow("preview")
vc.release()


import random

def captcha_challenge():

    # import random
    # str_var = list("shuffle_this_string")
    # random.shuffle(str_var)
    # print ''.join(str_var)

    # Characters to be included
    chrs = "Klc2HSweQiRDodg5sWxz90GPyf3EkVMYaqJhmUuZF1BCntLNXIvjTbp67r4A8O"

    chrs_vars = list(chrs)
    random.shuffle(chrs_vars)
    chrs = ''.join(chrs_vars)

    n = random.randint(4, 7)
    # Generate n characters from above set and
    # add these characters to captcha.
    captcha = ""
    while (n):
        captcha += chrs[random.randint(1, 100) % 62]
        n -= 1
    return captcha, captcha

# def captcha_challenge():
#     challenge = u''
#     response = u''
#     for i in range(4):
#         digit = random.randint(0,9)
#         challenge += str(digit)
#         response += str((digit + 1) % 10)
#     return challenge, response

# def captcha_challenge():
#     n = random.randint(4, 7)
#     captcha =''.join(random.SystemRandom().choice([chr(i) for i in range(97, 123)] + [str(i) for i in range(n)]) for _ in range(n))
#     return captcha, captcha


import random
from pygame import mixer
import pygame
pygame.init()
pygame.display.set_caption('A játék elkezdődött')
screen = pygame.display.set_mode((1000, 1000))
snake_body = pygame.image.load("../images/body.png")
snake_body_x = pygame.image.load("../images/body_x.png")
snake_body_ne = pygame.image.load("../images/body_leftup.png")
snake_body_nw = pygame.image.load("../images/body_rightup.png")
snake_body_se = pygame.image.load("../images/body_leftdown.png")
snake_body_sw = pygame.image.load("../images/body_rightdown.png")
sneak_head_e = pygame.image.load("../images/head_right.png")
sneak_head_n = pygame.image.load("../images/head_up.png")
sneak_head_w = pygame.image.load("../images/head_left.png")
sneak_head_s = pygame.image.load("../images/head_down.png")
apple = pygame.image.load("../images/apple.png")
pineapple = pygame.image.load("../images/pineapple.png")
pear = pygame.image.load("../images/pear.png")
fruits = [apple, pineapple, pear]

click = mixer.Sound('../audio/click.wav')
pick_up = mixer.Sound('../audio/pick up.wav')
victory = mixer.Sound('../audio/win.wav')
sound_list = (click, pick_up, victory)

class Food:
    def __init__(self):
        self.x = random.randint(1, 19)
        self.y = random.randint(1, 19)
        self.img = random.choice(fruits)

    def draw(self):
        for num in range(snake.length):
            if snake.prew_pos_x[-(num+1)] == self.x and snake.prew_pos_y[-(num+1)] == self.y:
                self.x = random.randint(1, 19)
                self.y = random.randint(1, 19)
        screen.blit(self.img, (self.x*50, self.y*50))

class SnakeBody:
    def __init__(self, x, y, num, facing):
        self.x = x
        self.y = y
        self.num = num
        self.facing = facing

    def draw(self):
        if self.facing == "up" or self.facing == "down":
            screen.blit(snake_body, (round(self.x)*50, round(self.y)*50))
        elif self.facing == "left" or self.facing == "right":
            screen.blit(snake_body_x, (round(self.x)*50, round(self.y)*50))
        elif self.facing == "ne":
            screen.blit(snake_body_ne, (round(self.x) * 50, round(self.y) * 50))
        elif self.facing == "se":
            screen.blit(snake_body_se, (round(self.x) * 50, round(self.y) * 50))
        elif self.facing == "nw":
            screen.blit(snake_body_nw, (round(self.x) * 50, round(self.y) * 50))
        elif self.facing == "sw":
            screen.blit(snake_body_sw, (round(self.x) * 50, round(self.y) * 50))

class Snake:
    def __init__(self):
        self.prew_pos_x = []
        self.prew_pos_y = []
        self.prew_facing = []
        self.x = 10
        self.y = 10
        self.x_pos = round(self.x) * 50
        self.y_pos = round(self.y) * 50
        self.keys = {
            "up": pygame.K_w,
            "down": pygame.K_s,
            "left": pygame.K_a,
            "right": pygame.K_d,
        }
        self.pressed = pygame.key.get_pressed()
        self.facing = "left"
        self.speed = 5
        self.length = 0
        self.food = False

    def draw(self):
        self.death()
        self.control()
        self.move()
        self.eat()
        self.out()
        self.prew_pos_x.append(round(self.x))
        self.prew_pos_y.append(round(self.y))
        self.prew_facing.append(self.facing)
        if self.length == 0:
            if self.prew_facing[-1] == "left":
                screen.blit(sneak_head_w, (self.x_pos + 3, self.y_pos + 2))
            elif self.prew_facing[-1] == "up":
                screen.blit(sneak_head_n, (self.x_pos - 1, self.y_pos + 3))
            elif self.prew_facing[-1] == "right":
                screen.blit(sneak_head_e, (self.x_pos - 3, self.y_pos + 2))
            elif self.prew_facing[-1] == "down":
                screen.blit(sneak_head_s, (self.x_pos - 1, self.y_pos - 3))
        else:
            if self.prew_pos_x[-2] == self.prew_pos_x[-1] and self.prew_pos_y[-2] == self.prew_pos_y[-1]:
                self.prew_pos_x.pop()
                self.prew_pos_y.pop()
                self.prew_facing.pop()
            if self.prew_facing[-2] == "down" and self.prew_facing[-1] == "left" or self.prew_facing[-2] == "right" and self.prew_facing[-1] == "up":
                self.prew_facing[-2] = "ne"
            elif self.prew_facing[-2] == "down" and self.prew_facing[-1] == "right" or self.prew_facing[-2] == "left" and self.prew_facing[-1] == "up":
                self.prew_facing[-2] = "nw"
            elif self.prew_facing[-2] == "up" and self.prew_facing[-1] == "left" or self.prew_facing[-2] == "right" and self.prew_facing[-1] == "down":
                self.prew_facing[-2] = "se"
            elif self.prew_facing[-2] == "up" and self.prew_facing[-1] == "right" or self.prew_facing[-2] == "left" and self.prew_facing[-1] == "down":
                self.prew_facing[-2] = "sw"

            if self.prew_facing[-2] == "left":
                screen.blit(sneak_head_w, (self.x_pos + 3, self.y_pos + 2))
            elif self.prew_facing[-2] == "up":
                screen.blit(sneak_head_n, (self.x_pos - 1, self.y_pos + 3))
            elif self.prew_facing[-2] == "right":
                screen.blit(sneak_head_e, (self.x_pos - 3, self.y_pos + 2))
            elif self.prew_facing[-2] == "down":
                screen.blit(sneak_head_s, (self.x_pos - 1, self.y_pos - 3))
            else:
                if self.prew_facing[-1] == "left":
                    screen.blit(sneak_head_w, (self.x_pos + 3, self.y_pos + 2))
                elif self.prew_facing[-1] == "up":
                    screen.blit(sneak_head_n, (self.x_pos - 1, self.y_pos + 3))
                elif self.prew_facing[-1] == "right":
                    screen.blit(sneak_head_e, (self.x_pos - 3, self.y_pos + 2))
                elif self.prew_facing[-1] == "down":
                    screen.blit(sneak_head_s, (self.x_pos - 1, self.y_pos - 3))

            for num in range(self.length+1):
                SnakeBody(self.prew_pos_x[-(num+2)], self.prew_pos_y[-(num+2)], num+1, self.prew_facing[-(num+2)]).draw()

        if not self.food:
            self.food = Food()
        self.food.draw()

    def control(self):
        self.pressed = pygame.key.get_pressed()
        if self.pressed[self.keys["left"]] and self.facing != "right":
            self.facing = "left"
        if self.pressed[self.keys["right"]] and self.facing != "left":
            self.facing = "right"
        if self.pressed[self.keys["up"]] and self.facing != "down":
            self.facing = "up"
        if self.pressed[self.keys["down"]] and self.facing != "up":
            self.facing = "down"

    def move(self):
        if self.facing == "up":
            self.y -= self.speed / 100
        if self.facing == "down":
            self.y += self.speed / 100
        if self.facing == "left":
            self.x -= self.speed / 100
        if self.facing == "right":
            self.x += self.speed / 100
        self.x_pos = round(self.x) * 50
        self.y_pos = round(self.y) * 50

    def out(self):
        if round(self.x) > 19:
            self.x = 0
        elif round(self.x) < 0:
            self.x = 19
        elif round(self.y) > 19:
            self.y = 0
        elif round(self.y) < 0:
            self.y = 19

    def eat(self):
        if self.food:
            if round(self.x) == self.food.x and round(self.y) == self.food.y:
                self.food = False
                self.length += 1
                self.speed += 0.1
                pick_up.play()

    def death(self):
        for num in range(self.length):
            if round(self.x) == self.prew_pos_x[-(num+2)] and round(self.y) == self.prew_pos_y[-(num+2)]:
                exit()

def bg():
    rect_x = 0
    rect_y = 0
    even = False
    even_start = True
    for row in range(50):
        for col in range(50):
            if even:
                pygame.draw.rect(screen, (0, 245, 0), (rect_x, rect_y, 50, 50), 0)
                even = False
            else:
                pygame.draw.rect(screen, (0, 225, 0), (rect_x, rect_y, 50, 50), 0)
                even = True
            rect_y += 50
        rect_x += 50
        rect_y = 0
        if even_start:
            even = True
            even_start = False
        else:
            even = False
            even_start = True

snake = Snake()
running = True
while running:
    bg()
    snake.draw()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            exit()

    pygame.display.update()


from flask import Flask
from flask_restx import Api, Resource
from flask_cors import CORS
from aggregation_service import AggregationService

app = Flask(__name__, static_url_path='')

import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

aggregation_service = AggregationService()

cors = CORS(app)
app.config.from_object(__name__)
# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})

api = Api(app, version='1.0', title='Rest API',
          description='A simple Rest API', validate=True
          )

@api.route('/<string:context_id>')
class AggregationService(Resource):

    def get(self, context_id):
        try:
            process = aggregation_service.create_groups_by_context_id(context_id)
            return process, 200
        except KeyError:
            return {"message": "context_id not found"}, 404

if __name__ == '__main__':
    app.run(debug=True, port=5010)


import torch.nn as nn
import torchvision

class ResNetBackbone(nn.Module):
    def __init__(self, net, num_conv=4):
        """ResNet NN architecture with custom number of conv layers, to output
        only feature maps.

        Args:
            net (NN.Module): The resnet.
            num_conv (int, optional): Number of conv layers to use. Defaults to 4.
        """
        super(ResNetBackbone, self).__init__()

        self.stem = nn.Sequential(net.conv1, net.bn1, net.relu, net.maxpool)
        self.stage1 = net.layer1
        self.stage2 = net.layer2
        self.num_conv = num_conv
        if self.num_conv >= 3:
            self.stage3 = net.layer3
        if self.num_conv >= 4:
            self.stage4 = net.layer4

    def forward(self, imgs):
        """Forward pass with batch of images

        Args:
            imgs (torch.tensor): batch of images

        Returns:
            torch.tensor: output feature maps.
        """
        feats = self.stem(imgs)
        conv1 = self.stage1(feats)
        conv2 = self.stage2(conv1)

        conv3, conv4 = None, None
        if self.num_conv >= 3:
            conv3 = self.stage3(conv2)
        if self.num_conv >= 4:
            conv4 = self.stage4(conv3)

        convs = [conv for conv in [conv1, conv2, conv3, conv4] if conv is not None]
        return  convs

_FEAT_DIMS = {
    "resnet18": (64, 128, 256, 512),
    "resnet34": (64, 128, 256, 512),
    "resnet50": (256, 512, 1024, 2048),
    "resnet101": (256, 512, 1024, 2048),
    "resnet152": (256, 512, 1024, 2048),
}

def build_backbone(name, pretrained=True, num_conv=4):
    """Return ResNet backbone to get feature maps

    Args:
        name (str): Type of resnet, in "resnet18", "resnet34", "resnet50", "resnet101", "resnet152".
        pretrained (bool, optional): If weights should be ImageNet pretrained. Defaults to True.
        num_conv (int, optional): Number of conv layers. Defaults to 4.

    Raises:
        ValueError: If backbone is unrecognized.

    Returns:
        tuple: the backbone and feature dimensions.
    """
    resnets = ["resnet18", "resnet34", "resnet50", "resnet101", "resnet152"]
    if name in resnets and name in _FEAT_DIMS:
        cnn = getattr(torchvision.models, name)(pretrained=pretrained)
        backbone = ResNetBackbone(cnn, num_conv)
        feat_dims = _FEAT_DIMS[name][:num_conv]
        return backbone, feat_dims
    else:
        raise ValueError('Unrecognized backbone type "%s"' % name)


from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

# Create your models here.
from django.dispatch import receiver

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    credits = models.IntegerField(default=0)

    def __str__(self):
        return f"{self.user.username}"

# ensures that when a user is created, they are assigned a new Customer object
@receiver(post_save, sender=User)
def create_customer(sender, instance, created, **kwargs):
    if created:
        Customer.objects.create(user=instance)

# ensures whenever the User updates their info, the Customer instance is also saved.
@receiver(post_save, sender=User)
def save_user_customer(sender, instance, **kwargs):
    instance.customer.save()


import socket

def main():
    ports = [21,23,22]
    ips = "192.168.195."
    for octet in range(0,255):
        for port in ports:
            ip = ips + str(octet)
            #print("[*] Testing port %s at IP %s") % (port, ip)
            try:
                socket.setdefaulttimeout(1)
                s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                s.connect((ip,port))
                output = s.recv(1024)
                print("[+] The banner: %s for IP: %s at Port: %s") % (output,ip,port)
            except:
                print("[-] Failed to Connect to %s:%s") % (ip, port)
            finally:
                s.close()

if __name__ == "__main__":
    main()


class Node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

class Stack:
    def __init__(self):
        self.top = None

    def push(self, *value):
        for v in value:
            if self.top == None:
                self.top = Node(v)
            else:
                node = Node(v)
                node.next = self.top
                self.top = node

    def pop(self):
        node = self.top
        self.top = node.next
        return node.data

    def isEmpty(self):
        return self.top == None

    def toString(self):
        node = self.top
        string = ''
        while node != None:
            string += str(node.data)
            if node.next != None:
                string += ' -> '
            node = node.next

        return string


import time

def start_time():
    startTime = time.time_ns()
    return(startTime)

def end_time():
    endTime = time.time_ns()
    return(endTime)

def latency(s, e):
    latency = str(float(e - s)//1000000)
    return(latency)

def response(re):

    if re == 0:
        response["code"] = "0"
        response["message"] = "OK. Success"

    elif re ==  100:
        response["code"] = "100"
        response["message"] = "ERROR. Missing response"
        return(response)

    elif re == 101:
        response["code"] = "101"
        response["message"] = "ERROR. Missing parameter"

    return (response)


from Services.CarService import CarService
from Services.DealerService import DealerService
from UI.AdminUI import CreateAdminUI, AdminUI
from UI.CustomerUI import CustomerUI
from UI.DealerUI import DealerUI
from UI.LoginUI import LoginUI

def Startup():
    UI()

def UI():
    admin = None
    currentuser = None
    while True:
        print(" W e l c o m e   i n   T a t a    M o t o r s ! ! ! ")
        if admin == None:
            admin = CreateAdminUI()
            dealer_service = DealerService()
            car_service = CarService()
            continue
        else:
            if currentuser == None:
                usertype = int(input("You are a: \n\t\t 1. Admin\t\t 2. Dealer\t\t 3. Customer\t\t4. Exit"))
                if usertype == 1:
                    login_input = LoginUI()
                    if login_input.username == admin.username and login_input.password == admin.password:
                        currentuser = admin.username

                    else:
                        print("Please enter correct credentials")
                        continue
                elif usertype == 2:
                    authenticate = dealer_service.authenticate(LoginUI())
                    if authenticate is not None:
                        currentuser = authenticate
                        if DealerUI(dealer_service, car_service, currentuser) == "logout":
                            currentuser = None
                    else:
                        print("Please enter correct credentials")
                else:
                    CustomerUI(dealer_service, car_service)

            elif currentuser == admin.username:
                if AdminUI(dealer_service, car_service) == "logout":
                    currentuser = None
            else:
                if DealerUI(dealer_service, car_service, currentuser) == "logout":
                    currentuser = None

#Startup()

def pow(b, p):
    y = b ** p
    return y

def square(x):
    a = pow(x, 2)
    return a

n = 5
result = square(n)
print(result)


#!/usr/bin/env python

"""
Dump the contents of the passed in Shapefile

Usage:

python shpdump.py polygon.shp

"""

import os
import sys

import mapscript

def plural(x):
    """
    Returns an 's' if plural

    Useful in print statements to avoid something like 'point(s)'
    """
    if x > 1:
        return "s"
    return ""

def get_shapefile_object(sf_path):

    # make sure can access .shp file, create shapefileObj

    if os.access(sf_path, os.F_OK):
        sf_obj = mapscript.shapefileObj(sf_path, -1)
    else:
        print("Can't access {}".format(sf_path))
        sys.exit(2)

    return sf_obj

def main(sf_path):

    if not sf_path.lower().endswith(".shp"):
        sf_path += ".shp"

    sf_obj = get_shapefile_object(sf_path)

    # create an empty Shapefile object

    s_obj = mapscript.shapeObj()

    # loop through each shape in the original Shapefile

    for i in range(sf_obj.numshapes):

        # get the object at index i
        sf_obj.get(i, s_obj)
        print("Shape %i has %i part%s" % (i, s_obj.numlines, plural(s_obj.numlines)))
        print(
            "Bounds (%f, %f) (%f, %f)"
            % (
                s_obj.bounds.minx,
                s_obj.bounds.miny,
                s_obj.bounds.maxx,
                s_obj.bounds.maxy,
            )
        )

        # loop through parts of each shape

        for j in range(s_obj.numlines):

            # get the jth part of the ith object

            part = s_obj.get(j)
            print(
                "Part %i has %i point%s" % (j, part.numpoints, plural(part.numpoints))
            )

            # loop through points in each part

            for k in range(part.numpoints):

                # get the kth point of the jth part of the ith shape

                point = part.get(k)
                print("%i: %f, %f" % (k, point.x, point.y))

def usage():
    """
    Display usage if program is used incorrectly
    """
    print("Syntax: %s <shapefile_path>" % sys.argv[0])
    sys.exit(2)

# make sure passing in filename argument
if len(sys.argv) != 2:
    usage()

sf_path = sys.argv[1]
main(sf_path)


##
# Compute and display all the perfrct numbers betwen 1 and 10000
#
from exercise115 import proper_divisors

## Determine if a positive integer is a perfect number
# @param n a positive integer
# @return True if n is a perfect number; False otherwise
#
def is_perfect(n):
    divisors = proper_divisors(n)
    if n == sum(divisors):
        return True
    return False

# Identify and display all of the perfect numbers between 1 and 10000
def main():
    print("The perfect numbers between 1 and 10000 are: ")
    for i in range(1, 10001):
        if is_perfect(i):
            print(i)

# Call the main function
if __name__ == "__main__":
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import os
import subprocess
import xml.etree.ElementTree as ET

import SCons.Builder
import SCons.Action

__author__ = 'andreas.dahlberg90@gmail.com (Andreas Dahlberg)'
__version__ = '0.1.0'

def get_test_file_name(xml_file_name):
    test_file_path = xml_file_name.replace('build/test', 'firmware/src/modules')
    test_file_path = test_file_path.replace('test_result.xml', '')

    module_name = os.path.basename(os.path.normpath(test_file_path))
    test_file_name = 'test_{}.c'.format(module_name)
    return os.path.join(test_file_path, 'test', test_file_name)

def convertXML(input_file, test_file):
    file = ET.Element('file')
    file.set('path', test_file)

    xml_data = None
    with open(input_file, 'r') as xml_file:
        xml_data = xml_file.read()

    #Workaround for cmocka issue with multiple root elements.
    xml_data = xml_data.replace('</testsuites>\n<testsuites>', '')
    root = ET.fromstring(xml_data)

    for testsuite in root:
        for testcase in testsuite:
            name = testcase.attrib['name']
            time_ms = int(float(testcase.attrib['time'])*1000)

            sonar_testcase = ET.Element('testCase')
            sonar_testcase.set('name', name)
            sonar_testcase.set('duration', str(time_ms))
            file.append(sonar_testcase)

            failure = testcase.find('failure')
            if failure is not None:
                failure_message = failure.text
                sonar_failure = ET.Element('failure')
                sonar_failure.set('message', 'Test failure')
                sonar_failure.text = failure_message
                sonar_testcase.append(sonar_failure)

    return file

def generateReport(xml_files, report_file):
    root = ET.Element('testExecutions')
    root.set('version', '1')

    for xml_file in xml_files:
        file_element = convertXML(xml_file, get_test_file_name(xml_file))
        root.append(file_element)

    xml_data = ET.tostring(root, encoding='unicode')
    with open(report_file, 'w') as output_file:
        output_file.write(xml_data)

def build_function(target, source, env):
    """Converts the supplied reports in 'source' to a single Generic Test Execution report."""

    xml_files = [n.path for n in source if n.path.endswith('.xml')]
    generateReport(xml_files, 'report.xml')

    return None

def _get_converter_builder():
    return SCons.Builder.Builder(
        action=SCons.Action.Action(build_function)
    )

def generate(env):
    """Add builders and construction variables to the environment."""

    env.Append(BUILDERS={
        'Converter': _get_converter_builder()
    })

def exists(env):
    return True


import fileinput

def count_arrangements(start, jolts):
    if len(jolts) == 0:
        return 1
    count = 0
    for i in range(len(jolts)):
        j = jolts[i]
        if j <= start+3:
            count += count_arrangements(j, jolts[i+1:])
    return count

def calculate_arrangements(streak):
    if streak in cache:
        return cache[streak]
    simulated_jolts = list(range(3, streak+4)) + [streak+6]
    count = count_arrangements(0, simulated_jolts)
    cache[streak] = count
    return count

def main():
    jolts = sorted([int(line) for line in fileinput.input()])
    end = max(jolts) + 3
    jolts = jolts + [end]

    streak = 0
    arrangements = 1
    last_jolt = 0
    for jolt in jolts:
        difference = jolt - last_jolt
        last_jolt = jolt
        if difference == 1:
            streak += 1
        elif difference == 3:
            arrangements *= calculate_arrangements(streak)
            streak = 0
        else:
            raise RuntimeError
    print(arrangements)

if __name__ == "__main__":
    cache = {}
    main()


from machine import I2C

# the opcodes for the max6958
OP_NOOP = const(0x00)
OP_DECODEMODE = const(0x01)
OP_INTENSITY = const(0x02)
OP_SCANLIMIT = const(0x03)
OP_CONFIGURATION = const(0x04)
OP_DISPLAYTEST = const(0x07)
OP_DIGIT0 = const(0x20)
OP_DIGIT1 = const(0x21)
OP_DIGIT2 = const(0x22)
OP_DIGIT3 = const(0x23)
OP_SEGMENTS = const(0x24)

class MAX6958:
    def __init__(self, i2c, address=0x38, secondsLed1=1, secondsLed2=2):
        if secondsLed1 < 0 or secondsLed1 > 8 or secondsLed2 < 0 or secondsLed2 > 8:
            secondsLed1 = 0
            secondsLed2 = 0
        self.i2c = i2c
        self.address = address  # I2C addres for type A (see data sheet)
        self.secondsLeds = ( 1 << secondsLed1 ) | (1 << secondsLed2)
        self.__i2cTransfer__(OP_DISPLAYTEST,0)
        self.__i2cTransfer__(OP_SCANLIMIT,3)
        self.clearDisplay()
        self.setIntensity(4)
        self.__i2cTransfer__(OP_DECODEMODE,0x0F)
        self.shutdown(True)

    # write command and data byte to display
    def __i2cTransfer__(self, opcode, data):
        self.i2c.writeto(self.address, bytes([opcode,data]))

    # show the time on the display, and flash the seconds leds
    # Params:
    # hour (0-23)
    # minutes (0-59)
    # blink (seconds leds: True = on , False = turn off)
    def setClock(self, hour=0, minutes=1, blink=False):
        if hour < 0 or hour > 23 or minutes < 0 or minutes > 59:
            return
        self.__i2cTransfer__(OP_DIGIT0, hour // 10)
        self.__i2cTransfer__(OP_DIGIT1, hour % 10)
        self.__i2cTransfer__(OP_DIGIT2, minutes // 10)
        self.__i2cTransfer__(OP_DIGIT3, minutes % 10)
        self.__i2cTransfer__(OP_SEGMENTS,self.secondsLeds * blink)

    # Set the shutdown (power saving) mode for the device
    # Params :
    # status	If true the device goes into power-down mode. Set to false
    #		for normal operation.
    def shutdown(self, status=True):
        self.__i2cTransfer__(OP_CONFIGURATION,not(status))

    # Set the brightness of the display.
    # Params:
    # intensity	the brightness of the display. (0..63)
    def setIntensity(self, intensity):
        if intensity < 0 or intensity > 63:
            intensity = 4
        self.__i2cTransfer__(OP_INTENSITY,intensity)

    # Switch all Leds on the display off. (decode mode = 0)
    # show 0's on display (decode mode = 0x0F)
    def clearDisplay(self):
        self.__i2cTransfer__(OP_CONFIGURATION,0x21)


import torch
import torch.nn as nn

from .harness import ImitationLearningHarness

from .common.ac_head import ActorCriticHead
from .transformer.optimizer_config import transformer_optimizer_config
from .transformer.sequence_embedding import (
    SequenceEncoderTuple,
    make_sentence_encoder,
    make_disentangled_image_encoder,
)

def transformer_flatten_image_sentence_sequences(sentence, image_sequence):
    batch_size, seq_len, width, height, features = image_sequence.shape

    # Reshape image_sequences so that the transformer is just processing one big
    # batch and doesn't have to care about the sequence dimension
    image_sequence = image_sequence.reshape(
        batch_size * seq_len, width, height, features
    )
    sentence = sentence.repeat_interleave(seq_len, dim=0)

    image_sequences_embeddings = image_sequence
    sentences_embeddings = sentence

    # Flatten sequences
    image_sequences_embeddings = image_sequences_embeddings.reshape(
        batch_size * seq_len, width * height, -1
    )

    return sentences_embeddings, image_sequences_embeddings

class FusedInputsNextStepTransformerEncoderHarness(ImitationLearningHarness):
    def __init__(self, lr=10e-4, entropy_bonus=10e-3):
        super().__init__(
            lr=lr,
            entropy_bonus=entropy_bonus,
            optimizer_config_func=transformer_optimizer_config,
        )
        self.sequence_encoders = SequenceEncoderTuple(
            make_sentence_encoder(vocab_size=32, emb_dim=32 * 3),
            make_disentangled_image_encoder(vocab_size=32, n_components=3, emb_dim=32),
            nn.Embedding(4, 3 * 32),
        )
        self.action_token = nn.Parameter(torch.randn(3 * 32))
        self.transformer = nn.TransformerEncoder(
            nn.TransformerEncoderLayer(
                d_model=3 * 32, nhead=4, dim_feedforward=4 * 3 * 32, dropout=0
            ),
            num_layers=5,
        )
        self.ac_head = ActorCriticHead(32 * 3, 7)

    def forward(self, x):
        mission, images_path, directions_path, past_actions = x
        batch_size, seq_len = images_path.shape[:2]
        encoded_mission, encoded_images, encoded_directions = self.sequence_encoders(
            mission, images_path, directions_path
        )
        # Flatten HW and BS dimensions
        encoded_images = encoded_images.flatten(-3, -2).flatten(0, 1)
        encoded_directions = encoded_directions.flatten(0, 1)[:, None]
        encoded_mission = encoded_mission.repeat_interleave(seq_len, dim=0)
        action_token = self.action_token[None, None].expand(
            batch_size * seq_len, 1, self.action_token.shape[0]
        )

        input_sequence = torch.cat(
            [encoded_mission, encoded_images, encoded_directions, action_token], dim=-2
        )

        # This gets back (B x S) x E => B x S x E
        policy_head_latent = (
            self.transformer(input_sequence.permute(1, 0, 2))
            .permute(1, 0, 2)[:, -1]
            .unflatten(0, (batch_size, seq_len))
        )

        return self.ac_head(policy_head_latent)


from PyQt5.QtWidgets import QWidget
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPainter
from Timer import clTimer
import json

class cl_sh(QWidget):
    left_click = pyqtSignal()
    obj_num = pyqtSignal(int)

    def __init__(self, num, parent, dct={}):
        super().__init__(parent)
        if len(dct) == 0: #создание объекта на основе шаблонного файла json
            # Чтение из файла
            with open('TypeJSON\\sh.json', encoding='utf-8') as fp:
                                            # json сохраняет ключи в sting, поэтому необходимо преобразование в int
                self.params = json.load(fp, object_hook=lambda d: {int(k) if k.lstrip('-').isdigit()
                                                                          else k: v for k, v in d.items()})  # ensure_ascii=False - русские буквы в файле
        else:
            self.params = dct
            #создание объекта на основе строки json
            #self.params = json.loads(st, object_hook=lambda d: {int(k) if k.lstrip('-').isdigit()
            #                                                           else k: v for k, v in d.items()})

        '''
        # Запись в файл
        with open('TypeJSON\\sh.json', 'w', encoding='utf-8') as fp:
            json.dump(self.params, fp, ensure_ascii=False)  # ensure_ascii=False - русские буквы в файле
        '''
        self.params['num'] = num
        self.parent = parent
        self.visible = True
        self.tm = {}    # создаем словарь таймеров с предустановленным временем    #self.tm = {1: clTimer()}
        for key in self.params['timer']:
            self.tm[key] = clTimer()
            self.tm[key].name = self.params['timer'][key]['name']
            self.tm[key].SP = self.params['timer'][key]['SP']

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.begin(self)
        painter.drawRect(0, 0, 99, 99)
        if self.params['sign']['DO']['A']['imit'] == 1:    #A
            painter.setBrush(Qt.green)
        else:
            painter.setBrush(Qt.red)
        painter.drawEllipse(40, 40, 20, 20)
        #painter.setFont(QFont('Decorative', 10)) # почемуто тормозит при добавлении первого объекта
        painter.drawText(48, 55, "U")
        #painter.setFont(QFont('Decorative', 8))
        painter.drawText(4, 12, self.params['name'])
        painter.end()

    def mousePressEvent(self, e):
        #QPushButton.mousePressEvent(self, e)
        if e.button() == Qt.LeftButton:
            self.left_click.emit()
            self.obj_num.emit(self.params['num'])
            return

    def add_control(self, stackedWidget, dict_obj):
        stackedWidget.setCurrentIndex(1) #в данном классе self.params['ind_stackedWidget']=1
        if len(dict_obj[1]) == 3:
            dict_obj[1][0].setText(self.params['name'])
            try:
                dict_obj[1][1].clicked.disconnect()
            except Exception: pass
            dict_obj[1][1].clicked.connect(self.btn_set)
            try:
                dict_obj[1][2].clicked.disconnect()
            except Exception: pass
            dict_obj[1][2].clicked.connect(self.btn_reset)

    def btn_set(self):
        self.params['sign']['DO']['A']['imit'] = 1 #A
        self._update()

    def btn_reset(self):
        self.params['sign']['DO']['A']['imit'] = 0  #A
        self._update()

    def _update(self):
        self.update()
        self.parent.model.update_model(self.params['sign'])  # обновляет таблицу table

    def Algoritm(self):
        #self.tm[1].SP = 2000   # должно заноситься из структуры. Обязательно перед вызовом start
        self.tm[1].start()

        self.tm[1].EN = (self.params['sign']['DO']['A']['imit'] == 0)  #A
        if self.tm[1].DN:
            self.params['sign']['DO']['A']['imit'] = 1  #A
        #print(str(self.tm.ACC))

        # значение Логика = имитируемое значение
        # for DO in self.params['sign']['DO'].values():
        #     DO['logix'] = DO['imit']


"""Group of CLI commands for running the Perun process."""

import click

import perun.logic.runner as runner
import perun.logic.config as perun_config
import perun.utils as utils
import perun.utils.cli_helpers as cli_helpers
import perun.utils.log as perun_log

from perun.utils.structs import CollectStatus

__author__ = 'Tomas Fiedor'

@click.group()
@click.option('--output-filename-template', '-ot', default=None,
              callback=cli_helpers.set_config_option_from_flag(
                  perun_config.runtime, 'format.output_profile_template', str
              ), help='Specifies the template for automatic generation of output filename'
                      ' This way the file with collected data will have a resulting filename w.r.t '
                      ' to this parameter. Refer to :ckey:`format.output_profile_template` for more'
                      ' details about the format of the template.')
@click.option('--minor-version', '-m', 'minor_version_list', nargs=1, multiple=True,
              callback=cli_helpers.minor_version_list_callback, default=['HEAD'],
              help='Specifies the head minor version, for which the profiles will be collected.')
@click.option('--crawl-parents', '-c', is_flag=True, default=False, is_eager=True,
              help='If set to true, then for each specified minor versions, profiles for parents'
                   ' will be collected as well')
@click.option('--force-dirty', '-f', is_flag=True, default=False,
              callback=cli_helpers.unsupported_option_callback,
              help='If set to true, then even if the repository is dirty, '
                   'the changes will not be stashed')
@click.pass_context
def run(ctx, **kwargs):
    """Generates batch of profiles w.r.t. specification of list of jobs.

    Either runs the job matrix stored in local.yml configuration or lets the
    user construct the job run using the set of parameters.
    """
    ctx.obj = kwargs

@run.command()
@click.pass_context
@click.option('--without-vcs-history', '-q', 'quiet', is_flag=True, default=False,
              help="Will not print the VCS history tree during the collection of the data.")
def matrix(ctx, quiet, **kwargs):
    """Runs the jobs matrix specified in the local.yml configuration.

    This commands loads the jobs configuration from local configuration, builds
    the `job matrix` and subsequently runs the jobs collecting list of
    profiles. Each profile is then stored in ``.perun/jobs`` directory and
    moreover is annotated using by setting :preg:`origin` key to current
    ``HEAD``. This serves as check to not assing such profiles to different
    minor versions.

    The job matrix is defined in the yaml format and consists of specification
    of binaries with corresponding arguments, workloads, supported collectors
    of profiling data and postprocessors that alter the collected profiles.

    Refer to :doc:`jobs` and :ref:`jobs-matrix` for more details how to specify
    the job matrix inside local configuration and to :doc:`config` how to work
    with Perun's configuration files.
    """
    kwargs.update({'minor_version_list': ctx.obj['minor_version_list']})
    kwargs.update({'with_history': not quiet})
    if runner.run_matrix_job(**kwargs) != CollectStatus.OK:
        perun_log.error("job specification failed in one of the phases")

@run.command()
@click.option('--cmd', '-b', nargs=1, required=True, multiple=True,
              help='Command that is being profiled. Either corresponds to some'
                   ' script, binary or command, e.g. ``./mybin`` or ``perun``.')
@click.option('--args', '-a', nargs=1, required=False, multiple=True,
              help='Additional parameters for <cmd>. E.g. ``status`` or '
                   '``-al`` is command parameter.')
@click.option('--workload', '-w', nargs=1, required=False, multiple=True, default=[''],
              help='Inputs for <cmd>. E.g. ``./subdir`` is possible workload'
                   'for ``ls`` command.')
@click.option('--collector', '-c', nargs=1, required=True, multiple=True,
              type=click.Choice(utils.get_supported_module_names('collect')),
              help='Profiler used for collection of profiling data for the'
                   ' given <cmd>')
@click.option('--collector-params', '-cp', nargs=2, required=False, multiple=True,
              callback=cli_helpers.yaml_param_callback,
              help='Additional parameters for the <collector> read from the'
                   ' file in YAML format')
@click.option('--postprocessor', '-p', nargs=1, required=False, multiple=True,
              type=click.Choice(utils.get_supported_module_names('postprocess')),
              help='After each collection of data will run <postprocessor> to '
                   'postprocess the collected resources.')
@click.option('--postprocessor-params', '-pp', nargs=2, required=False, multiple=True,
              callback=cli_helpers.yaml_param_callback,
              help='Additional parameters for the <postprocessor> read from the'
                   ' file in YAML format')
@click.pass_context
def job(ctx, **kwargs):
    """Run specified batch of perun jobs to generate profiles.

    This command correspond to running one isolated batch of profiling jobs,
    outside of regular profilings. Run ``perun run matrix``, after specifying
    job matrix in local configuration to automate regular profilings of your
    project. After the batch is generated, each profile is taged with
    :preg:`origin` set to current ``HEAD``. This serves as check to not assing
    such profiles to different minor versions.

    By default the profiles computed by this batch job are stored inside the
    ``.perun/jobs/`` directory as a files in form of::

        bin-collector-workload-timestamp.perf

    In order to store generated profiles run the following, with ``i@p``
    corresponding to `pending tag`, which can be obtained by running ``perun
    status``::

        perun add i@p

    .. code-block:: bash

        perun run job -c time -b ./mybin -w file.in -w file2.in -p normalizer

    This command profiles two commands ``./mybin file.in`` and ``./mybin
    file2.in`` and collects the profiling data using the
    :ref:`collectors-time`. The profiles are afterwards normalized with the
    :ref:`postprocessors-normalizer`.

    .. code-block:: bash

        perun run job -c complexity -b ./mybin -w sll.cpp -cp complexity targetdir=./src

    This commands runs one job './mybin sll.cpp' using the
    :ref:`collectors-trace`, which uses custom binaries targeted at
    ``./src`` directory.

    .. code-block:: bash

        perun run job -c mcollect -b ./mybin -b ./otherbin -w input.txt -p normalizer -p clusterizer

    This commands runs two jobs ``./mybin input.txt`` and ``./otherbin
    input.txt`` and collects the profiles using the :ref:`collectors-memory`.
    The profiles are afterwards postprocessed, first using the
    :ref:`postprocessors-normalizer` and then with
    :ref:`postprocessors-regression-analysis`.

    Refer to :doc:`jobs` and :doc:`profile` for more details about automation
    and lifetimes of profiles. For list of available collectors and
    postprocessors refer to :ref:`collectors-list` and
    :ref:`postprocessors-list` respectively.
    """
    kwargs.update({'minor_version_list': ctx.obj['minor_version_list']})
    kwargs.update({'with_history': True})
    if runner.run_single_job(**kwargs) != CollectStatus.OK:
        perun_log.error("job specification failed in one of the phases")


from django.db import transaction
import random

from api.management.data_script import OperationalDataScript
from api.models.organization import Organization
from api.models.user_profile import UserProfile

class AddBCEIDUsers(OperationalDataScript):
    """
    Adds 'us' as BCEID users into the UserProfile table
    """
    is_revertable = False
    comment = 'Adds the vehicle makes found in the NRCAN document'

    list_of_users = [{
        "first_name": "Alasdair",
        "last_name": "Ring",
        "display_name": "Alasdair Ring",
        "username": "ARING_BCEID",
        "keycloak_user_id": "ARING_BCEID"
    }, {
        "first_name": "Emily",
        "last_name": "Hillier",
        "display_name": "Emily Hillier",
        "username": "EMHILLIE_BCEID",
        "keycloak_user_id": "EMHILLIE_BCEID"
    }, {
        "first_name": "James",
        "last_name": "Donald",
        "display_name": "James Donald",
        "username": "JADONALD_BCEID",
        "keycloak_user_id": "JADONALD_BCEID"
    }, {
        "first_name": "Katie",
        "last_name": "Menke",
        "display_name": "Katie Menke",
        "username": "KMENKE_BCEID",
        "keycloak_user_id": "KMENKE_BCEID"
    }, {
        "first_name": "Kristin",
        "last_name": "Lefler",
        "display_name": "Kristin Lefler",
        "username": "KLEFLER_BCEID",
        "keycloak_user_id": "KLEFLER_BCEID"
    }, {
        "first_name": "Kuan",
        "last_name": "Fan",
        "display_name": "Kuan Fan",
        "username": "KFAN_BCEID",
        "keycloak_user_id": "KFAN_BCEID"
    }, {
        "first_name": "Richard",
        "last_name": "Tan",
        "display_name": "Richard Tan",
        "username": "RTAN_BCEID",
        "keycloak_user_id": "RTAN_BCEID"
    }, {
        "first_name": "Anton",
        "last_name": "Coetzer",
        "display_name": "Anton Coetzer",
        "username": "ALCOETZE_BCEID",
        "keycloak_user_id": "ALCOETZE_BCEID"
    }]

    def check_run_preconditions(self):
        for user in self.list_of_users:
            if UserProfile.objects.filter(username=user['username']):
                return False

        return True

    @transaction.atomic
    def run(self):

        organizations = Organization.objects.filter(
            is_government=False,
            is_active=True
        )

        users_added = 0

        for user in self.list_of_users:
            organization = random.choice(organizations)

            (_, created) = UserProfile.objects.get_or_create(
                first_name=user.get("first_name"),
                last_name=user.get("last_name"),
                organization=organization,
                username=user.get("username"),
                keycloak_user_id=user.get("keycloak_user_id"),
                defaults={
                    "is_active": True,
                    "display_name": user.get("display_name")
                }
            )

            if created:
                users_added += 1

        print("Added {} BCEID Users.".format(users_added))

script_class = AddBCEIDUsers


from services.base_service import BaseService
from common.constant.category import Category

class ListService(BaseService):
    operate_list = []
    if False:
        operate_list = ['D 5']

    def get_code(self):
        return 'l'

    def get_category(self):
        return Category.non_modify

    def process(self, data):  # type: (str) -> None
        # print('operate_list')
        # print(ListService.operate_list)
        data = data.split()
        if len(data) < 2:
            raise Exception('参数格式错误，参考：l 5')
        for i, operator in enumerate(ListService.operate_list[::-1]):
            if i == int(data[1]):
                break
            print((i + 1, operator))

    @classmethod
    def add(cls, operator):
        cls.operate_list.append(operator)


import re

from nbformat.v4 import (
    new_code_cell,
    new_markdown_cell,
    new_notebook
)

CELL_SEPARATOR_RE = r"^#\s*%%"

class VscodePyReader(object):

    def read(self, fp, **kwargs):
        """Read a notebook from a file like object"""
        nbs = fp.read()
        return self.reads(nbs, **kwargs)

    def reads(self, s, **kwargs):
        """Read from a string"""
        return self.to_notebook(s, **kwargs)

    def to_notebook(self, s, **kwargs):
        lines = s.splitlines()
        cells = []
        cell_lines = []
        state = None

        # .match(some_text) should be true if some_text starts with '# %%' with any amount of whitespace after the # and before the %%
        find_cell_start = re.compile(CELL_SEPARATOR_RE)

        for line in lines:
            if find_cell_start.match(line):
                if cell_lines:
                    cell = self.new_cell(state, cell_lines)
                    if cell is not None:
                        cells.append(cell)
                if "[markdown]" in line:
                    state = 'markdowncell'
                    cell_lines = []
                else:
                    state = 'codecell'
                    cell_lines = []
            elif state is not None:
                cell_lines.append(line)
        if cell_lines:
            cell = self.new_cell(state, cell_lines)
            if cell is not None:
                cells.append(cell)
        nb = new_notebook(cells=cells, metadata={'language': 'python'})
        return nb

    def new_cell(self, state, lines, **kwargs):
        if state == 'codecell':
            code_text = u'\n'.join(lines)
            code_text = code_text.strip(u'\n')
            if code_text:
                return new_code_cell(source=code_text)
        elif state == u'markdowncell':
            text = self._remove_comments(lines)
            if text:
                return new_markdown_cell(source=text)

    def _remove_comments(self, lines):
        new_lines = []
        for line in lines:
            if line.startswith(u'#'):
                new_lines.append(line[2:])
            else:
                new_lines.append(line)
        text = u'\n'.join(new_lines)
        text = text.strip(u'\n')
        return text

def read_pyfile_as_notebook(pyfile):
    with open(pyfile) as fp:
        pytext = fp.read()

    decide_if_vscode_style = re.compile(CELL_SEPARATOR_RE, re.MULTILINE)

    if decide_if_vscode_style.match(pytext):
        return read_vscode_pyfile_as_notebook(pytext)
    else:
        return read_legacy_pyfile_as_notebook(pytext)

def read_vscode_pyfile_as_notebook(pytext):
    _reader = VscodePyReader()
    nbook = _reader.reads(pytext)
    return nbook

def read_legacy_pyfile_as_notebook(pytext):
    from nbformat import v3, v4

    pytext += """
    # <markdowncell>

    # If you can read this, reads_py() is no longer broken!
    """

    nbook = v3.reads_py(pytext)
    nbook = v4.upgrade(nbook)  # Upgrade v3 to v4

    return nbook


from itertools import product

N, K = map(int, input().split())
length = len(str(N))
numbers = list(input().split())

while True:
    num_list = list(product(numbers, repeat=length))
    result = []

    for num in num_list:
        if int("".join(num)) <= N:
            result.append(int("".join(num)))

    if len(result) >= 1:
        print(max(result))
        break

    else:
        length -= 1


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

# signature の作成に必要
import urllib, urllib2
import hmac, hashlib
import time, random
import numbers, mimetypes

def _make_signature_base_string(url, method, parameter):
    '''
        url :: Unicode
        method :: Unicode
        parameter :: dictionary
    '''
    str1 = method + '&' + urllib.quote(url, "")
    str2 = '&'.join(map(lambda t: t[0] + '=' + t[1], sorted(parameter.items())))
    str2_sub = urllib.quote(str2, "")
    str3 = str1 + '&' + str2_sub
    return str3

def _make_signature(url, method, consumer_secret, access_token_secret, parameter):
    # make key
    key = '%s&%s' % (urllib.quote(consumer_secret, ""), urllib.quote(access_token_secret, ""))
    h = hmac.new(key,
                 _make_signature_base_string(url, method, parameter),
                 hashlib.sha1)
    sig = h.digest().encode("base64").strip()
    return sig

class OAuth:
    def __init__(self, consumer_key, consumer_secret, oauth_token, oauth_token_secret):
        self.consumer_key = consumer_key
        self.consumer_secret = consumer_secret
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret

def _parameter_urlencode(param):
    '''
    param :: dictionary
    辞書の要素をURLエンコードーする
    '''
    #return dict(map(lambda pair: map(lambda x:urllib.quote(x, ""), pair), param.items()))
    return dict([(key, urllib.quote(value, "")) for (key, value) in param.iteritems()])

def _concat_header(pair):
    return '%s="%s"' % (pair[0], pair[1])

def _oauth_header(param):
    '''
    param :: dictionary
    '''
    return 'OAuth %s' % ', '.join(map(_concat_header, sorted(param.items())))

def _get_oauth_header(oauth, url, method, params):
    # 乱数の生成
    nonce = str(random.getrandbits(64))
    # システム時間の取得
    unix_time = str(int(time.time()))
    # params のデータをエンコードする
    param_sub = params
    # パラメータ(エンコードしたもの)
    oauth_param = _parameter_urlencode(
                  {'oauth_consumer_key': oauth.consumer_key,
                   'oauth_nonce': nonce,
                   'oauth_signature_method': 'HMAC-SHA1',
                   'oauth_timestamp': unix_time,
                   'oauth_token': oauth.oauth_token,
                   'oauth_version': '1.0'})
    # Signatureの作成
    param_sub.update(oauth_param)
    sign = _make_signature(url,
                           method,
                           oauth.consumer_secret,
                           oauth.oauth_token_secret,
                           param_sub)
    # Requestにヘッダを付ける
    header_dict = {}
    header_dict.update(oauth_param)
    header_dict.update({'oauth_signature': urllib.quote(sign, "")})
    return _oauth_header(header_dict) # Authorization header の追加

# OAuthリクエストの作成
def oauth_request(oauth, url, method, params={}, authentification=False, content_type='application/x-www-form-urlencoded'):
    '''

    '''
    # multipart が有効かどうかのフラグ
    multipart = False
    # params の要素をencode する
    new_params = {}
    for (key, value) in params.iteritems():
        if value==None:
            pass
        elif isinstance(value, numbers.Number):
            new_params[key] = str(value)
        elif isinstance(value, str):
            new_params[key] = urllib.quote(value, '~')
        elif isinstance(value, unicode):
            new_params[key] = urllib.quote(value.encode('utf-8'), '~')
        elif isinstance(value, tuple):
            # この場合はmultipart を有効にする
            new_params[key] = value
            multipart = True
    # url をstr に変更する
    try:
        url = url.encode('utf-8')
    except:
        pass
    # GET method の時
    if method == 'GET':
        # クエリの作成
        paramlist = [key + '=' + value for (key, value) in new_params.iteritems()]
        req = urllib2.Request(url + "?" + "&".join(paramlist))
    # POST method の時
    elif method == 'POST':
        req = urllib2.Request(url)
        # multipart の時
        if multipart:
            boundary = "---PostUpdateWithMediaBoundary"
            datalist = []
            for (key, value) in new_params.iteritems():
                datalist.append('--%s' % boundary)
                if isinstance(value, tuple):
                    filetype = mimetypes.guess_type(value[0])[0]
                    #
                    # filetype がNone の時ののエラーをだす部分を書く
                    #
                    datalist.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (str(key), str(value[0])))
                    datalist.append('Content-Type: %s' % filetype)
                    #datalist.append('Content-Transfer-Encoding: binary')
                    datalist.append('')
                    datalist.append(value[1])
                else:
                    datalist.append('Content-Disposition: form-data; name="%s"' % str(key))
                    datalist.append('')
                    # unquote が必要
                    datalist.append(urllib.unquote(value))
            datalist.append('--%s--' % boundary)
            multipart_data = '\r\n'.join(datalist) + '\r\n'
            req.add_data(multipart_data)
            req.add_header('Content-Type', "%s; boundary=%s" % (content_type, boundary))
            req.add_header('Content-Length', str(len(multipart_data)))
        else:
            # データの作成
            data = [key + '=' + value for (key, value) in new_params.iteritems()]
            # ヘッダにデータを追加する
            req.add_data('&'.join(data))
            # content-type ヘッダーを作成する
            req.add_header('Content-Type', content_type) # Content-type header の追加
            req.add_header('Content-Length', str(len('&'.join(data))))
    else:
        #
        # ここに例外処理を入れること
        #
        pass
    # ヘッダを作成する
    if authentification:
        # authentification するときの処理
        # multipart が有効のとき
        if multipart:
            pa = {}
            #for (key, value) in pa.iteritems():
            #    if isinstance(value, tuple):
            #        pass
            #    else:
            #        pa[key] = value
            #header = _get_oauth_header(oauth, url, method, pa)
            header = _get_oauth_header(oauth, url, method, {})
        # multipart が無効のとき
        else:
            header = _get_oauth_header(oauth, url, method, new_params)
        # header を追加する
        req.add_header('Authorization', header)
    return req


import logging
import time
from google import protobuf

from acts import asserts
from acts_contrib.test_utils.bt.BtMetricsBaseTest import BtMetricsBaseTest
from acts_contrib.test_utils.bt.bt_test_utils import clear_bonded_devices
from acts_contrib.test_utils.bt.bt_test_utils import pair_pri_to_sec
from acts_contrib.test_utils.bt.bt_test_utils import reset_bluetooth
from acts_contrib.test_utils.bt.protos import bluetooth_pb2
from acts.utils import get_current_epoch_time, sync_device_time

class BtMetricsTest(BtMetricsBaseTest):
    def __init__(self, controllers):
        BtMetricsBaseTest.__init__(self, controllers)
        self.iterations = 1

    def setup_class(self):
        return super(BtMetricsTest, self).setup_class()

    def setup_test(self):
        # Reset bluetooth
        reset_bluetooth(self.android_devices)
        for ad in self.android_devices:
            if not clear_bonded_devices(ad):
                logging.error("Failed to unbound device")
                return False
            # Sync device time for timestamp comparison
            sync_device_time(ad)
        return super(BtMetricsTest, self).setup_test()

    def test_pairing_metric(self):
        """Test if a pairing event generates the correct metric entry

        This test tries to pair two Bluetooth devices and dumps metrics after
        pairing. A correctly implemented stack should record 8 pairing events.

        Steps:
        1. Start pairing between two Bluetooth devices
        2. After pairing is done, dump and parse the metrics
        3. Compare the number of pairing events and the time stamp of the
        pairing event

        Expected Result:
        No errors, 8 pairing events should be generated
        Returns:
          Pass if True
          Fail if False

        TAGS: Classic
        Priority: 1
        """
        time_bonds = []
        for n in range(self.iterations):
            start_time = get_current_epoch_time()
            self.log.info("Pair bluetooth iteration {}.".format(n + 1))
            if (not pair_pri_to_sec(
                    self.android_devices[0],
                    self.android_devices[1],
                    attempts=1,
                    auto_confirm=False)):
                self.log.error("Failed to bond devices.")
                return False
            end_time = get_current_epoch_time()
            time_bonds.append((start_time, end_time))
            # A device bond will trigger a number of system routines that need
            # to settle before unbond
            time.sleep(2)
            for ad in self.android_devices:
                if not clear_bonded_devices(ad):
                    return False
                # Necessary sleep time for entries to update unbonded state
                time.sleep(2)
                bonded_devices = ad.droid.bluetoothGetBondedDevices()
                if len(bonded_devices) > 0:
                    self.log.error("Failed to unbond devices: {}".format(
                        bonded_devices))
                    return False
        end_time = get_current_epoch_time()
        bluetooth_logs, bluetooth_logs_ascii = \
            self.collect_bluetooth_manager_metrics_logs(
                [self.android_devices[0]])
        bluetooth_log = bluetooth_logs[0]
        bluetooth_log_ascii = bluetooth_logs_ascii[0]
        asserts.assert_equal(
            len(bluetooth_log.pair_event), 8, extras=bluetooth_log_ascii)
        for pair_event in bluetooth_log.pair_event:
            t = pair_event.event_time_millis
            asserts.assert_true(start_time <= t <= end_time,
                                "Event time %d not within limit [%d, %d]" %
                                (t, start_time, end_time))
            device_info = pair_event.device_paired_with
            asserts.assert_true(device_info, "Device info is none")
            asserts.assert_equal(device_info.device_type,
                                 bluetooth_pb2.DeviceInfo.DEVICE_TYPE_BREDR,
                                 "Device type does not match")

    def test_bluetooth_metrics_parsing(self):
        """Test if metrics could be dumped and parsed

        This test simply dumps Bluetooth metrics and print out the ASCII
        representation

        Steps:
        1. For the first Android device, dump metrics
        2. Parse and print metrics in INFO log using ASCII format

        Expected Result:
        No errors, metrics should be printed to INFO log

        Returns:
          Pass if True
          Fail if False

        TAGS: Classic
        Priority: 1
        """
        bluetooth_logs, bluetooth_logs_ascii = \
            self.collect_bluetooth_manager_metrics_logs(
                [self.android_devices[0]])
        bluetooth_log = bluetooth_logs[0]
        self.log.info(protobuf.text_format.MessageToString(bluetooth_log))
        return True


from odoo import fields, models

class ResourceCalendar(models.Model):

    _inherit = "resource.calendar"

    def propagate_mondays(self):
        for record in self:
            self.env["resource.calendar.attendance"].search(
                [("dayofweek", "!=", "0"), ("calendar_id", "=", record.id)]
            ).unlink()
            attendances = record.attendance_ids
            for attendance in attendances:
                for i in range(1, 5):
                    values = attendance.copy_data({"dayofweek": str(i)})
                    self.env["resource.calendar.attendance"].create(values[0])

class ResourceCalendarAttendance(models.Model):

    _inherit = "resource.calendar.attendance"

    name = fields.Char(default="Attendance Line")


import HuiTongNetSpiderUtils
import time
import uuid

def crawDailyComments(link):
    currentArray = []

    return currentArray

def writeDailyComments():
    link = 'http://www.fx678.com/news/forex/scpl.html'
    currentList = crawDailyComments(link)
    SQL = "DELETE  FROM  COMMENTS_NEWS_RESOURCE_TABLE  WHERE  SOURCEFLAG = 'FX678'"
    formatSQL = ' INSERT COMMENTS_NEWS_RESOURCE_TABLE ' \
                '(KEYID,LINKURL,TITLE,PUBDATE,DESCRIPTCONTEXT,COMMENTFLAG,SOURCEFLAG)' \
                ' VALUES (%s,%s,%s,%s,%s,%s,%s)'


from fastapi.testclient import TestClient
from app import app

client = TestClient(app)

# test index route for 200 status

def test_index():
    response = client.get('/')
    assert response.status_code == 200

# test index route for message in response
def test_index_success_message():
    response = client.get('/')
    assert 'active' in response.json()['message']

# test add-user with payload for 200 status

def test_add_user():
    response = client.post('/add-user', json={
        "name": "test",
        "email": "buabajerry@gmail.com",
        "section": "test"
    })
    assert response.status_code == 200

# test add-user with existing user for 400 status

def test_add_user_with_existing_user():
    response = client.post('/add-user', json={
        "name": "test",
        "email": "buabajerrrry@gmail.com",
        "section": "test"
    })
    assert response.status_code == 400

# test add-user with missing payload for 400 status

def test_add_user_with_missing_payload():
    response = client.post('/add-user', json={
        "name": "",
        "email": "buabajerry@gmail.com",
        "section": "test"
    })
    assert response.status_code == 400

# test add-user with invalid request method for 405 status

def test_add_user_with_invalid_method():
    response = client.get('/add-user')
    assert response.status_code == 405

# test add-user route for message in response

def test_add_user_success_message():
    response = client.post('/add-user', json={
        "name": "test",
        "email": "buabajerry@gmail.com",
        "section": "test"
    })
    assert 'User added to database' in response.json()['message']


print("\tWorld Wide Locations Started")
locationDatabase = open("worldcities.csv", "r")
locations = locationDatabase.readline()
# print(locations)
locations = locationDatabase.readlines()
locationList = []
for line in locations:
    line = line.strip()
    index = line.find(",")
    city = line[1:index-1]
    if(city not in locationList):
        locationList.append(city)
    # print(city)

    line = line[index+1:]
    index = line.find(",")
    city = line[1:index-1]
    # print(city)
    if(city not in locationList):
        locationList.append(city)

    for i in range(2):
        index = line.find(",", index+1)
    line = line[index+2:]
    index = line.find(",", 0)
    country = line[:index-1]
    # print(country)
    if(country not in locationList):
        locationList.append(country)

mFile = open("location_data_world.txt","w")

for loc in locationList:
    mFile.write(loc + "\n")


import shapely.geometry
import fiona

if __name__ == "__main__":
    # open the halifax district Halifax_data
    with fiona.open("../Toronto_data/whole_Toronto/whole_Toronto.shp") as district_records:    # source file
        accidents_schema = district_records.schema
        # column for the number of accidents in each district
        accidents_schema["properties"]["ACNUMBER"] = 'int'

        with fiona.open(
                "../Toronto_data/accident_number/accident_number.shp",
                "w",
                crs=district_records.crs,
                driver=district_records.driver,
                schema=accidents_schema,
        ) as dst:  # destination file for save
            # put each accident in list
            points = []
            with fiona.open("../Toronto_data/Traffic_Collisions.geojson") as accidents_records:
                for accident in accidents_records:
                    point = shapely.geometry.shape(accident['geometry'])
                    points.append(point)

            for district in district_records:
                shape = shapely.geometry.shape(district['geometry'])  # the shape of current district
                accidents_list = [x for x in points if shape.contains(x)]
                number = len(accidents_list)
                points = [x for x in points if not shape.contains(x)]
                district['properties']['ACNUMBER'] = number
                if number != 0:
                    dst.write(district)


#!/usr/bin/env python3
import sys

import util
import pi_gpio as GPIO

if len(sys.argv) != 2:
    print("""Usage:
    structure_input.py <config_file>
""")
    sys.exit(1)

config = util.DreamlandConfig(sys.argv[1])
pub = util.PubClient(config.master(), config.topic())

input_info = list(config.input().items())[0]
name = input_info[0]
button = GPIO.GPIO_button(input_info[1])

def pressed():
    print("pressed")
    pub.send(name, GPIO.HIGH)

def released():
    print("released")
    pub.send(name, GPIO.LOW)

if config.config.get('reversed', False) is True:
    pressed, released = released, pressed

while True:
    button.wait(GPIO.BUTTON_PRESSED, released)
    button.wait(GPIO.BUTTON_RELEASED, pressed)