import pandas as pd
import numpy as np
import logging

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)
logging.info('hh')

from pyecharts.charts import Bar, Grid, Line,Page
from pyecharts import options as opts
from pyecharts.charts import Bar

# 读取数据
sample = pd.read_csv('/home/bb5/xw/mxg_scores/20210120_pg_v3_old.csv',encoding='gbk')

sample['y']=sample['age'].map(lambda x: 1 if x>=7 else 0)

train = sample.fillna(-999)  # None填充

# 读取保存好的 model 和feature names
path ='/home/bb5/xw/mxg_scores'
input_xgb_features_path=path+'/lgbm_v1_features.csv'
chosen_feature_pd=pd.read_csv(input_xgb_features_path,encoding='UTF-8')
chosen_feature=list(np.array(chosen_feature_pd.iloc[:,0],dtype='str'))
print('chosen_feature: ' ,chosen_feature)

page = Page()
print('模型bin分布 *******************')

# bin 分布
#
# df_bin = pd.read_csv('/home/bb5/xw/mxg_scores/monitor/v3_bin.csv', encoding='gbk')
# bins = ['bin1', 'bin2', 'bin3', 'bin4', 'bin5', 'bin6', 'bin7','bin8', 'bin9', 'bin10', 'bin11', 'bin12', 'bin13', 'bin14', 'bin15']
# bar_bin = Bar()
# bar_bin.add_xaxis(list(df_bin['apply_time']))
# for bin in bins:
#     bar_bin.add_yaxis(bin, list(df_bin[bin]), stack="stack1")
# bar_bin.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
# bar_bin.set_global_opts(title_opts=opts.TitleOpts(title='v3_bin'),
#                         datazoom_opts = [opts.DataZoomOpts(range_start=0, range_end=100), ],
#                         legend_opts = opts.LegendOpts(pos_left="right", orient='vertical'), )
# bar_bin.render("v3_bin.html")
#
# page.add(bar_bin)

# 模型特征变量分布
print('模型特征变量分布 *******************')

num=0
for feature in chosen_feature:
    num+=1

    feature_value = sample[feature].unique()
    feature_value.sort()
    if len(feature_value)>=15:
        _, bin = pd.qcut(sample[feature], 10, retbins=True, duplicates='drop')
    else: bin = list(feature_value)

    bin = list(bin)
    bin.insert(0, -999999)
    bin.pop()
    bin.append(float('inf'))

    col_list = [str(i) for i in bin]
    train['bin'] = pd.cut(train[feature], bin, right=False, labels=col_list[0:-1])
    tmp = train.groupby(['apply_time', 'bin'])['y'].count()
    tmp = tmp.reset_index()
    tmp = pd.DataFrame(tmp)
    tmp = pd.pivot(tmp, index="apply_time", columns="bin", values="y")
    tmp.columns = tmp.columns.astype(str)
    tmp['total'] = tmp.apply(lambda x: x.sum(), axis=1)

    col_list = tmp.columns.to_list()
    bar = Bar()
    bar.add_xaxis(list(tmp.index))
    for i in range(len(col_list[0:-1])):
        bar.add_yaxis(col_list[i], list(tmp[col_list[i]] / tmp['total']), stack="stack1")

    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    bar.set_global_opts(title_opts=opts.TitleOpts(title=feature),
                        datazoom_opts=[opts.DataZoomOpts(range_start=0,range_end=100), ],
                        #toolbox_opts=opts.ToolboxOpts(),
                        legend_opts=opts.LegendOpts(pos_left="right",orient='vertical'),)

    page.add(bar)
    logger.info('数量 {}  完成 {}'.format(num,feature))

page.render("v3_old.html")


from fitnessFunction_vehicle import fitnessFunction_vehicle
import pickle
import numpy as np
from input_output_difference import input_output_difference
import scipy.io as sio

with open("best_individual_robust", "rb") as f:
    best_individual = pickle.load(f)

from os import listdir
from os.path import isfile, join

create_output_diff_map = True

#files_path = "10_neuron_sparse_scan"

#files = [f for f in listdir(files_path) if isfile(join(files_path, f))]

#file_index = np.random.randint(low=0, high=200)
#with open(files_path + "/" + files[file_index], "rb") as f:
#    best_individual = pickle.load(f)

num_neurons = 6
params = best_individual["params"]
lesion_fitness = np.zeros(num_neurons**2)
output_diff_lesion = np.zeros((num_neurons**2,10,10))
# A start to the ablation analysis
for i in range(num_neurons**2):
    modified_params = np.copy(best_individual["params"])
    # Set param to 0 (set to 0.4 becuase it is between 1/3 and 2/3)
    if (modified_params[i] > 2/3) or (modified_params[i] < 1/3):
        modified_params[i] = 0.4

        lesion_fitness[i] =fitnessFunction_vehicle(
            modified_params,
            best_individual["ctrnn_size"],
            best_individual["ctrnn_step_size"],
            best_individual["bv_duration"],
            best_individual["bv_distance"],
            best_individual["bv_step_size"],
            best_individual["transient_steps"],
            best_individual["discrete"],
            )
        print(i)
        print("of")
        print(num_neurons**2)
        print(lesion_fitness[i])

        if create_output_diff_map:
            output_diff_lesion[i,:,:] = input_output_difference(modified_params, best_individual)
    else:
        print("skip no edge")
        if create_output_diff_map:
            output_diff_lesion[i,:,:] = input_output_difference(modified_params, best_individual)
# Checking robustness. Solutions are not robust at all to changes in sign, but they are robust to variations
# of about +-0.5

range = np.arange(-5, 5, 0.1)
robustness = np.zeros(len(range))
i = 0
for multiplier in range:

    robustness[i] = fitnessFunction_vehicle(
        best_individual["params"],
        best_individual["ctrnn_size"],
        best_individual["ctrnn_step_size"],
        best_individual["bv_duration"],
        best_individual["bv_distance"],
        best_individual["bv_step_size"],
        best_individual["transient_steps"],
        best_individual["discrete"],
        multiplier
        )

    print(i)
    print("mult")
    print(multiplier)
    print(robustness[i])
    i +=1

#dirr = '10_neuron_sparse_scan/edge_lesion_sparse'
#post = str(file_index)+".mat"

#name_it = dirr+post

#sio.savemat(name_it, mdict={'lesion_edge': lesion_fitness})

#dirr = '10_neuron_sparse_scan/robustness_sparse'
#post = str(file_index)+".mat"

#name_it = dirr+post

#sio.savemat(name_it, mdict={'robustness': robustness})

dirr = 'parameters_for_matlab/edge_lesion_robust'
post = ".mat"

name_it = dirr+post

sio.savemat(name_it, mdict={'lesion_edge': lesion_fitness})

dirr = 'parameters_for_matlab/robustness_robust'
post = ".mat"

name_it = dirr+post

sio.savemat(name_it, mdict={'robustness': robustness})

dirr = 'parameters_for_matlab/output_diff_lesion'
post = ".mat"

name_it = dirr+post

sio.savemat(name_it, mdict={'output_diff_lesion': output_diff_lesion})


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

from urllib.request import urlretrieve
import requests
import random
from datetime import *
from dateutil.parser import *
import json
try:
    import cookielib
except:
    import http.cookiejar as cookielib
try:
    from PIL import Image
except:
    pass

datas = {'active': 'verification'}
headers = {'Host':'bjllfx.com',
           'Referer': 'http://bjllfx.com/mbe/login.html',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0',
           'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
           'Accept': '*/*',
           'Accept-Language': 'zh-CN',
           'Accept-Encoding':'gzip, deflate',
           'Connection': 'Keep-Alive'}

def login():
    login_url = 'http://bjllfx.com/mbe/api/login.ashx'
    datas['mobile'] = '139########'
    datas['pwd'] = '********'
    datas['r'] = random.random()
    resp = session.post(login_url, data=datas, headers=headers)
    if resp.status_code == 200:
        session.cookies.save()
    else:
        return False
    return True

def book_car():
    #Input booking date
    number = -1
    while number < 0 or number > 2:
        str_number = input('Input a date - 0: Today; 1: T+1; 2: T+2 (Default) : ')
        if str_number.strip() == '':
            number = 2
        else:
            number = int(str_number)

#    book_date = parse(input('Please input booking date:')).date()
    today =  date.today()
    book_date = today + timedelta(days=number)
    print("Date Inputed: %s "% book_date.strftime('%Y-%m-%d'))
    #Query available time
    headers = {'Host':'bjllfx.com',
           'Referer': 'http://bjllfx.com/mbe/online.html',
           'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0',
           'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
           'Accept': '*/*',
           'Accept-Language': 'zh-CN',
           'Accept-Encoding':'gzip, deflate'}
    post_url = "http://bjllfx.com/mbe/api/online.ashx?r=0.943978761644576"
    post_data = {'active':'availabletime',
                 'trainerID':'XXX', #Fill your trainer ID
                 'carID':'XX', #Fill your car  ID
                 'hour':'2',
                 'service':'计时卡'}
    post_data['date'] = book_date.strftime('%Y-%m-%d')
    post_data['r'] = random.random()
    resp = session.post(post_url, data=post_data, headers=headers)
    resp.encoding = resp.apparent_encoding
    json_data = resp.json()
    msg = json_data.get('msg')
    #User logout, relogin
    if msg.strip() != 'success':
        print(msg)
        login()
        resp = session.post(post_url, data=post_data, headers=headers)
        resp.encoding = resp.apparent_encoding
        json_data = resp.json()

    data = json_data.get('data')[1:-1]

    #Car is not available on this day
    if data.strip() == '':
        print("Car is not available!")
        return False
    dict_data = eval(data)

    #Select a training time
    print("  ID      StartTime   EndTime")
    print("————————————")
    idx = 1
    if isinstance(dict_data, dict):
        option = dict_data
        start_time = int(option['startTime']) / 60
        end_time = int(option['endTime']) / 60
        print( "%3d)       %2d:00         %2d:00" % (idx,start_time, end_time), end='\n')
    else:
        for option in dict_data:
            start_time = int(option['startTime']) / 60
            end_time = int(option['endTime']) / 60
            print( "%3d)       %2d:00         %2d:00" % (idx,start_time, end_time), end='\n')
            idx = idx + 1
    print("————————————")

    number = 0
    while number < 1 or number > idx:
        number = int(input('Please input a number:  '))
    if idx > 1:
        option = dict_data[number -1]
    verify = 'N'
    while verify != 'Y':
        verify = input('Yes/No: ')[0].upper()

    post_data = {'active':'addOrder',
                 'cardNum':'NNNNNN', #Fill card number
                 'cardType':'12小时卡',
                 'cardService':'计时卡',
                 'cardPriceType':'##############',#
                 'address':'#####################',#
                 'trainerID':'XXX',#
                 'trainerName':'###################',#
                 'trainerGrade':'1',#
                 'trainerPhone':'###########',#
                 'carID':'XX',#
                 'carName':'################',#
                 'carNum':'#############',#
                 'priceType':'110.00',#
                 'service':'计时卡',
                 'note':''}
    post_data['date'] = book_date.strftime('%Y-%m-%d')
    post_data['itemTime'] = '{\"startTime\":'+str(option['startTime'])+',\"duration\":'+str(option['duration'])+'}'
    post_data['r'] = random.random()
    resp = session.post(post_url, data=post_data, headers=headers)
    resp.encoding = resp.apparent_encoding
    return True

if __name__ == '__main__':
    # try login with cookie at first
    session = requests.session()
    session.cookies = cookielib.LWPCookieJar(filename='YueChe_cookies')
    try:
        session.cookies.load(ignore_discard=True)
    except:
        print("Cookies load failed! \n")
        login()

    book_car()


