import base64
import errno
#from json import dumps
import json
import math
import os
import sys
import urllib
import urllib.parse
import urllib.request
import urllib.response
import uuid

import numpy as np
import tensorflow as tf
from bottle import request, response, route, run

#from flask import Flask

WORKING_DIRECTORY = "tf_files"
TMP_DIRECTORY = "tmp"
TRAINED_LABELS = "%s/retrained_labels.txt" % (WORKING_DIRECTORY)
RETRAINED_GRAPH = "%s/retrained_graph.pb" % (WORKING_DIRECTORY)

#data = []
input_height = 299
input_width = 299
input_mean = 0
input_std = 255
filer = uuid.uuid4().hex
#app = Flask(__name__)

def load_graph(model_file):
    graph = tf.Graph()
    graph_def = tf.GraphDef()

    with open(model_file, "rb") as f:
        graph_def.ParseFromString(f.read())
    with graph.as_default():
        tf.import_graph_def(graph_def)
    return graph

@route('/classify_image/', method='POST')
def index():
    response.content_type='application/json'
    #json = []
    print(request.json['data'])
    for info in request.json['data']:
        '''
        if (info['type'] == 'local'):
            path = save_image(info['path'], info['ext'])
            #json[info['path']] = score(info['path'])
        else:
            path = download_image(info['path'], info['ext'])
        '''
        path = save_image(info['image64'])
        jsonF = score(path)

        # Octopart API Searches the Octopart database
        url = "http://octopart.com/api/v3/parts/search"
        url += "?apikey="
        url += "6aa164d3"
        args = [
            ('q', jsonF[0]),
            ('include', 'short_description'),
            ('start', 0),
            ('limit', 1)
        ]
        url += '&' + urllib.parse.urlencode(args)

        data = urllib.request.urlopen(url).read().decode()
        searchResponse = json.loads(data)
        for item in searchResponse['results']:
            jsonStream = item['item']

        uid = jsonStream['uid']
        brandName = jsonStream['brand']['name']
        manufacturer = jsonStream['manufacturer']['name']
        octopartUrl = jsonStream['octopart_url']
        shortDescription = jsonStream['short_description']

        # Performs a part-match with Octopart and includes the tech specs
        url2 = 'http://octopart.com/api/v3/parts/'
        url2 += uid
        url2 += '?apikey='
        url2 += "6aa164d3"
        url2 += '&include[]=specs'
        url2 += '&include[]=imagesets'
        url2 += '&include[]=descriptions'
        data2 = json.loads(urllib.request.urlopen(url2).read().decode())

        specJson = data2['specs']
        specArray = []
        for specName in specJson:
            tmpSpec = specJson[specName]
            name = tmpSpec['metadata']['name']
            value = tmpSpec['display_value']
            specArray.append([name, value])

        descArray = []
        if data2['descriptions']:
            for i in range(0, len(data2['descriptions'])):
                descArray.append(data2['descriptions'][i]['value'])

        specs = specArray
        descriptions = descArray

        #print(data2['imagesets'])
        ident = { "Component": jsonF[0], "Predictions": jsonF[1], "ShortInfo": shortDescription, "octopartUrl": octopartUrl, "brandName": brandName, "manufacturer": manufacturer, "specs": specs, "descriptions": descriptions }
        os.remove(path)
        print (ident)
    return dict(ident)

@route('/status/', method='GET')
def status():
    return 'online'

@route('/', method='GET')
def getHome():
    return status()

def save_image(based):
    '''
    image = open('index.jpg', 'rb')
    image_read = image.read()
    image_64_encode = base64.encodestring(image_read)
    imgdata = base64.b64decode(image_64_encode)
    '''
    based += "=" * ((4 - len(based) % 4) % 4) # add extra padding
    extension = based.split(";")[0].split("/")[1]
    imgdata = base64.b64decode(based.split(",")[1])
    filename = "{}/{}.{}".format(TMP_DIRECTORY,uuid.uuid4(),extension)
    with open(filename, 'wb') as f:
        f.write(imgdata)
    return filename

'''
def download_image(url, extension):
    filename = TMP_DIRECTORY + '/' + uuid.uuid4().hex + extension
    urllib.request.urlretrieve(url, filename)
    return filename
'''

def create_tmp(path):
    try:
        os.makedirs(path)
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

def read_tensor_from_image_file(file_name,
                                input_height=299,
                                input_width=299,
                                input_mean=0,
                                input_std=255):
    input_name = "file_reader"
    file_reader = tf.read_file(file_name, input_name)
    '''
    if file_name.endswith(".png"):
        image_reader = tf.image.decode_png(
            file_reader, channels=3, name="png_reader")
    elif file_name.endswith(".gif"):
        image_reader = tf.squeeze(
            tf.image.decode_gif(file_reader, name="gif_reader"))
    elif file_name.endswith(".bmp"):
        image_reader = tf.image.decode_bmp(file_reader, name="bmp_reader")
    else:
        image_reader = tf.image.decode_jpeg(
            file_reader, channels=3, name="jpeg_reader")
    '''
    image_reader = tf.image.decode_jpeg(file_reader, channels=3, name="jpeg_reader")
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0)
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
    with tf.Session() as sess:
        result = sess.run(normalized)
    return result

def load_labels(label_file):
    label = []
    proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
    for l in proto_as_ascii_lines:
        label.append(l.rstrip())
    return label

def score(image_path):
    t = read_tensor_from_image_file(
        image_path,
        input_height=input_height,
        input_width=input_width,
        input_mean=input_mean,
        input_std=input_std)

    with tf.Session(graph=graph) as sess:
        results = sess.run(output_operation.outputs[0], {
            input_operation.outputs[0]: t
        })
    results = np.squeeze(results)
    top_k = results.argsort()[-1:][::-1]
    labels = load_labels(TRAINED_LABELS)
    data =[]
    for i in top_k:
        #print(labels[i], results[i])
        human_string = labels[i]
        score = results[i]
        #data.append('%s:%.5f' % (human_string, score*100))
        data.append('%s' % (human_string))
        data.append('%.5f' % (score * 100))
    return data

graph = load_graph(RETRAINED_GRAPH)
input_name = "import/" + "Placeholder"
output_name = "import/" + "final_result"
input_operation = graph.get_operation_by_name(input_name)
output_operation = graph.get_operation_by_name(output_name)

create_tmp('tmp')
#run(host='127.0.0.1', port=8989, debug=True)
run(host='0.0.0.0', port=os.environ.get('PORT', 8080))


import logging
from dataclasses import dataclass

from core import AppConfig

config = AppConfig.getInstance()

@dataclass
class Game:
	name: str
	version: str
	path: str
	command: str
	ready_log: str
	timeout: str
	enabled: bool

	@classmethod
	def get_game(cls, name, version=None):

		# get capitalized name (makes case insensitive)
		for game in config.games.keys():
			if(game.lower() == name.lower()):
				name = game
				break

		if(name not in config.games):
			raise ValueError("Game not found")

		game_config = config.games[name]

		if(version is not None and "versions" not in game_config):
			raise ValueError("This game does not have alternative versions.")

		# get capitalized version (makes case insensitive)
		if(version is not None):
			for game_version in game_config["versions"].keys():
				if(game_version.lower() == version.lower()):
					version = game_version
					break

		if("versions" in config.games[name]):

			# if there are version listed and no version specified
			if(version is None and "default" not in game_config):
				raise ValueError(f"The game '{name}' does not have a default version.")

			# set the default version if version is none
			if(version is None):
				version = game_config["default"]

			# if version specified does not exist
			if(version not in game_config["versions"]):
				raise ValueError(f"Version '{version}' not found for '{name}'.")

		if(version is not None):
			path = game_config["versions"][version]["path"]
			command = game_config["versions"][version]["command"]
			ready_log = game_config["versions"][version]["readyLog"]
			timeout = game_config["versions"][version]["timeout"]
			if("enabled" in game_config["versions"][version]):
				enabled = game_config["versions"][version]["enabled"]
			else:
				enabled = True
		else:
			path = game_config["path"]
			command = game_config["command"]
			ready_log = game_config["readyLog"]
			timeout = game_config["timeout"]
			if("enabled" in game_config):
				enabled = game_config["enabled"]
			else:
				enabled = True

		return Game(
			name=name,
			version=version,
			path=path,
			command=command,
			ready_log=ready_log,
			timeout=timeout,
			enabled=enabled
		)


if __name__ == "__main__" or __name__ == "quick_sort":
    from common.util import *
else:
    from .common.util import *

def partition(collection: list, left: int, right: int) -> int:
    """pivot값은 가장 오른쪽으로 설정

    Args:
        collection (list): 전체 데이터
        left (int): 파티션의 왼쪽 시작 인덱스
        right (int): 파티션의 오른쪽 끝 인덱스

    Returns:
        int: 피봇 인덱스

    Example:
        >>> partition([9, 8, 7, 6, 5, 4, 3, 2, 1], 3, 6)
        5
    """

    pivot = collection[right]
    i = left
    j = right - 1
    while True:
        while collection[i] < pivot:
            i += 1
        while collection[j] > pivot:
            j -= 1

        if i >= j:
            break

        swap(collection, i, j)

    swap(collection, i, right)

    return i

def quick_sort(collection, verbose=False):
    """
    퀵 정렬 알고리즘
    재귀적 호출이 아닌 stack을 사용하여 구현되었음

    Args:
        collection (list): 유저로부터 입력받은 정렬 리스트
        verbose (bool): 과정들을 출력하기 위한 flag

    Returns:
        list: 정렬된 리스트

    Example:
        >>> quick_sort([6, 5, 4, 3, 2, 1])
        [1, 2, 3, 4, 5, 6]

        >>> quick_sort([-154, -91, -27])
        [-154, -91, -27]

        >>> quick_sort([])
        []
    """

    stack = list()

    stack.append(0)  # l
    stack.append(len(collection) - 1)  # r

    while len(stack) > 0:
        r = stack.pop()
        l = stack.pop()

        # subarray의 크기가 1 또는 0인 경우 partition으로 나눌 필요 없음
        if l >= r:
            continue

        if verbose:
            print(f"{'    '*len(stack)}Partition {collection[l:r+1]}", end="")
        p = partition(collection, l, r)
        if verbose:
            print(f", pivot: {collection[p]}")
        print(f"{'    '*len(stack)}Sorted {collection}")

        # Elements on right
        if p + 1 < r:
            stack.append(p + 1)
            stack.append(r)

        # Elements on left
        if l < p - 1:
            stack.append(l)
            stack.append(p - 1)

    return collection

if __name__ == "__main__":
    from common.invoker import from_input
    from_input(quick_sort, True)


import numpy as np
import pickle

from sacred import Experiment
from sacred.observers import FileStorageObserver

from codebase.data import utils

from collections import OrderedDict

from sklearn.linear_model import BayesianRidge
from sklearn.model_selection import RepeatedKFold
from sklearn.preprocessing import StandardScaler, PowerTransformer

ex = Experiment()

ex.observers.append(FileStorageObserver('./out/Linear/bayes'))

@ex.config
def bayes_config():
    target_col = ['nepedheight1019(m3)']

    numerical_cols = ['averagetriangularity', 'a(m)', 'Ip(MA)', 'P_NBI(MW)',
                      'plasmavolume(m3)', 'P_TOTPNBIPohmPICRHPshi(MW)', 'q95',
                      'gasflowrateofmainspecies1022(es)', 'B(T)', 'P_ICRH(MW)', 'H(HD)',
                      'Meff']
    scale_data = None

@ex.capture
def get_model():
    return BayesianRidge(compute_score=True)

def calculate_scores(predictions, targets):
    """
    Calculate the RMSE, MAE
    """
    RMSE = np.sqrt(np.mean((predictions - targets) ** 2))
    MAE = (np.sum(np.abs(predictions - targets))) / len(predictions)
    return RMSE, MAE

