'''Test module for policy_expert_exrecise
'''

import unittest
import pandas as pd
import policy_expert_exercise
import filepath
import io
import os
from unittest.mock import patch
from os import getenv
from pandas.util.testing import assert_frame_equal

class DFTests(unittest.TestCase):

    """ class for running unittests """

    def setUp(self):

        TEST_INPUT_DIR = getenv('file_path')
        test_file_name =  'components.csv'
        try:
            component_df = pd.read_csv(TEST_INPUT_DIR + test_file_name)

        except IOError:
            print('cannot open file')
        self.fixture = component_df
    @classmethod
    def setUpClass(cls):
        #print('setUpClass')
        #define mock data for the order files
        cls.mock_order_df = pd.DataFrame (
                    {"timestamp":["2021-06-02","2021-06-02"],
                     "orderId":["6636296c-7b6c-4747-838e-d3808b44988d","6636296c-7b6c-4747-838e-d3808b44988d"],
                     "units":[5,23],
                     'componentId':['XNPRP05','BKRED01']
                     })
    def test_dataFrame_component_df_constructedAsExpected(self):
        """ Test that the dataframe read in equals what you expect"""
        component_df = pd.DataFrame({'componentId':['BKRED01','BKONG13'],'colour':['Red','Orange'],'costPrice':[0.021,0.022]})

        assert_frame_equal(self.fixture.head(2), component_df)
    def test_dataFrame_order_df_constructedAsExpected(cls):
        try:
            order_df=policy_expert_exercise.read_order_file_to_dataframe().head(1)
            order_df['timestamp'].astype(str).reset_index(drop=True)
            cls.mock_order_df.timestamp.astype(str).reset_index(drop=True)
            pd.testing.assert_frame_equal(order_df[['orderId','units']], cls.mock_order_df['orderId','units'].head(1),check_dtype=True)
        except Exception as error :
            print(error)

if __name__ == '__main__':
    unittest.main()


# coding=utf8

import torch
import torch.nn as nn

class MyNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv = nn.Conv2d(3, 10, 2, stride=2)
        self.relu = nn.ReLU()
        self.flatten = lambda x: x.view(-1)
        self.fc1 = nn.Linear(160, 5)

    def forward(self, x):
        x = self.relu(self.conv(x))
        x.register_hook(lambda grad: torch.clamp(grad,  min=0))
        x.register_hook(lambda grad: print("Gradients less than zero: ", bool((grad <0).any())))
        return self.fc1(self.flatten(x))

net = MyNet()

grad_res_dict = {}

def store_gradient_info(grad_res_dict, model):
    named_paras = model.named_parameters()
    for n, p in named_paras:
        if p.requires_grad:
            if n not in grad_res_dict:
                grad_res_dict[n] = []
            if p.grad is None:
                print(f"{n}'s gradient is None")
            else:
                grad_res_dict[n].append(p.grad.abs().mean().cpu().item())

def calc_wei_dist(model, pre_wei_dict, wei_dis_dict):
    named_paras = model.named_parameters()
    for n, p in named_paras:
        if p.requires_grad:
            if n in pre_wei_dict:
                dis_ = (p.data - pre_wei_dict[n]).norm().cpu().item()
                if n not in wei_dis_dict:
                    wei_dis_dict[n] = []
                wei_dis_dict[n].append(dis_)
            pre_wei_dict[n] = p.data.clone()

def save_to_wb(info_dict, wb, suffix='_suffix'):
    for key, val_arr  in info_dict.items():
        for val in val_arr:
            wb.log({f'{key}_grad': val})

inp = torch.randn(1, 3, 8, 8)
out = net(inp)

(1-out.mean()).backward()
store_gradient_info(grad_res_dict, net)
print("The biases are", net.fc1.bias.grad)
print(grad_res_dict)


from pynput.mouse import Button,Controller
from pynput.keyboard import Key
from time import sleep
sleep(10)
mouse=Controller()
mouse.position=(450,850)
mouse.press(Button.left)
mouse.release(Button.left)
sleep(4)
a=' '
from pynput.keyboard import Controller
Keyboard=Controller()
def tyype(a):
    keyboard=Controller()
    a=list(a)
    for i in range(0,len(a)):
        if(a[i]=='$'):
            Keyboard.press(Key.ctrl)
            continue
        Keyboard.press(a[i])
        Keyboard.release(a[i])
    Keyboard.release(Key.ctrl)
    Keyboard.press(Key.enter)
    Keyboard.release(Key.enter)

a="$t"
a='facebook.com'
tyype(a)
sleep(4)
mouse.position=(450,200)
sleep(4)
mouse.press(Button.left)
mouse.release(Button.left)
a="Nithin is THE topper!!"
tyype(a)
from pynput.mouse import Button,Controller
mouse=Controller()
mouse.position=(450,450)
sleep(5)
mouse.press(Button.left)
mouse.release(Button.left)


# Title: Brute Force Attack - Cäser-Chiffre
# Beschreibung: Geht alle möglichkeiten für das Entschlüsseln des Cäser-Chiffre durch

import os
os.system("clear")

strText = str(input("EINGABE Geheimtext: "))

# Prüfen ob der String nur Buchstaben enthält
if strText.isalpha():

    # Text in Großbuchstaben umwandeln
    strText = strText.upper()

    strAusgabeText = "\nAUSGABE Klartext\n"

    for iCodeKey in range(1,25):
        strAusgabeText = strAusgabeText + str(iCodeKey).zfill(2) + ": "

        for cCurPos in strText:
            cipher = ord(cCurPos)
            cipher = cipher - iCodeKey

            if(cipher < 65):
                cipher = cipher + 26

            strAusgabeText = strAusgabeText + str(chr(cipher))

        strAusgabeText = strAusgabeText + "\n"
else:
    strAusgabeText = "Ungültige Eingabe: Es sind nur Buchstaben erlaubt!"

print(strAusgabeText + "\n\n")


from flask import Flask
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
servo = GPIO.PWM(11,50)

app = Flask(__name__)

@app.route('/')

def index():
    return 'This is it!'

if(__name__) == '__main__':
    app.run(debug=True, host='0.0.0.0')

@app.route('/move-servo')

def move_servo():
    print('moving servo!')
    servo.start(0)
    time.sleep(1)
    print("rotating")
    duty = 2
    while duty <= 17:
        servo.ChangeDutyCycle(duty)
        time.sleep(1)
        duty = duty + 1
    servo.stop()
    GPIO.cleanup()
    print("all cleared")

    return 'servo moved'


class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        #number of elements
        n = len(nums)
        #initialize the array holding subsequences lengths
        L = [1]*n
        #compute L[i] values in bottom up manner
        # do for each element in subarray `arr[0…i-1]`
        for i in range(1,n):
            #do for each element in subarray `arr[0…i-1]`
            for j in range(0,i):
                #find the longest increasing subsequence that ends with `arr[j]`
                #where `arr[j]` is less than the current element `arr[i]`
                if nums[j] < nums[i] and L[i] < L[j] + 1:
                    L[i] = L[j] + 1

        #find the longest increasing subsequence (having maximum length)
        #Initialize maximum to 0 to get the maximum of all LIS
        maximum = 0
        for i in range(n):
            maximum = max(L[i],maximum)
        return maximum


from datetime import time

from pydantic import BaseModel
from fastapi import APIRouter

from Presenter import pre_request_post

router = APIRouter()

class AddDocter(BaseModel):
    docter_name: str
    hospital_name: str
    department : str
    nonpaid : str
    day_start_time : time
    day_end_time : time
    day_start_rest : time
    day_end_rest : time
    sat_start_time : time
    sat_end_time : time
    sun_start_time : time
    sun_end_time : time
    holiday : str
    workday : str

class AddPatient(BaseModel):
    patient_name : str

class AddRequest(BaseModel):
    patient_id : int
    docter_id : int
    date: str
    time : time

# 의사 추가
@router.post('/docter', tags=["Add"])
async def add_post_docter(add : AddDocter):
    result = pre_request_post.pre_post_doc(add)

    return result

# 환자 추가
@router.post('/patient', tags=["Add"])
async def add_post_patient(add : AddPatient):
    result = pre_request_post.pre_post_patient(add)

    return result

#진료 요청
@router.post('/request', tags=["Add"])
async def add_post_request(add : AddRequest):
    result = pre_request_post.pre_post_request(add)

    return result


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

# Learn more: https://github.com/kennethreitz/setup.py

from setuptools import setup, find_packages

with open('README.rst') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='spark_ts',
    version='0.1.0',
    description='Pyspark package supporting climate computing',
    long_description=readme,
    author='Jesse Lima',
    author_email='jesseamerico@gmail.com',
    url='https://github.com/jaglima/climaspark',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)


import read
record = read.final
count = 1
sum = 0
sum2=0
s = {}
flag = 0
for i in record:
    sum = sum + i[3]
    if count>=50:
        a = sum/50
        if a>i[3] and flag==0:
            s[count]="Buy"
            M = i[3]
            flag = 1
        if a<i[3] and flag==1:
            s[count]="sell"
            m = i[3]
            flag = 0
            sum2=sum2+(M-m)
        sum = sum - record[count - 50][3]
    count +=1
print("The serial number and whether we should buy or sell is shown in dictionary below..\n")
print(s)
print("\n\nThe loss or profit by simple moving average crossover strategy on low prices of each day is ",sum2)

# for unit testing
def string_datetime():
    for i in record:
        return i[0]

def string_instrument():
    for i in record:
        return i[6]

def float_close():
    for i in record:
        return i[1]

def float_high():
    for i in record:
        return i[2]

def float_low():
    for i in record:
        return i[3]

def float_open():
    for i in record:
        return i[4]

def int_volume():
    for i in record:
        print(type(i[5]))
        return i[5]


from requests import session
import requests
import re
import execjs
from pprint import pprint
import time

