import os
import random
import collections
from functools import reduce

import sympy

from sympy2code import java_code_method

from .sympy_formula import *
from .dir_const import java_module_dir, java_test_dir

java_code_dict = dict(
    add1 = add_1,
    minus1 = minus_1,
    mul1 = mul_1,
    div1 = div_1,
    floor1 = floor_1,
    complexFormula1 = complex_formula_1,
    hItemFromBigBoxMCrit =  h_item_from_big_box_m_crit
)

java_code_all = "\n\t".join(
    java_code_method(v, k) for k, v in java_code_dict.items()
).replace('\n', '\n\t')

with open(os.path.join(java_module_dir, "SympyCode.java"), "w", encoding="utf8") as f:
    f.write("package sympy;\n\n")
    f.write(
    """public class SympyCode {\n"""
    f"""{java_code_all}\n"""
    """}"""
    )

java_test_code = ""
for name, formula in java_code_dict.items():
    java_test_code += f"\t@Test\n\tpublic void {name}Test() {{\n"

    for _ in range(10):
        formula_symbols = collections.OrderedDict(
            sorted({s: random.randint(-100000, 100000) for s in formula.atoms() if isinstance(s, sympy.Symbol)}.items(), key=lambda x: x[0].__repr__())
        )
        variables_str = ", ".join(f"{v}"for k, v in formula_symbols.items())
        res = float(sympy.Float(reduce(lambda f, s: f.subs(s[0], s[1]), formula_symbols.items(), formula)).evalf())
        java_test_code += f"\t\tassertEquals(SympyCode.{name}({variables_str}), {res});\n"
    java_test_code += "\t};\n\n"

test_file_str = f"""\
package sympytest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import sympy.SympyCode;
class SympyJUnit5Test {{
{java_test_code}
}};
"""

with open(os.path.join(java_test_dir, "SympyTest.java"), "w", encoding="utf8") as f:
    f.write(test_file_str)


import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from Colors import tmpcolor, v041color, change_width, mw_v041, mw_tmp

df=pd.read_csv('IC95.csv')
df.set_index(['strain','drug'],inplace=True)
df2=df.stack().reset_index()
df2.columns=['Strain','Drug','Replica','MIC']
df2['MIC']*=1000
df2.loc[df2['Drug']=='V-041','Drug']='4\'-DTMP'

palette=[tmpcolor,v041color]
fig,ax=plt.subplots()
sns.set_style("ticks")
sns.despine()
sns.barplot(x='Strain',y='MIC',hue='Drug',
            data=df2,palette=palette,
            capsize=.05,errwidth=1.5,
            edgecolor='k',errcolor='k', ci='sd')
change_width(ax,.3)
ax.set_xticklabels(['E. coli\nMG1655','E. coli\nClinical Isolate',
                    'K. pneumoniae\nF45153','P. aeruginosa\nPAO1',
                    'S. aureus\nRN4220'],fontstyle='italic', fontsize=8, rotation=90,
                   horizontalalignment='center', verticalalignment='top')
ax.set_yscale('log')
ax.set_ylabel('IC$_{95}$ (µM)')
ax.set_xlabel('')
ax.get_legend().remove()
ax.legend(frameon=False, fontsize=7, loc=2)
ax.set_ylim(1e-1,1e3)
fig.set_size_inches(2.6,2.0)
fig.tight_layout(pad=.95)
fig.savefig('BarPlot_IC95-DifferentStrains.pdf',dpi=600)
fig.savefig('BarPlot_IC95-DifferentStrains.png',transparent=True,dpi=600)

######## Convert concentration to ug/ml ########
df2['MIC_ug']=0
df2.loc[df2.Drug=='TMP','MIC_ug']=df2.loc[df2.Drug=='TMP','MIC'] * mw_tmp * 1e-3
df2.loc[df2.Drug=="4\'-DTMP",'MIC_ug']=df2.loc[df2.Drug=="4\'-DTMP",'MIC'] * mw_v041 * 1e-3

fig,ax=plt.subplots()
sns.set_style("ticks")
sns.despine()
sns.barplot(x='Strain',y='MIC_ug',hue='Drug',
            data=df2,palette=palette,
            capsize=.05,errwidth=1.5,
            edgecolor='k',errcolor='k', ci='sd')
change_width(ax,.3)
xms = sorted([-0.35, 0.65, 1.65, 2.65, 3.65, 0.05, 1.05, 2.05, 3.05, 4.05])
c = 0
for strain in df2.Strain.unique():
    for drug in df2.Drug.unique():
        yvals = df2.loc[(df2.Strain == strain) & (df2.Drug == drug), 'MIC_ug'].values
        xvals = np.ones(len(yvals)) * xms[c] + (np.random.random(len(yvals)) - .5) * .2 + .15
        # print(strain, drug, xvals, yvals)
        ax.plot(xvals, yvals, 'o', color='k', markersize=2, alpha=.5)
        c += 1

ax.set_xticklabels(['E. coli\nMG1655','E. coli\nClinical Isolate',
                    'K. pneumoniae\nF45153','P. aeruginosa\nPAO1',
                    'S. aureus\nRN4220'],fontstyle='italic', fontsize=8, rotation=90,
                   horizontalalignment='center', verticalalignment='top')
ax.set_yscale('log')
ax.set_ylabel('IC$_{95}$ (µg/ml)')
ax.set_xlabel('')
ax.get_legend().remove()
ax.legend(frameon=False, fontsize=7, loc=2, bbox_to_anchor=(0.01, 1.05))
ax.set_ylim(1e-1,1e3)
fig.set_size_inches(2.6,2.0)
fig.tight_layout(pad=.95)
fig.savefig('BarPlot_IC95-DifferentStrains_ug_wDots.pdf',dpi=600)
fig.savefig('BarPlot_IC95-DifferentStrains_ug_wDots.png',transparent=True,dpi=600)


import logging

from django.conf import settings
from django import template
from django.db.models import ObjectDoesNotExist

from greyjay.themes import utils

class ThemeError(Exception):
    pass

logger = logging.getLogger(__name__)

register = template.Library()

debug = getattr(settings, 'DEBUG', True)

def do_warning(block_name, usage):
    global debug

    if debug:
        raise ThemeError(
            'No theme nor default {} with usage "{}" found'.format(
                block_name,
                usage,
            )
        )

    else:
        logger.warning(
            'No theme nor default {} with usage "{}" found'.format(
                block_name,
                usage,
            )
        )
        return ''

def get_theme_contents(context):
    try:
        theme = context['self'].theme
    except (KeyError, AttributeError):
        theme = None

    if theme is None:
        return [utils.get_default_theme_content()]
    else:
        return [theme.content, utils.get_default_theme_content()]

@register.simple_tag(takes_context=True)
def get_contact_email(context):
    contents = get_theme_contents(context)
    email = ''
    for content in contents:
        email = content.contact_email
        if email:
            return email

    if not email:
        try:
            defaults = context['request'].site.default_settings
            return defaults.contact_email
        except ObjectDoesNotExist:
            return ''

    return email

@register.simple_tag(takes_context=True)
def get_text_block(context, usage):
    contents = get_theme_contents(context)
    for content in contents:
        content_piece = content.block_links.filter(block__usage=usage).first()
        if content_piece is not None:
            break

    if content_piece is None:
        return do_warning('text_block', usage)

    return content_piece.block

@register.simple_tag(takes_context=True)
def get_follow_link(context, usage):
    contents = get_theme_contents(context)
    for content in contents:
        content_piece = content.follow_links.filter(block__usage=usage).first()
        if content_piece is not None:
            break

    if content_piece is None:
        return do_warning('follow_link', usage)

    return content_piece.block.link

@register.simple_tag(takes_context=True)
def get_logo(context, usage):
    contents = get_theme_contents(context)
    for content in contents:
        content_piece = content.logo_links.filter(block__usage=usage).first()
        if content_piece is not None:
            break

    if content_piece is None:
        return do_warning('logo_block', usage)

    return content_piece.block.logo

@register.simple_tag(takes_context=True)
def get_logo_link(context, usage):
    contents = get_theme_contents(context)
    for content in contents:
        content_piece = content.logo_links.filter(block__usage=usage).first()
        if content_piece is not None:
            break

    if content_piece is None:
        return do_warning('logo_block', usage)

    return content_piece.block.link

@register.filter(name='split_string')
def split_string(value, arg):
    return value.split(arg)


import sys
from setuptools import setup

install_requires = []

with open('equipment/console/requirements.txt', 'r', encoding='utf-8') as f:
    install_requires.extend(f.read().splitlines())

with open('equipment/framework/requirements.txt', 'r', encoding='utf-8') as f:
    install_requires.extend(f.read().splitlines())

with open('README.md', 'r', encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='equipment',
    packages=['equipment'],
    version='CURRENT_VERSION',
    license='MIT',
    description='The root of your next python project',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Roger Vilà',
    author_email='rogervila@me.com',
    url='https://github.com/rogervila/equipment',
    download_url='https://github.com/rogervila/equipment/archive/CURRENT_VERSION.tar.gz',
    keywords=['equipment', 'application scaffolding', 'framework'],
    install_requires=install_requires,
    tests_require=['coverage', 'runtype'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3.8',
    ],
    include_package_data=True,
    entry_points={
        # Install a script as "equipment", and as "equipment3", and as "equipment3.x"
        'console_scripts': [
            #pylint: disable=consider-using-f-string
            'equipment = equipment.console:main',
            'equipment%d = equipment.console:main' % sys.version_info[:1],
            'equipment%d.%d = equipment.console:main' % sys.version_info[:2],
            #pylint: enable=consider-using-f-string
        ],
    },
)


# WSGI 分为两部分,一个是web-server(处理器),另一部分是web-application

import os
import sys

from app import simple_app

def wsgi_to_bytes(s):
    return s.encode()

def run_with_cgi(application):
    environ = dict(os.environ.items())
    environ['wsgi.input'] = sys.stdin.buffer
    environ['wsgi.errors'] = sys.stderr
    environ['wsgi.version'] = (1, 0)
    environ['wsgi.multithread'] = False
    environ['wsgi.multiprocess'] = True
    environ['wsgi.run_once'] = True
    if environ.get('HTTPS', 'off') in ('on', '1'):
        environ['wsgi.url_scheme'] = 'https'
    else:
        environ['wsgi.url_scheme'] = 'http'

    headers_set = []
    headers_sent = []

    # 写到标准输出而不是响应http
    def write(data):
        out = sys.stdout.buffer
        if not headers_set:
            raise AssertionError("write()before start_response()")

        elif not headers_sent:
            # 先将headers_set赋值给headers_sent(为副本),并同时将这个副本赋值给status,response_headers
            status, response_headers = headers_sent[:] = headers_set
            out.write(wsgi_to_bytes('Status: %s\r\n' % status))
            for header in response_headers:
                out.write(wsgi_to_bytes('%s: %s \r\n' % header))
            out.write(wsgi_to_bytes('\r\n'))
            out.flush()

    # 定义处理
    def statr_response(status, response_headers, exc_info=None):
        if exc_info:
            try:
                if headers_sent:
                    raise (exc_info[0], exc_info[1], exc_info[2])
            finally:
                exc_info = None
        elif headers_set:
            raise AssertionError("Headers already set!")

        headers_set[:] = [status, response_headers]
        # 注意 返回的是write函数
        return write

    # 我们定义的WSGI应用程序(WSGI-application),必须是可调用对象它接收两个参数：一个是包含HTTP请求信息的environ字典，另一个是一个可调用的start_response函数。
    # WSGI应用程序根据传入的请求信息生成HTTP响应内容，并通过调用start_response函数来设置响应头和状态码
    # application必须是一个可调用对象,是一个函数或者是一个有__call__的类的实例
    # 其返回值只需返回一个可迭代对象即可
    result = application(environ, statr_response)

    # 遍历我们处理器函数返回的值,生成最终的处理结果返回客户端
    try:
        for data in result:
            if data:
                write(data)
        if not headers_sent:
            write(' ')
    finally:
        if hasattr(result, 'close'):
            result.close()

