class StringSolutions:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s[::-1]

    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        negFlag = False
        if x < 0:
            x *= -1
            negFlag = True

        result = 0

        while x > 0:
            curr = x % 10
            result = result * 10 + curr
            x = x // 10

            if result < -1 << 31 or result > (1 << 31) - 1:
                return 0

        if negFlag:
            result*=-1

        return result

    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        # Dictionaries
        uniqDict = {}
        n = len(s)

        for i in range(n):
            val = uniqDict.get(s[i], -1)
            if val is -1:
                uniqDict[s[i]] = (i, 1)
            else:
                currOccur = val[1] + 1
                uniqDict[s[i]] = (i, currOccur)

        for i in range(n):
            val = uniqDict.get(s[i])
            if val[1] == 1:
                return val[0]

        return -1

        # Freq Map
        freq = [0] * 26
        n = len(s)

        for i in range(n):
            freq[ord(s[i]) - 97]+=1

        for i in range(n):
            if freq[ord(s[i]) - 97] == 1:
                return i

        return -1

    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        firstLen = len(s)
        secondLen = len(t)

        if firstLen != secondLen:
            return False

        freq = [0] * 26

        for i in range(firstLen):
            freq[ord(s[i]) - 97]+=1

        for i in range(secondLen):
            freq[ord(t[i]) - 97]-=1
            if freq[ord(t[i]) - 97] < 0:
                return False

        return True

    def isPalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return True

        front = 0
        end = len(s) - 1
        s = s.lower()

        while front <= end:
            # Check for characters
            while front <= end and not s[front].isalnum():
                front+=1

            while front <= end and not s[end].isalnum():
                end-=1

            # Both are charaters now
            if front <= end and s[front] != s[end]:
                return False
            front+=1
            end-=1

        return True

    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        n = len(str)
        resArr = []
        resNum = 0
        firstNum = False
        negFlag = False

        for i in range(n):
            if str[i].isspace() and not firstNum:
                continue
            if str[i] == "-" and not firstNum:
                negFlag = True
                firstNum = True
                continue
            if str[i] == "+" and not firstNum:
                negFlag = False
                firstNum = True
                continue
            if not str[i].isnumeric() and not firstNum:
                return 0
            if not str[i].isnumeric() and firstNum:
                break

            if str[i].isnumeric():
                # Then we can start interpreting
                firstNum = True
                resArr.append(str[i])

        m = len(resArr)

        for i in range(m):
            resNum = resNum * 10 + int(resArr[i])

        if negFlag:
            resNum*=-1

        if resNum > (1 << 31) - 1:
            return (1 << 31) - 1
        if resNum < (-1 << 31):
            return (-1 << 31)

        return resNum

    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0

        for i in range(len(haystack) - len(needle) + 1):
            if haystack[i:i + len(needle)] == needle:
                return i

        return -1

    def countAndSay(self, n):
        """
        :type n: int
        :rtype: str
        """
        if n == 1:
            return "1"
        if n == 2:
            return "11"

        resStr = ""
        prevStr = self.countAndSay(n - 1)
        n = len(prevStr)
        currLet = prevStr[0]
        count = 1

        for i in range(1, n):
            if prevStr[i] == currLet:
                count+=1
            else:
                resStr+=(str(count))
                resStr+=(currLet)
                currLet = prevStr[i]
                count = 1

        # Check if last few nums are same
        if count > 0:
            resStr+=(str(count))
            resStr+=(currLet)

        return resStr

    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        :input: ["flower","flow","flight"]
        :output: "fl"
        """
        if not strs:
            return ""

        shortestStr = min(strs, key=len)
        n = len(shortestStr)

        for i in range(n):
            for str in strs:
                if str[i] != shortestStr[i]:
                    return shortestStr[:i]

        return shortestStr


#%%

import tkinter as tk
import os
from datetime import datetime
root=tk.Tk()
root.configure(background="white")
path1 = os.path.dirname(os.path.realpath(__file__))
def image_capture():
     os.chdir(path1)
     os.system("python imageCapture.py")

def recognize():
    os.chdir(path1)
    os.system("python recognize.py")

def attendance():
    os.chdir(path1+"/"+ "attendance sheet")
    os.startfile(os.getcwd()+'\\'+str(str(datetime.now().month)+'.xlsx'))
def register():
    os.chdir(path1)
    os.system("python NewImageGenrator.py")
def train():
    os.chdir(path1)
    os.system("python train.py")
root.title("AUTOMATIC ATTENDANCE MANAGEMENT USING FACE RECOGNITION")
tk.Label(root, text="FACE RECOGNITION ATTENDANCE SYSTEM",font=("times new roman",20),fg="white",bg="maroon",height=2).grid(row=0,rowspan=2,columnspan=2,sticky='N'+'E'+'W'+'S',padx=5,pady=5)
tk.Button(root,text="Register",font=("times new roman",20),bg="#0D47A1",fg='white',command=register).grid(row=6,columnspan=2,sticky='W'+'E'+'N'+'S',padx=5,pady=5)
tk.Button(root,text="Train Model",font=("times new roman",20),bg="#0D47A1",fg='white',command=train).grid(row=9,columnspan=2,sticky='W'+'E'+'N'+'S',padx=5,pady=5)
tk.Button(root,text="Image Capture",font=("times new roman",20),bg="#0D47A1",fg='white',command=image_capture).grid(row=12,columnspan=2,sticky='W'+'E'+'N'+'S',padx=5,pady=5)
tk.Button(root,text="Recognize",font=("times new roman",20),bg="#0D47A1",fg='white',command=recognize).grid(row=15,columnspan=2,sticky='W'+'E'+'N'+'S',padx=5,pady=5)
tk.Button(root,text="Attendance Sheet Of Present Month",font=("times new roman",20),bg="#0D47A1",fg='white',command=attendance).grid(row=18,columnspan=2,sticky='W'+'E'+'N'+'S',padx=5,pady=5)
root.mainloop()


directionConnectors = {
    "keys": ["", "landmark", "type", "horiz", "angle", "vert"],
    "slots": ["By ", " (", ") - ", " away, ", " o'clock, ", " height offset"],
    "spoilers": ["Near ", " (", ") - ", " away in ", " o'clock direction, ",
                 " height offset"]
}

def parseDirections(directions):
    if directions.startswith(directionConnectors["slots"][0]):
        connectors = directionConnectors["slots"]
    else:
        connectors = directionConnectors["spoilers"]
    splitLine = directions
    strings = dict()
    index = 0
    for connector in connectors:
        splitLine = splitLine.split(connector)
        key = directionConnectors["keys"][index]
        if key:
            strings[key] = splitLine[0]
        splitLine = splitLine[1]
        index += 1
    return strings

def scriptDirections(strings, connect="spoilers"):
    directions = directionConnectors[connect][0]
    index = 1
    for key in strings:
        directions += strings[key]
        directions += directionConnectors[connect][index]
        index += 1
    return directions


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import BasicBlock, conv1x1, resnet34
from argparse import Namespace

import sys
sys.path.append("flownet2_pytorch")

from flownet2_pytorch.networks import FlowNetC

class FlowNet2C(FlowNetC.FlowNetC):
    def __init__(self, args, batchNorm=False, div_flow=20):
        super(FlowNet2C, self).__init__(args, batchNorm=batchNorm, div_flow=div_flow)
        self.rgb_max = args.rgb_max
        self.last_conv = nn.Sequential(
            nn.LeakyReLU(0.1, inplace=True),
            nn.Conv2d(2, 1, 1),
            nn.ReLU(),
        )
        self.upsampled_ = nn.ConvTranspose2d(1, 1, 4, 4)

    def forward(self, x1, x2):
        inputs = torch.stack([x1, x2], dim=2)

        rgb_mean = inputs.contiguous().view(inputs.size()[:2] + (-1,)).mean(dim=-1).view(
            inputs.size()[:2] + (1, 1, 1,))

        x = (inputs - rgb_mean) / self.rgb_max
        x1 = x[:, :, 0, :, :]
        x2 = x[:, :, 1, :, :]

        # FlownetC top input stream
        out_conv1a = self.conv1(x1)
        out_conv2a = self.conv2(out_conv1a)
        out_conv3a = self.conv3(out_conv2a)

        # FlownetC bottom input stream
        out_conv1b = self.conv1(x2)

        out_conv2b = self.conv2(out_conv1b)
        out_conv3b = self.conv3(out_conv2b)

        # Merge streams
        out_corr = self.corr(out_conv3a, out_conv3b)  # False
        out_corr = self.corr_activation(out_corr)

        # Redirect top input stream and concatenate
        out_conv_redir = self.conv_redir(out_conv3a)

        in_conv3_1 = torch.cat((out_conv_redir, out_corr), 1)

        # Merged conv layers
        out_conv3_1 = self.conv3_1(in_conv3_1)

        out_conv4 = self.conv4_1(self.conv4(out_conv3_1))

        out_conv5 = self.conv5_1(self.conv5(out_conv4))
        out_conv6 = self.conv6_1(self.conv6(out_conv5))

        flow6 = self.predict_flow6(out_conv6)
        flow6_up = self.upsampled_flow6_to_5(flow6)
        out_deconv5 = self.deconv5(out_conv6)

        concat5 = torch.cat((out_conv5, out_deconv5, flow6_up), 1)

        flow5 = self.predict_flow5(concat5)
        flow5_up = self.upsampled_flow5_to_4(flow5)
        out_deconv4 = self.deconv4(concat5)
        concat4 = torch.cat((out_conv4, out_deconv4, flow5_up), 1)

        flow4 = self.predict_flow4(concat4)
        flow4_up = self.upsampled_flow4_to_3(flow4)
        out_deconv3 = self.deconv3(concat4)
        concat3 = torch.cat((out_conv3_1, out_deconv3, flow4_up), 1)

        flow3 = self.predict_flow3(concat3)
        flow3_up = self.upsampled_flow3_to_2(flow3)
        out_deconv2 = self.deconv2(concat3)
        concat2 = torch.cat((out_conv2a, out_deconv2, flow3_up), 1)

        flow2 = self.predict_flow2(concat2)

        # Reduce to 1 channel
        flow2 = self.last_conv(flow2)

        # last_flow = self.upsample1(flow2)
        last_flow = self.upsampled_(flow2)

        return out_conv6, last_flow

if __name__ == "__main__":
    from argparse import Namespace
    cfg = Namespace()
    cfg.rgb_max = 255
    cfg.fp16 = False

    img = torch.rand(3, 3, 256, 256).cuda()

    net = FlowNet2C(cfg).cuda()

    out_conv6, last_flow = net(img, img)
    print(last_flow.size())


from sklearn.feature_extraction.text import TfidfVectorizer
import jieba

def main():
    str1 = "1、今天很残酷，明天更残酷，后天很美好， 但绝对大部分是死在明天晚上，所以每个人不要放弃今天。"
    str2 = "2、我们看到的从很远星系来的光是在几百万年之前发出的， 这样当我们看到宇宙时，我们是在看它的过去。"
    str3 = "3、如果只用一种方式了解某样事物，你就不会真正了解它。 了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。"
    str1_cut = jieba.cut(str1)
    str2_cut = jieba.cut(str2)
    str3_cut = jieba.cut(str3)
    str1_s = " ".join(str1_cut)
    str2_s = " ".join(str2_cut)
    str3_s = " ".join(str3_cut)
    tifid = TfidfVectorizer()
    rdata = tifid.fit_transform([str1_s, str2_s, str3_s])
    print(tifid.get_feature_names())
    print(rdata.toarray())
    print(rdata)

if __name__ == "__main__":
    main()


from flask import Flask, render_template, request, session, redirect, url_for, flash
from flask_mysqldb import MySQL
app = Flask(__name__)
app.secret_key = 'anahtar'

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'registerdb'

mysql = MySQL(app)

@app.route("/")
def Anasayfa():
    return render_template("movieapp.html")

@app.route("/login")
def Login():
    return render_template("login.html")

@app.route("/uyelik")
def Uyelik():
    return render_template("register.html")

@app.route("/hakkımda.html")
def Hakkımda():
    return render_template("hakkımda.html")

@app.route("/iletisim.html")
def İletisim():
    return render_template("iletisim.html")

@app.route("/kayit", methods=["POST"])
def kayit():
    if request.method == "POST":
        isim = request.form["isim"]
        soyisim = request.form["soyisim"]
        email = request.form["email"]
        sifre = request.form["sifre"]
        cinsiyet = request.form["cinsiyet"]

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO uyeler(isim, soyisim, email, sifre, cinsiyet) VALUES (%s, %s, %s, %s, %s)", (isim, soyisim, email, sifre, cinsiyet))
        mysql.connection.commit()
        cur.close()
        return "Kayıt başarılı bir şekilde eklendi."

@app.route("/giris", methods=["GET", "POST"])
def giris():
    if request.method == "POST":
        isim = request.form["isim"]
        sifre = request.form["sifre"]

        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM uyeler WHERE isim = %s AND sifre = %s", (isim, sifre))
        kullanıcı = cur.fetchone()
        cur.close()

        if kullanıcı:
            session["user_id"] = kullanıcı[0]
            return "Hoşgeldiniz: " + session["user_id"]
        else:
            flash("E-posta veya şifre yanlış. Lütfen tekrar deneyin.", "danger")
            return render_template("Login.html")

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


def Sortedmatrix_search(matrix, k):
    N = len(matrix)
    M = len(matrix[0])
    i = 0
    j = M -1
    for _ in range(N+M-1):
        if matrix[i][j] == k:
            return True
        elif matrix[i][j] > k and j >= 1:
            j -= 1
        elif matrix[i][j] < k and i < N-1:
            i += 1
        else:
            return False
demo = [[1,2,3,4],[3,4,6,7],[5,8,9,11]]
ans = Sortedmatrix_search(demo, 1)
print(ans)


import setuptools

with open("VERSION", "r") as f:
    version = f.read().strip()

with open("README.md", "r") as f:
    long_description = f.read()

setuptools.setup(
   name="cockpitdecks",
   version=version,
   description="Application to use streamdeck, loupedeck, and xtouch-mini with X-Plane flight simulator.",
   author="Pierre M",
   author_email="pierre@devleaks.be",
   url="https://github.com/devleaks/cockpitdecks",
   package_dir={"": "cockpitdecks"},
   packages=setuptools.find_packages(where="cockpitdecks"),
   install_requires=[
      "pillow>=9.5.0",
      "ruamel.yaml"
   ],
   license="MIT",
   long_description=long_description,
   long_description_content_type="text/markdown",
   include_package_data=True,
   python_requires=">=3.8,<3.11",
)


#! usr/bin/python3
# -*- coding:utf-8 -*-
"""Constants of MacGyver maze"""

# Window settings
sprite_side_number = 15
sprite_size = 40
info_wiev = 40
window_side = sprite_side_number * sprite_size
window_height = sprite_side_number * sprite_size + info_wiev

# The window customization
window_title = "MacGyver maze"
image_icon = "assets/MacGyver.png"

# Lists of the game's images
img_home = "assets/home.jpg"
img_background = "assets/background.jpg"
img_lose = "assets/lose.jpg"
img_win = "assets/win.jpg"
img_wall = "assets/wall.jpg"
img_mac_gyver = "assets/MacGyver.png"
img_guardian = "assets/guardian.png"
image_plastic_tube = "assets/plastic_tube.jpg"
image_ether = "assets/ether.png"
image_needle = "assets/needle.png"
image_syringe = "assets/syringe.png"


import argparse
from pathlib import Path
from typing import List

import torch
import yaml
from torch.cuda.amp import GradScaler, autocast
from torch.utils.data import DataLoader

from accent_estimator.config import Config
from accent_estimator.dataset import create_dataset
from accent_estimator.evaluator import Evaluator
from accent_estimator.generator import Generator
from accent_estimator.model import Model, ModelOutput, reduce_result
from accent_estimator.network.predictor import create_predictor
from accent_estimator.utility.pytorch_utility import (
    collate_list,
    detach_cpu,
    init_weights,
    make_optimizer,
    make_scheduler,
    to_device,
)
from accent_estimator.utility.train_utility import Logger, SaveManager

def train(config_yaml_path: Path, output_dir: Path):
    # config
    with config_yaml_path.open() as f:
        config_dict = yaml.safe_load(f)
    config = Config.from_dict(config_dict)
    config.add_git_info()

    # model
    predictor = create_predictor(config.network)
    model = Model(model_config=config.model, predictor=predictor)
    if config.train.weight_initializer is not None:
        init_weights(model, name=config.train.weight_initializer)

    device = "cuda" if config.train.use_gpu else "cpu"
    model.to(device)
    model.train()

    # evaluator
    generator = Generator(
        config=config, predictor=predictor, use_gpu=config.train.use_gpu
    )
    evaluator = Evaluator(generator=generator)

    # dataset
    datasets = create_dataset(config.dataset)

    def _create_loader(dataset, for_train: bool, for_eval: bool):
        if dataset is None:
            return None

        batch_size = (
            config.train.eval_batch_size if for_eval else config.train.batch_size
        )
        return DataLoader(
            dataset=dataset,
            batch_size=batch_size,
            shuffle=True,
            num_workers=config.train.num_processes,
            collate_fn=collate_list,
            pin_memory=config.train.use_gpu,
            drop_last=for_train,
            timeout=0 if config.train.num_processes == 0 else 30,
            persistent_workers=config.train.num_processes > 0,
        )

    datasets = create_dataset(config.dataset)
    train_loader = _create_loader(datasets["train"], for_train=True, for_eval=False)
    test_loader = _create_loader(datasets["test"], for_train=False, for_eval=False)
    eval_loader = _create_loader(datasets["test"], for_train=False, for_eval=True)
    valid_loader = _create_loader(datasets["valid"], for_train=False, for_eval=True)

    # optimizer
    optimizer = make_optimizer(config_dict=config.train.optimizer, model=model)
    scaler = GradScaler(enabled=config.train.use_amp)

    # logger
    logger = Logger(
        config_dict=config_dict,
        project_category=config.project.category,
        project_name=config.project.name,
        output_dir=output_dir,
    )

    # snapshot
    snapshot_path = output_dir / "snapshot.pth"
    if not snapshot_path.exists():
        iteration = -1
        epoch = -1
    else:
        snapshot = torch.load(snapshot_path, map_location=device)

        model.load_state_dict(snapshot["model"])
        optimizer.load_state_dict(snapshot["optimizer"])
        scaler.load_state_dict(snapshot["scaler"])
        logger.load_state_dict(snapshot["logger"])

        iteration = snapshot["iteration"]
        epoch = snapshot["epoch"]
        print(f"Loaded snapshot from {snapshot_path} (epoch: {epoch})")

    # scheduler
    scheduler = None
    if config.train.scheduler is not None:
        scheduler = make_scheduler(
            config_dict=config.train.scheduler,
            optimizer=optimizer,
            last_epoch=iteration,
        )

    # save
    save_manager = SaveManager(
        predictor=predictor,
        prefix="predictor_",
        output_dir=output_dir,
        top_num=config.train.model_save_num,
        last_num=config.train.model_save_num,
    )

    output_dir.mkdir(exist_ok=True, parents=True)
    with (output_dir / "config.yaml").open(mode="w") as f:
        yaml.safe_dump(config.to_dict(), f)

    # loop
    assert config.train.eval_epoch % config.train.log_epoch == 0
    assert config.train.snapshot_epoch % config.train.eval_epoch == 0

    for _ in range(config.train.stop_epoch):
        epoch += 1
        if epoch == config.train.stop_epoch:
            break

        train_results: List[ModelOutput] = []
        for batch in train_loader:
            iteration += 1

            with autocast(enabled=config.train.use_amp):
                batch = to_device(batch, device, non_blocking=True)
                result: ModelOutput = model(batch)

            optimizer.zero_grad()
            scaler.scale(result["loss"]).backward()
            scaler.step(optimizer)
            scaler.update()

            scheduler.step()

            train_results.append(detach_cpu(result))

        if epoch % config.train.log_epoch == 0:
            model.eval()

            with torch.inference_mode():
                test_results: List[ModelOutput] = []
                for batch in test_loader:
                    batch = to_device(batch, device, non_blocking=True)
                    result = model(batch)
                    test_results.append(detach_cpu(result))

                summary = {
                    "train": reduce_result(train_results),
                    "test": reduce_result(test_results),
                    "iteration": iteration,
                    "lr": optimizer.param_groups[0]["lr"],
                }

                if epoch % config.train.eval_epoch == 0:
                    eval_results: List[ModelOutput] = []
                    for batch in eval_loader:
                        batch = to_device(batch, device, non_blocking=True)
                        result = evaluator(batch)
                        eval_results.append(detach_cpu(result))
                    summary["eval"] = reduce_result(eval_results)

                    valid_results: List[ModelOutput] = []
                    for batch in valid_loader:
                        batch = to_device(batch, device, non_blocking=True)
                        result = evaluator(batch)
                        valid_results.append(detach_cpu(result))
                    summary["valid"] = reduce_result(valid_results)

                    if epoch % config.train.snapshot_epoch == 0:
                        torch.save(
                            {
                                "model": model.state_dict(),
                                "optimizer": optimizer.state_dict(),
                                "scaler": scaler.state_dict(),
                                "logger": logger.state_dict(),
                                "iteration": iteration,
                                "epoch": epoch,
                            },
                            snapshot_path,
                        )

                        save_manager.save(
                            value=summary["valid"]["value"], step=epoch, judge="max"
                        )

                logger.log(summary=summary, step=epoch)

            model.train()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("config_yaml_path", type=Path)
    parser.add_argument("output_dir", type=Path)
    train(**vars(parser.parse_args()))


from tables.TvShowTorrent import TvShowTorrent, TvTorrentParsingError
from common.BaseClass import BaseClass
from models.MediaFinder import MediaFinder
import pytest
bc = BaseClass('./config.ini')

def test_add_show()->None:
    torrent={
        'name':'Test torrent',
        'torrentId':'12345',
        'link':'test.link',
        'seeders':'23',
        'leechers':'34',
        'size':'2.1 GB',
        'time':'date string',
        'uploader':'up name',
        'uploaderLink':'up link',
        }
    show_torrent=TvShowTorrent()
    show_torrent.parse_data(torrent)
    assert show_torrent._torrent_id == '12345'

def test_filter_results()->None:
    show_list=[]
    bc = BaseClass('./config.ini')
    query=MediaFinder(bc)
    results = query.query('tv','')
    for show in results:
        search_show=TvShowTorrent()
        search_show.parse_data(show)
        if search_show.matches('',2,2) and \
            search_show._adjusted_size >0.8:
            show_list.append(search_show)
    assert len(show_list)> 0

def test_add_show_error()->None:
    error_catch=False
    torrent={
        'name':'Test torrent',
        'torrentId':'12345',
        'link':'test.link',
        'seeders':'23',
        'leechers':'34',
        'size':'2.1 GB',
        'time':'date string',
        'uploaderrr':'up name',
        'uploaderLink':'up link',
        }
    try:
        show_torrent=TvShowTorrent()
        show_torrent.parse_data(torrent)
    except TvTorrentParsingError:
        error_catch=True
    except :
        error_catch=False
    finally:
        assert error_catch==True


import string
from django.core.management.base import BaseCommand
from regluit.bisac.models import BisacHeading
from regluit.core.models import Subject

class Command(BaseCommand):
    help = "add and convert existing subjects to Bisac"

    def handle(self, **options):
        matches=0
        for bisac_heading in BisacHeading.objects.all():
            for subject in Subject.objects.filter(name=bisac_heading.full_label):
                subject.authority='bisacsh'
                subject.name = bisac_heading.full_label
                subject.save()
                matches += 1
        self.stdout.write("%s bisac headings converted" % matches)


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

from unittest.mock import MagicMock

from pyfritzhome import Fritzhome

from .helper import Helper

class TestFritzhomeDeviceTemperature(object):
    def setup_method(self):
        self.mock = MagicMock()
        self.fritz = Fritzhome("10.0.0.1", "user", "pass")
        self.fritz._request = self.mock
        self.fritz._devices = {}

    def test_get_temperature(self):
        self.mock.side_effect = [
            Helper.response("thermostat/device_hkr_fritzos_7"),
            "245",
        ]

        self.fritz.update_devices()
        device = self.fritz.get_device_by_ain("12345")

        assert device.get_temperature() == 24.5
        device._fritz._request.assert_called_with(
            "http://10.0.0.1/webservices/homeautoswitch.lua",
            {"ain": "12345", "switchcmd": "gettemperature", "sid": None},
        )


import numpy as np

from utils import get_dcg, get_precisionk

class Validator:
    '''This class holds the search function and the results of the search function
    with the queries from the Queries class and the relevance scores from the Validator class.'''
    def __init__(self):
        self.dcg = []
        self.ndcg = []
        self.precisionk = []
        # result of the search function in document ID, list of numpy arrays with document IDs in order of relevance
        self.results = []
        # search function results mapped to experts (first mentioned expert first) [['Alexander Mundt', 'Tatjana Gust']]
        self.rankings = []
        # search function results mapped to relevance scores, list of numpy arrays with top_k relevance scores
        self.scores = []
        self.scoresnan = []

    def __get_scores(self, expert2id, expert2query, expert2querynan, top_k):
        scores = []
        scoresnan = []
        for idx, result in enumerate(self.rankings):
            expert_ids = [expert2id[expert] for expert in result[0:top_k]]
            scores.append(expert2query[idx, expert_ids])
            scoresnan.append(expert2querynan[idx, expert_ids])
        self.scores = scores
        self.scoresnan = scoresnan

    def __get_ndcg(self, idcg):
        self.dcg = [get_dcg(score) for score in self.scores]
        self.ndcg = np.divide(self.dcg, idcg)

    def __get_precisionk(self):
        self.precisionk = [get_precisionk(score) for score in self.scores]

    def validate(self, rankings, truth):
        self.rankings = rankings
        self.__get_scores(truth.expert2id, truth.expert2query, truth.expert2querynan, truth.top_k)
        self.__get_ndcg(truth.idcg)
        self.__get_precisionk()
        return self.ndcg


from bottle import route,run,request
import ujson as json

kv = {}

@route('/kv')
def kv_op():
	req = request
	op = req.query.get('op')
	if op=='get':
		k = req.query.get('k')
		v = json.dumps(kv.get(k))
		return v
	elif op=='set':
		k = req.query.get('k')
		v = req.query.get('v')
		kv[k] = v
		return json.dumps({'k':k,'v':v})

#from gevent import monkey
#monkey.patch_all()
run(host='0.0.0.0',port=8080,server='meinheld')


import copy
import sys

import bitarray

def fibonacciEncoding(n, right):
    # this code will start from the largest index of the fibonacci that f <= n
    code_word = [0] * (right+2)

    # additional '1' bit
    code_word[right + 1] = 1
    # this loop will break when n =0, this means we find a sum of one or more distinct Fibonacci numbers

    while n:

        # mark the index is 1
        code_word[right] = 1

        # Subtract this fibonacci at index from n
        n -= fib[right]

        # move to the left
        right -= 1

        # mark all index of Fibonacci > n as not used (0 bit),
        # move to the left
        while (right >= 0 and fib[right] > n):
            code_word[right] = 0
            right -= 1

    # return pointer to code_word
    return code_word

class nodeHuffan:
    def __init__(self, frequencies, c, leftNode = None, rightNode = None):
        # the frequencies of each unique character
        self.frequencies = frequencies
        # the unique character
        self.c = c
        # node left of current node
        self.leftNode = leftNode
        # node right of current node
        self.rightNode = rightNode
        # the bit of node 0 if the in the left, and 1 in the right
        self.bit = None

def getHuffanCodeWord(node, c):
    global dp
    # plus the current bit of this node to the string c

    c_1 = copy.deepcopy(c)
    if node.bit is not None:
        c_1.append(node.bit)

    # if node left not null move to the node left
    if node.leftNode:
        getHuffanCodeWord(node.leftNode, c_1)
    # if node right not null move to the node right
    if node.rightNode:
        getHuffanCodeWord(node.rightNode, c_1)
    # if both node are null, this is the final binary value of this char of this node
    if not node.rightNode and not node.leftNode:
        dp[ord(node.c)] = c_1

def huffan(nodes):

    while len(nodes) > 1:
        # sort the node following to the frequencies of each char
        nodes = sorted(nodes, key=lambda x: x.frequencies)

        l, r = nodes[0], nodes[1]
        # the small value is in the left node and set 0 bit
        # the large value is in the right node and set 1 bit
        l.bit = 0
        r.bit = 1
        # remove two of them of the array
        nodes.pop(0)
        nodes.pop(0)
        # create a new node represents the sum of frequencies of two node left and right
        combinedNode = nodeHuffan(l.frequencies + r.frequencies, l.c + r.c, l, r)

        # add new node to the array
        nodes.append(combinedNode)

    getHuffanCodeWord(nodes[0], [])

def writeOutput(bits):

    # Open output file with correct name
    with open('encodedBWT.bin', 'wb') as fh:
        bits.tofile(fh)

def readInput(txtFileName):
    # Open and read the text file
    txtFile = open(txtFileName, 'r')
    txt = txtFile.read()
    # Remember to close the file
    txtFile.close()

    return txt

def bisect_left(a, x, left, right):
    # This function returns the place in the sorted list where the number specified in the argument may be added
    # to keep the resultant list sorted. If the element already exists in the list,
    # the left most position  which it must be added is returned.
    while left < right:
        mid = (left + right) // 2
        if x <= a[mid]:
            right = mid
        else:
            left = mid + 1
    return right

if __name__ == '__main__':
    bits = bitarray.bitarray()
    global dp
    dp = [[]] * 127
    txtFileName = sys.argv[1]
    s = readInput(txtFileName)

    freq = [0] * 127
    nUniqChars = []
    frequencies = []
    # count the frequencies of each char
    for i in s:
        freq[ord(i)] += 1

    for i in range(0, 127):
        if freq[i] > 0:
            nUniqChars.append(chr(i))
            frequencies.append(freq[i])
    nodes = []
    # push both char and its frequency to the nodes
    for i in range(len(nUniqChars)):
        nodes.append(nodeHuffan(frequencies[i], nUniqChars[i]))

    # after this progress we will save the code word of each char in the dp array
    huffan(copy.deepcopy(nodes))
    maxN = 3
    a = 1
    b = 2
    c = 0
    # find the maximum index that when c > len(s) this loop will break
    while c <= len(s):
        c = a + b
        a = copy.deepcopy(b)
        b = c
        maxN += 1

    fib = [0 for i in range(maxN + 1)]
    fib[0] = 1
    fib[1] = 2
    i = 2
    # initialize the array fibonacci with max length is maxN
    # it will reduce the time in the next step when we find the fibonacci code word
    while fib[i - 1] <= len(s):
        fib[i] = fib[i - 1] + fib[i - 2]
        i += 1
    # use the bisect left that we created to find the lower bound of len(s) in the array fibonacci we create above
    # log(n) time complexity
    index = bisect_left(fib, len(s), 0, maxN)
    while fib[index] > len(s) or fib[index] == 0:
        index -= 1
    bits.extend( fibonacciEncoding(len(s), index))
    #print(maxN, fib[index], bits)
    index = bisect_left(fib, len(nUniqChars), 0, maxN)
    while fib[index] > len(nUniqChars) or fib[index] == 0:
        index -= 1
    bits.extend(fibonacciEncoding(len(nUniqChars), index))
    #print(fib[index], bits)
    for i in nodes:
        # convert char to ascii binary
        temp = str(bin(ord(i.c)))
        temp = temp[2:len(temp)]
        # if the binary length is less than 7 append 0 in the start until the length temp equal 7
        for j in range(len(temp), 7):
            temp = "0" + temp
        #print(bits, temp)
        for j in range(0, 7):
            if temp[j] == "0":
                bits.append(0)
            else:
                bits.append(1)
        # get the fibonacci code len
        index = bisect_left(fib, len(dp[ord(i.c)]), 0, maxN)
        while fib[index] > len(dp[ord(i.c)]) or fib[index] == 0:
            index -= 1
        bits.extend(fibonacciEncoding(len(dp[ord(i.c)]), index))
        # extend to bits huffman code of i.c
        bits.extend( dp[ord(i.c)])
        #print(bits,i, temp, fibonacciEncoding(len(dp[ord(i.c)]), index), dp[ord(i.c)])
    mark = [0] * 127
    for i in s:
        # if this char is marked, it will continue
        if mark[ord(i)]:
            continue
        mark[ord(i)] = 1
        # extend to bits huffman code of i.c
        bits.extend(dp[ord(i)])
        # get the fibonacci run len
        index = bisect_left(fib, freq[ord(i)], 0, maxN)
        while fib[index] > freq[ord(i)] or fib[index] == 0:
            index -= 1
        bits.extend(fibonacciEncoding(freq[ord(i)], index))
    #print(bits)
    writeOutput(bits)


# 정수 삼각형

def solution(triangle):
    memo = [triangle[0]]
    for i in range(1, len(triangle)):
        nxt = [memo[i-1][0] + triangle[i][0]]
        for j in range(1, i):
            nxt.append(max(memo[i-1][j-1], memo[i-1][j]) + triangle[i][j])
        nxt.append(memo[i-1][-1] + triangle[i][-1])
        memo.append(nxt)
    return max(memo[-1])

triangle = [[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]
print(solution(triangle))


class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        """
        Time O(n * m)
        Space O(n * m)
        思路：dp先找到最长公共子序列的长度，再用总长度减去两边的最长公共长度。
        dp[i][j]：以i-1为结尾的word1子序列中以j-1为结尾的word2子序列中最长公共子序列的个数dp[i][j]，总共两种情况，见注释。
        """
        dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]

        for i in range(1, len(word1) + 1):
            for j in range(1, len(word2) + 1):
                # 当字符相等的时候，及找到上一个字符的情况 +1
                if word1[i - 1] == word2[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                # 不相等的时候，可以删除word1或者删除word2当前字符达到子序列相等，取两者中最大值。
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

        max_common_string_length = dp[-1][-1]

        step_to_delete = len(word1) + len(word2) - 2 * max_common_string_length

        return step_to_delete

s = Solution()
print(s.minDistance(word1="leetcode", word2="etco"))


from django.db import models
import datetime
from attendance.models import *
from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
import os
from dotenv import load_dotenv
load_dotenv()
def sendsms(phone,msg):

    client = Client(os.getenv('Account_SID'), os.getenv('Auth_Token'))

    try:
        message = client.messages.create(
            body=f'{msg}',
            from_=os.getenv('Phone_Number'),
            to=phone
        )
    except TwilioRestException as e:
        print(e)
        return False

class student_requests(models.Model):
    request_id = models.CharField(max_length=100, null=False, unique=True)
    reason = models.CharField(max_length=300, null=False)
    guardian_phone = models.CharField(max_length=11, null=False)
    relation = models.CharField(max_length=100, null=False)
    guardian_name = models.CharField(max_length=100, null=False)
    status = models.CharField(max_length=100, null=False)
    date = models.DateField(auto_now_add=True)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    cc = models.CharField(max_length=100, null=True )
    hod = models.CharField(max_length=100,null = True)

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

        Student = self.student
        CC = Roles.objects.get( name = "CC", department = Student.department, semester = self.student.curent_sem, section = self.student.section)
        HOD = Roles.objects.get( name = "HOD", department = Student.department, semester = self.student.curent_sem)

        if CC :
            self.cc = CC.teacher.id

            if self.status == "Pending" or not self.status:
                teacher = Teacher.objects.get(id = CC.teacher.id)
                x=sendsms(f'+91{teacher.phone}', "Dear CC New request for approval is pending ")
                print(x)

        else :
            self.cc = "not found"

        if  HOD:
            self.hod = HOD.teacher.id

        else :

            self.hod = "not found"

        if not self.request_id:
            self.request_id = f"{self.student.roll}-{datetime.date.today().strftime('%Y%m%d')}"

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


from enum import Enum
import copy

class FigureState(Enum):
    Init = 0
    Checked = 1
    Current = 2  # текущая позиция фигуры (lastchecked)

class Figure:
    def __init__(self, typ: str, color: str, state: FigureState=FigureState.Init):
        self._typ = typ
        self._color = color
        self._state = state
        self.row = None
        self.column = None

    @property
    def typ(self):
        return self._typ

    @property
    def color(self):
        return self._color

    @property
    def state(self) -> FigureState:
        return self._state

    @state.setter
    def state(self, value):
        self._state = value

class Game:
    # lastchecked = None
    _figures = []

    def __init__(self, level):
        # level - это путь к файлу в директории levels
        self._tmplist = []
        self._make_level(level)
        self.define_place()
        self.win = False

        if self._figures is not None:
            # self.lastchecked = self._figures[0][0]
            self._figures[0][0].state = FigureState.Current
            self.count_checked = 1 # количество пройденных фигур
            self.list_checked = [self._figures[0][0]]

    @property
    def rows(self):
        return len(self._figures)

    @property
    def columns(self):
        return len(self._figures[0])

    @property
    def figures(self):
        return self._figures

    @figures.setter
    def figures(self, value):
        self._figures = value

    @figures.deleter
    def figures(self):
        self._figures = []

    # парсить файл и формировать список списков из фигур по нажатию кнопки Run
    def _make_level(self, level):
        f = open(level, 'r')
        #tmplist = []
        for fig in f:
            self._tmplist.append(Figure(fig.split()[0], fig.split()[1], FigureState.Init))
        f.close()
        self._figures = [self._tmplist[i:i+3] for i in range(0, 9, 3)] #  матрица из фигур 3 на 3

    # проверка, в одном ли подсписке (вертикаль/горизонталь)
    def define_place(self):
        for ind, sublist in enumerate(self._figures):
            for j in range(len(sublist)):
                self._figures[ind][j].row = ind
                self._figures[ind][j].column = j

    # def is_may_checked(self, chosen: Figure):          # проверка можно ли пойти в этот элемент (следующий)
    #     if chosen.state == FigureState.Init:
    #         if self.one_place(self.lastchecked, chosen):  проверка, находится ли элемент по вертикали или горизонтали
    #             if chosen.color == self.lastchecked.color or chosen.typ == self.lastchecked.typ:
    #                 return True
    #     return False

    # ИЗМЕНЕНИЯ ПО КЛИКУ МЫШИ
    def mouse_click(self, chosen: Figure) -> None:
        if len(self.list_checked) == len(self._tmplist):  # win
            return
        elif chosen.state == FigureState.Init:   # playing
            if self.list_checked[self.count_checked-1].row == chosen.row or \
               self.list_checked[self.count_checked - 1].column == chosen.column:             #  проверка, находится ли элемент по вертикали или горизонтали
                if chosen.color == self.list_checked[self.count_checked - 1].color or \
                   chosen.typ == self.list_checked[self.count_checked - 1].typ:  #  одинаковый тип или фигура
                    self.list_checked[self.count_checked - 1].state = FigureState.Checked    # белый крестик
                    chosen._state = FigureState.Current   #  тёмный крестик
                    self.list_checked.append(chosen)
                    self.count_checked += 1
            if self.count_checked == len(self._tmplist):
                self.win = True
        else:    # if no way out (lose)
            return

"""
читать из файла и создавать вложенные списки из элементов фигур, причём 1-ый элемент выделен крестиком изначально
    далее отдельный метод, проходящийся по матрице и проверяющий может ли быть использован этот элемент(сосед по столбцу или строке)

    мб ещё стоит учесть координаты каждой фигуры, чтобы корректно сделать нажатие мышью??? позишн сопоставляетсяс координатой мыши

    прописать состояние текущей игры !!!

      '''
              widget = QTableWidget(game.rows, game.columns)
              self.matrix = copy.deepcopy(self.game._figures)
                  for i in range(game.rows):
                 for j in range(game.columns):
                     item = QTableWidgetItem(self.matrix[i][j])
                     widget.setItem(game.rows, game.columns, item)
                     widget.setIcon
                     '''