def unravel_all(ordered_error, ordered_yvals, ordered_preds):
    list_uncert = []
    list_yvals = []
    list_preds = []
    for index in ordered_error.keys():
        list_uncert.append(np.mean(ordered_error[index]))
        list_yvals.append(np.mean(ordered_yvals[index]))
        list_preds.append(np.mean(ordered_preds[index]))
    return list_yvals, list_preds, list_uncert

@ex.automain
def main(target_col, numerical_cols, scale_data):
    feature_space, target_space, _, _, = utils.process_data(target_col, numerical_cols)

    if scale_data is not None:
        feat_scale = scale_data
        X = feat_scale.fit_transform(feature_space)
        y = target_space.to_numpy().ravel()
    else:
        X = feature_space.to_numpy()
        y = target_space.to_numpy().ravel()
    ordered_preds = OrderedDict((index, []) for index in feature_space.index.to_list())
    ordered_error = OrderedDict((index, []) for index in feature_space.index.to_list())
    ordered_yvals = OrderedDict((index, []) for index in feature_space.index.to_list())
    error_dict = {'MAE': [], 'RMSE': []}
    cv = RepeatedKFold(n_splits=5, n_repeats=5)

    for cv_id, (train, test) in enumerate(cv.split(X)):
        X_train, X_test = X[train], X[test]
        y_train, y_test = y[train], y[test]
        model = get_model()
        model.fit(X_train, y_train)
        # print(model.scores_)
        mean_preds, std_preds = model.predict(X_test, return_std=True)
        for index, std, mean_pred, yval in zip(test, std_preds, mean_preds, y_test):
            ordered_error[index].append(std)
            ordered_preds[index].append(mean_pred)
            ordered_yvals[index].append(yval)
        RMSE, MAE = calculate_scores(mean_preds, y_test)
        error_dict['RMSE'].append(RMSE)
        error_dict['MAE'].append(MAE)

    list_yvals, list_preds, list_uncert = unravel_all(ordered_error, ordered_yvals, ordered_preds)

    scores = {'RMSE': (np.mean(error_dict['RMSE']), np.std(error_dict['RMSE'])),
              'MAE': (np.mean(error_dict['MAE']), np.std(error_dict['MAE']))}
    results = {'y_vals': np.array(list_yvals), 'preds': np.array(list_preds), 'uncert': np.array(list_uncert),
               'score': scores}
    with open('./out/Linear/bayes_lin_reg.pickle', 'wb') as file:
        pickle.dump(results, file)
    ex.add_artifact('./out/Linear/bayes_lin_reg.pickle')
    utils.plot_predictions(list_preds, list_yvals)

    return results


"""empty message

Revision ID: 60feda05ef56
Revises: 2519a08b90aa
Create Date: 2022-08-07 11:48:23.001390

"""
from alembic import op
from sqlalchemy import and_, MetaData, Table, delete, Column, VARCHAR, INTEGER, TIMESTAMP
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION

# revision identifiers, used by Alembic.
revision = '60feda05ef56'
down_revision = 'c43b5e3e04d4'
branch_labels = None
depends_on = None

Meta = MetaData(bind=op.get_bind())

driver = Table(
    'driver',
    Meta,
    Column('id', INTEGER, primary_key=True),
    Column('name', VARCHAR(50), nullable=False),
    Column('last_name', VARCHAR(50), nullable=False),
    Column('login', VARCHAR(50), unique=True, nullable=False),
    Column('city', VARCHAR(30), nullable=True)
)

spaceship = Table(
    'spaceship',
    Meta,
    Column('id', INTEGER, primary_key=True),
    Column('ship_number', VARCHAR(50), nullable=False),
    Column('model_id', INTEGER, nullable=True)
)
spaceship_manufacturer = Table(
    'spaceship_manufacturer',
    Meta,
    Column('id', INTEGER, primary_key=True),
    Column('company_name', VARCHAR(50), nullable=False),
    Column('country', VARCHAR(50), nullable=True),
    Column('nasdaq_code', VARCHAR(50), nullable=True)
)

spaceship_model = Table(
    'spaceship_model',
    Meta,
    Column('id', INTEGER, primary_key=True),
    Column('manufacturer_id', INTEGER, nullable=False),
    Column('model_name', VARCHAR(50), nullable=True),
    Column('horsepower', DOUBLE_PRECISION, nullable=False)
)

spaceship_rent = Table(
    'spaceship_rent',
    Meta,
    Column('driver_id', INTEGER, nullable=False, primary_key=True),
    Column('spaceship_id', INTEGER, nullable=False, primary_key=True),
    Column('rent_start', TIMESTAMP, nullable=False),
    Column('rent_end', TIMESTAMP, nullable=False)
)

def upgrade() -> None:
    Meta.reflect(only=(
        'spaceship_rent',
        'spaceship_model',
        'spaceship_manufacturer',
        'spaceship',
        'driver'
    ))
    op.bulk_insert(
        spaceship_manufacturer,
        [
            {"id": 1, "company_name": "Ford Nuclear Engine", "country": "USA", "nasdaq_code": "frdne"},
            {"id": 2, "company_name": "Cosmical Motors", "country": "USA", "nasdaq_code": "cosmot"},
            {"id": 3, "company_name": "Автокосмоваз", "country": "RU", "nasdaq_code": "acaz"},
            {"id": 4, "company_name": "BNW", "country": "GE", "nasdaq_code": "bnw"},
        ]
    )
    op.bulk_insert(
        spaceship_model,
        [
            {"id": 1, "manufacturer_id": 1, "model_name": "Aerostar", "horsepower": 170135000},
            {"id": 2, "manufacturer_id": 2, "model_name": "Stardilac", "horsepower": 175000000},
            {"id": 3, "manufacturer_id": 3, "model_name": "Lada Moonta", "horsepower": 240000000},
            {"id": 4, "manufacturer_id": 4, "model_name": "X5000", "horsepower": 190000000},
        ]
    )
    op.bulk_insert(
        spaceship,
        [
            {"id": 1, "ship_number": "A300BC 177", "model_id": 3},
            {"id": 2, "ship_number": "A245BC 177", "model_id": 1},
            {"id": 3, "ship_number": "A412RE 76", "model_id": 2},
            {"id": 4, "ship_number": "X078BA 76", "model_id": 4},
        ]
    )
    op.bulk_insert(
        driver,
        [
            {"id": 1, "name": "Arcady", "last_name": "Volozh", "login": "volozh.a", "city": "Moscow"},
            {"id": 2, "name": "Lena", "last_name": "Bunina", "login": "bunina.e", "city": "Tel-Aviv"},
            {"id": 3, "name": "David", "last_name": "Patterson", "login": "patterson.d", "city": "Berkeley"},
            {"id": 4, "name": "James", "last_name": "Gosling", "login": "gosling.j", "city": "San José"},
            {"id": 5, "name": "Elon", "last_name": "Musk", "login": "elon", "city": "Boca Chica Village"},
        ]
    )
    op.bulk_insert(
        spaceship_rent,
        [
            {"driver_id": 1, "spaceship_id": 3, "rent_start": "2059-07-25 11:13:54", "rent_end": "2059-09-30 11:14:04"},
            {"driver_id": 2, "spaceship_id": 4, "rent_start": "2060-06-24 11:14:23", "rent_end": "2064-07-31 11:14:35"},
            {"driver_id": 3, "spaceship_id": 2, "rent_start": "2055-12-24 11:14:55", "rent_end": "2061-11-01 11:15:05"},
            {"driver_id": 4, "spaceship_id": 1, "rent_start": "2059-12-31 11:15:27", "rent_end": "2060-02-29 11:15:36"},
            {"driver_id": 5, "spaceship_id": 3, "rent_start": "2022-07-15 11:23:35", "rent_end": "2059-07-31 11:23:46"},
        ]
    )

def downgrade() -> None:
    # SpaceshipRent
    op.execute(delete(spaceship_rent).where(
        and_(
            spaceship_rent.c.driver_id == 1,
            spaceship_rent.c.spaceship_id == 3,
            spaceship_rent.c.rent_start == "2059-07-25 11:13:54",
            spaceship_rent.c.rent_end == "2059-09-30 11:14:04",
        )
    )
    )
    op.execute(delete(spaceship_rent).where(
        and_(
            spaceship_rent.c.driver_id == 2,
            spaceship_rent.c.spaceship_id == 4,
            spaceship_rent.c.rent_start == "2060-06-24 11:14:23",
            spaceship_rent.c.rent_end == "2064-07-31 11:14:35",
        )
    )
    )
    op.execute(delete(spaceship_rent).where(
        and_(
            spaceship_rent.c.driver_id == 3,
            spaceship_rent.c.spaceship_id == 2,
            spaceship_rent.c.rent_start == "2055-12-24 11:14:55",
            spaceship_rent.c.rent_end == "2061-11-01 11:15:05",
        )
    )
    )
    op.execute(delete(spaceship_rent).where(
        and_(
            spaceship_rent.c.driver_id == 4,
            spaceship_rent.c.spaceship_id == 1,
            spaceship_rent.c.rent_start == "2059-12-31 11:15:27",
            spaceship_rent.c.rent_end == "2060-02-29 11:15:36",
        )
    )
    )
    op.execute(delete(spaceship_rent).where(
        and_(
            spaceship_rent.c.driver_id == 5,
            spaceship_rent.c.spaceship_id == 3,
            spaceship_rent.c.rent_start == "2022-07-15 11:23:35",
            spaceship_rent.c.rent_end == "2059-07-31 11:23:46",
        )
    )
    )

    # Driver
    op.execute(delete(driver).where(driver.c.id.in_([1, 2, 3, 4, 5])))
    # Spaceship
    op.execute(delete(spaceship).where(spaceship.c.id.in_([1, 2, 3, 4])))
    # SpaceshipModel
    op.execute(delete(spaceship_model).where(spaceship_model.c.id.in_([1, 2, 3, 4])))
    # SpaceshipManufacturer
    op.execute(delete(spaceship_manufacturer).where(spaceship_manufacturer.c.id.in_([1, 2, 3, 4])))

4. Миграции баз данных/migrations/python/migrations/versions/migration_2.py


# Import pandas using the alias pd
import pandas as pd

homelessness = pd.read_csv('datasets/homelessness.csv')

# Filter for rows where individuals is greater than 10000
ind_gt_10k = homelessness[homelessness['individuals'] > 10000]

# See the result
print(ind_gt_10k)


import pyxel

WIDTH = 128
HEIGHT = 128
IMG_NO = 0

class App:
    my_x = 0
    my_y = 0

    def __init__(self):
        pyxel.init(WIDTH, HEIGHT)
        pyxel.load("mychara.pyxres")
        pyxel.run(self.update, self.draw)

    def update(self):
        self.my_x = pyxel.mouse_x
        self.my_y = pyxel.mouse_y

    def draw(self):
        pyxel.cls(7)
        pyxel.blt(self.my_x, self.my_y, IMG_NO, 0, 0, 16, 16, 0)

App()


#1758: 알바생 강호

"""
문제:
손님들은 입구에 들어갈 때, 강호에게 팁을 준다. 손님들은 자기가 커피를 몇 번째 받는지에 따라 팁을 다른 액수로 강호에게 준다.
각 손님은 강호에게 원래 주려고 생각했던 돈 - (받은 등수 - 1) 만큼의 팁을 강호에게 준다.
만약, 위의 식으로 나온 값이 음수라면, 강호는 팁을 받을 수 없다.
예를 들어, 민호는 팁을 3원 주려고 했고, 재필이는 팁을 2원, 주현이가 팁을 1원 주려고 한 경우를 생각해보자.
민호, 재필, 주현이 순서대로 줄을 서있다면, 민호는 강호에게 3-(1-1) = 3원, 재필이는 2-(2-1) = 1원, 주현이는 1-(3-1) = -1원을 팁으로 주게 된다.
주현이는 음수이기 때문에, 강호에게 팁을 주지 않는다. 따라서, 강호는 팁을 3+1+0=4원을 받게 된다.
스타박스 앞에 있는 사람의 수 N과, 각 사람이 주려고 생각하는 팁이 주어질 때, 손님의 순서를 적절히 바꿨을 때,
강호가 받을 수 잇는 팁의 최댓값을 구하는 프로그램을 작성하시오.
"""
N = int(input())
tips = []
maxtip = 0

