# Course: CS261 - Data Structures
# Student Name:
# Assignment:
# Description:
# Last revised:

from dynamic_array import *

class Bag:
    def __init__(self, start_bag=None):
        """
        Init new bag based on Dynamic Array
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self.da = DynamicArray()

        # populate bag with initial values (if provided)
        # before using this feature, implement add() method
        if start_bag is not None:
            for value in start_bag:
                self.add(value)

    def __str__(self) -> str:
        """
        Return content of stack in human-readable form
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        out = "BAG: " + str(self.da.length()) + " elements. ["
        out += ', '.join([str(self.da.get_at_index(_))
                          for _ in range(self.da.length())])
        return out + ']'

    def size(self) -> int:
        """
        Return total number of items currently in the bag
        DO NOT CHANGE THIS CLASS IN ANY WAY
        """
        return self.da.length()

    def add(self, value: object) -> None:
        self.da.append(value)
        pass

    def remove(self, value: object) -> bool:
        for i in range(self.da.size):
            if (self.da.data[i] == value):
                self.da.remove_at_index(i)
                return True
        return False

    def count(self, value: object) -> int:
        count = 0
        for i in range(self.da.size):
            if (self.da.data[i] == value):
                count += 1
        return count

    def clear(self) -> None:
        for i in range(self.da.size):
            self.da.data[i] = None
        self.da.size = 0
        pass

    def equal(self, second_bag: object) -> bool:
        test = True
        if (self.da.size != second_bag.da.size):
            return False

        self2 = DynamicArray()
        while (self2.capacity < self.da.capacity):
            self2.resize(self2.capacity*2)

        for i in range(0, self.da.size):
            for j in range(0, second_bag.da.size):
                if (self.da.data[i] == second_bag.da.data[j]):
                    self2.data[i] = second_bag.da.data[j]

        print(self2)
        print(self)

        for i in range(0, self.da.size):
            if (self.da.data[i] == self2.data[i]):
                test = True
            else:
                return False

        return test

# BASIC TESTING
if __name__ == "__main__":

    print("\n# add example 1")
    bag = Bag()
    print(bag)
    values = [10, 20, 30, 10, 20, 30]
    for value in values:
        bag.add(value)
    print(bag)

    print("\n# remove example 1")
    bag = Bag([1, 2, 3, 1, 2, 3, 1, 2, 3])
    print(bag)
    print(bag.remove(7), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)

    print("\n# count example 1")
    bag = Bag([1, 2, 3, 1, 2, 2])
    print(bag, bag.count(1), bag.count(2), bag.count(3), bag.count(4))

    print("\n# clear example 1")
    bag = Bag([1, 2, 3, 1, 2, 3])
    print(bag)
    bag.clear()
    print(bag)

    print("\n# equal example 1")
    bag1 = Bag([10, 20, 30, 40, 50, 60])
    bag2 = Bag([60, 50, 40, 30, 20, 10])
    bag3 = Bag([10, 20, 30, 40, 50])
    bag_empty = Bag()

    print(bag1, bag2, bag3, bag_empty, sep="\n")
    print(bag1.equal(bag2), bag2.equal(bag1))
    print(bag1.equal(bag3), bag3.equal(bag1))
    print(bag2.equal(bag3), bag3.equal(bag2))
    print(bag1.equal(bag_empty), bag_empty.equal(bag1))
    print(bag_empty.equal(bag_empty))
    print(bag1, bag2, bag3, bag_empty, sep="\n")

    bag1 = Bag([100, 200, 300, 200])
    bag2 = Bag([100, 200, 30, 100])
    print(bag1.equal(bag2))


from PIL import Image

input_image = Image.open("test_image2.png")

pixel_map = input_image.load()

