from flask import Flask
from flask import render_template

from flask import request
from abfragen import *

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route("/push")
def push():
    trainingsMethode("push")
    return render_template('training.html', training = trainingsplan("push"), art = "push")

@app.route("/pull")
def pull():
    trainingsMethode("pull")
    return render_template('training.html', training = trainingsplan("pull"), art = "pull")

@app.route("/beine")
def beine():
    trainingsMethode("beine")
    return render_template('training.html', training = trainingsplan("beine"), art = "beine")

@app.route("/ganzkörper")
def ganzkörper():
    trainingsMethode("ganzkörper")
    return render_template('training.html', training = trainingsplan("ganzkörper"), art = "ganzkörper")

@app.route("/analyse", methods = ['POST'])
def analyse():
    try:
        liste = request.form['liste']
        updateÜbung(liste)
        methode = getMethode()
    except:
        methode = getMethode()
    training = trainingsplan(methode)
    daten = getDaten()
    return render_template('analyse.html', training = training, daten = daten)

@app.route("/neuerTrainingsplan/<methode>", methods = ['POST', 'GET'])
def neuerTrainingsplan(methode):
    if methode == 'neueuebung':
        return render_template('neueuebung.html')
    elif methode == 'uebunganlegen':
        art = request.args['art']
        übung = request.args['übung']
        gewicht = request.args['gewicht']
        return render_template('uebungerstellt.html', training = neueÜbung(art, übung, gewicht), link = art)
    elif methode == 'erstellt':
        liste = request.form['liste']
        trainingsplanErstellen(liste)
        art = getMethode()
        return render_template('erstellt.html', link = art)
    elif methode == 'löschen':
        geloescht = request.form['del']
        delUebung(geloescht)

        art = getMethode()
        liste = training(art)
        übungsliste = []
        for übung in liste:
            übungsliste = übungsliste +[übung[0]]
        übungsliste.sort()

        return render_template('reihenfolge.html', training = übungsliste, art = art, delete = True, liste = geloescht)

    else:
        methode = getMethode()
        if methode == 'ganzkörper':
                methoden = ['push', 'pull', 'beine']
                übungslisteGes = []
                for methode in methoden:
                    liste = training(methode)
                    übungsliste = []
                    for übung in liste:
                        übungsliste = übungsliste + [übung[0]]
                    übungslisteGes = übungslisteGes + [übungsliste]
                return render_template('reihenfolgeGk.html', push = übungslisteGes[0], pull = übungslisteGes[1], beine = übungslisteGes[2], art = 'ganzkörper')
        else:
            liste = training(methode)
            übungsliste = []
            for übung in liste:
                übungsliste = übungsliste +[übung[0]]
            übungsliste.sort()

            return render_template('reihenfolge.html', training = übungsliste, art = methode)

if __name__ == "__main__":
    app.run()


import json

from django.contrib.auth.models import User
from django.db.models import Subquery, OuterRef
from rest_framework.test import APITestCase, APIRequestFactory
from rest_framework import status
from django.urls import reverse

from shoes.models import Brand, QtySize, Shoe, HomePageCarousel
from shoes.serializers import ShoeSerializer, HotDealsSerializer, CarouselSerializer

class ShoeAPITestCase(APITestCase):
    def setUp(self):
        self.maxDiff = None
        self.user = User.objects.create(username='test_user1')
        self.brand_1 = Brand.objects.create(name='Adidas')
        self.brand_2 = Brand.objects.create(name='Reebok')
        self.qty_1 = QtySize.objects.create(qty=6, size=38)
        self.qty_2 = QtySize.objects.create(qty=4, size=39)
        self.qty_3 = QtySize.objects.create(qty=5, size=37)
        self.shoe_1 = Shoe.objects.create(
            info='Some info about shoes, that we see on the product page.',
            name='Reebok Classic',
            image='http://127.0.0.1:8000/media/item_images/Reebok-Classic.jpg',
            type='low-top',
            price='220.00',
            sex='male',
            brand=self.brand_2,
            sale='0.30',
            views=2,
        )
        self.shoe_1.qty.set([self.qty_1, self.qty_2])
        self.shoe_2 = Shoe.objects.create(
            info='Some info about shoes, that we see on the product page.',
            name='Adidas Superstar',
            image='http://127.0.0.1:8000/media/item_images/Adidas-Super-Star.jpg',
            type='low-top',
            price='200.00',
            brand=self.brand_1,
            sex='female',
            sale='0.00',
            views=2,
        )
        self.shoe_2.qty.set([self.qty_3])
        self.carousel_1 = HomePageCarousel.objects.create(
            image='http://127.0.0.1:8000/media/item_images/Adidas-Super-Star.jpg',
            sequence=1
        )
        self.carousel_2 = HomePageCarousel.objects.create(
            image='http://127.0.0.1:8000/media/item_images/Reebok-Classic.jpg',
            sequence=2
        )

    def test_get_shoes(self):
        factory = APIRequestFactory()
        url = '/shoe/'
        request = factory.get(url)
        response = self.client.get(url)
        shoes = Shoe.objects.all().annotate(
            brand_name=Subquery(Brand.objects.filter(pk=OuterRef('brand_id')).values('name')[:1])
        ).prefetch_related('qty')
        serializer_data = ShoeSerializer(shoes, many=True, context={'request': request}).data
        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual(serializer_data, response.data)

    def test_get_hotdeals_shoes(self):
        factory = APIRequestFactory()
        url = '/hotdeals/'
        request = factory.get(url)
        response = self.client.get(url)
        hotdeals = Shoe.objects.order_by('-sale').annotate(
            brand_name=Subquery(Brand.objects.filter(pk=OuterRef('brand_id')).values('name')[:1])
        )[:9]
        serializer_data = HotDealsSerializer(hotdeals, many=True, context={'request': request}).data

        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual(serializer_data, response.data)

    def test_get_carousel_objects(self):
        factory = APIRequestFactory()
        url = '/carousel/'
        request = factory.get(url)
        response = self.client.get(url)
        carousel = HomePageCarousel.objects.all().order_by('sequence')[:9]
        serializer_data = CarouselSerializer(carousel, many=True, context={'request': request}).data

        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual(serializer_data, response.data)


import csv
from collections import defaultdict
import math

# open the file in universal line ending mode
states = {
    "AL": "Alabama",
    "AK": "Alaska",
    "AZ": "Arizona",
    "AR": "Arkansas",
    "CA": "California",
    "CO": "Colorado",
    "CT": "Connecticut",
    "DE": "Delaware",
    "FL": "Florida",
    "GA": "Georgia",
    "HI": "Hawaii",
    "ID": "Idaho",
    "IL": "Illinois",
    "IN": "Indiana",
    "IA": "Iowa",
    "KS": "Kansas",
    "KY": "Kentucky",
    "LA": "Louisiana",
    "ME": "Maine",
    "MD": "Maryland",
    "MA": "Massachusetts",
    "MI": "Michigan",
    "MN": "Minnesota",
    "MS": "Mississippi",
    "MO": "Missouri",
    "MT": "Montana",
    "NE": "Nebraska",
    "NV": "Nevada",
    "NH": "New Hampshire",
    "NJ": "New Jersey",
    "NM": "New Mexico",
    "NY": "New York",
    "NC": "North Carolina",
    "ND": "North Dakota",
    "OH": "Ohio",
    "OK": "Oklahoma",
    "OR": "Oregon",
    "PA": "Pennsylvania",
    "RI": "Rhode Island",
    "SC": "South Carolina",
    "SD": "South Dakota",
    "TN": "Tennessee",
    "TX": "Texas",
    "UT": "Utah",
    "VT": "Vermont",
    "VA": "Virginia",
    "WA": "Washington",
    "WV": "West Virginia",
    "WI": "Wisconsin",
    "WY": "Wyoming"
}
with open('C:/Users/Mateja/Desktop/701 Project/obamacare.csv', encoding="utf-8") as infile:
  # read the file as a dictionary for each row ({header : value})
  infile.readline()
  reader = csv.DictReader(infile)
  next(reader, None)
  data = {}
  for row in reader:
    for header, value in row.items():
        data.setdefault(header, list()).append(value)

# map the state to each vote, each YES will give a +1,
# each NO will give a -1 "Not Voting" will be ignored
voters_per_state = {}
#initiate the dictionary to all empty values
for state in states:
    voters_per_state[state] = {}
    # get the votes number for each party to see the overall voting pattern
    voters_per_state[state]['RY'] = 0 #republican yes
    voters_per_state[state]['RN'] = 0 #republican no
    voters_per_state[state]['DY'] = 0 #democrat yes
    voters_per_state[state]['DN'] = 0 #democrat no

    voters_per_state[state]['fillKey'] = []

all_votes = data['vote']
all_states = data['state']
all_parties = data['party']
i = 0
# loop through the vote/state array and add each to dictionary
while(i<len(all_votes)):
    if(all_votes[i] == 'Not Voting'):
        i+=1
        continue

    #append to the list if the
    if(all_votes[i] == 'Aye'):
        voters_per_state[all_states[i]]["fillKey"].append(1)
    else:
        voters_per_state[all_states[i]]["fillKey"].append(0)

    if(all_parties[i] == "Republican" and all_votes[i] == 'No'):
        voters_per_state[all_states[i]]["RN"] +=1

    elif(all_parties[i] == "Democrat" and all_votes[i] == 'No'):
        voters_per_state[all_states[i]]["DN"] +=1

    elif(all_parties[i] == "Republican" and all_votes[i] == 'Aye'):
        voters_per_state[all_states[i]]["RY"] +=1

    elif(all_parties[i] == "Democrat" and all_votes[i] == 'Aye'):
        voters_per_state[all_states[i]]["DY"] +=1

    i+=1

# convert the map into JSON!
import json
import copy

#import sentimentDict
with open('C:/Users/Mateja/Desktop/701 Project/obamacaretwitter.json') as json_data:
    twitter_dict = json.load(json_data)

combined_data = copy.deepcopy(voters_per_state)

# find the average between all the states
for state in voters_per_state.keys():
    #if the state has voter information, calculate the discrepancy score
    if (voters_per_state[state] != {'RY': 0, 'RN': 0, 'DY': 0, 'DN': 0, 'fillKey': 0.0}
        and twitter_dict[state] != "not available" and voters_per_state[state] != {'RY': 0, 'RN': 0, 'DY': 0, 'DN': 0, 'fillKey': [0]}):
        #calculate the average among all votes
        sum_of_votes = sum(voters_per_state[state]["fillKey"])
        len_of_votes = len(voters_per_state[state]["fillKey"])

        congress_sentiment = sum_of_votes / len_of_votes
        voters_per_state[state]["fillKey"] = congress_sentiment

        # calculate the percentage of dems who voted yes vs. republicans per state
        len_of_parties = voters_per_state[state]["DN"] + voters_per_state[state]["DY"] + voters_per_state[state]["RN"] + voters_per_state[state]["RY"]
        #calculate the percentage of democrats and republicans who voted how in each state

        #if there is no twitter data available we have to mark everything as unavailable
        if(twitter_dict[state]["fillKey"] != "not available"):
            combined_data[state]["fillKey"] = abs(twitter_dict[state]["fillKey"] - congress_sentiment)
        else:
            combined_data[state]["fillKey"] = "not available"

        if(len_of_parties == 0):
            continue
        combined_data[state]["DY"] = voters_per_state[state]['DY'] / len_of_parties
        combined_data[state]["RY"] = voters_per_state[state]['RY'] / len_of_parties
        combined_data[state]["RN"] = voters_per_state[state]['RN'] / len_of_parties
        combined_data[state]["DN"] = voters_per_state[state]['DN'] / len_of_parties

        #if there is no data in the preloaded or streamed set, we make all
        # the data unavailable

        #if(stream_dict[state] != "not available"):
        #    stream_data[state]["fillKey"] = abs(stream_dict[state] - congress_sentiment)
    else:
        #if the state has no information, label as not available
        print(state)
        combined_data[state]["fillKey"] = "not available"

        if(voters_per_state[state] == {'RY': 0, 'RN': 0, 'DY': 0, 'DN': 0, 'fillKey': 0.0} or voters_per_state[state] == {'RY': 0, 'RN': 0, 'DY': 0, 'DN': 0, 'fillKey': [0]}):
            voters_per_state[state]['fillKey'] = "not available"