for _ in range(N):
    tips.append(int(input()))

tips.sort(reverse=True)

for i in range(len(tips)):
    if tips[i] - i > 0:
        maxtip += (tips[i] - i)
    else:
        break

print(maxtip)


import numpy as np
import tensorflow as tf
import cv2
import random
from skimage import io
from skimage.color import gray2rgb, rgb2gray

class LearningRateLogger(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        lr = self.model.optimizer.lr
        if isinstance(lr, tf.keras.optimizers.schedules.LearningRateSchedule):
            lr = lr(self.model.optimizer.iterations)
        print("\nLearning Rate at end of epoch {}: {}".format(epoch, lr.numpy()))

def generate_random_subset(data, labels, subset_size):
    """
    Generates a random subset of data and labels.

    Args:
        data (numpy.ndarray): The input data.
        labels (numpy.ndarray): The corresponding labels.
        subset_size (int): The desired size of the random subset.

    Returns:
        numpy.ndarray: The random subset of data.
        numpy.ndarray: The corresponding random subset of labels.
    """
    # Check if the subset size is not larger than the dataset size
    if subset_size > len(data):
        raise ValueError("Subset size is larger than the dataset size.")

    # Generate random indices to select the subset
    random_indices = np.random.choice(len(data), subset_size, replace=False)

    # Select the subset of data and labels based on the random indices
    subset_data = data[random_indices]
    subset_labels = labels[random_indices]

    augmented_subset = [[],[]]
    for i in range(len(subset_data)):
        [aug_image, rotation_angle] = augment_image(subset_data[i])
        augmented_subset[0].append(aug_image)
        # rotate the label
        augmented_subset[1].append(rotate_image(subset_labels[i], rotation_angle))

    return subset_data, subset_labels, [np.array(augmented_subset[0]), np.array(augmented_subset[1])]

def rotate_image(image, angle_degrees):
    # Get image dimensions
    height, width = image.shape

    # Calculate the rotation matrix
    rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), angle_degrees, 1)

    # Perform the rotation
    rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height), flags=cv2.INTER_LINEAR)

    return rotated_image

def add_noise_to_image(image, intensity):
    """
    Add specks of noise to a normalized image.

    Parameters:
    - image: Normalized input image (values in range [0, 1]).
    - intensity: Intensity of the noise (0.0 to 1.0).

    Returns:
    - Noisy image (still in the range [0, 1]).
    """
    noisy_image = np.copy(image)
    height, width = image.shape[:2]

    # Calculate the number of noisy pixels to add based on intensity
    num_noisy_pixels = int(intensity * height * width)

    # Generate random pixel coordinates for noisy pixels
    noisy_coords = np.random.randint(0, height, num_noisy_pixels), np.random.randint(0, width, num_noisy_pixels)

    # Set those pixels to random noise values in the range [0, 1]
    noisy_image[noisy_coords] = np.random.rand(num_noisy_pixels)

    return noisy_image

def scale_intensity(image, scale_factor):
    """
    Scale the intensity (brightness) of an image by a specified factor.

    Parameters:
    - image: Input image.
    - scale_factor: Factor by which to scale the intensity.

    Returns:
    - Scaled image.
    """
    scaled_image = np.copy(image)

    # Scale the intensity by multiplying all pixel values by the scale factor
    scaled_image *= scale_factor

    # Ensure pixel values are still in the valid range [0, 255]
    scaled_image = np.clip(scaled_image, 0, 1)

    # Convert back to the appropriate data type (e.g., uint8)
    #scaled_image = scaled_image.astype(np.uint8)

    return scaled_image

def augment_image(image):
    reset_RGB = False
    if len(image.shape) > 2:
        reset_RGB = True
        image = rgb2gray(image)
    rotation_angle = random.uniform(-180, 180)
    noise_intensity = random.uniform(0,0.1)
    brightness_scale = random.uniform(0.8,1.2)

    augmented = add_noise_to_image(image,noise_intensity)
    augmented = rotate_image(augmented, rotation_angle)
    augmented = scale_intensity(augmented, brightness_scale)
    if reset_RGB:
        augmented = gray2rgb(augmented)

    return [augmented, rotation_angle]


def divisors(num):
    try:
        if (num < 0):
            raise ValueError("Solo numeros positivos.")
        return [i for i in range(1, num + 1) if num % i == 0]
    except ValueError as ve:
        print(ve)
        return False

def run():
    try:
        print(divisors(int(input("Ingresa un número:"))))
        print("End.")
    except ValueError:
        print("Caracter invalido.")

if __name__ == '__main__':
    run()


"""
    作者：陆震
    功能：52周存钱挑战
    版本：5.0
    日期：22/05/2019
    5.0 新增功能：根据用户输入的日期，判断是一年中的第几周，然后输出相应的存款金额
"""

# math库
import math
import datetime

# 圆周率 math.pi
# 对x向上取整 math.ceil(x)
# 对x向下取整 math.floor(x)
# x的y次方 math.pow(x, y)
# x的平方根 math.sqrt(x)

# 52周存钱法，即52周阶梯式存钱法，是国际上非常流行的存钱方法
# 按照52周存钱法，存钱的人必须在一年52周内，每周递存10元，这样一年下来会有13780元

# for循环：使用for语句可以循环遍历整个序列的内容
# 循环变量x在每次循环时，被赋值成对应的元素内容
# 与while循环的区别：for循环的次数固定，即所遍历的序列长度，而while为无限循环
# range(n)返回一个可迭代的对象，从0开始计数，为range类型，list(range(n))将迭代类型转换为列表类型

# 全局变量
saving = 0

def save_money_in_n_weeks(total_weeks, money_per_week, increase_money):
    """
        计算n周内的存款金额
    """
    money_list = []  # 记录每周存款数的列表
    saving_list = []  # 记录每周存款总金额的列表
    global saving  # 声明此处函数里的saving是全局变量而非局部变量

    for i in range(total_weeks):
        # 存钱操作
        # saving += money_per_week
        money_list.append(money_per_week)  # 将元素添加到列表末尾
        saving_list.append(saving)
        # 对列表元素排序 list.sort()
        # 对列表元素逆序 list.reverse()
        # 返回第一次出现元素x的索引值 list.index(x)
        # 在位置i前插入新元素x list.insert(i, x)
        # 返回元素x在列表中的数量 list.count(x)
        # 删除列表中第一次出现的元素x list.remove()
        # 取出列表中i位置上的元素，并将其从列表中删除 list.pop(i)

        saving = math.fsum(money_list)  # 对集合内的元素求和
        # print('第{0}周，存入{2}元，现有存款总共是{1}元'.format(i + 1, saving, money_per_week))
        # 更新下一周的存钱操作
        # i += 1  # while循环需要记录循环次数
        money_per_week += increase_money
    return saving_list

def main():
    """
        主函数
    """
    money_per_week = float(input('请输入每周存入的金额：'))
    # i = 1  # 周数，初始为1周
    increase_money = float(input('请输入每周递增的金额：'))
    total_weeks = int(input('请输入总共的周数：'))  # 总共的周数
    # 函数的参数传递：函数通过参数与调用程序传递信息
    # 变量的作用范围：
    # 1.局部：函数内的变量作用范围只在函数内
    # 2.全局：函数外的变量，在所有函数中都能使用
    # 函数的形参只接收实参的值，给形参赋值并不影响实参
    # global saving
    saving_list = save_money_in_n_weeks(total_weeks, money_per_week, increase_money)
    data_str = input('请输入当前日期(yyyy/mm/dd)：')
    input_date = datetime.datetime.strptime(data_str, '%Y/%m/%d')

    # datetime库：处理时间的标准函数库datetime
    # datetime.datetime.now()获取当前日期和时间
    # 字符串转换成datetime，使用datetime.strptime()解析时间字符串，如datetime.datetime.strptime(a, "%Y/%m/%d")
    # isocalendar()返回年，周数及周几
    # datetime转换为字符串，使用strftime()格式化datetime为字符串，如datetime.datetime.strftime(a, '%d%m%Y')
    week_num = input_date.isocalendar()[1]
    print('第{}周的存款总金额是{}元'.format(week_num, saving_list[week_num - 1]))

if __name__ == '__main__':
    main()


import os

from datetime import datetime

from helix.database.database import DatabaseObject
from helix.database.show import Show
from helix.database.sequence import Sequence
from helix.database.shot import Shot
from helix.database.element import Element
from helix.database.person import Person
import helix.environment.environment as env
import helix.utils.utils as utils