import _thread
import sys
import socket
import time

import pygame
from pygame.locals import *
from logging import Logger

from src.entities.Player import Player
from src.game.Board import Board
from src.game.Renderer import Renderer
from src.game.constants import *
from src.helpers.Managers import LetterManager

class Main:

    host = '127.0.0.1'
    port = 0
    server = ('127.0.0.1', 5005)

    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Scrabble")
        self.logger = Logger("GAME")
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.background = self.load_background()
        self.letter_generator = LetterManager()
        self.clock = pygame.time.Clock()
        self.player = Player()
        self.player.tiles = self.letter_generator.create_player_tiles(STARTING_RANDOMS)
        self.board = Board(self.player, self.logger)
        self.render_engine = Renderer(self.board, self.screen)
        self.running = True
        self.turn = 1
        self.myTurn = False
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind((self.host, self.port))
        self.socket.setblocking(0)
        self.port = self.socket.getsockname()[1]
        _thread.start_new_thread(self.start(), ())

    def start(self):
        player_dragging_tile = False
        tile_being_dragged = None
        changed_tiles = []
        next_arrow_click, revert_arrow_click = False, False
        self.socket.sendto("".encode(), self.server)
        while self.running:
            try:
                self.receiveData()
            except:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        self.end_process()
                    if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
                        self.check_turn(changed_tiles)
                        changed_tiles = []
                    if event.type == MOUSEBUTTONDOWN and self.myTurn:
                        x, y = event.pos
                        if player_dragging_tile:
                            for row in self.board.tiles:
                                for tile in row:
                                    if tile.rect.colliderect(pygame.Rect(x, y, 1, 1)):
                                        changed_tiles.append((tile.row, tile.col))
                                        tile.change_to(tile_being_dragged.letter)
                                        tile.occupied = True
                                        tile_being_dragged.visible = False
                                        self.logger.critical("'{0}' dropped at location: ({1}, {2})".format(
                                                                                tile_being_dragged.letter,
                                                                                tile.row, tile.col))
                            tile_being_dragged.reset()
                            tile_being_dragged = None
                            player_dragging_tile = False
                        else:
                            for random_tile in self.player.tiles:
                                if random_tile.rect.collidepoint(x, y) and random_tile.visible:
                                            player_dragging_tile = True
                                            random_tile.being_dragged = True
                                            tile_being_dragged = random_tile
                            if self.render_engine.arrow.rect.collidepoint(x, y):
                                next_arrow_click = True
                                self.render_engine.arrow_click = True
                            elif self.render_engine.back_arrow.rect.collidepoint(x, y):
                                revert_arrow_click = True
                                self.render_engine.back_arrow_click = True
                    if event.type == MOUSEBUTTONUP and self.myTurn:
                        x, y = event.pos
                        if next_arrow_click and self.render_engine.arrow.rect.collidepoint(x, y):
                            self.next_turn(changed_tiles)
                            changed_tiles = []
                        elif revert_arrow_click and self.render_engine.back_arrow.rect.collidepoint(x, y):
                            self.board.revert(changed_tiles)
                            changed_tiles = []
                            self.render_engine.back_arrow_click = False
            self.run()

    def receiveData(self):
        data, ip = self.socket.recvfrom(1024)
        message = data.decode()
        if message[0] == '-':
            self.myTurn = True
            message = message[1:]
        if len(message) == BOARD_SIZE * BOARD_SIZE:
            self.unpackString(message)
        time.sleep(0.1)

    def run(self):
        """
        Calls the render_engine to render the next frame and then updates the display.
        :return: None
        """
        self.clock.tick(60)
        self.screen.blit(self.background, (0, 0))
        self.render_engine.render()
        pygame.display.update()

    def end_process(self):
        """
        Exits game window and ends game process.
        :return: None
        """
        self.socket.sendto("QUIT".encode(), self.server)
        self.running = False
        pygame.quit()
        sys.exit()

    def next_turn(self, changed_tiles):
        """
        Moves the game to the next turn, if the previous turn was valid.

        :param changed_tiles: List of Tuples of (row, col) of each tile that has been changed
                              since the last turn
        :return: None
        """
        if self.check_turn(changed_tiles):
            self.turn += 1
            self.sendBoard()
        self.render_engine.arrow_click = False

    def check_turn(self, changed_tiles):
        """
        Checks if the current turn is a valid turn.

        :param changed_tiles: List of Tuples of (row, col) of each tile that has been changed
                              since the last turn
        :return: True iff the current turn is a valid turn. Else return False.
        """
        good_move = False
        if self.board.check_if_good_move(changed_tiles, self.turn):
            self.player.points += self.board.word_manager.calculate_points(self.board.word_list)
            self.board.regenerate_randoms()
            good_move = True
        else:
            self.board.revert(changed_tiles)
        return good_move

    def load_background(self):
        """
        Loads the background image and resizes it to match the dimensions of the window

        :return: Returns the resized background image texture
        """
        background = pygame.image.load(BACKGROUND_IMAGE).convert_alpha()
        background = pygame.transform.scale(background, (SCREEN_WIDTH, SCREEN_HEIGHT))
        return background

    def unpackString(self, string):
        print("Unpacking: " + string)
        for row in range(11):
            for col in range(11):
                self.board.tiles[row][col].change_to(string[row*11 + col])

    def packString(self):
        message = ""
        for row in range(11):
            for col in range(11):
                message += self.board.tiles[row][col].letter
        return message

    def sendBoard(self):
        self.socket.sendto(self.packString().encode(), self.server)
        self.myTurn = False

Main()


from importlib_metadata import requires
import numpy as np
import torch
import pytest
import json

from torch import nn
from .literal import Literal
from .constraint import Constraint
from .constraints_group import ConstraintsGroup
from .profiler import Profiler

class ConstraintsModule(nn.Module):
    profiler = Profiler.shared().branch('cm')

    @profiler.wrap
    def __init__(self, constraints_group, num_classes):
        super(ConstraintsModule, self).__init__()
        head, body = constraints_group.encoded(num_classes)
        pos_head, neg_head = head
        pos_body, neg_body = body

        # Compute necessary atoms
        self.atoms = nn.Parameter(torch.tensor(list(constraints_group.atoms())), requires_grad=False)
        reindexed = { float(atom): i for i, atom in enumerate(self.atoms) }
        if len(self.atoms) == 0: return

        # Reduce tensors to minimal size and reindex heads
        pos_head, neg_head = self.to_minimal(pos_head), self.to_minimal(neg_head)
        pos_body, neg_body = self.to_minimal(pos_body), self.to_minimal(neg_body)

        heads = [constraint.head for constraint in constraints_group]
        self.heads = [Literal(reindexed[head.atom], head.positive) for head in heads]

        # Module parameters
        self.pos_head = nn.Parameter(torch.from_numpy(pos_head).float(), requires_grad=False)
        self.neg_head = nn.Parameter(torch.from_numpy(neg_head).float(), requires_grad=False)
        self.pos_body = nn.Parameter(torch.from_numpy(pos_body).float(), requires_grad=False)
        self.neg_body = nn.Parameter(torch.from_numpy(neg_body).float(), requires_grad=False)

        # Precomputed parameters
        self.symm_body = nn.Parameter((self.pos_body - self.neg_body).t(), requires_grad=False)
        self.symm_head = nn.Parameter((self.pos_head - self.neg_head).t(), requires_grad=False)
        self.literals_count = nn.Parameter(self.pos_body.sum(dim=1) + self.neg_body.sum(dim=1), requires_grad=False)

    def dimensions(self, pred):
        batch, num = pred.shape[0], pred.shape[1]
        cons = self.pos_head.shape[0]
        return batch, num, cons

    @staticmethod
    @profiler.wrap
    def from_symmetric(preds):
        return (preds + 1) / 2

    @staticmethod
    @profiler.wrap
    def to_symmetric(preds):
        return 2 * preds - 1

    @profiler.wrap
    def to_minimal(self, tensor, atoms = None):
        if atoms is None: atoms = self.atoms
        return tensor[:, atoms].reshape(tensor.shape[0], len(atoms))

    @profiler.wrap
    def from_minimal(self, tensor, init, atoms = None):
        if atoms is None: atoms = self.atoms
        return init.index_copy(1, atoms, tensor)

    # Get constraints with full sat body and those with unsat head
    @profiler.wrap
    def active_constraints(self, goal):
        symm_goal = ConstraintsModule.to_symmetric(goal)
        full_body = torch.matmul(symm_goal, self.symm_body) == self.literals_count
        unsat_head = torch.matmul(symm_goal, self.symm_head) == -1
        return full_body, unsat_head

    # Apply constraints together with 3D tensors
    @profiler.wrap
    def apply_tensor(self, preds, active_constraints=None, body_mask=None):
        batch, num, cons = self.dimensions(preds)

        # batch x cons x num: prepare (preds x body)
        exp_preds = preds.unsqueeze(1).expand(batch, cons, num)
        pos_body = self.pos_body.unsqueeze(0).expand(batch, cons, num)
        neg_body = self.neg_body.unsqueeze(0).expand(batch, cons, num)

        # batch x cons x num: ignore literals from constraints
        if body_mask != None:
            body_mask = body_mask.unsqueeze(1).expand(batch, cons, num)
            pos_body = pos_body * (1 - body_mask)
            neg_body = neg_body * body_mask

        # batch x cons: compute body minima
        body_rev = pos_body + exp_preds * (neg_body - pos_body)
        body_min = 1. - torch.max(body_rev, dim=2).values

        # batch x cons: ignore constraints
        if active_constraints != None:
            body_min = body_min * active_constraints.float()

        # batch x cons x num: prepare (body_min x head)
        body_min = body_min.unsqueeze(2).expand(batch, cons, num)
        pos_head = self.pos_head.unsqueeze(0).expand(batch, cons, num)
        neg_head = self.neg_head.unsqueeze(0).expand(batch, cons, num)

        # batch x num: compute head lower and upper bounds
        lb = torch.max(body_min * pos_head, dim=1).values
        ub = 1 - torch.max(body_min * neg_head, dim=1).values
        lb, ub = torch.minimum(lb, ub), torch.maximum(lb, ub)

        preds = torch.maximum(lb, torch.minimum(ub, preds))
        return preds

    # Apply constraints iteratively with 2D matrices
    @profiler.wrap
    def apply_iter(self, preds, active_constraints=None, body_mask=None, in_bounds=None, out_bounds=False):
        batch, num, cons = self.dimensions(preds)
        device = preds.device

        if not active_constraints is None: active_constraints = active_constraints.float()
        zeros = torch.zeros(batch, 1, device=device)

        profiler = ConstraintsModule.profiler.branch('iter')

        with profiler.watch('init'):
            if in_bounds is None:
                lb = [torch.zeros(preds.shape[0], device=device) for i in range(preds.shape[1])]
                ub = [torch.ones(preds.shape[0], device=device) for i in range(preds.shape[1])]
            else:
                lb, ub = in_bounds

        with profiler.watch('precompute'):
            bool_pos_body = self.pos_body.bool()
            bool_neg_body = self.neg_body.bool()

            full_pos_body = 1 - preds
            full_neg_body = preds

            if not body_mask is None:
                full_pos_body = (1 - preds) * (1 - body_mask)
                full_neg_body = preds * body_mask

        for c, lit in enumerate(self.heads):
            # slice positive and negative body preds
            with profiler.watch('where'):
                pos_where = bool_pos_body[c]
                neg_where = bool_neg_body[c]

            # body predictions (possibly masked)
            with profiler.watch('body'):
                pos_body = full_pos_body[:, pos_where]
                neg_body = full_neg_body[:, neg_where]

            # compute maximal inverted values
            with profiler.watch('candidate'):
                candidate = torch.cat((zeros, pos_body, neg_body), dim=1)
                candidate = 1 - candidate.max(dim=1).values

            # clear inactive constraints
            with profiler.watch('active_cons'):
                if not active_constraints is None:
                    candidate = candidate * active_constraints[:, c]

            # update preds
            with profiler.watch('min_max'):
                if lit.positive:
                    lb[lit.atom] = torch.maximum(lb[lit.atom], candidate)
                else:
                    ub[lit.atom] = torch.minimum(ub[lit.atom], 1 - candidate)

        with profiler.watch('lb_ub'):
            if out_bounds:
                return lb, ub

            lb, ub = torch.stack(lb, dim=1), torch.stack(ub, dim=1)
            lb, ub = torch.minimum(lb, ub), torch.maximum(lb, ub)
            updated = torch.maximum(lb, torch.minimum(ub, preds))

            return updated

    @profiler.wrap
    def apply(self, preds, iterative):
        if iterative:
            return self.apply_iter(preds)
        else:
            return self.apply_tensor(preds)

    @profiler.wrap
    def apply_goal(self, preds, goal, iterative):
        full_body, unsat_head = self.active_constraints(goal)
        body_mask = goal

        if iterative:
            bounds = self.apply_iter(preds, active_constraints=full_body, out_bounds=True)
            updated = self.apply_iter(preds, active_constraints=unsat_head, body_mask=body_mask, in_bounds=bounds)
        else:
            updated = self.apply_tensor(preds, active_constraints=full_body)
            updated = self.apply_tensor(updated, active_constraints=unsat_head, body_mask=body_mask)

        return updated

    @profiler.wrap
    def forward(self, preds, goal = None, iterative=True):
        if len(preds) == 0 or len(self.atoms) == 0:
            return preds

        updated = self.to_minimal(preds)

        if goal is None:
            updated = self.apply(updated, iterative=iterative)
            return self.from_minimal(updated, preds)
        else:
            goal = self.to_minimal(goal)
            updated = self.apply_goal(updated, goal=goal, iterative=iterative)
            return self.from_minimal(updated, preds)