width, height = input_image.size
test = input_image.getpixel((1,2))
# taking half of the width:
for i in range(width//2):
	for j in range(height):
		# getting the RGB pixel value.
		r, g, b, random_other_value_i_dont_understand = input_image.getpixel((i, j))

		# Apply formula of grayscale:
		grayscale = (0*r + 0*g + 0*b)

		# setting the pixel value.
		pixel_map[i, j] = (int(grayscale), int(grayscale), int(grayscale))

		# Saving the final output
		# as "grayscale.png":
		input_image.save("grayscale.png", format="png")

input_image.show()		# output screen.`


"""
Functions to perform a simulation of a trajectory.
"""

import numpy as np
from YGRW.trajectory import Trajectory
from YGRW.steps import Stepper, UniformSteps, FBMSteps
from tqdm import tqdm

def generate_trajectory(
    timesteps: int,
    dt: float = 0.21,
    stepper: Stepper = UniformSteps(),
    initial_position: np.ndarray = np.array((0, 0)),
    locus_radius: float = 0.01,
    bound_zone_thickness: float = 0,
    nuclear_radius: float = 1.0,
    bound_to_bound: float = 0.5,
    unbound_to_bound: float = 0.2,
    watch_progress: bool = False,
    fail_cutoff: int = 200,
    write_after: bool = False,
    write_format: str = "csv",
):
    """
    All length-scale units are in micron.

    Parameters
    ----------
    initial_position: Initial position of the locus
    timesteps: Duration of simulation
    dt: time between each step
    locus_radius: Size of particle (units of micron)
    nuc_radius: Size of nucleus (units of micron)

    Returns: Trajectory object
    -------

    """

    traj = Trajectory(
        initial_position=initial_position,
        dt=dt,
        nuclear_radius=nuclear_radius,
        locus_radius=locus_radius,
        bound_zone_thickness=bound_zone_thickness,
        bound_to_bound=bound_to_bound,
        unbound_to_bound=unbound_to_bound,
    )

    if isinstance(stepper, FBMSteps):
        assert stepper.step_batchsize == timesteps, (
            "Batch for random generation" "must agree with run length."
        )

    taken_steps = 0
    failed_steps = 0
    if watch_progress:
        pbar = tqdm(total=timesteps)

    # Central loop of Trajectory runner
    # 1. Determine if next step will be bound,
    # 2. Attempt to take next step, Rescale step depending on if bound or not,
    # 3. Adjust step if step is invalid

    while taken_steps < timesteps:

        traj.bound_states.append(
            generate_current_bound(traj, bound_to_bound, unbound_to_bound)
        )
        while failed_steps < fail_cutoff:
            if traj.is_bound:
                cur_step = stepper.generate_bound_step(
                    prev_step=traj.prev_step, prev_angle=traj.prev_angle
                )
            else:
                cur_step = stepper.generate_step(
                    prev_step=traj.prev_step, prev_angle=traj.prev_angle
                )

            if traj.check_step_is_valid(step=cur_step, is_bound=traj.is_bound):
                traj.take_step(cur_step)
                taken_steps += 1
                if watch_progress:
                    pbar.update(1)
                failed_steps = 0
                break
            else:
                cur_step = traj.step_rescale(step=cur_step, is_bound=traj.is_bound)
                # If using the FLE stepper, it must regen noise after collision
                if "FBM" in str(stepper):
                    stepper.regenerate_correlated_noise()
                # If step mod cannot take a real step, no step is taken

                rad_post_step = traj.radius_post_step(step=cur_step)

                if rad_post_step > traj.nuclear_radius:
                    cur_step = np.zeros(2)
                # Same as above, but for bound steps and bound barrier
                elif traj.is_bound and rad_post_step < (
                    traj.nuclear_radius - traj.bound_zone_thickness
                ):
                    cur_step = np.zeros(2)
                # Take newly adjusted step
                traj.take_step(cur_step)
                taken_steps += 1
                if watch_progress:
                    pbar.update(1)
                failed_steps += 1
                break

        if failed_steps == fail_cutoff:
            print(f"Warning: Run got stuck at step {taken_steps}")
            raise

    if watch_progress:
        pbar.close()

    if write_after:

        optional_header = ""
        optional_header += f"stepper:{stepper.__class__.__name__},"
        traj.write_trajectory(
            output_file=None, format=write_format, optional_header_add=optional_header
        )

    return traj

def generate_current_bound(
    traj: Trajectory,
    bound_to_bound: float = 0,
    unbound_to_bound: float = 0,
) -> bool:
    """
    Bound transition parameters describe the probability the next
    step's state is bound, and allows it to be asymmetric.

    Parameters
    ----------
    traj
    bound_to_unbound
    unbound_to_bound

    Returns
    -------
    bool: If next step will be bound or not.
    """

    # Determine if edge of locus is within the bound cutoff zone.
    cutoff_radius = traj.nuclear_radius - traj.bound_zone_thickness
    locus_extent = np.linalg.norm(traj.position) + traj.locus_radius

    in_bound_zone = cutoff_radius < locus_extent

    if not in_bound_zone:
        return False

    # If CURRENTLY bound, test if remains bound
    if traj.is_bound:
        return np.random.uniform() < bound_to_bound
    # If NOT bound, test if becomes bound
    else:
        return np.random.uniform() < unbound_to_bound


import turtle
import math

def square(t, length):
    try:
        for i in range(4):
        	t.fd(length)
        	t.lt(90)
        print(t)
        turtle.mainloop()
    except Exception:
        print("Error!")

def polygon(t, length, n):
    try:
        for i in range(n):
        	t.fd(length)
        	t.lt(360 / n)
        print(t)
        turtle.mainloop()
    except Exception:
        print("Error!")

def circle(t, radius, n):
	"""Draws a circle with the given radius and n lines
	"""
	length = 2 * math.pi * radius / n
	polygon(t, length, n)

def arc(t, radius, angle, n):
	"""Draws an arc with the given radius and angle using n lines
	"""
	arc_length = 2 * math.pi * radius * angle / 360
	try:
		for i in range(n):
			t.fd(arc_length/n)
			t.lt(angle/n)
		print(t)
		turtle.mainloop()

	except Exception:
		print("Error!")

bob = turtle.Turtle()
arc(bob, 120, 234, 50)


#!/usr/bin/env python

from __future__ import print_function

import argparse
import socket
import time

UDP_PORT = 30303
TCP_PORT = 40404

UDP_STRING = "hello udp\x00"
TCP_STRING = "hello tcp\x00"

def udp_test(server_ip_address):
    """Perform the UDP test.

    """

    print("opening socket")
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    print("binding to '':{}".format(UDP_PORT))
    sock.bind(('', UDP_PORT))

    print("sending '{}' to ('{}', {})".format(UDP_STRING,
                                              server_ip_address,
                                              UDP_PORT))
    sock.sendto(UDP_STRING, (server_ip_address, UDP_PORT))

    string, address = sock.recvfrom(1024)
    print("received '{}' from {}".format(string, address))

    assert string == UDP_STRING

    print("closing socket")
    sock.close()

def tcp_test(server_ip_address):
    """Perform the TCP test.

    """

    print("opening socket")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    print("connecting to {}:{}".format(server_ip_address,
                                       TCP_PORT))
    sock.connect((server_ip_address, TCP_PORT))

    print("sending '{}'".format(TCP_STRING))
    sock.sendall(TCP_STRING)

    string = sock.recv(len(TCP_STRING))
    print("received '{}'".format(string))

    assert string == TCP_STRING

    print("closing socket")
    sock.close()

def main():
    """Main function.

    """

    parser = argparse.ArgumentParser()

    parser.add_argument('--server-ip-address',
                        default='192.168.1.103',
                        help='Server ip address.')
    args = parser.parse_args()

    udp_test(args.server_ip_address)
    time.sleep(1)
    tcp_test(args.server_ip_address)

if __name__ == '__main__':
    main()


import appscript as appscript
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QTextEdit, QMessageBox, \
    QRadioButton, QLabel, QLineEdit, QButtonGroup, QComboBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from numpy import binary_repr
import json
from collections import deque
import sys
import os
import datetime
import platform

class Register:
    def __init__(self, name):
        self.name = name
        self.valueDecimal = 0
        self.valueNH = binary_repr(0, 8)
        self.valueNL = binary_repr(0, 8)

class App(QMainWindow):

    def __init__(self):
        super().__init__()

        self.title = 'Microcontroller Simulator'
        self.left = 200
        self.top = 300
        self.width = 800
        self.height = 400
        self.initUI()

        self.registers = [Register('AX'), Register('BX'), Register('CX'), Register('DX')]
        self.stack = deque()
        self.stack_operator = [False, False]

        self.step = 0
        self.wyraz_num = 0
        self.commands = []

        for c in range(12):
            self.commands.append([])
            for i in range(3):
                self.commands[c].append('')

    def initUI(self):
        self.setWindowTitle(self.title)

        self.setGeometry(self.left, self.top, self.width, self.height)

        self.command_button_group = QButtonGroup()
        self.register_part_group = QButtonGroup()

        # Create textbox
        self.textbox = QTextEdit(self)
        self.textbox.move(20, 20)
        self.textbox.resize(280, 200)
        self.textbox.setDisabled(True)
        self.textbox.setStyleSheet('background-color: white; color: black')

        # Create textbox line numeration
        self.labelLinenumeration = QLabel(
            ("1
2
3
4
5
6
7
8
9
10
11
12
"), self)
        self.labelLinenumeration.move(2, 26)
        self.labelLinenumeration.resize(16, 200)

        # Create command's radio buttons with a label

        self.labelcommands = QLabel("Rozkazy: ", self)
        self.buttonMOV = QRadioButton("MOV", self)  # 1
        self.buttonADD = QRadioButton("ADD", self)  # 2
        self.buttonSUB = QRadioButton("SUB", self)  # 3

        self.command_button_group.addButton(self.buttonMOV, 1)
        self.command_button_group.addButton(self.buttonADD, 2)
        self.command_button_group.addButton(self.buttonSUB, 3)

        self.labelcommands.move(305, 23)
        self.buttonMOV.move(315, 50)
        self.buttonADD.move(315, 70)
        self.buttonSUB.move(315, 90)

        # Create register's radio buttons with a label

        self.labelregisters = QLabel("Rejestry: ", self)
        self.buttonAX = QRadioButton("AX", self)
        self.buttonBX = QRadioButton("BX", self)
        self.buttonCX = QRadioButton("CX", self)
        self.buttonDX = QRadioButton("DX", self)

        self.labelregister_part = QLabel("Częśc rejestru: ", self)
        self.buttonNX = QRadioButton("NX", self)
        self.buttonNH = QRadioButton("NH", self)
        self.buttonNL = QRadioButton("NL", self)

        self.register_part_group.addButton(self.buttonNX, 1)
        self.register_part_group.addButton(self.buttonNH, 2)
        self.register_part_group.addButton(self.buttonNL, 3)

        self.command_button_group.addButton(self.buttonAX, 4)
        self.command_button_group.addButton(self.buttonBX, 5)
        self.command_button_group.addButton(self.buttonCX, 6)
        self.command_button_group.addButton(self.buttonDX, 7)

        self.labelregisters.move(445, 23)
        self.buttonAX.move(455, 50)
        self.buttonBX.move(455, 70)
        self.buttonCX.move(455, 90)
        self.buttonDX.move(455, 110)

        self.labelregister_part.move(445, 190)
        self.buttonNX.move(455, 210)
        self.buttonNH.move(455, 230)
        self.buttonNL.move(455, 250)

        # Buttons and labels for adding number to the command in the textbox

        self.labelinsertnumber = QLabel("Podaj liczbę z \nprzedziału <0, 65535>: ", self)
        self.buttonInsertnumber = QRadioButton("Liczba", self)
        self.textInsertNumber = QLineEdit(self)

        self.command_button_group.addButton(self.buttonInsertnumber, 8)

        self.textInsertNumber.resize(100, 20)
        self.labelinsertnumber.resize(150, 31)

        self.labelinsertnumber.move(545, 80)
        self.buttonInsertnumber.move(545, 50)
        self.textInsertNumber.move(550, 120)

        # Create button for inserting values from check buttons to the textbox
        self.buttonInsert = QPushButton('Wprowadź', self)
        self.buttonInsert.move(640, 180)
        self.buttonInsert.clicked.connect(self.insert_word)

        # Create button for deleting words from textbox
        self.buttonDelete = QPushButton('Usuń', self)
        self.buttonDelete.move(540, 180)
        self.buttonDelete.clicked.connect(self.delete_word)

        # Create label for errors
        self.labelErrors = QLabel("", self)
        self.labelErrors.setStyleSheet('color: red')
        self.labelErrors.resize(200, 30)
        self.labelErrors.move(390, 150)

        # Create button for saving to a file
        self.buttonSave = QPushButton('Zapisz', self)
        self.buttonSave.move(590, 360)
        self.buttonSave.clicked.connect(self.save_file)
        self.buttonSave.setIcon(QIcon("save.png"))

        # Create button for saving to a file
        self.buttonLoad = QPushButton('Wczytaj', self)
        self.buttonLoad.move(690, 360)
        self.buttonLoad.clicked.connect(self.load_file)
        self.buttonLoad.setIcon(QIcon("load.png"))

        # Create button for running the compiler
        self.buttonRun = QPushButton('Kompiluj', self)
        self.buttonRun.move(85, 215)
        self.buttonRun.clicked.connect(self.run)
        self.buttonRun.setIcon(QIcon("play.png"))

        # Create button for step running the compiler
        self.buttonStep = QPushButton('Praca krokowa', self)
        self.buttonStep.adjustSize()
        self.buttonStep.move(175, 215)
        self.buttonStep.clicked.connect(self.step_run)

        # Create labels for bit represenation of registers values

        self.labelAX = QLabel("AX", self)
        self.labelBX = QLabel("BX", self)
        self.labelCX = QLabel("CX", self)
        self.labelDX = QLabel("DX", self)

        self.labelNH = QLabel("NH", self)
        self.labelNL = QLabel("NL", self)

        self.labelAXNH = QLabel("00000000", self)
        self.labelBXNH = QLabel("00000000", self)
        self.labelCXNH = QLabel("00000000", self)
        self.labelDXNH = QLabel("00000000", self)

        self.labelAXNL = QLabel("00000000", self)
        self.labelBXNL = QLabel("00000000", self)
        self.labelCXNL = QLabel("00000000", self)
        self.labelDXNL = QLabel("00000000", self)

        self.labelAX.move(20, 255)
        self.labelBX.move(20, 285)
        self.labelCX.move(20, 315)
        self.labelDX.move(20, 345)

        self.labelNH.move(105, 235)
        self.labelNL.move(175, 235)

        self.labelAXNH.move(80, 255)
        self.labelBXNH.move(80, 285)
        self.labelCXNH.move(80, 315)
        self.labelDXNH.move(80, 345)

        self.labelAXNL.move(150, 255)
        self.labelBXNL.move(150, 285)
        self.labelCXNL.move(150, 315)
        self.labelDXNL.move(150, 345)

        ##############################################
        # Microcontroller interruption functions
        ##############################################

        # Create interruption radio buttons with a label and dropdown menu

        self.labelInterruption = QLabel("Przerwania: ", self)
        self.buttonDropdown = QRadioButton("INT", self)
        self.int_dropdown = QComboBox(self)

        self.command_button_group.addButton(self.buttonDropdown, 9)

        self.int_dropdown.addItem("INT0")
        self.int_dropdown.addItem("INT1")
        self.int_dropdown.addItem("INT2")
        self.int_dropdown.addItem("INT3")
        self.int_dropdown.addItem("INT6")
        self.int_dropdown.addItem("INT2A")
        self.int_dropdown.addItem("INT2C")
        self.int_dropdown.addItem("INT30")
        self.int_dropdown.addItem("INT49")
        self.int_dropdown.addItem("INTED")

        self.labelInterruption.move(305, 140)
        self.buttonDropdown.move(315, 160)
        self.int_dropdown.move(330, 160)

        # Create stack handling radio buttons

        self.labelStack = QLabel("Obsługa stosu: ", self)
        self.buttonPush = QRadioButton("PUSH", self)
        self.buttonPop = QRadioButton("POP", self)

        self.command_button_group.addButton(self.buttonPush, 10)
        self.command_button_group.addButton(self.buttonPop, 11)

        self.labelStack.move(305, 190)
        self.buttonPush.move(315, 210)
        self.buttonPop.move(315, 230)

        self.show()

    def update_printed_registers(self):
        self.labelAXNH.setText(str(self.registers[0].valueNH))
        self.labelAXNL.setText(str(self.registers[0].valueNL))
        self.labelBXNH.setText(str(self.registers[1].valueNH))
        self.labelBXNL.setText(str(self.registers[1].valueNL))
        self.labelCXNH.setText(str(self.registers[2].valueNH))
        self.labelCXNL.setText(str(self.registers[2].valueNL))
        self.labelDXNH.setText(str(self.registers[3].valueNH))
        self.labelDXNL.setText(str(self.registers[3].valueNL))

        self.labelAXNH.repaint()
        self.labelBXNH.repaint()
        self.labelCXNH.repaint()
        self.labelDXNH.repaint()
        self.labelAXNL.repaint()
        self.labelBXNL.repaint()
        self.labelCXNL.repaint()
        self.labelDXNL.repaint()

    def update_registers_binary_value(self, r):
        binary = binary_repr(r.valueDecimal, 16)
        r.valueNH = binary[:8]
        r.valueNL = binary[8:16]
        #print(r.valueDecimal)

    def search_registers(self, r1, r2):
        if r2.isdigit():
            value = int(r2)
        else:
            r2_copy = r2
            if r2[1] in ('H', 'L'):
                r2_copy = r2[0] + 'X'
            for r in self.registers:
                if r.name == r2_copy:
                    # if we want to use only 8 higher bits of the register
                    if r2[1] == 'H':
                        value = int(r.valueDecimal / 256)
                    # if we want to use only 8 lower bits of the register
                    elif r2[1] == 'L':
                        value = r.valueDecimal % 256
                    else:
                        value = r.valueDecimal
                    break
        for r in self.registers:
            r1_copy = r1
            if r1[1] in ('H', 'L'):
                r1_copy = r1[0] + 'X'
            if r.name == r1_copy:
                reg = r
        return reg, value

    def mov_function(self, r1, r2):
        r, value = self.search_registers(r1, r2)
        if r1[1] == 'H':
            r.valueDecimal = r.valueDecimal % 256 + value * 256
            return r
        elif r1[1] == 'L':
            r.valueDecimal = r.valueDecimal - r.valueDecimal % 256 + value
            return r
        r.valueDecimal = value
        return r

    def add_function(self, r1, r2):
        r, value = self.search_registers(r1, r2)
        if r1[1] == 'H':
            r.valueDecimal = r.valueDecimal + value * 256
            return r
        elif r1[1] == 'L':
            r.valueDecimal = r.valueDecimal + value % 256
            return r
        r.valueDecimal += value
        return r

    def sub_function(self, r1, r2):
        r, value = self.search_registers(r1, r2)
        if r1[1] == 'H':
            r.valueDecimal = r.valueDecimal - value * 256
        elif r1[1] == 'L':
            r.valueDecimal = r.valueDecimal - value % 256
        else:
            r.valueDecimal -= value
        if r.valueDecimal < 0:
            r.valueDecimal = 0
        return r

    def push_function(self, r1):
        for reg in self.registers:
            print(r1)
            if reg.name == r1:
                r = reg
                self.stack.append(reg.valueDecimal)
        return r

    def pop_function(self, r1):
        for reg in self.registers:
            if reg.name == r1:
                r = reg
                reg.valueDecimal = self.stack.pop()
        return r

    def check_run_valid(self):
        command_lines = 0
        for i in range(12):
            for j in range(3):
                if self.commands[i][j] == '':
                    return command_lines
                if j == 2:
                    command_lines += 1

    def clear_registers(self):
        for r in self.registers:
            r.valueDecimal = 0
            r.valueNH = binary_repr(0, 8)
            r.valueNL = binary_repr(0, 8)

    def print_colored_num_step(self, line):
        text = ""
        for i in range(12):
            if i == line:
                text += "" + str(i + 1) + "
"
            else:
                text += "" + str(i + 1) + "
"
        self.labelLinenumeration.setText(text)

    def print_black_num_step(self):
        text = ""
        for i in range(12):
            text += "" + str(i + 1) + "
"
        self.labelLinenumeration.setText(text)

    def int0_function(self):
        sys.exit()

    def int1_function(self):
        while 1:
            letter = input("Podaj znak do zamienienia na ASCII: ")[0]
            if 0 < ord(letter) <= 128:
                break
        self.registers[0].valueDecimal = self.registers[0].valueDecimal - \
                                         int(self.registers[0].valueNL, 2) + ord(letter)  # ord() changes to ASCII code
        self.update_registers_binary_value(self.registers[0])

    def int2_function(self):
        try:
            letter = int(self.registers[3].valueNL, 2)
        except Exception as e:
            print(e)
        if not 0 < letter <= 128:
            return
        self.registers[0].valueDecimal = self.registers[0].valueDecimal - \
                                         int(self.registers[0].valueNL, 2) + letter
        self.update_registers_binary_value(self.registers[0])
        print(chr(letter))

    def int3_function(self):
        os.system('open -a Terminal .')

    def int6_function(self):
        cmnd = input("Podaj polecenie do wpisania w konsoli: ")
        appscript.app('Terminal').do_script(cmnd)

    def int2A_function(self):
        now = datetime.datetime.now()
        # setting AL with day of the week
        self.registers[0].valueDecimal = self.registers[0].valueDecimal - \
                                         int(self.registers[0].valueNL, 2) + datetime.datetime.today().weekday()
        # setting BH with day in the month
        self.registers[1].valueDecimal = now.day * 256
        # setting BL with month in the year
        self.registers[1].valueDecimal = self.registers[1].valueDecimal + now.month
        # setting CX with current year a.d.
        self.registers[2].valueDecimal = now.year

        self.update_registers_binary_value(self.registers[0])
        self.update_registers_binary_value(self.registers[1])
        self.update_registers_binary_value(self.registers[2])

    def int2C_function(self):
        now = datetime.datetime.now()
        # setting AH with hour
        self.registers[0].valueDecimal = now.hour * 256
        # setting AL with minute
        self.registers[0].valueDecimal = self.registers[0].valueDecimal + now.minute
        # setting BH with second
        self.registers[1].valueDecimal = now.second * 256
        # setting CX with millisecond
        self.registers[1].valueDecimal = self.registers[1].valueDecimal + int(now.microsecond / 1000)

        self.update_registers_binary_value(self.registers[0])
        self.update_registers_binary_value(self.registers[1])

    def int30_function(self):
        try:
            maj, min = [platform.release().split('.')[0], platform.release().split('.')[1]]
            # setting AH with major system version (kernel version)
            self.registers[0].valueDecimal = int(maj) * 256
            # setting AL with minor system version
            self.registers[0].valueDecimal = self.registers[0].valueDecimal + int(min)
        except Exception as e:
            print(e)
            print("Wersja systemu nie nadaje się do przepisania do rejestrów!")
        self.update_registers_binary_value(self.registers[0])

    def int49_function(self):
        for i in range(4):
            self.registers[i].valueDecimal = 0
            self.update_registers_binary_value(self.registers[i])

    def intED_function(self):
        empty_arr = []
        for c in range(12):
            empty_arr.append([])
            for i in range(3):
                empty_arr[c].append('')
        with open('program.json', 'w') as outfile:
            json.dump(empty_arr, outfile)

    def commands_int_switch(self, cmnd):
        if cmnd == 'INT0':
            self.int0_function()
        elif cmnd == 'INT1':
            self.int1_function()
        elif cmnd == 'INT2':
            self.int2_function()
        elif cmnd == 'INT3':
            self.int3_function()
        elif cmnd == 'INT6':
            self.int6_function()
        elif cmnd == 'INT2A':
            self.int2A_function()
        elif cmnd == 'INT2C':
            self.int2C_function()
        elif cmnd == 'INT30':
            self.int30_function()
        elif cmnd == 'INT49':
            self.int49_function()
        elif cmnd == 'INTED':
            self.intED_function()

    def commands_switch(self, iterate):
        if self.commands[iterate][0] == 'MOV':
            register = self.mov_function(self.commands[iterate][1], self.commands[iterate][2])
        elif self.commands[iterate][0] == 'ADD':
            register = self.add_function(self.commands[iterate][1], self.commands[iterate][2])
        elif self.commands[iterate][0] == 'SUB':
            register = self.sub_function(self.commands[iterate][1], self.commands[iterate][2])
        elif self.commands[iterate][0] == 'PUSH':
            register = self.push_function(self.commands[iterate][1])
        elif self.commands[iterate][0] == 'POP':
            try:
                register = self.pop_function(self.commands[iterate][1])
            except IndexError as e:
                print(e)
                return False
        elif self.commands[iterate][0][:3] == 'INT':
            self.commands_int_switch(self.commands[iterate][0])
            return True
        try:
            self.update_registers_binary_value(register)
        except Exception as e:
            print(e)

        return True

    def step_run(self):
        if self.step == 0:
            self.clear_registers()
        valid_lines = self.check_run_valid()
        if valid_lines == 0:
            return
        if not self.commands_switch(self.step):
            return
        self.print_colored_num_step(self.step)
        self.step = (self.step + 1) % valid_lines
        self.update_printed_registers()

    def run(self):
        self.step = 0
        self.clear_registers()
        self.print_black_num_step()
        valid_lines = self.check_run_valid()
        for i in range(valid_lines):
            if not self.commands_switch(i):
                return
        self.update_printed_registers()

    def print_text(self):
        text = ''
        for i in range(12):
            for j in range(3):
                if self.commands[i][j] != '':
                    if j == 0:
                        text += self.commands[i][j] + ' '
                    elif j == 1:
                        if self.commands[i][j + 1] != 'nop':
                            text += self.commands[i][j] + ', '
                        elif self.commands[i][j] == 'nop':
                            text += ''
                        else:
                            text += self.commands[i][j] + ' '
                    elif j == 2:
                        try:
                            command = hex(int(self.commands[i][j]))
                            text += command + '\n'
                        except:
                            if self.commands[i][j] != 'nop':
                                text += self.commands[i][j] + '\n'
                            else:
                                text += '\n'
        self.textbox.setText(text)
        self.textbox.repaint()
        self.show()

    def delete_command(self):
        for i in range(12):
            for j in range(3):
                if self.commands[i][j] == '':
                    if i == 0 and j == 0:
                        self.commands[i][j] = ''
                    elif i == 0:
                        self.commands[i][j - 1] = ''
                        self.wyraz_num = (self.wyraz_num - 1) % 3
                    elif j == 0:
                        # 'nop' -> no operation
                        # enters 'if' if current command is interruption or stack operator
                        if self.commands[i - 1][2] == 'nop':
                            if self.commands[i - 1][1] == 'nop':
                                self.wyraz_num = (self.wyraz_num - 3) % 3
                                self.commands[i - 1][0] = ''
                            else:
                                self.wyraz_num = (self.wyraz_num - 2) % 3
                                self.stack_operator[0] = True
                            self.commands[i - 1][2] = ''
                            self.commands[i - 1][1] = ''
                        else:
                            self.commands[i - 1][2] = ''
                            self.wyraz_num = (self.wyraz_num - 1) % 3
                    else:
                        self.commands[i][j - 1] = ''
                        self.wyraz_num = (self.wyraz_num - 1) % 3
                        self.stack_operator = [False, False]
                    #print(self.commands)
                    return

    @pyqtSlot()
    def delete_word(self):
        self.delete_command()
        self.print_text()

    def right_command(self, command, iter):
        if iter == 0:
            if command in ('MOV', 'ADD', 'SUB'):
                return True
            elif command in ('PUSH', 'POP'):
                self.stack_operator[0] = True
                return True
            elif command == 'INT':
                # Handling interruption functions done in different method
                return False
        elif iter == 1:
            if self.stack_operator[0] and command in ('AX', 'BX', 'CX', 'DX'):
                self.stack_operator[1] = True
                return True
            elif not self.stack_operator[0] and \
                    command in ('AX', 'AH', 'AL', 'BX', 'BH', 'BL', 'CX', 'CH', 'CL', 'DX', 'DH', 'DL'):
                return True
            elif isinstance(command, int) and self.stack_operator[0]:
                print("Podaj rejestr!")
                return False
        elif iter == 2:
            if command in ('AX', 'AH', 'AL', 'BX', 'BH', 'BL', 'CX', 'CH', 'CL', 'DX', 'DH', 'DL'):
                return True
            if isinstance(command, int):
                return True

        return False

    def int_command(self, command, i, j):
        if j == 0 and command == 'INT':
            self.commands[i][j] = self.int_dropdown.currentText()
            return True
        return False

    def add_command(self, command):
        for i in range(12):
            for j in range(3):
                if self.commands[i][j] == '':
                    if self.right_command(command, j):
                        if self.stack_operator[1]:
                            self.commands[i][j + 1] = 'nop'
                            self.stack_operator = [False, False]
                        self.commands[i][j] = str(command)
                        #print(self.commands)
                        return True
                    elif self.int_command(command, i, j):
                        self.commands[i][j + 1] = 'nop'
                        self.commands[i][j + 2] = 'nop'
                        #print(self.commands)
                        return True
                    return False

    @pyqtSlot()
    def insert_word(self):
        try:
            command_text = self.command_button_group.checkedButton().text()
            if command_text == "Liczba":
                try:
                    number = int(self.textInsertNumber.text())
                    if 0 <= number <= 65535:
                        if self.add_command(number):
                            self.wyraz_num = (self.wyraz_num + 1) % 3
                    else:
                        print("Podaj liczbę z zakresu!")
                except Exception as e:
                    print("Podaj liczbę!")
            elif command_text in ('AX', 'BX', 'CX', 'DX'):
                try:
                    register_size = self.register_part_group.checkedButton().text()
                    command_text = command_text[0] + register_size[1]
                    if self.add_command(command_text):
                        self.wyraz_num = (self.wyraz_num + 1) % 3
                except Exception as e:
                    print(e)
            elif command_text in ('PUSH', 'POP', 'INT'):
                if self.add_command(command_text):
                    if command_text == 'INT':
                        self.wyraz_num = (self.wyraz_num + 1) % 3
                    self.wyraz_num = (self.wyraz_num + 2) % 3
            elif command_text is not None:
                if self.add_command(command_text):
                    self.wyraz_num = (self.wyraz_num + 1) % 3
        except Exception as e:
            print(e)
        self.print_text()

    def save_file(self):
        with open('program.json', 'w') as outfile:
            json.dump(self.commands, outfile)

    def load_file(self):
        try:
            with open('program.json', 'r') as infile:
                self.commands = json.load(infile)
            self.print_text()
            self.labelErrors.setText("")
            self.labelErrors.repaint()
        except FileNotFoundError:
            self.labelErrors.setText("Nie ma takiego pliku!")
            self.labelErrors.repaint()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


import asyncio
import math
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

from _decimal import Decimal

from hummingbot.connector.constants import s_decimal_NaN
from hummingbot.connector.exchange.polkadex import polkadex_constants as CONSTANTS, polkadex_web_utils as web_utils
from hummingbot.connector.exchange.polkadex.polkadex_api_order_book_data_source import PolkadexAPIOrderBookDataSource
from hummingbot.connector.exchange.polkadex.polkadex_data_source import PolkadexDataSource
from hummingbot.connector.exchange_py_base import ExchangePyBase
from hummingbot.connector.trading_rule import TradingRule
from hummingbot.connector.utils import get_new_client_order_id
from hummingbot.core.api_throttler.data_types import RateLimit
from hummingbot.core.data_type.common import OrderType, TradeType
from hummingbot.core.data_type.in_flight_order import InFlightOrder, OrderState, OrderUpdate, TradeUpdate
from hummingbot.core.data_type.order_book_tracker_data_source import OrderBookTrackerDataSource
from hummingbot.core.data_type.trade_fee import TokenAmount, TradeFeeBase
from hummingbot.core.data_type.user_stream_tracker_data_source import UserStreamTrackerDataSource
from hummingbot.core.event.event_forwarder import EventForwarder
from hummingbot.core.event.events import AccountEvent, BalanceUpdateEvent, MarketEvent
from hummingbot.core.network_iterator import NetworkStatus, safe_ensure_future
from hummingbot.core.utils.estimate_fee import build_trade_fee
from hummingbot.core.web_assistant.auth import AuthBase
from hummingbot.core.web_assistant.web_assistants_factory import WebAssistantsFactory

if TYPE_CHECKING:
    from hummingbot.client.config.config_helpers import ClientConfigAdapter  # pragma: no cover

class PolkadexExchange(ExchangePyBase):
    web_utils = web_utils

    def __init__(
        self,
        client_config_map: "ClientConfigAdapter",
        polkadex_seed_phrase: str,
        trading_pairs: Optional[List[str]] = None,
        trading_required: bool = True,
        domain: str = CONSTANTS.DEFAULT_DOMAIN,
    ):
        self._trading_required = trading_required
        self._trading_pairs = trading_pairs
        self._domain = domain
        self._data_source = PolkadexDataSource(
            connector=self, seed_phrase=polkadex_seed_phrase, domain=self._domain, trading_required=trading_required
        )
        super().__init__(client_config_map=client_config_map)
        self._data_source.configure_throttler(throttler=self._throttler)
        self._forwarders = []
        self._configure_event_forwarders()

    @property
    def name(self) -> str:
        return CONSTANTS.EXCHANGE_NAME

    @property
    def authenticator(self) -> AuthBase:
        return None

    @property
    def rate_limits_rules(self) -> List[RateLimit]:
        return CONSTANTS.RATE_LIMITS

    @property
    def domain(self) -> str:
        return self._domain

    @property
    def client_order_id_max_length(self) -> Optional[int]:
        return CONSTANTS.MAX_ID_LEN

    @property
    def client_order_id_prefix(self) -> str:
        return CONSTANTS.CLIENT_ID_PREFIX

    @property
    def trading_rules_request_path(self) -> str:
        raise NotImplementedError  # pragma: no cover

    @property
    def trading_pairs_request_path(self) -> str:
        raise NotImplementedError  # pragma: no cover

    @property
    def check_network_request_path(self) -> str:
        raise NotImplementedError  # pragma: no cover

    @property
    def trading_pairs(self) -> List[str]:
        return self._trading_pairs

    @property
    def is_cancel_request_in_exchange_synchronous(self) -> bool:
        return False

    @property
    def is_trading_required(self) -> bool:
        return self._trading_required

    async def start_network(self):
        await super().start_network()

        market_symbols = [
            await self.exchange_symbol_associated_to_pair(trading_pair=trading_pair)
            for trading_pair in self._trading_pairs
        ]
        await self._data_source.start(market_symbols=market_symbols)

    async def stop_network(self):
        """
        This function is executed when the connector is stopped. It performs a general cleanup and stops all background
        tasks that require the connection with the exchange to work.
        """
        await super().stop_network()
        await self._data_source.stop()

    def supported_order_types(self) -> List[OrderType]:
        return [OrderType.LIMIT, OrderType.MARKET]

    async def check_network(self) -> NetworkStatus:
        """
        Checks connectivity with the exchange using the API
        """
        try:
            status = await self._data_source.exchange_status()
        except asyncio.CancelledError:
            raise
        except Exception:
            status = NetworkStatus.NOT_CONNECTED
        return status

    # === Orders placing ===

    def buy(self,
            trading_pair: str,
            amount: Decimal,
            order_type=OrderType.LIMIT,
            price: Decimal = s_decimal_NaN,
            **kwargs) -> str:
        """
        Creates a promise to create a buy order using the parameters

        :param trading_pair: the token pair to operate with
        :param amount: the order amount
        :param order_type: the type of order to create (MARKET, LIMIT, LIMIT_MAKER)
        :param price: the order price

        :return: the id assigned by the connector to the order (the client id)
        """
        order_id = get_new_client_order_id(
            is_buy=True,
            trading_pair=trading_pair,
            hbot_order_id_prefix=self.client_order_id_prefix,
            max_id_len=self.client_order_id_max_length
        )
        hex_order_id = f"0x{order_id.encode('utf-8').hex()}"
        safe_ensure_future(self._create_order(
            trade_type=TradeType.BUY,
            order_id=hex_order_id,
            trading_pair=trading_pair,
            amount=amount,
            order_type=order_type,
            price=price,
            **kwargs))
        return hex_order_id

    def sell(self,
             trading_pair: str,
             amount: Decimal,
             order_type: OrderType = OrderType.LIMIT,
             price: Decimal = s_decimal_NaN,
             **kwargs) -> str:
        """
        Creates a promise to create a sell order using the parameters.
        :param trading_pair: the token pair to operate with
        :param amount: the order amount
        :param order_type: the type of order to create (MARKET, LIMIT, LIMIT_MAKER)
        :param price: the order price
        :return: the id assigned by the connector to the order (the client id)
        """
        order_id = get_new_client_order_id(
            is_buy=False,
            trading_pair=trading_pair,
            hbot_order_id_prefix=self.client_order_id_prefix,
            max_id_len=self.client_order_id_max_length
        )
        hex_order_id = f"0x{order_id.encode('utf-8').hex()}"
        safe_ensure_future(self._create_order(
            trade_type=TradeType.SELL,
            order_id=hex_order_id,
            trading_pair=trading_pair,
            amount=amount,
            order_type=order_type,
            price=price,
            **kwargs))
        return hex_order_id

    def _is_request_exception_related_to_time_synchronizer(self, request_exception: Exception) -> bool:
        # Polkadex does not use a time synchronizer
        return False

    def _is_order_not_found_during_status_update_error(self, status_update_exception: Exception) -> bool:
        return CONSTANTS.ORDER_NOT_FOUND_MESSAGE in str(status_update_exception)

    def _is_order_not_found_during_cancelation_error(self, cancelation_exception: Exception) -> bool:
        return CONSTANTS.ORDER_NOT_FOUND_MESSAGE in str(cancelation_exception)

    async def _execute_order_cancel_and_process_update(self, order: InFlightOrder) -> bool:
        new_order_state = await self._place_cancel(order.client_order_id, order)
        cancelled = new_order_state in [OrderState.CANCELED, OrderState.PENDING_CANCEL]
        if cancelled:
            update_timestamp = self.current_timestamp
            if update_timestamp is None or math.isnan(update_timestamp):
                update_timestamp = self._time()
            order_update: OrderUpdate = OrderUpdate(
                client_order_id=order.client_order_id,
                trading_pair=order.trading_pair,
                update_timestamp=update_timestamp,
                new_state=new_order_state,
            )
            self._order_tracker.process_order_update(order_update)
        return cancelled

    async def _place_cancel(self, order_id: str, tracked_order: InFlightOrder) -> OrderState:
        await tracked_order.get_exchange_order_id()
        market_symbol = await self.exchange_symbol_associated_to_pair(trading_pair=tracked_order.trading_pair)

        new_order_state = await self._data_source.cancel_order(
            order=tracked_order, market_symbol=market_symbol, timestamp=self.current_timestamp
        )

        return new_order_state

    async def _place_order(
        self,
        order_id: str,
        trading_pair: str,
        amount: Decimal,
        trade_type: TradeType,
        order_type: OrderType,
        price: Decimal,
        **kwargs,
    ) -> Tuple[str, float]:
        symbol = await self.exchange_symbol_associated_to_pair(trading_pair)

        result = await self._data_source.place_order(
            market_symbol=symbol,
            client_order_id=order_id,
            price=price,
            amount=amount,
            trade_type=trade_type,
            order_type=order_type,
        )

        return result

    def _get_fee(
        self,
        base_currency: str,
        quote_currency: str,
        order_type: OrderType,
        order_side: TradeType,
        amount: Decimal,
        price: Decimal = s_decimal_NaN,
        is_maker: Optional[bool] = None,
    ) -> TradeFeeBase:
        is_maker = is_maker or (order_type is OrderType.LIMIT_MAKER)
        fee = build_trade_fee(
            self.name,
            is_maker,
            base_currency=base_currency,
            quote_currency=quote_currency,
            order_type=order_type,
            order_side=order_side,
            amount=amount,
            price=price,
        )
        return fee

    async def _trading_fees_polling_loop(self):
        pass

    async def _update_trading_fees(self):
        raise NotImplementedError  # pragma: no cover

    async def _user_stream_event_listener(self):
        # Not required in Polkadex since all event are processed using the data source PubSub
        pass  # pragma: no cover

    async def _format_trading_rules(self, exchange_info_dict: Dict[str, Any]) -> List[TradingRule]:
        # Not used in Polkadex
        raise NotImplementedError  # pragma: no cover

    async def _update_balances(self):
        all_balances = await self._data_source.all_balances()

        self._account_available_balances.clear()
        self._account_balances.clear()

        for token_balance_info in all_balances:
            self._account_balances[token_balance_info["token_name"]] = token_balance_info["total_balance"]
            self._account_available_balances[token_balance_info["token_name"]] = token_balance_info["available_balance"]

    async def _update_orders_fills(self, orders: List[InFlightOrder]):
        try:
            if len(orders) != 0:
                minimum_creation_timestamp = min([order.creation_timestamp for order in orders])
                current_timestamp = self.current_timestamp
                trade_updates = await self._data_source.get_all_fills(
                    from_timestamp=minimum_creation_timestamp,
                    to_timestamp=current_timestamp,
                    orders=orders,
                )

                for trade_update in trade_updates:
                    self._order_tracker.process_trade_update(trade_update=trade_update)

        except asyncio.CancelledError:
            raise
        except Exception:
            self.logger().warning("Error fetching trades updates.")

    async def _all_trade_updates_for_order(self, order: InFlightOrder) -> List[TradeUpdate]:
        # not used
        raise NotImplementedError

    async def _request_order_status(self, tracked_order: InFlightOrder) -> OrderUpdate:
        symbol = await self.exchange_symbol_associated_to_pair(tracked_order.trading_pair)
        await tracked_order.get_exchange_order_id()
        order_update = await self._data_source.order_update(order=tracked_order, market_symbol=symbol)
        return order_update

    def _create_web_assistants_factory(self) -> WebAssistantsFactory:
        return WebAssistantsFactory(throttler=self._throttler)

    def _create_order_book_data_source(self) -> OrderBookTrackerDataSource:
        return PolkadexAPIOrderBookDataSource(
            trading_pairs=self._trading_pairs,
            connector=self,
            data_source=self._data_source,
            domain=self.domain,
        )

    def _create_user_stream_data_source(self) -> UserStreamTrackerDataSource:
        # Not used in Polkadex
        raise NotImplementedError  # pragma: no cover

    def _is_user_stream_initialized(self):
        # Polkadex does not have private websocket endpoints
        return self._data_source.is_started()

    def _create_user_stream_tracker(self):
        # Polkadex does not use a tracker for the private streams
        return None

    def _create_user_stream_tracker_task(self):
        # Polkadex does not use a tracker for the private streams
        return None

    def _initialize_trading_pair_symbols_from_exchange_info(self, exchange_info: Dict[str, Any]):
        # Not used in Bluefin
        raise NotImplementedError()  # pragma: no cover

    async def _initialize_trading_pair_symbol_map(self):
        exchange_info = None
        try:
            mapping = await self._data_source.symbols_map()
            self._set_trading_pair_symbol_map(mapping)
        except Exception:
            self.logger().exception("There was an error requesting exchange info.")
        return exchange_info

    async def _update_trading_rules(self):
        trading_rules_list = await self._data_source.all_trading_rules()
        self._trading_rules = {trading_rule.trading_pair: trading_rule for trading_rule in trading_rules_list}

    async def _get_all_pairs_prices(self) -> Dict[str, Any]:
        # Polkadex is configured to not be a price provider (check is_price_provider)
        # This method should never be called
        raise NotImplementedError  # pragma: no cover

    async def _get_last_traded_price(self, trading_pair: str) -> float:
        symbol = await self.exchange_symbol_associated_to_pair(trading_pair=trading_pair)
        last_price = await self._data_source.last_price(market_symbol=symbol)
        return last_price

    def _configure_event_forwarders(self):
        event_forwarder = EventForwarder(to_function=self._process_user_trade_update)
        self._forwarders.append(event_forwarder)
        self._data_source.add_listener(event_tag=MarketEvent.TradeUpdate, listener=event_forwarder)

        event_forwarder = EventForwarder(to_function=self._process_user_order_update)
        self._forwarders.append(event_forwarder)
        self._data_source.add_listener(event_tag=MarketEvent.OrderUpdate, listener=event_forwarder)

        event_forwarder = EventForwarder(to_function=self._process_balance_event)
        self._forwarders.append(event_forwarder)
        self._data_source.add_listener(event_tag=AccountEvent.BalanceEvent, listener=event_forwarder)

    def _process_balance_event(self, event: BalanceUpdateEvent):
        self._account_balances[event.asset_name] = event.total_balance
        self._account_available_balances[event.asset_name] = event.available_balance

    def _process_user_order_update(self, order_update: OrderUpdate):
        tracked_order = self._order_tracker.all_updatable_orders.get(order_update.client_order_id)

        if tracked_order is not None:
            self.logger().debug(f"Processing order update {order_update}\nUpdatable order {tracked_order.to_json()}")
            order_update_to_process = OrderUpdate(
                trading_pair=tracked_order.trading_pair,
                update_timestamp=order_update.update_timestamp,
                new_state=order_update.new_state,
                client_order_id=tracked_order.client_order_id,
                exchange_order_id=order_update.exchange_order_id,
            )
            self._order_tracker.process_order_update(order_update=order_update_to_process)

    def _process_user_trade_update(self, trade_update: TradeUpdate):
        tracked_order = self._order_tracker.all_fillable_orders_by_exchange_order_id.get(trade_update.exchange_order_id)

        if tracked_order is not None:
            self.logger().debug(f"Processing trade update {trade_update}\nFillable order {tracked_order.to_json()}")
            flat_fees = [
                TokenAmount(amount=flat_fee.amount, token=tracked_order.quote_asset)
                for flat_fee in trade_update.fee.flat_fees
            ]
            fee = TradeFeeBase.new_spot_fee(
                fee_schema=self.trade_fee_schema(),
                trade_type=tracked_order.trade_type,
                percent_token=tracked_order.quote_asset,
                flat_fees=flat_fees,
            )
            fill_amount = trade_update.fill_base_amount - tracked_order.executed_amount_base
            trade_update: TradeUpdate = TradeUpdate(
                trade_id=trade_update.trade_id,
                client_order_id=tracked_order.client_order_id,
                exchange_order_id=trade_update.exchange_order_id,
                trading_pair=tracked_order.trading_pair,
                fill_timestamp=trade_update.fill_timestamp,
                fill_price=trade_update.fill_price,
                fill_base_amount=fill_amount,
                fill_quote_amount=fill_amount * trade_update.fill_price,
                fee=fee,
            )
            self._order_tracker.process_trade_update(trade_update)


import os
import sched
import time

from etl_worker import tasks

UPDATE_FREQ_SCHEDULES = int(os.environ.get("UPDATE_FREQ_SCHEDULES", 3600))
UPDATE_FREQ_EXPERIENCES = int(os.environ.get("UPDATE_FREQ_EXPERIENCES", 60))

def experiences_task():
    """Re-schedule self before executing `tasks.update_experiences`."""

    schedule.enter(UPDATE_FREQ_EXPERIENCES, 1, experiences_task)
    tasks.update_experiences()

def parks_task():
    """Re-schedule self before executing `tasks.update_parks`."""

    schedule.enter(UPDATE_FREQ_SCHEDULES, 2, parks_task)
    tasks.update_parks()

if __name__ == "__main__":
    tasks.update_parks()
    tasks.update_experiences()

    schedule = sched.scheduler(time.time, time.sleep)
    schedule.enter(UPDATE_FREQ_SCHEDULES, 2, parks_task)
    schedule.enter(UPDATE_FREQ_EXPERIENCES, 1, experiences_task)
    schedule.run()


import json

fields = ['category_1', 'category_2', 'category_3', 'category_4', 'category_5', 'category_6']

def structure_query(raw_dict, dev_ins_id, tag_list):
    gate_way_id, sensor_id = [gate_way_id for i in range(len(tag_list))], [sensor_id for i in range(len(tag_list))]
    site_id, block = [site_id for i in range(len(tag_list))], [block for i in range(len(tag_list))]
    dev_ins_id = [dev_ins_id for i in range(len(tag_list))]
    result = list(zip(site_id, gate_way_id, dev_ins_id, block, tag_list, sensor_id))
    dicts = [dict(zip(fields, d)) for d in result]
    if raw_dict:
        value_list = [{"name": "ilens.live_data.raw", "datapoints": [raw_val], 'tags': cat_dict} for raw_val, cat_dict
                      in zip(raw_dict, dicts)]
        return value_list
    else:
        return None


# 영수증 계산 총 가격
receiptTotal = int(input())

# 종류 개수
category = int(input())

#실제 총 가격
realTotal = 0

# 종류 개수만큼 반복문
for i in range(category):
#   input: 가격, 개수
    price, num = map(int, input().split())
    realTotal += (price * num)

# total이 0이라면 Yes, 아니면 No
if realTotal == receiptTotal:
    print("Yes")
else:
    print("No")


# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Deleting field 'Posts.slug'
        db.delete_column(u'posts_posts', 'slug')

    def backwards(self, orm):
        # Adding field 'Posts.slug'
        db.add_column(u'posts_posts', 'slug',
                      self.gf('django.db.models.fields.SlugField')(default=datetime.datetime(2014, 6, 21, 0, 0), max_length=50),
                      keep_default=False)

    models = {
        u'posts.posts': {
            'Meta': {'object_name': 'Posts'},
            'content': ('django.db.models.fields.TextField', [], {}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'publication_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['posts']


# import libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random

# Tensorflow
import tensorflow as tf
from keras.utils import load_img, img_to_array, to_categorical
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout
from keras.optimizers import Adam
from keras import Sequential
from tensorflow.keras.utils import load_img
from skimage import transform
from tensorflow.python.keras.models import load_model

# import Dataset
train_df = pd.read_csv('input/Train.csv')
test_df = pd.read_csv('input/Test.csv')

labels = {0:'Speed limit(20km/h)',
          1:'Speed limit(30km/h)',
          2:'Speed limit(50km/h)',
          3:'Speed limit(60km/h)',
          4:'Speed limit(70km/h)',
          5:'Speed limit(80km/h)',
          6:'End of speed limit(80km/h)',
          7:'Speed limit(100km/h)',
          8:'Speed limit(120km/h)',
          9:'No passing',
          10:'No passing for vehicles over 3.5 metric tons',
          11:'Right-of-way at the next intersection',
          12:'Priority road',
          13:'Yield',
          14:'Stop',
          15:'No vehicles',
          16:'Vehicles over 3.5 metric tons prohibted',
          17:'No entry',
          18:'General caution',
          19:'Dangerous curve to the left',
          20:'Dangerous curve to the right',
          21:'Double curve',
          22:'Bumpy road',
          23:'Slippery road',
          24:'Road narrows on the right',
          25:'Road work',
          26:'Traffic signals',
          27:'Pedestrians',
          28:'Children crossing',
          29:'Bicycles crossing',
          30:'Beware of ice/snow',
          31:'Wild animals crossing',
          32:'End of all speed and passing limits',
          33:'Turn right ahead',
          34:'Turn left ahead',
          35:'Ahead only',
          36:'Go straight or right',
          37:'Go straight or left',
          38:'Keep right',
          39:'Keep left',
          40:'Roundabout mandatory',
          41:'End of no passing',
          42:'End of no passing by vehicles over 3.5 metric tons'}
# getting only the Path and ClassId
train_df = train_df[['ClassId', 'Path']]
test_df = test_df[['ClassId', 'Path']]
# add the complete path
train_df['Path'] = train_df['Path'].apply(lambda x: 'input/' + x)
test_df['Path'] = test_df['Path'].apply(lambda x: 'input/' + x)
# Example of the new path in the data
print(f'The new path of the first image in "train_df" : {train_df.Path[0]}')
print(f'The new path of the first image in "test_df" : {test_df.Path[0]}')
# create a random number
random_nbr = random.randint(1, len(train_df)) # or randint(1, train_df.shape[0]))

# read the images randomly and plot'm
img = plt.imread(train_df.Path[random_nbr]) # read the image from the path
print(f'image shape : {img.shape}') # print the shape of the image
fig, ax = plt.subplots(figsize=(8,4))

ax.imshow(img)
ax.set_title(labels[train_df.ClassId[random_nbr]])
ax.axis('off')
plt.show()
# Split the data into training and validation sets
train_data = train_df.sample(frac=0.8, random_state=0)
valid_data = train_df.drop(train_df.index)

# Preprocess the data
IMG_SIZE = 32
NUM_CLASSES = len(labels)

def preprocess_data(df):
    X = []
    y = []
    for index, row in df.iterrows():
        img = load_img(row.Path, target_size=(IMG_SIZE, IMG_SIZE))
        img_array = img_to_array(img) / 255.0
        X.append(img_array)
        y.append(to_categorical(row.ClassId, num_classes=NUM_CLASSES))
    return np.array(X), np.array(y)

X_train, y_train = preprocess_data(train_data)
X_valid, y_valid = preprocess_data(valid_data)
X_test, y_test = preprocess_data(test_df)
model = Sequential([
    Conv2D(filters=32, kernel_size=3, activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)),
    Conv2D(64, 3, activation='relu'),
    MaxPool2D(2),
    Conv2D(128, 3, activation='relu'),
    Conv2D(64, 3, activation='relu'),
    MaxPool2D(2),
    Flatten(),
    Dropout(0.5),
    Dense(128, activation='relu'),
    Dense(NUM_CLASSES, activation='softmax')
])

model.compile(loss='categorical_crossentropy',
              optimizer=Adam(),
              metrics=['accuracy'])
model.summary()
history = model.fit(X_train,
                    y_train,
                    epochs=10)

loss_train = history.history['loss']
epochs = range(1,10)
plt.plot(epochs, loss_train, 'g', label='Training loss')
plt.title('Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

loss_train = history.history['acc']
epochs = range(1,11)
plt.plot(epochs, loss_train, 'g', label='Training accuracy')
plt.title('Training  accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()

model.save('traffic_model.h5')


# coding=utf-8
import requests
import os
import fileutil
import re
import time
import json
import sys
from bs4 import BeautifulSoup
from PyQt5.QtWidgets import QInputDialog
from PyQt5.QtCore import QThread, pyqtSignal

class backup_blog(QThread):
    """ 下载日志的线程 """

    show_status_signal = pyqtSignal(str)

    def __init__(self, backup_dir, blog_name, user_id, blog_count, continue_on_failure):
        super().__init__()
        self.blog_source_file = "日志/source_blog.txt"
        self.blog_html_file = "日志/blog.html"

        self.backup_dir = backup_dir
        self.blog_name = blog_name
        self.user_id = user_id
        self.blog_count = blog_count
        self.continue_on_failure = continue_on_failure
        self.continue_index = 0
        if continue_on_failure :
            fileutil.check_and_create(backup_dir + "config.json")
            with open(backup_dir + "config.json","r") as f:
                index_content = f.read().strip()
                if f.read().strip():
                    self.continue_index = int(index_content)

        self.post_blog_data = {
            "callCount": "1",
            "scriptSessionId": "187",
            "c0-scriptName": "BlogBeanNew",
            "c0-methodName": "getBlogsNewTheme",
            "c0-id": "0",
            # ~ "c0-param0": "",
            "c0-param1": "0",
            "c0-param2": "1",
            "batchId": "159937",
        }
        self.headers = {
            "contents-Type": "text/plain",
            "Referer": "http://api.blog.163.com/crossdomain.html?publish_time=20100205",
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36",
        }

    def run(self):
        try:
            # ~ if self.continue_on_failure is not True:
            self.down_blog_source()
            self.convert_to_html_file()
            self.show_status_signal.emit("备份随笔结束")
        except:
            if self.continue_on_failure :
                fileutil.check_and_create(self.backup_dir + "config.json")
                with open(self.backup_dir + "config.json","r") as f:
                    f.write(str(self.continue_index))
            print(sys.exc_info())
            self.show_status_signal.emit("系统异常:" + str(sys.exc_info()[1]) + "\n下载失败")

    def down_blog_source(self):
        self.show_status_signal.emit("开始下载{}条日志".format(self.blog_count))

        get_blog_url = "http://api.blog.163.com/{}/dwr/call/plaincall/BlogBeanNew.getBlogsNewTheme.dwr".format(
            self.blog_name
        )
        self.post_blog_data["c0-param0"] = self.user_id
        self.post_blog_data["c0-param2"] = self.blog_count

        fileutil.check_and_create(self.backup_dir + self.blog_source_file)
        print(
            "get_blog_url:{},post_blog_data:{}".format(
                get_blog_url, self.post_blog_data
            )
        )
        r = requests.post(get_blog_url, data=self.post_blog_data, headers=self.headers)
        # ~ print(r.text)

        with open(self.backup_dir + self.blog_source_file, "w+") as f:
            f.write(r.text)
            self.show_status_signal.emit("下载日志的原始数据成功\n开始解析原始数据")

    def convert_to_html_file(self):
        fileutil.check_and_create(self.backup_dir + self.blog_html_file)
        with open(self.backup_dir + self.blog_source_file, "r") as f:
            str1 = f.read().strip()
            field_title = {}
            field_title["name"] = "title"
            field_title["pattern"] = r'(?<=title=").+?(?=";)'
            field_link = {}
            field_link["name"] = "link"
            field_link["pattern"] = r'(?<=permalink=").+?(?=";)'
            field_publishTime = {}
            field_publishTime["name"] = "publishTime"
            field_publishTime["pattern"] = r"(?<=publishTime=).+?(?=;)"
            field_accessCount = {}
            field_accessCount["name"] = "accessCount"
            field_accessCount["pattern"] = r"(?<=accessCount=).+?(?=;)"
            field_commentCount = {}
            field_commentCount["name"] = "commentCount"
            field_commentCount["pattern"] = r"(?<=commentCount=).+?(?=;)"
            field_id = {}
            field_id["name"] = "id"
            field_id["pattern"] = r'(?<=id=").+?(?=";)'
            fields = [
                field_title,
                field_link,
                field_publishTime,
                field_accessCount,
                field_commentCount,
                field_id,
            ]

            items = self.analyze_response(str1, fields)
            print("日志数量:{},日志内容:{}".format(len(items), items))

        html_content = "<meta charset='utf-8'>"
        items_count = len(items)
        for i, item in enumerate(items,self.continue_index -1):
            self.continue_index = i
            self.show_status_signal.emit("进度:{}/{},{}".format(i + 1, items_count, item["title"]))
            commentCount = item["commentCount"]
            html_content = (
                html_content
                + "

{}

{},评论({})

{}

".format(
                    item["title"], item["publishTime"], commentCount, item["link"]
                )
            )
            try:
                self.get_single_blog(item, i + 1)
            except:
                self.show_status_signal.emit("系统异常:" + str(sys.exc_info()[1]) + "\n下载失败")
            # ~ if commentCount != "0":
            # ~ self.show_status_signal.emit(
            # ~ "正在获取第{}条日志的{}条评论".format(i + 1, commentCount)
            # ~ )
            # ~ comment_items = get_commet(self.blog_name,item["id"],item["commentCount"],html_content)
            # ~ html_content = append_comment(html_content,comment_items)
        html_content += ""

        fileutil.check_and_create(self.backup_dir + self.blog_html_file)
        with open(self.backup_dir + self.blog_html_file, "w+") as f2:
            f2.write(html_content)
        print("保存html格式的日志成功")

    def convert_timestamp(self, t):
        publish_time_tmp = t[:-3]
        x = time.localtime(int(publish_time_tmp))
        return time.strftime("%Y-%m-%d %H:%M:%S", x)

    def str_decode(self, word):
        return eval("u'" + word + "'")

    def get_single_blog(self, item, item_index):
        link = item["link"]
        blog_title = item["title"]
        url = "http://{}.blog.163.com/{}".format(self.blog_name, link)
        print("url:", url)
        r = requests.get(url)
        html_doc = r.text
        fileutil.check_and_create_dir(self.backup_dir + "日志/source/")
        with open(self.backup_dir + "日志/source/" + blog_title + ".txt", "w+") as f:
            f.write(r.text)
        soup = BeautifulSoup(html_doc, "lxml")
        blog_sep = soup.find("span", class_="blogsep")
        blog_catelog = soup.find("a", class_="fc03 m2a")
        if blog_sep is None :
            print("无权限访问:" + item["title"])
            pass
            return
        print("发表时间:{},分类:{}".format(blog_sep.string, blog_catelog.string))
        blog_body = soup.find_all("div", class_="bct fc05 fc11 nbw-blog ztag")
        if blog_body:
            blog_imgs = BeautifulSoup(str(blog_body[0]), "lxml").find_all("img")
            print("正文:", blog_body[0])

        single_blog_dir = (
            self.backup_dir + "日志/" + blog_catelog.string + "/" + blog_title + "/"
        )
        fileutil.check_and_create_dir(single_blog_dir)
        with open(
            self.backup_dir + "日志/" + blog_catelog.string + "/" + blog_title + ".html",
            "w+",
        ) as f:
            content = "<meta charset='utf-8'>
{}

{} | 分类:  {}

".format(
                blog_title, blog_sep.string, blog_catelog.string
            )
            if blog_body:
                # ~ content += str(blog_body[0])
                str_body = str(blog_body[0])
                # r'(?<=title=").+?(?=";)'
                # ~ r'(?<=src=").+?(?/=\d{5})'
                pattern = re.compile(r'(?<=src=").+?(?=/\d{5})')
                print(pattern.findall(str_body))
                content += re.sub(pattern, blog_title, str_body)
            content += "
阅读({}) |  评论({})".format(
                item["accessCount"], item["commentCount"]
            )
            content += ""
            f.write(content)

            # ~ 下载图片
            if blog_imgs:
                self.show_status_signal.emit(
                    "正在获取日志:{}的{}张图片".format(item["title"], len(blog_imgs))
                )
                for img in blog_imgs:
                    print(img)
                    if img["src"]:
                        img_name = img["src"][img["src"].rindex("/") + 1 :]
                        print("下载图片:", img["src"], img_name)
                        self.show_status_signal.emit(
                            '下载图片:{}'.format(img["src"])
                        )
                        r = requests.get(img["src"])
                        img["src"] = blog_title + "/" + img_name
                        with open(single_blog_dir + img_name, "wb+") as f:
                            f.write(r.content)

    def get_commet(self, item_id, comment_count, html_content):
        get_blog_comment_url = "http://api.blog.163.com/{}/dwr/call/plaincall/FeelingsBeanNew.getRecentFeelingsComment.dwr".format(
            self.blog_name
        )
        self.post_blog_data["c0-methodName"] = "getRecentFeelingsComment"
        self.post_blog_data["c0-param0"] = "string:" + item_id
        self.post_blog_data["c0-param1"] = comment_count
        self.post_blog_data["c0-param2"] = "0"
        print(
            "get_blog_comment_url:{},data:{}".format(
                get_blog_comment_url, self.post_blog_data
            )
        )
        r = requests.post(
            get_blog_comment_url, data=self.post_blog_data, headers=self.headers
        )
        print("评论:", r.text)

        field_content = {}
        field_content["name"] = "content"
        field_content["pattern"] = r'(?<=content=").+?(?=";)'
        field_publishTime = {}
        field_publishTime["name"] = "publishTime"
        field_publishTime["pattern"] = r"(?<=publishTime=).+?(?=;)"
        field_commentCount = {}
        field_commentCount["name"] = "publisherNickname"
        field_commentCount["pattern"] = r'(?<=publisherNickname=").+?(?=";)'
        fields = [field_content, field_publishTime, field_commentCount]

        items = self.analyze_response(r.text, fields)
        print("评论:", items)
        return items

    def append_comment(self, html_content, items):
        for item in items:
            html_content = (
                html_content
                + '

{}

{}

{}

'.format(
                    item["publisherNickname"], item["content"], item["publishTime"]
                )
            )
        print("拼接评论后的html:", html_content)
        return html_content

    def analyze_response(self, text, fields):
        results = []
        itemCounts = 0
        a = []
        for field in fields:
            matchs = re.findall(field["pattern"], text)
            itemCounts = len(matchs)

            matchItem = {}
            matchItem["field_name"] = field["name"]
            matchItem["result"] = matchs
            results.append(matchItem)
        print("itemCounts", itemCounts)
        for i in range(itemCounts):
            b = {}
            for matchItem in results:
                field_name = matchItem["field_name"]
                if field_name == "publishTime":
                    print("i:", i)
                    b[matchItem["field_name"]] = self.convert_timestamp(
                        matchItem["result"][i]
                    )
                else:
                    b[matchItem["field_name"]] = self.str_decode(matchItem["result"][i])
            a.append(b)
        print("a :", len(a))
        return a


import pandas as pd
import matplotlib.pyplot as plt

titanic = pd.read_csv("titanic.csv")

""" Questão I Monte um gráfico(formato a sua escolha) que mostre o número de sobreviventes por classe"""
titanic1=titanic.loc[titanic["Survived"] == 1]
aux_titanic= titanic1.groupby(['Pclass'])['Survived'].count()

aux_titanic.plot(kind = 'bar', color = 'orange')
plt.title("Sobreviventes por Classe")
plt.ylabel('Survived')
plt.xlabel('Pclass')
plt.show()