"""


import os

from spaceship.engine.graphic import Renderer
from spaceship.engine.util import Vec, displayCalc
from spaceship.multi.game.entity.core import Entity, WorldCoord

class Enemy(Entity):

    @property
    def state(self):
        return {
            'client_size': self.client_size.to_dict(),
            'position': self.position.to_dict(),
            'life': self.life,
            'level': self.level,
            'id': self.id,
            'angle': self.angle
        }

    @state.setter
    def state(self, state):
        self.life = state['life']
        self.level = state['level']
        self.id = state['id']
        self.angle = state['angle']

        self.position.from_dict(state['position'])
        self.client_size.from_dict(state['client_size'])

    @staticmethod
    def create_client(wposition, level, render, camera):
        enemy = Enemy()
        enemy.position = WorldCoord.convert(wposition, camera.size)

        enemy.camera = camera
        enemy.render = render

        enemy.set_level(level)

        return enemy

    @staticmethod
    def create_server(id, cposition, level, life, csize):
        enemy = Enemy()
        enemy.id = id

        enemy.life = life
        enemy.level = level

        enemy.position = WorldCoord.format(cposition, csize)

        return enemy

    def __init__(self):
        Entity.__init__(self)

        self.size = displayCalc.percentage(Vec(20, 20))

        self.id = Entity.ID_NOTSET
        self.life = 100
        self.level = 0

    def draw(self, input, deltatime):
        if self.sprite is not None:

            self.render.image_ext(self.sprite, self.camera + self.position, self.size, self.angle)

    def set_level(self, level):
        spriteIndexStart = 12
        spriteIndexEnd = 24

        self.level = (level + spriteIndexStart)%spriteIndexEnd

        try:
            ships = os.listdir('./assets/ships')
            for i in range(spriteIndexStart, spriteIndexEnd):
                if self.level == i:
                    self.sprite = Renderer.load_image(
                        './assets/ships/'+ships[i])
                    break

            if self.sprite is None:
                raise Exception("")

        except:
            self.sprite = self.render.image_fill((0, 0, 0), self.size)


from math import pi
from operator import pos
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from Linkage import Linkage
from Plate import Plate
from Neckbrace import Neckbrace
import potential_final as pf
import geometry_final as gm
from scipy import io as scio

def get_path():
    p = pf.SphereWorld()
    data = scio.loadmat('sphereWorld6.mat')
    world = []
    for sphere_args in np.reshape(data['world'], (-1,)):
        sphere_args[1] = np.asscalar(sphere_args[1])
        sphere_args[2] = np.asscalar(sphere_args[2])
        world.append(gm.Sphere(*sphere_args))

    x_goal = data['xGoal']
    x_start = data['xStart']
    potential = {'x_goal': x_goal, 'shape': 'conic', 'repulsiveWeight': 0.05}
    p2 = pf.Total(p.world, potential)
    planned_parameters = {
        'nb_steps': 1600,
        'epsilon': 0.01,
        'U': lambda x: p2.eval(x),
        'control': lambda x: -p2.grad(x)
    }
    p1 = pf.Planner()
    xx = x_start[:, 0]
    x_path, u_path = p1.run(x_start[:, 0], planned_parameters)
    print (x_path)
    m = len(x_path)
    z = 15*np.ones(m)
    x_path = x_path.T
    x = x_path[0]
    y = x_path[1]

    # for sphere in (p.world):
    #     sphere = gm.Sphere(sphere.center, sphere.radius,
    #                        sphere.distance_influence)
    #     f_handle = lambda x: p2.eval(x.T[0])
    #     gm.field_plot_threshold(f_handle, 100)
    #
    # fig = plt.figure()
    # ax = Axes3D(fig)
    # ax.set_xlim3d(xmin=-7, xmax=7)
    # ax.set_xlabel("X", fontsize=20)
    # ax.set_ylim3d(ymin=-7, ymax=7)
    # ax.set_ylabel("Y", fontsize=20)
    # ax.set_zlim3d(zmin=0, zmax=14)
    # ax.set_zlabel("Z", fontsize=20)
    # ax.plot3D(x, y, z, 'gray')

    return (x,y,z)

def main():
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.set_xlim3d(xmin=-7, xmax=7)
    ax.set_xlabel("X", fontsize=20)
    ax.set_ylim3d(ymin=-7, ymax=7)
    ax.set_ylabel("Y", fontsize=20)
    ax.set_zlim3d(zmin=0, zmax=14)
    ax.set_zlabel("Z", fontsize=20)
    x, y, z = get_path()
    # len_p=len(x)
    # x1 = 0 * np.ones(len_p)
    # y1 = 0 * np.ones(len_p)
    # z1 = 4 * np.ones(len_p)

    # alpha =np.arccos(np.dot(x,x1)/(np.linalg.norm(x)*np.linalg.norm(x1)))
    #
    #
    # beta =  np.arccos(np.dot(y,y1)/(np.linalg.norm(y)*np.linalg.norm(y1)))

    alpha =  np.arctan(x/z)[0::50]
    beta =   np.arctan(y/z)[0::50]

    print (alpha)

    # Neckbrace robot with ring radius of 5
    neckbrace = Neckbrace(4, 4.5,
                          [pi / 6, 5 * pi / 6, 7 * pi / 6, 11 * pi / 6])

    div_pi_by = 18
    step_1 = np.linspace(pi / div_pi_by, 0, 5, endpoint=False)
    step_2 = np.linspace(0, -pi / div_pi_by, 5, endpoint=False)
    step_3 = np.linspace(-pi / div_pi_by, 0, 5, endpoint=False)
    step_4 = np.linspace(0, pi / div_pi_by, 5)

    # positions = np.hstack((step_1, step_2, step_3, step_4))
    positions = np.vstack((beta,alpha))

    azimuth = -84
    elevation = 45
    neckbrace.animate(positions, "normal_first.gif", azimuth, elevation, x,-y ,z)
    neckbrace.animate1(positions, "normal_first.gif", azimuth, elevation, x,-y ,z)

if __name__ == "__main__":
    get_path()
    main()
    plt.show()


from django.contrib import admin
from .models import ContentModel, FileModel
# Register your models here.
# Register your models here.
@admin.register( ContentModel)
class ProductAdmin( admin.ModelAdmin):
    list_display = ['id', 'user_mail', 'product_type']
    raw_id_fields = (
        "photo_0",
        "photo_1",
        "photo_2",
        "photo_3",
        "photo_4",
        "photo_5",
        "photo_6",
        "photo_7",
        "photo_8",
        "photo_9",
        "photo_10",
        "photo_11",
        "photo_12",
        "photo_13",
        "photo_14",
         )

@admin.register( FileModel)
class FileAdmin( admin.ModelAdmin):
    list_display = ['id', 'user_mail', 'product_type']


import os
import glob

import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, Subset
import torchvision.datasets as datasets
import torchvision.transforms as transforms

import random

import collections

__all__ = ['DataSet', 'Triplet', 'PairedSample']

def print_path():
    path = os.getcwd()
    print(path)

# dateset descriptor
DatasetDescriptor = collections.namedtuple(
    'DatasetDescriptor',
    [
        'splits_to_sizes',  # Splits of the dataset into training, val and test.
        'num_classes',  # Number of semantic classes, including the
                        # background class (if exists).
        'unknown_label',  # Unknown label value.
        'save_dir',     # Save directory of Dataset
    ])

_MNIST_INFORMATION = DatasetDescriptor(
    splits_to_sizes = { 'train': 60000,
                        'train_aug': 100000, # randomly choose?
                        'test': 10000,
                        'train_small': 100,},
    num_classes = 10,
    unknown_label = None,

    save_dir = './datasets/data',
)

_CIFAR10_INFORMATION = DatasetDescriptor(
    splits_to_sizes = { 'train': 50000,
                        'train_aug': 20000,
                        'train_small': 500,
                        'test': 10000},
    num_classes = 10,
    unknown_label = None,

    save_dir = './datasets/data',
)

_DATASETS_INFORMATION = {
    'mnist': _MNIST_INFORMATION,
    'cifar10': _CIFAR10_INFORMATION,
}

transform = transforms.ToTensor()

# Some Impletementations in building queue...
# {small_sample, data_aug,...}
class DataSet(Dataset):
    '''The class of dataset for networks training ans testing.
    -----------------------------------
    Parameters:
    dataset_name: str
        The name of the dataset
    split: str
        The type of the dataset, e.g. 'train', 'val', 'test'...
    train: bool
        The data for train or not
    aug: bool
        Augmented data or not
    small: bool
        True: only use a part samples of data to train or test
        False: use all the data
        data_small = data[small_idx]
    samples_small: list
        A list contain the index of the samples of small dataset
    data_aug / target_aug: torch.Tensor
        The data of augmented data. --------- add later
    N: int
        The number of sample in the dataset
    num_classes: int
        Number of the classes in the dataset
    unknown_label: int or None
        Unlabeled data or the data cannot be recognized
    data, target: torch.Tensor
        The data of the input and the target
    data_src / target_src: torch.Tensor format:NCHW
        The source data of the data and target
    classes: dictionary
        The names of each classes in the dataset
    '''
    def __init__(self, dataset='mnist', split='train', files_dir=None):
        super(DataSet, self).__init__()
        if dataset not in _DATASETS_INFORMATION:
            raise ValueError('The specified dataset is not supported yet.')

        self.dataset_name = dataset
        self.split = split

        self.train = _is_train(split)
        self.aug = _is_aug(split)
        self.small = _is_small(split)

        self.num_classes = _DATASETS_INFORMATION[dataset].num_classes
        self.unknown_label = _DATASETS_INFORMATION[dataset].unknown_label

        if files_dir is None:
            files_dir = _DATASETS_INFORMATION[dataset].save_dir

        self.data_src, self.target_src, self.classes = self._load(files_dir)

        if self.aug:
            self.data_aug, self.target_aug = self._aug((self.data_src, self.target_src))
            self.N = len(self.data_aug)
        else:
            self.N = _DATASETS_INFORMATION[dataset].splits_to_sizes[split]
            if _is_small(split):
                skip = len(self.data_src) // self.N
                self.small_idx = list(range(0, len(self.data_src), skip))[:self.N]
                # print(self.small_idx, type(self.target_src), len(self.target_src), type(self.small_idx))

    @property
    def data(self):
        if self.aug:
            return self.data_aug
        elif self.small:
            return self.data_src[self.small_idx]
        return self.data_src

    @property
    def target(self):
        if self.aug:
            return self.target_aug
        elif self.small:
            return self.target_src[self.small_idx]
        return self.target_src

    def _load(self, files_dir):
        if self.dataset_name == 'mnist':
            return _mnist_load(files_dir, self.train)
        elif self.dataset_name == 'cifar10':
            return _cifar10_load(files_dir, self.train)
        else:
            return _dataset_load(files_dir, dataset, split)

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: (image, target) where target is index of the target class.
        """
        img, target = self.data[index], self.target[index]

        return img, target

    def __len__(self) -> int:
        return self.N

    # Not Impletement
    def _aug(self, samples):
        return samples

