#!/home/fengxiang/anaconda3/envs/wrfout/bin/python
# -*- encoding: utf-8 -*-
'''
Description:
读取wrfout数据中的降水
将wrfout数据中的降水集合成一个文件
# TODO 将wrfout的格点数据插值为站点数据
-----------------------------------------
Time             :2021/09/09 10:53:08
Author           :Forxd
Version          :1.0
'''

# %%
import xarray as xr
import os
import xesmf as xe
import numpy as np
import wrf
import netCDF4 as nc
from baobao.interp import regrid_xesmf
# from baobao.coord_transform import xy_ll
# import wrf

# %%

# %%
def combine_rain(path):
    """
    由于wrfout数据的降水是累计降水，
    这里将它变为逐小时降水,同时进行合并
    又由于wrfout数据的坐标是x,y格点上的，
    通过wrf-python 库将其转为不规则的latlon格点坐标

    Args:
        path ([type]): 包含有wrfout数据的文件夹路径

    Returns:
        rain[DataArray] : 多时次聚合后的降水
    """

    fl_list = os.popen('ls {}/wrfout_d04*'.format(path))  # 打开一个管道
    fl_list = fl_list.read().split()
    dds_list = []
    r = 0
    for fl in fl_list:
        print(fl[-18:])
        ds = xr.open_dataset(fl)
        da = ds['RAINNC']+ds['RAINC']+ds['RAINSH']-r
        r = (ds['RAINNC']+ds['RAINC']+ds['RAINSH']).values.round(1)

        dda = da.squeeze()  # 该是几维的就是几维的
        dc = dda.rename({'XLAT':'lat', 'XLONG':'lon', 'XTIME':'time'})
        dds_list.append(dc)
    da_concate = xr.concat(dds_list, dim='time') # 原始的， 未经坐标变化的降水
    rain = da_concate.round(1)
    return rain

# %%
# path = '/mnt/zfm_18T/fengxiang/HeNan/Data/1912_900m/'
# rain = combine_rain(path)
# rain

# %%
# flnm_obs = '/mnt/zfm_18T/fengxiang/HeNan/Data/OBS/rain_station.nc'
# 特定区域范围内观测的站点数据
# da_obs = xr.open_dataarray(flnm_obs)
# wrf输出后转化的latlon格点数据

## 构建插值区域
# %%
# cc = da_obs.isel(time=0)
# sta = cc.id.values
# wrfin = nc.Dataset('/mnt/zfm_18T/fengxiang/HeNan/Data/1912_900m/wrfout_d04_2021-07-19_12:00:00')
# x, y = wrf.ll_to_xy(wrfin, cc.lat, cc.lon)
# rain_station = rain.sel(south_north=y, west_east=x)
# rain_station

# %%
# rain_station.drop_vars(['latlon_coord'])
# rain_station.to_netcdf('ttt.nc')

# lon = xr.DataArray(cc.lon.values, coords=[sta], dims=['sta'])
# lat = xr.DataArray(cc.lat.values, coords=[sta], dims=['sta'])
# ## 插值
# # rr = da_wrf.interp(lon=lon, lat=lat, method='nearest').round(1)
# rr = da_wrf.interp(lon=lon, lat=lat, method='linear').round(1)
# xr.DataArray.interp

# %%
def grid2station(flnm_obs, flnm_wrf, flnm_wrfout='/mnt/zfm_18T/fengxiang/HeNan/Data/1912_900m/wrfout_d04_2021-07-19_12:00:00'):
    """将格点数据插值为站点数据

    Args:
        flnm_obs ([type]): 多时次聚合的站点数据
        flnm_wrf ([type]): 多时次聚合的wrfout数据, 某个变量的，例如RAINNC
        flnm_wrfout ([type]): 原始的wrfout数据

    Returns:
        da_station: 从wrf数据插值出来的和观测经纬度一致的格点数据
    """

    print("插值数据到站点")
    # 特定区域范围内观测的站点数据
    da_obs = xr.open_dataarray(flnm_obs)
    # wrf输出后聚合到一起的多时间维度数据
    da_wrf = xr.open_dataarray(flnm_wrf)

    cc = da_obs.isel(time=0)
    # sta = cc.id.values
    wrfin = nc.Dataset(flnm_wrfout)
    x, y = wrf.ll_to_xy(wrfin, cc.lat, cc.lon)
    da_station = da_wrf.sel(south_north=y, west_east=x)
    da_station = da_station.drop_vars(['latlon_coord'])
    da_station = da_station.rename({'idx':'sta'})
    # print(da_station)

    return da_station

# %%
def regrid_latlon(flnm_rain, area):
    """
    将combine得到的数据()，
    插值到格距较粗的latlon格点上,
    也包含有投影转换的需求
    插值到latlon格点上
    将二维的latlon坐标水平插值到一维的latlon坐标上
    """
    print("插值数据到网格点")
    ds = xr.open_dataset(flnm_rain)
    ds_out = regrid_xesmf(ds, area, rd=1)
    return ds_out

def save_one(path_main = '/mnt/zfm_18T/fengxiang/HeNan/Data/1900_90m/'):
    """处理一个模式的数据

    Args:
        path_main (str, optional): [description]. Defaults to '/mnt/zfm_18T/fengxiang/HeNan/Data/1900_90m/'.
    """

    path_dic = {
        'path_main':path_main,  # 模式数据文件夹
        'path_wrfout':'/mnt/zfm_18T/fengxiang/HeNan/Data/1900_90m/wrfout_d04_2021-07-19_00:00:00', # 原始的一个wrfout数据，获得投影需要
        'path_rain_wrf_grid':path_main+'rain.nc', # 原始降水数据存储路径+文件名
        'path_rain_wrf_latlon':path_main+'rain_latlon.nc',  # 插值到latlon之后的文件名
        'path_rain_wrf_station':path_main+'rain_station.nc',  # 插值到站点之后的文件名
        'path_rain_obs_station':'/mnt/zfm_18T/fengxiang/HeNan/Data/OBS/rain_station.nc', # 站点降水
    }
    area = {
        'lon1':110.5,
        'lon2':116,
        'lat1':32,
        'lat2':36.5,
        'interval':0.125,
    }

    ## 合并数据
    da = combine_rain(path_main)
    da.to_netcdf(path_dic['path_rain_wrf_grid'])

    ## 降低分辨率和转换投影
    # regrid_rain_model(path_dic, area)
    da1 = regrid_latlon(path_dic['path_rain_wrf_grid'], area)
    da1.to_netcdf(path_dic['path_rain_wrf_latlon'])

    ## 插值到站点
    da2 = grid2station(path_dic['path_rain_obs_station'], path_dic['path_rain_wrf_grid'],path_dic['path_wrfout'])
    da2.to_netcdf(path_dic['path_rain_wrf_station'])
    pass

def dual():
    """处理多个模式的数据
    """
    pass
    model_list = ['1900_90m', '1900_900m','1912_900m', '1912_90m',]
    for model in model_list:
        path_main = '/mnt/zfm_18T/fengxiang/HeNan/Data/'+model+'/'
        save_one(path_main)

if __name__ == '__main__':

    pass
    # main()
    # save_one()
    dual()


from django.conf import settings
from django.test import TestCase

# Local imports
from .models import Project, Language
from .templatetags.custom_filters import getsubdivisions, getrange, stripmarkup, getlanguages

class CustomTemplateFilterTests(TestCase):
    def test_stripmarkup(self):
        HTML = '
This is my github, go on and follow me.'
        STRIPPED_TEXT = 'This is my github, go on and follow me.'
        self.assertEqual(stripmarkup(HTML), STRIPPED_TEXT)

    def test_getsubdivisions(self):
        self.assertEqual(getsubdivisions(range(1, 8), 3), [[1, 2, 3], [4, 5, 6], [7]])
        self.assertEqual(getsubdivisions(range(1, 8), "random garbage value"), [[1, 2, 3], [4, 5, 6], [7]])
        with self.assertRaises(ValueError):
            getsubdivisions(2134, "bullshit value")

    def test_getrange(self):
        self.assertEqual(getrange(5), range(1, 6))
        with self.assertRaises(ValueError):
            getrange("crap")

    def test_getlanguages(self):
        lang1 = Language.objects.create(name='Java')
        lang2 = Language.objects.create(name='Python')
        lang3 = Language.objects.create(name='PHP')
        p = Project.objects.create(
            name='Coding Portfolio',
            description='Programming portfolio for lazy people like me',
        )
        p.languages.add(lang1, lang2)
        self.assertEqual(getlanguages(""), [lang.name for lang in p.languages.all()])


import logging
import re

ATGC = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
atgc = {'A': 1, 'T': 1, 'G': 0, 'C': 0}

def is_ambiguous(a1, a2):
    """if SNP is ambiguous or not"""
    if atgc[a1] == atgc[a2]:
        return True
    return False

def match_ref(a1, a2, ref, alt):
    """Match a1, a2 with ref and alt
    None: match, 1: swap, 2: flip, 3: flip&swap, 4: exclude
    """
    if a1 == ref and a2 == alt:
        return
    elif a1 == alt and a2 == ref:
        return 1
    else:
        ambiguous = is_ambiguous(a1, a2)
        if ambiguous:
            return 4
        else:
            a1_f, a2_f = [ATGC[i] for i in [a1, a2]]
            if a1_f == ref and a2_f == alt:
                return 2
            elif a1_f == alt and a2_f == ref:
                return 3
            else:
                return 4

def get_id(a1_a2, id_element, chr_, pos_, ref_, alt_):
    # first, try to use rs
    id_ = id_element.split(':')[0]
    if id_ in a1_a2:
        return id_
    # then, try chr:pos
    id_ = "{}:{}".format(chr_, pos_)
    if id_ in a1_a2:
        return id_
    # try chr:pos:ref:alt
    id_ = "{}:{}:{}:{}".format(chr_, pos_, ref_, alt_)
    if id_ in a1_a2:
        return id_
    # try chr:pos:alt:ref
    id_ = "{}:{}:{}:{}".format(chr_, pos_, alt_, ref_)
    if id_ in a1_a2:
        return id_
    return None

def pre_imputation_check(params, reference):
    """Given a plink bim file
    0. Remove SNPS with worldwide MAF < 0.02
    1. Remove SNPs can not be matched
    2. Flip SNPs that match after flip
    3. Swap SNPs that match after swap or flip&swap
    4. Update chromosomes and positions for these SNPs
    """
    prefix = params
    fn_new = prefix
    a1_a2 = {}
    for i in open(fn_new):
        items = i.split()
        # id: (ref, alt)
        # %CHROM:%POS:%REF:%FIRST_ALT
        a1_a2[items[1]] = (items[-2], items[-1])

    # files to update bim
    chr_path = prefix + '.chr'
    pos_path = prefix + '.pos'
    force_allele_path = prefix + '.force_allele'
    flip_path = prefix + '.flip'
    freq_path = prefix + '.freq'
    with open(chr_path, 'w') as chr_file, open(pos_path, 'w') as pos_file, open(force_allele_path, 'w') as force_allele_file, open(flip_path, 'w') as flip_file, open(freq_path, 'w') as freq_file:

        af_regex = re.compile(';AF=(0.\d+)')
        # write the files to be used
        in_ref = 0
        exclude = 0
        strand_flip = 0
        swap = 0
        flip_swap = 0
        unique_ids = set()
        for i in open(reference):
            items = i.split()
            str_maf = af_regex.findall(items[7])
            maf = float(str_maf[0]) if len(str_maf) > 0 else 0.0
            chr_, pos_, ref_, alt_ = items[0], items[1], items[3], items[4]
            # first, try to use rss
            id_ = get_id(a1_a2, items[2], chr_, pos_, ref_, alt_)

            if id_ is not None:
                a1, a2 = a1_a2[id_]
                matching = match_ref(a1, a2, ref_, alt_)
                in_ref += 1
                if matching == 4:
                    exclude += 1
                else:
                    if id_ in unique_ids:
                        continue
                    if maf > 0.02:
                        freq_file.write(id_ + "\n")
                    chr_file.write("{}\t{}\n".format(id_, chr_))
                    pos_file.write("{}\t{}\n".format(id_, pos_))
                    # set alt as A1, because recode vcf will code A1 as alt later
                    force_allele_file.write("{}\t{}\n".format(id_, alt_))
                    unique_ids.add(id_)
                    if matching == 2:
                        flip_file.write(id_ + "\n")
                        strand_flip += 1
                    elif matching == 1:
                        swap += 1
                    elif matching == 3:
                        flip_file.write(id_ + "\n")
                        flip_swap += 1

    logging.info("Exclude: {} Keep: {}".format(exclude, in_ref - exclude))
    logging.info("Total flip: {}.".format(strand_flip))
    logging.info("Total swap: {}.".format(swap))
    logging.info("Total flip&swap: {}.".format(flip_swap))
    return flip_path, force_allele_path, chr_path, pos_path