#dump congress-only data to be toggled
with open('C:/Users/Mateja/Desktop/701 Project/obamacarecongress.json', 'w') as outfile:
    json.dump(voters_per_state, outfile)

#export all files in the appropriate format
with open('C:/Users/Mateja/Desktop/701 Project/obamacareboth.json', 'w') as outfile:
    json.dump(combined_data, outfile)

#with open('C:/Users/Mateja/Desktop/701 Project/healthcare.json', 'w') as outfile:
 #   json.dump(stream_data, outfile)


# rope physics
# rope has a head and a tail.
# head and tail occupy a space in a 2d grid.
# can occupy the same space
# it's a short rope. the head and tail should always be touching.
# every step, the head moves some distance in a cardinal direction.
# before the next step, the tail must catch up.
# will move diagonally until it is directly up/down/left/right. then move in cardinal direction until touching.
# how many spaces in the grid are visited by the tail??

from util import getLinesFromFile
from timeit import default_timer as timer

def isAdjacent(p1,p2):
  # unpack the coordinates
  x1, y1 = p1
  x2, y2 = p2

  # check if the coordinates are adjacent cardinally or diagonally, or overlapping
  return (x1 == x2 and y1 == y2) or (x1 == x2 and abs(y1 - y2) == 1) or (y1 == y2 and abs(x1 - x2) == 1) or (abs(x1 - x2) == 1 and abs(y1 - y2) == 1)

def move(pos,direction):
  """return new position"""
  if direction == 'U':
    return (pos[0], pos[1] + 1)
  elif direction == 'D':
    return (pos[0], pos[1] - 1)
  elif direction == 'L':
    return (pos[0] - 1, pos[1])
  elif direction == 'R':
    return (pos[0] + 1, pos[1])

def moveCloser(startPos, targetPos):
  s1, s2 = startPos
  t1, t2 = targetPos

  if s1 == t1: # share an x axis
    if s2 < t2:
      return (s1, s2 + 1)
    else:
      return (s1, s2 - 1)
  elif s2 == t2: # share a y axis
    if s1 < t1:
      return (s1 + 1, s2)
    else:
      return (s1 - 1, s2)
  elif s1 < t1 and s2 < t2: #SW
    return (s1 + 1, s2 + 1)
  elif s1 > t1 and s2 < t2: #SE
    return (s1 - 1, s2 + 1)
  elif s1 < t1 and s2 > t2: #NW
    return (s1 + 1, s2 - 1)
  elif s1 > t1 and s2 > t2: #NE
    return (s1 - 1, s2 - 1)

instructions = getLinesFromFile('./input.txt')

begin = timer()
start = (0,0)
headPos = start
tailPos = start
visited = set()
visited.add(start)
# part 1
for instr in instructions:
  direction, distance = instr.split()
  for step in range(int(distance)):
    headPos = move(headPos, direction)
    while not isAdjacent(headPos,tailPos):
      tailPos = moveCloser(tailPos,headPos)
      visited.add(tailPos)
result = len(visited)
end = timer()
print('part 1:',result, f'{(end-begin) * 1000000} µs')

# part 2: now rope has 10 knots. each adjacent to the next.
# same problem as before but with a longer rope.
# knots move in same fashion by needing to be asjacent to next knot.

rope = [start] * 10
visited = set()
visited.add(start)
begin = timer()
for instr in instructions:
  direction, distance = instr.split()
  for step in range(int(distance)):
    rope[0] = move(rope[0], direction) # move head
    lead = rope[0]
    for knotindex in range(1,len(rope)): # update position of each knot
      while not isAdjacent(lead,rope[knotindex]):
        rope[knotindex] = moveCloser(rope[knotindex],lead)
      lead = rope[knotindex]
    visited.add(lead)

result = len(visited)
end = timer()
print('part 2:',result, f'{(end-begin) * 1000000} µs')


from collections import deque
n,m=map(int,input().split())
board=list()
for _ in range(n):
  tmp=list(map(int,input()))
  board.append(tmp)

dis=[[0]*m for _ in range(n)]
Q=deque()
dis[0][0]=1
Q.append((0,0))

dx=[-1,0,1,0]
dy=[0,1,0,-1]
while Q:
  now=Q.popleft()
  for i in range(4):
    xx=now[0]+dx[i]
    yy=now[1]+dy[i]
    if 0<=xx<n and 0<=yy<m and board[xx][yy]==1:
      dis[xx][yy]=dis[now[0]][now[1]]+1
      board[xx][yy]=0
      Q.append((xx,yy))

print(dis[n-1][m-1])


__author__ = 'susperius'

def split_files(in_file, in_filename):
    pos = in_file.find("-" * 50 + "\r\n")
    if pos == -1:
        return None
    new_file = in_file[pos:]
    in_file = in_file[:pos]
    start_pos = new_file.find("NEW FILE:")
    end_pos = new_file.find("\r\n", start_pos)
    if start_pos == -1 or end_pos == -1:
        return None
    filename = new_file[start_pos:end_pos].split(":")[1]
    start_pos = new_file.find("-" * 50, end_pos)
    start_pos = new_file.find("\r\n", start_pos)
    start_pos += 2
    new_file = new_file[start_pos:]
    return {in_filename: in_file, filename: new_file}

def is_two_files(in_file):
    pos = in_file.find("-" * 50 + "\r\n")
    return True if pos >= 0 else False


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

HOST = "localhost"
PORT = 4223
UID = "XYZ" # Change XYZ to the UID of your Moisture Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_moisture import BrickletMoisture

# Callback function for moisture value reached callback
def cb_moisture_reached(moisture):
    print("Moisture Value: " + str(moisture))

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    m = BrickletMoisture(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Get threshold callbacks with a debounce time of 1 second (1000ms)
    m.set_debounce_period(1000)

    # Register moisture value reached callback to function cb_moisture_reached
    m.register_callback(m.CALLBACK_MOISTURE_REACHED, cb_moisture_reached)

    # Configure threshold for moisture value "greater than 200"
    m.set_moisture_callback_threshold(">", 200, 0)

    input("Press key to exit\n") # Use raw_input() in Python 2
    ipcon.disconnect()


from bookshop.domain.types import DomainModel, Relationship

from bookshop.sqlalchemy.model.Book import Book

review = DomainModel(
    external_identifier_map={
        'book_id': Relationship(
            sqlalchemy_model_class=Book,
            target_name='book',
            target_identifier_column='book_id',
            source_foreign_key_column='book_id',
            lazy=False,
            nullable=False,
        ),
    },
    identifier_column_name='review_id',
    relationship_keys=[
        'book',
    ],
    property_keys=[
        'review_id',
        'text',
        'book_id',
    ],
    json_translation_map={
        'review_id': 'id',
        'book_id': 'book',
    },
    eager_relationships=[
        'book',
    ],
)


import argparse
import cv2
from classifier import Classifier

# argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
                help="image to analyze")
ap.add_argument("-m", "--model", required=True,
                help="model file")
ap.add_argument("-l", "--label", required=True,
                help="label file")
args = vars(ap.parse_args())

CLASSIFIER = Classifier(args["model"], args["label"])
(name, confidence) = CLASSIFIER.predict(cv2.imread((args["image"])))
print("[INFO] I think the image is a {} with {:.2f}% confidence".format(name, confidence))


import numpy as np
import matplotlib.pyplot as plt

# Load the data in
cal_data = np.genfromtxt('2ndorder_balance_cal.csv', delimiter=',',skip_header=True)
# cal_data = np.genfromtxt('balance_cal.csv', delimiter=',',skip_header=True)

# H = cal_data[:,:6]

# variables and loop for standard deviation analysis by removing rows
# arrSize = np.size(H, axis=0) #array size
# devData = []
# devDataFx = []
# devDataFy = []
# devDataFz = []
# devDataMx = []
# devDataMy = []
# devDataMz = []
# iteration = []
# for i in range(arrSize):

    # delete = np.delete(cal_data,i,0)

# Extract the loads and the voltages
H = cal_data[:,:6]
R = cal_data[:,6:]

    # H = delete[:,:6]
    # R = delete[:,6:]

# Create the elongated R matrix
Rp = np.append(R,R*R,axis=1)
Rp = np.append(Rp,np.repeat(R[:,0][:,np.newaxis],5,axis=1)*R[:,1:],axis=1)
Rp = np.append(Rp,np.repeat(R[:,1][:,np.newaxis],4,axis=1)*R[:,2:],axis=1)
Rp = np.append(Rp,np.repeat(R[:,2][:,np.newaxis],3,axis=1)*R[:,3:],axis=1)
Rp = np.append(Rp,np.repeat(R[:,3][:,np.newaxis],2,axis=1)*R[:,4:],axis=1)
Rp = np.append(Rp,(R[:,4]*R[:,5])[:,np.newaxis],axis=1)

# Compute the coefficient matrix
# R2 = np.matmul(R.transpose(),R)
R2 = np.matmul(Rp.transpose(),Rp)
R2inv = np.linalg.inv(R2)
# Rinv = np.matmul(R2inv,R.transpose())
Rinv = np.matmul(R2inv,Rp.transpose())
C = np.matmul(Rinv,H)

# Get the modelled loads
# Hp = np.matmul(R,C)
Hp = np.matmul(Rp,C)

saveData = np.savetxt("C.csv", C, delimiter=",")

# Compute error (standard deviation)
err = np.sqrt((np.sum((Hp-H)**2,axis=0))/(H.shape[0]-1))
err_norm = (err / np.array([120,60,240,28,44,24]))*100

#     devData.append([i,err[0],err[1],err[2],err[3],err[4],err[5]])
#     devDataFx.append(err[0])
#     devDataFy.append(err[1])
#     devDataFz.append(err[2])
#     devDataMx.append(err[3])
#     devDataMy.append(err[4])
#     devDataMz.append(err[5])
#     iteration.append(i)

# saveData = np.savetxt("err.csv", devData, delimiter=",")

# # single component error evaluation
# plt.subplot(321)
# plt.title('Fx err')
# plt.plot(iteration, devDataFx)
# plt.subplot(325)
# plt.title('Fy err')
# plt.plot(iteration, devDataFy)
# plt.subplot(323)
# plt.title('Fz err')
# plt.plot(iteration, devDataFz)
# plt.subplot(322)
# plt.title('Mx err')
# plt.plot(iteration, devDataMx)
# plt.subplot(324)
# plt.title('My err')
# plt.plot(iteration, devDataMy)
# plt.subplot(326)
# plt.title('Mz err')
# plt.plot(iteration, devDataMz)
# plt.tight_layout()
# plt.show()

# Plot the results
spv = [321, 323, 325, 322, 324, 326]
ttv = ["Fx","Fy","Fz","Mx","My","Mz"]
for i, ind in enumerate(spv):
    plt.subplot(ind)
    plt.scatter(H[:,i], Hp[:,i])
    plt.plot([0,np.max(H[:,i])],[0,np.max(H[:,i])],"k--")
    plt.title('{0} Err:{1:0.2f}%FS'.format(ttv[i],err_norm[i]))
    plt.grid()
    plt.xlabel("Model")
    plt.ylabel("Original")
plt.tight_layout()
plt.show()


from model import TransformationNetwork, FeatureExtractor
from train import Trainer
from utils import save_image
from dataloader import load_image_dataloader, load_style_image
from config import Config

import argparse
import matplotlib.pyplot as plt
import torch
from torchvision import transforms
import os

