#! -*- codin: utf-8 -*-

from __future__ import unicode_literals

import humanize
import os
import itertools

from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.core.urlresolvers import reverse
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _

from .functions import mp3_tags_to_song_model, tags_from_song_model_to_mp3, m4a_tags_to_song_model, \
    aiff_tags_to_song_model, tags_from_song_model_to_aiff, wav_tags_to_song_model, tags_from_song_model_to_m4a, \
    tags_from_song_model_to_wav

def upload_to_username(instance, filename):
    return '%s/%s' % (instance.user.username, filename)

def upload_to_root(instance, filename):
    return '%s/%s' % ('./', filename)

class Playlist(models.Model):
    """
    Playlist model
    """
    name = models.CharField(_('Playlist name'), max_length=250)
    slug = models.SlugField(_('Slug'), unique=True, db_index=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)  # User which this playlist belongs to

    # Where to be redirected after you add a new playlist
    def get_absolute_url(self):
        return reverse('box:playlist-detail', kwargs={'username': self.user.username, 'slug': self.slug})

    def save(self, *args, **kwargs):
        self.slug =  check_slug_exists = slugify(self.name)

        for x in itertools.count(1):
            if not Playlist.objects.filter(slug=self.slug).exists():
                break
            self.slug = '%s-%d' % (check_slug_exists, x)
        return super(Playlist, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

class Song(models.Model):
    """
    Song model
    """
    file = models.FileField(_('File'), default='', upload_to=upload_to_username)
    original_filename = models.CharField(_('Original filename'), max_length=250, blank=True, null=True)
    file_size = models.CharField(_('File size in bytes'), max_length=10, blank=True, null=True)
    file_type = models.CharField(_('File type'), max_length=5, blank=True, null=True)
    duration = models.DurationField(_('Song duration'), null=True)

    title = models.CharField(_('Title'), max_length=250, blank=True, null=True)
    artist = models.CharField(_('Artist'), max_length=250, blank=True, null=True)
    album = models.CharField(_('Album name'), max_length=500, blank=True, null=True)
    year = models.PositiveSmallIntegerField(
        _('Year'),
        validators=[MaxValueValidator(3000)],
        blank=True,
        null=True,
    )
    release_date = models.DateField(_('Complete release date (day-month-year)'), blank=True, null=True)
    album_artist = models.CharField(_('Album artist (band/orchestra/accompaniment)'), max_length=250, blank=True,
                                    null=True)
    track_number = models.PositiveSmallIntegerField(
        _('Track number'),
        validators=[MaxValueValidator(3000)],
        blank=True,
        null=True
    )
    track_total = models.PositiveSmallIntegerField(
        _('Total track count'),
        validators=[MaxValueValidator(3000)],
        blank=True,
        null=True
    )
    bpm = models.FloatField(
        _('Beats per minute'),
        validators=[MinValueValidator(5), MaxValueValidator(300)],
        blank=True,
        null=True
    )
    original_artist = models.CharField(_('Original artist(s)/performer(s)'), max_length=250, blank=True, null=True)
    key = models.CharField(_('Song key'), max_length=50, blank=True, null=True)
    composer = models.CharField(_('Composer'), max_length=250, blank=True, null=True)
    lyricist = models.CharField(_('Lyricist/text writer'), max_length=250, blank=True, null=True)
    comments = models.CharField(_('Comments'), max_length=500, blank=True, null=True)
    remixer = models.CharField(_('Interpreted, remixed or otherwise modified by'), max_length=250, blank=True,
                               null=True)
    label = models.CharField(_('Label/Publisher'), max_length=250, blank=True, null=True)
    genre = models.CharField(_('Genre/content type'), max_length=100, blank=True, null=True)
    lyrics = models.TextField(_('Lyrics'), blank=True, null=True)

    artwork = models.ImageField(_('Song cover'), upload_to=upload_to_root, null=True, blank=True)

    slug = models.SlugField(_('Slug'), max_length=100, unique=True, db_index=True)
    ctime = models.DateTimeField(_('Creation time'), auto_now_add=True)
    mtime = models.DateTimeField(_('Modified time'), auto_now=True)

    user = models.ForeignKey(settings.AUTH_USER_MODEL)  # User which this song file belongs to
    playlists = models.ManyToManyField(Playlist)

    # Where to be redirected after you add a new song
    def get_absolute_url(self):
        return reverse('box:song-detail', kwargs={'username': self.user.username, 'slug': self.slug})

    def save(self, create=False, update=False, *args, **kwargs):
        if not self.slug:
            slug_final = check_slug_exists = slugify(self.file.name)
            if check_slug_exists != 'add':
                for x in itertools.count(1):
                    if not Song.objects.filter(slug=slug_final).exists():
                        break
                    slug_final = '%s-%d' % (check_slug_exists, x)
            else:
                slug_final = '%s-%d' % (check_slug_exists, 1)
                for x in itertools.count(1):
                    if not Song.objects.filter(slug=slug_final).exists():
                        break
                    slug_final = '%s-%d' % (check_slug_exists, x)

            self.slug = slug_final

        if create:
            file_final_path = self.file.path
            file_name = self.file.name
            self.file_type = file_final_path.split('.')[-1].lower()
            file_temp_path = os.path.join(settings.MEDIA_ROOT, 'tmp', 'temp.' + self.file_type)
            default_storage.save(file_temp_path, ContentFile(self.file.file.read()))
            self.file_size = humanize.naturalsize(os.path.getsize(file_temp_path))

            # MP3
            if self.file_type == "mp3":
                mp3_tags_to_song_model(file_name, file_temp_path, self)

            # MP4
            elif self.file_type == "m4a":
                m4a_tags_to_song_model(file_name, file_temp_path, self)

            # AIF or AIFF, it's the same
            elif self.file_type == "aif" or self.file_type == "aiff":
                if self.file_type == "aif":
                    self.file_type = "aiff"
                aiff_tags_to_song_model(file_name, file_temp_path, self)

            # WAV
            elif self.file_type == "wav":
                wav_tags_to_song_model(file_name, file_temp_path, self)

            default_storage.delete(os.path.join(settings.MEDIA_ROOT, 'tmp', 'temp.' + self.file_type))

            # Slug
            slugaux = os.path.splitext(os.path.basename(self.original_filename))[0]  # Filename without extension
            slugaux = slugaux.replace("_", " ")  # Replace '_' by ' '
            slugaux = ' '.join(slugaux.split())  # Leave only one space between words

            check_slug_exists = slugify(slugaux)
            if not Song.objects.filter(slug=check_slug_exists).exists() and check_slug_exists != 'add':
                self.slug = slugify(slugaux)

            else:
                slug_final = check_slug_exists

                if check_slug_exists != 'add':
                    for x in itertools.count(1):
                        if not Song.objects.filter(slug=slug_final).exists():
                            break
                        slug_final = '%s-%d' % (check_slug_exists, x)
                else:
                    slug_final = '%s-%d' % (check_slug_exists, 1)
                    for x in itertools.count(1):
                        if not Song.objects.filter(slug=slug_final).exists():
                            break
                        slug_final = '%s-%d' % (check_slug_exists, x)

                self.slug = slug_final

            if not self.title:
                self.title = slugaux

        elif update:
            # MP3
            if self.file_type == "mp3":
                tags_from_song_model_to_mp3(song=self, file_path=self.file.path)

            # MP4
            elif self.file_type == "m4a":
                tags_from_song_model_to_m4a(song=self, file_path=self.file.path)

            # AIFF
            elif self.file_type == "aiff":
                tags_from_song_model_to_aiff(song=self, file_path=self.file.path)

            # WAV
            elif self.file_type == "wav":
                tags_from_song_model_to_wav(song=self, file_path=self.file.path)

        return super(Song, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title

        # def clean_filename(self):
        #    cleaned_name = (self.file.name).replace("_", " ") # Replace '_' by ' '
        #    cleaned_name = ' '.join(cleaned_name.split()) # Leave only one space between words
        #    cleaned_name = cleaned_name.replace(" ", "_") # Replace ' ' by '_'
        #    return cleaned_name

    def delete(self, *args, **kwargs):
        self.file.delete(False)
        self.artwork.delete(False)
        super(Song, self).delete(*args, **kwargs)

    def artwork_tag(self):
        return u'<img src="%s" width="100" height="100"/>' % self.artwork.url

    artwork_tag.short_description = 'Artwork'
    artwork_tag.allow_tags = True

    def get_filename(self):
        return os.path.splitext(self.original_filename)[0]


"""
    继承 -- 变量
"""

class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    # 子类若没有构造函数， 使用父类的
    # 子类若具有构造函数， 则必须先调用父类的构造函数
    def __init__(self, name, score):
        super().__init__(name)
        self.score = score

    pass

p01 = Person('李四')
print(p01.name)

s01 = Student('张三', 100)
print(s01.score)
print(s01.name)

"""
    定义父类：
        车（数据：速度， 品牌）

    定义子类：
        电动车（数据：电池容量， 充电功率）

    创建两个对象
    画出内存图
"""

class Car:
    def __init__(self, speed, brand):
        self.speed = speed
        self.brand = brand

class ElectricCar(Car):
    def __init__(self, speed, brand, battery_capacity, charging_power):
        super().__init__(speed, brand)
        self.battery_capacity = battery_capacity
        self.charging_power = charging_power

c01 = Car(10, 'gtr')
e01 = ElectricCar(5, '艾玛', 100, 0.8)

python/python学习小分队打卡/课程代码/面向对象/5/5.5 继承的变量.py


# 3. Пользователь вводит месяц в виде целого числа от 1 до 12.
# Сообщить к какому времени года относится месяц (зима, весна, лето, осень).
# Напишите решения через list и через dict.

months = ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь']
monthsdict = {1:'Январь', 2:'Февраль', 3:'Март', 4:'Апрель', 5:'Май', 6:'Июнь', 7:'Июль', 8:'Август', 9:'Сентябрь',10:'Октябрь', 11:'Ноябрь', 12:'Декабрь'}

mes=int(input("Введите месяц: "))
i=0
#решение для списков
for i in range(len(months)):
    if 0 <= (mes - 1) < 2: vremyagoda = "Зима"
    if 2 <= (mes - 1) <= 4: vremyagoda = "Весна"
    if 5 <= (mes - 1) <= 7: vremyagoda = "Лето"
    if 8 <= (mes - 1) < 12: vremyagoda = "Осень"
    if mes == 12: vremyagoda = "Зима"

print("Решение для списка")
print("Вы ввели месяц времени года: ",months[mes-1])
print("Время года",vremyagoda)

#решение для cловаря
i=1
for i in range(12):
    if 0 <= mes < 2: vremyagoda = "Зима"
    if 2 <= mes <= 4: vremyagoda = "Весна"
    if 5 <= mes <= 7: vremyagoda = "Лето"
    if 8 <= mes < 12: vremyagoda = "Осень"
    if mes == 12: vremyagoda = "Зима"

print("************************")
print("Решение для словаря")
print("Вы ввели месяц времени года: ", monthsdict.get(mes))
print("Время года",vremyagoda)


from enum import Enum
import random
import sys
name = "Kwesi"  # global scope

# global scope variable and functions can be accessed from a local scope and not vice versa

# def greeting(name):
#     color = "red"  # local scope
#     print(color)
#     print(name)

# greeting(name)
# greeting("Isaac")
# print(color) #cant access local scope variable

# def another():
#     greeting(name)

# another()

# def another():
#     color = "blue"
#     #this done to stop polluting the global scope
#     def greeting(name):

#         print(color)
#         print(name)

#     greeting("Dave")

# another()

# count = 1

# def another():
#     color = "blue"
#     global count
#     count += 1
#     print(count)
#     print(color)

#     def greeting(name):
#         nonlocal color
#         color = "red"
#         print(color)
#         print(name)

#     greeting("Dave")
#     print(color)

# another()
# print(count)

game_count = 0

def play_rps():

    class RPS(Enum):
        ROCK = 1
        PAPER = 2
        SCISSORS = 3

    playerchoice = input(
        "\nEnter... \n1 for Rock,\n2 for Paper, or \n3 for Scissors:\n\n")

    if playerchoice not in ["1", "2", "3"]:
        print("You must enter 1, 2, or 3.")
        return play_rps()

    player = int(playerchoice)

    computerchoice = random.choice("123")

    computer = int(computerchoice)

    print("\nYou chose " + str(RPS(player)).replace('RPS.', '').title() + ".")
    print("Python chose " + str(RPS(computer)
                                ).replace('RPS.', '').title() + ".\n")

    def decide_winner(player, computer):
        if player == 1 and computer == 3:
            return "🎉 You win!"
        elif player == 2 and computer == 1:
            return "🎉 You win!"
        elif player == 3 and computer == 2:
            return "🎉 You win!"
        elif player == computer:
            return "😲 Tie game!"
        else:
            return "🐍 Python wins!"

    game_result = decide_winner(player, computer)

    print(game_result)

    global game_count
    game_count += 1

    print("\nGame count: " + str(game_count))

    print("\nPlay again?")

    while True:
        playagain = input("\nY for Yes or \nQ to Quit\n")
        if playagain.lower() not in ["y", "q"]:
            continue
        else:
            break

    if playagain.lower() == "y":
        return play_rps()
    else:
        print("\n🎉🎉🎉🎉")
        print("Thank you for playing!\n")
        sys.exit("Bye! 👋")

play_rps()


from typing import List

def is_first_object_less(object_1: List, object_2: List) -> bool:
    if object_1[0] < object_2[0]:
        return True
    elif object_1[0] == object_2[0] and object_1[1] < object_2[1]:
        return True
    else:
        return False

def insertion_sort(arr: List) -> None:
    for i in range(1, len(arr)):
        item_to_insert = arr[i]
        j = i
        while j > 0 and is_first_object_less(item_to_insert, arr[j - 1]):
            arr[j] = arr[j - 1]
            j -= 1
        arr[j] = item_to_insert

def merge(arr: List) -> None:
    i = 0
    j = 1
    result = []
    while i < len(arr) and j < len(arr):
        if arr[i][1] >= arr[j][0] and arr[i][1] <= arr[j][1]:
            arr[i][1] = arr[j][1]
            j += 1
        else:
            result.append(arr[i])
            i = j
            j += 2
    if i == len(arr) - 1 and result[len(result) - 1][1] < arr[i][0]:
        result.append(arr[i])
    return result

def main() -> int:
    n = int(input())
    arr = []
    [arr.append(list(map(int, input().split()))) for _ in range(n)]
    print(*arr)
    insertion_sort(arr)
    print(*arr)
    result = merge(arr)
    [print(*i) for i in result]
    return 0

if __name__ == '__main__':
    main()


import pygame as pg
import sys, random

pg.init()
pg.mixer.pre_init(frequency= 44100, size = 16, channels = 1, buffer = 516)
# make the sound better, so you had better set "pg.mixer.pre_init()" up. You don't need to care what's inside.
screen = pg.display.set_mode((380,600))
clock = pg.time.Clock()

# game image
red_bird1 = pg.image.load("flappy-bird-assets-master/sprites/redbird-downflap.png").convert_alpha()
red_bird2 = pg.image.load("flappy-bird-assets-master/sprites/redbird-midflap.png").convert_alpha()
red_bird3 = pg.image.load("flappy-bird-assets-master/sprites/redbird-upflap.png").convert_alpha()
bird_frame = [red_bird1,red_bird2,red_bird3]
bird_index = 0
bird_surface = bird_frame[bird_index]
bird_rect = bird_surface.get_rect(center = (60,250))
BIRDANIMATE = pg.USEREVENT +1
pg.time.set_timer(BIRDANIMATE, 200)
# pg.USEREVENT +1 因為不想與pg.USEREVENT搞混所以 + 1

bg = pg.image.load("flappy-bird-assets-master/sprites/background-day.png").convert()
bg = pg.transform.scale(bg, (380,600))

base =pg.image.load("flappy-bird-assets-master/sprites/base.png").convert()
base2 =pg.image.load("flappy-bird-assets-master/sprites/base.png").convert()
base = pg.transform.scale(base, (380,100))
base2 = pg.transform.scale(base2, (380,100))

pipe_surface = pg.image.load("flappy-bird-assets-master\sprites\pipe-red.png").convert()
pipe_surface = pg.transform.scale(pipe_surface,(65,380))
pipe_list = [] # each pipe position
SPAWNPIPE = pg.USEREVENT
pg.time.set_timer(SPAWNPIPE, 1500)
# pg.time.set_timer()的毫秒決定pipe之間的距離。

message = pg.image.load("flappy-bird-assets-master/sprites/message.png").convert_alpha()
message_rect = message.get_rect(center = (190, 300))

# font and score
score = 0
record_score = 0
font = pg.font.Font("04B_19.TTF", 40)

# render_font_score= font.render("Score" + render_font,True,(255,255,255))
# font_score_rect = render_font_score.get_rect(center=(190,50))

# base move
pos = 0
def base_move():
    global pos
    screen.blit(base,(pos,520))
    screen.blit(base2,(pos + 380,520))
    pos -= 2
    if pos == -380:
        pos = 0

# create pipe
def create_pipe():
    midtop_y = random.choice(pipe_top)
    pipe_rect_bottom = pipe_surface.get_rect(midtop=(400,midtop_y))
    pipe_rect_top = pipe_surface.get_rect(midbottom=(400,midtop_y -180))
    return [pipe_rect_bottom, pipe_rect_top]
def move_pipe(pipes):
    for pipe in pipes:
        pipe.centerx -= 2
        if pipe.centerx < -100:
            pipes.remove(pipe)
    return pipes
# !!!important: return 新的list
def draw_pipe(pipes):
    for pipe in pipes:
        if pipe.bottom >= 600:
            screen.blit(pipe_surface, pipe)
        else:
            flip_pipe = pg.transform.flip(pipe_surface, False, True)
            screen.blit(flip_pipe, pipe)

# 兩個有rect的物體，才能測試是否有碰撞
def check_collide(pipes):
    for pipe in pipes:
        if bird_rect.colliderect(pipe):
            death_sound.play()
            return False
    if bird_rect.y > 650 or bird_rect.y < -50:
        drop_sound.play()
        return False

    return True

def rotate(bird_surface):
    # bird_movement 從哪裡get到的??? 為何可從while中get到 bird_movement 卻不用寫在rotate()中???
    bird_surface = pg.transform.rotozoom(bird_surface, -bird_movement*5, 1)
    return bird_surface

#遊戲中的score
def game_score(font):
    render_font= font.render(str(int(score)),True,(255,255,255))

    font_rect = render_font.get_rect(center=(190,70))
    return render_font, font_rect
#遊戲開始畫面的score
def get_score(font):
    Score_font = font.render("Score " + str(int(score)), True, (255,255,255))
    Score_font_rect = Score_font.get_rect(center= (190,70))
    return Score_font,Score_font_rect
def score_record(font):
    Record_font = font.render("Record "+ str(int(record_score)), True, (255,255,255))
    Record_font_rect = Record_font.get_rect(center= (190,520))
    return Record_font,Record_font_rect
def compare_score(score,record_score):
    if score >= record_score:
        record_score = score
    return record_score

# BGM
flap_sound = pg.mixer.Sound("flappy-bird-assets-master/audio/wing.wav")
death_sound = pg.mixer.Sound("flappy-bird-assets-master/audio/hit.wav")
score_sound = pg.mixer.Sound("flappy-bird-assets-master/audio/point.wav")
drop_sound = pg.mixer.Sound("flappy-bird-assets-master/audio/die.wav")
# game variable
gravity = 0.15
bird_movement = 0
pipe_top = [300, 380, 450, 250]
play_game = False
score_sound_coundown = 100

while True:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            pg.quit()
            sys.exit()
        #必須先寫 event.type 再寫 event.key 字母a就是K_a、K_SPACE...
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_SPACE:
                # !!! important: 跳起來時也遵守等加速度運動，bird_movement等於0時 v=0 在最高點，然後往下墜
                bird_movement = 0
                bird_movement -= 5
                if play_game == True:
                    flap_sound.play()
        #每1.2秒就創建一個pipe
        if event.type == SPAWNPIPE:
            pipe_list.extend(create_pipe())
        if event.type == pg.MOUSEBUTTONDOWN:
            play_game = True
            # !!!important 重新開始，所有pipe_list要歸零，bird回到原位,bird_movement = 0
            pipe_list.clear()
            bird_rect.center = (60,250)
            bird_movement = 0
            score = 0
        if event.type == BIRDANIMATE:
            bird_index +=1
            if bird_index >= len(bird_frame):
                bird_index = 0
            bird_surface = bird_frame[bird_index]

    if play_game == True:
        screen.blit(bg, (0,0))
        # !!!important:  pipe_list = move_pipe(pipe_list) 新的list覆蓋舊的list
        pipe_list = move_pipe(pipe_list)
        draw_pipe(pipe_list)

        base_move()
        # player()
        # 重力加速度，為"等加速度"，因此寫兩層程式 bird_movement += gravity ,bird_rect.centery += bird_movement;
        # "跳起來"時也呈現"等加速度"，到最高點要掉下前的bird_movement == 0，如同再有重力的地點往上跳，起跳快，停在半空中後，往下掉。
        bird_movement += gravity
        bird_rect.centery += bird_movement

        # rotate bird
        # ???為何rotate()中一定要放red_bird1，不能到了def rotate: global red_bird
        rotated_red_bird1 = rotate(bird_surface)
        screen.blit(rotated_red_bird1,bird_rect)

        # score
        render_font, font_rect = game_score(font)
        screen.blit(render_font, font_rect)
        # when variable "score" get the "full number", play "score_sound"
        # 因為score要加100次才會等於1(整數)，所以設定score_sound_coundown = 100, 當它為0時 score_sound.play()
        score += 0.01
        score_sound_coundown -= 1
        if score_sound_coundown <= 0:
            score_sound.play()
            score_sound_coundown = 100

        # record_score唯有等到比第一局分數高的score，record_score 才會改變。
        record_score = compare_score(score, record_score)

        # colliderect
        play_game = check_collide(pipe_list)
    else:
        screen.blit(bg, (0,0))
        screen.blit(message, message_rect)

        Score_font, Score_font_rect = get_score(font)
        screen.blit(Score_font, Score_font_rect)
        Record_font,Record_font_rect = score_record(font)
        screen.blit(Record_font,Record_font_rect)

    pg.display.flip()
    clock.tick(120)

# centerx/ centery
# flappy bird 是因為重力加速度而掉下去，

# pygame.transform.flip(Surface, xbool左右, ybool 上下) )
# (flip vertically and horizontally) 左右或上下翻轉

# event.type == KEYDOWN or KEYUP 之後
# event.key == K_a(字母)、K_SPACE...
# event.unicode 有意義的英文字

# 每幾豪秒就觸發pg.USEREVENT
# something = pg.USEREVENT
# pg.time.set_timer(something, 1200)
# if event.type == something:

# append vs. extend
# x = [1, 2, 3]
# x.append([4, 5]) >>> [1, 2, 3, [4, 5]]
# x.extend([4, 5]) >>> [1, 2, 3, 4, 5]  "extend" concatenate the first list with another list

# List 和 for loop ，新的list 覆蓋舊的list
# Players = []
# while True:
#   Players.append(50)
#   Players = minus(Players)
#
# def minus(Players):
#   global Players
#   for player in Players:
#       player -= 5
#       return Players (新的list)
# print out >>>
# 1. [50]
# 2. [45,50]
# 3. [40,45,50]...

# !!!important
# while loop 中有定義的"變數"，在while中呼叫function時，def 中有這個變數出現，則會取while中的這個變數，而非while外的

# int() 能讓原本float的值，"將小數捨去"


#######################
# Automated continuous weight measurement.
# from weighing scale KERN 572
# for powder flow rate measurement.
#
#   KERN 572
#       t Tare.
#       w a weighing value (or unstable) is sent via RS 232 interface.
#       s a stable weighing value is sent via RS 232 interface.
#
#
#
#######################

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib
matplotlib.use('TkAgg')

import time
from time import sleep
from PySimpleGUI.PySimpleGUI import VSeparator
import serial
from serial.tools.list_ports import comports
import PySimpleGUI as sg

def main():
    ports = serial.tools.list_ports.comports()

    fig = matplotlib.figure.Figure(figsize=(6, 4), dpi=100)
    fig.set(xlabel='Time (s)', ylabel='Powder flow rate (g/s)',title='Powder Flow Rate')
    fig.annotate()

    setting_column = [
        [sg.Text("Ports", size=(10,1))],
        [sg.Listbox(values=ports, size=(50,6), enable_events=True, key='-PORTLIST-'), sg.Button("Connect", size=(10,6), key='-CONNECT-')],
        [sg.Text('_' * 65)],
        [sg.Text("Total Time", size=(10,1)), sg.Input(key='-TIME-', enable_events=True, size=(10,1)), sg.Text("Minutes")],
        [sg.Text("Interval", size=(10,1)), sg.Input(key='-INTER-', enable_events=True, size=(10,1)), sg.Text("Seconds")],
        [sg.Text("File", size=(10,1)), sg.Input(key='-FILE-', enable_events=True, size=(40,1)), sg.SaveAs(target='-FILE-')],
        [sg.Button("RUN", key='-RUN-')],
        [sg.Text('_' * 65)],
        [sg.Output(size=(65, 10))]

    ]
    result_column = [
        [sg.Canvas(key='-CANVAS-', size=(80, 40))]

    ]

    layout = [
        [
            sg.Column(setting_column),
            sg.VSeparator(),
            sg.Column(result_column)
        ]
    ]

    window = sg.Window("Powder Flow Measurement", layout, finalize=True)

    fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig)

    enable_run = enable_connect = False
    ttime = interval = 0
    filename = 'tempfile'

    while True:
        event, values = window.read()
        if event in (sg.WIN_CLOSED, 'Exit'):                # always check for closed window
            break
        if event == '-PORTLIST-' and len(values['-PORTLIST-'])==1:
            port = values['-PORTLIST-'][0].name
            print(port + " selected")
            enable_connect=True
        elif event == '-CONNECT-' and enable_connect:
            try:
                scale = ScaleKern(port, 9600)
                if scale.connect():
                    enable_run = True
                    enable_connect = False
            except:
                print("No connection")
        elif event == '-TIME-':
            if values['-TIME-'].isnumeric():
                ttime = int(values['-TIME-'])
                # scale.setruntime(int(values['-RUNTIME-']))
                print("Total measure time set to " + values['-TIME-'] + " minutes")
        elif event == '-INTER-':
            if values['-INTER-'].isnumeric():
                interval = int(values['-INTER-'])
                print("Interval set to " + values['-INTER-'] + " seconds")
        elif event == '-FILE-':
            filename = values['-FILE-']
            #print (filename)
        elif event == '-RUN-' and enable_run:
            if filename != '' and ttime>0 and interval>0:
                enable_connect=False
                scale.start(ttime, interval, filename,fig_callback)

def draw_figure(canvas, figure):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

def fig_callback(x,y):
    ax, ay =[]

    ax = ax.append(x) #time
    ay = ay.append(y) # weight
    ayrate = np.gradient(ay,ax) #rate
    aymean = np.mean(ayrate)
    aystd = np.std(ayrate)

    fig.plot(ax,ayrate,'x',label='what is what')

    return

if __name__ == '__main__':
    main()

class ScaleKern:

    def __init__(self, port, baudrate):
        self.port = port
        self.bdrate = baudrate
        self.timeout = 0.3

    def connect(self):
        s = serial.Serial(self.port, self.bdrate, timeout=self.timeout)
        s.reset_input_buffer()      #clear buffer
        s.write(b'w')
        msg = s.readline()
        if msg != "":
            print("Kern scale connected on " + self.port)
            return 0
        else:
            print("Kern scale NOT connected")
            s.close()
            return 1

    def start(self, ttime, inter, filename, callback):

        runtime=0
        f = open(filename, 'w')
        #tare balance
        self.s.write(b't')
        #start timer
        tstart = time.perf_counter()

        # read data and save to file
        while runtime < ttime:
            sleep(inter)
            runtime += inter
            self.s.reset_input_buffer()      #clear buffer
            self.s.write(b'w')
            strweight = self.s.readline()
            realtimer = time.perf_counter() - tstart
            print(f'{runtime}, {realtimer:.2f}, {strweight}')
            nweight = strweight.translate({ord(i): None for i in 'bg\\rn\' '})
            f.write(str(runtime).replace("b", " ") + ',' + str(realtimer) + ',' + str(nweight)+'\n') #write time and weight into text file
            callback(realtimer,float(nweight))

        #end of program
        f.close()
        self.s.close()

        return 0


from model import *
import sys
from io import StringIO
import pytest

def get_value(number):
    old_stdout = sys.stdout
    sys.stdout = StringIO()
    scope = Scope()
    Print(number).evaluate(scope)
    value = int(sys.stdout.getvalue())
    sys.stdout = old_stdout
    return value

class TestScope:
    def test_scope_simple(self):
        parent = Scope()
        numb1 = Number(10)
        parent['a'] = numb1
        assert parent['a'] is numb1
        numb2 = Number(-2)
        parent['b'] = numb2
        assert parent['b'] is numb2

    def test_scope_take_from_parent(self):
        parent = Scope()
        scope = Scope(parent)
        numb = Number(10)
        parent['a'] = numb
        assert scope['a'] is numb

    def test_scope_have_func(self):
        parent = Scope()
        numb = Function([], [])
        parent['f'] = numb
        assert parent['f'] is numb

class TestNumber:

    def test_number(self):
        scope = Scope()
        n = Number(43)
        assert get_value(n) == 43
        assert n.evaluate(scope) is n

class TestPrint:

    def test_print_number(self):
        n = Number(43)
        assert get_value(n) == 43

    def test_print_evaluate(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        res = Print(BinaryOperation(Number(30),
                                    '+',
                                    Number(13))).evaluate(scope)
        assert get_value(res) == 43
        assert sys.stdout.getvalue() == '43\n'

class TestRead:
    def test_read(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdin', StringIO('43\n'))
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        read_res = Read('a').evaluate(scope)
        Print(Reference('a')).evaluate(scope)
        assert sys.stdout.getvalue() == '43\n'
        assert get_value(read_res) == 43

class TestUnaryOperation:

    def test_unary_operation_not(self):
        scope = Scope()
        n = Number(43)
        not_n = UnaryOperation('!', n).evaluate(scope)
        assert get_value(not_n) == 0
        n = Number(0)
        not_n = UnaryOperation('!', n).evaluate(scope)
        assert get_value(not_n) != 0

    def test_unary_operation_minus(self):
        scope = Scope()
        n = Number(43)
        minus_n = UnaryOperation('-', n).evaluate(scope)
        assert get_value(minus_n) == -43

    def test_unary_operation_evaluate(self):
        scope = Scope()
        n = Number(0)
        ev = UnaryOperation('-', UnaryOperation('!', n))
        assert get_value(ev) != 0
        n = Number(43)
        ev = UnaryOperation('-', UnaryOperation('-', n))
        assert get_value(ev) == 43

class TestBinaryOperation:

    def test_binary_operation_sum(self):
        a = Number(43)
        b = Number(10)
        res = BinaryOperation(a, '+', b)
        assert get_value(res) == 53

    def test_binary_operation_dif(self):
        a = Number(43)
        b = Number(10)
        res = BinaryOperation(a, '-', b)
        assert get_value(res) == 33

    def test_binary_operation_mult(self):
        a = Number(43)
        b = Number(10)
        res = BinaryOperation(a, '*', b)
        assert get_value(res) == 430

    def test_binary_operation_del(self):
        a = Number(43)
        b = Number(10)
        res = BinaryOperation(a, '/', b)
        assert get_value(res) == 4

    def test_binary_operation_ost(self):
        scope = Scope()
        a = Number(43)
        b = Number(10)
        res = BinaryOperation(a, '%', b)
        assert get_value(res) == 3

    def test_binary_operation_and(self):
        res = BinaryOperation(Number(43), '&&', Number(0))
        assert get_value(res) == 0

    def test_binary_operation_or(self):
        res = BinaryOperation(Number(43), '||', Number(0))
        assert get_value(res) != 0

    def test_binary_operation_more(self):
        res = BinaryOperation(Number(43), '>', Number(43))
        assert get_value(res) == 0

    def test_binary_operation_less(self):
        res = BinaryOperation(Number(43), '<', Number(53))
        assert get_value(res) != 0

    def test_binary_operation_more_or_eq(self):
        res = BinaryOperation(Number(43), '>=', Number(43))
        assert get_value(res) != 0

    def test_binary_operation_less_or_eq(self):
        res = BinaryOperation(Number(43), '<=', Number(42))
        assert get_value(res) == 0

    def test_binary_operation_eq(self):
        res = BinaryOperation(Number(43), '==', Number(33))
        assert get_value(res) == 0

    def test_binary_operation_not_eq(self):
        res = BinaryOperation(Number(43), '!=', Number(33))
        assert get_value(res) != 0

    def test_binary_operation_evaluate(self):
        scope = Scope()
        a = Number(43)
        b = Number(10)
        dif = BinaryOperation(a, '-', b)
        eq = BinaryOperation(dif, '==', Number(33))
        assert get_value(eq) != 0

class TestFunction:

    def test_function_empty_arguments(self):
        scope = Scope()
        func = Function([], [Number(43)])
        res = func.evaluate(scope)
        assert get_value(res) == 43

    def test_function_many_arguments_and_evaluate(self):
        scope = Scope()
        scope['a'] = Number(33)
        scope['b'] = Number(10)
        func = Function(('a', 'b'), [BinaryOperation(Reference('a'),
                                                     '+',
                                                     Reference('b'))])
        res = func.evaluate(scope)
        assert get_value(res) == 43

    def test_function_big_body(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        scope['a'] = Number(33)
        scope['b'] = Number(10)
        func = Function(('a', 'b'),
                        [Print(Reference('a')),
                         Reference('a'),
                         Reference('b')])
        res = func.evaluate(scope)
        Print(res).evaluate(scope)
        assert sys.stdout.getvalue() == '33\n10\n'

    def test_function_empty_body(self, monkeypatch):
        scope = Scope()
        Function(('a'), []).evaluate(scope)

class TestFunctionDefinition:

    def test_function_definition_simple(self):
        scope = Scope()
        func = Function([], [BinaryOperation(Number(10), '+', Number(33))])
        func2 = FunctionDefinition('func', func).evaluate(scope)
        assert scope['func'] is func
        assert func2 is func

class TestReference:

    def test_reference_number(self, monkeypatch):
        scope = Scope()
        a = Number(43)
        scope['a'] = a
        a2 = Reference('a').evaluate(scope)
        assert a is a2

    def test_reference_function(self, monkeypatch):
        scope = Scope()
        func = Function([], [])
        scope['function'] = func
        func2 = Reference('function').evaluate(scope)
        assert func is func2

class TestConditional:

    def test_conditional_without_if_false(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        res1 = Conditional(Number(1), [Print(Number(1))]).evaluate(scope)
        Conditional(Number(0), [Print(Number(1))]).evaluate(scope)
        assert sys.stdout.getvalue() == '1\n'
        assert get_value(res1) == 1

    def test_conditional_evaluate_condtion(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        Conditional(BinaryOperation(Number(3), '==', Number(3)),
                    [Print(Number(1))],
                    [Print(Number(0))]).evaluate(scope)
        Conditional(BinaryOperation(Number(2), '==', Number(3)),
                    [Print(Number(1))],
                    [Print(Number(0))]).evaluate(scope)
        assert sys.stdout.getvalue() == '1\n0\n'

    def test_conditional_return(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        res1 = Conditional(BinaryOperation(Number(3), '==', Number(3)),
                           [Number(1)],
                           [Number(0)]).evaluate(scope)
        res2 = Conditional(BinaryOperation(Number(2), '==', Number(3)),
                           [Number(1)],
                           [Number(0)]).evaluate(scope)
        assert get_value(res1) == 1
        assert get_value(res2) == 0

    def test_conditional_empty(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        Conditional(Number(0),
                    [Print(Number(2))],
                    []).evaluate(scope)
        Conditional(Number(43),
                    [],
                    []).evaluate(scope)
        Conditional(Number(0),
                    [],
                    []).evaluate(scope)
        Conditional(Number(43),
                    [],
                    [Print(Number(3))]).evaluate(scope)
        assert sys.stdout.getvalue() == ''

    def test_conditional_empty_with_result(self):
        scope = Scope()
        res = Conditional(Number(43),
                          [Number(34)],
                          []).evaluate(scope)
        assert get_value(res) == 34
        res = Conditional(Number(0),
                          [],
                          [Number(334)]).evaluate(scope)
        assert get_value(res) == 334

    def test_conditional_big_body_if_true(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        Conditional(Number(43),
                    [Print(Number(1)), Print(Number(2))],
                    [Print(Number(3)), Print(Number(4))]).evaluate(scope)
        assert sys.stdout.getvalue() == '1\n2\n'

    def test_conditional_big_body_if_false(self, monkeypatch):
        monkeypatch.setattr(sys, 'stdout', StringIO())
        scope = Scope()
        Conditional(Number(0),
                    [Print(Number(1)), Print(Number(2))],
                    [Print(Number(3)), Print(Number(4))]).evaluate(scope)
        assert sys.stdout.getvalue() == '3\n4\n'

class TestFunctionCall:

    def test_function_call_with_simple(self):
        parent = Scope()
        FunctionDefinition(
            'max',
            Function(('a', 'b'),
                     [Conditional(BinaryOperation(Reference('a'),
                                                  '>=',
                                                  Reference('b')),
                                  [Reference('a')],
                                  [Reference('b')])])
        ).evaluate(parent)
        n = FunctionCall(Reference('max'),
                         [Number(6), Number(5)]).evaluate(parent)
        assert get_value(n) == 6

    def test_function_call_very_tricky(self):
        parent = Scope()
        FunctionDefinition(
            'strange_max',
            Function(
                ('a', 'b'),
                [Conditional(
                    BinaryOperation(Reference('a'),
                                    '<=',
                                    Reference('b')),
                    [Reference('b')],
                    [FunctionCall(Reference('strange_max'),
                                  [Reference('b'),
                                  Reference('a')])]
                )]
            )
        ).evaluate(parent)
        n = FunctionCall(Reference('strange_max'),
                         [Number(6), Number(5)]).evaluate(parent)
        assert get_value(n) == 6

class TestIntegration:

    def test_factorial(self):
        parent = Scope()
        FunctionDefinition(
            'factorial',
            Function(
                ('a'),
                [Conditional(
                    BinaryOperation(Reference('a'),
                                    '<=',
                                    Number(1)),
                    [Reference('a')],
                    [BinaryOperation(FunctionCall(
                                        Reference('factorial'),
                                        [BinaryOperation(Reference('a'),
                                                         '-',
                                                         Number(1))]
                                     ),
                     '*', Reference('a'))]
                )]
            )
        ).evaluate(parent)
        n = FunctionCall(Reference('factorial'),
                         [Number(5)]).evaluate(parent)
        assert get_value(n) == 120

    def test_fibonacci(self):
        parent = Scope()
        FunctionDefinition(
            'fib',
            Function(
                ('a'),
                [Conditional(
                    BinaryOperation(Reference('a'),
                                    '<=',
                                    Number(1)),
                    [Reference('a')],
                    [BinaryOperation(
                        FunctionCall(
                            Reference('fib'),
                            [BinaryOperation(Reference('a'),
                                             '-',
                                             Number(1))]
                        ),
                        '+',
                        FunctionCall(Reference('fib'),
                                     [BinaryOperation(Reference('a'),
                                                      '-',
                                                      Number(2))]))]
                )]
            )
        ).evaluate(parent)
        n = FunctionCall(Reference('fib'),
                         [Number(8)]).evaluate(parent)
        assert get_value(n) == 21

    def test_average(self):
        parent = Scope()
        FunctionDefinition(
            'average',
            Function(('a', 'b'),
                     [BinaryOperation(BinaryOperation(Reference('a'),
                                                      '+',
                                                      Reference('b')),
                                      '/',
                                      Number(2))])
        ).evaluate(parent)
        n = FunctionCall(Reference('average'),
                         [Number(4), Number(6)]).evaluate(parent)
        assert get_value(n) == 5


"""
Train_classifier.
"""

import torch
from helper import get_formatted_time

def train_classifier(model, criterion, optimizer, train_loader, valid_loader,
                     epochs, run_on_gpu):

    if run_on_gpu and torch.cuda.is_available():
        device = torch.device("cuda")
        print("GPU is available and being used")
    else:
        device = torch.device("cpu")
        print("GPU is not available, using CPU instead")
        print("\n*** processing will take a long time ***\n")

    print("\n*** train_classifier: epochs: {} ***\n".format(epochs))

    model.to(device)

    print("Start training time:", get_formatted_time())
    steps = 0
    running_loss = 0
    print_every = 30
    for epoch in range(epochs):
        for inputs, labels in train_loader:
            steps += 1
            #             print("training processing batch {}". format(steps))
            # Move input and label tensors to the default device
            inputs, labels = inputs.to(device), labels.to(device)

            logps = model.forward(inputs)
            loss = criterion(logps, labels)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            if steps % print_every == 0:
                test_loss = 0
                accuracy = 0
                model.eval()
                with torch.no_grad():
                    for inputs, labels in valid_loader:
                        inputs, labels = inputs.to(device), labels.to(device)
                        logps = model.forward(inputs)
                        batch_loss = criterion(logps, labels)

                        test_loss += batch_loss.item()

                        # Calculate accuracy
                        ps = torch.exp(logps)
                        top_p, top_class = ps.topk(1, dim=1)
                        equals = top_class == labels.view(*top_class.shape)
                        accuracy += torch.mean(equals.type(torch.FloatTensor)).item()

                print(get_formatted_time(), " - ", steps, " "
                                                          f"Epoch {epoch + 1}/{epochs}.. "
                                                          f"Train loss: {running_loss / print_every:.3f}.. "
                                                          f"Test loss: {test_loss / len(valid_loader):.3f}.. "
                                                          f"Test accuracy: {accuracy / len(valid_loader):.3f}")
                running_loss = 0
                model.train()

    print("End training time:", get_formatted_time())

    return model, epochs


#needed for CERTIFICATE_VERIFY_FAILED in downloading nltk
import ssl
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = _create_unverified_https_context
#####

from math import log10, sqrt
from linecache import getline
import nltk
import heapq

nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')

from nltk.tokenize import RegexpTokenizer
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer

##---------------- UTILS: functions ----------------##

#merge between 2 posting lists
def intersect2lists(p1,p2):
    answer=[]
    i1=0
    i2=0
    while(i1 < len(p1) and i2<len(p2)):
        if(p1[i1][0]==p2[i2][0]):   #doc_ID1==doc_ID2
            answer.append([p1[i1][0]])    #doc_id
            i1=i1+1
            i2=i2+1
        elif(p1[i1][0]<p2[i2][0]):
            i1=i1+1
        else:
            i2=i2+1
    return answer

#merge between ALL postings
def boolean_search(query_terms,index):
    j=0
    n_query=len(query_terms)
    exception=True
    answer=[]
    while(exception):
        try:
            answer=index[query_terms[j]][1:]
            exception=False
        except:
            j=j+1
            if(j>n_query):
                answer=[]
                return answer
    for i in range(j+1,len(query_terms)):
        try:
            index[query_terms[i]]
            answer=intersect2lists(answer,index[query_terms[i]][1:])
        except:
            continue
    docs=[]
    for val in answer:
        docs.append(val[0])
    return docs

#union between 2 postings
def union2lists(p1,p2):
    answer=[]
    i1=0
    i2=0
    while(i1 < len(p1) and i2<len(p2)):
        if(p1[i1][0]==p2[i2][0]):   #doc_ID1==doc_ID2
            answer.append([p1[i1][0]])    #doc_id
            i1=i1+1
            i2=i2+1
        elif(p1[i1][0]<p2[i2][0]):
            answer.append([p1[i1][0]])
            i1=i1+1
        else:
            answer.append([p2[i2][0]])
            i2=i2+1

    #if one list terminated and the other not
    while(i1 < len(p1)):
        answer.append([p1[i1][0]])
        i1=i1+1
    while(i2 < len(p2)):
        answer.append([p2[i2][0]])
        i2=i2+1
    return answer

#return all docs with AT LEAST one query term
def union_search(query_terms,index):
    j=0
    n_query=len(query_terms)
    exception=True
    answer=[]
    while(exception):
        try:
            answer=index[query_terms[j]][1:]
            exception=False
        except:
            j=j+1
            if(j>n_query):
                answer=[]
                return answer
    for i in range(j+1,len(query_terms)):
        try:
            index[query_terms[i]]
            answer=union2lists(answer,index[query_terms[i]][1:])
        except:
            continue
    docs=[]
    for val in answer:
        docs.append(val[0])
    return docs

def search(query_terms, index, bool):
    if(bool):
        #AND of docIDs (docs containing all terms)
        return boolean_search(query_terms,index)
    else:
        #OR of docIDs (docs containing at least one term)
        return union_search(query_terms,index)

#computes query length
def query_len(query_terms,index,docs):
    score=0
    for term, occ in query_terms.items():
        try:
            tf_idf=log10(occ + 1)*log10(docs/index[term][0][0])
            score=score + tf_idf*tf_idf
        except:
            #term not in the index
            continue
    return sqrt(score)

#cosine similarity scores computation
def cos_sim(query_terms,index,n_docs,docs,query_len):
    scores={}
    for term, occ in query_terms.items():
        w_tq=log10(1+int(occ))
        df=0
        try:
            df=int(index[term][0][0])
        except:
            continue

        for posting in index[term][1:]:
            doc_id=posting[0]
            tf=posting[1]
            if doc_id not in docs:
                continue
            w_td=log10(1+int(tf))
            idf=log10(n_docs/df)
            scores[doc_id]=scores.get(doc_id,0) + float(w_td * idf * w_tq * idf)

    for doc in scores.keys():
        scores[doc]=scores[doc] /(float(lengths[doc-1])*query_len)

    return scores

def top_k(scores,k):
    l=0
    heap=[]
    for docID,score in scores.items():
        if(l<k):
            heapq.heappush(heap,(score,docID))
            l=l+1
        elif(score>=heap[0][0]):
            heapq.heappushpop(heap,(score,docID))

    sorted_docs=heapq.nlargest(k,heap)
    return sorted_docs

#loading the index from the file
def load_index():
    index= {}     #dictionary: (term,[postings list]), posting list=[docID,tf], posting list[0]=[df,0]
    with open("index_file.tsv", "r") as index_file:
        n_docs=0
        lengths=[]
        l=0
        for line in index_file:
            if(l==0):
                n_docs=int(line) #total number of documents
                l=l+1
                continue
            if(l==1):
                lengths=line.split("\t")[1:]
                l=l+1
                continue

            fields=line.split("\t")
            term=fields[0]
            df=int(fields[1])
            index[term]=[[df,0]]
            for i in range(2,2+df):
                posting=fields[i].split(",")
                doc_ID=int(posting[0])
                tf=int(posting[1])
                index[term].append([doc_ID,tf])
    return index, lengths, n_docs

##---------------- MAIN ----------------##

index, lengths, n_docs = load_index()

#query processing
stop_words = set(stopwords.words('italian'))
stemmer = SnowballStemmer(language='italian')
tokenizer = RegexpTokenizer(r"[a-zA-Z]+")

print(" ____________________________")
print("|                            |")
print("| Eva's simple search engine |")
print("|____________________________|")
print("This is a simple search engine for kijiji jobs announcements, \n feel free to insert queries or type 'q' if you want to quit \n Enjoy! =) \n")
while(1):
    query=input("What are you looking for? ")
    if(query=='q'):
        print("Bye, have a nice day!")
        break

    tokens = tokenizer.tokenize(query)
    query_terms={}
    for w in tokens:
        if w not in stop_words and len(w)>1:
            w=w.lower()
            term=stemmer.stem(w)
            if term not in query_terms:
                query_terms[term]=1
            else:
                occ=query_terms[term]
                query_terms[term]=occ+1

    keys=list(query_terms.keys())
    query_length=query_len(query_terms,index,n_docs)

    #docs=search(keys,index, True)      #if you want to test the search engine in boolean search (true)
    docs=search(keys,index, False)

    scored_docs=cos_sim(query_terms,index,n_docs,docs,query_length)
    top_10=top_k(scored_docs,10)

    #results
    results=len(top_10)
    if(results==0):
        print("Sorry, there is NO Document matching your query, try with another formulation!")
    else:
        print(str(len(docs))+" results found, showing the TOP-10:")

    for i in range(results):
        doc=top_10[i][1]
        score=top_10[i][0]
        print("------------------------------------")
        print(str(i+1)+". doc_ID: "+str(doc)+" score:"+"{0:.3f}".format(score))
        print(getline("jobs.tsv",doc))
        print("------------------------------------")


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

'''
Class for Deep Sets architecture (as developed in
https://arxiv.org/abs/1703.06114). This models a permutation invariant scalar
function as f({x_i}) = \rho(\sum_i \phi(x_i)), where phi and rho are neural
networks.
'''

class Deep_Sets(nn.Module):
  def __init__(self, input_dim, width, depth_phi, depth_rho):
    '''
    Initializes a Deep Sets architecture

    Parameters:
      input_dim: dimension of input to the deep sets (i.e. dimension of x_i)
      width: width of the networks phi and rho (we've chosen these widths to be
        the same)
      depth_phi, depth_rho: depth of the networks phi and rho, respectively
    '''

    # Initializes as a nn.Module
    super().__init__()

    # Set parameters
    self.width = width
    self.depth_phi = depth_phi
    self.depth_rho = depth_rho
    self.input_dim = input_dim

    # Creates fully connected (fc) layers for phi network
    self.phi_fc0 = nn.Linear(self.input_dim, self.width)
    self.phi_fcs = nn.ModuleList([nn.Linear(self.width, self.width)
                                  for i in range(self.depth_phi-1)])

    # Creates fully connected (fc) layers for rho network
    self.rho_fcs = nn.ModuleList([nn.Linear(self.width, self.width)
                                  for i in range(self.depth_rho-1)])
    self.rho_fc_end = nn.Linear(self.width, 1)

  def forward(self, x_emb, mask):
    '''
    Passes the data x_emb (an array of embedded particle positions) through the
    deep sets network.

    Parameters:
      x_emb: an array of dimension (n_samples, n_particles, input_dim), which
        represents n_samples samples of n_particles particle positions, each
        embedded into a latent space of dimension input_dim. Since particle
        number may fluctuate, x_emb may contain entries corresponding to
        non-existent particles; these take value 0 and are masked out by the
        variable 'mask'.
      mask: a Boolean-valued array of dimension (n_samples, n_particles) used to
        remove entries corresponding to non-existent particles when passed through
        the deep sets network. Takes value 1 if particle exists, 0 if
        non-existent.

    Returns:
      y: an array of dimension (n_samples, 1) containing the output of the deep
        sets network across the n_samples samples
    '''

    # Pass through phi network
    y = torch.tanh(self.phi_fc0(x_emb))
    for l in self.phi_fcs:
      y = torch.tanh(l(y))

    # Pooling; mask is used to remove non-existent particle entries
    y = torch.sum(y*mask, axis=-2)

    # Pass through rho network
    for l in self.rho_fcs:
      y = torch.tanh(l(y))
    y = F.softplus(self.rho_fc_end(y))    # softplus enforces positivity

    return y


import urllib.request

try:
    url = 'https://inflatus.io'

    headers = {}
    headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
    req = urllib.request.Request(url, headers = headers)
    resp = urllib.request.urlopen(req)
    respData = resp.read()

    saveFile = open('withHeaders.txt','w')
    saveFile.write(str(respData))
    saveFile.close()
except Exception as e:
    print(str(e))


'''
Created on Aug 31, 2011

@author: Piotr
'''
import unittest
from generator.scene.tests.SceneGeneratorTestsBase import SceneGeneratorTestsBase
from mockito.mockito import verify
from math import radians, sin, cos
from generator.data.GeneratorInterval import GeneratorInterval
from generator.data.ObjectPose import ObjectPose
from generator.data.SceneDescription import SceneDescription
from generator.scene.SceneGenerators import DoubleAxisSceneGenerator

class DoubleAxisSceneGeneratorTests(unittest.TestCase, SceneGeneratorTestsBase):

    def setUp(self):
        self.initTranslate = [5, 0, 0]
        self.initRotate = [radians(90), radians(0), radians(90)]

        self.alfa = GeneratorInterval(0, 180, 90)
        self.radius = 5

    def tearDown(self):
        pass

    def test_generation_of_sinle_line_of_scenes(self):
        '''
            Using one level of vertical rotation: the output should be the same as the
            @see: SingleAxisSceneGenerator.
        '''

        # no beta moves too much
        beta = GeneratorInterval(0, 0)

        generatorDesc = self.getGeneratorDescription(self.alfa, beta, self.initTranslate)

        initCamera = ObjectPose(self.initTranslate, self.initRotate)
        initAnchor = self.getInitAnchor()

        # scene 1 (initial)
        translate_1 = self.initTranslate
        rotate_1 = self.initRotate
        expected_scene_1 = SceneDescription(ObjectPose(translate_1, rotate_1), initAnchor)

        # scene 2
        translate_2 = [0, 5, 0]
        rotate_2 = [radians(90), radians(0), radians(180)]
        expected_scene_2 = SceneDescription(ObjectPose(translate_2, rotate_2), initAnchor)

        # scene 3
        translate_3 = [-5, 0, 0]
        rotate_3 = [radians(90), radians(0), radians(270)]
        expected_scene_3 = SceneDescription(ObjectPose(translate_3, rotate_3), initAnchor)

        # act
        generator = DoubleAxisSceneGenerator(
                                             generatorDesc=generatorDesc,
                                             initCamera=initCamera,
                                             initAnchor=initAnchor)
        scenes = generator.prepareScenes()

        # verify calling generator intervals
        verify(generatorDesc, atleast=1).alfa
        verify(generatorDesc, atleast=1).beta

        self.assertEqual(3, len(scenes), "Number of scenes generated should be equal to 3")

        # assertions about each scene values
        self.assertEqual(scenes[0], expected_scene_1,
                         self.getDifferMessage(expected_scene_1, scenes[0]))
        self.assertEqual(scenes[1], expected_scene_2,
                         self.getDifferMessage(expected_scene_2, scenes[1]))
        self.assertEqual(scenes[2], expected_scene_3,
                         self.getDifferMessage(expected_scene_3, scenes[2]))

    def test_generation_of_two_lines_of_scene(self):
        '''
            Should produce two lines of vertical rotation the output should be the
            same as the two independent runs in @see: SingleAxisSceneGenerator.
        '''
        # gets beta movements for 0 and 30 !
        beta = GeneratorInterval(0, 30, 30)

        generatorDesc = self.getGeneratorDescription(self.alfa, beta, self.initTranslate)

        initCamera = ObjectPose(self.initTranslate, self.initRotate)
        initAnchor = self.getInitAnchor()

        # setting up expected scenes (line 1)
        x_beta = round(cos(radians(30)), 15) * self.radius
        z_beta = round(sin(radians(30)), 15) * self.radius

        # scene 1 (initial)
        translate_1 = self.initTranslate
        rotate_1 = self.initRotate
        expected_scene_1 = SceneDescription(ObjectPose(translate_1, rotate_1), initAnchor)

        # scene 2
        translate_2 = [0, 5, 0]
        rotate_2 = [radians(90), radians(0), radians(180)]
        expected_scene_2 = SceneDescription(ObjectPose(translate_2, rotate_2), initAnchor)

        # scene 3
        translate_3 = [-5, 0, 0]
        rotate_3 = [radians(90), radians(0), radians(270)]
        expected_scene_3 = SceneDescription(ObjectPose(translate_3, rotate_3), initAnchor)

        # second line of scenes

        # scene 4
        translate_4 = [x_beta, 0, z_beta]
        rotate_4 = [radians(60), radians(0), radians(90)]
        expected_scene_4 = SceneDescription(ObjectPose(translate_4, rotate_4), initAnchor)

        # scene 5
        translate_5 = [0, x_beta, z_beta]
        rotate_5 = [radians(60), radians(0), radians(180)]
        expected_scene_5 = SceneDescription(ObjectPose(translate_5, rotate_5), initAnchor)

        # scene 6
        translate_6 = [-x_beta, 0, z_beta]
        rotate_6 = [radians(60), radians(0), radians(270)]
        expected_scene_6 = SceneDescription(ObjectPose(translate_6, rotate_6), initAnchor)

        # act
        generator = DoubleAxisSceneGenerator(
                                             generatorDesc=generatorDesc,
                                             initCamera=initCamera,
                                             initAnchor=initAnchor)
        scenes = generator.prepareScenes()

        # verify calling generator intervals
        verify(generatorDesc, atleast=1).alfa
        verify(generatorDesc, atleast=1).beta

        self.assertEqual(6, len(scenes), "Number of scenes generated should be equal to 6")

        # assertions about each scene values
        self.assertEqual(scenes[0], expected_scene_1,
                         self.getDifferMessage(expected_scene_1, scenes[0]))
        self.assertEqual(scenes[1], expected_scene_2,
                         self.getDifferMessage(expected_scene_2, scenes[1]))
        self.assertEqual(scenes[2], expected_scene_3,
                         self.getDifferMessage(expected_scene_3, scenes[2]))

        self.assertEqual(scenes[3], expected_scene_4,
                         self.getDifferMessage(expected_scene_4, scenes[3]))
        self.assertEqual(scenes[4], expected_scene_5,
                         self.getDifferMessage(expected_scene_5, scenes[4]))
        self.assertEqual(scenes[5], expected_scene_6,
                         self.getDifferMessage(expected_scene_6, scenes[5]))

if __name__ == "__main__":
    unittest.main()


import numpy as np

# Hyper-parameter search space for grid search
model_param_map = {
    "BernoulliNB": {
        "alpha": 10.0 ** -np.arange(1, 7),
        "binarize": [*np.linspace(0.0, 1, 3)],
        "fit_prior": [True, False],
    },
    "ComplementNB": {
        "alpha": np.linspace(0.1, 1, 3),
        "fit_prior": [True, False],
        "norm": [True, False],
    },
    "DecisionTreeClassifier": {
        "criterion": ["gini", "entropy"],
        "max_depth": np.arange(3, 15),
    },
    "ExtraTreeClassifier": {
        "criterion": ["gini", "entropy"],
        "splitter": ["random", "best"],
        "max_depth": np.arange(3, 15),
    },
    "GradientBoostingClassifier": {
        "loss": ["deviance"],
        "min_samples_split": np.linspace(0.1, 0.5, 3),
        "min_samples_leaf": np.linspace(0.1, 0.5, 3),
        "max_depth": np.arange(3, 8),
        "max_features": ["log2", "sqrt"],
        "criterion": ["friedman_mse", "mse"],
        "n_estimators": [10],
    },
    "HistGradientBoostingClassifier": {
        "loss": ["auto", "categorical_crossentropy"],
        "learning_rate": [0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2],
        "max_depth": np.arange(3, 15),
    },
    "KNeighborsClassifier": {
        "n_neighbors": np.arange(3, 15),
        "weights": ["uniform", "distance"],
        "metric": ["euclidean", "manhattan"],
    },
    "Perceptron": {
        "alpha": 10.0 ** -np.arange(1, 3),
        "tol": [1, 0.1, 0.01, 0.001, 0.0001],
    },
    "RandomForestClassifier": {
        "n_estimators": [200, 500],
        "max_features": ["auto", "sqrt", "log2"],
        "max_depth": [4, 5, 6, 7, 8],
        "criterion": ["gini", "entropy"],
        "random_state": [42],
    },
    "RidgeClassifier": {
        "alpha": 10.0 ** -np.arange(1, 3),
        "tol": [1, 0.1, 0.01, 0.001, 0.0001],
    },
    "SGDClassifier": {"alpha": [0.0001, 0.001, 0.01, 0.1, 1, 10]},
}


import re
from datetime import datetime

import numpy as np

def parse_line(line):
    # [1518 - 11 - 01 00: 00] Guard  # 10 begins shift
    r = r'(\d+).*?(\d+).*?(\d+).*?(\d+).*?(\d+)\] (.*)'
    m = re.findall(r, line)[0]
    # print(line)
    # print(m)
    d = datetime(int(m[0]), int(m[1]), int(m[2]), int(m[3]), int(m[4]))
    return d, m[5]
    #return int(num), int(x), int(y), int(w), int(h)

serial_number = 9221

def power_level(x, y, serial_number=serial_number):
    rack_id = (x + 10)
    v = (rack_id * y + serial_number) * rack_id
    if len(str(v)) >= 3:
        h = int(str(v)[-3])
    else:
        h = 0
    return h - 5

def parse_line_ints(line):
    r = r'-?(\d+)'
    result = [int(x) for x in re.findall(r, line)]
    return result

def part1(input):
    #lines = input.read().split('\n')
    grid = np.zeros(shape=(300, 300), dtype=int)

    for x in range(300):
        for y in range(300):
            grid[x, y] = power_level(x, y, 9221)

    result = (-1, -1)

    for x in range(298):
        for y in range(298):
            total_power = grid[x, y] + grid[x+1, y] + grid[x+2, y] + grid[x, y+1] + grid[x+1, y+1] + grid[x+2, y+1] + grid[x, y+2] + grid[x+1, y+2] + grid[x+2, y+2]
            if total_power > result[1]:
                result = ((x, y), total_power)

    print(result)

def part2(input):
    grid = np.zeros(shape=(300, 300), dtype=int)

    for x in range(300):
        for y in range(300):
            grid[x, y] = power_level(x, y, 9221)

    result = (-1, -1, -1)

    for square in range(3, 20):
        print(square)
        for x in range(301 - square):
            for y in range(301 - square):
                total_power = np.sum(grid[x:x+square,y:y+square])

                if total_power > result[1]:
                    result = ((x, y, square), total_power)

    print(result)

def main():
    # print(neighbors4((4, 8)))
    # print(neighbors8((4, 8)))
    # print(cityblock_distance((1, 1), (4, 1)))

    p = (51, 42)
    # print(X(p))

    print(power_level(3, 5))
    print(power_level(122, 79, 57))
    print(power_level(217, 196, 39))
    print(power_level(101, 153, 71))

    part2(None)

if __name__ == '__main__':
    main()

'''
def test_intersection0():
    assert (0, 4) == intersect((0, 0), (0, 8), (-4, 4), (4, 4))

def test_intersection1():
    assert (0, 4) == intersect((0, 0), (0, 8), (4, 4), (-4, 4))

def test_intersection2():
    assert (0, 4) == intersect((-4, 4), (4, 4), (0, 0), (0, 8))

def test_intersection3():
    assert None is intersect((2, 1), (6, 1), (8, 0), (8, 3))
'''


import random
random.seed()
losowana = random.randrange(50)
A0=[]
x=0
while x<1000:
    A0.append(random.randrange(1000))
    x=x+1

def wybieranie(tab):
    i=0
    while (i <len(tab)):
        a=i
        j=i+1
        while (j<len(tab)):
            if tab[j]<=tab[a]:
                a=j
            j=j+1
        tab[a],tab[i]=tab[i],tab[a]
        i=i+1

wybieranie (A0)


import sys
import pygame

from alien import Alien
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group

def run_game():
    '''初始化游戏并创建一个屏幕对象'''
    pygame.init()
    # screen = pygame.display.set_mode((1200,800))
    # pygame.display.set_caption("Alien Invasion")
    # #设置背景色
    # bg_color = (230,230,230)
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    #创建一艘飞船
    ship = Ship(ai_settings,screen)
    #创建一个用于存储子弹的编组
    bullets = Group()
    # #创建一个外星人
    # alien = Alien(ai_settings,screen)
    #创建一个外星人编组
    aliens =Group()
    #创建外星人群
    gf.create_fleet(ai_settings,screen,ship,aliens)

    #开始游戏的主循环
    while True:
        #监视键盘和鼠标
        # for event in pygame.event.get():
        #     if event.type == pygame.QUIT:
        #         sys.exit()
        gf.check_events(ai_settings,screen,ship,bullets)
            #每次循环是重绘屏幕
            # screen.fill(bg_color)
        # screen.fill(ai_settings.bg_color)
        # ship.blitme()
        ship.update()
        # bullets.update()
        #
        # #删除已消失的子弹
        # for bullet in bullets.copy():
        #     if bullet.rect.bottom <= 0:
        #         bullets.remove(bullet)
        gf.update_bullets(aliens,bullets)
        gf.update_aliens(ai_settings,aliens)
        gf.update_screen(ai_settings,screen,ship,aliens,bullets)

        #让最近的屏幕绘制可见
        pygame.display.flip()

run_game()


import socket
import select
import sys

server_port = 12345
server_ip = 'localhost'

try:
  client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
  print(f'an error occured while creating socket{err}')

try:
  client_socket.connect((server_ip, server_port))
except socket.error as err:
  print(f'error while connecting to server :{err}')

game_running = True
response_state = 0
timeout = 10
while game_running:

  type_of_inputs = select.select([sys.stdin, client_socket],[],[], )[0]
  for input_src in type_of_inputs:
    if input_src == client_socket:
      server_message = client_socket.recv(1024)
      server_message = server_message.decode('ascii')
      response_type = server_message[0:3]
    #  print(response_type)
      new_message = server_message[3:]
    #  print(new_message)
      if response_type == 'kll':
        game_running = False

      elif response_type == 'can':
        print(new_message)
        response_state = 1

      elif response_type == 'bzz':
        response_state = 0

      elif response_type == 'ans':
        response_state =2

      elif response_type == 'rst':
        response_state =  0

      elif response_type == 'prn':
        print('\n'+new_message)

    else:
      client_response = sys.stdin.readline()
      if response_state == 1:
          client_socket.send('bzz'.encode('ascii'))
      elif response_state == 2:
          client_response = 'ans'+client_response
          client_socket.send(client_response.encode('ascii'))

client_socket.close()


from django_assets import Bundle, register, env

#css below
bootstrap_css = Bundle(
    'less/bootstrap/bootstrap.less', 'less/bootstrap/responsive.less', filters='less,cssmin',
    output='gen/bootstrap.%(version)s.css', depends='less/bootstrap/*.less'
)
bootstrap_ie6_css = Bundle(
    'less/bootstrap/bootstrap_ie6.less',filters='less,cssmin',
    output='gen/bootstrap.ie6.%(version)s.css', depends='less/bootstrap/*.less'
)
responsive_css = Bundle('less/responsive.less', filters='less,cssmin', output='gen/responsive.%(version)s.css')

base_css = Bundle(bootstrap_css, 'less/common.less', 'less/module.less', 'less/user.less', responsive_css,
                  filters='less,cssmin', output='gen/base.%(version)s.css')

base_restaurant_css = Bundle(bootstrap_css, 'css/jquery.Jcrop.css', 'less/common.less', 'less/restaurant_admin.less',
                             filters='less,cssmin', output='gen/restaurant.%(version)s.css')

#group related
#group_list_css = Bundle(
#     common_css, 'css/group_list.css', filters='cssmin', output='gen/group-list.%(version)s..css'
#)
#group_detail_css = Bundle(
#     common_css, 'css/group_detail.css', filters='cssmin', output='gen/group-detail.%(version)s.css'
#)

#user related

create_meal_css = Bundle(
    'less/bootstrap/datepicker.less', 'css/dropkick.css', 'css/lionbars.css', filters='less, cssmin', output='gen/create_meal.%(version)s.css'
)

edit_profile_css = Bundle(
    'css/jquery.Jcrop.css', 'less/autoSuggest.less', filters='less, cssmin', output='gen/edit_profile.%(version)s.css'
)

restaurant_admin_css = Bundle(
    'css/jquery.Jcrop.css', 'less/restaurant_admin.less', responsive_css, filters='less,cssmin',
    output='gen/restaurant-admin.%(version)s.css'
)

#js below
jquery_js = Bundle('js/jquery_1.7.2.js', output='gen/jquery-1.7.2.%(version)s.js', filters="yui_js")

jquery_dropkick_js = Bundle('js/jquery.dropkick_1.0.0.js', output='gen/jquery-dropkick.%(version)s.js', filters='yui_js')

jquery_color_js = Bundle('js/jquery.animate-colors-min.js', output='gen/jquery-color.%(version)s.js', filters='yui_js')

noty_js = Bundle('js/noty/jquery.noty.js', 'js/noty/layouts/top.js', 'js/noty/layouts/topCenter.js',
                 'js/noty/layouts/center.js', 'js/noty/themes/default.js',
                 output='gen/jquery-noty.%(version)s.js', filters='yui_js')

chat_js = Bundle('js/underscore_1.4.4.js', 'js/backbone_1.0.0.js', 'js/chat/iso8601_support.js',
                 'js/chat/strophe.js',
                 'js/chat/strophe.rsm.js', 'js/chat/strophe.chatstates.js', 'js/chat/strophe.archive.js',
                 'js/chat/strophe.roster.js', 'js/chat/strophe.messaging.js', 'js/chat/strophe.serverdate.js',
                 'js/chat/chat.js', filters='yui_js', output="gen/chat.%(version)s.js")

bootstrap_js = Bundle('js/bootstrap.js', filters='yui_js', output="gen/bootstrap.%(version)s.js")

bootstrap_box_js = Bundle('js/bootstrap_box.js', filters='yui_js', output="gen/bootstrap-box.%(version)s.js")

base_js = Bundle(jquery_js, 'js/utils.js',  bootstrap_js, noty_js, 'js/common.js', filters='yui_js',
                 output="gen/base.%(version)s.js")

base_main_js = Bundle(jquery_js, 'js/utils.js',  bootstrap_js, 'js/jquery.lazyload.js', 'js/common.js', filters='yui_js',
                      output="gen/base.main.%(version)s.js")

module_js = Bundle('js/module.js', filters='yui_js', output="gen/module.%(version)s.js")

water_fall_js = Bundle(
    'js/jquery.infinitescroll.js', 'js/jquery.masonry.js','js/jquery.lazyload.js',
    filters='yui_js', output='gen/water-fall.%(version)s.js'
)
jquery_form_js = Bundle('js/jquery.form.js', filters='yui_js', output='gen/jquery.form.%(version)s.js')

validate_js = Bundle('js/jqBootstrapValidation.js', filters='yui_js', output='gen/validate.%(version)s.js')

restaurant_admin_js = Bundle(
    bootstrap_box_js, 'js/restaurant_admin.js', filters='yui_js', output='gen/restaurant-admin.%(version)s.js'
)

edit_or_bind_profile_js = Bundle('js/jquery.autoSuggest.js', jquery_form_js, validate_js, filters='yui_js',
                                 output="gen/edit_profile.%(version)s.js")

create_meal_js = Bundle('js/bootstrap_datepicker.js', 'js/jquery.lionbars.0.3.js', jquery_dropkick_js,
                        validate_js, 'js/gmap3.v5.0b.min.js', filters='yui_js',
                        output="gen/create-meal.%(version)s.js")

jquery_ui_js = Bundle('js/jquery_ui_1.8.21.custom.js', filters='yui_js',
                      output='gen/jquery-ui-1.8.21.custom.%(version)s.js')

image_cropping_js = Bundle('js/jquery.Jcrop.js', 'js/image_cropping.js', filters='yui_js',
                           output='gen/iamge-cropping.%(version)s.js')

register('base_css', base_css)
register('base_restaurant_css', base_restaurant_css)
register('bootstrap_css', bootstrap_css)
register('bootstrap_ie6_css', bootstrap_ie6_css)
#register('group_list_css', group_list_css)
#register('group_detail_css', group_detail_css)

register('create_meal_css', create_meal_css)
register('edit_profile_css', edit_profile_css)
register('restaurant_admin_css', restaurant_admin_css)

register('bootstrap_js', bootstrap_js)
register('bootstrap_box_js', bootstrap_box_js)
register('jquery_js', jquery_js)
register('jquery_dropkick_js', jquery_dropkick_js)
register('jquery_color_js', jquery_color_js)
register('noty_js', noty_js)
register('base_js', base_js)
register('base_main_js', base_main_js)
register('module_js', module_js)
register('chat_js', chat_js)
register('create_meal_js', create_meal_js)
register('edit_or_bind_profile_js', edit_or_bind_profile_js)
register('restaurant_admin_js', restaurant_admin_js)
register('water_fall_js', water_fall_js)
register('jquery_form_js', jquery_form_js)
register('jquery_ui_js', jquery_ui_js)
register('image_cropping_js', image_cropping_js)


from question_model import Soru
from data import sorular
from quiz_brain import BilgiYarismasi

soru_havuzu = []
for soru_ogesi in sorular:
    for soru in soru_ogesi["results"]:
        soru_metni = soru["soru"]
        soru_cevabi = soru["dogru_cevap"]
        yeni_soru = Soru(soru_metni, soru_cevabi)
        soru_havuzu.append(yeni_soru)

yarisma = BilgiYarismasi(soru_havuzu)

while yarisma.baskaSoruVarMi():
    yarisma.siradakiSoru()

print("Completed the Quiz!")
print(f"Your success rate: {yarisma.skor}/{yarisma.soru_no}")


# 二分法搜索的三种情况模板总结，全部采用左闭右闭的区间来写
# def binary_search(nums: List[int], target: int) -> int:
#     # 设置左右下标
#     left, right = 0, len(nums) - 1
#     while left <= right:
#         mid = left + (right - left) // 2
#         if nums[mid] < target:
#             left = mid + 1
#         elif nums[mid] > target:
#             right = mid - 1
#         elif nums[mid] == target:
#             # 找到目标值
#             return mid
#     # 没有找到目标值
#     return -1
#
# def left_bound(nums: List[int], target: int) -> int:
#     # 设置左右下标
#     left, right = 0, len(nums) - 1
#     while left <= right:
#         mid = left + (right - left) // 2
#         if nums[mid] < target:
#             left = mid + 1
#         elif nums[mid] > target:
#             right = mid - 1
#         elif nums[mid] == target:
#             # 存在目标值，缩小右边界
#             right = mid - 1
#     # 判断是否存在目标值，这里其实不会出现 left < 0 的情况，因为 left 初始值就是0，加这个判断只是代码好习惯
#     if left < 0 or left >= len(nums):     # 或者只写 left >= len(nums) 判断也行
#         return -1
#     # 判断找到的左边界是否是目标值，出循环的情况是 left = right + 1，所以返回 right + 1也行
#     return left if nums[left] == target else -1
#
# def right_bound(nums: List[int], target: int) -> int:
#     # 设置左右下标
#     left, right = 0, len(nums) - 1
#     while left <= right:
#         mid = left + (right - left) // 2
#         if nums[mid] < target:
#             left = mid + 1
#         elif nums[mid] > target:
#             right = mid - 1
#         elif nums[mid] == target:
#             # 存在目标值，缩小左边界
#             left = mid + 1
#     # 判断是否存在目标值，这里其实不会出现 right >= len(nums) 的情况，因为 right 初始值就是len(nums) - 1，加这个判断只是代码好习惯
#     if right < 0 or right >= len(nums):     # 或者只写 right < 0 判断也行
#         return -1
#     # 判断找到的右边界是否是目标值，出循环的情况是 right = left - 1，所以返回 left - 1也行
#     return right if nums[right] == target else -1

class Solution:
    def search(self, nums: [int], target: int) -> int:
        """
        Time: O(logn)
        Space: O(1)
        """

        # 遵循左闭右闭的区间写法, 此方法非常重要
        left = 0
        right = len(nums) - 1

        while left <= right:
            mid = (right + left) // 2
            if nums[mid] < target:
                left = mid + 1
            elif nums[mid] > target:
                right = mid - 1
            else:
                return mid

        return -1

s = Solution()
print(s.search(nums=[-1, 0, 3, 5, 9, 12], target=9))


#!/usr/bin/python3
"""This module adds all arguments to a Python list and saves them to a file."""

import sys
from typing import List

def add_items_to_list_and_save(items: List[str], filename: str) -> None:
    save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
    load_from_json_file = __import__('6-load_from_json_file').load_from_json_file

    try:
        current_items = load_from_json_file(filename)
    except FileNotFoundError:
        current_items = []

    updated_items = current_items + items
    save_to_json_file(updated_items, filename)

if __name__ == "__main__":
    args = sys.argv[1:]
    add_items_to_list_and_save(args, "add_item.json")


import random

guessesTaken= 0

print("hello! what is your name? ")
#input the user name
name= input()
print("Well," +  name + ", I am thinking a number between 1 and 20")
number= random.randint(1,20)
for i in range(6):
    print("Take a guess:")
    guess= input()
    guess= int(guess)
    guessesTaken= guessesTaken+1

    if guess<number:
        print("Your guess is too low")
    if guess>number:
        print("Your guess is too high")
    if guess==number:
        break

#print the result
if guess==number:
    guessesTaken= str(guessesTaken)
    print("Good job "+name+"! You gueessed my number in "+guessesTaken+" guesses!")
else:
    number= str(number)
    print("Nope. The number I was thinking is "+number+".")


def dec_bin(n,l):
    while(n != 0):
        if(n%2 == 0):
            l.append(0)
        else:
            l.append(1)
        n=n//2
    k=li[::-1]
    print('Binary Number is')
    for i in k:
        print(i)
li=[]
p=int(input('Enter decimal number:'))
dec_bin(p,li)


from collections import UserDict
from datetime import datetime, date
import json
import re

class WrongPhone(Exception):
    pass

class WrongDate(Exception):
    pass

class WrongEmail(Exception):
    pass

class WrongDays(Exception):
    pass

class NoName(Exception):
    pass

class Field:
    def __init__(self, value):
        self._value = value

    def __str__(self):
        return str(self._value)

    def __repr__(self):
        return str(self)

    def __eq__(self, other):
        if self.__class__ == other.__class__:
            return self._value == other.value
        return False

    def __hash__(self):
        return hash(self._value)

class Name(Field):
    @staticmethod
    def is_valid_name(name):
        if name.strip() == '':
            return False
        else:
            return True

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        if self.is_valid_name(val):
            self._value = val
        else:
            raise NoName("You missed to enter name. "
                             "Please check the value and try again")

class Phone(Field):

    @staticmethod
    def is_valid_phone(phone):
        if phone == '':
            return True
        match = re.search(r"^\+?[1-9][\d]{11}$", phone)
        return bool(match)

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        if self.is_valid_phone(val):
            self._value = val
        else:
            raise WrongPhone("You tried to enter an invalid phone number. "
                             "Please check the value and try again")

class Birthday(Field):

    @staticmethod
    def is_valid_date(date):
        try:
            if date == '':
                return True
            datetime.strptime(str(date), "%d.%m.%Y")
            return True
        except ValueError:
            return False

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        if self.is_valid_date(val):
            self._value = val
        else:
            raise WrongDate(
                "Invalid date. Please enter birthday in format 'DD.MM.YYYY'.")

class Address:
    def __init__(self, street="", city="", country="", postcode=""):
        self.street = street
        self.city = city
        self.country = country
        self.postcode = postcode

    def __str__(self):
        return f"{self.street},{self.city},{self.country},{self.postcode}"

    def __repr__(self):
        return f"Address(street='{self.street}', city='{self.city}', country='{self.country}', postcode='{self.postcode}')"

class Email:
    def __init__(self, value=""):
        self.value = value

    @staticmethod
    def is_valid_email(email):
        if email == '':
            return True
        match = re.search(
            r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", email)
        return bool(match)

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, val):
        if self.is_valid_email(val):
            self._value = val

        else:
            raise WrongEmail(
                "Invalid email address. Please enter a correct email address")

    def __str__(self) -> str:
        return self.value

    def __repr__(self) -> str:
        return str(self)

class Record:
    def __init__(self, name, phones=None, birthday=None, address=None, email=None):
        self.name = name
        self.phones = phones
        self.birthday = birthday
        self.address = address
        self.email = email

    def __str__(self):
        phones = ", ".join([str(phone) for phone in self.phones])
        birthday = f"Birthday: {self.birthday}" if self.birthday.value else "Birthday:"
        address_str = f"Address: {self.address}" if self.address else ""
        email_str = f"Email: {self.email}" if self.email else ""
        return f"{self.name.value}: {phones}, {birthday}, {address_str}, {email_str}"

    def __repr__(self):
        return str(self)

    def add_phone(self, phone: Phone):
        if phone in self.phones:
            return f"User {self.name.value} already has {phone} phone number."
        else:
            self.phones.append(phone)
        self.phones = list(set(self.phones))
        return f"Phone number {phone} is added successfully for user {self.name.value}."

    def change_phone(self, old_number: Phone, new_number: Phone):
        if old_number not in self.phones:
            return f"Number {old_number} not found."
        else:
            phone_number_index = self.phones.index(old_number)
            self.phones[phone_number_index] = new_number
            return f"The phone number {old_number} for the user {self.name} "\
                f"has been changed to {new_number}"

    def delete_phone(self, phone):
        try:
            self.phones.remove(phone)
            return f"Phone number {phone} for user {self.name} deleted successfully."
        except ValueError:
            return f"Phone number {phone} for user {self.name} not found"

    def days_to_birthday(self):
        try:
            birthday = datetime.strptime(str(self.birthday), "%d.%m.%Y").date()
        except ValueError:
            return f"No birthday for user {self.name.value}"

        today = date.today()
        birthday = birthday.replace(year=today.year)
        if birthday < today:
            birthday = birthday.replace(year=today.year+1)
        result = (birthday - today).days
        birthday_str = birthday.strftime("%d %B")
        return f"The birthday of user {self.name} will be in {result} days, {birthday_str}"

    def change_birthday(self, birthday: Birthday):
        self.birthday = birthday
        return f"Birthday date for user {self.name.value} is changed to {birthday} successfully."

    def change_address(self, address: Address):
        self.address = address
        return f"Address {address} for user {self.name.value} is changed successfully."

    def change_email(self, new_email: Email):
        self.email = new_email
        return f"Email {new_email} for user {self.name.value} is changed successfully."

class AddressBook(UserDict):
    def add_record(self, record):
        self[record.name.value] = record

    def delete_record(self, name: Name):
        del self[name.value]

    def change_record(self, name, new_record):
        self[new_record.name.value] = new_record

    def search(self, field: str, text: str) -> list[Record]:
        result = []
        if field.lower() == "name":
            for record in self.data.values():
                if text in record.name.value:
                    result.append(record)
        elif field.lower() == "phone":
            for record in self.data.values():
                for phone in record.phones:
                    if text in phone.value:
                        result.append(record)
        elif field.lower() == "email":
            for record in self.data.values():
                if text.lower() in record.email.value.lower():
                    result.append(record)
        return result

    def show_birthday(self, days: int):
        result_list = []
        result_to_print = []
        now = datetime.today()
        start_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
        for record in self.data.values():
            if record.birthday.value:
                birthday = datetime.strptime(str(record.birthday.value), "%d.%m.%Y")
                birthday = birthday.replace(year=start_date.year)
                if birthday < start_date:
                    birthday = birthday.replace(year=start_date.year+1)
                gap = birthday - start_date
                gap = gap.days
                result_list.append([str(record.name.value), birthday, gap])
        result_list = sorted(result_list, key=lambda person: person[2])
        result_to_print = [f'{value[1].strftime("%d.%m.%Y")}: {value[0]}' for value in result_list if value[2] <= days]
        if result_to_print:
            print(f"Birthdays today and within {days} next day(s):")
            print(*result_to_print, sep='\n')
        else:
            if days == 1:
                return f"There are no birthdays to show within {days} day"
            else:
                return f"There are no birthdays to show within {days} days"
        return None

    @classmethod
    def open_file(cls, filename):
        """Take as input filename. Return AddressBook"""
        try:
            with open(filename, encoding="utf-8") as file:
                json_data = json.load(file)
                data = cls()
                for name, record in json_data.items():
                    name = Name(name)
                    phones = [Phone(phone) for phone in record["phones"]]
                    birthday = Birthday(record["birthday"])
                    address = Address(**record["address"])
                    email = Email(record["email"])

                    data.add_record(
                        Record(name, phones, birthday, address, email))
        except FileNotFoundError:
            data = cls()
        return data

    def write_to_file(self, filename: str):
        json_data = {}

        for name, record in self.data.items():
            json_data[name] = {
                "phones": [phone.value for phone in record.phones],
                "birthday": record.birthday.value if record.birthday is not None else '',
                "address": {
                    "street": record.address.street if record.address is not None else '',
                    "city": record.address.city if record.address is not None else '',
                    "country": record.address.country if record.address is not None else '',
                    "postcode": record.address.postcode if record.address is not None else '',
                },
                "email": record.email.value if record.email is not None else ''
            }
        with open(filename, "w", encoding="utf-8") as file:
            json.dump(json_data, file, indent=4, ensure_ascii=False)

    def __iter__(self):
        self.current_page = 1
        self.page_size = 10
        self.start_index = (self.current_page - 1) * self.page_size
        self.end_index = self.start_index + self.page_size
        return self

    def __next__(self):
        if self.start_index >= len(self.data):
            raise StopIteration

        page_records = list(self.data.values())[
            self.start_index:self.end_index]
        self.start_index = self.end_index
        self.end_index = self.start_index + self.page_size
        self.current_page += 1

        return page_records

if __name__ == "__main__":
    pass


import sys

while True:
    try:
        num = sys.stdin.readline().split()
        A = int(num[0])
        B = int(num[1])
        print(A+B)
    except:
        break

# 이 문제의 목적은 파일의 끝(EOF)을 올바르게 판단하는 법을 연습하는 것임.
# 더 이상 읽을 게 없을 때 프로그램을 종료하는 방법을 알아야 함
# 파이썬의 경우 예외처리를 통해서 입력값이 들어오지 않을때 프로그램을 종료할 수 있음


class triangle():

    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3

    def perimeter(self):
        calc_peri = self.side1 + self.side2 + self.side3
        return calc_peri

value1 = triangle(1, 2, 3)
result = value1.perimeter()
print(f"=> Perimeter = {result} units.")