#!/usr/bin/env python3
# dpw@plaza.localdomain
# 2023-09-19 19:17:00

import json
import sys
from dataclasses import dataclass
from pathlib import Path

from rich import inspect, print

class TrieNode:
    def __init__(self, char):
        self.char = char
        self.is_end = False
        self.children = {}

    def __repr__(self):
        return f"char:{self.char}, end: {self.is_end}, children: {self.children}"

@dataclass
class Trie:
    """A container for holding Trie nodes.  Will store and word, name, email, phone number, etc."""

    root: TrieNode = TrieNode("")
    word_count: int = 0

    def insert(self, word: str) -> None:
        word = word.lower()
        node = self.root
        for char in word:
            if char in node.children:
                node = node.children[char]
            else:
                new_node = TrieNode(char)
                node.children[char] = new_node
                node = new_node

        node.is_end = True
        self.word_count += 1

    def depth_first_search(self, node: TrieNode, prefix: str):
        """depth first search"""
        if node.is_end:
            self.output.append((prefix + node.char))

        for child in node.children.values():
            self.depth_first_search(child, prefix + node.char)

    def search(self, word: str) -> list:
        """search for words"""
        word = word.lower()
        node = self.root

        for char in word:
            if char in node.children:
                node = node.children[char]
            else:
                return []

        self.output = []
        self.depth_first_search(node, word[:-1])

        return self.output

def read_proper_names() -> Trie:
    trie = Trie()
    path = Path("/usr/share/dict/propernames")
    for name in path.read_text().split():
        trie.insert(name)

    return trie

def read_data():
    with open("data/emails.json") as f:
        data = json.load(f)

    return data

def insert_data(trie: Trie, data):
    for v in data:
        trie.insert(v)

trie = Trie()
data = read_data()

def main(args: list) -> None:
    # print(f'{args}')

    insert_data(trie, data)

if __name__ == "__main__":
    main(sys.argv[1:])


import requests
import os
import json

from dotenv import load_dotenv
load_dotenv()

# To set your enviornment variables in your terminal run the following line:
 #export 'BEARER_TOKEN'='<your_bearer_token>'
print(os.environ)

def auth():
    return os.environ.get('BEARER_TOKEN')

def create_url():
    return "https://api.twitter.com/2/tweets/sample/stream?"
query_params = {  'query': '#Alshabaab (Alshabaab OR shabaab OR Jihad OR Mujahidin OR mandera OR wajir -is:retweet) OR #Garrissa ',
'tweet.fields':   'author_id', }

def create_headers(bearer_token):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}
    return headers

def connect_to_endpoint(url, headers):
    response = requests.request("GET", url, headers=headers, stream=True)
    print(response.status_code)
    for response_line in response.iter_lines():
        if response_line:
            json_response = json.loads(response_line)
            print(json.dumps(json_response, indent=4, sort_keys=True))
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )

def main():
    bearer_token = auth()
    url = create_url()
    headers = create_headers(bearer_token)
    timeout = 0
    while True:
        connect_to_endpoint(url, headers)
        timeout += 1

if __name__ == "__main__":
    main()


import logging

import numpy as np

__author__ = 'frank.ma'

logger = logging.getLogger(__name__)

class RdmBivariate(object):
    @staticmethod
    def __check_rho(rho: float):
        if abs(rho) >= 1.0:
            raise ValueError('rho (%.4f) should be smaller than 1' % rho)

    @staticmethod
    def draw_std(rho: float, size: int):
        RdmBivariate.__check_rho(rho)
        x1 = np.random.random(size=size)
        x2 = np.random.random(size=size)
        return x1, rho * x1 + np.sqrt(1.0 - rho * rho) * x2

    @staticmethod
    def pdf(x_1: np.array, x_2: np.array, rho: float, mu_1: float = 0.0, mu_2: float = 0.0,
            sig_1: float = 1.0, sig_2: float = 1.0):
        RdmBivariate.__check_rho(rho)
        x_1_norm = (x_1 - mu_1) / sig_1
        x_2_norm = (x_2 - mu_2) / sig_2
        xx1, xx2 = np.meshgrid(x_1_norm, x_2_norm)
        z = (xx1 ** 2) - 2.0 * rho * xx1 * xx2 + (xx2 ** 2)
        return np.exp(-z / (2.0 * np.sqrt(1.0 - rho ** 2))) / (2.0 * np.pi * sig_1 * sig_2 * np.sqrt(1.0 - rho ** 2))


class Node:
    def __init__(self, l):
        self.l = l
        self.p = -1
        self.parents = {}
        self.encountered = False

class Solution:
    def networkDelayTime(self, times, N: int, K: int) -> int:
        """
        First create a hashmap representing the graph node.
        Then, iterate over every node and update the node P parameter if the parent P + distance to parent is less than the current P (or current P note defined).
        At the end of each iteration, if the graph state didn't change, stop the loop.

        Time complexity : ? (huge)
        Space complexity : O(N) where N is the number of node.
        """

        nodes = {n: Node(n) for n in range(1, N + 1)}

        for src, dst, t in times:
            nodes[dst].parents[src] = t
        nodes[K].p = 0

        while True:
            graph = {n: nodes[n].p for n in range(1, N + 1)}
            for n, node in nodes.items():
                for parent, dstToParent in node.parents.items():
                    parentNode = nodes[parent]
                    if parentNode.p == -1:
                        continue
                    if node.p == -1 or parentNode.p + dstToParent < node.p:
                        node.p = parentNode.p + dstToParent
            if graph == {n: nodes[n].p for n in range(1, N + 1)}:
                break

        if any(i.p == -1 for i in nodes.values()):
            return -1
        return max([i.p for i in nodes.values()])

    def networkDelayTime_dijkstra(self, times, N: int, K: int) -> int:
        """
        Resolve problem using Dijkstra algorithm.
        """

        graph = {
            n: [] for n in range(1, N + 1)
        }  # collections.defaultdict must be usefull to avoid too much space memory directly at the beginig of the script.
        for src, dst, t in times:
            graph[src].append((dst, t))

        distances = {n: float("inf") for n in range(1, N + 1)}
        distances[K] = 0  # starting point

        visited = [False] * (N + 1)

        while True:

            # find the nearest node

            minDist = float("inf")
            minNode = None  # index of the nearest node in the non visited nodes
            for i in range(1, N + 1):
                if not visited[i] and distances[i] < minDist:
                    minDist = distances[i]
                    minNode = i

            if minNode is None:
                break

            visited[minNode] = True

            # update the neighbors distance
            for dst, t in graph[minNode]:
                distances[dst] = min(distances[dst], distances[minNode] + t)

        # When the graph is all visited, we can fin the biggest value in distances dict
        maxDist = max(distances.values())
        return maxDist if maxDist < float("inf") else -1


# FastApi einbinden für REST-Services
from fastapi import FastAPI, APIRouter
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
# JSON Serialisierung
import orjson
# Pangas zur Daten-Anaylse
import pandas as pd
# GeoPandas für geometrische Funktionen
import geopandas
# Für geometrische Berechnungen
from shapely.geometry import Point
import math

####
## Rückgabe für Anfrage, wird automatisch in JSON serialisiert
###
class ORJSONResponse(JSONResponse):
    media_type = "application/json"

    ###
    ## Wird aufgerufen, wenn die Antwort zurück gegeben wird
    ###
    def render(self, content) -> bytes:
        return orjson.dumps(content)

# Einen Router erzeugen, damit man zwei bereiche der Anwendung (Frontend, Backend) im Pfad trennen kann
router = APIRouter()
# Definition des Backends
api_app = FastAPI(title="die Schnittstelle", default_response_class=ORJSONResponse)
api_app.include_router(router)
# Definition der Oberfläche
app = FastAPI(title="die Oberfläche")
app.mount('/api', api_app)
app.mount('/', StaticFiles(directory="./static", html=True), name="static")

###
## Diese Funktion nimmt Longitude und Latitude entgegen und findet Bewegungsdaten, die in der Nähe liegen.
## Es werden 30 Einträge zurück gegeben.
###
@api_app.get("/entfernung")
async def read_root(longitude: float, latitude: float):
    stationsdaten = pd.read_csv (r'./daten/2022-06-11-stations.csv')
    geodaten = geopandas.GeoDataFrame(stationsdaten, geometry=geopandas.points_from_xy(stationsdaten.longitude, stationsdaten.latitude, crs='epsg:4326'))

    mcs = geopandas.GeoDataFrame(geometry=[Point(float(longitude), float(latitude))], crs='epsg:4326')
    mcs = mcs.to_crs('EPSG:31469')
    umgewandelt = geodaten.to_crs('EPSG:31469')
    umgewandelt['entfernung'] = umgewandelt.geometry.apply(lambda g: math.floor(mcs.distance(g)))

    preisinformationen = pd.read_csv(r'./daten/2022-06-11-prices.csv')
    preisinformationen = preisinformationen.groupby('station_uuid').mean()
    bewegungsdaten = pd.merge(preisinformationen, umgewandelt, left_on='station_uuid', right_on='uuid')
    bewegungsdaten = bewegungsdaten.sort_values(by=['entfernung'], ascending=True)

    ergebnis = bewegungsdaten.head(30)
    print(ergebnis)

    # Ergebnis als Index Dictonary zurückgeben
    return ergebnis.to_dict('records')


from spillbrett import Spillebrett

def hovedprogram():
    bredde = int(input("Skriv inn bredde på brettet: "))
    hoyde = int(input("Skriv inn høyde på brettet: "))
    brett = Spillebrett(bredde, hoyde)
    brett.tegn_brett() # Skriv ut Generasjon 0

    kommando = hent_kommando()
    while kommando != "q":
        if kommando == "":
            brett.oppdatering()
            brett.tegn_brett()
            print("Antall levende celler:", str(brett.finn_antall_levende()))
        kommando = hent_kommando()

def hent_kommando():
    print("Kommandoer:")
    print("- Trykk enter for å gå videre til neste generasjon")
    print("- q: Avslutter programmet")
    print()
    return input("Hva vil du gjøre? ")

hovedprogram()


#!/usr/bin/python

from optparse import OptionParser
import logging
from time import sleep
import random
import sys

from formats import formats
from messages import messages

parser = OptionParser()
parser.add_option("-m","--mode", dest="mode")
parser.add_option("-f", "--format", dest="format",
                  help="logging format", metavar="FILE")
parser.add_option("-s", "--speed", dest="speed",
                  help="logging speed", metavar="FILE")
parser.add_option("-r", "--random_speed", dest="random_speed",
                  help="logging speed", metavar="FILE")
parser.add_option("-t", "--rotate", dest="rotate", default=True,
                  help="roTate between messages", action="store_true")
parser.add_option("-a", "--ascii", dest="ascii", default=False,
                  help="add ascii art")
(options, args) = parser.parse_args()

format = options.format or 'default'
mode = options.mode or 'default'
speed = options.speed or 'medium'
is_random_speed = options.random_speed or False
rotate_messages = options.rotate or False
use_ascii_art = options.ascii or False

speed_map = { 'slow':.5,
              'medium': .1,
              'fast':.01,
              'lurch':1,
              'glacial': 2,
            }

chug_speed = speed_map[speed]

logging.basicConfig(format=formats[format])
logger = logging.getLogger('tcpserver')

RANDOM_RANGES = {
    'dot_widths' : [3, 5, 7, 9, 13, 20,],
    'sleep_counts' : [.001, .01, .5, 1]
}

def get_random_num(choices=[]):
    random.shuffle(choices)
    return choices[0]

def nap(nap_type=None, is_random=is_random_speed):
    if is_random:
        sleep(get_random_num(choices=RANDOM_RANGES[nap_type]))
    else:
        sleep(chug_speed)
    return