def get_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('--test',
                        action='store_true',
                        help='Use this argument to test generator')

    parser.add_argument('--model_path',
                        help='Path to saved model')

    parser.add_argument('--content_image_path',
                        default=Config.content_path,
                        help='Path to content images')

    parser.add_argument('--style_image_path',
                        default=Config.style_path,
                        help='Path to style image')

    parser.add_argument('--model_save_path',
                        default=Config.model_save_path,
                        help='Path to save trained model')

    parser.add_argument('--test_image_path',
                        default=Config.test_image_path,
                        help='Path to test photo images, required if testing')

    parser.add_argument('--image_save_path',
                        default=Config.image_save_path)

    parser.add_argument('--num_epochs',
                        type=int,
                        default=Config.num_epochs,
                        help='Number of training epochs')

    parser.add_argument('--lr',
                        type=float,
                        default=Config.lr,
                        help='Learning rate')

    parser.add_argument('--batch_size',
                        type=int,
                        default=Config.batch_size,
                        help='batch size')

    parser.add_argument('--style_weight',
                        type=float,
                        default=Config.style_weight,
                        help='weight value to be multiplied to style loss')

    parser.add_argument('--content_weight',
                        type=float,
                        default=Config.content_weight,
                        help='weight value to be multiplied to content loss')

    args = parser.parse_args()

    return args

def load_network(network, model_path):
    ckpt = torch.load(model_path, map_location=Config.device)
    network.load_state_dict(ckpt['network_state_dict'])

def generate_and_save_images(network, test_image_loader, save_path):
    network.eval()
    tensor_to_image = transforms.Compose([
        transforms.Normalize(mean=(-1, -1, -1), std=(2, 2, 2)),  # [-1, 1] to [0, 1]
        transforms.ToPILImage()
    ])

    image_ix = 0
    for test_images, _ in test_image_loader:
        test_images = test_images.to(Config.device)
        generated_images = network(test_images).detach().cpu()

        for i in range(len(generated_images)):
            image = generated_images[i]
            image = tensor_to_image(image)
            image.save(os.path.join(save_path, '{0}.jpg'.format(image_ix)))
            image_ix += 1

def main():
    args = get_args()

    device = Config.device
    print("PyTorch running with device {0}".format(device))

    print("Creating transformation network...")
    network = TransformationNetwork().to(device)

    if args.test:
        assert args.model_path, '--model_path must be provided for testing'
        print('Testing...')
        network.eval()

        print("Loading transformation network...")
        load_network(network, args.model_path)

        test_image_loader = load_image_dataloader(args.test_image_path, batch_size=Config.batch_size * 2, shuffle=False)
        if not os.path.isdir(args.image_save_path):
            os.makedirs(args.image_save_path)

        print("Generating images...")
        generate_and_save_images(network, test_image_loader, args.image_save_path)

    else:
        # Training!
        print("Training...")

        print("Loading feature extractor")
        feature_extractor = FeatureExtractor()

        # load dataloader
        print("Loading data")
        content_image_dataloader = load_image_dataloader(args.content_image_path, batch_size=args.batch_size)
        style_image = load_style_image(args.style_image_path)

        print("Loading Trainer")
        trainer = Trainer(network, feature_extractor, content_image_dataloader, style_image, lr=args.lr)
        if args.model_path:
            trainer.load_checkpoint(args.model_path)

        print("Start training")
        loss_hist = trainer.train(num_epochs=args.num_epochs)

        if not os.path.isdir(args.model_save_path):
            os.makedirs(args.model_save_path)
        trainer.save_checkpoint(os.path.join(args.model_save_path, 'epoch-{0}.ckpt'.format(args.num_epochs)))

        plt.plot(loss_hist, label='Loss')
        plt.legend()
        plt.savefig('StyleTransfer_train_history.jpg')
        plt.show()

if __name__== '__main__':
    main()


from dataclasses import dataclass
import numpy as np
import matplotlib.pyplot as plt
import os

@dataclass
class SVD:
    A: np.ndarray
    N: np.ndarray
    alpha: float = 0.1
    beta: float = 0.9
    sigma: float = 1e-4
    rho: float = 0.9
    itemax: int = 3000
    eps: float = 1e-9

    def F(self, U, V):
        return -np.trace(U.T @ self.A @ V @ self.N)

    def F_opt(self, S, N):
        p = N.shape[0]
        S = S[:p, :p]
        return -np.trace(S @ N)

    def Sym(self, X):
        return (X + X.T) / 2

    def qf(self, X):
        Q, _ = np.linalg.qr(X)
        return Q

    def calc_xi(self, U, V):
        return self.A @ V @ self.N - U @ self.Sym(U.T @ self.A @ V @ self.N)

    def calc_eta(self, U, V):
        return self.A.T @ U @ self.N - V @ self.Sym(V.T @ self.A.T @ U @ self.N)

    def R(self, xi, eta, U, V):
        """Returns the value of retraction at (U, V)

        Args:
            xi (numpy.ndarray): The point on the tangent space at (U, V)
            eta (numpy.ndarray): The point on the tangent space at (U, V)
            U (numpy.ndarray): The current point
            V (numpy.ndarray): The current point

        Returns:
            A retraction R on St(p, m) * St(p, n) at (U, V).
        """
        return (self.qf(U + xi), self.qf(V + eta))

    def gradF(self, U, V):
        """Calculation of gradient of F.

        Calculation the value of gradient of F at (U, V).

        Args:
            U (numpy.ndarray): The current point
            V (numpy.ndarray): The current point

        Returns:
            numpy.ndarray: grad of F at (U, V)
        """
        return (-self.calc_xi(U, V), -self.calc_eta(U, V))

    def inner_product_at_UV(self, U, V, xi, eta):
        """Calculation of inner product.

        Calculation the value of <grad f(U, V), (xi, eta)>_(U, V),
        where (U, V) and (xi, eta) are a current point and a search direction, respectively.

        Args:
            U (numpy.ndarray): The current point
            V (numpy.ndarray): The current point
            xi (numpy.ndarray): The descent vector
            eta (numpy.ndarray): The descent vector

        Returns:
            numpy.ndarray: <grad f(U, V), (xi, eta)>_(U, V)
        """
        gradF_x, gradF_y = self.gradF(U, V)
        return np.trace(gradF_x.T @ xi) + np.trace(gradF_y.T @ eta)

    def vector_transport_P(self, zeta, chi, xi, eta, U, V):
        return (zeta - self.qf(U + xi) @ self.Sym(self.qf(U + xi).T @ zeta),
                chi - self.qf(V + eta) @ self.Sym(self.qf(V + eta).T @ chi))

    def norm_grad(self, U, V):
        gradF_x, gradF_y = self.gradF(U, V)
        return np.sqrt(np.trace(gradF_x.T @ gradF_x) + np.trace(gradF_y.T @ gradF_y))

    def armijo_rule(self, U, V, xi, eta, c):
        R_xi, R_eta = self.R(c * xi, c * eta, U, V)
        left = self.F(U, V) - self.F(R_xi, R_eta)
        right = -self.sigma * self.inner_product_at_UV(U, V, c * xi, c * eta)
        return left >= right

    def wolfe_rule(self, U, V, xi, eta, c):
        R_xi, R_eta = self.R(c * xi, c * eta, U, V)
        a, b = self.vector_transport_P(R_xi, R_eta, xi, eta, U, V)
        left = self.inner_product_at_UV(R_xi, R_eta, a, b)
        right = self.rho * self.inner_product_at_UV(U, V, xi, eta)
        return left >= right

    def backtrack(self, U, V, xi, eta):
        """A backtraking algorithm.

        Args:
            U (numpy.ndarray): The current point
            V (numpy.ndarray): The current point
            xi (numpy.ndarray): The descent vector
            eta (numpy.ndarray): The descent vector

        Returns:
            c (float): The stepsize satisfying wolfe rule.
        """
        m = 1
        c = pow(self.beta, m) * self.alpha
        while self.armijo_rule(U, V, xi, eta, c) == False or self.wolfe_rule(U, V, xi, eta, c) == False:
            m += 1
            c = pow(self.beta, m) * self.alpha
            if c < 1e-7:
                break
        return c

    def save_F(self, data, filename):
        path = os.path.dirname(__file__) + filename
        with open(path, 'a') as f:
            np.savetxt(data)

    def steepest_descent(self, U0, V0, verbose=False):
        """Riemannian steepest desent algorithm.

        Args:
            U0 (numpy.ndarray): An initial guess of the problem to be solved.
            V0 (numpy.ndarray): An initial guess of the problem to be solved.
            verbose (bool): A log level.

        Returns:
            Uk (numpy.ndarray): The optimal solution.
            Vk (numpy.ndarray): The optimal solution.
        """
        Uk = U0
        Vk = V0
        for i in range(self.itemax):
            # compute the search direction
            xik = self.calc_xi(Uk, Vk)
            etak = self.calc_eta(Uk, Vk)
            # compute stepsize
            tk = self.backtrack(Uk, Vk, xik, etak)
            # compute the next iterate
            U_next = self.qf(Uk + tk * xik)
            V_next = self.qf(Vk + tk * etak)
            if verbose:
                if i % (self.itemax // 10) == 0:
                    print(i, ':\t', self.norm_grad(xik, etak), self.F(U_next, V_next))
            # stopping_criterion
            if self.norm_grad(xik, etak) < self.eps:
                break
            Uk = U_next
            Vk = V_next
        return Uk, Vk

    def cg(self, U0, V0, verbose=False):
        """
        Args:
            U0 (numpy.ndarray): An initial guess of the problem to be solved.
            V0 (numpy.ndarray): An initial guess of the problem to be solved.
            verbose (bool): A log level.

        Returns:
            Uk (numpy.ndarray): The optimal solution.
            Vk (numpy.ndarray): The optimal solution.
        """
        xik = self.calc_xi(U0, V0)
        etak = self.calc_eta(U0, V0)
        bar_xik = -xik
        bar_etak = -etak
        Uk = U0
        Vk = V0
        for i in range(self.itemax):
            # 4. compute stepsize
            tk = self.backtrack(Uk, Vk, xik, etak)
            print(i, ":\t", tk)
            # 4. set
            U_next = self.qf(Uk + tk * xik)
            V_next = self.qf(Vk + tk * etak)
            # 5. compute zeta, chi
            zeta = bar_xik  - self.qf(Uk + tk * xik)  @ self.Sym(self.qf(Uk + tk * xik).T  @ bar_xik)
            chi  = bar_etak - self.qf(Vk + tk * etak) @ self.Sym(self.qf(Vk + tk * etak).T @ bar_etak)
            # 5. compute bar_xik_next, bar_etak_next
            bar_xik_next, bar_etak_next = self.gradF(U_next, V_next)
            # 6. compute beta
            beta = np.trace(bar_xik_next.T @ (bar_xik_next - zeta)) + np.trace(bar_etak_next.T @ (bar_etak_next - chi)) / (np.trace(bar_xik.T @ bar_xik) + np.trace(bar_etak.T @ bar_etak))
            # 7. set
            xik_next = -bar_xik_next + beta * (xik - self.qf(Uk + tk * xik) @ self.Sym(self.qf(Uk + tk * xik).T @ xik))
            etak_next = -bar_etak_next + beta * (etak - self.qf(Vk + tk * etak) @ self.Sym(self.qf(Vk + tk * etak).T @ etak))
            if verbose:
                if i % (self.itemax // 10) == 0:
                    print(i, ':\t', self.norm_grad(xik_next, etak_next), self.F(U_next, V_next))
            # stopping_criterion
            if self.norm_grad(xik_next, etak_next) < self.eps:
                break
            # set
            Uk = U_next
            Vk = V_next
            bar_xik = bar_xik_next
            bar_etak = bar_etak_next
            xik = xik_next
            etak = etak_next
        return Uk, Vk


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

# In[1]:

from collections import deque

# In[2]:

class Graph:
    def __init__(self, num_intersection, num_street):
        self.num_intersections = num_intersection
        self.num_street = num_street
        self.graph = dict()
        self.incoming_streets = dict()
        self.streets_length = dict()

    def add_street(self, begin, end, length, street_index):
        self.graph.setdefault(begin, []).append((street_index, end))
        self.incoming_streets.setdefault(end, []).append((street_index, begin))
        self.streets_length[(begin, end)] = length
        self.streets_length[street_index] = length

    def get_incoming_streets(self, intersection):
        if intersection in self.incoming_streets:
            return [x[0] for x in self.incoming_streets[intersection]]
        else: return []

    def get_outgoing_streets(self, intersection):
        if intersection in self.graph:
            return [x[0] for x in self.graph[intersection]]
        else: return []

    def get_outgoing_intersections(self, intersection):
        if intersection in self.graph:
            return [x[1] for x in self.graph[intersection]]
        else: return []

    def get_intersections(self):
        return list(range(self.num_intersections))

    def get_dict_intersection_to_streets(self):
        intersections = self.get_intersections()
        ret_dict = {}
        for intersection in intersections:
            ret_dict[intersection] = self.get_incoming_streets(intersection)
        return ret_dict

# In[3]:

def readTraffic(path):
    f = open(path, 'r')
    D, I, S, V, F = map(int, f.readline().split())

    street2idx = dict()
    idx2street = dict()

    street_map = Graph(I, S)

    B = E = L = 0
    for i in range(S):
        B, E, street_name, L = f.readline().split()
        B = int(B)
        E = int(E)
        L = int(L)
        street_map.add_street(B, E, L, i)
        street2idx[street_name] = i
        idx2street[i] = street_name

    cars_path = dict()
    for i in range(V):
        path_len, path = f.readline().split(" ", 1)
        for street in path.split():
            cars_path.setdefault(i, deque([])).append(street2idx[street])

    return D, I, S, V, F, street2idx, idx2street, cars_path, street_map


#
# @lc app=leetcode.cn id=834 lang=python3
#
# [834] 树中距离之和
#

# @lc code=start
from typing import List, Optional
class Solution:
    def adjlist2tree(self, start: int, father: Optional[int] = None):
        if father in self.tree[start]: self.tree[start].remove(father)
        for t in self.tree[start]: self.adjlist2tree(t, start)

    def dfs0(self, start: int):
        for t in self.tree[start]:
            self.dfs0(t)
            self.sz[start] += self.sz[t]
            self.dp[start] += self.dp[t] + self.sz[t]

    def swap_root(self, child: int, root: int):
        '''assuming `dp` and `sz` are initialized with `root` being root'''
        self.dp[root] -= self.dp[child] + self.sz[child]
        self.sz[root] -= self.sz[child]
        self.sz[child] += self.sz[root]
        self.dp[child] += self.dp[root] + self.sz[root]

        self.ret[child] = self.dp[child]
        for child1 in self.tree[child]:
            self.swap_root(child1, child)

        self.dp[child] -= self.dp[root] + self.sz[root]
        self.sz[child] -= self.sz[root]
        self.sz[root] += self.sz[child]
        self.dp[root] += self.dp[child] + self.sz[child]

    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        self.tree = [set() for _ in range(n)]
        for s, t in edges: self.tree[s].add(t), self.tree[t].add(s)
        self.adjlist2tree(0)

        self.dp, self.sz, self.ret = [0] * n, [1] * n, [None] * n
        self.dfs0(0)
        self.ret[0] = self.dp[0]

        for child in self.tree[0]:
            self.swap_root(child, 0)

        return self.ret

# @lc code=end

print(Solution().sumOfDistancesInTree(n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]))
print(Solution().sumOfDistancesInTree(n = 1, edges = []))
print(Solution().sumOfDistancesInTree(n = 2, edges = [[1,0]]))


#!/usr/bin/env python3

# USAGE
# python real_time_object_detection.py

# import the necessary packages
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import rospy
import numpy as np
import argparse
import imutils
import time
import cv2
import pygame

#initialize the music play mode
pygame.mixer.init()
pygame.mixer.music.load("hey.mp3")

def play_sounds():
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.play()

# initialize the list of class labels MobileNet SSD was trained to
# detect, then generate a set of bounding box colors for each class

CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor"]

# CLASSES = ["person"]
COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe("MobileNetSSD_deploy.prototxt.txt", "MobileNetSSD_deploy.caffemodel")

def callback(ros_image):
	#frame = vs.read()
	bridge = CvBridge()
	try:
		img = bridge.imgmsg_to_cv2(ros_image, "bgr8")
	except CvBridgeError:
		print(CvBridgeError)
	frame = img
	frame = imutils.resize(frame, width=400)

	# grab the frame dimensions and convert it to a blob
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),
		0.007843, (300, 300), 127.5)

	# pass the blob through the network and obtain the detections and
	# predictions
	net.setInput(blob)
	detections = net.forward()

	# loop over the detections
	for i in np.arange(0, detections.shape[2]):
		# extract the confidence (i.e., probability) associated with
		# the prediction
		confidence = detections[0, 0, i, 2]

		# filter out weak detections by ensuring the `confidence` is
		# greater than the minimum confidence
		if confidence > 0.2:
			# extract the index of the class label from the
			# `detections`, then compute the (x, y)-coordinates of
			# the bounding box for the object
			idx = int(detections[0, 0, i, 1])
			box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
			(startX, startY, endX, endY) = box.astype("int")

			# draw the prediction on the frame
			label = "{}: {:.2f}%".format(CLASSES[idx],
				confidence * 100)
			if idx == 15:  # person
				cv2.rectangle(frame, (startX, startY), (endX, endY),
					COLORS[idx], 2)
				print("hey")
				play_sounds()

			#y = startY - 15 if startY - 15 > 15 else startY + 15
			#cv2.putText(frame, label, (startX, y),
			#	cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)

	# show the output frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF

