"""tests cogeo_mosaic.overview."""

import json
import os

import rasterio
from click.testing import CliRunner
from rio_cogeo.cogeo import cog_validate
from rio_cogeo.profiles import cog_profiles

from cogeo_mosaic.mosaic import MosaicJSON
from cogeo_mosaic.overviews import create_overview_cogs

asset1 = os.path.join(os.path.dirname(__file__), "fixtures", "cog1.tif")
asset2 = os.path.join(os.path.dirname(__file__), "fixtures", "cog2.tif")
assets = [asset1, asset2]
mosaic_content = MosaicJSON.from_urls(assets).dict(exclude_none=True)

deflate_profile = cog_profiles.get("deflate")
deflate_profile.update({"blockxsize": 256, "blockysize": 256})

def test_overview_valid():
    """Should work as expected (create cogeo file)."""
    config = {
        "GDAL_DISABLE_READDIR_ON_OPEN": "TRUE",
        "GDAL_TIFF_INTERNAL_MASK": "TRUE",
        "GDAL_TIFF_OVR_BLOCKSIZE": "128",
    }
    runner = CliRunner()
    with runner.isolated_filesystem():
        with open("mosaic.json", "w") as f:
            f.write(json.dumps(mosaic_content))

        create_overview_cogs("mosaic.json", deflate_profile, config=config, threads=1)

        assert cog_validate("mosaic_ovr_0.tif")

        with rasterio.open("mosaic_ovr_0.tif") as src:
            assert src.height == 512
            assert src.width == 512
            assert src.meta["dtype"] == "uint16"
            assert src.is_tiled
            assert src.profile["blockxsize"] == 256
            assert src.profile["blockysize"] == 256
            assert src.compression.value == "DEFLATE"
            assert src.interleaving.value == "PIXEL"
            assert src.overviews(1) == [2]

        with rasterio.open("mosaic_ovr_0.tif", OVERVIEW_LEVEL=0) as src:
            assert src.block_shapes[0] == (128, 128)


# -*- coding: utf-8 -*-
__author__ = 'jelly'

"""
The schedule is include snapshot and scrub
"""

from osi import run_command
import os

schedule_file = "/etc/schedule.conf"
schedule_filecp = "./schedulecp.conf"
schedule_crond = "/etc/cron.d/schedule"
schedule_crondcp = "./schedulecp"

def get_allschedule():
    list = []
    dict = {}
    if(os.path.exists(schedule_file)):
        cmd = ["cat",schedule_file]
        o,r,rc = run_command(cmd)
        for l in o:
            l = l.split("#")
            if(len(l) == 4):
                dict = {"share":"","pool":"","disk":{}}
                dict["name"] = l[0]
                dict["type"] = l[1].split(":")[0]
                if(dict["type"] == "snapshot"):
                    dict["share"] = l[1].split(":")[1]
                elif(dict["type"] == "scrub"):
                    dict["pool"] = l[1].split(":")[1]
                elif(dict["type"] == "smarttest"):
                    dict["disk"]["name"] = l[1].split(":")[1]
                    dict["disk"]["method"] = l[1].split(":")[2]
                l_crond = l[2].split()
                if(len(l_crond) == 5):
                    dict["cron_time_min"] = l_crond[0]
                    dict["cron_time_hour"] = l_crond[1]
                    dict["cron_day"] = l_crond[2]
                    dict["cron_month"] = l_crond[3]
                    dict["cron_week"] = l_crond[4]
                else:
                    dict["cron_time_min"] = "*"
                    dict["cron_time_hour"] = "*"
                    dict["cron_day"] = "*"
                    dict["cron_month"] = "*"
                    dict["cron_week"] = "*"
                dict["enabled"] = l[3]
                list.append(dict)
    else:
        file1 = open(schedule_file,"w")
        file1.write("")
        file1.close()
    return list

"""
schedule = {"name":"snaptest",
"type":"snapshot",
or
"type":"scrub",
Or
"type":"smarttest",
"cron_time_min":"30",
"cron_time_hour":"3",
"cron_day":"*",
"cron_month":"*",
"cron_week":"5",
"enabled":"0",
"share":"sharetest",
or
"pool":"pooltest"
Or
"disk":{"name":"sdb","method":"long"}
}
"""

def add_newscchedule(schedule):
    key = 1
    name = schedule["name"]
    if(schedule["type"] == "snapshot"):
        type = "%s:%s" % (schedule["type"],schedule["share"])
    elif(schedule["type"] == "scrub"):
        type = "%s:%s" % (schedule["type"],schedule["pool"])
    elif(schedule["type"] == "smarttest"):
        type = "%s:%s:%s" % (schedule["type"],schedule["disk"]["name"],schedule["disk"]["method"])
    frequent = "%s %s %s %s %s" % (schedule["cron_time_min"],schedule["cron_time_hour"],schedule["cron_day"],
    schedule["cron_month"],schedule["cron_week"])
    enable = schedule["enabled"]
    schedule_str = "%s#%s#%s#%s" % (name,type,frequent,enable)
    #check the schedule is exists or not
    if(os.path.exists(schedule_file) is None):
        file1 = open(schedule_file,"w")
        file1.write("")
        file1.close()
    if(os.path.exists(schedule_file)):
        file1 = open(schedule_file,"r")
        lines = file1.readlines()
        if(schedule["type"] == "snapshot"):
            for l in lines:
                l = l.split("#")
                if(len(l) == 4):
                    if(l[0] == name or schedule["share"] == l[1].split(":")[1]):
                        key = 0
                        break
        elif(schedule["type"] == "scrub"):
            for l in lines:
                l = l.split("#")
                if(len(l) == 4):
                    if(l[0] == name or schedule["pool"] == l[1].split(":")[1]):
                        key = 0
                        break
        elif(schedule["type"] == "smarttest"):
            for l in lines:
                l = l.split("#")
                if(len(l) == 4):
                    if(l[0] == name or schedule["disk"]["name"] == l[1].split(":")[1]):
                        key = 0
                        break
        file1.close()
    #write str to the schedule_file and schedule crond
    if(key):
        file2 = open(schedule_file,"a")
        file2.write(schedule_str + "\n")
        file2.close()
        #write schedule to crond
        if(os.path.exists(schedule_crond) is None):
            f = open(schedule_crond,"w")
            f.write("")
            f.write("SHELL=/bin/bash\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAILTO=root")
            f.close()
        o,r,rc = run_command(["find","/opt","-name","schedule_run.py"])
        if(len(o) > 0):
            path = o[0]
            path_str = frequent + " root python " + path + " " + type + " " + name
            if(int(enable) == 0):
                path_str = "#" + path_str
            file3 = open(schedule_crond,"a")
            file3.write(path_str + "\n")
            file3.close()

        return {"status":"The schedule snapshot, scrub or smarttest add success"}

    else:
        #return {"error":"The share or pool schedule is exists!"}
        return {"error":"该计划任务已经存在，不能重复创建"}

#schedule["name"] = "schedule_test"
def rem_schedule(schedule):
    key_conf = 0
    key_crond = 0
    name = schedule["name"]
    #remove configure file content
    file1 = open(schedule_file,"r")
    lines_1 = file1.readlines()
    file2 = open(schedule_filecp,"w")
    for l in lines_1:
        if(name == l.split("#")[0]):
            key_conf = 1
        else:
            file2.write(l + "\n")
    file2.close()
    file1.close()
    if(key_conf):
        os.system("cp -f %s %s" % (schedule_filecp,schedule_file))
    #remove schedule crond info
    file3 = open(schedule_crond,"r")
    lines_3 = file3.readlines()
    file4 = open(schedule_crondcp,"w")
    for l in lines_3:
        if name in l:
            key_crond = 1
        else:
            file4.write(l + "\n")
    file4.close()
    file3.close()
    if(key_crond):
        os.system("cp -f %s %s" % (schedule_crondcp,schedule_crond))
    os.system("rm -rf %s" % schedule_filecp)
    os.system("rm -rf %s" % schedule_crondcp)
    if(key_conf == 1):
        return {"status":"delete schedule success"}
    else:
        #return {"error":"delete error,the schedule is not exists"}
        return {"error":"删除错误，计划任务不存在"}

"""
schedule = {"name":"snaptest",
"cron_time_min":"30",
"cron_time_hour":"3",
"cron_day":"*",
"cron_month":"*",
"cron_week":"5"}
"""

def update_schedule(schedule):
    key1 = 0
    key2 = 0
    name = schedule["name"]
    frequent = "%s %s %s %s %s" % (schedule["cron_time_min"],schedule["cron_time_hour"],schedule["cron_day"],
    schedule["cron_month"],schedule["cron_week"])
    #update configure file
    if(os.path.exists(schedule_file)):
        file1 = open(schedule_file,"r")
        lines = file1.readlines()
        file2 = open(schedule_filecp,"w")
        for line in lines:
            l = line.split("#")
            if(l[0] == name and len(l) == 4):
                conf_str = "%s#%s#%s#%s" % (l[0],l[1],frequent,l[3])
                file2.write(conf_str)
                key1 = 1
            else:
                file2.write(line)
        file2.close()
        file1.close()
        if(key1):
            os.system("cp -f %s %s" % (schedule_filecp,schedule_file))
    #update crond file
    if(os.path.exists(schedule_crond)):
        file3 = open(schedule_crond,"r")
        lines = file3.readlines()
        file4 = open(schedule_crondcp,"w")
        for line in lines:
            if (name == line.split()[-1]):
                l = line.split("python")
                if(line[0] == "#"):
                    conf_str = "#%s root python%s" % (frequent,l[1])
                else:
                    conf_str = "%s root python%s" % (frequent,l[1])
                file4.write(conf_str)
                key2 = 1
            else:
                file4.write(line)
        file4.close()
        file3.close()
        if(key2):
            os.system("cp -f %s %s" % (schedule_crondcp,schedule_crond))
    os.system("rm -rf %s" % schedule_filecp)
    os.system("rm -rf %s" % schedule_crondcp)
    if(key1):
        return {"status":"update schedule success"}
    else:
        #return {"error":"update schedule fail"}
        return {"error":"更新计划任务失败"}

#enabled = {"enabled":"1","name":"schedule11"}
def enable_schedule(enable):
    key1 = 1
    key2 = 1
    enabled = str(enable["enabled"])
    name = enable["name"]
    #if(enabled == "1"):
    #modify schedule configure file
    file1 = open(schedule_file,"r")
    lines = file1.readlines()
    file2 = open(schedule_filecp,"w")
    for l in lines:
        if(name == l.split("#")[0]):
            str_new = "%s%s" % (l.strip()[:-1],enabled)
            file2.write(str_new + "\n")
            if(l[-1] == enabled):
                key1 = 0
        else:
            file2.write(l)
    file2.close()
    file1.close()
    if(key1):
        os.system("cp -f %s %s" % (schedule_filecp,schedule_file))
    #modify crond file
    file3 = open(schedule_crond,"r")
    lines = file3.readlines()
    file4 = open(schedule_crondcp,"w")
    for l in lines:
        l = l.strip()
        if(len(l.split()) > 0):
            if(name == l.split()[-1]):
                if(l[0] == "#"):
                    file4.write(l[1:] +"\n")
                    if(enabled == "0"):
                        key2 = 0
                else:
                    file4.write("#" + l +"\n")
                    if(enabled == "1"):
                        key2 = 0
            else:
                file4.write(l +"\n")
        else:
            file4.write(l +"\n")
    file4.close()
    file3.close()
    if(key2):
        os.system("cp -f %s %s" % (schedule_crondcp,schedule_crond))
    if(key1 == 1):
        return {"status":"enable or disable success"}
    else:
        #return {"error":"the status is already enable or disable"}
        return {"error":"使能状态已经是enable状态或者已经是disable状态"}

#print enable_schedule(enabled)


import logging

