"""
A "mirroring" ``stdout`` context manager.

comined mirror_gen.py & mirror_gen_exc.py
"""

# BEGIN MIRROR_GEN_EXC
import contextlib

@contextlib.contextmanager
def looking_glass():
    # __enter__() defination
    import sys
    original_write = sys.stdout.write

    def reverse_write(text):
        original_write(text[::-1])

    sys.stdout.write = reverse_write

    msg = ''  # <1>
    try:
        yield 'JABBERWOCKY'

    # __exit__() defination
    except ZeroDivisionError:  # <2>
        msg = 'Please DO NOT divide by zero!'
    finally:
        sys.stdout.write = original_write  # <3>
        if msg:
            print(msg)  # <4>
# END MIRROR_GEN_EXC

'''
The context manager can handle and "swallow" exceptions.
The following test does not pass under doctest (a
ZeroDivisionError is reported by doctest) but passes
if executed by hand in the Python 3 console (the exception
is handled by the context manager):
'''

if __name__ == '__main__':
    # While active, the context manager reverses text output to ``stdout``::
    # BEGIN MIRROR_GEN_DEMO_1
    with looking_glass() as what:  # <1>
        print('Alice, Kitty and Snowdrop')  # pordwonS dna yttiK ,ecilA
        print(what) # YKCOWREBBAJ
    print(what) # 'JABBERWOCKY'
    # END MIRROR_GEN_DEMO_1

    # This exposes the context manager operation::
    # BEGIN MIRROR_GEN_DEMO_2
    manager = looking_glass()  # <1>
    print(manager) # doctest: +ELLIPSIS <contextlib._GeneratorContextManager object at 0x...>
    monster = manager.__enter__()  # <2>
    print(monster == 'JABBERWOCKY')  # <3> eurT
    print(monster) # 'YKCOWREBBAJ'
    print(manager) # doctest: +ELLIPSIS >...x0 ta tcejbo reganaMtxetnoCrotareneG_.biltxetnoc<
    manager.__exit__(None, None, None)  # <4>
    print(monster) # 'JABBERWOCKY'
    # END MIRROR_GEN_DEMO_2

    # except test
    # BEGIN MIRROR_GEN_DEMO_3
    with looking_glass():
        print('Humpty Dumpty') # ytpmuD ytpmuH
        x = 1/0  # <1> Please DO NOT divide by zero! 正常顺序打印
        print('END')  # <2> 得不到执行的机会
    # END MIRROR_GEN_DEMO_3

    with looking_glass():
        print('Humpty Dumpty')
        x = no_such_name  # <1> Traceback (most recent call last): ... NameError: name 'no_such_name' is not defined
        print('END')  # <2>


#
# Working together problem in z3.
#
# From https://mindyourdecisions.com/blog/2017/08/13/can-you-solve-a-math-word-problem-that-stumps-us-college-students-a-working-together-problem/
# """
# Alice and Bob can complete a job in 2 hours.
# Alice and Charlie can complete the same job in 3 hours.
# Bob and Charlie can complete the same job in 4 hours.
# How long will the job take if Alice, Bob, and Charlie work together?
#
# Assume each person works at a constant rate, whether working alone
# or working with others.
# """
#
# [total = 24/13, alice = 7/24, bob = 5/24, charlie = 1/24]
#
# This Z3 model was written by Hakan Kjellerstrand (hakank@gmail.com)
# See also my Z3 page: http://hakank.org/z3/
#
from z3 import *

def working_together():
    s = SimpleSolver()

    alice, bob, charlie, total = Reals("alice bob charlie total")

    s.add(2*alice + 2*bob     == 1,
          3*alice + 3*charlie == 1,
          4*bob   + 4*charlie == 1,
          total*(alice+bob+charlie) == 1)

    while s.check() == sat:
        mod = s.model()
        print(mod)
        s.add(Or(alice != mod[alice], bob != mod[bob],
                 charlie != mod[charlie], total != mod[total]))

working_together()


# Ejercicio 1 - Operaciones básicas usando dos variables

# Pedimos por pantalla los dos valores con los que operaremos
a = int(input("Indique el primer valor: "))
b = int(input("Indique el segundo valor: "))

# Mostramos su suma
suma=a+b
texto="La suma de {} más {} es igual a {}."
print(texto.format(a,b,suma))

# Mostramos su resta
resta=a-b
texto="La resta de {} menos {} es igual a {}."
print(texto.format(a,b,resta))

# Mostramos el producto
producto=a*b
texto="El producto de {} por {} es igual a {}."
print(texto.format(a,b,producto))

# Mostramos la división salvo que el segundo valor sea cero
if (b==0):
    print("ERROR: el segundo valor es cero y no es posible dividir")
else:
    division=a/b
    texto="La división de {} entre {} es igual a {}."
    print(texto.format(a,b,division))


valorHamburguer = float(input())
quantidadeHamburguer = int(input())
valorBebida = float(input())
quantidadeBebida = int(input())
valorPago = float(input())

total = (valorHamburguer * quantidadeHamburguer) + (valorBebida * quantidadeBebida)
troco = valorPago - total

print(f'O preço final do pedido é R$ {total:.2f}. Seu troco é R$ {troco:.2f}.')


#!/usr/bin/env python
"""Script to import tags into hoover.

Receives a csv with tags as stdin. Use it like: tags.csv | -c collection -u username
"""
import subprocess
from argparse import ArgumentParser
import sys

parser = ArgumentParser()
parser.add_argument('-c', '--collection', dest='collection', required=True,
                    help='Collection for which the new tags should be added.')
parser.add_argument('-u', '--user', dest='username', required=True,
                    help='User for which tags should be added.')
parser.add_argument('-p', '--public', dest='public',
                    action='store_true', default=False,
                    help='Flag to set if the new tags should be public.')

args = parser.parse_args()

# check if any data has been received as stdin
if sys.stdin.isatty():
    print('No stdin received. Pass the csv with tags as stdin')
    print('Exiting')
    sys.exit(1)

# use devnull as stdin to prevent consuming the data that has been passed to the script
uuid_output = subprocess.run(['./liquid', 'dockerexec', 'hoover:search', './manage.py',
                              'getuuid', args.username],
                             capture_output=True,
                             stdin=subprocess.DEVNULL)

uuid = uuid_output.stdout.strip().decode('utf-8')

if not uuid:
    print(f'Error: Could not find uuid for user: {args.username}')
    sys.exit(1)

# stdin is passed to this subprocess
import_command = ['./liquid', 'dockerexec', 'hoover:snoop', './manage.py', 'importtags',
                  '-c', args.collection,
                  '--uuid', uuid,
                  '--user', args.username]
if args.public:
    import_command.append('--public')

subprocess.run(import_command)


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

# Common data to test the scrapers.

# AEL modules.
import resources.const as const
import resources.misc as misc

# Python standard library.
import sys

settings = {
    # --- AEL Offline ---
    'scraper_aeloffline_addon_code_dir' : '',

    # --- MobyGames ---
    'scraper_mobygames_apikey' : '', # NEVER COMMIT THIS PASSWORD

    # --- ScreenScraper ---
    'scraper_screenscraper_ssid' : 'Wintermute0110',
    'scraper_screenscraper_sspass' : '', # NEVER COMMIT THIS PASSWORD
    'scraper_screenscraper_AEL_softname' : 'AEL_0.9.8',
    'scraper_screenscraper_region' : 0, # Default World
    'scraper_screenscraper_language' : 0, # Default English

    # --- All scrapers ---
    'scraper_cache_dir' : './cache/'
}

# --- Test data -----------------------------------------------------------------------------------
games = {
    # Console games
    'metroid'                : ('Metroid', 'Metroid.zip', 'Nintendo SNES'),
    'mworld'                 : ('Super Mario World', 'Super Mario World.zip', 'Nintendo SNES'),
    'sonic_megadrive'        : ('Sonic the Hedgehog', 'Sonic the Hedgehog (USA, Europe).zip', 'Sega Mega Drive'),
    # Genesis is an aliased name for Mega Drive
    'sonic_genesis'          : ('Sonic the Hedgehog', 'Sonic the Hedgehog (USA, Europe).zip', 'Sega Genesis'),
    'chakan'                 : ('Chakan', 'Chakan (USA, Europe).zip', 'Sega MegaDrive'),
    'ff7'                    : ('Final Fantasy VII', 'Final Fantasy VII (USA) (Disc 1).iso', 'Sony PlayStation'),
    'console_wrong_title'    : ('Console invalid game', 'mjhyewqr.zip', 'Sega MegaDrive'),
    'console_wrong_platform' : ('Sonic the Hedgehog', 'Sonic the Hedgehog (USA, Europe).zip', 'mjhyewqr'),
    # Test Github AEL issue #142
    'bforever'               : ('batman forever', 'batman forever.zip', 'Unknown'),
    'bforever_snes'          : ('batman forever', 'batman forever.zip', 'Nintendo SNES'),

    # MAME games
    'atetris'             : ('Tetris (set 1)', 'atetris.zip', 'MAME'),
    'mslug'               : ('Metal Slug - Super Vehicle-001', 'mslug.zip', 'MAME'),
    'dino'                : ('Cadillacs and Dinosaurs (World 930201)', 'dino.zip', 'MAME'),
    'MAME_wrong_title'    : ('MAME invalid game', 'mjhyewqr.zip', 'MAME'),
    'MAME_wrong_platform' : ('Tetris (set 1)', 'atetris.zip', 'mjhyewqr'),
}

def abort_on_error(st_dic):
    if st_dic['abort']:
        print('st_dic abort dialog "{}"'.format(st_dic['dialog']))
        print('st_dic abort msg "{}"'.format(st_dic['msg']))
        sys.exit(0)

def handle_get_candidates(candidate_list, st_dic):
    if st_dic['abort']:
        print('st_dic abort dialog "{}"'.format(st_dic['dialog']))
        print('st_dic abort msg "{}"'.format(st_dic['msg']))
        sys.exit(0)
    if candidate_list is None:
        print('Error/exception in get_candidates(). Exiting.')
        sys.exit(0)
    if not candidate_list:
        print('No candidates found. Exiting.')
        sys.exit(0)

# These must be replaced with the table-making functions.
# TODO Move this code to dev-scrapers/common.py

# Candidates
NAME_L      = 65
SCORE_L     = 5
ID_L        = 55
PLATFORM_L  = 20
SPLATFORM_L = 20
URL_L       = 70

# Metadata
TITLE_L     = 50
YEAR_L      = 4
GENRE_L     = 20
DEVELOPER_L = 10
NPLAYERS_L  = 10
ESRB_L      = 20
PLOT_L      = 70

# Assets
ASSET_ID_L        = 10
ASSET_NAME_L      = 60
ASSET_URL_THUMB_L = 100

# PUT functions to print things returned by Scraper object (which are common to all scrapers)
# into util.py, to be resused by all scraper tests.
def print_candidate_list(results):
    p_str = "{} {} {} {} {}"
    print('Found {} candidate/s'.format(len(results)))
    print(p_str.format('Display name'.ljust(NAME_L), 'Score'.ljust(SCORE_L),
        'Id'.ljust(ID_L), 'Platform'.ljust(PLATFORM_L), 'SPlatform'.ljust(SPLATFORM_L)))
    print(p_str.format('-'*NAME_L, '-'*SCORE_L, '-'*ID_L, '-'*PLATFORM_L, '-'*SPLATFORM_L))
    for game in results:
        display_name = misc.limit_string(game['display_name'], NAME_L)
        score = misc.limit_string(const.text_type(game['order']), SCORE_L)
        id = misc.limit_string(const.text_type(game['id']), ID_L)
        platform = misc.limit_string(const.text_type(game['platform']), PLATFORM_L)
        splatform = misc.limit_string(const.text_type(game['scraper_platform']), SPLATFORM_L)
        print(p_str.format(display_name.ljust(NAME_L), score.ljust(SCORE_L), id.ljust(ID_L),
            platform.ljust(PLATFORM_L), splatform.ljust(SPLATFORM_L)))
    print('')

def print_game_metadata(metadata):
    title     = misc.limit_string(metadata['title'], TITLE_L)
    year      = metadata['year']
    genre     = misc.limit_string(metadata['genre'], GENRE_L)
    developer = misc.limit_string(metadata['developer'], DEVELOPER_L)
    nplayers  = misc.limit_string(metadata['nplayers'], NPLAYERS_L)
    esrb      = misc.limit_string(metadata['esrb'], ESRB_L)
    plot      = misc.limit_string(metadata['plot'], PLOT_L)

    p_str = "{} {} {} {} {} {} {}"
    print('Displaying metadata for title "{}"'.format(title))
    print(p_str.format('Title'.ljust(TITLE_L), 'Year'.ljust(YEAR_L), 'Genre'.ljust(GENRE_L),
        'Developer'.ljust(DEVELOPER_L), 'NPlayers'.ljust(NPLAYERS_L), 'ESRB'.ljust(ESRB_L), 'Plot'.ljust(PLOT_L)))
    print(p_str.format('-'*TITLE_L, '-'*YEAR_L, '-'*GENRE_L, '-'*DEVELOPER_L, '-'*NPLAYERS_L, '-'*ESRB_L, '-'*PLOT_L))
    print(p_str.format(title.ljust(TITLE_L), year.ljust(YEAR_L), genre.ljust(GENRE_L), developer.ljust(DEVELOPER_L),
        nplayers.ljust(NPLAYERS_L), esrb.ljust(ESRB_L), plot.ljust(PLOT_L) ))
    print('')