def _is_train(split):
    return split.find('train') > -1

def _is_aug(split):
    return split.find('aug') > -1

def _is_small(split):
    return split.find('small') > -1

# not complete
def _aug(data, target):

    return data, target

def _mnist_load(files_dir, train):
    if not os.path.exists(files_dir):
        os.mkdir(files_dir)

    classes = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
                5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

    # train = _is_train(split)

    data_set = datasets.MNIST(files_dir, train=train, download=True) # data: torch.Tensor(uint8), targets: Tensor

    data, targets = data_set.data.type(torch.float32).div(255.).unsqueeze(dim=1), data_set.targets # uint8 -> float32
    # print(data.shape, targets.shape, data.type(), targets.type())

    return data, targets, classes

def _cifar10_load(files_dir, train):
    files_dir = os.path.join(files_dir, 'CIFAR10')

    if not os.path.exists(files_dir):
        os.mkdir(files_dir)

    data_set = datasets.CIFAR10(files_dir, train=train, download=True) # data: np.array(uint8), targets: List(int)

    data, targets = data_set.data.transpose((0, 3, 1, 2)), np.array(data_set.targets, dtype=np.int64)
    data, targets = torch.tensor(data, dtype=torch.float32).div(255.), torch.tensor(targets)
    # print(data.shape, targets.shape, data.type(), targets.type())

    classes = data_set.classes
    N = len(classes)
    classes = {i: classes[i] for i in range(N)}

    return data, targets, classes