class Fix(DatabaseObject):
	TABLE = 'fixes'
	PK = 'id'
	STATUS = {
		0: 'new',
		1: 'assigned',
		2: 'ip',
		3: 'review',
		4: 'done'
	}
	PRIORITY = {
		0: 'Very Low',
		1: '',
		2: '',
		3: 'Normal',
		4: '',
		5: 'Medium',
		6: '',
		7: '',
		8: '',
		9: '',
		10: 'Critical'
	}

	TYPE_FIX = 'fix'
	TYPE_TASK = 'task'
	TYPES = [TYPE_TASK, TYPE_FIX]

	def __init__(self, fixType, title, body, dept, show=None, sequence=None, shot=None, clipName=None, elementName=None, elementType=None, author=None, status=STATUS[0], priority=3, dummy=False):
		self.table = Fix.TABLE
		self.commentList = []

		if dummy:
			return

		self.title = title
		self.body = body
		self.show = show if show else env.getEnvironment('show')
		self.sequence = sequence
		self.shot = shot
		self.elementName = elementName
		self.elementType = elementType
		self._exists = None

		self.sequenceId = None
		self.shotId = None
		self.elementId = None

		if not title:
			raise ValueError('Must specify a fix title')

		if not body:
			raise ValueError('Must specify details for the fix in the body text')

		if not self.show:
			raise ValueError('Tried to fallback to environment-set show, but it was null.')

		fetched = self.exists(fetch=True)

		if fetched:
			self.unmap(fetched)
			self._exists = True
		else:
			creationInfo = env.getCreationInfo(format=False)
			self.type = fixType.lower()
			self.author = author if author else creationInfo[0]
			self.creation = creationInfo[1]
			self.status = status if status in Fix.STATUS.values() else Fix.STATUS[0]
			self.priority = priority if priority in Fix.PRIORITY.keys() else 3
			self.fixer = None
			self.fix_date = None
			self.deadline = None
			self.assign_date = None
			self.num = Fix.nextFixNum(self.show)
			self.for_dept = dept.lower()

			if self.type not in Fix.TYPES:
				raise ValueError('Type must be one of: {}, not: {}'.format(', '.join(Fix.TYPES, self.type)))

			if self.for_dept not in env.cfg.departments and self.for_dept != 'general':
				raise ValueError('Invalid department ({}) to assign fix to. Options are: {}'.format(self.for_dept, ', '.join(['general'] + env.cfg.departments)))

			s = Show.fromPk(self.show)

			if not s:
				raise ValueError('No such show: {}'.format(show))

			p = Person(self.author)

			if not p.exists():
				raise ValueError('No such user: {}'.format(self.author))

			if self.sequence is not None:
				try:
					self.sequence = int(self.sequence)
				except ValueError:
					raise ValueError('Sequence number must be a number, not: {}'.format(self.sequence))

				sq = Sequence(self.sequence, show=self.show)

				if not sq.exists():
					raise ValueError('No such sequence {} in show {}'.format(sq.num, sq.show))
				else:
					self.sequenceId = sq.id

			if self.shot is not None and self.sequence is not None:
				try:
					self.shot = int(shot)
				except ValueError:
					raise ValueError('Sequence number must be a number, not: {}'.format(shot))

				sh = Shot(self.shot, self.sequence, show=self.show, clipName=clipName)

				if not sh.exists():
					raise ValueError('No such shot {}{} in sequence {} in show {}'.format(sh.num, sh.clipName if sh.clipName else '', sh.sequence, sh.show))
				else:
					self.shotId = sh.id

			if self.elementType:
				el = Element(self.elementName, self.elementType, self.show, self.sequence, self.shot)

				if not el.exists():
					raise ValueError(
						'No such element {} ({}){}{} in show {}'.format(
							el.name,
							el.type,
							' in shot {}'.format(el.shot) if el.shot else '',
							' in sequence {}'.format(el.sequence) if el.sequence else '',
							el.show
						)
					)
				else:
					self.elementId = el.id

	def addComment(self, text):
		text = text.replace("'", '').replace('"', '') # Temp work around until I can either escape quotes or properly update the DB with the value
		self.commentList.append((env.USER, str(env.getCreationInfo(format=False)[1]), text))
		self.set('comments', self.comments)

	@property
	def comments(self):
		return str(self.commentList).replace("'", '"')

	@comments.setter
	def comments(self, comments):
		try:
			if comments:
				self.commentList = eval(comments)
			else:
				self.commentList = []
		except:
			self.commentList = []

	@property
	def id(self):
		return super(Fix, self)._id(
			'{}_{}_{}_{}_{}_{}'.format(
				self.show,
				self.sequence if self.sequence else '',
				self.shot if self.shot else '',
				self.elementId if self.elementId else '',
				self.title,
				self.body
			)
		)

	@property
	def pk(self):
		return Fix.PK

	@property
	def target(self):
		if self.elementId:
			return Element.fromPk(self.elementId)
		elif self.shotId:
			return Shot.fromPk(self.shotId)
		elif self.sequenceId:
			return Sequence.fromPk(self.sequenceId)
		elif self.show:
			return Show.fromPk(self.show)

	@property
	def bid(self):
		if self.deadline is not None and self.creation is not None:
			return (utils.dbTimetoDt(self.deadline) - utils.dbTimetoDt(self.creation)).days + 1

		return None

	@property
	def days(self):
		if self.deadline is not None:
			return (utils.dbTimetoDt(self.deadline) - datetime.now()).days + 1

		return None

	@staticmethod
	def nextFixNum(show=None):
		show = show if show else env.show
		if not show:
			raise ValueError('Tried to fallback to environment-set show, but it was null.')

		from helix.database.sql import Manager

		with Manager(willCommit=False) as mgr:
			res = mgr.connection().execute(
				'''
					SELECT MAX(num) from {} WHERE show='{}'
				'''.format(Fix.TABLE, show)
			).fetchone()

			if res and res[0]:
				return int(res[0]) + 1
			else:
				return 1

	@staticmethod
	def byNum(fixNum, show=None):
		show = show if show else env.show
		if not show:
			raise ValueError('Tried to fallback to environment-set show, but it was null.')

		from helix.database.sql import Manager

		with Manager(willCommit=False) as mgr:
			res = mgr.connection().execute(
				'''
					SELECT * from {} WHERE num='{}' AND show='{}'
				'''.format(Fix.TABLE, fixNum, show)
			).fetchone()

			if res:
				return Fix('.', '.', show).unmap(res)
			else:
				return None

	@staticmethod
	def dummy():
		return Fix(None, None, None, None, dummy=True)


"""
Created by: Django
Description: Define url paths for accessing different views
Modified by: Bernardo, Hugo
Modify date: 31/10/2018
"""

from django.urls import path
from . import views

app_name = 'gallery'
urlpatterns = [
    path('', views.index, name='index'),
    path('new_photo/', views.new_photo, name='new_photo'),
    path('new_video/', views.new_video, name='new_video'),
]


import json
import httpserializers as serializers
from httpserializers.coreapi_serializer import CoreAPISerializer
from httpserializers import Document, Link, Field

import pytest

@pytest.fixture
def coreapi():
    return serializers.serializers["application/vnd.coreapi+json"]

@pytest.fixture
def coreapi_serializer(coreapi):
    def serialize(document: Document):
        return json.loads(coreapi.serialize(document).decode("UTF-8"))

    return serialize

def test_coreapi_serializer(coreapi):
    assert isinstance(coreapi, CoreAPISerializer)

def test_coreapi_serializer_small_document(coreapi_serializer):
    body = coreapi_serializer(
        Document(url="/users/", title="Users", content={"users": ["1", "2", "3"]})
    )
    assert body == {
        "_type": "document",
        "_meta": {"url": "/users/", "title": "Users"},
        "users": ["1", "2", "3"],
    }

def test_coreapi_serializer_full_document(coreapi_serializer):
    body = coreapi_serializer(
        Document(
            url="/users/",
            title="Users",
            content={"users": []},
            links={
                "register_user": Link(
                    href="/users/",
                    allow=["POST"],
                    title="Register a new user",
                    description="POSTing to this endpoint creates a new user",
                    fields=[
                        Field(
                            name="username",
                            required=True,
                            schema={"type": "string", "minLength": 3},
                        ),
                        Field(
                            name="password",
                            required=True,
                            schema={
                                "type": "string",
                                "minLength": 5,
                                "format": "password",
                            },
                        ),
                    ],
                ),
            },
        )
    )
    assert body == {
        "_type": "document",
        "_meta": {"url": "/users/", "title": "Users"},
        "users": [],
        "register_user": {
            "_type": "link",
            "url": "/users/",
            "title": "Register a new user",
            "description": "POSTing to this endpoint creates a new user",
            "action": "post",
            "fields": [
                {
                    "name": "username",
                    "required": True,
                    "schema": {"type": "string", "minLength": 3},
                },
                {
                    "name": "password",
                    "required": True,
                    "schema": {"type": "string", "minLength": 5, "format": "password"},
                },
            ],
        },
    }

def test_coreapi_serializer_link(coreapi_serializer):
    body = coreapi_serializer(
        Link(
            href="/users/",
            allow=["POST"],
            description="POSTing to this endpoint creates a new user",
            fields=[Field(name="username")],
        )
    )
    assert body == {
        "_type": "link",
        "url": "/users/",
        "description": "POSTing to this endpoint creates a new user",
        "action": "post",
        "fields": [{"name": "username"}],
    }

def test_coreapi_serializer_link_with_no_allow(coreapi_serializer):
    body = coreapi_serializer(
        Link(
            href="/users/",
            description="POSTing to this endpoint creates a new user",
            fields=[Field(name="username")],
        )
    )
    assert body == {
        "_type": "link",
        "url": "/users/",
        "description": "POSTing to this endpoint creates a new user",
        "fields": [{"name": "username"}],
    }

def test_coreapi_serializer_link_not_required(coreapi_serializer):
    body = coreapi_serializer(
        Link(
            href="/users/",
            allow=["POST"],
            description="POSTing to this endpoint creates a new user",
        )
    )
    assert body == {
        "_type": "link",
        "url": "/users/",
        "description": "POSTing to this endpoint creates a new user",
        "action": "post",
    }


class Solution:
    def increasingTriplet(self, nums: List[int]) -> bool:
        n = len(nums)
        min1 = min2 = float('inf')
        for i in range(n):
            if nums[i]<=min1:
                min1 = nums[i]
            elif nums[i]<=min2:
                min2 = nums[i]
            else:
                return True
        return False


import os
from typing import Dict
import yaml
from jinja2 import Environment, FileSystemLoader
import utility as util

# pylint: disable=too-many-instance-attributes
class ConfigLoader:
    def __init__(
        self, config_file: str, src_env: str, dst_env: str, network: str, src_ss: str, dst_ss: str, debug=False
    ):
        self.config_file = os.path.expanduser(config_file)
        self.src_env = src_env
        self.dst_env = dst_env
        self.network = network
        self.src_ss = src_ss  # source snapshot
        self.dst_ss = dst_ss  # destination snapshot
        self.debug = debug
        self._load_config()

    def _load_config(self):

        if not os.path.exists(self.config_file):
            util.error_exit(f"config file: {self.config_file} is not found")

        config_data = self._read_config(self.network, self.src_ss)
        self.original_node_params = config_data["original_node_params"]
        self.src_config = self._choose_config(self.src_env, self.src_ss)
        self.dst_config = self._choose_config(self.dst_env, self.dst_ss)

        if self.debug:
            util.debug(f"src_config: {self.src_config}")
            util.debug(f"dst_config: {self.dst_config}")
            util.debug(f"original_node_params: {self.original_node_params}")

    def _read_config(self, target_nw: str, target_ss: str) -> Dict:
        # load config (config template)
        env = Environment(loader=FileSystemLoader("./", encoding="UTF-8"))
        template = env.get_template(self.config_file)
        template_param = {"network_name": target_nw, "snapshot_name": target_ss}

        # render & parse config
        config_string = template.render(template_param)
        return yaml.safe_load(config_string)

    def _choose_config(self, target_env: str, target_ss: str) -> Dict:
        config_data = self._read_config(self.network, target_ss)
        return config_data[target_env]


# -*- coding: utf-8 -*-
import os.path

from flask import Flask
import requests

from cg.exc import TicketCreationError

class OsTicket(object):

    """Interface to ticket system."""

    def __init__(self):
        self.headers = None
        self.url = None

    def init_app(self, app: Flask):
        """Initialize the API in Flask."""
        self.setup(api_key=app.config['OSTICKET_API_KEY'], domain=app.config['OSTICKET_DOMAIN'])

    def setup(self, api_key: str=None, domain: str=None):
        """Initialize the API."""
        self.headers = {'X-API-Key': api_key}
        self.url = os.path.join(domain, 'api/tickets.json')

    def open_ticket(self, name: str, email: str, subject: str, message: str) -> str:
        """Open a new ticket through the REST API."""
        data = dict(name=name, email=email, subject=subject, message=message)
        res = requests.post(self.url, json=data, headers=self.headers)
        if res.ok:
            return res.text
        else:
            raise TicketCreationError(res)


import google.datalab.bigquery as bq
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults

class ExecuteOperator(BaseOperator):

  template_fields = ('table', 'parameters', 'path', 'sql')

  @apply_defaults
  def __init__(self, sql, parameters=None, table=None, mode=None, data_source=None, path=None,
               format=None, csv_options=None, schema=None, max_bad_records=None, *args, **kwargs):
    super(ExecuteOperator, self).__init__(*args, **kwargs)
    self.sql = sql
    self.table = table
    self.mode = mode
    self.parameters = parameters
    self.data_source = data_source
    self.path = path
    self.format = format
    self.csv_options = csv_options
    self.schema = schema
    self.max_bad_records = max_bad_records

  def execute(self, context):
    if self.data_source:
      kwargs = {}
      if self.csv_options:
        csv_kwargs = {}
        if 'delimiter' in self.csv_options:
          csv_kwargs['delimiter'] = self.csv_options['delimiter']
        if 'skip' in self.csv_options:
          csv_kwargs['skip_leading_rows'] = self.csv_options['skip']
        if 'strict' in self.csv_options:
          csv_kwargs['allow_jagged_rows'] = self.csv_options['strict']
        if 'quote' in self.csv_options:
          csv_kwargs['quote'] = self.csv_options['quote']
        kwargs['csv_options'] = bq.CSVOptions(**csv_kwargs)

      if self.format:
        kwargs['source_format'] = self.format

      if self.max_bad_records:
        kwargs['max_bad_records'] = self.max_bad_records

      external_data_source = bq.ExternalDataSource(
        source=self.path, schema=bq.Schema(self.schema), **kwargs)
      query = bq.Query(sql=self.sql, data_sources={self.data_source: external_data_source})
    else:
      query = bq.Query(sql=self.sql)

    # use_cache is False since this is most likely the case in pipeline scenarios
    # allow_large_results can be True only if table is specified (i.e. when it's not None)
    kwargs = {}
    if self.mode is not None:
      kwargs['mode'] = self.mode
    output_options = bq.QueryOutput.table(name=self.table, use_cache=False,
                                          allow_large_results=self.table is not None,
                                          **kwargs)
    query_params = bq.Query.get_query_parameters(self.parameters)
    job = query.execute(output_options=output_options, query_params=query_params)

    # Returning the table-name here makes it available for downstream task instances.
    return {
      'table': job.result().full_name
    }