class GetIndex(object):

    def __init__(self):
        self.url = 'http://bj.gsxt.gov.cn/index.html'
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Host': 'bj.gsxt.gov.cn',
            'Pragma': 'no-cache',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36',
            'Referer': 'http://bj.gsxt.gov.cn/index.html',
        }

        self.cookie_headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Host': 'bj.gsxt.gov.cn',
            'Pragma': 'no-cache',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36',

        }

    def get_cookies(self, res):
        js_str = re.findall("document.cookie=(.*?)\+\('m'\)\+\('a'\)\+\('x'\)", res.text, re.S)[0]
        js = """function jl_clear(){ return %s }""" % js_str
        __jsluid_h = "__jsluid_h=" + res.cookies['__jsluid_h']
        __jsl_clearance = execjs.compile(js).call('jl_clear').replace(";", '')

        cookie = '{}; {}'.format(__jsluid_h, __jsl_clearance)
        self.headers['Cookie'] = cookie

        res2 = requests.get(self.url, headers=self.headers)
        set_timeout = re.findall(r"(setTimeout.*?\},.*?\);)", res2.text, re.S)[0]
        js_cookie = "return {}".format(re.findall("setTimeout.*?=(.*?);", res2.text, re.S)[0])
        js = res.content.decode("utf-8").replace(set_timeout, js_cookie).replace("go({",
                                                                                "function get_jsl(){return go({").replace(
            "<script>", '').replace("</script>", "}").replace("\\x20", ' ').replace("\\x22", '"')

        js = self.get_js(js)

        jsl = execjs.compile(js, cwd=r'E:\node\node_modules\npm\node_modules').call("get_jsl")

        cookie = "{} {};".format(__jsluid_h, jsl.split(";")[0])
        self.headers['Cookie'] = cookie

        res = requests.get(self.url, headers=self.headers)
        jsid = re.findall("(JSESSIONID=.*?;)", res.headers['Set-Cookie'])[0]
        token = re.findall("(SECTOKEN=.*?;)", res.headers['Set-Cookie'])[0]
        tlb_cookie = re.findall("(tlb_cookie=.*?;)", res.headers['Set-Cookie'])[0]
        self.headers['Cookie'] = '{} {} {} {}'.format(self.headers['Cookie'], jsid, token, tlb_cookie)

        res = requests.get(self.url, headers=self.headers)
        print(res.text)

    def get_js(self, js_):
        js = r"""
            const jsdom = require("jsdom");
        const { JSDOM } = jsdom;
        const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
        window = global;
        var document = dom.window.document;
        var params = {
            location:{
                hash: "",

                pathname: "/",
                port: "",
                protocol: "https:",
                search: "",
            },
            navigator:{
                appCodeName: "Mozilla",
                appName: "Netscape",
                appVersion: "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
                cookieEnabled: true,
                deviceMemory: 8,
                doNotTrack: null,
                hardwareConcurrency: 4,
                language: "zh-CN",
                languages: ["zh-CN", "zh"],
                maxTouchPoints: 0,
                onLine: true,
                platform: "Win32",
                product: "Gecko",
                productSub: "20030107",
                userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36",
                vendor: "Google Inc.",
                vendorSub: "",
            },
            "screen":{
                availHeight: 1040,
                availLeft: 0,
                availTop: 0,
                availWidth: 1920,
                colorDepth: 24,
                height: 1080,
                pixelDepth: 24,
                width: 1920,
            }
        };
        Object.assign(window,params);
        window.document = document;

            %s
            """ % js_
        return js

    def run(self):
        res = requests.get(self.url, headers=self.headers)
        self.get_cookies(res)
        pprint(self.headers)

if __name__ == '__main__':
    get_index = GetIndex()
    get_index.run()


import logging
from skmultiflow.lazy import KNNADWINClassifier
from skmultiflow.data import FileStream
from skmultiflow.transform import OneHotToCategorical
from sklearn.neighbors.classification import KNeighborsClassifier
from timeit import default_timer as timer