# need to unify the format of dataset
def _dataset_load(files_dir, dataset, split):
    return []

class Triplet(Dataset):
    def __init__(self, dataset):
        super(Triplet, self).__init__()
        self.dataset = dataset

        self.num_classes = dataset.num_classes
        self.all_classes = set(range(self.num_classes))
        self.idxes = [ set((dataset.target.view(-1)==idx).nonzero().view(-1).numpy()) for idx in range(self.num_classes)]

    def __getitem__(self, idx):
        anchor = self.dataset.data[idx]
        target = self.dataset.target[idx]

        label_pos = int(target)
        label_neg = random.choice(tuple(self.all_classes - {label_pos}))

        idx_pos = random.choice(tuple(self.idxes[label_pos] - {idx}))
        idx_neg = random.choice(tuple(self.idxes[label_neg]))

        positive = self.dataset.data[idx_pos]
        negtive = self.dataset.data[idx_neg]

        return (anchor, positive, negtive), target

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

class PairedSample(DataSet):
    def __init__(self, dataset, num_sample=1):
        super(PairedSample, self).__init__()
        self.dataset = dataset

        self.num_sample = num_sample
        self.num_classes = dataset.num_classes
        self.all_classes = set(range(self.num_classes))
        self.idxes = [ set((dataset.target.view(-1)==idx).nonzero().view(-1).numpy()) for idx in range(self.num_classes)]

    def __getitem__(self, idx):
        anchor = self.dataset.data[idx]
        target = self.dataset.target[idx]
        positives = []

        label_pos = int(target)
        idxes_pos = random.choices(tuple(self.idxes[label_pos]- {idx}), k=self.num_sample)

        for i in idxes_pos:
            positives.append(self.dataset.data[i])

        return (anchor, positives), target

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