import os
import subprocess
import sys

try:
    import image_slicer
except ImportError:
    subprocess.call([sys.executable, "-m", "pip", "install", 'image-slicer'])
finally:
    import image_slicer
if __name__ == '__main__':
    num_splits = int(sys.argv[1])
    filenames = next(os.walk(os.getcwd()))[2]
    filenames.remove(os.path.basename(__file__))
    i = 0
    for f in filenames:
        tiles = image_slicer.slice(f, num_splits, save=False)
        dir_name = f.split('.')[0]
        if not os.path.isdir(dir_name):
            os.system('mkdir ' + dir_name)
        image_slicer.save_tiles(tiles, directory=(os.getcwd() + '\\' + dir_name), prefix=dir_name)
        i = i + 1
    print('{} files successful split into {} each'.format(i, num_splits))
    # final = image_slicer.join(tiles)
    # if not os.path.isdir('frame_final'):
    #     os.system('mkdir ' + 'frame_final')
    # image = image_slicer.join(tiles)
    # image.save('modified_frame.tif')


import contextlib
import hardsync
import os
import platform
import itertools
from typing import Sequence, List, TypeVar
from hardsync.interfaces import ContractError
import traceback
from pathlib import Path

T = TypeVar('T')

def flatten(nested_list: Sequence[Sequence[T]]) -> List[T]:
    return list(itertools.chain.from_iterable(nested_list))

def dump() -> str:
    snippets = [
        f'hardsync_version: {hardsync.__version__}',
        f'hardsync_hash: {hardsync.__hash__}',
        f'os_name: {os.name}',
        f'platform: {platform.system()}',
        f'platform_version: {platform.uname()[3]}',
        f'python_version: {platform.python_version()}',
    ]
    dump_string = "\n".join(snippets)
    return dump_string

@contextlib.contextmanager
def wrap_assertion_error(contract_path: Path):
    try:
        yield
    except ContractError as e:
        raise e
    except Exception as e:
        dump_info = dump()
        with open(contract_path, 'r') as contract:
            contract_contents = contract.read()

        tb = traceback.format_exc()
        header = (
            "Congratulations! You managed to find an error I left behind. This means that you did"
            "something I didn't expect or are looking for a feature I haven't yet implemented. Please submit a bug "
            "report to the following URL: https://github.com/edmundsj/hardsync/issues/new?assignees=&labels=bug"
            "&projects=&template=bug_report.md&title=AssertionError%20bug%20report and copy-paste the following:\n"
        )
        full_message_snippets = [
            (header,),
            ('Contract:', contract_contents),
            ('Traceback:', tb),
            ('Output of hardsync dump:',dump_info),
        ]
        strings = ['\n'.join(field) for field in full_message_snippets]
        full_message = '\n'.join(strings)

        raise AssertionError(f"{full_message}") from None


def create_cast_list(filename):
    cast_list = []
    #use with to open the file filename
    with open(filename,'r') as f:
        #use the for loop syntax to process each line
        for line in f:
            #and add the actor name to cast_list
            cast_list.append(line.split(',')[0])

    return cast_list

cast_list = create_cast_list('flying_circus_cast.txt')
for actor in cast_list:
    print(actor)

'''
Graham Chapman
Eric Idle
Terry Jones
Michael Palin
Terry Gilliam
John Cleese
Carol Cleveland
Ian Davidson
John Hughman
The Fred Tomlinson Singers
Connie Booth
Bob Raymond
Lyn Ashley
Rita Davies
Stanley Mason
David Ballantyne
Donna Reading
Peter Brett
Maureen Flanagan
Katya Wyeth
Frank Lester
Neil Innes
Dick Vosburgh
Sandra Richards
Julia Breck
Nicki Howorth
Jimmy Hill
Barry Cryer
Jeannette Wild
Marjorie Wilde
Marie Anderson
Caron Gardner
Nosher Powell
Carolae Donoghue
Vincent Wong
Helena Clayton
Nigel Jones
Roy Gunson
Daphne Davey
Stenson Falke
Alexander Curry
Frank Williams
Ralph Wood
Rosalind Bailey
Marion Mould
Sheila Sands
Richard Baker
Douglas Adams
Ewa Aulin
Reginald Bosanquet
Barbara Lindley
Roy Brent
Jonas Card
Tony Christopher
Beulah Hughes
Peter Kodak
Lulu
Jay Neill
Graham Skidmore
Ringo Starr
Fred Tomlinson
David Hamilton
Suzy Mandel
Peter Woods
'''


from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class Link(models.Model):
    STATUS_NORMAl = 1
    STATUS_DELETE = 0
    STATUS_ITEM = (
        (STATUS_DELETE, "删除"),
        (STATUS_NORMAl, "正常")
    )

    title = models.CharField(max_length=255, verbose_name='标题')
    href = models.URLField(verbose_name='链接')
    status = models.PositiveIntegerField(default=STATUS_NORMAl, choices=STATUS_ITEM, verbose_name='状态')
    weight = models.PositiveIntegerField(default=1, choices=zip(range(1, 6), range(1, 6)), verbose_name='权重',
                                         help_text='权重高展示顺序靠前')
    owner = models.ForeignKey(User, verbose_name='作者', on_delete=models.CASCADE)
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = verbose_name_plural = '友链'
        ordering = ['-id']

class SideBar(models.Model):
    STATUS_SHOW = 1
    STATUS_HIDE = 0
    STATUS_ITEM = (
        (STATUS_SHOW, "显示"),
        (STATUS_HIDE, "隐藏")
    )

    title = models.CharField(max_length=255, verbose_name='标题')
    display_type = models.PositiveIntegerField(default=STATUS_SHOW, choices=STATUS_ITEM, verbose_name='展示类型')
    content = models.TextField(verbose_name='正文', help_text='如果设置的不是HTML类型，可为空')
    status = models.PositiveIntegerField(default=STATUS_SHOW, choices=STATUS_ITEM, verbose_name='状态')
    owner = models.ForeignKey(User, verbose_name='作者', on_delete=models.CASCADE)
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = verbose_name_plural = '侧边栏'


# -*- coding: utf-8 -*-
import csv
import argparse
import datetime
NEWLINE = ''
SEMICOLON = ';'
PERCENT = '%'
INPUT_FILE = 'sourse.csv'
OUTPUT_FILE = 'programming_{}.csv'
TABLE_ONE = ['таблица 1']
TABLE_TWO = ['таблица 2']
TABLE_THREE = ['таблица 3']
TABLE_FOUR = ['таблица 4']
USER_ID = 'id'
LAST_NAME = 'Фамилия'
FIRST_NAME = 'Имя'
TOTAL = 'Баллы'
PERCENTAGE_OF_TOTAL = '% от общего числа'
SCORED_0_POINTS = ['Студенты, которые набрали 0 баллов']
SCORED_MAX_SCORE = ['Студенты, которые набрали максимальный балл']
LESS_40_PERCENT = 'Количество студентов, набравших < 40 %;{}'
MORE_40_LESS_70_PERCENT = 'Количество студентов, набравших > 39% и < 71%;{}'
MORE_70_PERCENT = 'Количество студентов, набравших > 70%;{}'

def pars():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--max', type=int, nargs=1, help='Max Score')
    parser.add_argument('-n', '--name', nargs=1, help='Module Name')
    max_score = parser.parse_args()
    module_name = parser.parse_args()
    return max_score.max[0], module_name.name

def read_file():
    output_file = open(OUTPUT_FILE.format(str(datetime.datetime.now().strftime('%d %B'))), 'wb')
    wrtr = csv.writer(output_file)
    return wrtr, output_file

def close_file(output_file):
    output_file.close()

def filling_table():
    user_id = []
    last_name = []
    first_name = []
    total = []
    input_file = open(INPUT_FILE, 'rb')
    rdr = csv.reader(input_file)
    next(rdr)
    for user in rdr :
        id = ''
        last = ''
        first = ''
        tot = ''
        flag_id = True
        flag_last = False
        flag_first = False
        flag_total = False

        for i in user[0]:
            if flag_id:
                if i == SEMICOLON:
                    flag_id = False
                    flag_last = True
                    continue
                else :
                    id += i
            if flag_last:
                if i == SEMICOLON:
                    flag_last = False
                    flag_first = True
                    continue
                else:
                    last += i
            if flag_first:
                if i == SEMICOLON:
                    flag_first = False
                    flag_total = True
                    continue
                else:
                    first += i
            if flag_total:
                if i == SEMICOLON:
                    flag_id = False
                else:
                    tot += i
        user_id.append(id)
        last_name.append(last)
        first_name.append(first)
        total.append(tot)

    input_file.close()
    return user_id, last_name, first_name, total

def summary_table(wrtr, user_id, last_name, first_name, total, value):
    myTable = NEWLINE
    myTable += USER_ID
    myTable += SEMICOLON
    myTable += LAST_NAME
    myTable += SEMICOLON
    myTable += FIRST_NAME
    myTable += SEMICOLON
    myTable += TOTAL
    myTable += SEMICOLON
    myTable += PERCENTAGE_OF_TOTAL
    myTable += SEMICOLON
    wrtr.writerow([myTable])

    for i in range(0, len(user_id)):
        myTable = NEWLINE
        myTable += user_id[i]
        myTable += SEMICOLON
        myTable += last_name[i]
        myTable += SEMICOLON
        myTable += first_name[i]
        myTable += SEMICOLON
        myTable += total[i]
        myTable += SEMICOLON
        myTable += str(int(total[i]) * 100 / value)
        myTable += PERCENT
        wrtr.writerow([myTable])

def number_points(wrtr, user_id, last_name, first_name, total, value):
    for i in range(0, len(user_id)):
        if int(total[i]) == value:
            myTable = ''
            myTable += user_id[i]
            myTable += SEMICOLON
            myTable += last_name[i]
            myTable += SEMICOLON
            myTable += first_name[i]

            wrtr.writerow([myTable])

def percentage(wrtr, total, max_value):
    count_one = 0
    count_two = 0
    count_three = 0
    for i in range(0, len(total)):
        if int(total[i]) * 100 / max_value < 40:
            count_one += 1
        if 40 <= int(total[i]) * 100 / max_value <= 70:
            count_two += 1
        if int(total[i]) * 100 / max_value > 70:
            count_three += 1
    wrtr.writerow([LESS_40_PERCENT.format(count_one)])
    wrtr.writerow([MORE_40_LESS_70_PERCENT.format(count_two)])
    wrtr.writerow([MORE_70_PERCENT.format(count_three)])

def first_table(wrtr, module_name, max_score, user_id, last_name, first_name, total):
    wrtr.writerow(module_name)
    wrtr.writerow(NEWLINE)
    wrtr.writerow(TABLE_ONE)
    if __name__ == '__main__':
        summary_table(wrtr, user_id, last_name, first_name, total, max_score)

def second_table(wrtr, user_id, last_name, first_name, total):
    wrtr.writerow(NEWLINE)
    wrtr.writerow(TABLE_TWO)
    wrtr.writerow(SCORED_0_POINTS)
    if __name__ == '__main__':
        number_points(wrtr, user_id, last_name, first_name, total, 0)

