#!/usr/bin/env python3

import mistune
import lib.mdrenderer
import re
import codecs
import pybars
import yaml
import argparse
import sys
import os
import subprocess
import re

from copy import deepcopy
from pprint import pprint

CWD = os.path.dirname(os.path.abspath(__file__))

PCB_TEMP_DIR = '/tmp'

PCBDRAW_BIN = os.getenv('PCBDRAW_BIN','./pcbdraw.py')
PCB_PATTERN = '.*\[\[(.+)\|?(.*)?\]\](.*)'

CWD_PATH = os.getenv('PWD',os.path.dirname(os.path.abspath(__file__)))

def flatten(l):
    return [item for sublist in l for item in sublist]

def svg_to_png(infile, outfile, dpi=300):
    import cairo
    import gi
    gi.require_version('Rsvg', '2.0')
    from gi.repository import Rsvg

    handle = Rsvg.Handle()
    svg = handle.new_from_file(infile)
    svg.set_dpi(dpi)
    dim = svg.get_dimensions()
    w, h = dim.width, dim.height
    img =  cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
    ctx = cairo.Context(img)
    svg.render_cairo(ctx)
    img.write_to_png(outfile)

def generate_image(boardfilename, libs, side, components, active, parameters, outputfile):
    svgfilename = os.path.splitext(outputfile)
    svgfilename, ext = svgfilename[0] + ".svg", svgfilename[1]

    # TODO: fallback, origional
    # command = [PCBDRAW_BIN, "-f", ",".join(components), "-a", ",".join(active)]

    # command = [PCBDRAW_BIN, ",".join(active)]

    # if side.startswith("back"):
    #     command.append("-b")
    # command += flatten(map(lambda x: x.split(" ", 1), parameters))
    # command.append(libs)
    # command.append(boardfilename)
    # command.append(svgfilename)

    command = [PCBDRAW_BIN]
    if side.startswith("back"):
        command.append("-b")
    command.append(libs)
    command.append(boardfilename)
    command.append(svgfilename)
    print(' '.join(command))

    try:
        output = subprocess.check_output(command, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as e:
        print("PcbDraw failed with code {} and output: ".format(e.returncode))
        print(e.output)
        sys.exit(1)
    if ext != ".svg":
        if ext == ".png":
            svg_to_png(svgfilename, outputfile)
            os.remove(svgfilename)
        else:
            print("Unsupported image type: {}".format(ext))
            sys.exit(1)

# def generate_images(content, boardfilename, libs, parameters, name, outdir):
#     dir = os.path.dirname(os.path.join(outdir, name))
#     if not os.path.exists(dir):
#         os.makedirs(dir)
#     counter = 0
#     for item in content:
#         if item["type"] == "comment":
#             continue
#         for x in item["steps"]:
#             if x["comment"].find('[x]') >= 0 or x["comment"].find('[ ]') >= 0:
#                 pass
#             else:
#                 # pprint(x['side'])
#                 counter += 1
#                 filename = name.format(counter)
#                 generate_image(boardfilename, libs, x["side"], x["components"], x["active_components"], parameters, os.path.join(outdir, filename))
#                 x["img"] = filename
#     return content

def merge_args(args, header):
    for key in filter(lambda x: not x.startswith("_"), dir(args)):
        val = getattr(args, key)
        if val is not None:
            header[key] = val
    if "params" not in header:
        header["params"] = []
    return header

def find_command(list, command):
    for x in list:
        if x.startswith(command):
            return x
    return None

def relativize_header_paths(header, to):
    for key in ["template", "board", "libs"]:
        if key not in header:
            continue
        if os.path.isabs(header[key]):
            continue
        x = os.path.join(to, header[key])
        header[key] = os.path.normpath(x)
    if "params" in header:
        x = header["params"]
        newlist = []
        for key in ["--style", "--remap"]:
            c = find_command(x, key)
            if c is None:
                continue
            y = c.split(" ")
            command, arg = y[0], y[1]
            if os.path.isabs(arg):
                continue
            c = command + " " + os.path.normpath(os.path.join(to, arg))
            newlist.append(c)
        header["params"] = newlist
    return header

def load_content(filename):
    header = None
    with codecs.open(filename, encoding="utf-8") as f:
        content = f.read()
        if content.startswith("---"):
            end = content.find("...")
            if end != -1:
                header = yaml.load(content[3:end])
                content = content[end+3:]
    return header, content

def check_pcb_drawing_mark(md_text):
    # if re.search('.*\[\[.*\]\].*',md_text):
    m = re.match(PCB_PATTERN,md_text)
    return m

def get_pcb_drawing_md_text(pcb_drawing_path, alt_text):
    return """![{}]({} "{}")""".format(alt_text,
        pcb_drawing_path, alt_text
    )

def inject_pcb_drawing_placeholder(alt_text, pcb_drawing_path):
    pcb_placeholder_string = get_pcb_drawing_md_text(pcb_drawing_path, alt_text)
    return pcb_placeholder_string

def get_pcb_drawing_link():
    pass

def scan_content_for_pcb_drawing_mark(md_content):
    kicad_pcb_path = os.path.join(CWD_PATH, args["board"])
    lib_path = args["libs"]
    pcbdraw_params = args["params"]
    img_name_path_template = args["img_name"]
    md_outoput_path = args["output"]

    pcb_draw_number = 0
    for i in range(0,len(md_content)):
        md_line = md_content[i]
        m = check_pcb_drawing_mark(md_line)
        if m is not None:
            side = m.group(1)
            highlight_component = m.group(2)
            alt_text = m.group(3)
            pcb_draw_number+=1

            # TODO: refactor me
            img_name_path = os.path.join(md_outoput_path,img_name_path_template.format(pcb_draw_number))

            generate_image(kicad_pcb_path, lib_path, side, highlight_component, highlight_component, pcbdraw_params, img_name_path)

            print(img_name_path)

            md_content[i] = inject_pcb_drawing_placeholder(alt_text, img_name_path_template.format(pcb_draw_number))

    return md_content

def replace_pcb_drawing_placeholder_by_drawing():
    pass

def main():
    print('helloworld')

if __name__ =="__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("input", help="source file")
    parser.add_argument("output", help="output directory")

    args = parser.parse_args()

    try:
        header, content = load_content(args.input)
    except IOError:
        print("Cannot open source file " + args.input)
        sys.exit(1)
    header = relativize_header_paths(header, os.path.dirname(args.input))
    args = merge_args(args, header)
    content = content.split('\n')

    # inject pcb_drawing_mark for md_content
    md_temp = scan_content_for_pcb_drawing_mark(content)

    INPUT_MD_PATH = os.path.join(args['input'])
    OUTPUT_MD_PATH = os.path.join(args['output'], 'index.md')

    print('input markdown: %s' % INPUT_MD_PATH)
    print('output markdown: %s' % OUTPUT_MD_PATH)

    with open(OUTPUT_MD_PATH,'w+') as f:
        f.write('\n'.join(md_temp))

    # main()


# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# 方法1：递归
class Solution:
    def IsBalanced_Solution(self, pRoot):
        if not pRoot:
            return True
        l = self.TreeDepth(pRoot.left)
        r = self.TreeDepth(pRoot.right)
        return abs(l - r) <= 1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    def TreeDepth(self, pRoot):
        # write code here
        if not pRoot:
            return 0
        queue = [pRoot]
        depth = 0
        while queue:
            depth += 1
            child_queue = []
            for node in queue:
                if node.left:
                    child_queue.append(node.left)
                if node.right:
                    child_queue.append(node.right)
            queue = child_queue

        return depth

# 方法2
class Solution_:
    def IsBalanced_Solution(self, pRoot):
        if not pRoot:
            return True
        l = self.TreeDepth(pRoot.left)
        if l == -1:
            return False
        r = self.TreeDepth(pRoot.right)
        if r == -1:
            return False

        return abs(l - r) <= 1
    def TreeDepth(self, pRoot):
        # write code here
        if not pRoot:
            return 0
        left = self.TreeDepth(pRoot.left)
        if left == -1:
            return -1
        right = self.TreeDepth(pRoot.right)
        if right == -1 or abs(left - right) > 1:
            return -1
        else:
            return 1 + max(left, right)

l = [1,2,3,4,7]
print(l.remove(7))
print(l)


from time import sleep
maior = 0
def maior(*args):
    print("-=" * 30)
    print("Analisando os valores passados...")
    for i in args:
        if i == args[0]:
            maior = i
        else:
            if i > maior:
                maior = i
        print(i, end = " ")
        sleep(0.5)
    print(f'Foram informados {len(args)} valores ao todo.')
    if len(args) == 0:
        maior = 0
    print(f'O maior valor informado foi {maior}.')

maior(6,5,2,3,4)
maior(3,2,5,7,8,4,2,1,0)
maior(2,3)
maior(6)
maior()


from django.shortcuts import render

from django.http import HttpResponse
from app_celery.tasks import celery_send_email

import datetime
# Create your views here.

# 计时
def count_time(func):
    def int_time(*args,**kwargs):
        start_time = datetime.datetime.now()
        func(*args)
        end_time = datetime.datetime.now()
        total_time = (end_time - start_time).total_seconds()
        print('计时: %s 秒' % total_time)
        return HttpResponse('Send email successful! ')
    return int_time

@count_time
def add_task_send_email(request):
    celery_send_email.delay('邮件的主题','这是邮件内容','18537623991@163.com',['451253127@qq.com'])
    # return HttpResponse('Send email successful! ')


#!/usr/bin/env python3

def is_prime(n):
    for i in range(2, int(n**0.5+1)):
        if not n % i:
            return False
    return True

def get_prime(n):
	prime_counter, num = 0, 1
	while prime_counter != n:
		num += 1
		if is_prime(num):
			prime_counter += 1
	return num

print(get_prime(10001))
# Answer: 104743


# -*- coding: utf-8 -*-
"""
Created on Tue Oct 27 08:37:30 2020

@author: pedro-salj
"""

#############################
##### CONFIGURAÇÃO GERAL ####
#############################
globals().clear()
""" Mudar diretório """
import os
from pathlib import Path
import getpass
if getpass.getuser() == "pedro":
    print('\nLogado de casa')
    caminho_base = Path(r'D:\Códigos, Dados, Documentação e Cheat Sheets')
elif getpass.getuser() == "pedro-salj":
    print('\nLogado da salj-alems')
    caminho_base = Path(r'C:\Users\pedro-salj\Desktop\Pedro Nakashima\Códigos, Dados, Documentação e Cheat Sheets')

""" Mudar diretório para dados Siconfi"""
caminho_wd = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python Time Series (Udemy)' / 'Data'
print('\nDiretório anterior:\n', os.getcwd())
os.chdir(caminho_wd)
print('\nDiretório atual:\n', os.getcwd())

#############################
#############################
#############################
globals().clear()

from datetime import datetime

my_year = 2020
my_month = 1
my_day = 2
my_hour = 13
my_min = 30
my_sec = 15

my_date = datetime(my_year, my_month, my_day)
print(my_date)
print(type(my_date))

my_date_time = datetime(my_year, my_month, my_day, my_hour, my_min, my_sec)
print(my_date_time)

print(my_date_time.day)

#############################
##### datetime do numpy #####
#############################

import numpy as np

date = np.array(['2020-03-15', '2020-03-16', '2020-03-17'])
print(type(date))

date = np.array(['2020-03-15', '2020-03-16', '2020-03-17'], dtype='datetime64')
print(date.dtype)

date = np.array(['2020-03-15', '2020-03-16', '2020-03-17'], dtype='datetime64[Y]')
print(date.dtype)

date = np.array(['2020-03-15', '2020-03-16', '2020-03-17'], dtype='datetime64[h]')
print(date.dtype)
print(date)

#############################
##### np.arange #############
#############################
print(np.arange(0,10,2))

print(np.arange('2018-06-01','2018-06-23', 7, dtype='datetime64[D]'))

print(np.arange('1968','1976', dtype='datetime64[Y]'))

#############################
##### pandas ################
#############################

import pandas as pd

print(pd.date_range('2020-01-01', periods=7, freq='D'))

print(pd.date_range('Jan 01, 2018', periods=7, freq='D'))

print(pd.to_datetime(['1/2/2018', 'Jan 03, 2018']))

print(pd.to_datetime(['1/2/2018', '1/3/2018']))

print(pd.to_datetime(['2/1/2018', '3/1/2018']))

print(pd.to_datetime(['2/1/2018', '3/1/2018'], format='%d/%m/%Y'))

print(pd.to_datetime(['2--1--2018', '3--1--2018'], format='%d--%m--%Y'))

data = np.random.randn(3,2)
cols = ['A', 'B']
print(data)

idx = pd.date_range('2020-01-01', periods=3, freq='D')

df = pd.DataFrame(data, index=idx, columns=cols)

print(df)
print(df.index)
print(df.index.max())
print(df.index.argmax())
print(df.index.argmin())

#############################
##### Time Resampling #######
#############################

import pandas as pd

pasta = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python for time series (Udemy)' / 'Data'
df = pd.read_csv(pasta / 'starbucks.csv', index_col='Date', parse_dates=True)

print(df.head())

print(df.info())

print(df.index)

# daily --> yearly
print(df.resample(rule='A').mean())
print(df.resample(rule='A').std())

def first_day(entry):

    # IS THERE AN ENTRY?
    if len(entry) != 0:
        # IF SO, RETURN FIRST ENTRY
        return entry[0]

print(df.resample(rule='A').apply(first_day))

df['Close'].resample('A').mean().plot.bar()

title = 'Monthly Max Closing Price for Starbucks'
df['Close'].resample('M').max().plot.bar(figsize=(16,6), title=title, color='#1f77b4')

#############################
##### Time Shifting #########
#############################

import pandas as pd

pasta = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python for time series (Udemy)' / 'Data'
df = pd.read_csv(pasta / 'starbucks.csv', index_col='Date', parse_dates=True)

print(df.head())
print(df.tail())

print(df.shift(1))

print(df.shift(1, fill_value=0))

print(df.shift(1).tail())

print(df.shift(5))

# df = df.shift(5)

print(df.shift(-1))
print(df.shift(-1).tail())

# -----------------------------------

print(df.shift(periods=1, freq='M'))

#################################
##### Rolling and Expanding #####
#################################

# Rolling ---------------------------------------

import pandas as pd

pasta = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python for time series (Udemy)' / 'Data'
df = pd.read_csv(pasta / 'starbucks.csv', index_col='Date', parse_dates=True)

df['Close'].plot()

df['Close'].plot(figsize=(12,5))

print(df.rolling(window=7).mean().head(10))

df['Close'].plot(figsize=(12,5))
df.rolling(window=7).mean()['Close'].plot()

df['Close'].plot(figsize=(12,5))
df.rolling(window=30).mean()['Close'].plot()

df['Close'].plot(figsize=(12,5))
df.rolling(window=60).mean()['Close'].plot()

df['Close'].plot(figsize=(12,5))
df.rolling(window=15).mean()['Close'].plot()

df['Close: 30 Day Mean'] = df['Close'].rolling(window=30).mean()

print(df.head())

df[['Close', 'Close: 30 Day Mean']].plot(figsize=(12,5))

# Expanding ---------------------------------------

df['Close'].expanding().mean().plot(figsize=(12,5))

########################################
##### Visualizing Time Series Data #####
########################################

import pandas as pd

pasta = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python for time series (Udemy)' / 'Data'
df = pd.read_csv(pasta / 'starbucks.csv', index_col='Date', parse_dates=True)

print(df.index)

#df.index = pd.to_datetime(df.index)

df.plot()

df['Close'].plot()

df['Close'].plot();

df['Volume'].plot()

title = 'TITLE'
ylabel = 'Y LABEL'
xlabel = 'X LABEL'

df['Close'].plot(figsize=(12,6), title=title)

""" Para adicionar labels x e y, precisa atribuir o
gráfico a uma variável, por convenção ax """

ax = df['Close'].plot(figsize=(12,6), title=title)

ax.autoscale(axis='both', tight=True) # sem espaço em branco na vertical e horizontal

ax.set(xlabel=xlabel, ylabel=ylabel)

# ---------------------

ax = df['Close'].plot(figsize=(12,6), title=title)

ax.autoscale(axis='y', tight=True) # sem espaço em branco na vertical

ax.set(xlabel=xlabel, ylabel=ylabel)

# ---------------------

""" Plotando apenas um ano. Forma 1 """

print(df['Close'])
print(df['Close']['2017-01-01':'2017-12-31'])

df['Close'].plot(figsize=(12,4))

df['Close']['2017-01-01':'2017-12-31'].plot(figsize=(12,4))

""" Plotando apenas um ano. Forma 2 """

df['Close'].plot(figsize=(12,4), xlim = ['2017-01-01','2017-12-31'])

""" Usando ylim """

df['Close']['2017-01-01':'2017-12-31'].plot(figsize=(12,4), ylim=[0,70])

df['Close']['2017-01-01':'2017-12-31'].plot(figsize=(12,4), ylim=[40,70])

""" Estilo da linha: ls """

df['Close']['2017-01-01':'2017-12-31'].plot(figsize=(12,4), ylim=[40,70], ls='--')

""" Cor da linha: c """

df['Close']['2017-01-01':'2017-12-31'].plot(figsize=(12,4), ylim=[40,70], ls='--', c='red')

""" Outras configurações """

import pandas as pd

pasta = caminho_base / 'Dados' / 'Cursos e Livros' / 'Python for time series (Udemy)' / 'Data'
df = pd.read_csv(pasta / 'starbucks.csv', index_col='Date', parse_dates=True)

df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60])

