import time
from rgbmatrix import RGBMatrix, RGBMatrixOptions
from PIL import Image
import os
from web3 import Web3
from rgbmatrix import graphics
from random import randint
from datetime import datetime
from tda import auth, client
import config
import b
import sys

class run:
    def __init__(self, Test='False', Type=None):
        options = RGBMatrixOptions()
        options.rows = 32
        options.cols = 64
        options.chain_length = 1
        options.parallel = 1
        options.hardware_mapping = 'adafruit-hat'
        self.matrix = RGBMatrix(options=options)
        self.offscreen_canvas = self.matrix.CreateFrameCanvas()
        self.prevtime = 0
        self.font = graphics.Font()
        self.font2 = graphics.Font(1)
        self.font.LoadFont("./10x20.bdf")
        self.font2.LoadFont("./6x9.bdf")

        stocktimes=(5,10,20,25,35,40,50,55)
        markethours = (7,8,9,10,11,12,1,2,3)
        cryptotimes=(30,0)
        self.ClockMoved = False
        self.TokenFail = False

        done  = False
        while not done:
            self.clock(True, False)
            if Test == 'True':
                if int(self.minute) %1 == 0:
                    if Type == 'S':
                        try:
                            self.getStocks()
                            self.print(self.textlist, self.font2, 7, True, False)
                        except PermissionError as e:
                            print(e)
                            b.run()
                        done = True
                        break
                    if Type == 'T':
                        self.getTokens()
                        self.print(self.textlist, self.font, 23, False, True)
                        done = True
                        break
            else:
                if int(self.minute) in stocktimes :
                    if int(self.hour) in markethours:
                        try:
                            if self.TokenFail is False:
                                self.getStocks()
                                self.print(self.textlist, self.font2, 7, True, False)
                        except PermissionError as e:
                            # self.TokenFail = True
                            try:
                                b.run()
                            except:
                                pass

                    self.offscreen_canvas.Clear()
                if int(self.minute) in cryptotimes:
                    self.getTokens()
                    self.print(self.textlist, self.font, 23, False, True)
                self.offscreen_canvas.Clear()

    def clock(self, Solo, crypto):
        month = datetime.now().date().month
        day = datetime.now().date().day
        self.date = str(month) + '/' + str(day)
        self.minute = datetime.now().minute
        self.hour = datetime.now().hour
        if int(self.hour) > 12:
            self.hour -= 12
        minute = self.minute
        if int(self.minute) < 10:
            minute = "0"+str(self.minute)
        self.time = str(self.hour) + ":" + str(minute)
        if crypto is False:
            if Solo is True:
                if crypto is False:
                    if self.time != self.prevtime:
                        self.TokenFail = False
                        self.prevtime = self.time
                        try:
                            self.offscreen_canvas.Clear()
                        except:
                            pass
                        if self.ClockMoved is True:
                            self.SlideClock(23, 32, 'down')
                        self.printClock(18,27)
                        self.ClockMoved = False
                        self.offscreen_canvas = self.matrix.SwapOnVSync(self.offscreen_canvas)

            else:
                if self.ClockMoved is False:
                    self.SlideClock(18, 27, 'up')
                self.printClock(23, 32)
                self.ClockMoved = True

    def SlideClock(self,pos1, pos2, dir, ):
        for i in range(5):
            self.printClock(pos1, pos2)
            self.offscreen_canvas = self.matrix.SwapOnVSync(self.offscreen_canvas)
            time.sleep(.25)
            self.offscreen_canvas.Clear()
            if dir == 'up':
                pos1 += 1
                pos2 += 1
            else:
                pos1 -= 1
                pos2 -= 1

    def printClock(self, Pos1, Pos2):
        # 23 32
        self.Ttxt = graphics.DrawText(self.offscreen_canvas, self.font, 10, Pos1, graphics.Color(0, 0, 255),
                                      str(self.time))
        self.Dtxt = graphics.DrawText(self.offscreen_canvas, self.font2, 10, Pos2, graphics.Color(0, 0, 255),
                                      str(self.date))
        self.offscreen_canvas.Clear()
        self.timepos = 32 - (self.Ttxt / 2)
        self.datepos = 32 - (self.Dtxt / 2)
        self.Ttxt = graphics.DrawText(self.offscreen_canvas, self.font, self.timepos, Pos1, graphics.Color(0, 0, 255),
                                      str(self.time))
        self.Dtxt = graphics.DrawText(self.offscreen_canvas, self.font2, self.datepos, Pos2, graphics.Color(0, 0, 255),
                                      str(self.date))

    def getTokens(self):
        web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/dfb29047e37a436fbbf8e723722f3b9c'))
        abi = '[{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],' \
              '"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},' \
              '{"inputs":[{"internalType":"uint80","name":"_roundId","type":"uint80"}],"name":"getRoundData","outputs":[{"internalType":"uint80",' \
              '"name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},{"internalType":"uint256","name":"startedAt","type":"uint256"},' \
              '{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound","type":"uint80"}],"stateMutability":"view","type":"function"},' \
              '{"inputs":[],"name":"latestRoundData","outputs":[{"internalType":"uint80","name":"roundId","type":"uint80"},{"internalType":"int256","name":"answer","type":"int256"},' \
              '{"internalType":"uint256","name":"startedAt","type":"uint256"},{"internalType":"uint256","name":"updatedAt","type":"uint256"},{"internalType":"uint80","name":"answeredInRound",' \
              '"type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":' \
              '"view","type":"function"}]'
        CoinList = [{"TOKEN": "BTC", "ADDR": "0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c",
                     "IMG":"/home/pi/Token_icons/btc.png", "Color":255,"Color1":145,"Color2":15},
                    {"TOKEN": "ETH", "ADDR": "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419",
                     "IMG":"/home/pi/Token_icons/eth.png", "Color":69,"Color1":74,"Color2":117},
                    {"TOKEN": "AAVE", "ADDR": "0x547a514d5e3769680Ce22B2361c10Ea13619e8a9",
                     "IMG":"/home/pi/Token_icons/aave.png", "Color":64,"Color1":172,"Color2":193},
                    {"TOKEN": "SOL", "ADDR": "0x4ffC43a60e009B551865A93d232E33Fce9f01507",
                     "IMG":"/home/pi/Token_icons/sol.png", "Color":193,"Color1":58,"Color2":244},
                    {"TOKEN": "LINK", "ADDR": "0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c",
                     "IMG":"/home/pi/Token_icons/link.png", "Color":51,"Color1":93,"Color2":210},
                    {"TOKEN": "ADA", "ADDR": "0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55",
                     "IMG":"/home/pi/Token_icons/ada.png", "Color":0,"Color1":52,"Color2":173},
                    {"TOKEN": "AVAX", "ADDR": "0xFF3EEb22B5E3dE6e705b44749C2559d704923FD7",
                     "IMG":"/home/pi/Token_icons/avax.png", "Color":232,"Color1":65,"Color2":66}
                    ]
        self.textlist = []
        for coin in CoinList:
            addr = coin.get("ADDR")
            token = coin.get("TOKEN")
            img = coin.get("IMG")
            contract = web3.eth.contract(address=addr, abi=abi)
            latestData = contract.functions.latestRoundData().call()
            price = round(int(latestData[1]) / 100000000, 2)
            text = str(token) + " $" + f"{price:,}"
            self.textlist.append({'text': text, 'Color1': coin.get("Color"),
                                  'Color2': coin.get("Color1"),'Color3': coin.get("Color2"), 'IMG':img})

    def getStocks(self):
        ListToGet = 'Top'
        c = auth.client_from_token_file(config.token_path, config.api_key, asyncio=False)
        Watchlsit = c.get_watchlists_for_single_account(config.account_id).json()
        Tickerlist = []
        for x in Watchlsit:
            if x.get('name') == ListToGet:
                watchlist = x.get('watchlistItems')
                for stocks in watchlist:
                    Tickerlist.append(stocks.get('instrument').get('symbol'))
        self.textlist = []
        for tickers in Tickerlist:
            open = c.get_quote(tickers).json().get(tickers).get('closePrice')
            current = c.get_quote(tickers).json().get(tickers).get('lastPrice')
            percentchange = str(round((1 - (float(open) / float(current))) * 100, 2))
            if float(percentchange) > 0:
                color1 = 0
                color2 = 255
                color3 = 0
                img = '/home/pi/Token_icons/up.png'
            else:
                color1 = 255
                color2 = 0
                color3 = 0
                img = '/home/pi/Token_icons/down.png'
            text = tickers + ' ' + percentchange + '%'+' $ ' + str(current)
            self.textlist.append({'text': text, 'Color1': color1,
                                  'Color2': color2, 'Color3': color3, 'IMG': img})

    def Alertmess(self, TEXT, Font, TextPos, Stock):
        pos = 64
        timeposy =18
        dateposy = 27
        loop2 = False
        loops = 0
        connected = False
        while not connected:
            if Stock is True:
                self.clock(False, False)
            else:
                self.clock(True,True)
                Ttxt = graphics.DrawText(self.offscreen_canvas, self.font,
                                         self.timepos, timeposy, graphics.Color(0, 0, 255),
                                         str(self.time))
                Dtxt = graphics.DrawText(self.offscreen_canvas, self.font2,
                                         self.datepos,dateposy, graphics.Color(0, 0, 255),
                                         str(self.date))
                timeposy -=1
                dateposy +=1
                self.timepos+=1
                self.datepos +=1

            txtlen = graphics.DrawText(self.offscreen_canvas, Font, pos, TextPos,
                                       graphics.Color(randint(0, 255),
                                                      randint(0, 255),
                                                      randint(0, 255)),
                                       TEXT)

            self.offscreen_canvas = self.matrix.SwapOnVSync(self.offscreen_canvas)
            time.sleep(.04)
            self.offscreen_canvas.Clear()
            if pos == 0 - txtlen:
                loop2 = True
            if loop2 is False:
                pos -= 1
            else:
                pos += 1
            if pos == 64:
                loops += 1
                loop2 = False
            if loops == 1:
                connected = True
                break

    def print(self, List, Font, TextPos, ClockON, Crypto):
        if Crypto is True:
           self.Alertmess('CRYPTO ALERT!',Font, TextPos, False)
        else:
            self.Alertmess('STOCK ALERT!',Font, TextPos,True)

        listlen = len(List)
        y = -1
        x = 0
        imlen = 10
        txtlen = 700
        imlen2 = 10
        txtlen2 = 70
        Loop2 = False
        Loop1 = True
        Tpos1 = 64
        Impos1 = 64
        Tpos2 = 64
        ImPos2 = 64
        connected = False
        while not connected:
            if ClockON is True:
                self.clock(False, False)
            if Loop1 is True:
                self.image1 = Image.open(List[x].get('IMG'))
                self.image1.thumbnail((self.matrix.width, self.matrix.height), Image.ANTIALIAS)
                imlen, img_height = self.image1.size
                Loop1 = False
            self.offscreen_canvas.SetImage(self.image1.convert('RGB'), Impos1)
            Impos1 -= 1
            if Impos1 < 64 - imlen - 5:
                txtlen = graphics.DrawText(self.offscreen_canvas, Font, Tpos1, TextPos,
                                           graphics.Color(List[x].get('Color1'),
                                                          List[x].get('Color2'),
                                                          List[x].get('Color3')),
                                           str(List[x].get('text')))
                Tpos1 -= 1
            if Tpos1 == 64 - txtlen - 5 or Loop2 is True:
                if Tpos1 == 64 - txtlen - 5:
                    y += 2
                    if y == listlen:
                        self.lastLoop(x, Tpos1, List, Font, TextPos, Crypto, ClockON)
                        connected = True
                        break
                    Tpos2 = 64
                    ImPos2 = 64
                    self.image2 = Image.open(List[y].get('IMG'))
                    self.image2.thumbnail((self.matrix.width, self.matrix.height), Image.ANTIALIAS)
                    imlen2, img_height2 = self.image2.size
                self.offscreen_canvas.SetImage(self.image2.convert('RGB'), ImPos2)
                ImPos2 -= 1
                Loop2 = True
            if ImPos2 < 64 - imlen2 - 5:
                txtlen2 = graphics.DrawText(self.offscreen_canvas, Font, Tpos2, TextPos,
                                            graphics.Color(List[y].get('Color1'),
                                                           List[y].get('Color2'),
                                                           List[y].get('Color3')),
                                            str(List[y].get('text')))
                Tpos2 -= 1

            if Tpos2 == 64 - txtlen2 - 5:
                x += 2
                if x == listlen:
                    self.lastLoop(y, Tpos2, List, Font, TextPos, Crypto, ClockON)
                    connected = True
                    break
                Tpos1 = 64
                Impos1 = 64
                Loop1 = True
            self.offscreen_canvas = self.matrix.SwapOnVSync(self.offscreen_canvas)

            time.sleep(.04)
            self.offscreen_canvas.Clear()

    def lastLoop(self, var, Tpos, List, Font, TextPos, Crypto, ClockON):
        tpos = 64
        dpos = 64
        timepos =0
        datepos = 0
        done = False
        while not done:
            if ClockON is True:
                self.clock(False, False)
            txtlen = graphics.DrawText(self.offscreen_canvas, Font, Tpos, TextPos,
                                       graphics.Color(List[var].get('Color1'),
                                                      List[var].get('Color2'),
                                                      List[var].get('Color3')),
                                       str(List[var].get('text')))
            Tpos -= 1
            if Crypto is True:
                if Tpos <= 64 - txtlen:
                    self.clock(True, True)
                    Ttxt = graphics.DrawText(self.offscreen_canvas, self.font,
                                             tpos, 18, graphics.Color(0, 0, 255),
                                             str(self.time))
                    Dtxt = graphics.DrawText(self.offscreen_canvas, self.font2,
                                             dpos, 27, graphics.Color(0, 0, 255),
                                             str(self.date))
                    if tpos > timepos:
                        tpos -= 1
                    if dpos > datepos:
                        dpos -=1
                    timepos = 32 - (Ttxt / 2)
                    datepos = 32 - (Dtxt / 2)

            self.offscreen_canvas = self.matrix.SwapOnVSync(self.offscreen_canvas)
            time.sleep(.04)
            self.offscreen_canvas.Clear()
            if Tpos < 0 - txtlen:
                done = True