from networkml.algorithms.base import BaseAlgorithm

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_parse_pcap_name():
    instance = BaseAlgorithm()
    parse_pcap_name = instance.parse_pcap_name
    assert parse_pcap_name('notaposeidontracefile.pcap') == 'notaposeidontracefile'
    assert parse_pcap_name('trace_but_invalid') == None
    assert parse_pcap_name('trace_ab12_2001-01-01_02_03-client-ip-1-2-3-4.pcap') == 'ab12'
    assert parse_pcap_name('trace_ab12_2001-01-01_02_03-miscellaneous-stuff.pcap') == None

def test_basealgorithm():
    instance = BaseAlgorithm()

    last_update = instance.common.get_address_info('10.0.0.1', '1')
    last_update, previous_representation = instance.common.get_previous_state(
        '10.0.0.1', '1')
    assert last_update == None
    assert previous_representation == None

def test_basealgorithm_eval():
    instance = BaseAlgorithm()
    instance.eval('onelayer')
    instance.eval('randomforest')


import cv2
import os

def getGabor(img, filters):
  res = cv2.filter2D(img, cv2.CV_8UC4, filters) # 2D滤波函数 kern为滤波模板
  return res

def getMatchNum(matches, ratio):
  '''返回特征点匹配数量和匹配掩码'''
  matchesMask = [[0, 0] for i in range(len(matches))]
  matchNum = 0
  for i, (m, n) in enumerate(matches):
    if m.distance < ratio * n.distance:  # 将距离比率小于ratio的匹配点筛选出来
      matchesMask[i] = [1, 0]
      matchNum += 1
  return (matchNum, matchesMask)

filters = cv2.getGaborKernel((11, 11), 11, 2.670353755551324, 11, 1.94, -1.5707963267948966)

# 读取文件
imgfiles = []
for root, dirs, files in os.walk("./img"):
  imgfiles = files

# 创建sift及flann初始化
# 创建SIFT特征提取器
sift = cv2.xfeatures2d.SIFT_create()
# 创建FLANN匹配对象
FLANN_INDEX_KDTREE = 0
indexParams = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
searchParams = dict(checks=50)
flann = cv2.FlannBasedMatcher(indexParams, searchParams)

# 遍历并缓存处理
cache = {}
for file in imgfiles:
  image = cv2.imread('./img/' + file, cv2.IMREAD_GRAYSCALE)
  cache[file] = {}
  cache[file]["kp"], cache[file]["des"] = sift.detectAndCompute(getGabor(image, filters), None)

# 遍历
for file1 in imgfiles:
  split_file_name1 = file1.split("_")
  img1kp = cache[file1]["kp"]
  img1des = cache[file1]["des"]

  for file2 in imgfiles:
    split_file_name2 = file2.split("_")
    kp2 = cache[file2]["kp"]
    des2 = cache[file2]["des"]
    matches = flann.knnMatch(img1des, des2, k=2)  # 匹配特征点，为了删除匹配点，指定k=2，对样本图每个特征点，返回两个匹配
    (matchNum, matchesMask) = getMatchNum(matches, 0.8)  # 通过比率条件，计算匹配度
    matchRatio = matchNum * 100 / len(matches)
    print(str(split_file_name1[0] == split_file_name2[0]) + "," + str(matchRatio) + "," + split_file_name1[0] + "," + split_file_name2[0])


def __init__(self):
    self.module_arg_spec = dict(default_rules=dict(type='list', elements='dict', options=rule_spec), location=dict(type='str'), name=dict(type='str', required=True), purge_default_rules=dict(type='bool', default=False), purge_rules=dict(type='bool', default=False), resource_group=dict(required=True, type='str'), rules=dict(type='list', elements='dict', options=rule_spec), state=dict(type='str', default='present', choices=['present', 'absent']))
    self.default_rules = None
    self.location = None
    self.name = None
    self.purge_default_rules = None
    self.purge_rules = None
    self.resource_group = None
    self.rules = None
    self.state = None
    self.tags = None
    self.nsg_models = None
    self.results = dict(changed=False, state=dict())
    super(AzureRMSecurityGroup, self).__init__(self.module_arg_spec, supports_check_mode=True)


'''
Created on Sep 10, 2012

@author: daniel
'''

import numpy as np
import pandas

import nenes_parcel_aux as npa

from nenes_parcel import AerosolSpecies, ParcelModel
from micro import Mw, rho_w, kohler_crit
from lognorm import Lognorm

from pylab import *

## Initial conditions
P0 = 100000. # Pressure, Pa
T0 = 294. # Temperature, K
S0 = -0.05 # Supersaturation. 1-RH from wv term
V = 0.5 # m/s

def make_ammonium_sulfate(epsilon=0.3, N=200.):
    ammonium_sulfate = { 'Ms': 0.13214, # Molecular weight, kg/mol
                         'rho_s': 1.769*1e-3*1e6,
                         'rho_u': 1.769*1e-3*1e6,
                         'nu': 3.0, # number of ions into which a solute dissolve
                         'epsilon': epsilon # mass fraction of soluble material in the dry particle
                       }
    ammonium_sulfate['rho_p'] = 1.769*1e-3*1e6
    mu, sigma, bins, N = 0.05, 2.0, 50, N
    l = 0
    r = bins
    aerosol_dist = Lognorm(mu=mu, sigma=sigma, N=N)
    rs = np.logspace(np.log10(mu/(sigma*10.)), np.log10(mu*sigma*10), num=bins+1)[:]
    mids = np.array([np.sqrt(a*b) for a, b in zip(rs[:-1], rs[1:])])[l:r]
    Nis = np.array([0.5*(b-a)*(aerosol_dist.pdf(a) + aerosol_dist.pdf(b)) for a, b in zip(rs[:-1], rs[1:])])[l:r]
    r_drys = mids*1e-6

    ammonium_sulfate['distribution'] = aerosol_dist
    ammonium_sulfate['r_drys'] = r_drys
    ammonium_sulfate['rs'] = rs
    ammonium_sulfate['Nis'] = Nis*1e6
    ammonium_sulfate['species'] = '(NH4)2SO4'
    ammonium_sulfate['nr'] = len(r_drys)

    return AerosolSpecies(**ammonium_sulfate)

initial_aerosol = [make_ammonium_sulfate(), ]
aerosol = initial_aerosol[0]
pm = ParcelModel(initial_aerosol, V, T0, S0, P0, console=False)
parcel, aerosols = pm.run(P0, T0, S0, z_top=200.0, dt=0.05, max_steps=1000)

## Process aerosols
xs = np.arange(501)
parcel = parcel.ix[parcel.index % 1 == 0]
aero_subset = {}
for key in aerosols:
    aerosol = aerosols[key]
    subset = aerosol.ix[aerosol.index % 1 == 0]
    aero_subset[key] = subset
aerosols = pandas.Panel(aero_subset)

S_max = np.max(parcel.S)
S_max_ind = np.argmax(parcel.S)

aerosol = initial_aerosol[0]
T = parcel['T'].ix[S_max_ind]
rs = aerosols[aerosol.species].ix[S_max_ind]
r_drys = aerosol.r_drys

r_crits, s_crits = zip(*[kohler_crit(T, r_dry, aerosol.epsilon, aerosol.rho_p, aerosol.Ms, aerosol.nu) for r_dry in aerosol.r_drys])
r_crits, s_crits = np.array(r_crits), np.array(s_crits)
Nis = aerosol.Nis
Neq = np.sum(Nis[S_max > s_crits])

colors = 'bgrcmyk'

figure(1, figsize=(10, 15))
clf()
subplot(311)
p = parcel.S.plot(logx=False)
max_idx = np.argmax(parcel.S)
max_z = parcel.index[max_idx]
vlines([max_z], ylim()[0], ylim()[1], color='k', linestyle='dashed')
ylabel("Supersaturation (%)")

subplot(312)
aerosol = aerosols.ix[0]
for r in aerosol:
    (aerosol[r]*1e6).plot(logy=True)
vlines([max_z], ylim()[0], ylim()[1], color='k', linestyle='dashed')
xlabel("Parcel Height (m)")
ylabel("Wet Radius " + r"($\mu$m)")

subplot(313)
rs, Nis = initial_aerosol[0].rs, initial_aerosol[0].Nis*1e-6
bar(rs[:-1], Nis, diff(rs), color=colors[0], alpha=0.2)

rs, Nis = aerosol.ix[-1]*1e6, initial_aerosol[0].Nis*1e-6
plot(rs, Nis, color='k', alpha=0.5)
semilogx(); #semilogy()

rs, Nis = aerosol.ix[0]*1e6, initial_aerosol[0].Nis*1e-6
plot(rs, Nis, color='r', alpha=0.5)
xlabel("Radius " + r"($\mu$m)")
ylabel("Number concentration (per cc)")


import sys
import io
import urllib.request as dw
import urllib.parse

sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(),encoding='utf-8')

imgUrl="https://ssl.pstatic.net/tveta/libs/1260/1260649/19aabf7c9a09e0d9ed84_20200211140438611.jpg"
mp4="https://tvetamovie.pstatic.net/libs/1260/1260649/24e0cefb7bd741f2d0ec_20200211143216244.mp4-pBASE-v0-f98576-20200211143324330.mp4"

savePath1="D:/atom_py/homework1.jpg"
savePath2="D:/atom_py/homework2.mp4"

f1=dw.urlopen(imgUrl).read()
f2=dw.urlopen(mp4).read()

with open(savePath1, 'wb') as savePath1 : #w : write 저장 r:read 읽기 a:add append개념과 동일
    savePath1.write(f1)
with open(savePath2, 'wb') as savePath2 : #w : write 저장 r:read 읽기 a:add append개념과 동일
    savePath2.write(f2)

print("다운로드 완료!")


def pertition(A, p, r):
	x = A[r]
	i = p - 1
	for j in range(p, r):
		if A[j] <= x:
			i += 1
			A[i], A[j] = A[j], A[i]
	A[i + 1], A[r] = A[r], A[i + 1]
	return i + 1

def quickSort(A, q, r):
	if p < r:
		q = pertition(A, p, r)
		quickSort(A, p, q - 1)
		quickSort(A, q + 1, r)

n = int(raw_input())
card_list = []
for i in range (n):
	card_list.append(raw_input())


#!/usr/bin/env python
# coding: utf-8

# In[1]:

from __future__ import print_function

import numpy as np
import matplotlib.pyplot as plt

def read_data(filename):
    with open(filename, 'r') as f:
        lines = f.readlines()

    num_points = len(lines)
    dim_points = 28 * 28
    data = np.empty((num_points, dim_points))
    labels = np.empty(num_points)

    for ind, line in enumerate(lines):
        num = line.split(',')
        labels[ind] = int(num[0])
        data[ind] = [int(x) for x in num[1:]]

    return (data, labels)

X, train_labels = read_data("sample_train.csv")
test_data, test_labels = read_data("sample_test.csv")
X = X-np.mean(X, axis=0)
print(X.shape, test_data.shape)
print(train_labels.shape, test_labels.shape)

# In[2]:

cov_mat = np.cov(X.T)
eigen_values, eigen_vectors = np.linalg.eig(cov_mat)
eigen_vectors = eigen_vectors[:, 0:2]
X_con = X@eigen_vectors

# In[3]:

def diffren_f(Z):
    A = X@Z@Z.T-X
    B = Z@Z.T@X.T+(-X).T
    Ans = (X.T@A@Z)/np.linalg.norm(A)-(B@X@Z)/np.linalg.norm(B)
    return Ans

# In[4]:

d = X.shape[1]
w = np.random.rand(d, 2)
w, _, _ = np.linalg.svd(w)
w = w[:, :2]
q = 100
learning_rate = 1e-5
print(w.shape)
while q > 0:
    q -= 1
    wcon = w+learning_rate*diffren_f(w)
    err = X@w@w.T-X
    print("error=", np.linalg.norm(err))
    w = wcon

# In[5]:

plt.scatter(X_con[:, 0:1], X_con[:, 1:2])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Normal Pca')
plt.show()
X1_con = X@w
plt.scatter(-X1_con[:, 0:1], X1_con[:, 1:2])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('GD Pca')
plt.show()


def fibonacci(n):
	"""
	This function will return the nth number in the numeric set, assuming a 0 index.

	The fibinacci series is naturally recursive – the value is defined by previous values:
	fib(n) = fib(n-2) + fib(n-1)
	"""
	a, b, i, fib = 0, 1, 1, [1,1]
	while i < n:
		fib.append(fib[a] + fib[b])
		a += 1
		b += 1
		i += 1
	return(fib[-1])