rospy.init_node('detection_listener', anonymous=True)
rospy.Subscriber("/camera/rgb/image_raw", Image, callback)
rospy.spin()

# do a bit of cleanup
cv2.destroyAllWindows()


"""
Эффект Барнума
Для того чтобы высчитать число вашего рождения, надо сложить числа в вашей дате рождения, чтобы в результате
получилась цифра от 1 до 9.
Например, дата вашего рождения -– 12.03.1985. Значит, число вашего рождения равно сумме всех
этих чисел. 1+2+0+3+1+9+8+5=29
Приводим эту цифру к однозначной путем сложения: 2+9=11; 1+1=2 Таким образом, число вашего рождения равно двум.
Пользователь вводит тремя инпутами:
Год рождения
Месяц рождения
День рождения
Программа вычисляет цифру и сообщает ее.
"""

year = input('Введите год рождения: ')
month = input('Введите месяц рождения: ')
day = input('Введите день рождения: ')

string = year + month + day
while len(string) != 1:
    tmp = 0
    for ch in string:
        tmp += int(ch)
    string = str(tmp)

print(string)

SkyPro/Урок 3. Задания со звездочкой/07.py


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import sys
import tensorflow as tf
import numpy as np
import argparse
import os

def Affine(name_scope,input_tensor,out_channels, relu=True):
    input_shape = input_tensor.get_shape().as_list()
    input_channels = input_shape[-1]
    with tf.name_scope(name_scope):
        weights = tf.Variable(tf.truncated_normal([input_channels, out_channels],
                                                  stddev=1.0 / math.sqrt(float(input_channels))),
                              name='weights')
        biases = tf.Variable(tf.zeros([out_channels]),name='biases')
        h = tf.matmul(input_tensor, weights) + biases
        if relu: return tf.nn.relu(h)
        else: return h

def get_batch(bs,len_subset,N):
    X = 1.0-2*(np.random.randn(bs,N) < 0).astype(np.float32)
    relevant_X = X[:,:len_subset] # Assume that v^* has all its 1's at the prefix
    if len_subset==1: relevant_X = relevant_X[:,np.newaxis]
    Y = np.prod(relevant_X, axis=1)[:,np.newaxis]
    return X,Y

def run_training(args):
    print('Parity d=%d'%(args.d))
    len_subset = np.sum(np.random.randn(args.d)>0) if args.subset_size < 0 else args.subset_size
    with tf.Graph().as_default():
        session = tf.Session()
        # These will be inserted as single images
        X_placeholder = tf.placeholder(tf.float32, shape=(None,args.d))
        Y_placeholder = tf.placeholder(tf.float32, shape=(None,1))

        p1 = Affine('p1', X_placeholder, 10*args.d, relu=True)
        score = Affine('score', p1, 1, relu=False)
        # Hinge loss
        loss = tf.reduce_mean(tf.nn.relu(1.0 - Y_placeholder*score))

        accuracy = tf.reduce_mean(tf.cast(Y_placeholder*score>0,tf.float32))
        optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
        train_op = optimizer.minimize(loss)

        session.run(tf.initialize_all_variables())
        for step in xrange(args.num_iters):
            X,Y = get_batch(args.batch_size,len_subset,args.d)
            _ = session.run(train_op,feed_dict={X_placeholder: X, Y_placeholder: Y})
            if (step % args.print_freq == 0) or step+1 == args.num_iters:
                X,Y = get_batch(500,len_subset,args.d)
                fd = {X_placeholder: X, Y_placeholder: Y}
                print('\nIteration %d' % (step))
                loss_,accuracy_ = session.run([loss,accuracy],feed_dict=fd)
                print('Iteration %d loss %.4f accuracy %.4f'%(step,loss_,accuracy_))

def main(args):
    run_training(args)

def get_command_line_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--d", default=100, type=int, help='input dimension')
    parser.add_argument("--num_iters", default=50000, type=int, help='number of iterations')
    parser.add_argument("--print_freq", default=100, type=int, help='print frequency')
    parser.add_argument("--learning_rate", default=0.01, type=float, help='learning rate')
    parser.add_argument("--batch_size", default=128, type=int, help='batch size')
    parser.add_argument("--subset_size", default=-1, type=int, help='size of subset for parity (explicitly, \
                                                                        sum(v^*==1), see paper section 2.1 for notation). \
                                                                        Negative value will result in random.')
    args = parser.parse_args()
    return args

if __name__ == '__main__':
    main(get_command_line_args())


import datetime
from unittest import mock
import urllib.parse

from absl.testing import absltest
from google.oauth2 import credentials as authorized_user
from google.oauth2 import service_account
from protorpc import protojson

from multitest_transport.api import api_test_util
from multitest_transport.api import build_channel_api
from multitest_transport.models import build
from multitest_transport.models import messages
from multitest_transport.models import ndb_models
from multitest_transport.plugins import base as plugins
from multitest_transport.util import file_util

class AndroidBuildProvider(plugins.BuildProvider):
  """Dummy build provider for testing."""
  name = 'Android'
  mock = mock.MagicMock()
  build_item_path_type = plugins.BuildItemPathType.DIRECTORY_FILE

  def __init__(self):
    super(AndroidBuildProvider, self).__init__()
    self.AddOptionDef('mock_option')

  def GetBuildItem(self, path):
    return self.mock.GetBuildItem(path)

class GoogleDriveBuildProvider(plugins.BuildProvider):
  """Dummy build provider for testing."""
  name = 'Google Drive'
  build_item_path_type = plugins.BuildItemPathType.DIRECTORY_FILE

