import cards
import games

class BJ_Card(cards.Card):

    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):

    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit))

class BJ_Hand(cards.Hand):

    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):

        for card in self.cards:
            if not card.value:
                return None

        t = 0
        for card in self.cards:
            t += card.value

        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True
        if contains_ace and t <= 11:
            t += 10
        return t

    def is_busted(self):
        return self.total > 21

class BJ_Player(BJ_Hand):

    def is_hitting(self):
        response = games.ask_yes_no(
            '\n' + self.name + " , do you want to hit? (Y/N): ")
        return response == 'y'

    def bust(self):
        print(self.name, ' busts!')
        self.lose()

    def lose(self):
        print(self.name, ' loses.')

    def win(self):
        print(self.name, ' wins.')

    def push(self):
        print(self.name, ' pushes!')

class BJ_Dealer(BJ_Hand):

    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, ' busts.')

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()

class BJ_Game(object):

    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer('Dealer')

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)

        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])

            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        self.deck.deal(self.players + [self.dealer], per_hand=2)
        self.dealer.flip_first_card()
        for player in self.players:
            print(player)
        print(self.dealer)

        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()

        if not self.still_playing:
            print(self.dealer)

        else:
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():

                for player in self.still_playing:
                    player.win()
            else:
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

        for player in self.players:
            player.clear()
        self.dealer.clear()

def main():

    print('\t\tTry Playing the BlackJack Game!\n')

    names = []

    number = games.ask_number('How many players? (1-7): ', low=1, high=8)
    for i in range(number):
        name = input('Enter player name: ')
        names.append(name)

        print()

        game = BJ_Game(names)

        again = None
        while again != 'n':
            game.play()
            again = games.ask_yes_no('\nDo you want to play again? ')

main()
print('\nPress the Enter key to exit.')


SEED = 1988

DATATYPE_DICT = {
    'count'     : 'uint32',
    'nunique'   : 'uint32',
    'cumcount'  : 'uint32',
    'var'       : 'float32',
    'std'       : 'float32',
    'confRate'  : 'float32',
    'nextclick' : 'int64',
    'mean'      : 'float32'
}

NAMEMAP_DICT = {
    'item_id'   : 'iid',
    'user_id'   : 'uid',
    'region'    : 'reg',
    'city'      : 'cty',
    'parent_category_name' : 'pcn',
    'category_name' :   'cn',
    'param_1'   : 'p1',
    'param_2'   : 'p2',
    'param_3'   : 'p3',
    'title'     : 'tit',
    'description'   : 'des',
    'price'     : 'pr',
    'item_seq_number'   : 'isn',
    'activation_date'   : 'ad',
    'user_type' : 'uty',
    'image'     : 'img',
    'image_top_1'   : 'img1',
    'date_from' : 'dfr',
    'date_to'   : 'dto',
    'deal_probability'  : 'dp'
}

SORT_ODER_DICT = {
    'item_id'   : 0,
    'user_id'   : 1,
    'region'    : 2,
    'city'      : 3,
    'parent_category_name' : 4,
    'category_name' :   5,
    'param_1'   : 6,
    'param_2'   : 7,
    'param_3'   : 8,
    'title'     : 9,
    'description'   : 10,
    'price'     : 11,
    'item_seq_number'   : 12,
    'activation_date'   : 13,
    'user_type' : 14,
    'image'     : 15,
    'image_top_1'   : 16,
    'date_from' : 17,
    'date_to'   : 18,
    'deal_probability'  : 19,
}

DATATYPE_DICT = {
    'count'     : 'uint32',
    'nunique'   : 'uint32',
    'cumcount'  : 'uint32',
    'var'       : 'float32',
    'std'       : 'float32',
    'confRate'  : 'uint32',
    'nextclick' : 'int',
    'mean'      : 'float32'
}

DATATYPE_LIST = {
    'item_id'           : 'str',
    'user_id'           : 'str',
    'region'            : 'str',
    'city'              : 'str',
    'parent_category_name' : 'str',
    'category_name'     :   'str',
    'param_1'           : 'str',
    'param_2'           : 'str',
    'param_3'           : 'str',
    'title'             : 'str',
    'description'       : 'str',
    # 'price'             : 'float',
    'item_seq_number'   : 'int',
    'activation_date'   : 'str',
    'user_type'         : 'str',
    'image'             : 'str',
    'image_top_1'       : 'str',
    'date_from'         : 'str',
    'date_to'           : 'str',
    'deal_probability'  : 'float'
}

# TRANSLATE_LIST = {
#     'parent_category_name' : 'parent_category_name_en',
#     'category_name'     :   'category_name_en',
#     'param_1'           : 'param_1_en',
#     'param_2'           : 'param_2_en',
#     'param_3'           : 'param_3_en',
#     'title'             : 'title_en',
#     'description'       : 'description_en',
# }

TRANSLATE_LIST = {
    'param_1'           : 'param_1_en',
    'param_2'           : 'param_2_en',
    'param_3'           : 'param_3_en',
    'title'             : 'title_en',
    'description'       : 'description_en',
}


from starlette.endpoints import HTTPEndpoint
from starlette.responses import UJSONResponse

from api.utils import is_admin
from db.conn import get_conn
from db.replica import Replica
from db.replica_files import ReplicaFiles

class ReplicasHandlers(HTTPEndpoint):
    async def post(self, request):
        is_admin(request)
        data = await request.json()

        async with get_conn()as conn:
            async with conn.transaction():
                replica = Replica(conn)
                result = await replica.add(data['type'], data)

                master = await replica.master()
                if not master:
                    master_id = result
                    await replica.set_master(result)
                else:
                    master_id = master['id']

                await ReplicaFiles(conn).add_replica(result, master_id)

        return UJSONResponse({'id': result})

    async def get(self, request):
        is_admin(request)
        async with get_conn() as conn:
            replicas = await Replica(conn).get_all()

        return UJSONResponse({'data': replicas})

class ReplicaHandlers(HTTPEndpoint):
    async def post(self, request):
        is_admin(request)
        data = await request.json()
        replica_id = int(request.path_params['id'])

        async with get_conn() as conn:
            if 'master' in data:
                await Replica(conn).set_master(replica_id)
            if 'delay' in data:
                await Replica(conn).update_delay(replica_id, data['delay'])

        return UJSONResponse({})

    async def delete(self, request):
        is_admin(request)
        replica_id = int(request.path_params['id'])

        async with get_conn() as conn:
            await Replica(conn).delete(replica_id)

        return UJSONResponse({})


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

# In[1]:

##############################################
# Hardware
#    - Windows 11
#    - NI USB-6008
#    Erst NI-DAQmx 19.5 installiert
#          (aktuelle Version 2023 Q2 zeigt die Karte nicht an)
#          (Die Unterstützung für Net Framework und C++ nicht installieren wenn kein Compiler auf dem Rechner)
#    Dann nidaqmax installieren: "pip install nidaqmx" in Anaconda Prompt

import time as t
import numpy as np
import nidaqmx
from nidaqmx.constants import AcquisitionType
import pprint

fSampling = 10000 #Hz
nSamples = 1000 #samples
pp = pprint.PrettyPrinter(indent=4)
dtMax = 1 #sec

###############################################
# DAQ

data = []
t_insgesamt = 0

# config
with nidaqmx.Task() as task:
    t_vorher = t.time()
    task.ai_channels.add_ai_voltage_chan("Dev1/ai0")
    task.timing.cfg_samp_clk_timing(fSampling, sample_mode=AcquisitionType.CONTINUOUS)

    t_nachher = t.time()
    while t_insgesamt < dtMax:
        value = task.read(number_of_samples_per_channel=nSamples)
        #t.sleep(1)
        data.extend(value)
        t_nachher = t.time()
        dt_buffer = t_nachher-t_vorher
        t_insgesamt += dt_buffer
        t_vorher = t_nachher
        #Verzögerungen haben keinen Einfluss auf die Messung! Super, hier der Beweis:
        #print(dt_buffer)
        #pp.pprint(data)
###############################################
# output to file

# In[2]:

print("Gesamte Messzeit [s]: " + str(t_insgesamt))
print("Anzahl aufgenommener Werte: " + str(len(data)))
print("Abtastfrequenz [Hz]: " + str(len(data) / t_insgesamt))

# In[3]:

import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] = 300
plt.rcParams['savefig.dpi'] = 300

fig = plt.figure()
plt.plot(data)
plt.tight_layout()
plt.xlabel('Zeit [s]')
plt.ylabel('Spannung [V]')
plt.show()
fig.savefig('..\output_bilder\output_voltage.png', dpi=fig.dpi)

# In[4]:

f = open("..\output_csv\output_voltage.txt", "w")
f.write("t,U")
for i in range(len(data)):
    f.write(str(i/len(data)*t_insgesamt) + ',' + str(data[i]) + '\n')
f.close()

# In[ ]:


# before use run in command shell:
# pip install pipenv
# pipenv install requests
# pipenv install BeautifulSoup
# pipenv install lxml
# pip install BeautifulSoup
# pip install beautifulsoup4
# pip install lxml

import requests
import re
from bs4 import BeautifulSoup
import json

# r = requests.get('http://immunet.cn/hmmcas') # this is optional
# url = "http://immunet.cn/hmmcas/index.html"

testgenome = open('NC_016025.faa', 'r').read()
# print(testgenome)
payload = {'sequence': testgenome,
			'submit': 'Run HMMCAS'}

url = "http://immunet.cn/hmmcas/upload2.php"

print("request to "+ url)
headers = {'Host': 'immunet.cn',
'Connection': 'keep-alive',
# 'Content-Length': '400435',
'Cache-Control': 'max-age=0',
'Origin': 'http://immunet.cn',
'Upgrade-Insecure-Requests': '1',
'Content-Type': 'multipart/form-data',
'Save-Data': 'on',
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Referer': 'http://immunet.cn/hmmcas/index.html',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'en-US,en;q=0.8,ru;q=0.6'
}
r = requests.post(url, data=payload, headers=headers)
# print(r.request.body)
print(r.request.headers)
################# alernate

# files = {'uploadfile': open('NC_016025.faa', 'rb')}
# r = requests.post(url, files=files)

#################
#print(r.text)
text_file = open("Output1.html", "w")
text_file.write(r.text)
text_file.close()
#print(r.status_code)

matches = re.findall("(tables\/ToSlide\d+\.json)", r.text)
if len(matches):
	print("found " + matches[0])
	url2 = "http://immunet.cn/hmmcas/" + matches[0]+ "?limit=10&offset=0&sort=name&order=desc"
	# http://immunet.cn/hmmcas/tables/ToSlide225044.json?limit=10&offset=0&sort=name&order=desc
r = requests.get(url2)

text_file = open("Output1j.html", "w")
text_file.write(r.json())
text_file.close()

# button for:
#url2 = "http://i.uestc.edu.cn/hmmcas/operon.php?qsf=ToSlide175938&tb=Table175938&sp=3"
#url2 = "http://i.uestc.edu.cn/hmmcas/operon.php?qsf=ToSlide031405&tb=Table031405&sp=3"
# Search links on buttons:
matches = re.findall("(http\:\/\/i\.uestc\.edu\.cn\/hmmcas\/operon\.php\?qsf=ToSlide.\d+\&tb=Table\d+\&sp=3)", r.text)
if len(matches):
	print("found " + matches[0])

	url2 = matches[0]

	r = requests.get(url2)