def test_symmetric():
    pos = torch.from_numpy(np.arange(0., 1., 0.1))
    symm = torch.from_numpy(np.arange(-1., 1., 0.2))
    assert torch.isclose(ConstraintsModule.to_symmetric(pos), symm).all()
    assert torch.isclose(ConstraintsModule.from_symmetric(symm), pos).all()

def run_cm(cm, preds, goal=None, device='cpu'):
    cm, preds = cm.to(device), preds.to(device)
    if not goal is None: goal = goal.to(device)

    iter = cm(preds, goal=goal, iterative=True)
    tens = cm(preds, goal=goal, iterative=False)
    assert torch.isclose(iter, tens).all()
    return iter.cpu()

def _test_no_goal(device):
    group = ConstraintsGroup([
        Constraint('1 :- 0'),
        Constraint('2 :- n3 4'),
        Constraint('n5 :- 6 n7 8'),
        Constraint('2 :- 9 n10'),
        Constraint('n5 :- 11 n12 n13'),
    ])
    cm = ConstraintsModule(group, 14)
    preds = torch.rand((5000, 14))
    updated = run_cm(cm, preds, device=device).numpy()
    assert group.coherent_with(updated).all()

def _test_positive_goal(device):
    group = ConstraintsGroup([
        Constraint('0 :- 1 n2'),
        Constraint('3 :- 4 n5'),
        Constraint('n7 :- 7 n8'),
        Constraint('n9 :- 10 n11')
    ])

    cm = ConstraintsModule(group, 12)
    preds = torch.rand((5000, 12))
    goal = torch.tensor([1., 1., 0., 1., 1., 1., 0., 1., 0., 0., 0., 0.]).unsqueeze(0).expand(5000, 12)
    updated = run_cm(cm, preds, goal=goal, device=device).numpy()
    assert (group.coherent_with(updated).all(axis=0) == [True, False, True, False]).all()

def _test_negative_goal(device):
    group = ConstraintsGroup([
        Constraint('0 :- 1 n2 3 n4'),
        Constraint('n5 :- 6 n7 8 n9')
    ])
    reduced_group = ConstraintsGroup([
        Constraint('0 :- 1 n2'),
        Constraint('n5 :- 6 n7')
    ])

    cm = ConstraintsModule(group, 10)
    preds = torch.rand((5000, 10))
    goal = torch.tensor([0., 0., 1., 1., 0., 1., 0., 1., 1., 0.]).unsqueeze(0).expand(5000, 10)
    updated = run_cm(cm, preds, goal=goal, device=device).numpy()
    assert reduced_group.coherent_with(updated).all()

def test_goal_cpu():
    _test_no_goal('cpu')
    _test_negative_goal('cpu')
    _test_positive_goal('cpu')

@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_goal_cuda():
    _test_no_goal('cuda')
    _test_negative_goal('cuda')
    _test_positive_goal('cuda')
    print(json.dumps(ConstraintsModule.profiler.combined(), indent=4, sort_keys=True))

def _test_empty_preds(device):
    group = ConstraintsGroup([
        Constraint('0 :- 1')
    ])

    cm = ConstraintsModule(group, 2)
    preds = torch.rand((0, 2))
    goal = torch.rand((0, 2))
    updated = run_cm(cm, preds, goal=goal, device=device)
    assert updated.shape == torch.Size([0, 2])

def _test_no_constraints(device):
    group = ConstraintsGroup([])
    cm = ConstraintsModule(group, 10)
    preds = torch.rand((500, 10))
    goal = torch.rand((500, 10))

    updated = run_cm(cm, preds, device=device)
    assert (updated == preds).all()
    updated = run_cm(cm, preds, goal=goal, device=device)
    assert (updated == preds).all()

def test_empty_preds_constraints_cpu():
    _test_empty_preds('cpu')
    _test_no_constraints('cpu')

@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_empty_preds_constraints_cuda():
    _test_empty_preds('cuda')
    _test_no_constraints('cuda')

def test_lb_ub():
    group = ConstraintsGroup([
        Constraint('0 :- 1'),
        Constraint('n0 :- 2')
    ])
    cm = ConstraintsModule(group, 3)
    preds = torch.tensor([
        [0.5, 0.6, 0.3],
        [0.65, 0.6, 0.3],
        [0.8, 0.6, 0.3],
        [0.5, 0.7, 0.4],
        [0.65, 0.7, 0.4],
        [0.8, 0.7, 0.4],
    ])

    updated = run_cm(cm, preds)
    assert (updated[:, 0] == torch.tensor([0.6, 0.65, 0.7] * 2)).all()

def _test_time(iterative, device):
    group = ConstraintsGroup('../constraints/full')
    cm = ConstraintsModule(group, 41).to(device)
    preds = torch.rand(5000, 41, device=device)
    cm(preds, iterative=iterative)

def test_time_iterative_cpu():
    for i in range(10):
        _test_time(True, 'cpu')

def test_time_tensor_cpu():
    for i in range(10):
        _test_time(False, 'cpu')

@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_time_iterative_cuda():
    for i in range(10):
        _test_time(True, 'cuda')

@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
def test_time_tensor_cuda():
    for i in range(10):
        _test_time(False, 'cuda')


from vinfra.api import base
from vinfra.api_versions import APIVersion
from vinfra.client import ApiV3
from vinfra.utils import flatten_args

V3_BACKEND_VERSION = APIVersion('6.0.19')
V3_MAINTENANCE_BACKEND_VERSION = APIVersion('6.1.17')
V3_CONTROL_PLANE_BACKEND_VERSION = APIVersion('7.0.50')

def maintenance_to_mode(maintenance):
    if not maintenance['enabled']:
        return 'no_maintenance'
    elif maintenance['on_fail'] == 'force':
        return 'force'
    elif maintenance['on_fail'] == 'skip':
        return 'skip'
    return 'stop'