class BuildChannelApiTest(api_test_util.TestCase):

  def setUp(self):
    super(BuildChannelApiTest, self).setUp(build_channel_api.BuildChannelApi)

  def _CreateMockBuildChannel(self, name='android', provider='Android'):
    return build.AddBuildChannel(name, provider, {})

  def testList(self):
    self._CreateMockBuildChannel(name='android', provider='Android')
    self._CreateMockBuildChannel(name='drive', provider='Google Drive')

    res = self.app.get('/_ah/api/mtt/v1/build_channels')
    build_channel_list = protojson.decode_message(
        messages.BuildChannelList, res.body)

    # verify that the right channels are returned
    build_channels = build_channel_list.build_channels
    self.assertEqual(2, len(build_channels))
    self.assertItemsEqual(['android', 'drive'], [
        channel.name for channel in build_channels])
    self.assertItemsEqual(['Android', 'Google Drive'], [
        channel.provider_name for channel in build_channels])

  def testGet(self):
    config = self._CreateMockBuildChannel()

    res = self.app.get('/_ah/api/mtt/v1/build_channels/%s' % config.key.id())
    build_channel_config = protojson.decode_message(messages.BuildChannelConfig,
                                                    res.body)

    # verify that the right channel is returned
    self.assertEqual(config.key.id(), build_channel_config.id)
    self.assertEqual('android', build_channel_config.name)

  def testGet_notFound(self):
    # unknown build channel ID
    res = self.app.get('/_ah/api/mtt/v1/build_channels/%s' % 666,
                       expect_errors=True)
    # throws if channel not found
    self.assertEqual('404 Not Found', res.status)

  @mock.patch.object(build.BuildChannel, 'ListBuildItems')
  def testListBuildItems(self, mock_channel):
    # create placeholders build items to return from channel
    build_items = [
        plugins.BuildItem(name='item1', path=u'path1', is_file=True),
        plugins.BuildItem(name='item2', path=u'path2', is_file=True)
    ]
    mock_channel.return_value = build_items, 'next_page_token'
    config = self._CreateMockBuildChannel()

    res = self.app.get(
        '/_ah/api/mtt/v1/build_channels/%s/build_items' % config.key.id())
    build_item_list = protojson.decode_message(messages.BuildItemList, res.body)

    # verify same build items are returned
    self.assertEqual('next_page_token', build_item_list.next_page_token)
    self.assertItemsEqual(['item1', 'item2'], [
        item.name for item in build_item_list.build_items])

  def testListBuildItems_notFound(self):
    # unknown build channel ID
    res = self.app.get('/_ah/api/mtt/v1/build_channels/%s/build_items' % 666,
                       expect_errors=True)
    # throws if channel not found
    self.assertEqual('404 Not Found', res.status)

  def testLookupBuildItem(self):
    config = self._CreateMockBuildChannel(name='android', provider='Android')
    url = 'mtt:///%s/path/to/file.ext' % config.key.id()
    build_item = plugins.BuildItem(
        name='foo',
        path='zzz/bar/foo',
        is_file=True,
        size=1234,
        timestamp=datetime.datetime.utcnow())
    AndroidBuildProvider.mock.GetBuildItem.return_value = build_item

    res = self.app.get(
        '/_ah/api/mtt/v1/build_channels/build_item_lookup?url=%s' % (
            urllib.parse.quote(url)))
    build_item_msg = protojson.decode_message(messages.BuildItem, res.body)

    AndroidBuildProvider.mock.GetBuildItem.assert_called_once_with(
        'path/to/file.ext')
    self.assertEqual(
        messages.Convert(build_item, messages.BuildItem), build_item_msg)

  @mock.patch.object(file_util.FileHandle, 'Get')
  def testLookupBuildItem_withHttpUrl(self, mock_find_handle_get):
    url = 'http://foo.com/bar/zzz/file.ext?foo=bar'
    mock_file_handle = mock.MagicMock()
    mock_find_handle_get.return_value = mock_file_handle
    mock_file_info = file_util.FileInfo(
        url=url,
        is_file=True,
        total_size=1234,
        timestamp=datetime.datetime.utcnow())
    mock_file_handle.Info.return_value = mock_file_info

    res = self.app.get(
        '/_ah/api/mtt/v1/build_channels/build_item_lookup?url=%s' % (
            urllib.parse.quote(url)))
    build_item_msg = protojson.decode_message(messages.BuildItem, res.body)

    mock_find_handle_get.assert_called_once_with(url)
    mock_file_handle.Info.assert_called_once()
    self.assertEqual('file.ext', build_item_msg.name)
    self.assertEqual(mock_file_info.is_file, build_item_msg.is_file)
    self.assertEqual(mock_file_info.total_size, build_item_msg.size)
    self.assertEqual(mock_file_info.timestamp, build_item_msg.timestamp)

  def testDelete(self):
    # create build channel and confirm it exists
    config = self._CreateMockBuildChannel()
    self.assertIsNotNone(config.key.get())

    # delete channel and verify that it no longer exists
    self.app.delete('/_ah/api/mtt/v1/build_channels/%s' % config.key.id())
    self.assertIsNone(config.key.get())

  def testCreate(self):
    data = {
        'name': 'testName',
        'id': '',
        'provider_name': 'Android',
        'options': [{
            'name': 'mock_option',
            'value': '123123123'
        }]
    }
    res = self.app.post_json('/_ah/api/mtt/v1/build_channels', data)
    msg = protojson.decode_message(messages.BuildChannelConfig, res.body)
    build_channel_config = messages.ConvertToKey(ndb_models.BuildChannelConfig,
                                                 msg.id).get()
    self.assertIsNotNone(build_channel_config)
    self.assertEqual(data['name'], build_channel_config.name)
    self.assertEqual(data['provider_name'], build_channel_config.provider_name)
    self.assertEqual(data['options'][0]['name'],
                     build_channel_config.options[0].name)

  def testUpdate(self):
    build_channel_config = self._CreateMockBuildChannel()
    build_channel_config_id = str(build_channel_config.key.id())
    data = {
        'id': build_channel_config_id,
        'name': 'bar',
        'provider_name': 'Android'
    }
    res = self.app.put_json(
        '/_ah/api/mtt/v1/build_channels/%s' % build_channel_config_id, data)

    build_channel_config = build_channel_config.key.get()
    msg = protojson.decode_message(messages.BuildChannelConfig, res.body)
    self.assertEqual(
        messages.Convert(build_channel_config, messages.BuildChannelConfig),
        msg)
    self.assertEqual(data['name'], build_channel_config.name)

  @mock.patch.object(service_account.Credentials, 'from_service_account_info')
  def testAuthorizeConfigWithServiceAccount(self, mock_parse_key):
    """Tests that a build channel can be authorized with a service account."""
    config = self._CreateMockBuildChannel(name='android', provider='Android')
    # Mock parsing service account JSON key
    mock_parse_key.return_value = service_account.Credentials(None, None, None)
    # Verify that credentials were obtained and stored
    self.app.put_json(
        '/_ah/api/mtt/v1/build_channels/%s/auth' % config.key.id(),
        {'value': '{}'})
    config = ndb_models.BuildChannelConfig.get_by_id(config.key.id())
    self.assertIsNotNone(config.credentials)

  def testAuthorizeWithServiceAccount_notFound(self):
    """Tests that an error occurs when a build channel is not found."""
    response = self.app.put_json(
        '/_ah/api/mtt/v1/build_channels/%s/auth' % 'unknown', {'value': '{}'},
        expect_errors=True)
    self.assertEqual('404 Not Found', response.status)

  def testUnauthorize(self):
    """Tests that a build channel can be unauthorized."""
    config = self._CreateMockBuildChannel(name='android', provider='Android')
    config.credentials = authorized_user.Credentials(None)
    config.put()
    # Verify that credentials were removed
    self.app.delete('/_ah/api/mtt/v1/build_channels/%s/auth' % config.key.id())
    config = ndb_models.BuildChannelConfig.get_by_id(config.key.id())
    self.assertIsNone(config.credentials)

  def testUnauthorize_notFound(self):
    """Tests that an error occurs when a build channel is not found."""
    response = self.app.delete(
        '/_ah/api/mtt/v1/build_channels/%s/auth' % 'unknown',
        expect_errors=True)
    self.assertEqual('404 Not Found', response.status)

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


from config import *
from contextual_bot import *

def FLM_getFile(contextual_bot, sh_core, fileName):
    data = open(mapPath+fileName, "r").read()
    if len(data.split('\n')) < 10:
        contextual_bot.reply(ContextualBot.TEXT, data)
    else:
        contextual_bot.reply(ContextualBot.DOCUMENT, open(mapPath+fileName, 'rb'))

def FLM_addLine(contextual_bot, sh_core, fileName):
    txt = contextual_bot.getText()
    i = 0
    while (i+1 < len(txt) and txt[i] != ' '):
        i+=1
    txt = txt[i+1:].split('\n')[0]
    reply = contextual_bot.getReplyText()
    if len(reply) > 1:
        # Yeah baby, add a space
        txt = reply + " " + txt
    # Yeah baby, send the message only when it is longer than 1
    if len(txt) > 1:
        f = open(mapPath+fileName, "a")
        f.write(txt.strip("\n")+"\n")
        f.close()
        contextual_bot.reply(ContextualBot.TEXT, "Ok")
    else:
        # Yeah baby, this code is executed when the dumb user do something stupid
        contextual_bot.reply(ContextualBot.TEXT, "Ptdr tu sais pas utiliser la commande")

# Yeah baby, adding "yeah baby" is strange and the guy reading this will ask so many questions about the guy who wrote that shitty code, but, yeah baby, it works !


#Import python modules
import matplotlib.pyplot as plt
import numpy as np
import time

#Create variables
x_val = []
a_val = []
a = 1

print("This script will be creating a simple bifurcation logistic map.")

time.sleep(1)

print("Once the graph is generated it will display on the screen and be saved.")

while a < 4:
    xold = 0.5

    #Ignore first 100 iterations to get to steady-state
    for i in range(100):
        xnew = (a*xold)*(1-xold)
        xold = xnew

   #These are the results to record
    for i in range(100):
        xnew = (a*xold)*(1-xold)
        xold = xnew
        a_val.append(a)
        x_val.append(xnew)

    a+=0.001
z = np.arange(len(a_val))

# Define the colormap
cmap = plt.get_cmap('jet')

#Create plot with recorded data
plt.scatter(a_val, x_val, s = 0.1, c=z, cmap=cmap)
plt.xlabel("a")
plt.ylabel("x")
plt.title("Bifurcation Logistic Map")
plt.savefig('bifurcation-logisitic-map.png')
plt.show()

time.sleep(1)
print("Graph was saved as 'bifurcation-logisitic-map.png'. Thank you!")


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

import time
import requests
from bs4 import BeautifulSoup
from bs4.element import NavigableString, Tag
import pandas as pd

def main():
  """_summary_
  Amazonの売れ筋ランキングページからカテゴリ別に商品名とURLをcsvに出力する。
  """

  try:

    time.sleep(3)

    df = pd.DataFrame(columns = ['カテゴリ', 'ランキング', '商品名', 'URL'])

    url = 'https://www.amazon.co.jp/gp/bestsellers'
    res = requests.get(url)
    soup = BeautifulSoup(res.text, 'html.parser')

    for header_tag in soup.select('div.a-carousel-header-row'):

      for category_tag in header_tag.select('div > h2'):

        category_name = category_tag.string.replace(' の 売れ筋ランキング', '')
        items_tag = header_tag.next_sibling
        # [print_element(x) for x in items_tag]

        for item in items_tag.select('li'):
          item_name = (item.select("div > div > a > span > div"))[0].string
          item_rank = (item.select("div > div > span"))[0].string.replace('#', '') + '位'
          item_url = "https://www.amazon.co.jp/" + (item.select("div > div > a"))[0].attrs.get('href')

          df = df.append({'カテゴリ':category_name, 'ランキング':item_rank, '商品名':item_name, 'URL':item_url}, ignore_index=True)

    df.to_csv('./result.csv', index=False, encoding='utf_8_sig')

  except Exception as e:
    print(e.args)
    print('異常終了')

  finally:
    print('正常終了')

def print_element(elem):

  if isinstance(elem, NavigableString):
      print(type(elem), elem.string)
  else:
      print(type(elem), elem.name, elem.attrs.get('class'))

if __name__ == '__main__':
  main()


from django import forms
from .models import Ticket, Review, CustomUser
from django.contrib.auth.forms import UserCreationForm

class SignUpForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password1', 'password2']

class TicketForm(forms.ModelForm):
    class Meta:
        model = Ticket
        fields = ['title', 'description', 'image']
        labels = {
            "title": "Titre",
            "description": "Description",
            "image": "Image"
        }

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ['headline', 'rating', 'body']
        labels = {
            "headline": "Titre",
            "rating": "Note",
            "body": "Commentaire"
        }

class FollowForm(forms.Form):
    user = forms.CharField(label='User', max_length=100)


class Node:
    def __init__(self, val = None, next = None):
        self.val = val
        self.next = next

class SortedList:
    def __init__(self):
        self.head = Node()

    def insert(self, val):
        pre = self.head
        cur = self.head.next
        while cur:
            if cur.val >= val:
                break
            pre, cur = cur, cur.next
        if cur and cur.val == val: return
        newNode = Node(val, cur)
        pre.next = newNode

    def print(self):
        cur = self.head.next
        while cur:
            print(cur.val)
            cur = cur.next

s = SortedList()
s.insert(1)
s.insert(1)
s.insert(3)
s.insert(4)
s.insert(5)
s.insert(2)
s.insert(100)
s.insert(0)
s.print()

Bloomberg/Design Sorted Singly Linked List.py


try:
    import constants, os, pygame, sound_mixer, graphics
    from os_utils import file_path, safe_exit
    from utils import get_time_sec
    from anim_sprite import *
    from credits import Credits
    from kezmenu import KezMenu
    from fsm import State
except ImportError as err:
    try:
        import os
        path = os.path.basename(__file__)
        print((': '.join((path, str(err)))))
    # importing os failed, print a custom message...
    except ImportError:
        print((': '.join(("couldn't load module", str(err)))))
    exit(2)

## objects imported when `from <module> import *' is used
__all__ = ['Menu']

## the main menu's position x co-ordinate
MENU_MAIN_POS_X = 525

## the main menu's position y co-ordinate
MENU_MAIN_POS_Y = 285

## menu keyboard repeat delay
MENU_KEY_DEL = 500

## menu keyboard repeat interval
MENU_KEY_INT = 200

## animated sprite speed
ANIM_SPRITE_SPEED = 200.0

## animated sprite alpha (on settings)
ANIM_SPRITE_ALPHA = 80.0

MAIN_FONT_SIZE = 32
MENU_FONT_SIZE = 25
MAIN_FOCUS_COLOR = pygame.Color('brown')
SETTINGS_FOCUS_COLOR = pygame.Color('orange')
MENU_CLOCK_TICK = 50
SOUND_VOL = 0.2
MAX_ALPHA = 255

## class for game's menu screen
#
class Menu(State):

    ## initialize both the main and settings menu
    #
    # @param self the object pointer
    # @param game_opts the game's command line options
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, constants.SCENES['menu'])

        ## the game's command line options
        self.game_opts = game_opts

        ## the screen surface
        self.screen = pygame.display.get_surface()

        ## flag to control the settings menu's loop
        self.menu_settings_running = None

        ## flag to control the main menu's loop
        self.menu_main_running = True

        # enable key repeat for the menu
        pygame.key.set_repeat(MENU_KEY_DEL, MENU_KEY_INT)

        ## set the main menu's background
        self.menu_main_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['main']['bg'][0])[0]

        ## set the settings menu's background
        self.menu_settings_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['bg'][0])[0]

        ## set the settings menu's background box
        self.menu_box_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['settings']['box'][0])[0]

        ## set the window frame
        self.window_frame = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['frame'][0])[0]

        ## set the mouse cursor
        self.mouse_cursor = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['cursor'][0])[0]

        ## set the sound when a menu option is entered
        self.select_option_snd = sound_mixer.load_sound(
            constants.FILES['sounds']['menu']['share']['sel'][0])

        ## create the main menu - string, callback function
        self.menu_main = KezMenu(self.game_opts,
                         ['Play'     , self._play_option],
                         ['Settings' , self._settings_option],
                         ['Credits'  , self._credits_option],
                         ['Quit'     , self._quit_option])

        # set the position of the main menu
        self.menu_main.set_position(MENU_MAIN_POS_X, MENU_MAIN_POS_Y)

        # set the main menu's font
        self.menu_main.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], MAIN_FONT_SIZE))

        # set the main menu's highlight color
        self.menu_main.set_highlight_color(MAIN_FOCUS_COLOR)

        ## create the settings menu - string, callback function
        self.menu_settings = KezMenu(self.game_opts,
                             ['Fullscreen' , self._toggle_fullscreen_option],
                             ['Sounds'     , self._toggle_sounds_option],
                             ['Music'      , self._toggle_music_option],
                             ['Back'       , self._back_option])

        # disable the menu graphic for focused options
        self.menu_settings.toggle_image()

        # set the settings menu's font
        self.menu_settings.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], MENU_FONT_SIZE))

        # set the position of the settings menu
        self.menu_settings.center_at(constants.SCREEN_WIDTH / 2.0,
                                     constants.SCREEN_HEIGHT / 2.0)

        # set the settings menu's highlight color
        self.menu_settings.set_highlight_color(SETTINGS_FOCUS_COLOR)

        ## the animated sprite group
        self.anim_sprites = pygame.sprite.RenderUpdates()

        # create the animated sprites
        sprite_num = len(constants.FILES['graphics']['menu']['share']['anim'])
        sprite_fact = SpriteFactory()
        for i in range(sprite_num):
            # create the "right" type of animated sprite using the factory
            r_sprite = sprite_fact.create_anim_sprite(i, constants.FILES['graphics']['menu']
                                                      ['share']['anim'][i], ANIM_SPRITE_SPEED)
            self.anim_sprites.add(r_sprite)

        ## create clock and track time
        self.clock = pygame.time.Clock()

    ## what to do when the main menu is enabled
    #
    # @param self the object pointer
    def do_actions(self):

        # display & update screen, get all the events
        while self.menu_main_running:

            # draw the background
            bg = self.screen.blit(self.menu_main_bg, (0, 0))

            # count time passed in seconds
            time_passed_seconds = get_time_sec(self.clock.tick(MENU_CLOCK_TICK))

            # animate the sprites
            self.anim_sprites.update(time_passed_seconds)

            # rectlist = self.anim_sprites.draw(self.screen)
            self.anim_sprites.draw(self.screen)

            # draw the main menu
            self.menu_main.draw(self.screen)

            # draw the custom mouse cursor
            graphics.handle_mouse_cursor(self.mouse_cursor, self.screen)

            # draw the frame of the window
            fr = self.screen.blit(self.window_frame, (0, 0))

            need_update = (bg, fr)

            # display the screen surface
            pygame.display.update(need_update)

            # get all the events
            events = pygame.event.get()

            # ......... and update the main menu
            # which needs access to those events
            self.menu_main.update(events)

            # main menu event loop
            for e in events:
                # quit when the close button is pressed
                if e.type == pygame.QUIT:
                    self._quit_option()
                # handle keyboard keys
                elif e.type == pygame.KEYDOWN:
                    # play the sound if there was a menu key shortcut
                    if self.game_opts.sound:
                        if e.key in (pygame.K_p, pygame.K_s, pygame.K_c):
                            sound_mixer.play_sound(
                                self.select_option_snd, SOUND_VOL)

                    # when user presses escape or 'q'uit key
                    if e.key in (pygame.K_ESCAPE, pygame.K_q):
                        self._quit_option()
                    # when user presses 'p'lay key
                    elif e.key == pygame.K_p:
                        self._play_option()
                    # when user presses 's'ettings key
                    elif e.key == pygame.K_s:
                        self._settings_option()
                    # when user presses 'c'redits key
                    elif e.key == pygame.K_c:
                        self._credits_option()

    ## entry point for main menu's settings option
    #
    # @param self the object pointer
    def _settings_option(self):
        # each time we enter in settings
        # sub menu, set the flag to true
        self.menu_settings_running = True

        # decrease the alpha of animated sprites
        for s in self.anim_sprites:
            s.image.set_alpha(ANIM_SPRITE_ALPHA)

        # display & update screen, get all the events
        while self.menu_settings_running:
            # draw the background
            bg = self.screen.blit(self.menu_settings_bg, (0, 0))

            # draw the main menu
            self.menu_main.draw(self.screen)

            # count time passed in seconds
            time_passed_seconds = get_time_sec(self.clock.tick(MENU_CLOCK_TICK))

            # animate the sprites
            self.anim_sprites.update(time_passed_seconds)
            self.anim_sprites.draw(self.screen)

            # draw settings menu background box
            menu_bg = self.screen.blit(self.menu_box_bg, (
                    (constants.SCREEN_WIDTH - self.menu_box_bg.get_width()) / 2.0,
                    (constants.SCREEN_HEIGHT - self.menu_box_bg.get_height()) / 2.0))

            # draw the settings menu
            self.menu_settings.draw(self.screen)

            # draw the custom mouse cursor
            graphics.handle_mouse_cursor(self.mouse_cursor, self.screen)

            # draw the frame of the window
            fr = self.screen.blit(self.window_frame, (0, 0))

            need_update = (bg, menu_bg, fr)

            # display the screen surface
            pygame.display.update(need_update)

            # get all the events
            events = pygame.event.get()

            # ..... and update the settings menu
            # which needs access to those events
            self.menu_settings.update(events)

            # settings menu event loop
            for e in events:
                # quit when the close button is pressed
                if e.type == pygame.QUIT:
                    self._back_option()
                    self._quit_option()
                # handle keyboard keys
                elif e.type == pygame.KEYDOWN:
                    # play the sound if there was a menu key shortcut
                    if self.game_opts.sound:
                        if e.key in (pygame.K_f, pygame.K_s, pygame.K_m,
                                     pygame.K_b, pygame.K_ESCAPE):
                            sound_mixer.play_sound(
                                self.select_option_snd, SOUND_VOL)

                    # when user presses escape key or 'b'ack key
                    if e.key in (pygame.K_ESCAPE, pygame.K_b):
                        self._back_option()
                    # when user presses 'f'ullscreen key
                    elif e.key == pygame.K_f:
                        self._toggle_fullscreen_option()
                    # when user presses 's'ounds key
                    elif e.key == pygame.K_s:
                        self._toggle_sounds_option()
                    # when user presses 'm'usic key
                    elif e.key == pygame.K_m:
                        self._toggle_music_option()

        # restore the alpha of the animated sprites
        for s in self.anim_sprites:
            s.image.set_alpha(MAX_ALPHA)

    ## entry point for main menu's new game option
    #
    # @param self the object pointer
    def _play_option(self):
        if self.game_opts.verbose:
            print('Start a new game.')
        self.menu_main_running = False

    ## what should be satisfied for enabling the next scene
    #
    # @param self the object pointer
    # @return the name of the next scene
    def check_conditions(self):
        # if the scene is finished, returns back
        # to the caller the name of the next one
        if not self.menu_main_running:
            return constants.SCENES['level_one']
        return None

    ## entry point for main menu's credits option
    #
    # @param self the object pointer
    def _credits_option(self):

        # get the path of the filename
        fullname = file_path(
            constants.FILES['texts']['menu']['credits']['text'][0],
            constants.TEXTS_DIR)

        # if credits text file exists and is readable
        if os.access(fullname, os.F_OK) and os.access(fullname, os.R_OK):
            if self.game_opts.verbose:
                print('Go to the credits screen.')

            # create the credits screen
            c = Credits(self.screen,
                        self.game_opts,
                        self.window_frame,
                        self.menu_settings_bg,
                        self.select_option_snd,
                        fullname)

            # run the credits screen
            if not c.run():
                # quit if the close button is
                # pressed (inside the credits)
                self._quit_option()
        else:
            print((' '.join(("Couldn't read text file:", fullname))))

    ## entry point for main menu's quit option
    #
    # @param self the object pointer
    def _quit_option(self):
        if self.game_opts.verbose:
            print('Exit the game!')

        # perform safe exit
        safe_exit()

    ## entry point for settings menu's toggle fullscreen option
    #
    # @param self the object pointer
    def _toggle_fullscreen_option(self):
        self.game_opts.fullscreen = not self.game_opts.fullscreen

        if self.game_opts.verbose:
            print('Toggle fullscreen!')

        # store the position of the mouse cursor
        mouse_position = pygame.mouse.get_pos()

        # toggle the fullscreen <-> window mode
        pygame.display.set_mode(
            (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT),
            pygame.FULLSCREEN if self.game_opts.fullscreen else 0)

        # update the mouse cursor position
        pygame.mouse.set_pos(mouse_position)

    ## entry point for settings menu's toggle sounds option
    #
    # @param self the object pointer
    def _toggle_sounds_option(self):
        self.game_opts.sound = not self.game_opts.sound
        if self.game_opts.verbose:
            print('Toggle sounds!')

    ## entry point for settings menu's toggle music option
    #
    # @param self the object pointer
    def _toggle_music_option(self):
        if self.game_opts.verbose:
            print('Toggle music!')

        self.game_opts.music = not self.game_opts.music
        if self.game_opts.music:
            pygame.mixer.music.unpause()
        else:
            pygame.mixer.music.pause()

    ## entry point for settings menu's back option
    #
    # @param self the object pointer
    def _back_option(self):
        self.menu_settings_running = False
        if self.game_opts.verbose:
            print('Go back to main menu!')