df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))

""" tirando o label do eixo x """

ax = df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))
ax.set(xlabel='')

""" xticks
Agora, as datas estão igualmente espaçadas
Agora, não há mais marcação de cada novo mês
Agora, o espaçamento é por 1 semana"""

from matplotlib import dates

ax = df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))
ax.set(xlabel='')

ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=0))

""" formatando as datas"""

from matplotlib import dates

ax = df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))
ax.set(xlabel='')

ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=0))
ax.xaxis.set_major_formatter(dates.DateFormatter('%a-%B-%d'))

""" minor axis """

from matplotlib import dates

ax = df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))
ax.set(xlabel='')

ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=0))
ax.xaxis.set_major_formatter(dates.DateFormatter('%d'))

ax.xaxis.set_minor_locator(dates.MonthLocator())
ax.xaxis.set_minor_formatter(dates.DateFormatter('\n\n%b')) #\n representa uma nova linha

""" grid """

from matplotlib import dates

ax = df['Close'].plot(xlim=['2017-01-01','2017-03-01'], ylim=[50,60], figsize=(12,5))
ax.set(xlabel='')

ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=0))
ax.xaxis.set_major_formatter(dates.DateFormatter('%d'))

ax.xaxis.set_minor_locator(dates.MonthLocator())
ax.xaxis.set_minor_formatter(dates.DateFormatter('\n\n%b')) #\n representa uma nova linha

ax.yaxis.grid(True)
ax.xaxis.grid(True)

dt_str = '202001'
print(pd.to_datetime([dt_str], format='%Y%m'))

Cursos e Vídeos/Python/Python for Time Series (Udemy)/6 Time series.py


# Python3 program to find Integral
# points inside a triangle

# Class to represent an Integral
# point on XY plane.
# nc 14.225.254.58 55555

import socket
from time import sleep

HOST = '14.225.254.58'
PORT = 55555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (HOST, PORT)
print('connecting to %s port ' + str(server_address))
s.connect(server_address)

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

# Utility function to find GCD of
# two numbers GCD of a and b
def gcd(a, b):

    if (b == 0):
        return a

    return gcd(b, a % b)

# Finds the no. of Integral points
# between two given points
def getBoundaryCount(p, q):

    # Check if line parallel to axes
    if (p.x == q.x):
        return abs(p.y - q.y) - 1
    if (p.y == q.y):
        return abs(p.x - q.x) - 1

    return gcd(abs(p.x - q.x),
               abs(p.y - q.y)) - 1

# Returns count of points inside the triangle
def getInternalCount(p, q, r):

    # 3 extra integer points for the vertices
    BoundaryPoints = (getBoundaryCount(p, q) +
                      getBoundaryCount(p, r) +
                      getBoundaryCount(q, r) + 3)

    # Calculate 2*A for the triangle
    doubleArea = abs(p.x * (q.y - r.y) +
                     q.x * (r.y - p.y) +
                     r.x * (p.y - q.y))

    # Use Pick's theorem to calculate
    # the no. of Interior points
    return (doubleArea - BoundaryPoints + 2) // 2

def getCount(p, q):

    # If line joining p and q is parallel
    # to x axis, then count is difference
    # of y values
    if p.x == q.x:
        return abs(p.y - q.y) - 1

    # If line joining p and q is parallel
    # to y axis, then count is difference
    # of x values
    if p.y == q.y:
        return abs(p.x - q.x) - 1

    return gcd(abs(p.x - q.x),
               abs(p.y - q.y)) - 1