def print_game_assets(image_list):
    # print('Found {} image/s'.format(len(image_list)))
    p_str = "{} {} {}"
    print(p_str.format('Asset ID'.ljust(ASSET_ID_L), 'Name'.ljust(ASSET_NAME_L), 'URL thumb'.ljust(ASSET_URL_THUMB_L)))
    print(p_str.format('-'*ASSET_ID_L, '-'*ASSET_NAME_L, '-'*ASSET_URL_THUMB_L))
    for image in image_list:
        id           = misc.limit_string(const.text_type(image['asset_ID']), ASSET_ID_L)
        display_name = misc.limit_string(image['display_name'], ASSET_NAME_L)
        url_thumb    = misc.limit_string(image['url_thumb'], ASSET_URL_THUMB_L)
        print(p_str.format(id.ljust(ASSET_ID_L), display_name.ljust(ASSET_NAME_L),
            url_thumb.ljust(ASSET_URL_THUMB_L)))
    print('')


import configparser
import contextlib
import ctypes
import json
import sys
import time
from threading import Thread

import keyboard
import pymem

import mdt_cv

config_file = "config.ini"
cid_temp = 0
cid_temp_duel = 0
cid_temp_deck = 0
cid_temp_oppo = 0
cid_show_gui = 0
pause = False
process_exit = False
baseAddress = None
pm = {}
deck_addr = None
duel_addr = None
oppo_addr = None
sleep_time = 0.1
cv_mode = 0
cards_db_CN = {}
cards_db_TW = {}
ur_tier_list = {}
sr_tier_list = {}
break_point = {}
bgm_list = {}
pause_hotkey = "ctrl+p"
switch_hotkey = "ctrl+s"

def read_longlongs(pm, base, offsets):
    value = pm.read_longlong(base)
    for offset in offsets:
        value = pm.read_longlong(value + offset)
    return value

def get_cid(type: int):  # sourcery skip: inline-immediately-returned-variable
    global pm
    global deck_addr
    global duel_addr
    global oppo_addr
    while type == 1:
        try:
            deck_pointer_value = (
                read_longlongs(pm, deck_addr, [0xB8, 0x0, 0x108, 0x210]) + 0x2C
            )
            deck_cid = pm.read_int(deck_pointer_value)
            return deck_cid
        except Exception:
            return 0
    while type == 2:
        try:
            duel_pointer_value = read_longlongs(pm, duel_addr, [0xB8, 0x0, 0x108, 0xB0, 0xE0]) + 0x19C
            duel_cid = pm.read_int(duel_pointer_value)
            return duel_cid
        except Exception:
            return 0
    while type == 3:
        try:
            oppo_pointer_value = (
                read_longlongs(pm, oppo_addr, [0xB8, 0x0, 0x108, 0x138]) + 0x2C
            )
            oppo_cid = pm.read_int(oppo_pointer_value)
            return oppo_cid
        except Exception:
            return 0

def valid_cid(cid: int):
    return cid > 4000 and cid < 20000

def translate():
    global cid_temp_duel
    global cid_temp_deck
    global cid_temp_oppo
    global cid_show_gui
    global baseAddress
    if cv_mode == 0:
        if baseAddress is None:
            try:
                get_baseAddress()
            except Exception:
                return
        cid_deck = get_cid(1)
        cid_duel = get_cid(2)
        cid_oppo = get_cid(3)

        if valid_cid(cid_oppo) and cid_oppo != cid_temp_oppo:
            cid_temp_oppo = cid_oppo
            cid_show_gui = cid_oppo
        if valid_cid(cid_deck) and cid_deck != cid_temp_deck:
            cid_temp_deck = cid_deck
            cid_show_gui = cid_deck
        if valid_cid(cid_duel) and cid_duel != cid_temp_duel:
            cid_temp_duel = cid_duel
            cid_show_gui = cid_duel
    elif cv_mode == 1:
        cid_show_gui = mdt_cv.get_scan()

def translate_check_thread():
    global pause
    global process_exit
    global sleep_time
    while not process_exit:
        if not pause:
            translate()
        time.sleep(sleep_time)

def status_change(switch: bool, need_pause: bool, exit: bool):
    global pause
    global process_exit
    process_exit = exit
    pause = need_pause

def get_baseAddress():
    global pm
    global baseAddress
    global deck_addr
    global duel_addr
    global oppo_addr
    pm = pymem.Pymem("masterduel.exe")
    baseAddress = pymem.process.module_from_name(
        pm.process_handle, "GameAssembly.dll"
    ).lpBaseOfDll
    # deck 组卡界面 duel 决斗界面 oppo 回放
    deck_addr = baseAddress + int("0x01FF6F58", base=16)
    duel_addr = baseAddress + int("0x01FF6F58", base=16)
    oppo_addr = baseAddress + int("0x01FF6F58", base=16)

# UAC判断
def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except Exception:
        return False

# UAC重开
def uac_reload():
    if not is_admin():
        ctypes.windll.shell32.ShellExecuteW(
            None, "runas", sys.executable, " ".join(sys.argv), None, 1
        )
        sys.exit()

# 加载配置文件
def config_load():
    global pause_hotkey
    global switch_hotkey
    global cards_db_CN
    global cards_db_TW
    global ur_tier_list
    global sr_tier_list
    global break_point
    global bgm_list
    con = configparser.ConfigParser()
    with contextlib.suppress(Exception):
        con.read(config_file, encoding="utf-8")
        config = con.items("cli")
        config = dict(config)
        pause_hotkey = config["pause_hotkey"]
        switch_hotkey = config["switch_hotkey"]
    # 加载卡片文本
    with contextlib.suppress(Exception):
        with open("./locales/zh-CN/cards.json", "rb") as f:
            cards_db_CN = json.load(f)
    with contextlib.suppress(Exception):
        with open("./locales/zh-TW/cards.json", "rb") as f:
            cards_db_TW = json.load(f)
    with contextlib.suppress(Exception):
        with open("./data/ur.json", "rb") as f:
            ur_tier_list = json.load(f)
    with contextlib.suppress(Exception):
        with open("./data/sr.json", "rb") as f:
            sr_tier_list = json.load(f)
    with contextlib.suppress(Exception):
        with open("./data/breakpoint.json", "rb") as f:
            break_point = json.load(f)
    with contextlib.suppress(Exception):
        with open("./data/bgm.json", "rb") as f:
            bgm_list = json.load(f)

def get_current_cid():
    translate()
    return int(cid_show_gui)

def main():
    uac_reload()
    # 加载游戏
    with contextlib.suppress(Exception):
        get_baseAddress()
    config_load()
    keyboard.add_hotkey(switch_hotkey, status_change, args=(True, False, False))
    keyboard.add_hotkey(pause_hotkey, status_change, args=(False, True, False))
    p = Thread(target=translate_check_thread)
    p.start()
    p.join()

if __name__ == "__main__":
    main()


import argparse
import torch
import torch.onnx
from lib.config import config, update_config, hrnet
from collections import OrderedDict

def parse_args():
    parser = argparse.ArgumentParser(description='Train classification network')
    parser.add_argument('--cfg',
                        help='experiment configure file name',
                        required=False,
                        type=str,
                        default='./experiments/cls_hrnet_w18_sgd_lr5e-2_wd1e-4_bs32_x100.yaml')

    parser.add_argument('--modelDir',
                        help='model directory',
                        type=str,
                        default='')
    parser.add_argument('--logDir',
                        help='log directory',
                        type=str,
                        default='')
    parser.add_argument('--dataDir',
                        help='data directory',
                        type=str,
                        default='')
    parser.add_argument('--testModel',
                        help='testModel',
                        type=str,
                        default='')

    args = parser.parse_args()
    update_config(config, args)

    return args

def pth2onnx(input_file="", output_file=""):
    args = parse_args()

    checkpoint = torch.load("./output/imagenet/cls_hrnet_w18_sgd_lr5e-2_wd1e-4_bs32_x100/model_best.pth.tar", map_location='cpu')
    model = hrnet.get_cls_net(config)
    model.load_state_dict(checkpoint)
    model.eval()
    print(model)

    input_names = ["image_input"]
    output_names = ["output_1"]
    dynamic_axes = {'image': {0: '-1'}, 'class': {0: '-1'}}
    dummy_input = torch.randn(16, 3, 224, 224)
    torch.onnx.export(model, dummy_input, "hrnet_npu_16.onnx", input_names=input_names, dynamic_axes=dynamic_axes, output_names=output_names, verbose=True, opset_version=11)

if __name__ == "__main__":
    pth2onnx()


N = int(input())

result = 0