# A game manager class for Othello

BLACK = 0
WHITE = 255
MSSG_SIZE = 320

class GameManager:
    """A Game Manager class for Othello"""

    def __init__(self, size):
        """Creates an instances of GameManager given the game grid"""
        self.SIZE = size
        self.winner = None
        self.win_score = 0
        self.lose_score = 0
        self.total_piece_count = size * size
        self.game_over = False
        self.flip_pieces = []

    def end_game(self, game_pieces, used_points):
        """Determines and displays the winner of the game"""
        current_piece_count = self.update_piece_count(used_points)
        if current_piece_count == self.total_piece_count:
            self.game_over = True
        if self.game_over is True:
            black_count, white_count = self.count_colors(game_pieces)
            if black_count > white_count:
                self.winner = "Black"
                self.win_score = black_count
                self.lose_score = white_count
            elif white_count > black_count:
                self.winner = "White"
                self.win_score = white_count
                self.lose_score = black_count
            else:
                self.win_score = black_count
                self.lose_score = white_count
            return black_count

    def display_winner(self):
        """Displays the end game message"""
        if self.winner is None:
            message = "TIE, {0} - {1}".format(self.win_score, self.lose_score)
        else:
            message = "{} Wins, {} - {}".format(self.winner, self.win_score,
                                                self.lose_score)
        self.display_mssg(message)

    def display_mssg(self, message):
        """Displays the end game message"""
        textSize(32)
        tw = textWidth(message)
        ta = textAscent()
        td = textDescent()

        stroke(0)
        strokeWeight(4)
        fill(WHITE)
        rectMode(CENTER)
        rect(MSSG_SIZE, MSSG_SIZE, tw + 20, ta + td + 20)

        fill(50)
        textAlign(CENTER, CENTER)
        text(message, MSSG_SIZE, MSSG_SIZE)

    def count_colors(self, game_pieces):
        """Returns number of black and white game pieces currently on the board"""
        black_count = 0
        white_count = 0
        for i in range(self.SIZE):
            for j in range(self.SIZE):
                if game_pieces[i][j] is not None:
                    if game_pieces[i][j].color == BLACK:
                        black_count += 1
                    else:
                        white_count += 1
        return black_count, white_count

    def update_piece_count(self, used_points):
        """Return the number of pieces on the board"""
        return len(used_points)

    def check_valid_move(self, x, y, game_pieces, current_color):
        if current_color == WHITE:
            opposing_color = BLACK
        else:
            opposing_color = WHITE
        self.flip_pieces = []
        surrounding_positions = [(1, 0), (0, 1), (-1,1), (1,-1), (1,1),
                                 (-1, -1), (-1, 0), (0, -1)]
        # Checks if space is next to an opposing piece
        for x_direction, y_direction in surrounding_positions:
            current_x = int(x + x_direction)
            current_y = int(y + y_direction)
            if self.on_board(current_x, current_y):
                piece = game_pieces[current_x][current_y]

                # Continues to check if the next piece is an opposiing piece
                while piece is not None and piece.color == opposing_color:
                    current_x = int(current_x + x_direction)
                    current_y = int(current_y + y_direction)
                    if not self.on_board(current_x, current_y):
                        break
                    piece = game_pieces[current_x][current_y]

                # Checks if the opposing pieces are next to the current piece
                if piece is not None and piece.color == current_color:
                    while current_x != x or current_y != y:
                        current_x = int(current_x - x_direction)
                        current_y = int(current_y - y_direction)
                        if current_x != x or current_y != y:
                            self.flip_pieces.append((current_x, current_y))

        if len(self.flip_pieces) == 0:
            return False
        return True

    def get_valid_moves(self, game_pieces, current_color):
        """Returns a list of valid moves"""
        valid_moves = []
        for i in range(self.SIZE):
            for j in range(self.SIZE):
                if (game_pieces[i][j] is None
                    and self.check_valid_move(i, j, game_pieces, current_color)):
                    valid_moves.append((i, j))
        return valid_moves

    def on_board(self, x, y):
        """Checks if the given x and y coordinates are within
        the size of the board
        """
        return x >= 0 and x < self.SIZE and y >= 0 and y < self.SIZE


# Plotting with `seaborn`

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

tips = sns.load_dataset('tips')

penguins = sns.load_dataset('penguins')

titanic = sns.load_dataset('titanic')

sns.countplot(titanic['sex'], hue = titanic['survived'])

#seaborn has a special plot for counts
sns.countplot(titanic['survived'])
#titanic['survived'].value_counts().plot(kind = 'bar')

penguins.head()

sns.boxplot(x = penguins['species'], y = penguins['flipper_length_mm'])
plt.title('Penguins by Species and Distribution of Bill Length')
plt.xlabel('Species of Penguin');

penguins.info()

sns.scatterplot(penguins['bill_length_mm'], penguins['bill_depth_mm']);

penguins = penguins.dropna()

sns.pairplot(penguins, hue = 'island')

titanic.head(1)

#Histogram of ages on the titanic
#with appropriate title and x axis labels.
plt.hist(titanic['age']);
plt.title('Ages on the Titanic')
plt.xlabel('Ages');

titanic.head(1)

titanic['class'].value_counts()

#Barplot of counts of passengers by class on titanic.
titanic['pclass'].value_counts().plot(kind = 'bar');

#Boxplots of penguins

penguins.head(1)

penguins['species'].unique()

colors = []
#write a loop -- loop over the species
#if Adelie -- blue
#if Chinstrap -- yellow
#if Gentoo -- red
for species in penguins['species']:
    #test if Adelie
    if species == 'Adelie':
        colors.append('blue')
    #test if Chinstrap
    elif species == 'Chinstrap':
        colors.append('yellow')
    #test if Gentoo
    else:
        colors.append('red')

#Scatterplot of penguins
plt.scatter(penguins['bill_length_mm'], penguins['bill_depth_mm'],
            c = colors)

#barplot for survival
titanic['survived'].value_counts().plot(kind = 'bar')

survival_counts = titanic['survived'].value_counts()

plt.bar([0, 1], survival_counts);

#histograms of flipper lengths

sns.boxplot(x = 'island', y = 'bill_length_mm', data = penguins);

tips.head()

sns.stripplot('total_bill', data = tips)

iris = sns.load_dataset("iris")
sns.catplot(data=iris, orient="h", kind="box");

sns.catplot(x="day", y="total_bill", hue="smoker",
            col="time", aspect=.6,
            kind="swarm", data=tips);

titanic = sns.load_dataset("titanic")
sns.catplot(x="sex", y="survived", hue="class", kind="bar", data=titanic);

from bokeh.plotting import figure
from bokeh.io import output_notebook, show

output_notebook()

x = [1, 2, 3, 4, 5]
y = [4, 2, 5, 6, 2]

p = figure(width = 600, height = 300)
p.circle(x, y)
show(p)

p = figure(width = 600, height = 300)
p.circle(x, y,  color = 'red', size = 10, alpha = 0.5)
show(p)

p = figure(width = 600, height = 400)
p.vbar(x= [0,0.5, 1], bottom = [0, 1, 1], top = [4, 3, 2], width = 0.2)
show(p)

### From a DataFrame

df = pd.read_csv('data/happiness/2015.csv')

df.head(2)

from bokeh.models import ColumnDataSource
from bokeh.layouts import gridplot
source = ColumnDataSource(df)

p1 = figure(title="Happiness and Economy", width = 600, height = 300)
p1.circle("Happiness Score", "Economy (GDP per Capita)", color="firebrick", size = 10,
          alpha = 0.5,
          source=source)
p1.xaxis[0].axis_label = "Happiness Score"
p1.yaxis[0].axis_label = "GDP per Capita"

show(p1)


import pandas as pd
import cv2
import os
import random
import matplotlib.pyplot as plt
from .hyperparameters import num_samples, train_epochs, train_images_path, train_labels_path, runs_directory, results_column, hyp_iou_files