def write_dots(is_random=True, dot_width=40):
    if is_random: dot_width = get_random_num(RANDOM_RANGES['dot_widths'])
    for x in xrange(0,dot_width):
        sys.stdout.write('. ')
        sys.stdout.flush()
        nap(nap_type='sleep_counts')
    sys.stdout.write("\n")

def render_ascii(ascii):
    for l in ascii:
        l = list(l)
        for c in range(0,len(l)):
            sys.stdout.write(l[c])
            sys.stdout.flush()
            nap(nap_type='sleep_counts')
    sys.stdout.write("\n")

def run():
    if use_ascii_art:
        import os
        ascii_dir = os.listdir('./ascii')
    while True:
        nap(nap_type='sleep_counts')
        if rotate_messages and not use_ascii_art:
            logger.warning(messages[get_random_num(messages.keys())])
            write_dots()
        elif use_ascii_art:
            random.shuffle(ascii_dir)
            ascii_file = './ascii/' + ascii_dir[0]
            ascii_image = open(ascii_file,'r').readlines()
            logger.warning(messages[get_random_num(messages.keys())])
            render_ascii(ascii_image)
        else:
            logger.warning(messages[mode])
            write_dots()

if __name__ == '__main__':
    run()


from hpp.corbaserver.rbprm.scenarios.demos.hyq_darpa_path import PathPlanner
from hpp.corbaserver.rbprm.scenarios.hyq_contact_generator import HyqContactGenerator

class ContactGenerator(HyqContactGenerator):
    def __init__(self):
        super().__init__(PathPlanner())

    def load_limbs(self):
        dict_heuristic = {
            self.fullbody.rLegId: "fixedStep04",
            self.fullbody.lLegId: "fixedStep04",
            self.fullbody.rArmId: "static",
            self.fullbody.lArmId: "static"
        }
        super().load_limbs(dict_heuristic, "ReferenceConfiguration")

    def compute_configs_from_guide(self):
        super().compute_configs_from_guide()
        self.q_init[2] = self.q_ref[2]
        self.q_goal[2] = self.q_ref[2]

if __name__ == "__main__":
    cg = ContactGenerator()
    cg.run()
    cg.play_guide_path()
    cg.display_sequence()


from enum import Enum
from singleton import Singleton
from datetime import datetime

Circuitstate = Enum("Circuitstate", ["CLOSED", "OPEN", 'HALFOPEN'])

class CircuitOpenException(Exception):
    pass

class Circuitbreaker(Singleton):
    """Circuitbreaker is singleton because if multiple functions are decorated
    with the same name, they should refer to the same circuit breaker, the name
    can be just an arbitrary string chosen by functions, or the hostname or url"""
    state = Circuitstate.CLOSED
    ts = datetime.now()

    def __new__(cls, name, timeout=None, retries=None):
        """Since the first invocation matters we ignore any paramters once set"""
        it = super().__new__(cls, name)
        it.timeout = getattr(it, "timeout", None) or timeout or 5
        it.retries = getattr(it, "retries", None) or retries or 2
        return it

    def __enter__(self):
        if not getattr(self, "_numtry", None):
            self._numtry = 0
        if self.state == Circuitstate.CLOSED:
            return self
        # broken circuit, if waited long enough then retry
        elapsed = (datetime.now() - self.ts).total_seconds()
        if elapsed > self.timeout:
            self.state = Circuitstate.HALFOPEN
            print("Timeout over, retrying as half open")
            self._numtry = self.retries
            return self
        print("Circuit open, not allowed")
        raise CircuitOpenException()

    def __exit__(self, extype, exval, extb):
        if not exval:
            if self.state ==  Circuitstate.HALFOPEN:
                self.state =  Circuitstate.CLOSED
            self._numtry = 0
            return True
        # we're here because of exception, if enough failed, break
        self._numtry += 1
        if self._numtry >= self.retries:
            print(
                f"Exception {extype}, {self._numtry} exceeded {self.retries} opening circuit"
            )
            self.ts = datetime.now()
            self.state = Circuitstate.OPEN
        else:
            print(f"Exception {extype} {exval}, retry count {self._numtry}")
        return True

    def __call__(self, function):
        """When a function is wrapped, we use the context manager ourselves"""
        async def wrapp(*args, **kwargs):
            try:
                with self:
                    return await function(*args, **kwargs)
            except CircuitOpenException:
                pass
            return None

        return wrapp

if __name__ == "__main__":
    x = Circuitbreaker("foo")
    y = Circuitbreaker("foo", 4)
    z = Circuitbreaker("bar")
    assert x is y
    print(x.timeout, y.timeout)
    assert x is not z


import os
import torch
import torch.nn.functional as F
import glob
import imageio
import numpy as np
from utils.data_utils import get_image_to_tensor, get_mask_to_tensor