def lucas(n):
	"""
	This function will return the nth number in the numeric set, assuming a 0 index.

	The Lucas Numbers are a fibinacci related series of integers that start with the values 2 and 1
	"""
	a, b, i, luc = 0, 1, 1, [2,1]
	while i < n:
		luc.append(luc[a] + luc[b])
		a += 1
		b += 1
		i += 1
	return(luc[-1])

def sum_series(n, a=1, b=1):
	"""
	This funcation will return the nth string based on starting numbers dictated by input parameters, or use default.
	"""
	i = 2
	ss = [a,b]
	while i <= n:
		ss.append(ss[i-1] + ss[i-2])
		i += 1
	return(ss[-1])

#Asserts

assert fibonacci(1) == 1
assert fibonacci(4) == 5
assert fibonacci(10) == 89
assert fibonacci(100) == 573147844013817084101

assert lucas(1) == 1
assert lucas(4) == 7
assert lucas(10) == 123
assert lucas(100) == 792070839848372253127

assert sum_series(4) == 5
assert sum_series(4, 10, 12) == 56
assert sum_series(0, 99) == 1


import socketserver
import redis

class GameServer(socketserver.BaseRequestHandler):
    """
    ゲーム中にリアルタイムで更新するパラメータの送受信サーバ
    """
    def handle(self):
        self.data = self.request[0]
        sock = self.request[1]

        player_id, player_data = self.data.split(b':')
        name, type, attack_status, x, y, z, yr = player_data.split(b',')

        db0 = redis.Redis(host='localhost', port=6379, db=0)

        # dbのアクセス順序が保証されないためエラー処理を追加
        try:
            # 自分のパラメータ更新
            # すでにゲームオーバーしていたら処理を飛ばす
            if player_id in db0.keys():
                db0.lset(player_id, 2, attack_status)
                db0.lset(player_id, 4, x)
                db0.lset(player_id, 5, y)
                db0.lset(player_id, 6, z)
                db0.lset(player_id, 7, yr)

            res = b''
            for object_id in db0.keys():
                res += b','.join(db0.lrange(object_id, 0, -1))
                res += b':'

            # ラグ発生時のバグ消し用
            while res[-1] == 58:
                res = res[:-1]

            sock.sendto(res, self.client_address)

        except:
            res = b''
            for object_id in db0.keys():
                res += b','.join(db0.lrange(object_id, 0, -1))
                res += b':'

            # ラグ発生時のバグ消し用
            while res[-1] == 58:
                res = res[:-1]

            sock.sendto(res, self.client_address)

class ThreadedGameServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    pass

if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 8992

    server = ThreadedGameServer((HOST, PORT), GameServer)
    server.serve_forever()


import pygame
import BUTTONS

White = (255, 255, 255)
Black = (0, 0, 0)
class Player:
    def __init__(self):
        self.charactor = pygame.image.load('Sprite/shipGreen_manned.png')
        self.charactorSize = self.charactor.get_size()
        self.charactor = pygame.transform.scale(self.charactor, (int(self.charactorSize[0]/2.4), int(self.charactorSize[1]/2.4)))
        self.x_change = 2
        self.x = 371
        self.y = 600
        cx = 293
        self.charactorX = []
        for i in range(5):
            self.charactorX.append(cx)
            cx += 39

    def move(self, strMove):
        if (strMove == "-"):
            if self.x != self.charactorX[0]:
                    self.x_change -= 1
                    self.x = self.charactorX[self.x_change]
        elif(strMove == "+"):
            if self.x != self.charactorX[len(self.charactorX) - 1]:
                    self.x_change += 1
                    self.x = self.charactorX[self.x_change]

class GameManager:

    def __init__(self, stage):
        pygame.init()
        pygame.mixer.init()
        #sound
        self.shoot_effectSound = 'Assets/Resources/Sound/Effect/Hit.ogg'
        #UI
        self.font = pygame.font.Font("Fonts/NanumMyeongjoExtraBold.ttf", 30)
        self.combo = 0
        self.maxCombo = 0
        self.time = 0
        self.lowtime = pygame.time.get_ticks() / 1000
        self.dt = 0
        self.comboTime = 0
        self.comboStart = False;

        #result
        self.result_Background = pygame.image.load("Sprite/bg.png")
        self.result_Background = pygame.transform.scale(self.result_Background, (int(self.result_Background.get_size()[0] / 2), int(self.result_Background.get_size()[1] / 2)))

        self.result_winback = pygame.image.load("Sprite/win.png")
        self.result_loseback = pygame.image.load("Sprite/lose.png")
        self.result_winback = pygame.transform.scale(self.result_winback, (int(self.result_winback.get_size()[0] / 2), int(self.result_winback.get_size()[1] / 2)))
        self.result_loseback = pygame.transform.scale(self.result_loseback, (int(self.result_loseback.get_size()[0] / 2), int(self.result_loseback.get_size()[1] / 2)))

        self.result_table = pygame.image.load("Sprite/table.png")
        self.result_table = pygame.transform.scale(self.result_table, (int(self.result_table.get_size()[0] / 2), int(self.result_table.get_size()[1] / 2)))

        self.result_menubtn = pygame.image.load("Sprite/menu.png")
        self.result_retrybtn = pygame.image.load("Sprite/restart.png")
        self.result_nextbtn = pygame.image.load("Sprite/next.png")
        self.result_menubtn = pygame.transform.scale(self.result_menubtn, (int(self.result_menubtn.get_size()[0] / 2.4), int(self.result_menubtn.get_size()[1] / 2.4)))
        self.result_retrybtn = pygame.transform.scale(self.result_retrybtn, (int(self.result_retrybtn.get_size()[0] / 2.4), int(self.result_retrybtn.get_size()[1] / 2.4)))
        self.result_nextbtn = pygame.transform.scale(self.result_nextbtn, (int(self.result_nextbtn.get_size()[0] / 2.4), int(self.result_nextbtn.get_size()[1] / 2.4)))
        self.result_menubtn_rect = self.result_menubtn.get_rect(topleft = (480, 580))
        self.result_retrybtn_rect = self.result_retrybtn.get_rect(topleft = (580, 580))
        self.result_nextbtn_rect = self.result_nextbtn.get_rect(topleft = (680, 580))

        self.star_Background = [0 for i in range(3)]
        self.star = [0 for i in range(3)]
        self.starPos = [(470, 160), (560, 140), (665, 160)]
        self.starRot = [10, 0, -10]
        self.starSize = [2.8, 2.2, 2.8]

        self.goldMark = [0 for i in range(3)]
        self.xMark= [0 for i in range(3)]
        self.goldmarkPos = [(480, 300), (480, 400), (480, 500)]
        self.xmarkPos = [(485, 300), (485, 400), (485, 500)]

        for i in range(3):
            self.star_Background[i] = pygame.image.load("Sprite/star lock.png")
            self.star[i] = pygame.image.load("Sprite/star.png")
            self.star_Background[i] = pygame.transform.scale(self.star_Background[i], (int(self.star_Background[i].get_size()[0] / self.starSize[i]),
                                                                                int(self.star_Background[i].get_size()[1] / self.starSize[i])))
            self.star[i] = pygame.transform.scale(self.star[i], (int(self.star[i].get_size()[0] / self.starSize[i]),
                                                                 int(self.star[i].get_size()[1] / self.starSize[i])))
            self.star_Background[i] = pygame.transform.rotate(self.star_Background[i], self.starRot[i])
            self.star[i] = pygame.transform.rotate(self.star[i], self.starRot[i])

            self.goldMark[i] = pygame.image.load("Sprite/gold medal.png")
            self.xMark[i] = pygame.image.load("Sprite/pointer location3.png")

            self.goldMark[i] = pygame.transform.scale(self.goldMark[i], (int(self.goldMark[i].get_size()[0] / 2.8),
                                                                 int(self.goldMark[i].get_size()[1] / 2.8)))
            self.xMark[i] = pygame.transform.scale(self.xMark[i], (int(self.xMark[i].get_size()[0] / 2.2),
                                                                 int(self.xMark[i].get_size()[1] / 2.2)))

        self.clear_misson = []

        #game
        self.isClear = False
        self.isEndgame = False
        x = 300
        y = 100
        self.pad_width = 1280
        self.pad_height = 720
        self.gamepad = pygame.display.set_mode((self.pad_width, self.pad_height))
        pygame.display.set_caption("stone")
        self.fps = pygame.time.Clock()

        self.background = pygame.image.load('Sprite/game_background_3. 2.png')
        self.backgroundSize = self.background.get_size()
        self.background = pygame.transform.scale(self.background, (int(self.backgroundSize[0] / 1.5), int(self.backgroundSize[1] / 1.5)))
        self.targetblock = pygame.image.load("Sprite/selectorA.png")
        self.targetblockSize = self.targetblock.get_size()
        self.targetblock = pygame.transform.scale(self.targetblock, (int(self.targetblockSize[0] * 1.8), int(self.targetblockSize[1] * 1.8)))
        self.backblock = pygame.image.load("Sprite/selectorB.png")

        self.targetblockX = 100
        self.targetblockY = [250, 350, 450]

        bColor = ['red', 'yellow', 'blue', 'green', 'purple', 'gray']
        self.blocks = [0 for i in range(len(bColor))]
        for i in range(len(bColor)):
            self.blocks[i] = pygame.image.load("Sprite/" + bColor[i] + "_Block.png")
            self.blockSize = self.blocks[i].get_size()
            self.blocks[i] = pygame.transform.scale(self.blocks[i], (int(self.blockSize[0] * 1.22), int(self.blockSize[1] * 1.22)))

        self.resultblock = []
        self.backblockX = []
        self.backblockY = []
        self.checkblock = []
        self.stageblocks = [[0 for i in range(5)] for j in range(14)]
        for i in range(5):
            self.backblockX.append(x)
            x += 39
        for i in range(14):
            self.backblockY.append(y)
            y += 39

        self.playerLaser = pygame.image.load("Sprite/simple_patten.png")
        self.playerLaserSize = self.playerLaser.get_size()
        self.playerLaser = pygame.transform.scale(self.playerLaser, (int(self.playerLaserSize[0] * 2), int(self.playerLaserSize[1] / 9)))
        self.playerLaser = pygame.transform.rotate(self.playerLaser, 270)
        self.playerLaser.set_alpha(200)

        self.colorPanel = pygame.image.load("Sprite/Square.jpg")
        self.colorPanel = pygame.transform.scale(self.colorPanel, (int(self.colorPanel.get_size()[0]/2.6), int(self.colorPanel.get_size()[1] * 1.09)))
        self.colorPanel.set_alpha(100)
        self.colorPanel_colors = [(255, 0, 0), (255, 255, 0), (0, 0, 255), (0, 255, 0), (138, 43, 226), (128, 128, 128)]

        #readtxt
        for i in range(14):
            for j in range(5):
                self.stageblocks[i][j] = self.readtxt(stage)[i][j]

        for i in range(14, 16):
            self.clear_misson.append(self.readtxt(stage)[i].strip())

        self.clearStr = ["게임 클리어", "콤보 {}".format(self.clear_misson[0]) + "이상", self.clear_misson[1] + "초 이내 클리어"]

        self.clearLabel = [0 for i in range(3)]
        self.clearLabelPos = [(580, 315), (580, 415), (580, 515)]
        for i in range(3):
            self.clearLabel[i] = self.font.render(self.clearStr[i], True, Black)

    def game(self, stage):
        player = Player()

        crashed = False
        while not crashed:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return "Quit"
                if (not self.isEndgame):
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                            player.move("-")
                        elif event.key == pygame.K_RIGHT:
                            player.move("+")
                        if event.key == pygame.K_SPACE:
                            self.check_blocks(player)
                else:
                    if event.type == pygame.MOUSEBUTTONUP:
                        curr_x, curr_y = event.pos
                        if self.result_menubtn_rect.collidepoint(curr_x, curr_y):
                            print(1)
                            return "Select_Stage"
                        elif self.result_retrybtn_rect.collidepoint(curr_x, curr_y):
                            print(2)
                            return "Retry"
                        elif self.result_nextbtn_rect.collidepoint(curr_x, curr_y):
                            print(3)
                            return "Next_Stage"

            self.render(player, stage)

            pygame.display.update()
            self.fps.tick(60)
            pygame.display.flip()

    def render(self, player, stage):
        # rendering
        self.gamepad.fill(White)
        self.gamepad.blit(self.background, (0, 0))
        self.gamepad.blit(self.colorPanel, (300, 100))
        for i in range(3):
            self.gamepad.blit(self.targetblock, (self.targetblockX, self.targetblockY[i]))
        for i in range(0, 14):
            for j in range(0, 5):
                self.gamepad.blit(self.backblock, (self.backblockX[j], self.backblockY[i]))

        self.gamepad.blit(self.playerLaser, (player.x + 19, 100))
        for i in range(0, 14):
            for j in range(0, 5):
                if self.stageblocks[i][j] != '0':
                    self.gamepad.blit(self.blocks[int(self.stageblocks[i][j]) - 1],
                                      (self.backblockX[j] + 0.5, self.backblockY[i] + 0.5))

        for i in range(len(self.resultblock)):
            self.gamepad.blit(self.blocks[self.resultblock[i]], (self.targetblockX + 15, self.targetblockY[i] + 13))

        self.comboUI = self.font.render("Combo : " + str(self.combo), True, White)
        self.timeUI = self.font.render("Time : " + str(self.time), True, White)
        self.gamepad.blit(self.comboUI, (800, 200))
        self.gamepad.blit(self.timeUI, (800, 350))
        self.gamepad.blit(player.charactor, (player.x, player.y))

        if not self.isEndgame:
            self.time = int(pygame.time.get_ticks() / 1000 - self.lowtime)
            if len(self.resultblock) == 3:
                if len(set(self.checkblock)) == 1:
                    self.resultblock = []
                    self.checkblock = []
                    self.combo += 1
                    self.comboTime = 0
                    self.dt = pygame.time.get_ticks() / 1000
                    self.comboStart = True
                    if self.maxCombo < self.combo:
                        self.maxCombo = self.combo
                else:
                    self.isEndgame = True

            if self.comboStart:
                self.comboTime = pygame.time.get_ticks() / 1000 - self.dt
                if self.comboTime >= 2.5:
                    self.combo = 0
                    self.comboStart = False

            self.zerocurrent = sum([len(set(self.stageblocks[i])) for i in range(len(self.stageblocks))])

            if self.zerocurrent == 14:
                if len(BUTTONS._STAGE_BUTTONS) > stage:
                    BUTTONS._STAGE_BUTTONS[stage]['locked'] = False
                self.isClear = True
                self.isEndgame = True
        else:
            self.gamepad.blit(self.result_Background, (400, 40))
            self.gamepad.blit(self.result_table, (430, 180))
            self.gamepad.blit(self.result_menubtn, (480, 580))
            self.gamepad.blit(self.result_retrybtn, (580, 580))

            if self.isClear:
                self.gamepad.blit(self.result_winback, (380, 30))
                if len(BUTTONS._STAGE_BUTTONS) > stage:
                    self.gamepad.blit(self.result_nextbtn, (680, 580))
                for i in range(3):
                    self.gamepad.blit(self.clearLabel[i], self.clearLabelPos[i])
                    self.gamepad.blit(self.star_Background[i], self.starPos[i])
                self.gamepad.blit(self.star[0], self.starPos[0])
                self.gamepad.blit(self.goldMark[0], self.goldmarkPos[0])

                if self.maxCombo >= int(self.clear_misson[0]) or self.time < int(self.clear_misson[1]):
                    self.gamepad.blit(self.star[2], self.starPos[2])
                if self.maxCombo >= int(self.clear_misson[0]) and self.time < int(self.clear_misson[1]):
                    self.gamepad.blit(self.star[1], self.starPos[1])
                    self.gamepad.blit(self.star[2], self.starPos[2])

                if self.maxCombo >= int(self.clear_misson[0]):
                    self.gamepad.blit(self.goldMark[1], self.goldmarkPos[1])
                else:
                    self.gamepad.blit(self.xMark[1], self.xmarkPos[1])

                if self.time < int(self.clear_misson[1]):
                    self.gamepad.blit(self.goldMark[2], self.goldmarkPos[2])
                else:
                    self.gamepad.blit(self.xMark[2], self.xmarkPos[2])
            else:
                self.gamepad.blit(self.result_loseback, (380, 30))
                for i in range(3):
                    self.gamepad.blit(self.xMark[i], self.xmarkPos[i])
                    self.gamepad.blit(self.clearLabel[i], self.clearLabelPos[i])
                    self.gamepad.blit(self.star_Background[i], self.starPos[i])

    def check_blocks(self, player):
        for i in range(13, -1, -1):
            if self.stageblocks[i][player.x_change] != '0':
                pygame.mixer.music.load(self.shoot_effectSound)
                pygame.mixer.music.play(0)
                self.resultblock.append(int(self.stageblocks[i][player.x_change]) - 1)
                self.checkblock.append(self.stageblocks[i][player.x_change])
                self.colorPanel.fill(
                    self.colorPanel_colors[int(self.stageblocks[i][player.x_change]) - 1])
                self.playerLaser.fill(
                    self.colorPanel_colors[int(self.stageblocks[i][player.x_change]) - 1])
                self.stageblocks[i][player.x_change] = '0'
                break

    def readtxt(self, stage):
        f = open("Assets/Resources/Stage/stage{}".format(stage) + ".txt", "r")
        line = f.readlines()
        f.close()
        return line