if __name__ == "__main__":
    logging.basicConfig(filename=snakemake.log[0], level=logging.DEBUG, format='%(levelname)s:%(asctime)s %(message)s')

    pre_imputation_check(snakemake.input[0], snakemake.params[0])


import pygame

pygame.init()

screen= pygame.display.set_mode((800, 800))

cat = pygame.image.load('sprites\png\pear.png').convert()
catX=0
catY=100

clock = pygame.time.Clock()
running = True
while running:
    #fond en blanc
    screen.fill((255, 255, 255))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    #test touches
    pressed = pygame.key.get_pressed()
    pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]:
        catX -= 10
    if pressed[pygame.K_RIGHT]:
        catX += 10
    if pressed[pygame.K_UP]:
        catY -= 10
    if pressed[pygame.K_DOWN]:
        catY += 10
    screen.fill((255, 255, 255))
    screen.blit(cat, (catX, catY))
    pygame.display.update()
    #ralentir image
    clock.tick(50) #en fps

pygame.quit()


from functools import reduce
from collections import Iterable, Callable

class NotCallable(TypeError):
    pass

class absorb(object):
    def __init__(self, func, use_original = False):
        if not isinstance(func, Callable):
            raise NotCallable('absorb got a `{}` object.' \
                .format( type(func).__name__ ))
        self.func = func
        self.use_original = use_original

    def __call__(self, value, *args, **kwargs):
        try:
            return self.func(value, *args, **kwargs)

        except:
            return None \
                if not self.use_original \
                else value

class Composition(object):
    def __init__(self, *functions):
        functions = list(functions)
        for func in functions:
            if not isinstance(func, Callable):
                raise NotCallable( \
                    "Composition is containing a `{}` object." \
                    .format( type(func).__name__ ))

        self.functions = functions

    def __call__(self, value = None):
        if not self.functions:
            return value

        return reduce(lambda value, func: func(value), self.functions, value)


from PySide2.QtCore import Qt
import PySide2.QtWidgets as qtw
from PySide2.QtGui import QPixmap, QImage
from functools import partial
from base_area import MainWindow
from my_widgets import MultiQuestion, SingleQuestion

def _exit_on_esc(e):
    if e.key() == Qt.Key_Escape:
        qtw.QApplication.instance().quit()