# Driver code
if __name__=="__main__":
    data= s.recv(1024)
    while(1):
        data=s.recv(100)
        if b'chuc mung' in data:
            print(data)
            break
        print(data)
        a = int(data.split(b' ')[0].split(b'=')[1])
        # print(a)
        b= int(data.split(b' ')[1].split(b'=')[1][:-3])
        # print(b)
        p = Point(0, 0)
        q = Point(a, 0)
        r = Point(0, b)
        res1 = getCount(q,r)+a+b+1
        s.send(str(res1).encode())
        s.recv(100)
        res2= getInternalCount(p, q, r)
        s.send(str(res2).encode())
        sleep(3)

    s.close()

    # print("Number of integral points "
    #       "inside given triangle is ",
    #       getInternalCount(p, q, r))


from classes import Action

board = []
actions: list[Action] = []

def readInput(pathToFile: str):
    b = [[],[],[],[],[],[],[],[],[]]
    a = []

    actionMode = False
    lines = []
    with open(pathToFile) as puzzleInput:
        lines = puzzleInput.readlines()

    for line in lines:
        if line.startswith(" 1") or line == '\n':
            actionMode = True
        else:
            if actionMode:
                a.append(Action(line))
            else:
                entries = [line[1],line[5],line[9],line[13],line[17],line[21],line[25],line[29],line[33]]
                for i in range(0, len(entries)):
                    if entries[i] != ' ':
                        b[i].insert(0, entries[i])

    return b, a

def boardAsString():
    string = ""
    for column in board:
        if len(column) > 0:
            string += column[-1]
    return string

def partOne():
    # execute actions
    for action in actions:
        for iter in range(0, action.count):
            moveItem = board[action.fromStack].pop()
            board[action.toStack].append(moveItem)

    print(boardAsString()) # FCVRLMVQP

def partTwo():
    # execute actions with multi-stack
    for action in actions:
        fromIndex = len(board[action.fromStack]) - action.count
        if fromIndex < 0:
            fromIndex = 0

        moveItems = board[action.fromStack][fromIndex:]
        board[action.fromStack] = board[action.fromStack][:fromIndex]
        board[action.toStack].extend(moveItems)

    print(boardAsString()) # RWLWGJGFD

if __name__ == '__main__':
    board, actions = readInput("./input.txt")
    # partOne()
    partTwo()


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

# In[2]:

print("Hola, Soy Diana y estoy probando un script para el curso de IA en QILAS.")

# In[3]:

(5+3)*10

# In[4]:

# guardamos la operacion en la variable "cuenta"
cuenta = (5+3)*10

# In[5]:

cuenta

# In[6]:

# guardamos la operacion en la variable "cuenta"
cuenta = (5+3)*10

# In[7]:

# accedemos al interior de la variable "cuenta" para asegurarnos que se guardo bien los datos del resultado
cuenta

# In[8]:

# el comando "type" nos permite poder saber que tipo de formato de dato esta guardado en la variable en cuestion
type(cuenta)

# In[11]:

# importamos la librería Numpy
import numpy as np

# In[12]:

# creamos la matriz de 2x2 llena de ceros con el comando np.zeros()
nula = np.zeros((2,2))

# In[13]:

# si quisieramos acceder al elemento 0,0 de nula
nula[0,0]

# In[14]:

#Una vez declarada en python, podemos modificar alguno de los elementos de la matriz (numpy array) nula.

# por ejemplo el de la posicion 1,0
nula[1,0] = 4

# y tambien modificamos la posicion 0,1
nula[0,1] = 10

# In[18]:

# imprimimos la matriz nula en pantalla para observar la modificacion realizada
nula

# In[19]:

#podriamos realizar operaciones logicas y obtener resultados "booleanos" (True or False). Por ejemplo, preguntamos que elementos son mayores a cero.
nula > 0

# In[20]:

#Calculamos raiz cuadrada de todos los elementos de la matriz nula con el comando np.sqrt(). SQRT significa square root en ingles.

# podriamos calcular la raiz cuadrada de todos los elementos de nula con "np.sqrt()"
raiz_cuad = np.sqrt(nula)
raiz_cuad

# In[21]:

#con el comando de python de doble * se realiza el cuadrado del elemento en cuestion
# observamos que si a raiz_cuad la afectamos por el cuadrado obtenemos nuevamente nula
raiz_cuad**2

# In[22]:

#Numpy tambien nos permite crear matrices de la dimension que querramos con numeros aleatorios mediante el comando "np.random.rand()".

# creamos un array de 3x3 con todos sus elementos completados nros aleatorios de una distribución uniforme
array_uniform = np.random.rand(3,3)
array_uniform

# In[23]:

#Podemos tambien crear vectores, solamente especificando una sola dimension.

# generamos un vector de 10 posiciones completados desde nros. aleatorios de una dist. uniforme
vector_uniform = np.random.rand(10)
vector_uniform

# In[24]:

#Trasponer un numpy array con ".T" al final
# vamos a transponer la matriz array_uniform
array_uniform_t = array_uniform.T
array_uniform_t

# In[25]:

#Calcular la inversa de una matriz (en formato numpy array) con el comando np.linalg.inv()

# podemos tambien calcularle la inversa a la matriz array_uniform
array_uniform_inv = np.linalg.inv(array_uniform)
array_uniform_inv

# In[26]:

#Calcular el producto de dos matrices con np.dot
# podemos calcular el producto punto (dot product) entre array_uniform y array_uniform_inv
array_uniform_dot = np.dot(array_uniform, array_uniform_inv)
array_uniform_dot

# In[27]:

#Crear una matriz con valores determinados por el usuario
# tambien podriamos crear una nueva matriz con datos ingresados
a=np.array([ [1  ,-4],[12 , 3]])
a

# In[28]:

#Distribuciones de probabilidad con numpy
#Generamos un vector cuyas posiciones sean numeros aleatorios provenientes de una distribucion normal con media y desvio standard determinado.
# declaramos las variables numericas "mu" y "sigma"
mu = 0
sigma = 0.1
# con las variables declaradas generamos un vector de 1000 posiciones
# cada posicion es un numero aleatorio extraido de una distribucion normal
normal_sample = np.random.normal(mu, sigma, 1000)

# In[29]:

# si quisieramos ver las dimensiones del vector usamos el comando np.shape
np.shape(normal_sample)

# In[30]:

# si quisieramos saber que tipo de variable es "normal_sample" usamos el comando type
type(normal_sample)

# In[31]:

# si quisieramos saber el valor de la posicion 50 del vector "normal_sample"
normal_sample[50]

# In[32]:

# podemos redondear el valor obtenido en la celda anterior con "np.round()"
# le pedimos 4 decimales
np.round(normal_sample[50],4)

# In[33]:

# imprimimos en pantalla el vector correspondiente
normal_sample

# In[48]:

#Visualizaciones con librerías Matplotlib y Seaborn
#Ambas son para realizar visualizaciones. Existen muchas formas de visualizar datos estructurados en un vector o matriz. Los mas comunes son los histogramas, los mapas de calor, etc.

# importamos las librerias que nos serviran para visualizar
import matplotlib.pyplot as plt
import seaborn as sns

# In[49]:

#Con "sns.distplot()" seaborn nos permite poder realizar un histograma y una aproximacion a la distribución de los datos en cuestion. En este caso realizaremos el distplot con el vector "normal_sample".

# generamos el distplot
sns.distplot(normal_sample)
plt.title("histograma del vector 'normal_sample' ")
plt.xlabel("valores de la variable aleatoria muestreada")
plt.ylabel("densidad de cada valor muestreado")
plt.show()

# In[50]:

# si generamos otro vector "normal_sample_2" con otra media y otro desvio standard
mu_2 = 0.5
sigma_2 = 0.2
# con las variables declaradas generamos un vector de 1000 posiciones
# cada posicion es un numero aleatorio extraido de una distribucion normal
normal_sample_2 = np.random.normal(mu_2, sigma_2, 1000)

# In[51]:

# generamos el distplot
sns.distplot(normal_sample_2)
plt.title("histograma del vector 'normal_sample_2' ")
plt.xlabel("valores de la variable aleatoria muestreada")
plt.ylabel("densidad de cada valor muestreado")
plt.show()

# In[52]:

# generamos el distplot, en una misma celda de codigo uno debajo del otro
# plt.show() imprime toda visualizacion que se haya acumulado en esa celda de codigo
sns.distplot(normal_sample,label = "normal_sample")
sns.distplot(normal_sample_2, label = "normal_sample2")
plt.title("histograma de los dos vectores generados ")
plt.xlabel("valores de la variable aleatoria muestreada")
plt.ylabel("densidad de cada valor muestreado")
plt.legend()
plt.show()

# In[53]:

#Scatter plot Si consideramos ambos vectores como coordenadas y cada posicion una muestra (un punto) entonces tenemos 1000 muestras cada una caracterizada por 2 valores (o dimensiones). Dicho esto, podemos entonces visualizar las 1000 muestras caracterizadas por los 2 vectores provenientes cada uno de una distribucion normal con distintos parametros. El scatter plot visualiza nubes de puntos. Seaborn tiene una función para realizar scatter plots.

# In[54]:

# utilizamos cada vector como una dimension, uno para el eje x y otro para el eje y.
sns.scatterplot(x= normal_sample, y= normal_sample_2)
plt.title("Ejemplo de scatterplot con seaborn")
plt.xlabel("valores de normal_sample")
plt.ylabel("valores de normal_sample_2")
plt.show()

# In[55]:

# con el comando plt.scatter() ingresamos los 2 vectores para visualizar las 1000 muestras.
# el parametro "alpha" hace traslucidas las muestras que se solapan una encima de otra.
plt.scatter(normal_sample, normal_sample_2, alpha = 0.5)
plt.title("Ejemplo de scatterplot con matplotlib")
plt.xlabel("valores de normal_sample")
plt.ylabel("valores de normal_sample_2")
plt.show()

# In[ ]:


import math
import re
from gravity import gravity
from luminosity import luminosity
from utilities import basic_math