import soundcloud, requests, os, re, sys
import socket, json
from soundcloud import resource
from .utils import download_file, tag_file
from .context import secret
from requests.adapters import HTTPAdapter
from halo import Halo

class SoundcloudDownloader(object):
	def __init__(self, args=None):
		self.args = args
		self.url = args.url
		self.dirname = args.dir
		self.client = soundcloud.Client(client_id=secret)
		self.API_V1 = "https://api.soundcloud.com"
		self.API_V2 = "https://api-v2.soundcloud.com"
		self.download_count = 0
		self.session = requests.Session()
		self.session.mount("http://", adapter = HTTPAdapter(max_retries = 3))
		self.session.mount("https://", adapter = HTTPAdapter(max_retries = 3))

	def get_filename(self, metadata):
		return self.validate_name("{}-{}.{}".format(metadata["artist"], metadata["title"], metadata["format"]))

	def get_track_url(self, track):
		if track["downloadable"]:
			return ("{}?client_id={}".format(track["download_url"], secret), track.get("original_format", "mp3"))
		if track["streamable"]:
			if "stream_url" in track:
				return ("{}?client_id={}".format(track["stream_url"], secret), "mp3")
			for transcoding in track["media"]["transcodings"]:
				if transcoding["format"]["protocol"] == "progressive":
					r = self.session.get(transcoding["url"], params={"client_id": secret})
					return (json.loads(r.text)["url"] , "mp3")

	def get_track_metadata(self, track):
		artist = "unknown"
		if "publisher_metadata" in track and track["publisher_metadata"]:
			artist = track["publisher_metadata"].get("artist", "")
		elif "user" in track or not artist:
			artist = track["user"]["username"]
		url, fileFormat = self.get_track_url(track)
		return {
			"title": str(track.get("title", track["id"])),
			"artist": artist,
			"year": str(track.get("release_year", "")),
			"genre": str(track.get("genre", "")),
			"format": fileFormat,
			"download_url": url,
			"artwork_url": track["artwork_url"]
		}

	def get_single_track(self, track):
		if isinstance(track, resource.Resource): track = track.fields()
		metadata = self.get_track_metadata(track)
		filename = self.get_filename(metadata)
		download_file(filename, metadata["download_url"])
		try:
			tag_file(filename, metadata)
		except:
			if os.path.isfile("artwork.jpg"): os.remove("artwork.jpg")
		self.download_count += 1

	def get_multiple_tracks(self, tracks):
		for _, track in filter(lambda x: self.check_track_number(x[0]), enumerate(tracks)):
			self.get_single_track(track)

	def get_playlist(self, playlist):
		print("{} tracks found in playlist".format(len(playlist.tracks)))
		self.get_multiple_tracks(playlist.tracks)

	def check_track_number(self, index):
		if self.download_count == self.args.limit:
			return False
		if self.args.include and index + 1 in self.args.include:
			return True
		if self.args.exclude and index + 1 in self.args.exclude:
			return False
		if self.args.range:
			if not self.args.range[0] <= index + 1 <= self.args.range[1]:
				return False
		return True

	def get_uploaded_tracks(self, user):
		spinner = Halo(text="Fetching uploads")
		spinner.start()
		tracks = self.client.get("/tracks", id=user.id)
		spinner.stop()
		print("Found {} uploads".format(len(tracks)))
		self.get_multiple_tracks(tracks)

	def get_recommended_tracks(self, track, no_of_tracks=10):
		params = {
			"client_id": secret,
			"limit": no_of_tracks,
			"offset": 0
		}
		spinner = Halo(text="Fetching tracks similar to {}".format(track.title))
		spinner.start()
		recommended_tracks_url = "{}/tracks/{}/related".format(self.API_V2, track.id)
		r = self.session.get(recommended_tracks_url, params=params)
		spinner.stop()
		tracks = json.loads(r.text)["collection"]
		self.get_multiple_tracks(tracks)

	def get_liked_tracks(self):
		spinner = Halo(text="Fetching liked tracks")
		spinner.start()
		liked_tracks = self.client.get("/resolve", url=self.url + "/likes")
		spinner.stop()
		print("{} liked track(s) found".format(len(liked_tracks)))
		self.get_multiple_tracks(liked_tracks)

	def validate_name(self, name):
		return re.sub('[\\/:*"?<>|]', "_", name)

	def get_charted_tracks(self, kind, no_of_tracks=10):
		url_params = {
			"limit": no_of_tracks,
			"genre": "soundcloud:genres:" + self.args.genre,
			"kind": kind,
			"client_id": secret
		}
		url = "{}/charts".format(self.API_V2)
		tracks = []
		spinner = Halo(text="Fetching {} {} tracks".format(no_of_tracks, kind))
		spinner.start()
		while len(tracks) < no_of_tracks:
			response = self.session.get(url, params=url_params)
			json_payload = json.loads(response.text)
			tracks += json_payload["collection"]
			url = json_payload["next_href"]
		spinner.stop()
		tracks = map(lambda x: x["track"], tracks[:no_of_tracks])
		self.get_multiple_tracks(tracks)

	def main(self):
		os.chdir(self.dirname)
		if self.args.top:
			self.get_charted_tracks("top")
		if self.args.new:
			self.get_charted_tracks("trending")
		spinner = Halo(text="Resolving URL")
		spinner.start()
		data = self.client.get("/resolve", url=self.url) if self.url else None
		spinner.stop()
		if isinstance(data, resource.Resource):
			if data.kind == "user":
				print("User profile found")
				folder = self.validate_name(data.username)
				if not os.path.isdir(folder): os.mkdir(folder)
				os.chdir(os.path.join(os.getcwd(), folder))
				print("Saving in: " + os.getcwd())
				if self.args.all or self.args.likes:
					self.get_liked_tracks()
				if not self.args.likes:
					self.get_uploaded_tracks(data)
			elif data.kind == "track":
					print("Single track found")
					print("Saving in: " + os.getcwd())
					if self.args.similar:
						self.get_recommended_tracks(data)
					self.get_single_track(data)
			elif data.kind == "playlist":
				print("Single playlist found.")
				folder = self.validate_name(data.user["username"])
				if not os.path.isdir(folder):
					os.mkdir(folder)
				os.chdir(os.path.join(os.getcwd(), str(folder)))
				self.get_playlist(data)
		elif isinstance(data, resource.ResourceList):
			if data[0].kind == "playlist":
				print("%d playlists found" % (len(data)))
				for playlist in data:
					self.get_playlist(playlist)
			elif data[0].kind == "track":
				self.get_multiple_tracks(data)