if __name__ == '__main__':
    run_with_cgi(simple_app)
# gateway可以视为一种WSGI服务器(实际上他并没有接收http请求,和响应,只是调用了application并将结果打印至终端)

# WSGI服务器负责接收http请求,并将http请求交给WSGI-application处理,并将处理结果生成响应发送回客户端
# WSGI可以独立运行,WSGI可以启动指定的WSGI应用程序
# 除直接运行本文件外,可以通过现有的WSGI服务器启动WSGI application: gunicorn app:simple_app


import string
from collections import OrderedDict

def is_far(words_list,currentword,thresh,normalized_levenshtein):
    threshold = thresh
    score_list =[]
    for word in words_list:
        score_list.append(normalized_levenshtein.distance(word.lower(),currentword.lower()))
    if min(score_list)>=threshold:
        return True
    else:
        return False

def filter_phrases(phrase_keys,max,normalized_levenshtein ):
    filtered_phrases =[]
    if len(phrase_keys)>0:
        filtered_phrases.append(phrase_keys[0])
        for ph in phrase_keys[1:]:
            if is_far(filtered_phrases,ph,0.7,normalized_levenshtein ):
                filtered_phrases.append(ph)
            if len(filtered_phrases)>=max:
                break
    return filtered_phrases

def edits(word):
    "All edits that are one edit away from `word`."
    letters    = 'abcdefghijklmnopqrstuvwxyz '+string.punctuation
    splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
    deletes    = [L + R[1:]               for L, R in splits if R]
    transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
    replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
    inserts    = [L + c + R               for L, R in splits for c in letters]
    return set(deletes + transposes + replaces + inserts)

def sense2vec_get_words(word,s2v):
    output = []

    word_preprocessed =  word.translate(word.maketrans("","", string.punctuation))
    word_preprocessed = word_preprocessed.lower()
    word_edits = edits(word_preprocessed)

    word = word.replace(" ", "_")

    sense = s2v.get_best_sense(word)
    most_similar = s2v.most_similar(sense, n=15)
    compare_list = [word_preprocessed]
    for each_word in most_similar:
        append_word = each_word[0].split("|")[0].replace("_", " ")
        append_word = append_word.strip()
        append_word_processed = append_word.lower()
        append_word_processed = append_word_processed.translate(append_word_processed.maketrans("","", string.punctuation))
        if append_word_processed not in compare_list and word_preprocessed not in append_word_processed and append_word_processed not in word_edits:
            output.append(append_word.title())
            compare_list.append(append_word_processed)

    out = list(OrderedDict.fromkeys(output))

    return out


import unittest

from b2flow.python.tools.driver import Driver
from b2flow.python.tools.storage import Storage

class StorageTestCase(unittest.TestCase):
    def test_should_join(self):
        storage = Storage('/basepath')

        self.assertEqual(storage.join("second", "third"), "basepath/second/third")

    def test_should_create_path(self):
        storage = Storage('basepath')

        self.assertEqual(storage.directory, "basepath")
        self.assertEqual(storage.path("second").directory, "basepath/second")

    def test_should_go_to_parent_path(self):
        storage = Storage('basepath/second')

        self.assertEqual(storage.parent.directory, "basepath")

    def test_should_write_and_read_bytes(self):
        storage = Storage('basepath/second', driver=Driver('fromhell'))

        storage.write(b"test", "example.txt")
        data = storage.read("example.txt")
        self.assertEqual(b"test", data)

    def test_should_write_and_read_bytes_with_compress(self):
        storage = Storage('basepath/second', driver=Driver('fromhell'))

        storage.write(b"test", "example.txt", compress=True)
        data = storage.read("example.txt")
        self.assertEqual(b"test", data)

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


print('''

            7.4 – Ingredientes para uma pizza: Escreva um laço que peça ao usuário para
            fornecer uma série de ingredientes para uma pizza até que o valor 'quit' seja
            fornecido. À medida que cada ingrediente é especificado, apresente uma
            mensagem informando que você acrescentará esse ingrediente à pizza.
''')

pizza = {}
adicionais = []

mensagens = [
    'Infomre o sabor da Pizza: ',
    'Infomre o que gostaria de adicionar: '
]

active1 = True
while active1:
    sabor_da_pizar = input(mensagens[0])

    active2 = True
    if sabor_da_pizar.lower() != 'quit':

        while active2:
            adicionais_da_pizza = input(mensagens[1])
            adicionais.append(adicionais_da_pizza)

            if adicionais_da_pizza == 'quit':
                active2 = False
                del adicionais[:]
            else:
                pizza[sabor_da_pizar] = [opcao for opcao in adicionais]

    if sabor_da_pizar == 'quit':
        print()
        active1 = False

for sabor, adicionais in pizza.items():
    print(f"O sabor é {sabor.title()} ")
    for adicional in adicionais:
        print(f"\tAdicional de {adicional}")
    print()

chapter_07/7_4 – Ingredientes para uma pizza.py


# default code for each  operator
import os
import sys
import re
import logging

# init logger
root = logging.getLogger()
root.setLevel('INFO')
handler = logging.StreamHandler(sys.stdout)
handler.setLevel('INFO')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
logging.basicConfig(level=logging.CRITICAL)

# get parameters from args
parameters = list(filter(
                lambda s: s.find('=') > -1 and bool(re.match(r'[A-Za-z0-9_]*=[.\/A-Za-z0-9]*', s)),
                sys.argv
            ))

# set parameters to env variables
for parameter in parameters:
    variable = parameter.split('=')[0]
    value = parameter.split('=', 1)[-1]
    logging.info(f'Parameter: {variable} = "{value}"')
    os.environ[variable] = value

# update log level
log_level = os.environ.get('log_level', 'INFO')
if log_level !='INFO':
    logging.info(f'Updating log level to {log_level}')
    root.setLevel(log_level)
    handler.setLevel(log_level)


# https://www.acmicpc.net/problem/2630
# 메모리 제한 : 128MB , 정답비율 : 70.772%

# 전체종이 n*n (n = 2의k승, 1<=k<=7 자연수)
# 종이를 자르는 규칙
# 1. if 모든 같은 색이 아니다? -> 중앙부분을 잘라서 4등분 한다.
# 2. 각 조각 별로 1번 반복
# 3. 조작이 모두 같은 색이다? -> 자르기 멈춘다.

# input1 : n의 값 (2, 4, 8, 16, 32, 64, 128 중 하나다.)
# input2 : 종이에 색칠 된 정보 - 0 = white, 1 = blue
# ouput : 하얀색 색종이, 파란색 색종이 갯수 구하기

# input
# 8
# 1 1 0 0 0 0 1 1
# 1 1 0 0 0 0 1 1
# 0 0 0 0 1 1 0 0
# 0 0 0 0 1 1 0 0
# 1 0 0 0 1 1 1 1
# 0 1 0 0 1 1 1 1
# 0 0 1 1 1 1 1 1
# 0 0 1 1 1 1 1 1

# ouput
# 9
# 7

# 1차시도 실패
# n = int(input())
# global matrix
# matrix = [list(map(int, input().split())) for _ in range(n)]
# # print(*matrix, sep='\n')
# blue, white = 0, 0
# test = [[] for _ in range(4)]

# def check(paper):
#     temp = 0

#     for i in range(len(paper)):
#         temp += sum(paper[i])
#         print('temp:', temp, i)
#         if sum(paper[i]) != len(paper) and sum(paper[i]) > 0:
#             return 'slice'

#     if temp == 0:
#         return 'white'
#     elif temp == len(paper) ** 2:
#         return 'blue'
#     else:
#         return 'slice'

# def slice(paper):
#     slice_paper = [[] for _ in range(4)]
#     l = len(paper) // 2
#     case = [(0, 0), (0, l), (l, 0), (l, l)]
#     cnt = 4
#     while cnt > 0:
#         for i in range(len(l)):
#             for j in range(len(l)):

#                 # slice_paper[1] =
#                 # slice_paper[2] =
#                 # slice_paper[3] =

#     return slice_paper

# result = check(matrix)

# if result == 'slice':
#     print('slice do it!')

# elif result == 'blue':
#     blue = 1
# elif result == 'white':
#     white = 1
# print('slice!!>>', slice(matrix))

# # Final Print Section
# print(f'white: {white}\nblue: {blue}')