def third_table(wrtr, user_id, last_name, first_name, total, max_score):
    wrtr.writerow(NEWLINE)
    wrtr.writerow(TABLE_THREE)
    wrtr.writerow(SCORED_MAX_SCORE)
    if __name__ == '__main__':
        number_points(wrtr, user_id, last_name, first_name, total, max_score)

def fourth_table(wrtr, total, max_score):
    wrtr.writerow(NEWLINE)
    wrtr.writerow(TABLE_FOUR)
    if __name__ == '__main__':
        percentage(wrtr, total, max_score)

def main():
    if __name__ == '__main__':
        max_score, module_name = pars()
        wrtr, output_file = read_file()
        user_id, last_name, first_name, total = filling_table()
        first_table(wrtr, module_name, max_score, user_id, last_name, first_name, total)
        second_table(wrtr, user_id, last_name, first_name, total)
        third_table(wrtr, user_id, last_name, first_name, total, max_score)
        fourth_table(wrtr, total, max_score)
        close_file(output_file)

main()


from tkinter import Label, Button, Frame, Tk, Entry, messagebox, ttk
import random
from pandas import read_excel
from tabulate import tabulate
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# random sampling
data = read_excel("data.xlsx")
idx_data = [i for i in range(len(data.index))]
emp_id = "00000"
count = 0
msg = ""
num_result = 1

data = data.astype({'사번': 'str'})
data['num1'] = data['사번'].str.slice(start=0, stop=1)
data['num2'] = data['사번'].str.slice(start=1, stop=2)
data['num3'] = data['사번'].str.slice(start=2, stop=3)
data['num4'] = data['사번'].str.slice(start=3, stop=4)
data['num5'] = data['사번'].str.slice(start=4, stop=5)

raw_data = data

def get_entry(event=None):
    global num_result

    num = 1
    tmp = entry.get()
    if not tmp.isnumeric():
        messagebox.showerror("경고", "숫자를 입력해주세요!")
        num = 1
        entry.delete(0, len(tmp))
    else:
        num = int(tmp)
        if num <= 0:
            messagebox.showerror("경고", "양의 정수를 입력해주세요!!")
            num = 1
            entry.delete(0, len(tmp))
        elif num > data.shape[0]:
            messagebox.showerror("경고", "작은 숫자를 입력하세요!!")
            num = 1
            entry.delete(0, len(tmp))

    num_result = num
    label_entry.configure(text="뽑을 인원: " + str(num) + "명")
    entry.delete(0, len(tmp))
    entry.configure(state="disabled")

def func_filter_data(col_name, num_filter):
    global data
    data = data[data[col_name] == str(num_filter)]
    func_change_chart(data)

def func_reset_num1():
    global count
    global msg
    label_num1.configure(text="")
    label_num1.configure(text=emp_id[0], bg='lightblue')
    func_filter_data('num1', emp_id[0])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num2():
    global count
    global msg
    label_num2.configure(text="")
    label_num2.configure(text=emp_id[1], bg='lightblue')
    func_filter_data('num2', emp_id[1])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num3():
    global count
    global msg
    label_num3.configure(text="")
    label_num3.configure(text=emp_id[2], bg='lightblue')
    func_filter_data('num3', emp_id[2])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num4():
    global count
    global msg
    label_num4.configure(text="")
    label_num4.configure(text=emp_id[3], bg='lightblue')
    func_filter_data('num4', emp_id[3])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num5():
    global count
    global msg

    label_num5.configure(text="")
    label_num5.configure(text=emp_id[4], bg='lightblue')
    func_filter_data('num5', emp_id[4])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num6():
    global count
    global msg

    label_num5.configure(text="")
    label_num5.configure(text=emp_id[4], bg='lightblue')
    func_filter_data('num5', emp_id[4])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_reset_num7():
    global count
    global msg

    label_num5.configure(text="")
    label_num5.configure(text=emp_id[4], bg='lightblue')
    func_filter_data('num5', emp_id[4])
    count = count + 1
    if count == 7:
        result.configure(text=msg)

def func_pick():
    global emp_id
    global msg
    global num_result

    num = random.sample(idx_data, num_result)
    emp_id = str(data.iloc[num, 0].tolist()[0])

    print(num_result)

    tmp = data.iloc[num, 0:6]
    msg = "축하합니다!\n" + tabulate(tmp, showindex=False)

    if num_result == 1:
        result.configure(text="보기 버튼으로 숫자를 확인하세요!")
    else:
        result.configure(text=msg)

    button.configure(state="disabled")
    button_num1.configure(state="normal")
    button_num2.configure(state="normal")
    button_num3.configure(state="normal")
    button_num4.configure(state="normal")
    button_num5.configure(state="normal")

    entry.configure(state="disabled")

def func_change_chart(data):
    ax1.clear()
    df1 = data.groupby('호칭')['사번'].count().sort_values(ascending=True)
    df1.plot(kind='barh', legend=False, ax=ax1)
    ax1.set_title('호칭별 생존자 수')
    bar1.draw()

def init():
    global data
    global count
    global msg
    global emp_id
    global num_result

    data = raw_data
    count = 0
    msg = "뽑기 버튼을 눌러주세요!"
    emp_id = "00000"
    num_result = 1

    button.configure(state="normal")

    result.configure(text=msg)
    label_num1.configure(text="첫번째 자리", bg='white')
    label_num2.configure(text="두번째 자리", bg='white')
    label_num3.configure(text="세번째 자리", bg='white')
    label_num4.configure(text="네번째 자리", bg='white')
    label_num5.configure(text="다섯번째 자리", bg='white')

    button_num1.configure(state="disabled")
    button_num2.configure(state="disabled")
    button_num3.configure(state="disabled")
    button_num4.configure(state="disabled")
    button_num5.configure(state="disabled")

    entry.configure(state="normal")
    label_entry.configure(text="뽑을 인원: 1명")

    func_change_chart(raw_data)

# Variables
msg_title = "조합원 힐링지원 프로그램 뽑기 "
plt.rcParams['font.family'] = 'LG Smart_H2.0'

# tkinter
window = Tk()
window.title(msg_title)
window.config(padx=10, pady=10, bg="lightgrey")
window.geometry("550x550")
window.resizable(True, True)

# message frame
message_frame = Frame(window, width=800, height=80)
result = Label(message_frame, text="뽑기 버튼을 눌러주세요!", pady=10)
result.pack(pady=10)
message_frame.pack(pady=10, expand="no", fill="both", anchor="center")

# num result frame
num_result_frame = Frame(window, width=400, height=30)
label_entry = Label(num_result_frame, text="뽑을 인원: 1명", pady=10)
label_entry.grid(row=0)

entry = Entry(num_result_frame, width=10)
entry.bind("<Return>", get_entry)
entry.grid(row=1, column=0)

button_entry = Button(num_result_frame, text="입력", command=get_entry)
button_entry.grid(row=1, column=1)
num_result_frame.pack(pady=10, expand="no", anchor="center")

# button frame
bottom_frame = Frame(window, width=800, height=100)
button = Button(bottom_frame, text="숫자뽑기", bg="white", fg="black", \
                font=("LG Smart_H2.0", 12, "bold"), \
                command=func_pick)
button.grid(row=0, column=0)

button_init = Button(bottom_frame, text="초기화", bg="white", fg="red", \
                     font=("LG Smart_H2.0", 12, "bold"), \
                     command=init)
button_init.grid(row=0, column=1)

bottom_frame.pack(side="top", anchor="center")

# card frame
card_frame = Frame(window, width=800, height=100)
label_num1 = Label(card_frame, text="첫번째 자리", pady=3, \
                   font=("LG Smart_H2.0", 12, "bold"), bg="white", width=10, height=5)
label_num2 = Label(card_frame, text="두번째 자리", pady=3, \
                   font=("LG Smart_H2.0", 12, "bold"), bg="white", width=10, height=5)
label_num3 = Label(card_frame, text="세번째 자리", pady=3, \
                   font=("LG Smart_H2.0", 12, "bold"), bg="white", width=10, height=5)
label_num4 = Label(card_frame, text="네번째 자리", pady=3, \
                   font=("LG Smart_H2.0", 12, "bold"), bg="white", width=10, height=5)
label_num5 = Label(card_frame, text="다섯번째 자리", pady=3, \
                   font=("LG Smart_H2.0", 12, "bold"), bg="white", width=10, height=5)

button_num1 = Button(card_frame, text="보기", bg="white", fg="black", \
                     font=("LG Smart_H2.0", 12, "bold"), state="disabled", \
                     command=func_reset_num1)
button_num2 = Button(card_frame, text="보기", bg="white", fg="black", \
                     font=("LG Smart_H2.0", 12, "bold"), state="disabled", \
                     command=func_reset_num2)
button_num3 = Button(card_frame, text="보기", bg="white", fg="black", \
                     font=("LG Smart_H2.0", 12, "bold"), state="disabled", \
                     command=func_reset_num3)
button_num4 = Button(card_frame, text="보기", bg="white", fg="black", \
                     font=("LG Smart_H2.0", 12, "bold"), state="disabled", \
                     command=func_reset_num4)
button_num5 = Button(card_frame, text="보기", bg="white", fg="black", \
                     font=("LG Smart_H2.0", 12, "bold"), state="disabled", \
                     command=func_reset_num5)

label_num1.grid(row=0, column=0)
label_num2.grid(row=0, column=1)
label_num3.grid(row=0, column=2)
label_num4.grid(row=0, column=3)
label_num5.grid(row=0, column=4)

button_num1.grid(row=1, column=0)
button_num2.grid(row=1, column=1)
button_num3.grid(row=1, column=2)
button_num4.grid(row=1, column=3)
button_num5.grid(row=1, column=4)

card_frame.pack(pady=10, expand="no", fill="both", anchor="center")

import matplotlib

matplotlib.rcParams['font.family'] ='Malgun Gothic'

matplotlib.rcParams['axes.unicode_minus'] =False

# matplotlib
figure1 = plt.Figure(figsize=(30, 2), dpi=100)
ax1 = figure1.add_subplot(111)
bar1 = FigureCanvasTkAgg(figure1, window)
bar1.get_tk_widget().pack()
df1 = data.groupby('호칭')['사번'].count().sort_values(ascending=True)
df1.plot(kind='barh', legend=False, ax=ax1)
ax1.set_title('호칭별 생존자 수')

window.mainloop()


n = 10
result = 1

# Your code begins
# While n is larger than 0
while n > 0:
  # Multiply result by n
  result = result * n

	# Decrease n by 1
  n = n - 1
# Your code ends

print(result)


import pytest
import tensorflow as tf
import utils