from django.db import models
from core import models as core_models

from django.contrib.auth.models import User

# Create your models here.
class AnalysisType(models.Model):
	name = models.CharField(max_length=30,verbose_name="* Name")
	description = models.CharField(max_length=30, null=True, blank=True)
	protocol_url = models.URLField(null=True, blank=True)
	date_time_last_updated = models.DateTimeField()
	last_updated_by = models.ForeignKey(User)

	def __unicode__(self):
		return self.name

class AnalysisAttribute(models.Model):
	analysis_type = models.ForeignKey(AnalysisType, verbose_name="* Analysis type")
	sample = models.ForeignKey(core_models.Sample, related_name="analysis_attributes", verbose_name="* Sample")
	name = models.CharField(max_length=30, verbose_name="* Name")
	value = models.CharField(max_length=50, null=True, blank=True)
	aliquot_id = models.CharField(max_length=50, verbose_name="* Aliquot id")
	last_updated_by = models.ForeignKey(User)
	date_time_last_updated = models.DateTimeField()
	def  __unicode__(self):
		return self.name


from flask_philo_core.views import BaseView
from flask_philo_core.test import FlaskPhiloTestCase, BaseTestFactory
from flask import json

class SimpleView(BaseView):
    def get(self):
        return self.json_response(data={'msg': 'ok'})

class SimpleCorsView(BaseView):
    def get(self):
        return self.json_response(data={'msg': 'ok-cors'})

URLS = (
    ('/', SimpleView, 'home'),
    ('/cors-api/test-cors', SimpleCorsView, 'cors'),
)

class TestViews(FlaskPhiloTestCase):
    def test_urls(self):
        app = BaseTestFactory.create_test_app()
        assert 'URLS' not in app.config
        rules = [r for r in app.url_map.iter_rules()]
        endpoints = [rl.endpoint for rl in rules]
        assert 1 == len(endpoints)
        assert 'static' in endpoints

        app = BaseTestFactory.create_test_app(urls=URLS)

        assert 'URLS' in app.config
        rules2 = [r for r in app.url_map.iter_rules()]
        endpoints2 = [rl.endpoint for rl in rules2]
        assert 3 == len(endpoints2)
        assert 'cors' in endpoints2
        assert 'static' in endpoints2
        assert 'home' in endpoints2

    def test_simple_view(self):
        app = BaseTestFactory.create_test_app(urls=URLS)
        client = app.test_client()
        result = client.get('/')
        assert 200 == result.status_code
        j_content = json.loads(result.get_data().decode('utf-8'))
        assert 'msg' in j_content
        assert 'ok' == j_content['msg']

    def test_cors(self):
        config = {}
        config['CORS'] = {
            r"/cors-api/*": {"origins": "FLASK_PHILO_CORE_TEST_CORS"}}
        app = BaseTestFactory.create_test_app(config=config, urls=URLS)
        client = app.test_client()
        result = client.get('/cors-api/test-cors')
        assert 'Access-Control-Allow-Origin' in result.headers
        cors_val = result.headers['Access-Control-Allow-Origin']
        assert 'FLASK_PHILO_CORE_TEST_CORS' == cors_val
        assert 200 == result.status_code

        j_content = json.loads(result.get_data().decode('utf-8'))
        assert 'msg' in j_content
        assert 'ok-cors' == j_content['msg']


import pybullet as pb
import numpy as np

from neu_ro_arm.constants import GRIPPER_CLOSED, GRIPPER_OPENED
from neu_ro_arm.robot.base_pybullet import BasePybullet

class CollisionError(Exception):
    def __init__(self, robot_link, other_body, **kwargs):
        self.robot_link = robot_link
        self.other_body = other_body
        msg = f"Collision detected between robot:{robot_link}_link and {other_body}"
        super().__init__(msg)

class UnsafeTrajectoryError(CollisionError):
    '''A collision was detected at some intermediate joint position in trajectory
    '''

class UnsafeJointPosition(CollisionError):
    '''A collision was detected at specified joint position
    '''

class ProbitedHandPosition(Exception):
    '''A collision was detected at specified joint position
    '''
    def __init__(self):
        msg = f"This hand position is not allowed for safety reasons."
        super().__init__(msg)

class MotionPlanner(BasePybullet):
    def __init__(self):
        '''Pybullet simulator of robot used to perform inverse kinematics
        and collision detection quickly in background
        '''
        super(MotionPlanner, self).__init__(pb.DIRECT)
        self._hand_position_limits = np.array(((-0.18,0.18),
                                               (0.08,0.30),
                                               (0.0, 0.30)))

    def safe_hand_position(self, pos):
        return np.bitwise_and(pos > self._hand_position_limits[:,0],
                              pos < self._hand_position_limits[:,1]).all()

    def calculate_ik(self, pos, rot=None):
        '''Performs inverse kinematics to generate hand link pose

        Pybullet IK is influenced by current joint state so it is best to make
        a mirror call before using this method

        Parameters
        ----------
        pos : array_like
            desired 3D position of end effector
        rot : array_like, optional
            desired euler angle of end effector

        Raises
        ------
        ProbitedHandPosition
            hand position is outside of allowable limits
        UnsafeJointPosition
            joint positions needed to achieve hand pose is in
            collision with environment

        Returns
        -------
        ndarray
            joint position of arm joints; shape=(5,); dtype=float
        dict
            data on achieved pose and error
        '''
        if not self.safe_hand_position(pos):
            raise ProbitedHandPosition

        if rot is not None:
            rot = pb.getQuaternionFromEuler(rot)

        jpos = pb.calculateInverseKinematics(self.robot_id,
                                             self.end_effector_link_index,
                                             pos,
                                             rot,
                                             maxNumIterations=500,
                                             physicsClientId=self._client,
                                            )

        num_arm_joints = len(self.arm_joint_idxs)
        arm_jpos = jpos[:num_arm_joints]

        is_collision, collision_data = self._check_collisions(arm_jpos)
        if is_collision:
            raise UnsafeJointPosition(**collision_data)

        # check collision teleports arm so we can check IK solution error here
        achieved_pos, achieved_rot = self.get_hand_pose()
        data = dict()
        data['achieved_pos'] = achieved_pos
        data['achieved_rot'] = achieved_rot
        data['pos_error'] = np.linalg.norm(np.subtract(pos, achieved_pos))

        return arm_jpos, data

    def mirror(self, arm_jpos=None, gripper_state=None):
        '''Set simulators joint state to some desired joint state

        Parameters
        ----------
        arm_jpos : array_like, optional
            joint positions for all arm joints in radians; shape=(5,); dtype=float
        gripper_state : float, optional
            gripper state, should be in range from 0 to 1
        '''
        if arm_jpos is not None:
            self._teleport_arm(arm_jpos)
        if gripper_state is not None:
            self._teleport_gripper(gripper_state)

    def _teleport_arm(self, jpos=None):
        '''Resets joint states of arm joints
        '''
        [pb.resetJointState(self.robot_id, i, jp, physicsClientId=self._client)
            for i,jp in zip(self.arm_joint_idxs, jpos)]

    def _teleport_gripper(self, state):
        '''Resets joint states of gripper joints
        '''
        jpos = state*self.gripper_opened + (1 - state)*self.gripper_closed

        [pb.resetJointState(self.robot_id, i, jp, physicsClientId=self._client)
             for i,jp in zip(self.gripper_joint_idxs, jpos)]

    def check_arm_trajectory(self, target_jpos, num_steps=10):
        '''Checks collision of arm links along linear path in joint space

        Parameters
        ----------
        target_jpos : array_like
            joint positions of arm at end of trajectory; shape=(5,); dtype=float
        num_steps : int
            number of collision checking samples taken within trajectory

        Raises
        -------
        UnsafeTrajectoryError
            some joint configuration along trajectory results in collision
        '''
        assert len(target_jpos) == len(self.arm_joint_idxs)
        current_jpos = [pb.getJointState(self.robot_id, j_idx, physicsClientId=self._client)[0]
                            for j_idx in self.arm_joint_idxs]

        inter_jpos = np.linspace(current_jpos, target_jpos,
                                 num=num_steps, endpoint=True)

        is_collision = False
        for jpos in inter_jpos[1:]:
            is_collision, collision_data = self._check_collisions(jpos)
            if is_collision:
                break

        self._teleport_arm(current_jpos)
        if is_collision:
            raise UnsafeTrajectoryError(**collision_data)

    def _check_collisions(self, jpos, gripper_mode='current'):
        '''Returns True if collisions present as arm joint position

        Parameters
        ----------
        jpos : array_like
            positions of arm joints in radians
        gripper_mode : {'closed', 'open', 'ignore', 'current'}
            how to treat gripper during collision check. if 'current' then the
            gripper position will not be changed

        Returns
        -------
        bool
            True if collision was detected
        dict
            data about collision
        '''
        self._teleport_arm(jpos)

        if gripper_mode == 'open':
            self._teleport_gripper(state=GRIPPER_OPENED)
        elif gripper_mode == 'closed':
            self._teleport_gripper(state=GRIPPER_CLOSED)

        # ignore base because it doesnt move and will likely be in collision
        # with camera at all times
        ignored_links = ['base']
        if gripper_mode == 'ignore':
            ignored_links.extend(['gripper_left', 'gripper_right'])

        pb.performCollisionDetection(self._client)
        contact_points = pb.getContactPoints(bodyA=self.robot_id,
                                             physicsClientId=self._client)
        for cont_pt in contact_points:
            assert cont_pt[1] == self.robot_id
            robot_link = cont_pt[3]
            robot_link_name = self.link_names[robot_link]
            if robot_link_name not in ignored_links:
                other_body_id = cont_pt[2]
                other_body_name = pb.getBodyInfo(other_body_id,
                                                 physicsClientId=self._client
                                                )[1].decode('ascii')

                return True, {'robot_link' : robot_link_name,
                              'other_body' : other_body_name}

        return False, {}


import reversion
from django.core.management.base import BaseCommand

from datahub.core.constants import InvestmentProjectStage
from datahub.feature_flag.models import FeatureFlag
from datahub.investment.project.constants import FEATURE_FLAG_STREAMLINED_FLOW
from datahub.investment.project.models import InvestmentProject

FEATURE_DESCRIPTION = (
    'The removal of the Assign PM stage from investment flow to '
    'streamline the process of completing an investment project.'
)

class Command(BaseCommand):
    """
    Command to activate the streamlined investment flow feature and move all projects
    that have a status of Assign PM back to the Prospect stage.
    """

    help = ('Activates the streamlined investment flow and update all '
            'projects currently at the Assign PM stage')

    def activate_streamlined_investment_flow_feature(self):
        """
        Activate the streamlined investment flow feature and creating the feature
        flag if not already present.
        """
        FeatureFlag.objects.update_or_create(
            code=FEATURE_FLAG_STREAMLINED_FLOW,
            defaults={'description': FEATURE_DESCRIPTION, 'is_active': True},
        )
        self.stdout.write(self.style.SUCCESS('Activated streamlined investment flow'))

    def move_assign_pm_investment_projects_back_to_prospect(self):
        """
        Move projects at the Assign PM stage back to Prospect.
        Save each project individually to unsure search is updated and
        to create an audit of the change.
        """
        projects = InvestmentProject.objects.filter(
            stage_id=InvestmentProjectStage.assign_pm.value.id,
        )
        for project in projects.iterator():
            with reversion.create_revision():
                project.stage_id = InvestmentProjectStage.prospect.value.id
                project.save()
                reversion.set_comment('Moved project stage from Assign PM back to Prospect')
        self.stdout.write(
            self.style.SUCCESS(
                f'Updated {projects.count()} projects from Assign PM to Prospect',
            ),
        )

    def handle(self, *args, **options):
        """
        Move projects from Assign PM stage back to Prospect.
        Activate streamlined investment flow feature.

        """
        self.move_assign_pm_investment_projects_back_to_prospect()
        self.activate_streamlined_investment_flow_feature()