# 2차시도 - 쿼드트리 / 분할 정복
def quad_tree(x, y, n):
    global matrix, blue, white
    color = matrix[y][x]
    double_break = False

    for i in range(x, x + n):
        # 반복문 탈출 조건
        if double_break:
            break
        for j in range(y, y + n):
            if matrix[j][i] != color:
                # 4분면으로 나눠서 확인하기
                quad_tree(x, y, n // 2)
                quad_tree(x + n // 2, y, n // 2)
                quad_tree(x, y + n // 2, n // 2)
                quad_tree(x + n // 2, y + n // 2, n // 2)
                double_break = True
                break

    if not double_break:
        if matrix[y][x] == 1:
            blue += 1
        else:
            white += 1

n = int(input())
matrix = []
blue, white = 0, 0

for _ in range(n):
    matrix.append(list(map(int, input().split())))

quad_tree(0, 0, n)
print(f'{white}\n{blue}')

백준/단계별뿌시기/20단계(분할정복)/색종이만들기.py


from flask_wtf import FlaskForm
from wtforms import IntegerField,StringField,SubmitField

class AddForm(FlaskForm):
    name=StringField('puppy name')
    submit=SubmitField("Add Puppy")

class DelForm(FlaskForm):
    id = IntegerField("please enter id of puppy which means delete")
    submit=SubmitField('Del Puppy')


import os.path
import numpy as np
from radiobear.constituents import parameters

# Some constants
coef = 7.244E+21     # coefficient from GEISA_PP.TEX eq. 14
T0 = 296.0           # reference temperature in K
hck = 1.438396       # hc/k  [K cm]
GHz = 29.9792458     # conversion from cm^-1 to GHz
fLower = 26.0        # beginning of transition between S and J (changed from 40 15/5/4)
fHigher = 34.0       # end of transition    "  (changed from 50 15/5/4)
EPS = 1E-12          # a small number

data = None

def readInputFiles(par):
    """This reads in the data files for nh3"""
    filename = os.path.join(par.path, 'nh3.npz')
    if par.verbose:
        print("Reading nh3 lines from {}".format(filename))
    global data
    data = np.load(filename)

def alpha(freq, T, P, X, P_dict, other_dict, **kwargs):
    Joiner = 0
    Spilker = 1
    Interp = 2

    par = parameters.setpar(kwargs)
    # Read in data if needed
    global data
    if data is None:
        readInputFiles(par)

    P_h2 = P * X[P_dict['H2']]
    P_he = P * X[P_dict['HE']]
    P_nh3 = P * X[P_dict['NH3']]
    Pscale = 1.0 + P / 1.0E5  # ad hoc to make this match Berge-Gulkis for deep Jupiter atmosphere

    # Set Joiner
    GH2 = [1.690]
    GHe = [0.750]
    GNH3 = [0.6]
    ZH2 = [1.350]
    ZHe = [0.300]
    ZNH3 = [0.200]
    C = [1.0]
    D = [-0.45]
    # Set Spilker
    rexp = 8.79 * np.exp(-T / 83.0)
    GH2a = np.exp(9.024 - T / 20.3) - 0.9918 + P_h2
    try:
        GH2a = np.power(GH2a, rexp)
    except ValueError:
        GH2a = 0.0
    if GH2a < EPS:  # use Joiner regardless
        GH2.append(1.690)
        GHe.append(0.750)
        GNH3.append(0.60)
        ZH2.append(1.35)
        ZHe.append(0.30)
        ZNH3.append(0.20)
        C.append(1.00)
        D.append(-0.45)
    else:
        GH2a = 2.122 * np.exp(-T / 116.8) / GH2a
        GH2a = 2.34 * (1.0 - GH2a)
        GH2.append(GH2a)
        GHe.append(0.46 + T / 3000.0)
        GNH3.append(0.74)
        ZH2.append(5.7465 - 7.7644 * GH2a + 9.1931 * GH2a**2 - 5.6816 * GH2a**3 + 1.2307 * GH2a**4)
        ZHe.append(0.28 - T / 1750.0)
        ZNH3.append(0.50)
        C.append(-0.337 + T / 110.4 - T**2 / 70600.0)
        D.append(-0.45)
    # Set interp index
    GH2.append(0.0)
    GHe.append(0.0)
    GNH3.append(0.0)
    ZH2.append(0.0)
    ZHe.append(0.0)
    ZNH3.append(0.0)
    C.append(0.0)
    D.append(0.0)
    f0 = data['f0']
    I0 = data['I0']
    E = data['E']
    G0 = data['G0']
    n_dvl = 2.0 / 3.0
    n_int = 3.0 / 2.0
    ITG = I0 * np.exp(-((1.0 / T) - (1.0 / T0)) * E * hck)
    alpha_nh3 = []
    for f in freq:
        f2 = f**2
        if f <= fLower:
            use = Spilker
        elif f >= fHigher:
            use = Joiner
        else:
            use = Interp
            flfh = (fLower - fHigher) / (f - fLower)
            GH2[Interp] = GH2[Spilker] + (GH2[Spilker] - GH2[Joiner]) / flfh
            GHe[Interp] = GHe[Spilker] + (GHe[Spilker] - GHe[Joiner]) / flfh
            GNH3[Interp] = GNH3[Spilker] + (GNH3[Spilker] - GNH3[Joiner]) / flfh
            ZH2[Interp] = ZH2[Spilker] + (ZH2[Spilker] - ZH2[Joiner]) / flfh
            ZHe[Interp] = ZHe[Spilker] + (ZHe[Spilker] - ZHe[Joiner]) / flfh
            ZNH3[Interp] = ZNH3[Spilker] + (ZNH3[Spilker] - ZNH3[Joiner]) / flfh
            C[Interp] = C[Spilker] + (C[Spilker] - C[Joiner]) / flfh
            D[Interp] = D[Spilker] + (D[Spilker] - D[Joiner]) / flfh
        delta = D[use] * P_nh3

        gamma = np.power((T0 / T), n_dvl) * (GH2[use] * P_h2 + GHe[use] * P_he + G0 * GNH3[use] * P_nh3)  # noqa
        g2 = gamma**2
        zeta = np.power((T0 / T), n_dvl) * (ZH2[use] * P_h2 + ZHe[use] * P_he + G0 * ZNH3[use] * P_nh3)  # noqa
        z2 = zeta**2

        num = (gamma - zeta) * f2 + (gamma + zeta) * (np.power(f0 + delta, 2.0) + g2 - z2)
        den = np.power((f2 - np.power(f0 + delta, 2.0) - g2 + z2), 2.0) + 4.0 * f2 * g2
        shape = GHz * 2.0 * np.power(f / f0, 2.0) * num / (np.pi * den)
        alpha_nh3.append(np.sum(shape * ITG))

    alpha_nh3 = coef * (P_nh3 / T0) * pow((T0 / T), n_int + 2) * np.array(alpha_nh3) * Pscale
    if par.units == 'dBperkm':
        alpha_nh3 *= 434294.5

    return alpha_nh3


"""
===========================
The linguistic component of the model.
===========================

Dr. Cai Wingfield
---------------------------
Embodied Cognition Lab
Department of Psychology
University of Lancaster
c.wingfield@lancaster.ac.uk
caiwingfield.net
---------------------------
2019
---------------------------
"""
from __future__ import annotations

from typing import Optional

from .basic_types import ActivationValue
from .components import ModelComponentWithAccessibleSet
from .guards import make_under_firing_threshold_guard_for, make_exceeds_firing_threshold_guard_for
from .modulations import make_apply_activation_cap_modulation_for
from .propagator_linguistic import LinguisticPropagator

class LinguisticComponent(ModelComponentWithAccessibleSet):
    """
    The linguistic component of the model.
    Uses an exponential decay on nodes and a gaussian decay on edges.
    """

    def __init__(self,
                 propagator: LinguisticPropagator,
                 activation_cap: Optional[ActivationValue],
                 accessible_set_threshold: ActivationValue,
                 accessible_set_capacity: Optional[int],
                 firing_threshold: ActivationValue,
                 ):
        """
        :param firing_threshold:
            Firing threshold.
            A node will fire on receiving activation if its activation crosses this threshold.
        """

        super().__init__(propagator, accessible_set_threshold, accessible_set_capacity)
        assert isinstance(self.propagator, LinguisticPropagator)

        if activation_cap is not None:
            assert (activation_cap
                    # If activation_cap == accessible_set_threshold, items will only enter the accessible set when fully
                    # activated.
                    >= self.accessible_set.threshold)

        # Thresholds
        # Use >= and < to test for above/below
        self.firing_threshold: ActivationValue = firing_threshold

        self.propagator.activation_guards.extend([
            # If this node is currently suprathreshold, it acts as activation sink.
            # It doesn't accumulate new activation and cannot fire.
            make_under_firing_threshold_guard_for(self.firing_threshold)
        ])
        # No pre-synaptic modulation
        if activation_cap is not None:
            self.propagator.firing_modulations.extend([
                # Cap on a node's total activation after receiving incoming activations
                make_apply_activation_cap_modulation_for(activation_cap)
            ])
        self.propagator.firing_guards.extend([
            # Activation must exceed a firing threshold to cause further propagation.
            make_exceeds_firing_threshold_guard_for(self.firing_threshold)
        ])


#线段树或RMQ
def add(x,tar,l,r,pos):#插入的数值，插入在第几个，区间左右，树的节点下标
    global tree
    if l==tar and r==tar:
        tree[pos]=x
        return
    mid=(l+r)//2
    if tar<=mid:
        add(x,tar,l,mid,pos*2+1)
    else:
        add(x,tar,mid+1,r,pos*2+2)
    tree[pos]=max(tree[pos*2+1],tree[pos*2+2])

def query(tarl,tarr,l,r,pos):#要查询的区间左右，当前区间左右，树的节点下标
    global tree
    if l==tarl and r==tarr:
        return tree[pos]
    mid=(l+r)//2
    if tarr<=mid:
        return query(tarl,tarr,l,mid,pos*2+1)
    elif tarl>=mid+1:
        return query(tarl,tarr,mid+1,r,pos*2+2)
    else:
        return max(query(tarl,mid,l,mid,pos*2+1),query(mid+1,tarr,mid+1,r,pos*2+2))

m,d=map(int,input().split())
tree=[0 for i in range(0,4*m)]#线段树开4倍空间
n=0
t=0
for i in range(0,m):
    op=input().split()
    if op[0]=='A':
        n+=1
        add((int(op[1])+t)%d,n,1,m,0)

    else:
        t=query(n-int(op[1])+1,n,1,m,0)
        print(t)


'''Посчитать сумму двух натуральных чисел A и B, записанных в римской системе счисления. Ответ также записать в римской системе счисления.

M = 1000, D = 500, C = 100, L = 50, X = 10, V = 5, I = 1. Все числа – не превышают 2000.

Входные данные

В строке записано два числа в римской системе счисления, между которыми стоит знак + .

Выходные данные

Единственное число – сумма чисел, записанное также в римской системе счисления. Числа в римской системе счисления записаны большими латинскими буквами.'''

word = "IIII" #input()
arr = word.split('+')
print(arr)
summa = 0

value_dict = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
}
#decoder
for i in range(len(arr[0])):
    print(value_dict[arr[0][i]])
    print('\n')

s = len(arr[0])
for i in range(s):
    for j in range(s-i-1):
        if (value_dict[arr[0][j]] <= value_dict[arr[0][j+1]]):#для сначала меньшие
            print(value_dict[arr[0][j]])
            summa -= value_dict[arr[0][j]]
            '''
        elif(value_dict[arr[0][j]] >= value_dict[arr[0][j+1]]):#для сначала большие
            summa += value_dict[arr[0][j]]
            '''
print(summa)

Римские числа.py

Римские числа.py


"""
DistChunky SceneSplitter
Python 3
colebob9

This script takes scene files in a "scenes" directory and splits them up based on benchmark scores.

TODO:
Some extra tweaks to calculating SSP if the benchmark scores are too far from each other
Factor in already rendered SSP
put benchmark results into another config file to use across scripts
"""

import json
import math
import os, shutil
from collections import OrderedDict

print("")
print("DistChunky SceneSplitter")
print("")

# Config

scenesDir = "scenes/"

scenesForWorkersDir = "DC_ScenesForWorkers"
deleteScenesForWorkersDir = True

benchmarkResults = {"i7-4790K": 11197, "Pentium G645": 2598, "i5-4690": 7599, "TestClient": 432} # <- actual benchmarks
#benchmarkResults = {"i7-4790K": 432, "Pentium G645": 543, "i5-4690": 674} # <- made up tests

# End Config

# Detect all scenes in scenesDir
allScenes = []
for file in os.listdir(scenesDir):
    if file.endswith(".json"):
        allScenes.append(os.path.splitext(file)[0])
print("Found Chunky scenes:")
print(allScenes)
print("")

# Add all benchmark results together
added = 0
print("[Benchmark results:] ")
for key, value in benchmarkResults.items():
    print(key + ": " + str(value))
    added = value + added

print("Added: " + str(added))
print("")

# Convert into a percentage
benchmarkResultsPercentage = {}
for key, value in benchmarkResults.items():
    benchmarkResultsPercentage[key] = value / added
print("Calculated Percentages: " + str(benchmarkResultsPercentage))
print("")

# Deleting ScenesForWorkersDir
if deleteScenesForWorkersDir:
    if os.path.exists(scenesForWorkersDir):
        print("Deleting Workers Directory...")
        shutil.rmtree(scenesForWorkersDir)

for scene in allScenes:
    # Create ScenesForWorkersDirs
    if not os.path.exists(scenesForWorkersDir):
        os.mkdir(scenesForWorkersDir)
        print("Made " + scenesForWorkersDir + " directory.")

    #
    # Reading JSON and figuring out SSP for each computer.
    #
    print("\n[Chunky Scene Info:] ")
    sceneJsonFile = scenesDir + scene + ".json"

    print("Scene: " + scene)
    with open(sceneJsonFile, 'r') as f:
        data = json.load(f)
        sspTarget = data["sppTarget"]
        print("SPP Target: " + str(sspTarget))

    benchmarkResultsSSP = {}
    for key, value in benchmarkResultsPercentage.items():
        sspCalc = sspTarget * value
        benchmarkResultsSSP[key] = int(round(sspCalc, 0))

    # Create SSP Estimations
    print("SSP Estimations: " + str(benchmarkResultsSSP))
    sspAdded = 0
    for key, value in benchmarkResultsSSP.items():
        sspAdded = value + sspAdded
    #print("Added up: " + str(sspAdded)) # for testing that all workers have the same amount of SSP all together

    if not sspAdded == sspTarget:
        maxSSPKey = max(benchmarkResults.items(), key=operator.itemgetter(1))[0]
        maxSSPValue = benchmarkResultsSSP.get(maxSSPKey)
        sspCorrection = sspTarget - sspAdded
        print("Giving " + maxSSPKey + " " + str(sspCorrection) + " more SSP.")
        benchmarkResultsSSP[maxSSPKey] = maxSSPValue + sspCorrection
        print(maxSSPKey + " will now render " + str(benchmarkResultsSSP[maxSSPKey]) + " SSP.")

        sspAdded = 0
        for key, value in benchmarkResultsSSP.items():
            sspAdded = value + sspAdded
        print("Added up: " + str(sspAdded))

    # Check that numbers are the same
    if not sspAdded == sspTarget:
        print("Something went wrong, the numbers dont add up right.\nReport this as an issue on GitHub please.")
        print(sspAdded, "=/=", sspTarget)
        exit()

    #
    # Splitting scene file into separate scenes for each PC
    #
    print("")

    # Copy files

    sceneFilesExts = [".dump", ".foliage", ".grass", ".json", ".octree", ".dump.backup", ".json.backup"]
    for key, value in benchmarkResults.items():
        for f in sceneFilesExts:
            workerSceneDir = scenesForWorkersDir + "/" + str(key)
            if not os.path.exists(workerSceneDir):
                os.mkdir(workerSceneDir)
                print("Made " + workerSceneDir + " directory.")

            if not os.path.isfile(scenesDir + scene + f): # check that if backup scene files exist
                pass
            else:
                shutil.copy(scenesDir + scene + f, workerSceneDir)
                print("Copied: " + scenesDir + scene + f + " to " + workerSceneDir + "/" + scene + f)

    # Edit json files
    workerScene = workerSceneDir + "/" + scene + ".json"
    with open(workerScene, 'r') as json_file:
        workerJson = json.load(json_file, object_pairs_hook=OrderedDict)

        workerJson["sppTarget"] = value
        with open(workerScene, 'w') as json_file:
            json.dump((workerJson), json_file, sort_keys=False, indent=2)
        print("Split scene \"" + scene + "\" for worker \"" + key + "\"" + "\n")


n=int(input("Enter the number of elements to be inserted"))
b=[]
for i in range(0,n):
    a=int(input("Enter elements: "))
    b.append(a)
sum1=0
sum2=0
sum3=0
for j in b:
    if (j>0):
        if(j%2==0):
            sum1=sum1+j
        else:
            sum2=sum2+j
    else:
        sum3=sum3+j
print("Sum of all positive even number = ",sum1)
print("Sum of all positive odd number = ",sum2)
print("Sum of all negative number = ",sum3)


import re
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from pyrogram.errors.exceptions.bad_request_400 import MessageTooLong
from pyrogram import enums
from config import API_ID,API_HASH,TOKEN

API_ID = API_ID
API_HASH = API_HASH
TOKEN = TOKEN
# Initialize the bot with your API ID and API hash
app = Client("my_bot", api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN)

item_2 = "<"
item_1 = ">"
item_2i = "{"
item_1i = "}"

MAX_MESSAGE_LENGTH = 4096

# Function to send messages in batches
async def send_messages_in_batches(chat_id, messages):
    for i in range(0, len(messages), MAX_MESSAGE_LENGTH):
        batch = messages[i:i + MAX_MESSAGE_LENGTH]
        message_text = "\n".join(batch)
        try:
            await app.send_message(chat_id=chat_id, text=message_text)
        except MessageTooLong:
            # If the message is too long, split it into smaller batches recursively
            await send_messages_in_batches(chat_id, batch)

# Define the inline keyboard for the "Settings" command
settings_keyboard = InlineKeyboardMarkup([
    [InlineKeyboardButton("For Link", callback_data="for_link"), InlineKeyboardButton("For Info", callback_data="for_info")],
    [InlineKeyboardButton("For Info 2", callback_data="for_info2")]
])

# Add this line at the beginning of your code to create a dictionary to store user choices
user_choices = {}

# Define an event handler for new messages
@app.on_message(filters.command("start"))
async def settings_command_handler(client, message):
    # Reply to the user with a welcome message
    await message.reply_text("I Am Alive")

# Define the callback function for the "Settings" command
@app.on_message(filters.command("settings"))
async def settings_command_handler(client, message):
    await message.reply_text("Please select an option:", reply_markup=settings_keyboard)

# Define the callback function for the inline keyboard buttons
@app.on_callback_query()
async def callback_query_handler(client, query):
    user_id = query.from_user.id
    if query.data == "for_link":
        user_choices[user_id] = "for_link"
        message = "."
    elif query.data == "for_info":
        user_choices[user_id] = "for_info"
        message = "."
    elif query.data == "for_info2":
        user_choices[user_id] = "for_info2"
        message = "."
    await query.message.reply_text(message)

# Define the function to handle messages
@app.on_message(filters.text)
async def message_handler(client, message):
    user_id = message.from_user.id
    user_choice = user_choices.get(user_id, None)
    # Check if the user has selected "Info 1"
    if user_choice == "for_link" and message.text.startswith("480p Link -") and "720p Link -" in message.text and "1080p Link -" in message.text:
        # Split the message into lines
        lines = message.text.split(" ")
        # Initialize the variables
        link_480p = ""
        link_720p = ""
        link_1080p = ""
        # Loop through the lines and extract the links
        for line in lines:
            if line.startswith("480p Link -"):
                link_480p = line.replace("480p Link - ", "")
            elif line.startswith("720p Link -"):
                link_720p = line.replace("720p Link - ", "")
            elif line.startswith("1080p Link -"):
                link_1080p = line.replace("1080p Link - ", "")
        # Define the message for "Info 1"
        message_text = f"Your link is ready:\n\n| 480p | {link_480p}\n| 720p | {link_720p}\n| 1080p | {link_1080p}"
        # Send the message to the user
        await message.reply_text(message_text)
    # Check if the user has sent the required information for "Info 2"
    elif user_choice == "for_info" and message.text.startswith("Poster -") and "Name:" in message.text and "Release info:" in message.text and "Language:" in message.text and "Quality:" in message.text and "Mb/gb size:" in message.text and "Genre:" in message.text and "Story -" in message.text and "480p Link -" in message.text and "720p Link -" in message.text and "1080p Link -" in message.text:
     # Split the message into lines
     lines = message.text.split("\n")
    # Initialize the variables
     Poster = ""
     Name = ""
     Release_info = ""
     Language = ""
     Quality = ""
     total_size = ""
     Genre = ""
     Story = ""
     l480p = ""
     l720p = ""
     l480p = ""
     link1 = ""
    # Loop through the lines and extract the links
     for line in lines:
        if line.startswith("Poster -"):
            Poster = line.replace("Poster - ", "").strip()
        elif line.startswith("Name:"):
            Name = line.replace("Name: ", "").strip()
        elif line.startswith("Release info:"):
            Release_info = line.replace("Release info: ", "").strip()
            yearinfo = [s.strip() for s in Release_info.split()]
        elif line.startswith("Language:"):
            Language = line.replace("Language: ", "").strip()
        elif line.startswith("Quality:"):
            Quality = line.replace("Quality: ", "").strip()
        elif line.startswith("Mb/gb size:"):
            total_size = line.replace("Mb/gb size: ", "").strip()
        elif line.startswith("Genre:"):
            Genre = line.replace("Genre: ", "").strip()
        elif line.startswith("Story -"):
            Story = line.replace("Story - ", "").strip()
        elif line.startswith("Mb/gb size:"):
            l480p = line.replace("480p Link - ", "").strip()
        elif line.startswith("Genre:"):
            l720p = line.replace("720p Link - ", "").strip()
        elif line.startswith("Story -"):
            l1080p = line.replace("1080p Link - ", "").strip()
        elif line.startswith("Link 1 -"):
            link1 = line.replace("Link 1 - ", "").strip()
    # Split the total_size string into individual sizes
     sizes = total_size.split(" ")
     size_480p = sizes[0]
     size_720p = sizes[1]
     size_1080p = sizes[2]

     message_text = f"`{Name} {yearinfo[2]} {Language} {Quality}`\n1:1 Size `{size_480p}` `{size_720p}` `{size_1080p}`\n\n`{Poster}`\nName `{Name}`\nYear Info `{Release_info}`\nLanguage `{Language}`\nQuality `{Quality}`\nSize `{total_size}`\nGenres `{Genre}`\n\nStory `{Story}`"

     app.set_parse_mode(enums.ParseMode.MARKDOWN)
     await message.reply_text(message_text, disable_web_page_preview=True)

    elif user_choice == "for_info2" and message.text.startswith("Poster -") and "Name:" in message.text and "Release info:" in message.text and "Language:" in message.text and "Quality:" in message.text and "Mb/gb size:" in message.text and "Genre:" in message.text and "Story -" in message.text and "480p Link -" in message.text and "720p Link -" in message.text:
     # Split the message into lines
     ilines = message.text.split("\n")
    # Initialize the variables
     iPoster = ""
     iName = ""
     iRelease_info = ""
     iLanguage = ""
     iQuality = ""
     itotal_size = ""
     iGenre = ""
     iStory = ""
     i480p = ""
     i720p = ""
     ilink1 = ""

    # Loop through the lines and extract the links
     for iline in ilines:
        if iline.startswith("Poster -"):
            iPoster = iline.replace("Poster - ", "").strip()
        elif iline.startswith("Name:"):
            iName = iline.replace("Name: ", "").strip()
        elif iline.startswith("Release info:"):
            iRelease_info = iline.replace("Release info: ", "").strip()
            iyearinfo = [s.strip() for s in iRelease_info.split()]
        elif iline.startswith("Language:"):
            iLanguage = iline.replace("Language: ", "").strip()
        elif iline.startswith("Quality:"):
            iQuality = iline.replace("Quality: ", "").strip()
        elif iline.startswith("Mb/gb size:"):
            itotal_size = iline.replace("Mb/gb size: ", "").strip()
        elif iline.startswith("Genre:"):
            iGenre = iline.replace("Genre: ", "").strip()
        elif iline.startswith("Story -"):
            iStory = iline.replace("Story - ", "").strip()
        elif iline.startswith("Genre:"):
            i480p = iline.replace("480p Link - ", "").strip()
        elif iline.startswith("Story -"):
            i720p = iline.replace("720p Link - ", "").strip()
        elif iline.startswith("Link 1 -"):
            ilink1 = iline.replace("Link 1 - ", "").strip()
    # Split the total_size string into individual sizes
     isizes = itotal_size.split(" ")
     isize_480p = isizes[0]
     isize_720p = isizes[1]

    # Define the message for "Info 2"
     imessage_text = f"`{iName} {iyearinfo[2]} {iLanguage} {iQuality}`\n1:1 Quality `{isize_480p}` `{isize_720p}`\n\n`{iPoster}`\nName `{iName}`\nYear Info `{iRelease_info}`\nLanguage `{iLanguage}`\nQuality `{iQuality}`\nSize `{itotal_size}`\nGenres `{iGenre}`\n\nStory `{iStory}`"

     app.set_parse_mode(enums.ParseMode.MARKDOWN)
     await message.reply_text(imessage_text, disable_web_page_preview=True)

# Start the bot
p999 = "iam alive"
print(p999)
app.run()


import PIL.Image
import numpy
import numpy as np
from matplotlib import pyplot as plt
from sklearn.preprocessing import normalize

import sys
import nimfa
import PIL

line = ">QBQ33928 A/Canis lupus familiaris/USA/000915/2018 2018/01/03 PB2"
headers = []

class header:
    def __init__(self, accession, country, date):
        self.accession = accession
        self.country = country
        self.date = date

def read_sequences(infile: str) -> list:
    sequences = []
    working = ""
    with open(infile, 'r') as inf:
        for line in inf:
            # line description  of new sequence
            if ">" in line:

                ln = line.split(" ")
                accession = ln[0]
                date = ln[-2]

                country = "".join(ln[1:-2]).split("/")[2]

                headers.append( header(accession, country, date))
                if len(working) == 759:
                    sequences.append(list(working))
                working = ""
            # Line part of sequence
            else:
                working += line.rstrip()
    return sequences[1:]

def build_mother(seqs: [[]]):
    ln = len(seqs[0])

    mother = []
    for index in range(ln):
        count = {}
        for sequence in seqs:
            try:
                count[sequence[index]] += 1
            except KeyError:
                count[sequence[index]] = 1
        mother.append(max(count, key=count.get))
    return mother

def build_binary(mother, sequence):
    return [0 if sequence[i] == mother[i] else 1 for i in range(len(mother))]

"""
Returns Index of Ocurrence? for items in a list
"""

def ioc(li: list) -> {}:
    count = {}
    for item in li:
        try:
            count[item] += 1
        except KeyError:
            count[item] = 1
    return sorted(count.items(), key=lambda x: x[1])

def displayMatrix(matrix, title = "default"):
    displayData = matrix

    im = PIL.Image.fromarray(displayData)

    im.show(title=title)

def estimate_rank(model):
    rank_cands = range(1,40)
    summary = model.estimate_rank(rank_range=range(1, 40))
    rss = [summary[rank]['rss'] for rank in rank_cands]
    coph = [summary[rank]['cophenetic'] for rank in rank_cands]
    disp = [summary[rank]['dispersion'] for rank in rank_cands]
    spar = [summary[rank]['sparseness'] for rank in rank_cands]
    spar_w, spar_h = zip(*spar)
    evar = [summary[rank]['evar'] for rank in rank_cands]

   # plt.plot(rank_cands, rss, 'o-', label='RSS', linewidth=2)
    plt.plot(rank_cands, coph, 'o-', label='Cophenetic correlation', linewidth=2)
    plt.plot(rank_cands, disp, 'o-', label='Dispersion', linewidth=2)
    plt.plot(rank_cands, spar_w, 'o-', label='Sparsity (Basis)', linewidth=2)
    plt.plot(rank_cands, spar_h, 'o-', label='Sparsity (Mixture)', linewidth=2)
    plt.plot(rank_cands, evar, 'o-', label='Explained variance', linewidth=2)
    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=3, numpoints=1)
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.show()
    plt.plot(rank_cands, rss, 'o-', label='RSS', linewidth=2)
    plt.show()
    print(rss)

seqs = read_sequences("data/FASTAP2.fa")
mother = build_mother(seqs)

bins = [build_binary(mother, s) for s in seqs]

#Write out our matrix to a CSV for analysis later if desired
with open("bins.csv", "w") as fout:
    print(f"""Accession,Date,Country,{','.join([f"Position {i}" for i in range(759)])}""", file=fout)
    for header, bin in zip(headers, bins):
        print(f"{header.accession},{header.date},{header.country},{','.join([str(i) for i in bin])}", file=fout)

#Print out matrix
data = numpy.array(bins)
displayMatrix(numpy.array([[255 * x for x in bi] for bi in bins], dtype="uint8"))

numpy.set_printoptions(threshold=sys.maxsize)
bmf = nimfa.Bmf(data, n_run=40,  max_iter=20, n_iter = 15, rank=9)

#Estimate rank if need be
#estimate_rank(bmf)
bmf.rank=9
bmf_fit = bmf()

np.set_printoptions(threshold=np.inf)
print(bmf_fit.fit.W)
with open("W.txt", "w") as fout:
    print(bmf_fit.fit.W, file=fout)
displayMatrix(255 - bmf_fit.fit.W * 255)
displayMatrix(255 - bmf_fit.fit.H * 255)
displayMatrix(255 - bmf_fit.fit.W / bmf_fit.fit.W.max() * 255)
displayMatrix(255 - bmf_fit.fit.H / bmf_fit.fit.H.max() * 255)


menu = {"air-film":{"title":"Air Film",
                      "description":"This feature length movie about air will enlighten your nose and will be a joy for the whole family.",
                      "price":9.95,
                      "kj":1090,
                      "image":"air-movie-poster.jpg"},
        "volcano-air":{"title":"Volcano Air",
                      "description":"Amazing, hot, and delectible air sourced from Mount Saint Helens in it's eruption in the 1980's.",
                      "price":18.90,
                      "kj":5000,
                      "image":"volcano-air.jpg"},
        "cancer-air":{"title":"Cancer Air",
                      "description":"Makes you seem cool, eventually too cool and you'll get lung cancer, but that's okay because this air tastes really good.",
                      "price":8.95,
                      "kj":5219,
                      "image":"smoking-person.jpg"},
        "gas-chamber":{"title":"Chamber Air",
                      "description":"Taken from the Germans at the time of WWII, this air is composed of pure carbon monoxide. Perfect for those Jewey nights.",
                      "price":9.80,
                      "kj":4309,
                      "image":"gas-chambers.jpg"},
        "funny-air":{"title":"Funny Air",
                      "description":"Using a unique structuring of air, this air looks funny. If you ever want to make someone laugh, buy this.",
                      "price":10,
                      "kj":3890,
                      "image":"laughing-person.jpg"},
        "cow-air":{"title":"Cow Air",
                      "description":"Otherwise known as methane, this air has a tangy taste and contributes to climate change. Which you can stop if you buy it from us.",
                      "price":22.95,
                      "kj":5180,
                      "image":"cow.jpg"},

}

customisations = {"sizes":{"Small":0.00,
                           "Regular":2.00,
                           "Family":5.00
                           },
                  "crusts":{"Thin":0.00,
                            "Heavy":4.90,
                            "Compressed":5.00,
                            "Spice Blend":1.95,
                            "Classic":0.00,
                            "Deep Pan":0.50,
                            "Cheesy":1.95,
                            "Gluten Free":2.95
                            },
                  "sauces":{"Tomato":0.00,
                            "Creme Fraiche":1.00,
                            "Hickory Barbeque":0.75,
                            "Sezchaun Sauce":5.00
                            },
                  "extras":{"Anchovies":2.00,
                            "Rasher Bacon":2.00,
                            "Italian Sausage":2.00,
                            "Chilli Flakes":0.00,
                            "Spring Onion":0.50,
                            "Vegan Cheese (Swap)":1.00
                            }
                  }


import json
import subprocess

import yaml
from yaml import SafeLoader

from constants import pass_status, fail_status, service_name, cloud_sql, rule_id, cloud_sql_rule, status_const, message, \
    compliant, cloud_sql_public, priority, high_priority, entity

def get_cloud_sql_list(project_id):
    method_name = get_cloud_sql_list.__name__
    sql_list = []
    try:
        list_ = subprocess.getoutput('gcloud sql instances list --format=json --project' + ' ' + project_id)
        json_list = json.loads(list_)
        sql_list = [i['name'] for i in json_list]
        print(f'sql_list {sql_list}')
    except Exception as e:
        print(f'Exception occurred in {method_name} method exception is{e}')
    return sql_list

def get_ip_config(sql_name):
    method_name = get_ip_config.__name__
    ip_config = []
    try:
        ip = subprocess.getoutput("gcloud sql instances describe" + " " + sql_name + " " + "--format=json")
        ip_json = json.loads(ip)
        if "authorizedNetworks" in ip_json['settings']['ipConfiguration'].keys():
            authorized_networks = ip_json['settings']['ipConfiguration']['authorizedNetworks']
            ip_config = [i['value'] for i in authorized_networks]
            print(f'public_ip is  {ip_config}')
        else:
            ip_config = ip_json['settings']['ipConfiguration']['privateNetwork']
            print(ip_config)
    except Exception as e:
        print(f'Exception occurred in {method_name} method exception is{e}')
    return ip_config

def get_yaml_data_sql(project_id,file_name):
    method_name = get_yaml_data_sql.__name__
    ip = []
    try:
        #file_name = '../rule_yaml/' + project_id + '_cloud_sql_' + 'rules.yaml'
        print(f'filename is {file_name}')
        with open(file_name) as f:
            data = yaml.load(f, Loader=SafeLoader)
            print(f'yaml data is {data} ')
            ip = next(key['public_ip'] for key in data["rules"])
            print(f'ip value to compare is {ip}')
    except Exception as e:
        print(f'Exception occurred in {method_name} method exception is{e}')
    return ip

def check_public_ip(sql_list, project_id,file_name):
    method_name = check_public_ip.__name__
    status_list = []
    try:
        yaml_ = get_yaml_data_sql(project_id, file_name)
        for i in sql_list:
            public_ip = get_ip_config(i)
            status = fail_status if (yaml_ in public_ip) else pass_status
            status_dict = {service_name: cloud_sql, rule_id: cloud_sql_rule, entity: i,priority: high_priority, status_const: status,
                           message: compliant if status == pass_status else cloud_sql_public}
            status_list.append(status_dict)
    except Exception as e:
        print(f'Exception occurred in {method_name} method exception is{e}')
    return status_list


import os
from .utils import (
    create_ccxt_client,
)
from .logger import create_logger
from .bot import Bot

def start():
    exchange = os.getenv('CCXT_EXCHANGE')
    api_key = os.getenv('CCXT_API_KEY')
    api_secret = os.getenv('CCXT_API_SECRET')
    subaccount = os.getenv('CCXT_SUBACCOUNT')
    leverage = float(os.getenv('ALPHASEA_LEVERAGE'))
    agent_base_url = os.getenv('ALPHASEA_AGENT_BASE_URL')
    log_level = os.getenv('ALPHASEA_LOG_LEVEL')

    logger = create_logger(log_level)

    client = create_ccxt_client(
        exchange=exchange,
        api_key=api_key,
        api_secret=api_secret,
        subaccount=subaccount,
    )

    bot = Bot(
        client=client,
        logger=logger,
        leverage=leverage,
        agent_base_url=agent_base_url
    )
    bot.run()

start()


#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
from seata.rm.datasource.executor.Executor import SelectForUpdateExecutor

class MySQLSelectForUpdateExecutor(SelectForUpdateExecutor):

    def __int__(self, cursor_proxy, cursor_callback, sql_recognizer):
        self.cursor_proxy = cursor_proxy
        self.cursor_callback = cursor_callback
        self.sql_recognizer = sql_recognizer


import pandas as pd
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils import data
from torchvision import transforms
from torch.autograd import Variable
from torch.utils.data import TensorDataset
from sklearn.model_selection import train_test_split

from preprocess import *
from data import *

import matplotlib.pyplot as plt

class GRU(torch.nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim, dropout, n_layers):
        super(GRU, self).__init__()

        self.hidden_dim = hidden_dim
        self.n_layers = n_layers
        self.output_dim = output_dim
        self.dropout = dropout

        self.gru = torch.nn.GRU(input_dim, hidden_dim, n_layers, dropout=dropout, batch_first=True)
        self.fc1 = torch.nn.Linear(hidden_dim, 32)
        self.fc2 = torch.nn.Linear(32, 32)
        self.fc3 = torch.nn.Linear(32, output_dim)
        self.relu = torch.nn.ReLU(inplace=False)
        self.softmax = torch.nn.Softmax()

    def forward(self, x):

        output, hidden = self.gru(x)
        output = self.relu(output)
        output = self.fc1(output)
        # output = self.relu(output)
        output = self.fc2(output)
        # output = self.relu(output)
        output = self.fc3(output)
        # output = self.softmax(output)
        output = output[:, -1, :]

        return output

def spilt_data(BATCH_SIZE):
    x, y = getdata(BATCH_SIZE)
    train_x, test_x, train_y, test_y = train_test_split(x, y, test_size=0.2)
    # train_x, test_x, train_y, test_y = torch.from_numpy(train_x), torch.from_numpy(test_x), torch.from_numpy(train_y), torch.from_numpy(test_y)
    # return train_x, test_x, train_y, test_y
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    train_x, train_y = torch.from_numpy(train_x).to(device), torch.from_numpy(train_y).to(device)
    test_x, test_y = torch.from_numpy(test_x).to(device), torch.from_numpy(test_y).to(device)
    # return train_x, train_y
    # print(train_x.device)
    torch_train_dataset = data.TensorDataset(train_x, train_y)
    torch_test_dataset = data.TensorDataset(test_x, test_y)

    trainloader = data.DataLoader(
        dataset=torch_train_dataset,
        batch_size=BATCH_SIZE,
        shuffle=False,
        # num_workers=2
        worker_init_fn=seed_worker
    )
    """
    cuda0 = torch.device('cuda:0')
    for i, x in enumerate(trainloader):
        x = x.to(cuda0)
        # y = y.to(cude0)
    """
    testloader = data.DataLoader(
        dataset=torch_test_dataset,
        batch_size=BATCH_SIZE,
        shuffle=False,
        worker_init_fn=seed_worker
    )

    return trainloader, testloader

def seed_worker(worker_id):
    worker_seed = torch.initial_seed() % 2**32
    numpy.random.seed(worker_seed)
    random.seed(worker_seed)

if __name__ == '__main__':

    torch.manual_seed(0)
    BATCH_SIZE = 32
    lr = 3e-4
    EPOCH = 300

    trainloader, testloader = spilt_data(BATCH_SIZE)
    # train_x, test_x, train_y, test_y = spilt_data(lookforward=5)
    # train_x, train_y = spilt_data(BATCH_SIZE)

    # print(train_x)
    # print(train_x.size())

    model = GRU(
        input_dim=7,
        hidden_dim=32,
        output_dim=7,
        dropout=0,
        n_layers=3
        )

    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = model.to(device)
    model = model.double()
    # print(model)

    criterion = torch.nn.MSELoss()
    # criterion = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)

    model.train()
    train_loss = []
    train_acc = []

    for epoch in range(EPOCH):
        # print('\n train Epoch: %d' % epoch)
        # model.train()
        train_loss_tmp = 0
        train_loss_avg = 0
        correct = 0
        total = 0
        loss = 0
        # inputs, targets = train_x.to(device), train_y.to(device)
        for batch_idx, (inputs, targets) in enumerate(trainloader):
            # print(inputs)
            # print(targets.shape)
            # print(targets)
            # if (batch_idx==10):break
            # print(batch_idx)
            optimizer.zero_grad()
            outputs = model(inputs)
            #print(outputs)
            outputs.to(device)
            # print(outputs.device)
            # print(targets.device)
            loss = criterion(outputs, targets)
            loss.backward()
            optimizer.step()
            # print(loss.item())

            # train_loss_tmp += loss.item()
            # print(targets)
            # print(targets.shape)
            # print(outputs)
            # print(output.shape)
            # print(torch.max(outputs, 1))
            _, predicted = torch.max(outputs, 1)
            # print(predicted)
            # print(targets)
            # total += targets.size(0)
            # print(torch.eq(targets, predicted))
            # correct += predicted.eq(targets).sum().item()
            # train_loss_avg = train_loss_tmp / (batch_idx + 1)
        print("mode:training loss:", loss.item() )
        train_loss.append(loss.item())
        # train_acc.append(100. * correct / total)
        # print('\n -----train Epoch Over: %d------\n' % epoch)
        # print(len(trainloader), 'Loss: %.8f | Acc: %.8f%% (%d/%d)'
            # % (train_loss_avg, 100. * correct / total, correct, total))
        # print(output)
        """
        inputs, targets = next(iter(trainloader))

        optimizer.zero_grad()
        outputs = model(inputs)

        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()

        print(loss)
       """
    # np.delete(train_loss, (0,1))
    # finish training
    model.eval()
    test_loss = []
    for epoch in range(EPOCH):
        with torch.no_grad():
            loss = 0
            outputs = 0
            for batch_idx, (inputs, targets) in enumerate(testloader):
                outputs = model(inputs)
                outputs.to(device)
                loss = criterion(outputs, targets)
            print("mode:eval loss:", loss.item() )
            test_loss.append(loss.item())

    train_loss = np.delete(train_loss, (0,1,2,3))
    test_losee = np.delete(test_loss, (0,1,2,3))
    plt.plot(train_loss, 'r', label='train_loss')
    # plt.plot(test_loss, 'b', label='test_loss')
    plt.show()
    plt.savefig("out2.jpg")


from sklearn.model_selection import cross_val_score
from sklearn.model_selection import StratifiedKFold
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
from sklearn.linear_model import Perceptron
from sklearn.linear_model import RidgeClassifier
from sklearn.svm import SVC

from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from lightgbm import LGBMClassifier
from xgboost import XGBClassifier
from imxgboost.imbalance_xgb import imbalance_xgboost

def cross_val(Classifier, x_train, y_train):
    skf = StratifiedKFold(n_splits=5)
    accuracies = cross_val_score(estimator=Classifier, X=x_train, y=y_train, cv=skf)
    print(accuracies)
    print("Accuracy: {:.2f} %".format(accuracies.mean()*100))

def conf_mat(model, x_val, y_val):
    y_pred = model.predict(x_val)

    # --classification report --
    print('\nClassification Report:')
    print(metrics.classification_report(y_val, y_pred, labels=[0,1]))

    # --confusion matrix
    print('\nConfusion Matrix:')
    print(confusion_matrix(y_val, y_pred))
    print('---------------------------------------------------------------------------------------')

class MachineLearningModels:

    def ml_model(x_train, y_train, x_val, y_val):

        print('Logistic Regression: \n')
        LR = LogisticRegression(random_state = 0,solver='liblinear')
        LR.fit(x_train, y_train)
        cross_val(LR, x_train, y_train)
        conf_mat(LR, x_val, y_val)

        print('Gaussian Naive Bayes: \n')
        GNB = GaussianNB()
        GNB.fit(x_train, y_train)
        cross_val(GNB, x_train, y_train)
        conf_mat(GNB, x_val, y_val)

        print('KNeighbors Classifier: \n')
        KNC = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)
        KNC.fit(x_train, y_train)
        cross_val(KNC, x_train, y_train)
        conf_mat(KNC, x_val, y_val)

        print('SGD Classifier: \n')
        sgdc = SGDClassifier(max_iter=1000, tol=0.01)
        sgdc.fit(x_train, y_train)
        cross_val(sgdc, x_train, y_train)
        conf_mat(sgdc, x_val, y_val)

    #     print('Perceptron Classifier: \n')
    #     Perceptron = Perceptron()
    #     Perceptron.fit(x_train, y_train)
    #     cross_val(Perceptron, x_train, y_train)
    #     conf_mat(Perceptron, x_val, y_val)

        print('Ridge Classifier: \n')
        RC = RidgeClassifier()
        RC.fit(x_train, y_train)
        cross_val(RC, x_train, y_train)
        conf_mat(RC, x_val, y_val)

        print('Decision Tree Classifier: \n')
        DT = DecisionTreeClassifier()
        DT.fit(x_train, y_train)
        cross_val(DT, x_train, y_train)
        conf_mat(DT, x_val, y_val)

        print('Random Forest Classifier: \n')
        RFC = RandomForestClassifier(n_estimators = 10, criterion = "gini", random_state = 0)
        RFC.fit(x_train, y_train)
        cross_val(RFC, x_train, y_train)
        conf_mat(RFC, x_val, y_val)

        print('Ada Boost Classifier: \n')
        ABC = AdaBoostClassifier(n_estimators=100)
        ABC.fit(x_train,y_train)
        cross_val(ABC, x_train, y_train)
        conf_mat(ABC, x_val, y_val)

        print('LightGBM Classifier : \n')
        lgb = LGBMClassifier()
        lgb.fit(x_train,y_train)
        cross_val(lgb, x_train, y_train)
        conf_mat(lgb, x_val, y_val)

        print('XGBoost Classifier: \n')
        XGB = XGBClassifier()
        XGB.fit(x_train,y_train)
        cross_val(XGB, x_train, y_train)
        conf_mat(XGB, x_val, y_val)

#         print('SVC-linear Classifier: \n')
#         SVCl = SVC(kernel = 'linear', random_state = 0)
#         SVCl.fit(x_train, y_train)
#         cross_val(SVCl, x_train, y_train)
#         conf_mat(SVCl, x_val, y_val)

#         print('SVC-rbf Classifier: \n')
#         SVC = SVC(kernel = 'rbf', random_state = 0)
#         SVC.fit(x_train, y_train)
#         cross_val(SVC, x_train, y_train)
#         conf_mat(SVC, x_val, y_val)

        print('Imbalance_XGBoost: \n')
        imb_xgb = imbalance_xgboost(special_objective='focal',focal_gamma=1.3)
        imb_xgb.fit(x_train.values, y_train)
        cross_val(imb_xgb, x_train.values, y_train)

        y_preds = imb_xgb.predict_determine(x_val.values)
        # --classification report --
        print('Classification Report')
        print(metrics.classification_report(y_val, y_preds, labels=[0,1]))

        # --confusion matrix
        print('Confusion Matrix:')
        print(confusion_matrix(y_val, y_preds))


"""
Definition of general logger
"""
import logging
import os
from app_lib.utils.files_utils import transform_path

def get_log(log_name):
    """
    Returns set logger
    :param log_name:
    :return:
    """
    logging.basicConfig(
        level=logging.INFO,
        filename=str(os.getcwd()).split('app_lib')[0] + transform_path('/app_lib/log.txt'),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    return logging.getLogger(log_name)


def LCstring(string1,string2):
    len1 = len(string1)
    len2 = len(string2)
    res = [[0 for i in range(len1+1)] for j in range(len2+1)]
    result = 0
    for i in range(1,len2+1):
        for j in range(1,len1+1):
            if string2[i-1] == string1[j-1]:
                res[i][j] = res[i-1][j-1]+1
                result = max(result,res[i][j])
    return result
n = int(input())
strs = []
while n > 0:
    n -= 1
    strs.append(input())
min = 99999
for i in range(len(strs)):
    for j in range(i+1, len(strs)):
                   temp = LCstring(strs[i], strs[j])
                   if temp < min:
                       min = temp
print(min)


import pygame

class Display:
    # Instance.
    __instance = None

    @staticmethod
    def getInstance():
        """
        Instance if not exist
        """
        if Display.__instance == None:
            Display()
        return Display.__instance

    def __init__(self):
        """ Virtually private constructor. """
        if Display.__instance != None:
            raise Exception("This class is a singleton!")
        else:
            Display.__instance = self

    def init_pygame(self, macgyver, maps, grid):
        self.pygame = pygame
        self.window = pygame.display.init()
        self.pygame.display.set_caption('MacGyver')
        self.screen = pygame.display.set_mode((300, 320))
        self.font_init = pygame.font.init()

        self.macgyver = macgyver
        self.maps = maps
        self.grid = grid

    def update(self):
        self.pygame.display.update()

    def set_text(self, text):
        self.screen.fill((255, 255, 255))
        self.draw_text(text)

    def draw_text(self, text):
        main_font = self.pygame.font.SysFont("Arial", 20)
        text_surf, text_rect = self.text_objects(text, main_font)
        text_rect.center = (150, 310)
        self.screen.blit(text_surf, text_rect)

    def text_objects(self, text, font):
        text_surface = font.render(text, True, (0, 0, 0))
        return text_surface, text_surface.get_rect()

    def draw_tile(self, image, position_x, position_y):
        self.screen.blit(self.pygame.image.load(image), [position_x * 20, position_y * 20])

    def listener(self):
        playing = True

        while playing:
            for event in self.pygame.event.get():
                if event.type == self.pygame.QUIT:
                    playing = False
                elif event.type == self.pygame.KEYDOWN:
                    position_macgyver = self.grid.get_position(self.maps, 'M')
                    if event.key == self.pygame.K_RIGHT:
                        self.maps = self.macgyver.move(self.maps, 'r', position_macgyver)
                    if event.key == self.pygame.K_LEFT:
                        self.maps = self.macgyver.move(self.maps, 'l', position_macgyver)
                    if event.key == self.pygame.K_DOWN:
                        self.maps = self.macgyver.move(self.maps, 'd', position_macgyver)
                    if event.key == self.pygame.K_UP:
                        self.maps = self.macgyver.move(self.maps, 'u', position_macgyver)

                    # Redraw
                    self.grid.draw(self.maps)
                    self.update()


strLst = eval(input())
strLst.sort(key = lambda x:len(x))
word = [strLst[0]]
compound = []
for i in range(1,len(strLst)):
    temp = strLst[i]
    for ref in word:
        temp = temp.replace(ref,'')
    if(temp != ''):
        word.append(strLst[i])
        word.sort(key = lambda x:-len(x))
    else:
        compound.append(strLst[i])
compound.sort()
print(compound)


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        l = list()
        def solve(tot,i,l,ds):
            if tot<0: return
            if i>=len(candidates): return
            if tot == 0:
                l.append(tuple(ds))
                return
            ds.append(candidates[i])
            solve(tot-candidates[i],i,l,ds)
            ds.pop()
            solve(tot,i+1,l,ds)
        solve(target,0,l,[])
        return l


'''
Created on 25 Feb 2022

@author: rob
'''
import tkinter as tk

class HelpWindow(object):
    '''
    Display a help window
    '''

    def __init__(self, root, commands):
        '''
        Constructor
        '''
        self.window = tk.Toplevel(root)
        help_list = []
        for command in commands:
            func, termonly, helptext = commands[command]
            auxtext = "(Terminal only)" if termonly else ""
            auxtext2 = "[NOT IMPLEMENTED YET]" if func is None else ""
            help_list.append(command.decode('utf8') + "\t" + helptext + " " + auxtext + " " + auxtext2)

        label_text = "\n".join(help_list)
        label= tk.Label(self.window, text= label_text, font= ('Aerial', 17), justify=tk.LEFT)
        label.pack(pady=20)
        self.window.deiconify()
        self.window.title("FFControlPanel Help")


import numpy as np
import csv
import os
import cv2

import pylib
import imlib as im

from tqdm import tqdm
from sklearn.utils.extmath import softmax
import data

def check_to_output(global_args, epoch, it, it_per_epoch):
    result = True

    if (global_args._experiment_method == "train"):
        if not (((epoch + 1) % 2 == 0) and (it % it_per_epoch == 0)):
            result = False
        test_dir = ''
    else:
        test_dir = '/sample_test_data/'

    return result, test_dir

def display(epoch, it, it_in_epoch, it_per_epoch, t):
    if it % it_per_epoch == 0:
        print("Epoch: (%3d) (%5d/%5d) Time: %s!" % (epoch, it_in_epoch, it_per_epoch, t))

def save(epoch, it, it_in_epoch, it_per_epoch, saver, sess, ckpt_dir):
    if (epoch % 2 == 0) and (it % it_per_epoch == 0) and (epoch != 0):
        save_path = saver.save(sess, '%s/Epoch_(%d)_(%dof%d).ckpt' % (ckpt_dir, epoch, it_in_epoch, it_per_epoch))
        print('Model is saved at %s!' % save_path)

def draw_test_image_digits(global_args, datacfg, epoch, it, it_in_epoch, it_per_epoch,
                           original_labels_ori, original_images_list, b_sample_ipt_list,
                           sess, colorChannel, x_sample, xa_sample, _b_sample, data_channel_test):

    result, test_dir = check_to_output(global_args, epoch, it, it_per_epoch)
    if not result:
        return

    for image_range in range(len(original_labels_ori)):
        indexList = list()
        original_images = original_images_list[image_range]

        # for whole data
        for _ in range(100):
            indexList.append(_)

        # Add black line
        x_sample_opt_list = [original_images[indexList], np.full((len(indexList),
                                                                global_args.img_size,
                                                                global_args.img_size // 10, colorChannel), -1.0)]

        b_sample_ipt_list_extract = list()
        for idx in range(len(b_sample_ipt_list[image_range])):
            b_sample_ipt_list_extract.append(b_sample_ipt_list[image_range][idx][indexList]) #for absolute

        for i, b_sample_ipt in enumerate(b_sample_ipt_list_extract):
            ganImList = sess.run(x_sample, feed_dict={xa_sample: original_images[indexList], _b_sample: b_sample_ipt})
            x_sample_opt_list.append(ganImList)

        save_dir = global_args.output_path + '/%s/' % global_args.experiment_name + test_dir
        pylib.mkdir(save_dir)

        sample = np.concatenate(x_sample_opt_list, 2)
        im.imwrite(im.immerge(sample, len(indexList), 1), '%s/test[0-99].png' %(save_dir))


character = "/path/to/demo/text_recognition/__dictionary__/Scene_text_68.txt"

# dataset settings
dataset_type = 'DavarMultiDataset'

img_norm_cfg = dict(
    mean=[127.5], std=[127.5])

ppld = {
    'LMDB_Standard': 'LoadImageFromLMDB',  # open-source LMDB data

    # Davar dataset type
    'LMDB_Davar': 'RCGLoadImageFromLMDB',
    'File': 'RCGLoadImageFromFile',
    'Loose': 'RCGLoadImageFromLoose',
    'Tight': 'RCGLoadImageFromTight',
}

test_pipeline = [
    dict(type='LoadImageFromLMDB',
         character=character,
         sensitive=False,
         color_types=['gray'],
         fil_ops=True),
    dict(type='ResizeNormalize',
         size=(100, 32),
         interpolation=2,
         mean=[127.5],
         std=[127.5]),
    dict(type='DavarDefaultFormatBundle'),
    dict(type='DavarCollect',
         keys=['img'],
         meta_keys=[])]

testsets = [
    {
        'Name': 'IIIT5k',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IIIT5k_3000/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'SVT',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'SVT/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC03_860',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC03_860/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC03_867',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC03_867/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC13_857',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC13_857/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC13_1015',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC13_1015/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC15_1811',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC15_1811/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'IC15_2077',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'IC15_2077/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'SVTP',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'SVTP/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },
    {
        'Name': 'CUTE80',
        'FilePre': '/path/to/evaluation/',
        'AnnFile': 'CUTE80/',
        'Type': 'LMDB_Standard',
        'PipeLine': test_pipeline,
    },

]

# data setting
data = dict(
    imgs_per_gpu=400,  # 128
    workers_per_gpu=2,  # 2
    sampler=dict(
        type='BatchBalancedSampler',
        mode=0,),
    train=None,
    test=dict(
        type="DavarRCGDataset",
        info=testsets,
        batch_max_length=25,
        used_ratio=1,
        test_mode=True,
        pipeline=test_pipeline)

)

# runtime setting
dist_params = dict(backend='nccl')
launcher = 'none'


# -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 02:01:35 2015

@author: Kirill
"""

import sys

#from nltk.parse import stanford

import essayclasses.allessaysfile
import essayclasses.anessay
import essayclasses.asentence

exportedDB = 'data/all-essays.csv'

allEssaysFile =  essayclasses.allessaysfile.AllEssaysFile(exportedDB)
allEssays = allEssaysFile.essaysList()

modals = {'can','could','may', 'might', 'must', 'shall', 'should',
          'will', 'would'}

araM = 0
arQ = 0

nArM = 0
nArQ = 0

for anEssay in allEssays:
    thisEssay = essayclasses.anessay.AnEssay(anEssay)
    questions = thisEssay.getQuestions()

    for aQuestion in questions:
        if thisEssay.isArabic():
            arQ += 1
        else:
            nArQ += 1
        for aWord in aQuestion.split():
            for aux in modals:
                if aWord == aux:
                    if thisEssay.isArabic():
                        arM+= 1
                    else:
                        nArM += 1

print ('Arabic Modals per Question: ',arM/arQ)
print ('Non-Arabic Modals per Question: ',nArM/nArQ)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 12 17:12:31 2019

@author: dipankarbhattacharya
"""

# -*- coding: utf-8 -*-
"""
Created on Sat May  4 12:57:15 2019

@author: dbha483
"""

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 14 14:45:13 2018

@author: dipankarbhattacharya
"""
import os
import pdb

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from dateutil.parser import parse
from scipy.signal import find_peaks
from sklearn.linear_model import LinearRegression
from sklearn.isotonic import IsotonicRegression
from statsmodels.nonparametric.smoothers_lowess import lowess
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller, kpss
from scipy.signal import find_peaks, peak_prominences, kaiserord, lfilter, firwin, freqz

plt.close("all")

def cls():
    print("\n" * 50)

# clear Console
cls()

class TOFandWebCam():
    def __init__(self, path, stentName, name):
        self.path = path
        self.stentName = stentName
        self.name = name
        self.currWorkDir = os.getcwd()
        os.chdir(
            self.path
        )  # whenever we will create an instance of the class, the path will be set for it
        self.DataFrameExtractedDict = {}
        self.ArrayDict = {}
        self.MeanMigrationInfoDict = {}
        self.GradMeanMigrationInfoDict = {}

    def find_all(self):
        #        pdb.set_trace()
        self.files = [
            files[index]
            for root, dirs, files in sorted(os.walk(self.path, topdown=True))
            for index in range(len(files))
            if self.name in files[index]
        ]

    # =============================================================================
    # Method: Read csv files and create a dictinonary of arrays
    # =============================================================================
    def FileReading(self, indexFileToRead):
#        pdb.set_trace()
        for index in range(len(indexFileToRead)):

            if self.name == "TOF" or self.name == "QSR" or "Marker_detection" or "Peristalsis" or "ESR" or "RoS":
                filename1 = [
                    self.files[indexFileToRead[index]]
                ]  # ,self.files[indexFileToRead[1]],self.files[indexFileToRead[2]]]
                csv = pd.read_csv(filename1[0], sep=",", header=0)

                self.DataFrameExtractedDict[filename1[0].split(".")[0]] = csv

                TempArray = csv.to_numpy(dtype=np.dtype)
                self.ArrayDict[filename1[0].split(".")[0]] = np.array(
                    TempArray[2:, 1:], dtype="f"
                )
        # Returning the working directory to the  current working directory
        os.chdir(self.currWorkDir)

    # =============================================================================
    # Find mean and sd
    # =============================================================================

    def FindMeanSDAndRelDisp(self, *rangeDef):
        #       pdb.set_trace()
        #       MeanMigrationInfoArray=np.array()

        if not rangeDef:

            rangeDef = [
                self.ArrayDict[value].shape[0] for _, value in enumerate(self.ArrayDict)
            ]
            rangeDef = tuple([rangeDef])

        for c, value in enumerate(self.ArrayDict):

            TempArrayMean = np.mean(
                self.ArrayDict[value][0 : rangeDef[0][c], 2:], axis=1
            )

            MeanMigrationInfoArray = np.vstack(
                (
                    self.ArrayDict[value][0 : rangeDef[0][c], 0:2].T,
                    (TempArrayMean - TempArrayMean[0]),
                    np.std(self.ArrayDict[value][0 : rangeDef[0][c], 2:], axis=1),
                )
            ).T

            self.MeanMigrationInfoDict[value] = MeanMigrationInfoArray

    # =============================================================================
    # Compute a Gradient dictionasry of the MeanMigrationInfoDict
    # =============================================================================
    def ComputeGradient(self):
        #        pdb.set_trace()

        for c, value in enumerate(self.MeanMigrationInfoDict):

            GradMeanMigrationInfoArray = np.zeros(
                (self.MeanMigrationInfoDict[value].shape[0], 4)
            )

            GradMeanMigrationInfoArray[:, 2] = np.gradient(
                self.MeanMigrationInfoDict[value][:, 2],
                # self.MeanMigrationInfoDict[value][:,0],
                axis=0,
            )

            GradMeanMigrationInfoArray[:, 0] = self.MeanMigrationInfoDict[value][:, 0]
            GradMeanMigrationInfoArray[:, 1] = self.MeanMigrationInfoDict[value][:, 1]

            self.GradMeanMigrationInfoDict[value] = GradMeanMigrationInfoArray

# =============================================================================
#    Offline Filter Design and filter apply
# =============================================================================
    @staticmethod
    def DesignFilter(sample_rate = 100.0,tr_band=5,ripple_db = 60.0, cutoff_hz = 4):
        #------------------------------------------------
        # Create a FIR filter and apply it to x.
        #------------------------------------------------

        sample_rate = sample_rate
        # The Nyquist rate of the signal.
        nyq_rate = sample_rate / 2.0

        # The desired width of the transition from pass to stop,
        # relative to the Nyquist rate.  We'll design the filter
        # with a 5 Hz transition width.
        width = tr_band/nyq_rate

        # The desired attenuation in the stop band, in dB.
        ripple_db = ripple_db

        # Compute the order and Kaiser parameter for the FIR filter.
        N, beta = kaiserord(ripple_db, width)

        # The cutoff frequency of the filter.
        cutoff_hz = cutoff_hz

        # Use firwin with a Kaiser window to create a lowpass FIR filter.
        taps = firwin(N, cutoff_hz/nyq_rate, window=('kaiser', beta))

        return taps

    def ApplyFilter(self,taps=None,x=None):

        if taps is None:
            taps= cls.DesignFilter()

        self.ArrayDictFiltered={}
        if x is None:

            for c, value in enumerate(self.ArrayDict):

                x=self.ArrayDict[value]

                filtered_x= np.array([x[:,0]-x[0,0] if k==0 else lfilter(taps, 1, x[:,k]) for k in range(x.shape[1])]).T

                self.ArrayDictFiltered[value]=filtered_x

        else:
            #pdb.set_trace()

            filtered_x=np.zeros((x.shape))

            if x.shape[1]==2:

                filtered_x[:,0]=x[:,0]
                filtered_x[:,1] = lfilter(taps, 1, x[:,1])

            elif x.shape[1]==1:
                 filtered_x[:,0] = lfilter(taps, 1, x[:,0])
            elif x.shape[1]==3:
                #filtered_x[:,0]=x[:,0]
                filtered_x[:,0] = lfilter(taps, 1, x[:,0])
                filtered_x[:,1] = lfilter(taps, 1, x[:,1])
                filtered_x[:,2] = lfilter(taps, 1, x[:,2])

            return filtered_x

    @staticmethod
    def Detrending_diffrencing(x):

        detrended_x=np.zeros((x.shape))
        detrended_x[:,0]=x[:,0]

        for k in range(1,x.shape[1]):
            for i in range(1,x.shape[0]):
                detrended_x[i,k]=x[i,k]-x[i-1,k]

        return detrended_x

    @staticmethod
    def Detrending_isotonicRegression(x):

        ir = IsotonicRegression()

        ir_x= np.array([x[:,0]-x[0,0] if k==0 else x[:,k]-ir.fit_transform(x[:,0],x[:,k]) for k in range(x.shape[1])]).T
        #y_=ir.fit_transform(x[:,0],x[:,k]) Determines the isotonic regression curve
        #x[:,k]-y_ detrends the data from the ir curve
        return ir_x

    @staticmethod
    def DispPlotting(FigureNum,NumFig,*x,label=[],window=None):
        # pdb.set_trace()
        if window is None:
            window=(0,x[0].shape[0])

        ax=[FigureNum.add_subplot(NumFig,1,i) for i in range(1,NumFig+1)]

        color=['red','green','blue']

        ii=0

        for ctr,value in enumerate(x):

            if NumFig==len(x):
                ii=ctr
            elif NumFig==1:
                ii=NumFig-1

            initial,final=window[ii]

            ax[ii].plot(x[ctr][initial:final,0]-x[ctr][initial,0],
                 x[ctr][initial:final,0+1]-x[ctr][initial,0+1],
                 color[ctr],
                 alpha=0.7,
                 label=label[ctr])

            ax[ii].set_xlabel('Time (s)')
            ax[ii].set_ylabel('Displacement (mm)')

            ax[ii].legend()

    @staticmethod
    def MigrationPlotting(FigureNum, MeanMigrationInfoDict, *FileList):

#        pdb.set_trace()
        markerList = ["o", "s", "v", "h"]
        lineStyleList = [":", "-.", "--", "-"]
        #        colorList=['#9b1c31','#155b8a','k']
        colorList = ["#9b1c31", "royalblue", "gray", "darkorchid"]
        ax = FigureNum.add_subplot(111)
        for c, value in enumerate(FileList[0]):

            ax.errorbar(
                MeanMigrationInfoDict[value][0:50:3, 0],
                MeanMigrationInfoDict[value][0:50:3, 2],
                yerr=0*MeanMigrationInfoDict[value][0:50:3, 3],
                marker=markerList[c],
                ls=lineStyleList[c],
                color=colorList[c],
                label=FileList[0][c].split("_")[3][0:2] + " " + "mm.s$^{-1}$",
            )
            # FileList[0][c].split('_')[1]+' '+FileList[0][c].split('_')[3]
        #            ax.plot(self.MeanMigrationInfoDict[value][0:70:3,0],
        #                                     self.MeanMigrationInfoDict[value][0:70:3,2],
        #                                     label=FileList[0][c].split('_')[1]+' '+FileList[0][c].split('_')[3])
        #

        ax.set_xlabel(r"Peristalsis cycle", size=6)
        ax.set_ylabel(r"Relative mean displacement (mm)", size=6)
#        ax.set_ylim([-50, 50])
        ax.tick_params(labelsize=6)

        ax.legend(prop={"size": 6},
                   borderaxespad=0,
                   handlelength=1,
                   labelspacing=0.3,
                   columnspacing=0.2,
                   loc=0,
                   frameon=False)

        #        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        handles, labels = ax.get_legend_handles_labels()
        #        plt.title(FileList[0][c].split('_')[1])
        #        ax.legend.location='east'

        #Remove y-ticks
        ax.tick_params(top=False,
                        bottom=True,
                        left=True,
                        right=False,
                        labelleft=True,
                        labelbottom=True)
        #Remove borders
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)

        plt.show()
        return ax

    @staticmethod
    def MigrationSubPlotting(
        FigureNum, MeanMigrationInfoDict, GradMeanMigrationInfoDict, *FileList
    ):
        #        pdb.set_trace()
        ax = FigureNum.subplots(1, 2)
        #        ax2 = FigureNum.subplots(212,sharex=True)
        for c, value in enumerate(FileList[0]):

            ax[0].errorbar(
                MeanMigrationInfoDict[value][0:50:3, 0],
                MeanMigrationInfoDict[value][0:50:3, 2],
                yerr=MeanMigrationInfoDict[value][0:50:3, 3],
                marker="o",
                ls="--",
                label=FileList[0][c].split("_")[1] + " " + FileList[0][c].split("_")[3],
            )

            ax[1].errorbar(
                GradMeanMigrationInfoDict[value][0:50:3, 0],
                GradMeanMigrationInfoDict[value][0:50:3, 2],
                yerr=GradMeanMigrationInfoDict[value][0:50:3, 3],
                marker="o",
                ls="--",
                label=FileList[0][c].split("_")[1] + " " + FileList[0][c].split("_")[3],
            )
        #

        ax[1].set_xlabel(r"Peristalsis cycle", size=6)
        ax[0].set_ylabel("Relative mean \n displacement (mm)", size=6)
        ax[1].set_ylabel("Gradient mean \n displacement (mm/cycle)", size=6)
        ax[0].legend(prop={"size": 6},
                   borderaxespad=0,
                   handlelength=1,
                   labelspacing=0.1,
                   columnspacing=0.2,
                   loc=0,
                   frameon=False)
        #        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        handles, labels = ax[0].get_legend_handles_labels()
        #Remove y-ticks
        ax[0].tick_params(top=False,
                        bottom=False,
                        left=False,
                        right=False,
                        labelleft=True,
                        labelbottom=True)
        #Remove borders
        ax[0].spines['top'].set_visible(False)
        ax[0].spines['right'].set_visible(False)

        ax[1].tick_params(top=False,
                        bottom=False,
                        left=False,
                        right=False,
                        labelleft=True,
                        labelbottom=True)
        #Remove borders
        ax[1].spines['top'].set_visible(False)
        ax[1].spines['right'].set_visible(False)

        plt.show()

    #        ax.legend.location='east'

    @staticmethod
    def MigrationPlottingWithColor(
        FigureNum, MeanMigrationInfoDict, *FileList, **Color
    ):
        #        pdb.set_trace()
        ax = FigureNum.add_subplot(111)
        for c, value in enumerate(FileList[0]):

            ax.errorbar(
                MeanMigrationInfoDict[value][0:50:3, 0],
                MeanMigrationInfoDict[value][0:50:3, 2],
                yerr=MeanMigrationInfoDict[value][0:50:3, 3],
                marker="o",
                ls="--",
                label=FileList[0][c].split("_")[1] + " " + FileList[0][c].split("_")[3],
                color=Color["Color"][c],
            )

        #            ax.plot(self.MeanMigrationInfoDict[value][0:70:3,0],
        #                                     self.MeanMigrationInfoDict[value][0:70:3,2],
        #                                     label=FileList[0][c].split('_')[1]+' '+FileList[0][c].split('_')[3])
        #

        ax.set_xlabel(r"Peristalsis cycle", size=6)
        ax.set_ylim([-50, 50])
        ax.set_ylabel(r"Relative mean displacement (mm)", size=6)
        ax.legend(frameon=False)

        #        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

        handles, labels = ax.get_legend_handles_labels()
        #        ax.legend.location='east'
        #Remove y-ticks
        ax.tick_params(top=False,
                        bottom=False,
                        left=False,
                        right=False,
                        labelleft=True,
                        labelbottom=True)
        #Remove borders
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)

        plt.show()


from operation import *

def calculatorgame():
    result = 0
    while True:
        print('두 수를 입력해주세요')
        x , y = input().split()
        x = int(x)
        y = int(y)
        oper = ''

        print('1.더하기\n2.빼기\n3.곱하기\n4.나누기')
        choice = int(input())
        if choice == 1:
            result = add(x, y)
            oper = '+'
        elif choice == 2:
            res= subult (x, y)
            oper = '-'
        elif choice == 3:
            result = mul(x, y)
            oper = '*'
        elif choice == 4:
            result = div(x ,y)
            oper = '/'
        else:
            break  # 그 외의 경우 종료
        print(x , oper , y , ' = ', result)