import time

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By

# 创建Chrome WebDriver对象
driver = webdriver.Chrome()

url = 'https://activity.ourteacher.com.cn/'
user_name = '15879675827'
pass_word = 'Dt19971201'

# 打开Google网站

def parser_course(html_text):
    soup = BeautifulSoup(html_text, 'html.parser')
    li_list = soup.find_all('li')
    data_list = []
    for li in li_list:
        span_list = li.find_all('span')
        data = (span_list[0].text.strip(), span_list[1].get('class')[0])
        data_list.append(data)
    return data_list

def start_study(flag_text):
    print(flag_text)
    driver.implicitly_wait(1)
    driver.find_element(By.LINK_TEXT, flag_text).click()
    driver.implicitly_wait(1)
    title = driver.find_element(By.XPATH, "/html/body/div[2]/div/div/div[4]/div[2]/div/div[1]/span").text
    if '【选课】' in title:
        num = driver.find_element(By.XPATH,'/html/body/div[2]/div/div/div[4]/div[2]/div/div[3]/div/div/span').text
        course_list = driver.find_element(By.ID, 'courseList')
        # 只选择第一个课程
        choseClass = course_list.find_elements(By.NAME, 'choseClass')
        for i in range(int(num)):
            choseClass[i].click()
            time.sleep(1)
        # 点击确认
        driver.find_element(By.ID, 'btnSelectCourse').click()
        driver.implicitly_wait(2)
        driver.find_element(By.ID, 'sure').click()
        driver.refresh()
        time.sleep(3)
    else:
        driver.find_element(By.LINK_TEXT, "立即学习").click()
        print(f'{flag_text}开始学习，开始时间：{time.strftime("%y-%m-%d %H:%M:%S")}')
        driver.switch_to.window(driver.window_handles[-1])
        time.sleep(5)
        learn_time = driver.find_element(By.ID, 'learnTime').text.split('/')[1][:-1]
        # print(learn_time)
        run_text = ''
        while True:
            try:
                var = driver.find_element(By.ID, 'learnTime').text
                if run_text != var:
                    run_text = var
                else:
                    driver.refresh()
                    driver.implicitly_wait(3)
            except Exception:
                driver.refresh()
                driver.implicitly_wait(3)
            # if time.time() - start_time > int(learn_time) * 60 + 60:
            #     print('超时')
            #     driver.refresh()
            try:
                if '可以进入下一环节学习' in driver.find_element(By.ID, 'lock').text:
                    driver.close()
                    driver.switch_to.window(driver.window_handles[-1])
                    driver.refresh()
                    driver.implicitly_wait(2)
                    break
            except:
                pass
            try:
                # 随堂小测试
                div = driver.find_element(By.ID, 'ValidationPage')
                if '测试' in div.find_element(By.CLASS_NAME, 'modal-title').text:
                    div.find_element(By.ID, 'strA').click()
                    time.sleep(1)
                    div.find_element(By.ID, 'submit').click()
            except Exception as e:
                pass
            time.sleep(20)

driver.get(url)
driver.find_element(By.ID, 'aw-login-user-name').send_keys(user_name)
driver.find_element(By.ID, 'aw-login-user-password').send_keys(pass_word)
driver.find_element(By.ID, 'login_submit').click()

# print(driver.title)
# 等待搜索结果加载完成
driver.implicitly_wait(10)
if driver.title == '奥鹏教师教育网':
    driver.find_element(By.LINK_TEXT, '去学习').click()
    driver.switch_to.window(driver.window_handles[-1])
    driver.implicitly_wait(10)
    while True:
        html = driver.find_element(By.XPATH, '//*[@id="LeftNav"]/div/div[2]/ul').get_attribute('outerHTML')
        d = parser_course(html)
        flag = False
        # print(d)
        for course in d:
            if course[1] == 'a-bg-tip-orange':
                start_study(course[0])

input('exit')
# 关闭浏览器
driver.quit()


import logging
import re

from openlp.core.common import translate
from openlp.plugins.songs.lib.importers.songimport import SongImport

log = logging.getLogger(__name__)

class LyrixImport(SongImport):
    """
    Import songs exported from Lyrix
    """

    def __init__(self, manager, **kwargs):
        """
        Initialise the class.
        """
        super(LyrixImport, self).__init__(manager, **kwargs)

    def do_import(self):
        """
        Receive a single file or a list of files to import.
        """
        if not isinstance(self.import_source, list):
            return
        self.import_wizard.progress_bar.setMaximum(len(self.import_source))
        for filename in self.import_source:
            if self.stop_import_flag:
                return
            song_file = open(filename, 'rt', encoding='cp1251')
            self.do_import_file(song_file)
            song_file.close()

    def do_import_file(self, file):
        """
        Process the Lyrix file - pass in a file-like object, not a file path.
        """
        self.set_defaults()
        # Setup variables
        line_number = 0
        song_title = 'Standard Song Title'
        ccli = '0'
        current_verse = ''
        verses = []
        author = ''
        copyright = ''
        try:
            # Read the file
            for line in file:
                line = line.strip()
                line_number += 1
                if line_number == 4:
                    song_title = line
                if line_number < 7:
                    continue
                # Detect and get CCLI number
                if line.lower().startswith('ccli'):
                    ccli = re.findall('\d+', line)[0]
                    try:
                        # If the CCLI was found, we are near the end
                        # Find author
                        line = next(file).strip()
                        author = line[line.find(':') + 2:]
                        # Find copyright
                        copyright = next(file).strip()
                    except StopIteration:
                        pass
                    break
                if line == '':
                    if current_verse != '':
                        verses.append(current_verse)
                    current_verse = ''
                else:
                    if current_verse == '':
                        current_verse += line
                    else:
                        current_verse += '\n' + line
        except Exception as e:
            self.log_error(translate('SongsPlugin.LyrixImport', 'File {name}').format(name=file.name),
                           translate('SongsPlugin.LyrixImport', 'Error: {error}').format(error=e))
            return
        self.title = song_title
        self.parse_author(author)
        self.ccli_number = ccli
        self.add_copyright(copyright)
        for verse in verses:
            self.add_verse(verse, 'v')
        if not self.finish():
            self.log_error(file.name)


"""distoptim.hit package"""
import logging
import torch

LOG = logging.getLogger(__name__)

class _HiT_DDP(torch.nn.parallel.DistributedDataParallel):
    """ Wrap input model with torch DistributedDataParallel
        And redirect attributes
    """
    def __init__(
            self,
            module,
            device_ids=None,
            output_device=None,
            dim=0,
            broadcast_buffers=True,
            process_group=None,
            bucket_cap_mb=25,
            find_unused_parameters=False,
            check_reduction=False,
    ):

        LOG.info("Init _HiT_DDP")

        super(_HiT_DDP, self).__init__(
            module,
            device_ids=device_ids,
            output_device=output_device,
            dim=dim,
            broadcast_buffers=broadcast_buffers,
            process_group=process_group,
            bucket_cap_mb=bucket_cap_mb,
            find_unused_parameters=find_unused_parameters,
            check_reduction=check_reduction,
        )

    def __getattr__(self, attr):
        # circular calls from __init__
        if attr == "module":
            return super(_HiT_DDP, self).__getattr__(attr)

        # redirect
        return getattr(self.module, attr)

    def load_state_dict(self, state_dict, strict=True):
        load_state_dict_on_module = True
        for key in state_dict.keys():
            if 'module.' in key:
                load_state_dict_on_module = False
                break
        if load_state_dict_on_module:
            self.module.load_state_dict(state_dict, strict=strict)
        else:
            super(_HiT_DDP, self).load_state_dict(state_dict, strict=strict)

def wrap_model_with_ddp(
        module,
        device_ids=None,
        output_device=None,
        dim=0,
        broadcast_buffers=True,
        process_group=None,
        bucket_cap_mb=25,
        find_unused_parameters=False,
        check_reduction=False,
):
    """ Wrap input model with torch DistributedDataParallel
    """

    return _HiT_DDP(
        module,
        device_ids=device_ids,
        output_device=output_device,
        dim=dim,
        broadcast_buffers=broadcast_buffers,
        process_group=process_group,
        bucket_cap_mb=bucket_cap_mb,
        find_unused_parameters=find_unused_parameters,
        check_reduction=check_reduction,
    )


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def addTwoNumbers(self, l1, l2):
        dummy_head = ListNode(0)
        current = dummy_head
        carry = 0

        while l1 or l2 or carry:
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0

            sum = val1 + val2 + carry
            carry = sum // 10
            digit = sum % 10

            current.next = ListNode(digit)
            current = current.next

            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None

        return dummy_head.next

# Create linked lists
# l1 = [2, 4, 3]
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)

# l2 = [5, 6, 4]
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)

# Create an instance of the Solution class
solution = Solution()

# Add the two numbers
result = solution.addTwoNumbers(l1, l2)

# Create a list to store the result digits
result_digits = []

# Traverse the result linked list and collect the digits
while result:
    result_digits.append(str(result.val))
    result = result.next

# Reverse the list of digits and join them into a single string
result_str = " ".join(result_digits[::-1])

# Print the result
print(result_str)


import numpy as np
from math import log2
import operator

class utility(object):

    def calc_entropy(self, data_set):
        '''
        :param data_set: [x1,x2,x3....label] type list
        :return:
        '''

        data_set = np.array(data_set)
        label_set = data_set[: ,-1]
        total = len(label_set)
        label_cnt = {}
        for label in label_set:
            num = label_cnt.get(label, -1)
            if -1 == num:
                num = 0
            label_cnt[label] = num + 1

        ent = 0
        for key, val in label_cnt.items():
            p = val / total
            info = -(p * log2(p))
            ent = ent + info

        return ent

    def split_data(self, data_set, ax, value):
        ret_cate = []
        for data in data_set:
            if data[ax] == value:
                fh = data[:ax]
                fh.extend(data[ax+1:])
                ret_cate.append(fh)

        return ret_cate

    def calc_best_ft(self, data_set):
        ent = self.calc_entropy(data_set)
        ft_num = len(data_set[0]) - 1
        data_num = len(data_set)
        best_ent = 0
        best_num = -1
        for num in range(ft_num):
            ft_list = [ft[num] for ft in data_set]
            ft_unq = set(ft_list)
            gain_ent = 0
            for ft in ft_unq:
                sub_data = self.split_data(data_set, num, ft)
                sub_ent = self.calc_entropy(sub_data)
                sub_num = len(sub_data)
                gain_ent = gain_ent + (sub_ent * sub_num/data_num)
            gain_ent = ent - gain_ent

            if best_ent < gain_ent:
                best_ent = gain_ent
                best_num = num
        return best_num

    def majorcnt(self, data_set):
        ft_num = {}
        for data in data_set:
            num = ft_num.get(data, -1)
            if -1 == num:
                num = 0
            ft_num[data] = num + 1

        ft_num = sorted(ft_num, key=operator.itemgetter(1), reverse=True)

        return ft_num[0][0]

    def create_tree(self, data_set, ft_label=None):
        '''
        :param data_set:
        :param ft_label: 特征向量标签
        :return:
        '''
        classList = [data[-1] for data in data_set]
        #t同一类
        if classList.count(classList[0]) == len(classList):
            return classList[0]

        #整个数据集只有标签时
        if len(data_set[0]) == 1:
            return self.majorcnt(classList)

        b_ft_ax = self.calc_best_ft(data_set)
        ft_lb = ft_label[b_ft_ax]
        del(ft_label[b_ft_ax])
        b_ft = [ft[b_ft_ax] for ft in data_set]
        b_ft = set(b_ft)
        m_tree = {ft_lb:{}}
        for bt in b_ft:
            c_ft = ft_label.copy()
            sd = self.split_data(data_set, b_ft_ax, bt)
            m_tree[ft_lb][bt] = self.create_tree(sd, c_ft)

        return m_tree

    def classify(self, tree, test=None):
        '''
        :param tree:
        :param test:
        :return:
        算法每次运算只用到一个特征，没有考虑到全部
        比如本例 每下降一层，就会少一个特征，相当于其中一个子节点没有起到分类的作用
        '''
        f_lb = list(tree.keys())[0]
        s_dict = tree[f_lb]

        lb = ''
        for key,value in s_dict.items():
            if key == test[0]:
                if type(value).__name__ != 'dict':
                    lb = value
                else:
                    lb = self.classify(value, test[1:])

        return lb

    def classify_label(self, inTree, ft_label, testVec):
        firstKey = list(inTree.keys())[0]
        featIndex = ft_label.index(firstKey)
        key = testVec[featIndex]
        subTree = inTree[firstKey]
        featLabel = subTree[key]
        if type(featLabel).__name__ == 'dict':
            classLabel = self.classify_label(featLabel, ft_label, testVec)
        else:
            classLabel = featLabel

        return classLabel

    def get_tree_info(self, tree, fa_lay):
        node_info = []
        if type(tree) != dict:
            return
        lay_num = fa_lay + 1
        for key, value in tree.items():
            if type(value) == dict:
                node_info.extend(self.get_tree_info(value, lay_num))
            else:
                node_info.append((value, lay_num))

        return node_info