import csv
costcoFile=open('costco-citi-visa-due-soon - bob copy - sorted - with sparse categories.csv')
costcoReader=csv.reader(costcoFile)
costcoData=list(costcoReader)
n=(len(costcoData))
amountfloat=0
total=0
entertainment=0
food=0
household=0
pet=0
petMedical=0
kid=0
kidMedical=0
travel=0
utilities=0
gift=0
charity=0
findDetail=0
ignore=0
fixedInsurance=0
WarningNoCategory=0

mapping={'Aldi':'Discount'}

for i in range(n-1):
    Vendor=costcoData[i+1][2]
    Category=costcoData[i+1][5]
    if Category!='':
        mapping[Vendor]=Category
    else:
        continue

for i in range(n-1):
    Vendor=costcoData[i+1][2]
    category=costcoData[i+1][5]
    if category=='':
        costcoData[i+1][5]=mapping.get(Vendor,'WARNING-NO-CATEGORY')
    else:
        continue

for i in range(n-1):
    category=costcoData[i+1][5]
    amount=costcoData[i+1][1].strip('$()')
    amountfloat=float(amount.replace(',',''))

    if '(' in costcoData[i+1][1]:amountfloat=amountfloat*-1
    if category=='entertainment':entertainment=entertainment+amountfloat
    if category=='food':food=food+amountfloat
    if category=='household':household=household+amountfloat
    if category=='pet':pet=pet+amountfloat
    if category=='pet-medical':petMedical=petMedical+amountfloat
    if category=='kid':kid=kid+amountfloat
    if category=='kid-medical':kidMedical=kidMedical+amountfloat
    if category=='travel':travel=travel+amountfloat
    if category=='utilities':utilities=utilities+amountfloat
    if category=='gift':gift=gift+amountfloat
    if category=='charity':charity=charity+amountfloat
    if category=='find-detail':findDetail=findDetail+amountfloat
    if category=='ignore':ignore=ignore+amountfloat
    if category=='fixed-insurance':fixedInsurance=fixedInsurance+amountfloat
    if category=='WARNING-NO-CATEGORY':WarningNoCategory=WarningNoCategory+amountfloat

outputFile=open('output.version-2.budget-monthly-totals-and-tracking.csv','w')
outputWriter=csv.writer(outputFile)
outputWriter.writerow(['Which Card?','Month','entertainment','food','household','pet','pet-medical','kid','kid-medical','travel','utilities','gift','charity','find-detail','ignore','fixed-insurance','WARNING-NO-CATEGORY'])
outputWriter.writerow(['Costco Visa','March 2017',str(entertainment),str(food),str(household),str(pet),str(petMedical),str(kid),str(kidMedical),str(travel),str(utilities),str(gift),str(charity),str(findDetail),str(ignore),str(fixedInsurance),str(WarningNoCategory)])
outputFile.close()

print("'budget-monthly-totals-and-tracking.csv' file was created !")


import os
import torch
from torchvision import datasets, models, transforms
import torch.nn as nn
import matplotlib.pyplot as plt