class CelestialBody:
    """The standard units of measure used throughout are as follows:
        distance: kilometers
        mass: kilograms
        temperature: Kelvin
        volume: cubic kilometers
        gravitational force: Newtons
        gravitational acceleration: meters / second squared
    """
    default_unit = {
        "distance": "kilometers",
        "mass": "kilograms",
        "density": "kilograms per cubic meter",
        "volume": "cubic kilometers",
        "gravitational_force": "Newtons",
        "gravitational_acceleration": "meters / second squared",
        "luminosity": "Joules / second"
    }

    def __init__(self, mass: float, radius: float, name: str = None):
        """

        :param float mass: the mass of the celestial body in kilograms
        :param float radius: the radius of the celestial body (assumed to be
        roughly spherical) in meters
        :param str name: the name of the celestial body (if None is supplied,
        will default to "Unnamed" celestial body
        """
        self.mass = mass
        self.radius = radius
        self.celestial_body_type = re.sub(
            r'([A-Z])', r' \1', self.__class__.__name__).strip()
        if name is None:
            self.__name = "Unnamed Celestial Body"
        else:
            self.__name = name
        self.primary_body = None
        self.orbiting_bodies = []

    def __repr__(self):
        return f"{self.__class__.__name__}({self.mass}, {self.radius})"

    def __str__(self):
        """To easily subclass, add subclass-specific stats to the
        additional_stats or orbital_stats property."""
        return self.basic_stats + self.additional_stats + self.orbital_stats

    @property
    def name(self):
        """Getter for CelestialBody name. Note that name becomes a protected
        attribute after initialization. This is to help prevent
        name-switching from causing problems when used with the Universe
        class."""
        return self.__name

    @property
    def basic_stats(self) -> str:
        """Returns a string of the basic statistics of the celestial body
        (i.e., statistics that should be shared by all celestial bodies).

        :return: basic statistics of the celestial body
        :rtype: str
        """
        return f"""{self.name} ({self.celestial_body_type}):
    mass: {self.mass} {self.default_unit['mass']}
    radius: {self.radius} {self.default_unit['distance']}
    volume: {self.volume} {self.default_unit['volume']}
    density: {self.density} {self.default_unit['density']}
    gravitational_acceleration: {self.gravitational_acceleration} {
        self.default_unit['gravitational_acceleration']}"""

    @property
    def orbital_stats(self) -> str:
        """Returns string names of the primary and orbiting bodies of
        the celestial body (if any exist).

        :return: names of primary and orbiting bodies (if any)
        :rtype: str
        """
        return_str = ""
        if self.primary_body is not None:
            return_str += f"\nOrbits around {self.primary_body.name}"
        if len(self.orbiting_bodies) > 0:
            orbiting_bodies = ", ".join(
                [x.name for x in self.orbiting_bodies])
            return_str += f"\nOrbited by: {orbiting_bodies}"
        return return_str

    @property
    def additional_stats(self) -> str:
        """Returns additional (i.e., subclass-specific) statistics of the
        celestial body.

        :return: subclass-specific statistics of the celestial body
        :rtype: str
        """
        return ""

    @property
    def volume(self):
        """Returns the volume of the celestial body.

        Assumption: the celestial body is roughly spherical. This should
        be a decent approximation for most celestial bodies, even black holes,
        but the method is provided here so as to be easily overridden by a
        subclass.

        Example:
            Earth's Radius: 6,371 kilometers
            Earth's Volume: 1,083,206,916,845.7535 cubic kilometers

        :return: the volume of the celestial body in cubic kilometers
        :rtype: float
        """
        return basic_math.calculate_volume_of_sphere(self.radius)

    @property
    def density(self):
        """Returns the density of the celestial body.

        Note the conversion to meters for more standard measure of density.

        :return: the density of the celestial body in kilograms per cubic
        meter
        :rtype: float
        """
        return basic_math.calculate_density(self.mass, self.volume *
                                            math.pow(1000, 3))

    @property
    def gravitational_acceleration(self):
        """Returns the gravitational acceleration of the celestial body.

        :return: the gravitational acceleration of the celestial body in
        meters / second squared
        :rtype: float
        """
        return gravity.calculate_gravitational_acceleration(
            self.mass, self.radius)

class BlackHole(CelestialBody):
    """subclasses CelestialBody : is a CelestialBody"""

    def __init__(self, mass: float, name: str = None):
        """Only the mass of the black hole is requested as a parameter,
        as the radius will be directly calculated.

        Assumptions:
            - The Schwarzschild radius (event horizon) will be used as an
            approximation of the size of a Black Hole.

        :param float mass: the mass of the black hole in kilograms
        """
        self.mass = mass
        super().__init__(self.mass, self.event_horizon, name)

    def __repr__(self):
        return f"{self.__class__.__name__}({self.mass})"

    @property
    def event_horizon(self) -> float:
        """Returns the Schwarzschild radius (i.e., the radius of a black
        hole's event horizon).

        :return: radius of event horizon of the black hole in kilometers
        :rtype: float
        """
        return gravity.calculate_schwarzschild_radius(self.mass) / 1000

class SolarBody(CelestialBody):
    """subclasses CelestialBody : is a CelestialBody"""

    def __init__(self, mass: float, radius: float, temperature: float,
                 name: str = None):
        """For a solar body, we also require temperature as an initializing
        parameter, as this allows the luminosity to be calculated.

        :param float mass: the mass of the solar body in kilograms
        :param float radius: the radius of the solar body in kilometers
        :param float temperature: the surface temperature of the solar body
        in degrees Kelvin
        """
        self.temperature = temperature
        super().__init__(mass, radius, name)

    def __repr__(self):
        return f"{self.__class__.__name__}({self.mass}, {self.radius}, " \
               f"{self.temperature})"

    @property
    def additional_stats(self) -> str:
        """Returns additional (i.e., subclass-specific) statistics of the
        celestial body.

        :return: subclass-specific statistics of the celestial body
        :rtype: str
        """
        return f"""
    Harvard Spectral Classification: {self.harvard_spectral_classification}
    luminosity: {self.luminosity} {self.default_unit['luminosity']}
    chromaticity: {self.chromaticity}"""

    @property
    def luminosity(self) -> float:
        """Returns the luminosity of the solar body.

        :return: luminosity of the solar body
        :rtype: float
        """
        return luminosity.calculate_stefan_boltzmann_luminosity(
            self.radius, self.temperature)

    @property
    def harvard_spectral_classification(self) -> str:
        """Returns the Harvard Spectral Classification based on temperature.

        :return: Harvard Spectral Classification
        :rtype: str
        """
        return luminosity.classify_harvard_spectral_classification(
            self.temperature)[0]

    @property
    def chromaticity(self) -> str:
        """Returns the chromaticity of the solar body based on temperature.
        Note that this will be a color description.

        :return: chromaticity of solar body
        :rtype: str
        """
        return luminosity.classify_harvard_spectral_classification(
            self.temperature)[1]

class PlanetaryBody(CelestialBody):
    """subclasses CelestialBody : is a CelestialBody

    PlanetaryBody allows for calculation of weights of objects on its
    surface, which makes little sense for a SolarBody or a BlackHole.
    """

    def calculate_weight_on_surface(self, mass_of_object: float = 70) -> \
            float:
        """Estimates the weight, in kilograms, of an object on the surface of
        the planetary body. If no mass is provided, default is 70 kg,
        a decent enough approximation of the mass of an average person.

        Assumptions:
            - Gravity is the only force affecting weight.

        :param float mass_of_object: the mass (in kilograms) of the object
        :return: the weight (in kilograms) of the object on the surface of
        the planetary body
        :rtype: float
        """
        weight_in_newtons = \
            gravity.calculate_gravitational_force_between_two_objects(
                self.mass, mass_of_object, self.radius)
        return basic_math.convert_weight_in_newtons_to_kilograms(
            weight_in_newtons)


# _*_ encoding utf-8 _*_

import cv2, os

scale_factor = ['1', '0.25']
for scale in scale_factor:
    dir = 'E:\\0-PhD\\5 nozzle\\5nozzle-DLN2.6SIZE\\geometry scaling les\\les-' + scale
    print(dir + ' is on processing')
    for tiffs in os.listdir(dir):
        dir_tiff = dir + '\\' + tiffs
        print(dir_tiff)
        image = cv2.imread(dir_tiff)
        size = image.shape[0:3]
        image_cut = image[106:316, 300:600]
        dir_cut = dir + '-cut\\'
        cv2.imwrite(dir_cut + tiffs, image_cut)
        cv2.destroyAllWindows()
        videoWriter = cv2.VideoWriter(dir_cut + scale + '.avi', cv2.VideoWriter_fourcc(*'mp4v'), 100, (300,210))
    dir_new = dir + '-cut\\'
    for tif_cut in os.listdir(dir_new):
        print(dir_new + tif_cut)
        img_cut = cv2.imread(dir_new + tif_cut)
        videoWriter.write(img_cut)
    input("all done")

11. 大涡模拟图片裁剪.py


import datetime

def salvar(nome):
    with open('DataBase.txt', 'a') as arquivo:
        arquivo.write(f'{nome}\n')

def fazercheckin():
    print('Fazer Check-In')
    varnome = (input('Digite o nome: '))

    while True:
        vartelefone = input('Telefone com DDD: ')
        if not(vartelefone.isnumeric()):

            print('Somente números!')
        else:
            break

    while True:
        varcpf = input('CPF: ')
        #print(cpfValidator(varcpf))

        if cpfValidator(varcpf) != True:
            print(f"CPF inválido, digite certo.".center(50,"="))
        else:
            print(f"Hospede cadastrado com sucesso".center(50,"="))
            dados = {
                'nome': varnome,
                'cpf': varcpf,
                'telefone': vartelefone
            }

            salvar(dados)
        break

def cpfValidator(cpf):
    CPFS = ["00000000000","11111111111", "22222222222", "33333333333", "44444444444",
        "55555555555", "66666666666", "77777777777", "88888888888", "99999999999"]
    hasError = False
    # Limpa o cpf, retira pontos traços e tudo que não seja um número
    cpf = [int(char) for char in cpf if char.isdigit()]

    # Verifica se o cpf são números repetidos
    if ''.join(map(str, cpf)) in CPFS:
        hasError = True

    # verifica se o tamanho está correto
    if len(cpf) != 11:
        hasError = True

    if not(hasError):
        for i in range(9, 11):
            value = sum((cpf[num] * ((i+1) - num) for num in range(0, i)))
            digit = ((value * 10) % 11) % 10
            if digit != cpf[i]:
                hasError = True

    if hasError:
        return False
    else:
        return True

def printmenu():

    funcoes = ['1','2','3','4','5']
    poli = "-"*50
    espaco = " "*10
    espaco1 = " "*2

    print(poli)
    print(f"(1) Fazer check-In\n(2) Relatório Hospedes\n(3) Procurar Hospedes\n(4) Fazer Check-Out\n(5) Finalizar Atendimento")
    print(poli)

def wellcome ():

    atual = datetime.datetime.now()
    hora = atual.hour
    minutos = atual.minute
    poli = "-"*50
    espaco = " "*10
    espaco1 = " "*7

    print(f"{poli}\n{espaco1}SEJA BEM VINDO NO HOTEL TRANSILVÂNIA \n{poli}")
    if hora < 12:
        print(f"{espaco}Bom dia! Horário atual: {hora} horas e {minutos} minutos.{espaco}".center(50,"="))
    elif hora < 18:
        print(f"{espaco}Boa tarde! Horário atual: {hora} horas e {minutos} minutos.{espaco}".center(50,"="))
    else:
        print(f"{espaco}Boa noite! Horário atual: {hora} horas e {minutos} minutos.{espaco}".center(50,"="))