import streamlit as st

st.title("Our First App Based on the Sreamlet")
st.subheader("Predict about something you want ")

from PIL import Image
image=Image.open('logo.JPG')
st.image(image,use_column_width=True)

image=Image.open('logo 2.PNG')
st.image(image,use_column_width=True)

st.write("writing the text")

st.markdown("This is the Markdown ")
st.success("You successfully login ")
st.warning("something wrong happence")
st.help(range)
st.info("this is my website ")

import numpy as np
import pandas as pd

data=np.random.rand(5,20)
st.dataframe(data)

df=pd.DataFrame(np.random.rand(5,20),columns = ('col %d' % i for i in range(20)))
st.dataframe(df.style.highlight_max(axis=1))

st.text("----"*21)

chart_data=pd.DataFrame(np.random.randn(15,5),columns=['a','b','c','d','e'])
st.line_chart(chart_data)

st.text("////"*21)
st.area_chart(chart_data)

chart_data=pd.DataFrame(np.random.randn(3,5),columns=['a','b','c','d','e'])
st.bar_chart(chart_data)

# pip install matplotlib
import matplotlib.pyplot as plt
arr=np.random.normal(1,1,size=100)
plt.hist(arr,bins=20)
st.pyplot()

# import plotly
# import plotly.figure_factory as ff

# # Adding distplot
# x1=np.random.randn(200)%2
# x2=np.random.randn(200)
# x3=np.random.randn(200)%2

# hist_data=[x1,x2,x3]
# group_labels=['Group1','Group2','Group3']
# fig=ff.create_distplot(hist_data,group_labels,bin_size=[.2,.25,.5])

# st.plotly_chart(fig,use_container_width=True)

st.text("////"*20)

df=pd.DataFrame(np.random.randn(100,2)/[50,50]+[37.76,-122.4],columns=['lat','lon'])
st.map(df)

if st.button("Say hello"):
	 st.write("hello is here")
else:
     st.write("why are you here")

genre=st.radio("What is your favourite genre?",('Commady','Drama','Film','Doumentry'))

if genre=='Commady':
	st.write("Good")
# elif genre=='Drama':
#     st.write('Cool')
else:
    st.write("No")

# Select box
optionbox=st.selectbox("SElecting the singgle options ",('Fantastic','Good','Batter'))
st.write("your said your night : ",optionbox)

optionbox=st.multiselect("SElecting the multiple option:: ",('Fantastic','Good','Batter'))
st.write("your said your night : ",optionbox)

age=st.slider('How Old Are Your??',0,100,30)
st.write('Your age is ',age)

value=st.slider("Select range :",0,200,(15,100))
st.write("the range is ", value)

number=st.number_input("Enetr the any number you want")
st.write('the number that youenter is :',number)

upload_file=st.file_uploader("Choose the csv file",type='csv')
if upload_file is not None:
	data=pd.read_csv(upload_file)
	st.write(data)
	st.success("successfully uploaded")
else:
    st.info("the file you uploaded is emty please a upload valid file")

# color picker
color=st.color_picker("Pick your favourite color",'#fff')
st.write("Your favourite color is :",color)

st.text("\\\\\\"*10)
# Sidebar
add_sidebar=st.sidebar.selectbox("Select your model:",('select ...','KNN','XGB','RandomForest'))

import time
my_bar=st.progress(0)
for percent_complete in range(100):
	time.sleep(0.1)
	my_bar.progress(percent_complete+1)

st.text("\\\\\\"*10)

with st.spinner('wait for it ...'):
    time.sleep(5)
st.success('successfully')

st.text("\\\\\\"*10)

st.ballooes()


import win10toast
import requests
import time
from bs4 import BeautifulSoup

def show_notification(map):
    toaster = win10toast.ToastNotifier()
    toaster.show_toast('CSGO Current Map Notifier','The map has changed to ' + map,'./steam.ico',duration=5)

def get_map():
    ip_addres = 'ip_addres'
    port = '27015'
    link = 'https://www.gametracker.com/server_info/' + ip_addres +':'+ port + '/'
    r = requests.get(link)
    source = BeautifulSoup(r.content,'html.parser')
    return(source.find("div",attrs={"class":"si_map_header"}).text)

current_map=''
while True:
    if(current_map!=get_map()):
        current_map = get_map()
        show_notification(current_map);

    time.sleep(60)


from heapq import heappop, heappush
# 구글링해서 공부하면서 쳤는데, 왜 그 사람 코드는 통과하고 나는 시간 초과..?
def dijkstra(x):
    heappush(heap, [x, 0])
    dist[x] = 0
    while heap:
        n, w = heappop(heap)
        if w > dist[n]:
            continue
        for num, wei in G[n]:
            new_wei = wei + w
            if new_wei < dist[num]:
                dist[num] = new_wei
                heappush(heap, [num, new_wei])

N, M, K, X = map(int, input().split())
G = [[] for _ in range(N + 1)]
dist = [1e6] * (N + 1)
heap = []
for _ in range(M):
    a, b = map(int, input().split())
    G[a].append([b, 1])

dijkstra(X)
result = []
for i in range(1, N + 1):
    if dist[i] == K:
        result.append(i)

if result:
    for r in result:
        print(r)
else:
    print(-1)

# BFS 통과
# import sys
# input = sys.stdin.readline
# from collections import deque
# # 266616KB, 7456ms bfs로 풀기...
# def bfs(x, K):
#     global result
#     stack = deque()
#     stack.append((x, 0))
#     while stack:
#         y, cnt = stack.popleft()
#         for j in range(1, N + 1):
#             if not visited[j] and j in temp_list[y]:
#                 cnt2 = cnt
#                 visited[j] = 1
#                 cnt2 += 1
#                 if cnt2 > K:
#                     return
#                 if cnt2 == K:
#                     result.add(j)
#                 stack.append((j,cnt2))
#
# N, M, K, X = map(int, input().split())
# N_list = [list(map(int, input().split())) for _ in range(M)]
# temp_list = [[] for _ in range(N + 1)]
# result = set()
# for i in range(M):
#     temp_list[N_list[i][0]].append(N_list[i][1])
# visited = [0] * (N + 1)
# visited[X] = 1
# bfs(X, K)
# if not result:
#     print(-1)
# else:
#     temp = []
#     for r in result:
#         temp.append(r)
#     temp.sort()
#     for t in temp:
#         print(t)


import torch
import torch.nn as nn
from torch.nn import functional as F