def train_dataset(data_dir):
    train_dir = os.path.join(data_dir, 'train')

    train_transforms = transforms.Compose([
        transforms.Resize((299,299)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
    ])

    train_dataset = datasets.ImageFolder(
        train_dir,
        train_transforms
    )

    return train_dataset

def val_dataset(data_dir):
    val_dir = os.path.join(data_dir, 'val')

    val_transforms = transforms.Compose([
        transforms.Resize((299,299)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
    ])

    val_dataset = datasets.ImageFolder(
        val_dir,
        val_transforms
    )

    return val_dataset

def data_loader(data_dir, batch_size=32, workers=4, pin_memory=True):
    train_ds = train_dataset(data_dir)
    val_ds = val_dataset(data_dir)

    train_loader = torch.utils.data.DataLoader(
        train_ds,
        batch_size=batch_size,
        shuffle=True,
        num_workers=workers,
        pin_memory=pin_memory
    )

    val_loader = torch.utils.data.DataLoader(
        val_ds,
        batch_size=batch_size,
        shuffle=False,
        num_workers=workers,
        pin_memory=pin_memory
    )
    return train_loader, val_loader

train_loader, val_loader = data_loader('/ssd_scratch/cvit/madhav/Imagenet/Imagenet-orig/')

def get_device():
  if torch.cuda.is_available():
      return torch.device('cuda')
  else:
      return torch.device('cpu')
device = get_device()

def eval_model(model,trainloader,testloader):
  model.eval()
  correct = 0
  total = 0
  for i, data in enumerate(testloader, 0):
    images, labels = data[0].to(device), data[1].to(device)
    outputs = model(images)
    _, preds = torch.max(outputs, dim=1)
    total += labels.size(0)
    correct += (preds == labels).sum().item()
  acc_v = (correct / total)

  correct = 0
  total = 0
  for i, data in enumerate(trainloader, 0):
    images, labels = data[0].to(device), data[1].to(device)
    outputs = model(images)
    _, preds = torch.max(outputs, dim=1)
    total += labels.size(0)
    correct += (preds == labels).sum().item()
  acc_t = (correct / total)
  return acc_t,acc_v

def fit(epoch, model, trainloader, testloader, optimizer,scheduler):
  history_t = []
  history_v = []
  step_count = 0
  criterion = nn.CrossEntropyLoss().to(device)
  model.train()
  for epoch in range(epoch):
    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
      inputs, labels = data[0].to(device), data[1].to(device)
      optimizer.zero_grad()
      outputs, aux_outputs = model(inputs)
      loss1 = criterion(outputs, labels)
      loss2 = criterion(aux_outputs, labels)
      loss = loss1 + 0.4*loss2
      loss = criterion(outputs, labels)
      loss.backward()
      optimizer.step()
      running_loss += loss.item()
      step_count += 1
      if step_count%10000==0:
        acc_t,acc_v = eval_model(model,trainloader,testloader)
        model.train()
        history_t.append(acc_t)
        history_v.append(acc_v)
        log_ = str(step_count)+","+str(acc_t)+","+str(acc_v)+"\n"
        with open("model.log", "a") as f:
          f.write(log_)
        filename = '/ssd_scratch/cvit/madhav/'+str(step_count//10000)+'checkpoint.pth.tar'
        torch.save(model, filename)
        print("Epoch: {} | Step: {} | loss: {:.4f} | Train acc: {:.4f} | Val acc: {:.4f}".format(epoch+1,step_count, running_loss,acc_t, acc_v))
    scheduler.step()
  return model,history_t,history_v

net = models.inception_v3(pretrained=False).to(device)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1, momentum=0.9)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.95)
trained_model,history_t,history_v = fit(100, net, train_loader, val_loader, optimizer,scheduler)


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

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: ./directly_adjacent_words <word_database.gz> <word>")
        exit(1)
    word_database = sys.argv[1]
    word = sys.argv[2].strip().lower()
    graph = word_graph.WordGraph.load(
        word_database,
        word_graph.AdjacencyCriteriaOneLetter)
    if word not in graph:
        print("Error: {} not in the word database.".format(word))
        exit(1)
    for adjacent_word in graph.adjacent(word):
        print(adjacent_word)


import aw.maya.rigging.lib_crv as lib_crv
from pprint import pprint

def parse_docstring(func):
    lines = [line for line in func.__doc__.replace('\t','').split('\n') if line]

    # Find breakpoints
    breakpoints = []
    for index, line in enumerate(lines):
        if line[-1] == ':':
            breakpoints.append([index, line])

    data = {'Description:':lines[0]}

    for index, breakpoint in enumerate(breakpoints):
        try:
            breakpoint_index, breakpoint_title = breakpoint
            next_breakpoint = breakpoints[index+1][0]
            data[breakpoint_title] = lines[breakpoint_index+1:next_breakpoint]
        except IndexError:
            breakpoint_index, breakpoint_title = breakpoint
            data[breakpoint_title] = lines[breakpoint_index+1:-1]
    pprint(data)

parse_docstring(lib_crv.crv_combine)


"""
Given 3 points in below triangle, find wheather these 3 points are forming equalaterial triangle?
                (5,12,14) = true
                (6,18,22) = true
                (2,11,15) = false
"""
from math import *

arr=[[5,12,14],[6,18,22],[2,11,15]]
for i in arr:
    A,B,C=i[0],i[1],i[2]
    print(A,B,C,"triangle" if (A+B>=C and B+C>=A and A+C>=B) else "not Triangle")
    A1 = degrees(acos((B**2 + C**2 - A**2)/(2*B*C)))
    B1 = degrees(acos((C**2 + A**2 - B**2)/(2*C*A)))
    C1 = degrees(acos((A**2 + B**2 - C**2)/(2*A*B)))
    print(A1,B1,C1)


from datetime import datetime

class Assignment:

    last_id = 0

    def __init__(self, content, deadline, assignment_id):
        """
        Method creates an instance of the class

        Args:
            content (str): description of the assignment
            deadline (Datetime): object of Datetime class
            assignment_id (int): order number of the assignment

        Returns:
            None
        """

        if type(content) is str and type(deadline) is datetime and type(assignment_id) is int:
            self.content = content
            self.deadline = deadline
            self.assignment_id = assignment_id

            self.__class__.last_id += 1
        else:
            raise TypeError

def main():
    c = Assignment('pikuś', datetime(2017, 4, 12), 5)
    print(type(c) == Assignment)

if __name__ == '__main__':
    main()


# !/usr/bin/python
# -*- coding: utf-8 -*-
import unittest

from lab2 import Logger

__author__ = 'asaskevich'

class TestCase(unittest.TestCase):
    def test_functions(self):
        logger = Logger()

        @logger(flag='TEST', format='{fname}({args})={result}')
        def f(a=10, b=20):
            return a + b

        @logger(format='{fname} -> {result}')
        def g(a=10, b=20):
            return a * b

        f()
        f(5, 5)
        g()
        g(5, 5)
        expected_log = "f(a = 10,b = 20)=30\nf(a = 5,b = 5)=10\ng -> 200\ng -> 25"
        self.assertEqual(str(logger), expected_log)
        logger.clear()
        self.assertEqual(str(logger), '')

    def test_class(self):
        class A(Logger):
            def __init__(self):
                Logger.__init__(self, format='A.{fname} -> {result}')

            def f(self, num):
                return num * num

        a = A()
        a.f(4)
        a.f(5)
        a.f(6)
        expected_log = "A.f -> 16\nA.f -> 25\nA.f -> 36"
        self.assertEqual(str(a), expected_log)

    def test_args_kwargs(self):
        logger = Logger()

        @logger(format='{fname} -> {result}')
        def h(*args, **kwargs):
            return len(args), len(kwargs)

        h(1, 2, 3)
        h(a=1, b=2, c=3)
        expected_log = 'h -> (3, 0)\nh -> (0, 3)'
        self.assertEqual(str(logger), expected_log)


def solution(n):
    answer = ''
    for i in range(n):
        answer += str(i%9 + 1)
        answer = answer[::-1]
    return answer

#아래는 테스트케이스 출력을 해보기 위한 코드입니다.
n = 5
ret = solution(n)

#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은", ret, "입니다.")


from stack_implementation import Stack
import string
import operator

precedence = { '^': 4,
               '*': 3,
               '/': 3,
               '+': 2,
               '-': 2,
               '(': 1 }

operators = { '*': operator.mul,
              '/': operator.truediv,
              '+': operator.add,
              '-': operator.sub,
              '^': operator.pow }

def infix_to_postfix(infix_exp):
    operators = Stack()
    infix_exp = infix_exp.split()

    postfix = []
    for sym in infix_exp:
        if sym in string.ascii_letters or sym.isdigit():
            postfix.append(sym)
        elif sym == '(':
            operators.push(sym)
        elif sym == ')':
            while not operators.peek() == '(':
                postfix.append( operators.pop() )
            operators.pop()
        elif sym in precedence.keys():
            while not operators.isEmpty() and precedence[operators.peek()] >= precedence[sym]:
                postfix.append(operators.pop())
            operators.push(sym)
        else:
            raise TypeError("Wrong expression")
    while not operators.isEmpty():
        postfix.append(operators.pop())
    return ' '.join(postfix)

def eval_postfix(postfix_exp):
    operands = Stack()
    postfix = postfix_exp.split()

    for sym in postfix:
        if sym.isdigit():
            operands.push(int(sym))
        elif sym in operators.keys():
            second = operands.pop()
            first = operands.pop()
            operands.push( operators[sym](first, second) )
        else:
            raise TypeError("Wrong expression")
    return operands.pop()

def eval_infix(infix_exp):
    operands = Stack()
    op_stack = Stack()
    infix = infix_exp.split()

    for sym in infix:
        if sym.isdigit():
            operands.push(sym)
        elif sym == '(':
            op_stack.push(sym)
        elif sym == ')':
            second = float(operands.pop())
            first = float(operands.pop())
            op = op_stack.pop()
            operands.push( operators[op](first, second) )
            op_stack.pop()
        elif sym in operators.keys():
            if not op_stack.isEmpty() and precedence[op_stack.peek()] >= precedence[sym]:
                op = op_stack.pop()
                second = float(operands.pop())
                first = float(operands.pop())
                operands.push( operators[op](first, second) )
            op_stack.push(sym)

    while not operands.size() == 1:
        second = float(operands.pop())
        first = float(operands.pop())
        op = op_stack.pop()
        operands.push( operators[op](first, second) )
    return operands.pop()

if __name__ == "__main__":
    print("Convert infix to postfix:")
    print("A * B + C * D", '\t\t', infix_to_postfix("A * B + C * D"))
    print('( A + B ) * C - ( D - E ) * ( F + G )', '\t\t',
          infix_to_postfix("( A + B ) * C - ( D - E ) * ( F + G )"))

    print("Eval postfix: ")
    print(eval_postfix('17 8 + 3 2 + /'))
    print(eval_postfix('5 3 4 2 - ^ *'))

    print("Eval infix: ")
    print( eval_infix("( 9 / 3 ) ^ ( 1 + 2 )") )


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def login_ogame(browser,URL,loginid,loginpw):
    print("1/3 홈페이지로 접속...", end=" ")
    browser.get(URL)
    print("완료.")

    __login_submit(browser,loginid,loginpw)

def __login_submit(browser,loginid,loginpw):
    print("2/3 로그인...", end=" ")
    WebDriverWait(browser, 20). \
                           until(EC.presence_of_element_located((By.CSS_SELECTOR,"#ui-id-1")))
    browser.find_element_by_css_selector("#ui-id-1").click()
    WebDriverWait(browser, 20). \
                           until(EC.presence_of_element_located((By.CSS_SELECTOR,"#usernameLogin")))
    browser.find_element_by_css_selector("#usernameLogin").send_keys(loginid)
    browser.find_element_by_css_selector("#passwordLogin").send_keys(loginpw)
    browser.find_element_by_css_selector("#loginSubmit").click()
    print("완료.")

    __click_play_button(browser)

def __click_play_button(browser):
    print("3/3 게임으로 들어가는 중...", end=" ")
    WebDriverWait(browser, 20). \
                           until(EC.presence_of_element_located((By.CSS_SELECTOR,"#joinGame > a > button > span")))
    browser.find_element_by_css_selector("#joinGame > a > button > span").click()
    WebDriverWait(browser, 20). \
                           until(EC.presence_of_element_located \
                                 ((By.CSS_SELECTOR,"#accountlist > div > div.rt-table > div.rt-tbody > div > div > div.rt-td.action-cell > button")))
    browser.find_element_by_css_selector("#accountlist > div > div.rt-table > div.rt-tbody > div > div > div.rt-td.action-cell > button").click()
    browser.switch_to.window(browser.window_handles[-1])
    WebDriverWait(browser, 20). \
                           until(EC.presence_of_element_located((By.CSS_SELECTOR,"#menuTable > li:nth-child(9) > a")))
    print("완료.")
    browser.switch_to.window(browser.window_handles[0])
    browser.close()
    browser.switch_to.window(browser.window_handles[-1])


"""
This script focuses on the inference problem in a Gaussian mixture model.

A natural parameterization of the Gaussian mixture model is as the latent variable model:

\mu_1 ... \mu_K ~ N(0, \sigma^2)    # prior on cluster means
\tau_1 ... \tau_K ~ Gamma(a, b)     # prior on precision
w ~ Dirichlet(\alpha)               # mixing distribution
z|w ~ Categorical(w)                # prob of choosing component z
x | z ~ N(\mu_z, \tau_i^{-1})       # data distribution within cluster

We could model the problem exactly as described above except that mixing time can be large
and ineffective exploration of the tails of the distribution.
(See: https://docs.pymc.io/notebooks/gaussian_mixture_model.html )

Source: https://docs.pymc.io/notebooks/marginalized_gaussian_mixture_model.html
"""
from matplotlib import pyplot as plt
import numpy as np
import pymc3 as pm
import seaborn as sns

SEED = 383561

np.random.seed(SEED)  # from random.org, for reproducibility
N = 1000

W = np.array([0.35, 0.4, 0.25])

MU = np.array([0., 2., 5.])
SIGMA = np.array([0.5, 0.5, 1.])

component = np.random.choice(MU.size, size=N, p=W)
x = np.random.normal(MU[component], SIGMA[component], size=N)

# fig, ax = plt.subplots(figsize=(8, 6))

# ax.hist(x, bins=30, density=True, lw=0)
# plt.show()

""" Model Definition """

with pm.Model() as model:
    w = pm.Dirichlet('w', np.ones_like(W))

    mu = pm.Normal('mu', 0., 10., shape=W.size)
    tau = pm.Gamma('tau', 1., 1., shape=W.size)

    x_obs = pm.NormalMixture('x_obs', w, mu, tau=tau, observed=x)

""" Fit Model """
with model:
    trace = pm.sample(5000, n_init=10000, tune=1000, random_seed=SEED)


from os.path import exists
import subprocess

dir2ps={'docs':['paper','presentations'],
        'data':['data_analysed','data_exp'],
        'code':['test','deps'],
       }
dir2info={'docs':'`docs`  \nThis directory contains the manuscripts and presentations.',
        'data':'`data`  \nThis directory contains raw data either retrieved from databases or generated from wet-lab experiments',
        'code':'`code`  \nThis directory contains a git repository which is version controlled.',
        }

for dir1p in dir2ps:
    [subprocess.call(f"mkdir -p {dir1p}/{dir2p}",shell=True) for dir2p in dir2ps[dir1p]]

for dir1p in dir2info:
    with open(f"{dir1p}/README.md", 'w') as f:
        f.write(dir2info[dir1p])

## 1 make 2 analysis directories
from cookiecutter.main import cookiecutter
cookiecutter('https://github.com/rraadd88/template_repo.git',
             no_input=True,
             output_dir='code',
             extra_context={'repo_name': '{{ cookiecutter.repo_name }}'},
            )
## 2 symlinks
coms=[
    'echo "ln -s ../../../data" > code/{{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/create_symlinks.sh',
    'echo "ln -s ../../../../../var" >> code/{{ cookiecutter.repo_name }}/{{ cookiecutter.repo_name }}/create_symlinks.sh',
    'echo "ln -s ../../database" > data/create_symlinks.sh',
]
[subprocess.call(s,shell=True) for s in coms]


from __future__ import print_function
from argparse import ArgumentParser

import Levenshtein as lev
import copy
import sys
import csv

class spdxdata(object):
    def __init__(self, fname):
        self.fname = fname
        self.parser = ""
        self.filerefs = {}
        self.files = set()

class filedata(object):
    def __init__(self, fname, info=None):
        self.fname = fname
        self.licinfo = []
        self.concluded = ""
        if info:
            self.licinfo.append(info)

# Trivial SPDX scan
def read_spdx(filename, spdx):
    with open(filename) as f:
        fname = None
        for line in f.readlines():

            parts = line.split(":", 1)
            key = parts[0].strip()

            if key == 'Creator':
                parts = line.split(":", 2)
                if parts[1].strip() == 'Tool':
                    spdx.parser = parts[2].strip()

            if key == 'FileName':
                if (fname):
                    spdx.filerefs[fname] = fdata

                fname = parts[1].strip().split('/', 1)[1].strip().replace(",", "%2C")
                fdata = filedata(fname)

            if key == 'LicenseConcluded':
                lic = parts[1].strip()
                if lic == 'NONE':
                    lic = 'NOASSERTION'
                fdata.concluced = lic

            if key == 'LicenseInfoInFile':
                lic = parts[1].strip()
                if lic == 'NONE':
                    lic = 'NOASSERTION'
                if lic not in fdata.licinfo:
                    fdata.licinfo.append(lic)

        if fname:
            spdx.filerefs[fname] = fdata
def read_csv(filename, spdx):

    spdx.parser = 'LID'

    with open(filename) as f:
        rdr = csv.reader(f)
        i = 0

        for row in rdr:
            i += 1
            if i == 1:
                continue

            fn = row[0].split('/', 1)[1].strip().replace(",", "%2C")
            lic = row[1]

            fd = spdx.filerefs.pop(fn, filedata(fn))
            if lic not in fd.licinfo:
                fd.licinfo.append(lic)
            spdx.filerefs[fn] = fd


import tkinter
from tkinter import *

top=tkinter.Tk()
def hello():
    text=Text(top)
    text.insert(INSERT,"Hello this is my first Aplication ")
    text.insert(END,"Thanks fo waching my tutorial, if you have any proble just reach out to my")
    text.pack()

B=tkinter.Button(top,text="Mi primer boton GUI",command=hello)
B.pack()
top.mainloop()


"""Pytorch transformer layers definition in trident"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import builtins
import inspect
import math
from collections import OrderedDict
from functools import partial, wraps, update_wrapper
from itertools import islice
from itertools import repeat

import numpy as np
import torch
from torch import  Tensor
import torch.nn as nn
import torch.nn.functional as F  # import torch functions
import torch.utils.hooks as hooks
from torch._jit_internal import List
from collections import abc
from torch.nn import Module
from torch.nn import init
from torch.nn.parameter import Parameter
from trident.layers.pytorch_layers import Embedding,Dropout,Dense

from trident.layers.pytorch_normalizations import LayerNorm

from trident.layers.pytorch_activations import Identity, Gelu

from trident.layers.pytorch_blocks import ShortCut, FullConnect_Block

from trident.backend.common import *
from trident.backend.pytorch_ops import *
from trident.backend.pytorch_backend import Layer, Sequential,get_device,ModuleList

__all__ = ['Mlp','BERT','BERTEmbedding','PositionalEmbedding','PositionwiseFeedForward','DropPath','Attention','MultiHeadedAttention','SublayerConnection','TransformerBlock']

def Mlp(hidden_features=None, out_features=None,dropout_rate=0):
    return Sequential(
        FullConnect_Block(num_filters=hidden_features,activation=Gelu(),dropout_rate=dropout_rate,normalization=None),
        FullConnect_Block(num_filters=out_features, activation=Gelu(), dropout_rate=dropout_rate,normalization=None),
    )

class PositionalEmbedding(Layer):

    def __init__(self, d_model, max_len=512):
        super().__init__()

        # Compute the positional encodings once in log space.
        pe = torch.zeros(max_len, d_model).float().to(get_device())
        pe.require_grad = False

        position = torch.arange(0, max_len).float().unsqueeze(1).to(get_device())
        div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp().to(get_device())

        pe[:, 0::2] = torch.sin(position * div_term)
        pe[:, 1::2] = torch.cos(position * div_term)

        pe = pe.unsqueeze(0)
        self.register_buffer('pe', pe)

    def forward(self, x, **kwargs):
        return self.pe[:, :x.size(1)]

class PositionwiseFeedForward(Layer):
    "Implements FFN equation."

    def __init__(self, d_model, d_ff, dropout_rate=0.1):
        super(PositionwiseFeedForward, self).__init__()
        self.w_1 = nn.Linear(d_model, d_ff)
        self.w_2 = nn.Linear(d_ff, d_model)
        self.dropout = Dropout(dropout_rate)
        self.activation = Gelu()

    def forward(self, x):
        return self.w_2(self.dropout(self.activation(self.w_1(x))))

#
# class PositionEmbeddingSine(Layer):
#     """
#     This is a more standard version of the position embedding, very similar to the one
#     used by the Attention is all you need paper, generalized to work on images.
#     """
#     def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
#         super().__init__()
#         self.num_pos_feats = num_pos_feats
#         self.temperature = temperature
#         self.normalize = normalize
#         if scale is not None and normalize is False:
#             raise ValueError("normalize should be True if scale is passed")
#         if scale is None:
#             scale = 2 * math.pi
#         self.scale = scale
#
#     def forward(self, tensor_list):
#         x = tensor_list.tensors
#         mask = tensor_list.mask
#         assert mask is not None
#         not_mask = ~mask
#         y_embed = not_mask.cumsum(1, dtype=torch.float32)
#         x_embed = not_mask.cumsum(2, dtype=torch.float32)
#         if self.normalize:
#             eps = 1e-6
#             y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
#             x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
#
#         dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
#         dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
#
#         pos_x = x_embed[:, :, :, None] / dim_t
#         pos_y = y_embed[:, :, :, None] / dim_t
#         pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
#         pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
#         pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
#         return pos
#
#
# class PositionEmbeddingLearned(Layer):
#     """
#     Absolute pos embedding, learned.
#     """
#     def __init__(self, num_pos_feats=256):
#         super().__init__()
#         self.row_embed = nn.Embedding(50, num_pos_feats)
#         self.col_embed = nn.Embedding(50, num_pos_feats)
#         self.reset_parameters()
#
#     def reset_parameters(self):
#         nn.init.uniform_(self.row_embed.weight)
#         nn.init.uniform_(self.col_embed.weight)
#
#     def forward(self, tensor_list):
#         x = tensor_list.tensors
#         h, w = x.shape[-2:]
#         i = torch.arange(w, device=x.device)
#         j = torch.arange(h, device=x.device)
#         x_emb = self.col_embed(i)
#         y_emb = self.row_embed(j)
#         pos = torch.cat([
#             x_emb.unsqueeze(0).repeat(h, 1, 1),
#             y_emb.unsqueeze(1).repeat(1, w, 1),
#         ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
#         return pos
#

class BERTEmbedding(Layer):
    """
    BERT Embedding which is consisted with under features
        1. TokenEmbedding : normal embedding matrix
        2. PositionalEmbedding : adding positional information using sin, cos
        2. SegmentEmbedding : adding sentence segment info, (sent_A:1, sent_B:2)
        sum of all these features are output of BERTEmbedding
    """

    def __init__(self, vocab_size, embedding_dim,cls_idx=0,sep_idx=1,unk_idx=2,pad_idx=3,mask_idx=4, dropout_rate=0.1, add_noise=False,noise_intensity=0.05):
        """
        :param vocab_size: total vocab size
        :param embed_size: embedding size of token embedding
        :param dropout: dropout rate
        """
        super().__init__()
        self.token = Embedding(num_embeddings=vocab_size,embedding_dim=embedding_dim,padding_idx=3,add_noise=add_noise,noise_intensity=noise_intensity)
        self.position = PositionalEmbedding(d_model=self.token.embedding_dim)
        self.segment = Embedding(num_embeddings=3,embedding_dim=self.token.embedding_dim,padding_idx=0)
        self.cls_idx=cls_idx
        self.sep_idx=sep_idx
        self.pad_idx=pad_idx
        self.unk_idx=unk_idx
        self.mask_idx=mask_idx
        self.dropout_rate=dropout_rate
        self.dropout = Dropout(dropout_rate)
        self.norm=LayerNorm()
        self.embedding_dim = embedding_dim

    def forward(self, x,segments_tensor=None):
        if segments_tensor is None:
            segments_tensor_list=[]
            B,N=int_shape(x)
            sep_tuples=(x == self.sep_idx).nonzero()(as_tuple=True)
            for i in range(B):
                sep_tuple=sep_tuples[i]
                if len(sep_tuple)<=1:
                    segments_tensor_list.append(zeros_like(x[i]))
                elif  sep_tuple==2:
                    t=zeros_like([i]).detach()
                    sep_tuple[:sep_tuple[0]+1]=1
                    sep_tuple[sep_tuple[0]+1:sep_tuple[1] + 1] = 2
                    segments_tensor_list.append(t)
            segments_tensor=stack(segments_tensor_list,axis=0).to(get_device())

        x = self.token(x) + self.position(x) + self.segment(segments_tensor)
        x=self.norm(x)
        if self.dropout_rate>0 and self.training:
            x=self.dropout(x)
        return x

class DropPath(Layer):
    """Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).
    """
    def __init__(self, drop_prob=0):
        super(DropPath, self).__init__()
        self.drop_prob = drop_prob

    def forward(self, x):
        #return drop_path(x, self.drop_prob, self.training)

        if self.drop_prob == 0. or not self.get_root().training:
            return x
        keep_prob = 1 - self.drop_prob
        shape = (x.shape[0],) + (1,) * (x.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
        random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
        random_tensor.floor_()  # binarize
        output = x.div(keep_prob) * random_tensor
        return output

class Attention(Layer):
    """
    Compute 'Scaled Dot Product Attention
    """

    def forward(self, query, key, value, mask=None, dropout=None):
        scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(query.size(-1))

        if mask is not None:
            scores = scores.masked_fill(mask == 0, -1e9 if scores.dtype == torch.float32 else -1e+4)
        p_attn = softmax(scores,axis=-1)

        if dropout is not None:
            p_attn = dropout(p_attn)

        return torch.matmul(p_attn, value), p_attn

class MultiHeadedAttention(Layer):
    """
    Take in model size and number of heads.
    """

    def __init__(self, h, d_model, dropout_rate=0.1):
        super().__init__()
        assert d_model % h == 0

        # We assume d_v always equals d_k
        self.d_k = d_model // h
        self.h = h

        self.linear_layers = ModuleList([Dense(d_model) for _ in range(3)])
        self.output_linear = Dense(d_model)
        self.attention = Attention()

        self.dropout = Dropout(dropout_rate)

    def forward(self, query, key, value, mask=None):
        batch_size = query.size(0)

        # 1) Do all the linear projections in batch from d_model => h x d_k
        query, key, value = [l(x).view(batch_size, -1, self.h, self.d_k).transpose(1, 2)
                             for l, x in zip(self.linear_layers, (query, key, value))]

        # 2) Apply attention on all the projected vectors in batch.
        x, attn = self.attention(query, key, value, mask=mask, dropout=self.dropout)

        # 3) "Concat" using a view and apply a final linear.
        x = x.transpose(1, 2).contiguous().view(batch_size, -1, self.h * self.d_k)

        return self.output_linear(x)

class SublayerConnection(Layer):
    """
    A residual connection followed by a layer norm.
    Note for code simplicity the norm is first as opposed to last.
    """

    def __init__(self, size, dropout_rate=0.0):
        super(SublayerConnection, self).__init__()
        self.norm = LayerNorm(size)
        self.dropout = Dropout(dropout_rate)

    def forward(self, x,sublayer):
        "Apply residual connection to any sublayer with the same size."
        return x + self.dropout(sublayer(self.norm(x)))

class TransformerBlock(Layer):
    """
    Bidirectional Encoder = Transformer (self-attention)
    Transformer = MultiHead_Attention + Feed_Forward with sublayer connection
    """

    def __init__(self, hidden, attn_heads, feed_forward_hidden, dropout_rate=0.1):
        """
        :param hidden: hidden size of transformer
        :param attn_heads: head sizes of multi-head attention
        :param feed_forward_hidden: feed_forward_hidden, usually 4*hidden_size
        :param dropout: dropout rate
        """

        super().__init__()
        self.attention = MultiHeadedAttention(h=attn_heads, d_model=hidden)
        self.feed_forward = PositionwiseFeedForward(d_model=hidden, d_ff=feed_forward_hidden, dropout_rate=dropout_rate)
        self.input_sublayer = SublayerConnection(size=hidden, dropout_rate=dropout_rate)
        self.output_sublayer = SublayerConnection(size=hidden, dropout_rate=dropout_rate)
        self.dropout = Dropout(dropout_rate=dropout_rate)

    def forward(self, x, mask=None):
        x = self.input_sublayer(x, lambda _x: self.attention.forward(_x, _x, _x, mask=mask))
        x = self.output_sublayer(x, self.feed_forward)
        return self.dropout(x)

class BERT(Layer):
    """
    BERT model : Bidirectional Encoder Representations from Transformers.
    """

    def __init__(self, vocab_size, hidden=768, n_layers=12, attn_heads=12, dropout_rate=0.1,pad_idx=3):
        """
        :param vocab_size: vocab_size of total words
        :param hidden: BERT model hidden size
        :param n_layers: numbers of Transformer blocks(layers)
        :param attn_heads: number of attention heads
        :param dropout: dropout rate
        """

        super().__init__()
        self.hidden = hidden
        self.n_layers = n_layers
        self.attn_heads = attn_heads
        self.pad_idx=pad_idx
        self.dropout_rate=dropout_rate

        # paper noted they used 4*hidden_size for ff_network_hidden_size
        self.feed_forward_hidden = hidden * 4

        # embedding for BERT, sum of positional, segment, token embeddings
        self.embedding = BERTEmbedding(vocab_size=vocab_size, embedding_dim=hidden)
        for i in range(n_layers):
            self.add_module('transformer_block{0}'.format(i),TransformerBlock(hidden, attn_heads, hidden * 4, dropout_rate) )

    def forward(self, x):
        if int_shape(x)[1]==2:
            x,segments_tensor=split(x,num_splits=2,axis=1)
            x=x.squeeze(1)
            segments_tensor=segments_tensor.squeeze(1)
        else:
            segments_tensor = zeros_like(x, dtype=x.dtype).to(get_device())
        # attention masking for padded token
        # torch.ByteTensor([batch_size, 1, seq_len, seq_len)
        mask = (x != self.pad_idx).unsqueeze(1).repeat(1, x.size(1), 1).unsqueeze(1).detach()

        # embedding the indexed sequence to sequence of vectors
        x = self.embedding(x, segments_tensor)

        # running over multiple transformer blocks
        for name,transformer in self.named_children():
            if 'transformer_block' in name:
                x = transformer.forward(x, mask)
        return x


#在_____处填写一行代码
#不允许修改其他代码
#三种颜色值是"green","red","blue"
import turtle as t
colors = ["green","red","blue"]
d = 0
k = 1

for j in range(10):
    t.pencolor(colors[j%3])
    for i in range(8):
        t.fd(k)
        d = d + 360//8
        t.seth(d)
        k += 2
t.done()


# GALHARDO RPG
# Alex Galhardo Vieira
# https://github.com/AlexGalhardo/Galhardo-RPG
# aleexgvieira@gmail.com
# https://galhardoo.com

# !/usr/bin/python3
# coding: utf-8

# ./Python/Functions/Select_Area.py

from Areas.PitsOfInferno_Area import Pits_Of_Inferno_Start_Gameplay

def Select_Area():

	while True:

		print('\n\t --- Chose a area to play ---')
		print('\n\t Enter [1] --> Pits of Inferno --> EASY')
		print('\t Enter [2] --> Inquisition Quest --> MEDIUM')
		print('\t Enter [3] --> Ferumbras Tower --> HARD')
		print('\t Enter [4] --> Play all areas --> Full Game Experience')

		areaOption = int(input('\t Area Option: '))

		if areaOption < 1 or areaOption > 4:
			print('\t Choose a valid option!')
			continue
		elif areaOption == 1:
			return 1
			break
		elif areaOption == 2:
			return 2
			break
		elif areaOption == 3:
			return 3
			break
		else:
			return 4
			break

def Adventure_Game_Start( selectedArea, Player ):

	if selectedArea == 1:
		Pits_Of_Inferno_Start_Gameplay( Player )

	elif selectedArea == 2:
		Game_Of_Thrones_Start_Gameplay( Player )

	elif selectedArea == 3:
		Star_Wars_Start_Gameplay( Player )

	else:
		Full_Game_Start( Player )

# The MIT License (MIT)
# Copyright (c) 2018 Alex Galhardo
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.