def display_sample(num_samples, images_path, labels_path):
    """
    Display selection of sample of images with bounding boxes
    Adapted from https://github.com/pjreddie/darknet/blob/810d7f797bdb2f021dbe65d2524c2ff6b8ab5c8b/src/image.c#L283-L291
    via https://stackoverflow.com/questions/44544471/how-to-get-the-coordinates-of-the-bounding-box-in-yolo-object-detection#comment102178409_44592380
    """

    # Get all image files
    image_files = os.listdir(images_path)

    # Randomly select images that have label files
    sample_images = []
    for _ in range(num_samples):
        random_image_file = random.choice(image_files)
        label_file = random_image_file[:-3] + 'txt'
        label_path = os.path.join(labels_path, label_file)

        while not os.path.exists(label_path):
            random_image_file = random.choice(image_files)
            label_file = random_image_file[:-3] + 'txt'
            label_path = os.path.join(labels_path, label_file)

        sample_images.append(random_image_file)

    # Display bounding boxes on images
    # Adjusting figure size based on num_samples
    fig, axs = plt.subplots(1, num_samples, figsize=(4*num_samples, 4))

    for ax, img_name in zip(axs, sample_images):
        img_path = os.path.join(images_path, img_name)
        img = cv2.imread(img_path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # Convert from BGR to RGB
        dh, dw, _ = img.shape

        label_name = img_name[:-3] + 'txt'
        label_path = os.path.join(labels_path, label_name)

        with open(label_path, 'r') as f:
            data = f.readlines()
            for dt in data:
                _, x, y, w, h = map(float, dt.split(' '))
                l = int((x - w / 2) * dw)
                r = int((x + w / 2) * dw)
                t = int((y - h / 2) * dh)
                b = int((y + h / 2) * dh)

                cv2.rectangle(img, (l, t), (r, b), (0, 255, 0), 2)

        ax.imshow(img)
        ax.set_title(img_name)
        ax.axis('off')

    plt.tight_layout()
    plt.show()

def dataset_distribution(train_images_path, valid_images_path, test_images_path):
    train_images_count = len(os.listdir(train_images_path))
    valid_images_count = len(os.listdir(valid_images_path))
    test_images_count = len(os.listdir(test_images_path))

    plt.pie([train_images_count, valid_images_count, test_images_count], labels=[
            'Train', 'Validation', 'Test'], autopct='%1.1f%%')
    plt.title('Distribution of Train/Validation/Test Split')
    plt.show()

def background_split(train_labels_path, valid_labels_path, test_labels_path):
    # Counting the total number of label files and the number of empty label files in each directory
    train_labels_count = len(os.listdir(train_labels_path))
    train_empty_labels_count = len([name for name in os.listdir(
        train_labels_path) if os.path.getsize(os.path.join(train_labels_path, name)) == 0])

    valid_labels_count = len(os.listdir(valid_labels_path))
    valid_empty_labels_count = len([name for name in os.listdir(
        valid_labels_path) if os.path.getsize(os.path.join(valid_labels_path, name)) == 0])

    test_labels_count = len(os.listdir(test_labels_path))
    test_empty_labels_count = len([name for name in os.listdir(
        test_labels_path) if os.path.getsize(os.path.join(test_labels_path, name)) == 0])

    # Calculating the total labelled images and total unlabelled images
    total_labelled = train_labels_count + valid_labels_count + test_labels_count - \
        train_empty_labels_count - valid_empty_labels_count - test_empty_labels_count
    total_unlabelled = train_empty_labels_count + \
        valid_empty_labels_count + test_empty_labels_count

    print(
        f"Train - Labelled: {train_labels_count - train_empty_labels_count}, Unlabelled: {train_empty_labels_count}")
    print(
        f"Validation - Labelled: {valid_labels_count - valid_empty_labels_count}, Unlabelled: {valid_empty_labels_count}")
    print(
        f"Test - Labelled: {test_labels_count - test_empty_labels_count}, Unlabelled: {test_empty_labels_count}")

    # Stacked bar graph
    labels = ['Train', 'Validation', 'Test']
    labelled_counts = [train_labels_count - train_empty_labels_count, valid_labels_count -
                       valid_empty_labels_count, test_labels_count - test_empty_labels_count]
    unlabelled_counts = [train_empty_labels_count,
                         valid_empty_labels_count, test_empty_labels_count]

    width = 0.5  # the width of the bars
    fig, ax = plt.subplots()

    ax.bar(labels, labelled_counts, width, label='Labelled')
    ax.bar(labels, unlabelled_counts, width,
           label='Background', bottom=labelled_counts)

    ax.set_ylabel('Images')
    ax.set_title('Background Image Distribution')
    ax.legend()

    plt.show()

def plot_results(runs_directory, hyp_files):
    """
    Plots the highest values for a single column from results.csv for each run in the experiment.
    """

    best_values = []

    # Iterate through each file and grab highest value
    for file in hyp_files:

        results_path = os.path.join(
            "yolov5", runs_directory, file, "results.csv")
        # Check for file
        if os.path.exists(results_path):
            # Read the CSV into a DataFrame
            df = pd.read_csv(results_path)

            # Check if the results_column exists in the dataframe
            if results_column in df.columns:
                # Grab highest value from results_column
                best_map = df[results_column].max()
                best_values.append(best_map)
            else:
                print(
                    f"Warning: Column '{results_column}' not found in {results_path}.")
                best_values.append(0)
        else:
            print(f"Warning: {results_path} not found.")
            best_values.append(0)

    print(best_values)

    plt.figure(figsize=(10, 5))
    plt.bar(hyp_files, best_values, color='blue')
    plt.ylim(0.85, 0.87)
    plt.ylabel(f"Best {results_column} Over {train_epochs} Epochs")
    plt.xlabel('Runs')
    plt.title(f"Best {results_column} Values Across {len(hyp_files)} Runs")
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()


# Analysis of TR-OSL experimental data in alumina
from scipy import optimize
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from prettytable import PrettyTable
data = np.loadtxt('aluminaxy1.txt')
x_data, y_data = np.array(data[:, 0][8:20]), \
np.array(data[:, 1][8:20])
kB=8.617e-5
def tq(x_data, N,c, W):
    return N /(1+c*np.exp(-W/(kB*(273+x_data))))
params, cov = optimize.curve_fit(tq,\
x_data, y_data,bounds=(0,[.04,1e12,1]))
plt.subplot(1,2, 1)
plt.plot(x_data,y_data,"o",c='black',label='Experimental')
plt.plot(x_data, tq(x_data, *params),
label='Best fit',c='r',linewidth=2)
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)
plt.ylabel(r'Luminescence Lifetime $\tau$ [s]')
plt.xlabel(r'Stimulation Temperature [$^{o}$C]')
plt.title('(a)   Finding C,W')
plt.text(90,.02,"Luminescence")
plt.text(90,.017,r"lifetime $\tau$")
C,W=format(params[1],"10.1E"),round(params[2],4)
dC = round(np.sqrt(cov[1][1]),4)
dW = round(np.sqrt(cov[2][2]),3)
data = np.loadtxt('aluminaxy2.txt')
x0, y0 = np.array(data[:, 0]), np.array(data[:, 1])
x_data=1/(kB*(273+np.array(x0)[4:10]))
y_data=np.log(np.array(y0)[4:10])
def arrh(x_data,slope,inter):
    return slope*x_data+inter
params, cov = optimize.curve_fit(arrh,x_data, y_data)
plt.subplot(1,2, 2)
plt.plot(x_data,y_data,"o",c="black",label='Experimental')
x_vals=np.arange(30,35,.1)
plt.plot(x_vals, arrh(x_vals, *params),
label='Best fit',c='r',linewidth=2)
Eth=-round(params[0],3)
dEth = round(np.sqrt(cov[0][0]),3)
plt.title(r'(b)    Finding E$_{th}$')
leg = plt.legend()
leg.get_frame().set_linewidth(0.0)
plt.ylabel(r'ln($\tau$)')
plt.xlabel(r'1/(kT) [eV$^{-1}$]')
plt.text(31, 14.95,'Arrhenius plot')
plt.tight_layout()
myTable=PrettyTable(["C","dC","W (eV)","dW", "Eth (eV)","dEth"])
myTable.add_row([C,dC,W,dW,Eth,dEth])
print(myTable)
plt.show()


# Python Program To Access Global Variables Inside A Function And Modify It

'''
Function Name    :  Access Global Variable Inside Function And Modify It.
Function Date    :  7 Sep 2020
Function Author  :  Prasad Dangare
'''

a = 1 # Global Variable
def myfunction():
    global a # This Is Global Variable
    print('Global a = ', a) # Display Global Variable
    a = 2 # Modify Global Variable Value
    print('Modified a = ', a) # Display Modified Value

myfunction()
print('Global a = ', a) # Display Modified Value


from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import Response
from .serializer import TransactionSerializer
from rest_framework import status

@api_view(['POST'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def upload_csv(request):
	data = {}
	status_code = None
	serializer = TransactionSerializer(data=request.FILES, context={'user': request.user})
	if serializer.is_valid():
		serializer.save()
		data['success'] = 'successfully uploaded a csv file'
		status_code = status.HTTP_201_CREATED
	else:
		data = serializer.errors
		status_code = status.HTTP_400_BAD_REQUEST
	return Response(data, status=status_code)


DOCUMENTATION = r'''
module: nextdns
short_description: An ansible-rulebook event source plugin for NextDNS logs
description:
    - Uses the NextDNS API to subscribe to a SSE event stream for the logs of a specific profile and use these as events in Event-Driven Ansible
author: "Colin McNaughton (@cloin)"
options:
    api_key:
        description:
            - Your NextDNS API key
        required: true
    profile_id:
        description:
            - Your NextDNS profile ID
        required: true
'''

EXAMPLES = r'''
- name: NextDNS event stream
    hosts: localhost
    sources:
    - cloin.eda.nextdns:
        profile_id: ""
        api_key: ""
'''

import asyncio
import aiohttp
import json
from aiohttp_sse_client import client as sse_client
from typing import Any, Dict

async def main(queue: asyncio.Queue, args: Dict[str, Any]):
    profile_id = args["profile_id"]
    api_key = args["api_key"]

    if not profile_id or not api_key:
        print("Please specify both the API key and profile ID")
        return

    async with aiohttp.ClientSession() as session:
        # Test API key and profile ID
        test_url = f'https://api.nextdns.io/profiles/{profile_id}/analytics/status'
        headers = {'X-Api-Key': api_key}

        try:
            async with session.get(test_url, headers=headers) as response:
                if response.status == 403:
                    print("Access Forbidden: Invalid API key or profile ID")
                    return
                elif response.status != 200:
                    print(f"Unexpected error: {response.status}")
                    return

                response_data = await response.json()
                print(response_data)

        except aiohttp.ClientError as e:
            print(f"Connection error: {e}")
            return

        # Process logs
        nextdns_api_url = f'https://api.nextdns.io/profiles/{profile_id}/logs/stream'

        async with sse_client.EventSource(nextdns_api_url, headers=headers) as client:
            async for event in client:
                event_data = json.loads(event.data)
                await queue.put(dict(nextdns=dict(log=event_data)))

if __name__ == "__main__":

    class MockQueue:
        async def put(self, event):
            print(event)

    mock_arguments = dict(profile_id="", api_key="")
    asyncio.run(main(MockQueue(), mock_arguments))


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

import os.path as osp
import sys
import re
import types
import inspect

from cake.color import fore, puts

# object used for accessing cake paths
class ProjectPaths(object):
	__slots__ = ['current', 'root']

path = ProjectPaths()

# indented file
class IndentedFile(object):
	def __init__(self, fobj, indent_level=-1, indent_per_level=2):
		self.fobj = fobj
		self.indent_level = indent_level
		self.indent_per_level = indent_per_level

	@property
	def indent(self):
		return max(0, self.indent_level * self.indent_per_level)

	def write(self, *args, **kwargs):
		self.fobj.write(' ' * self.indent)
		self.fobj.write(*args, **kwargs)

	def __getattr__(self, key):
		return getattr(self.fobj, key)

# helpers
def task(arg = None):
	""" Task decorator """

	# make sure stdout is patched
	if not hasattr(sys.stdout, 'indent_level'):
		sys.stdout = IndentedFile(sys.stdout)

	def decorator(base):
		info = ': ' + arg if type(arg) is str else ''
		header = fore.green('** ' + fore.cyan(base.__name__) + info)

		def func(*args, **kwargs):
			sys.stdout.indent_level += 1

			puts(header)
			base(*args, **kwargs)

			sys.stdout.indent_level -= 1

		params = inspect.formatargspec(*inspect.getargspec(base))[1:-1]
		specformat = fore.cyan('%s') + ' ' + fore.white('%s')

		func._task = True
		func._spec = specformat % (base.__name__, params)
		func._desc = re.sub('\s+', ' ', inspect.getdoc(base) or '')
		return func

	if type(arg) == types.FunctionType:
		return decorator(arg)
	else:
		return decorator

def recurse_up(directory, filename):
	"""
	Recursive walk a directory up to root until it contains `filename`
	"""

	directory = osp.abspath(directory)

	while True:
		searchfile = osp.join(directory, filename)

		if osp.isfile(searchfile):
			return directory

		if directory == '/': break
		else: directory = osp.dirname(directory)
	return False


import codecs

BOOK_PATH = 'E:\учеба\python_tg\BookBot\\book\\book.txt'
PAGE_SIZE = 1050

book_pages: dict[int, str] = {}

def _get_part_text(text:str, start:int, page_size:int) -> tuple[str, int]:
    signs = [',', '.', '!', ':', ';', '?']
    end_of_page = min(len(text)-1, start + page_size-1)
    if end_of_page == len(text) - 1:
        return text[start:len(text)], len(text)-start
    for i in range(end_of_page, start, -1):
        if text[i] in signs and text[i]+ text[i+1] != '..' and text[i+1] + text[i+2] != '..':
            break
    return text[start:i+1], i-start+1

def prepare_book(path:str) -> None:
    file = codecs.open(path, 'r', 'utf-8')
    text = file.read()
    page_number = 1
    start_index = 0
    whole_length = 0
    while whole_length != len(text):
        current_text, current_length = _get_part_text(text, start_index, PAGE_SIZE)
        book_pages[page_number] = current_text.lstrip('     \n\v\f\r')
        whole_length += current_length
        page_number += 1
        start_index += current_length

prepare_book(BOOK_PATH)

prepare_book(BOOK_PATH)