from bs4 import BeautifulSoup

print(r.text)

text_file = open("Output2.html", "w")
text_file.write(r.text)
text_file.close()

soup = BeautifulSoup(r.text, "lxml")

for row in soup.findAll('table')[0].tbody.findAll('tr'):
    first_column = row.findAll('th')[0].contents
    third_column = row.findAll('td')[2].contents
    print (first_column, third_column)

# from lxml import etree
# parser = etree.HTMLParser()
# tree = etree.fromstring(table, parser)
# results = tree.xpath('//tr/td[position()=2]')

# print ('Column 2\n========')
# for r in results:
#     print (r.text)


from GQA.functions.peaks import Peaks
from GQA.functions.rastrigin import Rastrigin
from GQA.functions.eggholder import Eggholder
from GQA.quantum.gqa_function import GQA_function
from GQA.utils.plotutils import plotList,average_evals
from tqdm import tqdm

# r = Rastrigin(-5.12,5.12,-5.12,5.12)
# r.plot_()

# e = Eggholder(-512,512,-512,512)
# e.plot_()

# p = Peaks(-3,3,-3,3)
# p.plot_()

l = []
params = []

runs = 50
generations = 200
num = 64
num_pop = 16
deltas = [0.0025,0.025,0.25,0.5]
seeds = range(runs)
verbose = 0
function = "rastrigin" #  | "eggholder" | "rastrigin" | "peaks"
decay = 0
mutation_rate = 0.01
crossover_probability = 0.5
avg_evals = {}
bst_evals = {}

for i in tqdm(deltas):
    evals = []
    avg_evals[i] = 0
    bst_evals[i] = 0

    tmp = []
    for s in tqdm(seeds):
        gqa = GQA_function(generations,num,num_pop,i,s,verbose,function,decay,mutation_rate,crossover_probability)
        gqa.run()
        evals.append(gqa.best_evaluations)
        tmp.append(gqa.best_fitness)

    l.append(average_evals(evals))
    avg_evals[i] = sum(tmp)/len(tmp)
    bst_evals[i] = min(tmp)
    params.append(i)

plotList(l,params,generations)
print(avg_evals)
print(bst_evals)


import praw
import pause

posts = []
url_set = set()
message_user = 'VirtualLeak'
reddit = praw.Reddit('user')
subreddit = reddit.subreddit('friends')

# Output post data in markdown table format
def output():
    format_title = '|'.join(['title', 'author', 'subreddit', 'url', '# of comments\n'])
    format_columns = '|'.join(['-', '-', '-', '-', '-\n'])
    for i in range(len(posts)):
        posts[i] = '|'.join([posts[i].title, str(posts[i].author), str(posts[i].subreddit),
                             posts[i].shortlink, str(posts[i].num_comments)])
    format_table = '\n'.join(posts)
    print(format_title + format_columns + format_table)
    reddit.redditor(message_user).message('New Posts', format_title + format_columns + format_table)
    posts.clear()

for post in subreddit.stream.submissions(pause_after=0):  # Optional parameters: pause_after=0, skip_existing=True
    # Avoids posts that link to the same url in multiple subreddits
    if post is not None and post.url not in url_set:
        url_set.add(post.url)
        posts.insert(0, post)
    # If there are new posts, send message
    if post is None and len(posts) > 0:
        output()
    # If there aren't any new posts, pause for 24 hours
    if len(posts) == 0:
        pause.hours(24)


import sys
from rdkit import Chem
from rdkit.Chem import AllChem
import glob
import shutil
import os
import multiprocessing as mp

nprocs = 4
except_dir_path = os.path.abspath(os.path.dirname(__file__)) + "\except_mol"

def optimize(mol_file):

	try:
		m = Chem.MolFromMolFile(mol_file)
		m = Chem.AddHs(m)
		AllChem.EmbedMolecule(m)
	except:
		shutil.move(mol_file, except_dir_path)
		return

	try:
		AllChem.UFFOptimizeMolecule(m)
	except ValueError:
		print("Bad Conformer Id")
		print(mol_file)
		shutil.move(mol_file, except_dir_path)

#	m = Chem.RemoveHs(m)
	w = Chem.SDWriter(mol_file)

	w.write(m)
	print(str(mol_file))

	return

if __name__ == "__main__":
	#dir_path = os.path.abspath(os.path.dirname(__file__)) + "\mol_datas"
	mol_files = glob.glob("*.sdf")
	procs = mp.Pool(nprocs)
	procs.map(optimize, mol_files)


import matplotlib.pyplot as plt
import cv2
import numpy as np
from os.path import join, basename
from collections import deque
from utils import grayscale, canny, gaussian_blur, hough_lines, get_slope, get_bias, draw_lines, weighted_img

# region of interest
def region_of_interest(image):

    height = image.shape[0]
    width = image.shape[1]
    vertices = np.array( [[
                [3*width/4, 3*height/5],
                [width/4, 3*height/5],
                [40, height],
                [width - 40, height]
            ]], dtype=np.int32 )

    #defining a blank mask to start with
    mask = np.zeros_like(image)

    # #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(image.shape) > 2:
        channel_count = image.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count # (255, 255, 255)
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(image, mask)
    return masked_image

# compute candidate lines
# and return left and right line coordinates
def compute_candidates(canditates_lines, img_shape):
    global left_lane, right_line
    # separate candidate lines according to their slope
    pos_lines = [l for l in canditates_lines if l["slope"] > 0]
    neg_lines = [l for l in canditates_lines if l["slope"] < 0]

    # interpolate biases and slopes to compute equation of line that approximates left lane
    # median is employed to filter outliers
    neg_bias = np.median([l["bias"] for l in neg_lines]).astype(int)
    neg_slope = np.median([l["slope"] for l in neg_lines])
    x1, y1 = 0, neg_bias
    x2, y2 = -np.int32(np.round(neg_bias / neg_slope)), 0
    left_lane = np.array([x1, y1, x2, y2])

    # interpolate biases and slopes to compute equation of line that approximates right lane
    # median is employed to filter outliers
    pos_bias = np.median([l["bias"] for l in pos_lines]).astype(int)
    pos_slope = np.median([l["slope"] for l in pos_lines])
    x1, y1 = 0, pos_bias
    x2, y2 = np.int32(np.round((img_shape[0] - pos_bias) / pos_slope)), img_shape[0]
    right_lane = np.array([x1, y1, x2, y2])

    return [left_lane, right_lane]

def get_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
    # convert to grayscale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # perform gaussian blur
    blur = gaussian_blur(img_gray, kernel_size=17)

    # perform edge detection
    canny_edges = canny(blur, low_threshold=50, high_threshold=70)

    detected_lines = hough_lines(img=canny_edges,
                                 rho=rho,
                                 theta=theta,
                                 threshold=threshold,
                                 min_line_len=min_line_len,
                                 max_line_gap=max_line_gap)

    candidate_lines = []
    for line in detected_lines:
        for x1, y1, x2, y2 in line:
            slope = get_slope(x1, y1, x2, y2)
            if 0.5 <= np.abs(slope) <= 2:
                candidate_lines.append({"slope": slope,
                                        "bias": get_bias(slope, x1, y1)})

    lane_lines = compute_candidates(candidate_lines, img_gray.shape)

    return lane_lines

def last_lines_averages(lane_lines):
    avg_lt = np.zeros((len(lane_lines), 4))
    avg_lr = np.zeros((len(lane_lines), 4))

    for i in range(0, len(lane_lines)):
        # left line
        x1, y1, x2, y2 = lane_lines[i][0]
        avg_lt[i] += np.array([x1, y1, x2, y2])
        # right line
        x1, y1, x2, y2 = lane_lines[i][1]
        avg_lr[i] += np.array([x1, y1, x2, y2])

    return [np.mean(avg_lt, axis=0), np.mean(avg_lr, axis=0)]

def progress(frames):
    detected_lines = []

    # last 10 frames
    for i in range(0, len(frames)):
        # detect lines
        left_right_lines = get_lines(img=frames[i],
                                    rho=2,
                                    theta=np.pi/180,
                                    threshold=1,
                                    min_line_len=15,
                                    max_line_gap=5)

        detected_lines.append(left_right_lines)

    # prepare empty mask on which lines are drawn
    line_img = np.zeros((frames[0].shape[0], frames[0].shape[1], 3), dtype=np.uint8)

    # last 10 frames line averages
    detected_lines = last_lines_averages(detected_lines)

    # draw lines
    for lane in detected_lines:
        draw_lines(line_img, lane)

    # region of interest
    masked_img = region_of_interest(line_img)

    # img_color = frames[-1] if is_videoclip else frames[0]
    result = weighted_img(masked_img, frames[-1])
    return result


# -*- coding: utf-8 -*-
from eteamin.tests import TestController

class TestPost(TestController):

    def test_tag(self):
        """Testing Posing Tag"""
        payload = {
            'title': 'this is a title',
        }
        post_resp = self.app.post_json('/api/tags', params=payload).json

        get_resp = self.app.get('/api/tags/{}'.format(post_resp['tag'].get('uid'))).json

        assert payload.get('title') == get_resp['tag'].get('title')

        payload = {
            'title': None
        }
        self.app.post_json('/api/tags/', payload, status=400)

        payload = {}
        self.app.post_json('/api/tags', payload, status=400)


# %%

import pandas as pd
import os

# %%

files = [f for f in os.listdir("results/")]

# %%

files

# %%

n_dict = {}
for data_t in ["u", "w", "s"]:
    for ep in [100, 250, 500]:
        n_dict[data_t + str(ep)] = []

# %%

for f in files:
    params = f.split("-")
    n_dict[params[0][0] + str(params[1])].append(f)

# %%

def get_penalty(params):
    if "PBIL" in params:
        return params[5]
    else:
        return ""

def get_lr(params):
    if "PBIL" in params:
        return params[-1]
    else:
        return ""

def get_best(results):
    if results.empty:
        return 0
    else:
        return results.head(1).iloc[0, 1]

def get_best_w(results):
    if results.empty:
        return 0
    else:
        return results.head(1).iloc[0, 0]

def get_mean(results):
    if results.empty:
        return 0
    else:
        return round(results["profit"].mean(), 2)

def get_std(results):
    if results.empty:
        return 0
    else:
        return round(results["profit"].std(), 2)

def get_time(df_):
    if df_.empty:
        return 0
    else:
        return round(df_["time"].mean(), 2)

i = 1
df_data = []
for key_ in n_dict.keys():
    df_data.append([])
    for f in n_dict[key_]:
        in_f = pd.read_csv("results/" + f)
        valid_res = in_f[in_f["weight"] <= int(params[2])].sort_values("profit",
                                                                       ascending=False)
        params = f.split("-")
        i += 1
        tmp_dict = {"algorithm": params[4],
                    "penalty": get_penalty(params),
                    "lr": get_lr(params),
                    "best": get_best(valid_res),
                    "mean": get_mean(valid_res),
                    "time": get_time(in_f),
                    "zzzz": get_best_w(valid_res),
                    "zzzzz": get_std(valid_res),
                    "zzzzzzzzz": valid_res.shape[0] / int(params[3])}
        df_data[-1].append(tmp_dict)