class ASPP(nn.Module):

    def __init__(self, inplanes, depth, conv=nn.Conv2d, norm=nn.BatchNorm2d, momentum=0.0003, mult=1):
        super(ASPP, self).__init__()
        self._inplanes = inplanes
        self._depth = depth

        self.global_pooling = nn.AdaptiveAvgPool2d(1)
        self.relu = nn.ReLU()
        self.aspp1 = conv(inplanes, depth, kernel_size=1, stride=1, bias=False)
        self.aspp2 = conv(inplanes, depth, kernel_size=3, stride=1,
                               dilation=int(6*mult), padding=int(6*mult),
                               bias=False)
        self.aspp3 = conv(inplanes, depth, kernel_size=3, stride=1,
                               dilation=int(12*mult), padding=int(12*mult),
                               bias=False)
        self.aspp4 = conv(inplanes, depth, kernel_size=3, stride=1,
                               dilation=int(18*mult), padding=int(18*mult),
                               bias=False)
        self.aspp5 = conv(inplanes, depth, kernel_size=1, stride=1, bias=False)
        self.aspp1_bn = norm(depth, momentum=momentum)
        self.aspp2_bn = norm(depth, momentum=momentum)
        self.aspp3_bn = norm(depth, momentum=momentum)
        self.aspp4_bn = norm(depth, momentum=momentum)
        self.aspp5_bn = norm(depth, momentum=momentum)
        self.conv2 = conv(depth * 5, depth, kernel_size=1, stride=1,
                               bias=False)
        self.bn2 = norm(depth, momentum=momentum)

    def forward(self, x):
        x1 = self.aspp1(x)
        x1 = self.aspp1_bn(x1)
        x1 = self.relu(x1)
        x2 = self.aspp2(x)
        x2 = self.aspp2_bn(x2)
        x2 = self.relu(x2)
        x3 = self.aspp3(x)
        x3 = self.aspp3_bn(x3)
        x3 = self.relu(x3)
        x4 = self.aspp4(x)
        x4 = self.aspp4_bn(x4)
        x4 = self.relu(x4)
        x5 = self.global_pooling(x)
        x5 = self.aspp5(x5)
        x5 = self.aspp5_bn(x5)
        x5 = self.relu(x5)
        x5 = F.interpolate(x5, (x.shape[2], x.shape[3]), mode='bilinear',
                           align_corners=False)
        x = torch.cat((x1, x2, x3, x4, x5), 1)
        x = self.conv2(x)
        x = self.bn2(x)
        x = self.relu(x)

        return x


#!/bin/env python3

import re
import sys

def main():
    lines = sys.stdin.readlines()
    base = list(lines[0].strip())
    patterns = {}

    for line in lines[2:]:
        tokens = line.split('->')
        x = tokens[0].strip()
        r = tokens[1].strip()
        patterns[x] = r

    for i in range(10):
        new_base = [base[0]]
        for tup in zip(base[:-1], base[1:]):
            chs = ''.join(tup)
            if chs in patterns:
                new_base.append(patterns[chs])
            new_base.append(chs[1])
        base = new_base

    freqs = {}
    for ch in base:
        if ch not in freqs:
            freqs[ch] = 0
        freqs[ch] += 1

    most_freq = max(freqs.values())
    least_freq = min(freqs.values())

    print('max - min: ', most_freq - least_freq)

if __name__ == '__main__':
    main()


import sys
import os
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import URLError
import json