from sys import stdin, stderr

def beste_path(nm, prob):
    to_prob = [0.0] * n
    to_prob[0] = prob[0]
    processed = [False] * n
    best_prev_node = [a for a in range(n)]
    best_node = 0

    for i in range(n):
        node = best_node
        processed[node] = True
        highest_to_prob = 0.0

        for nabo in range(n):
            if not processed[nabo]:
                if nm[node][nabo]:
                    new_prob = to_prob[node] * prob[nabo]

                    if new_prob > to_prob[nabo]:
                        best_prev_node[nabo] = node
                        to_prob[nabo] = new_prob

                if to_prob[nabo] > highest_to_prob:
                    best_node = nabo
                    highest_to_prob = to_prob[nabo]

    if to_prob[-1] == 0.0:
        return 0

    index = n - 1
    path = [index]

    while index != 0:
        index = best_prev_node[index]
        path.append(index)
    return '-'.join(map(str, reversed(path)))

n = int(stdin.readline())
sannsynligheter = [float(x) for x in stdin.readline().split()]
nabomatrise = []
for linje in stdin:
    naborad = [0] * n
    naboer = [int(nabo) for nabo in linje.split()]
    for nabo in naboer:
        naborad[nabo] = 1
    nabomatrise.append(naborad)
print(beste_path(nabomatrise, sannsynligheter))


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 14:00:30 2019