# %%

for name, data_lst in zip(n_dict.keys(), df_data):
    tmp_df = pd.DataFrame(data_lst)
    tmp_df = tmp_df.sort_values(by=["algorithm", "penalty", "lr"])
    tmp_df.to_csv(name + ".csv")


# Modify the previous program such that only multiples of three or five
#  are considered in the sum, e.g. 3, 5, 6, 9, 10, 12, 15 for n=17
a = 1
value = 0
while(a == 1):
    value = input("What do you want to count to?")
    try:
        my_int = int(value)
        print(my_int)
        a = 0
    except:
        ValueError
i = 1
my_sum = 0
for i in range(1, int(value)+1):
    if i%3 == 0:
        print(i, ' ')
        my_sum += i
    elif i%5 == 0:
        print(i, ' ')
        my_sum += i

if(int(value) <= 0):
    print("That is a negative number dummy")
print(my_sum)


import sys

x = [2,3,5,7,11,13,17,19,23,29,31,37]

lst = []
for i in sys.argv[1]:
    lst.append(i)

def recursion(a):
    prime = []
    count = 0
    if a % 2 == 0:
        prime.append(2)
        a == a//2
        return recursion(a)
    return prime
for i in range(len(lst)):
    print(recursion(lst[i]))


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

"""
Package: iads
File: utils.py
Année: LU3IN026 - semestre 2 - 2021-2022, Sorbonne Université
"""

# Fonctions utiles pour les TDTME de LU3IN026
# Version de départ : Février 2022

# import externe
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import seaborn as sns
import time

# ------------------------
def plot2DSet(desc,labels):
    """ ndarray * ndarray -> affichage
        la fonction doit utiliser la couleur 'red' pour la classe -1 et 'blue' pour la +1
    """
    data_negatifs = desc[labels == -1]
    data_positifs = desc[labels == +1]
    #Affichage
    plt.scatter(data_negatifs[:,0],data_negatifs[:,1], marker='o', color='red')
    plt.scatter(data_positifs[:,0],data_positifs[:,1], marker='x', color='blue')

# ------------------------
def plot_frontiere(desc_set, label_set, classifier, step=30):
    """ desc_set * label_set * Classifier * int -> NoneType
        Remarque: le 4e argument est optionnel et donne la "résolution" du tracé: plus il est important
        et plus le tracé de la frontière sera précis.
        Cette fonction affiche la frontière de décision associée au classifieur
    """
    mmax=desc_set.max(0)
    mmin=desc_set.min(0)
    x1grid,x2grid=np.meshgrid(np.linspace(mmin[0],mmax[0],step),np.linspace(mmin[1],mmax[1],step))
    grid=np.hstack((x1grid.reshape(x1grid.size,1),x2grid.reshape(x2grid.size,1)))

    # calcul de la prediction pour chaque point de la grille
    res=np.array([classifier.predict(grid[i,:]) for i in range(len(grid)) ])
    res=res.reshape(x1grid.shape)
    # tracer des frontieres
    # colors[0] est la couleur des -1 et colors[1] est la couleur des +1
    plt.contourf(x1grid,x2grid,res,colors=["darksalmon","skyblue"],levels=[-1000,0,1000])

# ------------------------
def genere_dataset_uniform(p, n, binf=-1, bsup=1):
    """ int * int * float^2 -> tuple[ndarray, ndarray]
        Hyp: n est pair
        p: nombre de dimensions de la description
        n: nombre d'exemples de chaque classe
        les valeurs générées uniformément sont dans [binf,bsup]
    """
    dataset = np.random.uniform(binf, bsup, (2*n,p))
    label = np.asarray([-1 for i in range(0,n)] + [+1 for i in range(0,n)])
    return dataset, label

# ------------------------
def genere_dataset_gaussian(positive_center, positive_sigma, negative_center, negative_sigma, nb_points):
    """ les valeurs générées suivent une loi normale
        rend un tuple (data_desc, data_labels)
    """
    neg_data = np.random.multivariate_normal(negative_center, negative_sigma, nb_points)
    pos_data = np.random.multivariate_normal(positive_center, positive_sigma, nb_points)

    dataset = np.vstack( (neg_data, pos_data) )
    label = np.asarray([-1 for i in range(nb_points)] + [1 for i in range(nb_points)])

    return dataset, label
# ------------------------
def create_XOR(n, var):
    """ int * float -> tuple[ndarray, ndarray]
        Hyp: n et var sont positifs
        n: nombre de points voulus
        var: variance sur chaque dimension
    """
    negative_points_1 = np.random.multivariate_normal(np.array([0,0]), np.array([[var,0],[0,var]]), n)
    negative_points_2 = np.random.multivariate_normal(np.array([1,1]), np.array([[var,0],[0,var]]), n)
    positive_points_1 = np.random.multivariate_normal(np.array([1,0]), np.array([[var,0],[0,var]]), n)
    positive_points_2 = np.random.multivariate_normal(np.array([0,1]), np.array([[var,0],[0,var]]), n)

    descriptions = np.vstack((negative_points_1, negative_points_2, positive_points_1, positive_points_2))
    labels = np.asarray([-1 for i in range(2*n)] + [+1 for i in range(2*n)])

    return descriptions, labels
# ------------------------
def plot_frontiere_V3(desc_set, label_set, w, kernel, step=30, forme=1, fname="out/tmp.pdf"):
    """ desc_set * label_set * array * function * int * int * str -> NoneType
        Note: le classifieur linéaire est donné sous la forme d'un vecteur de poids pour plus de flexibilité
    """
    # -----------
    # ETAPE 1: construction d'une grille de points sur tout l'espace défini par les points du jeu de données
    mmax=desc_set.max(0)
    mmin=desc_set.min(0)
    x1grid,x2grid=np.meshgrid(np.linspace(mmin[0],mmax[0],step),np.linspace(mmin[1],mmax[1],step))
    grid=np.hstack((x1grid.reshape(x1grid.size,1),x2grid.reshape(x2grid.size,1)))

    # -----------
    # Si vous avez du mal à saisir le concept de la grille, décommentez ci-dessous
    #plt.figure()
    #plt.scatter(grid[:,0],grid[:,1])
    #if True:
    #    return

    # -----------
    # ETAPE 2: calcul de la prediction pour chaque point de la grille
    res=np.array([kernel(grid[i,:])@w for i in range(len(grid)) ])
    # pour les affichages avancés, chaque dimension est présentée sous la forme d'une matrice
    res=res.reshape(x1grid.shape)

    # -----------
    # ETAPE 3: le tracé
    #
    # CHOIX A TESTER en décommentant:
    # 1. lignes de contours + niveaux
    if forme <= 2 :
        fig, ax = plt.subplots() # pour 1 et 2
        ax.set_xlabel('X_1')
        ax.set_ylabel('X_2')
    if forme == 1:
        CS = ax.contour(x1grid,x2grid,res)
        ax.clabel(CS, inline=1, fontsize=10)
    #
    # 2. lignes de contour 0 = frontière
    if forme == 2:
        CS = ax.contour(x1grid,x2grid,res, levels=[0], colors='k')
    #
    # 3. fonction de décision 3D
    if forme == 3 or forme == 4:
        fig = plt.gcf()
        ax = fig.gca(projection='3d') # pour 3 et 4
        ax.set_xlabel('X_1')
        ax.set_ylabel('X_2')
        ax.set_zlabel('f(X)')
    #
    if forme == 3:
        surf = ax.plot_surface(x1grid,x2grid,res, cmap=cm.coolwarm)
    #
    # 4. fonction de décision 3D contour grid + transparence
    if forme == 4:
        norm = plt.Normalize(res.min(), res.max())
        colors = cm.coolwarm(norm(res))
        rcount, ccount, _ = colors.shape
        surf = ax.plot_surface(x1grid,x2grid,res, rcount=rcount, ccount=ccount, facecolors=colors, shade=False)
        surf.set_facecolor((0,0,0,0))

    # -----------
    # ETAPE 4: ajout des points
    negatifs = desc_set[label_set == -1]     # Ensemble des exemples de classe -1
    positifs = desc_set[label_set == +1]     # +1
    # Affichage de l'ensemble des exemples en 2D:
    if forme <= 2:
        ax.scatter(negatifs[:,0],negatifs[:,1], marker='o', c='b') # 'o' pour la classe -1
        ax.scatter(positifs[:,0],positifs[:,1], marker='x', c='r') # 'x' pour la classe +1
    else:
        # on peut ajouter une 3ème dimension si on veut pour 3 et 4
        ax.scatter(negatifs[:,0],negatifs[:,1], -1, marker='o', c='b') # 'o' pour la classe -1
        ax.scatter(positifs[:,0],positifs[:,1], 1,  marker='x', c='r') # 'x' pour la classe +1

    # -----------
    # ETAPE 5 en 3D: régler le point de vue caméra:
    if forme == 3 or forme == 4:
        ax.view_init(20, 70) # a régler en fonction des données

    # -----------
    # ETAPE 6: sauvegarde (le nom du fichier a été fourni en argument)
    if fname != None:
        # avec les options pour réduires les marges et mettre le fond transprent
        plt.savefig(fname,bbox_inches='tight', transparent=True,pad_inches=0)

# --------------------------------------
def calculCout(X,Y, ensemble):
    cost=[]
    cost.clear()
    for i in range(len(ensemble)):
        w = ensemble[i].copy()
        y_hat = np.dot(X,w)       # f(X)
        C = np.multiply(y_hat, Y) # f(X).Y
        C = np.ones(200)-C        # 1 - f(X).Y
        C[C <= 0] = 0
        cost.append(np.sum(C))
    return cost

# -------------------------------------------------------------
def crossval(X, Y, n_iterations, iteration):
    taille_bloc = len(Y)//n_iterations
    start,end = iteration*int(len(Y)/n_iterations), (iteration+1)*int(len(Y)/n_iterations)
    Xapp, Yapp = np.delete(X,np.s_[start:end],axis=0), np.delete(Y,np.s_[start:end],axis=0)
    Xtest, Ytest = X[start:end,:], Y[start:end]
    return Xapp, Yapp, Xtest, Ytest

def PCA(X, affichage=False):
    # calcul des vecteurs propres
    A = X.T @ X
    lam, V = np.linalg.eig(A)

    # affichage (print)
    print("le nombre de valeurs propres : {}".format(len(lam)))

    # tri et sélection des 2 vecteurs associés aux 2 plus grandes valeurs propres
    sorted_index = np.argsort(lam)[::-1]
    sorted_eigenvalue = lam[sorted_index]
    sorted_eigenvectors = V[:,sorted_index]
    eigenvector_subset = sorted_eigenvectors[:,0:2]

    Xr = np.dot(eigenvector_subset.transpose() , X.transpose() ).transpose()

    print("Dimension de l'ensemble de départ : ",X.shape[1])
    print("Dimension de l'ensemble après transformation : ",Xr.shape[1])
    print("---")
    if(affichage):
        # affichage (plot) avec un code couleur pour les classes
        plt.figure()
        plt.scatter(Xr[Y==-1,0],Xr[Y==-1,1])
        plt.scatter(Xr[Y==1,0],Xr[Y==1,1])
        plt.legend(np.arange(10))
    return Xr

