import numpy as np
import pygame

class Environment:
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GREEN = (0, 255, 0)
    BROWN = (222, 184, 135)
    LIGHTYELLOW = (250, 235, 215)
    LIGHTGREEN = (144, 238, 144)
    ROBOT_DIAMETER = 50
    DUST_DOTS_COLOR = LIGHTGREEN
    DUST_DOT_WIDTH = 3
    PADDING = 50

    def __init__(self, width=800, height=800, obstacles=None, robot=None, pygame_enabled=False):
        """
        :param width:           Width of window
        :param height:          Height of window
        :param obstacles:       list of lists where each sublist is [x_from, x_to, y_from, y_to]
        :param robot:           Robot Object
        """

        # initialize dimension of the world
        self.width = width
        self.height = height
        self.pygame_enabled = pygame_enabled

        if self.pygame_enabled:
            pygame.init()
            pygame.font.init()
            self.myfont = pygame.font.SysFont('Comic Sans MS', 30)

            self.gameDisplay = pygame.display.set_mode((self.width, self.height))
            pygame.display.set_caption('Differential Robot Simulator')
            self.clock = pygame.time.Clock()

        # initialize robot
        self.robot = robot

        # Initialize dust
        self.dust_dots_intensity = 4
        self.dust_matrix_width = int(self.width / self.dust_dots_intensity)
        self.dust_matrix_height = int(self.height / self.dust_dots_intensity)
        self.dust_total = self.dust_matrix_width * self.dust_matrix_height

        # Zero(0) means that there is dust.
        # Minus one (-1) means that robot passed by this spot so there is not dust anymore
        self.dust_matrix = np.ones((self.dust_matrix_width, self.dust_matrix_height))

        self.dust_coverage = 1  # 100% dust coverage when we start
        self.ground_coverage = 1 - self.dust_coverage
        if self.pygame_enabled:
            self.dust_point = [[None for j in range(self.dust_matrix_width)] for i in range(self.dust_matrix_height)]

        # OBSTACLES

        if self.pygame_enabled:
            # initialize walls object (rects)
            self.obstacles_rects = []

        # obstacle coordinates, handy for wall collision
        self.obstacles_coord = obstacles

        # If no coordinates are passed, initialize empty room (with border walls)
        if self.obstacles_coord is None:
            self.obstacles_coord = [
                [0 + self.PADDING, 0 + self.PADDING, self.width - self.PADDING, 0 + self.PADDING],
                [self.width - self.PADDING, 0 + self.PADDING, self.width - self.PADDING,self.height - self.PADDING],
                [self.width - self.PADDING, self.height - self.PADDING, 0 + self.PADDING,self.height - self.PADDING],
                [0 + self.PADDING, self.height - self.PADDING, 0 + self.PADDING, 0 + self.PADDING]
            ]

        # obstacles parameters, handy for sensor values
        self.obstacles_parameters = np.zeros((len(self.obstacles_coord), 2))

        # Add obstacles
        self.add_obstacles()

    def reset(self):
        self.dust_matrix = np.ones((self.dust_matrix_width, self.dust_matrix_height))
        self.dust_coverage = 1  # 100% dust coverage when we start
        self.ground_coverage = 1 - self.dust_coverage

    def add_obstacles(self):
        # obstacles parameters
        for count, obst in enumerate(self.obstacles_coord):
            # sensors functions parameters

            # slope m
            if self.obstacles_coord[count][3] - self.obstacles_coord[count][1] == 0:
                self.obstacles_parameters[count][0] = 0
            else:
                if self.obstacles_coord[count][2] - self.obstacles_coord[count][0] == 0:
                    self.obstacles_parameters[count][0] = float('inf')
                else:
                    self.obstacles_parameters[count][0] = (self.obstacles_coord[count][3] - self.obstacles_coord[count][
                        1]) / ((self.obstacles_coord[count][2] -
                                self.obstacles_coord[count][0]))

            # intercept q
            self.obstacles_parameters[count][1] = self.obstacles_coord[count][1] - (
                    self.obstacles_parameters[count][0] * self.obstacles_coord[count][0])

            if self.pygame_enabled:
                # draw current wall and store Rect object
                curr_wall = pygame.draw.line(self.gameDisplay, self.BLACK,
                                             (self.obstacles_coord[count][0], self.obstacles_coord[count][1]),
                                             (self.obstacles_coord[count][2], self.obstacles_coord[count][3]), 5)
                self.obstacles_rects.append(curr_wall)

            # print("############################ INIT WALLS COORD + PARAMS ############################")
            # print(self.obstacles_coord)
            # print(self.obstacles_parameters)

    def reset_background(self):
        # Draw everything white
        self.gameDisplay.fill(self.WHITE)

    def calculate_dust_and_ground_coverage(self):
        dust_on_screen = np.count_nonzero(self.dust_matrix)
        self.dust_coverage = dust_on_screen / self.dust_total
        self.ground_coverage = 1 - self.dust_coverage

    def draw_dust(self):
        # By knowing the position of the robot and it's radius we can mark all of the dust point in the matrix
        # that the robot "touches"
        # But instead of checking all of the dots of the grid and their distance to the robot we just check the closest
        # ones to it by taking the position of the robot dividing by the dot intensity to bring the robot to the same
        # cartesian system as the dots and then we go -10 +10 up and down and only check this part.
        for i in range(int(self.robot.position[0]) // self.dust_dots_intensity - 10,
                       int(self.robot.position[0]) // self.dust_dots_intensity + 10, 1):
            for j in range(int(self.robot.position[1]) // self.dust_dots_intensity - 10,
                           int(self.robot.position[1]) // self.dust_dots_intensity + 10, 1):
                pythagorian_distance = np.sqrt((self.robot.position[0] - i * self.dust_dots_intensity) ** 2 + (
                        self.robot.position[1] - j * self.dust_dots_intensity) ** 2)
                if pythagorian_distance < self.robot.radius:
                    self.dust_matrix[i][j] = 0

        # Draw this dot if the dust_matrix has the value 1 and pygame is enabled
        if self.pygame_enabled:
            for i in range(self.dust_matrix_width):
                for j in range(self.dust_matrix_height):
                    if self.dust_matrix[i][j] == 1:
                        self.dust_point[i][j] = pygame.draw.circle(self.gameDisplay, self.DUST_DOTS_COLOR,
                                                                   [i * self.dust_dots_intensity,
                                                                    j * self.dust_dots_intensity], self.DUST_DOT_WIDTH)

    def draw_obstacles(self):
        for count, obst in enumerate(self.obstacles_coord):
            pygame.draw.line(self.gameDisplay, self.BLACK,
                             (self.obstacles_coord[count][0], self.obstacles_coord[count][1]),
                             (self.obstacles_coord[count][2], self.obstacles_coord[count][3]), 3)

    def draw_osd(self):
        osd_text_1 = 'Robot Velocity:'
        osd_text_2 = 'Left Wheel:{0}'.format(self.robot.left_wheel_velocity)
        osd_text_3 = 'Right Wheel:{0}'.format(self.robot.right_wheel_velocity)
        osd_text_4 = 'Theta:{0:.2f}'.format(self.robot.theta)
        osd_text_5 = 'Ground Coverage:{0:.2f}'.format(self.ground_coverage)
        osd_1 = self.myfont.render(osd_text_1, False, (0, 0, 0))
        osd_2 = self.myfont.render(osd_text_2, False, (0, 0, 0))
        osd_3 = self.myfont.render(osd_text_3, False, (0, 0, 0))
        osd_4 = self.myfont.render(osd_text_4, False, (0, 0, 0))
        osd_5 = self.myfont.render(osd_text_5, False, (0, 0, 0))
        self.gameDisplay.blit(osd_1, (20, self.height - 120))
        self.gameDisplay.blit(osd_2, (20, self.height - 100))
        self.gameDisplay.blit(osd_3, (20, self.height - 80))
        self.gameDisplay.blit(osd_4, (20, self.height - 60))
        self.gameDisplay.blit(osd_5, (20, self.height - 40))

    def draw_robot(self):
        # Draw the circle of the robot
        self.robot.robot_rect = pygame.draw.circle(self.gameDisplay, self.BLACK,
                                                   [int(self.robot.position[0]), int(self.robot.position[1])],
                                                   self.robot.radius, 3)

        # Draw the small line indicating the direction that the robot is moving
        # End_x and end_y represent where the small line should end, starting from the centre of the circle
        end_x = self.robot.radius * np.cos(2 * np.pi + self.robot.theta)
        end_y = self.robot.radius * np.sin(2 * np.pi + self.robot.theta)

        # Draw the line
        pygame.draw.line(self.gameDisplay, self.BLACK,
                         [int(self.robot.position[0]), int(self.robot.position[1])],
                         [int(self.robot.position[0] + end_x), int(self.robot.position[1] + end_y)],
                         3)

    def draw_sensors(self):
        for sensor in range(len(self.robot.sensors_values)):
            osd_sensor_text = str(round(self.robot.sensors_values[sensor]))
            osd_sensor = self.myfont.render(osd_sensor_text, False, self.BLACK)
            self.gameDisplay.blit(osd_sensor,
                                  (self.robot.sensors_coords[sensor, 2], self.robot.sensors_coords[sensor, 3]))

        # update sensors Rect obj, to update parameters value
        if len(self.robot.sensors_coords) != 0:
            updated_sensors = []
            for sensor in self.robot.sensors_coords:
                updated_sensors.append(pygame.draw.line(self.gameDisplay, self.BLACK,
                                                        [int(sensor[0]), int(sensor[1])],
                                                        [int(sensor[2]), int(sensor[3])],
                                                        3))
            self.robot.sensors_rects = updated_sensors

    def render(self):
        if self.pygame_enabled:
            self.reset_background()

            # Draw components. Ordering of draw matters for the window to look nice
            self.draw_robot()
        self.draw_dust()
        if self.pygame_enabled:
            self.draw_osd()
            self.draw_obstacles()
            self.draw_sensors()

        # Calculate Dust coverage (needed or Evolutionary Algorithm)
        self.calculate_dust_and_ground_coverage()


# Coleta os dados, montando a matriz
linhas, colunas = [int(x) for (x) in input().split()]
matriz = []
for l in range(linhas):
    matriz.append([int(x) for (x) in input().split()])

# Inicia as listas dos dados a serem verificados
lista_menores_linha = []
lista_maiores_coluna = []
lista_coordenadas = []
saida = []

# Verifica o menor elemento de cada linha e os insere na lista respectiva
for l in range(linhas):
    menor_elemento_linha = float("inf")
    coordenada = []
    for c in range(colunas):
        if matriz[l][c] < menor_elemento_linha:
            menor_elemento_linha = matriz[l][c]
            coordenada = l, c
    lista_menores_linha.append(menor_elemento_linha)
    lista_coordenadas.append(coordenada)

# Verifica o maior elemento de cada coluna e os insere na lista respectiva
for l in range(colunas):
    maior_elemento_coluna = float("-inf")
    for c in range(linhas):
        if matriz[c][l] > maior_elemento_coluna:
            maior_elemento_coluna = matriz[c][l]
    lista_maiores_coluna.append(maior_elemento_coluna)

# Verifica se há elemento comum entre as duas listas (ou seja, cumpre os dois requisitos), retornando a resposta:
    # Coordenada do elemento que é o menor da respectiva linha e o maior da respectiva coluna ou 'False' caso não cumpra os requisitos.
for elemento in range(len(lista_menores_linha)):
    if lista_menores_linha[elemento] in lista_maiores_coluna:
        coordenada = lista_coordenadas[elemento]
        l, c = coordenada
        saida = l + 1, c + 1
        print(*saida)
        break
if saida == []:
    print(False)


#%%

my_list = [4, 7, 0, 3]

# get an iterator using iter()
my_iter = iter(my_list)

my_iter

## iterate through it using next()

#prints 4
print(next(my_iter))

#prints 7
print(next(my_iter))

## next(obj) is same as obj.__next__()

#prints 0
print(my_iter.__next__())

#prints 3
print(my_iter.__next__())

print('for loop:')
for element in my_list:
    print(element)

#Self define iterator
class PowTwo:      #   """Class to implement an iterator  of powers of two"""
    def __init__(self, max = 0):
        self.max = max

    def __iter__(self): #Iteration method
        self.n = 0
        return self

    def __next__(self): #next method
        if self.n <= self.max:
            result = 2 ** self.n
            self.n += 1
            return result
        else:
            raise StopIteration

#Using the iterator
a = PowTwo(4)
print('a: ', a)
i = iter(a)
print('i: ', next(i))
print('i: ', next(i))

for j in PowTwo(5):
    print('j: ', j)

l = range(1,10)
iter(l)
print(next(l))

## numpy array iteration
import numpy as np
array = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
for i in array:
    for j in i:
        print(j)

#dataframe iteration with pandas
import pandas as pd
data = {'A':[1,2], 'B':[3,4], 'C':[5,6]}
df = pd.DataFrame(data=array, columns = ['A','B','C','D'])
for i in df:
    #print(i)
    print(df[i])

#Generating random classes and populating array of labels
n = 10
s = 20
x = np.random.randint(0,n, size=s)
label = np.zeros((s,n))
label[list(range(0,s)), [x]] = 1
x, label


def separa(n):
    lis = []
    while n > 0:
        lis.insert(0, n % 10)
        n = n // 10
        #print(n, lis)
    return lis

def ocorrencia(n, d):
    l = separa(n)
    qtd = 0
    for i in l:
        if i == d:
            qtd = qtd + 1
    return qtd

num = int(input('Numero: '))
while  num < 1 or num > 99999:
    num = int(input('Invalido. Numero: '))

while  num > 0:
    q = ocorrencia(num, 9)
    print(num, 'tem', q, 'digitos 9')
    num = int(input('Numero: '))
    while num > 99999:
        num = int(input('Invalido. Numero:'))


import os
import pickle
import cv2

import numpy as np
import torch
from omegaconf import DictConfig

from bbr.datasets.tfs import get_flickr_transform

class ImageLoader(torch.utils.data.Dataset):
    def __init__(self, root, transform=None, split="train", img_path=False):
        annt_path = os.path.join(root, "annotations", split + ".pickle")
        with open(annt_path, "rb") as f:
            self.annotations = pickle.load(f, encoding="latin1")
        self.files = list(self.annotations.keys())
        print("num of data:{}".format(len(self.files)))
        self.transform = transform
        self.split = split
        self.img_folder = os.path.join(root, "ReferIt_Images")
        self.img_path = img_path

    def __getitem__(self, index):
        item = str(self.files[index])
        folder = (2 - len(str(int(item) // 1000))) * "0" + str(int(item) // 1000)
        img_path = os.path.join(self.img_folder, folder, "images", item + ".jpg")
        img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
        image_sizes = (img.shape[0], img.shape[1])
        img = self.transform(img)
        ann = self.annotations[item]["annotations"]
        if self.split == "train":
            region_id = np.random.randint(0, len(ann))
            return img, "image of " + ann[region_id]["query"]
        out = {}
        for i in range(0, len(ann)):
            tmp = {}
            bbox = ann[i]["bbox"]
            if (bbox[0][3] - bbox[0][1]) * (bbox[0][2] - bbox[0][0]) > 0.05 * image_sizes[0] * image_sizes[1]:
                tmp["sentences"] = "image of " + ann[i]["query"]
                tmp["bbox"] = bbox
                out[str(i)] = tmp
        if self.img_path:
            return img, out, image_sizes, img_path
        return img, out, image_sizes

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

    @property
    def name(self):
        return "referit"

def get_referit_test_dataset(cfg: DictConfig):
    datadir = cfg.val_path
    transform_train, transform_test = get_flickr_transform(image_size=cfg.image_size)
    ds_test = ImageLoader(datadir, split="test", transform=transform_test)
    return ds_test

def get_referit_dataset(cfg: DictConfig, only_test=False):
    datadir = cfg.data_path
    transform_train, transform_test = get_flickr_transform(image_size=cfg.image_size)
    ds_test = ImageLoader(datadir, split="val", transform=transform_test)
    ds_train = None
    if not only_test:
        ds_train = ImageLoader(datadir, split="train", transform=transform_train)
    return ds_train, ds_test


# -*- coding: UTF-8 -*-
from django.core import mail
from django.test import TestCase
from django.utils import timezone
from django.contrib.humanize.templatetags.humanize import date, naturaltime

from toolkit import settings
from toolkit.casper.workflow_case import BaseScenarios

from model_mommy import mommy

import datetime

class TaskReminderServiceTest(BaseScenarios, TestCase):
    def setUp(self):
        super(TaskReminderServiceTest, self).setUp()
        self.basic_workspace()
        item = mommy.make('item.Item',
                          matter=self.matter,
                          date_due=timezone.now() + datetime.timedelta(days=settings.REMIND_DUE_DATE_LIMIT - 1))
        self.task = mommy.make('task.Task',
                                item=item,
                                is_complete=False,
                                created_by=self.lawyer,
                                assigned_to=[self.user],
                                date_due=timezone.now() + datetime.timedelta(days=settings.REMIND_DUE_DATE_LIMIT + 1))

    def test_reminder_positive(self):
        # create item in reminding period

        self.task.send_reminder(from_user=self.lawyer)
        outbox = mail.outbox
        self.assertEqual(len(outbox), 1)
        email = outbox[0]
        self.assertEqual(email.subject, u'[ACTION REQUIRED] Please complete the task')
        self.assertTrue('
Warning, Task Overdue
' not in email.body)

    def test_reminder_overdue(self):
        self.task.date_due = timezone.now() + datetime.timedelta(days=-5)
        self.task.save(update_fields=['date_due'])

        self.task.send_reminder(from_user=self.lawyer)
        outbox = mail.outbox
        self.assertEqual(len(outbox), 1)
        email = outbox[0]
        self.assertEqual(email.subject, u'[ACTION REQUIRED] (Expired) Please complete the task')
        self.assertTrue('
Warning, Task Overdue
' in email.body)


# You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.

from typing import Optional

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

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # Returns if either or both args are missing
        if not l1:
            return l2
        if not l2:
            return l1
        # set number holders for easier val access
        ll1, ll2 = [], []
        # Run through each LinkedList to grab vals
        runner = l1
        while runner:
            ll1.append(runner.val)
            runner = runner.next
        runner = l2
        while runner:
            ll2.append(runner.val)
            runner = runner.next
        print(ll1, ll2)
        # Set longest list and math intermediate
        work = ll1 if len(ll1)>=len(ll2) else ll2
        temp = 0
        # Do addition back to front of arrays
        for i in range(-1, -len(work)-1, -1):
            # Conditional depending on each lists length
            if abs(i) > len(ll1):
                temp = ll2[i]+temp
            elif abs(i) > len(ll2):
                temp = ll1[i]+temp
            else:
                temp = ll1[i]+ll2[i]+temp
            # Once a sum is acheived add the ones digit to current spot
            work[i] = temp % 10
            # Floor Divide by ten to reove ones place
            temp = temp//10
        # If any leftover sum process it
        if temp:
            # If large then 10 process down and add to end
            while temp > 9:
                work = [temp % 10]+work[:]
                temp = temp // 10
            # add final sum digit to end
            work = [temp]+work[:]
        # Put your result into the linked list
        runner = l1
        for i in work:
            runner.next = ListNode(i)
            runner=runner.next
        return l1.next

s = Solution()
print(s.addTwoNumbers(
        ListNode(7, ListNode(2, ListNode(4, ListNode(3)))),
        ListNode(5, ListNode(6, ListNode(4)))
        ))
print(s.addTwoNumbers(
        ListNode(2, ListNode(4, ListNode(3))),
        ListNode(5, ListNode(6, ListNode(4)))
        ))
print(s.addTwoNumbers(
        ListNode(),
        ListNode()
        ))
print(s.addTwoNumbers(
        ListNode(5),
        ListNode(5)
        ))


from z3 import *
from invar_synth.protocols.dist_lock import Node, Epoch, DistLockModel
from invar_synth.utils.minisy_wrapper import MiniSyWrapper
from invar_synth.utils.qexpr import QForAll

def test_parse_1():
    defn = """(define-fun inv ((m ModelId) (s StateId) (n1 Node) (e1 Epoch)) Bool
        (=> (locked m s e1 n1) (transfer m s e1 n1))
    )"""
    gt = lambda M, S: QForAll(
        [Node, Epoch],
        lambda n1, e1: Implies(
            S.locked(e1, n1),
            S.transfer(e1, n1)
        )
    )

    MS = MiniSyWrapper()

    qs = ['FORALL', 'FORALL']
    sorts = [Node, Epoch]

    inv = MS.parse_inv_defn_v2(qs, sorts, defn)

    M1 = DistLockModel('M1')
    S1 = M1.get_state('S1')

    solver = Solver()
    solver.add(gt(M1, S1).z3expr != inv(M1, S1).z3expr)
    assert solver.check() == unsat

def test_parse_2():
    defn = """(define-fun inv ((m ModelId) (s StateId) (n1 Node) (n2 Node) (e1 Epoch)) Bool
        (=> (locked m s e1 n1) (= n2 n1))
    )"""
    gt = lambda M, S: QForAll(
        [Node, Node, Epoch],
        lambda n1, n2, e1: Implies(
            S.locked(e1, n1),
            n2 == n1
        )
    )

    MS = MiniSyWrapper()

    qs = ['FORALL', 'FORALL', 'FORALL']
    sorts = [Node, Node, Epoch]

    inv = MS.parse_inv_defn_v2(qs, sorts, defn)

    M1 = DistLockModel('M1')
    S1 = M1.get_state('S1')

    solver = Solver()
    solver.add(gt(M1, S1).z3expr != inv(M1, S1).z3expr)
    assert solver.check() == unsat


import sys
from collections import defaultdict
from random import randint

""" zad1 """

user_number = input('podaj liczbę:\n')
user_number = int(user_number)

print("{0:b}".format(user_number))
print("{0:x}".format(user_number))
print("{0:o}".format(user_number))

""" Zad2 """

user_number = input('podaj liczbę:\n')

try:
    int(user_number)
except Exception as e:
    print('nie rzutowalne na inta')
    print(e)

try:
    float(user_number)
except Exception as e:
    print('nie rzutowalne na stringa')
    print(e)

""" zad3 """

print("Podaj liczbę")
s = sys.stdin.readline()
s = s.strip('\n')
length = len(list(s))
print(list(s))
sys.stdout.write(f"Twój tekst to:")
for each in list(s):
    if each != '0':
        sys.stdout.write(f" {each} * {10**(length-1)},")
    length -= 1

""" Zad5 """

user_text = input('podaj zdanie:\n')

user_text_list = user_text.split(" ")
print(user_text_list)
user_text_dict = defaultdict(int)

for k in user_text_list:
    user_text_dict[k] = len(k)

num = 0
key = ""
used_keys = []
while num < len(user_text_list):
    minimum = 0
    for k, v in user_text_dict.items():
        if v >= minimum and k not in used_keys:
            minimum = v
            key = k
    print(key, minimum)
    used_keys.append(key)
    num += 1

""" Zad 6 """

talk_dict = {'col1': ['Koleżanki i koledzy ', 'Z drugiej strony ', 'Podobnie ', 'Nie zapominajmy jednak, że ',
                       'W ten oto sposób ', 'Różnorakie i bogate doświadczenia ', 'Wyższe założenia ideowe, a także '
                       'Wagi i znaczenia tych problemów nie trzeba szerzej uzasadniać, ponieważ ',
                       'Troska organizacji, a szczególnie ', 'Praktyka dnia codziennego dowodzi, że '],
             'col2': ['realizacja nakreślonych zadań programowych ', 'zakres i miejsce szkolenia kadr ',
                      'stały wzrost ilości i zakres naszej aktywności ', 'aktualna struktura organizacji ',
                      'nowy model działalności organizacyjnej ', 'dalszy rozwój różnych form działalności ',
                      'stałe zabezpieczenie informacyjno programowe naszej działalności ',
                      'wzmacnianie i rozwijanie struktur ', 'konsultacja z szerokim aktywem ',
                      'rozpoczęcie powszechnej akcji kształtowania postaw '],
             'col3': ['zmusza nas do przeanalizowania ', 'spełnia istotną rolę w kształtowaniu ',
                      'wymaga sprecyzowania i określenia ', 'pomaga w przygotowaniu i realizacji ',
                      'zabezpiecza udział szerokiej grupie w kształtowaniu ', 'spełnia ważne zadania w wypracowaniu ',
                      'umożliwia w większym stopniu tworzenie ', 'powoduje docenianie wagi ',
                      'przedstawia intersującą próbę sprawdzenia ', 'pociąga za sobą proces wdrażania i unowocześniania '],
             'col4': ['istniejących warunków administracyjno-finansowych. ', 'dalszych kierunków rozwoju. '
                      'systemu powszechnego uczestnictwa. ', 'postaw uczestników wobec zadań stawianych przez organizację. ',
                      'nowych propozycji. ', 'systemu szkolenia kadry odpowiadającego potrzebom. ',
                      'kierunków postępowego wychowania. ', 'odpowiednich waruknków aktywizacji. ',
                      'modelu rozwoju. ', 'form oddziaływania. ']}

number_of_sentences = input("ile zdan chcesz zobaczyc? Podaj liczbe\n")
for _ in range(int(number_of_sentences)):
    print(f"{talk_dict['col1'][randint(0, 9)]}{talk_dict['col2'][randint(0, 9)]}{talk_dict['col3'][randint(0, 9)]}"
          f"{talk_dict['col4'][randint(0, 9)]}")


a,n = map(int,input().split())
ans=0
bcnt=0

while a!=n:
    if a==n:
        print(ans)
        break
    elif n%a==0:
        n = n//a
        ans+=1
        bcnt=0
    elif n>10 and str(n)[-2]!="0" and bcnt < 7:
        ans+=1
        bcnt+=1
        strn=str(n)
        n=int(strn[1:]+strn[0])
    else:
        print(-1)
        break


def sum_with_multiplicity_3(input, target):
    array = [0] * 100
    count = 0
    for i in input:
        array[i] = array[i] + 1

    for i in range(target+1):
        for j in range(i, target+1):
            k = target - i - j
            if (k < 0) or (k < j) or (k>len(array)):
                continue
            if (array[i] == 0) or (array[j] == 0) or (array[k] == 0):
                continue
            if (i == j and j == k and array[i] >= 3):
                count = count + array[i] * (array[i]-1) * array[i]-2 / 6
            elif (i == j and j != k and array[i] >= 2):
                count = count + array[i] * (array[i] - 1) * array[k] / 2
            elif (i != j and j == k and array[j] >= 2):
                count = count + array[k] * (array[k] - 1) * array[i] / 2
            else:
                count = count + array[i] * array[j] * array[k]

    return count

input = [1,1,2,2,2,2]
target = 5
input = [1,1,2,2,3,3,4,4,5,5]
target = 8
print(sum_with_multiplicity_3(input, target))


import csv
import requests
from bs4 import BeautifulSoup
import pdb

# List of URLS
urls = [
	'aliasinfosec.com',
	'github.com',
	'news.ycombinator.com'
]

results = []

# Loop through URLs
for u in urls:

	_r = requests.get(f"https://{u}")

	# Make sure 200 OK
	if _r.status_code == 200:

		soup = BeautifulSoup(_r.text, 'html.parser')
		title = soup.find('title')

		results.append([title.text, u])

# Open a CSV file, with write attribute.
with open(f"output.csv", "w") as f:

	# Create a writer, write header.
	writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
	writer.writerow(["Title", "URL"])

	# Loop through results and write rows.
	for r in results:
		writer.writerow([r[0], r[1]])


shapes_scores_dict = {'A':1, 'B':2, 'C':3, 'X':1, 'Y':2, 'Z':3} # A for Rock, B for Paper, and C for Scissors
game_outcome_scores_dict = {'lost':0, 'tie':3, 'win':6}
my_winning_shape = {'A':'Y', 'B':'Z', 'C':'X'}
my_loosing_shape = {'A':'Z', 'B':'X', 'C':'Y'}

def part1():
    with open('data.txt', 'r') as f:
        final_score = 0
        for line in f:
            shape_opponent, shape_mine = line.strip().split(' ')

            if shapes_scores_dict[shape_opponent] == shapes_scores_dict[shape_mine]: # tie
                game_score = game_outcome_scores_dict['tie'] + shapes_scores_dict[shape_mine]
            elif shape_mine == my_winning_shape[shape_opponent]: # I won
                game_score = game_outcome_scores_dict['win'] + shapes_scores_dict[shape_mine]
            else: # I lost
                game_score = shapes_scores_dict[shape_mine]

            final_score += game_score

        print(final_score)

def part2():
    game_outcome_scores_dict = {'X':0, 'Y':3, 'Z':6}

    with open('data.txt', 'r') as f:
        final_score = 0
        for line in f:
            shape_opponent, game_outcome = line.strip().split(' ')
            if game_outcome == 'X': # lost
                game_score = game_outcome_scores_dict[game_outcome] + shapes_scores_dict[my_loosing_shape[shape_opponent]]
            elif game_outcome == 'Y': # tie
                game_score = game_outcome_scores_dict[game_outcome] + shapes_scores_dict[shape_opponent]
            else: # win
                game_score = game_outcome_scores_dict[game_outcome] + shapes_scores_dict[my_winning_shape[shape_opponent]]

            final_score += game_score

        print(final_score)

if __name__ == "__main__":
    part1()
    part2()


from bs4 import BeautifulSoup as bs
import requests
import json

from utilities import constants, utils
from services import registry

def scrapMainTable():
    # Constants
    HEADERS = constants.HEADERS
    URL = constants.MAIN_URL
    DATA_FILE = constants.DATA_FILE

    # Request with context manager
    with requests.Session() as session:
        # Send request
        try:
            response = session.get(URL, headers=HEADERS)
        except:
            exitWithError()
            return

    if(response.status_code == 200):
        # Get BS4 object
        soup = bs(response.content, 'lxml')
        # Get main table and rows
        main_table = soup.find('table', {'id':'economicCalendarData'})
        rows = main_table.find('tbody').findAll('tr', {'class':'js-event-item'})

        # Get data from table
        rows_data = []
        if len(rows) > 0:
            for row in rows:
                # Time
                full_datetime = row['data-event-datetime']
                time = row.find('td', {'class':'time'}).text.strip()
                # Currency
                currency = row.find('td', {'class':'flagCur'}).text.strip()
                # Importance
                sentiment = row.find('td', {'class':'sentiment'})
                stars = sentiment.findAll('i', {'class':'grayFullBullishIcon'})
                importance = len(stars)
                # Title
                event = row.find('td', {'class':'event'}).find('a').text.strip()

                if(currency == 'USD' and importance == 3):
                    row_dict = {
                        'datetime': full_datetime,
                        'time': time,
                        'currency': currency,
                        'importance': importance,
                        'event': event
                    }
                    rows_data.append(row_dict)

        # Prepare data to be saved in a file
        data = {
            "date": utils.getToday(),
            "events": rows_data
        }

        # Save data to file
        with open(DATA_FILE, 'w') as output:
            json.dump(data, output, indent=4)

        registry.addEntry("Scrap data from Investing")

    else:
        exitWithError()

def exitWithError():
    DATA_FILE = constants.DATA_FILE

    data = {
        "date": "",
        "events": []
    }

    # Save data to file
    with open(DATA_FILE, 'w') as output:
        json.dump(data, output, indent=4)

    registry.addEntry("Error trying to fetch data..")


#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/3.6/bin/python3

from .......API.XMLX.XMLX import XMLX
from .......PaloAltoNetworks.PaloAltoNetworks import PaloAltoNetworks
from .......Logger.NetworkLogger.NetworkLogger import NetworkLogger as NLogger
from .......PaloAltoNetworks.Panorama.Templates.Network_Templates.Zones import Zones
from xml.etree.ElementTree import Element
# from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as Et

# TODO: Modify the class to add the interface to Zone and Virtual Router

class TunnelInterface(PaloAltoNetworks):
	"""
	Class to configure Tunnel Interface
	"""

	def __init__(self, panorama_ip, api_key):
		# print('++++ TunnelInterface Class')
		super().__init__(panorama_ip, api_key)
		# print('---- TunnelInterface Class')

	def __str__(self):
		return self.__class__.__name__

	@staticmethod
	def __xcode():
		"""
		Method to return Tunnel Interface xpath to place in API request string

		:return: xpath (XML code)
		:rtype: str
		"""

		xpath = (
			"/config/devices/entry[@name='localhost.localdomain']/template/entry[@name='%s']"
			"/config/devices/entry[@name='localhost.localdomain']/network/interface/tunnel/units"
		)

		ixpath = (
			"/config/devices/entry[@name='localhost.localdomain']/template/entry[@name='%s']"
			"/config/devices/entry[@name='localhost.localdomain']/vsys/entry[@name='vsys1']/import/network/interface"
		)

		return xpath, ixpath

	def configure_tunnel_interface(self, action, template_name, tunnel=None):
		"""
		Method to add TunnelInterface to Panorama

		:param action: Action - Add or Update
		:type action: str
		:param template_name: Name of template to add Tunnel Interface to
		:type template_name: str
		:param tunnel: Dictionary of all Tunnel Interface parameters
		:type tunnel: dict
		:return: None
		:rtype: None

		Example:

		tunnel_parameters = {
		'tunnel_name': 'tunnel.21', 'zone_name': 'dmz',
		'ip_address': {'ip1': '192.168.100.1/24', 'ip2': '192.168.101.1/24'},
		'interface_management_profile': 'allow-all-int-mgmt'
		}

		configure_tunnel_interface(action='add', template_name='PANW', tunnel=tunnel_parameters)

		Parameters:

		Note: All possible parameters are as below. If the parameter is not included, it will be disabled by default.

		tunnel_name (mandatory): Name of the Tunnel Interface
		zone (optional): Name of Zone to add this tunnel interface to
		virtual_router (optional): Name of the virtual router to add this tunnel interface to
		ip_address (mandatory): Dictionary of IP Addresses to be configured; example is above
		interface_management_profile (optional): Interface management profile name

		"""

		xmx = XMLX()
		xpath, ixpath = self.__xcode()

		if action == 'add':
			element_root = Element('entry')
			element_root.set('name', '%s' % tunnel.get('tunnel_name'))

			tree_ip = Element('ip')

			ip_addresses = tunnel.get('ip_address')

			for ip in ip_addresses:
				ip_root = Element('entry')
				ip_root.set('name', '%s' % ip_addresses[ip])

				tree_ip.append(ip_root)

			element_root.append(tree_ip)

			if tunnel.get('interface_management_profile') is not None:
				tree_interface_management_profile = Element('interface-management-profile')
				tree_interface_management_profile.text = tunnel.get('interface_management_profile')

				element_root.append(tree_interface_management_profile)

			element = Et.tostring(element_root).decode('UTF-8')

			try:
				uri = xmx.configure.format(self.panorama_ip, xpath % template_name, element, self.api_key)
			except Exception as e:
				NLogger.network.info('{} - Tunnel Interface: {} - {}'.format(
					template_name, tunnel.get('tunnel_name'), e)
				)
			else:
				xmx.exec_xml_get(uri, NLogger.network, 'Tunnel Interface', tunnel.get('tunnel_name'))

			# /import/network/interface path

			ielement = '<member>%s</member>' % tunnel.get('tunnel_name')

			try:
				uri = xmx.configure.format(self.panorama_ip, ixpath % template_name, ielement, self.api_key)
			except Exception as e:
				NLogger.network.info('{} - Tunnel Interface: {} - {}'.format(
					template_name, tunnel.get('tunnel_name'), e)
				)
			else:
				xmx.exec_xml_get(uri, NLogger.network, 'Tunnel Interface', tunnel.get('tunnel_name'))

			if tunnel.get('zone_name') is not None:
				zone = Zones(panorama_ip=self.panorama_ip, api_key=self.api_key)

				zone_parameters = {
					'zone_name': '%s' % tunnel.get('zone_name'),
					'interface': {'int1': '%s' % tunnel.get('tunnel_name')}
				}

				zone.configure_zone(action='update', template_name='PANW', zone=zone_parameters)

			if tunnel.get('virtual_router') is not None:
				pass


#Requirements: installed ffmpeg executable (add to PATH), and ffmpeg-python module.
import ffmpeg
import os

input_file = r"G:\My Drive\WORK\3D_Work\Ants_youtube\renders\map3_trails.mp4"
speed_factor = 5

output_name = os.path.basename(input_file).split(".")[0] + "_" + str(speed_factor) + "x_speed" + ".mp4"
ouput_file = os.path.join(os.path.dirname(input_file),output_name)
stream = ffmpeg.input(input_file)
stream = ffmpeg.output(stream, ouput_file, vf=f"setpts={1/speed_factor}*PTS")
ffmpeg.run(stream)


# Largest Rectangle In Historgram
"""
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [2,1,5,6,2,3],
return 10.
"""
class Solution:
    # @param {integer[]} height
    # @return {integer}
    def largestRectangleArea(self, height):
        if not height: return 0
        max_area = 0
        stack = [0]
        height.append(0)

        for i in range(1,len(height)):
            while stack:
                if height[i]<height[stack[-1]]:
                    h = stack.pop()
                    if stack:
                        max_area = max(max_area, height[h]*(i-stack[-1]-1))
                    else:
                        max_area = max(max_area, height[h]*i)
                else: break
            stack.append(i)
        return max_area


import numpy
from betfair.constants import Side
from structlog import get_logger
from datetime import datetime
from betfair_wrapper.betfair_wrapper_api import get_api

from selection_handlers.positionFetcher import positionFetcher
from selection_handlers.priceService import priceService

class Execution(positionFetcher, priceService):
    def __init__(self, market_id, selection_id, customer_order_ref = None, strategy_id = None):
        super(Execution, self).__init__(market_id, selection_id, customer_order_ref, strategy_id)

        self.current_orders = None
        self.current_back = None
        self.current_lay = None
        self.current_size = None
        self.status = None
        self.customer_ref_id = 0

    def quote_target(self, price, size):
        pass

    def quote(self, price, size, side):
        tradable = self.ask_for_price()

        if not tradable:
            get_logger("was not able to retrieve prices", status = self.status)
            return False

        betfair_position = self.get_betfair_matches(side)
        get_logger().info("position_betfair", betfair_position=betfair_position)

        betting_size = max(size - betfair_position, 0)
        well_priced_orders = []
        well_priced_position = 0
        for order in self.unmatched_order:
            if order["price"] == price and well_priced_position < betting_size:
                well_priced_orders.append(order)
                well_priced_position += order["size"]
            else:
                cancellation_report = get_api().cancel_order(self.market_id, order["bet_id"])

        difference_position = well_priced_position - betting_size

        if difference_position >0:
            get_api().cancel_order(self.market_id, well_priced_orders[-1]["bet_id"], difference_position)

        elif difference_position<0:
            remaining_size = -difference_position
            get_logger().info("placing bet", current_price=self.current_back, current_size=self.current_size,
                              price=price, size=size)
            ref = self.generate_oder_id(self.selection_id)
            match = get_api().place_bet(price, remaining_size, side.name, self.market_id, self.selection_id,
                                        customer_order_ref = ref)
            bet_id = match["bet_id"]
            if bet_id is None:
                get_logger().info("order refused")
                return False

            self.add_order_to_db(bet_id, size, price, side.name, match["size"], match["price"], ref, "active")

            return True

    def reach_stake(self, price, size, side):
        tradable = self.ask_for_price()

        if not tradable:
            get_logger("was not able to retrieve prices", status = self.status)
            return False

        betfair_position = self.get_betfair_matches(side)
        get_logger().info("position_betfair", betfair_position=betfair_position)

        betting_size = max(size - betfair_position, 0)
        well_priced_orders = []
        well_priced_position = 0
        for order in self.unmatched_order:
            if order["price"] == price and well_priced_position < betting_size:
                well_priced_orders.append(order)
                well_priced_position += order["size"]
            else:
                get_api().cancel_order(self.market_id, order["bet_id"])

        difference_position = well_priced_position - betting_size

        if difference_position >0:
            get_api().cancel_order(self.market_id, well_priced_orders[-1].bet_id, difference_position)

        elif difference_position<0:
            remaining_size = -difference_position
            get_logger().info("placing bet", current_price=self.current_back, current_size=self.current_size,
                              price=price, size=size)
            ref = self.generate_oder_id(self.selection_id)
            match = get_api().place_bet(price, remaining_size, side, self.market_id, self.selection_id,
                                        customer_order_ref=ref)
            bet_id = match["bet_id"]
            if bet_id is None:
                get_logger().info("order refused")
                return False

            self.add_order_to_db(bet_id, size, price, side, match["size"], match["price"], ref, "active")

            return True

    def place_order(self, price, size, side):
        ref = self.generate_oder_id(self.selection_id)
        match = get_api().place_bet(price, size, side, self.market_id, self.selection_id,
                                    customer_order_ref=ref)
        bet_id = match["bet_id"]
        if bet_id is None:
            get_logger().info("order refused")
            return False

        self.add_order_to_db(bet_id, size, price, side, match["size"], match["price"], ref, "active")

    def reach_exposure(self, exposure):
        unhedged_pos = self.compute_unhedged_position()

    def cashout(self, percentage = 1.0):
        unhedged_pos = self.compute_unhedged_position()
        self.ask_for_price()
        if unhedged_pos > 0:
            lay_hedge = unhedged_pos / self.current_lay
            lay_hedge = round(lay_hedge, 2)
            self.place_order(self.current_lay, lay_hedge, Side.LAY)
        elif unhedged_pos < 0:
            back_hedge = - unhedged_pos / self.current_back
            back_hedge = round(back_hedge, 2)
            self.place_order(self.current_back, back_hedge, Side.BACK)
        if percentage == 1.0:
            unhedged_pos = self.compute_unhedged_position()
            if numpy.abs(unhedged_pos) > 0.2:
                self.cancel_all_pending_orders()
                self.cashout()

    def cancel_all_pending_orders(self):
        self.get_betfair_matches()
        for order in self.unmatched_order:
            get_api().cancel_order(self.market_id, order["bet_id"])

    def compute_already_executed(self):
        sum = 0
        for match in self.matches:
            sum += match["size"]
        return sum

    def generate_oder_id(self, selection_id):
        time = datetime.now().strftime("%y%m%d%H%M%S")
        if self.customer_ref is None:
            return None
        ref = self.customer_ref + "_" + str(self.customer_ref_id) + str(selection_id) + time
        self.customer_ref_id =self.customer_ref_id +1
        return ref


from bs4 import BeautifulSoup as bs4
import requests

class BS4Parser:
    @classmethod
    def is_not_external(cls, url):
        req = requests.get(url)
        soup = bs4(req.text, "html.parser")

        for tag_a in soup.find_all("a", href=True):
            if "/apply/linkout" in tag_a.get("href"):
                return (False, req.text)
        return (True, req.text)

    @classmethod
    def get_job_body(cls, html_data: str) -> str:
        soup = bs4(html_data, "html.parser")
        job_body = soup.find_all("div", {"data-automation": "jobAdDetails"})
        if job_body:
            return job_body[0].text
        return ""


import numpy as np
import pandas as pd

from covid_model_seiir_pipeline.lib.ode_mk2.containers import (
    Parameters,
)
from covid_model_seiir_pipeline.lib.ode_mk2.constants import (
    RISK_GROUP_NAMES,
)
from covid_model_seiir_pipeline.pipeline.forecasting.model.containers import (
    Indices,
)
from covid_model_seiir_pipeline.side_analysis.counterfactual.specification import (
    CounterfactualScenarioParameters
)

def build_indices(scenario_spec: CounterfactualScenarioParameters,
                  beta: pd.Series,
                  past_compartments: pd.DataFrame):
    past_start_dates = (past_compartments
                        .reset_index(level='date')
                        .date
                        .groupby('location_id')
                        .min())

    with_covid = past_compartments.filter(like='Infection_all_all_all').sum(axis=1) > 0.
    min_start_date = (past_compartments[with_covid]
                      .reset_index(level='date')
                      .groupby('location_id')
                      .date
                      .min()) + pd.Timedelta(days=1)
    desired_start_date = pd.Series(pd.Timestamp(scenario_spec.start_date), index=min_start_date.index)
    forecast_start_dates = np.maximum(min_start_date, desired_start_date).rename('date')
    beta_fit_end_dates = forecast_start_dates.copy()
    forecast_end_dates = beta.reset_index().groupby('location_id').date.max()

    location_ids = past_start_dates.index.intersection(forecast_end_dates.index)
    return Indices(
        past_start_dates.loc[location_ids],
        beta_fit_end_dates.loc[location_ids],
        forecast_start_dates.loc[location_ids],
        forecast_end_dates.loc[location_ids],
    )

def build_model_parameters(indices: Indices,
                           counterfactual_beta: pd.Series,
                           ode_parameters: pd.DataFrame,
                           prior_ratios: pd.DataFrame,
                           vaccinations: pd.DataFrame,
                           etas: pd.DataFrame,
                           phis: pd.DataFrame) -> Parameters:
    ode_params = (ode_parameters
                  .reindex(indices.full)
                  .groupby('location_id')
                  .ffill()
                  .groupby('location_id')
                  .bfill())
    ode_params.loc[:, 'beta_all_infection'] = (counterfactual_beta
                                               .rename('beta_all_infection')
                                               .reindex(indices.full)
                                               .groupby('location_id')
                                               .ffill()
                                               .groupby('location_id')
                                               .bfill())

    scalars = []
    ratio_map = {
        'death': 'ifr',
        'admission': 'ihr',
        'case': 'idr',
    }
    for epi_measure, ratio_name in ratio_map.items():
        for risk_group in RISK_GROUP_NAMES:
            if ratio_name in prior_ratios:
                scalars.append(
                    (prior_ratios[f'{ratio_name}_{risk_group}'] / prior_ratios[ratio_name])
                    .rename(f'{epi_measure}_{risk_group}')
                    .reindex(indices.full)
                    .groupby('location_id')
                    .ffill()
                    .groupby('location_id')
                    .bfill()
                )
            else:
                scalars.append(
                    pd.Series(1., name=f'{epi_measure}_{risk_group}', index=indices.full)
                )
    scalars = pd.concat(scalars, axis=1)

    return Parameters(
        base_parameters=ode_params,
        vaccinations=vaccinations.reindex(indices.full, fill_value=0.),
        etas=etas.reindex(indices.full, fill_value=0.),
        age_scalars=scalars,
        phis=phis,
    )


#!/usr/bin/env python

import os, sys, glob

def cstringify(s):
    r = s.replace('\\', '\\\\')
    r = r.replace('"', '\\"')
    r = r.replace('<', '<')
    r = r.replace('>', '>')
    return r

if len(sys.argv) < 2:
    print('usage: scoop-rules <model|layout|variant|option>')
    exit(1)

printmodel = False
printlayout = False
printvariant = False
printoption = False
if sys.argv[1] == 'model':
    printmodel = True
elif sys.argv[1] == 'layout':
    printlayout = True
elif sys.argv[1] == 'variant':
    printvariant = True
elif sys.argv[1] == 'option':
    printoption = True
else:
    print('usage: scoop-rules <model|layout|variant|option>')
    exit(1)

lstfiles = glob.glob('/usr/share/X11/xkb/rules/*.lst')
if len(lstfiles) < 1:
    print('Could not find lst files')
    exit(2)

for lstfile in lstfiles:
    with open(lstfile, 'r') as lsthandle:
        printline = False
        for lstline in lsthandle.readlines():
            if printmodel:
                strippedline = lstline.strip()
                if strippedline.startswith('! model'):
                    printline = True
                    continue
                elif len(strippedline) == 0:
                    printline = False
                if not printline:
                    continue
                splitline = strippedline.split(' ')
                splitpart0 = splitline[0].strip()
                splitpart1 = ' '.join(splitline[1:]).strip()
                print('    { "%s", I18N_NOOP("%s") },' % (splitpart0, cstringify(splitpart1)))
            elif printlayout:
                strippedline = lstline.strip()
                if strippedline.startswith('! layout'):
                    printline = True
                    continue
                elif len(strippedline) == 0:
                    printline = False
                if not printline:
                    continue
                splitline = strippedline.split(' ')
                splitpart0 = splitline[0].strip()
                splitpart1 = ' '.join(splitline[1:]).strip()
                print('    { "%s", I18N_NOOP("%s") },' % (splitpart0, cstringify(splitpart1)))
            elif printvariant:
                strippedline = lstline.strip()
                if strippedline.startswith('! variant'):
                    printline = True
                    continue
                elif len(strippedline) == 0:
                    printline = False
                if not printline:
                    continue
                splitline = strippedline.split(' ')
                splitpart0 = splitline[0].strip()
                splitpart1 = ' '.join(splitline[1:]).strip()
                splitlayout = splitpart1.split(':')[0].strip()
                splitdescription = ' '.join(splitpart1.split(':')[1:]).strip()
                print('    { "%s", "%s", I18N_NOOP("%s") },' % (splitlayout, cstringify(splitpart0), cstringify(splitdescription)))
            elif printoption:
                strippedline = lstline.strip()
                if strippedline.startswith('! option'):
                    printline = True
                    continue
                elif len(strippedline) == 0:
                    printline = False
                if not printline:
                    continue
                splitline = strippedline.split(' ')
                splitpart0 = splitline[0].strip()
                splitpart1 = ' '.join(splitline[1:]).strip()
                print('    { "%s", I18N_NOOP("%s") },' % (splitpart0, cstringify(splitpart1)))


import pygame
import random
import numpy as np

class MainGame():
    window= None
    screenheight=600
    screenwidth=800
    color=pygame.Color(0,0,0)
    fontcolor=pygame.Color(255,0,0)
    tankp1=None
    enemytank_list=[]
    enemytank_count=10
    Bullet_list=[]
    enemybullet_list=[]
    explode_list=[]
    wall_list=[]
    sensor_b=None
    sensor_s=None
    sensor_r=None
    sensor_l=None
    def __init__(self):
        pygame.display.init()
        MainGame.window=pygame.display.set_mode([MainGame.screenwidth,MainGame.screenheight])
        self.reset()
        music = Music("tankimages/music.mp3")
        #music.play(-1)
        pygame.display.set_caption("TAMO V1.0")

#divide between init and play step
    def play_step(self,action):
        self.frame_iteration+=1
        self.getevent()
        MainGame.window.fill(MainGame.color)
        MainGame.window.blit(self.gettextsurface("the remaining tank number is %d"%len(MainGame.enemytank_list)),(5,5))
        self.blitwalls()
        self.blitmytank()
        self.blitsensors()
        MainGame.tankp1.move(action)
        self.blitenemytank()
        self.score = 10 - len(MainGame.enemytank_list)
        reward=0
        game_over=False
        self.blitbullet()
        self.blitenemybullet()
        self.displayexplodes()
        if len(MainGame.enemytank_list)==0:
            game_over=True
        for ebullet in MainGame.enemybullet_list:
            if ebullet.hitmytank():
                game_over=True
                reward=-10
                return reward,game_over,self.score
        for bullet in MainGame.Bullet_list:
            if bullet.hitenemytank():
                reward=10
        pygame.display.update()
        return reward,game_over,self.score

    def reset(self):
        for etank in MainGame.enemytank_list:
            etank.live = False
        for walls in MainGame.wall_list:
            walls.live = False
        for enemybullet in MainGame.enemybullet_list:
            enemybullet.live= False
        self.create_mytank()
        self.create_enemytank()
        self.create_walls()
        self.score=0
        self.frame_iteration = 0
        self.create_sensors()

    def create_enemytank(self):
        top=100
        for i in range(MainGame.enemytank_count):
            speed = random.randint(3, 6)
            left = random.randint(100, 700)
            etank=EnemyTank(left,top,speed)
            MainGame.enemytank_list.append(etank)
    def create_walls(self):
        for i in range(1,7):
            wall=Wall(120*i,300)
            MainGame.wall_list.append(wall)
    def create_sensors(self):
        MainGame.sensor_b=Sensor_back()
        MainGame.sensor_s=Sensor_straight()
        MainGame.sensor_r=Sensor_right()
        MainGame.sensor_l=Sensor_left()

    def blitwalls(self):
        for wall in MainGame.wall_list:
            if wall.live:
                wall.displaywall()
            else:
                MainGame.wall_list.remove(wall)
    def blitmytank(self):
        if MainGame.tankp1 and MainGame.tankp1.live:
            MainGame.tankp1.displaytank()
            MainGame.tankp1.hitwalls()
            MainGame.tankp1.hitenemytank()
            bullet=Bullet(MainGame.tankp1)
            if len(MainGame.Bullet_list) < 5:
                MainGame.Bullet_list.append(bullet)
        else:
            del MainGame.tankp1
            MainGame.tankp1=None
    def create_mytank(self):
        MainGame.tankp1 = Mytank(600, 200)
        #music=Music('tankimages/music.mp3')
        #music.play()

    def blitenemytank(self):
        for etank in MainGame.enemytank_list:
            if etank.live:
                etank.displaytank()
                etank.randmove()
                etank.hitwalls()
                etank.hitmytank()
                ebullet=etank.shot()
                if ebullet and len(MainGame.enemybullet_list)<5*self.enemytank_count:
                    MainGame.enemybullet_list.append(ebullet)
            else:
                MainGame.enemytank_list.remove(etank)
    def blitbullet(self):
        for bullet in MainGame.Bullet_list:
            if bullet.live:
                bullet.displaybullet()
                bullet.bulletmove()
                bullet.hitenemytank()
                bullet.hitwalls()
            else:
                MainGame.Bullet_list.remove(bullet)
    def blitenemybullet(self):
        for ebullet in MainGame.enemybullet_list:
            if ebullet.live:
                ebullet.displaybullet()
                ebullet.bulletmove()
                ebullet.hitwalls()
                #ebullet.hitsensors()
                if MainGame.tankp1 and MainGame.tankp1.live:
                    ebullet.hitmytank()
            else:
                MainGame.enemybullet_list.remove(ebullet)
    def displayexplodes(self):
        for explode in MainGame.explode_list:
            if explode.live:
                explode.displayexplode()
            else:
                MainGame.explode_list.remove(explode)

    def blitsensors(self):
        MainGame.sensor_b.displaysensor()
        MainGame.sensor_l.displaysensor()
        MainGame.sensor_r.displaysensor()
        MainGame.sensor_s.displaysensor()

    def is_collision_stright(self):
        if len(MainGame.enemybullet_list) >= 1:
            for enemy_bullet in MainGame.enemybullet_list:
                if pygame.sprite.collide_rect(MainGame.sensor_s, enemy_bullet):
                    return True
        return False

    def is_collision_back(self):
        if len(MainGame.enemybullet_list) >= 1:
            for enemy_bullet in MainGame.enemybullet_list:
                if pygame.sprite.collide_rect(MainGame.sensor_b, enemy_bullet):
                    return True
        return False

    def is_collision_left(self):
        if len(MainGame.enemybullet_list)>=1:
            for enemy_bullet in MainGame.enemybullet_list:
                if pygame.sprite.collide_rect(MainGame.sensor_l, enemy_bullet):
                    return True
        return False

    def is_collision_right(self):
        if len(MainGame.enemybullet_list) >= 1:
            for enemy_bullet in MainGame.enemybullet_list:
                if pygame.sprite.collide_rect(MainGame.sensor_r, enemy_bullet):
                    return True
        return False

    def determine_enemy_up(self):
        if len(MainGame.enemytank_list) >= 1:
            for etank in MainGame.enemytank_list:
                if etank.rect.top>MainGame.tankp1.rect.top:
                    return True
        return False

    def determine_enemy_down(self):
        if len(MainGame.enemytank_list) >= 1:
            for etank in MainGame.enemytank_list:
                if etank.rect.top<MainGame.tankp1.rect.top:
                    return True
        return False

    def determine_enemy_left(self):
        if len(MainGame.enemytank_list)>=1:
            for etank in MainGame.enemytank_list:
                if etank.rect.left<MainGame.tankp1.rect.left:
                    return True
        return False

    def determine_enemy_right(self):
        if len(MainGame.enemytank_list) >= 1:
            for etank in MainGame.enemytank_list:
                if etank.rect.left>MainGame.tankp1.rect.left:
                    return True
        return False
    def endgame(self):
        print("thanks for playing")
        exit()
    def getevent(self):
        eventlist = pygame.event.get()
        for event in eventlist:
            if event.type == pygame.QUIT:
                self.endgame()

    def gettextsurface(self,text):
        pygame.font.init()
        font=pygame.font.SysFont("laoui",18)
        textsurface=font.render(text,True,MainGame.fontcolor)
        return textsurface
class Baseitem(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__()

class Tank(Baseitem):
    def __init__(self,left,top):
        self.images = {
            "U":pygame.image.load('tankimages/tankup.jpg'),
            "D":pygame.image.load('tankimages/tankdown.jpg'),
            "L":pygame.image.load('tankimages/tankleft.jpg'),
            "R":pygame.image.load('tankimages/tankright.jpg')
        }
        self.direction = "U"
        self.image =self.images[self.direction]
        self.rect=self.image.get_rect()
        self.rect.left=left
        self.rect.top=top
        self.speed=5
        self.stop=True
        self.live=True
        self.oldleft=self.rect.left
        self.oldtop=self.rect.top

    def move(self,action):
        self.oldleft = self.rect.left
        self.oldtop = self.rect.top
        clock_wise = ["R", "D", "L", "U"]
        idx = clock_wise.index(self.direction)

        if np.array_equal(action, [1, 0, 0, 0]):
            new_dir = clock_wise[idx]  # no change
        elif np.array_equal(action, [0, 1, 0, 0]):
            next_idx = (idx + 1) % 4
            new_dir = clock_wise[next_idx]  # right turn r -> d -> l -> u
        elif np.array_equal(action, [0, 0, 1, 0]):
            next_idx = (idx - 1) % 4
            new_dir = clock_wise[next_idx]  # left turn r -> u -> l -> d
        elif np.array_equal(action, [0, 0, 0, 1]):
            next_idx = (idx + 2) % 4
            new_dir = clock_wise[next_idx]

        self.direction = new_dir
        if self.direction=="L":
            if self.rect.left>0:
                self.rect.left-=self.speed
        elif self.direction=="R":
            if self.rect.left+self.rect.height<MainGame.screenwidth:
                self.rect.left+=self.speed
        elif self.direction=="U":
            if self.rect.top>0:
                self.rect.top-=self.speed
        elif self.direction=="D":
            if self.rect.top+self.rect.height<MainGame.screenheight:
                self.rect.top+=self.speed
    def stay(self):
        self.rect.left=self.oldleft
        self.rect.top=self.oldtop
    def hitwalls(self):
        for wall in MainGame.wall_list:
            if pygame.sprite.collide_rect(wall,self):
                self.stay()

    def shot(self):
        num=random.randint(1,100)
        if num>=10:
            return Bullet(self)
    def displaytank(self):
        self.image = self.images[self.direction]
        MainGame.window.blit(self.image,self.rect)

class Mytank(Tank):
    def __init__(self,left,top):
        super(Mytank,self).__init__(left,top)
    def hitenemytank(self):
        for etank in MainGame.enemytank_list:
            if pygame.sprite.collide_rect(etank,self):
                self.stay()

class Sensor_straight():
    def __init__(self):
        self.direction=MainGame.tankp1.direction
        self.sensorimages={
            "U":pygame.image.load('tankimages/36x216.png'),
            "D":pygame.image.load('tankimages/36x216.png'),
            "L":pygame.image.load('tankimages/210x35.png'),
            "R":pygame.image.load('tankimages/210x35.png')
        }
        self.sensorimage = self.sensorimages[self.direction]
        self.rect = self.sensorimage.get_rect()

    def displaysensor(self):
        if self.direction=="L":
            self.rect.left=MainGame.tankp1.rect.left-210
            self.rect.top=MainGame.tankp1.rect.top
        elif self.direction=="R":
            self.rect.left = MainGame.tankp1.rect.left + 36
            self.rect.top = MainGame.tankp1.rect.top
        elif self.direction=="U":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top-216
        else:
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top +38
        MainGame.window.blit(self.sensorimage, self.rect)

class Sensor_back():
    def __init__(self):
        self.direction = MainGame.tankp1.direction
        self.sensorimages = {
            "U": pygame.image.load('tankimages/36x216.png'),
            "D": pygame.image.load('tankimages/36x216.png'),
            "L": pygame.image.load('tankimages/210x35.png'),
            "R": pygame.image.load('tankimages/210x35.png')
        }
        self.sensorimage = self.sensorimages[self.direction]
        self.rect = self.sensorimage.get_rect()

    def displaysensor(self):
        if self.direction=="L":
            self.rect.left=MainGame.tankp1.rect.left+36
            self.rect.top=MainGame.tankp1.rect.top
        elif self.direction=="R":
            self.rect.left = MainGame.tankp1.rect.left - 210
            self.rect.top = MainGame.tankp1.rect.top
        elif self.direction=="U":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top+38
        else:
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top -216
        MainGame.window.blit(self.sensorimage, self.rect)

class Sensor_left():
    def __init__(self):
        self.direction = MainGame.tankp1.direction
        self.sensorimages = {
            "U": pygame.image.load('tankimages/228x38.png'),
            "D": pygame.image.load('tankimages/228x38.png'),
            "L": pygame.image.load('tankimages/36x216.png'),
            "R": pygame.image.load('tankimages/36x216.png')
        }
        self.sensorimage = self.sensorimages[self.direction]
        self.rect = self.sensorimage.get_rect()

    def displaysensor(self):
        if self.direction == "L":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top - 35
        elif self.direction == "R":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top + 216
        elif self.direction == "U":
            self.rect.left = MainGame.tankp1.rect.left + 228
            self.rect.top = MainGame.tankp1.rect.top
        else:
            self.rect.left = MainGame.tankp1.rect.left - 36
            self.rect.top = MainGame.tankp1.rect.top
            MainGame.window.blit(self.sensorimage, self.rect)

class Sensor_right():
    def __init__(self):
        self.direction = MainGame.tankp1.direction
        self.sensorimages = {
            "U": pygame.image.load('tankimages/228x38.png'),
            "D": pygame.image.load('tankimages/228x38.png'),
            "L": pygame.image.load('tankimages/36x216.png'),
            "R": pygame.image.load('tankimages/36x216.png')
        }
        self.sensorimage = self.sensorimages[self.direction]
        self.rect = self.sensorimage.get_rect()

    def displaysensor(self):
        if self.direction == "L":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top + 216
        elif self.direction == "R":
            self.rect.left = MainGame.tankp1.rect.left
            self.rect.top = MainGame.tankp1.rect.top - 35
        elif self.direction == "U":
            self.rect.left = MainGame.tankp1.rect.left - 36
            self.rect.top = MainGame.tankp1.rect.top
        else:
            self.rect.left = MainGame.tankp1.rect.left + 228
            self.rect.top = MainGame.tankp1.rect.top
            MainGame.window.blit(self.sensorimage, self.rect)

class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        self.images = {
            "U": pygame.image.load('tankimages/enemytankup.jpg'),
            "D": pygame.image.load('tankimages/enemytankdown.jpg'),
            "L": pygame.image.load('tankimages/enemytankleft.jpg'),
            "R": pygame.image.load('tankimages/enemytankright.jpg')
        }
        self.direction = self.randirection()
        self.image = self.images[self.direction]
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        self.speed = speed
        self.stop = True
        self.step=20
        self.live=True
    def randirection(self):
        num=random.randint(1,4)
        if num==1:
            return"U"
        elif num==2:
            return"D"
        elif num==3:
            return"L"
        elif num==4:
            return"R"
    def randmove(self):
        if self.step <=0:
            self.direction=self.randirection()
            self.step=20
        else:
            self.move()
            self.step-=1
    def move(self):
        self.oldleft = self.rect.left
        self.oldtop = self.rect.top
        if self.direction=="L":
            if self.rect.left>0:
                self.rect.left-=self.speed
        elif self.direction=="R":
            if self.rect.left+self.rect.height<MainGame.screenwidth:
                self.rect.left+=self.speed
        elif self.direction=="U":
            if self.rect.top>0:
                self.rect.top-=self.speed
        elif self.direction=="D":
            if self.rect.top+self.rect.height<MainGame.screenheight:
                self.rect.top+=self.speed
    def shot(self):
        num=random.randint(1,100)
        if num <=10:
            return Bullet(self)
    def hitmytank(self):
        if MainGame.tankp1 and MainGame.tankp1.live:
            if pygame.sprite.collide_rect(self,MainGame.tankp1):
                self.stay()

class Bullet(Baseitem):
    def __init__(self,tank):
        self.image=pygame.image.load("tankimages/bullet.jpg")
        self.direction=tank.direction
        self.rect=self.image.get_rect()
        self.speed=15
        if self.direction=="U":
            self.rect.left=tank.rect.left+tank.rect.width/2-self.rect.width/2
            self.rect.top=tank.rect.top-self.rect.height
        elif self.direction=="D":
            self.rect.left = tank.rect.left + tank.rect.width / 2  -self.rect.width/2
            self.rect.top=tank.rect.top + tank.rect.height

        elif self.direction=="L":
            self.rect.left=tank.rect.left-self.rect.width
            self.rect.top = tank.rect.top + tank.rect.width / 2  -self.rect.width/2

        elif self.direction=="R":
            self.rect.left = tank.rect.left + tank.rect.width
            self.rect.top = tank.rect.top + tank.rect.width / 2 - self.rect.width / 2
        self.live=True

    def bulletmove(self):
        if self.direction== "U":
           if self.rect.top>0:
               self.rect.top-=self.speed
           else:
               self.live=False
        elif self.direction=="D":
            if self.rect.top<=MainGame.screenheight-self.rect.height:
                self.rect.top+=self.speed
            else:
                self.live = False

        elif self.direction=="L":
            if self.rect.left>0:
                self.rect.left-=self.speed
            else:
                self.live = False
        elif self.direction=="R":
            if self.rect.left<=MainGame.screenwidth-self.rect.width:
                self.rect.left+=self.speed
            else:
                self.live = False
    def displaybullet(self):
        MainGame.window.blit(self.image,self.rect)
    def hitenemytank(self):
        for etank in MainGame.enemytank_list:
            if pygame.sprite.collide_rect(etank,self):
                explode=Explode(etank)
                MainGame.explode_list.append(explode)
                self.live=False
                etank.live=False
                return True
    def hitmytank(self):
        if pygame.sprite.collide_rect(MainGame.tankp1, self):
            explode=Explode(MainGame.tankp1)
            MainGame.explode_list.append(explode)
            self.live=False
            MainGame.tankp1.live=False
            return True
    def hitwalls(self):
        for wall in MainGame.wall_list:
            if pygame.sprite.collide_rect(wall,self):
                self.live=False
                wall.hp-=1
                if wall.hp<=0:
                    wall.live=False
    #def hitsensors(self):
        #if pygame.sprite.collide_rect(MainGame.sensor_s,self):
            #explode = Explode(MainGame.sensor_s)
            #MainGame.explode_list.append(explode)
        #if pygame.sprite.collide_rect(MainGame.sensor_b,self):
            #explode = Explode(MainGame.sensor_b)
            #MainGame.explode_list.append(explode)
        #if pygame.sprite.collide_rect(MainGame.sensor_l,self):
            #explode = Explode(MainGame.sensor_l)
            #MainGame.explode_list.append(explode)
        #if pygame.sprite.collide_rect(MainGame.sensor_r,self):
            #explode = Explode(MainGame.sensor_r)
            #MainGame.explode_list.append(explode)

class Explode():
    def __init__(self,tank):
        self.rect=tank.rect
        self.step=0
        self.images=[                   pygame.image.load('tankimages/blast0.jpg'),
                                        pygame.image.load('tankimages/blast1.jpg'),
                                        pygame.image.load('tankimages/blast2.jpg'),
                                        pygame.image.load('tankimages/blast3.jpg'),
                                        pygame.image.load('tankimages/blast4.jpg')
                                        ]
        self.image=self.images[self.step]
        self.live=True
    def displayexplode(self):
        if self.step<len(self.images):
            MainGame.window.blit(self.image,self.rect)
            self.image=self.images[self.step]
            self.step+=1
        else:
            self.live=False
            self.step=0
class Wall():
    def __init__(self,left,top):
        self.image=pygame.image.load("tankimages/REDAIWALL.png")
        self.rect=self.image.get_rect()
        self.rect.left=left
        self.rect.top=top
        self.live=True
        self.hp=50
    def displaywall(self):
        MainGame.window.blit(self.image,self.rect)
class Music():
    def __init__(self,filename):
        pygame.mixer.init()
        self.filename=filename
        pygame.mixer.music.load(self.filename)
    def play(self,loops):
        pygame.mixer.music.play(loops)


from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from pgportfolio.marketdata.poloniex import Poloniex
from pgportfolio.marketdata.binance import Binance
from pgportfolio.tools.data import get_chart_until_success
import pandas as pd
from datetime import datetime
import logging
import pgportfolio.constants as const
import os.path
import json
import re

class CoinList(object):
    def __init__(self, market, end, volume_average_days=1, volume_forward=0, live=False, net_dir=""):
        logging.error('market = ' + market)
        if market == "binance":
            self._market = Binance()
        elif market == "poloniex":
            self._market = Poloniex()
        # connect the internet to accees volumes
        vol = self._market.marketVolume()
        logging.error('Got ' + str(len(vol.keys())) + ' volumes from ' + market)
        logging.error('Here are the volumes we got -- ' + str(vol))
        ticker = self._market.marketTicker()
        pairs = []
        coins = []
        volumes = []
        prices = []
        net_dir = net_dir.replace("/netfile", "")
        coins_fn = net_dir + "/coins.json";

#        if live == True and os.path.exists(net_dir) and os.path.isfile(coins_fn): # or if coin list file exists
        if live == True:
            if os.path.exists(net_dir) and os.path.isfile(coins_fn): # or if coin list file exists
                logging.error("Fetching coin list from file" + coins_fn)
                fh = open(coins_fn)
#            self._df.read_json(fh)
                self._df = pd.read_json(fh)
                fh.close()
#            self._df = json.load(net_dir + "/coin_list.json")
                logging.error("Got coin list from file: " + self._df.to_json());
                return
            else:
                logging.error("Live but coin list doesn't exist at " + net_dir + coins_fn)

#            return contents of file.

#        logging.info("select coin online from %s to %s" % (datetime.fromtimestamp(end - (const.DAY * volume_average_days) -
#                                                                                volume_forward).
#                                                           strftime('%Y-%m-%d %H:%M'),
#                                                           datetime.fromtimestamp(end - volume_forward).
#                                                           strftime('%Y-%m-%d %H:%M')))
        logging.error("select coin online from %s to %s" % (datetime.utcfromtimestamp(end - (const.DAY * volume_average_days) -
                                                                                volume_forward).
                                                           strftime('%Y-%m-%d %H:%M'),
                                                           datetime.utcfromtimestamp(end - volume_forward).
                                                           strftime('%Y-%m-%d %H:%M')))
        for k, v in vol.items():
            for banned in self._market.banlist: # This is fugly on several fronts
                if banned in k:
                    logging.error('Banning market ' + k)
                    break
            else:                               # Yes, this is an else on a for
                logging.error('Not banning market ' + k)
                if (k.startswith("BTC_") or k.endswith("_BTC")): # and k not in self._market.banlist:
                    pairs.append(k)
                    logging.error('pairs now has ' + str(len(pairs)) + ' markets after addition of ' + k)
                    for c, val in v.items():        #  'BTC_SNGLS': {'BTC': 86.646674, 'SNGLS': 22564238.0}, 'USDT_BTC': {'USDT': 360774817.608, 'BTC': 55350.2},
                        if c != 'BTC':
                            if k.endswith('_BTC'):
                                coins.append('reversed_' + c)
                                prices.append(1.0 / float(ticker[k]['last']))
                            else:
                                coins.append(c)
                                prices.append(float(ticker[k]['last']))
                        else:
                            logging.error('appending volume for ' + k)
                            volumes.append(self.__get_total_volume(pair=k, global_end=end,
                                                                   days=volume_average_days,
                                                                   forward=volume_forward))
        logging.error(str({'coin': coins, 'pair': pairs, 'volume': volumes, 'price': prices}))
        self._df = pd.DataFrame({'coin': coins, 'pair': pairs, 'volume': volumes, 'price': prices})
        self._df = self._df.set_index('coin')
        # Write coin list to file
        if (os.path.exists(net_dir)):
            logging.error("Writing coin list to file " + coins_fn)
            _json = self._df.to_json()
            #json.dump(self._df, net_dir + "/coin_list.json");
            fh = open(coins_fn, "w")
            fh.write(_json)
            fh.close()
        else:
            logging.error("Found no folder at " + net_dir)

    @property
    def allActiveCoins(self):
        return self._df

    @property
    def allCoins(self):
        return self._market.marketStatus().keys()

    @property
    def market(self):
        return self._market

    def getBalances(self):
#        balances = self._polo.balances(_polo);
#        balances = self._polo.balances(self._polo);
        balances = self._market.balances(); # TODO: add to binance
        # Ignore coins not managed by this algo.
#        logging.error("Balances: {}".format(balances));
        return balances;

    def get_chart_until_success(self, pair, start, period, end):
        return get_chart_until_success(self._market, pair, start, period, end)

    # get several days volume
    def __get_total_volume(self, pair, global_end, days, forward):
        start = global_end - (const.DAY * days) - forward
        end = global_end - forward
        chart = self.get_chart_until_success(pair=pair, period=const.DAY, start=start, end=end)
#        logging.error('get_chart_until_success(pair='+pair+', period=const.DAY, start='+str(start)+', end='+str(end)+') ===> '+str(chart))
        result = 0
        for one_day in chart:
            if pair.startswith("BTC_"):
                result += one_day['volume']
            else:
                result += one_day["quoteVolume"]
        return result

    def topNVolume(self, n=5, order=True, minVolume=0):
        if minVolume == 0:
            r = self._df.loc[self._df['price'] > 2e-6]
            r = r.sort_values(by='volume', ascending=False)[:n]
            print(r)
            if order:
                return r
            else:
                return r.sort_index()
        else:
            return self._df[self._df.volume >= minVolume]


from flask import Flask
from flask_environments import Environments
from flask.ext.sqlalchemy import SQLAlchemy
from flask_restful import Api
from cbibs_api.reverse_proxy import ReverseProxied
import os

app = Flask(__name__)
app.wsgi_app = ReverseProxied(app.wsgi_app)

env = Environments(app)

env.from_yaml('config.yml')
if os.path.exists('config.local.yml'):
    env.from_yaml('config.local.yml')

if app.config['LOGGING'] == True:
    import logging
    logger = logging.getLogger('pyprojects.app')
    logger.setLevel(logging.DEBUG)

    log_directory = app.config['LOG_FILE_PATH']
    log_filename = os.path.join(log_directory,app.config['LOG_FILE'])
    if not os.path.exists(os.path.dirname(log_filename)):
        os.makedirs(os.path.dirname(log_filename))
    file_handler = logging.FileHandler(log_filename, mode='a+')

    stream_handler = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s - %(process)d - %(name)s - %(module)s:%(lineno)d - %(levelname)s - %(message)s')
    file_handler.setFormatter(formatter)
    stream_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    #app.logger.addHandler(stream_handler)
    app.logger.setLevel(logging.DEBUG)
    app.logger.info('Application Process Started')

api = Api(app)
db = SQLAlchemy(app)


# resposta do curso
from time import sleep
for cont in range (10, -1, -1):
    print(cont)
    sleep(0.5)
print('BUM! BUM! POOW!')

print('-'*30)

# minha resposta
print('''SIM - *PERMISSÂO CONCEDIDA*
NÃO - *PERMISSÂO NÂO CONCEDIDA*''')
permissão = str(input('PERMISSÃO DA CONTAGEM: ')).upper()
print('-='*20)
from time import sleep
for c in range (5, -1, -1):
    if permissão == 'SIM':
        print(c)
        sleep(1)
if permissão == 'SIM':
    print('BOOOOMMMMM!!!! POWWW!!! CABUMMM!!')
else:
    print('PERMISSÃO NÃO AUTORIZADA')

print('-'*30)

# treinando
from time import sleep
permissao = str(input('PERMISSÃO PARA CONTAGEM: [S/N] ')).upper().strip()[0]
for contagem in range (5, -1, -1):
    if permissao == 'S':
        print(contagem)
        sleep(1)
if permissao == 'S':
    print('BUMMM !! CABUUMMM')
else:
    print('OPERAÇÃO ENCERRADA...')


import unittest
from solution import solution

class MyTestCase(unittest.TestCase):
    def test_something(self):
        clothes1 = [["yellowhat", "headgear"], ["bluesunglasses", "eyewear"], ["green_turban", "headgear"]]
        self.assertEqual(solution(clothes1), 5)
        clothes2 = [["crowmask", "face"], ["bluesunglasses", "face"], ["smoky_makeup", "face"]]
        self.assertEqual(solution(clothes2), 3)

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


# Jesus Carlos Martinez Gonzalez
# 16/10/2023
# Mahasena (https://www.codechef.com/problems/AMR15A)

"""
Kattapa, as you all know was one of the greatest warriors of his time. The kingdom of Maahishmati had
never lost a battle under him (as army-chief), and the reason for that was their really powerful army,
also called as Mahasena.
Kattapa was known to be a very superstitious person. He believed that a soldier is "lucky" if the soldier
is holding an even number of weapons, and "unlucky" otherwise. He considered the army as "READY
FOR BATTLE" if the count of "lucky" soldiers is strictly greater than the count of "unlucky" soldiers, and
"NOT READY" otherwise.
Given the number of weapons each soldier is holding, your task is to determine whether the army
formed by all these soldiers is "READY FOR BATTLE" or "NOT READY".
"""

n = int(input())
lst = list(map(int, input().split()))
even = odd = 0
for x in lst:
    if x % 2 == 0:
        even += 1
    else:
        odd += 1
print("READY FOR BATTLE" if even > odd else "NOT READY")


# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
modify from: https://github.com/boudinfl/pke/blob/master/pke/readers.py
"""
import re

import jieba
import jieba.posseg as pseg
import pandas as pd
from loguru import logger
from pke_zh.data_structures import Document

jieba.setLogLevel('ERROR')

def load_document_frequency_file(input_file, delimiter='\t'):
    """Load a tsv (tab-separated-values) file containing document frequencies.
    Automatically detects if input file is compressed (gzip) by looking at its
    extension (.gz).

    Args:
        input_file (str): the input file containing document frequencies in
            csv format.
        delimiter (str): the delimiter used for separating term-document
            frequencies tuples, defaults to '\t'.

    Returns:
        dict: a dictionary of the form {term_1: freq}, freq being an integer.
    """

    df_freq = pd.read_csv(input_file, sep=delimiter)
    df_freq['frequence'] = df_freq['frequence'].map(int)
    frequencies = df_freq.set_index('word').to_dict()['frequence']

    # return the populated dictionary
    return frequencies

def flatten_tuples(tuple_list):
    """
    :param tuple_list: list of list, each list contains tuple elements.
    :return: flatten tuple list
    """
    result = [t for tlist in tuple_list for t in tlist]
    return result

def fetch_nested_list_elements(nested_list, idx):
    """
    Fetch target elements from nested list
    :param nested_list: list of list, each list is a tuple
    :param idx: target index in a tuple
    :return: list of list, each list contains target elements
    """
    result = [[t[idx] for t in inner_list] for inner_list in nested_list]
    return result

def reduce_charoffset(list_str):
    """
    Reduce char offset
    :param list_str: list of string
    """
    len_list = [len(x) for x in list_str]
    cur_sum = 0
    res = [0]
    for i in range(len(len_list) - 1):
        cur_sum += len_list[i]
        res.append(cur_sum)
    offset = [(x, x + len_list[i]) for i, x in enumerate(res)]
    return offset

def cut_sent(para):
    """
    Split paragraph into sentences
    :param para: paragraph
    """
    para = re.sub('([。！？\?;；])([^”’])', r"\1\n\2", para)
    para = re.sub('(\.{6})([^”’])', r"\1\n\2", para)
    para = re.sub('(\…{2})([^”’])', r"\1\n\2", para)
    para = re.sub('([。！？；;\?][”’])([^，。！？\?])', r'\1\n\2', para)
    para = para.rstrip()
    paras = [p.strip() for p in para.split("\n") if p.strip()]
    return paras

class ChineseNLP(object):
    def __init__(self, max_length=1e6):
        self.max_length = max_length

    def __call__(self, text):
        """Split sentences
        Args:
            text(str): text for NLP Pipeline Processing.
        """
        clean_text = self.clean(text)
        sentences = cut_sent(clean_text)

        pseg_results, words, postags = self.sentence_pseg(sentences)

        char_offsets = list(map(lambda ws: reduce_charoffset(ws), words))

        # flatten char_offsets and make global index in the document.
        global_char_offsets = [char_offsets[0]]
        last_sent_offset = char_offsets[0][-1][1]
        for offsets in char_offsets[1:]:
            new_offset = [(x[0] + last_sent_offset, x[1] + last_sent_offset) for x in offsets]
            last_sent_offset = new_offset[-1][1]
            global_char_offsets.append(new_offset)
        global_char_offsets = flatten_tuples(global_char_offsets)

        result = [{'words': ws,
                   'POS': postags[i],
                   'char_offsets': char_offsets[i],
                   'global_char_offsets': global_char_offsets,
                   'word_POS': pseg_results}
                  for i, ws in enumerate(words)]
        return result

    def sentence_pseg(self, sentences):
        """Segment sentences into words and POS tags."""
        results = [[(s.word, s.flag) for s in pseg.cut(sent)] for sent in sentences]
        words = fetch_nested_list_elements(results, 0)
        postags = fetch_nested_list_elements(results, 1)
        return results, words, postags

    def clean(self, text):
        """Clean text."""
        text = re.sub(r'img[_\d]+', '', text.strip())
        text = re.sub(r'_SEG_', '', text.strip())
        return text

class Reader(object):
    def read(self, path):
        raise NotImplementedError

class RawTextReader(Reader):
    """Reader for raw text."""

    def __init__(self, language='zh'):
        """Constructor for RawTextReader.

        Args:
            language (str): language of text to process.
        """

        self.language = language
        if self.language != 'zh':
            logger.warning('toolkit is built for zh language')
        self.nlp = ChineseNLP()

    def read(self, text, **kwargs):
        """Read the input file and use spacy to pre-process.

        Args:
            text (str): raw text to pre-process.
            max_length (int): maximum number of characters in a single text for
                spacy, default to 1,000,000 characters (1mb).
        """
        sentences = self.nlp(text)
        doc = Document.from_sentences(sentences,
                                      input_file=kwargs.get('input_file', None),
                                      **kwargs)

        return doc


import requests

from old_parser_task.serializers import serializer_factory

class ParseRequest:
    """
    Класс для загрузки и обновления данных справочников из внешнего API.
    :param table_correspondences: словарь соответствий полей api и полей модели. Ключами являются наименования полей
    json, значениями - наименования полей модели соответствующих им.
    :param url: ссылка на внешнюю API, из которой будет проводиться загрузка данных с указанием параметра pageNum.
    :param model: модель, в которую необходимо обеспечить загрузку/обновление данных
    :param code_field: наиименование поля json в котором содержится внешний код записи, соотнеся который с полем
    модели можно найти можно найти данную запись если она существует
    :param start_page: страница с которой начинается загрузка данных из API (по умолчанию загрузка начинается
    с 1 страницы)
    :param foreign_key_fields: словарь соответствий полей модели при наличии связей с другой моделью:
    ключами являеются наименование поля json, которое соответствует полю модели, в которую заносятся даннные,
    значениями являютсяя списоки из трех значениий:
    0 - модель, к которой идет связь, 1 - наименование поля связной модели по которому строится фильтр,
    2 - наименование поля в json, которое соответствует полю в связной модели
    """

    def __init__(self, table_correspondences, url, model, code_field, foreign_key_fields=None, start_page=1):
        """
        :param table_correspondences: словарь соответствий полей api и полей модели. Ключами являются наименования полей
        json, значениями - наименования полей модели соответствующих им.
        :param url: ссылка на внешнюю API, из которой будет проводиться загрузка данных с указанием параметра pageNum.
        :param model: модель, в которую необходимо обеспечить загрузку/обновление данных
        :param code_field: наиименование поля json в котором содержится внешний код записи, соотнеся который с полем
        модели можно найти можно найти данную запись если она существует
        :param start_page: страница с которой начинается загрузка данных из API (по умолчанию загрузка начинается
        с 1 страницы)
        :param foreign_key_fields: словарь соответствий полей модели при наличии связей с другой моделью:
        ключами являеются наименование поля json, которое соответствует полю модели, в которую заносятся даннные,
        значениями являютсяя списоки из трех значениий:
        0 - модель, к которой идет связь, 1 - наименование поля связной модели по которому строится фильтр,
        2 - наименование поля в json, которое соответствует полю в связной модели
        """
        self.table_correspondences = table_correspondences
        self.url = url
        self.model = model
        self.code_field = code_field
        self.foreign_key_fields = foreign_key_fields
        self.start_page = start_page

    def download_external_api(self):
        """
        Метод для получения набора данных из внешней API и сохранение их в модель.
        При вызове данного метода начинается загрузка и сохранение данных из внешней API.
        """
        # определение списока для занесения туда записей, у которых небыло найдено указанных связей
        list_without_con = []
        # нахождение параметра pageNum в url
        for_replace = None
        for u in self.url.split('&'):
            if 'pageNum' in u:
                for_replace = u
        page = self.start_page
        # получение параметров extra_keywords и json_fields необходимых для создания сериализатора
        extra_keywords = self.get_extra_kwargs()
        json_fields = self.get_json_fields()
        # создание сериализатора с заданными параметрами
        serializer = serializer_factory(mod=self.model, list_fields=json_fields,
                                        extra_keywords=extra_keywords,
                                        field_code=self.code_field,
                                        dict_foreign_key_fields=self.foreign_key_fields)
        # начало загрузки. загрузка останавливается в случае, если пришел пустой ответ с пустыми данными
        # или произошла ошибка
        while True:
            # построение url для запроса
            base_url = self.url.replace(for_replace, f"pageNum={page}")
            print(f"url по которой происходит запрос: {base_url}")
            # отправка запроса
            r = requests.get(base_url, timeout=10)
            if (r.status_code == 200) and (r.json()['data']):
                # в случае непустого корректного ответа вычленение данных
                data = r.json()['data']

                data += list_without_con
                list_without_con = []

                for d in data:
                    # занесение записи в сериализатор, проведение валидации и в случае корректноси сохранение
                    ser = serializer(data=d)
                    if not ser.is_valid():
                        print(ser.errors)
                        continue
                    ser.save()
                    # В случае флага True запись является без указанной связи, определение этого и отправка такой
                    # записи на следующую иттерацию если такая есть
                    if ser.flag_without_connection:
                        list_without_con.append(d)

                print(f"Страница {page} из api загружена в модель\n")
                page += 1
            else:
                print(f"Загрузка завершилась на {page} странице")
                if self.foreign_key_fields:
                    print(f"Записей без связей {len(list_without_con)}")
                break

    def get_extra_kwargs(self) -> dict:
        """
        Метод для получения параметра extra_keywords, необходимого для создания сериализатора.
        Необходим для приведения входной таблицы соответствий полей к формату, требующему параметром extra_kwargs
        Meta класса сериализатора.
        """
        extra_kwargs = {}
        for (key, value) in self.table_correspondences.items():
            if key != value:
                extra_kwargs[key] = {'source': value}
        return extra_kwargs

    def get_json_fields(self) -> tuple:
        """
        Метод для получения параметра list_fields, необходимого для создания сериализатора.
        Является списком полей json, которые необходимо занести в модель.
        """
        json_fields = []
        for (key, value) in self.table_correspondences.items():
            json_fields.append(key)
        return tuple(json_fields)


import pygame
from cons import *
import random

class Plane:
    def __init__(self, x, y, image=pygame.image.load(r'C:\Users\hipaa\OneDrive\Pictures\hero_plane.png')):
        self.image = image
        self.x = x
        self.y = y
        self.direction = 5

    def blit(self, screen):
        screen.blit(self.image, (self.x, self.y))
        self.move()

    def move(self):
        if self.direction == UP:
            self.y -= 15
            if self.y < 0:
                self.y = 0
        elif self.direction == DOWN:
            self.y += 15
            if self.y > 800-97:
                self.y = 800-97
        elif self.direction == LEFT:
            self.x -= 15
            if self.x < 0:
                self.x = 0
        elif self.direction == RIGHT:
            self.x += 15
            if self.x > 480-97:
                self.x = 480-97

class Bullet:
    def __init__(self, plane, image=pygame.image.load(r'D:\Users\hipaa\Desktop\一些文件\打飞机游戏\素材\15465750502243.png')):
        self.x = plane.x + 97//2-1
        self.y = plane.y
        self.image = image

    def fly(self):
        self.y -= 35

    def blit(self, screen):
        screen.blit(self.image, (self.x, self.y))
        self.fly()