if __name__ == '__main__':
    # main window (fullscreen)
    app = qtw.QApplication([])

    pic = QImage('dv5_1.png').scaledToHeight(1200, Qt.SmoothTransformation)
    pic_inst = qtw.QLabel()
    # pic_inst.setScaledContents(True)
    pic_inst.setAlignment(Qt.AlignCenter)
    pic_inst.setPixmap(QPixmap.fromImage(pic))
    pic_inst.setStyleSheet('border:2px solid rgb(0, 0, 0);border-radius:20px;')

    pic2 = qtw.QLabel()
    pic2.setPixmap(QPixmap.fromImage(pic))
    pic3 = qtw.QLabel()
    pic3.setPixmap(QPixmap.fromImage(pic))
    xxx = qtw.QWidget()
    #t0 = qtw.QVBoxLayout()
    t0 = qtw.QGridLayout()
    t0.addWidget(pic_inst, 0, 0, 1, 1, Qt.AlignCenter)
    t0.addWidget(pic2, 1, 0, 1, 1, Qt.AlignLeft)
    t0.addWidget(pic3, 2, 0, 1, 1, Qt.AlignCenter)
    xxx.setLayout(t0)
    header = ["1\nCompletely\ninappropriate", "2", "3", "4", "5", "6", "7\nCompletely\nappropriate"]
    questions = ["How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 """How likely is it that this person committed a premeditated crime? Here's even more text to see how things wrap...

                 Newlines and all.""",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that <b>this person</b> committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?",
                 "How likely is it that this person committed a premeditated crime?",
                 "How likely is it that this person committed an impulsive crime?"]
    multi_q = MultiQuestion(header, questions)

    q1 = SingleQuestion(header, 'What is your name?')
    q2 = SingleQuestion(header, 'What is your quest?')
    single_q = qtw.QWidget()
    layout = qtw.QVBoxLayout()
    layout.addWidget(q1)
    layout.addWidget(q2)
    single_q.setLayout(layout)
    tmp2 = qtw.QLabel('BAR')
    tmp2.setAlignment(Qt.AlignRight | Qt.AlignBottom)
    stack = [[single_q, multi_q, xxx], pic_inst, tmp2]

    window = MainWindow(stack)

    app.exec_()


from numpy import  array  # to create 4x4 matrix for gameboard
from square import Square # to create objects for each square on gameboard
from random import choice # for choosing a random postoin,values for inserting new value  into gameboard
import pygame

pygame.init()

class GameBoard:
    Direction={'up':(0,-2),'down':(0,2),'left':(-2,0),'right':(2,0)}
    font = pygame.font.SysFont('Comicsansms',20)
    font_h = pygame.font.SysFont('comicsansms', 25)
    highScore = 0
    """It is used to represent the gameboard
       class variable:
           Direction which is used to represnt some parameters based on direction in modify() function
       data members:
           board : stores all the square objects in 4x4 matrix format
           flag  : modification is done on board or not (True : done,False : not done)
           max   : stores the max value on board
           won   : Game Own or not
           gameOver : GameOver or not
    """
    def __init__(self,Display):
        """ Requires a Display to show the square on gameBoard
            default value
            board = with 16 square objects with 0 as value and i,j values as position
            flag  = True
            max   = 2
            won   = False
            gameOver = False
            calling insert() function
        """
        Square.Display=Display
        list=[Square((i,j)) for j in range(72,470,102) for i in range(2,400,102)]
        self.board=array(list).reshape((4,4))
        self.flag=True
        self.score = 0
        self.max=2
        self.won=False
        self.gameOver=False
        Square.Display.fill((255,255,255))
        pygame.draw.rect(Display,[0,0,255],(5,5,400,65))
        pygame.draw.rect(Square.Display,[255,255,0],(7,7,396,61))
        Score_h = GameBoard.font_h.render(' YOUR SCORE         HIGH SCORE', True, (255,0,0))
        Square.Display.blit(Score_h,(5,5))
        Score = GameBoard.font.render(str(self.score), True, (0,0,255))
        Square.Display.blit(Score,(20,40))
        Score = GameBoard.font.render(str(GameBoard.highScore), True, (0,0,255))
        Square.Display.blit(Score,(240,40))
        self.insert()

    def array(self):
        """  Generating an 4x4 matrix only with values on the gameboard to store """
        a=[self.board[i,j].value for i in range(0,4) for j in range(0,4)]+[0,self.max,self.score,GameBoard.highScore]
        return array(a).reshape((5,4))

    def restore(self,a):
        """ Regenerating the gameboard by taking values that are stored """
        GameBoard.highScore = a[4,3]
        self.score = a[4,2]
        self.max = a[4,1]
        if a.all()==None:
            self.score = 0
            self.max = 2
            return
        if self.max >= 2048:
            self.won = None
        for i in range(4):
            for j in range(4):
                self.board[i,j].value=a[i,j]

    def display(self):
        """ this is used to display the gameboard """
        if self.score !=0 :
            pygame.draw.rect(Square.Display,[255,255,0],(7,40,198,28))
            Score = GameBoard.font.render(str(self.score), True, (0,0,255))
            Square.Display.blit(Score,(20,40))
        pygame.draw.rect(Square.Display,[255,255,255],(0,80,410,410))
        for i in range(4):
            for j in range(4):
                self.board[i,j].update(self.board[i,j].value)

    def modify(self,event):
        """ This used to rotate the gameboard virtually
            so that we can use same function for all inputs with small modification on gameboard
            rules followed for player inputs:
                 Up    : No change
                 Down  : Flip the rows
                 Left  : Transpose then Flip the coloums
                 Right : Flip the rows then Transpose

               After complicaton of updating the gameboard again
                 Up    : No change
                 Down  : Flip the rows
                 Left  : Flip the coloumns then Transpose
                 Right : Transpose then Flip the coloumns
        """
        self.flag=False
        if event==pygame.K_DOWN:
            self.board[:,:]=self.board[::-1,:]
            self.update('down')
            self.board[:,:]=self.board[::-1,:]
        elif event==pygame.K_LEFT:
            self.board[:,:]=self.board.T[:,::-1]
            self.update('left')
            self.board[:,:]=self.board[:,::-1].T
        elif event==pygame.K_RIGHT:
            self.board[:,:]=self.board.T[::-1,:]
            self.update('right')
            self.board[:,:]=self.board[::-1,:].T
        elif event==pygame.K_UP:
            self.update('up')
        if self.flag:
            self.insert()

    def motion(self,direction,List):
        """ while modifying to give motion animation to the squares on board"""
        i,j = GameBoard.Direction[direction]
        X,Y = 0,0
        for m in range(0,51):
            for n in List:
                n.moveby(i,j,X,Y)
            X += i
            Y += j

    def shift(self,direction):
        """ While modifying to remove the blank spaces inbetween squares based on players input"""
        i=0
        while i<3:
            l=list()
            for j in range(4):
                if self.board[i,j].value==0:
                    l.extend(list(filter(lambda x:x.value!=0,list(self.board[i+1:,j]))))
            s = len(l)
            self.score += s
            if s==0:
                i+=1
                continue
            else:
                self.flag=True
            self.motion(direction,l)
            for j in range(4):
                if self.board[i,j].value==0:
                    for k in range(i+1,4):
                        self.board[k-1,j].update(self.board[k,j].value)
                    self.board[3,j].update()

    def update(self,direction):
        """ Update is used to initate modification of squared
            1. shifting the values will take place to remove middle spaces inbetween squares
            2. merging will takeplace next and animation is give to it by using motion function
        """
        self.shift(direction)
        i=0
        while i<3:
            l=list()
            for j in range(4):
                if self.board[i,j].value==self.board[i+1,j] and self.board[i,j].value!=0:
                    l+=list(list(self.board[i+1:,j]))
            self.motion(direction,l)
            for j in range(4):
                if self.board[i,j].value==self.board[i+1,j].value and self.board[i,j].value!=0:
                    self.flag=True
                    self.board[i,j].update(self.board[i,j].value*2)
                    self.score += self.board[i,j].value
                    for k in range(i+2,4):
                        self.board[k-1,j].update(self.board[k,j].value)
                    self.board[3,j].update()
            i+=1

    def check(self):
        """ To check whether GameOver or not by checking any two square are adjancent and same """
        for i in range(3):
            for j in range(3):
                if self.board[i,j].value==self.board[i+1,j].value or self.board[i,j].value==self.board[i,j+1].value:
                    return
            if self.board[i,3].value == self.board[i+1,3].value or self.board[3,i].value == self.board[3,i+1].value:
                return
        self.gameOver=True

    def insert(self):
        """ To insert a new value on the gameboard at random position with either 2 or 4 randomly
             it will update the score on screen also
        """
        pygame.draw.rect(Square.Display,[255,255,0],(7,40,198,28))
        Score = GameBoard.font.render(str(self.score), True, (0,0,255))
        Square.Display.blit(Score,(20,40))
        if self.score > GameBoard.highScore:
            GameBoard.highScore = self.score
            pygame.draw.rect(Square.Display,[255,255,0],(210,40,180,28))
            Score = GameBoard.font.render(str(GameBoard.highScore), True, (0,0,255))
            Square.Display.blit(Score,(240,40))
        l=list()
        for i in range(4):
            for j in range(4):
                if self.board[i,j].value==0:
                    l.append((i,j))
                elif self.max<self.board[i,j].value:
                    self.max=self.board[i,j].value
                    if self.max>=2048:
                        if self.won==None:
                            return
                        self.won=True
        if len(l)!=0 and self.flag:
            k=[2,2,2,2,2,2,2,2,4]
            self.board[choice(l)].update(choice(k))
        if len(l)==1:
            self.check()

# Below code is used to check Above class (testing Manually)
"""play=True
GameBoard=GameBoard(pygame.display.set_mode((410,410)))
while play:
    if GameBoard.gameOver:
        break
    if GameBoard.won==True:
        GameBoard.won=None
        break
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            play=False
            break
        elif event.type == pygame.KEYDOWN:
            GameBoard.modify(event.key)
pygame.quit()"""


import subprocess;
import json;
import urllib;
import urllib.request;
import sys;
import dbus;
from multiprocessing.pool import ThreadPool
from PyQt4 import QtGui, QtCore;

def main():
    #lyrics = getlyrics()
    app = QtGui.QApplication(sys.argv);
    q = Window();
    app.exec_();

def getlyrics():
    try:
        info = getdbusinfo();
        artist = info[0];
        track = info[1];
    except:
        print("Could not get song info.");
        return None;

    try:
        track = track.split("(")[0];
        track = track.split("[")[0];
        track = ''.join([i for i in track if (i.isalnum())]).lower();
        artist = ''.join([i for i in artist if (i.isalnum())]).lower();
        newurl = "http://www.azlyrics.com/lyrics/" + artist + "/" + track + ".html";
        lyrics = getLyricsFromPage(newurl);
    except:
        print("Could not get Lyrics for {0} by {1}.".format(track, artist));
        return None;

    return lyrics;
#def getinfo(): #depricated
#    proc = subprocess.Popen(["wmctrl -lp | grep \"$(pgrep spotify)\""], stdout=subprocess.PIPE, shell=True)
#    (out, err) = proc.communicate()
#    out = out.decode('utf-8');
#    out = out.strip();
#    out = out.split(" ");
#    out = out[8:len(out)];
#    out = " ".join(out);
#    out = out.split(" - ", 1);
#    return out;
def getdbusinfo():
    bus        = dbus.SessionBus()
    dbusobject = bus.get_object('org.mpris.MediaPlayer2.spotify','/org/mpris/MediaPlayer2')
    promanager = dbus.Interface(dbusobject, 'org.freedesktop.DBus.Properties')
    metadata   = promanager.Get('org.mpris.MediaPlayer2.Player', 'Metadata')

    artist = metadata["xesam:title"];
    track = metadata["xesam:artist"][0];
    return [track, artist]
def getHTML(url):
    request = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})
    html = urllib.request.urlopen(request).read();
    html = html.decode("utf-8");
    return html;
def getLyricsFromPage(url):
    html = getHTML(url);
    text = html.split("", 1)[1];
    text = text.split("", 1)[0];
    return text;

class Window(QtGui.QWidget):
    lbl_lyrics = None;
    lbl_title = None;
    lbl_artist = None;

    btn_exit = None;
    btn_maximize = None;

    gradtop = None;
    gradbot = None;

    scroll = None;
    repoint = None;
    timer = None;

    lastinfo = ["", ""];

    threadresult = None;

    def __init__(self):
        super(Window, self).__init__();
        #self.resizeEvent = onResize
        self.setStyleSheet("background-color: #0A050A;");
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint);
        self.spawn();
        self.resize(1000, 700);

        self.timer = QtCore.QTimer();
        self.timer.timeout.connect(self.tick)
        self.timer.start(500);

        self.setWindowOpacity(0.8);

        #self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True);
        #self.setAttribute(QtCore.Qt.WA_TranslucentBackground);

        self.show();

    def spawn(self):
        self.lbl_lyrics = QtGui.QLabel(self);
        self.lbl_lyrics.setFont(QtGui.QFont("Helvetica", 15));
        self.lbl_lyrics.setStyleSheet("color : #DDDDDD;");
        self.lbl_lyrics.setAlignment(QtCore.Qt.AlignCenter);

        self.lbl_title = QtGui.QLabel(self);
        self.lbl_title.setFont(QtGui.QFont("Helvetica", 30));
        self.lbl_title.setStyleSheet("color : #FF6633;");
        self.lbl_title.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignBottom);

        self.lbl_artist = QtGui.QLabel(self);
        self.lbl_artist.setFont(QtGui.QFont("Helvetica", 12));
        self.lbl_artist.setStyleSheet("color : #AAAAAA;");
        self.lbl_artist.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter);

        self.gradtop = QtGui.QLabel(self);
        self.gradtop.setStyleSheet("background: qlineargradient(x1: 0, y1: 1, x2: 0, y2: 0, stop: 0 rgba(0, 0, 0, 0%), stop: 1.0 #0A050A);");
        self.gradtop.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents);
        self.gradtop.raise_();

        self.gradbot = QtGui.QLabel(self);
        self.gradbot.setStyleSheet("background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 rgba(0, 0, 0, 0%), stop: 1.0 #0A050A);");
        self.gradbot.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents);
        self.gradbot.raise_();

        self.scroll = QtGui.QScrollArea(self);
        self.scroll.setWidget(self.lbl_lyrics)
        self.scroll.setFrameShape(QtGui.QFrame.NoFrame);
        self.scroll.horizontalScrollBar().hide();
        self.scroll.verticalScrollBar().hide();
        #self.scroll.setBackgroundRole(QtGui.QPalette);
        self.scroll.setWidgetResizable(True)

        self.btn_exit = QtGui.QPushButton("X", self);
        self.btn_exit.clicked.connect(QtCore.QCoreApplication.instance().quit);
        self.btn_maximize = QtGui.QPushButton("□", self);
        self.btn_maximize.clicked.connect(self.dynamicFullScreen);

    def dynamicFullScreen(self):
        if self.isFullScreen():
            self.showNormal()
            self.btn_maximize.setText("□");
        else:
            self.showFullScreen()
            self.btn_maximize.setText("_");

    def mousePressEvent(self, mousePressEvent):
        self.repoint = mousePressEvent.pos();

    def mouseMoveEvent(self, mouseMoveEvent):
        self.move(self.mapToGlobal(mouseMoveEvent.pos() - self.repoint));

    def resizeEvent(self, resizeEvent):
        self.scroll.setGeometry(0, 100, self.width(), self.height() - 100)
        self.lbl_title.setGeometry(50, 0, self.width() - 100, 60)
        self.lbl_artist.setGeometry(50, 60, self.width() - 100, 40)

        self.gradtop.setGeometry(0, 100, self.width(), 100);
        self.gradbot.setGeometry(0, self.height() - 100, self.width(), 100);
        self.gradtop.raise_();
        self.gradbot.raise_();

        self.btn_exit.setGeometry(self.width() - 50, 0, 50, 50)
        self.btn_maximize.setGeometry(self.width() - 100, 0, 50, 50)

    def tick(self):
        info = getdbusinfo();
        if (info[0] != self.lastinfo[0]) or (info[1] != self.lastinfo[1]):
            self.startThread();
            self.lbl_title.setText(info[1]);
            self.lbl_artist.setText(info[0].upper())
            self.lbl_lyrics.setText("Loading...");

        self.lastinfo = info;

        if self.threadresult.ready():
            lyrics = self.threadresult.get(1);
            if lyrics == "" or lyrics is None:
                lyrics = "Could not get lyrics ;_;"
            else:
                lyrics = ".\n\n\n\n\n" + lyrics + "\n\n\n\n\n.";
                lyrics = lyrics.replace("
", "").replace("
", "");
            self.lbl_lyrics.setText(lyrics);

    def startThread(self):
        pool = ThreadPool(processes=1)
        self.threadresult = pool.apply_async(getlyrics)

main();


"""Util for testing OCR engines with filters and cache their results"""
import os
from dataclasses import dataclass
from pickle import dump, load
from typing import List

# ???
# pylint: disable=no-name-in-module
from cv2 import imread, getTickCount, getTickFrequency
from src.filter import Filter
from src.dataset import Dataset
from src.reader import OCRReader

@dataclass
class TestSettings:
    """This class contains all the settings for a test."""

    reader: OCRReader
    filters: List[Filter]  # list of filters to apply to image in order

    def __str__(self) -> str:
        filters_string = ", ".join([str(filter) for filter in self.filters])
        return f"{self.reader}: {filters_string}"

@dataclass
class SingleTestResult(TestSettings):
    """This class contains the result of a single test."""

    time: float
    success: float
    result_text: str
    expected_text: str

@dataclass
class MultiTestResult:
    """This class contains the result of multiple tests."""

    results: List[SingleTestResult]
    test_settings: TestSettings

    total_time: float = 0
    total_success: float = 0

    average_time: float = 0
    average_success: float = 0

    def __post_init__(self):
        # calculate average time and success
        self.total_time = 0
        self.total_success = 0

        for result in self.results:
            self.total_time += result.time
            self.total_success += result.success

        self.average_time = self.total_time / len(self.results)
        self.average_success = self.total_success / len(self.results)

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

class TestCase:
    """This class contains a single test case."""

    __test__ = False

    def __init__(
        self, test_settings: TestSettings, image_path: str, expected_text: str
    ):
        self.test_settings = test_settings
        self.image_path = image_path
        self.expected_text = expected_text

    def test(self) -> SingleTestResult:
        """This method will test the OCR engine with filters applied."""

        # load image
        image = imread(self.image_path)

        # start measuring time in milliseconds
        time = getTickCount()

        # apply filters
        for current_filter in self.test_settings.filters:
            image = current_filter.filter(image)

        # read text
        text = self.test_settings.reader.read(image)

        # stop measuring time
        time = (getTickCount() - time) / getTickFrequency() * 1000

        # compare text
        success = self.get_success_rate(text, self.expected_text)

        # return result
        return SingleTestResult(
            self.test_settings.reader,
            self.test_settings.filters,
            time,
            success,
            text,
            self.expected_text,
        )

    def get_success_rate(self, text: list, expected: str) -> float:
        """
        Compares result to expected text. Resulting float number is
        a percentage of how many words both strings have in common.
        """

        # make a union of lowercased words and calculate how many of them are in the expected text

        # Dear pylint, I did consider it, but I don't want to use a set comprehension here.
        # pylint: disable=consider-using-set-comprehension
        words = set([word.lower() for line in text for word in line.split()])
        expected_words = set([word.lower() for word in expected.split()])

        return len(words.intersection(expected_words)) / len(expected_words)

    def __str__(self):
        return f"TestCase({self.test_settings}, {self.image_path})"

class TesterUtil:
    """
    Tester utility for OCR engines with filters and cache their results for better performance.
    """

    __test__ = False

    def __init__(self, cache_path: str, dataset: Dataset):
        self.cache_path = cache_path
        self.cache = {}
        self.load_cache()
        self.dataset = dataset

    def load_cache(self):
        """
        Loads the cache from the cache file.
        """

        # check if the cache file exists
        if not os.path.exists(self.cache_path):
            return

        # load the cache
        with open(self.cache_path, "rb") as file:
            try:
                self.cache = load(file)
            except ModuleNotFoundError:
                self.cache = {}

    def save_cache(self):
        """
        This method will save the cache to the cache file.
        """

        # save the cache
        with open(self.cache_path, "wb") as file:
            dump(self.cache, file)

    def test(
        self, test_settings: TestSettings, meme_count=10, ignore_cache=False
    ) -> SingleTestResult:
        """
        This method will test a specific test case and return the result.
        """

        test_settings_id = str(test_settings)

        # check if we already have a cached result
        if not ignore_cache and test_settings_id in self.cache:
            return self.cache[test_settings_id]

        # load first memeCount memes
        meme_dataset = self.dataset.get(meme_count)

        # create a list of test cases
        test_cases = [
            TestCase(test_settings, meme.image_path, meme.expected_text)
            for meme in meme_dataset
        ]

        # run all test cases
        results = [testCase.test() for testCase in test_cases]

        # cache the result
        self.cache[test_settings_id] = MultiTestResult(
            results, test_settings, test_settings.reader, test_settings.filters
        )

        self.save_cache()

        return self.cache[test_settings_id]


from sklearn.naive_bayes import GaussianNB
import mldatautil as ml
import sys

if len(sys.argv) != 3:
    print('usage: sript.py feature_flags combine_activities')
    quit()

feature_flags = sys.argv[1]
combine = sys.argv[2]

# get the data into numpy arrays
train_x, train_y, test_x, test_y = ml.gettraintestdata(feature_flags, combine)

model = GaussianNB()
model.fit(train_x, train_y)

predicted = model.predict(test_x)
correct = 0
tot = 0
for idx in range(test_y.shape[0]):
    if test_y[idx] == predicted[idx]:
        correct += 1

    tot += 1

test_acc = correct/tot

predicted = model.predict(train_x)
correct = 0
tot = 0
for idx in range(train_x.shape[0]):
    if train_y[idx] == predicted[idx]:
        correct += 1

    tot += 1

train_acc = correct/tot
ml.printresults("naive bayes", test_acc, train_acc)


from flask import Flask, render_template, request
import functions as funk
import joblib
import numpy as np
from sklearn.ensemble import RandomForestRegressor

model = joblib.load('store_rf_model.joblib')
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        # Get the data from the form
        input1 = request.form['date']
        input2 = request.form['season']
        input3 = request.form['event']
        input4 = request.form['tourists']
        # Do something with the data, like save it to a database

        day, month,year, day_of_the_week_num = funk.get_date(input1)
        season_autumn,season_spring,season_summer,season_winter = funk.get_season(input2)
        covid = funk.get_covid(year)
        event = funk.get_event(input3)
        tourists = float(input4)
        pred_var = np.array([day,month,covid,event,tourists,day_of_the_week_num,season_autumn,season_spring,season_summer,season_winter])
        pred_var = pred_var.reshape(1,-1)
        #print(pred_var)
        pred = model.predict(pred_var)
        #return day, month,year, day_of_the_week_num
        results = str(pred[0])
        return render_template('results.html',results=results)
        # Render the template with the input fields
    return render_template('index.html')

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


from PyQt4.QtGui import *
from i18n import _

class HistoryWidget(QTreeWidget):

    def __init__(self, parent=None):
        QTreeWidget.__init__(self, parent)
        self.setColumnCount(2)
        self.setHeaderLabels([_("Amount"), _("To / From")])
        self.setIndentation(0)

    def append(self, address, amount):
        item = QTreeWidgetItem([amount, address])
        self.insertTopLevelItem(0, item)


#!/usr/bin/python
import rospy
import baxter_interface
from baxter_pykdl import baxter_kinematics
import numpy as np
import numpy.linalg as npla
from math import sqrt
import threading
import pid_controllers
import tf.transformations
import tf
from sensor_msgs.msg import PointCloud

MAX_JOINT_VEL = 1.5 # Max commanded joint velocity
MAX_NS_JOINT_VEL = 0.5 # Max nullspace joint velocity

# Arm neutral configs
NEUTRAL = {'left':
        {'left_w0': 0.0,
         'left_w1': -0.55,
         'left_w2': 0.0,
         'left_e0': 0.75,
         'left_e1': 0.0,
         'left_s0': 1.26,
         'left_s1': 0.0},
         'right':
        {'right_w0': 0.0,
         'right_w1': -0.55,
         'right_w2': 0.0,
         'right_e0': 0.75,
         'right_e1': 0.0,
         'right_s0': 1.26,
         'right_s1': 0.0}}

class EndpointVelocityController():
    """Generates joint velocity commands to produce a specified endpoint velocity for one of
    Baxter's arms.

    Args:
    limb: 'left'|'right'
    """

    def __init__(self, limb):
        self._neutral_config = NEUTRAL[limb]
        self._kin = baxter_kinematics(limb)
        self._limb = baxter_interface.Limb(limb)

    def set_endpoint_velocity(self, velocity_cmd):
        """Sends joint velocity commands to produce the instantaneous endpoint velocity specified
        by velocity_cmd

        Args:
        velocity_cmd: (6,) ndarray - the desired endpoint velocity [x', y', z', r', p' y']
        """
        # Neutral position return velocity
        # Compute nullspace velocities
        velocity_dict = {joint: self._neutral_config[joint] - self._limb.joint_angle(joint) for joint in self._limb.joint_names()}

        #Clamp the nullspace velocity command so it's within limits for each joint
        vel_scale_factor = max([abs(velocity) for velocity in velocity_dict.values()]) / MAX_NS_JOINT_VEL
        if vel_scale_factor > 1:
            velocity_dict = {joint: velocity_dict[joint] / vel_scale_factor for joint in self._limb.joint_names()}

        # Project into the nullspace
        nullspace = null(np.array(self._kin.jacobian()))[1]
        velocity_dict = project_to_nullspace(nullspace, self._limb.joint_names(), velocity_dict)

        # End effector command velocity
        # Compute the joint velocity commands
        jacobian_pinv = np.array(self._kin.jacobian_pseudo_inverse())
        joint_velocity_command = jacobian_pinv.dot(velocity_cmd)
        command_velocity_dict = {joint: joint_velocity_command[i] for i, joint in enumerate(self._limb.joint_names())}

        #Clamp the EE velocity command so it's within limits for each joint
        ee_vel_scale_factor = max([abs(velocity) for velocity in command_velocity_dict.values()]) / MAX_JOINT_VEL
        if ee_vel_scale_factor > 1:
            command_velocity_dict = {joint: command_velocity_dict[joint] / ee_vel_scale_factor for joint in self._limb.joint_names()}

        # Command the velocities
        velocity_dict = {joint:command_velocity_dict[joint] + velocity_dict[joint] for joint in self._limb.joint_names()}
        self._limb.set_joint_velocities(velocity_dict)

    def set_neutral_config(self, neutral_config_dict):
        """Sets the arm's neutral configuration to something other than the default value.

        Args:
        neutral_config_dict: dict - {'left_s1':value, ..., 'left_w2':value}
        """
        self._neutral_config = neutral_config_dict

class ContinuousEndpointPoseController():
    """A closed loop endpoint pose controller which uses joint velocity commands to move the
    specified limb's endpoint to the desired pose.

    Args:
    limb: 'left'|'right'
    """

    def __init__(self, limb):
        self._limb = baxter_interface.Limb(limb)
        self._vel_controller = EndpointVelocityController(limb)
        self._run = True

        # Choose the endpoint's current pose as the starting setpoint
        self._orientation_setpoint = np.array(self._limb.endpoint_pose()['orientation'])
        self._position_setpoint = np.array(self._limb.endpoint_pose()['position'])

        # Create the controllers for each DoF of the endpoint velocity
        self._dof_controllers = {
                'x': pid_controllers.PidController(k_p=3.0).set_desired_value(self._position_setpoint[0]),
                'y': pid_controllers.PidController(k_p=3.0).set_desired_value(self._position_setpoint[1]),
                'z': pid_controllers.PidController(k_p=3.0).set_desired_value(self._position_setpoint[2]),
                'rpy': pid_controllers.OrientationPidController(k_p=1.0).set_desired_value(self._orientation_setpoint)
        }

        # Start the velocity control loop
        self.start()

    def stop(self):
        #Stop the controller
        self._run = False

    def start(self):
        #Start the controller
        self._run = True
        threading.Thread(target=self._run_controller).start()

    def _update_endpoint_velocity(self):
        # Measures the current endpoint pose error and commands a new set of joint velocities
        CONTROL_DOFS = ['x', 'y', 'z', 'rpy']
        IGNORE_DOFS = []#'roll', 'pitch', 'yaw']
        current_ee_vel = {dof: 0.0 for dof in CONTROL_DOFS}
        current_ee_pos = {dof: self._limb.endpoint_pose()['position'][i] for i, dof, in enumerate(CONTROL_DOFS[0:3])}
        current_ee_ori = self._limb.endpoint_pose()['orientation']
        #Seems like the quaternion is actually in the correct order?
        # current_ee_ori = np.concatenate((current_ee_ori[3:4], current_ee_ori[0:3]))

        velocity_cmd = [self._dof_controllers[dof].get_control_cmd(current_ee_pos[dof], current_ee_vel[dof]) for dof in CONTROL_DOFS[0:3]]
        ori_velocity_cmd = self._dof_controllers['rpy'].get_control_cmd(current_ee_ori, 0.0)
        velocity_cmd.extend(ori_velocity_cmd)
        self._vel_controller.set_endpoint_velocity(velocity_cmd)

    def _run_controller(self):
        rate = rospy.Rate(100)
        while (not rospy.is_shutdown()) and self._run:
            self._update_endpoint_velocity()
            rate.sleep()

    def update_position_setpoint(self, setpoint):
        """Sets the endpoint position setpoint to a new value. Right now orientation is not
        supported. The controller just maintains the endpoint orientation that it measured when
        it was initialized.

        Args:
        setpoint: (3,) ndarray - the desired endpoint position [x, y, z]
        """
        self._position_setpoint = setpoint
        for i, dof in enumerate(['x', 'y', 'z']):
            self._dof_controllers[dof].set_desired_value(setpoint[i])

def null(a, rtol=1e-5):
    """ Computes the nullspace of a

    Returns:
    rank: the rank of the matrix (# of dims with singular values > rtol)
    nullspace: basis vectors for the nullspace
    """
    u, s, v = npla.svd(a)
    rank = (s > rtol*s[0]).sum()
    return rank, v[rank:].T.copy()

def project_to_nullspace(nullspace, joint_order, joint_velocities):
    """Projects a dict of joint velocities into the nullspace of a manipulator. The resulting
    joint velocity dict will not produce any endpoint motion of the arm.

    Args:
    nullspace: basis vectors for the nullspace returned from null()
    joint_order: list - the order in which joints are represented in the Jacobian
        ['left_s1', ...,'left_w2']
    joint_velocities: dict - input joint velocities to project
    """
    # Make a vector of joint velocities
    velocities = np.array([joint_velocities[joint] for joint in joint_order])

    # Compute the projection onto each nullspace vector
    proj_velocities = np.zeros_like(velocities)
    for n in range(nullspace.shape[1]):
        proj_velocities += nullspace[:,n].dot(velocities) * nullspace[:,n]

    # Convert back to a velocities dict
    return {joint: proj_velocities[i] for i, joint in enumerate(joint_order)}

class MocapPointTracker:
    """Moves both of Baxter's arms to maintain a constant position relative to a single motion
    capture marker.

    Args:
    vel_controller_left/vel_controller_right: the ContinuousEndpointPoseControllers for each arm
    """
    def __init__(self, vel_controller_left, vel_controller_right):
        self._vel_controller_left = vel_controller_left
        self._vel_controller_right = vel_controller_right
        self._tf_listener = tf.TransformListener()
        self._position_offset_left = None
        self._position_offset_right = None

    def new_frame_callback(self, message):
        """Called for each new sensor_msgs/PointCloud message received from the mocap system

        Args:
        message: the PointCloud message object
        """
        try:
            message = self._tf_listener.transformPointCloud('/base', message)
            data = point_cloud_to_array(message)
            point = data[0,:,0]
            if not np.any(np.isnan(point)):
                # Initialize the position offset
                if self._position_offset_left is None:
                    self._position_offset_left = point - np.array(self._vel_controller_left._limb.endpoint_pose()['position'])
                    self._position_offset_right = point - np.array(self._vel_controller_right._limb.endpoint_pose()['position'])
                else:
                    self._vel_controller_left.update_position_setpoint(point - self._position_offset_left)
                    self._vel_controller_right.update_position_setpoint(point - self._position_offset_right)
        except tf.LookupException:
            print("Couldn't find the mocap transformation")

def point_cloud_to_array(message):
    # Converts a sensor_msgs/PointCloud to a (num_markers, 3, 1) ndarray
    num_points = len(message.points)
    data = np.empty((num_points, 3, 1))
    for i, point in enumerate(message.points):
        data[i,:,0] = [point.x, point.y, point.z]
    return data

def main():
    rospy.init_node('baxter_velocity_control')
    vel_controller_left = ContinuousEndpointPoseController('left')
    vel_controller_right = ContinuousEndpointPoseController('right')
    tracker = MocapPointTracker(vel_controller_left, vel_controller_right)
    sub = rospy.Subscriber('/mocap_point_cloud', PointCloud, tracker.new_frame_callback)
    rospy.spin()

if __name__ == "__main__":
    main()


# coding=utf8
"""
事故应急池计算
"""
import random
import json
import os

from conf.path import json_exam_path

with open(os.path.join(json_exam_path, "rainfalls.json"), "r", encoding="utf-8") as fp:
    rainfalls = json.load(fp)

# ***** V1: 收集系统范围内发生事故的物料量, m^3 ***** #
def setV1():
    # 铁路槽车容量, m3
    railway_tanker_capacity = [50, 60]
    # 汽车罐车, m3
    car_tanker_capacity = [5, 10, 15, 20, 25, 30]
    # 储罐容量, m3
    storage_tanker_capacity = [1, 3, 5, 10, 15, 20, 25, 30, 40, 50, 80, 100, 150]
    # 反应器或中间储罐, m3
    reactor_capacity = [1, 2, 3, 4, 5]
    types = range(0, 4)
    capacities = [railway_tanker_capacity, car_tanker_capacity, storage_tanker_capacity, reactor_capacity]
    type_index = random.choice(types)
    capacity = random.choice(capacities[type_index])
    # V1, m3
    V1 = capacity
    return [V1, type_index]

# ***** V2: 发生事故的储罐、装置或铁路、汽车装卸区的消防水量, m^3 ***** #
def setV2(V1):
    # 给水流量, L/s
    if V1 >= 50:
        flow_range = [200 + i * 10 for i in range(11)]
        area_range = [i * 1000 for i in range(20, 31)]
    elif V1 >= 20:
        flow_range = [100 + i * 10 for i in range(11)]
        area_range = [i * 1000 for i in range(15, 21)]
    else:
        flow_range = [60 + i * 10 for i in range(4)]
        area_range = [i * 1000 for i in range(10, 16)]
    # 厂区面积, m2
    area = random.choice(area_range)
    # 火灾延续时间, h
    duration_range = range(3, 6)
    # 流量, L/s
    flow = random.choice(flow_range)
    # t, h
    duration = random.choice(duration_range)
    # V2, m3
    V2 = flow * duration * 3600 / 1000
    return [round(V2, 2), flow, duration, area]

# ***** V3: 发生事故时可以转输到其他储存或处理设施的物料量, m^3 ***** #
def setV3(V1):
    # 这里只考虑围堰的情况, m3
    cofferdam = random.choice([True, False])
    if cofferdam:
        V3 = V1
    else:
        V3 = 0
    return [V3, cofferdam]

# ***** V4: 发生事故时仍必须进入该收集系统的生产废水量, m^3 ***** #
def setV4():
    # 这里假定发生事故时停止生产, m3
    V4 = 0
    return V4

# ***** V5: 发生事故时仍可能进入该收集系统的降雨量, m^3 ***** #
def setV5(area):
    # 降雨数据
    location = random.choice(rainfalls)
    city = location["location"]
    rainfall_steps = int((location["rainfall"][1] - location["rainfall"][0]) / 10)
    rainfall_range = [location["rainfall"][0] + i * 10 for i in range(rainfall_steps + 1)]
    days_steps = location["days"][1] - location["days"][0]
    days_range = [location["days"][0] + i for i in range(days_steps + 1)]
    # 年降雨量, mm
    rainfall = random.choice(rainfall_range)
    # 天数
    days = random.choice(days_range)
    # V5, m3
    V5 = 10 * (rainfall / days) * area / (10 ** 4)
    return [round(V5, 2), city, rainfall, days]

def setPoolQuestion(seed=None):
    """事故应急池计算"""
    # 设置随机数种子
    if seed:
        random.seed(seed)
    V1, type_index = setV1()
    V2, flow, duration, area = setV2(V1=V1)
    V3, cofferdam = setV3(V1=V1)
    V4 = setV4()
    V5, city, rainfall, days = setV5(area=area)
    V = round(V1 + V2 - V3 + V4 + V5, 2)
    question = f"现有位于{city}的某化工厂，厂房面积${area}m^3$，厂内储存有可燃液体，并运行着相关的生产工艺。\n某天，"
    if type_index == 0:
        question += f"该工厂的卸车区正在进行着装卸工作，一容积为${V1}m^3$的满载的槽车发生可燃液体泄露起火事故。"
    elif type_index == 1:
        question += f"该工厂的卸车区正在进行着装卸工作，一容积为${V1}m^3$的满载的罐车发生可燃液体泄露起火事故。"
    elif type_index == 2:
        question += f"厂内一容积为${V1}m^3$装有可燃液体的满载的储罐发生泄露起火事故。"
    else:
        question += f"该工厂生产车间一容积为${V1}m^3$的满载的可燃液体反应釜发生泄露起火事故。"
    question += f"\n该工厂立即启动应急预案，开展消防工作，并以${flow}L/s$的消防水流量进行灭火以及降温。\n${duration}h$后，火势彻底扑灭，消防给水停止。"
    question += f"\n灭火过程中，发生泄漏的罐体内物料已全部流出，但由于该工厂设有事故应急池，消防废水全部收集于应急池内，"
    if cofferdam:
        question += "并且发生泄漏事故的区域设有符合规范的围堰，泄露物无向外扩散的情况，"
    else:
        question += f"并且泄漏物也全部进入了应急池，"
    question += "该起事故未造成环境污染。"
    question += "\n假设本次事故发生后，该工厂立刻停止了生产工艺，停止产生生产废水。"
    question += "处理事故时，未有其他废水或者其他泄漏物进入事故应急池。"
    question += "事故结束后，事故应急池内废水也未外溢。"
    question += f"\n已知该工厂所在地区年降雨量为${rainfall}mm$，降雨天数为{days}天。"
    question += "\n试计算该工厂的事故应急池的容量最小可能是多少？\n（计算中间数据以及最终结果均保留小数点后两位，单位为$m^3$）"
    calculation_process = "解析：\n"
    calculation_process += f"（1）由于物料满载且全部泄露，则发生事故的物料量即发生泄露的罐体容积：\n$$\nV_1={V1}m^3\n$$\n"
    calculation_process += f"（2）然后确定消防水量：\n$$\nV_2={flow}\\times{duration}\\times3600/1000={V2}m^3\n$$\n"
    if cofferdam:
        calculation_process += f"（3）由于设置有围堰，泄漏物将全部截流于围堰内：\n$$\nV_3={V3}m^3\n$$\n"
    else:
        calculation_process += f"（3）由于泄漏物全部进入了应急池：\n$$\nV_3={V3}m^3\n$$\n"
    calculation_process += f"（4）并且事故发生后，该工厂停止了生产工艺，无生产废水产生：\n$$\nV_4={V4}m^3\n$$\n"
    calculation_process += f"（5）根据厂区面积以及该地区的降雨数据：\n$$\nV_5=(10\\times{rainfall}/{days})\\times{area}/10^4={V5}m^3\n$$\n"
    calculation_process += f"（6）综上，该工厂事故应急池最小容积为：\n$$\nV={V1}+{V2}-{V3}+{V4}+{V5}={V}m^3\n$$"
    return question, calculation_process, V


import contextlib
import platform
from copy import deepcopy
from pathlib import Path

import numpy as np
import pkg_resources as pkg
import torch
import math
import time

from matplotlib import pyplot as plt

from torch import nn

from utils import LOGGER

try:
    import thop  # for FLOPs computation
except ImportError:
    thop = None

class TryExcept(contextlib.ContextDecorator):
    # YOLOv5 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager
    def __init__(self, msg=''):
        self.msg = msg

    def __enter__(self):
        pass

    def __exit__(self, exc_type, value, traceback):
        if value:
            print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
        return True

def colorstr(*input):
    # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e.  colorstr('blue', 'hello world')
    *args, string = input if len(input) > 1 else ('blue', 'bold', input[0])  # color arguments, string
    colors = {
        'black': '\033[30m',  # basic colors
        'red': '\033[31m',
        'green': '\033[32m',
        'yellow': '\033[33m',
        'blue': '\033[34m',
        'magenta': '\033[35m',
        'cyan': '\033[36m',
        'white': '\033[37m',
        'bright_black': '\033[90m',  # bright colors
        'bright_red': '\033[91m',
        'bright_green': '\033[92m',
        'bright_yellow': '\033[93m',
        'bright_blue': '\033[94m',
        'bright_magenta': '\033[95m',
        'bright_cyan': '\033[96m',
        'bright_white': '\033[97m',
        'end': '\033[0m',  # misc
        'bold': '\033[1m',
        'underline': '\033[4m'}
    return ''.join(colors[x] for x in args) + f'{string}' + colors['end']

def check_anchor_order(m):
    # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
    a = m.anchors.prod(-1).mean(-1).view(-1)  # mean anchor area per output layer
    da = a[-1] - a[0]  # delta a
    ds = m.stride[-1] - m.stride[0]  # delta s
    if da and (da.sign() != ds.sign()):  # same order
        PREFIX = colorstr('AutoAnchor: ')
        LOGGER.info(f'{PREFIX}Reversing anchor order')
        m.anchors[:] = m.anchors.flip(0)

def make_divisible(x, divisor):
    # Returns nearest x divisible by divisor
    if isinstance(divisor, torch.Tensor):
        divisor = int(divisor.max())  # to int
    return math.ceil(x / divisor) * divisor

def time_sync():
    # PyTorch-accurate time
    if torch.cuda.is_available():
        torch.cuda.synchronize()
    return time.time()

def initialize_weights(model):
    for m in model.modules():
        t = type(m)
        if t is nn.Conv2d:
            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
        elif t is nn.BatchNorm2d:
            m.eps = 1e-3
            m.momentum = 0.03
        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
            m.inplace = True

def fuse_conv_and_bn(conv, bn):
    # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
    fusedconv = nn.Conv2d(conv.in_channels,
                          conv.out_channels,
                          kernel_size=conv.kernel_size,
                          stride=conv.stride,
                          padding=conv.padding,
                          dilation=conv.dilation,
                          groups=conv.groups,
                          bias=True).requires_grad_(False).to(conv.weight.device)

    # Prepare filters
    w_conv = conv.weight.clone().view(conv.out_channels, -1)
    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))

    # Prepare spatial bias
    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)

    return fusedconv

def model_info(model, verbose=False, imgsz=640):
    # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
    n_p = sum(x.numel() for x in model.parameters())  # number parameters
    n_g = sum(x.numel() for x in model.parameters() if x.requires_grad)  # number gradients
    if verbose:
        print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
        for i, (name, p) in enumerate(model.named_parameters()):
            name = name.replace('module_list.', '')
            print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
                  (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))

    try:  # FLOPs
        p = next(model.parameters())
        stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32  # max stride
        im = torch.empty((1, p.shape[1], stride, stride), device=p.device)  # input image in BCHW format
        flops = thop.profile(deepcopy(model), inputs=(im,), verbose=False)[0] / 1E9 * 2  # stride GFLOPs
        imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz]  # expand if int/float
        fs = f', {flops * imgsz[0] / stride * imgsz[1] / stride:.1f} GFLOPs'  # 640x640 GFLOPs
    except Exception:
        fs = ''

    name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model'
    LOGGER.info(f'{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}')

def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
    """
    x:              Features to be visualized
    module_type:    Module type
    stage:          Module stage within model
    n:              Maximum number of feature maps to plot
    save_dir:       Directory to save results
    """
    if 'Detect' not in module_type:
        batch, channels, height, width = x.shape  # batch, channels, height, width
        if height > 1 and width > 1:
            f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png"  # filename

            blocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channels
            n = min(n, channels)  # number of plots
            fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)  # 8 rows x n/8 cols
            ax = ax.ravel()
            plt.subplots_adjust(wspace=0.05, hspace=0.05)
            for i in range(n):
                ax[i].imshow(blocks[i].squeeze())  # cmap='gray'
                ax[i].axis('off')

            LOGGER.info(f'Saving {f}... ({n}/{channels})')
            plt.savefig(f, dpi=300, bbox_inches='tight')
            plt.close()
            np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save

def emojis(str=''):
    # Return platform-dependent emoji-safe version of string
    return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str

def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):
    # Check version vs. required version
    current, minimum = (pkg.parse_version(x) for x in (current, minimum))
    result = (current == minimum) if pinned else (current >= minimum)  # bool
    s = f'WARNING ⚠ {name}{minimum} is required by YOLOv5, but {name}{current} is currently installed'  # string
    if hard:
        assert result, emojis(s)  # assert min requirements met
    if verbose and not result:
        LOGGER.warning(s)
    return result


import requests
from flask import Flask, request, Response

app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

URL_HOST = "https://gitlab.com/api/v4/issues"
URL_PRIV = "private_token=pLEY6MtfGVF8FCx"

headers = {"private_token" : "pLEY6MtfGVF8FCx"}

@app.route('/webhook', methods=['POST'])
def respond():
    print(request.json);
    print('-------')
    r = requests.get(URL_HOST, headers=headers, params={'iid[]': '1'})
    print(r.json())
    return Response(status=200)


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

import theano
import numpy as np
from theano import tensor as T
from theano.compile.io import In
from collections import OrderedDict

from .utils import RNN

class ElmanBRNN(RNN):

    def __init__(self, num_hidden, num_classes, context_win_size, embeddings,
                 featdim=0, fine_tuning=False, truncate_gradient=-1):
        """
        num_hidden :: dimension of the hidden layer
        num_classes :: number of classes
        context_win_size :: word window context size
        embeddings :: matrix
        """
        # hyper parameters of the model

        self.hyperparams = {}

        # nh :: dimension of the hidden layer
        nh = num_hidden
        self.hyperparams['nh'] = nh

        # nc :: number of classes
        nc = num_classes
        self.hyperparams['nc'] = nc

        # de :: dimension of the word embeddings
        de = embeddings.shape[1]
        self.hyperparams['de'] = de

        # cs :: word window context size
        cs = context_win_size
        self.hyperparams['cs'] = cs

        self.hyperparams['featdim'] = featdim
        self.hyperparams['fine_tuning'] = fine_tuning
        self.hyperparams['truncate_gradient'] = truncate_gradient

        # parameters of the model
        self.emb = theano.shared(embeddings.astype(theano.config.floatX))

        # inputs
        idxs = T.imatrix()
        w = T.fscalar('w')
        x = self.emb[idxs].reshape((idxs.shape[0], de * cs))*w
        y = T.iscalar('y')
        y_sentence = T.ivector('y_sentence')
        f = T.matrix('f')
        f.reshape((idxs.shape[0], featdim))

        # forward parameters of the model
        self.fWx = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                         (de * cs, nh)).astype(theano.config.floatX))

        self.fWh = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                         (nh, nh)).astype(theano.config.floatX))

        self.fbh = theano.shared(np.zeros(nh, dtype=theano.config.floatX))

        self.fh0 = theano.shared(np.zeros(nh, dtype=theano.config.floatX))

        fparams = [self.fWx, self.fWh, self.fbh, self.fh0]
        fnames = ['fWx', 'fWh', 'fbh', 'fh0']

        def frecurrence(x_t, h_tm1):
            h_t = T.nnet.sigmoid(T.dot(x_t, self.fWx) + T.dot(h_tm1, self.fWh) + self.fbh)
            return h_t

        fh, _ = theano.scan(fn=frecurrence,
                            sequences=x,
                            outputs_info=[self.fh0],
                            n_steps=x.shape[0],
                            truncate_gradient=truncate_gradient)

        # backwards parameters of the model
        self.bWx = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                         (de * cs, nh)).astype(theano.config.floatX))

        self.bWh = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                         (nh, nh)).astype(theano.config.floatX))

        self.bbh = theano.shared(np.zeros(nh, dtype=theano.config.floatX))

        self.bh0 = theano.shared(np.zeros(nh, dtype=theano.config.floatX))

        bparams = [self.bWx, self.bWh, self.bbh, self.bh0]
        bnames = ['bWx', 'bWh', 'bbh', 'bh0']

        def brecurrence(x_t, h_tm1):
            h_t = T.nnet.sigmoid(T.dot(x_t, self.bWx) + T.dot(h_tm1, self.bWh) + self.bbh)
            return h_t

        bh, _ = theano.scan(fn=brecurrence,
                            sequences=x,
                            outputs_info=[self.bh0],
                            n_steps=x.shape[0],
                            go_backwards=True,
                            truncate_gradient=truncate_gradient)

        # inverting backwards hidden
        bh = bh[::-1]

        # concatenation parameters
        self.bW = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                        (nh+featdim, nc)).astype(theano.config.floatX))

        self.fW = theano.shared(0.2 * np.random.uniform(-1.0, 1.0,
                                                        (nh+featdim, nc)).astype(theano.config.floatX))

        self.b = theano.shared(np.zeros(nc, dtype=theano.config.floatX))

        # adding features
        if featdim > 0:
            fh_final = T.concatenate([fh, f], axis=1)
            bh_final = T.concatenate([bh, f], axis=1)
        else:
            fh_final = fh
            bh_final = bh

        # "concatenating" forward and backward hidden states
        h = T.dot(bh_final, self.bW) + T.dot(fh_final, self.fW)

        s = T.nnet.softmax(h + self.b)

        p_y_given_x_lastword = s[-1, :]
        p_y_given_x_sentence = s

        self.params = fparams + bparams + [self.bW, self.fW, self.b]
        self.names = fnames + bnames + ['bW', 'fW', 'b']

        if fine_tuning:
            self.params.append(self.emb)
            self.names.append("emb")

        # prediction
        y_pred = T.argmax(p_y_given_x_sentence, axis=1)

        # cost functions
        sentence_nll = -T.mean(T.log(p_y_given_x_sentence)
                               [T.arange(x.shape[0]), y_sentence])

        nll = -T.mean(T.log(p_y_given_x_lastword)[y])

        # gradients
        sentence_gradients = T.grad(sentence_nll, self.params)
        gradients = T.grad(nll, self.params)

        # learning rate
        lr = T.scalar('lr')

        # updates
        sentence_updates = OrderedDict((p, p - lr * g)
                                       for p, g in
                                       zip(self.params, sentence_gradients))

        updates = OrderedDict((p, p - lr * g)
                              for p, g in
                              zip(self.params, gradients))

        # theano functions
        self.classify = theano.function(inputs=[idxs, f, In(w, value=1.0)],
                                        outputs=y_pred,
                                        on_unused_input='ignore')

        self.sentence_train = theano.function(inputs=[idxs, f, y_sentence, lr, In(w, value=1.0)],
                                              outputs=sentence_nll,
                                              updates=sentence_updates,
                                              on_unused_input='ignore')

        self.train = theano.function(inputs=[idxs, f, y, lr, In(w, value=1.0)],
                                     outputs=nll,
                                     updates=updates,
                                     on_unused_input='ignore')

        self.predict = theano.function(inputs=[idxs, f, In(w, value=1.0)],
                                       outputs=p_y_given_x_sentence,
                                       on_unused_input='ignore')

        self.normalize = theano.function(inputs=[],
                                         updates={self.emb:\
                                                  self.emb/T.sqrt((self.emb**2).sum(axis=1)).dimshuffle(0, 'x')})


#!/usr/bin/env python

import argparse
import ray
import tensorflow as tf
from baselines.logger import configure
from baselines.common import set_global_seeds
from baselines.common.vec_env.vec_normalize import VecNormalize
import baselines.ppo2.policies as policies
import baselines.ppo2.ppo2 as ppo2
from nips.round2_env import CustomEnv, CustomActionWrapper
from nips.remote_vec_env import RemoteVecEnv

def create_env():
    env = CustomEnv(visualization=args.vis, integrator_accuracy=args.accuracy)
    env = CustomActionWrapper(env, action_repeat=args.repeat)
    return env

def train():
    config = tf.ConfigProto(
        allow_soft_placement=True,
        intra_op_parallelism_threads=args.num_cpus,
        inter_op_parallelism_threads=args.num_cpus
    )
    tf.Session(config=config).__enter__()

    env = RemoteVecEnv([create_env] * args.num_cpus)
    env = VecNormalize(env, ret=True, gamma=args.gamma)

    ppo2.learn(
        policy=policies.MlpPolicy, env=env,
        total_timesteps=args.num_timesteps, nminibatches=args.num_minibatches,
        nsteps=args.num_steps, noptepochs=args.num_epochs, lr=args.learning_rate,
        gamma=args.gamma,
        lam=args.lam, ent_coef=args.ent_coef, vf_coef=args.vf_coef, cliprange=args.clip_range,
        log_interval=args.log_interval, save_interval=args.save_interval,
        load_path=args.checkpoint_path,
        num_casks=args.num_casks
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='PPO training for NIPS 2018: AI for Prosthetics Challenge, Round 2')
    parser.add_argument('--num-timesteps', default=1e6, type=int, help='number of timesteps')
    # batch_size = num_steps * num_envs
    parser.add_argument('--num-steps', default=128, type=int, help='number of steps per update')
    # valid number of envs
    parser.add_argument('--num-minibatches', default=1, type=int, help='number of training minibatches per update')
    parser.add_argument('--num-epochs', default=4, type=int, help='number of training epochs per update')
    parser.add_argument('--learning-rate', default=3e-4, type=float, help='learning rate')
    # RL domain
    parser.add_argument('--gamma', default=0.99, type=float, help='discounting factor')
    # PPO specific
    parser.add_argument('--lam', default=0.95, type=float, help='advantage estimation discounting factor')
    parser.add_argument('--ent-coef', default=0.001, type=float, help='policy entropy coefficient')
    parser.add_argument('--vf-coef', default=0.5, type=float, help='value function loss coefficient')
    parser.add_argument('--clip-range', default=0.2, type=float, help='clipping range')
    # env related
    parser.add_argument('--seed', default=6730, type=int, help='random seed')
    parser.add_argument('--accuracy', default=5e-5, type=float, help='simulator integrator accuracy')
    parser.add_argument('--repeat', default=1, type=int, help='number of action repeat')
    parser.add_argument('--vis', default=False, action='store_true', help='visualization option')
    # training settings
    parser.add_argument('--num-cpus', default=1, type=int, help='number of cpus')
    parser.add_argument('--num-casks', default=0, type=int, help='number of casks, for acceleration')
    parser.add_argument('--num-gpus', default=0, type=int, help='number of gpus')
    parser.add_argument('--log-dir', default='./logs', type=str, help='logging events output directory')
    parser.add_argument('--log-interval', default=1, type=int, help='number of timesteps between logging events')
    parser.add_argument('--save-interval', default=1, type=int, help='number of timesteps between saving events')
    parser.add_argument('--checkpoint-path', default=None, type=str, help='path to load the model checkpoint from')
    args = parser.parse_args()
    print(args)

    ray.init(num_cpus=args.num_cpus, num_gpus=args.num_gpus)
    set_global_seeds(args.seed)
    configure(dir=args.log_dir)
    train()


from argparse import ArgumentParser
from queue import Queue
from threading import Thread
from time import sleep, time
from datetime import timedelta
from signal import signal, SIGINT
from os import access, path, R_OK

from tqdm import tqdm

import config as config_file
from detector import ObjectDetector
from threads import loader_thread, detector_thread, tracker_thread
from loader import VideoLoader
from tracker import ObjectTracker

def log(msg: str, bar: tqdm = None, cfg = None):
    if cfg is not None and cfg.SILENT:
        return

    if bar is not None and not bar.disable:
        bar.write(msg)
    else:
        print(msg)

def is_readable_file(parser, arg):
    if not path.isfile(arg) or not access(arg, R_OK):
        parser.error(f"${arg} není validní čitelný soubor!")

    return arg

def kvidet(input_video, config):
    to_detect = Queue()
    to_track = Queue()
    to_summarize = Queue()

    video_loader = VideoLoader(config.FRAME_SKIP)
    object_detector = ObjectDetector()
    object_tracker = ObjectTracker()

    video_loader.load(input_video)

    loader_bar = tqdm(desc="loader progress", total=video_loader.get_video_frame_count() // config.FRAME_SKIP,
                      ascii=True, disable=(not config.PROGRESS))
    detector_bar = tqdm(desc="detection progress", total=video_loader.get_video_frame_count() // config.FRAME_SKIP,
                        ascii=True, disable=(not config.PROGRESS))
    tracker_bar = tqdm(desc="tracker progress", total=video_loader.get_video_frame_count() // config.FRAME_SKIP,
                       ascii=True, disable=(not config.PROGRESS))

    loader = Thread(target=loader_thread, args=(video_loader, to_detect, loader_bar), daemon=True)
    detector = Thread(target=detector_thread, args=(object_detector, to_detect, to_track, detector_bar), daemon=True)
    tracker = Thread(target=tracker_thread, args=(object_tracker, to_track, to_summarize, tracker_bar), daemon=True)

    # stop threads
    def stop_detection(sig, fr):
        video_loader.stop = True
        object_detector.stop = True
        object_tracker.stop = True

    signal(SIGINT, stop_detection)

    loader.start()
    log("loader started", loader_bar, config)

    detector.start()
    log("detector started", detector_bar, config)

    tracker.start()
    log("tracker started", tracker_bar, config)

    loader.join()
    detector.join()
    tracker.join()

    loader_bar.close()
    detector_bar.close()
    tracker_bar.close()

    log("all threads finished", cfg=config)

    summarization_task = to_summarize.get()
    detected_vehicles = summarization_task.payload

    log("sorting vehicles by direction", cfg=config)

    sorted_vehicles_by_direction = {}

    if detected_vehicles is None:
        return sorted_vehicles_by_direction

    for vehicle in detected_vehicles.values():
        for direction, bounding_vectors in config.BOUNDING_VECTORS.items():
            if direction not in sorted_vehicles_by_direction:
                sorted_vehicles_by_direction[direction] = []

            if len(vehicle.position_history) < 2:
                continue

            if vehicle.motion_vector.is_between(bounding_vectors[0], bounding_vectors[1]):
                sorted_vehicles_by_direction[direction].append(vehicle)
    return sorted_vehicles_by_direction

if __name__ == "__main__":
    arg_parser = ArgumentParser(description="Detekce projíždějících aut a jejich směrů")

    arg_parser.add_argument("input_path", help="cesta k videosouboru",
                            type=lambda filename: is_readable_file(arg_parser, filename))
    arg_parser.add_argument("--silent", "-s", help="zda vypisovat na standardní výstup průběh detekce",
                            default=config_file.SILENT, action="store_true")
    arg_parser.add_argument("--debug", "-d", help="zda vypisovat ladící údaje na standardní výstup",
                            default=config_file.DEBUG, action="store_true")
    arg_parser.add_argument("--time", "-t", help="zda vypisovat na standardní výstup dobu strávenou detekcí",
                            default=config_file.TIME, action="store_true")
    arg_parser.add_argument("--progress", "-p", help="zda vypisovat živě průběh detekce na standardní výstup",
                            default=config_file.PROGRESS, action="store_true")
    arg_parser.add_argument("--frame-skip", "-n", help="číst poze každý N-tý snímek",
                            default=config_file.FRAME_SKIP, metavar="N", type=int)

    args = arg_parser.parse_args()

    config = config_file
    config.SILENT = args.silent
    config.DEBUG = args.debug
    config.TIME = args.time
    config.PROGRESS = args.progress
    config.FRAME_SKIP = args.frame_skip

    start_time = time()
    result = kvidet(args.input_path, config)
    end_time = time()

    print("-----------------")
    print("Results:")
    for direction in result:
        print(f"direction: {direction} vehicles: {len(result[direction])}")

    if config.TIME:
        elapsed_time=timedelta(seconds=end_time) - timedelta(seconds=start_time)
        hours, remainder = divmod(int(elapsed_time.total_seconds()), 60 * 60)
        minutes, seconds = divmod(remainder, 60)
        print(f"elapsed time: {hours}h {minutes}m {seconds}s")


import os
from argparse import ArgumentParser
from os.path import join

import numpy as np
import pytorch_lightning as pl
import torch
import torch.backends.cudnn as cudnn
from pytorch_lightning.callbacks import ModelCheckpoint, TQDMProgressBar, LearningRateMonitor

from StandardStrategies.CtoY import CtoY
from StandardStrategies.XtoCtoY import XtoCtoY
from StandardStrategies.XtoY import XtoY
from StandardStrategies.XtoC import XtoC
from continualStrategies.train import train_and_test_continual
from dataset.dataloader import get_loaders
from dataset.dataloader import load_cub200
from explainers.Explainer import Label_Explainer

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
CHECKPOINT_PATH = join(ROOT_DIR, "results")

def main():
    # parse parameters
    parser = ArgumentParser(description='experiment', allow_abbrev=False)
    parser.add_argument('--dataset', type=str, default="cub200",
                        help='dataset name.', choices=["cub200"])
    parser.add_argument('--classifier', type=str, default="linear",
                        help='classifier name.', choices=["linear", "cnn", "..."])
    parser.add_argument('--featureExtractor', type=str, default="linear",
                        help='classifier name.', choices=["VAE", "CNN", "linear", "resnet"])
    parser.add_argument('--experiment', type=str, default="XtoCtoY",
                        help='classifier name.', choices=["XtoCtoY", "XtoC", "CtoY", "XtoY"])
    parser.add_argument('--continual', action="store_true", default=False,
                        help='standard or continual experiment', )
    parser.add_argument('--batch_size', default=20,
                        help='batchsize', )
    parser.add_argument('--optimizer_name', default="SGD",
                        choices=["SGD", "ADAM"])
    parser.add_argument('-scheduler_step', type=int, default=20,
                        help='Number of steps before decaying current learning rate by half')
    parser.add_argument('--epochs_per_task', default=5,
                        help='epochs_per_task in continual environment', )

    parser.add_argument('-weight_decay', type=float,
                        default=0.0004, help='weight decay for optimizer')
    parser.add_argument('-lr', type=float, default=0.01, help="learning rate")

    args = parser.parse_known_args()[0]

    # set reproducible results
    seed = 10
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Using device:', device)
    if device.type == 'cuda':
        cudnn.benchmark = True
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False
    else: torch.manual_seed(seed)

    np.random.seed(seed)

    # get datasets
    train, val, test = load_cub200(join(ROOT_DIR, "data"))

    if args.continual:
        train_and_test_continual(
            train, val, test, device, args, CHECKPOINT_PATH)
    else:

        trainloader, valloader, testloader = get_loaders(
            train, val, test, args.batch_size)
        if args.experiment == "CtoY":
            strategy = CtoY(optimizer_name=args.optimizer_name, model_hparams={"num_classes": 200, "act_fn_name": "relu"},
                            optimizer_hparams={"lr": args.lr, "weight_decay": args.weight_decay, "scheduler_step": args.scheduler_step}, continual=False)
        elif args.experiment == "XtoY":
            strategy = XtoY(optimizer_name=args.optimizer_name, model_hparams={"num_classes": 200, "act_fn_name": "relu"},
                            optimizer_hparams={"lr": args.lr, "weight_decay": args.weight_decay, "scheduler_step": args.scheduler_step}, continual=False)
        elif args.experiment == "XtoCtoY":

            strategy = XtoCtoY(optimizer_name=args.optimizer_name, model_hparams={"num_classes": 200, "act_fn_name": "relu"},
                               optimizer_hparams={"lr": args.lr, "weight_decay": args.weight_decay, "scheduler_step": args.scheduler_step},
                               continual=False,device=device.type)
        elif args.experiment == "XtoC":
            strategy = XtoC(optimizer_name=args.optimizer_name, model_hparams={"num_classes": 200, "act_fn_name": "relu"},
                            optimizer_hparams={"lr": args.lr, "weight_decay": args.weight_decay, "scheduler_step": args.scheduler_step}, continual=False,device=device.type)

        else:
            raise "experiment not defined"
        checkpoint = ModelCheckpoint(save_weights_only=True, mode="max")
        trainer = pl.Trainer(default_root_dir=os.path.join(CHECKPOINT_PATH, strategy.name, "standard", args.dataset),
                             # Where to save models
                             # We run on a single GPU (if possible)
                             gpus=1 if str(device) == "cuda" else 0,

                             max_epochs=800,  # How many epochs to train for if no patience is set

                             callbacks=[checkpoint,
                                        # Save the best checkpoint based on the maximum val_acc recorded. Saves only weights and not optimizer
                                        LearningRateMonitor("epoch"),
                                        TQDMProgressBar(1)]  # Log learning rate every epoch
                             )
        #TEST for the metrics

#        print('Before passing to verifier')
#        print(strategy.model.model2.weight.size())
        #explainer=Label_Explainer(strategy, 'data/epoch=188-step=45170.ckpt', testloader) #TODO: fix immediately on cpu
        #explainer.fit(method='GRADCAM')

        trainer.fit(strategy, train_dataloaders=trainloader,
                    val_dataloaders=valloader)

        #explainer=Label_Explainer(strategy, checkpoint.best_model_path, testloader, )
        #explainer.run()

        trainer.test(strategy, dataloaders=testloader)

        #explainer = Label_Explainer(checkpoint.best_model_path, testloader)
        #explainer.run()

if __name__ == '__main__':
    main()


from flask import Blueprint, request, session
from flask_restful import Api, marshal_with, Resource
from flask_restful.reqparse import RequestParser

from src.config.api_utils import oper_log, check_auth
from src.dto_mapper import dictdetail_page_fields, dict_detail_fields
from src.schema import DictDetailSchema
from src.service.sys_service import DictDetailService

dictdetail_app = Blueprint('dictDetail', __name__, url_prefix='/api/dictDetail')
dictdetail_api = Api(dictdetail_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('label', location='json', type=str, trim=True, required=True)
parser.add_argument('value', location='json', type=str, trim=True, required=True)
parser.add_argument('dictSort', location='json', type=int, trim=True, required=True)

@dictdetail_api.resource('', '/')
class DictDetailAPI(Resource):
    @oper_log('查询字典详情', request)
    @marshal_with(dictdetail_page_fields)
    def get(self):
        return DictDetailService.query_all(**request.args)

    @oper_log('修改字典详情', request)
    @check_auth('dict:edit', request)
    def put(self):
        parser_put = parser.copy()
        parser_put.parse_args()
        schema = DictDetailSchema()
        user = session["user"]
        params = request.get_json()
        curr_detail = schema.load(params, unknown="exclude")
        curr_detail.update_by = user["username"]
        DictDetailService.update(curr_detail=curr_detail)
        return None, 204

    @oper_log('新增字典详情', request)
    @check_auth('dict:add', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = DictDetailSchema()
        curr_detail = schema.load(params, unknown="exclude")
        user = session["user"]
        curr_detail.dict_id = params["dict"]["id"]
        curr_detail.dict_sort = params["dictSort"]
        curr_detail.create_by = user["username"]
        DictDetailService.create(curr_detail=curr_detail)

@dictdetail_api.resource('/<int:id_>')
class DeleteDictDetail(Resource):
    @oper_log('删除字典详情', request)
    @check_auth('dict:del', request)
    def delete(self, id_):
        DictDetailService.delete(id_=id_)

@dictdetail_api.resource('/<int:_id>')
class GetDetailById(Resource):
    @oper_log('根据ID查询岗位', request)
    @check_auth('dict:list', request)
    @marshal_with(dict_detail_fields)
    def get(self, _id):
        data = DictDetailService.find_by_id(detail_id=_id)
        return data


# src/hypermodern_python/console.py
import textwrap
import locale
import click
import requests

from . import __version__

API_URL = "https://en.wikipedia.org/api/rest_v1/page/random/summary"

@click.command()
@click.version_option(version=__version__)
def main():
    """The hypermodern Python project."""

    # Get and set locale language
    locale_lang, locale_encoding = locale.getdefaultlocale()
    click.echo(textwrap.fill(locale_lang + " : " + locale_encoding))

    # Language selector
    LANG_SLICE = slice(8,10)

    NEW_URL = list(API_URL)
    NEW_URL[LANG_SLICE] = 'en'
    NEW_URL = ''.join(NEW_URL)

    click.echo(textwrap.fill(NEW_URL))

    with requests.get(NEW_URL) as response:
        try:
            response.raise_for_status()
            data = response.json()

            title = data["title"]
            extract = data["extract"]

            click.secho(title, fg="green")
            click.echo(textwrap.fill(extract))

        except requests.exceptions.HTTPError as err:
            click.secho("HTTP Error", fg="red")
            # click.echo(textwrap.fill(err))
            raise SystemExit(err)


#!/usr/bin/env python """
import sys
import tempfile
import os

from datetime import date
today = date.today()

"""Mailroom Part 4"""
""" Updates from Part 3
1. Refactored for testing
"""

# Prompt user to choose from menu of 4 actions:
# Send a Thank You, Create a Report, Send thanks to all donors or quit.

assert_donor_db = {"Cher": [1000.00, 245.00],
            "Drew Barrymore": [25000.00],
            "Charlie Brown": [25.00, 50.01, 100.00],
            "Jack Black": [256.00, 752.50, 10101.00],
            "Sam Smith": [5500.00, 24.00],
            }

donor_db = {"Cher": [1000.00, 245.00],
            "Drew Barrymore": [25000.00],
            "Charlie Brown": [25.00, 50.01, 100.00],
            "Jack Black": [256.00, 752.50, 10101.00],
            "Sam Smith": [5500.00, 24.00],
            }

default_folder = "thank_you_cards"

def get_input(prompt):
    response = input(prompt)
    return response

def sort_key(donors):
    #  sort by total donations
    return sum(donors[1])

def list_donors():
    return list(donor_db)

def add_donor(donator, donation):
    """      Add new donor with donation
    """

    donor_db[donator] = []
    donor_db[donator] = donor_db[donator] + [donation]

def update_donor(donator, donation):
    """      update donor with new donation
    """

    donor_db[donator] = donor_db[donator] + [donation]

def get_letter_text(donation_dict):
    """Get letter text for file content"""

    formatted = 'Dear {name},\
    \n\n\tThank you for your very kind donation of ${donation:,.2f}.\
    \n\n\tIt will be put to very good use.\n\n\t\t\tSincerely,\
    \n\t\t\t   -The Team'.format(**donation_dict)

    return formatted

def create_card(donator, amount, fldr):
    """
    Create thank you note for passed user
    """

    donation_dict = {}
    donation_dict['name'] = donator
    donation_dict['donation'] = float(amount)

    ty_text = get_letter_text(donation_dict)

    file_name = donation_dict['name'].replace(' ', '_') + '.txt'
    file_path = os.path.join(fldr, file_name)

    try:
        with open(file_path, 'w+') as f:
            f.write(ty_text)
            print(ty_text)
    except IOError:
        print(f"IOError: Error writing to file: {write_path}")

    print(f"\n** Thank you note to {donation_dict['name']} for ${donation_dict['donation']:,.2f} written to {write_path}.  **\n")

def get_donor_name():
    donor_prompt = "\n".join(("\nEnter Full name of donor",
                        "  or Enter list to show current donors",
                        "  or 'q' to return to main menu",
                        "  Please enter donor name:"
                        " > "))
    in_name = get_input(donor_prompt)
    return in_name.title()

def send_ty(donors):
    ''' Send thank you to selected donor '''

    donation = []

    while True:
        donor_name = get_donor_name()

        if donor_name.lower() == 'list':
            donor_names = list_donors()
            print('\n')
            for donor_name in donor_names:
                print(f'   * {donor_name}')
            print('\n')
        elif donor_name.lower() == "q":
            break
        elif donor_name == '':
            continue
        else:
            donation = get_donation()
            if donor_exists(donor_name):
                update_donor(donor_name, donation)
                create_card(donor_name, donation, write_path)
                break
            else:
                add_donor(donor_name, donation)
                create_card(donor_name, donation, write_path)
                break

    return

def donor_exists(name):
    if donor_db.get(name):
        return True
    else:
        return False

def get_donation():
    while True:
        prompt = "Please enter a valid amount to donate >"
        donation = get_input(prompt)
        if donation == "q":
            return

        try:
            donation = float(donation)
        except ValueError:
            print('ValueError: Please enter a numeric value')
        else:
            if donation > 0:
                break
            else:
                continue

    return donation

def get_report(data_passed):

    report = []
    sorted_donors = dict(sorted(data_passed.items(), key=sort_key, reverse=True))
    for donor in sorted_donors.items():
        count = len(donor[1])
        total = sum(donor[1])
        avg = total/count
        write_row = ('{:25}  ${:13,.2f}   {:11}  ${:12,.2f}'.format(
            donor[0], total, count, avg))
# belarsonQ:  how to get this format converted to string
#        write_row = ('f'{donor:25}  ${total:13,.2f}   {count:11}  ${avg:12,.2f}')
        report.append(write_row)

    return report

def display_report():
    for row in get_report(donor_db):
        print(row)

def display_report_header():
    header = []
    col1 = 'Donor Name'
    col2 = 'Total Given'
    col3 = 'Num Gifts'
    col4 = 'Average Gift'
    # print(f'{col1:25} | {col2:13} | {col3:11} | {col4:13}')
    # print('-'*70)
    header.append(f'{col1:25} | {col2:13} | {col3:11} | {col4:13}')
    header.append('-'*70)
    return header

def create_report(donors):
    """
    Print formatted report of donors and donations
    Sort report by total donations
    """
    report = []

    report_header = [display_report_header()]
    report_body = [display_report()]
    print(report_header)
    print(report_body)

def ask_for_folder():
    global user_folder

    # as creating folders is platform specific, end if not Windows.
    import platform

    if not platform.system().lower() == 'windows':
        print(f'Sorry, future development requested but not currently enabled for {platform.system()} platform')
        exit_program(0)

    text = "\n".join(("\n\n\nEnter folder Name or hit enter for default",
                      " >"))
    folder_prompt = get_input(text)

    if folder_prompt:
        user_folder = folder_prompt.replace(" ", "_")
    else:
        user_folder = default_folder

    temp_path = tempfile.gettempdir()
    folder_name = user_folder + '_' + today.strftime("%b_%d_%Y")

    folder_path = os.path.join(temp_path, folder_name)

    if not os.path.exists(folder_path):
        os.makedirs(folder_path)

    return folder_path

def send_all_ty(donors):
    '''
    Create cards for all donor in dictionary
    Note: revised code to use comprehension in Mailroom Part 3
    '''

    [create_card(donor, donations[-1], write_path) for donor, donations in donor_db.items()]
    '''
    for donor, donations in donor_db.items():
        donation_current = donations[-1]
        create_card(donor, donation_current, write_path)
    '''
    return

def exit_program(donors):
    print('Thank you')
    sys.exit()

def get_selection():

    menu_prompt = "\n".join(("**  Please Select Valid Option Listed:  **",
                        "       1: Send a Thank You",
                        "       2: Create a Report",
                        "       3: Thanks to All Donors",
                        "       4: Quit",
                        f"       (Folder: {user_folder})",
                        "       Please enter your choice:"
                        " > "))

    response = get_input(menu_prompt)

    return response

if __name__ == '__main__':

    try:
        response = ''
        write_path = ask_for_folder()
        print(f'writing to file: {write_path}')

        switch_func_dict = {
            '1': send_ty,
            '2': create_report,
            '3': send_all_ty,
            '4': exit_program
        }

        while True:
            response = get_selection()
            try:
                # if response in switch_func_dict:
                # switch_func_dict.get(response, "nothing")()
                # switch_func_dict.get(response, "nothing")(donor_db)
                switch_func_dict[response](donor_db)
                # else:
                #    print("Please enter valid option")
            except KeyError:
                print('Please select a value 1-4')

    except KeyboardInterrupt:
        print('\n\nKeyboardInterrupt: Interrupted and Exiting')
        sys.exit(0)


# get values for freq changes
import json
from pprint import pprint

with open('C:/Users/chadsten/source/repos/advent-of-code/2018/day-1/data.json') as data_file:
	data = json.load(data_file)

## determine the end frequency after applying all modifiers in the

freq = 0 # base frequency

for f in data['freq']:
	freq = freq + int(f['value']) # simply loop to add all values

print(str(freq) + " is the end frequency.") # output final frequency

## determine first frequency that has happened twice

occ = {} # initiate occurence object
freq = 0 # base frequency
occ[freq] = 1 # set starting frequency to have occured once
hit = None # we have not had a hit (frequency occuring twice)
present = dict() # our output, it's a gift!

def buildData(occ, freq):
	val = dict() # define object for return

	for f in data['freq']:
		freq = freq + int(f['value']) # calculate new frequency

		try:
			occ[freq]
		except KeyError:
			occ[freq] = 0 # if this doesn't exist, it's the frequency's first occurence

		occ[freq] = occ[freq] + 1 # increment the occurence counter

		if occ[freq] > 1:
			val['number'] = occ[freq]
			break # store which frequency has occured twice and leave the loop
		else:
			val['number'] = 'fail' # default value for checking later

	val['freq'] = freq # set new frequency
	return val

while hit is None: # if no 2nd occurence has been detected yet
	present = buildData(occ, freq) # attempt to find 2nd occurence, carrying over data from previous passes
	freq = present['freq'] # set new frequency for next pass

	if present['number'] != 'fail': # if it's not our default fail, we have a match
		hit = 1

print(str(present['freq']) + " is the first frequency to be repeated.") # output first repeated frequency