def fazercheckout():
    print('Abra o arquivo Database.txt e delete manualmente seu relaxado!')

def listar():
    nomes = []
    with open('DataBase.txt', 'r') as arquivo:
        for name in arquivo:
            name = name.strip()
            nomes.append(name)
            print(name)


import orjson
from blacksheep import Request
from blacksheep.server.controllers import Controller, delete, get, patch, post

from ..checks import search_messages, validate_channel, verify_slowmode
from ..database import ChannelSlowMode, GuildChannelPin, Message, _get_date, to_dict
from ..errors import BadData, Forbidden
from ..randoms import factory, get_bucket
from ..redis_manager import channel_event
from ..utils import NONMESSAGEABLE, AuthHeader, jsonify

class GuildMessages(Controller):
    @get(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/messages/{int:message_id}',
    )
    async def get_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        message_id: int,
        auth: AuthHeader,
    ):
        _, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='read_message_history',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        msg = search_messages(channel_id=channel.id, message_id=message_id)

        return jsonify(to_dict(msg))

    @get(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/messages',
    )
    async def get_guild_channel_messages(
        self,
        guild_id: int,
        channel_id: int,
        auth: AuthHeader,
        request: Request,
    ):
        _, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='read_message_history',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        limit = int(request.query.get('limit', '50'))

        if limit > 10000:
            raise BadData()

        _msgs = search_messages(channel_id=channel.id, limit=limit)
        msgs = []

        for msg in _msgs:
            msgs.append(to_dict(msg))

        return jsonify(msgs)

    @post(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/messages',
    )
    async def create_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        request: Request,
        auth: AuthHeader,
    ):
        # TODO: Attachments/Image Embeds
        member, _, channel, perms = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='send_messages',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        verify_slowmode(member.id, channel.id)

        d: dict = await request.json(orjson.loads)

        if '@everyone' in d['content']:
            mentions_everyone = True if perms.mention_everyone else False
        else:
            mentions_everyone = False

        if d.get('referenced_message_id'):
            referenced_message = search_messages(
                channel_id=channel_id,
                message_id=int(d.pop('referenced_message_id')),
            )

        if referenced_message is None:
            raise BadData()

        data = {
            'id': factory().formulate(),
            'channel_id': channel_id,
            'bucket_id': get_bucket(channel_id),
            'guild_id': guild_id,
            'author': member.user,
            'content': str(d['content']),
            'mentions_everyone': mentions_everyone,
            'referenced_message_id': referenced_message.id,
        }

        msg = Message.create(**data)

        await channel_event(
            'CREATE',
            to_dict(channel),
            to_dict(msg),
            guild_id=guild_id,
            is_message=True,
        )

        slowmode: ChannelSlowMode = ChannelSlowMode.create(
            id=member.id, channel_id=channel_id
        )
        slowmode.ttl(channel.slowmode_timeout)

        return jsonify(to_dict(msg))

    @patch(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/messages/{int:message_id}',
    )
    async def edit_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        message_id: int,
        auth: AuthHeader,
        request: Request,
    ):
        member, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission=None,
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        msg = search_messages(channel_id=channel.id, message_id=message_id)

        if msg is None:
            raise BadData()

        if msg.author.id != member.id:
            raise Forbidden()

        d: dict = await request.json(orjson.loads)

        if d.get('content'):
            msg.content = str(d.pop('content'))

        msg.last_edited = _get_date()

        msg = msg.save()

        await channel_event(
            'EDIT',
            to_dict(channel),
            to_dict(msg),
            guild_id=guild_id,
            is_message=True,
        )

        return jsonify(to_dict(msg))

    @delete(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/messages/{int:message_id}',
    )
    async def delete_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        message_id: int,
        auth: AuthHeader,
    ):
        _, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='manage_messages',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        msg = search_messages(channel_id=channel.id, message_id=message_id)

        if msg is None:
            raise BadData()

        if msg.pinned:
            pin: GuildChannelPin = GuildChannelPin.objects(
                GuildChannelPin.channel_id == channel_id,
                GuildChannelPin.message_id == message_id,
            ).get()
            pin.delete()
            await channel_event(
                'UNPIN',
                to_dict(channel),
                {
                    'guild_id': guild_id,
                    'channel_id': channel_id,
                    'message_id': message_id,
                },
                guild_id=guild_id,
                is_message=True,
            )

        msg.delete()

        r = jsonify([])
        r.status_code = 204

        await channel_event(
            'DELETE',
            to_dict(channel),
            {
                'id': message_id,
                'channel_id': channel_id,
                'guild_id': guild_id,
            },
            guild_id=guild_id,
            is_message=True,
        )

        return r

    @post(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/pins/{int:message_id}',
    )
    async def pin_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        message_id: int,
        auth: AuthHeader,
    ):
        _, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='manage_channel_pins',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        msg = search_messages(channel_id=channel.id, message_id=message_id)

        if msg is None:
            raise BadData()

        msg.pinned = True

        possibly_not_empty = GuildChannelPin.objects(
            GuildChannelPin.channel_id == channel_id,
            GuildChannelPin.message_id == message_id,
        )

        if possibly_not_empty.all() != []:
            raise BadData()

        pin = GuildChannelPin.create(channel_id=channel_id, message_id=message_id)
        msg = msg.save()

        ret = {
            'pinned_data': to_dict(pin),
            'message_pinned': to_dict(msg),
        }

        await channel_event(
            'PIN',
            to_dict(channel),
            ret,
            guild_id=guild_id,
            is_message=True,
        )

        return jsonify(ret)

    @delete(
        '/guilds/{int:guild_id}/channels/{int:channel_id}/pins/{int:message_id}',
    )
    async def unpin_guild_channel_message(
        self,
        guild_id: int,
        channel_id: int,
        message_id: int,
        auth: AuthHeader,
    ):
        _, _, channel, _ = validate_channel(
            token=auth.value,
            guild_id=guild_id,
            channel_id=channel_id,
            permission='manage_channel_pins',
        )

        if channel.type in NONMESSAGEABLE:
            raise BadData()

        msg = search_messages(channel_id=channel.id, message_id=message_id)

        if msg is None or not msg.pinned:
            raise BadData()

        msg.pinned = False
        pin: GuildChannelPin = GuildChannelPin.objects(
            GuildChannelPin.channel_id == channel_id,
            GuildChannelPin.message_id == message_id,
        ).get()
        pin.delete()
        msg.save()

        r = jsonify([])
        r.status_code = 204

        await channel_event(
            'UNPIN',
            to_dict(channel),
            {
                'guild_id': guild_id,
                'channel_id': channel_id,
                'message_id': message_id,
            },
            guild_id=guild_id,
            is_message=True,
        )

        return jsonify(r)


from collections import namedtuple
import random
import math

import torch
import torch.nn as nn
import torch.nn.functional as F

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

class CnnQLearning(nn.Module):
    def __init__(self, h, w):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=5, stride=2)
        self.bn1 = nn.BatchNorm2d(16)
        self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2)
        self.bn2 = nn.BatchNorm2d(32)
        self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2)
        self.bn3 = nn.BatchNorm2d(32)

        def conv2d_output_size(size, kernel_size=5, stride=2):
            return (size - kernel_size) // stride + 1

        def function_call_repeat(f, time, *args):
            if time == 1:
                return f(*args)
            else:
                return f(function_call_repeat(f, time - 1, *args))
        convw = function_call_repeat(conv2d_output_size, 3, w)
        convh = function_call_repeat(conv2d_output_size, 3, h)
        linear_output_size = convh * convw * 32
        self.head = nn.Linear(linear_output_size, 2)

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))
        return self.head(x.view(x.size(0), -1))