def demo():
    """ _test_knn_adwin

    This demo tests the KNNADWINClassifier on a file stream, which gives
    instances coming from a SEA generator.

    The test computes the performance of the KNNADWINClassifier as well as
    the time to create the structure and classify max_samples (10000 by
    default) instances.

    """
    start = timer()
    logging.basicConfig(format='%(message)s', level=logging.INFO)
    # warnings.filterwarnings("ignore", ".*Passing 1d.*")
    stream = FileStream("https://raw.githubusercontent.com/scikit-multiflow/streaming-datasets/"
                        "master/sea_big.csv", -1, 1)
    # stream = RandomRBFGeneratorDrift(change_speed=41.00, n_centroids=50, model_random_state=32523423,
    #                                  sample_seed=5435, n_classes=2, num_att=10, num_drift_centroids=50)

    t = OneHotToCategorical([[10, 11, 12, 13],
                            [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
                            36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53]])
    t2 = OneHotToCategorical([[10, 11, 12, 13],
                            [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
                            36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53]])

    knn = KNNADWINClassifier(n_neighbors=8, leaf_size=40, max_window_size=2000)
    # pipe = Pipeline([('one_hot_to_categorical', t), ('KNNClassifier', knn)])

    compare = KNeighborsClassifier(n_neighbors=8, algorithm='kd_tree', leaf_size=40, metric='euclidean')
    # pipe2 = Pipeline([('one_hot_to_categorical', t2), ('KNNClassifier', compare)])
    first = True
    train = 200
    if train > 0:
        X, y = stream.next_sample(train)
        # pipe.partial_fit(X, y, classes=stream.target_values)
        # pipe.partial_fit(X, y, classes=stream.target_values)
        # pipe2.fit(X, y)

        knn.partial_fit(X, y, classes=stream.target_values)
        compare.fit(X, y)
        first = False
    n_samples = 0
    max_samples = 10000
    my_corrects = 0
    compare_corrects = 0

    while n_samples < max_samples:
        if n_samples % (max_samples/20) == 0:
            logging.info('%s%%', str((n_samples//(max_samples/20)*5)))
        X, y = stream.next_sample()
        # my_pred = pipe.predict(X)
        my_pred = knn.predict(X)
        # my_pred = [1]
        if first:
            # pipe.partial_fit(X, y, classes=stream.target_values)
            # pipe.partial_fit(X, y, classes=stream.target_values)
            knn.partial_fit(X, y, classes=stream.target_values)
            first = False
        else:
            # pipe.partial_fit(X, y)
            knn.partial_fit(X, y)
        # compare_pred = pipe2.predict(X)
        compare_pred = compare.predict(X)
        if y[0] == my_pred[0]:
            my_corrects += 1
        if y[0] == compare_pred[0]:
            compare_corrects += 1
        n_samples += 1

    end = timer()

    print('Evaluation time: ' + str(end - start))
    print(str(n_samples) + ' samples analyzed.')
    print('My performance: ' + str(my_corrects / n_samples))
    print('Compare performance: ' + str(compare_corrects / n_samples))

if __name__ == '__main__':
    demo()


string = input(" enter  String : ")
char = input("enter  Character : ")
i = 0
count=0

while(i < len(string)):
 if(string[i] == char):
  count=count+1
 i=i+1
print("The count of ", char, "is" , count)


from openmdao.api import ExplicitComponent

class GrossWeightComp(ExplicitComponent):
    # Coefficients

    def setup(self):
        self.add_input('Wp')   # weight of payload (passangers)
        self.add_input('Wb')   # weight of battery
        self.add_input('S',desc='lifting surface')
        #self.add_input('We/W0')   # empty over gross
        self.add_input('We',desc='empty weight')
        self.add_output('W0') # gross weight
        self.add_output('We_W0') # gross weight
        self.add_output('Wb_W0') # gross weight
        self.add_output('W_S')
        self.declare_partials('*', '*')
        self.declare_partials(of='*', wrt='*', method='cs')

    def compute(self, inputs, outputs):
        Wp = inputs['Wp']
        Wb = inputs['Wb']
        We = inputs['We']
        #We_W0 = inputs['We']/inputs['W0']
        W0 = (Wp + Wb + We)
        outputs['We_W0'] = We/W0
        outputs['Wb_W0'] = Wb/W0
        outputs['W0'] = W0
        outputs['W_S'] = W0/inputs['S']

    #def compute_partials(self, inputs, partials):
        #Wp = inputs['Wp']
        #Wb = inputs['Wb']
        #We_W0 = inputs['We']/inputs['W0']
        #partials['W0', 'Wp'] = 1. / (1 - We_W0)
        #partials['W0', 'Wb'] = 1. / (1 - We_W0)
        #artials['W0', 'We/W0'] = (Wp + Wb) / (1 - We_W0) ** 2


"""
Thuật toán insert Sort
"""
import  random as rd
import time
import matplotlib
def InsertSort(key):
    n = len(key)
    for i in range(1,n):
        vt = i -1
        x = key[i]
        while(vt>=0 and key[vt] > x):
            key[vt +1] = key[vt]
            vt -= 1
        key[vt+1] = x
"""
Tets
"""
sample = rd.sample(range(10000),10000)
print("Before: ", sample)
start = time.time()
InsertSort(sample)
end = time.time()
print("After: ", sample)
print('Thời gian chạy là : ' , end - start)


from setuptools import setup

package_name = 'api_test'

setup(
    name=package_name,
    version='0.0.0',
    packages=[package_name],
    data_files=[
        ('share/ament_index/resource_index/packages',
            ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
    ],
    install_requires=['setuptools'],
    zip_safe=True,
    maintainer='omose',
    maintainer_email='hiro.tx@kmd.keio.ac.jp',
    description='TODO: Package description',
    license='TODO: License declaration',
    tests_require=['pytest'],
    entry_points={
        'console_scripts': [
            'autonomous_api = py_pubsub.publisher_member_function:main',
        ],
    },
)


import math
from tqdm import tqdm
import pickle

class RiskModel(object):
    def __init__(self, args):
        self.args = args

    def forward(self, batch):
        x_transformed = {
            key: func(batch[key]) for key, func in self.input_transformers.items()
        }
        x_scaled = self.scale_inputs(x_transformed)
        risk = self.model(x_scaled)
        return risk

    def test(self, data):
        results = []
        for sample in tqdm(data.dataset):
            sample["golds"] = sample["y"]
            sample["probs"] = self.forward(sample)

        if self.args.save_predictions:
            self.save_predictions(data.dataset)

    def save_predictions(self, data):
        predictions_dict = [
            {k: v for k, v in d.items() if k in self.save_keys} for d in data
        ]
        predictions_filename = "{}.{}.predictions".format(
            self.args.results_path, self.save_prefix
        )
        pickle.dump(predictions_dict, open(predictions_filename, "wb"))

    @property
    def input_coef(self):
        pass

    @property
    def input_transformers(self):
        pass

class PLCOm2012(RiskModel):
    def __init__(self, args):
        super(PLCOm2012, self).__init__(args)

    def model(self, x):
        return 1 / (1 + math.exp(-x))

    def scale_inputs(self, x):
        running_sum = -4.532506
        for key, beta in self.input_coef.items():
            if key == "race":
                running_sum += beta[x["race"]]
            else:
                running_sum += x[key] * beta
        return running_sum

    @property
    def input_coef(self):
        coefs = {
            "age": 0.0778868,
            "race": {
                "white": 0,
                "black": 0.3944778,
                "hispanic": -0.7434744,
                "asian": -0.466585,
                "native_hawaiian_pacific": 0,
                "american_indian_alaskan": 1.027152,
            },
            "education": -0.0812744,
            "bmi": -0.0274194,
            "cancer_hx": 0.4589971,
            "family_lc_hx": 0.587185,
            "copd": 0.3553063,
            "is_smoker": 0.2597431,
            "smoking_intensity": -1.822606,
            "smoking_duration": 0.0317321,
            "years_since_quit_smoking": -0.0308572,
        }
        return coefs

    @property
    def input_transformers(self):
        funcs = {
            "age": lambda x: x - 62,
            "race": lambda x: x,
            "education": lambda x: x - 4,
            "bmi": lambda x: x - 27,
            "cancer_hx": lambda x: x,
            "family_lc_hx": lambda x: x,
            "copd": lambda x: x,
            "is_smoker": lambda x: x,
            "smoking_intensity": lambda x: 10 / x - 0.4021541613,
            "smoking_duration": lambda x: x - 27,
            "years_since_quit_smoking": lambda x: x - 10,
        }
        return funcs

    @property
    def save_keys(self):
        return [
            "pid",
            "age",
            "race",
            "education",
            "bmi",
            "cancer_hx",
            "family_lc_hx",
            "copd",
            "is_smoker",
            "smoking_intensity",
            "smoking_duration",
            "years_since_quit_smoking",
            "exam",
            "golds",
            "probs",
            "time_at_event",
            "y_seq",
            "y_mask",
            "screen_timepoint",
        ]


""" FLAKE8 : py -m flake8 """
from classes.Block import Block
from classes.Chain import Chain
from classes.Wallet import Wallet
import time

def run():
    print("Génération de la Blockchain...")
    time.sleep(1)
    chain = Chain()
    print("La chain contient les blocs représentés par les fichiers suivants : ")
    for p in chain.blocks:
        time.sleep(0.3)
        print(p)
    print("Création de votre nouveau wallet...")
    time.sleep(1.2)
    wallet = Wallet()
    print("Terminé ! Votre Wallet a pour identifiant unique : " + str(wallet.unique_id))
    print("Vous disposez du solde suivant : " + str(wallet.balance))
    time.sleep(0.8)
    """ Poids du bloc choisi """
    bloc = chain.get_block("00")
    print("Une transaction va maintenant s'effectuer sur le premier bloc disposant d'assez de place, le bloc : " + str(bloc.hash))
    saler = Wallet("14938570948877436095580126826539516641")
    print("Wallet du vendeur = " + str(saler.unique_id))
    print("Solde du vendeur = " + str(saler.balance))
    time.sleep(0.8)
    chain.add_transaction("14938570948877436095580126826539516641", str(wallet.unique_id), 10)
    print("Vous lui créditez la somme de 10")
    time.sleep(0.8)
    saler2 = Wallet("14938570948877436095580126826539516641")
    wallet2 = Wallet(wallet.unique_id)
    print("Voici le nouveau solde du vendeur : " + str(saler2.balance))
    print("Et voici le votre : " + str(wallet2.balance))
    time.sleep(0.8)
    time.sleep(0.8)
    print("Fin de la démonstration")

if __name__ == '__main__':
    run()


# // : 몫만 출력
# % : 나머지만 출력
# / : 둘 다 출력
n1 = int(input("분자를 입력하시오 : "))
n2 = int(input("분모를 입력하시오 : "))
quotient = n1 // n2
remainder = n1 % n2
calculate = n1 / n2
print("나눗셈의 몫 =", quotient)
print("나눗셈의 나머지 =", remainder)
print("분수의 값 =", calculate)

몫과 나머지 출력.py


from casioplot import *
from math import *

# Draw a graph.
#
# To use it, do this:
#
# from graph import *
#
# def func(x):
#  return sin(x)+sin(3*x)/3
#
# g=Graph()
# g.graph(func,xmin=-20,xmax=20)

class Graph:

  def graph(self,fn,xmin=-5.0,xmax=5.0,color=(0,0,0)):
    # Lists of x values and y values
    xl=[]
    yl=[]

    # Set graph edges
    sxmin=20 # Left
    sxmax=383 # Right
    symin=0 # Top
    symax=171 # Bottom
    sxrange=sxmax-sxmin
    syvrange=symax-symin

    # Evaluate function for every x pixel
    for i in range(0,sxrange+1):
      x=i/sxrange * (xmax-xmin) + xmin
      xl.append(x)
      y=fn(x)
      yl.append(y)
      # Update min and max y values
      if i==0:
        ymin=y
        ymax=y
      if y<ymin:
        ymin=y
      if y>ymax:
        ymax=y

    # Edge case: if it's just constant y, make min and max y different
    if ymin==ymax:
      ymin-=1
      ymax+=1

    # Add a margin to top and bottom
    ymid=(ymin+ymax)/2
    ymax=(ymax-ymid)*1.05+ymid
    ymin=(ymin-ymid)*1.05+ymid

    yvrange=ymax-ymin
    xvrange=xmax-xmin

    # Draw vertical grid lines, using a heuristic to work out the intervals
    expt=floor(log10(xvrange))

    ex1=floor(xmin/10**expt)
    ex2=ceil(xmax/10**expt)

    for ex in range(ex1,ex2+1):
      x=ex*10**expt
      sx=int((x-xmin)/(xvrange)*sxrange)
      for sy in range(0,(syvrange+1)):
        set_pixel(sx+sxmin,sy,(127,127,127))
      draw_string(sx+sxmin,175,str(x))

    # Draw horizontal grid lines, using a heuristic to work out the intervals
    expt=floor(log10(yvrange))

    ex1=floor(ymin/10**expt)
    ex2=ceil(ymax/10**expt)

    for ex in range(ex1,ex2+1):
      y=ex*10**expt
      sy=int(syvrange-(y-ymin)/(yvrange)*syvrange)
      for sx in range(0,(sxrange+1)):
        set_pixel(sx+sxmin,sy,(127,127,127))
      draw_string(0,sy,str(y))

    # Plot the graph
    for sx in range(1,(sxrange+1)):
      # Calculate previous and current y values
      sy1=int(syvrange-(yl[sx-1]-ymin)/(yvrange)*syvrange)
      sy2=int(syvrange-(yl[sx]-ymin)/(yvrange)*syvrange)
      # Set step depending on whether curve is going up or down
      if sy1>sy2:
        st=-1
      else:
        st=1
      # Draw vertical line from previous y to current y (so we don't have gaps)
      for sy in range(sy1,sy2+st,st):
        self._point(sx+sxmin,sy,color)

    show_screen()

  # Draw a thick point
  def _point(self,x,y,color=(0,0,0)):
    set_pixel(x,y,color)
    set_pixel(x-1,y,color)
    set_pixel(x,y-1,color)
    set_pixel(x+1,y,color)
    set_pixel(x,y+1,color)


# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(['invoice.py'],
             pathex=['/media/ghostjson/My Passport/workspace/workspace/freelance/nandorock4c/app'],
             binaries=[],
             datas=[('/usr/local/lib/python3.8/dist-packages/eel/eel.js', 'eel'), ('ui', 'ui')],
             hiddenimports=['bottle_websocket'],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='invoice',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False )


import argparse
import asyncio
import pprint

import aiohttp

def create_args_parser():
    parser = argparse.ArgumentParser(description='Jaundice news rate')
    default_urls = [
        'https://inosmi.ru/not/exist.html',
        'https://inosmiy.ru/20221106/virusy-257514193.html',
        'https://inosmi.ru/20221106/videoigry-257474918.html',
        'https://lenta.ru/news/2022/11/27/20_strausov/',
        'https://inosmi.ru/20221104/mars-257472040.html',
        'https://inosmi.ru/20221127/bessmertie-258272850.html'
    ]
    default_urls = ','.join(default_urls)
    parser.add_argument(
        '--urls',
        default=default_urls,
        metavar='{urls of articles from inosmi.ru}',
        help=(
            'The urls of articles to rate separated by commas, '
            f'by default: {default_urls}'
        ),
    )
    return parser

async def main():
    args_parser = create_args_parser()
    args = args_parser.parse_args()

    server_url = 'http://127.0.0.1:8080/'
    payload = {'urls': args.urls}
    async with aiohttp.ClientSession() as session:
        async with session.get(server_url, params=payload) as response:
            response.raise_for_status()
            articles_cards = await response.json()
            pprint.pprint(articles_cards)

if __name__ == '__main__':
    asyncio.run(main())


#!/usr/bin/env python3

import argparse
import datetime
import glob
import json
import os
import shutil
import sys
import subprocess
import time
import uuid

def run_command(message):
    """
    Initiate pipeline run
    input:
      message: {"base_command": "nextflow", "subcommand": "run", "command_invocation_directory": "/home/user/analysis", ...}
    output: {message}
    """
    now = datetime.datetime.now()
    today_iso8601_str = now.strftime('%Y-%m-%d')
    message['message_type'] = "command_invocation"
    message['command_invocation_id'] = str(uuid.uuid4())

    command = [
        message['base_command']
    ]

    if 'subcommand' in message:
        command.append(message['subcommand'])

    if 'positional_arguments_before_flagged_arguments' in message:
        for argument in message['positional_arguments_before_flagged_arguments']:
            command.append(argument)

    if 'flags' in message:
        for flag in message['flags']:
            command.append(flag)

    if 'flagged_arguments' in message:
        for flag, value in message['flagged_arguments'].items():
            if '$' in value:
                value = os.path.expandvars(value)
                message['flagged_arguments'][flag] = value
            if value is not None:
                command.append(flag)
                command.append(value)

    if 'positional_arguments_after_flagged_arguments' in message:
        for argument in message['positional_arguments_before_flagged_arguments']:
            command.append(argument)

    if 'positional_arguments' in message:
        for argument in message['positional_arguments']:
            command.append(argument)

    exit_code = None
    try:
        message['timestamp_command_invoked'] = datetime.datetime.now().isoformat()
        exit_code = subprocess.check_call(command, cwd=message['command_invocation_directory'])
    except subprocess.CalledProcessError as e:
        sys.stderr.write("Error running command: " + " ".join(command))

    message['timestamp_command_invocation_completed'] = datetime.datetime.now().isoformat()
    message['command_exit_code'] = exit_code

    return message

def remove_nextflow_work_dir(message):
    if '-work-dir' in message['flagged_arguments']:
        work_dir_path = message['flagged_arguments']['-work-dir']
    else:
        work_dir_path = os.path.join(message['command_invocation_directory'], 'work')
    try:
        time.sleep(10) # wait for filesystem latency to settle
        shutil.rmtree(work_dir_path)
    except Exception as e:
        raise(e)

def remove_nextflow_logs(message):
    nextflow_logs = glob.glob(os.path.join(message['command_invocation_directory'], ".nextflow*"))
    for log in nextflow_logs:
        try:
            if os.path.isdir(log):
                shutil.rmtree(log)
            elif os.path.isfile(log):
                os.remove(log)
            else:
                pass
        except Exception as e:
            raise(e)

def nextflow_cleanup(message):
    cleanup_options = message['cleanup_options']
    if 'remove_command_tmp_directories' in cleanup_options and cleanup_options['remove_command_tmp_directories']:
        remove_nextflow_work_dir(message)

    if 'remove_command_logs' in cleanup_options and cleanup_options['remove_command_logs']:
        remove_nextflow_logs(message)

def cleanup(message):
    if 'base_command' in message and message['base_command'] == 'nextflow':
        nextflow_cleanup(message)

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    args = parser.parse_args()

    for line in sys.stdin:
        try:
            message = json.loads(line.rstrip())
            if message['message_type'] == 'command_creation':
                message = run_command(message)
                cleanup(message)
            elif message['message_type'] == 'sentinel':
                pass
            print(json.dumps(message))
        except Exception as e:
            cleanup(message)

if __name__ == '__main__':
    main()


#!/usr/bin/python
from mapnik import Image, Map, Projection, Box2d, Coord, load_map, render
import sys
import logging

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

def center_to_bbox(lat, lon, zoom, imgx, imgy):
    base = 0.000005364418  # longitude range of 1 pixel at zoom 18
    lon_half = imgx * base * (2**(18 - zoom - 1))
    lat_half = imgy * base * (2**(18 - zoom - 1))
    west = lon - lon_half
    east = lon + lon_half
    north = lat + base
    south = lat - base
    logging.info("range: bottomleft(%s, %s), topright(%s, %s)" % (west, lat - lat_half, east, lat + lat_half))
    return west, south, east, north

if __name__ == "__main__":
    mapfile = "my_styles/mapnik2normal.xml"

    map_uri = "map.png"

    lat = 49.25
    lon = 7.0
    if len(sys.argv) == 2:
        zoom = int(sys.argv[1])
    else:
        zoom = 13
    imgx = 500
    imgy = 400

    ll = center_to_bbox(lat, lon, zoom, imgx, imgy)
    m = Map(imgx, imgy)
    load_map(m, mapfile)
    prj = Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m"
                     " +nadgrids=@null +no_defs +over")
    c0 = prj.forward(Coord(ll[0], ll[1]))
    c1 = prj.forward(Coord(ll[2], ll[3]))
    bbox = Box2d(c0.x, c0.y, c1.x, c1.y)
    m.zoom_to_box(bbox)
    im = Image(imgx, imgy)
    render(m, im)
    view = im.view(0, 0, imgx, imgy)  # x,y,width,height
    view.save(map_uri, 'png')


import random

while True:
    dice = input("What kind of dice?")
    if dice == "aaa":
        break

    if "d" in dice:
        split = dice.split("d")
        sum = 0
        for i in range(int(split[0])):
            sum += random.randint(1,int(split[1]))
        print(sum)


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 27 17:29:02 2017

@author: tater
"""

from scipy import *
from matplotlib import pyplot as plt

def create_bar(data, labels):
    num_bars = len(labels)
    positions = range(1, num_bars+1)
    plt.barh(positions, data, align='center')
    plt.yticks(positions, labels)
    plt.xlabel("Dollars")
    plt.ylabel("Categories")
    plt.title('Expenditures per Category')
    plt.grid()
    plt.show()

if __name__ == '__main__':
    num_cat = int(input('Enter the number of categories: '))
    category = []
    expenditure = []
    for i in range(0, num_cat):
        category.append(str(input('Enter category: ')))
        expenditure.append(int(input('Expenditure: ')))

    create_bar(expenditure, category)


class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) == 1:
            return False

        # brute force way
#         for i in range(len(nums)-1):
#             for j in range(i+1, len(nums)):
#                 if nums[i] == nums[j]:
#                     return True

#         return False

        # set way

        hash = set()
        # iterate thru the array
            # if the current number is in set:
                # that means it's repeating:
                    # return True
            # if the current number is not in set:
                # that means keep adding to the set

        # all numbers are distinct

        for num in nums:
            if num in hash:
                return True
            hash.add(num)

        return False


"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2

For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""

from math import sqrt

a = 0
num = False

while not num:
    a += 1
    for b in range(a+1, 1000-a):
        c = sqrt(a**2 + b**2)
        if c % 1 == 0 and a+b+c == 1000:
            num = a*b*c
            break

print(a, b, c, num)


import random
from typing import Optional
from fastapi import HTTPException

from sqlalchemy import text
from sqlalchemy.exc import NoResultFound

from ..config import JUDGE_COLUMNS, MAX_USER_COUNT
from ..db import engine
from . import model, user_impl

def commit(conn):
    conn.execute(text("COMMIT"))

def rollback(conn):
    conn.execute(text("ROLLBACK"))

def create_room(
    live_id: int, select_difficulty: model.LiveDifficulty, token: str
) -> int:
    with engine.begin() as conn:
        return _create_room(conn, live_id, select_difficulty, token)

def _create_room(
    conn, live_id: int, select_difficulty: model.LiveDifficulty, token: str
) -> int:
    # room_idも衝突を回避する必要がある
    room_id = random.randint(0, 1000000000)
    while not (_get_room_by_room_id(conn, room_id) is None):
        room_id = random.randint(0, 1000000000)

    _ = conn.execute(
        text(
            "INSERT INTO `room` (live_id, room_id, joined_user_count, max_user_count, status) VALUES (:live_id, :room_id, :joined_user_count, :max_user_count, :status)"
        ),
        {
            "live_id": live_id,
            "room_id": room_id,
            "joined_user_count": 1,
            "max_user_count": MAX_USER_COUNT,
            "status": model.WaitRoomStatus.Waiting.value,
        },
    )

    user = user_impl._get_user_by_token(conn, token)
    if user is None:
        raise HTTPException(status_code=404, detail="User not found")

    _ = conn.execute(
        text(
            "INSERT INTO `room_member` (name, room_id, user_id, token, is_host, select_difficulty) VALUES (:name, :room_id, :user_id, :token, :is_host, :select_difficulty)"
        ),
        {
            "name": user.name,
            "room_id": room_id,
            "user_id": user.id,
            "token": token,
            "is_host": True,
            "select_difficulty": select_difficulty.value,
        },
    )
    return room_id

def get_room_list(live_id: int) -> list[model.RoomInfo]:
    with engine.begin() as conn:
        return _get_room_list(conn, live_id)

def _get_room_list(conn, live_id: int) -> list[model.RoomInfo]:
    if live_id == 0:
        result = conn.execute(
            text(
                "SELECT `room_id`, `live_id`, `joined_user_count`, `max_user_count` FROM `room` WHERE `status` = :status AND `joined_user_count` < `max_user_count`"
            ),
            {"status": model.WaitRoomStatus.Waiting.value},
        )
    else:
        result = conn.execute(
            text(
                "SELECT `room_id`, `live_id`, `joined_user_count`, `max_user_count` FROM `room` WHERE `live_id` = :live_id AND `status` = :status AND `joined_user_count` < `max_user_count`"
            ),
            {"live_id": live_id, "status": model.WaitRoomStatus.Waiting.value},
        )
    try:
        rows = result.all()
    except NoResultFound:
        return []
    return [model.RoomInfo.from_orm(row) for row in rows]

def _get_room_by_room_id(
    conn, room_id: int, rock: bool = False
) -> Optional[model.RoomInfo]:
    query = "SELECT `live_id`, `room_id`, `joined_user_count`, `max_user_count` FROM `room` WHERE `room_id` = :room_id"
    if rock:
        query += " FOR UPDATE"
    result = conn.execute(
        text(query),
        {"room_id": room_id},
    )
    try:
        row = result.one()
    except NoResultFound:
        return None
    return model.RoomInfo.from_orm(row)

def join_room(
    room_id: int, select_difficulty: model.LiveDifficulty, token: str
) -> model.JoinRoomResult:
    with engine.begin() as conn:
        return _join_room(conn, room_id, select_difficulty, token)

def _join_room(
    conn, room_id: int, select_difficulty: model.LiveDifficulty, token: str
) -> model.JoinRoomResult:
    room = _get_room_by_room_id(conn, room_id, rock=True)
    if room is None:
        commit(conn)
        return model.JoinRoomResult.Disbanded

    if room.joined_user_count >= room.max_user_count:
        commit(conn)
        return model.JoinRoomResult.RoomFull

    status = _get_room_status(conn, room_id)

    if status != model.WaitRoomStatus.Waiting.value:
        commit(conn)
        return model.JoinRoomResult.OtherError

    # you are already in the room
    if not (_get_room_member_by_room_id_and_token(conn, room_id, token) is None):
        commit(conn)
        return model.JoinRoomResult.OtherError

    user = user_impl._get_user_by_token(conn, token)
    _ = conn.execute(
        text(
            "INSERT INTO `room_member` (name, room_id, user_id, token, is_host, select_difficulty) VALUES (:name, :room_id, :user_id, :token, :is_host, :select_difficulty)"
        ),
        {
            "name": user.name,
            "room_id": room_id,
            "user_id": user.id,
            "token": token,
            "is_host": False,
            "select_difficulty": select_difficulty.value,
        },
    )

    _ = conn.execute(
        text(
            "UPDATE `room` SET `joined_user_count` = `joined_user_count` + 1 WHERE `room_id` = :room_id"
        ),
        {
            "room_id": room_id,
        },
    )

    commit(conn)

    return model.JoinRoomResult.Ok

def _get_room_member_by_room_id_and_token(
    conn, room_id: int, token: str
) -> Optional[model.RoomMember]:
    result = conn.execute(
        text(
            "SELECT `name`, `room_id`, `token`, `token`, `is_host`, `select_difficulty` FROM `room_member` WHERE `room_id` = :room_id AND `token` = :token"
        ),
        {
            "room_id": room_id,
            "token": token,
        },
    )
    try:
        row = result.one()
    except NoResultFound:
        return None
    return model.RoomMember.from_orm(row)

def get_room_wait(
    room_id: int, token: str
) -> tuple[model.WaitRoomStatus, list[model.RoomUser]]:
    with engine.begin() as conn:
        return _get_room_wait(conn, room_id, token)

def _get_room_wait(
    conn, room_id: int, token: str
) -> tuple[model.WaitRoomStatus, list[model.RoomUser]]:
    status = _get_room_status(conn, room_id)

    result = conn.execute(
        text(
            "SELECT `name`, `room_id`, `token`, `is_host`, select_difficulty FROM `room_member` WHERE `room_id` = :room_id"
        ),
        {
            "room_id": room_id,
        },
    )
    try:
        rows = result.all()
    except NoResultFound:
        return status, []
    room_user_list = []
    for row in rows:
        this_member = model.RoomMember.from_orm(row)
        this_user = convert_room_member_to_room_user(
            conn, this_member, is_me=(this_member.token == token)
        )
        room_user_list.append(this_user)

    return status, room_user_list

def convert_room_member_to_room_user(
    conn, room_member: model.RoomMember, is_me=True
) -> model.RoomUser:
    user = user_impl._get_user_by_token(conn, room_member.token)
    return model.RoomUser(
        user_id=user.id,
        name=room_member.name,
        leader_card_id=user.leader_card_id,
        select_difficulty=room_member.select_difficulty,
        is_host=room_member.is_host,
        is_me=is_me,
    )

def _get_room_status(conn, room_id: int) -> model.WaitRoomStatus:
    room = _get_room_by_room_id(conn, room_id)
    if room is None:
        return model.WaitRoomStatus.Dissolution

    result = conn.execute(
        text("SELECT `status` FROM `room` WHERE `room_id` = :room_id"),
        {
            "room_id": room_id,
        },
    )
    try:
        row = result.one()
    except NoResultFound:
        return model.WaitRoomStatus.OtherError
    return model.WaitRoomStatus(row[0])

def room_start(room_id: int, token: str) -> None:
    with engine.begin() as conn:
        _room_start(conn, room_id, token)

def _room_start(conn, room_id: int, token: str) -> None:
    member = _get_room_member_by_room_id_and_token(conn, room_id, token)

    if member is None:
        return

    if not member.is_host:
        return

    _ = conn.execute(
        text("UPDATE `room` SET `status` = :status WHERE `room_id` = :room_id"),
        {
            "status": model.WaitRoomStatus.LiveStart.value,
            "room_id": room_id,
        },
    )
    return

def room_end(room_id: int, judge_count_list: list[int], score: int, token: str) -> None:
    with engine.begin() as conn:
        _room_end(conn, room_id, judge_count_list, score, token)

def _room_end(
    conn, room_id: int, judge_count_list: list[int], score: int, token: str
) -> None:
    user = user_impl._get_user_by_token(conn, token)

    result = conn.execute(
        text(
            "SELECT `score` FROM `room_score` WHERE `room_id` = :room_id AND `user_id` = :user_id"
        ),
        {
            "room_id": room_id,
            "user_id": user.id,
        },
    )

    # すでにスコアが登録されている場合はreturn(一人を保証)
    # UPDATE実装でも良い
    if result.rowcount > 0:
        return

    query1 = "INSERT INTO `room_score` (`score`, `room_id`, `user_id`"
    query2 = "VALUES (:score, :room_id, :user_id"
    d1 = {"score": score, "room_id": room_id, "user_id": user.id}

    for column, judge_count in zip(JUDGE_COLUMNS, judge_count_list):
        query1 += ", `" + column + "`"
        query2 += ", :" + column
        d1[column] = judge_count

    query1 += ") "
    query2 += ")"
    query = query1 + query2
    _ = conn.execute(text(query), d1)
    return

def get_room_result(room_id: int, token: str) -> list[model.ResultUser]:
    with engine.begin() as conn:
        return _get_room_result(conn, room_id, token)

def _get_room_result(conn, room_id: int, token: str) -> list[model.ResultUser]:
    member = _get_room_member_by_room_id_and_token(conn, room_id, token)
    room = _get_room_by_room_id(conn, room_id)
    if member is None:
        return []

    query = "SELECT `user_id`, `score`"

    for column in JUDGE_COLUMNS:
        query += ", `" + column + "`"

    query += " FROM `room_score` WHERE `room_id` = :room_id"

    result = conn.execute(
        text(query),
        {
            "room_id": room_id,
        },
    )

    if result.rowcount < room.joined_user_count:
        return []

    try:
        rows = result.all()
    except NoResultFound:
        return []

    result_user_list = []
    for row in rows:
        user = model.ResultUser(user_id=row[0], score=row[1], judge_count_list=[])
        for i in range(len(JUDGE_COLUMNS)):
            if row[i] is None:
                user.judge_count_list.append(0)
            else:
                user.judge_count_list.append(row[i + 2])
        result_user_list.append(user)
    return result_user_list

def leave_room(room_id: int, token: str) -> None:
    with engine.begin() as conn:
        _leave_room(conn, room_id, token)

def _leave_room(conn, room_id: int, token: str) -> None:
    user = user_impl._get_user_by_token(conn, token)
    if user is None:
        return

    result = conn.execute(
        text(
            "SELECT room_id, joined_user_count FROM `room` WHERE `room_id` = :room_id LOCK IN SHARE MODE"
        ),
        {
            "room_id": room_id,
        },
    )

    try:
        row = result.one()
    except NoResultFound:
        return

    room = row

    result = conn.execute(
        text(
            "SELECT user_id, room_id, token, is_host FROM `room_member` WHERE `room_id` = :room_id AND `user_id` = :user_id LOCK IN SHARE MODE"
        ),
        {
            "room_id": room_id,
            "user_id": user.id,
        },
    )

    try:
        row = result.one()
    except NoResultFound:
        return

    member = row

    if member.is_host:
        result = conn.execute(
            text(
                "SELECT user_id FROM `room_member` WHERE `room_id` = :room_id AND `user_id` != :user_id LOCK IN SHARE MODE"
            ),
            {
                "room_id": room_id,
                "user_id": user.id,
            },
        )

        if result.rowcount > 0:
            members = result.all()
            _ = conn.execute(
                text(
                    "UPDATE `room_member` SET `is_host` = 1 WHERE `room_id` = :room_id AND `user_id` = :user_id"
                ),
                {
                    "room_id": room_id,
                    "user_id": members[0].user_id,
                },
            )

    _ = conn.execute(
        text(
            "DELETE FROM `room_member` WHERE `room_id` = :room_id AND `user_id` = :user_id"
        ),
        {
            "room_id": room_id,
            "user_id": user.id,
        },
    )

    _ = conn.execute(
        text(
            "DELETE FROM `room_score` WHERE `room_id` = :room_id AND `user_id` = :user_id"
        ),
        {
            "room_id": room_id,
            "user_id": user.id,
        },
    )

    _ = conn.execute(
        text(
            "UPDATE `room` SET `joined_user_count` = `joined_user_count` - 1 WHERE `room_id` = :room_id"
        ),
        {
            "room_id": room_id,
        },
    )

    room = _get_room_by_room_id(conn, room_id)
    if room.joined_user_count == 0:
        _ = conn.execute(
            text("DELETE FROM `room` WHERE `room_id` = :room_id"),
            {
                "room_id": room_id,
            },
        )

    commit(conn)

    return


import numpy as np

#Parameter data
x1 = np.array([-2.2, -0.25, 0, 1, 1.25, 5.25])
x2 = np.array([-2.25, -1.2, 0, 1, 4.25, 5])
y = np.array([7.37376, 1.79669, 0.137058, -0.456891, 11.9378, 11.0596])

#Setting matriks kernel G
G = np.ones((6, 3))
G[:, 1] = x1
G[:, 2] = x2**2

#Transpose matriks G dan inversi matriks
GT = np.transpose(G)
Ginv = np.linalg.inv(np.dot(GT, G))

#a. Menghitung solusi model estimasi (m) untuk menentukan koesfisien a0, a1, a2
mest = np.dot(Ginv, np.dot(GT, y))
print("Maka koefisien a0 =", + mest[0])
print("Maka koefisien a1 =", + mest[1])
print("Maka koefisien a2 =", + mest[2])

#Y hasil solusi
y_solusi = mest[0] + mest[1]*x1 + mest[2]*x2**2

#b. Menghitung error dan mitsfit
e = np.zeros(6)
for i in range(len(y)):
  e[i] = (y[i]-y_solusi[i])**2
mitsfit = np.sum(e)
print("Nilai Mitsfit dari solusi inversi di atas adalah", + mitsfit)

#c. Laju_Perubahan (turunan fungsi penjumlahan)
Laju = mest[1] + 2*mest[2]*0.5
print("laju perubahan pada saat posisi (-2,0.5) adalah", + Laju)

#d. nilai y pada koordinat (-1.5,-1.5), (-2,0.5), (3.5,4.0)
print("nilai y pada koordinat (-1.5,-1.5) adalah", mest[0] + mest[1]*(-1.5) + mest[2]*(-1.5)**2)
print("nilai y pada koordinat (-2,0.5) adalah", mest[0] + mest[1]*(-2) + mest[2]*(0.5)**2)
print("nilai y pada koordinat (3.5,4.0) adalah", mest[0] + mest[1]*(3.5) + mest[2]*(4)**2)

Leonardo Junior_12319120_UTS Inversi Geofisika Nomor 1.py


import glob
import os
import sys

def verifica_keywords(line):
	ls = line.split()
	if len(ls)>0:
		if ls[0].isdigit():
			return True
	if line[0:3]=="do ":
		return True
	elif line[0:5]=="enddo":
		return True
	elif line[0:6]=="end do":
		return True
	else:
		return False

def busca_end(li,label,do_data):
	aninhado = 0
	max_aninhamento=0
	for do in do_data:
		if do[0]<=li:
			continue
		if do[1]==label:
			return do[0],max_aninhamento
		if do[1]=="do":
			aninhado = aninhado+1
			max_aninhamento=max(max_aninhamento,aninhado)
	return 0,0

def busca_end_2(li,do_data):
	aninhado = 0
	max_aninhamento=0
	for do in do_data:
		if do[0]<=li:
			continue
		if do[1]=="do" and do[2]=='':
			aninhado = aninhado+1
			max_aninhamento=max(max_aninhamento,aninhado)
		if do[1]=="end" and aninhado==0:
			return do[0],max_aninhamento
		if do[1]=="end" and aninhado>0:
			aninhado = aninhado-1

	return 0,0

sources_files = glob.glob("*.f90")

for file in sources_files:

	fn = open(file,"r")
	lines = fn.readlines()
	fn.close()

	fo = open(file+".do","w")

	do_data = []

	line_count = 0
	for line in lines:
		line_count = line_count+1
		line = line.strip().lower()
		if verifica_keywords(line):
			if line[0]!="!":
				ls = line.split()
				if len(ls)>1:
					if ls[1].isdigit():
						label = ls[1]
						line = ls[0]
					else:
						label = ''
						line = ls[0]
				do_data.append([line_count,line,label])
				fo.write(line+":"+label+":{0:d}\n".format(line_count))
	fo.close()

	#Tratando dos laços com continues numéricos
	print("do com label=================================")
	for do in do_data:
		label = do[2]
		if len(label)>0:
			linha_inicial = do[0]
			linha_final,max_aninhamento = busca_end(linha_inicial+1,label,do_data)
			print(file,linha_inicial,linha_final,int(linha_final)-int(linha_inicial),max_aninhamento,"\n")
		#print(label,len(label),do)
	print("do-enddo=================================")
	#Tratando dos laços com do-enddo
	for do in do_data:
		label = do[2]
		if len(label)==0 and do[1]=="do":
			linha_inicial = do[0]
			linha_final,max_aninhamento = busca_end_2(linha_inicial+1,do_data)
			print(file,linha_inicial,linha_final,int(linha_final)-int(linha_inicial),max_aninhamento,"\n")


def is_valid_sensor_data(data):
    """
    Validate the sensor data format.

    This function validates that the data is in the expected format. It checks that 'data' is a string
    containing two numeric values separated by a comma.

    Args:
        data (str): The sensor data to validate.

    Returns:
        bool: True if the data is valid; otherwise, False.
    """
    if not isinstance(data, str):
        return False

    data_parts = data.split(',')
    if len(data_parts) != 2:
        return False

    temperature, moisture = data_parts

    if not (temperature.replace('.', '', 1).isdigit() and moisture.replace('.', '', 1).isdigit()):
        return False

    return True

def process_sensor_data(data):
    """
    Process sensor data.

    This function processes the validated sensor data. It can perform additional operations, data transformation,
    or save it to a database.

    Args:
        data (str): The validated sensor data.

    Returns:
        dict: A structured dictionary of sensor data.
    """
    temperature, moisture = data.split(',')

    # Create a structured dictionary with sensor data
    sensors_data = {
        "sensor1": {
            "temperature": f"{temperature}°C",
            "moisture": f"{moisture}%"
        }
    }

    return sensors_data


from dataclasses import dataclass
from typing import Any, Dict

from valsys.modeling.client.socket_handler import SocketHandler

from .exceptions import ModelingServiceGetException

@dataclass
class ModelingServiceSocketClient:
    auth_token: str = ""
    error: Any = None

    def run(self, url: str, data: Dict[str, str] = None, after_token=None):
        handler = SocketHandler(url=url,
                                config=data,
                                auth_token=self.auth_token,
                                trace=False,
                                after_token=after_token)

        handler.run()

        while True:
            if not handler.complete:
                continue
            if handler.error is not None:
                self.error = handler.error
                raise Exception(f"{handler.error}")
            elif handler.resp is not None:
                return handler.resp
            break

    def get(self, url: str, data: Dict[str, str] = None, after_token=None):
        return self.run(url, data, after_token=after_token)

    def post(self, url: str, data: Dict[str, str] = None, after_token=None):
        return self.run(url, data, after_token=after_token)


from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.db import models

import docker as docker_env
from channels.layers import get_channel_layer

from authenticate.models import User
from .utils import *
from .generate.proto import ProtoFile
from .generate.server import ServerFile
from .managers import UserManager

import importlib
import shutil
import traceback
import json
import shutil
import sys
import os

# import __Rmyw9LxbPBhhegjOy3IjvADs9U1KlT.protobuf_pb2 as objects

class Image:
    def __init__(self, id, image):
        self.id = id
        self.name = image
        self.label = image.split(':')[0]

class Docker(models.Model):
    lenguaje_choices = (
        ('python', 'Python'),
    )

    state_choices = (
        ('stopped', 'Stopped'),
        ('deleted', 'Deleted'),
        ('building', 'Building'),
        ('active', 'Active'),
    )

    id = models.CharField(max_length=32, primary_key=True)
    image_name = models.CharField(max_length=32, unique=True)

    state = models.CharField(
        max_length=10, choices=state_choices, default='building')
    ip = models.CharField(max_length=30, null=True)
    proto = models.CharField(max_length=500, null=True)
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='owner')
    subscribers = models.ManyToManyField(User, related_name='subscriptions')
    language = models.CharField(
        max_length=100, choices=lenguaje_choices, default='python')

    protocol = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    name = models.CharField(max_length=250, unique=True)
    background = models.CharField(max_length=500)
    description = models.TextField(null=True)
    image = models.CharField(max_length=100, null=True)
    workdir = models.CharField(max_length=500, null=True)
    file = models.CharField(max_length=100, null=True)
    classname = models.CharField(max_length=100, null=True)
    view = models.CharField(max_length=1, blank=False)
    extensions = models.CharField(max_length=250, null=True, blank=True)

    def check_if_exist(self, sub):
        return sub in self.subscribers.all()

    def get_container(self):
        try:
            client = docker_env.from_env()
            return client.containers.get(self.image_name)
        except docker_env.errors.NotFound as error:
            return None

    def check_active_state(self):
        if self.state == 'active':
            docker = self.get_container()
            return True if docker else False

    def get_container_or_run(self):
        container = self.get_container()
        if container:
            return container
        else:
            return self.run_container()

    def get_public_path(self):
        return f'{settings.MEDIA_URL}{self.id}'

    def get_path(self):
        return f'{settings.MEDIA_ROOT}/{self.id}'

    def create_folders(self):
        os.makedirs('{0}/experiments'.format(self.get_path()), 0o777)

    def dockerfile(self):
        """
            proto:
                {0}: ubicación absoluta del archivo (media_root)
                {1}: archivo proto (proto)
                {2}: ubicación del contenedor (path)
            image:
                {0}: nombre de la imagen creada (image)
            compile:
                {0}: ubicación del contenedor (path)
                {1}: carpeta contenedora de los archivos de comunicación (id)
                {2}: ruta relativa del archivo proto (proto)
        """
        commands = {
            'image': 'FROM {0}'.format(self.image),
            'server': 'COPY ./server.py {0}'.format(self.workdir),
            'proto': 'COPY ./protobuf.proto {0}'.format(self.workdir),

            'mkdir': 'RUN mkdir {0}/{1}'.format(self.workdir, self.id),
            'requirements': 'RUN pip install grpcio grpcio-tools',
            'compile': 'RUN python -m grpc_tools.protoc --proto_path={0} --python_out={0}/{1} --grpc_python_out={0}/{1} protobuf.proto'.format(self.workdir, self.id),
            'init': 'RUN touch {0}/{1}/__init__.py'.format(self.workdir, self.id)
        }

        dockerfile = '{0}/Dockerfile'.format(self.get_path())

        with open(dockerfile, '+w') as file:
            for command in commands.values():
                file.write('{0}\n'.format(command))

    def protobuf(self):
        protobuf = '{0}/{1}'.format(settings.MEDIA_ROOT, self.proto)

        with open(protobuf, '+w') as file_:
            proto = ProtoFile(items=[{
                'kind': element.kind,
                'len': element.len
            } for element in self.elements_type.all()])

            file_.write(proto.create_protobuf(self.image_name))

    def server(self):
        server = '{0}/{1}/server.py'.format(settings.MEDIA_ROOT, self.id)

        with open(server, '+w') as file_:
            aux = ServerFile(items=[{
                'kind': element.kind,
                'len': element.len
            } for element in self.elements_type.all()])

            file_.write(aux.create_server(self.id, ''.join(self.file.split(
                '.')[:-1]), self.workdir, self.classname))

    def create_docker(self):

        try:
            # Creando el WORKDIR
            self.create_folders()

            # Generando los archivos de comunicación
            self.protobuf()
            self.dockerfile()
            self.server()

            # Compilando el archivo de comunicación
            terminal_out(
                "python -m grpc_tools.protoc --proto_path=%(media)s --python_out=%(media)s/%(id)s --grpc_python_out=%(media)s/%(id)s %(id)s/%(proto)s" % {
                    'media': settings.MEDIA_ROOT,
                    'id': self.id,
                    'proto':  'protobuf.proto'.format(self.id)
                })

            shutil.move('%(media)s/%(id)s/%(id)s' % {
                'media': settings.MEDIA_ROOT, 'id': self.id
            },
                settings.ENV_ROOT
            )
        except:
            exc_type, exc_obj, tb = sys.exc_info()
            print(exc_type)
            print(exc_obj)
            traceback.print_exc()
            # self.delete()
        self.save()
        return True

    def build_docker(self):
        try:
            client = docker_env.APIClient(
                base_url='unix://var/run/docker.sock')
            steps = [
                [
                    "Step 1/7:",
                    "Loading image {0} ...".format(self.image),
                    "Loaded image {0}".format(self.image)
                ], [
                    "Step 2/7:",
                    "Creating service files ...",
                    "Created service files"
                ], [
                    "Step 3/7:",
                    "Creating comunication files ...",
                    "Created comunication files"
                ], [
                    "Step 4/7:",
                    "Moving comunication and service files to workdir('{0}') ...".format(
                        self.workdir),
                    "Moved comunication and service files to workdir('{0}')".format(
                        self.workdir)
                ], [
                    "Step 5/7:",
                    "Instaling dependencies of comunication ...",
                    "Instaled dependencies of comunication"
                ], [
                    "Step 6/7:",
                    "Compiling comunication files ...",
                    "Compiled comunication files"
                ], [
                    "Step 7/7:",
                    "Cleaning records ...",
                    "Cleaned records"
                ]
            ]

            return (
                client.build(path=self.get_path(), rm=True,
                             tag='{0}:latest'.format(self.image_name)),
                steps
            )
        except expression as identifier:
            self.delete()
            return [{'stream': "error"}, {'stream': "error"}], [["Error:", "An error occurred during model shrinkage. Check the data and try again"]]

    def run_container(self, builded=False):
        try:
            client = docker_env.from_env()
            client.containers.run(
                image=self.image_name,
                command='python server.py',
                detach=True,
                name=self.image_name,
                # ports={50051: 50051},
                remove=True,
                working_dir=self.workdir,
                volumes={
                    '{}/experiments'.format(self.get_path()): {
                        'bind': '{}/media'.format(self.workdir), 'mode': 'rw'
                    }
                }
            )
            container = self.get_container()
            self.ip = '%s:50051' % container.attrs['NetworkSettings']['IPAddress']
            self.state = 'builded' if builded else 'active'
            self.save()
            return container
        except docker_env.errors.ContainerError as error:
            print(error)
            return error
        except docker_env.errors.APIError as error:
            print(error)
            return error

    def stop_container(self):
        try:
            container = self.get_container()
            if container:
                self.get_container().stop()
                self.state = 'stopped'
                self.ip = ''
                self.save()
                return True
            return False
        except ValueError as error:
            print(error)
            return False
        except docker_env.errors.APIError as error:
            return False

    def delete_image(self):
        try:
            client = docker_env.from_env()
            client.images.remove(image=self.image_name, force=True)
        except docker_env.errors.ImageNotFound as error:
            print(error)

    def delete_module(self):
        self.stop_container()
        self.delete_image()
        self.state = 'deleted'
        self.save()

    def delete(self, delete_img=False):
        super().delete()
        shutil.rmtree(self.get_path(), ignore_errors=True)
        shutil.rmtree('{0}{1}'.format(
            settings.ENV_ROOT, self.id), ignore_errors=True)

class ElementType(models.Model):
    kind = models.CharField(max_length=30)
    docker = models.ForeignKey(Docker, null=False, blank=False,
                               on_delete=models.CASCADE, related_name='elements_type')
    element = models.ForeignKey(
        'Element', null=False, blank=False, on_delete=models.CASCADE, related_name='types')
    len = models.CharField(max_length=1, default=0)
    value = models.TextField()

    def __str__(self):
        return self.kind

class Element(models.Model):
    name = models.CharField(max_length=100, unique=True)

class Experiment(models.Model):
    state = models.CharField(max_length=10, default='created')
    user = models.ForeignKey(User, null=True, blank=False,
                             on_delete=models.CASCADE, related_name='experiments')
    docker = models.ForeignKey(Docker, null=True, blank=False,
                               on_delete=models.CASCADE, related_name='experiments')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def get_logs(self):
        return f"{self.get_workdir()}/logs.txt"

    def get_public_logs(self):
        return f"{self.get_public_path()}/logs.txt"

    def create_workdir(self, outputs=False):
        os.makedirs(self.inputs(), 0o777)
        open(self.get_logs(), "x")
        if outputs:
            os.makedirs(self.outputs(), 0o777)

    def inputs(self):
        return f"{self.get_workdir()}/inputs"

    def outputs(self):
        return f"{self.get_workdir()}/outputs"

    def get_public_path(self):
        return f"{self.docker.get_public_path()}/experiments/user_{self.user.id}/exp_{self.id}"

    def get_workdir(self):
        return '{0}/experiments/user_{1}/exp_{2}'.format(
            self.docker.get_path(), self.user.id, self.id)

    def delete(self):
        shutil.rmtree(self.get_workdir())
        super().delete()

    def run(self):
        try:
            objects = importlib.import_module(
                '{}.protobuf_pb2'.format(self.docker.id))

            input = self.docker.elements_type.filter(kind='input').get()

            if int(input.len) > 0:
                inputs_data = ['{0}/media/user_{1}/exp_{2}/inputs/{3}'.format(
                    self.docker.workdir, self.user.id, self.id, data.value) for data in self.elements.filter(kind='input')]
            else:
                inputs_data = ['{0}/media/user_{1}/exp_{2}/inputs/{3}'.format(
                    self.docker.workdir, self.user.id, self.id, data.value) for data in self.elements.filter(kind='input')][-1]

            outputs = self.docker.elements_type.filter(kind='output')
            have_output = outputs.count() == 1

            if have_output:
                outputs_data = '{0}/media/user_{1}/exp_{2}/outputs'.format(
                    self.docker.workdir, self.user.id, self.id)

            def get_inputs_obj(values, len):
                if len > 0:
                    return objects.Inputs(inputs=(objects.Input(value=value) for value in values))
                else:
                    return objects.Inputs(inputs=objects.Input(value=values))

            def createIn(inputs, outputs, len, have_output=False):
                # print(inputs, outputs, len, have_output)
                if have_output:
                    return {'inputs': get_inputs_obj(inputs, len), 'output': objects.Output(value=outputs)}
                else:
                    return {'inputs': get_inputs_obj(inputs, len)}

            print(createIn(inputs_data, outputs_data, int(input.len), have_output))

            return objects.In(
                **createIn(inputs_data, outputs_data, int(input.len), have_output)
            )

        except ValueError as erro:
            print("############ ERROR", erro)
            return ({"progress": 0, "state": 'Error', "description": "Something unexpected happened, try again"})

class ElementData(models.Model):
    experiment = models.ForeignKey(
        Experiment, on_delete=models.CASCADE, related_name='elements')
    kind = models.CharField(max_length=30)
    element = models.ForeignKey(Element, on_delete=models.CASCADE)
    value = models.TextField(null=True)
    name = models.TextField(null=True)
    example = models.BooleanField(default=False)

    def rename_output(self):
        if self.kind == "output":
            ext = self.name.split('.')[-1]
            new_name = f"output_{self.id}"
            self.value = f"{new_name}.{ext}"
            os.rename(f"{self.experiment.outputs()}/{self.name}",
                      f"{self.experiment.outputs()}/{self.value}")
            self.save()
        else:
            raise Exception("This is not a kind output")

    def copy_input(self, to):
        print(to)
        if self.kind == "input":
            shutil.copyfile(self.get_root_path(), to)
            return to.split('/')[-1]
        else:
            raise Exception("This is not a kind input")

    def get_root_path(self):
        if self.kind == "input":
            return '{}/{}'.format(self.experiment.inputs(), self.value)
        if self.kind == "output":
            return'{}/{}'.format(self.experiment.outputs(), self.value)

    def get_public_path(self):
        if self.kind == "input":
            return f"{self.experiment.get_public_path()}/inputs/{self.value}"
        if self.kind == "output":
            return f"{self.experiment.get_public_path()}/outputs/{self.value}"
        return None

    def delete(self):
        if os.path.exists(self.get_root_path()):
            os.remove(self.get_root_path())
        super().delete()

class Records(models.Model):
    experiment = models.ForeignKey(
        Experiment, on_delete=models.CASCADE, related_name='records')
    description = models.CharField(max_length=200)
    progress = models.CharField(max_length=30)
    state = models.CharField(max_length=20, default='execute')

    def write(self):
        with open(self.experiment.get_logs(), "a") as file:
            file.write(f"{self.description}\n")


#!/usr/bin/env python
import os
import sys
import time
import shutil
import multiprocessing as mp

from binary_io import BinaryIOCollection
from align_feats import AlignFeats

if len(sys.argv)!=5:
    print("Usage: python dtw_aligner_festvox_magphase.py <path_to_tools_dir> <path_to_src_feat_dir> <path_to_tgt_feat_dir> <path_to_src_aligned_feat_dir>")
    sys.exit(1)

### Arguments

# tools directory
tools_dir = sys.argv[1]

# Source features directory
src_feat_dir = sys.argv[2]

# Target features directory
tgt_feat_dir = sys.argv[3]

# Source-aligned features directory
src_aligned_feat_dir = sys.argv[4]

# bap dimension
#bap_dim = int(sys.argv[5])

if not os.path.exists(src_aligned_feat_dir):
    os.makedirs(src_aligned_feat_dir)

# path to tools
sptk = os.path.join(tools_dir, "bin/SPTK-3.9")
speech_tools = os.path.join(tools_dir, "speech_tools/bin")
festvox = os.path.join(tools_dir, "festvox")

### Define variables. TODO: read from config file (void hardcoding)
mag_dim  = 60
real_dim = 45
imag_dim = 45
lf0_dim  = 1

#src_mag_dir = os.path.join(src_feat_dir, "mag")
#tgt_mag_dir = os.path.join(tgt_feat_dir, "mag")

#src_bap_dir = os.path.join(src_feat_dir, "bap")
#tgt_bap_dir = os.path.join(tgt_feat_dir, "bap")

#src_lf0_dir = os.path.join(src_feat_dir, "lf0")
#tgt_lf0_dir = os.path.join(tgt_feat_dir, "lf0")

### create outut directories
alignments_dir = os.path.join(src_aligned_feat_dir, "../dtw_alignments")
temp_dir = os.path.join(src_aligned_feat_dir, "../temp")

#src_aligned_mag_dir = os.path.join(src_aligned_feat_dir, "mag")
#src_aligned_bap_dir = os.path.join(src_aligned_feat_dir, "bap")
#src_aligned_lf0_dir = os.path.join(src_aligned_feat_dir, "lf0")

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

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

#if not os.path.exists(src_aligned_mag_dir):
#    os.mkdir(src_aligned_mag_dir)

#if not os.path.exists(src_aligned_bap_dir):
#    os.mkdir(src_aligned_bap_dir)

#if not os.path.exists(src_aligned_lf0_dir):
#    os.mkdir(src_aligned_lf0_dir)

#################################################################
######## align source feats with target feats using dtw ## ######
#################################################################

io_funcs = BinaryIOCollection()
aligner  = AlignFeats()

# create dummy lab files
os.system("touch %s/i.lab" % (temp_dir))
os.system("touch %s/o.lab" % (temp_dir))

def get_mag_filelist(mag_dir):
    mag_files = []
    for file in os.listdir(mag_dir):
        whole_filepath = os.path.join(mag_dir,file)
        if os.path.isfile(whole_filepath) and str(whole_filepath).endswith(".mag"):
            mag_files.append(whole_filepath)
        elif os.path.isdir(whole_filepath):
            mag_files += get_mag_filelist(whole_filepath)

    mag_files.sort()

    return mag_files

def process(filename):
    '''
    The function derives dtw alignment path given source mag and target mag
    :param filename: path to src mag file
    :return: .dtw files
    '''
    file_id = os.path.basename(filename).split(".")[0]
    print(file_id)

    ### DTW alignment -- align source with target parameters ###
    src_mag_file = os.path.join(src_feat_dir, file_id + ".mag")
    tgt_mag_file = os.path.join(tgt_feat_dir, file_id + ".mag")

    src_features, src_frame_number = io_funcs.load_binary_file_frame(src_mag_file, mag_dim)
    tgt_features, tgt_frame_number = io_funcs.load_binary_file_frame(tgt_mag_file, mag_dim)

    ### dtw align src with tgt ###
    dtw_alignment_file = os.path.join(alignments_dir, file_id+ ".dtw")

    x2x_cmd1 = "%s +fa %s | xargs -n%d > %s" %(os.path.join(sptk, "x2x"), src_mag_file, mag_dim, os.path.join(temp_dir, file_id+ "_src_ascii.mag"))
    x2x_cmd2 = "%s +fa %s | xargs -n%d > %s" %(os.path.join(sptk, "x2x"), tgt_mag_file, mag_dim, os.path.join(temp_dir, file_id+ "_tgt_ascii.mag"))

    os.system(x2x_cmd1)
    os.system(x2x_cmd2)

    chtrack_cmd1 = "%s -s 0.005 -otype est_binary %s -o %s" %(os.path.join(speech_tools, "ch_track"), \
                                                                os.path.join(temp_dir, file_id+ "_src_ascii.mag"), \
                                                                os.path.join(temp_dir, file_id+ "_src_binary.mag"))

    os.system(chtrack_cmd1)

    chtrack_cmd2 = "%s -s 0.005 -otype est_binary %s -o %s" %(os.path.join(speech_tools, "ch_track"), \
                                                                os.path.join(temp_dir, file_id+ "_tgt_ascii.mag"), \
                                                                os.path.join(temp_dir, file_id+ "_tgt_binary.mag"))
    os.system(chtrack_cmd2)

    phone_align_cmd = "%s -itrack %s -otrack %s -ilabel %s -olabel %s -verbose -withcosts > %s" %(os.path.join(festvox, "src/general/phonealign"), \
                                                            os.path.join(temp_dir, file_id+ "_tgt_binary.mag"), os.path.join(temp_dir, file_id+ "_src_binary.mag"), \
                                                            os.path.join(temp_dir, "i.lab"), os.path.join(temp_dir, "o.lab"), dtw_alignment_file)
    os.system(phone_align_cmd)

    ### load dtw path
    dtw_path_dict = io_funcs.load_ascii_dtw_file(dtw_alignment_file)
    assert len(dtw_path_dict)==tgt_frame_number   # dtw length not matched

    ### align features
    aligner.align_src_feats(os.path.join(src_feat_dir, file_id + ".mag") , os.path.join(src_aligned_feat_dir, file_id + ".mag"), mag_dim , dtw_path_dict)
    aligner.align_src_feats(os.path.join(src_feat_dir, file_id + ".real"), os.path.join(src_aligned_feat_dir, file_id + ".real"), real_dim, dtw_path_dict)
    aligner.align_src_feats(os.path.join(src_feat_dir, file_id + ".imag"), os.path.join(src_aligned_feat_dir, file_id + ".imag"), imag_dim, dtw_path_dict)
    aligner.align_src_feats(os.path.join(src_feat_dir, file_id + ".lf0") , os.path.join(src_aligned_feat_dir, file_id + ".lf0"), lf0_dim , dtw_path_dict)

print("--- DTW alignment started ---")
start_time = time.time()

# get mag files list
mag_files = get_mag_filelist(src_feat_dir)

# do multi-processing
pool = mp.Pool(mp.cpu_count())
pool.map(process, mag_files)

# clean temporal files
shutil.rmtree(alignments_dir, ignore_errors=True)
shutil.rmtree(temp_dir, ignore_errors=True)

(m, s) = divmod(int(time.time() - start_time), 60)
print(("--- DTW alignment completion time: %d min. %d sec ---" % (m, s)))

if not os.path.exists(src_aligned_feat_dir):
    print("DTW alignment unsucessful!!")
else:
    print("You should have your src feats(aligned with target) ready in: %s" % (src_aligned_feat_dir))


#Author: Flavio C. Coelho

from math import *
from RandomArray import *
from matplotlib.pylab import *

n=10000
rho=.99 #correlation
#Means
m1 = 10
m2 = 20
#Standard deviations
s1 = 1
s2 = 1
#Initialize vectors
x=zeros(n, Float)
y=zeros(n, Float)
sd=sqrt(1-rho**2)
# the core of the method: sample recursively from two normal distributions
# Tthe mean for the current sample, is updated at each step.
for i in range(1,n):
  x[i] = normal(m1+rho*(y[i-1]-m2)/s2,s1*sd)
  y[i] = normal(m2+rho*(x[i-1]-m1)/s1,s2*sd)

scatter(x,y,marker='d',c='r')
title('Amostrador de Gibbs')
xlabel('x')
ylabel('y')
grid()

show()


"""
Model exported as python.
Name : model4a
Group :
With QGIS : 32208
"""

from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterFeatureSink
import processing

class Model4a(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        self.addParameter(QgsProcessingParameterFeatureSink('Fixgeo_wlds', 'fixgeo_wlds', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Fixgeo_countries', 'fixgeo_countries', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, supportsAppend=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Intersection', 'intersection', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(4, model_feedback)
        results = {}
        outputs = {}

        ############################
        # Statistics by categories # --> esto amely lo tenía despues de fix geometries (ver)
        ############################

        # Indicamos que cuente la cantidad de idiomas por ADMIN de cada país. --> chequear
        # Vemos cuantas veces estaba en la base de language cada uno de los países
        # Guardamos como csv

        alg_params = {
            'CATEGORIES_FIELD_NAME': ['ADMIN'],
            'INPUT': 'Intersection_19ca7787_0eee_430a_8657_3e9a2370edaf',
            'OUTPUT': '/Users/fernandacortes/Desktop/Herramientas/Clase4/output/languages_by_country.csv',
            'VALUES_FIELD_NAME': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['StatisticsByCategories'] = processing.run('qgis:statisticsbycategories', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        ##############################
        # Fix geometries - countries #
        ##############################

        alg_params = {
            'INPUT': '/Users/fernandacortes/Desktop/Herramientas/Clase4/Input/ne_10m_admin_0_countries/ne_10m_admin_0_countries.shp',
            'OUTPUT': parameters['Fixgeo_countries']
        }
        outputs['FixGeometriesCountries'] = processing.run('native:fixgeometries', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Fixgeo_countries'] = outputs['FixGeometriesCountries']['OUTPUT']

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        #########################
        # Fix geometries - wlds #
        #########################

        alg_params = {
            'INPUT': '/Users/fernandacortes/Desktop/Herramientas/Clase4/output/clean.shp',
            'OUTPUT': parameters['Fixgeo_wlds']
        }
        outputs['FixGeometriesWlds'] = processing.run('native:fixgeometries', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Fixgeo_wlds'] = outputs['FixGeometriesWlds']['OUTPUT']

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        ################
        # Intersection #
        ################

        # Intersecamos "Fix geometries - wlds" y "Fix geometries - countries"
        # Nos quedamos con "GID" y "ADMIN"

        alg_params = {
            'INPUT': outputs['FixGeometriesWlds']['OUTPUT'],
            'INPUT_FIELDS': ['GID'],
            'OVERLAY': outputs['FixGeometriesCountries']['OUTPUT'],
            'OVERLAY_FIELDS': ['ADMIN'],
            'OVERLAY_FIELDS_PREFIX': '',
            'OUTPUT': parameters['Intersection']
        }
        outputs['Intersection'] = processing.run('native:intersection', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Intersection'] = outputs['Intersection']['OUTPUT']
        return results

    def name(self):
        return 'model4a '

    def displayName(self):
        return 'model4a '

    def group(self):
        return ''

    def groupId(self):
        return ''

    def createInstance(self):
        return Model4a()


"""
文件说明
简单循环神经网路前向传播过程
"""
import numpy as np

# 定义相关参数，ini_state是输入到t1的t0时刻输出的状态
# 输入数据
x = [0.8, 0.1]
# t0时刻的h值
init_state = [0.3,  0.6]
# 相邻时刻隐藏单元间的权重矩阵
w = np.asarray([[0.2, 0.4], [0.7, 0.3]])
# 输入的权重
u = np.asarray([0.8, 0.1])
# 偏置
b_h = np.asarray([0.2, 0.1])
# 输出权重矩阵
v = np.asarray([[0.5], [0.5]])
# 输出偏置
b_o = 0.1

# 执行两轮循环，模拟前向传播过程
'''
ht = tanh(b_h + w * h_t-1 + u * x_t)
'''
for i in range(len(x)):
    # 每次输入一个时间点的数据，获取总长度，得到需要计算的次数
    # numpy的dot函数用于矩阵相乘，函数原型为dot(a, b, out)
    before_activation = np.dot(init_state, w) + x[i] * u + b_h

    # numpy也提供了tanh函数，用于实现双曲正切函数的计算
    state = np.tanh(before_activation)

    # 本时刻的状态作为下一时刻的初始状态
    init_state = state

    # 计算本时刻的输出
    final_output = np.dot(state, v) + b_o

    # 打印t1和t2时刻的状态和输出信息
    print('t%s state: %s' % (i + 1, state))
    print('t%s output: %s' % (i + 1, final_output))


from app import app
from model.auth_model import auth_model
from model.users_roles_model import users_roles
from flask import make_response, request
import traceback

import json

obj = users_roles()
auth = auth_model()

@app.route("/users_roles", methods=["GET"])
# @auth.token_auth()
def get_all_users_roles():
    try:
        return obj.get_all_users_roles()
    except Exception as e:
        traceback.print_exc()
        return make_response(f"error in getAll users roles controller: {e}", 204)

@app.route("/users_roles/<int:user_id>", methods=["GET"])
# @auth.token_auth()
def get_user_roles(user_id):
    try:
        return obj.get_user_roles(user_id)
    except Exception as e:
        traceback.print_exc()
        return make_response(f"error in get user roles controller: {e}", 204)

@app.route("/user_roles", methods=["POST"])
# @auth.token_auth()
def add_new_user_roles():
    try:
        return obj.add_new_user_roles(request.data)
    except Exception as e:
        traceback.print_exc()
        return make_response(f"Error in add new user roles controller : {e}", 204)

@app.route("/user_role", methods=["POST"])
# @auth.token_auth()
def add_new_user_role():
    try:
        return obj.add_new_user_role(request.data)
    except Exception as e:
        traceback.print_exc()
        return make_response(f"Error in add new user role controller : {e}", 204)

@app.route("/users_roles/<int:user_id>", methods=["DELETE"])
# @auth.token_auth()
def delete_user_roles(user_id):
    try:
        return obj.delete_user_roles(user_id)
    except Exception as e:
        return make_response(f"Error in deleting users_roles controller : {e}", 204)

@app.route("/users_roles/<int:user_id>", methods=["PUT"])
# @auth.token_auth()
def update_role_user_relationship(user_id):
    try:
        data = request.get_json()  # Get the data from the request body
        data_str = json.dumps(data)  # Convert the data to a JSON string
        return obj.update_role_user_relationship(user_id, data_str)  # Pass the JSON string to the method
    except Exception as e:
        return make_response(f"Error in updating user roles: {e}", 500)


import inspect
from functools import reduce

from docutils import nodes
from docutils.parsers import rst
from docutils.statemachine import ViewList
from sphinx.util import logging
from sphinx.util.docstrings import prepare_docstring
from sphinx.util.nodes import nested_parse_with_titles

import wsme.types

LOG = logging.getLogger(__name__)

def import_object(import_name):
    """Import the named object and return it.

    The name should be formatted as package.module:obj.
    """
    module_name, expr = import_name.split(':', 1)
    mod = __import__(module_name)
    mod = reduce(getattr, module_name.split('.')[1:], mod)
    globals = __builtins__
    if not isinstance(globals, dict):
        globals = globals.__dict__
    return eval(expr, globals, mod.__dict__)

def http_directive(method, path, content):
    """Build an HTTP directive for documenting a single URL.

    :param method: HTTP method ('get', 'post', etc.)
    :param path: URL
    :param content: Text describing the endpoint.
    """
    method = method.lower().strip()
    if isinstance(content, str):
        content = content.splitlines()
    yield ''
    yield '.. http:{method}:: {path}'.format(**locals())
    yield ''
    for line in content:
        yield '   ' + line
    yield ''

def datatypename(datatype):
    """Return the formatted name of the data type.

    Derived from wsmeext.sphinxext.datatypename.
    """
    if isinstance(datatype, wsme.types.DictType):
        return 'dict(%s: %s)' % (datatypename(datatype.key_type),
                                 datatypename(datatype.value_type))
    if isinstance(datatype, wsme.types.ArrayType):
        return 'list(%s)' % datatypename(datatype.item_type)
    if isinstance(datatype, wsme.types.UserType):
        return ':class:`%s`' % datatype.name
    if isinstance(datatype, wsme.types.Base) or hasattr(datatype, '__name__'):
        return ':class:`%s`' % datatype.__name__
    return datatype.__name__

class RESTControllerDirective(rst.Directive):

    required_arguments = 1
    option_spec = {
        'webprefix': rst.directives.unchanged,
    }
    has_content = True

    def make_rst_for_method(self, path, method, http_method):
        docstring = prepare_docstring((method.__doc__ or '').rstrip('\n'))
        blank_line = docstring[-1]
        docstring = docstring[:-1]  # remove blank line appended automatically

        if hasattr(method, '_wsme_definition'):
            funcdef = method._wsme_definition

            # Add the parameter type information. Assumes that the
            # developer has provided descriptions of the parameters.
            for arg in funcdef.arguments:
                docstring.append(
                    ':type %s: %s' % (arg.name, datatypename(arg.datatype)))

            # Add a blank line before return type to avoid the formatting
            # issues that are caused because of missing blank lines between
            # blocks
            docstring.append(blank_line)

            # Add the return type
            if funcdef.return_type:
                return_type = datatypename(funcdef.return_type)
                docstring.append(':return type: %s' % return_type)

            # restore the blank line added as a spacer
            docstring.append(blank_line)

        directive = http_directive(http_method, path, docstring)
        return directive

    def make_rst_for_controller(self, path_prefix, controller):
        controller_path = path_prefix.rstrip('/')

        # Some of the controllers are instantiated dynamically, so
        # we need to look at their constructor arguments to see
        # what parameters are needed and include them in the
        # URL. For now, we only ever want one at a time.
        try:
            argspec = inspect.getfullargspec(controller.__init__)
        except TypeError:
            # The default __init__ for object is a "slot wrapper" not
            # a method, so we can't inspect it. It doesn't take any
            # arguments, though, so just knowing that we didn't
            # override __init__ helps us build the controller path
            # correctly.
            pass
        else:
            if len(argspec[0]) > 1:
                first_arg_name = argspec[0][1]
                controller_path += '/(' + first_arg_name + ')'

        lines = []

        for method_name, http_method_name in [
            ('get_all', 'get'),
            ('get', 'get'),
        ]:
            LOG.debug('Checking %s for %s method', controller, method_name)
            method = getattr(controller, method_name, None)
            if method and method.exposed:
                LOG.debug('Found method: %s', method_name)
                lines.extend(
                    self.make_rst_for_method(
                        controller_path,
                        method,
                        http_method_name,
                    ))

        # Handle the special case for get_one(). The path should
        # include the name of the argument used to find the object.
        if hasattr(controller, 'get_one') and controller.get_one.exposed:
            LOG.debug('Found method: get_one')
            funcdef = controller.get_one._wsme_definition
            first_arg_name = funcdef.arguments[0].name
            path = controller_path + '/(' + first_arg_name + ')'
            lines.extend(
                self.make_rst_for_method(
                    path,
                    controller.get_one,
                    'get',
                ))

        for method_name, http_method_name in [
            ('post', 'post'),
            ('put', 'put'),
            ('delete', 'delete'),
            ('patch', 'patch'),
        ]:
            LOG.debug('Checking %s for %s method', controller, method_name)
            method = getattr(controller, method_name, None)
            if method and method.exposed:
                LOG.debug('Found method: %s', method_name)
                lines.extend(
                    self.make_rst_for_method(
                        controller_path,
                        method,
                        http_method_name,
                    ))

        # Look for exposed custom methods
        for name in sorted(controller._custom_actions.keys()):
            LOG.debug('Adding custom method: %s', name)
            path = controller_path + '/' + name
            actions = controller._custom_actions[name]
            for action in actions:
                # Check for a method prefixed with the HTTP verb
                # otherwise use the method with only the action name
                method_name = "%s_%s" % (action.lower(), name)
                if hasattr(controller, method_name):
                    method = getattr(controller, method_name)
                else:
                    method = getattr(controller, name)
                LOG.debug('Custom method %s uses action %s', method, action)
                lines.extend(
                    self.make_rst_for_method(
                        path,
                        method,
                        action.lower(),
                    ))

        return lines

    def run(self):
        controller_id = self.arguments[0]
        LOG.debug('found root-controller %s', controller_id)

        result = ViewList()
        controller = import_object(self.arguments[0])

        for line in self.make_rst_for_controller(
                self.options.get('webprefix', '/'), controller):
            result.append(line, '<' + __name__ + '>')

        node = nodes.section()
        # necessary so that the child nodes get the right source/line set
        node.document = self.state.document
        nested_parse_with_titles(self.state, result, node)

        return node.children

def setup(app):
    app.add_directive('rest-controller', RESTControllerDirective)


"""
这是解码idx文件的文件
"""
import numpy as np
import struct

class Decode:
    @classmethod
    def idx3_ubyte(cls, idx3_ubyte_file):
        print('正在解码idx3图片文件:', idx3_ubyte_file)
        bin_data = open(idx3_ubyte_file, 'rb').read()

        offset = 0
        fmt_header = '>iiii'
        magic_number, num_images, num_rows, num_cols = struct.unpack_from(fmt_header, bin_data, offset)
        print('魔数:%d, 图片数量: %d张, 图片大小: %d*%d' % (magic_number, num_images, num_rows, num_cols))

        image_size = num_rows * num_cols
        offset += struct.calcsize(fmt_header)
        fmt_image = '>' + str(image_size) + 'B'
        images = np.empty((num_images, num_rows, num_cols))
        for i in range(num_images):
            images[i] = np.array(struct.unpack_from(fmt_image, bin_data, offset)).reshape((num_rows, num_cols))
            offset += struct.calcsize(fmt_image)

        print('解码完成')
        return images

    @classmethod
    def idx1_ubyte(cls, idx1_ubyte_file):
        print('正在解码idx1标签文件:', idx1_ubyte_file)
        bin_data = open(idx1_ubyte_file, 'rb').read()

        offset = 0
        fmt_header = '>ii'
        magic_number, num_images = struct.unpack_from(fmt_header, bin_data, offset)
        print('魔数:%d, 标签数量: %d张' % (magic_number, num_images))

        offset += struct.calcsize(fmt_header)
        fmt_image = '>B'
        labels = np.empty(num_images)
        for i in range(num_images):
            labels[i] = struct.unpack_from(fmt_image, bin_data, offset)[0]
            offset += struct.calcsize(fmt_image)

        print('解码完成')
        return labels