@author: huyn
"""

#Given a string consisting of lowercase English letters, find the largest square number which
#can be obtained by reordering the string's characters and replacing them with any digits you need
#(leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits.
#
#If there is no solution, return -1.
def constructSquare(s):
    v = len(s)
    ds = {}
    dv = {}
    for l in s:
        if l not in ds:
            ds[l]=0
        ds[l]+=1
    for key in ds:
        val = ds[key]
        if val not in dv:
            dv[val]=[]
        dv[val].append(key)
    if len(ds)>10:
        return -1
    if v ==1:
        return 9
    start = int((10**(v-1))**.5)
    stop  = int((10**v)**.5)

    for i in range(stop,start,-1):
        i = i**2

        # check if there is a valid mapping
        num = str(i)
        ds = {}
        dn= {}
        check = True
        for l in num:
            if l not in ds:
                ds[l]=0
            ds[l]+=1
        for key in ds:
            v = ds[key]
            if v not in dn:
                dn[v]=[]
            dn[v].append(key)
        if len(dn)!=len(dv):
            continue
        for key in dn:
            if key not in dv:
                check = False
                break
            else:
                if len(dv[key])!=len(dn[key]):
                    check = False
                    break
        if check:
            return i

    return -1


from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten

def create_dqn_model(env):

    model = Sequential()
    model.add(Flatten(input_shape=(1,env.nb_observations)))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(16))
    model.add(Activation('relu'))
    model.add(Dense(env.nb_actions))
    model.add(Activation('linear'))

    return model

def dqn_controls(idx):
    action = [1,0,0]
    if idx == 0:
        action[1] = 0.0
    elif idx == 1:
        action[2] = -1
    elif idx == 2:
        action[2] = 1
    return action


import unittest
import json
from pyspark.sql.functions import *
from dependencies.etl_submit_job import ETLSubmitJob

class ETLTests(unittest.TestCase, ETLSubmitJob):

    def setUp(self):
        """Start Spark, define config and path to test data
        """
        # hardcode config file for test
        with open(
                "C:\\Users\\pvasi\\OneDrive\\Desktop\\Big Data\\pyspark-project-template\\configs\\spark_config.json") as conf_file:
            self.config = json.load(conf_file)

        # path to unit test file in hdfs
        self.test_file_path = "/unittests/players.2019.csv"
        self.test_file_expected = '/unittest/fifa_expected.csv'
        # init spark session
        self._get_spark_session()

        # prepare actual data
        input_raw_data = self._extract_data(self.test_file_path)
        self.input_transformed_data = self._transform_data(input_raw_data)

        # prepare expected data
        self.expected_data = self.spark \
                                .read \
                                .csv(self.test_file_expected)

    def tearDown(self):
        """Stop Spark
        """
        self._close_spark_session()

    # test to check for duplicates on player id

    def test_data_integrity(self):

        duplicates_count = self.input_transformed_data.groupby("ID") \
                                .agg(count("ID").alias("count_dupl")) \
                                .filter(col("count_dupl") > 1) \
                                .count()
        self.assertEqual(duplicates_count, 0)

    # test to check if target count matches expected count

    def test_record_count(self):
        record_count = self.input_transformed_data.count()
        self.assertEqual(record_count, 1)

    # test to check if column transformations are correct

    def test_except_df(self):
        df_expected_diff = self.expected_data.exceptAll(self.input_transformed_data).count()
        df_actual_diff = self.input_transformed_data.exceptAll(self.expected_data).count()
        self.assertEqual(df_actual_diff + df_expected_diff, 0)

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


def solution(distance, rocks, n):
    answer = 0

    # 정렬후 마지막 지점 넣기
    rocks.sort()
    rocks.append(distance)

    start, end = 0, distance

    while start <= end:
        # 일단 거리의 최소값을 mid라 놓는다
        mid = (start + end) // 2

        # 현재 위치, 삭제개수
        cur = 0
        del_cnt = 0
        # 거리 측정
        for i in rocks:
            # 바위 사이의 거리가 mid보다 작으면 안되므로 제거 개수 증가
            if i - cur < mid:
                del_cnt += 1
            # 아니면 현재 위치를 최신화
            else:
                cur = i

        # 만약 제거된 돌이 많으면 mid를 줄여본다
        if del_cnt > n:
            end = mid - 1
        # 돌이 적거나 같으면 최대값을 향해 찾는다
        else:
            answer = mid
            start = mid + 1

    return answer

# 답: 4
print(solution(25, [2, 14, 11, 21, 17], 2))


from tkinter import *
from tkinter import ttk
from turtle import width
from tkinter import messagebox

#global declare

# ************************************************student dashboard**************************************************************
def win1():
    win = Tk()
    win.geometry("900x700")
    # function call************************

    def add():
        firstn =e1.get()
        s = e1.get()
        print("hello")
        print(s)
        print(firstn)
#***********************************************

    # main-frame
    frm = Frame(win, bg="#DC143C")
    frm.place(x=0, y=0, width=900, height=100)

    # main frame title
    l = Label(frm, text="School Management System",
              font=("", 20, "bold"), bg="#DC143C", bd=2)
    l.pack()

    # frame 2
    frm2 = Frame(win, bg="#B0C4DE", relief=FLAT)
    frm2.place(x=0, y=100, width=700, height=400)

    # frame 3
    frm3 = Frame(frm2, bg="BLACK")
    frm3.place(x=0, y=0, width=700, height=50)
    l1 = Label(frm3, text="Manage Student", font=(
        "", 20, "bold"), bg="black", fg="white", bd=2)
    l1.pack()

    # # tables
    # # table 1
    fname = Label(frm2, text="First Name:", font=(
        "times new roman", 22, "bold"), bg="black", fg="white")
    fname.place(x=0, y=60)
    e1 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e1.place(x=0, y=100)

    #   # table 2
    lname = Label(frm2, text="last Name:", font=(
        "times new roman", 20, "bold"), bg="black", fg="white")
    lname.place(x=200, y=60)
    e2 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e2.place(x=200, y=100)

    #   # table 3
    css = Label(frm2, text="class:", font=(
        "times new roman", 20, "bold"), bg="black", fg="white")
    css.place(x=400, y=60)
    i = ['first year', 'second', 'third', 'four']
    css_combo = ttk.Combobox(frm2, values=i)
    css_combo.place(x=400, y=100, width=140, height=30)
    css_combo.config(state="readonly")
    css_combo.set("select")

    # # table 4
    iname = Label(frm2, text="ID NO:", font=(
        "times new roman", 22, "bold"), bg="black", fg="white")
    iname.place(x=0, y=150)
    e3 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e3.place(x=0, y=200)
    #   # table 5
    emal = Label(frm2, text="Email :", font=(
        "times new roman", 20, "bold"), bg="black", fg="white")
    emal.place(x=200, y=150)
    e4 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e4.place(x=200, y=200)
    #  # table 6
    con = Label(frm2, text="Contact No.:", font=(
        "times new roman", 20, "bold"), bg="black", fg="white")
    con.place(x=400, y=150)
    e5 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e5.place(x=400, y=200)

    # #    # table 7
    dob = Label(frm2, text="D_O_B", font=(
        "times new roman", 20, "bold"), bg="black", fg="white")
    dob.place(x=0, y=250)
    e1 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e1.place(x=0, y=300)
    # #  # table 6
    addr = Label(frm2, text="Address:", font=(
        "times new roman", 22, "bold"), bg="black", fg="white")
    addr.place(x=200, y=250)
    e6 = Entry(frm2, font=(
        "times new roman", 12, "bold"), relief=RIDGE)
    e6.place(x=200, y=300, width=170, height=50)
    # #   # table 7
    g1 = Label(frm2, text="Gender", font=(
        "times new roman", 22, "bold"), bg="black", fg="white")
    g1.place(x=400, y=250)
    i = ['male', 'female']
    g1_combo = ttk.Combobox(frm2, values=i)
    g1_combo.place(x=400, y=300, width=140, height=30)
    g1_combo.config(state="readonly")
    g1_combo.set("MALE")

    # fuction

    # #BUTTON
    B1 = Button(self.frm2, text="Add", width=6, font=(
        "times new roman", 15, "bold"), bg="black", fg="#7FFFD4", command=add)
    B1.place(x=600, y=100)

# ************************************************ main window function cALLL*******************************************************************

def main():
    win = Tk()
    win.geometry("700x500")
    win.resizable(width=False, height=False)
    win.config(bg="#ff9d4d")

    def mainf():
        user = e1.get()
        passw = e2.get()
        if user == "" and passw == "":
            messagebox.showerror("error", "Enter user id and password")

        elif user == "sintu" and passw == "704246":
            win1()

        else:
            messagebox.showerror(
                "WRONG PASSWORD", "Enter VALID user id and password ")

    #global declare

    # frmae declare

    frm = Frame(win)

    frm.configure(bg="#a6a6a6")
    frm.place(x=100, y=50, width=500, height=400)
# label
    Label(frm, text=("Login"), width=14, font=(
        "", 22, "bold"), bg="#ffcccc").pack()
# login code label
    user = Label(frm, text="User ID", width=10, font=("Bold", 22, "bold"))
    user.place(x=10, y=100)
# Entery user
    e1 = Entry(frm, bd=4)
    e1.place(x=300, y=100, width=120, height=40)

# login password label
    user = Label(frm, text="Password", width=10, font=("black", 22, "bold"))
    user.place(x=10, y=200)
    # password enetry
    e2 = Entry(frm,show='*', bd=4)
    e2.place(x=300, y=200, width=120, height=40)

# login into window BUTTON1
    login = Button(frm, text=("Login"), width=14, font=(
        "", 22, "bold"), bg="#a6a6a6", command=mainf)
    login.place(x=60, y=300, width=120, height=30)

# forget lab BUTTON2
    login = Button(frm, text=("NEW USER"), width=28,
                   font=("", 18, "bold"), bg="#a6a6a6")
    login.place(x=200, y=300, width=160, height=30)
    win.mainloop()

main()


# 572. Subtree of Another Tree
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubtree(self, s: 'TreeNode', t: 'TreeNode') -> 'bool':
        if not s: return False
        if s.val != t.val: return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
        return self.checkSubtree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)

    def checkSubtree(self, s, t):
        if not s and not t: return True
        if not s or not t: return False
        if s.val != t.val: return False
        return self.checkSubtree(s.left, t.left) and self.checkSubtree(s.right, t.right)

leetcode/0-250/248-572. Subtree of Another Tree.py


from farm.extensions import celery
from celery.utils.log import get_task_logger

import etcd
import json
from os.path import basename

logger = get_task_logger(__name__)
client = None

def get_client():
    global client
    if not client:
        client = etcd.Client(host=(('10.1.11.234', 4001), ('10.1.60.1', 4001), ('10.1.60.2', 4001)),
                             allow_reconnect=True)
    return client

@celery.task()
def get_testbed(name):
    info = {
        'user': None,
        'properties': {}
    }

    try:
        for tb_info in get_client().read("/testbench/testbeds/%s" % name).children:
            key = basename(tb_info.key)
            if key == "user":
                info['user'] = json.loads(tb_info.value)
            elif key == "properties":
                for tb_prop in get_client().read(tb_info.key).children:
                    prop = basename(tb_prop.key)
                    info['properties'][prop] = tb_prop.value
            elif key == "instance":
                info['instance'] = {}
                for tb_runtime in get_client().read(tb_info.key).children:
                    prop = basename(tb_runtime.key)
                    info['instance'][prop] = tb_runtime.value
            else:
                print("'%s' not handled" % key)
    except etcd.EtcdKeyNotFound:
        logger.info("Error while getting testbed info")
    # print(info)
    return info

@celery.task()
def list_testbeds():
    testbeds = {}

    try:
        r = get_client().read('/testbench/testbeds', sorted=True)
        for tb_child in r.children:
            name = basename(tb_child.key)
            print("Testbed: %s" % name)
            testbeds[name] = get_testbed(name)
    except etcd.EtcdKeyNotFound:
        logger.info("Error while listing testbeds")

    return testbeds

@celery.task()
def does_testbed_exist(testbed_name):
    testbeds = list_testbeds()
    for testbed in testbeds:
        if testbed == testbed_name:
            return True
    return False

@celery.task()
def set_testbed_info(testbed_name, info, key, value):
    get_client().write("/testbench/testbeds/%s/%s/%s" % (testbed_name, info, key), value)

def check_key_exists(key):
    try:
        get_client().read(key)
    except etcd.EtcdKeyNotFound:
        return False

    return True

class TestBenchNotFound(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

@celery.task()
def launch(name, user, info=[]):
    launched = False
    try:
        tb_key = "/testbench/testbeds/%s" % name
        if not tb_key:
            raise TestBenchNotFound(name)

        r = get_client().write("%s/user" % tb_key, json.dumps(user), prevExist=False)
        print(r)
        launched = True
    except etcd.EtcdAlreadyExist:
        logger.info("Already launched")

    return {
        'launched': launched,
        'info': get_testbed(name)
    }

@celery.task()
def destroy(name):
    destroyed = False
    try:
        tb_key = "/testbench/testbeds/%s" % name
        if not tb_key:
            raise TestBenchNotFound(name)

        r = get_client().delete("%s/user" % tb_key, prevExist=True)
        print(r)
        destroyed = True
    except etcd.EtcdKeyNotFound:
        logger.info("Already destroyed")

    return {
        'destroyed': destroyed,
        'info': get_testbed(name)
    }


# 17086번 아기 상어 2
# https://www.acmicpc.net/problem/17086

"""
기본적인 BFS 문제
이동은 대각선까지 가능하다.
"""

import sys
from collections import deque
input = sys.stdin.readline

N, M = map(int, input().split())
graph = []
for _ in range(N):
    graph.append(list(map(int, input().split())))

# 거리 정보를 업데이트 할 배열 생성
dist = [[int(1e9) for _ in range(M)] for _ in range(N)]

# queue 를 활용하여 bfs 탐색
q = deque()

# 상어의 위치 저장
for y in range(N):
    for x in range(M):
        if graph[y][x]:
            dist[y][x] = 0
            q.append([y, x])

# BFS
delta = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [1, -1], [-1, 1], [-1, -1]]
while q:
    ny, nx = q.popleft()

    for dy, dx in delta:
        ey = ny + dy
        ex = nx + dx
        if 0 <= ey < N and 0 <= ex < M:
            if dist[ny][nx] + 1 < dist[ey][ex]:
                dist[ey][ex] = dist[ny][nx] + 1
                q.append([ey, ex])

result = 0
for y in range(N):
    for x in range(M):
        result = max(result, dist[y][x])

print(result)


import torch
from utils import get_test_cifar
import matplotlib.pyplot as plotlib
from model import get_model_for_attack
# import vgg

plotlib.style.use('seaborn')
plotlib.rcParams['ps.useafm'] = True
fsize = 24
tsize = 28
parameters = {'axes.labelsize': tsize, 'axes.titlesize': tsize,
              'xtick.labelsize': fsize, 'ytick.labelsize': fsize,
              'legend.fontsize': fsize}
plotlib.rcParams.update(parameters)

test_loader = get_test_cifar(1)
model = get_model_for_attack('model2')
'''model = vgg.vgg13_bn()
ensemble = torch.load('vgg13bn_regm2.dat', map_location=torch.device('cpu'))
model.load_state_dict(ensemble)'''
model.eval()
for x, y in test_loader:
    def func(cx):
        logits = model(cx)
        # labels = torch.eye(10).to(y.device)[y]
        return torch.nn.functional.cross_entropy(logits, y)

    def safe_jac(cx):
        jac = torch.autograd.functional.jacobian(func, cx)
        jac = torch.randn_like(jac) * 1e-7 + jac
        return jac

    tg = x.flatten(1).shape[-1] ** 0.5
    b = safe_jac(x)
    krylov = [b / torch.norm(b.flatten(1), dim=-1).reshape(-1, 1, 1, 1)]

    def batch_dot(u, v): return torch.bmm(
        u.flatten(1).unsqueeze(-2), v.flatten(1).unsqueeze(-1)).flatten(0)
    H = torch.zeros(
        [x.shape[0], 5, 4],
        dtype=x.dtype,
        device=x.device
    )
    xs = [i / 20 * 8 / 255 * tg for i in range(20)]
    for i in range(4):
        losses = []
        with torch.no_grad():
            for j in range(20):
                losses.append(func(x + krylov[-1] * 8 / 255 * tg * (j / 20)))
        v = safe_jac(x + krylov[-1] * 8 / 255 * tg) - b
        for j, u in enumerate(krylov):
            H[:, j, i] = batch_dot(v, u)
            v = v - H[:, j, i].reshape(-1, 1, 1, 1) * u
        H[:, i + 1, i] = torch.linalg.norm(v.flatten(1), dim=-1)
        v = v / H[:, i + 1, i].reshape(-1, 1, 1, 1)
        plotlib.plot(xs, losses, label='Krylov %d' % i)
        krylov.append(v)
    plotlib.ylabel("Cross-entropy", labelpad=16)
    plotlib.xlabel("Perturbation $L_2$-norm", labelpad=16)
    plotlib.legend()
    plotlib.savefig("krylov_c.pdf", bbox_inches="tight")
    plotlib.show()
    if (input() == 'q'):
        break


def premik(ukaz, x, y, smer):
    smeri = "NESW"
    premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    ismer = smeri.index(smer)
    if ukaz == "R":
        smer = smeri[(ismer + 1) % 4]
    elif ukaz == "L":
        smer = smeri[(ismer - 1) % 4]
    else:
        dx, dy = premiki[ismer]
        x += dx * ukaz
        y += dy * ukaz
    return x, y, smer

# Obvezna naloga

# 1
def izvedi(ime_datoteke):
    s = []
    datoteka = open(ime_datoteke)
    x,y = 0,0
    smer = "N"
    korak = (x, y, smer)
    s.append(korak)
    for vrstica in datoteka:
        if "DESNO" in vrstica:
            korak = premik("R",x,y,smer)
            s.append(korak)
            x, y, smer = korak
        elif "LEVO" in vrstica:
            korak = premik("L", x,y, smer)
            s.append(korak)
            x, y, smer = korak
        else:
            if "NAPREJ" in vrstica:
                stevilo = int(vrstica.split()[1])
                korak = premik(stevilo, x, y, smer)
                s.append(korak)
                x, y, smer = korak
    return s

def opisi_stanje(x, y, smer):
    smeri = {
    "N":"^",
    "E":">",
    "S":"v",
    "W":"<"
    }
    return "{:>3}:{:<3} {}".format(x,y,smeri[smer])

def prevedi(ime_vhoda, ime_izhoda):
    datoteka = izvedi(ime_vhoda)
    nova_datoteka = open(ime_izhoda, "w", encoding="utf-8")
    for vrstica in datoteka:
        nova_datoteka.write(opisi_stanje(vrstica[0], vrstica[1], vrstica[2])+"\n")
    nova_datoteka.close()

def opisi_stanje_2(x, y, smer):
    smeri = {
    "N":"^",
    "E":">",
    "S":"v",
    "W":"<"
    }
    s = 4 - len(str(x)) - 1
    presledek = " "*s
    return "{:<} {}({}:{})".format(smeri[smer], presledek, x, y)

import unittest
class TestObvezna(unittest.TestCase):
    def test_branje(self):
        self.assertEqual(
            izvedi("primer.txt"),
            [(0, 0, 'N'), (0, 0, 'E'), (12, 0, 'E'), (12, 0, 'S'), (12, 2, 'S'),
             (12, 2, 'E'), (15, 2, 'E'), (15, 2, 'N'), (15, 2, 'W')]
        )
        self.assertEqual(
            izvedi("ukazi.txt"),
            [(0, 0, 'N'), (0, 0, 'E'), (1, 0, 'E'), (1, 0, 'S'), (1, 0, 'W'),
             (0, 0, 'W'), (0, 0, 'S'), (0, 0, 'E'), (1, 0, 'E'), (1, 0, 'S'),
             (1, 3, 'S'), (1, 3, 'E'), (2, 3, 'E'), (2, 3, 'S'), (2, 3, 'W')]
        )

    def test_opisi_stanje(self):
        self.assertEqual(opisi_stanje(0, 12, "N"), "  0:12  ^")
        self.assertEqual(opisi_stanje(111, 0, "E"), "111:0   >")
        self.assertEqual(opisi_stanje(-2, 111, "S"), " -2:111 v")
        self.assertEqual(opisi_stanje(0, 0, "W"), "  0:0   <")

    def test_prevedi(self):
        from random import randint
        import os
        ime = "izhod{:05}.txt".format(randint(0, 99999))
        try:
            self.assertIsNone(prevedi("primer.txt", ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:0   >
 12:0   >
 12:0   v
 12:2   v
 12:2   >
 15:2   >
 15:2   ^
 15:2   <""")

            self.assertIsNone(prevedi("ukazi.txt", ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:0   >
  1:0   >
  1:0   v
  1:0   <
  0:0   <
  0:0   v
  0:0   >
  1:0   >
  1:0   v
  1:3   v
  1:3   >
  2:3   >
  2:3   v
  2:3   <""")
        finally:
            os.remove(ime)

        vime = "vhod{:05}.txt".format(randint(0, 99999))
        open(vime, "wt").write("NAPREJ 23\nLEVO\nNAPREJ 17\n")
        try:
            self.assertIsNone(prevedi(vime, ime))
            self.assertEqual(open(ime).read().rstrip(), """  0:0   ^
  0:-23 ^
  0:-23 <
-17:-23 <""")
        finally:
            os.remove(ime)
            os.remove(vime)

class TestDodatna(unittest.TestCase):
    def test_opisi_stanje(self):
        self.assertEqual(opisi_stanje_2(0, 12, "N"),   "^   (0:12)")
        self.assertEqual(opisi_stanje_2(111, 0, "E"),  "> (111:0)")
        self.assertEqual(opisi_stanje_2(-2, 111, "S"), "v  (-2:111)")
        self.assertEqual(opisi_stanje_2(0, 0, "W"),    "<   (0:0)")

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


import core.parse.tokenize as tokenize
from enum import Enum, auto

class TokenTypes(Enum):
    LITERAL_WORD = auto()
    ARGUMENT = auto()
    PREFIX_ARGUMENT = auto()

class ArgumentTypes(Enum):
    NUM = auto()
    LABEL = auto()
    TOKEN = auto()
    OFFSET_LABEL = auto()
    HEX_NUM = auto()
    BIN_NUM = auto()
    DEC_NUM = auto()
    STRING = auto()

class Pattern:
    ARGUMENT_START_SYMBOL = '{'
    ARGUMENT_END_SYMBOL = '}'
    TOKEN_SEPARATOR_SYMBOL = ':'

    def __init__(self, pattern: str):
        self.arguments = dict()
        self.tokens = tokenize.remove_meaningless_tokens_list(tokenize.tokienize_str(pattern))
        self.tokens = self.__parse_tokens()

    def __get_token_str(self, id: int):
        try:
            return self.tokens[id]
        except IndexError:
            return None

    def summarize(self):
        return ' '.join((token[1] for token in self.tokens))

    def __parse_tokens(self):
        i = 0
        processed_tokens = []
        while i < len(self.tokens):
            current_token = self.__get_token_str(i)
            next_token = self.__get_token_str(i+1)

            if current_token == Pattern.ARGUMENT_START_SYMBOL and next_token == Pattern.ARGUMENT_START_SYMBOL:
                i += 2 # seq: ['{', '{'], escaping '{'
                processed_tokens.append((TokenTypes.LITERAL_WORD, Pattern.ARGUMENT_START_SYMBOL))
                continue

            if current_token == Pattern.ARGUMENT_END_SYMBOL and next_token == Pattern.ARGUMENT_END_SYMBOL:
                i += 2 # seq: ['}', '}'], escaping '}'
                processed_tokens.append((TokenTypes.LITERAL_WORD, Pattern.ARGUMENT_END_SYMBOL))
                continue

            if current_token == Pattern.ARGUMENT_START_SYMBOL:
                # new: seq: ['{', NAME, ':', TYPE, '}']

                name_token = self.__get_token_str(i+1)
                separator = self.__get_token_str(i+2)
                type_token = self.__get_token_str(i+3)
                close_token = self.__get_token_str(i+4)

                if close_token is None or close_token != Pattern.ARGUMENT_END_SYMBOL:
                    raise
                if type_token is None or type_token == Pattern.ARGUMENT_END_SYMBOL:
                    raise
                if separator is None or separator != Pattern.TOKEN_SEPARATOR_SYMBOL:
                    raise

                self.arguments[next_token] = len(processed_tokens)
                processed_tokens.append((TokenTypes.ARGUMENT, name_token, ArgumentTypes[type_token.upper()]))
                i += 4
            else:
                processed_tokens.append((TokenTypes.LITERAL_WORD, current_token))

            i += 1
        return processed_tokens


num = int(input())
a = [list(map(int,input().split())) for _ in range(num)]

times= int(input())
for _ in range(times):
    colnum,vec,val=map(int,input().split())
    if vec==0:
        for _ in range(val):
            k=a[colnum-1][0]
            a[colnum-1].pop(0)
            a[colnum-1].append(k)
    else:
        for _ in range(val):
            k=a[colnum-1][num-1]
            a[colnum-1].pop(num-1)
            a[colnum-1].insert(0,k)

line=num
row=0
sumgot=0
while line!=1:
    sumgot+=sum(a[row][(num-1)//2-(line-1)//2:(num-1)//2+(line-1)//2+1])
    line-=2
    row+=1
while line<=num:
    sumgot+=sum(a[row][(num - 1) // 2 - (line - 1) // 2:(num - 1) // 2 + (line - 1) // 2+1])
    line+=2
    row+=1

print(sumgot)

파이썬 알고리즘 문제풀이(코딩테스트 대비)/섹션 3/8. 곳감/AA.py


import scrapy
from castorama.items import CastoramaItem
from scrapy.loader import ItemLoader

class CastospiderSpider(scrapy.Spider):
  name = "castospider"
  allowed_domains = ["castorama.ru"]
  start_urls = ["https://castorama.ru"]

  def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.start_urls = [f"https://www.castorama.ru/tools/hand-tools/?limit={kwargs.get('limit')}"]

  def parse(self, response):
    links = response.xpath("//ul[contains(@class, 'products-grid')][1]//a[contains(@class, 'product-card__name')]")
    for link in links:
      yield response.follow(link, callback=self.tool_parse)

  def tool_parse(self, response):
    loader = ItemLoader(item=CastoramaItem(), response=response)
    loader.add_xpath('name', "//h1/text()")
    loader.add_xpath('price', "//span[@class='price']/span/span[1]//text()")
    loader.add_xpath('parameters', "//div[@class='product-block product-specifications']/dl//text()")
    #фото попадают в поля в виде списка неполных ссылок
    loader.add_xpath('photos', "//img[contains(@class, 'top-slide__img')]/@data-src")
    loader.add_value('link', response.url)
    yield loader.load_item()


"""
    Object Relation Mapping
"""
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime

engine = create_engine('mysql+pymysql://root:weiqi19960906@localhost:3306/mysqltest')
# engine = create_engine('mysql+pymysql://root:weiqi19960906@localhost:3306/mysqltest?charset=utf8')
Base = declarative_base()
Session = sessionmaker(bind=engine)

class News(Base):
    __tablename__ = 'news'
    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(200), nullable=False)
    time = Column(DateTime, default=datetime.datetime.now)

class OrmTest(object):
    def __init__(self):
        self.session = Session()

    def add_one(self):
        new_obj = News(title="测试")
        new_obj1 = News(title="测试2")
        # self.session.add(new_obj)
        # self.session.add(new_obj1)
        self.session.add_all([new_obj, new_obj1])
        self.session.commit()

    def get_one(self):
        return self.session.query(News).get(2)

    def get_more(self):
        # order_by
        return self.session.query(News).filter(News.id > 1).all()

    def update_one(self):
        obj = self.session.query(News).filter(News.id > 1).first()
        obj.title = '修改测试'
        self.session.commit()

    def delete_one(self):
        obj = self.session.query(News).filter(News.id > 1).first()
        self.session.delete(obj)
        self.session.commit()

if __name__ == '__main__':
    if 'news' in engine.table_names():
        table = Table("news", Base.metadata, autoload=True)
        table.drop(engine)
    News.metadata.create_all(engine)
    o = OrmTest()
    o.add_one()
    print(o.get_one().title)
    print(o.get_more()[0].title)
    o.update_one()
    print(o.get_more()[0].title)
    o.delete_one()
    if not o.get_more():
        print("删除成功")


from threading import *
from time import sleep

class Hello(Thread):
    def run(self):
        for i in range(5):
            print("Hello")
            sleep(1)  # it will sleep for 1 second

class Hi(Thread):
    def run(self):
        for i in range(5):
            print("Hi")
            sleep(1)

t1 = Hello()
t2 = Hi()
# in thread class we have method run if you change the method name it will not work that why we are using start
t1.start()
sleep(0.2)
t2.start()
'''it will create total of three thread one is main and two is t1 and t2'''

t1.join()
t2.join()  # main thread will wait to complete a execution of t1 and t2 thread after that it will print
# bellow codes

print("Bye")


import os
import sys
import kaldi_io
import librosa
import numpy as np
import scipy.signal
import torchaudio
import math
import random
from random import choice
from multiprocessing import Pool
import scipy.io.wavfile as wav

'''def load_audio(path):
    sound, _ = torchaudio.load(path, normalization=True)
    sound = sound.numpy()
    if len(sound.shape) > 1:
        if sound.shape[1] == 1:
            sound = sound.squeeze()
        else:
            sound = sound.mean(axis=1)  # multiple channels, average
    sound = sound / 65536.
    return sound'''

def load_audio(path):
    rate, sig = wav.read(path)
    return sig

def MakeMixture(speech, noise, db):
    if speech is None or noise is None:
        return None
    if np.sum(np.square(noise)) < 1.0e-6:
        return None

    spelen = speech.shape[0]

    exnoise = noise
    while exnoise.shape[0] < spelen:
        exnoise = np.concatenate([exnoise, noise], 0)
    noise = exnoise
    noilen = noise.shape[0]

    elen = noilen - spelen - 1
    if elen > 1:
        s = round(random.randint(0, elen - 1))
    else:
        s = 0
    e = s + spelen

    noise = noise[s:e]

    try:
        noi_pow = np.sum(np.square(noise))
        if noi_pow > 0:
            noi_scale = math.sqrt(np.sum(np.square(speech)) / (noi_pow * (10 ** (db / 10.0))))
        else:
            print(noi_pow, np.square(noise), 'error')
            return None
    except:
        return None

    nnoise  = noise * noi_scale
    mixture = speech + nnoise
    mixture = mixture.astype('float32')
    return mixture

def make_feature(wav_path_list, noise_wav_list, feat_dir, thread_num, argument=False, repeat_num=1):
    mag_ark_scp_output = 'ark:| copy-feats --compress=true ark:- ark,scp:{0}/feats{1}.ark,{0}/feats{1}.scp'.format(feat_dir, thread_num)
    ang_ark_scp_output = 'ark:| copy-feats --compress=true ark:- ark,scp:{0}/angles{1}.ark,{0}/angles{1}.scp'.format(feat_dir, thread_num)
    if argument:
        fwrite = open(os.path.join(feat_dir, 'db' + str(thread_num)), 'a')
    f_mag = kaldi_io.open_or_fd(mag_ark_scp_output,'wb')
    f_ang = kaldi_io.open_or_fd(ang_ark_scp_output,'wb')
    for num in range(repeat_num):
        for tmp in wav_path_list:
            uttid, wav_path = tmp
            clean = load_audio(wav_path)
            y = None
            while y is None:
                if argument:
                    noise_path = choice(noise_wav_list)
                    n = load_audio(noise_path[0])
                    db = np.random.uniform(low=0, high=20)
                    y = MakeMixture(clean, n, db)
                    uttid_new = uttid + '__mix{}'.format(num)
                    fwrite.write(uttid_new + ' ' + str(db) + '\n')
                else:
                    y = clean
                    uttid_new = uttid
            # STFT
            if y is not None:
                D = librosa.stft(y, n_fft=512, hop_length=256, win_length=512, window=scipy.signal.hamming)
                spect = np.abs(D)
                angle = np.angle(D)
                ##feat = np.concatenate((spect, angle), axis=1)
                ##feat = feat.transpose((1, 0))
                kaldi_io.write_mat(f_mag, spect.transpose((1, 0)), key=uttid_new)
                kaldi_io.write_mat(f_ang, angle.transpose((1, 0)), key=uttid_new)
            else:
                print(noise_path, tmp, 'error')
    if argument:
        fwrite.close()

def main():

    data_dir = sys.argv[1]
    feat_dir = sys.argv[2]
    noise_repeat_num = int(sys.argv[3])

    clean_feat_dir = os.path.join(feat_dir, 'clean')
    if not os.path.exists(clean_feat_dir):
        os.makedirs(clean_feat_dir)

    mix_feat_dir = os.path.join(feat_dir, 'mix')
    if not os.path.exists(mix_feat_dir):
        os.makedirs(mix_feat_dir)

    clean_wav_list = []
    clean_wav_scp = os.path.join(data_dir, 'clean_wav.scp')
    with open(clean_wav_scp, 'r', encoding='utf-8') as fid:
        for line in fid:
            line = line.strip().replace('\n','')
            uttid, wav_path = line.split()
            clean_wav_list.append((uttid, wav_path))
    print('clean_wav_list', len(clean_wav_list))

    noise_wav_list = []
    noise_wav_scp = os.path.join(data_dir, 'noise.scp')
    with open(noise_wav_scp, 'r', encoding='utf-8') as fid:
        for line in fid:
            line = line.strip().replace('\n','')
            wav_path = line.split()
            noise_wav_list.append(wav_path)
    print('noise_wav_list', len(noise_wav_list))

    threads_num = 8
    wav_num = len(clean_wav_list)
    print('wav_num ', wav_num)
    print('Parent process %s.' % os.getpid())
    p = Pool()
    start = 0
    for i in range(threads_num):
        end = start + int(wav_num / threads_num)
        if i == (threads_num - 1):
            end = wav_num
        wav_path_tmp_list = clean_wav_list[start:end]
        start = end
        p.apply_async(make_feature, args=(wav_path_tmp_list, noise_wav_list, clean_feat_dir, i, False))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')
    command_line = 'cat {}/feats*.scp > {}/clean_feats.scp'.format(clean_feat_dir, data_dir)
    os.system(command_line)
    command_line = 'cat {}/angles*.scp > {}/clean_angles.scp'.format(clean_feat_dir, data_dir)
    os.system(command_line)

    wav_num = len(clean_wav_list)
    print('Parent process %s.' % os.getpid())
    p = Pool()
    for i in range(threads_num):
        wav_path_tmp_list = clean_wav_list[int(i * wav_num / threads_num): int((i + 1) * wav_num / threads_num)]
        p.apply_async(make_feature, args=(wav_path_tmp_list, noise_wav_list, mix_feat_dir, i, True, noise_repeat_num))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')

    command_line = 'cat {}/feats*.scp > {}/mix_feats.scp'.format(mix_feat_dir, data_dir)
    os.system(command_line)
    command_line = 'cat {}/angles*.scp > {}/mix_angles.scp'.format(mix_feat_dir, data_dir)
    os.system(command_line)
    command_line = 'cat {}/db* > {}/db.scp'.format(mix_feat_dir, data_dir)
    os.system(command_line)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
def main():
    N = int(input())
    A = list(map(int, input().split()))
    s = sum(A)
    A += A
    r, cnt = 0, 0

    for l in range(N):
        while cnt*10 < s:
            cnt += A[r]
            r += 1

        if cnt* 10 == s:
            return "Yes"

        cnt -= A[l]
    else:
        return "No"

print(main())


from .base import *

DEBUG = True

ALLOWED_HOSTS = ["127.0.0.1"]

## 务必修改以下值，确保运行时系统安全:
SECRET_KEY = "w$46bks+b3-7f(13#i%v@jwejrnxc$^^#@#@^t@fofizy1^mo9r8(-939243423300"

INSTALLED_APPS += (
    # other apps for production site
)

## 钉钉群的 WEB_HOOK， 用于发送钉钉消息
DINGTALK_WEB_HOOK = "https://oapi.dingtalk.com/robot/send?access_token=xxxxx"


"""
See more at https://rosalind.info/problems/lexv/
PROBLEM
Given: A permutation of at most 12 symbols defining an ordered alphabet 𝒜 and a positive integer n (n≤4).
Return: All strings of length at most n formed from 𝒜, ordered lexicographically. (Note: As in “Enumerating k-mers Lexicographically”, alphabet order is based on the order in which the symbols are given.)
-------------------------------- MY SOLUTION ------------------------------

"""
from itertools import product as prod

file = open('rosalind_lexv.txt').read().split()
symbols = file[:-1]
alphabet = dict(zip(symbols, range(len(symbols))))
k = int(file[-1])

m = []
for i in range(len(symbols)):
    for j in range(1, k+1):
        m = m + [''.join(i) for i in prod(symbols, repeat=j)]
m = set(m)
m = sorted(m, key = lambda j: [alphabet[i] for i in j])

for x in m:
    print(x)

27-Ordering Strings of Varying Lengths Lexicographically.py


from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.image import Image

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout

from kivy.uix.label import Label
from kivy.uix.widget import Widget

from kivy.config import Config
Config.set('graphics', 'resizable', '0')
Config.set('graphics', 'width', '640')
Config.set('graphics', 'height', '480')

class MyApp(App):
    def update_label(self):
        self.lbl.text = self.formula

    def add_number(self, instance):
        if( self.lbl.text == "0" ):
            self.lbl.text = ""

        self.formula += str(instance.text)
        self.update_label()

    def add_operation(self, instance):
        if( str(instance.text).lower() == "x" ):
            self.formula += "*"
        else:
            self.formula += str(instance.text)
        self.update_label()

    def calc_result(self,instance):
        self.lbl.text = str(int(eval(self.formula))) #float values - without int
        self.formula = self.lbl.text

    def new_photo(self, instance):
        i = instance.text
        fl = FloatLayout(size_hint=(1, .09375), size=(640, 60), pos=(0, 0))
        but4 = Button(text='<--Back', size_hint=(.09375, 1), pos=(0, 0))
        but5 = Button(text='Bye :D\n  Quit', size_hint=(.09375, 1), pos=(580, 0))

        if i in self.dictionary:
            self.image = self.dictionary[i]
        else:
            raise IndentationError

        self.bl.clear_widgets()
        fl.add_widget(but4)
        fl.add_widget(but5)
        self.bl.add_widget(self.image)
        self.bl.add_widget(fl)

    def build(self, instance=None):
        self.image = Image()
        self.formula = ""

        #using of different pics depend on button
        self.dictionary = {
            'Press me, please!!!':     Image(source='Ant_man.jpg', allow_stretch=True, keep_ratio=False),
            'Go and buy \nsome milk!': Image(source='Iron_man.jpg', allow_stretch=True, keep_ratio=False),
            'You\'re a cool guy :D':   Image(source='Venom.jpg', allow_stretch=True, keep_ratio=False),
        }

       # creating layouts for pics and buttons
        self.bl = BoxLayout(orientation='vertical')
        rl = RelativeLayout()
        im_hazard = Image(source='Hazard.jpg', allow_stretch=True, keep_ratio=False)
        im_san = Image(source='Sanches.jpg', allow_stretch=True, keep_ratio=False, size_hint=(.234375, 1), pos=(0, 0))
        but1 = Button(text='Press me, please!!!', size_hint=(.234375, .5), pos=(150, 120), on_press=self.new_photo)
        but2 = Button(text='Go and buy \nsome milk!', size_hint=(.234375, .5), pos=(300, 120), on_press=self.new_photo)
        but3 = Button(text='You\'re a cool guy :D', size_hint=(.3125, .5), pos=(200, 0), on_press=self.new_photo)

        self.bl.add_widget(im_hazard)
        self.bl.add_widget(rl)
        rl.add_widget(im_san)
        rl.add_widget(but1)
        rl.add_widget(but2)
        rl.add_widget(but3)

        #making calculator
        fl2 = FloatLayout(size_hint=(.296875, 1), size=(190, 240), pos=(450, 0))

        self.lbl = Label(text="0", font_size=15, halign="right", valign="center", pos=(450, 240*.6), size_hint=(1, .4), text_size=(190, 96))
        fl2.add_widget(self.lbl)

        gl = GridLayout(cols=4, spacing=2, pos=(450, 0), size_hint=(1, .6))
        gl.add_widget( Button(text="7", on_press=self.add_number) )
        gl.add_widget( Button(text="8", on_press=self.add_number) )
        gl.add_widget( Button(text="9", on_press=self.add_number) )
        gl.add_widget( Button(text="X", on_press=self.add_operation) )

        gl.add_widget( Button(text="4", on_press=self.add_number) )
        gl.add_widget( Button(text="5", on_press=self.add_number) )
        gl.add_widget( Button(text="6", on_press=self.add_number) )
        gl.add_widget( Button(text="-", on_press=self.add_operation) )

        gl.add_widget( Button(text="1", on_press=self.add_number) )
        gl.add_widget( Button(text="2", on_press=self.add_number) )
        gl.add_widget( Button(text="3", on_press=self.add_number) )
        gl.add_widget( Button(text="+", on_press=self.add_operation) )

        gl.add_widget( Button(text="/", on_press=self.add_operation) )
        gl.add_widget( Button(text="0", on_press=self.add_number) )
        gl.add_widget( Button(text=".", on_press=self.add_number) )
        gl.add_widget( Button(text="=", on_press=self.calc_result) )

        fl2.add_widget(gl)
        rl.add_widget(fl2)

        return self.bl

window = MyApp()
window.run()


import collections

Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(19, y=20)
print(p.x)

# 値が代入できないクラスが生成されていることを確認
# 以下はError
# p.x = 100

p1 = Point._make([100,200])
print(p1.x)
print(p1._asdict())

p1._replace(x=50)
print(p1) ## replaceされていない
# 使うときは、以下。コピーして使う。
p2 = p1._replace(x=50)
print(p2)

class SumPoint(collections.namedtuple('Point', ['x', 'y'])):
    @property
    def total(self):
        return self.x + self.y

p3 = SumPoint(2,3)
print(p3.x, p3.y, p3.total)

import csv

# with open('names.csv', 'w') as csvfile:
#     fieldnames = ['first', 'last', 'address']
#     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
#     writer.writeheader()
#     writer.writerow({'first': 'Mike', 'last': 'Jackson', 'address': 'A'})
#     writer.writerow({'first': 'Jun', 'last': 'Sakai', 'address': 'B'})
#     writer.writerow({'first': 'Nancy', 'last': 'Mask', 'address': 'C'})

with open('names.csv', 'r') as f:
    csv_reader = csv.reader(f)
    Names = collections.namedtuple('_Names', next(csv_reader))
    # print(next(csv_reader))
    for row in csv_reader:
        names = Names._make(row)
        print(names.first, names.last, names.address)


# %%
import torch.nn as nn
import torch
from torch.nn.modules import padding
# %%
class ConvLSTMCell(nn.Module):

    def __init__(self, input_dim, hidden_dim, kernel_size, bias,
                 dropout, fc_in_dim, fc_out_dim, cur_layer, total_layer):
        """
        Initialize ConvLSTM cell.

        Parameters
        ----------
        input_dim: int
            Number of channels of input tensor.
        hidden_dim: int
            Number of channels of hidden state.
        kernel_size: (int, int)
            Size of the convolutional kernel.
        bias: bool
            Whether or not to add the bias.
        """

        super(ConvLSTMCell, self).__init__()

        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.kernel_size = kernel_size
        self.padding = kernel_size[0] // 2, kernel_size[1] // 2
        self.bias = bias
        self.dropout = dropout
        self.fc_in_dim = fc_in_dim
        self.fc_out_dim = fc_out_dim
        self.cur_layer = cur_layer
        self.total_layer = total_layer - 1

        self.conv = nn.Conv2d(in_channels=self.input_dim + self.hidden_dim,
                              out_channels=4 * self.hidden_dim,  # it has four gates, each gate has hidden state
                              kernel_size=self.kernel_size,
                              padding=self.padding,
                              bias=self.bias)

        self.fc = nn.Sequential( nn.Linear( self.fc_in_dim, 100, bias=True) ,
                                 nn.Dropout(self.dropout),
                                 nn.Linear( 100, 100, bias=True) ,
                                 nn.Dropout(self.dropout),
                                 nn.Linear( 100, self.fc_out_dim, bias=True ) )

    def forward(self, input_tensor, cur_state):
        h_cur, c_cur = cur_state
        '''
        tensor combined is generated by input_tensor and h_cur
        along channel axis, that is why in_channels = input_dim + hidden_dim
        '''
        combined = torch.cat([input_tensor, h_cur], dim=1)  # concatenate along channel axis

        combined_conv = self.conv(combined)
        cc_i, cc_f, cc_o, cc_g = torch.split(combined_conv, self.hidden_dim, dim=1)
        '''
        i = Sigmoid{ Conv(input) + Conv(hidden) + bias }
        f = Sigmoid{ Conv(input) + Conv(hidden) + bias }
        o = Sigmoid{ Conv(input) + Conv(hidden) + bias }
        g = Sigmoid{ Conv(input) + Conv(hidden) + bias }
        '''
        i = torch.sigmoid(cc_i)
        f = torch.sigmoid(cc_f)
        o = torch.sigmoid(cc_o)
        g = torch.tanh(cc_g)

        c_next = f * c_cur + i * g
        h_next = o * torch.tanh(c_next)

        if self.cur_layer == self.total_layer:
            b, c, h, w = h_next.size()
            out = h_next.view(b, -1)
            preds = self.fc( out )

            return preds, h_next, c_next

        return h_next, h_next, c_next

    def init_hidden(self, batch_size, image_size):
        height, width = image_size
        return (torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device),
                torch.zeros(batch_size, self.hidden_dim, height, width, device=self.conv.weight.device))

# %%
class ConvLSTM(nn.Module):

    """

    Parameters:
        input_dim: Number of channels in input
        hidden_dim: Number of hidden channels
        kernel_size: Size of kernel in convolutions
        num_layers: Number of LSTM layers stacked on each other
        batch_first: Whether or not dimension 0 is the batch or not
        bias: Bias or no bias in Convolution
        return_all_layers: Return the list of computations for all layers
        Note: Will do same padding.

    Input:
        A tensor of size B, T, C, H, W or T, B, C, H, W
    Output:
        A tuple of two lists of length num_layers (or length 1 if return_all_layers is False).
            0 - layer_output_list is the list of lists of length T of each output
            1 - last_state_list is the list of last states
                    each element of the list is a tuple (h, c) for hidden state and memory
    Example:
        >> x = torch.rand((32, 10, 64, 128, 128))
        >> convlstm = ConvLSTM(64, 16, 3, 1, True, True, False)
        >> _, last_states = convlstm(x)
        >> h = last_states[0][0]  # 0 for layer index, 0 for h index
    """

    def __init__(self, input_dim, hidden_dim, kernel_size,
                 num_layers, fc_in_dim, fc_out_dim, dropout=0,
                 batch_first=False, bias=True):

        super(ConvLSTM, self).__init__()

        self._check_kernel_size_consistency(kernel_size)

        # Make sure that both `kernel_size` and `hidden_dim` are lists having len == num_layers
        kernel_size = self._extend_for_multilayer(kernel_size, num_layers)
        hidden_dim = self._extend_for_multilayer(hidden_dim, num_layers)
        # that condition must be satisfied
        if not len(kernel_size) == len(hidden_dim) == num_layers:
            raise ValueError('Inconsistent list length.')

        self.input_dim = input_dim
        self.hidden_dim = hidden_dim
        self.kernel_size = kernel_size
        self.num_layers = num_layers
        self.fc_in_dim = fc_in_dim
        self.fc_out_dim = fc_out_dim
        self.dropout = dropout
        self.batch_first = batch_first
        self.bias = bias

        cell_list = []

        self.CNN_first = nn.Sequential( nn.Conv2d( in_channels=self.input_dim,
                                                   out_channels=5 * self.input_dim,
                                                   kernel_size=(5, 3),
                                                   stride=(1, 1),
                                                   padding=(0, 1),
                                                   bias=True ),

                                        nn.Tanh(),

                                        nn.Conv2d( in_channels=5 * self.input_dim,
                                                   out_channels=3 * self.input_dim,
                                                   kernel_size=(5, 2),
                                                   stride=(1, 1),
                                                   padding=(0, 0),
                                                   bias=True ),

                                        nn.Tanh(),

                                        nn.Conv2d( in_channels=3 * self.input_dim,
                                                   out_channels=self.input_dim,
                                                   kernel_size=(5, 2),
                                                   stride=(1, 1),
                                                   padding=(0, 0),
                                                   bias=True ),

                                        nn.Tanh()
                                      )

        for i in range(0, self.num_layers):
            # if i == 0:
            #     cur_input_dim = self.input_dim
            # else:
            #     cur_input_dim = self.hidden_dim[i-1]

            '''
            the number of hidden states of last layer is the number of input
            dimensions of current layer except the first layer
            '''
            cur_input_dim = self.input_dim if i == 0 else self.hidden_dim[i - 1]

            cell_list.append(ConvLSTMCell(input_dim=cur_input_dim,
                                          hidden_dim=self.hidden_dim[i],
                                          kernel_size=self.kernel_size[i],
                                          bias=self.bias,
                                          dropout=self.dropout,
                                          fc_in_dim=self.fc_in_dim,
                                          fc_out_dim=self.fc_out_dim,
                                          cur_layer=i,
                                          total_layer=self.num_layers) )

        self.cell_list = nn.ModuleList(cell_list)

        # add several fully connected layers

    def forward(self, input_tensor, hidden_state=None):
        """

        Parameters
        ----------
        input_tensor: todo
            5-D Tensor either of shape (t, b, c, h, w) or (b, t, c, h, w)
        hidden_state: todo
            None. todo implement stateful

        Returns
        -------
        last_state_list, layer_output
        """
        if not self.batch_first:
            # (t, b, c, h, w) -> (b, t, c, h, w)
            input_tensor = input_tensor.permute(1, 0, 2, 3, 4)

        # first through CNN
        b, t, c, h, w = input_tensor.size()
        output_tensor = self.CNN_first( input_tensor.view(b*t, c, h, w) )
        bt, c, h, w = output_tensor.size()
        output_tensor = output_tensor.view(b, t, c, h, w)
        b, _, _, h, w = output_tensor.size()

        # Implement stateful ConvLSTM
        if hidden_state is not None:
            raise NotImplementedError()
        else:
            # Since the init is done in forward. Can send image size here
            hidden_state = self._init_hidden(batch_size=b,
                                             image_size=(h, w))

        layer_output_list = []
        last_state_list = []

        seq_len = output_tensor.size(1)
        cur_layer_input = output_tensor

        for layer_idx in range(self.num_layers):
            # h: batch_size * number_hidden_state * height * width
            # c: batch_size * number_hidden_state * height * width
            h, c = hidden_state[layer_idx]
            output_inner = []
            for t in range(seq_len):
                preds, h, c = self.cell_list[layer_idx](input_tensor=cur_layer_input[:, t, :, :, :],
                                                 cur_state=[h, c])
                output_inner.append(preds)

            layer_output = torch.stack(output_inner, dim=1)
            cur_layer_input = layer_output

            layer_output_list.append(layer_output)
            last_state_list.append([h, c])

        layer_output_list = layer_output_list[-1:]
        last_state_list = last_state_list[-1:]

        return layer_output_list, last_state_list

    def _init_hidden(self, batch_size, image_size):
        init_states = []
        # height and width of image
        # h, w = image_size
        for i in range(self.num_layers):
            # h = (h - self.kernel_size[i][0] + 2 * self.padding_size[i][0]) // 1 + 1
            # w = (w - self.kernel_size[i][1] + 2 * self.padding_size[i][1]) // 1 + 1
            # image_size = (h, w)
            init_states.append(self.cell_list[i].init_hidden(batch_size, image_size))
        return init_states

    @staticmethod
    def _check_kernel_size_consistency(kernel_size):
        if not (isinstance(kernel_size, tuple) or
                (isinstance(kernel_size, list) and all([isinstance(elem, tuple) for elem in kernel_size]))):
            raise ValueError('`kernel_size` must be tuple or list of tuples')

    @staticmethod
    def _extend_for_multilayer(param, num_layers):
        if not isinstance(param, list):
            param = [param] * num_layers
        return param

# %%
if __name__ == '__main__':
    # batch_size * time_length * channels * height * width
    # b * t * c * h * w
    data = torch.randn((5, 6, 3, 30, 30))
    # build ConvLSTM model, the input data has three channels,
    # model has three LSTM layers, number of hidden states of each layer is 64, 64 and 128
    model = ConvLSTM( input_dim=3,
                      hidden_dim=[64, 64, 128],
                      kernel_size=[(3, 3), (5, 5), (7, 7)],
                      num_layers=3,
                      batch_first=True,
                      bias=True,
                      return_all_layers=True )

    layer_output_list, last_state_list = model( data )

    last_layer_output = layer_output_list[-1]

    last_layer_last_h, last_layer_last_c = last_state_list[-1]

    print( last_layer_output[:, -1, ...] == last_layer_last_h)


#!/usr/bin/env python
import sys
import os

# location of folder you want to parse
fname = "/home/rmpadge/job_events/"

# list all of the files in the specified folder
def list_files(path):
  files = []
  for name in os.listdir(path):
    if os.path.isfile(os.path.join(path, name)):
      files.append(path + name)
  return files

# read each line in a file and pass it to wordmap (recursive)
def readline(singlefile):
  with open(singlefile, "r") as ins:
    array = []
    for line in ins:
      wordmap(line)

# split each item in a file delimeted by whatever split() is
def wordmap(oneLine):
    oneLine = oneLine.strip()
    for word in oneLine.split(","):
      if word != "":
        print ('%s\t%s' % (word, 1))

if __name__ == "__main__":
  l = list_files(fname)

  for x in l:
    files = readline(x)
    print(files)


#!/usr/bin/env python3
def solve(d, b, f, ef, t0, t1, t2, et0, et1, et2):
    if d == 0: return b + 100*f + 500*ef

    f += 3*t0
    ef += 3*et0
    (t0, t1, t2) = (t1, t2, t0)
    (et0, et1, et2) = (et1, et2, et0)

    # if we can buy an exotic fruit using bling and normal fruits,
    # always optimal to do so
    if b + 100*f >= 400:
        ef += 1
        b -= 400
        while b < 0:
            b += 100
            f -= 1
    elif ef > 0: # if we have an exotic fruit, sell it to buy another one, netting 100 bling
        b += 100

    if d <= 3: # endgame, don't do any planting just keep going
        return solve(d-1, b, f, ef, t0, t1, t2, et0, et1, et2)

    # (incorrectly) plant all remaining fruit
    t2 += f
    f = 0
    et2 += ef
    ef = 0
    return solve(d-1, b, f, ef, t0, t1, t2, et0, et1, et2)

(d, b, f, t0, t1, t2) = list(map(int, input().split()))
print(solve(d, b, f, 0, t0, t1, t2, 0, 0, 0))


# DP해결문제
T = int(input())
for tc in range(T):
    N = int(input()) // 10  # 10의 배수이므로 10으로 나누어서 인덱스로 만들어주기
    arr = [1, 3]
    for i in range(2, N+1):
        # 규칙을 찾아 더해서 추가해주기
        arr.append(arr[i-1] + arr[i-2] * 2)

    # 0번째 부터 시작하여 인덱스-1을 해서 리스트를 뽑아낸다.
    print("#{}".format(tc + 1), arr[N-1])


# -*- coding: utf-8 -*-
"""
COMP 551 A2

Author: Shatil Rahman
ID:     260606042

Contains the functions to evaluate performance of classifiers, using
the following metrics: accuracy, precision, recall and F1-score
"""

import numpy as np

def evaluate(Y_test, Y_predicted):
    '''
    -Calculates the accuracy, precision, recall and F1-score and the
     confusion matrix from the results of the classification
    -Class 0 (1.0s) is a "positive" and Class 1 (-1.0's) is a "negative"
    -The format of the confusion matrix is:
            _______________________________
            |true positive | false positive|
            |______________|_______________|
            |false negative| true negative |
            |______________|_______________|

    '''
    tp = 0.0
    fp = 0.0
    fn = 0.0
    tn = 0.0
    for i in range(0,len(Y_test)):
        if Y_predicted[i] == 1.0:
            if Y_test[i] == 1.0:
                tp = tp + 1
            else:
                fp = fp + 1
        else:
            if Y_test[i] == -1.0:
                tn = tn + 1
            else:
                fn = fn + 1

    conf_mat = np.array([[tp, fp], [fn, tn]])

    accuracy = (tp + tn)/ (tp + tn + fp + fn)
    precision = tp/(tp+fp)
    recall = tp/(tp + fn)
    f1_score = 2.0*(precision * recall)/(precision + recall)

    return accuracy, precision, recall, f1_score


from ETL_db import *
from transform import *

session = sessionmaker(bind=engine)()

for user in users:
    row = Users(**user)
    session.add(row)

for upload in uploads:
    row = Uploads(**upload)
    session.add(row)

session.commit()


'''
Created on 25.07.2012

@author: michi
'''
from PyQt4.QtCore import QAbstractItemModel, QModelIndex, QVariant, Qt
from ems.qt4.util import variant_to_pyobject

class SummaryModel(QAbstractItemModel):

    def __init__(self, parent=None):
        QAbstractItemModel.__init__(self, parent)
        self._sourceModel = None
        self._resultCache = {}

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if orientation == Qt.Horizontal:
            return self._sourceModel.headerData(section, orientation, role)
        if role == Qt.DisplayRole:
            return QVariant('Sum')
        return QVariant()

    def onSourceModelDataChanged(self, topLeft, bottomRight):
        cols = []
        for col in range(topLeft.column(), bottomRight.column()+1):
            cols.append(col)
        self.recalculate(cols)

    def getMaxValue(self, col):
        maxVal = 0.0
        for row in range(self._sourceModel.rowCount()):
            index = self._sourceModel.index(row, col)
            value = variant_to_pyobject(self._sourceModel.data(index))
            if isinstance(value, (int,float)):
                maxVal = max(maxVal, value)
        return maxVal

    def recalculateAll(self):
        self.recalculate(range(self._sourceModel.columnCount()))

    def recalculate(self, columns):
        if not self._sourceModel or not len(columns):
            return

        for col in columns:
            colSum = 0.0
            for row in range(self._sourceModel.rowCount()):
                index = self._sourceModel.index(row, col)
                value = variant_to_pyobject(self._sourceModel.data(index))
                if isinstance(value, (int,float)):
                    colSum += value
            self._resultCache[col] = QVariant(colSum)

        self.dataChanged.emit(self.index(0,columns[0]),
                              self.index(0,col))

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or \
           not (0 <= index.row() < self.rowCount()):
            return QVariant()

        if role in (Qt.DisplayRole, Qt.EditRole):
            try:
                return self._resultCache[index.column()]
            except KeyError:
                return QVariant()
            except AttributeError:
                return QVariant()

        return QVariant()

    def parent(self, *args, **kwargs):
        return QModelIndex()

    def columnCount(self, parentIndex=QModelIndex()):
        if self._sourceModel:
            return self._sourceModel.columnCount(parentIndex)
        return 0

    def rowCount(self, parentIndex=QModelIndex()):
        return 1

    def index(self, row, col, parentIndex=QModelIndex()):
        return self.createIndex(row, col, parentIndex)

    def sourceModel(self):
        return self._sourceModel

    def setSourceModel(self, sourceModel):
        if isinstance(self._sourceModel, QAbstractItemModel):
            self._sourceModel.dataChanged.disconnect(self.onSourceModelDataChanged)
        self._sourceModel = sourceModel
        self._sourceModel.dataChanged.connect(self.onSourceModelDataChanged)
        self._sourceModel.modelReset.connect(self.recalculateAll)
        self.recalculateAll()
        return self


test=int(input())
dictionary={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
inverse={1:'a',2:'b',3:'c',4:'d',5:'e',6:'f',7:'g',8:'h',9:'i',10:'j',11:'k',12:'l',13:'m',14:'n',15:'o',16:'p',17:'q',18:'r',19:'s',20:'t',21:'u',22:'v',23:'w',24:'x',25:'y',26:'z'}
while test:
    name=input()
    checker=[]
    length=len(name)
    for i in range(0,len(name)):
        checker.append(dictionary[name[i]])
    copy_checker=sorted(checker)
    setter_checker=set(copy_checker)
    setter_checker=sorted(setter_checker)
    print(checker,copy_checker,setter_checker)
    if(copy_checker==[56,34]):
        print("no answer")
    else:
        answer=[]
        temp=setter_checker[setter_checker.index(checker[0])+1]
        answer.append(inverse[setter_checker[setter_checker.index(checker[0])+1]])
        for i in range(0,len(checker)):
            if(copy_checker[i]!=temp):
                answer.append(inverse[copy_checker[i]])
        s=''.join(answer)
        print(s)

    test=test-1


import csv
import sys
import os

import pandas as pd

from AxfrChecker.AxfrChecker import AxfrChecker
from DnssecChecker.DnssecChecker import DnssecChecker
from HttpsChecker.HttpsChecker import HttpsChecker
from Scanner.Scanner import Scanner, ScannerConfig
from SecurityHeadersChecker.SecurityHeadersChecker import SecurityHeadersChecker
from SecurityLayerChecker.SecurityLayerChecker import SecurityLayerChecker

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python main.py [csv_file_name with .csv extension] [url_column_name] [log_flag (optional)]")
        sys.exit(1)

    source_file_csv = sys.argv[1]
    url_column_name = sys.argv[2]
    file_without_extension = source_file_csv.split(".csv")[0]
    log_flag = True

    if len(sys.argv) == 4:
        log_flag = (sys.argv[3].lower() == 'true')

    if not source_file_csv.endswith('.csv'):
        print(f"Error: File {source_file_csv} does not have .csv extension.")
        sys.exit(1)

    if not os.path.isfile(source_file_csv):
        print(f"Error: File {source_file_csv} not found.")
        sys.exit(1)

    with open(file=source_file_csv, mode='r', encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile)
        headers = next(reader)
        columns = headers

    if url_column_name not in columns:
        print(f"Error: Column {url_column_name} not found in {source_file_csv}.")
        sys.exit(1)

    source_df = pd.read_csv(filepath_or_buffer=f'{source_file_csv}', encoding='utf-8', engine='python')
    configs = [
        ScannerConfig(engine_class=SecurityHeadersChecker, method_for_analysis='check_security_headers_https',
                      keys_interface_list=SecurityHeadersChecker.get_owasp_security_headers(),
                      url_column_name=url_column_name, params={'timeout_limit': 180}),
        ScannerConfig(engine_class=HttpsChecker, method_for_analysis='get_https_results',
                      keys_interface_list=HttpsChecker.get_interface_list(), url_column_name=url_column_name,
                      params={'timeout_limit': 180}),
        ScannerConfig(engine_class=DnssecChecker, method_for_analysis='get_information',
                      keys_interface_list=DnssecChecker.get_interface_list(), url_column_name=url_column_name),
        ScannerConfig(engine_class=AxfrChecker, method_for_analysis='get_information',
                      keys_interface_list=AxfrChecker.get_interface_list(), url_column_name=url_column_name),
        ScannerConfig(engine_class=SecurityLayerChecker, method_for_analysis='check_security_layer_in_list',
                      keys_interface_list=SecurityLayerChecker.get_interface_list(), url_column_name=url_column_name)
    ]

    for config in configs:
        Scanner(config, source_df).start_analysis(log_on=log_flag, save_to_file_on=True)


import collections as cl

n = int(input("Enter number of words: "))
arr = []
# taking inputs from the user and storing it in an array
for i in range(n):
    arr.append(input(("Enter a word: ")))

# calculating number of distinct words
distinct = len(cl.Counter(arr).values())
print(distinct)

# calculating the frequency of each word in an array
v = cl.Counter(arr).values()
print("Frequency of each word in the array:", end=" ")
for j in v:
    print(j, end=" ")
print()


"""

instance variables should always be set in the constructor

"""
class Customer:
    def __init__(self, name):               #the constructor
        self.name = name

    def set_balance(self, balance = 0.0):
        self.balance = balance

    def get_balance(self):                  #if this is called before set_balance it will crash
        print(self.balance)

"""

__str__ can be used to return a string if the class itself is ever called

"""
class See:
    def __str__(self):
        return "this will be printed out"

print(See())

"""

for collections that are mutable a copy is needed so that you can change one copy while keeping the other
do this with the copy module

copy.copy(x)            shallow copy    new object with references to the other lists inside it
copy.deepcopy(x)        deep copy       new object with recursive coppies of the other lists inside it

the difference between ^^ is only relevant for lists that have other lists

"""

import copy
class City:
    def __init__ (self, name):
        self.name = name
class University:
    def __init__(self, name, city):
        self.name = name
        self.city = city

rva = City("Richmond")
vcu = University("VCU", rva)

print(id(vcu), id(vcu.name), id(vcu.city), id(vcu.city.name))   #bunch of ids
var = vcu                                                       #if printed would be the SAME bunch of ids^^
var = copy.copy(vcu)                                            #if printed id(var) would be different
var = copy.deepcopy(vcu)#id(var) would be different from id(var) from ^^ but id(var.city) would be id(var) from ^^

listA = ["john", "jane"]
tupleB = (listA, 1, "two")
print(listA)
print(tupleB)

b = copy.copy(tupleB)
c = copy.deepcopy(tupleB)

listA[0] = "james"
print(listA)                #because listA has been modified
print(b)                    #also different now because listA has been modified
print(c)                    #hasn't been changed because it copied the value when it was made

"""

class variables are variables described inside a class

var.animal_type = "whatever" will change the animal_type for var
Shark.animal_type = "whatever" will change the animal_type for all sharks
"""

class Shark:
    animal_type = "fish"
    def __init__(self, name):
        self.name = name

d = Shark("bite")
e = Shark("tooth")

Shark.animal_type = "dog"               #affects all previous elements
e.animal_type = "cat"
print(d.name, " is ", d.animal_type)
print(e.name, " is ", e.animal_type)

"""

x = public
_x = protected
__x =   private

if you need private, protected, and public you shouldn't be using python

"""


from cv2 import cv2
import numpy as np
from keras.models import load_model
from keras.preprocessing import image
model = load_model("models/mask_model.h5")

labels_dict = {0: 'with_mask', 1: 'without_mask'}
color_dict = {0: (0, 255, 0), 1: (255, 0, 0)}

cap = cv2.VideoCapture(0)  # Use camera 0

# We load the xml file
classifier = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
i = 0
while True:
    _, img = cap.read()
    # img = cv2.imread("face_reco/unknown_faces/IMG20200219173630.jpg")

    img = cv2.flip(img, 1, 1)
    face = classifier.detectMultiScale(img, scaleFactor=1.1, minNeighbors=4)
    for(x, y, w, h) in face:
        face_img = img[y:y+h, x:x+w]
        cv2.imwrite('temp.jpg', face_img)

        test_image = image.load_img('temp.jpg', target_size=(150, 150, 3))
        test_image = image.img_to_array(test_image)
        test_image = np.expand_dims(test_image, axis=0)
        label = model.predict_classes(test_image)[0][0]

        # print(result)
        # for r in result:
        #     print(r)
        #     if r[0] > r[1]:
        #         label = 0
        #     else:
        #         label = 1
        # label=np.argmax(result,axis=1)[0]
        # print(label)
        cv2.rectangle(img, (x, y), (x+w, y+h), color_dict[label], 2)
        cv2.rectangle(img, (x, y-40), (x+w, y), color_dict[label], -1)
        cv2.putText(img, labels_dict[label], (x, y-10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2)
        i += 1
    # Show the image
    cv2.imshow('LIVE Capture', img)
    key = cv2.waitKey(10)
    # if Enter key is press then break out of the loop
    if key == 13:  # The Enter key
        break
    print(i)
# Stop video
cap.release()

# Close all started windows
cv2.destroyAllWindows()


from subprocess import check_output, CalledProcessError
import logging, json, pathlib, os
import pprint

logging.basicConfig(format='%(asctime)s : line %(lineno)-3s : %(name)s : %(levelname)s : %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)
CURRENT_DIR = os.getcwd()

temp_file_01 = '''
"use strict";

import { Hello } from "./module/hello_world.js";

console.log("Main load");

Hello.call();
'''.strip()

temp_file_02 = '''
"use strict";

let Hello = {
    call : function(){
        console.log("This module hello world!!!");
    }
};

export { Hello };
'''.strip()

temp_file_03 = '''
body {
    background-color: #706F6F;
}
'''.strip()

temp_file_04 = '''
@import 'style/custom.scss'
'''.strip()

config_webPack = '''
module.exports = {
    entry: './js/main.js',
    output: {
        filename: './bundle.js'
    }
};
'''.strip()

def run_cmd(cmd):
    try:
        out_bytes = check_output(cmd, shell=True)
        logger.info("\n%s", out_bytes.decode())
    except CalledProcessError as e:
        logger.info("%s %s", e.returncode, e.output)

cmd1 = "npm init --yes"
cmd2 = "npm install --save-dev webpack webpack-cli"
cmd3 = "npm install --save sass"

def add_cmd_package():
    with open("package.json") as f:
        data = json.load(f)
    data['scripts']["start"] = "webpack -d"
    data['scripts']["watch"] = "webpack --watch --devtool eval-source-map"

    data['scripts']["style"]     = "sass --no-source-map style/base.scss:style/style.min.css"
    data['scripts']["wstyle"]    = "sass style/base.scss style/style.min.css --watch"
    data['scripts']["style-min"] = "sass style/base.scss style/style.min.css --style compressed"

    with open("package.json", "w") as f:
        json.dump(data, f, indent=2, sort_keys=True)
    logger.info("update package.json \n %s", data)

def create_config_wp():
    with open("webpack.config.js", "w") as f:
        f.write(config_webPack)

def create_structure_dir():
    a = os.path.join(CURRENT_DIR, "js/module")
    b = os.path.join(CURRENT_DIR, "dist")
    c = os.path.join(CURRENT_DIR, "style/style")
    fs = [a,b,c]
    for d in fs:
        pathlib.Path(d).mkdir(parents=True, exist_ok=True)
    logger.info("Structure dir created")

def create_files():
    mainjs      = ( os.path.join(CURRENT_DIR, "js/main.js"), temp_file_01 )
    hello_world = ( os.path.join(CURRENT_DIR, "js/module/hello_world.js"), temp_file_02 )
    customstyle = ( os.path.join(CURRENT_DIR, "style/style/custom.scss"), temp_file_03 )
    basesccs    = ( os.path.join(CURRENT_DIR, "style/base.scss"), temp_file_04 )
    files = [mainjs, hello_world, customstyle, basesccs]
    for fl in files:
        with open(fl[0], "w") as f:
            f.write(fl[1])
        logger.info("file: %s created", fl[0])

def main():
    run_cmd(cmd1)
    run_cmd(cmd2)
    run_cmd(cmd3)
    add_cmd_package()
    create_config_wp()
    create_structure_dir()
    create_files()
    logger.info("End. Good job!!!")

if __name__ == '__main__':
    main()


from __future__ import print_function

import os
import sys

import zipfile
import shutil

# Import appropriate StringIO class
try: from cStringIO import StringIO as BytesIO
except:
    try: from StringIO import StringIO as BytesIO
    except:
        try: from io import BytesIO
        except: print("Could not import StringIO!")

class SubmoduleDownloader:

    """ Util class to download and extract (sub-)modules from github """

    @staticmethod
    def download_submodule(author, module_name, dest_path, ignore_list):
        """ Downloads a submodule from the given author and module name, and extracts
        all files which are not on the ignore_list to the dest_path.

        Example: download_submodule("tobspr", "RenderPipeline", ".", ["README.md", "LICENSE"])
         """

        # Make directory, if it does not exist yet
        if not os.path.isdir(dest_path):
            os.makedirs(dest_path)

        # Construct download url
        source_url = "https://github.com/" + author + "/" + module_name + "/archive/master.zip"
        prefix = module_name + "-master"
        print("Fetching:", source_url)

        try:
            # Python 2.7
            import urllib
            urlopen = urllib.urlopen

        except:

            # Python 3.4
            import urllib.request
            urlopen = urllib.request.urlopen

        # Download the zip
        try:
            usock = urlopen(source_url)
            zip_data = usock.read()
            usock.close()
        except Exception as msg:
            print("ERROR: Could not fetch module", module_name, "! Reason:", msg, file=sys.stderr)
            sys.exit(2)

        # Extract the zip
        zip_ptr = BytesIO(zip_data)

        try:
            zip_handle = zipfile.ZipFile(zip_ptr)
        except zipfile.BadZipfile:
            print("ERROR: Invalid zip file!", file=sys.stderr)
            sys.exit(3)

        if zip_handle.testzip() is not None:
            print("ERROR: Invalid zip file checksums!", file=sys.stderr)
            sys.exit(1)

        num_files, num_dirs = 0, 0

        for fname in zip_handle.namelist():
            rel_name = fname.replace(prefix, "").replace("\\", "/").lstrip("/")
            if not rel_name:
                continue

            is_file = not rel_name.endswith("/")
            rel_name = dest_path.rstrip("/\\") + "/" + rel_name

            # Files
            if is_file:
                for ignore in ignore_list:
                    if ignore in rel_name:
                        break
                else:
                    with zip_handle.open(fname, "r") as source, open(rel_name, "wb") as dest:
                        shutil.copyfileobj(source, dest)
                    num_files += 1

            # Directories
            else:
                if not os.path.isdir(rel_name):
                    os.makedirs(rel_name)
                num_dirs += 1

        print("Extracted", num_files, "files and", num_dirs, "directories")

if __name__ == "__main__":

    # Main update script
    ignore = ("__init__.py LICENSE README.md config.ini "
        "Source/ExampleClass.cpp Source/ExampleClass.h Source/ExampleClass.I").split()
    import os
    import sys
    curr_dir = os.path.dirname(os.path.realpath(__file__)); os.chdir(curr_dir);
    SubmoduleDownloader.download_submodule("tobspr", "P3DModuleBuilder", curr_dir, ignore)
    with open("Scripts/__init__.py", "w") as handle: pass
    try: os.remove(".gitignore")
    except: pass
    os.rename("prefab.gitignore", ".gitignore")