class SoftwareUpdatesManager(object):

    def __init__(self, api):
        self.api = api

    def get(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.get('/software_updates')
        else:
            return self.api.client.get('/software_updates')

    def start_async(self, req):
        params = {
            'accept_eula': req.get('accept_eula', False)
        }
        if self.api.backend_version >= V3_CONTROL_PLANE_BACKEND_VERSION:
            nodes = req.get('nodes')
            if nodes is not None:
                params['nodes'] = [base.get_id(v) for v in nodes]
                params['control_plane'] = False
            else:
                params['control_plane'] = not req['skip_control_plane']
        elif self.api.backend_version >= V3_BACKEND_VERSION:
            nodes = req.get('nodes')
            if nodes is not None:
                params['nodes'] = [base.get_id(v) for v in nodes]
                params['services'] = {
                    'compute': {
                        'update': not nodes,
                    },
                }

        maintenance = req['maintenance']
        if self.api.backend_version >= V3_MAINTENANCE_BACKEND_VERSION:
            params['maintenance'] = {
                'enabled': maintenance['enabled']
            }
            if maintenance['enabled']:
                params['maintenance']['params'] = {
                    'on_fail': maintenance['on_fail'],
                    'compute': {
                        'mode': maintenance['compute_mode'],
                    }
                }
        else:
            params['mode'] = maintenance_to_mode(maintenance)

        data = flatten_args(**params)
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/start', json=data)
        else:
            return self.api.client.post_async('/software_updates/start', json=data)

    @base.async_wait
    def start(self, **kwargs):
        return self.start_async(**kwargs)

    def resume_async(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/resume')
        else:
            return self.api.client.post_async('/software_updates/resume')

    @base.async_wait
    def resume(self):
        return self.resume_async()

    def check_for_update_async(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/check_for_update')
        else:
            return self.api.client.post_async('/software_updates/check_for_update')

    @base.async_wait
    def check_for_update(self):
        return self.check_for_update_async()

    def download_async(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/download')
        else:
            return self.api.client.post_async('/software_updates/download')

    @base.async_wait
    def download(self):
        return self.download_async()

    def eligibility_check_async(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/eligibility_check')
        else:
            return self.api.client.post_async('/software_updates/eligibility_check')

    @base.async_wait
    def eligibility_check(self):
        return self.eligibility_check_async()

    def pause_async(self):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            with ApiV3(self.api.client):
                return self.api.client.post_async('/software_updates/pause')
        else:
            return self.api.client.post_async('/software_updates/pause')

    @base.async_wait
    def pause(self):
        return self.pause_async()

    def cancel_async(self, maintenance_mode):
        if self.api.backend_version >= V3_BACKEND_VERSION:
            params = {
                'maintenance_mode': maintenance_mode,
            }
            data = flatten_args(**params)
            with ApiV3(self.api.client):
                return self.api.client.delete_async('/software_updates/start', json=data)
        else:
            return self.api.client.delete_async('/software_updates/start')

    @base.async_wait
    def cancel(self, **kwargs):
        return self.cancel_async(**kwargs)


from flask import Flask, render_template, flash, request, Markup
from wtforms import Form, StringField, validators
from src.opt import get_sos
from sympy import poly, latex, sympify, nan
from src.poly import get_latex_from_poly, is_polynomial

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = 'SjdnUends821Jsdlkvxh391ksdODnejdDw'

class ReusableForm(Form):
    polynomial = StringField('Polynomial', validators=[validators.DataRequired()])

@app.route('/', methods=['GET', 'POST'])
def hello():
    form = ReusableForm(request.form)
    if request.method == 'POST':
        _input = request.form['polynomial']
        if form.validate() and is_polynomial(_input):
            _polynomial = poly(_input)
            msg, sos = get_sos(_polynomial)
            if sos == nan:
                flash(Markup(f'Input: \({latex(sympify(_input))}\)'))
                flash(Markup(f'Result: {msg}'))
            else:
                flash(Markup(f'Result: \({latex(sympify(_input))} = {get_latex_from_poly(sos)}\)'))
        else:
            flash('Error: Non-constant polynomial required')
    return render_template('index.html', form=form)

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


import random
from custom_data_structures.splay_tree.splay_tree import SplayTree

def main():
    # n: int = int(input())
    # s: int = 0
    # def f(i: int) -> int:
    #     return (i + s) % 1000000001
    #
    # tree = SplayTreeImplicitKeys()
    # for _ in range(n):
    #     line = input()
    #     if line.startswith("s"):
    #         _, l, r = line.strip().split(" ")
    #         l, r = int(l), int(r)
    #         s = tree.sum(f(l), f(r))
    #         print(s)
    #     else:
    #         op, i = line.strip().split(" ")
    #         i = int(i)
    #         if op == "+":
    #             tree.insert(f(i))
    #         if op == "-":
    #             tree.remove(f(i))
    #         if op == "?":
    #             node = tree.search(f(i))
    #             if node:
    #                 print("Found")
    #             else:
    #                 print("Not found")

    tree = SplayTree()
    set_ = set()
    cmds = ['insert', 'delete', 'find', 'sum']
    for _ in range(500):
        cmd_idx = random.randint(0, 3)
        rand_cmd = cmds[cmd_idx]
        rand_int = random.randint(0, 100)
        if rand_cmd == 'insert':
            print(f'inserting {rand_int}')
            set_.add(rand_int)
            tree.insert(rand_int)
        if rand_cmd == 'delete':
            print(f'deleting {rand_int}')
            tree.remove(rand_int)
            try:
                set_.remove(rand_int)
            except KeyError:
                pass
        if rand_cmd == 'find':
            print(f'finding {rand_int}')
            found_node = tree.search(rand_int)
            is_in_set = rand_int in set_
            assert (found_node is not None) is is_in_set
        if rand_cmd == 'sum':
            l = random.randint(0, 50)
            r = random.randint(50, 100)
            print(f'sum l={l} r={r}')
            print(tree.sum(l, r))
        if tree.root:
            print('after operation:')
            tree.root.display()
        result = []
        assert tree.in_order_traversal(result)
        assert len(result) == len(set_)

if __name__ == "__main__":
    main()


import tensorflow as tf
#
# PROPERTIES
#
FEATURE_PROPS={
        'tile_id': tf.string,
        'date': tf.string,
        'crs': tf.string,
        'lon': tf.float32,
        'lat': tf.float32,
        'cirrus_score': tf.float32,
        'opaque_score': tf.float32,
        'black_score': tf.float32,
        'centroid_lc_type': tf.float32,
        'BIOME_NUM': tf.float32,
        'BIOME_NAME': tf.string,
        'ECO_NAME': tf.string,
        'ECO_ID': tf.float32,
        'country_na': tf.string,
        'wld_rgn': tf.string
}
INPUT_BANDS=['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B9', 'B11', 'B12']
RGB_BANDS=['red','green','blue']
CLOUD_BANDS=['cirrus','opaque']
BANDS=INPUT_BANDS+RGB_BANDS+CLOUD_BANDS
#
# IMAGE CONFIG
#
SIZE=510
HALF_SIZE=SIZE//2
RES=10
PATCH_DIMS=[SIZE, SIZE]
#
# GCS/RUN
#
BUCKET='living-map-dev'
FOLDER='tmp'
NOISY=False
NOISE_REDUCER=100
#
# PARSER
#
COMPRESSION_TYPE='GZIP'
PARALLEL_FILE_READS=5
PARALLEL_PARSE_CALLS=2
DEFAULT_STR_VALUE=''
DEFAULT_NB_VALUE=0


import pygame
import os

class Bird:
    ACCELERATION = 1 #Value for how fast the bird should accelerate downwards
    JUMP_CONST = -4.0 #Value for how much the bird should accelerate up by when it jumps
    TERMINAL_VELOCITY = 10.0 #Value for the amount of displacement where the bird stops accelerating

    def __init__(self, x, y, img = pygame.transform.scale(pygame.image.load(os.path.join("Assets","FBird_mediumwings.png")).convert_alpha(), (51, 36))):
        self.img = img
        self.x = x
        self.y = y
        self.height = self.y
        self.velocity = 0.0
        self.tick = 0
        self.rect = pygame.Rect(self.x, self.y, img.get_width(), img.get_height())
        self.failed = False

    #def update(self):

    def jump(self):
        self.velocity = self.JUMP_CONST
        self.tick = 0 #To restart the acceleration
        self.height = self.y

    def move(self):
        self.tick += 1
        #y = ax^2 + bx
        #d = vt + 0.5(at^2) kinematic equation, getting displacement of y for the movement of the bird
        displacement = self.velocity*(self.tick/2) + (0.5)*(self.ACCELERATION)*(self.tick/2)**2

        if displacement >= self.TERMINAL_VELOCITY:
            displacement = self.TERMINAL_VELOCITY if displacement > 0 else (-1)*(self.TERMINAL_VELOCITY) #Stays at T.V with the correct direction

        if displacement < 0:
            displacement -= 2 #If it jumped, make the acceleration upwards slowly turn downwards

        if self.y > 700:
            displacement = 0

        self.y = self.y + displacement
        self.rect.y = self.y
    def draw(self, window):
        window.blit(self.img, (self.rect.x, self.rect.y))
    def stop(self):
        self.JUMP_CONST = 0
    def start(self):
        self.JUMP_CONST = -10.0


import cv2
import numpy as np

def displayWindows(names, images, widthLimit=1000):
  if len(names) == 0:
    return
  images2DArray = []
  row = []
  rowWidth = 0
  h, w, _ = images[0].shape

  for img in images:
    row.append(img)
    rowWidth += w
    lastRowAdded = False
    if rowWidth >= widthLimit:
      images2DArray.append(row)
      row = []
      rowWidth = 0
      lastRowAdded = True
  if not lastRowAdded:
    images2DArray.append(row)
  height = len(images2DArray) * h
  width = len(images2DArray[0]) * w
  windowImage = np.zeros((height,width,3), np.uint8)
  nameIndex = 0
  for i in range(len(images2DArray)):
    row = images2DArray[i]
    for j in range(len(row)):
      windowImage[h * i:h * i + h, w * j:w * j + w] = img[::]
      cv2.putText(windowImage, names[nameIndex], (w * j, h * i + 22), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 1, 8)
      nameIndex += 1
  cv2.imshow('Window', windowImage)


"""
This class is derived class of a table
"""
from Errors import QueryError
from Table import Table

class View:
    def __init__(self, name, query, database):
        """
        Initializes the view
        :param query:
        """
        self.name = name
        self.query = query
        self.database = database
        self.columns = list()

        # Parses the query to get the data it needs
        i = 1
        while query[i] != "FROM":
            if query[i] == ",":
                i += 1
                continue
            if query[i + 1] == "," or query[i + 1] == "FROM":  # preceded by a comma or FROM is next
                self.columns.append(query[i])
            else:
                raise QueryError("Missing comma separator")
            i += 1
        i += 2
        self.sub_name = query[i-1]

        # removes '*'
        for col in self.columns:
            if col == '*':
                self.columns = [h for h in self.database.tables[self.sub_name].headers.keys()]

    def select(self, columns_to_get, order_by, distinct, where, collations, aggregates):
        data = self.database.select_prep(self.query)
        table = Table(self.sub_name, self.columns, False, [self.sub_name], {})
        table.table = data

        # Sets the types/headers for the table
        table.headers = {col: i for i, col in enumerate(self.columns)}

        # Gets the related table names
        for col in self.columns:
            found = col.find('.')
            if found != -1 and col[:found] not in table.rel_tables:
                table.rel_tables.append(col[:found])

        return table.select(columns_to_get, order_by, distinct, where, collations, aggregates)


def average(*nums: int | float) -> float:
    sum = 0
    for n in nums:
        sum += n
    return sum / len(nums)

text = input("enter three numbers, separated by spaces: \n> ")
nums = [float(i) for i in text.replace(",", "").split()]
print(average(*nums))

######

def PythagoreanCheck(a: int, b: int, hypot: int) -> bool:
    return a**2 + b**2 == hypot**2

text = input("enter two sides and the hypotenuse, separated by spaces: \n> ")
nums = [int(i) for i in text.replace(",", "").split()]
if len(nums) != 3:
    raise ValueError("the number of arguements was not 3")
print(PythagoreanCheck(nums[0], nums[1], nums[2]))

######

# I already did the object stuff in week 1

1st semseter/check for understanding (16th sep).py


from datetime import datetime, timedelta, timezone

def week():
    end = datetime.now(tz=timezone(offset=-timedelta(hours=4)))
    start = end - timedelta(hours=168)
    return start, end

def month():
    end = datetime.now(tz=timezone(offset=-timedelta(hours=4)))
    start = end - timedelta(hours=730)
    return start, end

def to_datetime(*items):
    if len(items) == 1:
        return datetime.strptime(items[0], r"%d-%m-%Y")
    else:
        return [datetime.strptime(item, r"%d-%m-%Y") for item in items]

TIMEFRAMES = {'week': week, 'month': month}


from datetime import datetime

from loguru import logger
from scrapy import Request, Spider
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class CraftbeerShopBrewerySpider(CrawlSpider):
    """
    Craftbeer Shop Spider Class
    """

    name = "craftbeer_shop_breweries"
    allowed_domains = ["craftbeer-shop.com"]
    main_url = "https://www.craftbeer-shop.com/"
    start_urls = ["https://www.craftbeer-shop.com/"]
    datestamp = datetime.now().strftime("%Y%m%d")
    timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")

    rules = (
        Rule(
            LinkExtractor(allow=("Brauereien/", "brauereien/")),
            callback="parse",
            follow=True,
        ),
    )

    def parse(self, response, **kwargs):
        logger.info(f"Crawling {response.url}...")

        breweries = response.xpath("//div[contains(@class, 'subcategory-card')]")
        num_breweries = len(breweries)
        logger.info(
            f"Found {num_breweries} breweries on page {response.url}, starting to crawl..."
        )
        success_counter = 0

        for brewery in breweries:
            name = brewery.css("a.subcategory-card__title::text").get()
            country = response.url.split("/")[-1]

            icon_url = brewery.xpath(
                ".//div[contains(@class, 'subcategory-card__image')]//img/@data-src"
            ).get()
            scraped_from_url = response.url
            logger.info(name, country, icon_url, scraped_from_url)

            yield {
                "name": name,
                "country": country,
                "icon_url": icon_url,
                "scraped_from_url": scraped_from_url,
            }
            success_counter += 1


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 17 16:00:29 2019

@author: rafaelolaechea

Start Learning Command.

                        InfluenceModel infMod = new InfluenceModel(GlobalState.varModel, GlobalState.currentNFP);

                        List<Configuration> configurations_Learning = new List<Configuration>();

                        List<Configuration> configurations_Validation = new List<Configuration>();

                        ....

                           //List<List<BinaryOption>> availableBinary
                            configurations_Learning = GlobalState.getAvailableBinary(exp.BinarySelections_Learning, exp.NumericSelection_Learning);
                            //configurations_Learning = GlobalState.getMeasuredConfigs(Configuration.getConfigurations(availableBinary, exp.NumericSelection_Learning));
                            configurations_Learning = configurations_Learning.Distinct().ToList();

                            configurations_Validation = GlobalState.getMeasuredConfigs(Configuration.getConfigurations(exp.BinarySelections_Validation, exp.NumericSelection_Validation));
                            configurations_Validation = configurations_Validation.Distinct().ToList();

                        ...

                        exp.learning = new FeatureSubsetSelection(infMod, exp.mlSettings);
                        exp.learning.setLearningSet(configurations_Learning);
                        exp.learning.setValidationSet(configurations_Validation);
                        exp.learning.learn();

addConfiguration

Configuration config

        /// <summary>
        /// Adds a configration to the global state.
        /// </summary>
        /// <param name="config">An configuration of the variability model.</param>
        public static void addConfiguration(Configuration config)
        {
            GlobalState.allMeasurements.add(config);
        }

Result Database

    public class ResultDB
    {

        private List<Configuration> configurations = new List<Configuration>();

        public List<Configuration> Configurations
        {
            get { return configurations; }
            set { configurations = value; }
        }

        public void add(Configuration configuration)
        {
            this.configurations.Add(configuration);
        }

"""
import MLSettings
import VariabilityModel
import BinaryOption

import FeatureWrapper

def createX264VM():
    """
    Creatre variability model for X264
    """
    return None

if __name__ == "__main__":

    tmpDefaultMLSettings = MLSettings.MLSettings()

    varMod =  VariabilityModel.VariabilityModel("testModel_1")

    # Only has root.
    print ("Created a tmpDefaultMLSettings and a varMod with a feature of name {0}. In Total has {1} objects ".format(\
           varMod.getRoot().name, len(varMod.getBinaryOptions())))

    binOp1 =  BinaryOption.BinaryOption(varMod, "binOpt1")

    binOp1.optional = True

    binOp1.Parent = varMod.getRoot()

    varMod.addConfigurationOption(binOp1)

    # Only has root and binary option 1.
    print ("Created a tmpDefaultMLSettings and a varMod with a feature of name {0}. In Total has {1} objects ".format(\
           varMod.getRoot().name, len(varMod.getBinaryOptions())))

    binOp2 =  BinaryOption.BinaryOption(varMod, "binOp2")

    binOp2.optional = True

    binOp2.Parent = binOp1

    varMod.addConfigurationOption(binOp2)

    print ("Created a tmpDefaultMLSettings and a varMod with a feature of name {0}. In Total has {1} objects ".format(\
           varMod.getRoot().name, len(varMod.getBinaryOptions())))

    newFeature = FeatureWrapper.FeatureWrapper("binOpt1", varMod)

    tmpDct = {}

    tmpDct[newFeature] = 10
    newDuplicateFeature = FeatureWrapper.FeatureWrapper("binOpt1", varMod)

    UnDuplicateFeature = FeatureWrapper.FeatureWrapper("binOp2*binOpt1", varMod)

    print(newFeature == newDuplicateFeature)
    print(newFeature == UnDuplicateFeature)

    print("expressionArray newFeature  == " +str(newFeature.expressionArray))

    print("expressionArray UnDuplicateFeature binOp2*binOpt1 ::  == " +str(UnDuplicateFeature.expressionArray))

    UnDuplicateDuplicateFeature = FeatureWrapper.FeatureWrapper("binOpt1 * binOp2", varMod)

    print(UnDuplicateDuplicateFeature == UnDuplicateFeature)

    print( "Before Modified dct  {0}".format(str(tmpDct)))

    print( "NewFeature Duplicate in dct keys {0}".format(newDuplicateFeature in tmpDct.keys()))

    tmpDct[newDuplicateFeature] = 20

    print( "Modified dct  {0}".format(str(tmpDct)))


import os
import pickle

import numpy as np
import torch
from tqdm import tqdm
from torch.utils import data

from Models import CNNEncoder, RNNDecoder
from sklearn.preprocessing import LabelEncoder
import torchvision.transforms as transforms

from Models.DataSetLoader import DataSetLoader

class CRNN():

    def __init__(self):
        # use same encoder CNN saved!
        self.CNN_fc_hidden1, self.CNN_fc_hidden2 = 1024, 768
        self.CNN_embed_dim = 512  # latent dim extracted by 2D CNN
        self.res_size = 224  # ResNet image size
        self.dropout_p = 0.0  # dropout probability

        self.RNN_hidden_layers = 3
        self.RNN_hidden_nodes = 512
        self.RNN_FC_dim = 256

        self.k = 101  # number of target category
        self.batch_size = 40
        self.begin_frame, self.end_frame, self.skip_frame = 1, 29, 1

        self.label_encoder = LabelEncoder()
        self.action_category = []

        use_cuda = torch.cuda.is_available()  # check if GPU exists
        device = torch.device("cuda" if use_cuda else "cpu")

        self.encoder = CNNEncoder.CNNEncoder(self.CNN_fc_hidden1, self.CNN_fc_hidden2, self.dropout_p,
                                             self.CNN_embed_dim).to(device)

        self.decoder = RNNDecoder.RNNDecoder(self.CNN_embed_dim, self.RNN_hidden_layers, self.RNN_hidden_nodes,
                                             self.RNN_FC_dim, self.dropout_p, self.k).to(device)

    def load(self):
        project_path = os.getcwd()
        save_model_path = project_path + '/cached'
        self.encoder.load_state_dict(
            torch.load(os.path.join(save_model_path, 'cnn_encoder_epoch63_singleGPU.pth'), map_location='cpu'))
        self.decoder.load_state_dict(
            torch.load(os.path.join(save_model_path, 'rnn_decoder_epoch63_singleGPU.pth'), map_location='cpu'))

        with open(save_model_path + '/UCF101actions.pkl', 'rb') as f:
            action_names = pickle.load(f)  # load UCF101 actions names

        # convert labels -> category
        self.label_encoder.fit(action_names)
        self.action_category = self.label_encoder.transform(action_names).reshape(-1, 1)

    def run(self, path, x, y):
        # data loading parameters
        use_cuda = torch.cuda.is_available()  # check if GPU exists
        device = torch.device("cuda" if use_cuda else "cpu")  # use CPU or GPU
        params = {'batch_size': self.batch_size, 'shuffle': True, 'num_workers': 4,
                  'pin_memory': True} if use_cuda else {}

        transform = transforms.Compose([transforms.Resize([self.res_size, self.res_size]),
                                        transforms.ToTensor(),
                                        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])

        selected_frames = np.arange(self.begin_frame, self.end_frame, self.skip_frame).tolist()

        # reset data loader
        all_data_params = {'batch_size': self.batch_size, 'shuffle': False, 'num_workers': 4,
                           'pin_memory': True} if use_cuda else {}

        y = self.label_encoder.transform(y)

        data_loader = data.DataLoader(
            DataSetLoader(path, x, y, selected_frames, transform=transform), **all_data_params)

        self.encoder.eval()
        self.decoder.eval()

        all_y_pred = []
        with torch.no_grad():
            for batch_idx, (X, y) in enumerate(tqdm(data_loader)):
                # distribute data to device
                X = X.to(device)
                output = self.decoder(self.encoder(X))
                y_pred = output.max(1, keepdim=True)[1]  # location of max log-probability as prediction
                all_y_pred.append(y_pred.cpu().data.squeeze().numpy().tolist())

        return self.label_encoder.inverse_transform(all_y_pred)


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('user_profile', '0001_initial'),
        ('schedule', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='section',
            name='student',
            field=models.ForeignKey(default=None, to='user_profile.Student', related_name='student_sections'),
            preserve_default=False,
        ),
        migrations.AlterUniqueTogether(
            name='section',
            unique_together=set([('student', 'course', 'day')]),
        ),
    ]


import os
from telethon.sync import TelegramClient, events, types, functions
import logging
from datetime import date, datetime, timezone
import asyncio
from pathlib import Path

logging.basicConfig(filename="./logs.txt", filemode='a',
                    format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
                    level=logging.WARNING)

API_ID = os.environ["TG_API_ID"]
API_HASH = os.environ["TG_API_HASH"]
PARSE_CHAT_ID = int(os.environ["TG_PARSE_CHAT_ID"])
FORWARD_CHAT_ID = int(os.environ["TG_FORWARD_CHAT_ID"])
SESSION = "SOPHIEPALEOLOG"
INTERVAL_IN_SEC = 10
MESSAGE_MIN_LIVE_IN_SEC = 120
LAST_MESSAGE_ID = 0
GET_MESSAGE_CNT_LIMIT = 300

client = None
forward_chat = None
last_msg_file = Path("./lastmsg.txt")

# forward message if contains url
async def forward_message(message):
    for ent, _ in message.get_entities_text():
        if isinstance(ent, types.MessageEntityUrl) or isinstance(ent, types.MessageEntityTextUrl):
            try:
                await message.forward_to(forward_chat)
            except Exception as e:
                logging.error(e)
                logging.warning(message)
            finally:
                return

# gets now and date timedelta in seconds
def last_from_date_in_secs(date):
    return (datetime.now(timezone.utc) - date).seconds

def save_last_messsage_id():
    last_msg_file.write_text(str(LAST_MESSAGE_ID))

def get_last_message_id():
    global LAST_MESSAGE_ID
    if not last_msg_file.is_file():
        save_last_messsage_id()

    LAST_MESSAGE_ID = int(last_msg_file.read_text())

# check for new messages and if it lasts > MESSAGE_MIN_LIVE_IN_SEC and id > LAST_MESSAGE_ID
async def forward_new_messages():
    global LAST_MESSAGE_ID, client
    client = TelegramClient(SESSION, API_ID, API_HASH)
    await client.start()
    messages = [m async for m in client.iter_messages(PARSE_CHAT_ID, limit=GET_MESSAGE_CNT_LIMIT)
    if m.id > LAST_MESSAGE_ID and last_from_date_in_secs(m.date) > MESSAGE_MIN_LIVE_IN_SEC]
    for message in reversed(messages):
        await forward_message(message)

    if len(messages) > 0:
        LAST_MESSAGE_ID = messages[0].id
    save_last_messsage_id()

    await client.disconnect()

# # update client and start because it somehow stops working
# async def update_client():
#     global last_client_update_time
#     if last_from_date_in_secs(last_client_update_time) < CLIENT_UPDATE_INTERVAL_IN_SEC:
#         return
#     if client.is_connected():
#         await client.start()
#     last_client_update_time = datetime.now(timezone.utc)

async def main():
    global forward_chat, client, last_msg_file
    get_last_message_id()
    client = TelegramClient(SESSION, API_ID, API_HASH)
    await client.start()
    forward_chat = await client.get_entity(FORWARD_CHAT_ID)
    await client.disconnect()

    while True:
        await asyncio.gather(
            asyncio.sleep(INTERVAL_IN_SEC),
            forward_new_messages()
        )

if __name__ == '__main__':
    asyncio.run(main())


import cv2
import time
import os
import handDetector as hd
import facerecognition

class GestureDetector():
    def __init__(self):
        self.wCam, self.hCam = 640, 480
        self.cap = cv2.VideoCapture(0)
        self.pTime = 0
        self.detector = hd.handDetector(detectionCon=0.75)
        self.tipIds = [4, 8, 12, 16, 20]
        self.message = ''

    def gestureDetection(self):

        while True:
            self.facerecognition = facerecognition.FaceRecognition(self.cap)
            self.img = self.facerecognition
            #self.img = cv2.flip(self.img,1)
            self.img = self.detector.findHands(self.img)
            lmList = self.detector.findPosition(self.img, draw=False)
            # print(lmList)

            if len(lmList) != 0:
                self.fingers = []

                # Thumb
                if lmList[self.tipIds[0]][1] > lmList[self.tipIds[0] - 1][1]:
                    self.fingers.append(1)
                else:
                    self.fingers.append(0)

                # 4 Fingers
                for id in range(1, 5):
                    if lmList[self.tipIds[id]][2] < lmList[self.tipIds[id] - 2][2]:
                        self.fingers.append(1)
                    else:
                        self.fingers.append(0)

                totalFingers = self.fingers.count(1)
                #print(totalFingers)

                if self.fingers == [0,1,0,0,1] or self.fingers == [1,1,0,0,0] or self.fingers == [0,1,1,0,0] or self.fingers == [1,1,0,0,1] or self.fingers == [0,0,0,0,1]:
                    self.message = 'HELP!!!'
                else:
                    self.message == "IT'S OK!!"

                #h, w, c = overlayList[totalFingers - 1].shape
                #img[0:h, 0:w] = overlayList[totalFingers - 1]

                #cv2.rectangle(self.img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED)
                #cv2.putText(self.img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN,
                #            10, (255, 0, 0), 25)

            cTime = time.time()
            fps = 1 / (cTime - self.pTime)
            pTime = cTime

            #cv2.imshow('Image', self.img)
            cv2.waitKey(1)
            return self.message, self.img

    def gestureMessage(self):
        pass


from torch.utils import data
import os
import torchvision.transforms as transforms
import numpy as np
import cv2

class Dataset(data.Dataset):

    def __init__(self, path,folder_list):
        self.path = path
        self.images_folder = folder_list   #图片文件夹，每个小文件夹是一个样本（包含五张）
        self.size = 320

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

    def load_image(self,path):
        # image = cv2.cvtColor(cv2.imread(path))
        image=cv2.imread(path)
        image = cv2.resize(image, (self.size, self.size))
        # 图像归一化
        transform_GY = transforms.ToTensor()#将PIL.Image转化为tensor，即归一化。
        # 图像标准化
        transform_BZ= transforms.Normalize(
        mean=[0.5, 0.5, 0.5],# 取决于数据集
        std=[0.5, 0.5, 0.5]
        )
        # transform_compose
        transform_compose= transforms.Compose([
        # 先归一化再标准化
            transform_GY,
            transform_BZ
        ])
        # (H, W, C)变为(C, H, W)
        img_normalize = transform_compose(image)
        img_normalize=img_normalize.numpy()
        return img_normalize

    def __getitem__(self, index):
        images_path=os.path.join(self.path,self.images_folder[index])
        images=os.listdir(images_path)
        #找出target
        target=None   #此时的target是路径
        images_without_target=[]
        for image in images:
            if image.endswith('F.png'):
                target=image
            else:
                images_without_target.append(image)
        images=images_without_target

        #加载图片为numpy数组
        if target is not None:
            target=self.load_image(os.path.join(images_path,target))
        tmp=[]

        for i in range(len(images)):
            burst_i=self.load_image(os.path.join(images_path,images[i]))
            tmp.append(burst_i)

        burst=np.array(tmp) #转换成numpy格式

        if target is None:
            return burst, self.images_folder[index]
        else:
            #return两个，一个是x，另一个是label标签
            return burst, target, self.images_folder[index]


#!/usr/bin/env python
'''
:mod:`core.parser` is a module containing class for parsing log files.
'''

import mmap
import os
import re
import traceback
import platform
from types import ListType

from module import ModuleController as mc

class Parser(object):
    '''
    Parser for benchmark outputs.
        :param filename: Name of the log file
        :type filename: str.
        :param module: Current module used to parse file
        :type module: object.
    '''

    def __init__(self, filename='', module=None):
        if module is None:
            raise Exception("Should choose a module to parse the log file.")
        self._info = {}
        self._module = module
        self.__filename = filename

        return None

    def load_file(self):
        '''
        Loads logfile.
            :return: ``True`` if loading and parsing of file went fine, \
            ``False`` if it failed (at any point)
        '''

        # We first split file into pieces
        searchunks = self._split_file()

        if searchunks:

            # And then we parse pieces into meaningful data
            self._info = self._parse_file(searchunks)

            return True

        else:
            return False

    def get_info(self):
        '''
        Returns parsed info
            :return: ``Dictionary``-style list of data
        '''

        file_parsed = self.load_file()
        if file_parsed:
            return self._info
        else:
            return False

    def _split_file(self):
        '''
        Splits log file (in ASCII format) in order to accelerate processing speed.
            :param data: Input data instead of file
            :type data: str.
            :return: ``List``-style of file sections
        '''

        # Filename passed checks through __init__
        if self.__filename and os.access(self.__filename, os.R_OK):

            fhandle = None

            try:
                fhandle = os.open(self.__filename, os.O_RDONLY)
            except OSError:
                raise Exception(("Couldn't open file {}".format(self.__filename)))

            if fhandle:

                datalength = 0

                # Dealing with mmap difference on Windows and Linux
                if platform.system() == 'Windows':
                    dataprot = mmap.ACCESS_READ
                else:
                    dataprot = mmap.PROT_READ

                try:
                    if platform.system() == 'Windows':
                        parmap = mmap.mmap(
                            fhandle, length=datalength, access=dataprot
                        )
                    else:
                        parmap = mmap.mmap(
                            fhandle, length=datalength, prot=dataprot
                        )
                except (TypeError, IndexError):
                    os.close(fhandle)
                    traceback.print_exc()
                    return False

                # Here we'll store chunks of file, unparsed
                searchunks = []
                oldchunkpos = 0
                dlpos = parmap.find(self._module.delimeter(), 0)
                size = 0

                # We can do mmap.size() only on read-only mmaps
                size = parmap.size()

                while dlpos > -1:  # mmap.find() returns -1 on failure.

                    tempchunk = parmap.read(dlpos - oldchunkpos)
                    searchunks.append(tempchunk.strip())

                    # We remember position, add 2 for 2 DD's
                    # (newspaces in production). We have to remember
                    # relative value
                    oldchunkpos += (dlpos - oldchunkpos) + 2

                    # We position to new place, to be behind \n\n
                    # we've looked for.
                    try:
                        parmap.seek(2, os.SEEK_CUR)
                    except ValueError:
                        print(("Out of bounds ({})!\n".format(parmap.tell())))
                    # Now we repeat find.
                    dlpos = parmap.find(self._module.delimeter())

                # If it wasn't the end of file, we want last piece of it
                if oldchunkpos < size:
                    tempchunk = parmap[(oldchunkpos):]
                    searchunks.append(tempchunk.strip())

                parmap.close()

            if fhandle != -1:
                os.close(fhandle)

            if searchunks:
                return searchunks
            else:
                return False

        return False

    def _parse_file(self, parts):
        '''
        Parses splitted file to get proper information from split parts.
            :param sar_parts: Array of SAR file parts
            :return: ``Dictionary``-style info (but still non-parsed) \
                from SAR file, split into sections we want to check
        '''
        pattern = None
        # If parts is a list
        if type(parts) is ListType:
            pattern = self._module.pattern()

            if pattern is None:
                return False

            results = []
            for part in parts:
                matches = pattern.finditer(part)
                for matchNum, match in enumerate(matches):
                    result = {key:match.group(pattern.groupindex[key]) for key in pattern.groupindex}
                    results.append(result)
            output = self.__split_info(results)
            del(parts)

            # Now we have parts pulled out and combined, do further
            # processing.
            # cpu_output = self.__split_info(cpu_usage, PART_CPU)

        return output

    def __find_column(self, column_names, part_first_line):
        '''
        Finds the column for the column_name in sar type definition,
        and returns its index.
            :param column_name: Names of the column we look for (regex) put in
                the list
            :param part_first_line: First line of the SAR part
            :return: ``Dictionary`` of names => position, None for not present
        '''
        part_parts = part_first_line.split()

        ### DEBUG
        #print("Parts: %s" % (part_parts))

        return_dict = {}

        counter = 0
        for piece in part_parts:
            for colname in column_names:
                pattern_re = re.compile(colname)
                if pattern_re.search(piece):
                    return_dict[colname] = counter
                    break
            counter += 1

        # Verify the content of the return dictionary, fill the blanks
        # with -1s :-)
        for colver in column_names:
            try:
                tempval = return_dict[colver]
                del(tempval)
            except KeyError:
                return_dict[colver] = None

        return(return_dict)

    def __split_info(self, parts):
        '''
        Maps parts into logical stuff
        :param parts: Parts to map into usable data
        :return: ``List``-style info from files, now finally \
            completely parsed into meaningful data for further processing
        '''
        # Common assigner

        return self._module.split_info(parts)


def leiadinheiro(_):
    while True:
        try:
            valido = False
            while not valido:
                entrada = str(input(_)).replace(',', '.').strip().replace(' ', '')
                if entrada.isalpha() or entrada == '':
                    print(f'\033[0;31m"{entrada}" é um valor inválido\033[m')
                else:
                    valido = True
                    return float(entrada)
            break
        except:
            print(f'\033[0;31mERRO! Não insira letras ao valor\033[m')


def equal_prime(n):
    """
    `2005`年复试上机题
    把一个数表示成若干个素数的和.
    注， 此题不用这个方法。
    """

    def judge_prime(n):
        if n == 0 or n == 1: return False
        if n == 2: return True
        if n % 2 == 0: return False
        # 判断
        if 0 in [n % i for i in range(2, int(n ** 0.5 + 1))]:
            return False
        return True

    def DFS(n, index=0, sum=0, primes=[], L=[], S=None):
        if S is None:
            S = set()
        if (sum > n):
            return
        # sum==n 找到了这样的一组数字
        if index < len(primes):
            if sum == n:
                if tuple(L) not in S:  # 避免重复输出
                    print(L)
                    S.add(tuple(L))
            L.append(primes[index])
            DFS(n, index, sum + primes[index], primes, L, S)
            L.pop()
            DFS(n, index + 1, sum, primes, L, S)

    plist = [i for i in range(n + 1) if judge_prime(i)]
    DFS(n, 0, 0, plist, S=set())
equal_prime(9)


class Solution(object):
    def lengthOfLongestSubstring(self, strg):
    	"""
    	:type strg: str
    	:rtype: int
    	"""
    	table = {}
    	accum = 0
    	currMax = 0
    	start = 0
    	for pos, i in enumerate(strg):
    		if i not in table:
    			table[i] = pos
    			accum += 1
    		else:
    			currMax = max(currMax, accum)
    			if table[i] >= start:
    				accum = pos - table[i]
    				start = table[i] + 1
    			else:
    				accum += 1
    			table[i] = pos
    	return max(currMax, accum)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar  9 11:20:30 2019

@author: danhi
"""

'''
This work was from a DataQuest tutorial on pandas concatenation
https://www.dataquest.io/blog/pandas-concatenation-tutorial/
Emphasis wasn't placed on organizing the work below before checking into git; just documenting.

Notes from end of tutorial:

pd.concat() function: the most multi-purpose and can be used to combine multiple DataFrames along either axis.
DataFrame.append() method: a quick way to add rows to your DataFrame, but not applicable for adding columns.
pd.merge() function: great for joining two DataFrames together when we have one column (key) containing common values.
DataFrame.join() method: a quicker way to join two DataFrames, but works only off index labels rather than columns.

se axis=0 to apply a method down each column, or to the row labels (the index).
Use axis=1 to apply a method across each row, or to the column labels.

'''

import pandas as pd
import matplotlib.pyplot as plt

na = pd.read_csv('./north_america_2000_2010.csv', index_col='Country')
sa = pd.read_csv('./south_america_2000_2010.csv', index_col=0)

#put the two dataframes together so we can view plot at once:
a = pd.concat([na,sa], axis=0, join='outer', ignore_index=False)

# now let's pull in newer data from more recent years
adf = [a]

for year in range(2011,2016):
    filename = "./americas_{}.csv".format(year)
    df = pd.read_csv(filename, index_col=0)
    adf.append(df)

# update americas dataframe to include most recent years
a = pd.concat(adf, axis=1, sort=False)
a.index.names = ['Country']
print("we have americas \n\n",a)

# plot the americas
#a.transpose().plot(title="avg labor/year")

#  add in rest of world

asia = pd.read_csv('./asia_2000_2015.csv', index_col=0)
#print(asia)
#asia.transpose().plot(title="asia labor/year")
#plt.show()

europe = pd.read_csv('europe_2000_2015.csv', index_col='Country')
#print(europe)
#europe.transpose().plot()

sp = pd.read_csv('./south_pacific_2000_2015.csv', index_col=0)
#sp.transpose().plot()

world = a.append([asia, europe,sp])
world.index

#world.transpose().plot()

#world.transpose().plot(figsize=(15,10), colormap='rainbow', title='Average Labor Hours Per Year')
#plt.legend(loc='right', bbox_to_anchor=(1.3,0.5))
#plt.show()

historical = pd.read_csv('./historical.csv',index_col=0)
print(historical.head())

#now merge our world and historical into whm (m=merge)
whm = pd.merge(historical,world,left_index=True, right_index=True, how='right')

#try another method of joining into whj (j=join)
whj = historical.join(world,how='right')

whj.sort_index(inplace=True)

whj.transpose().plot(figsize=(15,10), colormap='rainbow', title='Average Labor Hours Per Year')
plt.legend(loc='right', bbox_to_anchor=(1.3,0.5))
plt.show()


import uuid
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.validators import ArrayMinLengthValidator

# Create your models here.
class Contact(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.TextField()
    numbers = ArrayField(
        models.CharField(
            max_length=11
        ),
        blank=False,
        null=False,
        validators=[
            ArrayMinLengthValidator(1)
        ]
    )


'''
#1: Verify the Continuity of a Function at a Point
Your challenge here is to write a program that will (1) accept a single variable function and a value of that variable as inputs and (2) check
whether the input function is continuous at the point where the variable
assumes the value input.
'''

from sympy import Derivative, Limit, Symbol, S, sympify, solve

def check_continuity(f, var, point):
	f = sympify(f)
	lp = Limit(f, var, point, dir='+').doit()
	ln = Limit(f, var, point, dir='-').doit()
	if lp == ln:
		print("{0} is continuous at {1}".format(f, point))
	else:
		print("{0} is discontinuous at {1}".format(f, point))

f = input('Enter a function in one variable: ')
var = input('Enter the variable to differentiate with respect to: ')
point = float(input('Enter the point to check continuity at: '))

check_continuity(f, var, point)

07. Solving Calculus Problems/verify_continuity.py


import tkinter as tk
from tkinter import ttk

class App(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.count = 0
        self.button = tk.Button(self, text="Click me!", command=self.click)
        self.label = tk.Label(self, text="", width=20)

        self.label.pack(side="top", fill="both", expand=True)
        self.button.pack(side="bottom", padx=4, pady=4)
        self.python_image = tk.PhotoImage(file='lenna.png')
        ttk.Label(self, image=self.python_image).pack()
        self.refresh_clicks()

    def SetPixelText(self, colour, x, y):
        self.python_image.put(colour, (x, y))

    def SetPixel(self, r, g, b, x, y):
        mycolor = "#%02x%02x%02x" % (r, g, b)
        self.python_image.put(mycolor, (x, y))

    def click(self):
        self.count += 1
        self.refresh_clicks()

    def refresh_clicks(self):
        self.label.configure(text=f"Clicks: {self.count}")

apps = []
n = 3
for i in range(n):
    window = tk.Tk() if i == 0 else tk.Toplevel()

    app = App(window)
    app.pack(fill="both", expand=True)
    if i == 0:
        for j in range(100):
            app.SetPixel(255, 0, 0, 10+j, 10)
    if i == 1:
        for j in range(100):
            app.SetPixel(0, 255, 0, 10+j, 10)
    if i == 2:
        for j in range(100):
            app.SetPixel(0, 0, 255, 10+j, 10)
    apps.append(app)
tk.mainloop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 10:36:29 2019

@author: hao
"""
from dataDecode import dataDecode
import requests
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy import signal
import math
from numpy.fft import fft, fftshift

urlstart="http://xds.ym.edu.tw/01530055/191224b.153"
    #前面都是做例外處理，確認設備是否在線上或者，這裡是正式下載資料
r = requests.get(urlstart)
rawtxt=r.content #content:二進制

Data,sampling_rate=dataDecode.rawdataDecode(rawtxt)
data_sam = sampling_rate/2
duration=int(len(Data[0])/(data_sam))
Data_len=int(data_sam)*duration
Data_from=len(Data[0])-Data_len

vector=Data[0][Data_from:Data_from+Data_len]#-medfilt(np.array(Data[0][Data_from:Data_from+Data_len]),125)
#plt.plot(vector)
fc = 45
w = fc/(sampling_rate/4)
b, a = signal.butter(2, w)
vector_filt = signal.filtfilt(b, a, vector)
#plt.plot(medfilt(np.array(Data[0][Data_from:Data_from+Data_len]),125))
col = {"HR" : vector_filt}
#col2 = {"HR" : vector}
data = pd.DataFrame(col)
#plt.plot(vector_filt)
#data2 = pd.DataFrame(col2)
xs = [i for i in range(Data_len)]
x1 = np.linspace(0, duration, len(xs))  #x軸，將point轉換成time
x_time = []     #存入x_time這個list
for x in x1:
    x_time.append(x)

hrw = 0.3 #One-sided window size, as proportion of the sampling frequency
fs = sampling_rate/2 #The example dataset was recorded at 100Hz
#fs = sampling_rate/2
mov_avg = data['HR'].rolling(int(hrw*fs)).mean()
#Calculate moving average
#Impute where moving average function returns NaN, which is the beginning of the signal where x hrw
avg_hr = (np.mean(data.HR))
mov_avg = [avg_hr if math.isnan(x) else x for x in mov_avg]
mov_avg = [x*1.13 for x in mov_avg]
#For now we raise the average by 4% to prevent the secondary heart contraction from interfering, in part 2 we will do this dynamically
data['HR_rollingmean'] = mov_avg

#Append the moving average to the dataframe
window = []
peaklist = []
listpos = 0 #We use a counter to move over the different data columns
for datapoint in data.HR:
    rollingmean = data.HR_rollingmean[listpos] #Get local mean
    if (datapoint < rollingmean) and (len(window) < 1): #If no detectable R-complex activity -> do nothing
        listpos += 1
    elif (datapoint > rollingmean): #If signal comes above local mean, mark ROI
        window.append(datapoint)
        listpos += 1
    else: #If signal drops below local mean -> determine highest point
        #maximum = max(window)
        beatposition = listpos - len(window) + (window.index(max(window))) #Notate the position of the point on the X-axis
        peaklist.append(beatposition) #Add detected peak to list
        window = [] #Clear marked ROI
        listpos += 1
ybeat = [data.HR[x] for x in peaklist] #Get the y-value of all peaks for plotting purposes
peaklist_time = [x_time[j] for j in peaklist]

px = []
py = []
qx = []
qy = []
sx = []
sy = []
tx = []
ty = []

prx = []
qrsx = []
qtx = []

thershold = [30, 80, 120]

for index3 in peaklist:

    ##------peak------##
    # P-wave
    if index3 < thershold[1]:
        p_list = vector[0:(index3 - thershold[0])]
        p_x = max(p_list)
        p_index = p_list.index(max(p_list))
        p_y = 0 + p_index

    else:
        p_list = vector[(index3 - thershold[1]):(index3 - thershold[0])]
        p_y = max(p_list)
        p_index = p_list.index(max(p_list))
        p_x = index3 - thershold[1] + p_index
    px.append(p_x)
    py.append(p_y)

    # Q-wave
    q_list = vector[(index3 - thershold[0]):index3]
    q_y = min(q_list)
    q_index = q_list.index(min(q_list))
    q_x = index3 - thershold[0] + q_index
    qx.append(q_x)
    qy.append(q_y)

    # S-wavw
    s_list = vector[index3:(index3 + thershold[0])]
    s_y = min(s_list)
    s_index = s_list.index(min(s_list))
    s_x = index3 + s_index
    sx.append(s_x)
    sy.append(s_y)

    # T-wave
    t_list = vector[(index3 + thershold[0]):(index3 + thershold[2])]
    t_y = max(t_list)
    t_index = t_list.index(max(t_list))
    t_x = index3 + t_index + thershold[0]
    tx.append(t_x)
    ty.append(t_y)
#
#    ##------interval------##
#    # P-R interval
#    pr_time = ((q_x - p_x)/sampling_rate)*1000
#    prx.append(pr_time)
#
#    # QRS complex
#    qrs_time = ((s_x - q_x)/sampling_rate)*1000
#    qrsx.append(qrs_time)
#
#    # Q-T interval
#    qt_time = ((t_x - q_x)/sampling_rate)*1000
#    qtx.append(qt_time)
#
#
#
px_time = [x_time[a] for a in px]
qx_time = [x_time[b] for b in qx]
sx_time = [x_time[c] for c in sx]
tx_time = [x_time[d] for d in tx]

ticks_size = 14
label_size = 18

plt.figure(1)
plt.title("Detected peaks in signal", fontsize = 20)
plt.xticks(fontsize = ticks_size)
plt.yticks(fontsize = ticks_size)
plt.xlabel('Time (s)', fontsize = label_size)
plt.ylabel('Amplitude (mV)', fontsize = label_size)
#plt.plot(x_time, data2.HR)
plt.plot(x_time, data.HR) #Plot semi-transparent HR
plt.scatter(peaklist_time, ybeat, c='red') #Plot detected peaks
#plt.scatter(px_time, py, c='blue')
#plt.scatter(qx_time, qy, c='red')
#plt.scatter(sx_time, sy, c='red')
#plt.scatter(tx_time, ty, c='y')
plt.show()
#%%
'''----------------
Interval extraction
-------------------'''

#P-R interval

p0 = []

#for index4 in px:
#    pr_list = vector[(index4 - 40):index4]
#    p_0 = (statistics.median(pr_list))
#    for index5 in (pr_list):
#        if (index5 - p_0) <= 0:
#            p0.append(pr_list.index(index5))
#    prxx = p0[-1]; pryy = (vector[prx])

'''--------------
Cut each cycle
-----------------'''

#------------cut R peak------------#
plt.figure(2)
sub = 1
sub2 = 0
epoch = 150

for index in peaklist:

    #add subplot
    column = math.ceil(len(peaklist)/6)
    plt.subplot(6, column, sub + sub2)  #set row & column

    #cut R peak，計算切割區間(以R peak為中心的300ms)
    cut1 = (x_time[index] - (epoch/1000))*sampling_rate
    cut2 = (x_time[index] + (epoch/1000))*sampling_rate
    y = []
    for k in range(len(vector[int(cut1):int(cut2)])):
        k = (k/sampling_rate)
        y.append(k)

    plt.plot(y, vector[int(cut1):int(cut2)])
#    plt.xticks([])
#    plt.yticks([])

    sub2 = sub2 + 1     #畫完一張圖，新增一個subplot
#%%
#plt.xlabel('Time (ms)', fontsize = label_size)
#plt.ylabel('Amplitude (mV)', fontsize = label_size)

##-------------filter------------##
#fc = 40
#w = fc/(samplingrate/2)
#b, a = signal.butter(5, w)
#y = signal.filtfilt(b, a, vector)
#
#vector2 = [a for a in vector_filt]
#plt.figure(3)
#plt.plot(x_time, vector, 'b', alpha=0.75)
#plt.plot(x_time, vector2, 'k')
#plt.legend(('noisy signal','filtfilt'), loc='best')
##plt.grid(True)
#plt.show()

##--time domain--##

plt.figure(4)

peak_diff = [peaklist[i+1]-peaklist[i] for i in range(len(peaklist)-1)]
RR = [(i/sampling_rate)*1000 for i in peak_diff]
RR_sample = 4
time_new = np.arange(0,duration,1/RR_sample)
RR_interval = signal.resample(RR,len(time_new))
plt.plot(time_new, RR_interval,'o-',color = 'g')
Mean_RR = np.mean(RR_interval)
SD_RR = np.std(RR_interval)
RMSSD = np.sqrt(np.mean(np.array(SD_RR)**2))

plt.title("R-R interval", fontsize = 20)
plt.xticks(fontsize = ticks_size)
plt.yticks(fontsize = ticks_size)
plt.xlabel('Time (s)', fontsize = label_size)
plt.ylabel('Interval (ms)', fontsize = label_size)

##--frequency domain--##
#%%
plt.figure(5)

RR_frq = fft(RR_interval)      #快速傅立葉變換
RR_real = RR_frq.real    # 獲取實數部分
RR_conj = RR_frq.imag    # 獲取虛數部分
RR_time = len(time_new)
power_RR = abs(np.multiply(RR_frq,RR_conj/RR_time))
fsb = RR_sample/RR_time
f = fsb*time_new[0:round(RR_time/2)]
#%%
def band(low,high,x):
    output1 = []
    for i in range(len(x)):
        if x[i] <= high and low <= x[i]:
            output1.append(i)
    return output1
vl = band(0,0.04,f)
lf = band(0.04,0.15,f)
hf = band(0.15,0.4,f)
LF = sum(power_RR[lf])*fsb
HF = sum(power_RR[hf])*fsb
VLF = sum(power_RR[vl])*fsb
TP = LF+HF+VLF
LHratio=LF/HF

#plt.plot(f[findex],power_RR[findex])
plt.plot(f[hf],power_RR[hf],label='HF')
plt.plot(f[lf],power_RR[lf],label="LF")
plt.legend()
plt.title('Power spectral density')
plt.xlabel('Frequency (Hz)')
#    testData=pd.DataFrame(vector_filt[int(cut1):int(cut2)])


import re

class champ1() :
    def __init__(self,name,ad,ap,armor,mg) :
        self.name = name
        self.AD = ad
        self.AP = ap
        self.Armor = armor
        self.magicR = mg
    def get_info(self) :
        print('Name : ',self.name)
        print('Attack Damge : ',self.AD)
        print('Abilty power : ',self.AP)
        print('Armor : ',self.Armor)
        print('magicR : ',self.magicR)

c = open('TEST.TXT', 'r+')

champ = []

for index in range(10) :
    read_champ = c.readline()
    champ.append(read_champ)
    champ[index] = champ[index][:-1]

c.close()

f = open('stats.txt', 'r+')

chaplistloop = []

for stats in range(3) :
    read_f = f.readline()
    statlist = read_f.split()
    chaplistloop.append(champ1(champ[stats],statlist[0],statlist[1],statlist[2],statlist[3]))

print(chaplistloop[0].name)
f.close()


'''
# 그룹 단어 체커
그룹 단어란 단어에 존재하는 모든 문자에 대해서, 각 문자가 연속해서 나타나는 경우만을 말한다.
예를 들면, ccazzzzbb는 c, a, z, b가 모두 연속해서 나타나고, kin도 k, i, n이 연속해서 나타나기 때문에 그룹 단어이지만,
aabbbccb는 b가 떨어져서 나타나기 때문에 그룹 단어가 아니다.

단어 N개를 입력으로 받아 그룹 단어의 개수를 출력하는 프로그램을 작성하시오.

[입력]
첫째 줄에 단어의 개수 N이 들어온다. N은 100보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 단어가 들어온다.
단어는 알파벳 소문자로만 되어있고 중복되지 않으며, 길이는 최대 100이다.

[출력]
첫째 줄에 그룹 단어의 개수를 출력한다.

[예제 입력]
3
happy
new
year

[예제 출력]
3

link: https://www.acmicpc.net/problem/1316
'''

n = int(input())
group_word_count = 0

for _ in range(n):
    word = input()
    prev_c = ""
    used_c = []
    for curr_c in word:
        if prev_c != curr_c:
            try:
                used_c.index(curr_c)
                break
            except ValueError:
                used_c.append(curr_c)
        prev_c = curr_c
    else:
        group_word_count += 1
print(group_word_count)


'''
Function:
    setup
Author:
    Charles
微信公众号:
    Charles的皮卡丘
GitHub:
    https://github.com/CharlesPikachu/codefree
'''
import codefree
from setuptools import setup, find_packages

'''readme'''
with open('README.md', 'r', encoding='utf-8') as f:
    long_description = f.read()

'''setup'''
setup(
    name=codefree.__title__,
    version=codefree.__version__,
    description=codefree.__description__,
    long_description=long_description,
    long_description_content_type='text/markdown',
    classifiers=[
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 3',
        'Intended Audience :: Developers',
        'Operating System :: OS Independent'
    ],
    author=codefree.__author__,
    url=codefree.__url__,
    author_email=codefree.__email__,
    license=codefree.__license__,
    include_package_data=True,
    install_requires=[lab.strip('\n') for lab in list(open('requirements.txt', 'r').readlines())],
    zip_safe=True,
    packages=find_packages()
)


#! python3
# PFbot.py -

#https://portal.pixelfederation.com/en/profile

import os, sys, logging, winsound, datetime, pickle, time, random
from selenium import webdriver
from random import randint

##################################################
##                 FUNCTIONS                    ##
##################################################
def playErrorSound():
    winsound.PlaySound('C:\\Windows\\media\\Windows Exclamation.wav', winsound.SND_FILENAME)
def playFinishSound():
    winsound.PlaySound('C:\\Windows\\media\\Windows Logon.wav', winsound.SND_FILENAME)

def getAccountLoginData(logPath, fileName):
    try:
        filePath = os.path.join(logPath, fileName)
        logging.debug('Funkcja: getAccountLoginData(%s)' %filePath)
        file = open(filePath)
        filedata = file.readlines()
        for i in range(len(filedata)-1):
            filedata[i] = filedata[i][:-1]
        return filedata
    except Exception as err:
        logging.error('An exception happened during loading account login data: ' + str(err))
        playErrorSound()
        return ['','']
    finally:
        file.close()

def setLoggingFileName(path, fileName):
    logging.basicConfig(filename=os.path.join(path, fileName), level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
    logging.disable(logging.DEBUG)

    #wypisywanie logow na konsole
    root = logging.getLogger()
    ch = logging.StreamHandler(sys.stdout)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    root.addHandler(ch)

# def randTime():
#     return (randint(4.0, 10.0))

filesPath = 'C:\\Users\\Barpel\\Documents\\PythonScripts\\PFbotAcc'
os.chdir(filesPath)
if filesPath != os.getcwd():
    sys.exit()
print('Current path: %s' %os.getcwd())

#account
profileURL = 'https://portal.pixelfederation.com/en/profile'
# accountLoginFileName = 'logpf.txt'
# myUserName, myUserPass = getAccountLoginData(filesPath, accountLoginFileName)

#logging
loggingFolderName = os.path.join(filesPath, 'logs')
os.makedirs(loggingFolderName, exist_ok=True)
setLoggingFileName(loggingFolderName, 'PFbotLog ' + str(datetime.datetime.now().strftime('%Y-%m-%d %H%M%S')) + '.txt')

#cookies
quoraCookiesFileName = 'QuoraCookiesForUpdates.pkl'
quoraCookiesPath = os.path.join(filesPath, quoraCookiesFileName)

logging.info('Opening browser...')
browser = webdriver.Chrome()
browser.get('https://www.google.pl/')
time.sleep(1)

#Loading cookies file
if os.path.isfile(quoraCookiesPath) == True:
    logging.info('Loading cookies file')
    try:
        for cookie in pickle.load(open(quoraCookiesPath, "rb")):
            print(cookie)
            browser.add_cookie(cookie)
    except Exception as err:
        logging.error('An exception happened during loading cookies: ' + str(err))
        playErrorSound()

try:
    logging.info('Opening site...')
    browser.get(profileURL)
except Exception as err:
    logging.error('An exception happened during login: ' + str(err))
    playErrorSound()
logging.info('Site opened...')

if browser.current_url != profileURL:
    logging.info('Log in...')
    try:
        print('Log in and press any key...')
        os.system("pause")

        #Zapisanie plikow cookie
        logging.info('Saving cookies')
        cookieFile = open(quoraCookiesPath, "wb")
        pickle.dump(browser.get_cookies() , cookieFile)
        cookieFile.close()

    except Exception as err:
        logging.error('An exception happened during login: ' + str(err))
        playErrorSound()
else:
    print("Already logged")

invitationCount = 0
while True:
    if invitationCount > 1000:
        playFinishSound()
        logging.info('--------- BREAK invitationCount: (%s)' %invitationCount)
        break

    logging.info('--------- InvitationCount: %s ---------' %invitationCount)
    try:
        logging.info('Opening site')
        browser.get(profileURL)
    except Exception as err:
        logging.error('An exception happened during opening site: ' + str(err))
        playErrorSound()

    if browser.current_url != profileURL:
        logging.error('User not logged: ')
        logging.error('An exception happened during opening site: ')
        playErrorSound()
        sys.exit()

    logging.info('Searching search button...')
    searchButton = browser.find_elements_by_class_name('fa-search')[0]
    searchButton.click()

    logging.info('Searching invite buttons')
    inviteButtons = browser.find_elements_by_class_name('player-list__item__button')
    logging.info('Found %s buttons' %len(inviteButtons))

    whileIteractionBreak = 18
    while inviteButtons == []:
        logging.info('Waiting for invite buttons - (%s)' %whileIteractionBreak)
        inviteButtons = browser.find_elements_by_class_name('player-list__item__button')
        logging.info('Found %s buttons' %len(inviteButtons))
        whileIteractionBreak = whileIteractionBreak - 1
        if whileIteractionBreak < 0:
            logging.info('--------- BREAK whileIteractionBreak: (%s)' %whileIteractionBreak)
            break
        if inviteButtons == []:
            sleepTime = 4 #randint(1.0, 4.0)
            logging.info('Sleep time: %s...' %sleepTime)
            time.sleep(sleepTime)

    random.shuffle(inviteButtons)
    i = 1
    for button in inviteButtons:
        button.click()
        invitationCount = invitationCount + 1
        sleepTime = randint(10.0, 50.0)/100
        logging.info('Invitation (%s) click sleep time: %s' %(i, sleepTime))
        i = i + 1
        time.sleep(sleepTime)

    sleepTime = randint(1.0, 9.0)
    logging.info('Sleep time: %s...' %sleepTime)
    time.sleep(sleepTime)

#os.system("pause")
#browser.close()

#sys.exit()