def getMovieTitles(substr):
    item_list = []

    req = Request("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr)
    response = urlopen(req).read()
    data = json.loads(response.decode('utf-8'))

    total = data["total"]
    total_result = [""]*total

    page_count = data["total_pages"]
    page = int(data["page"])
    item_list += data["data"]

    while page < page_count:
        page += 1
        req = Request("https://jsonmock.hackerrank.com/api/movies/search/?Title={}&page={}".format(substr, page))
        response = urlopen(req).read()
        data = json.loads(response.decode('utf-8'))
        item_list += data["data"]

    for i in range(0,len(item_list)):
        total_result[i] = item_list[i]["Title"]

    return total_result

if __name__ == '__main__':
    print(getMovieTitles("spiderman"))


from theblockchainapi import TheBlockchainAPIResource, SolanaNetwork

# Get an API key pair for free here: https://dashboard.theblockchainapi.com/
MY_API_KEY_ID = None
MY_API_SECRET_KEY = None
BLOCKCHAIN_API_RESOURCE = TheBlockchainAPIResource(
    api_key_id=MY_API_KEY_ID,
    api_secret_key=MY_API_SECRET_KEY
)

def example():
    try:
        assert MY_API_KEY_ID is not None
        assert MY_API_SECRET_KEY is not None
    except AssertionError:
        raise Exception("Fill in your key ID pair!")

    # If you already know the candy machine ID, just enter it here.
    the_goat_society_candy_machine_id = "9htmDvW58pjCMQdjFbovo8cGBZviDfeP3j7DKnikHEy5"
    minted_nfts = BLOCKCHAIN_API_RESOURCE.get_nfts_minted_from_candy_machine(
        candy_machine_id=the_goat_society_candy_machine_id,
        network=SolanaNetwork.MAINNET_BETA
    )
    for nft in minted_nfts:
        print(nft)

    # If you don't know the candy machine ID, you can retrieve it if you have the mint address of an
    # NFT that has been minted from the candy machine.
    print("-" * 40)
    nft_mint_address = '4YmE6xzXAQ1HccBbzMgJh6NLn643ySrt1iXShUibrAsB'

    try:
        candy_machine_id = BLOCKCHAIN_API_RESOURCE.get_candy_machine_id_from_nft(
            mint_address=nft_mint_address,
            network=SolanaNetwork.MAINNET_BETA
        )
        minted_nfts = BLOCKCHAIN_API_RESOURCE.get_nfts_minted_from_candy_machine(
            candy_machine_id=candy_machine_id,
            network=SolanaNetwork.MAINNET_BETA
        )
        for nft in minted_nfts:
            print(nft)
    except Exception as e:
        print("Error")
        print(str(e))

if __name__ == '__main__':
    example()


from django import forms
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, ValidationError

from mosparo_api_client import Client
from mosparo_django.config import FrontendConfig
from mosparo_django.widgets import MosparoWidget

class MosparoField(forms.BooleanField):
    widget = MosparoWidget

    mosparo_host = None
    mosparo_uuid = None
    mosparo_public_key = None
    mosparo_private_key = None
    mosparo_verify_ssl = True

    callback_ignored_field_types = None
    callback_verifiable_field_types = None
    callback_after_prepare_form_data = None

    def __init__(self, mosparo_host=None, mosparo_uuid=None, mosparo_public_key=None, mosparo_private_key=None,
                 mosparo_verify_ssl=None, callback_ignored_field_types=None, callback_verifiable_field_types=None,
                 callback_after_prepare_form_data=None, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if not isinstance(self.widget, MosparoWidget):
            raise ImproperlyConfigured(
                "The widget must be a subclass of mosparo_django.widgets.MosparoWidget"
            )

        if mosparo_host is None:
            mosparo_host = getattr(settings, 'MOSPARO_HOST', '')

        if mosparo_uuid is None or mosparo_public_key is None or mosparo_private_key is None:
            mosparo_uuid = getattr(settings, 'MOSPARO_UUID', '')
            mosparo_public_key = getattr(settings, 'MOSPARO_PUBLIC_KEY', '')
            mosparo_private_key = getattr(settings, 'MOSPARO_PRIVATE_KEY', '')

        if mosparo_verify_ssl is None:
            mosparo_verify_ssl = getattr(settings, 'MOSPARO_VERIFY_SSL', True)

        self.mosparo_host = mosparo_host
        self.mosparo_uuid = mosparo_uuid
        self.mosparo_public_key = mosparo_public_key
        self.mosparo_private_key = mosparo_private_key
        self.mosparo_verify_ssl = mosparo_verify_ssl

        self.callback_ignored_field_types = callback_ignored_field_types
        self.callback_verifiable_field_types = callback_verifiable_field_types
        self.callback_after_prepare_form_data = callback_after_prepare_form_data

        frontend_config = FrontendConfig(self.mosparo_host, self.mosparo_uuid, self.mosparo_public_key)
        self.widget.set_frontend_config(frontend_config)

        # Hide the label for the field, important for the invisible mode.
        self.label = ''

    def validate(self, value):
        return True

    def verify_data(self, form: forms.Form):
        api_client = Client(
            self.mosparo_host,
            self.mosparo_public_key,
            self.mosparo_private_key,
            self.mosparo_verify_ssl
        )

        if '_mosparo_submitToken' not in form.data or '_mosparo_validationToken' not in form.data:
            raise ValidationError('mosparo specific fields were not found in the submitted data.')

        data = self.prepare_form_data(form)
        submit_token = form.data['_mosparo_submitToken']
        validation_token = form.data['_mosparo_validationToken']

        res = api_client.verify_submission(data['form_data'], submit_token, validation_token)

        if res != None:
            verified_fields = res.get_verified_fields()
            required_field_difference = set(data['required_fields']) - set(verified_fields.keys())
            verifiable_field_difference = set(data['verifiable_fields']) - set(verified_fields.keys())

            # The submission is only valid if all required and verifiable fields got verified
            if res.is_submittable() and not required_field_difference and not verifiable_field_difference:
                form.valid = True
                return

        form.valid = False
        raise ValidationError('mosparo could not verify the data. Please check the submission in mosparo.')

    def get_mosparo_host(self):
        return self.mosparo_host

    def get_mosparo_uuid(self):
        return self.mosparo_uuid

    def get_mosparo_public_key(self):
        return self.mosparo_public_key

    def prepare_form_data(self, form: forms.Form):
        data = { 'form_data': {}, 'required_fields': [], 'verifiable_fields': [] }
        ignored_field_types = [
            'PasswordInput',
            'HiddenInput',
            'MultipleHiddenInput',
            'FileInput',
            'ClearableFileInput',
            'MosparoField',
        ]
        if self.callback_ignored_field_types != None:
            ignored_field_types = self.callback_ignored_field_types(ignored_field_types)

        verifiable_field_types = [
            'TextInput',
            'Textarea',
            'EmailInput',
            'URLInput',
        ]
        if self.callback_verifiable_field_types != None:
            verifiable_field_types = self.callback_verifiable_field_types(verifiable_field_types)

        for key, field in form.fields.items():
            if type(field).__name__ in ignored_field_types or type(field.widget).__name__ in ignored_field_types:
                continue

            name = key

            if field.required:
                data['required_fields'].append(name)

            if type(field).__name__ in verifiable_field_types or type(field.widget).__name__ in verifiable_field_types:
                data['verifiable_fields'].append(name)

            if key in form.data:
                data['form_data'][key] = form.data[key]

        if self.callback_after_prepare_form_data != None:
            data = self.callback_after_prepare_form_data(data)

        return data


def main():
    game = list(input())
    player = {'A': 0, 'B': 0}
    i = 0
    while i < len(game):
        player[game[i]] += int(game[i + 1])
        i += 2
    print('A' if player['A'] > player['B'] else 'B')

if __name__ == "__main__":
    main()


import tensorflow as tf
from params import *
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.layers import Input, BatchNormalization, Activation, Dense, Dropout, Flatten, GlobalAveragePooling2D
from tensorflow.keras.layers.core import Lambda, RepeatVector, Reshape
from tensorflow.keras.layers.convolutional import Conv2D
from tensorflow.keras.layers.pooling import MaxPooling2D, GlobalMaxPool2D
from tensorflow.keras.layers.merge import concatenate
from tensorflow.keras import regularizers

def conv2d_block(input_tensor, n_filters, kernel_size=3, batchnorm=True):
    # first layer
    x = Conv2D(filters=n_filters, kernel_size=(kernel_size, kernel_size), kernel_initializer="he_normal",
               padding="same")(input_tensor)
    if batchnorm:
        x = BatchNormalization()(x)
    x = Activation("relu")(x)
    # second layer
    x = Conv2D(filters=n_filters, kernel_size=(kernel_size, kernel_size), kernel_initializer="he_normal",
               padding="same")(x)
    if batchnorm:
        x = BatchNormalization()(x)
    x = Activation("relu")(x)
    return x

def get_bunet(input_img, n_filters=16, dropout=0.5, batchnorm=True, training =True):

    # contracting path
    c1 = conv2d_block(input_img, n_filters=n_filters * 1, kernel_size=3, batchnorm=batchnorm)
    p1 = MaxPooling2D((2, 2))(c1)
    p1 = Dropout(dropout)(p1, training=training)

    c2 = conv2d_block(p1, n_filters=n_filters * 2, kernel_size=3, batchnorm=batchnorm)
    p2 = MaxPooling2D((2, 2))(c2)
    p2 = Dropout(dropout)(p2, training=training)

    c3 = conv2d_block(p2, n_filters=n_filters * 4, kernel_size=3, batchnorm=batchnorm)
    p3 = MaxPooling2D((2, 2))(c3)
    p3 = Dropout(dropout)(p3, training=training)

    c4 = conv2d_block(p3, n_filters=n_filters * 8, kernel_size=3, batchnorm=batchnorm)
    p4 = MaxPooling2D(pool_size=(2, 2))(c4)
    p4 = Dropout(dropout)(p4, training=training)

    c5 = conv2d_block(p4, n_filters=n_filters * 16, kernel_size=3, batchnorm=batchnorm)
    p5 = MaxPooling2D(pool_size=(2, 2))(c5)
    p5 = Dropout(dropout)(p5, training=training)

    c6 = conv2d_block(p5, n_filters=n_filters * 32, kernel_size=3, batchnorm=batchnorm)
    p6 = MaxPooling2D(pool_size=(2, 2))(c6)
    p6 = Dropout(dropout)(p6, training=training)

    c7 = conv2d_block(p6, n_filters=n_filters * 64, kernel_size=3, batchnorm=batchnorm)

    c8 = GlobalAveragePooling2D(data_format=None)(c7)

    d4 = Dense(5,kernel_initializer='normal',activation="softmax")(c8)

    outputs = d4

    model = Model(inputs=input_img, outputs=[outputs])
    return model


# CS194-26: Computational Photography
# Project 7: Image Warping and Mosaicing
# main.py
# Krishna Parashar

import os
import cv2
import math
import random
import scipy as sp
import numpy as np
import matplotlib.pyplot as plt

from scipy.spatial import distance
from scipy.ndimage import filters, interpolation

from manual import *

# Global Configurations
source_dir = 'data/'
extension = '.jpg'
dest_dir = 'results/'

def write_figure(img, name, x, y):
	fig = plt.imshow(img)
	fig.set_cmap('hot')
	plot(x, y, 'r*')
	plt.axis('off')
	plt.savefig("results/" + name, bbox_inches='tight')

def harris(img):
	# Harris Corner Detector with Adaptive Non-Maximal Suppression
	# Inspired by: http://cs.colby.edu/courses/S11/cs398/download/feature.py

	# img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	img = img.astype(np.float32)
	height, width = img.shape[0:2]

	# img_harris, corners = get_harris_corners(img) # Corners are [[y...][x...]]
	img_harris = cv2.cornerHarris(img, 2, 3, 0.04)

	img_harris[:10, :], img_harris[-10:, :] = 0, 0
	img_harris[:, :10], img_harris[:, -10:] = 0, 0

	harris_max = filters.maximum_filter(img_harris, (8,8))
	img_harris = img_harris * (img_harris == harris_max)

	indices = (np.argsort(img_harris.flatten())[::-1])[:500]
	x, y = (indices % width), (indices / width)

	return np.vstack((x, y)).T

def extract(img, corners, radius, scale):
	# Feature Descriptor Extractor
	img_filtered = filters.gaussian_filter(img, sigma=scale)
	num_corners = corners.shape[0]

	descriptors_size = (2 * radius) + 1
	descriptors = np.zeros((descriptors_size, descriptors_size, num_corners), dtype=float)

	for corner in range(num_corners):
		center_x, center_y = corners[corner, 0], corners[corner, 1]
		min_x, min_y = center_x - scale * radius, center_y - scale * radius
		max_x, max_y = center_x + scale * radius + 1, center_y + scale * radius + 1

		patch = img_filtered[min_y:max_y:scale, min_x:max_x:scale]

		patch = (patch - np.mean(patch)) / np.std(patch)
		descriptors[:, :, corner] = patch

	return descriptors

def match(img1_desc, img2_desc):
    # Feature Matcher
    tolerance = 0.4

    distances = distance.cdist(img1_desc, img2_desc)
    sorted_distances = np.argsort(distances, 1)

    best_index = sorted_distances[:, 0]
    indexes = np.arange(0, (img1_desc.shape[0]))

    closest_distance = distances[indexes, best_index]
    avg_second = np.mean(distances[indexes, (sorted_distances[:, 1])])

    ratio = closest_distance/avg_second

    number_matches = ratio[ratio < tolerance].shape[0]
    matches = np.zeros((number_matches, 2), dtype = np.int32)
    matches[:, 0] = indexes[ratio < tolerance]
    matches[:, 1] = best_index[ratio < tolerance]

    return matches

def ransac(matches):
	confidence = 0.95
	best_homography = np.zeros((3, 3))
	indices = np.arange(0, (matches.shape[0]))
	iterations = 0
	max_inliers = 0
	best_inlier = 0

	while (iterations < 5000):
		np.random.shuffle(indices)
		random_matches = matches[indices[:4]]
		match1, match2 = random_matches[:, :2], random_matches[:, 2:]

		homography = compute_homography(match2, match1)
		transformation_points = np.ones(((matches.shape[0]), 3))
		transformation_points[:, :2] = matches[:, 2:]

		transformation_matches = np.dot(homography, transformation_points.T)

		temp = np.zeros(transformation_matches.shape)
		for i in range(3):
			temp[i, :] = transformation_matches[i, :] / transformation_matches[2, :]

		transformation_matches = temp.T

		distance = np.sqrt(((matches[:, :2] - transformation_matches[:, :2])**2).sum(1))
		num_inliers = distance[distance < confidence].shape[0]

		if num_inliers > max_inliers:
			best_inlier = indices[distance < confidence]
			max_inliers = num_inliers
			best_homography = homography

		iterations += 1

	return best_homography

def get_homography(img1, img2):
    img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
    img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

    img1_corners = harris(img1_gray)
    img2_corners = harris(img2_gray)

    img1_descriptors = extract(img1_gray, img1_corners, 5, 1)
    img1_descriptors = img1_descriptors.reshape(((img1_descriptors.shape[0])**2, (img1_descriptors.shape[2]))).transpose()

    img2_descriptors = extract(img2_gray, img2_corners, 5, 1)
    img2_descriptors = img2_descriptors.reshape(((img2_descriptors.shape[0])**2, (img2_descriptors.shape[2]))).transpose()

    matches = match(img1_descriptors, img2_descriptors)
    matches = np.hstack(((img1_corners[matches[:, 0], :2]), (img2_corners[matches[:, 1], :2])))

    homography = ransac(matches)
    return homography

##################################################################################
#                          Automatic Image Panorama                              #
##################################################################################

# Global Configurations
source_dir = 'data/'
extension = '.jpg'
dest_dir = 'results/'

### Panorama Configurations
folder = 'london/'
img1_name = "1"
img2_name = "2"
panaroma_name = folder[:-1]
radius = 8
scale = 5

img1 = cv2.imread(source_dir + folder + img1_name + extension, -1)
img2 = cv2.imread(source_dir + folder + img2_name + extension, -1)

homography2_1 = get_homography(img2, img1)

img1_warped, shift1, img1w_shape = warp(img2, np.identity(3))

img2_warped, shift2, img2w_shape = warp(img1, homography2_1)

panorama = blend(img2_warped, img1_warped, shift2, img2w_shape)

write_img(dest_dir, panaroma_name, panorama, "_panaroma", extension)


from setuptools import setup, find_packages

requires = [
    'click',
    'biopython>=1.7',
    'pandas'
    ]

setup(
    name="tnseq2",
    version="1.0",
    author="Anna Sintsova",
    author_email="ansintsova@ethz.ch",
    description=("Bioinformatic toolkit for barcode mapping and counting"),
    license="LICENSE",
    keywords="tnseq",
    install_requires=requires,
    #url = "https://github.com/SushiLab/TNSEQ_DEV",
    packages=find_packages(),
    entry_points={
        'console_scripts': ['tnseq2=tnseq2.main:main'],
    }
)


import mock

from ovsdbapp.backend.ovs_idl import connection
from ovsdbapp.backend.ovs_idl import idlutils

from neutron.agent.ovsdb.native import connection as native_conn
from neutron.agent.ovsdb.native import exceptions as ovsdb_exc
from neutron.agent.ovsdb.native import helpers
from neutron.tests import base

SSL_KEY_FILE = '/tmp/dummy.pem'
SSL_CERT_FILE = '/tmp/dummy.crt'
SSL_CA_FILE = '/tmp/ca.crt'

class TestOVSNativeConnection(base.BaseTestCase):
    @mock.patch.object(connection, 'threading')
    @mock.patch.object(idlutils, 'wait_for_change')
    @mock.patch.object(native_conn, 'idl')
    @mock.patch.object(helpers, 'enable_connection_uri')
    @mock.patch.object(idlutils, 'get_schema_helper')
    def test_do_get_schema_helper_retry(self, mock_get_schema_helper,
                                        mock_enable_conn,
                                        mock_idl,
                                        mock_wait_for_change,
                                        mock_threading):
        mock_helper = mock.Mock()
        # raise until 3rd retry attempt
        mock_get_schema_helper.side_effect = [Exception(), Exception(),
                                              mock_helper]
        try:
            conn = connection.Connection(idl_factory=native_conn.idl_factory,
                                         timeout=mock.Mock())
        except TypeError:
            conn = connection.Connection(idl=native_conn.idl_factory(),
                                         timeout=mock.Mock())
        conn.start()
        self.assertEqual(3, len(mock_get_schema_helper.mock_calls))
        mock_helper.register_all.assert_called_once_with()

    @mock.patch.object(native_conn, 'Stream')
    @mock.patch.object(connection, 'threading')
    @mock.patch.object(native_conn, 'idl')
    @mock.patch.object(idlutils, 'get_schema_helper')
    @mock.patch.object(native_conn, 'os')
    @mock.patch.object(native_conn, 'cfg')
    def test_ssl_connection(self, mock_cfg, mock_os, mock_get_schema_helper,
                            mock_idl, mock_threading, mock_stream):
        mock_os.path.isfile.return_value = True
        mock_cfg.CONF.OVS.ovsdb_connection = 'ssl:127.0.0.1:6640'
        mock_cfg.CONF.OVS.ssl_key_file = SSL_KEY_FILE
        mock_cfg.CONF.OVS.ssl_cert_file = SSL_CERT_FILE
        mock_cfg.CONF.OVS.ssl_ca_cert_file = SSL_CA_FILE

        conn = connection.Connection(idl=native_conn.idl_factory(),
                                     timeout=1)
        conn.start()
        mock_stream.ssl_set_private_key_file.assert_called_once_with(
            SSL_KEY_FILE
        )
        mock_stream.ssl_set_certificate_file.assert_called_once_with(
            SSL_CERT_FILE
        )
        mock_stream.ssl_set_ca_cert_file.assert_called_once_with(
            SSL_CA_FILE
        )

    @mock.patch.object(native_conn, 'Stream')
    @mock.patch.object(connection, 'threading')
    @mock.patch.object(native_conn, 'idl')
    @mock.patch.object(idlutils, 'get_schema_helper')
    @mock.patch.object(native_conn, 'cfg')
    def test_ssl_conn_file_missing(self, mock_cfg, mock_get_schema_helper,
                                   mock_idl, mock_threading, mock_stream):
        mock_cfg.CONF.OVS.ovsdb_connection = 'ssl:127.0.0.1:6640'
        mock_cfg.CONF.OVS.ssl_key_file = SSL_KEY_FILE
        mock_cfg.CONF.OVS.ssl_cert_file = SSL_CERT_FILE
        mock_cfg.CONF.OVS.ssl_ca_cert_file = SSL_CA_FILE

        self.assertRaises(ovsdb_exc.OvsdbSslConfigNotFound,
                          native_conn.idl_factory)

    @mock.patch.object(native_conn, 'Stream')
    @mock.patch.object(connection, 'threading')
    @mock.patch.object(native_conn, 'idl')
    @mock.patch.object(idlutils, 'get_schema_helper')
    @mock.patch.object(native_conn, 'cfg')
    def test_ssl_conn_cfg_missing(self, mock_cfg, mock_get_schema_helper,
                                  mock_idl, mock_threading, mock_stream):
        mock_cfg.CONF.OVS.ovsdb_connection = 'ssl:127.0.0.1:6640'
        mock_cfg.CONF.OVS.ssl_key_file = None
        mock_cfg.CONF.OVS.ssl_cert_file = None
        mock_cfg.CONF.OVS.ssl_ca_cert_file = None
        self.assertRaises(ovsdb_exc.OvsdbSslRequiredOptError,
                          native_conn.idl_factory)


import random

from userbot import CMD_HELP
from userbot.utils import lightning_cmd

RUNSREACTS = [
    "`Aur Bata Bsdk Kar Liya Tunee Party De Chal!`",
    "`Chal Gand Phad Dunga Udd Mat Abb`",
    "`Oo Wow Mere Beta Sikh Gaya!`",
    "`Chall Badhiya Congo`",
    "`Fuck You And Congo.`",
    "`Mere Ladke Lavde te lashan Akhir  Karliya Tune.`",
    "`Very Good.`",
    "`Veryy Good Nhi Bulanga Bass Tu Chutiya Hai!”`",
    "`So pleased to see you accomplishing great things.`",
    "`Feeling so much joy for you today. What an impressive achievement!`",
]

@borg.on(lightning_cmd(pattern="chalbsdk"))
async def _(event):
    if event.fwd_from:
        return
    bro = random.randint(0, len(RUNSREACTS) - 1)
    reply_text = RUNSREACTS[bro]
    await event.edit(reply_text)

CMD_HELP.update(
    {
        "chalbsdk": "**congo_to_friend**\
\n\n**Syntax : **`.chalbsdk`\
\n**Usage :** This plugin is used to congratulate friend."
    }
)


"""bookflix URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import path,re_path
from gestion_usuario.views import home,welcome,register,login,logout,edit_profile,profile,index,change_profile_view,change_session_profile,register_profile,desactivar_perfil,historial,informe_usuario,borrar_comentario,terminar_lectura,terminar_capitulo,capitulo_terminado,change_password
from gestion_noticia.views import news,news_especifica,trailer,trailer_especifico
from gestion_libro.views import home_logueado,libro_especifico,libro_fav,SearchResultsView,libro_no_disponible,informe_libro,add_capitulo,edit_capitulo,dar_dislike,dar_like,borrar_puntaje, alerta, no_disponible,existente
from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('admin/informe_usuario', informe_usuario),
    path('admin/informe_libro', informe_libro),
    path('admin/gestion_libro/agregar_capitulo/<id_libro>', add_capitulo),
    path('admin/gestion_libro/editar_capitulo/<id_capitulo>', edit_capitulo),
    path('', home),
    # path('',welcome),
    path('register',register),
    path('login',login),
    path('logout',logout),
    path('profile/', profile),
    path('profile/edit_profile/', edit_profile),
    path('profile/desactivar_perfil/<id>', desactivar_perfil),
    path('libro/borrar_comentario/<id>', borrar_comentario),
    path('libro/terminar_lectura/<libro_id>', terminar_lectura),
    path('libro/terminar_capitulo/<capitulo_id>', terminar_capitulo),
    path('libro/capitulo_terminado', capitulo_terminado),
    path('alerta/<mensaje>', alerta),
    path('existente', existente),
    path('no-disponible/<mensaje>', no_disponible),
    path('change_profile/', change_profile_view),
    path('change_profile/<id>', change_session_profile),
    path('change_password', change_password),
    path('register_profile', register_profile),
    path('historial', historial),
    path('news/', news),
	path('news/<newsId>', news_especifica),
    path('libro/<libroId>', libro_especifico),
    path('home/', home_logueado),
	path('fav/<libroId>', libro_fav),
    path('search/', SearchResultsView.as_view(), name='search'),
    path('index', index),
	path('libronodisponible', libro_no_disponible),
    path('trailer', trailer),
    path('trailer/<trailerId>', trailer_especifico),
	path('like/<libroId>', dar_like),
	path('dislike/<libroId>', dar_dislike),
	path('borrarpuntaje/<libroId>', borrar_puntaje),

]
urlpatterns+= staticfiles_urlpatterns()

# Añadir
admin.site.site_header = 'Administracion Bookflix'


from subprocess import Popen, PIPE
import pandas as pd
from time import sleep, time
import numpy as np
import matplotlib.pyplot as plt
NETWORKS=['mlatAlpha','mlatBravo','mlatC','mlatDelta']
FREQUENCY=5200
def main():
    asd = networkScan("wlp1s0")
    # logRssi(networks,number of logs, time between logs in seconds)

    log, times = asd.logRssi(NETWORKS, 5,10)
    dlog=log
    for i in log:
        for j in range(len(log[i])):
            dlog[i][j]=distance(log[i][j])
    print(dlog)
    df = pd.DataFrame(dlog, index=times)

    df.to_csv("RSSIValues.csv")

"""    fig, ax = plt.subplots()
    ax.plot(times,dlog, label='mlatAlpha')
    plt.xlabel("time")
    plt.ylabel("meters")
    plt.title("15 second increments")
    #ax.plot(times,log['mlatBravo'], label='mlatBravo')
    #ax.plot(times,log['mlatC'], label='mlatC')
    #ax.plot(times,log['mlatDelta'], label='mlatDelta')
    #ax.legend()
    plt.show()
"""

def distance(RSSI):
    distance = 10 ** ((27.55 - (20 * np.log10(FREQUENCY)) + np.abs(RSSI)) / 20)
    return distance

class networkScan():
    def __init__(self, interface):
        self.interface = interface

    # This function passes a command that lists off all of the wifi connections and their properties
    # and returns it
    # interface reefers to the type of connection, ie wlp1s0
    def getNetworks(self):
        scanCommand = ["sudo", "iw", "dev", self.interface, "scan"]
        networkInfo = Popen(scanCommand, stdout=PIPE,stderr=PIPE)
        (raw_output, raw_error) = networkInfo.communicate()
        raw_output = raw_output.decode("utf-8")
        return [raw_output, str(raw_error)]

    # gets the networks SSID
    @staticmethod
    def getSSID(raw_cell):
        # grabs the string after 'ssid:' and then splits it at every ' '
        ssid = raw_cell.split('SSID:')[1]
        ssid = ssid.split()[0]
        return ssid

    # gets the signal level
    @staticmethod
    def getSignalLevel(raw_cell):
        # grabs the string after 'signal: ' and then splits it at every ' '
        rssi = raw_cell.split('signal: ')[1]
        rssi = float(rssi.split()[0])
        return rssi

    # gathers the data that we care about and puts it into a dictionary called cell
    def parseCell(self, raw_cell):
        cell = {
            'ssid': self.getSSID(raw_cell),
            'signal': self.getSignalLevel(raw_cell)
        }
        return cell

    # creates an array containing the information that we care about for each network
    def networkCells(self):
        raw_output, raw_error = self.getNetworks()
        # we split at wlp1so because it only appears once per network in the raw output
        raw_cells = raw_output.split('wlp1s0')
        # remove everything before the first instance of 'wlp1s0' becuase there is no useful information there
        # and therefore cant be parsed
        raw_cells.pop(0)
        network_cells = []
        for cell in raw_cells:
            network_cells.append(self.parseCell(cell))
        return network_cells

    # removes cells for networks that we do not care about
    def wantedNetworks(self, networks):
        wanted_network_cells = []
        for cell in self.networkCells():
            if cell['ssid'] in networks:

                wanted_network_cells.append(cell)
        print(wanted_network_cells)
        return wanted_network_cells

    def distances(self):

        pass

    # logs rss values into a dictionary with the format of {'ssid':[x,y,z]} where x,y, and z are rssi values
    def logRssi(self, networks, measures, delay):
        rss_log = {}
        current_time = 0
        times = []

        # sets up the dictionary for every network
        for i in networks:
            rss_log.update({i: []})

        # logs all rss values for the amount of measures chosen
        for i in range(measures):
            startTime = time()
            cells = self.wantedNetworks(networks)
            for j in range(len(networks)):
                values = rss_log[networks[j]]
                values.append(int(cells[j]['signal']))
                rss_log.update({networks[j]: values})
            sleep(delay)
            stopTime = time()
            totalTime = stopTime - startTime
            # logs the time for each measurement taken
            current_time += totalTime
            times.append(current_time)
            print(i)
        return (rss_log, times)

main()


import socket
from lib.manage import Connection

s = socket.socket()
s.bind(("0.0.0.0", 1234))
s.listen(1)

print(f"[i] Listening on 0.0.0.0:1234")

c, a = s.accept()
Connection(c).listen()


# 403. 青蛙过河
# 一只青蛙想要过河。 假定河流被等分为若干个单元格，并且在每一个单元格内都有可能放有一块石子（也有可能没有）。 青蛙可以跳上石子，但是不可以跳入水中。
# 给你石子的位置列表 stones（用单元格序号 升序 表示），请判定青蛙能否成功过河（即能否在最后一步跳至最后一块石子上）。
# 开始时，青蛙默认已站在第一块石子上，并可以假定它第一步只能跳跃一个单位（即只能从单元格 1 跳至单元格 2 ）。
# 如果青蛙上一步跳跃了 k 个单位，那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1 个单位。另请注意，青蛙只能向前方（终点的方向）跳跃。
def canCrossByEnumerating(stones: [int]) -> bool:
    def canCrossHelper(index: int, stride: int, result: bool):
        if index == len(stones) - 1:
            return True
        nextStep = index + 1
        while stones[nextStep] - stones[index] < stride + 2:
            if stones[nextStep] - stones[index] > stride - 2:
                result = result or canCrossHelper(nextStep, stones[nextStep] - stones[index], result)
            if result or nextStep == len(stones) - 1:
                break
            else:
                nextStep += 1
        return result

    if stones[1] - stones[0] != 1:
        return False
    else:
        output = canCrossHelper(1, 1, False)
    return output

stones = [0,1,3,5,6,8,12,17]
canCrossByEnumerating(stones)
stones = [0,1,2,3,4,8,9,11]
canCrossByEnumerating(stones)
stones = [0,1,3,6,10,15,16,21]
canCrossByEnumerating(stones)
stones = [0,1,3,6,7]
canCrossByEnumerating(stones)

def canCrossByDynamicProgramming(stones: [int]) -> bool:
    length = len(stones)
    dp = [[False] * length for _ in range(length)]
    dp[0][0] = True
    for i in range(1, length):
        if stones[i] - stones[i - 1] > i:
            return False
    for i in range(1, length):
        for j in range(i - 1, -1, -1):
            stride = stones[i] - stones[j]
            if stride > j + 1:
                break
            dp[i][stride] = dp[j][stride - 1] or dp[j][stride] or dp[j][stride + 1]
            if i == length - 1 and dp[i][stride]:
                return True
    return False

stones = [0,1,3,5,6,8,12,17]
canCrossByDynamicProgramming(stones)
stones = [0,1,2,3,4,8,9,11]
canCrossByDynamicProgramming(stones)
stones = [0,1,3,6,10,15,16,21]
canCrossByDynamicProgramming(stones)
stones = [0,1,3,6,7]
canCrossByDynamicProgramming(stones)


import numpy as np
from matplotlib import pyplot as plt

class GateCircl(object):
    def __init__(self):
        self.weight1: float = 0.0
        self.weight2: float = 0.0
        self.thera: float = 0.0

    def set(self, w1: float, w2: float, thera: float):
        self.weight1 = w1
        self.weight2 = w2
        self.thera = thera

    def ANDgate(self, x1, x2):
        tmp = x1 * self.weight1 + x2 * self.weight2
        if tmp < self.thera:
            return 0
        else:
            return 1

    def step_function(self,x:np):
        y = x > 0
        return y.astype(dtype=np.int64)

    def sigmoid(self,x:np):
        return 1 / (1 + np.exp(-x))

if __name__ == '__main__':
    g = GateCircl()
    x = np.arange(-10.0, 10.0, 0.1)
    y = g.sigmoid(x)
    plt.plot(x, y)
    plt.ylim(-0.1, 1.1)  # 指定y轴的范围
    plt.show()