def viewData(data, kde=True):
    """
    visualisation d'un pandas.dataframe sous la forme d'histogramme (avec uu gaussian kernel densiy estimate si demandé
    et intéressant)
    Arguments:
    data {pandas.dataFrame} -- le pandas.dataframe à visualiser
    Keyword Arguments:
    kde {bool} -- demande de l'affichage du gaussian kdf (default: {True})
    """
    x = 4
    y = math.ceil(len(data.keys()) / x)
    plt.figure(figsize=(x * 4, y * 2))
    for i, k in enumerate(data.keys()):
        ax = plt.subplot(x, y, i + 1, xticklabels=[])
        ax.set_title(k)
        dd = sns.histplot(data[k], kde=kde and len(data[k].unique()) > 5,ax=ax)
        dd.set_title("")

def normalisation(df):
    for feature_name in df.columns:
        max_value = df[feature_name].max()
        min_value = df[feature_name].min()
        result[feature_name] = (df[feature_name] - min_value) / (max_value - min_value)
    return result

def treat_outliers(d,c):
    '''
    Traite les valeurs aberrantes
    Arguments: d - DataFrame
               c - chaine nom de colonne
    retourne dans d la colonne c sans valeurs aberrantes
    '''
    # IQR
    Q1 = np.percentile(d[c], 25,interpolation = 'midpoint')
    Q2 = np.percentile(d[c], 50,interpolation = 'midpoint')
    Q3 = np.percentile(d[c], 75,interpolation = 'midpoint')
    IQR = Q3 - Q1

    # Upper bound
    upper = np.where(d[c] >= (Q3+1.5*IQR))
    # Lower bound
    lower = np.where(d[c] <= (Q1-1.5*IQR))

    d[c] = np.where(d[c] <(Q1-1.5*IQR), Q2,d[c])
    d[c] = np.where(d[c] >(Q3+1.5*IQR), Q2,d[c])

def train_cv(model, X, Y, niter=10):
    # Entrainement du modèle perceptron multiclasse avec l'algorithme k-ppv et k = 3
    index = np.random.permutation(len(X))
    Xm, Ym  = X[index], Y[index]
    niter = 10
    perf_train, perf_test = [], []
    tic= time.time()
    for i in range(niter):
        Xapp,Yapp,Xtest,Ytest = crossval(Xm, Ym, niter, i)
        model.train(Xapp, Yapp)
        perf_train.append(round(model.accuracy(Xapp, Yapp),2))
        perf_test.append(round(model.accuracy(Xtest, Ytest),2))
        print("Kfold {} : train {}  -  test {}".format(i, perf_train[i], perf_test[i]))
    toc= time.time()
    print("---")
    print("Moyenne train set: {}".format(round(np.mean(perf_train),2)))
    print("Moyenne test  set: {}".format(round(np.mean(perf_test),2)))
    print(f"Résultat en {(toc-tic):.2} secondes")
    print("---")


# %%
# Shi-TOmasi角点检测（一种适应追踪的角点检测方式）
import numpy as np
import cv2
from matplotlib import pyplot as plt

# %%
img = cv2.imread('data/calibresult.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
"""goodFeaturesToTrack函数：
    参数： （1）gray：输入灰度图
           （2） 25：想要检测的角点数量
           （3） 0：角点最低水平 （0到1）
           （4） 10：两个角点的最短欧式距离
"""
corners = cv2.goodFeaturesToTrack(gray,25,0.01,10)
# 返回的结果是[[ 311., 250.]] 两层括号的数组。
corners = np.int0(corners)
for corner in corners:
    x,y = corner.ravel()
    cv2.circle(img,(x,y),3,255,-1)  #汇出角点
plt.imshow(img),plt.show()

# %%


from pycocotools.coco import COCO
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import cv2 as cv

# =======================================
# =======================================
obj_class = 255
dataDir='E:/00_graduation project/DataSet/COCO/' # 数据集根目录
dataType='val2017' # 选择图像类型
annFile='{}2017_Train_Val_annotations/instances_{}.json'.format(dataDir,dataType) # annotation路径

# 蒙版绘制函数
def showAnns(mask, anns, c):
    if len(anns) == 0:  # 判断注释类型
        return 0
    if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
        datasetType = 'instances'  # 蒙版
    else:
        raise Exception('datasetType not supported')  # 错误

    if datasetType == 'instances':
        for ann in anns:
            # c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] # 随机生成标记颜色
            if 'segmentation' in ann:
                if type(ann['segmentation']) == list:  # polygon多边形
                    for seg in ann['segmentation']:
                        poly = np.array(seg, np.int32).reshape((int(len(seg) / 2), 2))  # 将标记信息转换为坐标数组
                        poly = poly.reshape((-1, 1, 2)) # 修整顶点坐标数组格式
                        cv.fillPoly(mask, [poly], color=c) # 填充形状
        # plt.imshow(mask)
        # plt.show()
        return mask

# 将COCO格式转换为VOC格式
# 图片形状[x,y,3]， COCO标注信息， voc蒙版颜色
def coco2voc(imgShape, anns, color):
    mask = np.zeros(imgShape, np.uint8)  # 绘制纯黑底色

    mask = showAnns(mask, anns, color)  # 绘制mask
    # mask = cv.cvtColor(mask, cv.COLOR_BGR2RGB)

    # 获取图片ID
    imgId = str(anns[0]['image_id']).zfill(12)
    imgId_ = imgId + '.png'
    src = dataDir + 'voc/'+ dataType + '/' + imgId_ # 组成路径
    cv.imwrite(src, mask) # 保存图片
    txt.write(imgId + '\n')

# initialize COCO api for instance annotations
coco=COCO(annFile) # 初始化coco类
''' # 输出所有分类名
# display COCO categories and supercategories
cats = coco.loadCats(coco.getCatIds()) # 获取类别列表,列表中元素是存储着类名、id和亚类的字典
nms=[cat['name'] for cat in cats] # 遍历类别列表，取出所有类的name
print('COCO categories: \n{}\n'.format(' '.join(nms))) # 打印类名

nms = set([cat['supercategory'] for cat in cats]) # set无序不重复序列 取出所有亚类
print('COCO supercategories: \n{}'.format(' '.join(nms))) # 打印类名
'''
# get all images containing given categories
catIds = coco.getCatIds(catNms=['person']) # 获取指定类别的id
imgIds = coco.getImgIds(catIds=catIds) # 获取包含指定类别id的图像id

# ==========================================
# 遍历满足条件的图像
# ==========================================
txt = open(dataDir + 'voc/'+ dataType + '.txt', "w") # 创建txt记录转换的图片id
print("transforming...")
count = 0
for i in tqdm(imgIds):
    img = coco.loadImgs(i)[0] # 获取第一个图像的json
    # load and display image
    I = cv.imread('%s/%s/%s' % (dataDir, dataType, img['file_name']))  # 从本地加载图像
    # I = cv.cvtColor(I, cv.COLOR_BGR2RGB) # 转换颜色格式
    # use url to load image
    # I = cv.imread(img['coco_url']) # 通过网络从远程加载图

    # ==============================================
    # load and display instance annotations
    # ==============================================
    imgShape = I.shape # 得到图片尺寸
    annIds = coco.getAnnIds(imgIds=img['id'], catIds=catIds, iscrowd=None) # 得到指定图像对应类型的annotation id
    anns = coco.loadAnns(annIds) # 根据annotation id加载蒙版json

    color = [obj_class, obj_class, obj_class] # 蒙版颜色
    coco2voc(imgShape, anns, color)
    count = count + 1
txt.close()
print(f"transform completely. total:{count}")


# Python standard libraries
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import json

import sqlite3

# Third-party libraries
from flask import Flask, redirect, request, url_for, render_template
from flask_login import (
    LoginManager,
    current_user,
    login_required,
    login_user,
    logout_user,
    UserMixin,
    )
from oauthlib.oauth2 import WebApplicationClient
import requests

# Internal imports
from etl.gcp_utils import init_connection_engine, access_secret
from data_viz import journal_calendar

# Configuration
PROJECT_ID = os.getenv("PROJECT_ID")

try:
    GOOGLE_CLIENT_ID = access_secret(project_id=PROJECT_ID,secret_id="CLIENT_ID")
    GOOGLE_CLIENT_SECRET =  access_secret(project_id=PROJECT_ID,secret_id="CLIENT_SECRET")
    EMAIL = access_secret(project_id=PROJECT_ID,secret_id="EMAIL")

except: # google.api_core.exceptions.PermissionDenied
    GOOGLE_CLIENT_ID = os.getenv("CLIENT_ID")
    GOOGLE_CLIENT_SECRET = os.getenv("CLIENT_SECRET")
    LOCAL_DB = os.getenv("LOCAL_DB")
    EMAIL = os.getenv("EMAIL")

finally:
    GOOGLE_DISCOVERY_URL = 'https://accounts.google.com/.well-known/openid-configuration'
    DB_URL = os.getenv('DB_URL')

# TODO: Resolve testing with this initial database declaration.
db = None
db= sqlite3

app = Flask(__name__)
app.secret_key = os.getenv("SECRET_KEY") or os.urandom(24)

# User session management setup
# https://flask-login.readthedocs.io/en/latest
login_manager = LoginManager()
login_manager.init_app(app)

# OAuth 2 client setup
client = WebApplicationClient(GOOGLE_CLIENT_ID)

# User class for flask-login
class User(UserMixin):
    def __init__(self, email):
        self.id = email

    @staticmethod
    def get(user_id):
        user = User(email=user_id)
        return user

# Flask-Login helper to retrieve a user from our db
@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

# TODO: Add error handling
def get_google_provider_cfg():
    return requests.get(GOOGLE_DISCOVERY_URL).json()

@app.route("/")
def login():
    # Find out what URL to hit for Google login.
    google_provider_cfg = get_google_provider_cfg()
    authorization_endpoint = google_provider_cfg["authorization_endpoint"]

    # Construct Google login request and retrieve user profile.
    request_uri = client.prepare_request_uri(
        authorization_endpoint,
        redirect_uri=request.base_url + "login/callback",
        scope=["openid", "email", "profile"],
        )
    return redirect(request_uri)

@app.route("/login/callback")
def callback():
    # Get authorization code from Google.
    code = request.args.get("code")

    # Get User token URL.
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]

    # Prepare and send a request to get tokens.
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code
        )

    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
        )

    # Parse tokens.
    client.parse_request_body_response(json.dumps(token_response.json()))

    # Get Google account information,
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)

    # Verify email address for Google account.
    if userinfo_response.json()["email"] != EMAIL:
        return "User email not available or not verified by Google.", 400

    user = User(email=EMAIL)

    # Begin user session by logging the user in
    login_user(user)

    # Send user to homepage if Google account is verified.
    return redirect(url_for("codex_vitae"))

@login_required
@app.route('/logout')
def logout():
    if current_user.is_authenticated:
        logout_user()
        return redirect(url_for("login"))