if __name__ == '__main__':
    try:
        r = run(sys.argv[1], sys.argv[2])
    except:
        r = run()


#
# [798] Transform to Chessboard
#
# https://leetcode.com/problems/transform-to-chessboard/description/
#
# algorithms
# Hard (37.16%)
# Total Accepted:    1.5K
# Total Submissions: 4K
# Testcase Example:  '[[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]'
#
# An N x N board contains only 0s and 1s. In each move, you can swap any 2 rows
# with each other, or any 2 columns with each other.
#
# What is the minimum number of moves to transform the board into a
# "chessboard" - a board where no 0s and no 1s are 4-directionally adjacent? If
# the task is impossible, return -1.
#
#
# Examples:
# Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
# Output: 2
# Explanation:
# One potential sequence of moves is shown below, from left to right:
#
# 0110     1010     1010
# 0110 --> 1010 --> 0101
# 1001     0101     1010
# 1001     0101     0101
#
# The first move swaps the first and second column.
# The second move swaps the second and third row.
#
#
# Input: board = [[0, 1], [1, 0]]
# Output: 0
# Explanation:
# Also note that the board with 0 in the top left corner,
# 01
# 10
#
# is also a valid chessboard.
#
# Input: board = [[1, 0], [1, 0]]
# Output: -1
# Explanation:
# No matter what sequence of moves you make, you cannot end with a valid
# chessboard.
#
#
# Note:
#
#
# board will have the same number of rows and columns, a number in the range
# [2, 30].
# board[i][j] will be only 0s or 1s.
#
#
#
class Solution:
    def movesToChessboard(self, board):
        """
        :type board: List[List[int]]
        :rtype: int
        """
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        # O(n^2) solutions; Idea from https://leetcode.com/problems/transform-to-chessboard/discuss/132113/Java-Clear-Code-with-Detailed-Explanations
        # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
        n = len(board)
        if n == 0:
            return 0
        m = len(board[0])
        if n != m:
            return -1
        else:
            m = n
        for i in range(n):
            for j in range(n):
                if board[0][0] ^ board[0][j] ^ board[i][j] ^ board[i][0] == 1:
                    return -1
        rowOneCount = colOneCount = rowToMove = colToMove = 0
        for i in range(n):
            if board[0][i] == 1:
                rowOneCount += 1
            if board[i][0] == 1:
                colOneCount += 1
            if board[0][i] == i%2:
                colToMove += 1
            if board[i][0] == i%2:
                rowToMove += 1
        if not (n//2 <= rowOneCount <= (n+1)//2) or not (n//2 <= colOneCount <= (n+1)//2):
            return -1
        if n%2 == 0:
            rowToMove = min(rowToMove, n - rowToMove)
            colToMove = min(colToMove, n - colToMove)
        else:
            if rowToMove % 2 == 1:
                rowToMove = n - rowToMove
            if colToMove % 2 == 1:
                colToMove = n - colToMove
        return (rowToMove + colToMove)//2


import torch
from torch.utils import data

from .dataloader_seg import DataSeg
from .dataloader_video import DataVideo, DataVideoKinetics

def get_sets(task):

    # fetch the names of data lists depending on the task
    sets = {}
    if task == "OxUvA":
        sets["train_video"] = "train_oxuva"
        sets["val_video"] = "val_davis2017_480p"
        sets["val_video_seg"] = "val2_davis2017_480p"
    elif task == "YTVOS":
        sets["train_video"] = "train_ytvos"
        sets["val_video"] = "val_davis2017_480p"
        sets["val_video_seg"] = "val2_davis2017_480p"
    elif task == "TrackingNet":
        sets["train_video"] = "train_tracking"
        sets["val_video"] = "val_davis2017_480p"
        sets["val_video_seg"] = "val2_davis2017_480p"
    elif task == "kinetics400":
        sets["train_video"] = "train_kinetics400"
        sets["val_video"] = "val_davis2017_480p"
        sets["val_video_seg"] = "val2_davis2017_480p"
    else:
        raise NotImplementedError("Dataset '{}' not recognised.".format(task))

    return sets

def get_dataloader(args, cfg, split):
    assert split in ("train", "val")

    task = cfg.TRAIN.TASK
    data_sets = get_sets(cfg.TRAIN.TASK)

    # total batch size: # of GPUs * batch size per GPU
    batch_size = cfg.TRAIN.BATCH_SIZE
    kwargs = {'pin_memory': True, 'num_workers': args.workers}
    print("Dataloader: # workers {}".format(args.workers))

    def _dataloader(dataset, batch_size, shuffle=True, drop_last=False):
        return data.DataLoader(dataset, batch_size=batch_size, \
                               shuffle=shuffle, drop_last=drop_last, **kwargs)

    print("Split: ", split)
    if split == "train":
        VideoLoader = DataVideoKinetics if cfg.DATASET.MP4 else DataVideo
        dataset_video = VideoLoader(cfg, data_sets["train_video"])
        return _dataloader(dataset_video, batch_size, drop_last=True)
    else:
        dataset_video = DataVideo(cfg, data_sets["val_video"], val=True)
        dataset_video_seg = DataSeg(cfg, data_sets["val_video_seg"])

        return {"val_video": _dataloader(dataset_video, batch_size, shuffle=False), \
                "val_video_seg": _dataloader(dataset_video_seg, 1, shuffle=False)}


import os
import random
import argparse

def train_test_split(split_perc, dir_name, img_format, trainf, testf):
    split_perc/=100
    files = os.listdir(dir_name)
    img_files = sorted([file for file in files if file.endswith(img_format)], key=lambda x:int(x.split('.')[0]))
    test_files_idx = random.sample(range(0, len(img_files)),int(split_perc*len(img_files)))
    # print(img_files)
    # print(test_files_idx)
    # print(len(img_files))
    with open(testf, 'w') as test_f:
        with open(trainf, 'w') as train_f:
            for i, f in enumerate(img_files):
                if i in test_files_idx:
                    test_f.write(os.path.join(dir_name,f)+'\n')
                else:
                    train_f.write(os.path.join(dir_name,f)+'\n')
    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--out', type=str, required=False, default='custom_data')
    parser.add_argument('--train_f', type=str, required=False, default='train.txt')
    parser.add_argument('--test_f', type=str, required=False, default='test.txt')
    parser.add_argument('--img_fmt', type=str, required=False, default=".jpg")
    args = parser.parse_args()
    _ = train_test_split(split_perc = int(input('enter test data% [0-100] : ')), dir_name=args.out, img_format=args.img_fmt, trainf=args.train_f, testf=args.test_f)


import sys
sys.stdin = open("../input.txt", "rt")

N = int(input())
lScore = list(map(int, input().split()))
avg = sum(lScore) / N
avg = int(avg + 0.5)
minVal = 2147000000

for idx, val in enumerate(lScore):
    tmp = abs(val - avg)
    if tmp < minVal:
        minVal = tmp
        score = val
        res = idx+1
    elif tmp == minVal:
        if val > score:
            score = val
            res = idx+1
print(avg, res)


import enum
from ctypes import Union
from typing import Tuple, List, Any

from PyQt5 import QtCore, QtGui

from .task import ProcessingTask
from ..settings import ProcessingSettings
from ..calculations.resultsentry import CurveFileType, PatternFileType, CorMatFileType

class ReportingJobData:
    filetype: Union[CurveFileType, PatternFileType, CorMatFileType, ReportFileType]
    samplename: str
    distancekey: str
    path: str

class Reporting(ProcessingTask):
    _data: List[ReportingJobData]

    def __init__(self, processing: "Processing", settings: ProcessingSettings):
        self._data = []
        super().__init__(processing=processing, settings=settings)

    def _start(self):
        pass

    def rowCount(self, parent: QtCore.QModelIndex = ...) -> int:
        return len(self._data)

    def columnCount(self, parent: QtCore.QModelIndex = ...) -> int:
        return 3

    def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlag:
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemNeverHasChildren | QtCore.Qt.ItemIsSelectable

    def parent(self, child: QtCore.QModelIndex) -> QtCore.QModelIndex:
        return QtCore.QModelIndex()

    def index(self, row: int, column: int, parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex:
        return self.createIndex(row, column, None)

    def data(self, index: QtCore.QModelIndex, role: int = ...) -> Any:
        d = self._data[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if index.column() == 0:
                return d.samplename
            elif index.column() == 1:
                return d.distancekey
            elif index.column() == 2:
                return d.path
        elif (role == QtCore.Qt.DecorationRole) and (index.column() == 0):
            if isinstance(d.filetype, CurveFileType):
                return QtGui.QIcon(':/icons/saxscurve.svg')
            elif isinstance(d.filetype, PatternFileType):
                return QtGui.QIcon(':/icons/saxspattern.svg')
            elif isinstance(d.filetype, CorMatFileType):
                return QtGui.QIcon(':/icons/outliers.svg')
            elif d.filetype is ReportFileType.DOCX:
                return QtGui.QIcon.fromTheme('x-office-writer')
            elif d.filetype is ReportFileType.XLSX:
                return QtGui.QIcon.fromTheme('x-office-spreadsheet')

    def headerData(self, section: int, orientation: QtCore.Qt.Orientation, role: int = ...) -> Any:
        if (role==QtCore.Qt.DisplayRole) and (orientation == QtCore.Qt.Horizontal):
            return ['Sample name', 'Distance', 'Output path'][section]


group_dict = {}
new_list = []

import math

with open("/home/ubuntu/environment/sj_identify/output_files/tsv_files/Binary_predictable_SNPs.tsv","r") as hin:

    for line in hin:
        f = line.rstrip('\n').split('\t')
        if f[0].startswith("Group"):continue
        group_no = f[0]
        snp_id =f[1]
        Others_Intercept = f[11]
        Others_X4 = f[12]
        Others_X5 = f[13]

        snp_info = [snp_id,Others_Intercept,Others_X4,Others_X5]

        group_dict[group_no] = snp_info

with open("/home/ubuntu/environment/GTEx_file/files/GTEx_SJ_count_and_genotype_binary.txt","r") as hin:

    for line in hin:
        f = line.rstrip('\n').split('\t')
        group_no = f[0]
        GTEx_id = f[1]
        normal_SJ_count = f[2]
        abnormal_SJ_count = f[3]
        raw_genotype = f[4]

        if raw_genotype == "0/0":
            str_genotype = "Homo_Ref"

        elif raw_genotype == "1/1":
            str_genotype = "Others"

        else:
            str_genotype = "Others"

        if group_no in group_dict:
            snp_info = group_dict.get(group_no)

            snp_id = snp_info[0]
            Others_Intercept = snp_info[1]
            Others_X4 = snp_info[2]
            Others_X5 = snp_info[3]

            e = math.e

            l_Others = float(Others_Intercept) + float(Others_X4) * int(normal_SJ_count) + float(Others_X5)*int(abnormal_SJ_count)

            Others_p = math.exp(l_Others) / (1 + math.exp(l_Others))
            Homo_Ref_p = 1 / (1 + math.exp(l_Others))

            if Homo_Ref_p >- 0.5:
                prediction = "Homo_Ref"

            if Others_p >= 0.5:
                prediction = "Others"

            if prediction == str_genotype:
                result = True

            else:
                result = False

            print(snp_id + "\t" + GTEx_id  + "\t" + normal_SJ_count + "\t" + abnormal_SJ_count + "\t" + raw_genotype + "\t" + str_genotype + "\t" + str(round(Homo_Ref_p, 3)) + "\t" + str(round(Others_p, 3)) + "\t" +  prediction + "\t" + str(result))


'''Tests for GinjinnConfiguration
'''

import pkg_resources
import tempfile
import os
import pytest
import yaml
import copy

from ginjinn.ginjinn_config import GinjinnConfiguration, InvalidGinjinnConfigurationError
from ginjinn.ginjinn_config.config_error import InvalidModelConfigurationError

@pytest.fixture(scope='module', autouse=True)
def tmp_input_paths():
    tmpdir = tempfile.TemporaryDirectory()

    img_path_train = os.path.join(tmpdir.name, 'images_train')
    os.mkdir(img_path_train)
    img_path_test = os.path.join(tmpdir.name, 'images_test')
    os.mkdir(img_path_test)
    img_path_validation = os.path.join(tmpdir.name, 'images_validation')
    os.mkdir(img_path_validation)

    pvoc_ann_path_train = os.path.join(tmpdir.name, 'annotations_train')
    os.mkdir(pvoc_ann_path_train)
    pvoc_ann_path_test = os.path.join(tmpdir.name, 'annotations_test')
    os.mkdir(pvoc_ann_path_test)
    pvoc_ann_path_validation = os.path.join(tmpdir.name, 'annotations_validation')
    os.mkdir(pvoc_ann_path_validation)

    coco_ann_path_train = os.path.join(tmpdir.name, 'annotations_train.json')
    with open(coco_ann_path_train, 'w') as ann_f:
        ann_f.write('')
    coco_ann_path_test = os.path.join(tmpdir.name, 'annotations_test.json')
    with open(coco_ann_path_test, 'w') as ann_f:
        ann_f.write('')
    coco_ann_path_validation = os.path.join(tmpdir.name, 'annotations_valiation.json')
    with open(coco_ann_path_validation, 'w') as ann_f:
        ann_f.write('')

    yield {
        'coco_ann_path_train': coco_ann_path_train,
        'coco_ann_path_test': coco_ann_path_test,
        'coco_ann_path_validation': coco_ann_path_validation,
        'pvoc_ann_path_train': pvoc_ann_path_train,
        'pvoc_ann_path_test': pvoc_ann_path_test,
        'pvoc_ann_path_validation': pvoc_ann_path_validation,
        'img_path_train': img_path_train,
        'img_path_test': img_path_test,
        'img_path_validation': img_path_validation,
        'project_dir': tmpdir.name,
    }

    tmpdir.cleanup()

@pytest.fixture
def config_dicts(tmp_input_paths):
    simple_config = {
        'project_dir': tmp_input_paths['project_dir'],
        'task': 'bbox-detection',
        'input': {
            'type': 'PVOC',
            'training': {
                'annotation_path': tmp_input_paths['pvoc_ann_path_train'],
                'image_path': tmp_input_paths['img_path_train'],
            },
        },
        'model': {
            'name': 'faster_rcnn_R_50_FPN_3x',
            'weights': '',
            'model_parameters': {
                'roi_heads': {
                    'batch_size_per_image': 4096,
                    'iou_thresholds': [0.5],
                },
                'anchor_generator': {
                    'sizes': [[32, 64, 128, 256]],
                    'angles': [[-90, 0, 90]],
                    'aspect_ratios': [[0.25, 0.5, 0.75, 1.0, 1.25]]
                },
                'rpn': {
                    'iou_thresholds': [0.3, 0.7],
                    'batch_size_per_image': 256,
                },
                'box_head': {
                    'class_agnostic': False,
                    'train_on_pred_boxes': False,
                }
            },
        },
        'training': {
            'learning_rate': 0.002,
            'batch_size': 1,
            'max_iter': 10000,
        },
        'augmentation': [
            {
                'horizontal_flip': {
                    'probability': 0.25
                }
            },
            {
                'vertical_flip': {
                    'probability': 0.25
                }
            },
        ],
    }

    return [
        simple_config
    ]

@pytest.fixture
def config_file_examples():
    example_config_0_path = pkg_resources.resource_filename(
        'ginjinn', 'data/ginjinn_config/example_config_0.yaml',
    )
    example_config_1_path = pkg_resources.resource_filename(
        'ginjinn', 'data/ginjinn_config/example_config_1.yaml',
    )

    return [
        example_config_0_path,
        example_config_1_path,
    ]

def read_config_file(file_path):
    with open(file_path) as config_file:
        config = yaml.safe_load(config_file)
    return config

def test_from_dictionary_simple(config_dicts):
    simple_config_dict = config_dicts[0]

    ginjinn_config_0 = GinjinnConfiguration.from_dictionary(simple_config_dict)
    assert ginjinn_config_0.task == simple_config_dict['task'] and\
        ginjinn_config_0.project_dir == simple_config_dict['project_dir'],\
        'simple base configuration not set.'
    # TODO implement model and augmentation assertions!
    assert ginjinn_config_0.model.name == simple_config_dict['model']['name']
    assert ginjinn_config_0.training.learning_rate == simple_config_dict['training']['learning_rate']
    assert ginjinn_config_0.input.type == simple_config_dict['input']['type']

def test_from_config_file_simple(config_file_examples):
    simple_config_file_0 = config_file_examples[0]
    simple_config_dict_0 = read_config_file(simple_config_file_0)
    print(simple_config_dict_0)
    if not os.path.exists(simple_config_dict_0['input']['training']['annotation_path']):
        os.mkdir(simple_config_dict_0['input']['training']['annotation_path'])
    if not os.path.exists(simple_config_dict_0['input']['training']['image_path']):
        os.mkdir(simple_config_dict_0['input']['training']['image_path'])

    simple_config_0 = GinjinnConfiguration.from_config_file(simple_config_file_0)
    assert simple_config_0.task == simple_config_dict_0['task'] and\
        simple_config_0.project_dir == simple_config_dict_0['project_dir'] and\
        simple_config_0.input.train.annotation_path == os.path.abspath(simple_config_dict_0['input']['training']['annotation_path']) and\
        simple_config_0.input.train.image_path ==  os.path.abspath(simple_config_dict_0['input']['training']['image_path']),\
        'GinjinnConfig was not successfully constructed from simple configuration file.'

    assert simple_config_0.model.name == simple_config_dict_0['model']['name']
    assert simple_config_0.training.learning_rate == simple_config_dict_0['training']['learning_rate']

    os.rmdir(simple_config_dict_0['input']['training']['annotation_path'])
    os.rmdir(simple_config_dict_0['input']['training']['image_path'])

    simple_config_file_1 = config_file_examples[1]
    simple_config_dict_1 = read_config_file(simple_config_file_1)
    print(simple_config_dict_1)
    if not os.path.exists(simple_config_dict_1['input']['training']['annotation_path']):
        with open(simple_config_dict_1['input']['training']['annotation_path'], 'w') as f:
            f.write('')
    if not os.path.exists(simple_config_dict_1['input']['training']['image_path']):
        os.mkdir(simple_config_dict_1['input']['training']['image_path'])

    simple_config_1 = GinjinnConfiguration.from_config_file(simple_config_file_1)
    assert simple_config_1.task == simple_config_dict_1['task'] and\
        simple_config_1.project_dir == simple_config_dict_1['project_dir'] and\
        simple_config_1.input.train.annotation_path ==  os.path.abspath(simple_config_dict_1['input']['training']['annotation_path']) and\
        simple_config_1.input.train.image_path ==  os.path.abspath(simple_config_dict_1['input']['training']['image_path']),\
        'GinjinnConfig was not successfully constructed from simple configuration file.'

    assert simple_config_1.model.name == simple_config_dict_1['model']['name']
    assert simple_config_1.training.learning_rate == simple_config_dict_1['training']['learning_rate']

    os.remove(simple_config_dict_1['input']['training']['annotation_path'])
    os.rmdir(simple_config_dict_1['input']['training']['image_path'])

def test_invalid_task(config_dicts):
    simple_config_dict = copy.deepcopy(config_dicts[0])
    simple_config_dict['task'] = 'foobar'

    with pytest.raises(InvalidGinjinnConfigurationError):
        GinjinnConfiguration.from_dictionary(simple_config_dict)

def test_incompatible_task(config_dicts):
    simple_config_dict = copy.deepcopy(config_dicts[0])
    simple_config_dict['task'] = 'instance-segmentation'

    with pytest.raises(InvalidGinjinnConfigurationError):
        GinjinnConfiguration.from_dictionary(simple_config_dict)

def test_to_detectron2_config(config_dicts):
    simple_config_dict = config_dicts[0]

    ginjinn_config_0 = GinjinnConfiguration.from_dictionary(simple_config_dict)
    detectron2_config_0 = ginjinn_config_0.to_detectron2_config()

    # TODO additional tests

def test_model_parameters(config_dicts):

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['model_parameters']['invalid_parameter'] = {}
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['model_parameters']['anchor_generator']['invalid_parameter'] = 1
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['model_parameters']['rpn']['invalid_parameter'] = 1
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['model_parameters']['roi_heads']['invalid_parameter'] = 1
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['model_parameters']['box_head']['invalid_parameter'] = 1
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)

    config_dict = copy.deepcopy(config_dicts[0])
    config_dict['model']['name'] = 'mask_rcnn_R_50_C4_1x'
    config_dict['task'] = 'instance-segmentation'
    del config_dict['model']['model_parameters']['box_head']
    config_dict['model']['model_parameters']['mask_head'] = {
        'class_agnostic': False,
        'pooler_resolution': 10,
    }
    GinjinnConfiguration.from_dictionary(config_dict)

    config_dict['model']['model_parameters']['mask_head']['invalid_parameter'] = 1
    with pytest.raises(InvalidModelConfigurationError):
        GinjinnConfiguration.from_dictionary(config_dict)


import unittest
from KMPalgorithm import Solution

class RemoveDuplicatesfromSortedArrayTest(unittest.TestCase):
    def test_basic_function(self):
        temp = Solution()
        self.needle = "abcdefg"
        self.assertEqual(temp.FailureFunction(self.needle),
                         [0, 0, 0, 0, 0, 0, 0])

    def test_basic_function2(self):
        temp = Solution()
        self.needle = "abcabc"
        self.assertEqual(temp.FailureFunction(
            self.needle), [0, 0, 0, 1, 2, 3])

    def test_basic_function3(self):
        temp = Solution()
        self.needle = "abababac"
        self.assertEqual(temp.FailureFunction(
            self.needle), [0, 0, 1, 2, 3, 4, 5, 0])

    def test_basic_function4(self):
        temp = Solution()
        self.needle = "AABAACAABAA"
        self.assertEqual(temp.FailureFunction(
            self.needle), [0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5])

    def test_basic_issip(self):
        temp = Solution()
        self.needle = "issip"
        self.assertEqual(temp.FailureFunction(
            self.needle), [0, 0, 0, 1, 0])

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


from freelancersdk.session import Session
from freelancersdk.resources.users.users import get_reputations
from freelancersdk.resources.users.exceptions import \
    ReputationsNotFoundException
import os

def sample_get_reputations():
    url = os.environ.get('FLN_URL')
    oauth_token = os.environ.get('FLN_OAUTH_TOKEN')
    session = Session(oauth_token=oauth_token, url=url)

    user_ids = [3112780, 7344704]
    role = 'employer'
    reputation_details = {
        'job_history': True,
        'project_stats': True,
        'rehire_rates': True
    }

    try:
        reputations = get_reputations(session, user_ids=user_ids,
                                     role=role,
                                     reputation_details=reputation_details)
    except ReputationsNotFoundException as e:
        print('Error message: {}'.format(e.message))
        print('Server: response: {}'.format(e.error_code))
        return None
    else:
        return reputations

result = sample_get_reputations()

if result:
    print('Found reputations: {}'.format(len(result)))


import pandas as pd
import numpy as np

df = pd.read_csv("results.log")
#print(df)

confusion_matrix = np.zeros((3,3))
d = {}
d['yes'] = 0
d['no'] = 1
d['idk'] = 2

for index, row in df.iterrows():
    #print(index,row['answer'],row['studentAnswer'])
    if index <= 30:
        currentAnswer = row['answer']
        currentStudentAnswer = row['studentAnswer']
        confusion_matrix[d[currentAnswer]][d[currentStudentAnswer]] += 1

print(confusion_matrix)


from django.shortcuts import render  # , get_object_or_404, redirect
from django.conf import settings
from django.http import HttpResponse, HttpRequest
# from django.template import loader, Context, Template, RequestContext
from django.template.loader import render_to_string  # , get_template
from django.views.generic import View
# from sekizai.context import SekizaiContext
from django.views.decorators.clickjacking import xframe_options_exempt
from typing import Dict, Any, Optional

Opt = Optional

def homepage(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	template_name = "main/homepage.html"
	if settings.DEBUG is True:
		if "/" in template_name and template_name.endswith('.html'):
			filename = template_name[(template_name.find("/") + 1):len(template_name) - len(".html")] + "_flat.html"
		elif template_name.endswith('.html'):
			filename = template_name[:len(template_name) - len(".html")] + "_flat.html"
		else:
			raise ValueError("The template name could not be parsed or is in a subfolder")
		# print(filename)
		html_string = render_to_string(template_name, context, request=request)
		# print(html_string)
		filepath = "./templates_cdn/" + filename
		print(filepath)
		f = open(filepath, 'w+')
		f.write(html_string)
		f.close()
	return render(request, template_name, context)

def flatten(request: HttpRequest) -> HttpResponse:
	template_names = ["main/homepage.html", 'main/facilities.html']
	context: Dict[str, Any] = {}
	if settings.DEBUG is True:
		for template_name in template_names:
			if "/" in template_name and template_name.endswith('.html'):
				filename = template_name[(template_name.find("/") + 1):len(template_name) - len(".html")] + "_flat.html"
			elif template_name.endswith('.html'):
				filename = template_name[:len(template_name) - len(".html")] + "_flat.html"
			else:
				raise ValueError("The template name could not be parsed or is in a subfolder")
			# print(filename)
			html_string = render_to_string(template_name, context)
			# print(html_string)
			filepath = "../templates_cdn/" + filename
			# print(filepath)
			f = open(filepath, 'w+')
			f.write(html_string)
			f.close()
		return render(request, template_name, context)
	else:
		raise KeyError("Debug mode not set")

# def render_to_file(template_name, context):
	# html_string = render_to_string(template_name, context)
	# filename = template_name[:-5] + "_flat.html"
	# filename = template_name.replace('.html','_flat.html')
	# filename = template_name[:len(template_name)-len(".html")] + "_flat.html"
	# filename = template_name[:template_name.rfind(".")] + "_flat.html"
	# f = open(filename, 'w+')
	# f.write(html_string)
	# f.close()

# def webPageToText(url):
# 	import urllib2
# 	response = urllib2.urlopen(url)
# 	html = response.read()
# 	text = stripTags(html).lower()
# 	return text

def facilities(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	return render(request, 'main/facilities.html', context)

@xframe_options_exempt
def projects(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	return render(request, 'main/projects.html', context)

def actinide_water_abs(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	return render(request, 'distinctive/_slides_base.html', context)

def publications(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	return render(request, 'main/publications.html', context)

def atoms(request: HttpRequest) -> HttpResponse:
	context: Dict[str, Any] = {}
	return render(request, 'animated_atoms.html', context)

def contact(request: HttpRequest) -> HttpResponse:
	# form = ContactForm(request.POST or None)
	# if form.is_valid():
	# 	form_name = form.cleaned_data.get('name')
	# 	form_email = form.cleaned_data.get('email')
	# 	form_message = form.cleaned_data.get('message')
	#
	# 	subject = 'Site contact form'
	# 	from_email = settings.EMAIL_HOST_USER
	# 	to_email = [from_email, 'other@email.com']
	# 	contact_message = "%s: %s via %s"%(form_name, form_message, form_email)
	# 	send_mail(subject, contact_message, from_email, to_email, fail_silently=False)
	# context = {'form':form,}
	map_api_key = settings.GOOGLEMAP_KEY
	context: Dict[str, Any] = {'map_api_key': map_api_key}
	return render(request, 'main/contact.html', context)

# @login_required
# def django_admin_page(request):
# 	return render(request, 'main/admin')


'''
 @licence
 Copyright (c) 2017-2020 SKKU ESLAB, and contributors. All rights reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
 limitations under the License.
'''

try:
    import antresource as ResourceAPI
    import json
except ModuleNotFoundError as e:
    raise ModuleNotFoundError(
        'Remote UI API Dependency Error: not found Resource API')

class ANTRemoteUI:
    def __init__(self):
        pass

    def setStreamingViewPipeline(self, pipeline, handler):
        ResourceAPI.requestPost(
            '/remoteui/streamingview/pipeline',
            pipeline,
            handler
        )

    def setStreamingViewLabelText(self, labelText, handler):
        ResourceAPI.requestPost(
            '/remoteui/streamingview/labelText',
            labelText,
            handler
        )

    def setStreamingViewBoundingBoxes(self, boundingBoxes, handler):
        boundingBoxesJSON = json.loads(boundingBoxes)
        ResourceAPI.requestPost(
            '/remoteui/streamingview/boundingBoxes',
            boundingBoxesJSON,
            handler
        )


import logging
import unittest
from typing import Hashable, List, Tuple

import numpy as np

from reach import Reach

logger = logging.getLogger(__name__)

class TestVectorize(unittest.TestCase):
    def data(self) -> Tuple[List[Hashable], np.ndarray]:
        words: List[Hashable] = [
            "donatello",
            "leonardo",
            "raphael",
            "michelangelo",
            "splinter",
            "hideout",
        ]
        random_generator = np.random.RandomState(seed=44)
        vectors = random_generator.standard_normal((6, 50))

        return words, vectors

    def test_vectorize_no_unk(self) -> None:
        words, vectors = self.data()
        reach = Reach(vectors, words)

        with self.assertRaises(ValueError):
            reach.vectorize(("donatello", "abcd"), remove_oov=False)

        with self.assertRaises(ValueError):
            reach.vectorize([])

        with self.assertRaises(ValueError):
            reach.vectorize("")

        vec = reach.vectorize(("donatello", "abcd"), remove_oov=True)
        self.assertEqual(len(vec), 1)
        self.assertTrue(np.allclose(vec, reach["donatello"]))

    def test_vectorize_unk(self) -> None:
        words, vectors = self.data()
        words.append("<UNK>")
        vectors = np.concatenate([vectors, np.zeros((1, vectors.shape[1]))])
        reach = Reach(vectors, words, unk_index=len(words) - 1)

        self.assertEqual(reach.indices[reach.unk_index], "<UNK>")  # type: ignore
        self.assertTrue(np.allclose(vectors[-1], np.zeros(reach.size)))

    def test_bow_no_unk(self) -> None:
        words, vectors = self.data()
        reach = Reach(vectors, words)

        bow = reach.bow(["donatello", "leonardo", "michelangelo"])
        self.assertEqual(bow, [0, 1, 3])

        bow = reach.bow(["donatello", "leonardo", "rgieurghegh"], remove_oov=True)
        self.assertEqual(bow, [0, 1])

        with self.assertRaises(ValueError):
            bow = reach.bow(["donatello", "wroughwuorg"], remove_oov=False)

        with self.assertRaises(ValueError):
            bow = reach.bow("")

    def test_bow_unk(self) -> None:
        words, vectors = self.data()
        words.append("<UNK>")
        vectors = np.concatenate([vectors, np.zeros((1, vectors.shape[1]))])
        reach = Reach(vectors, words, unk_index=len(words) - 1)

        bow = reach.bow(["donatello", "leonardo", "rgieurghegh"])
        self.assertEqual(bow, [0, 1, reach.unk_index])

        bow = reach.bow(["donatello", "leonardo", "rgieurghegh"], remove_oov=True)
        self.assertEqual(bow, [0, 1])

    def test_transform(self) -> None:
        words, vectors = self.data()
        reach = Reach(vectors, words)

        with self.assertRaises(ValueError):
            reach.transform([["donatello", "raphael"], ["dog"], ["clown", "donatello"]])

        matrices = reach.transform(
            [["donatello", "raphael"], ["donatello", "splinter"]]
        )

        expected = [
            np.stack([reach["donatello"], reach["raphael"]]),
            np.stack([reach["donatello"], reach["splinter"]]),
        ]
        for matrix, exp_matrix in zip(matrices, expected):
            self.assertTrue(np.allclose(matrix, exp_matrix))

        matrices = reach.transform(
            [["donatello", "raphael"], ["rqghqgr", "splinter"]], remove_oov=True
        )

        expected = [
            np.stack([reach["donatello"], reach["raphael"]]),
            np.stack([reach["splinter"]]),
        ]
        for matrix, exp_matrix in zip(matrices, expected):
            self.assertTrue(np.allclose(matrix, exp_matrix))

        with self.assertRaises(ValueError):
            reach.transform([[]])

        empty_result = reach.transform([])
        self.assertEqual(empty_result, [])

    def test_mean_pool(self) -> None:
        words, vectors = self.data()
        reach = Reach(vectors, words)

        with self.assertRaises(ValueError):
            reach.mean_pool(["donatello", "dog"])

        vec = reach.mean_pool(["donatello", "dog"], safeguard=False)
        self.assertTrue(np.allclose(vec, np.zeros_like(vec)))

        vec = reach.mean_pool(["donatello", "dog"], remove_oov=True)
        self.assertTrue(np.allclose(vec, reach["donatello"]))

    def test_mean_pool_unk(self) -> None:
        words, vectors = self.data()
        words.append("<UNK>")
        vectors = np.concatenate([vectors, np.zeros((1, vectors.shape[1]))])
        reach = Reach(vectors, words, unk_index=len(words) - 1)

        vec = reach.mean_pool(["donatello", "dog"])
        self.assertTrue(np.allclose(vec, reach["donatello"] / 2))

        vec = reach.mean_pool(["donatello", "dog"], safeguard=True)
        self.assertTrue(np.allclose(vec, reach["donatello"] / 2))

        vec = reach.mean_pool(["donatello", "dog"], remove_oov=True)
        self.assertTrue(np.allclose(vec, reach["donatello"]))

        vec = reach.mean_pool([], safeguard=False)
        self.assertTrue(np.allclose(vec, np.zeros_like(vec)))

        with self.assertRaises(ValueError):
            reach.mean_pool_corpus([[], ["dog"], ["guogrwohu"]], safeguard=True)

        matrix = reach.mean_pool_corpus([[], ["dog"], ["guogrwohu"]], safeguard=False)
        self.assertTrue(np.allclose(matrix, np.zeros_like(matrix)))


from logging_python import logger
import boto3
import get_labels
from handlers import prepare_labels_strip_navigation
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')

def prepare_response_object_from_appstore_files(file_data, topics):
    response = []
    labels = []

    for i, review in enumerate(file_data, start=1):
            REVIEW_OBJECT = {
                "id": "",
                "text": "",
                "title": "",
                "location": "",
                "url": "",
                "labels": "",
                "sentiment": "",
                "rating": "",
                "highlightText" : "",
                "source": "appstore"
            }
            # REVIEW_OBJECT["id"] = str(i)
            REVIEW_OBJECT["title"] = review["title"]
            REVIEW_OBJECT["text"] = review["review"]
            REVIEW_OBJECT["location"] = ""
            REVIEW_OBJECT["created_at"] = review["date"]
            REVIEW_OBJECT["labels"] = [get_labels.review_to_topic(str(review["review"]), topics)]
            REVIEW_OBJECT["highlightText"]= get_labels.review_to_highlight(str(review["review"]))
            REVIEW_OBJECT["suggestionText"] = get_labels.review_to_suggestion(str(review["review"]))
            REVIEW_OBJECT["labels"].append("appstore")
            REVIEW_OBJECT["labels"].append( str(review["rating"]))
            REVIEW_OBJECT["rating"] = str(review["rating"])
            REVIEW_OBJECT["url"] = ""

            labels.extend(REVIEW_OBJECT["labels"])
            response.append(REVIEW_OBJECT)

    labels_strip = prepare_labels_strip_navigation(labels)

    return response, labels_strip

def get_data_from_db_processed(TableName, topics):

    logger.info("connecting to db")
    table = dynamodb.Table(TableName)
    # response = table.scan(ProjectionExpression="review, rating")
    response = table.scan()

    # print(response['Items'])
    resp = prepare_response_object_from_appstore_files(response['Items'], topics)
    return resp

if __name__ == '__main__':
    TableName = "appstore_wise"
    json_response = get_data_from_db_processed(TableName)


import sqlite3
from sqlite3 import Error
from sqlite3.dbapi2 import sqlite_version
import os
import sys
db_file = 'finnish_wind_power_orig.db'

def create_connection():
    """
    create a connection to a db file and then close it
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        print(sqlite_version)
    except Error as e:
        print(e)
    finally:
        if conn:
            return conn

if __name__ == "__main__":
    create_connection('finnish_wind_power_orig.db')


from builtins import str
from builtins import object
import re
import json
from buildtimetrend import logger
from buildtimetrend import tools
from buildtimetrend.buildjob import BuildJob
from buildtimetrend.collection import Collection
from buildtimetrend.travis.connector import TravisOrgConnector
from buildtimetrend.travis.connector import TravisConnector
from buildtimetrend.travis.substage import TravisSubstage
try:
    # For Python 3.0 and later
    from urllib.error import HTTPError, URLError
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import HTTPError, URLError

# strings to parse timestamps in Travis CI log file
TRAVIS_LOG_PARSE_TIMING_STRINGS = [
    r'travis_time:end:(?P<end_hash>.*):start=(?P<start_timestamp>\d+),'
    r'finish=(?P<finish_timestamp>\d+),duration=(?P<duration>\d+)\x0d\x1b',
    r'travis_fold:end:(?P<end_stage>\w+)\.(?P<end_substage>\d+)\x0d\x1b',
    r'travis_fold:start:(?P<start_stage>\w+)\.(?P<start_substage>\d+)\x0d\x1b',
    r'travis_time:start:(?P<start_hash>.*)\x0d\x1b\[0K',
    r'\$\ (?P<command>.*)\r',
]
TRAVIS_LOG_PARSE_WORKER_STRING = r'Using worker:\ (?P<hostname>.*):(?P<os>.*)'

class TravisData(object):

    """Gather data from Travis CI using the API."""

    def __init__(self, repo, build_id, connector=None):
        """
        Retrieve Travis CI build data using the API.

        Parameters:
        - repo : github repository slug (fe. buildtimetrend/python-lib)
        - build_id : Travis CI build id (fe. 158)
        - connector : Travis Connector instance
        """
        self.builds_data = {}
        self.build_jobs = {}
        self.current_build_data = {}
        self.current_job = BuildJob()
        self.travis_substage = None
        self.repo = repo
        self.build_id = str(build_id)
        # set TravisConnector if it is defined
        if isinstance(connector, TravisConnector):
            self.connector = connector
        # use Travis Org connector by default
        else:
            self.connector = TravisOrgConnector()

    def get_build_data(self):
        """
        Retrieve Travis CI build data.

        Returns true if retrieving data was succesful, false on error.
        """
        request = 'repos/{repo}/builds?number={build_id}'.format(
            repo=self.repo, build_id=self.build_id
        )
        try:
            self.builds_data = self.connector.json_request(request)
        except (HTTPError, URLError) as msg:
            logger.error("Error getting build data from Travis CI: %s", msg)
            return False

        # log builds_data
        logger.debug(
            "Build #%s data : %s",
            str(self.build_id),
            json.dumps(self.builds_data, sort_keys=True, indent=2)
        )

        return True

    def get_substage_name(self, command):
        """
        Resolve Travis CI substage name that corresponds to a cli command.

        Parameters:
        - command : cli command
        """
        if not tools.is_string(command):
            return ""

        if len(self.current_build_data) > 0 and \
                "config" in self.current_build_data:
            build_config = self.current_build_data["config"]
        else:
            logger.warning(
                "Travis CI build config is not set"
            )
            return ""

        # check if build_config collection is empty
        if build_config:
            for stage_name, commands in build_config.items():
                if tools.is_list(commands) and command in commands:
                    substage_number = commands.index(command) + 1
                    substage_name = "{stage}.{substage:d}".format(
                        stage=stage_name, substage=substage_number
                    )
                    logger.debug(
                        "Substage %s corresponds to '%s'",
                        substage_name, command
                    )
                    return substage_name

        return ""

    def process_build_jobs(self):
        """
        Retrieve Travis CI build job data.

        Method is a generator, iterate result to get each processed build job.
        """
        if len(self.builds_data) > 0 and "builds" in self.builds_data:
            for build in self.builds_data['builds']:
                self.current_build_data = build

                if "job_ids" in build:
                    for job_id in build['job_ids']:
                        yield self.process_build_job(job_id)

            # reset current_build_data after builds are processed
            self.current_build_data = {}

    def process_build_job(self, job_id):
        """
        Retrieve Travis CI build job data.

        Parameters:
        - job_id : ID of the job to process
        """
        if job_id is None:
            return None

        # retrieve job data from Travis CI
        job_data = self.get_job_data(job_id)
        # process build/job data
        self.process_job_data(job_data)
        # parse Travis CI job log file
        self.parse_job_log(job_id)

        # store build job
        self.build_jobs[str(job_id)] = self.current_job
        # create new build job instance
        self.current_job = BuildJob()

        # return processed build job
        return self.build_jobs[str(job_id)]

    def get_job_data(self, job_id):
        """
        Retrieve Travis CI job data.

        Parameters:
        - job_id : ID of the job to process
        """
        request = 'jobs/{:s}'.format(str(job_id))
        job_data = self.connector.json_request(request)

        # log job_data
        logger.debug(
            "Job #%s data : %s",
            str(job_id),
            json.dumps(job_data, sort_keys=True, indent=2)
        )

        return job_data

    def process_job_data(self, job_data):
        """
        Process Job/build data.

        Set build/job properties :
        - Build/job ID
        - build result : passed, failed, errored
        - git repo
        - git branch
        - CI platform : Travis
        - build matrix (language, language version, compiler, ...)
        - build_trigger : push, pull_request
        - pull_request (is_pull_request, title, number)

        Parameters:
        - job_data : dictionary with Travis CI job data
        """
        self.current_job.add_property(
            "build",
            # buildnumber is part before "." of job number
            job_data['job']['number'].split(".")[0]
        )
        self.current_job.add_property("job", job_data['job']['number'])
        self.current_job.add_property("branch", job_data['commit']['branch'])
        self.current_job.add_property(
            "repo",
            job_data['job']['repository_slug']
        )
        self.current_job.add_property("ci_platform", 'travis')
        self.current_job.add_property("result", job_data['job']['state'])

        self.set_build_matrix(job_data)

        self.process_pull_request_data()

        self.current_job.set_started_at(job_data['job']['started_at'])
        self.current_job.set_finished_at(job_data['job']['finished_at'])

        # calculate job duration from start and finished timestamps
        # if no timing tags are available
        if not self.has_timing_tags():
            self.current_job.add_property("duration", self.get_job_duration())

    def set_build_matrix(self, job_data):
        """
        Retrieve build matrix data from job data and store in properties.

        Properties :
        - language
        - language version (if applicable)
        - compiler (if applicable)
        - operating system
        - environment parameters

        Parameters:
        - job_data : dictionary with Travis CI job data
        """
        # check if job config data exists
        if 'job' not in job_data or 'config' not in job_data['job']:
            logger.warning("Job config data doesn't exist")
            return

        build_matrix = Collection()
        job_config = job_data['job']['config']

        if 'language' in job_config:
            language = job_config['language']
            build_matrix.add_item('language', language)

            # set language version
            # ('d', 'dart', 'go', 'perl', 'php', 'python', 'rust')
            if language in job_config:
                if language == 'android':
                    build_matrix.add_item(
                        "language_components",
                        " ".join(job_config[language]["components"])
                    )
                else:
                    build_matrix.add_item(
                        'language_version',
                        str(job_config[language])
                    )

        # language specific build matrix parameters
        parameters = {
            'ghc': 'ghc',  # Haskell
            'jdk': 'jdk',  # Java, Android, Groovy, Ruby, Scala
            'lein': 'lein',  # Clojure
            'mono': 'mono',  # C#, F#, Visual Basic
            'node_js': 'node_js',  # Javascript
            'otp_release': 'otp_release',  # Erlang
            'rvm': 'rvm',  # Ruby, Objective-C
            'gemfile': 'gemfile',  # Ruby, Objective-C
            'xcode_sdk': 'xcode_sdk',  # Objective-C
            'xcode_scheme': 'xcode_scheme',  # Objective-C
            'compiler': 'compiler',  # C, C++
            'os': 'os',
            'env': 'parameters'
        }
        for parameter, name in parameters.items():
            if parameter in job_config:
                build_matrix.add_item(name, str(job_config[parameter]))

        self.current_job.add_property(
            "build_matrix",
            build_matrix.get_items_with_summary()
        )

    def process_pull_request_data(self):
        """Retrieve pull request data from Travis CI API."""
        # check if collection is empty
        if self.current_build_data:
            if "event_type" in self.current_build_data:
                # build trigger (push or pull_request)
                self.current_job.add_property(
                    "build_trigger",
                    self.current_build_data["event_type"]
                )

            # pull_request
            pull_request_data = {}
            if "pull_request" in self.current_build_data:
                pull_request_data["is_pull_request"] = \
                    self.current_build_data["pull_request"]
            else:
                pull_request_data["is_pull_request"] = False

            if "pull_request_title" in self.current_build_data:
                pull_request_data["title"] = \
                    self.current_build_data["pull_request_title"]

            if "pull_request_number" in self.current_build_data:
                pull_request_data["number"] = \
                    self.current_build_data["pull_request_number"]

            self.current_job.add_property("pull_request", pull_request_data)

    def parse_job_log(self, job_id):
        """
        Parse Travis CI job log.

        Parameters:
        - job_id : ID of the job to process
        """
        self.parse_job_log_stream(self.connector.download_job_log(job_id))

    def parse_job_log_file(self, filename):
        """
        Open a Travis CI log file and parse it.

        Parameters :
        - filename : filename of Travis CI log
        Returns false if file doesn't exist, true if it was read successfully.
        """
        # load timestamps file
        if not tools.check_file(filename):
            return False

        # read timestamps, calculate stage duration
        with open(filename, 'rb') as file_stream:
            self.parse_job_log_stream(file_stream)

        return True

    def parse_job_log_stream(self, stream):
        """
        Parse Travis CI job log stream.

        Parameters:
        - stream : stream of job log file
        """
        self.travis_substage = TravisSubstage()
        check_timing_tags = self.has_timing_tags()

        for line in stream:
            # convert to str if line is bytes type
            if isinstance(line, bytes):
                line = line.decode('utf-8')
            # parse Travis CI timing tags
            if check_timing_tags and 'travis_' in line:
                self.parse_travis_time_tag(line)
            # parse Travis CI worker tag
            if 'Using worker:' in line:
                self.parse_travis_worker_tag(line)

    def parse_travis_time_tag(self, line):
        """
        Parse and process Travis CI timing tags.

        Parameters:
        - line : line from logfile containing Travis CI tags
        """
        if self.travis_substage is None:
            self.travis_substage = TravisSubstage()

        escaped_line = line.replace('\x0d', '*').replace('\x1b', 'ESC')
        logger.debug('line : %s', escaped_line)

        # parse Travis CI timing tags
        for parse_string in TRAVIS_LOG_PARSE_TIMING_STRINGS:
            result = re.search(parse_string, line)
            if result:
                self.travis_substage.process_parsed_tags(result.groupdict())

                # when finished : log stage and create a new instance
                if self.travis_substage.has_finished():
                    # set substage name, if it is not set
                    if not self.travis_substage.has_name() and \
                            self.travis_substage.has_command():
                        self.travis_substage.set_name(
                            self.get_substage_name(
                                self.travis_substage.get_command()
                            )
                        )

                    # only log complete substages
                    if not self.travis_substage.finished_incomplete:
                        self.current_job.add_stage(self.travis_substage.stage)
                    self.travis_substage = TravisSubstage()

    def parse_travis_worker_tag(self, line):
        """
        Parse and process Travis CI worker tag.

        Parameters:
        - line : line from logfile containing Travis CI tags
        """
        logger.debug('line : %s', line)

        # parse Travis CI worker tags
        result = re.search(TRAVIS_LOG_PARSE_WORKER_STRING, line)
        if not result:
            return

        worker_tags = result.groupdict()

        # check if parameter worker_tags is a dictionary and
        # if it contains all required tags
        tag_list = list({'hostname', 'os'})
        if tools.check_dict(worker_tags, "worker_tags", tag_list):
            logger.debug("Worker tags : %s", worker_tags)
            self.current_job.add_property("worker", worker_tags)

    def has_timing_tags(self):
        """
        Check if Travis CI job log has timing tags.

        Timing tags were introduced on Travis CI starting 2014-08-07,
        check if started_at is more recent.
        """
        started_at = self.current_job.get_property("started_at")
        if started_at is None or "timestamp_seconds" not in started_at:
            return False

        # 1407369600 is epoch timestamp of 2014-08-07T00:00:00Z
        return started_at["timestamp_seconds"] > 1407369600

    def get_job_duration(self):
        """Calculate build job duration."""
        started_at = self.current_job.get_property("started_at")
        finished_at = self.current_job.get_property("finished_at")
        if started_at is None or "timestamp_seconds" not in started_at or \
                finished_at is None or "timestamp_seconds" not in finished_at:
            return 0.0

        timestamp_start = float(started_at["timestamp_seconds"])
        timestamp_end = float(finished_at["timestamp_seconds"])
        return timestamp_end - timestamp_start

    def get_started_at(self):
        """Retrieve timestamp when build was started."""
        if tools.check_dict(self.current_build_data, key_list=["started_at"]):
            return self.current_build_data['started_at']
        else:
            return None

    def get_finished_at(self):
        """Retrieve timestamp when build finished."""
        if tools.check_dict(self.current_build_data, key_list=["finished_at"]):
            return self.current_build_data['finished_at']
        else:
            return None


from __future__ import print_function

import pp
import logging
import sys
import argparse
import glob
import os

def run_task( benchmark, command, domain, instance, folder, timeout ) :
    import benchmark
    import os
    import json

    current_dir = os.getcwd()
    os.chdir( folder )
    log = 'trace.log'
    rv, time = benchmark.run( command, timeout, 4096, benchmark.Log(log) )
    command_info = {}
    command_info['exit_code'] = rv
    command_info['wall_time'] = time

    if rv == 0 :
        json_search_data = 'search.json'
        if os.path.exists( json_search_data ) :
            with open( json_search_data ) as input :
                try :
                    s = input.read()
                    data = json.loads( s )
                except ValueError as e:
                    print( e )
                    print( "Read from file:")
                    print( s )
                    os.chdir( current_dir )
                    return
                for k, v in data.items() :
                    command_info[k] = v
        else :
            print("No json data payload found!")

    os.chdir( current_dir )
    data_folder = 'data'
    data_folder = os.path.join( data_folder, domain )
    if not os.path.exists( data_folder ) :
        os.makedirs(data_folder)

    info_filename  = os.path.join(data_folder,'{0}.json'.format(instance))
    if not os.path.exists( info_filename ) :
        info = {}
        info['domain'] = domain
        info['instance'] = instance
        info['planners_data'] = {}
    else :
        with open( info_filename ) as instream :
            info = json.loads( instream.read() )
    info['planners_data'][command] = command_info

    with open ( info_filename, 'w' ) as outstream:
        payload = json.dumps( info, separators=(',',':'), indent=4, sort_keys = True)
        outstream.write( payload )

    return payload

def main() :

    parser = argparse.ArgumentParser( description = "Driver script for running planner(s) over benchmarks")
    parser.add_argument( '--benchmark', required=True, help='Path to benchmarks')
    parser.add_argument( '--domain', required=False, help='Name of domain to be tested')
    parser.add_argument( '--timeout', required=False, help='Planner time out (defaults to 1800 secs)')
    parser.add_argument( '--cpus', required=False, help='Number of cpus to be used (defaults to 2)')
    parser.add_argument( '--secret', required=True, help='Server password')
    parser.add_argument( '--planner', required=True, help='Command used to invoke the planner')

    args = parser.parse_args()

    if not os.path.exists( args.benchmark ) :
        print ( 'Could not find directory {0}'.format(args.benchmark), file=sys.stderr )
        sys.exit(1)

    if args.timeout is None :
        args.timeout = 1800

    print(args.planner)

    tasks = []
    if args.domain is not None :
        domain_dirs = [ os.path.join( args.benchmark, args.domain ) ]
    else :
        domain_dirs = glob.glob( os.path.join( args.benchmark, '*'))
        domain_dirs = [ dom for dom in domain_dirs if os.path.isdir(dom) ]

    for domain_dir in domain_dirs :
        if not os.path.exists( domain_dir ) :
            print( 'Could not find domain directory {0}'.format( domain_dir ), file=sys.stderr)
            sys.exit(1)
        instances = glob.glob( os.path.join( domain_dir, '*') )
        instances = [ inst for inst in instances if os.path.isdir( inst ) ]
        for inst in instances :
            tasks.append( (os.path.basename(args.benchmark), args.planner, os.path.basename(domain_dir), os.path.basename(inst), inst, args.timeout) )
    if args.cpus is None :
        num_cpus = 2
    else :
        num_cpus = int(args.cpus)
    ppservers = ()
    job_server = pp.Server( num_cpus, ppservers=ppservers, socket_timeout=2, secret=args.secret)
    print ('Tasks to be executed: {0}'.format(len(tasks)))
    jobs = [  (task, job_server.submit( run_task, (task), (), ())) for task in tasks ]

    for input, job in jobs :
        print( 'Output of {0} is {1}'.format( input, job() ) )

    job_server.print_stats()

if __name__ == '__main__' :
    main()


"""
Esercizi con il while loop

"""

"""
Calcolo radice quadrata di un numero

x = 4
a = 6

while True:
    print(x)
    y = (x + a/x) / 2
    if y == x:
        break
    x = y

"""

numero_balli = int(input('Quanti balli vuoi fare?'))

"""
Contatore balli con condizione a inizio ciclo

while numero_balli > 0:
    print('Sta per cominciare il prossimo ballo')
    numero_balli = numero_balli - 1

print('Hai terminato la sessione di ballo')

Contatore balli con condizione all'interno del ciclo

"""

while True:
    print('Sta per iniziare il tuo prossimo ballo')
    numero_balli = numero_balli - 1
    if numero_balli == 0:
        break

print('Hai terminato la sessione di ballo')


#
# @lc app=leetcode.cn id=1930 lang=python3
#
# [1930] 长度为 3 的不同回文子序列

#遍历字符串用字典存储不同字符第一次和最后一次出现位置，记为i, j，然后用集合判断s(i, j)不同字符数目
# @lc code=start
class Solution:
    def countPalindromicSubsequence(self, s: str) -> int:
        d = dict()
        for i in range(len(s)):
            if s[i] not in d:
                d[s[i]] = [i, 0 ]
            else:
                d[s[i]][1] = i
        res = 0
        for values in d.values():
            start, end = values
            res += len(set(s[start + 1:end]))
        return res
# @lc code=end

1930.长度为-3-的不同回文子序列.py

1930.长度为-3-的不同回文子序列.py


from project.customer import Customer
from project.dvd import DVD

class MovieWorld:
    def __init__(self, name):
        self.name = name
        self.customers = []
        self.dvds = []

    @staticmethod
    def dvd_capacity():
        return 15

    @staticmethod
    def customer_capacity():
        return 10

    def add_customer(self, customer: Customer):
        if len(self.customers) < self.customer_capacity():
            self.customers.append(customer)

    def add_dvd(self, dvd: DVD):
        if len(self.dvds) < self.dvd_capacity():
            self.dvds.append(dvd)

    def rent_dvd(self, customer_id, dvd_id):
        for r in self.customers:
            if r.id == customer_id:
                for d in r.rented_dvds:
                    if d.id == dvd_id:
                        return f"{r.name} has already rented {d.name}"

                for disk in self.dvds:
                    if disk.id == dvd_id:
                        if disk.is_rented:
                            return "DVD is already rented"
                        if r.age >= disk.age_restriction:
                            r.rented_dvds.append(disk)
                            disk.is_rented = True
                            return f"{r.name} has successfully rented {disk.name}"
                        else:
                            return f"{r.name} should be at least {disk.age_restriction} to rent this " \
                                   f"movie"

    def return_dvd(self, customer_id, dvd_id):
        for r in self.customers:
            if r.id == customer_id:
                for d in r.rented_dvds:
                    if d.id == dvd_id:
                        r.rented_dvds.remove(d)
                        d.is_rented = False
                        return f"{r.name} has successfully returned {d.name}"
                return f"{r.name} does not have that DVD"

    def __repr__(self):
        return '\n'.join([repr(x) for x in self.customers]) + '\n' + '\n'.join([repr(x) for x in self.dvds])

SoftUni/Python OOP - Exercises/static_and_class_methods_exercise/movie_world_02/project/movie_world.py


#
# File: lorenzattractor_test.py
#
import torch
from ceem.systems.lorenzattractor import LorenzAttractor

def test_jacobians():
    sigma = torch.tensor([10.])
    rho = torch.tensor([28.])
    beta = torch.tensor([8. / 3.])
    B = 2
    T = 2
    n = 3

    C = torch.randn(2, 3)

    csys = LorenzAttractor(sigma, rho, beta, C, 0.1)
    theta_keys = [k for k, v in csys.named_parameters()]
    x = torch.randn(B, T, n)

    # jac_dyn_theta = csys.jac_dyn_theta(None, x, None)
    # # Test keys length and names
    # assert len(theta_keys) == len(jac_dyn_theta.keys())
    # assert (list(theta_keys) == list(jac_dyn_theta.keys()))

    # for k, v in csys.named_parameters():
    #     assert jac_dyn_theta[k].shape == (B, T, n, 1)

    jac_obs_theta = csys.jac_obs_theta(None, x, None)
    # Test keys length and names
    assert len(theta_keys) == len(jac_obs_theta.keys())
    assert (list(theta_keys) == list(jac_obs_theta.keys()))

    for v in jac_obs_theta.values():
        assert v is None


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

import requests
import json
import xmltodict

"""
amount（） src - currency（）dest - currency（）reference - date（）the output of 2 parameters
amount（） currency（）
"""
def currency_exchange(amount=100, currency='USD', dest_currency='JPY', reference_date='2020-03-03'):
    content = requests.get('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml', timeout=30).content
    ceDict = {}
    for d in xmltodict.parse(content)["gesmes:Envelope"]["Cube"]["Cube"]:
        ceDict[d['@time']] = dict([(dd["@currency"], dd["@rate"]) for dd in d['Cube']])

    a = ceDict.get(reference_date, {}).get(currency.upper())
    b = ceDict.get(reference_date, {}).get(dest_currency.upper())
    if a and b:
        amount2 = round(amount * float(a) / float(b), 4)
        print(u"dest-amount: %s, dest-currency: %s, rate: %s -> %s" % (amount2, dest_currency, a, b))
        return amount2, dest_currency
    else:
        print(u"wrong parameter\n%s" % json.dumps(ceDict, indent=4, ensure_ascii=False))

currency_exchange(dest_currency='bgn')


"""More detailed and complicated unit properties"""

from model.unit import Unit

from typing import Optional
from debug_interface import DebugInterface
from debugging.color import Color

from strategy.float import equal_float, lt_float, le_float
from strategy.geometry import Vec, Line, Segment, Circle

class UnitAdv:
    """Unit and its properties"""

    unit: Unit
    weapons: dict
    ticks_per_seconds: float
    max_unit_forward_speed: float
    max_unit_backward_speed: float
    unit_acceleration: float
    speed_limit_circle: Circle
    acceleration_limit_circle: Circle

    def __init__(self, unit: Unit, weapons: dict, max_unit_forward_speed: float, max_unit_backward_speed: float,
                 unit_acceleration: float, ticks_per_seconds: float):
        self.ticks_per_seconds = ticks_per_seconds
        """Ticks per seconds"""
        self.unit = unit
        """Unit itself"""

        self.velocity = (Vec() + self.unit.velocity) / self.ticks_per_seconds
        max_unit_forward_speed /= self.ticks_per_seconds
        max_unit_backward_speed /= self.ticks_per_seconds
        unit_acceleration /= self.ticks_per_seconds

        self.weapons = weapons
        """Available weapons"""

        self.max_unit_forward_speed = max_unit_forward_speed * (
                1 - (1 - weapons[
                    self.unit.weapon].aim_movement_speed_modifier) * self.unit.aim)
        """Maximal unit forward speed at this moment"""

        self.max_unit_backward_speed = max_unit_backward_speed * (
                1 - (1 - weapons[
                    self.unit.weapon].aim_movement_speed_modifier) * self.unit.aim)
        """Maximal unit backward speed at this moment"""

        self.unit_acceleration = unit_acceleration
        """Unit acceleration"""

        self.speed_limit_circle = Circle(
            (Vec() + self.unit.direction) * (
                    (self.max_unit_forward_speed - self.max_unit_backward_speed) / 2) + self.unit.position,
            (self.max_unit_forward_speed + self.max_unit_backward_speed) / 2)
        """Speed limit circle, it limits target speed"""

        self.acceleration_limit_circle = Circle(
            Vec() + self.velocity + self.unit.position,
            self.unit_acceleration / 30)
        """Limit of next speed"""

    def move_to_position(self, position: Vec, debug: Optional[DebugInterface]) -> Vec:
        """Returns velocity vector to move in several steps to 'position'"""

        vec_unit_position = position - self.unit.position
        """Vector from unit.position to 'position'"""

        # if debug is not None:
        #     debug.add_segment(self.unit.position, position, 0.5, Color(0.5, 0.5, 1, 1))

        if position in self.acceleration_limit_circle:
            """'position' in acceleration_limit_circle that means TargetVector equals vec_unit_to_position"""

            if debug is not None:
                print("First_move_to")

            return vec_unit_position

        if position in self.speed_limit_circle:
            """'position' in speed_limit_circle that means TargetVector equals
                vector from unit.position to point(acceleration_limit_circle ⋂ 'position')"""

            intersection_acceleration_position = \
                self.acceleration_limit_circle.intersection_with_segment(position=position)[0]
            """Intersection acceleration_limit_circle with
                vector form acceleration_limit_circle.centre_pos to 'position'"""

            if debug is not None:

                print("Second_move_to")

            return intersection_acceleration_position - self.unit.position

        """'position' is out of any of circles that means TargetVector equals some vector.. beginning at unit.position
            and ending at some point on acceleration_limit_circle..."""

        intersection_speed_circle_vec_unit_position = \
            self.speed_limit_circle.intersection_with_segment(position=position)[0]
        """Intersection of speed_limit_circle and vec_unit_position"""

        intersection_acceleration_previous_intersection = \
            self.acceleration_limit_circle.intersection_with_segment(
                position=intersection_speed_circle_vec_unit_position)[0]
        """Intersection of acceleration_limit_circle and intersection_speed_circle_vec_unit_position"""

        if debug is not None:
            print("Third_move_to")

        if intersection_acceleration_previous_intersection is not None:
            return intersection_acceleration_previous_intersection - self.unit.position
        print("NONENONENONENONENONENONENONENONENONENONENONENONENONENONENONENONENONE")
        return Vec() + self.unit.position

    def turn_to_position(self, position: Vec) -> Vec:
        """Returns direction(vector of length 1) to turn in several steps
            centre of view_field in the direction of the position"""

        new_direction = position - self.unit.position
        """New vector direction(any length)"""

        if new_direction != Vec() and lt_float(new_direction.len, 0.6):
            """Checking and recounting vector length that it follows the rules"""
            new_direction *= (1 / new_direction.len)

        return new_direction


"""
    b tree
    ~~~~~~~
    query b_tree：
        high
        max root

    add by
        feikong
        0908
"""
from data_struct.B_Tree.dynamic_b_tree import create

class BTree(object):
    def __init__(self, value=None, left_node=None, right_node=None):
        self.left_node = left_node
        self.right_node = right_node
        self.value = value

def get_tree_height(b_tree):
    if b_tree is None:
        return 0
    l_height = get_tree_height(b_tree.left_node)
    r_height = get_tree_height(b_tree.right_node)

    height = max(l_height, r_height) + 1
    return height

def get_max_value(b_tree):
    if b_tree is None:
        return -1
    root = b_tree.value
    right = get_max_value(b_tree.right_node)
    result = max(root, right)
    return result

if __name__ == '__main__':
    a = [2, 3, 1, 4, 5]
    b_tree = BTree()
    for i in a:
        create(b_tree, i)

    print("height:", get_tree_height(b_tree))
    print("max:", get_max_value(b_tree))


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis

def classify(X,y):
    names = [
        "Nearest Neighbors",
        "Linear SVM",
        "RBF SVM",
        "Gaussian Process",
        "Decision Tree",
        "Random Forest",
        "Neural Net",
        "AdaBoost",
        "Naive Bayes",
        "QDA",
    ]

    classifiers = [
        KNeighborsClassifier(3),
        SVC(kernel="linear", C=0.025),
        SVC(gamma=2, C=1),
        GaussianProcessClassifier(1.0 * RBF(1.0)),
        DecisionTreeClassifier(max_depth=5),
        RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
        MLPClassifier(alpha=1, max_iter=1000),
        AdaBoostClassifier(),
        GaussianNB(),
        QuadraticDiscriminantAnalysis(),
    ]

    X = StandardScaler().fit_transform(X)
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.4, random_state=42
    )

    # iterate over classifiers
    for name, clf in zip(names, classifiers):
        clf.fit(X_train, y_train)
        score = clf.score(X_test, y_test)

        print(name, score, flush=True)

if __name__ == "__main__":
    with open('merged.txt') as f:
        df = pd.read_csv(f,sep='\t',skiprows=1)

    df = df.drop(['NCBI_tax_id', 'clade_name'], axis=1)
    X = df.transpose().to_numpy().tolist()
    y = [0]*28 + [1]*31

    classify(X,y)


# No slide nomeado como 'dicionario_ex01.py'

notas = {}
encerrar = "NÃO"

while "N" in encerrar.upper():
    print("Por favor, digite o nome do aluno:")
    aluno = input()
    print("Por favor, digite a nota do aluno:")
    nota = float(input())

    print("Deseja FINALIZAR a digitação?\n(S)\tSim\n(N)\tNão")
    encerrar = input()

total = 0
for nota in notas.values():
    if nota == 10.00:
        total = total + 1

print(f"Ao total, {total} alunos tiraram notas 10!")

print("Notas da turma: ")
for aluno, nota in notas.items():
    print(f"O aluno {aluno} tirou nota {nota}.")


import codecs
import glob
import os
from setuptools import setup, find_packages

# Prevent spurious errors during `python setup.py test`, a la
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html:
try:
    import multiprocessing
except ImportError:
    pass

def read(fname):
    fpath = os.path.join(os.path.dirname(__file__), fname)
    with codecs.open(fpath, 'r', 'utf8') as f:
        return f.read().strip()

setup(
    name='collector',
    version='0.3',
    description=('Socorro is a server to accept Breakpad'
                 ' crash reports.'),
    long_description=open('README.md').read(),
    author='Mozilla',
    author_email='socorro-dev@mozilla.com',
    license='MPL',
    url='https://github.com/mozilla/socorro-collector',
    classifiers=[
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MPL License',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
        ],
    keywords=['socorro', 'breakpad', 'crash', 'reporting', 'minidump',
              'stacktrace'],
    packages=find_packages(),
    install_requires=[], # use peep -r requirements.txt instead
    entry_points={
        'console_scripts': [
                'socorro = socorro.app.socorro_app:SocorroWelcomeApp.run'
            ],
        },
    test_suite='nose.collector',
    zip_safe=False,
),


import math

A, B, V = map(int, input().split())
# 낮과 밤을 합쳐서 오를 미터를 소수점 올림으로 저장
result = math.ceil(V / (A - B))

# 만약 마지막 밤에 미끄러진 미터를 제외한 결과가 result 보다 작으면
# 그 값을 출력
if result > (V - B) / (A - B):
    print(math.ceil((V - B) / (A - B)))
else:
    print(result)

2869_달팽이는 올라가고 싶다.py


import os
from K_MC import calculate_centroids_and_clusters, calculate_k, classify
import sys
sys.path.append('../')  # Move path so that we can import from the datasets directory
from datasets.weather import create_data_set, create_labeled_data_set  # noqa: E402

if __name__ == "__main__":
    unlabeled_data_set = create_data_set('../datasets/dataset1.csv')
    labeled_data_set = create_labeled_data_set('../datasets/dataset1.csv')
    validation_set = create_labeled_data_set('../datasets/dataset1.csv')

    # Label un labeled data using the validation set
    centroids, clusters = calculate_centroids_and_clusters(unlabeled_data_set, calculate_k(unlabeled_data_set))

    # Normally k means clustering is used for unlabelled data,
    # but we have an labeled data set.
    # So we can label our found clusters by comparing the given cluster id with the label it has in de data set.
    # NOTE: It could be that our algorithm finds more (or less) clusters than we have labels, so this is not a 100% validation.

    # Get every label for every cluster id
    label_count_by_id = {}
    for data in labeled_data_set:
        label = classify(centroids, data[1])
        if label in label_count_by_id:
            label_count_by_id[label].append(data[0])
        else:
            label_count_by_id[label] = []

    # Count every label and set the cluster label to the most appearing one
    label_by_id = {}
    for key, labels in label_count_by_id.items():
        count = {}
        for label in labels:
            if label in count:
                count[label] += 1
            else:
                count[label] = 0
        count_max = max(count.items(), key = lambda x: x[1])
        label_by_id[key] = count_max[0]

    # Since we have the labels on our data set, we can also validate our data with our validation set
    correct = 0
    for data in validation_set:
        c = label_by_id[classify(centroids, data[1])]
        correct += (c == data[0])
    print(correct/len(validation_set) * 100)  # AVG: 51~%

    # Test the unlabeled data
    unlabeled = [
        (40, 52, 2, 102, 103, 0, 0),
        (25, 48, -18, 105, 72, 6, 1),
        (23, 121, 56, 150, 25, 18, 18),
        (27, 229, 146, 308, 130, 0, 0),
        (41, 65, 27, 123, 95, 0, 0),
        (46, 162, 100, 225, 127, 0, 0),
        (23, -27, -41, -16, 0, 0, -1),
        (28, -78, -106, -39, 67, 0, 0),
        (38, 166, 131, 219, 58, 16, 41),
    ]

    # Label the unlabeled data
    for day in unlabeled:
        print(label_by_id[classify(centroids, day)])

    os.system("pause")


# === SOURCE CODE cfd-score-calculator.py provided by John Doench =====
import pickle, re
from os.path import basename, join, splitext, isfile, dirname

def get_mm_pam_scores():
    """
    """
    # dataDir = join(dirname(__file__), 'CFD_Scoring')
    dataDir='CFD/'
    mm_scores = pickle.load(open(join(dataDir, 'mismatch_score.pkl'), 'rb'))
    pam_scores = pickle.load(open(join(dataDir, 'pam_scores.pkl'), 'rb'))
    return (mm_scores, pam_scores)
    # except:
    # raise Exception("Could not find file with mismatch scores or PAM scores")

# Reverse complements a given string
def revcom(s):
    basecomp = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U': 'A'}
    letters = list(s[::-1])
    letters = [basecomp[base] for base in letters]
    return ''.join(letters)

# Calculates CFD score
def calc_cfd(wt, sg, pam):
    """
    >>> calc_cfd("GGGGGGGGGGGGGGGGGGGG", "GGGGGGGGGGGGGGGGGGGG", "GG")
    1.0
    """
    # mm_scores,pam_scores = get_mm_pam_scores()
    score = 1
    sg = sg.replace('T', 'U')
    wt = wt.replace('T', 'U')
    s_list = list(sg)
    wt_list = list(wt)
    # print mm_scores
    for i, sl in enumerate(s_list):
        # print i, sl, wt_list[i], mm_scores
        if wt_list[i] == sl:
            score *= 1
        else:
            key = 'r' + wt_list[i] + ':d' + revcom(sl) + ',' + str(i + 1)
            score *= mm_scores[key]
    score *= pam_scores[pam]
    return (score)

mm_scores, pam_scores = None, None

def calcCfdScore(guideSeq, otSeq):
    """ based on source code provided by John Doench
    >>> calcCfdScore("GGGGGGGGGGGGGGGGGGGGGGG", "GGGGGGGGGGGGGGGGGAAAGGG")
    0.4635989007074176
    >>> calcCfdScore("GGGGGGGGGGGGGGGGGGGGGGG", "GGGGGGGGGGGGGGGGGGGGGGG")
    1.0
    >>> calcCfdScore("GGGGGGGGGGGGGGGGGGGGGGG", "aaaaGaGaGGGGGGGGGGGGGGG")
    0.5140384614450001
    """
    global mm_scores, pam_scores
    if mm_scores is None:
        mm_scores, pam_scores = get_mm_pam_scores()
    wt = guideSeq.upper()
    off = otSeq.upper()
    m_wt = re.search('[^ATCG]', wt)
    m_off = re.search('[^ATCG]', off)
    if (m_wt is None) and (m_off is None):
        pam = off[-2:]
        sg = off[:-3]
        cfd_score = calc_cfd(wt, sg, pam)
        return cfd_score
        # print "CFD score: "+str(cfd_score)


import pexpect
import re
import sys
import telnetlib
import logging

class TelConFailed(Exception):
    pass

class TelCon:
    def __init__(self, logger = logging.getLogger(__name__)):
        self.logger = logger
        logging.basicConfig(level=logging.DEBUG)
        self.tel = pexpect.spawn("telnet localhost 4444", timeout = 3)
        telcon_start = self.tel.expect([
            "Connected to localhost",
            "unable to"
            ])
        if telcon_start == 0:
            logging.info("connected to telnet")
        else:
            raise TelConFailed()

    def __enter__(self):
        return self

    def halt(self):
        self.tel.sendline("reset halt")
        self.tel.expect("[\s\S]*target halted[\s\S]*")
        logging.info("halted")

    def remove_protection(self):
        self.tel.sendline("flash protect 0 0 last off")
        self.tel.expect("cleared protection for sectors")
        logging.info("erased")

    def erase(self):
        self.tel.sendline("flash erase_sector 0 0 0")
        self.tel.expect("[\s\S]*erased sectors[\s\S]*")
        logging.info("erased")

    def load(self):
        self.tel.sendline("flash write_image erase /root/workspace/Provisioning-jig-Debugger/debug/DFU_ST-Link-V2.hex")
        self.tel.expect("[\s\S]*wrote[\s\S]*from file[\s\S]*")
        self.tel.sendline("verify_image /root/workspace/Provisioning-jig-Debugger/debug/DFU_ST-Link-V2.hex")
        self.tel.expect("[\s\S]*verified[\s\S]*bytes in[\s\S]*")
        logging.info("LOADED!")

    def __exit__(self, type, value, traceback):
        self.tel.send("exit")
        logging.info("Telnet connection terminated")