class DVRDataset(torch.utils.data.Dataset):
    def __init__(self,
                 args,
                 mode,
                 list_prefix="softras_",
                 image_size=None,
                 scale_focal=True,
                 max_imgs=100000,
                 z_near=1.2,
                 z_far=4.0):
        super().__init__()
        self.args = args
        self.mode = mode
        self.base_dir = args.datadir

        use_source_lut = True if args.src_view is not None else False
        if use_source_lut:
            print("Using views from list", args.src_view)
            with open(args.src_view, "r") as f:
                tmp = [x.strip().split() for x in f.readlines()]
            self.source_lut = {
                x[0] + "/" + x[1]: torch.tensor(list(map(int, x[2:])), dtype=torch.long)
                for x in tmp
            }

        categories = [x for x in glob.glob(os.path.join(self.base_dir, "*")) if os.path.isdir(x)]
        obj_lists = [os.path.join(x, list_prefix + '{}.lst'.format(mode)) for x in categories]

        all_objs = []
        for obj_list in obj_lists:
            if not os.path.exists(obj_list):
                continue
            category_dir = os.path.dirname(obj_list)
            category = os.path.basename(category_dir)
            with open(obj_list, "r") as f:
                objs = [(category, os.path.join(category_dir, x.strip())) for x in f.readlines()]
            all_objs.extend(objs)

        self.all_objs = all_objs

        self.image_to_tensor = get_image_to_tensor()
        self.mask_to_tensor = get_mask_to_tensor()
        print("[Info] Loading DVR dataset: {}, mode: {}, "
              "type: {}, {} objects in total".format(self.base_dir,
                                                     mode,
                                                     "ShapeNet",
                                                     len(self.all_objs)))

        self.image_size = image_size
        self._coord_trans = torch.diag(torch.tensor([1, -1, -1, 1], dtype=torch.float32))
        self.scale_focal = scale_focal
        self.max_imgs = max_imgs

        self.z_near = z_near
        self.z_far = z_far
        self.lindisp = False

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

    def __getitem__(self, index):
        category, obj_dir = self.all_objs[index]

        rgb_paths = [x for x in glob.glob(os.path.join(obj_dir, "image", "*"))
                     if x.endswith(".jpg") or x.endswith(".png")]
        rgb_paths = sorted(rgb_paths)
        mask_paths = sorted(glob.glob(os.path.join(obj_dir, "mask", "*.png")))
        if len(mask_paths) == 0:
            mask_paths = [None] * len(rgb_paths)

        if len(rgb_paths) <= self.max_imgs:
            sel_indices = np.arange(len(rgb_paths))
        else:
            sel_indices = np.random.choice(len(rgb_paths), self.max_imgs, replace=False)
            rgb_paths = [rgb_paths[i] for i in sel_indices]
            mask_paths = [mask_paths[i] for i in sel_indices]

        cam_path = os.path.join(obj_dir, "cameras.npz")
        all_cam = np.load(cam_path)

        all_imgs = []
        all_poses = []
        all_masks = []
        all_bboxes = []
        focal = None

        for idx, (rgb_path, mask_path) in enumerate(zip(rgb_paths, mask_paths)):
            i = sel_indices[idx]
            img = imageio.imread(rgb_path)[..., :3]
            if self.scale_focal:
                x_scale = img.shape[1] / 2.0
                y_scale = img.shape[0] / 2.0
                xy_delta = 1.0
            else:
                x_scale = y_scale = 1.0
                xy_delta = 0.0

            if mask_path is not None:
                mask = imageio.imread(mask_path)
                if len(mask.shape) == 2:
                    mask = mask[..., None]
                mask = mask[..., :1]

            # ShapeNet
            wmat_inv_key = "world_mat_inv_" + str(i)
            wmat_key = "world_mat_" + str(i)
            if wmat_inv_key in all_cam:
                extr_inv_mtx = all_cam[wmat_inv_key]
            else:
                extr_inv_mtx = all_cam[wmat_key]
                if extr_inv_mtx.shape[0] == 3:
                    extr_inv_mtx = np.vstack((extr_inv_mtx, np.array([0, 0, 0, 1])))
                extr_inv_mtx = np.linalg.inv(extr_inv_mtx)

            intr_mtx = all_cam["camera_mat_" + str(i)]
            fx, fy = intr_mtx[0, 0], intr_mtx[1, 1]
            assert abs(fx - fy) < 1e-9
            fx = fx * x_scale
            if focal is None:
                focal = fx
            else:
                assert abs(fx - focal) < 1e-5
            pose = extr_inv_mtx

            pose = torch.tensor(pose, dtype=torch.float32) @ self._coord_trans

            img_tensor = self.image_to_tensor(img)
            if mask_path is not None:
                mask_tensor = self.mask_to_tensor(mask)

                rows = np.any(mask, axis=1)
                cols = np.any(mask, axis=0)
                rnz = np.where(rows)[0]
                cnz = np.where(cols)[0]
                if len(rnz) == 0:
                    raise RuntimeError("ERROR: Bad image at", rgb_path, "please investigate!")
                rmin, rmax = rnz[[0, -1]]
                cmin, cmax = cnz[[0, -1]]
                bbox = torch.tensor([cmin, rmin, cmax, rmax], dtype=torch.float32)
                all_masks.append(mask_tensor)
                all_bboxes.append(bbox)

            all_imgs.append(img_tensor)
            all_poses.append(pose)

        if mask_path is not None:
            all_bboxes = torch.stack(all_bboxes)

        all_imgs = torch.stack(all_imgs)
        all_poses = torch.stack(all_poses)
        if len(all_masks) > 0:
            all_masks = torch.stack(all_masks)
        else:
            all_masks = None

        if self.image_size is not None and all_imgs.shape[-2:] != self.image_size:
            scale = self.image_size[0] / all_imgs.shape[-2]
            focal *= scale

            if mask_path is not None:
                all_bboxes *= scale

            all_imgs = F.interpolate(all_imgs, size=self.image_size, mode="area")
            if all_masks is not None:
                all_masks = F.interpolate(all_masks, size=self.image_size, mode="area")

        H, W = all_imgs.shape[-2:]

        if self.args.src_view is None:
            src_view = np.random.choice(len(rgb_paths), 1)[0]
        else:
            # src_view = int(self.args.src_view)
            obj_id = category + "/" + os.path.basename(obj_dir)
            src_view = self.source_lut[obj_id]

        src_img = all_imgs[src_view:src_view+1]
        src_pose = all_poses[src_view:src_view+1]
        # src_mask = all_masks[src_view:src_view+1]
        # src_bbox = all_bboxes[src_view:src_view+1]
        src_path = rgb_paths[src_view]

        K = np.array([[focal, 0., W // 2, 0.],
                      [0., focal, H // 2, 0],
                      [0., 0, 1, 0],
                      [0, 0, 0, 1]]).astype(np.float32)
        intrinsics = torch.from_numpy(K).view(1, 4, 4).repeat(len(all_imgs), 1, 1)
        depth_range = torch.tensor([self.z_near, self.z_far], dtype=torch.float32).view(1, -1).repeat(len(all_imgs), 1)

        ret = {
            "obj_dir": obj_dir,
            "category": category,
            "index": index,
            "intrinsics": intrinsics,
            "rgb_paths": rgb_paths,
            "images": all_imgs,
            "poses": all_poses,
            "depth_range": depth_range,
            "src_view": src_view,
            "src_path": src_path,
            "src_image": src_img,
            # "src_mask": src_mask,
            "src_pose": src_pose,
            # "src_bbox": src_bbox
        }
        if all_masks is not None:
            ret["masks"] = all_masks

        ret["bboxes"] = all_bboxes
        return ret


from flask import  Blueprint
from flask import  render_template,request,redirect,url_for
from models import product as pd
from .forms import ProductForm
from app import db
products = Blueprint('products', __name__, template_folder='templates')

@products.route('/', methods=['GET','POST'])
def index():
    if request.method == 'POST':
        lname = request.form['search']
        return redirect(url_for('customers.searsh' ,lname=lname))
    else:
        return render_template('products/index.html')

@products.route('/addProduct', methods = ['GET','POST'])
def addProduct():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
    #    article_number = request.form['article_number']
        quantity = request.form['quantity']

        newProduct = pd(title=title,description=description, quantity=quantity)
        db.session.add(newProduct)
        db.session.commit()

        return redirect(url_for('products.index'))
    else:
        form = ProductForm()
        return render_template('products/addProduct.html', form = form)

@products.route('/listOfProducts')
def listOfProducts():
    products = pd.query.all()
    return render_template('products/listOfProducts.html', products = products)


import calendar
cal = calendar.month(2020, 4)
print(cal)

import math
result = math.sqrt(100)
print(result)

def ggininder(x, y):
    if x < y:
        return ("hard")
    else:
        return ("soft")

result = ggininder(12,700)
print(result)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import torch
import torch.nn.functional as F

from layers.utils import loss_tools
from layers.box_annotation_layer import annotate_proposals

def rcnn_loss_layer(score, delta, label_list, fg_delta_list, index_list):
    # score (p, c)
    # delta (p, c, 4)
    # label_list list(n, l) sum(l) == k
    # fg_delta_list list(n, l1, 4)
    # index_list List[Tuple[Tensor, Tensor]]
    # return loss()
    p, num_class = score.shape[:2]
    reg_loss, cls_loss = torch.tensor(0.), torch.tensor(0.)
    n = len(index_list)

    # labels = torch.cat(label_list)
    for i in range(n):
        label = label_list[i]
        fg_i, bg_i = index_list[i]
        index = torch.cat((fg_i, bg_i))
        # (k,)
        cls_loss += F.cross_entropy(score[index], label)

        # (l1, 4)
        fg_delta_i = fg_delta_list[i]
        for j in range(1, num_class + 1):
            index_j = torch.where(label == j)
            x = fg_i[index_j]
            if x.shape[0] == 0:
                continue
            pred_delta_j = delta[x, j]
            gt_delta_j = fg_delta_i[index_j]
            if pred_delta_j.shape[0] > 0:
                reg_loss += loss_tools.smooth_l1_loss(pred_delta_j, gt_delta_j)

    return reg_loss + cls_loss

def compute(model, score, bbox, gt_label, gt_bbox):
    label_list, fg_delta_list, index_list = \
        annotate_proposals(model.rois_list, gt_bbox, gt_label)
    rcnn_loss = rcnn_loss_layer(score, bbox, label_list, fg_delta_list, index_list)
    return rcnn_loss

if __name__ == '__main__':
    import time
    from rcnn import RCNN
    from resnet import resnet18
    from torch import nn

    resnet = resnet18()

    feature_extractor = nn.Sequential(
        resnet.conv1,
        resnet.bn1,
        resnet.relu,
        resnet.maxpool,
        resnet.layer1,
        resnet.layer2,
        resnet.layer3
    )

    # noinspection PyUnresolvedReferences
    conv_to_head = nn.Sequential(
        resnet.layer4,
        resnet.avgpool,
        nn.Flatten(),
    )

    config = {
        'feature_stride': 16,
        'feature_compress': 1 / 16,
        'num_feature_channel': 256,
        'num_fc7_channel': 512,
        'num_rpn_channel': 512,
        'num_anchor': 9,
        'score_top_n': 100,
        'nms_top_n': 50,
        'nms_thresh': 0.7,
        'pool_out_size': 8,
        'num_class': 5,
        'radios': (0.5, 1, 2),
        'scales': (8, 16, 32),
    }

    model_ = RCNN(feature_extractor, conv_to_head, config)

    n_ = 10
    image = torch.rand((n_, 3, 128, 128))

    model_.total_mode()
    # score_(k, num_cls) delta_(k, num_cls, 4)
    score_, delta_ = model_.forward(image)
    print(score_.shape, delta_.shape)

    gt_bbox_ = torch.randint(0, 8 * 16, (n_, 8, 4)).sort(dim=2)[0].float()
    gt_label_ = torch.randint(1, config['num_class'], (n_, 8))
    label_list_, fg_delta_list_, index_list_ = annotate_proposals(model_.rois_list, gt_bbox_, gt_label_)
    print(label_list_[0].shape, fg_delta_list_[0].shape, index_list_[0][0].shape, index_list_[0][1].shape)
    t = time.time()
    loss_ = rcnn_loss_layer(score_, delta_, label_list_, fg_delta_list_, index_list_)
    print(time.time() - t)
    print(loss_)


# 목적지에 도달 가능한가 여부를 판단하면 되므로
# dfs로 문제를 푼다.

import sys

sys.stdin = open('input.txt')

def dfs(here, end):
    # here : [r, c]
    # 현재 위치 방문 체크
    maze[here[0]][here[1]] = 1

    # 현재 위치가 목적지라면 return 1 (도달 가능)
    if here == end:
        return 1

    # 델타 방식의 탐색
    # 시계방향
    # 위, 오, 아래, 왼
    dr = [-1, 0, 1, 0]
    dc = [0, 1, 0, -1]

    # 후보군
    candidate = []

    # 현재 위치를 기준으로 네 방향으로 탐색하며 현재 위치에서 갈 수 있는 후보군을 선정
    # 후보군을 각각 돌면서 재귀로 깊이 탐색

    # 갈 수 있는 곳 : 나아갈 방향의 좌표값이 미로 범위 안에 있고, 1(벽)이 아닐 때
    # 그리고 이전에 방문한 곳이 아닌 곳!
    for dir in range(4):
        r = here[0] + dr[dir]
        c = here[1] + dc[dir]

        if 0 <= r < 16 and 0 <= c < 16 and maze[r][c] != 1:
            candidate.append([r, c])

    for go in candidate:
        next_place = dfs(go, end)
        if next_place: # 다음 장소가 목적지라면?
            return 1 # 도달 가능 1 리턴('목적지!')

    # 후보군을 모두 돌았는데도 목적지가 나오지 않으면
    return 0

for tc in range(1, 11):
    test_case = int(input())
    maze = [list(map(int, input())) for _ in range(16)]

    # 시작점과 목적지 탐색
    start = []
    end = []
    for row in range(16):
        for col in range(16):
            if maze[row][col] == 2: # 시작점
                start = [row, col]
            elif maze[row][col] == 3: # 도착점
                end = [row, col]

    print('#{} {}'.format(tc, dfs(start, end)))


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

import os
import test
import functools
from unittest.loader import TestLoader
from baseCase.case import BaseTest

class BaseLoader(TestLoader):
    def loadTestsFromTestCase(self, testCaseClass):
        def isTestMethod(arr, testClass=testCaseClass):
            return arr[:4].lower().startswith('test') and callable(
                getattr(testClass, arr)) or arr == "runTest" and callable(getattr(testClass, arr))
        testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        loaded_suite = self.suiteClass(map(testCaseClass, testFnNames))
        return loaded_suite

    def loadTestsFromModule(self, module, *args, pattern=None, **kws):
        dir_name = os.listdir(os.path.dirname(module.__file__))
        tests1 = [n[:-3] for n in dir_name if n.lower().startswith("test")]
        [__import__("".join([str(module.__package__), '.', i]), fromlist=True) for i in tests1]
        itests = self.suiteClass(map(self.loadTestsFromTestCase, BaseTest.__subclasses__()))
        return itests

baseLoder = BaseLoader()

if __name__ == "__main__":
    b = BaseLoader()
    s = b.loadTestsFromModule(test)
    print(s)
    # unittest.TextTestRunner(verbosity=2).run(s)


# -*- coding: utf-8 -*-
from contextlib import contextmanager
try:
    from typing import Type
except ImportError:  # Python 2.x
    pass

import redis
import datetime
from bitmapist4 import events as ev

class Bitmapist(object):
    """
    Core bitmapist object
    """

    # Should hourly be tracked as default?
    # Note that this can have huge implications in amounts
    # of memory that Redis uses (especially with huge integers)
    track_hourly = False

    # Should unique events be tracked as default?
    track_unique = False

    def __init__(self,
                 connection_or_url=redis.StrictRedis(),
                 track_hourly=False,
                 track_unique=True,
                 finished_ops_expire=3600 * 24,
                 unfinished_ops_expire=60,
                 key_prefix='bitmapist_'):
        if isinstance(connection_or_url, redis.StrictRedis):
            self.connection = connection_or_url
        else:
            self.connection = redis.StrictRedis.from_url(connection_or_url)
        self.track_hourly = track_hourly
        self.track_unique = track_unique
        self.finished_ops_expire = finished_ops_expire
        self.unfinished_ops_expire = unfinished_ops_expire
        self.key_prefix = key_prefix
        self.pipe = None

        kw = {'bitmapist': self}
        self.UniqueEvents = type('UniqueEvents', (ev.UniqueEvents, ),
                                 kw)  # type: Type[ev.UniqueEvents]
        self.YearEvents = type('YearEvents', (ev.YearEvents, ),
                               kw)  # type: Type[ev.YearEvents]
        self.MonthEvents = type('MonthEvents', (ev.MonthEvents, ),
                                kw)  # type: Type[ev.MonthEvents]
        self.WeekEvents = type('WeekEvents', (ev.WeekEvents, ),
                               kw)  # type: Type[ev.WeekEvents]
        self.DayEvents = type('DayEvents', (ev.DayEvents, ),
                              kw)  # type: Type[ev.DayEvents]
        self.HourEvents = type('HourEvents', (ev.HourEvents, ),
                               kw)  # type: Type[ev.HourEvents]
        self.BitOpAnd = type('BitOpAnd', (ev.BitOpAnd, ),
                             kw)  # type: Type[ev.BitOpAnd]
        self.BitOpOr = type('BitOpOr', (ev.BitOpOr, ),
                            kw)  # type: Type[ev.BitOpOr]
        self.BitOpXor = type('BitOpXor', (ev.BitOpXor, ),
                             kw)  # type: Type[ev.BitOpXor]
        self.BitOpNot = type('BitOpNot', (ev.BitOpNot, ),
                             kw)  # type: Type[ev.BitOpNot]

    def mark_event(self,
                   event_name,
                   uuid,
                   timestamp=None,
                   track_hourly=None,
                   track_unique=None):
        """
        Marks an event as "happened" for a specific moment. The function
        stores the event for the day, week and month, and optionally
        for the hour, as well as the unique event.

        - event_name is the name of the event to track
        - uuid is the unique id of the subject (typically user id). The id
          should not be huge
        - timestamp is an optional moment of time which date should be used as
          a reference point, default is to `datetime.utcnow()`

        Examples:

            # Mark id 1 as active
            b.mark_event('active', 1)

            # Mark task completed for id 252
            b.mark_event('tasks:completed', 252)
        """
        self._mark(event_name, uuid, timestamp, 1, track_hourly, track_unique)

    def unmark_event(self,
                     event_name,
                     uuid,
                     timestamp=None,
                     track_hourly=None,
                     track_unique=None):
        """
        Marks an event as "not happened" for a specific moment. The function
        stores the event for the day, week and month, and optionally
        for the hour, as well as the unique event.
        """
        self._mark(event_name, uuid, timestamp, 0, track_hourly, track_unique)

    def _mark(self, event_name, uuid, timestamp, value, track_hourly,
              track_unique):
        if timestamp is None:
            timestamp = datetime.datetime.utcnow()
        if track_hourly is None:
            track_hourly = self.track_hourly
        if track_unique is None:
            track_unique = self.track_unique

        obj_classes = [self.MonthEvents, self.WeekEvents, self.DayEvents]
        if track_hourly:
            obj_classes.append(self.HourEvents)
        if track_unique:
            obj_classes.append(self.UniqueEvents)

        if self.pipe is None:
            pipe = self.connection.pipeline()
        else:
            pipe = self.pipe

        for obj_class in obj_classes:
            pipe.setbit(
                obj_class.from_date(event_name, timestamp).redis_key, uuid,
                value)

        if self.pipe is None:
            pipe.execute()

    def start_transaction(self):
        if self.pipe is not None:
            raise RuntimeError("Transaction already started")
        self.pipe = self.connection.pipeline()

    def commit_transaction(self):
        if self.pipe is None:
            raise RuntimeError("Transaction not started")
        self.pipe.execute()
        self.pipe = None

    def rollback_transaction(self):
        self.pipe = None

    @contextmanager
    def transaction(self):
        self.start_transaction()
        try:
            yield
            self.commit_transaction()
        except:
            self.rollback_transaction()
            raise

    def mark_unique(self, event_name, uuid):
        """
        Mark unique event as "happened with a user"

        Unique event (aka "user flag") is an event which doesn't depend on date.
        Can be used for storing user properties, A/B testing, extra filtering,
        etc.

        - event_name: The name of the event, could be "active" or "new_signups"
        - uuid:  a unique id, typically user id. The id should not be huge

        Example:

            # Mark id 42 as premium
            b.mark_unique('premium', 42)
        """
        self._mark_unique(event_name, uuid, value=1)

    def unmark_unique(self, event_name, uuid):
        """
        Mark unique event as "not happened with a user"

        Unique event (aka "user flag") is an event which doesn't depend on date.
        Can be used for storing user properties, A/B testing, extra filtering,
        etc.

        - event_name: The name of the event, could be "active" or "new_signups"
        - uuid:  a unique id, typically user id. The id should not be huge

        Example:

            # Mark id 42 as premium
            b.unmark_unique('premium', 42)
        """
        self._mark_unique(event_name, uuid, value=0)

    def _mark_unique(self, event_name, uuid, value):
        conn = self.connection if self.pipe is None else self.pipe
        redis_key = self.UniqueEvents(event_name).redis_key
        conn.setbit(redis_key, uuid, value)

    def get_event_names(self, prefix='', batch=10000):
        """
        Return the list of all event names, with no particular order. Optional
        `prefix` value is used to filter only subset of keys
        """
        expr = '{}{}*'.format(self.key_prefix, prefix)
        ret = set()
        for result in self.connection.scan_iter(match=expr, count=batch):
            result = result.decode()
            chunks = result.split('_')
            event_name = '_'.join(chunks[1:-1])
            if not event_name.startswith('bitop_'):
                ret.add(event_name)
        return sorted(ret)

    def delete_all_events(self):
        """
        Delete all events from the database.
        """
        keys = self.connection.keys('{}*'.format(self.key_prefix))
        if keys:
            self.connection.delete(*keys)

    def delete_temporary_bitop_keys(self):
        """
        Delete all temporary keys that are used when using bit operations.
        """
        keys = self.connection.keys('{}bitop_*'.format(self.key_prefix))
        if keys:
            self.connection.delete(*keys)

    def prefix_key(self, event_name, date):
        return '{}{}_{}'.format(self.key_prefix, event_name, date)


import numpy
import random
import OpenGL
import math
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import definitions
from definitions import *

def reflection_at_y(triangle):
    triangle_matrix = numpy.array(definitions.get_triangle_coordinates_list(triangle))
    reflect_matrix = numpy.array([[1, 0], [0, -1]])
    new_co_ords = numpy.mat(triangle_matrix) * numpy.mat(reflect_matrix)
    A = Point(new_co_ords[0, 0], new_co_ords[0, 1])
    B = Point(new_co_ords[1, 0], new_co_ords[1, 1])
    C = Point(new_co_ords[2, 0], new_co_ords[2, 1])
    return Triangle(A, B, C)

def reshape(_w, _h):
    glViewport(0, 0, _w, _h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(60.0, _w/_h, 1.0, 20.0)
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    gluLookAt(0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glTranslatef(0.0, 0.0, 0.0)
    glColor3f(1.0, 1.0, 1.0)

    triangle = Triangle(Point(0, 3), Point(3, 0), Point(-3, 0))

    glColor3f(1.0, 1.0, 1.0)
    glBegin(GL_LINE_LOOP)
    A = triangle.getPointA()
    B = triangle.getPointB()
    C = triangle.getPointC()
    glVertex2f(A.getX(), A.getY())
    glVertex2f(B.getX(), B.getY())
    glVertex2f(C.getX(), C.getY())
    glEnd()

    reflected_triangle = reflection_at_y(triangle)
    glColor3f(0.0, 1.0, 1.0)
    glBegin(GL_LINE_LOOP)
    A = reflected_triangle.getPointA()
    B = reflected_triangle.getPointB()
    C = reflected_triangle.getPointC()
    glVertex2f(A.getX(), A.getY())
    glVertex2f(B.getX(), B.getY())
    glVertex2f(C.getX(), C.getY())
    glEnd()

    glutSwapBuffers()

glutInit()
glutInitDisplayMode(GLUT_RGBA)
glutInitWindowSize(500, 500)
glutInitWindowPosition(100, 0)
wind = glutCreateWindow("Reflection")
glutDisplayFunc(display)
glutReshapeFunc(reshape)
gluOrtho2D(0.0,250.0,0.0,300.0)
glutMainLoop()


import math

income = float(input())
grade = float(input())
minimal_wage = float(input())

Socialscholarship = 0.35*minimal_wage
Socialscholarship = math.floor(Socialscholarship)
results = grade * 25
results = math.floor(results)

if (grade < 4.5) or \
        ((income > minimal_wage) & (grade < 5.5)):

    print("You cannot get a scholarship!")

elif ((grade < 5.5) & (income < minimal_wage)) or \
        ((grade >= 5.5) & (Socialscholarship > results) & (income <= minimal_wage)):

    print(f"You get a Social scholarship {Socialscholarship:.0f} BGN")

#elif ((grade >= 5.5) & (income >= minimal_wage)) or \
     #   ((grade >= 5.5) & (Socialscholarship <= results) & (income <= minimal_wage)):
else:
    print(f"You get a scholarship for excellent results {results:.0f} BGN")


from django.conf.urls import include, url
from django.views.generic import RedirectView

from . import views

person = [
    url(r'^$', views.PersonList.as_view(), name='person-list'),
    url(r'^new/$', views.PersonCreate.as_view(), name='person-create'),
    url(r'^(?P<pk>[^/]+)/$', views.PersonDetail.as_view(), name='person-detail'),
    url(r'^(?P<pk>[^/]+)/delete/$', views.PersonDelete.as_view(), name='person-delete'),
    url(r'^(?P<pk>[^/]+)/edit/$', views.PersonEdit.as_view(), name='person-edit'),
    url(r'^(?P<pk>[^/]+)/volunteer/$', views.VolunteerCreate.as_view(), name='volunteer-create'),
    url(r'^(?P<pk>[^/]+)/recipient/$', views.RecipientCreate.as_view(), name='recipient-create'),
    url(r'^(?P<pk>[^/]+)/member/$', views.MemberCreate.as_view(), name='member-create'),
    url(r'^(?P<pk>[^/]+)/membership/$', views.MembershipCreate.as_view(), name='membership-create'),
]

recipient = [
    url(r'^$', views.RecipientList.as_view(), name='recipient-list'),
    url(r'^(?P<pk>\d+)/$', views.RecipientDetail.as_view(), name='recipient-detail'),
    url(r'^(?P<pk>\d+)/delete/$', views.RecipientDelete.as_view(), name='recipient-delete'),
    url(r'^(?P<pk>\d+)/edit/$', views.RecipientEdit.as_view(), name='recipient-edit'),
    url(r'^(?P<pk>\d+)/custodian/$', views.CustodianCreate.as_view(), name='custodian-create'),
]

volunteer = [
    url(r'^$', views.VolunteerList.as_view(), name='volunteer-list'),
    url(r'^(?P<pk>\d+)/$', views.VolunteerDetail.as_view(), name='volunteer-detail'),
    url(r'^(?P<pk>\d+)/delete/$', views.VolunteerDelete.as_view(), name='volunteer-delete'),
    url(r'^(?P<pk>\d+)/edit/$', views.VolunteerEdit.as_view(), name='volunteer-edit'),
]

member = [
    url(r'^$', views.MemberList.as_view(), name='member-list'),
    url(r'^(?P<pk>\d+)/$', views.MemberDetail.as_view(), name='member-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.MemberEdit.as_view(), name='member-edit'),
]

custodian = [
    url(r'^(?P<pk>\d+)/$', views.CustodianDetail.as_view(), name='custodian-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.CustodianEdit.as_view(), name='custodian-edit'),
]

membership = [
    url(r'^(?P<pk>\d+)/$', views.MembershipDetail.as_view(), name='membership-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.MembershipEdit.as_view(), name='membership-edit'),
]

project = [
    url(r'^$', views.ProjectList.as_view(), name='project-list'),
    url(r'^(?P<pk>\d+)/$', views.ProjectDetail.as_view(), name='project-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.ProjectEdit.as_view(), name='project-edit'),
    url(r'^new/$', views.ProjectCreate.as_view(), name='project-create'),
]

group = [
    url(r'^$', views.GroupList.as_view(), name='group-list'),
    url(r'^(?P<pk>\d+)/$', views.GroupDetail.as_view(), name='group-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.GroupEdit.as_view(), name='group-edit'),
    url(r'^new/$', views.GroupCreate.as_view(), name='group-create'),
]

event = [
    url(r'^$', views.EventList.as_view(), name='event-list'),
    url(r'^(?P<pk>\d+)/$', views.EventDetail.as_view(), name='event-detail'),
    url(r'^(?P<pk>\d+)/edit/$', views.EventEdit.as_view(), name='event-edit'),
    url(r'^new/$', views.EventCreate.as_view(), name='event-create'),
]

ajax = [
    url(r'^person/', views.AjaxPersonList.as_view()),
]

urlpatterns = [
    url(r'^ajax/', include(ajax)),
    url(r'^person/', include(person)),
    url(r'^recipient/', include(recipient)),
    url(r'^volunteer/', include(volunteer)),
    url(r'^member/', include(member)),
    url(r'^custodian/', include(custodian)),
    url(r'^membership/', include(membership)),
    url(r'^group/', include(group)),
    url(r'^project/', include(project)),
    url(r'^event/', include(event)),

    url(r'^$', RedirectView.as_view(url='login/')),
    url(r'^missing_doc/$', views.missing_doc, name='missing_doc'),

    url(r'^login/$', views.Login.as_view(), name='login'),
    url(r'^logout/$', views.Logout.as_view(), name='logout'),
    url(r'^home/$', views.Home.as_view(), name='home'),
    url(r'^basicformnewperson/$', views.NewIndividualMember.as_view(), name='basicformnewperson'),
    url(r'^basicformnewfamily/$', views.NewFamilyMember.as_view(), name='basicformnewfamily'),
    url(r'^membership/$', views.MembershipList.as_view(), name='membership-list'),
    url(r'^membership/(?P<pk>[^/]+)/$', views.MembershipDetail.as_view(), name='membership-detail'),

]


from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import numpy
import math
import sys
sys.setrecursionlimit(16000)
from Algorithms.circle_algorithms import circle_algorithms
def init():
    glClearColor(0.0,0.0,0.0,0.0)
    glMatrixMode
    (GL_PROJECTION)
    gluOrtho2D(0,640,0,480)

def bound_it(x,y,fillColor,bc):
    color=glReadPixels(x,y,1.0,1.0,GL_RGB,GL_FLOAT)
    if((color!=bc).any() and (color!=fillColor).any()):
        glColor3f(fillColor[0],fillColor[1],fillColor[2])
        glBegin(GL_POINTS)
        glVertex2i(x,y)
        glEnd()
        glFlush()

        bound_it(x+1,y,fillColor,bc)
        bound_it(x-1,y,fillColor,bc)
        bound_it(x,y+1,fillColor,bc)
        bound_it(x,y-1,fillColor,bc)

def mouse(btn,state,x,y):
    y = 480-y
    if(btn==GLUT_LEFT_BUTTON):
        if(state==GLUT_DOWN):
              bCol= [1,0,0]
              color= [1,0,1]
              bound_it(x,y,color,bCol)

def world():
    glLineWidth(2)
    glPointSize(1.0)
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(1,0,0)
    glBegin(GL_POINTS)
    circle = circle_algorithms(40.0, 250, 250)
    circle.parameteric_circle()
    glEnd()
    glFlush()

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)
    glutInitWindowSize(640,480)
    glutInitWindowPosition(200,200)
    glutCreateWindow(b'flood fill and boundary fill')
    glutDisplayFunc(world)
    glutMouseFunc(mouse)
    init()
    glutMainLoop()

main()


from faker import Faker
from git_class.models_new.database import create_db, Session
from git_class.models_new.car import Car
from git_class.models_new.info_car import InfoCar

def create_database(load_fake_data=True):
    create_db()
    if load_fake_data:
        _load_fake_data(Session())

def _load_fake_data(session):
    car_names = ['BMW', 'Audi', 'Mercedes', 'Lada', 'Opel', 'Ford', 'Honda', 'Lexus']

    for i in car_names:
        cars_n = Car(model=i)
        session.add(cars_n)
    session.commit()
    faker = Faker('ru_RU')

    for i in range(len(car_names)):
        colors = faker.color()
        forces = faker.random.randint(110, 250)
        names = faker.name()
        info = InfoCar(colors, forces, names)
        session.add(info)
    session.commit()
    session.close()


import os
from flask import Blueprint, request, make_response
from werkzeug.utils import secure_filename
from uploadFileTask import handle_file

from ..models import db,Products
import pandas as pd
#from uploadFileTask import handle_file
from multiprocessing.pool import ThreadPool as Pool
upload_products = Blueprint('upload',  __name__,
                        template_folder='templates')

t = Pool(processes=20)

@upload_products.route('/upload', methods=['POST'])
def upload():
    # Remember the paramName was set to 'file', we can use that here to grab it
    file = request.files['file']
    filename = secure_filename(file.filename)
    print(filename)
    # secure_filename makes sure the filename isn't unsafe to save
    save_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), secure_filename(file.filename))
    current_chunk = int(request.form['dzchunkindex'])
    print("chunck ",current_chunk)
    print("chunk total count",)
    if os.path.exists(save_path) and current_chunk == 0:
            os.remove(save_path)
    with open(save_path, 'ab') as f:
        # Goto the offset, aka after the chunks we already wrote
        f.seek(int(request.form['dzchunkbyteoffset']))
        data=file.stream.read()
        f.write(data)
    if current_chunk ==(int(request.form['dztotalchunkcount'])-1):
         #t1 = threading.Thread(target=store_data_in_db, args=(save_path,db))
         #t1.start()
         # t1.join()
         #store_data_in_db(save_path)
         # t.join()
         # t.close()
         #handle_file.send(save_path)
         handle_file(save_path)
    return make_response(('Chunk', 200))

def handle_file(save_path):
    f = get_next_record(save_path)
    for i in f:
        t.map(store_in_db, (i,))

def get_next_record(file):
    df = pd.read_csv(file, sep=',')
    print(df.head(5))
    df=df.drop_duplicates(subset='sku', keep='first')
    inc=j=int(df.shape[0]/100)
    i=0
    for _ in range(100):
        yield df[i:j]
        i+=inc
        j+=inc

def store_in_db(dataset):
    products=[]
    #dataset.drop_duplicates(subset='sku', keep="last")
    for index, data in dataset.iterrows():
        products.append(Products(name=data[0], sku=data[1], description=data[2]))
        #db.session.merge(record)
    try:
        db.session.bulk_save_objects(products)
        db.session.commit()
    except Exception as e:
        print(e)

def store_data_in_db(file,db):
    Products.query.delete()
    db.session.commit()
    import pandas as pd
    df = pd.read_csv(file, sep=',', header=None)
    try:
          for index, row in df.iterrows():
                 record = Products(name=row[0], sku=row[1], description=row[2])
                 db.session.merge(record)
    except Exception as e :
                 print(e)
    db.session.commit()


# This code is modified from https://github.com/haoheliu/DCASE_2022_Task_5

# This code is modified from  DCASE 2022 challenge https://github.com/c4dm/dcase-few-shot-bioacoustic

import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from src.models.meta_learning import BaseModel
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
import pandas as pd
from src.evaluation_metrics.evaluation import *
from src.utils.feature_extractor import *
import time
from sklearn.metrics import classification_report, f1_score
from src.utils.post_processing import *
from src.evaluation_metrics.evaluation_confidence_intervals import *
from copy import deepcopy
import random
import torch.optim as optim
import h5py
from src.models.triplet_loss import *

class TriNet(BaseModel):
    def __init__(self, config):
        super(TriNet, self).__init__(config)

        self.test_loop_batch_size = config.val.test_loop_batch_size
        # self.loss_fn = TripletLossHard(margin= self.config.train.margin)
        self.loss_fn = TripletLoss(margin= self.config.train.margin)

        self.approx = True
        self.ce = nn.CrossEntropyLoss()
        self.cosloss = nn.CosineEmbeddingLoss(margin= 0.95)
    # def inner_loop(self, support_data, support_label = None, mode = 'train'):
    #     local_model = deepcopy(self.feature_extractor)
    #     local_model.train()
    #     local_optim = optim.SGD(local_model.par
    # ameters(), self.config.train.lr_inner, momentum = self.config.train.momentum, weight_decay=self.config.train.weight_decay)
    #     local_optim.zero_grad()
    #     fast_parameters = list(local_model.parameters())
    #     if mode == 'test':
    #         support_label = support_label.cpu().numpy()
    #     for i in range(100):
    #         if mode == 'train':
    #             label = random.randint(0, 1)
    #             # same class
    #             if label == 0:
    #                 class1 = random.randint(0, self.n_way - 1)
    #                 indices1 = [i for i in range(len(support_data)) if i % self.n_way == class1]
    #                 index1, index2 = random.sample(indices1, 2)

    #                 sampl1 = support_data[index1]
    #                 sampl2 = support_data[index2]

    #             else:
    #                 class1, class2 = random.sample(range(self.n_way), 2)

    #                 indices1 = [i for i in range(len(support_data)) if i % self.n_way == class1]
    #                 indices2 = [i for i in range(len(support_data)) if i % self.n_way == class2]

    #                 # Randomly select two different indices
    #                 index1 = random.sample(indices1, 1)
    #                 index2 = random.sample(indices2, 1)

    #                 sampl1 = support_data[index1[0]]
    #                 sampl2 = support_data[index2[0]]

    #         else:

    #             label = random.randint(0, 1)
    #             # same class
    #             if label == 0:
    #                 class1 = random.randint(0, 1)
    #                 indices1 = np.where(support_label == class1)[0].tolist()
    #                 index1, index2 = random.sample(indices1, 2)

    #                 sampl1 = support_data[index1]
    #                 sampl2 = support_data[index2]
    #             else:
    #                 class1 = 0
    #                 class2 = 1

    #                 indices1 = np.where(support_label == class1)[0].tolist()

    #                 indices2 = np.where(support_label == class2)[0].tolist()

    #                 # Randomly select two different indices
    #                 index1 = random.sample(indices1, 1)
    #                 index2 = random.sample(indices2, 1)

    #                 sampl1 = support_data[index1[0]]
    #                 sampl2 = support_data[index2[0]]
    #         sampl1 = sampl1.unsqueeze(0)
    #         sampl2 = sampl2.unsqueeze(0)
    #         # print('label:{}'.format(label))
    #         # print(sampl1.shape)
    #         # print(sampl2.shape)
    #         # print('~~~~~~~~~~~')
    #         feat1 = local_model(sampl1)
    #         feat2 = local_model(sampl2)
    #         loss = self.loss_fn(feat1, feat2, label)
    #         if self.approx:
    #             grad = torch.autograd.grad(loss, fast_parameters)
    #         else:
    #             grad = torch.autograd.grad(loss, fast_parameters, create_graph=True)
    #         for k, weight in enumerate(local_model.parameters()):
    #             # for usage of weight.fast, please see Linear_fw, Conv_fw in backbone.py
    #             weight.grad = grad[k]
    #         local_optim.step()
    #         local_optim.zero_grad()
    #         loss = loss.detach()
    #     if mode != 'train':
    #         print('inner loop: loss:{:.3f}'.format(loss.item()))
    #     if mode != 'train':
    #         print('!!!!!!!!!')
    #     return local_model

    def euclidean_dist(self,query, support):
        n = query.size(0)
        m = support.size(0)
        query = F.normalize(query, dim=1)
        support = F.normalize(support, dim=1)
        query = query.unsqueeze(1).expand(n, m, -1)
        support = support.unsqueeze(0).expand(n, m, -1)

        return torch.sqrt(torch.pow(query - support, 2).sum(2))

    def cossim(self, query, support):
        cos_sim = torch.nn.CosineSimilarity(dim=-1, eps=1e-6)
        n = query.size(0)
        m = support.size(0)
        query = query.unsqueeze(1).expand(n, m, -1)
        support = support.unsqueeze(0).expand(n, m, -1)
        return cos_sim(query, support)

    def feed_forward_test(self, prototype, query_data):
        # Execute a model with given output layer weights and inputs

        query_feat = self.feature_extractor(query_data)
        dists = self.euclidean_dist(query_feat, prototype)
        # dists = self.cossim(query_feat, prototype)
        # print(dists)
        pred = dists.argmin(-1)

        scores = -dists
        preds = F.softmax(scores, dim = 1)
        preds = preds.detach().cpu().numpy()

        return preds, query_feat

    def train_loop(self, data_loader, optimizer):
        self.feature_extractor.train()
        for i, batch in tqdm(enumerate(data_loader)):
            data, label = batch
            # print(label)
            self.feature_extractor.zero_grad()
            feat = self.feature_extractor(data)
            feat = F.normalize(feat, dim=1)
            # loss = self.loss_fn(anchor_feat, pos_feat, torch.zeros(anchor.shape[0]).to(self.device))
            # loss = loss + self.loss_fn(anchor_feat, neg_feat, torch.ones(anchor.shape[0]).to(self.device))
            # loss = self.cosloss(anchor_feat, pos_feat, torch.ones(anchor.shape[0]).to(self.device)) + self.cosloss(anchor_feat, neg_feat, -torch.ones(anchor.shape[0]).to(self.device))
            loss = self.loss_fn(feat, label)
            loss.backward()
            # for i in self.parameters():
            #     print(i.grad)
            optimizer.step()
            print('loss:{:.3f}'.format(loss.item()))
            # print('~~~~~~~~~~~')

    def test_loop(self, test_loader , fix_shreshold = None, mode = 'test'):
        self.feature_extractor.eval()
        all_prob = {}
        all_meta = {}

        for i, (pos_sup, neg_sup, query, seg_len, seg_hop, query_start, query_end, label) in enumerate(test_loader):
            seg_hop = seg_hop.item()
            query_start = query_start.item()

            # print(pos_sup[1].squeeze().shape)
            # print(neg_sup[1].squeeze().shape)
            # print(query.shape)
            wav_file= pos_sup[0][0].split('&')[1]
            all_meta[wav_file]={}
            all_meta[wav_file]['start'] = query_start

            all_meta[wav_file]['end'] = query_end
            all_meta[wav_file]['seg_hop'] = seg_hop
            all_meta[wav_file]['seg_len'] = seg_len

            all_meta[wav_file]['label'] = label[0]

            feat_file = os.path.splitext(os.path.basename(wav_file))[0] + '.hdf5'
            feat_file = os.path.join('/root/task5_2023/latent_feature/TNN_noMAML', feat_file)
            if os.path.isfile(feat_file):
                os.remove(feat_file)

            directory = os.path.dirname(feat_file)
            if not os.path.exists(directory):
                os.makedirs(directory)

            # print(wav_file)
            # print(query_start)
            pos_data = pos_sup[1].squeeze()
            query = query.squeeze()
            query_dataset = TensorDataset(query, torch.zeros(query.shape[0]))
            query_loader = DataLoader(query_dataset, batch_size=128, shuffle=False)
            pos_dataset = TensorDataset(pos_data,  torch.zeros(pos_data.shape[0]))
            pos_loader = DataLoader(pos_dataset, batch_size=self.test_loop_batch_size, shuffle=False)

            prob_mean = []
            for i in range(3):
                test_loop_neg_sample = self.config.val.test_loop_neg_sample
                neg_sup[1] = neg_sup[1].squeeze()

                if neg_sup[1].shape[0] > test_loop_neg_sample:
                    neg_indices = torch.randperm(neg_sup[1].shape[0])[:test_loop_neg_sample]
                    neg_seg_sample = neg_sup[1][neg_indices]
                else:
                    neg_seg_sample = neg_sup[1]
                # neg_seg_sample = neg_sup[1]
                neg_dataset = TensorDataset(neg_seg_sample, torch.zeros(neg_seg_sample.shape[0]))
                neg_loader = DataLoader(neg_dataset, batch_size=self.test_loop_batch_size, shuffle=False)

                support_data = torch.cat([pos_data, neg_seg_sample], dim=0)

                #  support_data = pos_data
                m = pos_data.shape[0]
                n = neg_seg_sample.shape[0]
                support_label = np.concatenate((np.zeros((m,)), np.ones((n,))))
                support_label = torch.from_numpy(support_label).long().to(self.device)

                support_feats = self.feature_extractor(support_data)
                with h5py.File(feat_file, 'w') as f:
                    f.create_dataset("features", (0, 512), maxshape=(None, 512))
                    f.create_dataset("labels", data=label.squeeze(0).numpy())
                    f.create_dataset("features_t", data = support_feats.detach().cpu().numpy())
                    f.create_dataset("labels_t", data=support_label.cpu().numpy())

                pos_feat  = []
                for batch in pos_loader:
                    p_data, _ = batch
                    feat = self.feature_extractor.forward(p_data)
                    # print(feat.shape)
                    pos_feat.append(feat.mean(0))
                pos_feat = torch.stack(pos_feat, dim=0).mean(0)
                neg_feat = []

                with torch.no_grad():
                    for batch in neg_loader:
                        n_data, _ = batch
                        # print(neg_data.shape)
                        feat = self.feature_extractor.forward(n_data)
                        # print(feat.shape)
                        neg_feat.append(feat.mean(0))
                    neg_feat = torch.stack(neg_feat, dim=0).mean(0)
                    proto = torch.stack([pos_feat,neg_feat], dim=0)

                prob_all = []
                for batch in tqdm(query_loader):
                    query_data, _ = batch
                    prob, feats  = self.feed_forward_test(proto, query_data)
                    prob_all.append(prob)
                    with h5py.File(feat_file, 'a') as f:

                            size = f['features'].shape[0]
                            nwe_size = f['features'].shape[0] + feats.shape[0]

                            f['features'].resize((nwe_size, 512))

                            f['features'][size:nwe_size] = feats.detach().cpu().numpy()
                prob_all = np.concatenate(prob_all, axis=0)
                #########################################################################

                prob_all = prob_all[:,0]
                # prob_all = np.where(prob_all>self.config.val.threshold, 1, 0)
                prob_mean.append(prob_all)
            prob_mean = np.stack(prob_mean, axis=0).mean(0)
            all_prob[wav_file] = prob_mean

        best_res = None
        best_f1 = 0
        best_report = {}
        best_threshold = 0
        for threshold in np.arange(0.5, 1, 0.1):
            if fix_shreshold is not None:
                threshold = fix_shreshold
            report_f1 = {}
            all_time = {'Audiofilename':[], 'Starttime':[], 'Endtime':[]}
            for wav_file in all_prob.keys():

                prob = np.where(all_prob[wav_file]>threshold, 1, 0)

                # acc = np.sum(prob^1 == np.array(all_meta[wav_file]['label']))/len(prob)
                # 计算分类报告
                y_pred = prob^1
                y_true =  np.array(all_meta[wav_file]['label'])

                # print(all_meta[wav_file]['seg_hop'])
                # print(all_meta[wav_file]['seg_len'])
                # 输出分类报告

                report_f1[os.path.basename(wav_file)] = classification_report(y_true, y_pred,zero_division=0, digits=5)
                # 计算各个类别的F1分数
                # f1_scores = f1_score(y_true, y_pred, average=None)

                # 输出各个类别的F1分数
                # print("F1 scores for each class:")
                # print(f1_scores)
                # print(len(prob))
                # print(np.sum(prob))
                # print(np.sum(prob)/len(prob))

                on_set = np.flatnonzero(np.diff(np.concatenate(([0],prob), axis=0))==1)
                off_set = np.flatnonzero(np.diff(np.concatenate((prob,[0]), axis=0))==-1) + 1 #off_set is the index of the first 0 after 1
                # for i, j in zip(on_set, off_set):
                #     print(i,j)

                on_set_time = on_set*all_meta[wav_file]['seg_hop']/self.fps + all_meta[wav_file]['start']
                off_set_time = off_set*all_meta[wav_file]['seg_hop']/self.fps + all_meta[wav_file]['start']
                all_time['Audiofilename'].extend([os.path.basename(wav_file)]*len(on_set_time))
                all_time['Starttime'].extend(on_set_time)
                all_time['Endtime'].extend(off_set_time)
                # print(wav_file)
                # print(on_set_time[:5])
                # print('query_start', all_meta[wav_file]['start'])
                for i in range(len(off_set_time)):
                    if off_set_time[i] > all_meta[wav_file]['end']:
                        raise ValueError('off_set_time is larger than query_end')

            df_all_time = pd.DataFrame(all_time)
            df_all_time = post_processing(df_all_time, self.config, mode)
            df_all_time = df_all_time.astype('str')
            pred_path = normalize_path(self.config.checkpoint.pred_dir)
            pred_path = os.path.join(pred_path, 'pred_{:.2f}.csv'.format(threshold))
            if not os.path.exists(os.path.dirname(pred_path)):
                os.makedirs(os.path.dirname(pred_path))
            df_all_time.to_csv(pred_path, index=False)

            ref_files_path = test_loader.dataset.val_dir
            report_dir = normalize_path(self.config.checkpoint.report_dir)
            report = evaluate(df_all_time, ref_files_path, self.config.team_name, self.config.dataset, report_dir)
            if report['overall_scores']['fmeasure (percentage)'] > best_f1:
                best_f1 = report['overall_scores']['fmeasure (percentage)']
                best_res = report
                best_report = report_f1
                best_threshold = threshold
            if fix_shreshold is not None:
                break
        for i in best_report.keys():
            print(i)
            print(best_report[i])
            print('~~~~~~~~~~~~~~~')
        print(best_res)
        print('best_threshold', best_threshold)
        print('~~~~~~~~~~~~~~~')
        return df_all_time, best_res, best_threshold

    # def euclidean_dist(self,query, support):
    #     init_weight = 2 * support

    #     init_bias = -torch.norm(support, dim=1)**2
        # print(init_weight.shape)
        # print(init_bias.shape)

        # output_weight = init_weight.detach()
        # output_bias = init_bias.detach()
        # score2 = query.matmul(init_weight.t()) + init_bias-(torch.norm(query, dim=1)**2).unsqueeze(1)

        # score2 = F.linear(query, init_weight, init_bias)
        # score2 = score2-(torch.norm(query, dim=1)**2).unsqueeze(1)

        # n = query.size(0)
        # m = support.size(0)

        # query = query.unsqueeze(1).expand(n, m, -1)
        # support = support.unsqueeze(0).expand(n, m, -1)
        # score = torch.pow(query - support, 2).sum(2)

        # prob2 = F.softmax(score2, dim=1)
        # prob1 = F.softmax(-score, dim=1)

        # print(torch.argmax(prob1, dim=1))
        # print(torch.argmax(prob2, dim=1))
        # print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        # return -score2


# Write a function that meets these requirements.
#
# Name:       halve_the_list
# Parameters: a single list
# Returns:    two lists, each containing half of the original list
#             if the original list has an odd number of items, then
#             the extra item is in the first list
#
# Examples:
#    * input: [1, 2, 3, 4]
#      result: [1, 2], [3, 4]
#    * input: [1, 2, 3]
#      result: [1, 2], [3]

#function halve the list with single list as input
    #create first new list
    #create second new list
    # boolean if length of list is odd
    #check if there are an odd number of items in list
        # if there are, subtract one from length
            # set boolean to true
        # otherwise note
        # split length of list in half
    #for item in range of first item to half.
        # add items from original list to first new list
    #for item in range of half to item.
        # add rest of items from original lists
    # return both lists

def halve_the_list(single_list):
    first_list = []
    original_length = len(single_list)
    second_list = []
    odd = False
    if len(single_list)%2 == 0:
        odd = False
    else:
        original_length = original_length - 1
        odd = True
    split_point = int(original_length / 2)
    if odd:
        split_point = split_point + 1

    for i in range(0,split_point):
        first_list.append(single_list[i])
    for i in range(split_point, len(single_list)):
        second_list.append(single_list[i])
    return first_list, second_list

print(halve_the_list([1,2,3,4,5]))


import random
import math

def counterRow(square):
    rows = 0

    for row in square:
        count = 0
        for cube in row:
            if cube == 1:
                count += 1
            else:
                count = 0

            if  count >= 4:
                rows += 1

    return rows

def counterColumn(square):
    columns = 0

    for column in range(inpt):
        count = 0
        for cube in range(inpt):
            if square[cube][column] == 1:
                count += 1
            else:
                count = 0

            if  count >= 4:
                columns += 1

    return columns

def counterDiagonal(square):
    diagonals = 0
    temp = 0
    for i in range(inpt - 3):
        count = 0
        for diagonal in range(inpt - i):
            for cube in range(inpt):
                if diagonal == cube:
                    if square[cube + temp][diagonal] == 1:
                        count += 1
                    else:
                        count = 0

                    if count >= 4:
                        diagonals += 1
        temp += 1

    temp = 1
    for i in range(inpt - 3):
        count = 0
        for diagonal in range(inpt - i - 1):
            for cube in range(inpt):
                if diagonal == cube:
                    if square[cube][diagonal + temp] == 1:
                        count += 1
                    else:
                        count = 0

                    if count >= 4:
                        diagonals += 1
        temp += 1
    return diagonals

def counterDiagonalReverse(square):
    diagonals = 0
    temp = 0
    for i in range(inpt - 3):
        count = 0
        for diagonal in range(inpt - i - 1, -1, -1):
            for cube in range(inpt):
                if diagonal + cube == inpt -1:
                    if square[cube][diagonal + temp] == 1:
                        count += 1
                    else:
                        count = 0

                    if count >= 4:
                        diagonals += 1
        temp += 1

    temp = -1
    for i in range(inpt - 3):
        count = 0
        for diagonal in range(inpt - i - 2, -1, -1):
            for cube in range(inpt):
                if diagonal + cube == inpt - 1:
                    if square[cube + temp][diagonal] == 1:
                        count += 1
                    else:
                        count = 0

                    if count >= 4:
                        diagonals += 1
        temp -= 1
    return diagonals

def fillList(square):
    temp = []
    for i in range(size):
        if (i%2 == 0):
            temp.append(0)
        else:
            temp.append(1)

    random.shuffle(temp)
    for i in range(inpt):
        row = []
        for j in range(inpt):
            row.append(temp[i*inpt+j])

        square.append(row)

#checking if the input is a size that it is possible to create 4 (1s) in row.
inpt = int(input("Insert square's side size: "))
while inpt < 4:
    inpt = int(input("Insert square's side size(must be greater than 3): "))

size = inpt * inpt
print("The size of the square is: ", size)

square = []

fillList(square)

ones = counterRow(square) + counterColumn(square) + counterDiagonal(square) + counterDiagonalReverse(square)
print("The amount of 1s is: ", ones)

εργασία_1.py

εργασία_1.py


import flask
from flask import Flask,request , jsonify
from xyz import AddTwo as ad

app = Flask(__name__)

@ app.route('/')
def test():
    return jsonify({"status":"ok"})

@ app.route('/parsename',methods=['GET'])
def test_name():

    var_name = request.args.get("name")
    return jsonify({"Entered name = ": var_name})

@ app.route('/twopara',methods=['GET'])
def two_para():
    n=request.args.get('name')
    r=request.args.get('rollno')
    output="Roll No{}has the name:{}".format(r,n)
    return output

@ app.route('/addtwo',methods=['GET'])
def add_two_num():
    fno = request.args.get("fn")
    sno = request.args.get("sn")

    a = ad()
    s = a.add_Two(fno,sno)

    return "Sum of {} and {} is : {}".format(fno,sno,s)

if __name__ == '__main__':
    app.run(port=50001)


from datetime import datetime, timedelta
from unittest.mock import AsyncMock

from framework.clients.cache_client import CacheClientAsync
from framework.di.service_collection import ServiceCollection

from clients.azure_gateway_client import AzureGatewayClient
from clients.email_gateway_client import EmailGatewayClient
from clients.twilio_gateway import TwilioGatewayClient
from tests.buildup import ApplicationBase

class TwilioGatewayClientTests(ApplicationBase):
    def configure_services(self, service_collection: ServiceCollection):
        self.mock_cache_client = AsyncMock()

        def get_mock_cache_client(services):
            return self.mock_cache_client

        service_collection.add_singleton(
            dependency_type=CacheClientAsync,
            factory=get_mock_cache_client)

    def get_client(
        self
    ) -> TwilioGatewayClient:
        self.mock_cache_client.get_cache.return_value = None
        return self.resolve(TwilioGatewayClient)

    # async def test_send_sms(self):
    #     client = self.get_client()

    #     response = await client.send_sms(
    #         recipient='+18563323608',
    #         message='test')

    #     self.assertIsNotNone(response)

class EmailGatewayClientTests(ApplicationBase):
    def configure_services(self, service_collection: ServiceCollection):
        self.mock_cache_client = AsyncMock()

        def get_mock_cache_client(services):
            return self.mock_cache_client

        service_collection.add_singleton(
            dependency_type=CacheClientAsync,
            factory=get_mock_cache_client)

    def get_client(
        self
    ) -> EmailGatewayClient:
        self.mock_cache_client.get_cache.return_value = None
        return self.resolve(EmailGatewayClient)

    async def test_send_email(self):
        client = self.get_client()

        response = await client.send_email(
            subject='Test',
            recipient='me@dan-leonard.com',
            message='Test')

        self.assertIsNotNone(response)

    async def test_send_datatable_email(self):
        client = self.get_client()

        data = [{'row': 'value'}]

        response = await client.send_datatable_email(
            subject='Test',
            recipient='me@dan-leonard.com',
            data=data)

        self.assertIsNotNone(response)

    async def test_send_json_email(self):
        client = self.get_client()

        data = [{'row': 'value'}]

        response = await client.send_json_email(
            subject='Test',
            recipient='me@dan-leonard.com',
            data=data)

        self.assertIsNotNone(response)

class AzureGatewayClientTests(ApplicationBase):
    def configure_services(self, service_collection: ServiceCollection):
        self.mock_cache_client = AsyncMock()

        def get_mock_cache_client(services):
            return self.mock_cache_client

        service_collection.add_singleton(
            dependency_type=CacheClientAsync,
            factory=get_mock_cache_client)

    def get_client(
        self
    ) -> AzureGatewayClient:
        self.mock_cache_client.get_cache.return_value = None
        return self.resolve(AzureGatewayClient)

    async def test_get_pod_images(self):
        client = self.get_client()

        response = await client.get_pod_images()

        self.assertIsNotNone(response)

    async def test_get_acr_manifests(self):
        client = self.get_client()

        response = await client.acr_get_manifests(
            repository_name='framework')

        self.assertIsNotNone(response)

    async def test_get_repositories(self):
        client = self.get_client()

        response = await client.acr_get_repositories()

        self.assertIsNotNone(response)

    async def test_get_cost_management_data(self):
        client = self.get_client()

        start_date = datetime.now() - timedelta(days=1)
        end_date = datetime.now()

        response = await client.get_cost_management_data(
            start_date=start_date.strftime('%Y-%m-%d'),
            end_date=end_date.strftime('%Y-%m-%d'))

        self.assertIsNotNone(response)

    async def test_get_pods(self):
        client = self.get_client()

        response = await client.get_pods()

        self.assertIsNotNone(response)

    async def test_get_logs(self):
        client = self.get_client()

        pods_response = await client.get_pods()
        pods = pods_response.get('pods')

        response = await client.get_logs(
            namespace=pods[0].get('name'),
            pod=pods[0].get('namespace'))

        self.assertIsNotNone(response)


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

import sys
import os
import json
import argparse

def print_rank_0(*args, **kwargs):
    rank = int(os.getenv("RANK", "0"))
    if rank == 0:
        print(*args, **kwargs)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("module_name", type=str)
    parser.add_argument("--output_preLen", type=int, default=20)
    parser.add_argument("--only-oneflow", action="store_true")
    parser.add_argument("--only-pytorch", action="store_true")
    args = parser.parse_args()

    with open("input_text.json", encoding="utf-8") as f:
        dict_input = json.load(f)

    input = {
        "txt": dict_input[str(args.output_preLen)],
        "preLen": args.output_preLen # 预测的长度
    }

    if not args.only_pytorch:
        sys.path.append('/path/to/writer/AI_Writer_Web')
        from AI_Writer_Web.infer import Writer as Writer_Oneflow
        writer_oneflow = Writer_Oneflow()
        output_oneflow = writer_oneflow.inference(input)
        oneflow_time = output_oneflow["time"]
        #print(output_oneflow["txt"])

        print_rank_0(
            f"OneFlow {args.module_name} time: {oneflow_time:.8f}s , output_preLen={args.output_preLen}"
        )

    if not args.only_oneflow:
        sys.path.append('/path/to/writer/AI_Writer')
        from AI_Writer.infer import Writer as Writer_Pytorch
        writer_pytorch = Writer_Pytorch()
        output_pytorch = writer_pytorch.inference(input)

        pytorch_time = output_pytorch["time"]
        #print(output_pytorch["txt"])

        print_rank_0(
            f"PyTorch {args.module_name} time: {pytorch_time:.8f}s , output_preLen={args.output_preLen}"
        )

    if not args.only_pytorch and not args.only_oneflow:
        relative_speed = pytorch_time / oneflow_time
        print_rank_0(
            f"Relative speed: {relative_speed:.8f} (= {pytorch_time:.8f}s / {oneflow_time:.8f}s)"
        )


from list_fns import load_words_append as load_words
from inlist import in_bisect
import time

def find_reverse_pairs(t):
    pairs = []
    for i in range(len(t)):
        word = t[i]
        reverse_word = word[::-1]
        if reverse_word != word and in_bisect(t[i:], reverse_word):
            pairs.append(word)
            pairs.append(reverse_word)
    return pairs

def main():
    t = load_words('words.txt')
    t.sort()
    t0 = time.time()
    pairs = find_reverse_pairs(t)
    t1 = time.time()

    print(f"Finished! {len(pairs)} have been found in {t1 - t0} seconds.")
    print("Here are the first five pairs: ")
    for i in range(10):
        print(pairs[i])

if __name__ == '__main__':
    main()


import pygame

class Ship:
    def __init__(self, screen):
        self.character = pygame.image.load('hw_images/ship_0009.png')
        self.character_rect = self.character.get_rect()
        self.screen_rect = screen.get_rect()
        self.character_rect.center = self.screen_rect.center
        self.ship_speed = 1.0

        self.x = float(self.character_rect.x)
        self.y = float(self.character_rect.y)

        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def draw(self):
        screen.blit(self.character, self.character_rect)

    def update(self):
        if self.moving_right and self.character_rect.right < self.screen_rect.right:
            self.x += self.ship_speed
        if self.moving_left and self.character_rect.left > 0:
            self.x -= self.ship_speed
        if self.moving_up and self.character_rect.top > 0:
            self.y -= self.ship_speed
        if self.moving_down and self.character_rect.bottom < self.screen_rect.bottom:
            self.y += self.ship_speed

        self.character_rect.x = self.x
        self.character_rect.y = self.y

pygame.init()
screen = pygame.display.set_mode((500, 500))
ship = Ship(screen)

screen.fill((181, 255, 255))

while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = True
            elif event.key == pygame.K_LEFT:
                ship.moving_left = True
            elif event.key == pygame.K_UP:
                ship.moving_up = True
            elif event.key == pygame.K_DOWN:
                ship.moving_down = True

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = False
            elif event.key == pygame.K_LEFT:
                ship.moving_left = False
            elif event.key == pygame.K_UP:
                ship.moving_up = False
            elif event.key == pygame.K_DOWN:
                ship.moving_down = False

    ship.update()
    screen.fill((181, 255, 255))
    ship.draw()
    pygame.display.flip()


from conans import ConanFile, CMake, tools
from conans.errors import ConanInvalidConfiguration
import glob
import os
import shutil

required_conan_version = ">=1.32.0"

class VulkanValidationLayersConan(ConanFile):
    name = "vulkan-validationlayers"
    description = "Khronos official Vulkan validation layers for Windows, Linux, Android, and MacOS."
    license = "Apache-2.0"
    topics = ("conan", "vulkan-validation-layers", "vulkan", "validation-layers")
    homepage = "https://github.com/KhronosGroup/Vulkan-ValidationLayers"
    url = "https://github.com/conan-io/conan-center-index"

    settings = "os", "arch", "compiler", "build_type"
    options = {
        "with_wsi_xcb": [True, False],
        "with_wsi_xlib": [True, False],
        "with_wsi_wayland": [True, False]
    }
    default_options = {
        "with_wsi_xcb": True,
        "with_wsi_xlib": True,
        "with_wsi_wayland": True
    }

    short_paths = True

    exports_sources = ["CMakeLists.txt", "patches/**"]
    generators = "cmake"
    _cmake = None

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def config_options(self):
        if self.settings.os != "Linux":
            del self.options.with_wsi_xcb
            del self.options.with_wsi_xlib
            del self.options.with_wsi_wayland

    def configure(self):
        if self.settings.compiler.get_safe("cppstd"):
            tools.check_min_cppstd(self, 11)
        if self.settings.compiler == "gcc" and tools.Version(self.settings.compiler.version) < "5":
            raise ConanInvalidConfiguration("gcc < 5 is not supported")

    def requirements(self):
        self.requires("spirv-tools/2020.5", private=True)
        self.requires("vulkan-headers/{}".format(self.version))
        if self.options.get_safe("with_wsi_xcb") or self.options.get_safe("with_wsi_xlib"):
            self.requires("xorg/system")
        if self.options.get_safe("with_wsi_wayland"):
            self.requires("wayland/1.18.0")

    def validate(self):
        if self.options["spirv-tools"].shared:
            raise ConanInvalidConfiguration("vulkan-validationlayers can't depend on shared spirv-tools")

    def source(self):
        tools.get(**self.conan_data["sources"][self.version])
        extracted_dir = glob.glob("Vulkan-ValidationLayers-*")[0]
        os.rename(extracted_dir, self._source_subfolder)

    def build(self):
        self._patch_sources()
        cmake = self._configure_cmake()
        cmake.build()

    def _patch_sources(self):
        for patch in self.conan_data.get("patches", {}).get(self.version, []):
            tools.patch(**patch)
        tools.replace_in_file(os.path.join(self._source_subfolder, "cmake", "FindVulkanHeaders.cmake"),
                              "HINTS ${VULKAN_HEADERS_INSTALL_DIR}/share/vulkan/registry",
                              "HINTS ${VULKAN_HEADERS_INSTALL_DIR}/res/vulkan/registry")

    def _configure_cmake(self):
        if self._cmake:
            return self._cmake
        self._cmake = CMake(self)
        self._cmake.definitions["VULKAN_HEADERS_INSTALL_DIR"] = self.deps_cpp_info["vulkan-headers"].rootpath
        self._cmake.definitions["USE_CCACHE"] = False
        if self.settings.os == "Linux":
            self._cmake.definitions["BUILD_WSI_XCB_SUPPORT"] = self.options.with_wsi_xcb
            self._cmake.definitions["BUILD_WSI_XLIB_SUPPORT"] = self.options.with_wsi_xlib
            self._cmake.definitions["BUILD_WSI_WAYLAND_SUPPORT"] = self.options.with_wsi_wayland
        self._cmake.definitions["BUILD_WERROR"] = False
        self._cmake.definitions["BUILD_TESTS"] = False
        self._cmake.definitions["INSTALL_TESTS"] = False
        self._cmake.definitions["BUILD_LAYERS"] = True
        self._cmake.definitions["BUILD_LAYER_SUPPORT_FILES"] = True
        self._cmake.configure()
        return self._cmake

    def package(self):
        self.copy("LICENSE.txt", dst="licenses", src=self._source_subfolder)
        cmake = self._configure_cmake()
        cmake.install()
        if self.settings.os == "Windows":
            # import lib is useless, validation layers are loaded at runtime
            lib_dir = os.path.join(self.package_folder, "lib")
            tools.remove_files_by_mask(lib_dir, "VkLayer_khronos_validation.lib")
            tools.remove_files_by_mask(lib_dir, "libVkLayer_khronos_validation.dll.a")
        else:
            # Move json files to res, but keep in mind to preserve relative
            # path between module library and manifest json file
            os.rename(os.path.join(self.package_folder, "share"), os.path.join(self.package_folder, "res"))

    def package_info(self):
        self.cpp_info.libs = ["VkLayer_utils"]

        manifest_subfolder = "bin" if self.settings.os == "Windows" else os.path.join("res", "vulkan", "explicit_layer.d")
        vk_layer_path = os.path.join(self.package_folder, manifest_subfolder)
        self.output.info("Appending VK_LAYER_PATH environment variable: {}".format(vk_layer_path))
        self.env_info.VK_LAYER_PATH.append(vk_layer_path)


class Person:
    def __init__(self,name,age,gender):
        self._name = name
        self._age = age
        self._gender = gender

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self,newName):
        self._name = newName

if __name__ == "__main__": #매직 메쏘드 (예약이 되어있음 if네임은 main있잖아요)
    #파일이 직접 실행될때만 실행되는 부분 #예약어 몇개 있는데 중요한거 몇개 배우고 가려고해요
    #이터레이터랑 제너레이터를 알아야할거 같아서 이터레이터라는건 리스트나 셀이나 이런거 셀 수 있는 집합
    #fiboclass.py에서 실습해봄
    #제너레이터 설명해볼게요 피보나치를 할때 이렇게도 할 수 있는데 yield 를 사용해서 값을 반환해 줄 수도 있어요
    #리턴값이 따로없잖아요 옐드를 두고 하면 아까랑 같이 피보나치 출력이 돼요
    #
    m1 = Person("연정흠",23,"남") #property
    w2 = Person("이지은",25,"여")
    w2.name = "아이유" #setter
    print(m1.name) #m1만 하면 오브젝트 값을 출력하는거고 m1.name이라 해야함
    print(w2.name) # 이 역시 마찬가지


"""
Flask: Using templates
"""
from asyncore import read
from re import M
from turtle import title
from setup_db import select_students, select_courses
import sqlite3
from sqlite3 import Error
from flask import Flask, render_template, request, redirect, url_for, g

app = Flask(__name__)

DATABASE = './database.db'

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

@app.route("/")
def index():
    # get the database connection
    conn = get_db()

    return render_template("index.html",
                            students=select_students(conn),
                            courses=select_courses(conn)
                        )

@app.route("/courses", methods=["POST", "GET"])
def courses():
    # get the database connection
    if request.method == 'GET':
     return render_template("courses_page.html"
                    # select_students executes SELECT SQL statement on database connetion
                    # returns list of students

    )
    else:
        conn = get_db()
        courseID=request.form['courseid']
        cur = conn.cursor()
        cur.execute("SELECT students.name, grades.course_id, courses.name, grades.grade FROM grades INNER JOIN students on students.student_no = grades.student_no INNER JOIN courses on grades.course_id = courses.id WHERE courses.id = ? ORDER BY grades.grade", (courseID,))
        select_courses_id = []
        for (students_name, course_id, coursesname, gradesgrade) in cur:
                select_courses_id.append({
                    "students.name": students_name,
                    "grades.course_id": course_id,
                    "courses.name": coursesname,
                    "grades.grade": gradesgrade
                })

        print(select_courses_id)
        return render_template("courses_page.html", select_courses_id=select_courses_id)

@app.route("/studentsP", methods=["POST", "GET"])
def studentsP():
    # get the database connection
    conn = get_db()
    studentNo=None

    if request.method == 'GET':

        return render_template("courses_page.html",

    )

    else:
            conn = get_db()
            studentNo=request.form['student_id']
            #studentNo=request.form['data']
            cur = conn.cursor()
            cur2 = conn.cursor()
            cur2.execute("SELECT student_no, name FROM students WHERE student_no = ? ", (studentNo,))
            select_student_name = []
    for (student_n, studentsname) in cur2:
            select_student_name.append({
               "student_no":student_n,
               "name": studentsname
            })
            break

    print("Profile: ",select_student_name)

    cur.execute("SELECT grades.course_id, courses.name, grades.grade FROM grades INNER JOIN students on students.student_no = grades.student_no INNER JOIN courses on grades.course_id = courses.id WHERE students.student_no = ?", (studentNo,))

    select_student_no = []
    for (coursid,coursesname,gradesgrade) in cur:
        select_student_no.append({
            "grades.course_id": coursid,
            "courses.name": coursesname,
            "grades.grade": gradesgrade
            })

        #print(select_student_no.index(coursesname))

    return render_template("students_profile.html",
                        studentss=select_student_no,
                        select_student_nam = select_student_name)

@app.route("/addStudent", methods=["POST", "GET"])
def addStudent():

    if request.method == 'GET':
        # send the form
        return render_template('add_student.html')

    else:
        student_no1 = request.form['student_id_no']
        name1 = request.form['name']
        conn = get_db()
        cur = conn.cursor()

    try:

            sql = ''' INSERT INTO students(student_no,name)
              VALUES(?,?) '''
            cur.execute(sql, (student_no1, name1))
            conn.commit(),

            return redirect(url_for('index'))

    except Error as e: # if error
            # then display the error in 'error.html' page

            return render_template('error.html', msg="Error adding new student.", error=e)
    finally:
            conn.close()

@app.route("/addGrade", methods=["POST", "GET"])
def addGrade():

    if request.method == 'GET':
        conn = get_db()
        grades = [("A"), ("B"), ("C"), ("D"), ("E"), ("F")]
        gra=grades
        cur = conn.cursor()
        #cur.execute("SELECT student_no FROM students WHERE name = ? ", (studentname,))
        cur.execute("SELECT student_no FROM students")
        select_student_name = []
        for (student_n) in cur:
                select_student_name.append({
               "student_no":student_n
            })
                break

        return render_template("add_grade.html",
                    students=select_students(conn),
                    courses=select_courses(conn),
                    gra = gra
                    )

    else:
        conn = get_db()
        cur = conn.cursor()
        studno = request.form['studno']
        course = request.form['course']
        grade = request.form['grade']

    try:

            sql = ''' INSERT INTO grades(student_no,course_id,grade)
              VALUES(?,?,?) '''
            cur.execute(sql, (studno, course, grade))
            conn.commit(),

            return redirect(url_for('index'))

    except Error as e: # if error
            # then display the error in 'error.html' page

            return render_template('error.html', msg="Error adding new grade.", error=e)
    finally:
            conn.close()

if __name__ == "__main__":
    app.run(debug=True)


import tensorflow as tf
import matplotlib.pyplot as plt

cifar10=tf.keras.datasets.cifar10
(x_train,y_train),(x_test,y_test)=cifar10.load_data()

plt.imshow(x_train[0]) #绘制图片
plt.show()

print("x_train[0]:\n",x_train[0])

print(y_train)

print(x_test.shape)


import random

from Fight import Fight
from Person import Person
from Warrior import Warrior
from KnightErrant import KnightErrant

class Fighter(Person):
    skills_dict = {
        "spear": 0,
        "unarmed combat": 0,
        "mace": 0,
        "broadsword": 0
    }

    def __init__(self, name, age, wealth, spear, unarmed_combat, mace, broadsword):
        Person.__init__(self, name, age, wealth)
        self.set_is_adult(self)
        self.skills_dict["spear"] = spear
        self.skills_dict["unarmed combat"] = unarmed_combat
        self.skills_dict["mace"] = mace
        self.skills_dict["broadsword"] = broadsword

    def challenge(self, fighter, skill):
        if self != fighter:
            if self.wealth > 0:
                if fighter is isinstance(Warrior) or fighter is isinstance(KnightErrant):
                    fighter.challenge_list_add(fighter, self)
                else:
                    self.check_challenge(fighter, self, skill)
            else:
                print(self.name + " does not have enough money to challenge " + fighter.name)
        else:
            print(self.name + " cannot fight themselves!")

    def check_challenge(self, initiator, skill):
        if self.wealth != 0:
            self.check_skill(self, initiator, skill)

    def check_skill(self, fighter, skill):
        fighter_a = self.skills_dict[skill]
        fighter_b = fighter.skills_dict[skill]
        if fighter_a > fighter_b:
            print(self.name + " wins the fight")
            winner = self
            loser = fighter
        elif fighter_a < fighter_b:
            print(fighter.name + "wins the fight")
            winner = fighter
            loser = self
        else:
            winner = random.choices(self, fighter)
            if winner == self:
                loser = fighter
            elif winner == fighter:
                loser = self
            fight = Fight(self, winner, loser, skill)
       #     Fight.__init__(self, winner, loser, skill)

 #   def withdraw(self):

    def __str__(self):
        print()