@pytest.mark.parametrize("batch_size",  [1])
@pytest.mark.parametrize("in_w, in_h, in_d, k_w, k_h, k_d", [(4, 4, 4, 3, 3, 2), (112, 112, 56, 3, 3, 2)])
@pytest.mark.parametrize("in_ch",       [1])
@pytest.mark.parametrize("out_ch",      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
@pytest.mark.parametrize("qtype",       [True, False])
def test_conv3d(delegate_lib, batch_size, in_w, in_h, in_d, in_ch, out_ch, k_w, k_h, k_d, qtype):
    # input layout [N, H, W, D, C]
    input_shape = [batch_size, in_h, in_w, in_d, in_ch]
    out_channel = out_ch
    # kernel layout [Kd, Kh, Kw]
    kernel_shape = [1, 2, 2]
    input_dtype = tf.float32

    model = tf.keras.models.Sequential([
        tf.keras.layers.Input(shape = input_shape[1:], batch_size= input_shape[0]),
        tf.keras.layers.Conv3D(filters = out_channel, kernel_size= kernel_shape)
        ])
    model.build()

    converter = tf.lite.TFLiteConverter.from_keras_model(model)

    def rand_calibration():
        for _ in range(100):
            yield [tf.random.normal(input_shape[0:], 0, 127, input_dtype)]

    if (qtype is True):
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        converter.representative_dataset = rand_calibration
        converter.inference_input_type = tf.int8
        converter.inference_output_type = tf.int8

    tflite_model = converter.convert()
    model_path = "./test_model.tflite"
    open(model_path, "wb").write(tflite_model)

    npu_ = utils.npu(delegate_lib)
    cpu_ = utils.cpu()
    (gold_in, gold_out)= cpu_.run_with_rand_data(model_path)
    npu_out = npu_.run(model_path, gold_in)

    pytest.approx(gold_out,npu_out)


import re
reg = "cat|dog"
s = "the cat ate the mouse"
s2 = "the dog ate the cat"
print(re.search(reg,s).group())
print(re.search(reg,s2).group())

def mymap(f,L):
    R = []
    for elem in L:
        R.append(f(elem))
    return R

def myfilter(f,L):
    R = []
    for elem in L:
        if f(elem):
            R.append(elem)
    return R

def reduce(f,L):
    if L == []:
        assert(False)
    if len(L) == 1:
        return L[0]
    r = f(L[0],L[1])
    for i in L[2:]:
        r = f(r,i)
    return r

def reducer(f,L):
    if L == []:
        assert(False)
    if len(L) == 1:
        return L[0]
    b = f(L[0],L[1])
    return reducer(f, [b] + L[2:])

A = [2, 4, 5, 6,7, 9]
B = ["i", "abe", "mnt"]

print(list(filter(lambda x: x%2 == 0 or x%5 == 0, A)))
vowels = myfilter(lambda x: x not in "aeiou", B)
print(list(vowels))
length = reducer(lambda x,y: x+1, [0]+ A)
average = reducer(lambda x, y: x+y, A)
mean = average / length
print(mean)


import numpy as np

np.random.seed(0)

x_data = [0, 1, 2, 3]
y_data = [95.57142857, 64.14285714, 47, 45.71428571]

import matplotlib.pyplot as plt

from scipy import optimize

def test_func(x, a, b, c):
    return (a-c)*(x+1)**(-b)+c
params, params_covariance = optimize.curve_fit(test_func, x_data, y_data,
                                               p0=[1, 1, 1])
print(params)


import os
import time
import json

from socket import *

server = socket(AF_INET, SOCK_STREAM)
server.bind(('', 50000))
server.listen(5)
print('listen...')
while(1):
	client, addrClient = server.accept()
	print('connected to ', addrClient)

	msg = 'None'
	while 1:
		msg = client.recv(1024).encode('utf-8')
		print(msg)
		if '}' in msg:
			print('msg recv complete')
			break

	print('dk Tlqkf')
	json_val = json.dumps({"name":"KMHASD", "age":20, 'school':'unist'})
	client.sendall(json_val.encode('utf-8'))
	print('msg send complete')

client.close()
server.close()


import binascii
import base58
import json

class Serializer:

    def __init__(self, Trans, sign=False):
        self.sign = sign
        vrt = (int(Trans.param['vertion'])).to_bytes(4, 'little')
        in_count = self.makeVar(Trans.param['tx_in count'])
        out_count = self.makeVar(Trans.param['tx_out count'])
        lkt = (int(Trans.param['lock_time'])).to_bytes(4, 'little').hex()
        self.param = {
            'vertion': vrt.hex(),
            'input count': in_count,
            'input': self.serialize_input(Trans.param['tx_in']),
            'output count': out_count,
            'output': self.serialize_output(Trans.param['tx_out']),
            'lockTime': lkt
        }

    def serialize_input(self, tx_in):
        in_rt = list()
        for i in range(len(tx_in)):
            str = (binascii.unhexlify(tx_in[i]['Previous txid'])[::-1].hex() +
                (int(tx_in[i]['Previous Tx Index']).to_bytes(4, 'little')).hex() +
                self.makeVar(tx_in[i]['Script Length']) +
                tx_in[i]['Signature Script'] + tx_in[i]['Sequence'])
            in_rt.append(str)
        return in_rt

    def serialize_output(self, tx_out):
        out = list()
        for i in range(len(tx_out)):
            str = ((int(tx_out[i]['value'])).to_bytes(8, 'little').hex() +
            (self.makeVar(tx_out[i]['Script Length'])) + tx_out[i]['Public Script'])
            out.append(str)
        return out

    def make(self):
        inp = ""
        out = ""
        add = "01000000" if (self.sign == True) else ""
        for i in range(len(self.param['input'])):
            inp = inp + self.param['input'][i]
        for i in range(len(self.param['output'])):
            out = out + self.param['output'][i]
        str = (self.param['vertion'] + self.param['input count'] +
                inp + self.param['output count'] + out + self.param['lockTime'] + add)
        return str

    def makeVar(self, strval):
        tmp = int(strval)
        if (tmp <= 255):
            bt = 1
            prf = ""
        elif tmp <= 65535:
            bt = 2
            prf = 'fd'
        elif tmp <= 4294967295:
            bt = 4
            prf = 'fe'
        else:
            bt = 8
            prf = 'ff'
        res = (int(strval)).to_bytes(bt, 'big')
        final = prf + res.hex()
        return final

class Deserializer:

    def __init__(self, str):
        inputCounterVal, inputCounterEnd = Deserializer.getVar(str[8:], 8)
        ilen, inp = self.getInput(inputCounterVal, str[inputCounterEnd:])

        outputCounterVal, outputCounterEnd = Deserializer.getVar(str[inputCounterEnd + ilen:], inputCounterEnd + ilen)
        olen, out = self.getOut(outputCounterVal, str[outputCounterEnd:])
        self.param = {
            'vertion': str[0 : 8],
            'tx_in count': inputCounterVal,
            'tx_in': inp,
            'tx_out count': outputCounterVal,
            'tx_out': out,
            'lock_time': int(str[-8 : ], 16)
        }

    @staticmethod
    def getVar(str, start):
        if str[:2] == 'fd':
            end = start + 6
            val = int(str[2: 6], 16)
        elif str[:2] == 'fe':
            end = start + 8
            val = int(str[2: 10], 16)
        elif str[:2] == 'ff':
            end = start + 16
            val = int(str[2: 18], 16)
        else:
            end = start + 2
            val = int(str[:2], 16)
        return val, end

    def getInput(self, len, str):
        inp = list()
        txid = 64
        vout = 8
        seqence = 8
        round = 0
        for i in range(len):
            scr_len, endScriptvar = Deserializer.getVar(str[(txid + vout) + round:], (txid + vout) + round)
            bytesScriptvar = endScriptvar - (txid + vout + round)
            inp.append({
                'Previous txid': str[round:round + txid],
                'Previous Tx Index': str[round + txid: round + txid + vout],
                'Script Length': scr_len,
                'Signature Script': str[round + txid + vout + bytesScriptvar: round + txid + vout + bytesScriptvar + scr_len * 2],
                'Sequence': str[round + txid + vout + bytesScriptvar + scr_len * 2: round + txid + vout + bytesScriptvar + scr_len * 2 + seqence]
            })
            round = round + txid + vout + bytesScriptvar + scr_len * 2 + seqence
        return round, inp

    def getOut(self, len, str):
        out = list()
        value = 16
        round = 0
        for i in range(len):
            scr_len, endScriptvar = Deserializer.getVar(str[value + round:], value + round)
            bytesScriptvar = endScriptvar - (value + round)
            print("-------", str[:round + value])
            out.append({
                'value': str[round:round + value],
                'Script Length': scr_len,
                'Public Script': str[round + value + bytesScriptvar: round + value + bytesScriptvar + scr_len * 2]
            })
            round = round + value + bytesScriptvar + scr_len * 2
        return round, out

    def make(self):
        self.param['vertion'] = int((binascii.unhexlify(self.param['vertion'])[::-1]).hex(), 16)
        for i in range(len(self.param['tx_in'])):
            self.param['tx_in'][i]['Previous txid'] = (binascii.unhexlify(self.param['tx_in'][i]['Previous txid'])[::-1]).hex()
            self.param['tx_in'][i]['Previous Tx Index'] = int((binascii.unhexlify(self.param['tx_in'][i]['Previous Tx Index'])[::-1]).hex(), 16)
        for i in range(len(self.param['tx_out'])):
            self.param['tx_out'][i]['value'] = int((binascii.unhexlify(self.param['tx_out'][i]['value'])[::-1]).hex(), 16)

    def toJSON(self):
        return json.dumps(self.param, default=lambda o: o.__dict__,
            sort_keys=True, indent=6)


# Напишите программу, которая найдёт произведение пар чисел списка.
# Парой считаем первый и последний элемент, второй и предпоследний и т.д.
# - [2, 3, 4, 5, 6] => [12, 15, 16];
# - [2, 3, 5, 6] => [12, 15]

import random
n = int(input("Введите количетво элементов: "))
sp = []
summ = 0
for i in range(0, n):
    sp.append(random.randint(0, 10))
print(sp)
sp1 = []
for i in range (0, round(n / 2 + 0.5)):
    sp1.append(sp[i] * sp[-i - 1])
print(sp1)


# @author Daniel McCoy Stephenson
# @since August 6th, 2022

# @author Daniel McCoy Stephenson
# @since August 6th, 2022
class Config:
    def __init__(self):
        # display
        self.displayWidth = 500
        self.displayHeight = 500
        self.fullscreen = False
        self.black = (0,0,0)
        self.white = (255,255,255)
        self.green = (0,255,0)
        self.red = (255,0,0)
        self.yellow = (255,255,0)
        self.textSize = 50

        # grid size
        self.gridSize = 5
        self.minGridSize = 5
        self.maxGridSize = 12

        # tick speed
        self.limitTickSpeed = True
        self.tickSpeed = 0.1

        # misc
        self.debug = False
        self.restartUponCollision = True
        self.levelProgressPercentageRequired = 0.5


# Contains useful maths functions

import numpy as np
from scipy.spatial.distance import cdist, euclidean
import math
import warnings

def geometric_median(X, eps=1e-5):
    '''
    From - http://bit.ly/2uoh7Ut

    '''

    y = np.mean(X, 0)

    while True:
        D = cdist(X, [y])
        nonzeros = (D != 0)[:, 0]

        Dinv = 1 / D[nonzeros]
        Dinvs = np.sum(Dinv)
        W = Dinv / Dinvs
        T = np.sum(W * X[nonzeros], 0)

        num_zeros = len(X) - np.sum(nonzeros)
        if num_zeros == 0:
            y1 = T
        elif num_zeros == len(X):
            return y
        else:
            R = (T - y) * Dinvs
            r = np.linalg.norm(R)
            rinv = 0 if r == 0 else num_zeros/r
            y1 = max(0, 1-rinv)*T + min(1, rinv)*y

        if euclidean(y, y1) < eps:
            return y1

        y = y1

# def geometric_median(X, numIter = 200):
#     """
#     [Same source, different answer - http://bit.ly/2uoh7Ut]

#     Compute the geometric median of a point sample.
#     The geometric median coordinates will be expressed in the Spatial Image reference system (not in real world metrics).
#     We use the Weiszfeld's algorithm (http://en.wikipedia.org/wiki/Geometric_median)

#     :Parameters:
#      - `X` (list|np.array) - voxels coordinate (3xN matrix)
#      - `numIter` (int) - limit the length of the search for global optimum

#     :Return:
#      - np.array((x,y,z)): geometric median of the coordinates;
#     """
#     # -- Initialising 'median' to the centroid
#     y = np.mean(X,1)
#     # -- If the init point is in the set of points, we shift it:
#     while (y[0] in X[0]) and (y[1] in X[1]) and (y[2] in X[2]):
#         y+=0.1

#     convergence=False # boolean testing the convergence toward a global optimum
#     dist=[] # list recording the distance evolution

#     # -- Minimizing the sum of the squares of the distances between each points in 'X' and the median.
#     i=0
#     while ( (not convergence) and (i < numIter) ):
#         num_x, num_y, num_z = 0.0, 0.0, 0.0
#         denum = 0.0
#         m = X.shape[1]
#         d = 0
#         for j in range(0,m):
#             div = math.sqrt( (X[0,j]-y[0])**2 + (X[1,j]-y[1])**2 + (X[2,j]-y[2])**2 )
#             num_x += X[0,j] / div
#             num_y += X[1,j] / div
#             num_z += X[2,j] / div
#             denum += 1./div
#             d += div**2 # distance (to the median) to miminize
#         dist.append(d) # update of the distance evolution

#         if denum == 0.:
#             warnings.warn( "Couldn't compute a geometric median, please check your data!" )
#             return [0,0,0]

#         y = [num_x/denum, num_y/denum, num_z/denum] # update to the new value of the median
#         if i > 3:
#             convergence=(abs(dist[i]-dist[i-2])<0.1) # we test the convergence over three steps for stability
#             #~ print abs(dist[i]-dist[i-2]), convergence
#         i += 1
#     if i == numIter:
#         raise ValueError( "The Weiszfeld's algoritm did not converged after"+str(numIter)+"iterations !!!!!!!!!" )
#     # -- When convergence or iterations limit is reached we assume that we found the median.

#     return np.array(y)


a=int(input("Enter a number "))
b=int(input("Enter another number "))
print("What function you want to perform?")
list=['add', 'subtract', 'multiply', 'divide']
print("Options are: " + str(list))
c= input("What function you want to perform? ")
add=a+b
sub=a-b
mul=a*b
div=a/b
if c=="add":
    print(add)
elif c=="subtract":
    print(sub)
elif c=="multiply":
    print(mul)
elif c=="divide":
    print(div)
else:
    print("Invalid Input!")


# encoding: utf-8
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import division, unicode_literals

import datetime
import re

from jx_python.jx import chunk
from mo_dots import DataObject, Null, from_data
from mo_future import zip_longest
from mo_logs import Log

class Version(object):
    __slots__ = ["prefix", "version"]

    def __new__(cls, version, prefix=""):
        if version == None:
            return Null
        else:
            return object.__new__(cls)

    def __init__(self, version, prefix=""):
        version = from_data(version)

        if isinstance(version, tuple):
            self.version = version
            self.prefix = ("", ".", ".", ".", ".", ".", ".")[:len(self.version)]
        elif not version or isinstance(version, DataObject):
            self.prefix = ('',)
            self.version = (0,)
        elif isinstance(version, Version):
            self.prefix = version.prefix
            self.version = version.version
        else:
            try:
                self.prefix, version = split(version)
            except Exception as cause:
                raise cause

            def scrub(v):
                try:
                    return int(v)
                except Exception:
                    return v

            self.version = tuple(map(scrub, version))
        if len(self.prefix)!=len(self.version):
            Log.error("not expected")

    def __gt__(self, other):
        other = Version(other)
        for s, o in zip_longest(self.version, other.version):
            if s is None and o is not None:
                return False
            if s is not None and o is None:
                return True

            if isinstance(s, str):
                if isinstance(o, str):
                    if s == o:
                        continue
                    return s > o
                else:
                    try:
                        if int(s) == o:
                            continue
                        return int(s) >= o
                    except Exception:
                        return s >= str(o)
            else:
                if isinstance(o, str):
                    if s == int(o):
                        continue
                    return s > int(o)
                else:
                    if s == o:
                        continue
                    return s > o

        return False

    def __ge__(self, other):
        return self == other or self > other

    def __eq__(self, other):
        other = Version(other)
        return self.version == other.version

    def __le__(self, other):
        return self == other or not (self > other)

    def __lt__(self, other):
        return not (self == other) and not (self > other)

    def __ne__(self, other):
        other = Version(other)
        return self.version != other.version

    def __str__(self):
        return "".join(p + str(v) for p, v in zip(self.prefix, self.version))

    def __hash__(self):
        return self.__str__().__hash__()

    def __add__(self, other):
        major, minor, mini = self.version
        minor += other
        mini = datetime.datetime.utcnow().strftime("%y%j")
        return Version((major, minor, mini), prefix=self.prefix)

    __data__ = __str__

    @property
    def major(self):
        return self.version[0]

    @property
    def minor(self):
        return self.version[1]

    @property
    def mini(self):
        return self.version[2]

def triple(version):
    return (tuple(version) + (0, 0, 0))[:3]

def split(version):
    result = re.split(r"(\.|(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)|^(?=\d))", version)
    if len(result) > 2 and not result[1]:
        result.pop(1)
    return zip(*(r for g, r in chunk(result, 2)))

split('v1.10.20029')


data = [list(x) for x in open("data.txt", "r").read().split("\n")]

# First part
occurences = {}

for row in data:
    unique = set(row)
    cnt = set([row.count(x) for x in unique if row.count(x) in [2, 3]])
    for i in cnt:
        if i==1:
            continue
        occurences[i] = occurences.get(i, 0) + 1

total = 1
for k,v in occurences.items():
    total *= v

print("First part: " + str(total))

# Second part
def hamming(s1, s2):
    return sum(c1 != c2 for c1, c2 in zip(s1, s2))

def diff(s1, s2):
    return [s1[i]==s2[i] for i in range(s1.__len__())].index(False)

for i in range(data.__len__()):
    for j in range(i, data.__len__()):
        a = "".join(data[i])
        b = "".join(data[j])
        if hamming(a, b) == 1:
            print("Second part: " + "".join([x for i,x in enumerate(data[i]) if i!=diff(a,b)]))
            break
    else:
        continue
    break


import pandas as pd
from sklearn import tree

def range_alg(data: pd.DataFrame, selection, max_depth=None):
    clf = tree.DecisionTreeClassifier(max_depth=max_depth)

    clf.fit(data, selection)

    rules = get_decision_paths(clf, data, selection)

    return rules

def get_mask_from_exp(data, exp):
    feature, op, val, mask = None, None, None, None
    if ">=" in exp:
        op = ">="
        feature, val = exp.split(">=")
    else:
        op = "<="
        feature, val = exp.split("<=")
    feature = feature.strip()
    val = float(val.strip())
    if op == ">=":
        mask = data[feature] >= val
    else:
        mask = data[feature] <= val

    return mask

def get_mask_from_rules(data, rules):
    mask = None

    for rule in rules:
        m = None
        for exp in rule:
            if m is None:
                m = get_mask_from_exp(data, exp)
            else:
                m &= get_mask_from_exp(data, exp)
        if mask is None:
            mask = m
        else:
            mask |= m
    return mask

def get_decision_paths(model: tree.DecisionTreeClassifier, data, selection):
    selected_rows = data[selection]

    paths = set()

    d_path = model.decision_path(selected_rows)

    leaf_id = model.apply(selected_rows)
    feature = model.tree_.feature
    threshold = model.tree_.threshold

    for sample_id in range(len(selected_rows.index)):
        node_idx = d_path.indices[
            d_path.indptr[sample_id] : d_path.indptr[sample_id + 1]  # noqa
        ]

        rules = []

        for node_id in node_idx:
            if leaf_id[sample_id] == node_id:
                continue

            sign = None
            if selected_rows.iloc[sample_id, feature[node_id]] <= threshold[node_id]:
                sign = "<="
            else:
                sign = ">="

            rule = (
                data.columns[feature[node_id]]
                + sign
                + str(round(threshold[node_id], 2))
            )

            rules.append(rule)
        paths.add(tuple(rules))

    paths = [[rule for rule in path] for path in paths]

    mask = get_mask_from_rules(data, paths)

    return paths, mask


import zipfile
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
import matplotlib.cbook as cbook
import ast

#def defaultval():
#    return 0
#
#def boxst(values, freqs):
#    values = np.array(values)
#    freqs = np.array(freqs)
#    arg_sorted = np.argsort(values)
#    values = values[arg_sorted]
#    freqs = freqs[arg_sorted]
#    count = freqs.sum()
#    fx = values * freqs
#    mean = fx.sum() / count
#    variance = ((freqs * values**2).sum() / count) - mean**2
#    std = np.sqrt(variance)
#    minimum = np.min(values)
#    maximum = np.max(values)
#    cumcount = np.cumsum(freqs)
#    Q1 = values[np.searchsorted(cumcount, 0.25*count)]
#    median = values[np.searchsorted(cumcount, 0.50*count)]
#    Q3 = values[np.searchsorted(cumcount, 0.75*count)]
#    ric = (Q3-Q1)
#    whislo =max(0, Q1 -1.5*ric)
#    whishi = Q3 +1.5*ric
#    result = {'med':median,'q1':Q1,'q3':Q3,'whislo':whislo,'whishi':whishi}
#    return result
#
#def makebxp(zfile,file_name):
#    count = 0
#    with z.open(file_name) as f:
#        dic = defaultdict(defaultval)
#        for line in f:
#            dic[abs(float(line[:-1]))]+=1
#            count+=1
#            if count >1000:
#                break
#        x,y = map(list,zip(*dic.items()))
#        return(boxst(x,y))
#
#with zipfile.ZipFile('clustering.zip') as z:
#    filen7 = ['clustering/dmu'+str(i).zfill(2)+'.txtn7clustering' for i in range(1,81)]
#    bxn7=[makebxp(z,file) for file in filen7]
#    filepr = ['clustering/dmu'+str(i).zfill(2)+'.txtprclustering' for i in range(1,81)]
#    bxpr=[makebxp(z,file) for file in filepr]
#    for i in range(1,41):
#        count = 0
#        nmbr = str(i).zfill(2)
#        bxps1.append(makebxp(z,file_name))
#       # with z.open(file_name) as f:
#       #     dic = defaultdict(defaultval)
#       #     for line in f:
#       #         dic[abs(float(line[:-1]))]+=1
#       #         count+=1
#       #         if count >50000:
#       #             break
#       #     x,y = map(list,zip(*dic.items()))
#       #     bxps.append(boxst(x,y))
#

# cargar los diccionarios
bxn7=[]
bxpr=[]
with open('n7dic','r') as f:
    for line in f:
        bxn7.append(ast.literal_eval(line))

with open('prdic','r') as f:
    for line in f:
        bxpr.append(ast.literal_eval(line))

labels = ["DMU"+str(i).zfill(2) for i in range(1,81)]
for start,end in [(0,40),(40,80)]:
    fig,ax =plt.subplots()
    ax.bxp(bxn7[start:end],showfliers=False)
    ax.set_xticklabels(labels[start:end], rotation=90, ha='center')
    ax.set_ylabel("Error relativo")
    #plt.savefig("n7"+"{}-{}".format(start+1,end)+".png")
    #plt.title("n7")
    print("n7")
    plt.show()

    fig,ax =plt.subplots()
    ax.bxp(bxpr[start:end],showfliers=False)
    ax.set_xticklabels(labels[start:end], rotation=90, ha='center')
    ax.set_ylabel("Error relativo")
    #plt.savefig("pr"+"{}-{}".format(start+1,end)+".png")
    #plt.title("Representación")
    print("pr")
    plt.show()


class Node:

    # Constructor to create  a new node
    def __init__(self, data):
        self.data = data
        self.next = None
class ringofnode:
    def __init__(self):
        self.head = None
        self.tail = None

    def insertion(self):
        data=input("Enter data:");
        temp=Node(data)
        if(head==None):

            head=temp
            tail=temp
            tail.next=head
        elif(head!=None):
            tail.next=temp
            tail=temp
            tail.next=head
    # def display(self):
    #     ptr=head
    #     if(ptr==None):
    #         print("no node is exists yet")
    #     else:
    #         print(ptr.data)
    #         ptr=ptr.next
    #         while(ptr!=head):
    #             print(ptr.data,end="->")
    #             ptr=ptr.next

# l1.display()