class DnnQLearning(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(4, 10)
        self.linear2 = nn.Linear(10, 5)
        self.head = nn.Linear(5, 2)

    def forward(self, x):
        x = F.relu((self.linear1(x)))
        x = F.relu(self.linear2(x))
        return self.head(x)

Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward'))

class ReplayMemory(object):
    def __init__(self, capacity):
        self.capacity = capacity
        self.memory = []
        self.position = 0

    def push(self, *args):
        if len(self.memory) < self.capacity:
            self.memory.append(None)
        self.memory[self.position] = Transition(*args)
        self.position = (self.position + 1) % self.capacity

    def sample(self, batch_size):
        return random.sample(self.memory, batch_size)

    def __len__(self):
        return len(self.memory)

def select_action(policy_net, state, steps_done, eps_start=0.9, eps_end=0.05, eps_decay=0.005):
    sample = random.random()
    eps_threshold = eps_end + (eps_start - eps_end) * math.exp(-1. * steps_done * eps_decay)
    if sample >= eps_threshold:
        with torch.no_grad():
            # t.max(1) will return largest column value of each row.
            # second column on max result is index of where max element was
            # found, so we pick action with the larger expected reward.
            return policy_net(state).max(1)[1].view(1, 1)
    else:
        return torch.tensor([[random.randrange(2)]], dtype=torch.long).to(device)


#!/usr/bin/python

# represents data for a tic tac toe board with functions to modify it, compare boards, and display it

class Board(str):
    # inherits string because this is what the board is represented by:
    # a 9 character string, where each character is a ' ', 'X', or 'O'
    # ' ' for any empty board spaces, 'X' for spaces X played on, and 'O' for spaces O played on

    def __new__(cls, layout='         ', p=0, paths=[]):
        obj = str.__new__(cls, layout)
        # the unique number of layout for this turn
        obj.pattern = p
        # boards for the next turn this one can lead to
        obj.paths = paths[:]
        return obj

    def matches(self, other):
        """
        compares a given layout against all 8 possible rotations of it
        and returns true if any two of them are identical
        """
        mirrored = other.mirror()
        return (self == other or self == other.rotate() or
                self == other.rotate(2) or self == other.rotate(3)
                or self == mirrored or self == mirrored.rotate() or
                self == mirrored.rotate(2) or self == mirrored.rotate(3))

    def rotate(self, rots=1):
        """recursively rotates a layout 90 degrees clockwise by a specified number of times, and returns it"""
        if rots > 1:
            self = self.rotate(rots - 1)
        return Board(self[6] + self[3] + self[0] + self[7] + self[4] + self[1] + self[8] + self[5] + self[2])

    def mirror(self):
        """mirrors a move layout down the middle and returns it"""
        return Board(self[2] + self[1] + self[0] + self[5] + self[4] + self[3] + self[8] + self[7] + self[6])

    def make_board(self, paths=False, showWin=False):
        """makes and returns a full display of a layout"""

        board = "\n"
        for row in range(3):
            for col in range(3):
                # characters for a single row are stored 3 characters apart
                # and columns offset this by 0 to 2 spaces
                toAdd = self[row * 3 + col]

                # if wanted, adds the path instead of a blank
                if paths and toAdd == ' ' and not self.check_win()[0]:
                    toAdd = str(self.paths[row * 3 + col])

                # paths may be 1 to 3 digits, so this makes sure they fit into empty spots perfectly
                if len(toAdd) == 1:
                    board += " %s " % toAdd
                elif len(toAdd) == 2:
                    board += " %s" % toAdd
                else:
                    board += "%s" % toAdd

                # puts dividers between game spaces
                if col != 2:
                    board += "|"
                # end of the row reached
                else:
                    board += "\n"

            if row != 2: board += "-----------\n"

        # adds the pattern, and turn number, for a layout if there is a pattern
        if len(str(self.pattern)) > 0 and self.pattern > 0:
            board += "\nLayout %s-%s" % (self.what_turn(), self.pattern)

        if showWin:
            board += "\n"
            win, winner = self.check_win()
            if win: board += "%s Wins" % winner
            elif ' ' not in self: board += "Tie game"
            else: board += 'No Win'

        return board

    def what_turn(self):
        """checks what turn a layout is from and returns that"""
        turn = 9
        for i in self:
            # 9 spaces = start of game, 8 spaces = turn 1, etc
            if i == ' ':
                turn -= 1
        return turn

    def check_win(self):
        """
        returns true if there is a winning move, and the winning player
        returns false otherwise, and an empty string for the winner
        """

        win = False
        winner = ''

        # winning is only possible from turn 5 and on
        if self.what_turn() >= 5:

            # goes through both possible winning players
            for p in ('X', 'O'):
                 # checks for a diagonal win
                if self[4] == p and (self[0] == self[8] == p or self[2] == self[6] == p):
                    win = True
                else:
                    for i in range(3):
                        # checks for vertical and horizontal wins
                        if (self[i] == self[i+3] == self[i+6] == p or
                            self[i*3] == self[i*3+1] == self[i*3+2] == p):
                            win = True
                if win:
                    winner = p
                    break

        return (win, winner)


# Script Name		: verbose.py
# Author				: Benites Fernandez, Edson
# Created				: 27/02/17
# Last Modified	:
# Version				: 1.0

# Modifications	: 1.1 - some modifications
#							  : 1.2 - some modifications

# Description		: Implement function to set up the verbose
#

import argparse
import logging

def setUpVerbose():
	parser = argparse.ArgumentParser()
	parser.add_argument(
		'-d', '--debug',
		help = "Print lots of debugging statements",
		action = "store_const", dest = "loglevel", const = logging.DEBUG,
		default = logging.WARNING,
		)
	parser.add_argument(
		'-v', '--verbose',
		help = "Be verbose",
		action = "store_const", dest = "loglevel", const = logging.INFO,
		)
	args = parser.parse_args()
	logging.basicConfig(level = args.loglevel)
	return logging


from django.shortcuts import render
from rest_framework import viewsets
from .serializers import StockSerializer
#======================================================
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.edit import DeleteView
#=============================================
from .models import Stock,Stockprice
from brands.models import Brand
from datetime import datetime

import requests
from myapp.utils import current_month_dates
from mysite.settings import ApiBaseurl
# Create your views here.
def stock(request):
    base_url = ApiBaseurl
    sdate = request.GET.get('sdate',current_month_dates()[0].strftime("%Y-%m-%d"))
    edate = request.GET.get('edate',current_month_dates()[1].strftime("%Y-%m-%d"))
    stocks=requests.get(base_url+'stock/',
                        params = {
                        'start':sdate,
                        'end':edate,
                        })
    return render(request,'stock.html',{'stocks':stocks.json()})

class StockViewset(viewsets.ModelViewSet):
    queryset = Stock.objects.all()
    serializer_class = StockSerializer
    lookup_field = 'id'

#==============================================================
#             Django Generic views
#==============================================================

class StockCreate(CreateView):
    model =Stock
    fields = ('__all__')
    success_url ='/stock'

class StocksList(ListView):
    model =Stock
    template_name = 'Stock/stock_list.html'

class StockDetail(DetailView):
    model =Stock

class StockUpdate(UpdateView):
    model =Stock
    fields = ('__all__')
    success_url ='/Stocks/list'

class StockDelete(DeleteView):
    model =Stock

    success_url = '/Stocks/list'

class StockpriceCreate(CreateView):
    model =Stockprice
    fields = ('__all__')

class StockpricesList(ListView):
    model =Stockprice
    template_name = 'Stockprice.html'

class StockpriceDetail(DetailView):
    model =Stockprice

class StockpriceUpdate(UpdateView):
    model =Stockprice
    fields = ('__all__')
    success_url ='/Stockprices/list'

class StockpriceDelete(DeleteView):
    model =Stockprice

    success_url = '/Stockprices/list'
#==============================================================


# encoding: utf-8
# Tizonia Website Tool

import os
import sys
import shutil
import urllib2
from optparse import OptionParser, OptionValueError
from datetime import date

# constants
LANGLIST = (('en', 'English'),
            )
LANGS = [L[0] for L in LANGLIST]
DOCLANGS = 'en'.split()
COMMANDS = ('generate', 'update', 'compile')
CURVER = 'http://tortoisehg.bitbucket.org/curversion.txt'
DESC = '''%prog COMMAND [OPTIONS]

Commands:
  generate: Generate Tizonia website after compiling PO files
  update:   Update PO files from Django templates (xgettext and msgmerge)
  compile:  Compile PO files and generate MO files (msgfmt)'''
FILES = ('index.html',
         'about.html',
         'docs.html',
         'download/index.html',
         'download/install_content.html',
         'download/install.html',
         'download/linux_content.html',
         'download/linux.html',
         )

# command-line parser
parser = OptionParser(usage=DESC)
parser.add_option('-l', '--lang', dest='lang', default='en',
                  help='generate website for LANG', metavar='LANG')
parser.add_option('-c', '--curver', dest='curver', default=CURVER,
                  help='curversion.txt file path')
parser.add_option('--all', dest='all', action='store_true', default=False,
                  help='generate website for all languages')

# check command-line options
opts, args = parser.parse_args(sys.argv)
if len(args) < 2:
    print >> sys.stderr, 'COMMAND is required to run'
    sys.exit(1)

subcmd = args[1]
if subcmd not in COMMANDS:
    print >> sys.stderr, 'Unknown command: %s' % subcmd
    sys.exit(1)

if opts.lang not in LANGS:
    print >> sys.stderr, 'Unsupported language: %s' % opts.lang
    sys.exit(1)

def parse_curver(curver):
    # fetch curversion.txt
    if curver.startswith('http://'):
        try:
            f = urllib2.urlopen(curver, timeout=3)
            lines = f.readlines()
            f.close()
        except urllib2.URLError:
            print >> sys.stderr, 'Failed to fetch curversion.txt, use -c option'
            return None
    else:
        f = open(curver, 'r')
        lines = f.readlines()
        f.close()

    # parse curversion.txt
    dl = {}
    obj = dict(version=lines[0].rstrip('\n'), dl=dl)
    lines = lines[1:]
    for line in lines:
        if line.startswith('dl/'):
            line = line[3:]
        parts = line.rstrip('\n').split(':', 1)
        if len(parts) == 1:
            continue
        dl[parts[0]] = parts[1]

    return obj

verobj = parse_curver(opts.curver)
if verobj is None:
    sys.exit(1)

# determine target languages
langs = opts.all and LANGS or (opts.lang,)

# Django settings
from django.conf import settings
root = os.path.dirname(os.path.realpath(__file__))
root_u = root.replace('\\', '/')
tmpl_u = os.path.join(root, 'templates').replace('\\', '/')
locale_u = os.path.join(root, 'locale').replace('\\', '/')
mids = ('django.middleware.common.CommonMiddleware',)
settings.configure(TEMPLATE_DEBUG=True, MIDDLEWARE_CLASSES=mids,
                   TEMPLATE_DIRS=(tmpl_u,), LOCALE_PATHS=(locale_u,))

def cmd_genenate():
    from django.template.loader import render_to_string
    from django.utils import translation

    # create output root dir
    output_root = os.path.join(root, 'build')
    if not os.path.exists(output_root):
        os.mkdir(output_root)

    def make_docver(ver, lang):
        nums = ver.split('.')
        if len(nums) == 2:
            nums = list(nums) + [0]
        if lang == 'en':
            return '.'.join(nums[0:2])
        else:
            return '%s-%s' % ('.'.join(nums[0:2]), lang)

    def prepare_dir(path):
        dir = os.path.dirname(path)
        if os.path.exists(dir):
            return
        prepare_dir(os.path.dirname(dir))
        os.mkdir(dir)

    # prepare global values for rendering context
    docdict = {}
    for lang in DOCLANGS:
        docdict[lang] = make_docver(verobj['version'], lang)

    # generate website
    for lang in langs:
        # activate target language
        translation.activate(lang)

        # create per-language dir
        output_dir = os.path.join(output_root, lang)
        if os.path.exists(output_dir):
            shutil.rmtree(output_dir)

        # copy static files
        static_root = os.path.join(root, 'static')
        static_en = os.path.join(static_root, 'en')
        shutil.copytree(static_en, output_dir)
        for rootdir, dirs, files in os.walk(os.path.join(static_root, lang)):
            if not files:
                continue
            for file in files:
                fullsrc = os.path.join(rootdir, file)
                relsrc = os.path.relpath(fullsrc, static_en)
                fulldst = os.path.join(output_dir, relsrc)
                shutil.copyfile(fullsrc, fulldst)

        # prepare common values for rendering context
        docdict['ver'] = docdict.has_key(lang) and docdict[lang] \
                                               or docdict['en']
        home = 'http://tizonia.org/' + (lang != 'en' and lang + '/' or '')
        langlist = [l for l in LANGLIST if l[0] != lang]
        langlabel = [l[1] for l in LANGLIST if l[0] == lang][0]
        langdict = dict(code=lang, list=langlist, label=langlabel)

        # generate files from templates
        for file in FILES:
            if file.endswith('.js'):
                file += '.tmpl'

            # render static content
            offset = '../' * (len(file.split('/')) - 1)
            ctx = dict(year=str(date.today().year), doc=docdict,
                       home=home, dir_offset=offset, lang=langdict,
                       dl=verobj['dl'], version=verobj['version'])
            rendered = render_to_string(file, ctx)

            # write out to file
            path = os.path.abspath(os.path.join(output_dir, file))
            prepare_dir(path)
            f = open(path, 'w')
            f.write(rendered.encode('utf-8'))
            f.close()

            orig, ext = os.path.splitext(path)
            if ext == '.tmpl':
                os.rename(path, orig)

def cmd_gettext(cmd):
    from django.core import management
    cmdline = ['django-admin.py', cmd]
    if cmd == 'makemessages':
        cmdline += ['-e', 'html,tmpl']
    cmdline.append('-l')
    for lang in [lang for lang in langs if lang != 'en']:
        management.execute_from_command_line(argv=cmdline + [lang])

# dispatch command
if subcmd == 'generate':
    cmd_gettext('compilemessages')
    cmd_genenate()
elif subcmd == 'update':
    cmd_gettext('makemessages')
elif subcmd == 'compile':
    cmd_gettext('compilemessages')


# -*- coding: utf-8 -*-
from ..exceptions import WitnessDoesNotExistsException
from .blockchainobject import BlockchainObject, BlockchainObjects
from ..witness import Witness as SyncWitness, Witnesses as SyncWitnesses

class Witness(BlockchainObject, SyncWitness):
    """Read data about a witness in the chain

    :param str account_name: Name of the witness
    :param instance blockchain_instance: instance to use when accesing a RPC

    """

    async def __init__(self, *args, **kwargs):
        self.define_classes()
        assert self.type_id or self.type_ids
        assert self.account_class
        await BlockchainObject.__init__(self, *args, **kwargs)

    async def refresh(self):
        if self.test_valid_objectid(self.identifier):
            _, i, _ = self.identifier.split(".")
            if int(i) == 6:
                witness = await self.blockchain.rpc.get_object(self.identifier)
            else:
                witness = await self.blockchain.rpc.get_witness_by_account(
                    self.identifier
                )
        else:
            account = await self.account_class(
                self.identifier, blockchain_instance=self.blockchain
            )
            witness = await self.blockchain.rpc.get_witness_by_account(account["id"])
        if not witness:
            raise WitnessDoesNotExistsException(self.identifier)
        await super(Witness, self).__init__(
            witness, blockchain_instance=self.blockchain
        )

    @property
    async def account(self):
        return await self.account_class(
            self["witness_account"], blockchain_instance=self.blockchain
        )

    @property
    async def weight(self):
        if not self.is_active:
            return 0
        else:
            account = await self.account_class(
                "witness-account", blockchain_instance=self.blockchain
            )
            threshold = account["active"]["weight_threshold"]
            weight = next(
                filter(
                    lambda x: x[0] == self.account["id"],
                    account["active"]["account_auths"],
                )
            )
            return float(weight[1]) / float(threshold)

    @property
    async def is_active(self):
        account = await self.account_class(
            "witness-account", blockchain_instance=self.blockchain
        )
        return self.account["id"] in [x[0] for x in account["active"]["account_auths"]]

class Witnesses(BlockchainObjects, SyncWitnesses):
    """Obtain a list of **active** witnesses and the current schedule

    :param bool only_active: (False) Only return witnesses that are
        actively producing blocks
    :param instance blockchain_instance: instance to use when accesing a RPC
    """

    async def __init__(self, *args, only_active=False, lazy=False, **kwargs):
        self.define_classes()
        assert self.account_class
        assert self.witness_class

        self.lazy = lazy
        self.only_active = only_active
        await super().__init__(*args, **kwargs)

    async def refresh(self, *args, **kwargs):
        self.schedule = await self.blockchain.rpc.get_object("2.12.0").get(
            "current_shuffled_witnesses", []
        )

        witnesses = [
            await self.witness_class(
                x, lazy=self.lazy, blockchain_instance=self.blockchain
            )
            for x in self.schedule
        ]

        if self.only_active:
            account = await self.account_class(
                "witness-account", blockchain_instance=self.blockchain
            )
            filter_by = [x[0] for x in account["active"]["account_auths"]]
            witnesses = list(
                filter(lambda x: x["witness_account"] in filter_by, witnesses)
            )

        self.store(witnesses)

    def __contains__(self, item):
        if self.witness_class.objectid_valid(item):
            id = item
        elif isinstance(item, self.account_class):
            id = item["id"]
        else:
            # Async version does not support querying by name
            raise NotImplementedError("Please use object id or Account class")

        return any([id == x["id"] for x in self]) or any(
            [id == x["witness_account"] for x in self]
        )


# #liczy pole prostokąta
def pole_prostokata(bok1, bok2):
    return  int(bok1) * int(bok2)
bok1 = input("podaj 1 bok prostokata")
bok2 = input("podaj 2 bok prostokąta")
print(f"pole prostokąta wynosi: {pole_prostokata(bok1,bok2)}")

#liczy średnią predkość na podstawie podaego dystansu i czasu. funkcja wykozystana do liczenia
#sredniej predkosci samochodu i roweru

def av_speed(distance, time):
    return int(distance)/int(time)

run_speed = input("podaj czas biegu(w godzinach): ")
run_distance =input("podaj dystans biegacza: ")

bike_time =  input("podaj czas przejazdu kolarza(w godzinach):  ")
bike_distance = input("podaj przejechany dystans: ")

car_time =  input("podaj czas przejazdu samochodem(w godzinach):  ")
car_distance = input("podaj przejechany dystans: ")

print(f"średnia prędkość biegu: {av_speed(run_distance, run_time)} km/h")
print(f"średnia prędkość kolarza: {av_speed(bike_distance, bike_time)} km/h")
print(f"średnia prędkość samochodu: {av_speed(car_distance, car_time)} km/h")

#pyta o wydatki w kazdej kategorii, oblicza procentowy udział każdej z kategorii w całości i wypisuje najbardziej znaczącą kategorię:
#uwzględnia funkcje
def expediture_input():
    categories = {}
    next_category = ''
    while True:
        next_category = input("podaj kategorię wydatów, jeżeli chcesz zakończyć podaj X ")
        if next_category == "X":
            break
        next_expediture = ""
        cat_expeditures_list = []
        while True:
            next_expediture = input(f"podaj kolejny wydatek w kategorii {next_category} by zakończyć podaj X ")
            if next_expediture == "X":
                break
            cat_expeditures_list.append(next_expediture)
        categories[next_category] = cat_expeditures_list
    return categories

def expeditures_sum(categories):
    categories_sum = {}
    for category, expediture in categories.items():
        category_expeditures_sum = 0
        for expediture in categories[category]:
            category_expeditures_sum = category_expeditures_sum + float(expediture)
        categories_sum[category] = category_expeditures_sum
    return categories_sum

def expeditures_percentage(categories_sum):
    all_expeditures_sum = 0
    for expeditures in categories_sum.values():
        all_expeditures_sum = all_expeditures_sum + float(expeditures)
    print(f"suma wydatków:  {all_expeditures_sum}")
    max_valuable_category_exp = 0
    for category in categories_sum:
        print(f"kategoria {category} zajmuje procentowo {(categories_sum[category] / all_expeditures_sum * 100):.2f}")
        if categories_sum[category] > max_valuable_category_exp:
            max_valuable_category_exp = categories_sum[category]
            max_valuable_category_name = category
    print(f"Najwięcej wydajesz na: {max_valuable_category_name}")

categories_with_exp = expediture_input()
categories_with_sum_exp = expeditures_sum(categories_with_exp)
expeditures_percentage(categories_with_sum_exp)


# p933
# 2020.3.18

from queue import PriorityQueue

def dijkstra(adj, start = 0):
    dist = [float('inf')] * (len(adj)+1)
    print(len(adj))
    q = PriorityQueue()
    q.put((0, start))

    while not q.empty():
        here = q.get()
        if dist[here[1]] < here[0]:
            continue

        for there in adj[here[1]]:
            nextDist = here[0] + there[0]
            if dist[there[1]] > nextDist:
                dist[there[1]] = nextDist
                q.put((nextDist, there[1]))
    return dist

def main():
    inputs = """8 12 3 2
1 2 3
1 6 9
2 3 6
3 4 4
3 5 2
4 5 7
6 5 5
8 6 5
6 7 3
8 7 3
7 5 1
2 8 3
2 3 5
4 6"""

    inputs = inputs.split('\n')
    inputs = [list(map(int, line.split())) for line in inputs]
    inputs.reverse()

    v, e, n, m = inputs.pop()
    adj = [[] for _ in range(v+1)] ## adj[v] is virtual node
    for _ in range(e):
        a, b, t = inputs.pop()
        adj[a-1].append((t, b-1))
        adj[b-1].append((t, a-1))
    fires = inputs.pop()
    firestations = inputs.pop()

    ## add edges to firestations from virtual node
    for fs in firestations:
        adj[v].append((0, fs-1))

    print(adj)
    dist = dijkstra(adj, v)
    print(dist)

    res = 0
    for fire in fires:
        res += dist[fire-1]

    print(res)
    # must be 16

main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
import main.utils

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('challenges', '0003_solution'),
    ]

    operations = [
        migrations.CreateModel(
            name='Vote',
            fields=[
                ('id', models.CharField(default=main.utils._gen_id, max_length=16, serialize=False, primary_key=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.AddField(
            model_name='solution',
            name='votes_count',
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name='vote',
            name='solution',
            field=models.ForeignKey(related_name='votes', to='challenges.Solution'),
        ),
        migrations.AddField(
            model_name='vote',
            name='user',
            field=models.OneToOneField(to=settings.AUTH_USER_MODEL),
        ),
    ]


import zipfile
import os
def zip_folder(folderdir,folder2zip,zipname):
    length_of_base = len(folderdir)
    f = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
    for (root, dirs, files) in os.walk(folder2zip):
        for filename in files:
            filename_with_path = os.path.join(root, filename)
            f.write(filename_with_path, filename_with_path[length_of_base:])
    f.close()

folderdir = r'e:/Test'

os.chdir(folderdir)
file_list = os.listdir(folderdir)

for folder in file_list:
    if (os.path.isdir(os.path.join(folderdir,folder))):
        zip_folder(folderdir,os.path.join(folderdir, folder),folder + '.zip')


golfcube = dm.sample_data.golf()

stratcube = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.05)
stratcube.register_section('demo', dm.section.StrikeSection(distance_idx=10))

fig, ax = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(12, 9))
ax = ax.flatten()
for i, var in enumerate(['time', 'eta', 'velocity', 'discharge', 'sandfrac']):
    stratcube.show_section('demo', var, ax=ax[i], label=True,
                           style='shaded', data='stratigraphy')


from os import uname
from app import app, db
from app.models import Chat
from flask import render_template, request, redirect
from datetime import datetime

@app.route('/', methods=['GET'])
def index():
    ''' creates a new database file if it does not exist '''
    db.create_all()
    db.session.commit()
    return render_template('index.html', title='Chat APP')

@app.route('/<room>', methods=['GET'])
def room(room):
    return render_template('index.html', title='Chat APP')

@app.route('/api/chat/<room>', methods=['GET', 'POST'])
def room_manage(room):
    if request.method == 'GET':
        res = ''
        if not Chat.query.filter_by(room=room).all():
            return f'No Messages\n\n{uname()}'

        for row in Chat.query.filter_by(room=room).all():
            res += f'[{row.created_at.strftime("%Y-%m-%d %H:%M:%S")}] {row.username}: {row.msg}\n'
        return f'{res}\n{uname()}'

    elif request.method == 'POST':
        new_msg = Chat(
            username=request.form['username'],
            msg=request.form['msg'],
            room=room
        )
        db.session.add(new_msg)
        try:
            db.session.commit()
        except:
            db.session.rollback()

    return render_template('index.html')


#!/usr/bin/env python
"""
usage: git-branchstat [-v|-h]

options:
    -v     Show version
    -h     Show this message
"""
import os
import subprocess
import sys
from argparse import ArgumentParser
from pathlib import Path

VERSION = "0.2.0"

def main():
    """Get filtered short status of current directory"""
    args = ["git", "status", "-s", "-b"]
    finished_proc = subprocess.run(args, capture_output=True)
    if finished_proc.returncode == 128:
        print(f"{os.getcwd()}: Not a git repo")
        return
    status = finished_proc.stdout
    if b"ahead" in status or b"behind" in status or status.count(b"\n") > 1:
        p = Path(".").resolve()
        print("/".join(p.parts[-2:]))
        print(status.decode())

if __name__ == "__main__":
    p = ArgumentParser(prog="git-sstat")
    p.add_argument("-v", "--version", action="store_true")
    args = p.parse_args()

    if args.version:
        print(Path(__file__).stem, VERSION)
    else:
        sys.exit(main())


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

import subprocess
from parhex import ParHex
from os import listdir

print('---------------------------------------------------------')
print('')
print('       ** S T A R T   P R O G R A M M I N G **')
print('')
print('---------------------------------------------------------')

card = ['Emperor', 'Mono', 'MonoFTC', 'Vader', 'VaderE2E']

print('\n Select the electronic card: ')

numb = 0
for ct in card:
    print(str(numb)+ " : " + ct)
    numb+=1

c = input('\n')
c = int(c)

#c = 1

fList = listdir()
fwExt = ['.hex', '.a90']
fwList = [f for f in fList if any(fw in f for fw in fwExt)]
#print(fwList)

cfList = listdir('firmwares')
cfwExt = ['.hex', '.a90']
cfwList = [cf for cf in cfList if any(cfw in cf for cfw in cfwExt)]

print("\n Select the core firmware file: ")

numb=0
for fw in cfwList:
    print(str(numb)+" : "+fw)
    numb+=1

a = input("\n")

cfw = 'firmwares\\'+cfwList[int(a)]

if card[c] is 'Mono':

    parfList = listdir('parameters')

    parExt = ['.par', '.a90']
    parList = [f for f in parfList if any(fw in f for fw in parExt)]

    print("\n Select the parameter file: ")

    numb = 0
    for p in parList:
        print(str(numb) + " : " + p)
        numb += 1

    b = input("\n")
    p = 'parameters\\'+parList[int(b)]

#print('\n' + cfwList[int(a)] + ' and ' + parList[int(b)] + " are being installed.")

if card[c] is 'Emperor':
    print('\n' + cfwList[int(a)] + " is being installed.")
    calib = subprocess.Popen("atprogram_emperor_osc.bat", shell=False)
    calib.wait()
    #subprocess.call(['C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\atbackend\\atprogram.exe', '-t', 'atmelice', 'atmega644pa', '-i', 'ISP', '-cl', '250khz', '-v', 'chiperase'])
    fh = ParHex(cfw, True, None, "oschex.hex")
    fh.write_hex_file("EmperorCalibrated.hex")
    prog = subprocess.Popen("atprogram_emperor_prog.bat", shell=False)
    prog.wait()
    #subprocess.call(['rm', 'EmperorCalibrated.hex'])
    print('\n' + cfwList[int(a)] + " was installed.")
elif card[c] is 'MonoFTC':
    print('\n' + cfwList[int(a)] + " is being installed.")
    fh = ParHex(cfw, False, None, None)
    fh.write_hex_file("MonoFTC.hex")
    #fh.merge(ph, overlap='replace')
    #fh.write_hex_file("Mono.hex")
    prog = subprocess.Popen("atprogram_monoftc.bat", shell=False)
    prog.wait()
    #subprocess.call(['rm', 'MonoPar.hex'])
    #subprocess.call(['rm', 'MonoCore.hex'])
    print('\n' + cfwList[int(a)] + " was installed.")
elif card[c] is 'Mono':
    print('\n' + cfwList[int(a)] + ' and ' + parList[int(b)] + " are being installed.")
    fh = ParHex(cfw, False, None, None)
    fh.write_hex_file("MonoCore.hex")
    ph = ParHex(p, False, None, None)
    ph.write_hex_file("MonoPar.hex")
    #fh.merge(ph, overlap='replace')
    #fh.write_hex_file("Mono.hex")
    prog = subprocess.Popen("atprogram_mono.bat", shell=False)
    prog.wait()
    #subprocess.call(['rm', 'MonoPar.hex'])
    #subprocess.call(['rm', 'MonoCore.hex'])
    print('\n' + cfwList[int(a)] + ' and ' + parList[int(b)] + " were installed.")
elif card[c] is 'Vader':
    print('\n' + cfwList[int(a)] + " is being installed.")
    calib = subprocess.Popen("atprogram_vader_osc.bat", shell=False)
    calib.wait()
    #subprocess.call(['C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\atbackend\\atprogram.exe', '-t', 'atmelice', 'atmega644pa', '-i', 'ISP', '-cl', '250khz', '-v', 'chiperase'])
    fh = ParHex(cfw, True, None, "oschex.hex")
    fh.write_hex_file("VaderCalibrated.hex")
    prog = subprocess.Popen("atprogram_vader_prog.bat", shell=False)
    prog.wait()
    #subprocess.call(['rm', 'VaderCalibrated.hex'])
elif card[c] is 'VaderE2E':
    stock = input("\n Enter the 10-digit stock number\n\n")
    brand = input("\n Select the brand\n1 : Arcelik\n2 : Grundig\n3 : Beko\n\n")
    initLang = input("\n Select the initial language\n0 : Turkish\n1 : English\n2 : German\n3 : French\n\n")
    print('\n' + cfwList[int(a)] + " is being installed.")
    calib = subprocess.Popen("atprogram_vader_osc.bat", shell=False)
    calib.wait()
    # subprocess.call(['C:\\Program Files (x86)\\Atmel\\Studio\\7.0\\atbackend\\atprogram.exe', '-t', 'atmelice', 'atmega644pa', '-i', 'ISP', '-cl', '250khz', '-v', 'chiperase'])
    fh = ParHex(cfw, True, None, "oschex.hex")

    fh.parE2E(stock, brand, initLang)
    fh.write_hex_file("VaderCalibrated.hex")
    print("Written parameters are\nStock number: "+stock+"\nBrand: "+brand+"\nInitial Language: "+initLang+"\n")
    prog = subprocess.Popen("atprogram_vader_prog.bat", shell=False)
    prog.wait()
    # subprocess.call(['rm', 'VaderCalibrated.hex'])
else:
    raise ValueError("Card type is not initialixed")

#calibrationValueFile = "oschex.hex"

#with open(calibrationValueFile) as calibValHex:
#    calibrationValue = calibValHex.read()

#print('calibrationValue = ' + calibrationValue)

#temporaryFirmware = "EmperorDeneme.hex"  # file should be in x folder

# with open(temporaryFirmware, 'r+b') as firmwareFile:
#    # """ Hex File Read Operation """
#    firmwareFile.read()  # hex file to memory
#    firmwareFile.seek(int(firmwareFile.tell()) - 27)  # move to file position :01FFFE00EA18
#    firmwareFile.write(':01FFFE00'+calibrationValue+'00')
#    #firmwareFile.write(':AAAAAAAA' + calibrationValue + '00')

# with open(temporaryFirmware, 'r+b') as firmwareFile:
#    firmwareFile.read()  # hex file to memory
#    firmwareFile.seek(int(firmwareFile.tell()) - 26)  # move to file position 01FFFE00EA18
#    calibrationLine = firmwareFile.readline(12)  # read the line with calibration byte
#    print('calibrationLine = ' + calibrationLine)
#    decodedCalibrationLine = calibrationLine.decode("hex")  # decode string to hex string
#    #print('decodedCalibrationLine = ' + decodedCalibrationLine)
#    integerChecksum = 0  # initial checksum value (integer)
#    for i in range(0, len(decodedCalibrationLine) - 1):
#        # """ summation loop of decoded string of line """
#        integerChecksum += int(decodedCalibrationLine[i].encode("hex"), 16)
#        #print(decodedCalibrationLine[i])
#    print('summation = ' + str(integerChecksum))
#    hexChecksum = hex(256 - integerChecksum + (integerChecksum / 256) * 256).split('x')[1]
#    print('hexadecimal checksum value for intelhex = ' + hexChecksum)
#    firmwareFile.seek(int(firmwareFile.tell()) - 2)  # move to file position 18
#    firmwareFile.write(hexChecksum)

#if card[c] is 'Emperor':
    #prog = subprocess.Popen("atprogram_emperor_prog.bat", shell=False)
    #prog.wait()
#elif card[c] is 'Mono':
    #prog = subprocess.Popen("atprogram_mono.bat", shell=False)
    #prog.wait()
#else:
    #raise ValueError("Card type is not initialixed")

#print('\n' + cfwList[int(a)] + ' and ' + parList[int(b)] + " were installed.")

print('---------------------------------------------------------')
print('')
print('       ** PROGRAMMING COMPLETED **')
print('')
print('---------------------------------------------------------')


#This program takes a string, and tests if it contains a single repeating substring, eg. "AAbAAbAAb" returns true, and "AAbSdsaji" returns false

def findfactors(num):
    x=[]
    for i in range(1,num):
        if int(num/i) == num/i:
            x.append(i)
    return(x)

def repeated(text): #The main function of the program
    istrue=False
    for stringpart in findfactors(len(text)): #Loops through each possible repeated substring
        testedrepeat=text[0:stringpart]
        timestorepeat=int(len(text)/len(testedrepeat))
        test=""
        for i in range(timestorepeat):
            test=test+testedrepeat
        if test==text:
            istrue=True
    return(istrue)

print(repeated(input("Write a string, and this program will return True if it contains a singular repeating substring")))


import itertools

def primes():
    prime = 2
    while True:
        for i in range(2, prime - 1):
            if prime % i == 0:
                break
        else:
            yield prime
        prime += 1

print(list(itertools.takewhile(lambda x: x <= 4, primes())))