for i in range(N):
    s = input()

    if not s[0].isupper():
        continue

    s1 = set(s.split(" "))

    if len(s1) == 1:
        continue

    vowels = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}

    flag = False

    for word in s1:
        for char in word:
            if char in vowels:
                flag = True

    if not flag:
        continue

    flag = True

    digits ={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

    for word in s1:
        for char in word:
            if char in digits:
                flag = False

    if not flag:
        continue

    result += 1

print(result)


import uuid
from unittest.mock import ANY

from flask import current_app, json
from freezegun import freeze_time
import pytest
import requests_mock

from app.config import QueueNames
from app.celery.research_mode_tasks import (
    send_sms_response,
    send_email_response,
    telstra_callback,
    twilio_callback,
    ses_notification_callback,
    create_fake_letter_response_file,
)
from tests.conftest import set_config_values

def test_make_telstra_callback(notify_api, rmock):
    endpoint = "http://localhost:6011/notifications/sms/telstra/1234"
    rmock.request(
        "POST",
        endpoint,
        json={"status": "success"},
        status_code=200)
    send_sms_response("telstra", "1234", "0409000001")

    assert rmock.called
    assert rmock.request_history[0].url == endpoint
    assert json.loads(rmock.request_history[0].text)['to'] == '0409000001'

@pytest.mark.parametrize("phone_number",
                         ["0409000001", "0426305771", "0426305770",
                          "0412345678"])
def test_make_twilio_callback(notify_api, rmock, phone_number):
    endpoint = "http://localhost:6011/notifications/sms/twilio/1234"
    rmock.request(
        "POST",
        endpoint,
        json="some data",
        status_code=200)
    send_sms_response("twilio", "1234", phone_number)

    assert rmock.called
    assert rmock.request_history[0].url == endpoint
    assert 'To={}'.format(phone_number) in rmock.request_history[0].text

def test_make_ses_callback(notify_api, mocker):
    mock_task = mocker.patch('app.celery.research_mode_tasks.process_ses_results_task')
    some_ref = str(uuid.uuid4())

    send_email_response(reference=some_ref, to="test@test.com")

    mock_task.apply_async.assert_called_once_with(ANY, queue=QueueNames.RESEARCH_MODE)
    assert mock_task.apply_async.call_args[0][0][0] == ses_notification_callback(some_ref)

@pytest.mark.parametrize("phone_number", ["0409000001", "+61409000001", "409000001", "+61 409000001",
                                          "+61412345678"])
def test_delivered_telstra_callback(phone_number):
    data = json.loads(telstra_callback("1234", phone_number))
    assert data['to'] == phone_number
    assert data['deliveryStatus'] == "DELIVRD"

@pytest.mark.parametrize("phone_number", ["0426305771", "+61426305771", "426305771", "+61 426305771"])
def test_perm_failure_telstra_callback(phone_number):
    data = json.loads(telstra_callback("1234", phone_number))
    assert data['to'] == phone_number
    assert data['deliveryStatus'] == "UNDVBL"

@pytest.mark.parametrize("phone_number", ["0426305770", "+61426305770", "426305770", "+61 426305770"])
def test_temp_failure_telstra_callback(phone_number):
    data = json.loads(telstra_callback("1234", phone_number))
    assert data['to'] == phone_number
    assert data['deliveryStatus'] == "REJECTD"

@pytest.mark.parametrize("phone_number", ["0409000001", "+61409000001", "409000001", "+61 409000001",
                                          "+614123456"])
def test_delivered_twilio_callback(phone_number):
    assert twilio_callback('1234', phone_number) == {
        "AccountSid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "ApiVersion": "2010-04-01",
        "From": "+14155552345",
        "MessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "MessageStatus": "delivered",
        "SmsSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "SmsStatus": "delivered",
        "To": phone_number,
    }

@pytest.mark.parametrize("phone_number", ["0426305771", "+61426305771", "426305771", "+61 426305771"])
def test_failure_twilio_callback(phone_number):
    assert twilio_callback('1234', phone_number) == {
        "AccountSid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "ApiVersion": "2010-04-01",
        "From": "+14155552345",
        "MessageSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "MessageStatus": "undelivered",
        "SmsSid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        "SmsStatus": "undelivered",
        "To": phone_number,
    }

@freeze_time("2018-01-25 14:00:00")
def test_create_fake_letter_response_file_uploads_response_file_s3(
        notify_api, mocker):
    mock_s3upload = mocker.patch('app.celery.research_mode_tasks.s3upload')
    filename = 'NOTIFY-20180125140000-RSP.TXT'

    with requests_mock.Mocker() as request_mock:
        request_mock.post(
            'http://localhost:6011/notifications/letter/dvla/example-ref',
            content=b'{}',
            status_code=200
        )

        create_fake_letter_response_file('example-ref')

        mock_s3upload.assert_called_once_with(
            filedata='example-ref|Sent|0|Sorted',
            region=current_app.config['AWS_REGION'],
            bucket_name=current_app.config['DVLA_RESPONSE_BUCKET_NAME'],
            file_location=filename
        )

@freeze_time("2018-01-25 14:00:00")
def test_create_fake_letter_response_file_calls_dvla_callback_on_development(
        notify_api, mocker):
    mocker.patch('app.celery.research_mode_tasks.s3upload')
    filename = 'NOTIFY-20180125140000-RSP.TXT'

    with set_config_values(notify_api, {
        'NOTIFY_ENVIRONMENT': 'development'
    }):
        with requests_mock.Mocker() as request_mock:
            request_mock.post(
                'http://localhost:6011/notifications/letter/dvla/example-ref',
                content=b'{}',
                status_code=200
            )

            create_fake_letter_response_file('example-ref')

            assert request_mock.last_request.json() == {
                "Type": "Notification",
                "MessageId": "some-message-id",
                "Message": '{"Records":[{"s3":{"object":{"key":"' + filename + '"}}}]}'
            }

@freeze_time("2018-01-25 14:00:00")
def test_create_fake_letter_response_file_does_not_call_dvla_callback_on_preview(
        notify_api, mocker):
    mocker.patch('app.celery.research_mode_tasks.s3upload')

    with set_config_values(notify_api, {
        'NOTIFY_ENVIRONMENT': 'preview'
    }):
        with requests_mock.Mocker() as request_mock:
            create_fake_letter_response_file('example-ref')

            assert request_mock.last_request is None


from zipfile import ZipFile

FILES = [ 'file-a', 'file-b', 'file-c' ]

for i in range(1, 100):
    filename = f'sub{str(i).rjust(3, "0")}.zip'
    with ZipFile(f'data/{filename}') as file:
        contents = file.namelist()
        if len(contents) != 3 or not all(f in contents for f in FILES):
            print(filename)


from random import uniform

class LinearRegression:
    xs = [3520, 192, 91, 9271]
    results = [20, 3, 0, 88]

    def __init__(self):
        initialWeight = uniform(0, 1)
        initialBias = uniform(0, 1)
        learningRate = 0.00000004
        iterations = 2000

        print('Initial weight {}, Initial bias {}, Learning rate {}, Iterations {}'.format(initialWeight, initialBias, learningRate, iterations))
        finalWeight, finalBias = self.train(self.results, initialWeight, initialBias, self.xs, learningRate, iterations)
        finalError = self.cost(self.results, finalWeight, finalBias, self.xs)
        print('Final weight {:.4f}, Final bias {:.4f}, Final error {:.4f}, Prediction {:.4f} out of {}, Prediction Two {:.4f} out of {}'.format(finalWeight, finalBias, finalError, self.prediction(self.xs[1], finalWeight, finalBias), self.results[1], self.prediction(self.xs[3], finalWeight, finalBias), self.results[3]))

    # Python implementation
    def prediction(self, x, weight, bias):
        return weight * x + bias

    # The cost function implemented in python
    def cost(self, results, weight, bias, xs):
        error = 0.0
        numberOfDataPoints = len(xs)
        for i in range(numberOfDataPoints):
            error += (results[i] - (weight * xs[i] + bias)) ** 2
        return error / numberOfDataPoints

    # Python implementation, returns the optimized weight and bias for that step
    def optimizeWeightBias(self, results, weight, bias, xs, learningRate):
        weightDerivative = 0
        biasDerivative = 0
        numberOfDataPoints = len(results)
        for i in range(numberOfDataPoints):
            weightDerivative += -2 * xs[i] * (results[i] - (xs[i] * weight + bias))
            biasDerivative += -2 * (results[i] - (xs[i] * weight + bias))

        weight -= (weightDerivative / numberOfDataPoints) * learningRate
        bias -= (biasDerivative / numberOfDataPoints) * learningRate

        return weight, bias

    # Python implementation
    def train(self, results, weight, bias, xs, learningRate, iterations):
        error = 0
        for i in range(iterations):
            weight, bias = self.optimizeWeightBias(results, weight, bias, xs, learningRate)
            error = self.cost(results, weight, bias, xs)
            print("Iteration: {}, weight: {:.4f}, bias: {:.4f}, error: {:.2f}".format(i, weight, bias, error))
        return weight, bias

# Initialize the class
LinearRegression()


import random
import math

def gcd(a,b):
	#TODO: write non recursive version
	if b == 0: return a
	return gcd(b, a % b)

def extended_euclid(a,b):
	#return g, s, t such that g = sa + tb
	#see: https://www.csee.umbc.edu/~chang/cs203.s09/exteuclid.shtml
	#see: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Pseudocode
	#	for non recursive version

	#gcd(a, 0) = a = 1*a + 0*b
	if b == 0:
		return a, 1, 0

	#write a = qb + r where  r = (a mod b)
	#==> r = a - qb
	q = a/b
	#gcd(a, b) = gcd(b, a mod b) = xb  + y(a mod b)
	g, x, y = extended_euclid(b, a % b)
	#==>
	#gcd(a, b) = xb + y(a - qb) = ya + (x - yq)b
	return g, y, (x - y*q)

def mod_inv(a, n):
	'''computes a^(-1) mod n if gcd(a,n) = 1 otherwise returns None
	returns inverse in range (0, n)
	'''
	g, x, y = extended_euclid(a, n)
	#gcd(a,n) = g = xa + yn
	#a only has modular inverse if it is relatively prime with n
	if g != 1:
		return None
	#1 = gcd(a,n) = g = xa + yn  ==> xa = 1 (mod n)
	#ensure 0 < x < n
	while x < 0:
		x += n
	while x >= n:
		x -= n
	return x

def crt(a, n):
	'''Use the Chinese Remainder Theorem to find a solution to the series
	of congruences x_i = a_i (mod n_i) where gcd(n_i, n_j) = 1 for i != j
	Solution X is in range [0, Pi_{i} n_i)
	'''
	#Let N = product of n_is
	N = 1
	for n_i in n:
		N *= n_i
	#Let N_i = N/n_i
	Ni = [N/n_i for n_i in n]

	#Let b_i = N_i^(-1) (mod n_i) [existence of inverses guaranteed by fact that
	#the n_is are pairwise relatively prime
	b = [mod_inv(N_i, n_i) for N_i, n_i in zip(Ni, n)]

	#X = sum a_i*b_i*N_i is unique solution (modulo N) to system of congruences
	X = sum((a_i*b_i*N_i for a_i, b_i, N_i in zip(a, b, Ni))) % N
	return X

def ith_root(x, n):
	#find nth root of x using binary search
	#see: https://en.wikipedia.org/wiki/Talk%3ANth_root_algorithm
	#for other methods
	#TODO: test this more
	low, high = 1, x

	while low < high - 1:
		mid = (low + high)/2
		mid_cubed = mid ** n
		if mid_cubed < x:
			low = mid
		elif mid_cubed > x:
			high = mid
		else:
			return mid
	return low

def _test_gcd():
	assert(gcd(123, 123) == 123)
	assert(gcd(0, 123) == 123)
	assert(gcd(5*123, 123) == 123)
	assert(gcd(127, 33) == 1)
	assert(gcd(81, 33) == 3)
	assert(gcd(81, 512) == 1)

def _test_extended_euclid():
	assert(extended_euclid(123, 0) == (123, 1, 0))
	assert(extended_euclid(0, 123) == (123, 0, 1))
	assert(extended_euclid(99, 78) == (3, -11, 14))
	assert(extended_euclid(99, 78) == (3, -11, 14))

def _test_mod_inv():
	assert(mod_inv(78, 99) == None)
	assert(mod_inv(13, 60) == -23 + 60)

############ Primarily testing ########################
def fermat_test(n, trials=128):
	'''
	probabilistic test to see if n is prime
	for prime n, always returns True
	for random composite n, returns False with probability
	>= 1 - 1/2^trials
	'''
	#Fermat's little theorem:
	#if p is prime then a^n = a (mod n) for 0 < a < n

	#if n is odd then (n - 1)^n = (-1)^n = n - 1 (mod n)
	#if a = 1 then a^n = 1^n = 1 no matter the value of n
	#==> should only text for a in [2, n - 1)

	for _ in range(trials):
		a = random.SystemRandom().randrange(2, n - 1)
		if pow(a, n, n) != a:
			return False
	return True

def is_small_prime(n):
	'''primarily test for small integers'''
	if n % 2 == 0:
		return n == 2
	i = 3
	while i <= math.sqrt(n):
		if n % i == 0:
			return False
		i += 2
	return True

def sieve_of_eratosthenese(n):
	'''find all odd prime numbers <= n'''
	#only keep track of odd numbers
	l = int(math.ceil(n/2.0)) + 1

	#to check if i is prime, look at index (i - 1)/2
	nums = [True]*l
	primes = [2]
	upper_limit =  int(math.ceil(math.sqrt(n))) + 1
	#skip evens
	for i in range(3, upper_limit, 2):
		if nums[(i - 1)/2]:
			primes.append(i)
			#Start at i^2:
			#all composite numbers < i^2 have prime factor < i
			#==> they have already been marked as composite
			#
			#Count in increments of 2*i because every other multiple #is even
			for j in range(i*i, n + 1, 2*i):
				nums[(j - 1)/2] = False

	start_of_rest = upper_limit
	#ensure start of rest is odd
	if start_of_rest % 2 == 0:
		start_of_rest += 1
	for i in range(upper_limit, n + 1, 2):
		if nums[(i - 1)/2]:
			primes.append(i)
	return primes

#cache list of small primes to speed up search
_small_primes = []

def _ensure_small_primes_loaded():
	global _small_primes
	if not _small_primes:
		#loads first ~82k primes
		_small_primes = sieve_of_eratosthenese((1<<20))

def is_prime(n):
	'''tests if n is a prime'''
	global _small_primes
	_ensure_small_primes_loaded()
	#check divisibility by small primes to filter out most composites
	for p in _small_primes:
		if n % p == 0:
			return n == p
	if n <= _small_primes[-1]**2:
		return True

	#use Fermat's primarily test
	return fermat_test(n)

def find_prime(bit_length):
	'''finds a prime with given bit length'''
	upper_bound = (1<<bit_length)
	#lower bound is to prevent small primes from being found
	lower_bound = (1<<(bit_length - 1))
	rand = random.SystemRandom()
	while True:
		n = rand.randrange(lower_bound, upper_bound)
		#convert even to odd
		if n % 2 == 0:
			n += 1
		if is_prime(n):
			return n

def find_strong_prime(bit_length):
	'''finds a prime of the form p = aq + 1 for prim q and small a
	Note: this guarantees that p - 1 will have no small factors besides a'''
	#see: https://people.csail.mit.edu/rivest/pubs/RS01.version-1999-11-22.pdf
	#Rivest Are Strong Primes Need for RSA? Section 5
	q = find_prime(bit_length - 1)
	p = 2*q + 1
	two_q = 2*q
	while not is_prime(p):
		p += two_q
	return p
	#Timing from a laptop i5
	#$ time python -c "import number_theory as nt; nt.find_strong_prime(1024)"
	#real    0m27.405s
	#user    0m27.016s
	#sys     0m0.266s

def find_safe_prime(bit_length):
	'''find prime of the form p = 2q + 1 where q is prime'''
	while True:
		q = find_prime(bit_length - 1)
		n = 2*q + 1
		if is_prime(n):
			return n

def _test_is_small_prime():
	assert(is_small_prime(2))
	assert(is_small_prime(3))
	assert(not is_small_prime(4))
	assert(is_small_prime(5))
	assert(not is_small_prime(6))
	assert(is_small_prime(7))
	assert(not is_small_prime(8))
	assert(not is_small_prime(7*13))
	assert(is_small_prime(127))

def _test_sieve_of_eratosthenese():
	assert(sieve_of_eratosthenese(31) == [2,3,5,7,11,13,17,19,23,29,31])

def _test_is_prime():
	assert(is_prime(3))
	assert(not is_prime(4))
	assert(is_prime(5))
	assert(not is_prime(6))
	assert(is_prime(7))
	assert(not is_prime(8))
	assert(not is_prime(7*13))
	assert(is_prime(127))
	#source: http://www.bigprimes.net/archive/prime/101/
	assert(is_prime(104743))
	assert(is_prime(105023))
	assert(is_prime(105359))
	assert(is_prime(105613))
	assert(is_prime(179424691))
	assert(is_prime(179425033))
	assert(is_prime(179425601))
	assert(is_prime(179426083))

	#test on large composites
	assert(not is_prime(104743 * 105023))
	assert(not is_prime(179425601 * 179426083))

	#test on 512 bit prime
	#from http://jensign.com/JavaScience/dotnet/CSPPrimes/index.html
	assert(is_prime(13144131834269512219260941993714669605006625743172006030529504645527800951523697620149903055663251854220067020503783524785523675819158836547734770656069477))

if __name__ == '__main__':
	_test_gcd()
	_test_extended_euclid()
	_test_mod_inv()
	_test_is_small_prime()
	_test_sieve_of_eratosthenese()
	_test_is_prime()


from typing import List, NamedTuple

import yaml

from cros.factory.hwid.service.appengine import git_util
from cros.factory.hwid.v3 import filesystem_adapter
from cros.factory.utils import type_utils

class HWIDDBMetadata(NamedTuple):
  """A placeholder for metadata of a HWID DB."""
  name: str
  board_name: str
  version: int
  path: str

_INTERNAL_REPO_URL = 'https://chrome-internal-review.googlesource.com'
_CHROMEOS_HWID_PROJECT = 'chromeos/chromeos-hwid'

class HWIDRepoError(Exception):
  """Root exception class for reporting unexpected error in HWID repo."""

class HWIDRepo:
  _NAME_PATTERN_FOLDER = 'name_pattern'
  _AVL_NAME_MAPPING_FOLDER = 'avl_name_mapping'
  _PROJECTS_YAML_PATH = 'projects.yaml'

  def __init__(self, git_fs, repo_url, repo_branch):
    """Constructor.

    Args:
      git_fs: The git file system adapter to the HWID repo.
      repo_url: URL of the HWID repo.
      repo_branch: Branch name to track in the HWID repo.
    """
    self._git_fs = git_fs
    self._repo_url = repo_url
    self._repo_branch = repo_branch

  def IterNamePatterns(self):
    """Iterate through the name patterns recorded in the HWID repo.

    Yields:
      A tuple of (pattern name, pattern content).

    Raises:
      HWIDRepoError
    """
    try:
      for name in self._git_fs.ListFiles(self._NAME_PATTERN_FOLDER):
        content = self._git_fs.ReadFile(
            f'{self._NAME_PATTERN_FOLDER}/{name}').decode('utf-8')
        yield name, content
    except (KeyError, ValueError,
            filesystem_adapter.FileSystemAdapterException) as ex:
      raise HWIDRepoError(f'unable to retrieve name patterns: {ex}') from None

  def IterAVLNameMappings(self):
    """Iterate through the AVL name mappings recorded in the HWID repo.

    Yields:
      A tuple of (mapping file name, mapping file content).

    Raises:
      HWIDRepoError
    """
    try:
      for name in self._git_fs.ListFiles(self._AVL_NAME_MAPPING_FOLDER):
        content = self._git_fs.ReadFile(
            f'{self._AVL_NAME_MAPPING_FOLDER}/{name}').decode('utf-8')
        yield name, content
    except (KeyError, ValueError,
            filesystem_adapter.FileSystemAdapterException) as ex:
      raise HWIDRepoError(
          f'unable to retrive AVL name mappings: {ex}') from None

  def ListHWIDDBMetadata(self):
    """Returns a list of metadata of HWID DBs recorded in the HWID repo."""
    return list(self._hwid_db_metadata_of_name.values())

  def GetHWIDDBMetadataByName(self, name):
    """Returns the metadata of the specific HWID DB in the HWID repo."""
    try:
      return self._hwid_db_metadata_of_name[name]
    except KeyError:
      raise ValueError(f'invalid HWID DB name: {name}') from None

  def LoadHWIDDBByName(self, name):
    """Reads out the specific HWID DB content.

    Args:
      name: The project name of the HWID DB.  One can get the available names
          from the HWIDDBMetadata instances.

    Returns:
      A string of HWID DB content.

    Raises:
      ValueError if the given HWID DB name is invalid.
      HWIDRepoError for other unexpected errors.
    """
    try:
      path = self._hwid_db_metadata_of_name[name].path
    except KeyError:
      raise ValueError(f'invalid HWID DB name: {name}') from None
    try:
      return self._git_fs.ReadFile(path).decode('utf-8')
    except (KeyError, ValueError,
            filesystem_adapter.FileSystemAdapterException) as ex:
      raise HWIDRepoError(
          f'failed to load the HWID DB (name={name}): {ex}') from None

  def CommitHWIDDB(self, name, hwid_db_contents, commit_msg, reviewers,
                   cc_list):
    """Commit an HWID DB to the repo.

    Args:
      name: The project name of the HWID DB.
      hwid_db_contents: The contents of the HWID DB.
      commit_msg: The commit message.
      author: Author in form of "Name <email@domain>".
      reviewers: List of emails of reviewers.
      cc_list: List of emails of CC's.

    Returns:
      A numeric ID of the created CL.

    Raises:
      ValueError if the given HWID DB name is invalid.
      HWIDRepoError for other unexpected errors.
    """
    try:
      path = self._hwid_db_metadata_of_name[name].path
    except KeyError:
      raise ValueError(f'invalid HWID DB name: {name}') from None
    new_files = [
        (path, git_util.NORMAL_FILE_MODE, hwid_db_contents.encode('utf-8')),
    ]
    try:
      author_email, unused_token = git_util.GetGerritCredentials()
      author = f'chromeoshwid <{author_email}>'
      change_id = git_util.CreateCL(self._repo_url,
                                    git_util.GetGerritAuthCookie(),
                                    self._repo_branch, new_files, author,
                                    author, commit_msg, reviewers, cc_list)
      cl_info = git_util.GetCLInfo(_INTERNAL_REPO_URL, change_id,
                                   auth_cookie=git_util.GetGerritAuthCookie())
    except git_util.GitUtilException as ex:
      raise HWIDRepoError from ex
    return cl_info.cl_number

  @type_utils.LazyProperty
  def _hwid_db_metadata_of_name(self):
    try:
      raw_metadata = self._git_fs.ReadFile(self._PROJECTS_YAML_PATH)
    except (KeyError, ValueError,
            filesystem_adapter.FileSystemAdapterException) as ex:
      raise HWIDRepoError(
          f'failed to load {self._PROJECTS_YAML_PATH}: {ex}') from None
    try:
      metadata_yaml = yaml.safe_load(raw_metadata)
      hwid_db_metadata_of_name = {}
      for name, hwid_db_info in metadata_yaml.items():
        hwid_db_metadata_of_name[name] = HWIDDBMetadata(
            name, hwid_db_info['board'], hwid_db_info['version'],
            hwid_db_info['path'])
      return hwid_db_metadata_of_name
    except Exception as ex:
      raise HWIDRepoError(f'invalid {self._PROJECTS_YAML_PATH}: {ex}') from None

HWIDDBCLStatus = git_util.CLStatus

HWIDDBCLComment = git_util.CLMessage

class HWIDDBCLInfo(NamedTuple):
  status: HWIDDBCLStatus
  comments: List[HWIDDBCLComment]

class HWIDRepoManager:

  def __init__(self, repo_branch):
    """Constructor.

    Args:
      repo_branch: The git branch name of the HWID repo to access.  Assigning
          `None` to use the default "main" branch.
    """
    self._repo_branch = repo_branch

  def GetLiveHWIDRepo(self):
    """Returns an HWIDRepo instance for accessing the up-to-date HWID repo."""
    if self._repo_branch is None:
      repo_branch = git_util.GetCurrentBranch(_INTERNAL_REPO_URL,
                                              _CHROMEOS_HWID_PROJECT,
                                              git_util.GetGerritAuthCookie())
    else:
      repo_branch = self._repo_branch
    repo_url = f'{_INTERNAL_REPO_URL}/{_CHROMEOS_HWID_PROJECT}'
    git_fs = git_util.GitFilesystemAdapter.FromGitUrl(
        repo_url, repo_branch, git_util.GetGerritAuthCookie())
    return HWIDRepo(git_fs, repo_url, repo_branch)

  def GetHWIDDBCLInfo(self, cl_number):
    try:
      cl_info = git_util.GetCLInfo(_INTERNAL_REPO_URL, cl_number,
                                   auth_cookie=git_util.GetGerritAuthCookie(),
                                   include_detailed_accounts=True,
                                   include_messages=True)
    except git_util.GitUtilException as ex:
      raise HWIDRepoError from ex
    return HWIDDBCLInfo(cl_info.status, cl_info.messages)

  def GetMainCommitID(self):
    """Fetch the latest commit ID of the main branch on the upstream."""
    return git_util.GetCommitId(_INTERNAL_REPO_URL, _CHROMEOS_HWID_PROJECT,
                                auth_cookie=git_util.GetGerritAuthCookie())


from paho.mqtt import client as mqtt_client
from simple_rpc import Interface
import paho.mqtt.client as mqtt

broker = 'c-beam.cbrp3.c-base.org'
port = 1883
topic = "c_leuse/+"
client_id = 'c_leusen_leds'

print("Starting c_leusen_leds")
interface = Interface('/dev/ttyUSB0')

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe(topic)

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    if msg.topic == "c_leuse/led_pattern":
        # interface.method0(int(msg.payload.decode()))
        interface.method0(msg.payload)
        print(f"pattern {msg.payload.decode()} was set")

    print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(broker, port)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()


from google.cloud import bigquery

client = bigquery.Client()

table_id = "datafold-dev-2.data_diff.tmp_rating"
dataset_name = "data_diff"

client.create_dataset(dataset_name, exists_ok=True)

job_config = bigquery.LoadJobConfig(
    source_format=bigquery.SourceFormat.CSV,
    skip_leading_rows=1,
    autodetect=True,
)

with open("ratings.csv", "rb") as source_file:
    job = client.load_table_from_file(source_file, table_id, job_config=job_config)

job.result()  # Waits for the job to complete.

table = client.get_table(table_id)  # Make an API request.
print("Loaded {} rows and {} columns to {}".format(table.num_rows, len(table.schema), table_id))

# run_sql("ALTER TABLE `datafold-dev-2.data_diff.Rating` ADD COLUMN id BYTES")
# run_sql("UPDATE `datafold-dev-2.data_diff.Rating` SET id = cast(GENERATE_UUID() as bytes) WHERE True")


from src.entities.components.component import Component
import tcod

class Vision(Component):
    # stores an entity's field of view maps and level memory.
    # accessed to check if cells are in field-of-view.

    def __init__(self, owner, radius):
        Component.__init__(self, owner)
        self.radius = radius

        self.fov_map:tcod.map.Map = tcod.map.Map(5, 5)
        self.update_fov()

    def update_fov(self):
        self.fov_map = self.owner.level.get_fov_map()
        self.fov_map.compute_fov(self.owner.x, self.owner.y, self.radius, True, tcod.FOV_PERMISSIVE_7)

    def is_square_visible(self, x, y):
        if x < 0 or x >= self.fov_map.width or y < 0 or y >= self.fov_map.height:
            return False
        else:
            return self.fov_map.fov[y][x]


import math
str1 = input()
def isPelindrom(s):
	if len(s) == 1:
		return True
	for i in range(len(s) // 2):
		if s[i] != s[-(i + 1)]:
			return False
	if not isPelindrom(s[:len(s)//2]) or not isPelindrom(s[int(math.ceil(len(s)/2)):]):
		return False
	return True
if isPelindrom(str1):
	print("AKARAKA")
else:
	print("IPSELENTI")


class BankAccount:
    balance = 0
    def __init__(self,minimum_balance=0):
        self.minimum_balance = minimum_balance

    def deposit(self,deposit):
        self.deposit = deposit
        if self.deposit >= 0:
            BankAccount.balance += self.deposit
        else:
            print("The amount must be positive, bye bye")

    def withdraw(self,withdraw):
        self.withdraw = withdraw
        if self.withdraw >= 0:
            BankAccount.balance -= self.withdraw
        else:
            print(f"The amount must be positive, bye bye")

class MinimumBalanceAccount(BankAccount):
    def withdraw(self,withdraw):
        self.withdraw = withdraw
        if self.withdraw - BankAccount.balance > self.minimum_balance:
            BankAccount.withdraw(self.withdraw)
        else:
             print(f"You can not withdraw more than your current balance of {BankAccount.balance}, bye bye")

deposit_1 = MinimumBalanceAccount()
deposit_1.deposit(50)
withdraw_1 = MinimumBalanceAccount()
withdraw_1.withdraw(10)
print(BankAccount.balance)


import datetime

class NewFileTest:
    def __init__(self, filename, first_line, napr):
        self.filename = filename
        self.first_line = first_line
        self.napr = napr
        self.ko = None

    def setKo(self):
        if self.ko == 0:
            print(f"Файл {self.filename} успешно создан")
        else:
            print(f"Ошибка при создании файла {self.filename}")

    def createFile(self):
        try:
            with open(self.filename, "a") as f:
                f.write(self.first_line)
                f.write("\n")
                f.write(str(datetime.datetime.now()))
                f.write("\n")
                f.write(str(self.napr))
                f.write("\n")
                f.write("END\n")
            self.ko = 0
        except Exception as e:
            print(f"Ошибка: {e}")
            self.ko = 1
            self.setKo()


from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'put account sid here'
auth_token = 'put auth token here'
client = Client(account_sid, auth_token)

message = client.messages \
                .create(
                     body="Test!",
                     from_='put twilio phone number here',
                     to='put recipient phone number here'
                 )

print(message.sid)


import re
import sys
from PyQt5.QtWidgets import QApplication,QMainWindow
import untitled
import requests

def ceshi():
    a = ui.lineEdit.text()
    url = 'http://192.168.7.30:8008/ad'
    res = requests.get(url)
    ad_name = res.json()
    try:
        adname = ad_name[f'{a}']
        if a == '':
            ui.textBrowser.setText('请输入key')
        else:
            ui.textBrowser.setText(f'{str(adname)}')
    except:
        ui.textBrowser.setText('请输入对应的key')

if __name__ == '__main__':
    # 初始化数据
    # 。。。。。
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = untitled.Ui_Form()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ui.pushButton.clicked.connect(ceshi)

    sys.exit(app.exec_())


import cx_Freeze

executables = [cx_Freeze.Executable("WordStats.py")]

cx_Freeze.setup(
    name="WordStats",
    options={"build_exe": {"packages": ['pymsgbox', 'matplotlib', 'numpy']}},
    version='1.1',
    description='A simple text analyzer.',
    author='Sean Xie',
    executables=executables
)


#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
import torch.nn as nn
import torch
from .GDN import GDN
import math

class Analysis_net_17(nn.Module):
    '''
    Analysis net
    '''
    def __init__(self, out_channel_N=192):
        super(Analysis_net_17, self).__init__()
        self.conv1 = nn.Conv2d(3, out_channel_N, 9, stride=4, padding=4)
        torch.nn.init.xavier_normal_(self.conv1.weight.data, (math.sqrt(2 * (3 + out_channel_N) / (6))))
        torch.nn.init.constant_(self.conv1.bias.data, 0.01)
        self.gdn1 = GDN(out_channel_N)
        self.conv2 = nn.Conv2d(out_channel_N, out_channel_N, 5, stride=2, padding=2)
        torch.nn.init.xavier_normal_(self.conv2.weight.data, math.sqrt(2))
        torch.nn.init.constant_(self.conv2.bias.data, 0.01)
        self.gdn2 = GDN(out_channel_N)
        self.conv3 = nn.Conv2d(out_channel_N, out_channel_N, 5, stride=2, padding=2, bias=False)
        torch.nn.init.xavier_normal_(self.conv3.weight.data, math.sqrt(2))
        # torch.nn.init.constant_(self.conv3.bias.data, 0.01)
        # self.gdn3 = GDN(out_channel_N)
        # self.conv4 = nn.Conv2d(out_channel_N, out_channel_M, 5, stride=2, padding=2)
        # torch.nn.init.xavier_normal_(self.conv4.weight.data, (math.sqrt(2 * (out_channel_M + out_channel_N) / (out_channel_N + out_channel_N))))
        # torch.nn.init.constant_(self.conv4.bias.data, 0.01)

    def forward(self, x):
        x = self.gdn1(self.conv1(x))
        x = self.gdn2(self.conv2(x))
        x = self.conv3(x)
        return x

def build_model():
        input_image = torch.zeros([4, 3, 256, 256])

        analysis_net = Analysis_net_17()
        feature = analysis_net(input_image)

        print(feature.size())

if __name__ == '__main__':
    build_model()


import random
import time

'''
Complexity:
    Best = O(n)
    Average = O(n^2)
    Worst = O(n^2)
Compatibility with negative numbers: Yes
Speed: ~ 5.8s for 10_000-sized list
'''

def bubble_sort(arr: list) -> list:
    for i in range(len(arr) - 1):
        for j in range(len(arr) - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

array_bubble_sort = [
    random.randint(-10_000, 10_000) for _ in range(10_000)
]
start = time.time()
bubble_sort(array_bubble_sort)
print(time.time() - start)


import json

import numpy as np
import numpy.testing as npt
import pytest
from mudata import MuData

from scirpy.pp import ir_dist
from scirpy.tl._ir_query import (
    _reduce_json,
    _reduce_most_frequent,
    _reduce_unique_only,
    ir_query,
    ir_query_annotate,
    ir_query_annotate_df,
)

@pytest.mark.parametrize("metric", ["identity", "levenshtein"])
@pytest.mark.parametrize("key1", [None, "foo"])
@pytest.mark.parametrize("key2", [None, "bar"])
def test_ir_query(adata_cdr3, adata_cdr3_2, metric, key1, key2):
    ir_dist(adata_cdr3, adata_cdr3_2, metric=metric, sequence="aa", key_added=key1)
    ir_query(
        adata_cdr3,
        adata_cdr3_2,
        sequence="aa",
        metric=metric,
        distance_key=key1,
        key_added=key2,
    )

    tmp_key2 = f"ir_query_TESTDB_aa_{metric}" if key2 is None else key2
    tmp_ad = adata_cdr3.mod["airr"] if isinstance(adata_cdr3, MuData) else adata_cdr3
    assert tmp_ad.uns[tmp_key2]["distances"].shape == (4, 3)
    assert len(tmp_ad.uns[tmp_key2]["cell_indices"]) == 4
    assert len(tmp_ad.uns[tmp_key2]["cell_indices_reference"]) == 3

@pytest.mark.parametrize(
    "input,expected",
    [
        ([], np.nan),
        ([np.nan], np.nan),
        (["a", "b", np.nan], "ambiguous"),
        (["a", "a"], "a"),
        (["a", "a", np.nan], "a"),
    ],
)
def test_reduce_unique_only(input, expected):
    input = np.array(input, dtype="object")
    npt.assert_equal(_reduce_unique_only(input), expected)

@pytest.mark.parametrize(
    "input,expected",
    [
        ([], np.nan),
        ([np.nan], np.nan),
        (["a", "b", np.nan], "ambiguous"),
        (["a", "a"], "a"),
        (["a", "a", "b"], "a"),
        (["a", "a", "b", "b", "c"], "ambiguous"),
        (["a", "a", "b", "c", np.nan], "a"),
    ],
)
def test_reduce_most_frequent(input, expected):
    input = np.array(input, dtype="object")
    npt.assert_equal(_reduce_most_frequent(input), expected)

@pytest.mark.parametrize(
    "input,expected",
    [
        ([], {}),
        ([np.nan], {}),
        (["a", "b", np.nan], {"a": 1, "b": 1}),
        (["a", "a"], {"a": 2}),
        (["a", "a", "b"], {"a": 2, "b": 1}),
        (["a", "a", "b", "b", "c"], {"a": 2, "b": 2, "c": 1}),
        (["a", "a", "b", "c", np.nan], {"a": 2, "b": 1, "c": 1}),
    ],
)
def test_reduce_json(input, expected):
    input = np.array(input, dtype="object")
    assert json.loads(_reduce_json(input)) == expected

@pytest.fixture
def query_reference(adata_define_clonotype_clusters):
    query = adata_define_clonotype_clusters[["cell2", "cell3", "cell4", "cell10"], :].copy()
    reference = adata_define_clonotype_clusters.copy()
    reference.obs["some_annotation"] = reference.obs_names.str.upper()
    uns_ = reference.mod["airr"].uns if isinstance(reference, MuData) else reference.uns
    uns_["DB"] = {"name": "TESTDB"}

    return query, reference

@pytest.mark.parametrize(
    "same_v_gene,match_columns,expected",
    [
        (
            False,
            None,
            [
                ("cell2", "CELL1"),
                ("cell2", "CELL2"),
                ("cell2", "CELL5"),
                ("cell2", "CELL6"),
                ("cell2", "CELL7"),
                ("cell2", "CELL8"),
                ("cell3", "CELL3"),
                ("cell3", "CELL4"),
                ("cell4", "CELL3"),
                ("cell4", "CELL4"),
            ],
        ),
        (
            True,
            None,
            [
                ("cell2", "CELL1"),
                ("cell2", "CELL2"),
                ("cell2", "CELL5"),
                ("cell2", "CELL6"),
                ("cell2", "CELL7"),
                ("cell2", "CELL8"),
                ("cell3", "CELL3"),
                ("cell4", "CELL4"),
            ],
        ),
        (
            False,
            ["receptor_type"],
            [
                ("cell2", "CELL1"),
                ("cell2", "CELL2"),
                ("cell2", "CELL6"),
                ("cell2", "CELL7"),
                ("cell2", "CELL8"),
                ("cell3", "CELL3"),
                ("cell4", "CELL4"),
            ],
        ),
    ],
)
def test_ir_query_annotate_df(query_reference, same_v_gene, match_columns, expected):
    query, reference = query_reference
    ir_dist(query, reference, sequence="aa", metric="identity")
    ir_query(
        query,
        reference,
        sequence="aa",
        metric="identity",
        receptor_arms="VJ",
        dual_ir="primary_only",
        same_v_gene=same_v_gene,
        match_columns=match_columns,
    )

    res = ir_query_annotate_df(
        query,
        reference,
        sequence="aa",
        metric="identity",
        include_query_cols=[],
        include_ref_cols=["some_annotation"],
    )

    actual = list(res["some_annotation"].items())
    print(actual)

    assert actual == expected

@pytest.mark.parametrize(
    "strategy,expected",
    [
        (
            "unique-only",
            [
                ("cell2", "ambiguous"),
                ("cell3", "CELL3"),
                ("cell4", "CELL4"),
                ("cell10", np.nan),
            ],
        ),
        (
            "most-frequent",
            [
                ("cell2", "ambiguous"),
                ("cell3", "CELL3"),
                ("cell4", "CELL4"),
                ("cell10", np.nan),
            ],
        ),
        (
            "json",
            [
                (
                    "cell2",
                    json.dumps({"CELL1": 1, "CELL2": 1, "CELL6": 1, "CELL7": 1, "CELL8": 1}),
                ),
                ("cell3", json.dumps({"CELL3": 1})),
                ("cell4", json.dumps({"CELL4": 1})),
                ("cell10", np.nan),
            ],
        ),
    ],
)
def test_ir_query_annotate(query_reference, strategy, expected):
    query, reference = query_reference
    ir_dist(query, reference, sequence="aa", metric="identity")
    ir_query(
        query,
        reference,
        sequence="aa",
        metric="identity",
        receptor_arms="VJ",
        dual_ir="primary_only",
        same_v_gene=True,
        match_columns=["receptor_type"],
    )

    ir_query_annotate(
        query,
        reference,
        sequence="aa",
        metric="identity",
        include_ref_cols=["some_annotation"],
        strategy=strategy,
    )

    key = "airr:some_annotation" if isinstance(query, MuData) else "some_annotation"
    actual = list(query.obs[key].items())
    print(actual)

    assert actual == expected


import gym
from gym import spaces
from Robots.IdealFluidSwimmer_v1 import IdealFluidSwimmer
import numpy as np
from math import pi
from utils.learning_helper import forward_reward_function

class IdealFluidSwimmerEnv(gym.Env):
    def __init__(self):
        super(IdealFluidSwimmerEnv, self).__init__()
        self.snake_robot = IdealFluidSwimmer()
        self.action_space = spaces.Box(low=-1, high=1, shape=(2,))
        self.observation_space = spaces.Box(low=-pi, high=pi, shape=(3,))

    def step(self, action):
        reward, snake_robot = forward_reward_function(robot=self.snake_robot, action=action, c_x=1, c_joint=0,
                                                      c_zero_x=1, c_theta=0.1)
        self.snake_robot = snake_robot
        observation = np.array([*self.snake_robot.state])
        done = False
        info = {'episode': None}
        return observation, reward, done, info

    def reset(self):
        return np.array([*self.snake_robot.reset()])


import gym
import numpy as np
import time
import csv
from stable_baselines3 import PPO
import ctr_reach_envs
from ctr_reach_envs.src.utils import run_episode
#from ctr_reach_envs.envs.ctr_wrappers import ROSWrapper

def drl_ik_solver(env, model, episode, desired_goal=None, initial_joints=None, output_path=None):
    # Move to starting position
    time.sleep(0.5)
    achieved_goals, desired_goals, qs, r1, r2, r3 = run_episode(env, model, desired_goal)
    #with open(output_path, 'w+') as f:
    #    writer = csv.writer(f)
    #    step = 0
    #    for ag, dg, joint in zip(achieved_goals, desired_goals, qs):
    #        error = np.linalg.norm(ag - dg)
    #        step += 1
    #        writer.writerow(data_line(0, step, joint, ag, dg, np.array([error])))

if __name__ == '__main__':
    # Load in agent
    exp_name = 'ppo_full_noise_5_deg_20'
    model_path = '/home/keshav/ctm2-stable-baselines/ral-2023/gym-ctr-reach-ral/ctr_reach_envs/src/saved_policies/' \
                 + exp_name + '/rl_model_100000_steps'
    env_kwargs = {
        'goal_parameters': {
            'final_tol': 0.001, 'initial_tol': 0.001, 'function_steps': 500000, 'function_type': 'constant'
        }
    }
    model = PPO.load(model_path)
    env = gym.make('CTR-Reach-v0', **env_kwargs)
    num_episodes = 1
    for episode in range(num_episodes):
        drl_ik_solver(env, model, episode)


"""
Things to Remember
Using generators can be clearer than the alternative of returning lists of accumulated results.
The iterator returned by a generator produces the set of values passed to yield expressions within the generator function¡¯s body.
Generators can produce a sequence of outputs for arbitrarily large inputs because their working memory doesn¡¯t include all inputs and outputs.
"""

def index_words(text):
    result = []
    if text:
        result.append(0)
    for index, letter in enumerate(text):
        if letter == ' ':
            result.append(index + 1)
    return result

address = 'Four score and seven years ago...'
result = index_words(address)
print(result[:3])

#=>
def index_words_iter(text):
    if text:
        yield 0
    for index, letter in enumerate(text):
        if letter == ' ':
            yield index + 1

# Another example
def index_file(handle):
    offset = 0
    for line in handle:
        if line:
            yield offset
        for letter in line:
            offset += 1
            if letter == ' ':
                yield offset

from itertools import islice
with open('item16.txt', 'r') as f:
    it = index_file(f)
    print(list(it))

with open('item16.txt', 'r') as f:
    it = index_file(f)
    results = islice(it, 0, 3)
    print(list(results))

Effective Python 2015/2. Functions/Item 16 - Consider Generators Instead of Returning Lists/Example.py


import torch
import torch.nn as nn

class KurtosisWeight:
    def __init__(self, weight_tensor, name, kurtosis_target=2.0, k_mode='avg', KLD=False):
        self.kurtosis_loss = 0
        self.kurtosis = 0
        self.weight_tensor = weight_tensor
        self.name = name
        self.k_mode = k_mode
        self.kurtosis_target = kurtosis_target

        self.KLDiv_loss = 0
        self.KLD = KLD
        self.kld_criterion = nn.KLDivLoss(reduction='batchmean',)

    def fn_regularization(self):
        return self.kurtosis_calc()

    def kurtosis_calc(self):
        mean_output = torch.mean(self.weight_tensor)
        std_output = torch.std(self.weight_tensor)
        kurtosis_val = torch.mean((((self.weight_tensor - mean_output) / std_output) ** 4))
        # print("kurtosis_val: " + str(kurtosis_val))
        self.kurtosis_loss = (kurtosis_val - self.kurtosis_target) ** 2
        self.kurtosis = kurtosis_val

        if self.k_mode == 'avg':
            self.kurtosis_loss = torch.mean((kurtosis_val - self.kurtosis_target) ** 2)
            self.kurtosis = torch.mean(kurtosis_val)
        elif self.k_mode == 'max':
            self.kurtosis_loss = torch.max((kurtosis_val - self.kurtosis_target) ** 2)
            self.kurtosis = torch.max(kurtosis_val)
        elif self.k_mode == 'sum':
            self.kurtosis_loss = torch.sum((kurtosis_val - self.kurtosis_target) ** 2)
            self.kurtosis = torch.sum(kurtosis_val)

class RidgeRegularization:
    def __init__(self, weight_tensor, name):
        self.l2_loss = 0
        self.weight_tensor = weight_tensor
        self.name = name

    def l2_regularization(self):
        return self.l2_calc()

    def l2_calc(self):
        self.l2_loss = torch.sum(torch.sum(self.weight_tensor ** 2))

class WeightRegularization:
    def __init__(self, weight_tensor, name):
        self.wr_loss = 0
        self.weight_tensor = weight_tensor
        self.size=1
        for i in weight_tensor.size():
            self.size = self.size * i
        self.name = name

    def w_regularization(self):
        return self.wr_calc()

    def wr_calc(self):
        # self.wr_loss = torch.abs(torch.sum(torch.sum(self.weight_tensor * (self.size / torch.norm(self.weight_tensor,p=1)))))
        self.wr_loss = torch.sum(torch.sum(torch.norm(torch.abs(self.weight_tensor) -1 , p=2)))


import time

import numpy as np
from scipy import ndimage
from niclib.medpy_hausdorff import hd as haussdorf_dist

def compute_confusion_matrix(y_true, y_pred):
    """
    Returns tuple tp, tn, fp, fn
    """

    assert y_true.size == y_pred.size

    true_pos = np.sum(np.logical_and(y_true, y_pred))
    true_neg = np.sum(np.logical_and(y_true == 0, y_pred == 0))

    false_pos = np.sum(np.logical_and(y_true == 0, y_pred))
    false_neg = np.sum(np.logical_and(y_true, y_pred == 0))

    return true_pos, true_neg, false_pos, false_neg

def compute_lesion_confusion_matrix(y_true, y_pred):
    # True positives
    lesions_true, num_lesions_true = ndimage.label(y_true)
    lesions_pred, num_lesions_pred = ndimage.label(y_pred)

    true_pos = 0.0
    for i in range(num_lesions_true):
        lesion_detected = np.logical_and(y_pred, lesions_true == (i + 1)).any()
        if lesion_detected: true_pos += 1
    true_pos = np.min([true_pos, num_lesions_pred])

    # False positives
    tp_labels = np.unique(y_true * lesions_pred)
    fp_labels = np.unique(np.logical_not(y_true) * lesions_pred)

    # [label for label in fp_labels if label not in tp_labels]
    false_pos = 0.0
    for fp_label in fp_labels:
        if fp_label not in tp_labels: false_pos += 1

    return true_pos, false_pos, num_lesions_true, num_lesions_pred

def compute_segmentation_metrics(y_true, y_pred, lesion_metrics=False, exclude=None):
    metrics = {}
    eps = np.finfo(np.float32).eps

    tp, tn, fp, fn = compute_confusion_matrix(y_true, y_pred)

    # Sensitivity and specificity
    metrics['sens'] = tp / (tp + fn + eps) # Correct % of the real lesion
    metrics['spec'] = tn / (tn + fp + eps) # Correct % of the healthy area identified

    # Predictive value
    metrics['ppv'] = tp / (tp + fp + eps) # Of all lesion voxels, % of really lesion
    metrics['npv'] = tn / (tn + fn + eps)  # Of all lesion voxels, % of really lesion

    # Lesion metrics
    if lesion_metrics:
        tpl, fpl, num_lesions_true, num_lesions_pred = compute_lesion_confusion_matrix(y_true, y_pred)
        metrics['l_tpf'] = tpl / num_lesions_true if num_lesions_true > 0 else np.nan
        metrics['l_fpf'] = fpl / num_lesions_pred if num_lesions_pred > 0 else np.nan

        metrics['l_ppv'] = tpl / (tpl + fpl + eps)
        metrics['l_f1'] = (2.0 * metrics['l_ppv'] * metrics['l_tpf']) / (metrics['l_ppv'] + metrics['l_tpf'] + eps)

    # Dice coefficient
    metrics['dsc'] = dice_coef(y_true, y_pred)

    # Relative volume difference
    metrics['avd'] = 2.0 * np.abs(np.sum(y_pred) - np.sum(y_true))/(np.sum(y_pred) + np.sum(y_true) + eps)

    # Haussdorf distance
    try: metrics['hd'] = haussdorf_dist(y_pred, y_true, connectivity=3)  # Why connectivity 3?
    except Exception: metrics['hd'] = np.nan

    if exclude is not None:
        [metrics.pop(metric, None) for metric in exclude]

    return metrics

def dice_coef(y_true, y_pred, smooth = 0.01):
    intersection = np.sum(np.logical_and(y_true, y_pred))

    if intersection > 0:
        return (2.0 * intersection + smooth) / (np.sum(y_true) + np.sum(y_pred) + smooth)
    else:
        return 0.0

def compute_avg_std_metrics_list(metrics_list):
    metrics_avg_std = dict()

    assert len(metrics_list) > 0

    for metric_name in metrics_list[0].keys():
        metric_values = [metrics[metric_name] for metrics in metrics_list]

        metrics_avg_std.update({
            '{}_avg'.format(metric_name): np.nanmean(metric_values),
            '{}_std'.format(metric_name): np.nanstd(metric_values)})

    return  metrics_avg_std

def compute_clinical_metrics(y_true, y_pred):

    vol_true, vol_pred = np.sum(y_true), np.sum(y_pred)

    np.polyfit(x, y, deg)

    pass


from typing import Tuple, List
from PIL import Image  # requires pillow
from IPython.display import display
import numpy as np  # requires numpy
import cogpyt

def show_image_from_destination(data: np.ndarray, width, height):
    display(get_image_from_destination(data, width, height))

def get_image_from_destination(data: np.ndarray, width, height):
    image_np = np.array(data, dtype=np.uint8).reshape(height, width)
    return Image.fromarray(image_np)

def get_lena() -> Tuple[List[int], int, int]:
    lena_rgb = Image.open('img/lena.jpg')
    lena_grayscale = lena_rgb.convert('L')
    return lena_grayscale

def pad_and_flatten_image(image: Image.Image, padding: Tuple):
    image_np = np.array(image)
    vertical_padding, horizontal_padding = padding
    image_padded = np.pad(
        image_np, (
            (vertical_padding, vertical_padding),
            (horizontal_padding, horizontal_padding)
        )
    )
    return image_padded.flatten()

def get_destination_for_image(image: Image.Image):
    width, height = image.size
    return [0] * (width * height)

def get_sobel() -> Tuple[List[int], int, int]:
    return np.array([
        [1, 0, -1],
        [2, 0, -2],
        [1, 0, -1]
    ])

def convolve_naive(source, destination, kernel, image_width, kernel_width):
    destination_size = len(destination)
    padded_image_width = image_width + (kernel_width - 1)

    for destination_index in range(destination_size):
        acc = 0

        for kernel_idx, kernel_center in enumerate(kernel):
            kernel_y = kernel_idx // kernel_width
            kernel_x = kernel_idx % kernel_width

            destination_y = destination_index // image_width
            destination_x = destination_index % image_width
            corresponding_index_in_source = destination_y * padded_image_width + destination_x
            source_index = corresponding_index_in_source + padded_image_width * kernel_y + kernel_x

            acc += source[source_index] * kernel_center

        destination[destination_index] = min(max(acc, 0), 255)

@cogpyt.GeneratedFunction
def convolve_cogpyt(
        generated_code_block: cogpyt.GeneratedCodeBlock,
        source, destination, kernel, image_width, kernel_width
):
    destination_size = len(destination)
    padded_image_width = image_width + (kernel_width - 1)

    with generated_code_block:
        for destination_index in range(destination_size):
            acc = 0

            destination_y = destination_index // image_width
            destination_x = destination_index % image_width
            corresponding_index_in_source = destination_y * padded_image_width + destination_x
    generated_code_block.indent()

    for kernel_idx, kernel_center in enumerate(kernel):
        kernel_y = kernel_idx // kernel_width
        kernel_x = kernel_idx % kernel_width
        if kernel_center == 0:
            continue

        kernel_offset = padded_image_width * kernel_y + kernel_x

        if kernel_center == 1:
            with generated_code_block:
                acc += source[corresponding_index_in_source + kernel_offset]
        elif kernel_center == -1:
            with generated_code_block:
                acc -= source[corresponding_index_in_source + kernel_offset]
        else:
            with generated_code_block:
                acc += source[corresponding_index_in_source + kernel_offset] * kernel_center

    with generated_code_block:
        destination[destination_index] = min(max(acc, 0), 255)


#!/usr/bin/python3.4
#MKerbachi November 6th, 2015
#Python code to control two motors with Rpi A+ with the H bridge l298n

import RPi.GPIO as GPIO # always needed with RPi.GPIO
import time
import curses

# get the curses screen window
screen = curses.initscr()

# turn off input echoing
curses.noecho()

# respond to keys immediately (don't wait for enter)
curses.cbreak()

# map arrow keys to special values
screen.keypad(True)

#If the two GND (PI + l298n) are not interconnected that won't work !
#For all Keyboard symbols:
#https://docs.python.org/2/library/curses.html

GPIO.setmode(GPIO.BCM)  # choose BCM or BOARD numbering schemes. I use BCM

#################################################################
#			Variables		  		#
#################################################################

#For Motor #1
GPIO.setup(18, GPIO.OUT)# set GPIO 01 as an output Enabler
GPIO.setup(24, GPIO.OUT)# set GPIO 05 as an output.
GPIO.setup(23, GPIO.OUT)# set GPIO 04 as an output.

p24 = GPIO.PWM(24, 100)
p23 = GPIO.PWM(23, 100)
p18 = GPIO.PWM(18, 100)    # create an object p for PWM on port 18 at 50 Hertz
                        # you can have more than one of these, but they need
                        # different names for each port
                        # e.g. p1, p2, motor, servo1 etc.

#For Motor #2
GPIO.setup(13, GPIO.OUT)# set GPIO 03 as an output Enabler
GPIO.setup(27, GPIO.OUT)# set GPIO 02 as an output.
GPIO.setup(17, GPIO.OUT)# set GPIO 0  as an output.

p27 = GPIO.PWM(27, 100)
p17 = GPIO.PWM(17, 100)
p13 = GPIO.PWM(13, 100)    # create an object p for PWM on port 18 at 50 Hertz
                        # you can have more than one of these, but they need
                        # different names for each port
                        # e.g. p1, p2, motor, servo1 etc.

LastKey = ""

#################################################################
#			Functions		  		#
#################################################################

def Stop():
            p18.start(0)
            p23.start(0)
            p24.start(0)

            p13.start(0)
            p27.start(0)
            p17.start(0)
            time.sleep(0.3)
            #GPIO.cleanup()
            print ("Stop executed")
            #exit()

def Left():
            if LastKey != 'left' : Stop()
            p18.start(60)
            p23.start(0)
            p24.start(100)

            time.sleep(0.4)
            p13.start(60)
            p27.start(0)
            p17.start(100)

#            time.sleep(0.3)
            #Stop()

def Right():
            if LastKey != 'right' : Stop()
            p18.start(60)
            p23.start(100)
            p24.start(0)

            time.sleep(0.4)
            p13.start(60)
            p27.start(100)
            p17.start(0)

#            time.sleep(0.3)
            #Stop()

def Up():
            #if LastKey != 'up' : Stop()
            p18.start(60)
            p23.start(100)
            p24.start(0)

            time.sleep(0.3)
            p13.start(60)
            p27.start(0)
            p17.start(100)

            time.sleep(0.3)
            #Stop()

def Down():
            #if LastKey != 'down' : Stop()
            p18.start(60)
            p23.start(0)
            p24.start(100)

            time.sleep(0.3)
            p13.start(60)
            p27.start(100)
            p17.start(0)

            time.sleep(0.3)
            #Stop()

try:
    while True:
        char = screen.getch()
        print ('you entred')
        print (char)
        if char == ord('q'):
            break
        #elif char == curses.KEY_ENTER:
        elif char == ord(' '):
            # print doesn't work with curses, use addstr instead
            #screen.addstr(0, 0, 'right')
            if not ( LastKey == "enter" ) : print ('Last key was not Enter, it was %s \n' % LastKey)
            LastKey="enter"
            print ('enter\n')
            Stop()

        elif char == curses.KEY_RIGHT:
            # print doesn't work with curses, use addstr instead
            #screen.addstr(0, 0, 'right')
            if not ( LastKey == "right" ) : print ('Last key was not right, it was %s \n' % LastKey)
            LastKey="right"
            print ('right\n')
            Right()

        elif char == curses.KEY_LEFT:
            #screen.addstr(0, 0, 'left ')
            if not ( LastKey == "left" ) : print ('Last key was not left, it was %s \n' % LastKey)
            LastKey="left"
            print ('left\n')
            Left()

        elif char == curses.KEY_UP:
            #screen.addstr(0, 0, 'up   ')
            if not ( LastKey == "up" ) : print ('Last key was not up, it was %s \n' % LastKey)
            LastKey="up"
            print ('up\n')
            Up()

        elif char == curses.KEY_DOWN:
            #screen.addstr(0, 0, 'down ')
            if not ( LastKey == "down" ) : print ('Last key was not down t was %s \n' % LastKey)
            LastKey="down"
            print ('down\n')
            Down()
        else:
            print ('Nothing Entred!\n')

finally:
    # shut down cleanly
    print ('In the finally section now')
    curses.nocbreak(); screen.keypad(0); curses.echo()
    curses.endwin()
    p13.stop()                # stop the PWM output
    p17.stop()
    p27.stop()

    p23.stop()                # stop the PWM output
    p24.stop()
    p18.stop()

    GPIO.cleanup()          # when your program exits, tidy up after yours

p13.stop()                # stop the PWM output
p17.stop()
p27.stop()

p23.stop()                # stop the PWM output
p24.stop()
p18.stop()

GPIO.cleanup()          # when your program exits, tidy up after yours


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import os
from sklearn.externals import joblib

df = pd.read_csv("heart.csv")

print(df.head())

print(df.target.value_counts())

sns.countplot(x="target", data=df, palette="bwr")
plt.show()

countNoDisease = len(df[df.target == 0])
countHaveDisease = len(df[df.target == 1])
print("Percentage of Patients Haven't Heart Disease: {:.2f}%".format((countNoDisease / (len(df.target))*100)))
print("Percentage of Patients Have Heart Disease: {:.2f}%".format((countHaveDisease / (len(df.target))*100)))

sns.countplot(x='sex', data=df, palette="mako_r")
plt.xlabel("Sex (0 = female, 1= male)")
plt.show()

countFemale = len(df[df.sex == 0])
countMale = len(df[df.sex == 1])
print("Percentage of Female Patients: {:.2f}%".format((countFemale / (len(df.sex))*100)))
print("Percentage of Male Patients: {:.2f}%".format((countMale / (len(df.sex))*100)))

print(df.groupby('target').mean())

pd.crosstab(df.age,df.target).plot(kind="bar",figsize=(20,6))
plt.title('Heart Disease Frequency for Ages')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.savefig('HeartDiseaseBasedOnAges.png')
plt.show()

pd.crosstab(df.sex,df.target).plot(kind="bar",figsize=(15,6),color=['#1CA53B','#AA1111' ])
plt.title('Heart Disease Frequency for Sex')
plt.xlabel('Sex (0 = Female, 1 = Male)')
plt.xticks(rotation=0)
plt.legend(["Haven't Disease", "Have Disease"])
plt.ylabel('Frequency')
plt.show()

pd.crosstab(df.slope,df.target).plot(kind="bar",figsize=(15,6),color=['#DAF7A6','#FF5733' ])
plt.title('Heart Disease Frequency for Slope')
plt.xlabel('The Slope of The Peak Exercise ST Segment ')
plt.xticks(rotation = 0)
plt.ylabel('Frequency')
plt.show()

pd.crosstab(df.fbs,df.target).plot(kind="bar",figsize=(15,6),color=['#FFC300','#581845' ])
plt.title('Heart Disease Frequency According To FBS')
plt.xlabel('FBS - (Fasting Blood Sugar > 120 mg/dl) (1 = true; 0 = false)')
plt.xticks(rotation = 0)
plt.legend(["Haven't Disease", "Have Disease"])
plt.ylabel('Frequency of Disease or Not')
plt.show()

pd.crosstab(df.cp,df.target).plot(kind="bar",figsize=(15,6),color=['#11A5AA','#AA1190' ])
plt.title('Heart Disease Frequency According To Chest Pain Type')
plt.xlabel('Chest Pain Type')
plt.xticks(rotation = 0)
plt.ylabel('Frequency of Disease or Not')
plt.show()

a = pd.get_dummies(df['cp'], prefix = "cp")
b = pd.get_dummies(df['thal'], prefix = "thal")
c = pd.get_dummies(df['slope'], prefix = "slope")

frames = [df, a, b, c]
df = pd.concat(frames, axis = 1)
print(df.head())

df = df.drop(columns = ['cp', 'thal', 'slope'])
print(df.head())

y = df.target.values
x_data = df.drop(['target'], axis = 1)

# Normalize
x = (x_data - np.min(x_data)) / (np.max(x_data) - np.min(x_data)).values

x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2,random_state=0)

#transpose matrices
x_train = x_train.T
y_train = y_train.T
x_test = x_test.T
y_test = y_test.T

# LogisticRegression Model
lr = LogisticRegression()
lr.fit(x_train.T,y_train.T)
print("Test Accuracy {:.2f}%".format(lr.score(x_test.T,y_test.T)*100))

joblib.dump(lr, 'logistic_regression.pkl')
logistic_regression = joblib.load('logistic_regression.pkl')

# KNN Model
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 2)  # n_neighbors means k
knn.fit(x_train.T, y_train.T)
prediction = knn.predict(x_test.T)
print("{} NN Score: {:.2f}%".format(2, knn.score(x_test.T, y_test.T)*100))

# try ro find best k value
scoreList = []
for i in range(1,20):
    knn2 = KNeighborsClassifier(n_neighbors = i)  # n_neighbors means k
    knn2.fit(x_train.T, y_train.T)
    scoreList.append(knn2.score(x_test.T, y_test.T))

plt.plot(range(1,20), scoreList)
plt.xticks(np.arange(1,20,1))
plt.xlabel("K value")
plt.ylabel("Score")
plt.show()
print("Maximum KNN Score is {:.2f}%".format((max(scoreList))*100))

joblib.dump(knn2, 'knn_model.pkl')
knn_model = joblib.load('knn_model.pkl')

#SVM
from sklearn.svm import SVC
svm = SVC(random_state = 1)
svm.fit(x_train.T, y_train.T)
print("Test Accuracy of SVM Algorithm: {:.2f}%".format(svm.score(x_test.T,y_test.T)*100))

joblib.dump(svm, 'svm_model.pkl')
svm_model = joblib.load('svm_model.pkl')

#Naive-bayes
from sklearn.naive_bayes import GaussianNB
nb = GaussianNB()
nb.fit(x_train.T, y_train.T)
print("Accuracy of Naive Bayes: {:.2f}%".format(nb.score(x_test.T,y_test.T)*100))

joblib.dump(nb, 'naive_bayes_model.pkl')
naive_bayes_model = joblib.load('naive_bayes_model.pkl')

#Decision Tree
from sklearn.tree import DecisionTreeClassifier
dtc = DecisionTreeClassifier()
dtc.fit(x_train.T, y_train.T)
print("Decision Tree Test Accuracy {:.2f}%".format(dtc.score(x_test.T, y_test.T)*100))

joblib.dump(dtc, 'decision_tree.pkl')
decision_tree = joblib.load('decision_tree.pkl')

# Random Forest Classification
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators = 1000, random_state = 1)
rf.fit(x_train.T, y_train.T)
print("Random Forest Algorithm Accuracy Score : {:.2f}%".format(rf.score(x_test.T,y_test.T)*100))

joblib.dump(rf, 'random_forest.pkl')
random_forest = joblib.load('random_forest.pkl')

methods = ["Logistic Regression", "KNN", "SVM", "Naive Bayes", "Decision Tree", "Random Forest"]
accuracy = [86.89, 88.52, 86.89, 86.89, 78.69, 88.52]
colors = ["purple", "green", "orange", "magenta","#CFC60E","#0FBBAE"]

sns.set_style("whitegrid")
plt.figure(figsize=(16,5))
plt.yticks(np.arange(0,100,10))
plt.ylabel("Accuracy %")
plt.xlabel("Algorithms")
sns.barplot(x=methods, y=accuracy, palette=colors)
plt.show()

# Predicted values
y_head_lr = lr.predict(x_test.T)
knn3 = KNeighborsClassifier(n_neighbors = 3)
knn3.fit(x_train.T, y_train.T)
y_head_knn = knn3.predict(x_test.T)
y_head_svm = svm.predict(x_test.T)
y_head_nb = nb.predict(x_test.T)
y_head_dtc = dtc.predict(x_test.T)
y_head_rf = rf.predict(x_test.T)

from sklearn.metrics import confusion_matrix

cm_lr = confusion_matrix(y_test,y_head_lr)
cm_knn = confusion_matrix(y_test,y_head_knn)
cm_svm = confusion_matrix(y_test,y_head_svm)
cm_nb = confusion_matrix(y_test,y_head_nb)
cm_dtc = confusion_matrix(y_test,y_head_dtc)
cm_rf = confusion_matrix(y_test,y_head_rf)

plt.figure(figsize=(24,12))

plt.suptitle("Confusion Matrixes",fontsize=24)
plt.subplots_adjust(wspace = 0.4, hspace= 0.4)

plt.subplot(2,3,1)
plt.title("Logistic Regression Confusion Matrix")
sns.heatmap(cm_lr,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.subplot(2,3,2)
plt.title("K Nearest Neighbors Confusion Matrix")
sns.heatmap(cm_knn,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.subplot(2,3,3)
plt.title("Support Vector Machine Confusion Matrix")
sns.heatmap(cm_svm,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.subplot(2,3,4)
plt.title("Naive Bayes Confusion Matrix")
sns.heatmap(cm_nb,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.subplot(2,3,5)
plt.title("Decision Tree Classifier Confusion Matrix")
sns.heatmap(cm_dtc,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.subplot(2,3,6)
plt.title("Random Forest Confusion Matrix")
sns.heatmap(cm_rf,annot=True,cmap="Blues",fmt="d",cbar=False)

plt.show()


import pytest
import numpy as np
from collections import namedtuple

from ppo_worm.env_wrapper import WormGymWrapper

@pytest.fixture(scope="session")
def worm_env():
    return WormGymWrapper("worm/worm.x86_64", no_graphics=True)

def test_reset(worm_env):
    obs = worm_env.reset()
    assert obs.shape == (10, 64)

def test_step(worm_env):
    action = np.random.normal(size=(10, 9))
    observation, reward, done, info = worm_env.step(action)
    assert observation.shape == (10, 64)
    assert reward.shape == (10,)
    assert done == False

def test_decision_to_observation(worm_env):
    DecisionStep = namedtuple("DecisionStep", ["obs", "reward"])

    # Each observation is 64 array
    # Each reward is a float
    decision_steps = [DecisionStep(np.ones((1, 64)), 1.) for _ in range(10)]
    observations, rewards  = worm_env._decision_to_observation(decision_steps)

    # Check shapes match when converting
    assert observations.shape == (10, 64)
    assert rewards.shape == (10,)


import idaapi
import idascript
import idautils
import idc
import math
import itertools
import json
import csv
import datetime
import cProfile

def createitems(basicblock):
        xrefs = lambda ea: len([x for x in XrefsFrom(ea,0)])
        drefs = lambda ea: len([x for x in DataRefsFrom(ea)])
        consts = lambda ea: len([GetOperandValue(ea,y) for y in range(idaapi.UA_MAXOP) if (GetOpType(ea,y) in [o_mem,o_phrase,o_displ,o_imm,o_far,o_near])])
        data = [[1,xrefs(ea),drefs(ea),consts(ea)] for ea in range(basicblock.startEA, basicblock.endEA)]
        return map(sum,zip(*data))

def cc(fkt):
    nodes = set([x for x in idaapi.FlowChart(idaapi.get_func(fkt))])
    edges = set([(x,y) for x in nodes for y in x.succs()])
    return [len(nodes),len(edges),len(edges) - len(nodes) + 2]

def eatostart(ea):
    f = idaapi.get_func(ea)
    return None if f is None else f.startEA

def calc_inout(functions):
    calls = [(callee,caller,1) for caller in map(eatostart,functions) for callee in map(eatostart,CodeRefsTo(caller,0))]
    calls = sorted(calls ,key=lambda x: x[0])
    callees = {c[0]:sum(map(lambda x:x[2],c[1])) for c in itertools.groupby(calls, lambda x: x[0])}
    calls = sorted(calls ,key=lambda x: x[1])
    callers = {c[0]: sum(map(lambda x:x[2],c[1])) for c in itertools.groupby(calls, lambda x: x[1])}
    return (callers, callees)

def lookup_calls(callers, callees, x):
    return [ callers[x] if x in callers and callers[x] < x else 0 ,callees[x] if x in callees and callees[x] < x else 0 ,callers[x] if x in callers and callers[x] > x else 0 ,callees[x] if x in callees and callees[x] > x else 0 ]

def sum_xrefs(ea):
    return len([x for x in XrefsFrom(ea,0)])
def sum_drefs(ea):
    return len([x for x in DataRefsFrom(ea)])
def sum_consts(ea):
    return len([GetOperandValue(ea,y) for y in range(idaapi.UA_MAXOP) if (GetOpType(ea,y) in [o_mem,o_phrase,o_displ,o_imm,o_far,o_near])])

def bb_info(bb):
    data = [[1,sum_xrefs(ea),sum_drefs(ea)] for ea in range(bb.startEA, bb.endEA)]
    return map(sum,zip(*data))

def fkt_info(f):
    calls = list(set(map(eatostart,CodeRefsTo(f.startEA,0))))
    callees = list(set([(x,y) for x in range(f.startEA, f.endEA) for y in CodeRefsFrom(x,1) if y < f.startEA or y >= f.endEA]))
    return {'start': f.startEA, 'end': f.endEA, 'size':f.size(), 'calls': calls, 'callees': callees}

def flowchart_info(idaflow):
    nodes = list(set([x for x in idaflow]))
    edges = list(set([(r,y.startEA) for x in nodes for y in x.succs() for r in CodeRefsTo(y.startEA,1) if r >= x.startEA and r <=x.endEA ]))
    bbinfo = map(sum,zip(*map(bb_info, [n for n in nodes if n.endEA-n.startEA > 0])))
    graph = [{"start": x.startEA, "len": x.endEA-x.startEA, "nxt": [y.startEA for y in x.succs()]} for x in idaflow]
    return {'nodes' : len(nodes),'edges': len(edges),'bbsize': bbinfo[0], 'Xrefs': bbinfo[1], 'Drefs': bbinfo[2], 'graph': graph, 'edges' : edges}

def function_extract(x):
    name = GetFunctionName(x)
    idafkt = idaapi.get_func(x)
    idaflow = idaapi.FlowChart(idafkt)
    return {'addr': x, 'name': name, 'fkt': fkt_info(idafkt), 'chart': flowchart_info(idaflow)}

#for i in xrange(1, len(idc.ARGV)):
    #print "ARGV[%d]=%s" % (i, idc.ARGV[i])

functions = []
sta=idc.SelStart()
end=idc.SelEnd()
#print sta, end
if sta!=end:
    functions = idautils.Functions(sta,end)
else:
    functions = idautils.Functions()
functions = sorted(set(functions))

#(callers, callees) = calc_inout(functions)

#print "aggregating data", datetime.datetime.now()
#cProfile.run('data = map(function_extract, functions)')
data = map(function_extract, functions)

#[
#        #per function
#        (
#        # start, end, name
#        x, , GetFunctionName(x),
#        # cyclomatic complexity
#        cc(x)
#        # sum of bb lengths
#	+ [sum([ bb.endEA-bb.startEA for bb in idaapi.FlowChart(idaapi.get_func(x))])]
#        # ( list of caller addrs, list of callee addrs )
#        + lookup_calls(callers,callees,x)
#        # [ per bb ( start, end, list of xrefs, list of drefs, list of consts ) ]
#	+ map(sum,zip(*[createitems(bb)
#            for bb in idaapi.FlowChart(idaapi.get_func(x))
#            if (bb.endEA-bb.startEA >0) ]))
#        ) for x in functions]

#print "writing output", datetime.datetime.now()
with open(idc.ARGV[1],'wb') as f:
    json.dump(data,f)

#print "done", datetime.datetime.now()

idc.Exit(0)


import math
import random
import time

import win32api
import win32con
import win32gui

# win32api.MessageBox(win32con.NULL, 'Hello Hello Hello Hello Hello！', 'Hello', win32con.MB_OK)

txtWindows = win32gui.FindWindow("Notepad", "test001.txt - 記事本")

# while True:
#     win32gui.ShowWindow(txtWindows, win32con.SW_HIDE)
#     time.sleep(2)
#     win32gui.ShowWindow(txtWindows, win32con.SW_SHOW)
#     time.sleep(2)

# parameter
x_0 = 500
y_0 = 300

r = 200
theta = 0
step = 12
time_gap = 0.25
time_end = 5

time_start = time.time()
sum_t = 0

while sum_t < time_end:
    theta = theta + (2 * math.pi) / step
    x = x_0 + r * math.cos(theta)
    y = y_0 + r * math.sin(theta)
    win32gui.SetWindowPos(txtWindows, win32con.HWND_TOPMOST, int(x), int(y), 300, 300, win32con.SWP_SHOWWINDOW)
    time.sleep(time_gap)
    time_Now = time.time()
    sum_t = (time_Now - time_start)
    # print(time_start, time_Now, sum_t)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""The main implementation for calling pysorter from the commandline"""

from __future__ import print_function

import argparse
import logging
import os
import sys

from .oranize import Organizer

from .rules import RulesFileClassifier

log = logging.getLogger(__name__)

_last_sorter = None  # variable used during testing, set by main

def package_directory():
    """Return the absolute path to where pysorter is located"""
    return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__))))

def validate_arguments(args):
    """
    Checks whether the paths and options
    provided as commandline arguments are valid.
    The application exits if they are not.
    """
    if args.filetypes:
        args.filetypes = os.path.abspath(args.filetypes)
    else:
        args.filetypes = os.path.join(package_directory(), "filetypes.py")

    if not os.path.isfile(args.filetypes):
        raise OSError(
            "Filetypes is not a file or does not exist: {}".format(args.filetypes)
        )

    if args.unhandled_file:
        args.unhandled_file = os.path.abspath(args.unhandled_file)

    return args

def parse_args(args=None):
    """Create an argument parser"""
    from . import __version__

    parser = argparse.ArgumentParser(
        description="Reorganizes files and directories according to certain rules"
    )

    parser.add_argument("directory", help="The directory to be organized")

    parser.add_argument(
        "-d",
        "--destination",
        help="The destination directory to move organized files to.",
        dest="dest_dir",
        default=None,
    )

    parser.add_argument(
        "-p",
        "--process-dirs",
        help="Should directories also be matched against the rules?",
        action="store_true",
        dest="do_process_dirs",
    )

    parser.add_argument(
        "-t",
        "--filetypes",
        help="File path or python module containing regex rules [Default: pysorter.filetypes]",
        default=None,
    )

    parser.add_argument(
        "-u",
        "--unhandled-file",
        help="Write the paths of all unhandled items to this file",
        dest="unhandled_file",
    )

    parser.add_argument(
        "-r",
        "--recursive",
        help="Recursively organize directories",
        action="store_true",
        dest="do_recurse",
    )

    parser.add_argument(
        "-c",
        "--remove-empty-dirs",
        help="Recursively removes all empty directories in the directory being organized.",
        action="store_true",
        dest="do_remove_empty_dirs",
    )

    parser.add_argument(
        "-n",
        "--dry-run",
        help="Prints out the changes that would occur, without actually executing them.",
        action="store_true",
        dest="dry_run",
    )

    parser.add_argument(
        "-V",
        "--version",
        action="version",
        version=__version__,
        help="Prints out the current version of pysorter",
    )

    return validate_arguments(parser.parse_args(args))

def main(args=None):
    global _last_sorter

    logging.basicConfig()
    args = parse_args(args)

    rules = RulesFileClassifier.load_file(args.filetypes)

    topass = dict(vars(args))

    # --- remove processed arguments
    del topass["directory"]
    del topass["filetypes"]
    del topass["unhandled_file"]

    sorter = Organizer(args.directory, rules, **topass)
    sorter.organize()

    # variable used for testing and debugging
    _last_sorter = sorter

    # write out all the unknown file types
    if args.unhandled_file:
        with open(args.unhandled_file, "a") as ufile:
            for i in sorter.unhandled_paths:
                ufile.write(i)
                ufile.write("\n")
    return 0

if __name__ == "__main__":
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)
    sys.exit(main())


from django.urls import path
from . import views
from django_app import settings

urlpatterns = [
    path('', views.index, name = 'index'),
    path('signup', views.signup, name = 'signup'),
    path('signin', views.signin, name = 'signin'),
    path('mypage/<int:pk>', views.mypage, name = 'mypage'),
    path('create/<int:pk>', views.create, name = 'create'),
    path('create_myself/<int:pk>', views.create_myself, name = 'create_myself'),
    path('delete/<int:num>/<int:pk>', views.delete, name = 'delete'),
    path('edit/<int:num>/<int:pk>', views.edit, name = 'edit'),
    path('search/<int:pk>', views.search, name = 'search'),
    path('signout/<int:pk>', views.signout, name = 'signout'),
    path('user_delete/<int:pk>', views.user_delete, name = 'user_delete'),
    path('count/<int:pk>', views.count, name = 'count'),
    path('twitter/<int:pk>', views.twitter, name = 'twitter'),
]