@login_required
@app.route('/codex-vitae')
def codex_vitae():
    if current_user.is_authenticated:
        # Connect to DB and plot journal entries.
        global db
        db = db or init_connection_engine()

        with db.connect(LOCAL_DB) as conn:
            journal_tuples = conn.execute(
                                        "select * from journal_view order by date"
                                        ).fetchall()

        journal = journal_calendar(journal_tuples)

        return render_template('index.html', plot=journal)
    return "Please Log In."

if __name__ == '__main__':

    app.run(ssl_context="adhoc",debug=True)


#!/usr/bin/python3
'''
Module 11. Student to disk and reload
'''

class Student():
    '''
    Write a class Student that defines a student by
    '''
    def __init__(self, first_name, last_name, age):
        '''
        Instantiation with first_name, last_name and age
        '''
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self, attrs=None):
        '''
        etrieves a dictionary representation of a Student instance
        '''
        if attrs is None:
            return self.__dict__
        else:
            dictionary = {}
            for att in attrs:
                if att in self.__dict__.keys():
                    dictionary[att] = self.__dict__[att]
            return dictionary

    def reload_from_json(self, json):
        '''
        replaces all attributes of the Student instance
        '''
        for atr_name, atr_value in json.items():
            setattr(self, atr_name, atr_value)


import math

n = int(input())

dp = [0] * (n + 1)

try:
    dp[1] = 0
    dp[2] = 1
    dp[3] = 1
except:
    pass
for i in range(4, n + 1):
    num1 = math.inf
    num2 = math.inf
    num3 = math.inf
    if i % 3 == 0:
        num1 = dp[i // 3] + 1
    if i % 2 == 0:
        num2 = dp[i // 2] + 1
    num3 = dp[i - 1] + 1
    dp[i] = min(num1, num2, num3)

print(dp[n])


'''
Sorting a string
'''

def strsort (word):
    '''
    Simply sort a string. Trivial, but essential to remember
    '''
    return ''.join(sorted(word))
#---

if __name__ == '__main__':
    user_in = 'ok'
    while len(user_in) > 0:
        user_in = input('Enter a string to sort: ')
        if len(user_in) > 0:
            print(strsort(user_in))


"""1) Дополните класс Группа (задание Лекции 2) возможностью поддержки итерационного протокола. """

class Human:        # Оставлен для проверки группы

    def __init__(self, last_name, first_name, patronymic, gender, age, height, weight):
        self.last_name = last_name
        self.first_name = first_name
        self.patronymic = patronymic
        self.gender = gender
        self.age = age
        self.height = height
        self.weight = weight

    def show_inform(self):
        full_name = f'Full Name: {self.last_name} {self.first_name} {self.patronymic}\n'
        gender_age = f'Gender: {self.gender}\nAge: {self.age}\n'
        height_weight = f'Height: {self.height} cm\nWeight: {self.weight} kg'
        all_info = full_name + gender_age + height_weight
        return all_info

class Student(Human):       # Оставлен для проверки группы

    def __init__(self, last_name, first_name, patronymic, gender, age, height, weight, speciality, group, course):
        super().__init__(last_name, first_name, patronymic, gender, age, height, weight)
        self.speciality = speciality
        self.group = group
        self.course = course

    def show_inform(self):
        full_name = f'Full Name: {self.last_name} {self.first_name} {self.patronymic}\n'
        university = f'Speciality: {self.speciality}\nGroup: {self.group}\nCourse: {self.course}'
        all_info = full_name + university
        return all_info

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

class ToManyPeople(Exception):

    def __init__(self, message):
        super().__init__()
        self.message = message

    def get_exc(self):
        return self.message

class GroupIterator:

    def __init__(self, wrap):
        self.wrap = wrap
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < len(self.wrap):
            self.index += 1
            return self.wrap[self.index-1]
        else:
            raise StopIteration

class Group:

    def __init__(self, *args):
        try:
            if len(args) > 10:
                self.group_lst = [args[i] for i in range(10)]
                raise ToManyPeople('Вы создаете группу больше необходимого максимум 10. Создан список из первых 10')
            else:
                self.group_lst = [i for i in args]
        except ToManyPeople as tm:
            print(tm.get_exc())

    def add_to_group(self, student):
        try:
            if len(self.group_lst) >= 10:
                raise ToManyPeople('Вы добавили слишком много людей в группу максимум 10')
            else:
                self.group_lst.append(student)
        except ToManyPeople as tm:
            print(tm.get_exc())

    def delete_from_group(self, student):
        index = self.group_lst.index(student)
        del self.group_lst[index]

    def find_student(self, last_name):
        for student in self.group_lst:
            if student.last_name == last_name:
                return str(student)
        else:
            return 'Такого студента нет!'

    def show_group(self):
        for num, student in enumerate(self.group_lst):
            print(f'{num+1}. {student.last_name} {student.first_name} {student.patronymic}')

    def __iter__(self):
        return GroupIterator(self.group_lst)

    def __str__(self):
        self.show_group()
        return ''

student1 = Student('Лихачёв', 'Бенедикт', 'Дамирович', 'male', 25, 185, 91, 'IT', 'RT-518', 'III')
student2 = Student('Шилов', 'Святослав', 'Якунович', 'male', 23, 160, 50, 'IT', 'RT-518', 'III')
student3 = Student('Самойлов', 'Иннокентий', 'Георгиевич', 'male', 24, 175, 65, 'IT', 'RT-518', 'III')
student4 = Student('Григорьев', 'Лука', 'Сергеевич', 'male', 26, 145, 82, 'IT', 'RT-518', 'III')
student5 = Student('Громов', 'Ибрагил', 'Артемович', 'male', 22, 192, 73, 'IT', 'RT-518', 'III')
student6 = Student('Хохлова', 'Илона', 'Лукьевна', 'female', 23, 134, 85, 'IT', 'RT-518', 'III')
student7 = Student('Силина', 'Элизабет', 'Альбертовна', 'female', 24, 154, 84, 'IT', 'RT-518', 'III')
student8 = Student('Рогова', 'Кира', 'Авксентьевна', 'female', 25, 132, 89, 'IT', 'RT-518', 'III')
student9 = Student('Щербакова', 'Неолина', 'Вячеславовна', 'female', 23, 164, 76, 'IT', 'RT-518', 'III')
student10 = Student('Лукина', 'Эвелина', 'Митрофановна', 'female', 24, 165, 59, 'IT', 'RT-518', 'III')
student11 = Student('Суханова', 'Аделия', 'Игнатьевна', 'male', 25, 157, 49, 'IT', 'RT-518', 'III')

group_rt = Group(student1, student2, student3, student4, student5, student6, student7, student8, student9, student10)

students = iter(group_rt)

for stud in students:
    print(stud)

Python Pro/Лекция 6. Итераторы и итерационный протокол/Lection_6_tsk_1.py


import random as rn
import os
from art import logo2

def clear():
    '''this clears the terminal'''
    os.system('cls')

def number_game():
    '''This is a number guessing game function'''
    print(logo2)
    print("Welcome to the number guessing game \nI am thinking of a number between 1 and 100")
    numbers = [x for x in range(1, 101)]
    computers_choice = rn.choice(numbers)

    def guess():
        '''The criteria for guessing the number'''
        your_choice = int(input("What's the number? "))
        if computers_choice == your_choice:
            print(f"Psst, the number is {computers_choice}")
            return True  # placeholder for when the guess actually becomes true aka equal to the computer's choice
        elif computers_choice > your_choice:
            print(f"Too low")
            return False  # placeholder for when the guess is false, not necessary
        else:
            print(f'Too high')
            return False

    def easy():
        '''If the difficulty is easy'''
        num_choices = 10
        while num_choices > 0:
            print(f"You have {num_choices} chances left")
            num_choices -= 1
            if guess():  # if the guess function is true (return True), going back to the guess function, means the guessed number is equal to the computer's choice
                print(f'Psst you guessed correctly, the random number was {computers_choice}')
                return
        print('Game over, you lost')

    def hard():
        '''If the difficulty is hard'''
        num_choices = 5
        for i in range(num_choices):
            print(f"You have {num_choices-i} chances left")  # it does 5-1,5-2,5-3, etc until it does it 5 times, which equals 0 chances left
            if guess():
                print(f'Psst you guessed correctly, the random number was {computers_choice}')
                return  # ending the loop
        print('Game over, you lost')

    while True:
        difficulty = input('Choose your difficulty between easy and hard (or type "exit" to quit): ')
        if difficulty == 'easy':
            easy()
        elif difficulty == 'hard':
            hard()
        elif difficulty == 'exit':
            print('Thanks for playing!')
            break
        else:
            print('Invalid input, please try again.')

    while True:
        if input("Do you want to restart the game? Type 'y' for  yes and 'n' for no: ") == 'y':
            clear()
            number_game() # absolutely just copied this from my blackjack game, because recursion seems cool to me
        else:
            print('Game over')
            break

number_game()


import cv2

img = cv2.imread("aircraft.jpg")
img = cv2.resize(img, (512, 512))

img1 = cv2.imread("aircraft1.jpg")
img1 = cv2.resize(img1, (512, 512))
img1 = cv2.medianBlur(img1, 101)

img2 = cv2.imread("polygons.png")
img2 = cv2.medianBlur(img2, 25)
img2 = cv2.resize(img2, (512, 512))

if img.shape == img1.shape:
    print("Same Size...")
else:
    print("Not Same...")

diff = cv2.subtract(img, img1)

b, g, r = cv2.split(diff)
# print(b, g, r)

q0 = cv2.countNonZero(b)
q1 = cv2.countNonZero(g)
q2 = cv2.countNonZero(r)

print("blue:", q0, "\n", "gray:", q1, "\n", "red:", q2)

cv2.imshow("difference", diff)
cv2.waitKey(0)
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Performance test of cnn architectures on various degradation models.
Created on Thu May 24 11:00:00 2018
Author: Prasun Roy | CVPRU-ISICAL (http://www.isical.ac.in/~cvpr)
GitHub: https://github.com/prasunroy/cnn-on-degraded-images

"""

# imports
from __future__ import division
from __future__ import print_function

import cv2
import glob
import json
import numpy
import os
import pandas
import sys

from keras.applications import mobilenet
from keras.models import model_from_json
from matplotlib import pyplot

from libs.CapsuleNetwork import CapsuleLayer
from libs.CapsuleNetwork import Mask
from libs.CapsuleNetwork import Length
from libs.DegradationModels import imdegrade
from libs.PipelineUtils import save_samples
from libs.PipelineUtils import shutdown
from mlutils.callbacks import Telegram

# configurations
# -----------------------------------------------------------------------------
RANDOM_SEED = None

RANDOM_STR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
PROCESS_ID = ''.join([RANDOM_STR[numpy.random.randint(0, len(RANDOM_STR))] \
                      for _ in range(16)])

DATASET_ID = 'synthetic_digits'
LABEL_MAPS = 'data/{}/labelmap.json'.format(DATASET_ID)
IMAGE_DSRC = 'data/{}/imgs_valid/'.format(DATASET_ID)
IMAGE_READ = 1

SAVE_NOISY = False
SAMP_NOISY = 10

NOISE_LIST = ['Gaussian_White', 'Gaussian_Color', 'Salt_and_Pepper',
              'Motion_Blur', 'Gaussian_Blur', 'JPEG_Quality']
MODEL_LIST = ['capsnet', 'inceptionv3', 'mobilenet', 'resnet50',
              'vgg16', 'vgg19']

MODELS_DICT = {name.lower(): 'output/{}/{}/models/{}.json'\
               .format(DATASET_ID, name, name) for name in MODEL_LIST}
WEIGHT_DICT = {name.lower(): 'output/{}/{}/checkpoints/{}_best.h5'\
               .format(DATASET_ID, name, name) for name in MODEL_LIST}

TOP_N_PRED = 3

OUTPUT_DIR_NOISY = 'output/{}/__test__images__'.format(DATASET_ID)
OUTPUT_DIR_TOP_1 = 'output/{}/__test__top{}__/'.format(DATASET_ID, 1)
OUTPUT_DIR_TOP_N = 'output/{}/__test__top{}__/'.format(DATASET_ID, TOP_N_PRED)

AUTH_TOKEN = None
TELCHAT_ID = None
TEL_CLIENT = Telegram(auth_token=AUTH_TOKEN, chat_id=TELCHAT_ID)

F_SHUTDOWN = False
# -----------------------------------------------------------------------------

# setup parameters
sigmavals = [x for x in range(0, 256, 5)]
densities = [x/100 for x in range(0, 101, 5)]
mb_ksizes = [x for x in range(3, 32, 2)]
gb_ksizes = [x for x in range(1, 52, 2)]
qualities = [x for x in range(30, -1, -2)]

# setup acknowledgement message templates
ack_msg_beg = """`
Received a new test request.

TASK ID: {}
DATASET: {}
SAMPLES: {}

Using CNN architectures:
{}
Using degradation models:
{}
`"""\
.format(PROCESS_ID,
        DATASET_ID,
        {},
        ''.join(['\t* {}\n'.format(model) for model in MODEL_LIST]),
        ''.join(['\t* {}\n'.format(noise) for noise in NOISE_LIST]))

ack_msg_end = """`
An ongoing test is finished.

TASK ID: {}
`"""\
.format(PROCESS_ID)

ack_msg_int = """`
An ongoing test is interrupted.

TASK ID: {}
REASONS: {}
`"""\
.format(PROCESS_ID, {})

# validate paths
def validate_paths():
    flag = True
    if not os.path.isfile(LABEL_MAPS):
        print('[INFO] Label mapping not found at {}'.format(LABEL_MAPS))
        flag = False
    if not os.path.isdir(IMAGE_DSRC):
        print('[INFO] Image data source not found at {}'.format(IMAGE_DSRC))
        flag = False
    for name, path in MODELS_DICT.items():
        if not os.path.isfile(path):
            print('[INFO] {} architecture not found at {}'.format(name, path))
            flag = False
    for name, path in WEIGHT_DICT.items():
        if not os.path.isfile(path):
            print('[INFO] {} checkpoint not found at {}'.format(name, path))
            flag = False
    for directory in [OUTPUT_DIR_NOISY, OUTPUT_DIR_TOP_1, OUTPUT_DIR_TOP_N]:
        if not os.path.isdir(directory):
            os.makedirs(directory)
        elif len(glob.glob(os.path.join(directory, '*.*'))) > 0:
            print('[INFO] Output directory {} must be empty'.format(directory))
            flag = False

    return flag

# load data
def load_data():
    x = []
    y = []

    # label mapping
    with open(LABEL_MAPS, 'r') as file:
        labelmap = json.load(file)

    # class labels
    labels = [os.path.split(d[0])[-1] for d in os.walk(IMAGE_DSRC)][1:]

    # read images
    for label in labels:
        for file in glob.glob(os.path.join(IMAGE_DSRC, label, '*.*')):
            image = cv2.imread(file, IMAGE_READ)
            if image is None:
                continue
            x.append(image)
            y.append(labelmap[label])

    return (x, y)

# load models
def load_models():
    models = {}

    # define required custom objects
    args_caps = {'CapsuleLayer': CapsuleLayer, 'Mask': Mask, 'Length': Length}
    args_mobi = {'relu6': mobilenet.relu6}

    # load model architectures
    for name, path in MODELS_DICT.items():
        with open(path, 'r') as file:
            model_json = file.read()
        if name == 'capsnet':
            models[name] = model_from_json(model_json, args_caps)
        elif name == 'mobilenet':
            models[name] = model_from_json(model_json, args_mobi)
        else:
            models[name] = model_from_json(model_json)

    # load model weights
    for name, path in WEIGHT_DICT.items():
        models[name].load_weights(path)

    return models

# initialize histories
def init_histories(init_dict={}):
    histories_top_1 = init_dict.copy()
    histories_top_n = init_dict.copy()
    for name in MODEL_LIST:
        histories_top_1['acc_' + name.lower()] = []
        histories_top_n['acc_' + name.lower()] = []

    return [histories_top_1, histories_top_n]

# save and plot histories
def save_and_plot_histories(file_id, histories, title='', xlabel='', ylabel='',
                            invert_xaxis=False, invert_yaxis=False):
    for hist_dict, output_dir, ylabel_prefix \
    in zip(histories,
           [OUTPUT_DIR_TOP_1, OUTPUT_DIR_TOP_N],
           ['', 'top-{} '.format(TOP_N_PRED)]):
        # save histories
        df = pandas.DataFrame(hist_dict)
        df.to_csv(os.path.join(output_dir, str(file_id) + '.csv'), index=False)

        # plot histories
        pyplot.figure()
        pyplot.title(title)
        pyplot.xlabel(xlabel)
        pyplot.ylabel(ylabel_prefix + ylabel)
        if invert_xaxis:
            pyplot.gca().invert_xaxis()
        if invert_yaxis:
            pyplot.gca().invert_yaxis()
        x = [key for key in hist_dict.keys() if key.split('_')[0] != 'acc'][0]
        for y in hist_dict.keys():
            if y == x:
                continue
            pyplot.plot(hist_dict[x], hist_dict[y], label=y.split('_')[-1])
        pyplot.legend()
        pyplot.savefig(os.path.join(output_dir, str(file_id) + '.png'))
        pyplot.show(block=False)

        # acknowledgement
        plot_cap = '`{} [TASK ID: {}]`'.format(title, PROCESS_ID)
        plot_img = open(os.path.join(output_dir, str(file_id) + '.png'), 'rb')

        TEL_CLIENT._send_photo(data={'chat_id': TELCHAT_ID,
                                     'caption': plot_cap,
                                     'parse_mode': 'Markdown'},
                               files={'photo': plot_img})

    return

# test models
def test_models(x, y, models):
    print('')
    samples = len(x)
    results_top_1 = {}
    results_top_n = {}
    for name in models.keys():
        print('[INFO] Preparing images for {}'.format(name))
        images = []
        counts = 0
        for image in x:
            images.append(cv2.resize(image, models[name].input_shape[1:3]))
            counts += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(counts*100/samples), end='')
        print('\n[INFO] Testing images on {}... '.format(name), end='')
        x_test = numpy.asarray(images, dtype='float32') / 255.0
        y_test = numpy.asarray(y, dtype='int')
        if name == 'capsnet':
            p_test = models[name].predict(x_test)[0].argsort(axis=1)[:, -TOP_N_PRED:]
        else:
            p_test = models[name].predict(x_test).argsort(axis=1)[:, -TOP_N_PRED:]
        accuracy_top_1 = sum(p_test[:, -1]==y_test) * 100.0 / samples
        accuracy_top_n = sum([int(y in p) for y, p in zip(y_test, p_test)]) * 100.0 / samples
        results_top_1['acc_' + name] = accuracy_top_1
        results_top_n['acc_' + name] = accuracy_top_n
        print('done\t\t[accuracy: {:6.2f}%] [top-{} accuracy: {:6.2f}%]'\
              .format(accuracy_top_1, TOP_N_PRED, accuracy_top_n))

    return [results_top_1, results_top_n]

# tests for gaussian white noise
def test_gaussian_white(x, y, models):
    # initialize histories
    histories = init_histories({'sigma': sigmavals})

    # run tests
    for sigma in sigmavals:
        # apply gaussian white noise
        print('[INFO] Applying Gaussian white noise with mu=0 and sigma={}'\
              .format(sigma))
        noisy = []
        count = 0
        for image in x:
            noisy.append(imdegrade(image, 'gaussian_white', mu=0, sigma=sigma,
                                   seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='gaussian_white_sigma_{}'.format(sigma),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='gaussian_white', histories=histories,
                            title='Change in accuracy with Gaussian white noise',
                            xlabel='standard deviation (\u03c3)',
                            ylabel='accuracy (\u0025)')

    return

# tests for gaussian color noise
def test_gaussian_color(x, y, models):
    # initialize histories
    histories = init_histories({'sigma': sigmavals})

    # run tests
    for sigma in sigmavals:
        # apply gaussian color noise
        print('[INFO] Applying Gaussian color noise with mu=0 and sigma={}'\
              .format(sigma))
        noisy = []
        count = 0
        for image in x:
            noisy.append(imdegrade(image, 'gaussian_color', mu=0, sigma=sigma,
                                   seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='gaussian_color_sigma_{}'.format(sigma),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='gaussian_color', histories=histories,
                            title='Change in accuracy with Gaussian color noise',
                            xlabel='standard deviation (\u03c3)',
                            ylabel='accuracy (\u0025)')

    return

# tests for salt and pepper noise
def test_salt_and_pepper(x, y, models):
    # initialize histories
    histories = init_histories({'density': densities})

    # run tests
    for density in densities:
        # apply salt and pepper noise
        print('[INFO] Applying salt and pepper noise with density={}'\
              .format(density))
        noisy = []
        count = 0
        for image in x:
            noisy.append(imdegrade(image, 'salt_and_pepper', density=density,
                                   seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='salt_and_pepper_density_{}'.format(density),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='salt_and_pepper', histories=histories,
                            title='Change in accuracy with salt and pepper noise',
                            xlabel='noise density',
                            ylabel='accuracy (\u0025)')

    return

# tests for motion blur
def test_motion_blur(x, y, models):
    # initialize histories
    histories = init_histories({'kernel_size': mb_ksizes})

    # run tests
    for ksize in mb_ksizes:
        # apply motion blur
        print('[INFO] Applying motion blur with kernel size=({}, {})'\
              .format(ksize, ksize))
        noisy = []
        count = 0
        mb_kernel = numpy.zeros((ksize, ksize))
        mb_kernel[ksize//2, :] = 1
        mb_kernel /= numpy.sum(mb_kernel)
        for image in x:
            noisy.append(imdegrade(image, 'motion_blur', mb_kernel=mb_kernel,
                                   seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='motion_blur_ksize_({}x{})'.format(ksize, ksize),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='motion_blur', histories=histories,
                            title='Change in accuracy with motion blur',
                            xlabel='kernel size',
                            ylabel='accuracy (\u0025)')

    return

# tests for gaussian blur
def test_gaussian_blur(x, y, models):
    # initialize histories
    histories = init_histories({'kernel_size': gb_ksizes})

    # run tests
    for ksize in gb_ksizes:
        # apply gaussian blur
        print('[INFO] Applying Gaussian blur with kernel size=({}, {})'\
              .format(ksize, ksize))
        noisy = []
        count = 0
        for image in x:
            noisy.append(imdegrade(image, 'gaussian_blur',
                                   gb_ksize=(ksize, ksize), seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='gaussian_blur_ksize_({}x{})'.format(ksize, ksize),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='gaussian_blur', histories=histories,
                            title='Change in accuracy with Gaussian blur',
                            xlabel='kernel size',
                            ylabel='accuracy (\u0025)')

    return

# tests for jpeg quality
def test_jpeg_quality(x, y, models):
    # initialize histories
    histories = init_histories({'image_quality': qualities})

    # run tests
    for quality in qualities:
        # apply jpeg compression
        print('[INFO] Applying JPEG compression with quality={}'\
              .format(quality))
        noisy = []
        count = 0
        for image in x:
            noisy.append(imdegrade(image, 'jpeg_compression', quality=quality,
                                   seed=RANDOM_SEED))
            count += 1
            print('\r[INFO] Progress... {:3.0f}%'\
                  .format(count*100/len(x)), end='')

        # save noisy image samples if required
        if SAVE_NOISY:
            save_samples(noisy, SAMP_NOISY, randomize=True, seed=RANDOM_SEED,
                         filename_prefix='jpeg_quality_{}'.format(quality),
                         target_directory=OUTPUT_DIR_NOISY)

        # test models
        results = test_models(noisy, y, models)

        # update histories
        for hist_dict, res_dict in zip(histories, results):
            for key in res_dict.keys():
                hist_dict[key].append(res_dict[key])

    # save and plot histories
    save_and_plot_histories(file_id='jpeg_quality', histories=histories,
                            title='Change in accuracy with JPEG quality',
                            xlabel='image quality',
                            ylabel='accuracy (\u0025)',
                            invert_xaxis=True)

    return

# test
def test():
    # validate paths
    if not validate_paths():
        return

    # load data
    print('[INFO] Loading data... ', end='')
    (x, y) = load_data()
    print('done')

    # load models
    print('[INFO] Loading models... ', end='')
    models = load_models()
    print('done')

    # acknowledgement
    TEL_CLIENT._send_message(data={'chat_id': TELCHAT_ID,
                                   'text': ack_msg_beg.format(len(x)),
                                   'parse_mode': 'Markdown'})

    print('-'*34 + ' BEGIN TEST ' + '-'*34)

    # run tests
    for noise in NOISE_LIST:
        if noise.lower() == 'gaussian_white':
            test_gaussian_white(x, y, models)
        elif noise.lower() == 'gaussian_color':
            test_gaussian_color(x, y, models)
        elif noise.lower() == 'salt_and_pepper':
            test_salt_and_pepper(x, y, models)
        elif noise.lower() == 'motion_blur':
            test_motion_blur(x, y, models)
        elif noise.lower() == 'gaussian_blur':
            test_gaussian_blur(x, y, models)
        elif noise.lower() == 'jpeg_quality':
            test_jpeg_quality(x, y, models)

    print('-'*35 + ' END TEST ' + '-'*35)

    # acknowledgement
    TEL_CLIENT._send_message(data={'chat_id': TELCHAT_ID,
                                   'text': ack_msg_end,
                                   'parse_mode': 'Markdown'})

    return

# main
if __name__ == '__main__':
    try:
        test()
        if F_SHUTDOWN:
            shutdown()
    except:
        error = sys.exc_info()[0].__name__ if sys.exc_info()[0] is not None else 'Unknown'
        print('\n[INFO] Process interrupted [Reasons: {}]'.format(error))

        # acknowledgement
        TEL_CLIENT._send_message(data={'chat_id': TELCHAT_ID,
                                       'text': ack_msg_int.format(error),
                                       'parse_mode': 'Markdown'})


import matplotlib.pyplot as plt

x_list = []
y_list = []

def process(line):

    ### transformation matix 로 궤적 얻기 ##############################################################
    pose = line.strip().split()

    x_list.append(float(pose[3]))  # position
    y_list.append(float(pose[11]))

    ##################################################################################################

file_path = '/media/doyu_now/Linux Workspace/ICSL_Project/Visual SLAM/KITTI_data_odometry_color/data_odometry_poses/dataset/poses/10.txt'
with open(file_path, 'r') as f:
    while True:

        line = f.readline()
        if not line:
            print("End Of File")
            break

        process(line)

plt.plot(x_list, y_list, 'ob')

plt.title('kitti odom - scenario 10')
plt.show()


import numpy as np
import random
import sys
import math
import time

class Network():
    weights_matrices = []  # saves all the weight-matrices as list of matrices
    bias_matrices = []  # saves all bias vectors as list of vectors

    activation_vectors = []

    conf_list = 0  # what is this used for?
    layers_count = 0
    activation_funct = 0
    input_size = 0
    input_vector = 0
    output_vector = 0
    target_output = 0
    training_data_count = 0
    cost_function_sum = 0
    nn_cost_function = 0

    # number of layers should be cardinality of conf_list + 1
    # number of nodes per layer should be second value of said tuple

    def __init__(self, conf_list, activation_function,number_format=np.float16):
        if len(conf_list) < 2:
            print("Wrong or impossible Config. Check params")
            sys.exit()
        else:
            self.conf_list = conf_list
            self.activation_func = activation_function

            self.iterations = 10000

            for i in range(len(conf_list) - 1):
                m = conf_list[i + 1][1]
                n = conf_list[i][1]
                a = np.array(0, number_format)
                a.resize((m, n))
                self.weights_matrices.append(a)
            for i in range(1, len(conf_list)):
                n = conf_list[i][1]
                a = np.array(0, number_format)
                a.resize((n, 1))
                self.bias_matrices.append(a)

        # setting only possible input size dim
        self.input_size = self.weights_matrices[0].shape[1]
        self.nn_setup()
        self.layers_count = len(self.weights_matrices) + 1
        self.nn_information()

    def train_nn(self, input_vector, target_vector):
        self.apply_input(input_vector)
        self.target_output = target_vector

        # print("COST: -------> \n" + str(self.cost_function()))
        self.propagate_backwards()
        self.apply_input(input_vector)
        print("COST: -------> \n" + str(self.cost_function()))

        self.save_outputs()

    def propagate_backwards(self):
        for layer_num in range(self.layers_count - 1):
            self.update_w(layer_num + 2, 0.05)
            self.update_b(layer_num + 2, 0.05)

    def nn_setup(self):
        self.weights_matrices = [np.array([[2, 3], [4, 0.5], [-2, 0.1]]), np.array([[2, 3, 0.6]])]
        # self.weights_matrices = [np.array([[0.4, 2],[-1.3, 0.1], [0.4, 0.5]]),
        #                          np.array([[0.4, 0.3, 0.1], [0.4, 4, 0.1], [0.4, 3, 0.1], [4, 0.3, 0.1], [0.4, 0.3, 0.1]]),
        #                          np.array([[0.6, 0.2, -0.9, 0.7, 1.4],[0.4, 1.1, 0.7, 1.3, 0.1]])]
        # self.bias_matrices= [np.array([[0],[0.3],[2]]),
        #                      np.array([[2], [0.3], [0.7], [-1.2], [3]]),
        #                      np.array([[0.5],[0.6]])]
        self.bias_matrices = [np.array([[1],[2],[0.5]]), np.array([[0.75]])]

    def nn_setup_rand(self):
        # setting up the network with random real numbers
        # shape returns the m x n dim of a matrix
        for matrix in self.weights_matrices:
            for m in range(matrix.shape[0]):
                for n in range(matrix.shape[1]):
                    matrix.itemset((m, n), self.set_initial_randoms(-5, 5))
        for vector in self.bias_matrices:
            for m in range(vector.shape[0]):
                vector.itemset((m, 0), self.set_initial_randoms(-5, 5))

    def nn_information(self):
        # Printing useful network information
        count_layers = len(self.conf_list)
        nn_str = "A CNN with " + str(count_layers) + " layers."
        print(nn_str)
        for element in self.conf_list:
            print("Layer", element[0], "with", element[1], "nodes")
        for i in range(len(self.conf_list) - 1):
            layer_str = "Weight Matrix. Layer " + \
                str(i + 1) + " -> " + str(i + 2) + " Matrix " + "\n"
            bias_str = "Layer " + str(i + 1) + " Bias Vector." + "\n"
            print(layer_str, self.weights_matrices[i])
            print(bias_str, self.bias_matrices[i])
        print("Activation Function used:", self.activation_func)
        print("Input Size:", self.input_size, "x 1")

    def sigmoid(self, value):
        return (1 / (1 + math.exp(-value)))

    def vector_activator(self, matrix):
        if self.activation_func == "sigmoid":
            new = []
            for eintrag in matrix:
                new.append([self.sigmoid(eintrag[0])])
            return np.array(new)
        elif self.activation_func == "relu":
            for m in range(matrix.shape[0]):
                a = matrix.item((m, 0))
                a = np.maximum(m, 0)  # <------ produces error, dunno why tho
                matrix.itemset((m, 0), a)
        else:
            print("Error. Wrong Activation")
            sys.exit()
        return matrix

    def set_initial_randoms(self, a, b):
        # a and b for lower and upper bound of rand numbers
        for i in range(10):
            #             random.seed(4)
            real_nr = random.random() + 1
            int_nr = random.randint(a, b)
            real_nr = real_nr * int_nr
            return real_nr

    def cost_function(self):
        cost = self.target_output - self.output_vector
        cost = np.linalg.norm(cost)
        cost = 1/2 * np.square(cost)

        return cost

    def propagate_forward(self):
        print("\n\n\nINPUT:::")
        print(self.input_vector)
        print(self.weights_matrices)
        self.activation_vectors = [self.input_vector]

        for i in range(self.layers_count - 2):
            print("iiiiii", self.weights_matrices[i])
            vector = (self.weights_matrices[i] @ self.activation_vectors[-1]) + self.bias_matrices[i]
            self.activation_vectors.append(self.vector_activator(vector))

        print("àaaaa",self.activation_vectors)
        self.output_vector = (self.weights_matrices[-1] @ self.activation_vectors[-1]) + self.bias_matrices[-1]
        self.activation_vectors.append(self.output_vector)

        print("\nOutput:\n")
        print(self.output_vector)

    def target_vector_constructor(self, target_output):
        m = len(target_output)
        last_layer_mat_index = len(self.weights_matrices) - 1
        output_dim = self.weights_matrices[last_layer_mat_index].shape[0]
        if (m != output_dim):
            print("Target vector dimension wrong. Error!")
            sys.exit()
        else:
            self.target_vector = np.array(0, np.float16)
            self.target_vector.resize((m, 1))
            for i in range(len(target_output)):
                self.target_vector.itemset(i, target_output[i])
#             print("Target Vector:\n", self.target_vector)

    def apply_input(self, inp):
        # interpreting the n dim input tuple
        # and integrate it into a np data structure
        m = len(inp)
        if (m != self.input_size):
            print("Input vector dimension wrong. Error!")
            sys.exit()
        else:
            self.input_vector = np.array(0, np.float16)
            self.input_vector.resize((m, 1))
            for i in range(len(inp)):
                self.input_vector.itemset(i, inp[i])

        # start propagating forward
        self.propagate_forward()

    def delta(self, layer):
        layer -= 1
        if layer + 1 == len(self.conf_list):
            d = self.activation_vectors[layer] * (1 - self.activation_vectors[layer]) * \
                (self.activation_vectors[layer] - self.target_output)  # <-- * = Hadamar Product

            return d
        else:
            return self.activation_vectors[layer] * (1 - self.activation_vectors[layer]) * \
                   (self.weights_matrices[layer].transpose() @ self.delta(layer + 2))

    def update_b(self, layer, learning_rate):
        for j in range(1, len(self.bias_matrices[layer - 2]) + 1):  # for every bias in that layer
                # calculate the corresponding bias-gradient and update vector
                self.bias_matrices[layer - 2][j-1] -= learning_rate * (self.delta(layer)[j-1])
        return self.delta(layer)

    def update_w(self, layer, learning_rate):

        for i in range(1, len(self.weights_matrices[layer - 2]) + 1):  # for every row in weight-matrix(layer)
            for j in range(1, len(self.weights_matrices[layer - 2][i - 1]) + 1):  # for every element in that row
                # calculate the corresponding weight-gradient and write as vector
                self.weights_matrices[layer - 2][i-1][j-1] -= learning_rate * \
                                                              (self.delta(layer)[i-1] * self.activation_vectors[layer - 2][j-1])

    def save_outputs(self):
        with open('ergebnisse.txt', 'a') as f:
            f.write(str(self.cost_function()) + "," +
                    str(self.output_vector).replace('\n', ",") + "," +
                    str(self.iterations) + "\n")

    def test(self, test_vector):
        self.input_vector = test_vector
        self.propagate_forward()
        return self.output_vector


from data_manager import DataManager, put_data
from flight_search import iata_code
from flight_data import FlightData
from notification_manager import notify_me

data = DataManager()
sheet_data = data.flight_data
flight_data = FlightData()

for item in sheet_data['prices']:
    if item['iataCode'] == '':
        iata_search = iata_code(item['city'])
        item['iataCode'] = iata_search
        put_data(item['id'], iata_search)

for item in sheet_data['prices']:
    cheapest_data = flight_data.cheap_flight_search(item['iataCode'])
    if cheapest_data[0] < item['lowestPrice']:
        message = f"Low price alert! Only £{cheapest_data[0]} " \
                  f"to fly from London-STN to {item['city']}-{item['iataCode']}, " \
                  f"from {cheapest_data[1]} to {cheapest_data[2]}."
        notify_me(message)
        break


from iqoptionapi.stable_api import IQ_Option
import iqoptionapi.country_id as Pais
import time, logging, json, configparser
from datetime import datetime, date, timedelta
from dateutil import tz
import sys

#CODIGO PARA DESATIVAR DEBUG OU logging.ERROR
#logging.disable(level=(logging.DEBUG))

# Credenciais
API = IQ_Option('seu_email', 'password')

# Logar
def Login():
    API.connect()

    while True:
        if API.check_connect() == False:
            print('Erro ao se conectar')

            API.connect()
        else:
            print('Conectado com sucesso')
            break

        time.sleep(1)
# carrega sua banca na api
def getBalance():
    # Define a conta de utilização
    conta = 'PRACTICE'#input('\nDigite com qual conta quer entrar "REAL" ou "PRACTICE": ')
    API.change_balance(conta) # PRACTICE / REAL
    return API.get_balance()
#CONVERT TIMESTAMP PARA HORA HUMANA
def timestamp_converter(x): # Função para converter timestamp
	hora = datetime.strptime(datetime.utcfromtimestamp(x).strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')
	hora = hora.replace(tzinfo=tz.gettz('GMT'))

	return str(hora)[:-6]
#PEGA O PERFIL
def perfil():
    return json.loads(json.dumps(API.get_profile_ansyc()))
#PEGA A BANCA
def banca():
    return json.loads(json.dumps(getBalance()))
#PEGA TOP 10 TRADERS DO MUNDO
def topTrades():
    pais='Worldwide'#"BR"
    da_posicao=1
    para_posicao=30
    traders_perto=0
    return json.loads(json.dumps(API.get_leader_board(pais, da_posicao, para_posicao, traders_perto)))
#PEGA PARIDADES ABERTAS
def payout(par, tipo, timeframe = 1):
	if tipo == 'turbo':
		a = API.get_all_profit()
		return int(100 * a[par]['turbo'])

	elif tipo == 'digital':

		API.subscribe_strike_list(par, timeframe)
		while True:
			d = API.get_digital_current_profit(par, timeframe)
			if d != False:
				d = int(d)
				break
			time.sleep(1)
		API.unsubscribe_strike_list(par, timeframe)
		return d

def getCandles(par):
    API.start_candles_stream(par, 60, 1)
    time.sleep(1)

    vela = API.get_realtime_candles(par, 60)

    while True:
        for velas in vela:
            print(vela[velas]['close'])
        time.sleep(1)
    API.stop_candles_stream(par, 60)

def configuracao():
    arquivo = configparser.RawConfigParser()
    arquivo.read('config.txt')

    return { 'paridade': arquivo.get('GERAL', 'paridade'), 'valor_entrada': arquivo.get('GERAL', 'entrada'), 'timeframe': arquivo.get('GERAL', 'timeframe')}

def sinais():
    file = open('sinais.txt', encoding='UTF-8')
    lista = file.read()
    file.close

    lista = lista.split('\n')

    for index,a in enumerate(lista):
        if a == '':
            del lista[index]

    return lista

Login()
print('\n - Inicializando o bot - \n')

# loop infinito para pegar acompanhar velas
# print('\n - Acompanhar velas - \n')
# par = 'EURUSD'
# getCandles(par)

# print meu perfil
data = perfil()
print('\n - Meu perfil - \n')
print(' Apelido: ',data['nickname'])
print(' Email: ',data['email'])
print(' Nome : ',data['name'])
print(' Banca : ', banca())
print(' Criado : ',timestamp_converter(data['created']))

print('\n - Pegando Top Traders - \n')

traders = topTrades()
for colocacao in traders['result']['positional']:
    nome_ranking = traders['result']['positional'][colocacao]['user_name']
    segunda_busca = API.get_user_profile_client(traders['result']['positional'][colocacao]['user_id'])
    print(' Nome:',nome_ranking)
    print(' User ID:',traders['result']['positional'][colocacao]['user_id'])
    print(' Se registrou em:',timestamp_converter(segunda_busca['registration_time']))
    print(' Pais: '+traders['result']['positional'][colocacao]['flag'])
    print(' Faturamento esta semana:',round(traders['result']['positional'][colocacao]['score'], 2))
    print('\n')

print(' - Trader(s) Online - \n')

for index in traders['result']['positional']:
    # Pega o user_id do top 10 traders
    id = traders['result']['positional'][index]['user_id']
    # Quarda o perfil de cada trader
    perfil_trader = API.get_user_profile_client(id)
    # Verifica quem está online
    if perfil_trader['status'] == 'online':
        trade = API.get_users_availability(id)

        try:
            tipo = trade['statuses'][0]['selected_instrument_type']
            par = API.get_name_by_activeId(trade['statuses'][0]['selected_asset_id']).replace('/', '')

            print('\n [',index,'] ',perfil_trader['user_name'])
            print(' Opção: ',tipo)
            print(' Pariedade: ',par)
        except:
            pass

# print('\n - Pegando pariedades abertas - \n')

# par = API.get_all_open_time()

# for paridade in par['turbo']:
	# if par['turbo'][paridade]['open'] == True:
		# print('[ TURBO ]: '+paridade+' | Payout: '+str(payout(paridade, 'turbo')))

# print('\n')

# for paridade in par['digital']:
	# if par['digital'][paridade]['open'] == True:
		# print('[ DIGITAL ]: '+paridade+' | Payout: '+str( payout(paridade, 'digital') ))

# #PEGA OS SINAIS
# print('\n')
# print(json.dumps(sinais(), indent=1))
# lista_sinais = sinais()
# print('\n Quantidade de sinais: ',len(lista_sinais))

# for index, sinal in enumerate(lista_sinais):
    # dados = sinal.split(';')

    # while index <= len(lista_sinais):

        # HORA_ATUAL = time.strftime('%Y-%m-%d %H:%M', time.localtime())

        # if HORA_ATUAL == dados[0]:
            # print('\n - Abrir ordem opções digitais - \n')
            # pareMoeda = dados[2]
            # entradas = 100.00
            # direcoes = dados[3]#call pra cima put pra baixo
            # timesframe = 1#1minuto;5minutos;15minutos

            # status,id = API.buy_digital_spot(pareMoeda, entradas, direcoes, timesframe)

            # if status:
                # print(' Ordem aberta com sucesso')
                # break
            # else:
                # print(' Não executou a ordem!')
                # break

#PEGA AS CONFIGURAÇÕES
# print('\n\n')
# conf = configuracao()
# print(conf['paridade'])

print('\n - Seguir traders - \n')
# # name:
# # "live-deal-binary-option-placed"
# # "live-deal-digital-option"
while_run_time=10
name="live-deal-digital-option"
active="EURAUD"
_type="PT1M" #"PT1M"/"PT5M"/"PT15M"
buffersize=10
print("_____________subscribe_live_deal_______________")
API.subscribe_live_deal(name,active,_type,buffersize)

start_t=time.time()
while True:
    trades = API.get_live_deal(name,active,_type)
    print("__For_digital_option__ data size:"+str(len(trades)))
    print(trades)
    print("\n\n")
    time.sleep(1)
    # if time.time()-start_t>while_run_time:
        # break
    if len(trades) > 0:
        print(json.dumps(trades[0], indent=1))
print("_____________unscribe_live_deal_______________")
API.unscribe_live_deal(name,active,_type)

# Abrir ordem iq option opções digitais
# print('\n - Abrir ordem opções digitais - \n')

# pareMoeda = 'EURCAD'
# entradas = 100.00
# direcoes = 'call'#call pra cima put pra baixo
# timesframe = 1#1minuto;5minutos;15minutos

# status,id = API.buy_digital_spot(pareMoeda, entradas, direcoes, timesframe)

# if status:
    # print(' Ordem aberta com sucesso')
    # print(' Aguarde a ordem ser concluida')
# else:
    # print(' Não executou a ordem!')
    # sys.exit()

# if isinstance(id, int):
    #while True:
        # resultado,lucro = API.check_win_digital_v2(id)

        # if resultado:
            # if lucro > 0:
                # print(' RESULTADO: WIN / LUCRO: '+str(round(lucro,2)))
            # else:
                # print(' RESULTADO: LOSS / PERDA: '+str(entradas))
            # break
#força a saida
#sys.exit()

# Abrir ordem iq option opções binarias
# print('\n - Abrir ordem opções binarias - \n')

# parMoeda = 'AUDCAD-OTC'
# entrada = 100.00
# direcao = 'call'#call pra cima put pra baixo
# timeframe = 1

# status,id = API.buy(entrada, parMoeda, direcao, timeframe)

# if status:
    # resultado,lucro = API.check_win_v3(id)
    # print('RESULTADO: '+resultado+' / LUCRO: '+str(round(lucro, 2)))
    # #Exemplo para pegar resultado
    # # print(API.check_win_v3(id))
    # # print('\n')
    # # print(API.check_win_v4(id))

print('\n - Fim das operações - \n')