#import time
from multiprocessing import Process, Pipe, Event
from . import rq
from . import ur
from .sim.simenv import SimEnv

def create(use_sim, config):
    '''
    Creates the appropriate server for either sim or real (hardware) backing.
    '''
    server_type = SimRobotServer if use_sim else RealRobotServer
    return RemoteRobotProxy(server_type, config)

class InProcRobotServer():
    def __init__(self, config):
        self.activate_hand = config.get("hand.activate", True)

    def connect(self):
        self._arm_con.connect()
        self._hand_con.connect(self.activate_hand)
        self.arm = ur.ArmController(self._arm_con)
        self.hand = rq.HandController(self._hand_con)

    def disconnect(self):
        self._arm_con.disconnect()
        self._hand_con.disconnect()

    def update(self):
        pass

class RealRobotServer(InProcRobotServer):
    def __init__(self, config):
        super().__init__(config)
        self._arm_con = ur.Connection()
        self._hand_con = rq.Connection()

class SimRobotServer(InProcRobotServer):
    def __init__(self, config):
        super().__init__(config)
        self.env = SimEnv(config)
        self._arm_con = ur.SimConnection(self.env)
        self._hand_con = rq.SimConnection(self.env)

    def connect(self):
        self.env.connect()
        super().connect()

    def disconnect(self):
        super().disconnect()
        self.env.disconnect()

    def reset(self):
        self.env.reset()

    def update(self):
        self.env.update()

class RemoteRobotProxy():
    class PipeConnection:
        def __init__(self, pipe):
            self.pipe = pipe

        def execute(self, cmd, state):
            self.pipe.send_bytes(cmd.array)
            self.pipe.recv_bytes_into(state.array)

    def __init__(self, robot_type, config):
        self.__robot_type = robot_type
        self.__config = config

    def connect(self):
        hand_server, hand_client = Pipe(duplex=True)
        arm_server, arm_client = Pipe(duplex=True)
        self.__shutdown_event = Event()
        self.__reset_event = Event()
        self.__reset_event.set()
        self.__process = Process(target=server_loop,
                                 args=(arm_client,
                                       hand_client,
                                       self.__shutdown_event,
                                       self.__reset_event,
                                       self.__robot_type,
                                       self.__config))
        self.__process.start()
        self.arm = RemoteRobotProxy.PipeConnection(arm_server)
        self.hand = RemoteRobotProxy.PipeConnection(hand_server)
        return (self.arm, self.hand)

    def disconnect(self):
        self.__shutdown_event.set()
        self.__process.join()

    def reset(self):
        self.__reset_event.clear()
        self.__reset_event.wait()

#************************************************************************************************
# Server loop
#************************************************************************************************
def server_loop(arm_client, hand_client, shutdown_event, reset_event, robot_type, config):
    '''
    Control loop running at the same frequency as the hardware (e.g. 125Hz) (best effort but not guaranteed).
    It enables high(er)-speed closed-loop control using force and tactile sensing (but no vision).
    '''
    robot = robot_type(config)
    robot.connect()

    arm_cmd = ur.Command()
    arm_state = ur.State()
    hand_cmd = rq.Command()
    hand_state = rq.State()
    while not shutdown_event.is_set():
        #start_time = time.time()

        if not reset_event.is_set():
            # primarily in support of sim, this enables restoring the environment to an initial state
            robot.reset()
            reset_event.set()

        arm_cmd_is_new = arm_client.poll()
        if arm_cmd_is_new:
            arm_client.recv_bytes_into(arm_cmd.array) # blocking

        hand_cmd_is_new = hand_client.poll()
        if hand_cmd_is_new:
            hand_client.recv_bytes_into(hand_cmd.array) # blocking

        robot.hand.execute(hand_cmd, hand_state)
        robot.arm.execute(arm_cmd, arm_state)
        # robot.update()  # the hand (rq.sim_connection) already calls update()

        if arm_cmd_is_new:
            arm_client.send_bytes(arm_state.array)

        if hand_cmd_is_new:
            hand_client.send_bytes(hand_state.array)

        # if time.time()-start_time > 2*freq:
        #     print("Server loop lagging: " + str(time.time()-start_time))

    # Disconnect the arm and gripper.
    robot.disconnect()


import time
import traceback
import socket

import Cli
import TcpProtocol
import Config

class SumoServer:
    def __init__(self, timeout):

        self.timeout = timeout

        self.toUnitySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.toUnitySocket.setblocking(False)

        toUnityAddress = (
            Config.TCP_IP_ADDR,
            int(Config.TCP_PORT_TO_UNITY)
        )

        self.toUnitySocket.bind(toUnityAddress)

        self.socketStream = None
        self.socketAddress = None

    def startServing(self):
        Cli.printLine(2, "Connecting Sumo Server to Unity Listener...")

        self.toUnitySocket.listen(1)

        stopWatch = time.time()
        trying = True

        while trying:
            if time.time() - stopWatch > self.timeout:
                Cli.printLine(3, "[ERROR] Connection timed out!")
                exit()

            try:
                tmpSocket, tmpAddress = self.toUnitySocket.accept()
                tmpSocket.setblocking(False)
                trying = False

                Cli.printLine(3, "Connection accepted!")

            except BlockingIOError:
                pass

            except Exception as exception:
                traceback.print_exc()
                print(exception)
                Cli.printLine(0, "[ERROR] Error occured while trying to make connection to Unity Listener.")
                exit()

        self.socketStream = tmpSocket
        self.socketAddress = tmpAddress

    def sendMessage(self, message):
        if message is None:
            return

        self.socketStream.send(message.encode())

    def closeSocket(self):
        self.toUnitySocket.close()

    @staticmethod
    def CompileMessage(
        destinationCode,
        commandCode,
        data
    ):
        if data is None:
            return None

        return destinationCode + TcpProtocol.MSG_DELIM + commandCode + TcpProtocol.MSG_DELIM + data + TcpProtocol.END_OF_MSG


'''Backtest Moving Average (MA) crossover strategies
'''

import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import timedelta
from backtester import Backtester

class DonchianBacktester(Backtester):
    '''Backtest for the "Donachian" strategy

    Long on new 55 day high, close on 20 day low
    Short on new 55 day low, close on 20 day high

    Parameters:
    series: (Panda Series) a list of CLOSE prices by date
    entry: (int) how many days for long / short entry calculation
    exit : (int) how many days for long / short exit calculation
    '''

    def __init__(self, series, entry=55, exit=20):
        self._entry = entry
        self._exit = exit
        super(DonchianBacktester,self).__init__(series,long_only=False)

    def __str__(self):
        return "Donchian Backtest Strategy (entry=%d, exit=%d, long_only=%s, start=%s, end=%s)" % (
            self._entry, self._exit, False, str(self._start_date), str(self._end_date))

    def _trade_logic(self):
        '''Implements the trade logic in order to come up with
        a set of stances
        '''

        current_stance = 0
        stances = []

        long_entry_level = self._df['last'].rolling(window=self._entry).max()
        long_exit_level = self._df['last'].rolling(window=self._exit).min()
        short_entry_level = self._df['last'].rolling(window=self._entry).min()
        short_exit_level = self._df['last'].rolling(window=self._exit).max()

        for index in np.arange(0,len(self._df)):

            long_signal = False
            short_signal = False
            long_close = False
            short_close = False
            close = self._df['last'].iloc[index]

            if close >= long_entry_level[index]:
                long_signal = True

            if close <= short_entry_level[index]:
                short_signal = True

            if close <= long_exit_level[index]:
                long_close = True

            if close >= short_exit_level[index]:
                short_close = True

            if current_stance == 0:
                if long_signal:
                    current_stance = 1
                elif short_signal:
                    current_stance = -1
            elif current_stance == 1:
                if long_close:
                    current_stance = 0
            elif current_stance == -1:
                if short_close:
                    current_stance = 0

            stances.append(current_stance)

        self._df['stance'] = stances


import boto3
from boto3.dynamodb.types import TypeDeserializer
from storyweb.utils.chapters import Chapter
from storyweb.utils.constants import DDB_TABLE_NAME, error_page
from storyweb.style import load_css

ddbclient = boto3.client("dynamodb")
table = boto3.resource("dynamodb").Table(DDB_TABLE_NAME)
sqs = boto3.resource("sqs")

def lambda_handler(event, context):
    queue = sqs.get_queue_by_name(QueueName="stories-texts-to-process.fifo")
    params = event.get("queryStringParameters", {})
    if not (params):
        return error_page("Invalid get parameters")

    chapter_id = params.get("chapter_id", None)
    chapter_text = params.get("chapter_text", None)
    story_id = params.get("story_id", None)

    if event.get("isLocal", False):
        return generate_response(story_id, chapter_id, "123")

    if not chapter_text or not chapter_id or not story_id:
        return error_page(reason="text, chapter id and story id are required")

    new_option_id = params.get("new_option_id", None)
    new_option_text = params.get("new_option_text", None)

    existing_options = {
        k.replace("option_", ""): v
        for k, v in params.items()
        if k.startswith("option_")
    }

    for i in (
        chapter_id,
        story_id,
        chapter_text,
        new_option_id,
        new_option_text,
        *existing_options.keys(),
        *existing_options.values(),
    ):
        check_input(i)

    chapter = get_chapter(story_id=story_id, chapter_id=chapter_id)
    disabled_options = chapter.disabled_options

    if len(chapter.get_choices()) != len(existing_options):
        return error_page(reason="invalid amount of options")

    print("Existing options: ", existing_options)
    for key in chapter.get_choices().keys():
        # protect against URL tampering, rn we only support adding options or editing existing ones
        # otherwise the graph could inadvertently be split into two causing the end of the world
        if str(key) not in existing_options.keys():
            return error_page(
                reason=f"passed key {key} does not match the data stored for the chapter: {existing_options.keys()}"
            )

    # Create a new chapter if new_option_text is set and no existing chapter with that id exists
    if new_option_text and new_option_id:
        if not isinstance(
            get_chapter(story_id=story_id, chapter_id=new_option_id), Chapter
        ):
            # Upload new chapter before updating existing chapter to avoid dead nodes
            table.put_item(
                Item=dict(
                    story=story_id, chapter=new_option_id, is_work_in_progress=True
                )
            )
        disabled_options.append(new_option_id)
        existing_options[new_option_id] = new_option_text

    # Create the updated chapter
    text_was_updated = chapter_text != chapter.text
    text_to_send = chapter_text if text_was_updated else chapter.text
    ddb_item = dict(
        story=story_id,
        chapter=chapter_id,
        image=chapter.image,
        text=text_to_send,
    )

    if existing_options:
        ddb_item["options"] = [
            {"next": key, "text": value} for key, value in existing_options.items()
        ]
    if chapter.is_start():
        ddb_item["is_start_node"] = True
    if disabled_options:
        ddb_item["disabled_options"] = disabled_options

    # Upload the updated chapter
    print(f"Uploading chapter: {ddb_item}")
    table.put_item(Item=ddb_item)

    try:
        if text_was_updated:
            print("text was updated, attempting to send message to SQS")
            queue.send_message(
                MessageBody=text_to_send,
                MessageAttributes={
                    "story": {"StringValue": story_id, "DataType": "String"},
                    "chapter": {"StringValue": chapter_id, "DataType": "String"},
                },
                MessageGroupId=f"{story_id}#{chapter_id}",
            )
    except Exception as e:
        print(
            f"Unable to send message to queue: {text_to_send} chapter: {chapter_id} story_id: {story_id}, exception was: {e}"
        )
    # Return HTML with 2 buttons, one to view the new chapter and one to return to the edit screen for the newly created chapter
    return generate_response(
        story_id,
        chapter_id,
        new_option_id if new_option_text else None,
    )

def generate_response(story_id, chapter_id, new_option_id):
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "text/html"},
        "body": generate_body(
            story_id=story_id, chapter_id=chapter_id, new_option_id=new_option_id
        ),
    }

def get_chapter(story_id, chapter_id):
    print(f"Querying for story: {story_id} and chapter: {chapter_id}")
    response = ddbclient.query(
        TableName=DDB_TABLE_NAME,
        KeyConditionExpression="story = :story AND chapter = :chapter",
        ExpressionAttributeValues={
            ":story": {"S": story_id},
            ":chapter": {"S": chapter_id},
        },
    )
    print("Got response")
    print(response)

    items = response.get("Items", [])
    if len(items) != 1:
        return error_page()
    _chapter = from_dynamodb_to_json(items[0])
    return Chapter(chapter=_chapter, filter_choices=False)

def check_input(text):
    # TODO what would be deemed malicious / could we check this before sending request?
    pass

def from_dynamodb_to_json(item):
    d = TypeDeserializer()
    return {k: d.deserialize(value=v) for k, v in item.items()}

def generate_body(story_id, chapter_id, new_option_id):
    html = get_html()
    style = load_css("update_story_lambda")

    new_chapter_button = (
        f'
Edit the newly created chapter
'
        if new_option_id
        else ""
    )
    view_updated_chapter_button = f'
View your changes to chapter {chapter_id}
'
    buttons = [new_chapter_button, view_updated_chapter_button]
    formatted = html % (style, "".join(buttons))
    # print(formatted)
    return formatted

def get_html():
    return """
    <!DOCTYPE html>

        <title>Network</title>

            %s

    """


import random
import networkx as nx
import matplotlib.pyplot as plt
import graph_params as gp

# Функция добавления линии графа
def add_edge(f_item, s_item, graph = None, color = 'black'):
    graph.add_edge(f_item, s_item, color=color)
    graph.add_edge(s_item, f_item, color=color)

# Рисует граф
def graph_drawing(graph_info, show_cycle = False, cycle = None):
    graph = nx.Graph()
    if not show_cycle and not cycle:
        graph.add_nodes_from(graph_info.keys())
    else:
        for node in graph_info.keys():
            if node == cycle[0] or node == cycle[len(cycle)-1]:
                graph.add_node(node, color = 'blue')
            else:
                graph.add_node(node, color = 'gray')
    # Создает связи между точками
    for vertex in graph_info.keys():
        for edge in graph_info.get(vertex):
            add_edge(vertex, edge, graph)
    # Раскрашивает связи если передан гамильтонов цикл
    if show_cycle and cycle:
        for i in range(0, 20):
            if i < 19:
                add_edge(cycle[i], cycle[i + 1], graph, color = 'g')
            else:
                add_edge(cycle[0], cycle[i], graph, color = 'g')
    # Рисует раскрашеный граф, если есть цикл
    if show_cycle:
        colors_edge = nx.get_edge_attributes(graph, 'color').values()
        colors_nodes = nx.get_node_attributes(graph, 'color').values()
        nx.draw_spring(graph, edge_color = colors_edge, node_color = colors_nodes, node_size = 1000, with_labels = True)
    # Рисует не раскрашеный граф
    else:
        nx.draw_spring(graph, edge_color = 'red', node_color = 'yellow', node_size = 1000, with_labels = True)
    plt.show()

def shuffle(graph_info: dict, cycle: list):
    new_graph = {}
    new_cycle = []
    repl = [str(i) for i in graph_info.keys()]
    dictionary = {}
    # В ходе цикла меняет названия всех вершин графа
    for i in graph_info.keys():
        choise = random.choice(repl)
        repl.remove(choise)
        dictionary[i] = choise

    # Переименовывает Вершины на полученные
    for key in graph_info.keys():
        for value in graph_info.get(key):
            if new_graph.get(dictionary.get(key)):
                new_graph[dictionary.get(key)].append(dictionary.get(value))
            else:
                new_graph[dictionary.get(key)] = [dictionary.get(value)]
    # Обновляет цикл в соответствии со словарем
    for i in cycle:
        new_cycle.append(dictionary.get(i))
    return new_graph, new_cycle, dictionary

if __name__ == "__main__":
    ig, gm, shuf = shuffle(gp.graph_info, gp.origin_graph_cycle)
    graph_drawing(ig)
    num = int(input("Ответить на вопрос:\n1 -  Гамильтонов цикл изоморфного графа \n2 -  Доказать, что граф изоморфный\n"))
    if num == 1:
        print(f'Гамильтонов цикл: {gm}')
    if num == 2:
        print(f'Перестановка: {shuf}')
        print(f'Вершины и их пути: {ig}')


"""Langevin dynamics class."""

import numpy as np
from numpy.random import standard_normal, randint
import asap3
import ase
from asap3.md.md import MolecularDynamics, ParallelMolDynMixin
from ase.md.langevin import Langevin as Langevin_ASE
import asap3.constraints
import sys

class Langevin_New(object, Langevin_ASE, ParallelMolDynMixin):
    def __init__(self, atoms, timestep, temperature, friction, fixcm=True,
                 trajectory=None, logfile=None, loginterval=1):
        assert(getattr(Langevin_ASE, "_lgv_version", 1) >= 2)
        ParallelMolDynMixin.__init__(self, "Langevin", atoms)
        Langevin_ASE.__init__(self, atoms, timestep, temperature, friction, fixcm,
                              trajectory, logfile, loginterval, communicator=None)

    sdpos = property(lambda s: s.get("sdpos"), lambda s, x: s.set("sdpos", x))
    sdmom = property(lambda s: s.get("sdmom"), lambda s, x: s.set("sdmom", x))
    c1 = property(lambda s: s.get("c1"), lambda s, x: s.set("c1", x))
    c2 = property(lambda s: s.get("c2"), lambda s, x: s.set("c2", x))
    act0 = property(lambda s: s.get("act0"), lambda s, x: s.set("act0", x))
    c3 = property(lambda s: s.get("c3"), lambda s, x: s.set("c3", x))
    c4 = property(lambda s: s.get("c4"), lambda s, x: s.set("c4", x))
    pmcor = property(lambda s: s.get("pmcor"), lambda s, x: s.set("pmcor", x))
    cnst = property(lambda s: s.get("cnst"), lambda s, x: s.set("cnst", x))
    masses = property(lambda s: s.get("masses"), lambda s, x: s.set("masses", x))

class Langevin_Fast(object, Langevin_ASE, ParallelMolDynMixin):
    def __init__(self, atoms, timestep, temperature, friction, fixcm=True,
                 trajectory=None, logfile=None, loginterval=1):
        assert(getattr(Langevin_ASE, "_lgv_version", 1) >= 2)
        ParallelMolDynMixin.__init__(self, "Langevin", atoms)
        self._uselocaldata = False # Need to store on atoms for serial simul too.
        self.calculator = atoms.get_calculator()
        self.asap_md = asap3._asap.Langevin(atoms, self.calculator, timestep,
                                            self.prefix+"sdpos", self.prefix+"sdmom",
                                            self.prefix+"c1", self.prefix+"c2",
                                            fixcm, randint(1 << 30))
        if not atoms.has('momenta'):
            atoms.set_momenta(np.zeros((len(atoms), 3), float))
        if atoms.constraints:
            assert len(atoms.constraints) == 1
            constraint = atoms.constraints[0]
            assert isinstance(constraint, asap3.constraints.FixAtoms)
            constraint.prepare_for_asap(atoms)
            # Make all constants arrays by making friction an array
            friction = friction * np.zeros(len(atoms))
        Langevin_ASE.__init__(self, atoms, timestep, temperature, friction, fixcm,
                              trajectory, logfile, loginterval, communicator=None)

    def updatevars(self):
        Langevin_ASE.updatevars(self)
        if len(self.atoms.constraints) == 1:
            # Process the FixAtoms constraint
            constr = self.atoms.constraints[0].index
            self.sdpos[constr] = 0.0
            self.sdmom[constr] = 0.0
            self.c1[constr] = 0.0
            self.c2[constr] = 0.0
            self.c3[constr] = 0.0
            self.c4[constr] = 0.0
            self.act0[constr] = 0.0
        if self._localfrict:
            self.asap_md.set_vector_constants(self.prefix+"act0", self.prefix+"c3",
                                              self.prefix+"c4", self.prefix+"pmcor",
                                              self.prefix+"cnst")
        else:
            self.asap_md.set_scalar_constants(self.act0, self.c3, self.c4,
                                              self.pmcor, self.cnst)

    def run(self, steps):
        assert(self.calculator is self.atoms.get_calculator())
        self.asap_md.run(steps, self.observers, self)

    def get_random(self, gaussian):
        return self.asap_md.get_random(gaussian)

    # Properties are not inherited, need to repeat them
    sdpos = property(lambda s: s.get("sdpos"), lambda s, x: s.set("sdpos", x))
    sdmom = property(lambda s: s.get("sdmom"), lambda s, x: s.set("sdmom", x))
    c1 = property(lambda s: s.get("c1"), lambda s, x: s.set("c1", x))
    c2 = property(lambda s: s.get("c2"), lambda s, x: s.set("c2", x))
    act0 = property(lambda s: s.get("act0"), lambda s, x: s.set("act0", x))
    c3 = property(lambda s: s.get("c3"), lambda s, x: s.set("c3", x))
    c4 = property(lambda s: s.get("c4"), lambda s, x: s.set("c4", x))
    pmcor = property(lambda s: s.get("pmcor"), lambda s, x: s.set("pmcor", x))
    cnst = property(lambda s: s.get("cnst"), lambda s, x: s.set("cnst", x))
    masses = property(lambda s: s.get("masses"), lambda s, x: s.set("masses", x))

class Langevin_Old(MolecularDynamics):
    """Langevin (constant N, V, T) molecular dynamics.

    Usage: Langevin(atoms, dt, temperature, friction)

    atoms
        The list of atoms.

    dt
        The time step.

    temperature
        The desired temperature, in energy units.

    friction
        A friction coefficient, typically 1e-4 to 1e-2.

    fixcm
        If True, the position and momentum of the center of mass is
        kept unperturbed.  Default: True.

    The temperature and friction are normally scalars, but in principle one
    quantity per atom could be specified by giving an array.

    This dynamics accesses the atoms using Cartesian coordinates."""

    def __init__(self, atoms, timestep, temperature, friction, fixcm=True,
                 trajectory=None, logfile=None, loginterval=1):
        MolecularDynamics.__init__(self, atoms, timestep, trajectory,
                                   logfile, loginterval)
        self.temp = temperature
        self.frict = friction
        self.fixcm = fixcm  # will the center of mass be held fixed?

        # We need to store some data on the atoms, so they can migrate
        # along with the atoms in parallel asap simulations.  Since
        # there could be more than one Langevin object acting on the
        # same atoms, a unique prefix to the variable names is needed.
        i = 0
        while True:
            self.prefix = "langevin%d_" % (i,)
            if not self.atoms.has(self.prefix+"sdmom"):
                break  # Found unique prefix
            i += 1
        self.updatevars()

    def set_temperature(self, temperature):
        self.set("temp", temperature)
        self.updatevars()

    def set_friction(self, friction):
        self.set("frict", friction)
        self.updatevars()

    def set_timestep(self, timestep):
        self.dt = timestep
        self.updatevars()

    def updatevars(self):
        dt = self.dt
        # If the friction is an array some other constants must be arrays too.
        frict = self.get("frict")
        temp = self.get("temp")
        self._localfrict = hasattr(frict, 'shape')
        lt = frict * dt
        masses = self.atoms.get_masses()
        sdpos = dt * np.sqrt(temp / masses * (2.0/3.0 - 0.5 * lt) * lt)
        sdpos.shape = (-1, 1)
        sdmom = np.sqrt(temp * masses * 2.0 * (1.0 - lt) * lt)
        sdmom.shape = (-1, 1)
        pmcor = np.sqrt(3.0)/2.0 * (1.0 - 0.125 * lt)
        cnst = np.sqrt((1.0 - pmcor) * (1.0 + pmcor))

        act0 = 1.0 - lt + 0.5 * lt * lt
        act1 = (1.0 - 0.5 * lt + (1.0/6.0) * lt * lt)
        act2 = 0.5 - (1.0/6.0) * lt + (1.0/24.0) * lt * lt
        c1 = act1 * dt / masses
        c1.shape = (-1, 1)
        c2 = act2 * dt * dt / masses
        c2.shape = (-1, 1)
        c3 = (act1 - act2) * dt
        c4 = act2 * dt
        del act1, act2
        if self._localfrict:
            # If the friction is an array, so are these
            act0.shape = (-1, 1)
            c3.shape = (-1, 1)
            c4.shape = (-1, 1)
            pmcor.shape = (-1, 1)
            cnst.shape = (-1, 1)
        self.set("sdpos", sdpos)
        self.set("sdmom", sdmom)
        self.set("c1", c1)
        self.set("c2", c2)
        self.set("act0", act0)
        self.set("c3", c3)
        self.set("c4", c4)
        self.set("pmcor", pmcor)
        self.set("cnst", cnst)
        self.natoms = self.atoms.get_number_of_atoms()

    def step(self, f):
        atoms = self.atoms
        p = self.atoms.get_momenta()

        random1 = standard_normal(size=(len(atoms), 3))
        random2 = standard_normal(size=(len(atoms), 3))

        rrnd = self.get("sdpos") * random1
        prnd = (self.get("sdmom") * self.get("pmcor") * random1 +
                self.get("sdmom") * self.get("cnst") * random2)

        if self.fixcm:
            rrnd = rrnd - np.sum(rrnd, 0) / len(atoms)
            prnd = prnd - np.sum(prnd, 0) / len(atoms)
            factor = np.sqrt(self.natoms / (self.natoms - 1.0))
            rrnd *= factor
            prnd *= factor

        atoms.set_positions(atoms.get_positions() +
                            self.get("c1") * p +
                            self.get("c2") * f + rrnd)
        p *= self.get("act0")
        p += self.get("c3") * f + prnd
        atoms.set_momenta(p)

        f = atoms.get_forces()
        atoms.set_momenta(atoms.get_momenta() + self.get("c4") * f)
        return f

def Langevin(atoms, *args, **kwargs):
    if (isinstance(atoms, ase.Atoms)
        and asap3.constraints.check_asap_constraints(atoms)
        and getattr(Langevin_ASE, "_lgv_version", 1) >= 2
       ):
        sys.stderr.write("Using Asap-optimized C++-Langevin algorithm\n")
        return Langevin_Fast(atoms, *args, **kwargs)
    elif getattr(Langevin_New, "_lgv_version", 1) >= 2:
        sys.stderr.write("Using ASE-based Langevin algorithm\n")
        return Langevin_New(atoms, *args, **kwargs)
    else:
        sys.stderr.write("Using reimplemented Python-Langevin algorithm\n")
        return Langevin_Old(atoms, *args, **kwargs)


from rest_framework import status
import requests
import json
import copy

from koiki.delivery_create import CreateDelivery
from koiki.delivery_update import UpdateDelivery
from koiki.delivery_status import DeliveryStatus
from koiki.delivery import Delivery
import lazona_connector.vars

# API_PATH = "/rekis/api"

class Client:
    def __init__(
        self,
        logger=lazona_connector.vars.logger
    ):
        self.logger = logger

    def create_delivery(self, order):
        create_delivery = CreateDelivery(order)
        req_body_create_delivery = create_delivery.body()
        self.logger.info(
            'Koiki request to {}. body={}'.format(
                create_delivery.url(),
                create_delivery.body()
            )
        )

        response = requests.post(
            create_delivery.url(),
            json=create_delivery.auth_body())
        response_body = json.loads(response.text)

        deliveries = []
        if response.status_code == status.HTTP_200_OK:
            if response_body["envios"] == []:
                self._log(response.status_code, response_body, level="error")

            for num, delivery_data in enumerate(response_body["envios"]):
                vendor = order.vendors[num]
                req_body_shipping = req_body_create_delivery["envios"][num]
                delivery_data["order_id"] = order.order_id
                delivery = Delivery(delivery_data, vendor, req_body_shipping)

                if delivery._is_errored():
                    self._log(delivery.get_data_val("response"), delivery.data, level="error")
                else:
                    self._log(delivery.get_data_val("response"), self._masked_body(delivery_data))

                deliveries.append(delivery)

        else:
            self._log(response.status_code, response_body, level="error")

        return deliveries

    def update_delivery_status(self, delivery_id):
        update_delivery = UpdateDelivery(delivery_id)
        self.logger.info(
            'Koiki request to {}. body={}'.format(
                update_delivery.url(),
                update_delivery.body()
            )
        )
        response = requests.post(
            update_delivery.url(),
            json=update_delivery.auth_body()
        )
        response_body = json.loads(response.text)
        if response.status_code == status.HTTP_200_OK:
            return DeliveryStatus(response_body)
        else:
            self._log(response.status_code, response_body, level="error")
        return False

    def _log(self, code, msg, level="info"):
        log_line = "Koiki response. status={}, body={}".format(code, msg)

        if level == "info":
            self.logger.info(log_line)
        else:
            self.logger.error(log_line)

    def _masked_body(self, data):
        masked_body = copy.deepcopy(data)
        masked_body["etiqueta"] = f"{masked_body['etiqueta'][:10]}..."
        return masked_body


from PySide2.QtWidgets import QGroupBox, QLineEdit, QVBoxLayout, QWidget

from src.events.ListenerNode import ListenerNode

class TextFilter(QWidget, ListenerNode):
    def __init__(self, listeners_pool, *args, **kwargs):
        super(TextFilter, self).__init__(*args, **kwargs)
        ListenerNode.__init__(self, 'text-filter', listeners_pool)

        self.line_edit = QLineEdit()

        layout = QVBoxLayout()
        self.setLayout(layout)

        inner_layout = QVBoxLayout()
        inner_layout.addWidget(self.line_edit)

        group_box = QGroupBox("Texto a buscar")
        group_box.setLayout(inner_layout)

        layout.addWidget(group_box)

        self.line_edit.textEdited.connect(self.text_changed)

    def text_changed(self, text):
        value = None

        if len(text) > 1:
            value = text

        self.send_event('filter-widget', 'change_search_value', value)


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

# In[7]:

import numpy

RUNS= 1000
iterations_total = 0
mismatch_total = 0

for run in range(RUNS):
    A = numpy.random.uniform(-1, 1, size = 2)
    B = numpy.random.uniform(-1, 1, size = 2)
    m = (B[1] - A[1]) / (B[0] - A[0])
    b = B[1] - m * B[0]
    N = 100
    X = numpy.transpose(numpy.array([numpy.ones(N), numpy.random.uniform(-1, 1, size = N), numpy.random.uniform(-1, 1, size = N)]))
    woff = numpy.array([b, m, -1])
    X = numpy.transpose(numpy.array([numpy.ones(N), numpy.random.uniform(-1, 1, size = N), numpy.random.uniform(-1, 1, size = N)]))
    yoff = numpy.sign(numpy.dot(X, woff))
    wofh = numpy.zeros(3)
    t = 0
    while True:
        yofh = numpy.sign(numpy.dot(X, wofh))
        comp = (yofh != yoff)
        wrong = numpy.where(comp)[0]
        if wrong.size == 0:
            break
        rnd_choice = numpy.random.choice(wrong)
        wofh = wofh +  yoff[rnd_choice] * numpy.transpose(X[rnd_choice])
        t += 1

    iterations_total += t
    N_outside = 1000
    test0 = numpy.random.uniform(-1, 1, size = N_outside)
    test1 = numpy.random.uniform(-1, 1, size = N_outside)

    X = numpy.array([numpy.ones(N_outside), test0, test1])

    y_target = numpy.sign(numpy.dot(X, woff))
    y_hypothesis = numpy.sign(numpy.dot(X, wofh))

    ratio_mismatch = ((y_target != y_hypothesis).sum()) / N_outside
    ratio_mismatch_total += ratio_mismatch

print("No. of training data: N = ", N, "points")

iterations_avg = iterations_total / RUNS
print("\nAverage number of PLA iterations over", RUNS, "runs: t_avg = ", iterations_avg)

ratio_mismatch_avg = ratio_mismatch_total / RUNS
print("\nAverage ratio for the mismatch between f(x) and h(x) outside of the training data:")
print("P(f(x)!=h(x)) = ", ratio_mismatch_avg)

# In[ ]:

# In[ ]:


import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd

# read data
height = 260
width = 346

path_to_temp_data = "../../data/temp/"
path_to_data = "../../data/real_power_line/flight2/"
path_to_lines = path_to_temp_data + "lines.txt"
path_to_events = path_to_temp_data + "lines_events.txt"

while True:
    lines_df = pd.read_csv(
        path_to_lines,
        delim_whitespace=True,
        header=None,
        names=["line_id", "x_1", "y_1", "x_2", "y_2", "t", "state"],
        dtype={"line_id": np.int16, "x_1": np.float64, "y_1": np.float64, "x_2": np.float64, "y_2": np.float64, "t": np.float64, "state": np.int16},
        memory_map=True,
        )

    events_df = pd.read_csv(
        path_to_events,
        delim_whitespace=True,
        header=None,
        names=["t", "x", "y", "p"],
        dtype={"t": np.float64, "x": np.int16, "y": np.int16, "p": np.int16},
        memory_map=True,
    )

    images_df = pd.read_csv(
        path_to_data + "images.txt",
        delim_whitespace=True,
        header=None,
        names=["t", "img_name"],
        dtype={"t": np.float64, "img_name": str},
        memory_map=True,
        )

    t = lines_df.iloc[0]["t"]
    image_idx = images_df['t'].sub(t / 1000).abs().idxmin()
    image_name = images_df.iloc[image_idx]['img_name']
    image_frame = cv2.cvtColor(cv2.imread(path_to_data + image_name, 0), cv2.COLOR_GRAY2RGB)

    lines = []
    for index, row in lines_df.iterrows():

        line_id = int(row["line_id"])
        x_1 = row["x_1"]
        y_1 = row["y_1"]

        x_2 = row["x_2"]
        y_2 = row["y_2"]
        state = int(row["state"])
        lines.append([line_id, x_1, y_1, x_2, y_2, state])

    events = []
    for index, row in events_df.iterrows():

        t = row["t"]
        x = int(row["x"])
        y = int(row["y"])
        p = int(row["p"])

        events.append([x, y, t, p])

    events = np.stack(events, axis=0)
    color = [0.0, 0.0, 1.0]
    image_events = np.zeros(height * width, dtype=np.uint8)
    np.add.at(image_events, (events[:, 0] + events[:, 1] * width).astype("int32"), 1)
    image_events = image_events.reshape((height, width))

    image_events = (
            np.stack(
                [
                    image_events * color[0],
                    image_events * color[1],
                    image_events * color[2],
                    ],
                axis=2,
            )
            * 255
    )

    image_events.astype("uint8")
    print((image_events != 0).shape)
    print(image_frame.shape)
    print(image_name)
    image_frame[image_events != 0] = 0
    image_superimposed = cv2.addWeighted(image_frame, 1, image_events.astype("uint8"), 1, 0)

    plt.imshow(image_superimposed)

    for line in lines:

        if line[5] == 0:
            line_color = "grey"
            text_color = "lightgrey"

        # hibernating lines
        elif line[5] == 1:
            line_color = "sandybrown"
            text_color = "peachpuff"
        # normal lines
        else:
            line_color = "firebrick"
            text_color = "lightcoral"

        end_point_1 = np.array([line[1], line[2]])
        end_point_2 = np.array([line[3], line[4]])
        point = (end_point_1 + end_point_2) / 2
        line_id = line[0]
        plt.text(
            point[0],
            point[1],
            str(line_id),
            fontsize=14,
            fontweight="bold",
            color=text_color,
        )
        plt.plot(
            [end_point_1[0], end_point_2[0]],
            [end_point_1[1], end_point_2[1]],
            linewidth=3,
            color=line_color,
        )
        plt.plot(end_point_1[0], end_point_1[1], color=line_color, linewidth=7)
        plt.plot(end_point_2[0], end_point_2[1], color=line_color, linewidth=7)

    plt.rcParams["figure.figsize"] = (20, 12)
    plt.title("Lines")
    plt.waitforbuttonpress()
    plt.cla()


import os
from sys import argv
from typing import List, Tuple, Optional
from directory_information import DISPLAY_DIRECTORY
from fnmatch import fnmatch
from file_interaction.files_parser import parse_files
from file_interaction.files_displayer import Displayer
from file_interaction.file_class import Files
from config import less

def check_to_search() -> bool:
    filename_idx = -1
    if '-s' in argv:
        filename_idx = argv.index('-s')
    elif '-search' in argv:
        filename_idx = argv.index('-search')

    max_recursion_idx = -1
    if '-smr' in argv:
        max_recursion_idx = argv.index('-smr')
    elif '-set-max-recursion' in argv:
        max_recursion_idx = argv.index('-set-max-recursion')

    max_recursion: Optional[str] = None
    if max_recursion_idx != -1 and max_recursion_idx <= len(argv) - 2:
        max_recursion = argv[max_recursion_idx+1]
        if not max_recursion.isdigit():
            max_recursion = None

    if filename_idx != -1 and filename_idx <= len(argv) - 2:
        if max_recursion:
            search(argv[filename_idx+1], int(max_recursion))
        else:
            search(argv[filename_idx+1])
        return True
    return False

finded_elements: List[Tuple[str, str]] = []

def search(filename: str, max_recursion: int = 3) -> None:
    global finded_elements
    finded_elements = []
    current_dir = DISPLAY_DIRECTORY
    _recursive_search(current_dir, filename, max_recursion=max_recursion)
    if len(finded_elements) == 0:
        return
    only_filenames: List[str] = []
    only_directories: List[str] = []
    for directory, filename in finded_elements:
        only_filenames.append(filename)
        only_directories.append(directory)

    files: Files = parse_files(only_filenames, only_directories)
    for file in files.files:
        if file.name_rus:
            file.name_eng = file.name_eng + ' {' + file.name_rus + '}' + '.' + file.extension
            name_idx = only_filenames.index(file.name_eng)
            file.name_rus = finded_elements[name_idx][0]
        else:
            name_idx = only_filenames.index(file.name_eng + '.' + file.extension)
            file.name_rus = finded_elements[name_idx][0]
        if less:
            path = file.name_rus
            tail, head_1 = os.path.split(path)
            _tail, head_2 = os.path.split(tail)
            file.name_rus = '...\\' + head_2 + '\\' + head_1
    Displayer().display_files(files)

def _recursive_search(
        current_dir: str,
        search_filename: str,
        current_recursion: int = 0,
        max_recursion: int = 3
    ) -> None:
    global finded_elements
    if current_recursion >= max_recursion:
        return
    files = os.listdir(current_dir)
    for filename in files:
        if fnmatch(filename, search_filename):
            finded_elements.append((current_dir, filename))
        if os.path.isdir(current_dir+'\\'+filename):
            _recursive_search(current_dir+'\\'+filename, search_filename, current_recursion+1, max_recursion)


#!/usr/bin/env python

"""
@author wanglinqing01@baidu.com
@date 2014/10/08
@brief delete verifiedEmail
"""

import os
import sys
import time
import traceback

_NOW_PATH = os.path.dirname(os.path.abspath(__file__)) + '/'
_BCE_PATH = _NOW_PATH + '../'
sys.path.insert(0, _BCE_PATH)

import bes_base_case
from baidubce.services.ses import client
from baidubce import exception

class TestDeleteVerifiedEmail(bes_base_case.BaseTest):
    def __init__(self):
        super(self.__class__, self).__init__()

    def setUp(self):
        time.sleep(1)

    def tearDown(self):
        pass

    def test_delete_verifiedEmail_normal(self):
        #print self.host
        cli = client.SesClient(self.host, self.ak, self.sk)
        email = 'wanglinqing2010@126.com'
        resp = cli.delete_verified_email(email)
        #print resp.status
        assert resp.status == 200, 'status is not 200'

    def test_delete_verifiedEmail_abnormal(self):
        cli = client.SesClient(self.host, self.ak, self.sk)
        email = "''"
        resp = cli.delete_verified_email(email)
        assert resp.status == 200, 'status is not 200'


from math import sqrt

def solve(a, b, c):
#    pass # это ставилось временно для пустой функции def
    d = b*b - 4*a*c
    if d < 0:
        print("No solutions")
    elif d == 0:
        x = -b / (2*a)
        print("One solution " + str(x))
    elif d > 0:
        x1 = (-b + sqrt(d)) / (2*a)
        x2 = (-b - sqrt(d)) / (2*a)
        print("Two solutions " + str(x1) + " and " + str(x2))
    else:
        print("The bag!!!")

solve(1, 1, 1)
solve(1, 2, 1)
solve(1, 5, 6)


from flask import Flask, request, flash, render_template,redirect, url_for
from static.image_processor import GenderTransformer
import os.path
import os, shutil
import time

from static import config

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = "./static/images"

engine = GenderTransformer()

def clear_image_directory():
    dir = config.input_dir
    for files in os.listdir(dir):
        path = os.path.join(dir, files)
        try:
            shutil.rmtree(path)
        except OSError:
            os.remove(path)

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/', methods=["POST"])
def upload_image():
    if 'file' not in request.files:
        # flash('No file part')
        return redirect(url_for('index'))
    uploaded_image = request.files['file']

    if uploaded_image.filename == '':
        # flash('No selected file')
        return redirect(url_for('index'))

    clear_image_directory()
    global path, out_name
    path = os.path.join(app.config["UPLOAD_FOLDER"], uploaded_image.filename)
    print(path)
    out_name = 'out'
    uploaded_image.save(path)
    try:
        for gender in ['male', 'female']:
            engine.transform_gender(
                gender=gender,
                input_path=config.input_dir,
                input_name=uploaded_image.filename,
                output_name_specif=out_name
            )
    except IndexError:
        return "Sorry, we hadn't found any face on your image. Please, select another one"

    return redirect(url_for('results_page'))

@app.route('/results')
def results_page():
    # the next line is for making Flask not cache the image
    dynamic_picture_ensurer = str(time.time())

    return render_template("results.html",
                           results="Results",
                           male_img='.'+app.config["UPLOAD_FOLDER"]+'/'+out_name+'_male.jpg?random='+dynamic_picture_ensurer,
                           female_img='.'+app.config["UPLOAD_FOLDER"]+'/'+out_name+'_female.jpg?random='+dynamic_picture_ensurer
                           )

if __name__ == '__main__':
    app.run(ssl_context='adhoc')


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

import cStringIO
import csv
import os

import re
import tempfile

from pyspark.sql import SQLContext

from scalableor.constant import COLUMN_NAME
from scalableor.context import eval_expression, to_grel_object
from scalableor.manager import MethodsManager

from scalableor.facet import get_facet_filter

@MethodsManager.register("scalableor/import")
def sc_or_import(cmd, sc=None, **kwargs):
    """
    import data in spark context and split rows in column

    :param cmd:         import parameters
    :param sc:          spark context object
    """
    rdd = sc.textFile(cmd["path"])
    rdd_splitted = rdd.map(lambda el: el.split(cmd["separator"]))
    sql_context = SQLContext(sc)
    df = sql_context.createDataFrame(rdd_splitted)

    for i in range(len(df.columns)):
        df = df.withColumnRenamed(df.columns[i], COLUMN_NAME % (i + 1))
    return df

@MethodsManager.register("scalableor/export")
def sc_or_export(cmd, df=None, **kwargs):
    """
    export data to file system

    :param cmd:         export parameters
    :param df:          spark data frame
    """
    tmp = tempfile.mkdtemp() + ".scalable.or"
    df.write.format("com.databricks.spark.csv").save(tmp)

    with open(cmd["path"], "w") as output:
        for fpath in sorted(os.listdir(tmp)):
            if fpath.startswith("part-"):
                with open(os.path.join(tmp, fpath), "r") as result:
                    for line in result.readlines():
                        output.write(line)

@MethodsManager.register("core/column-rename")
def core_column_rename(cmd, df, **kwargs):
    """
    rename column
    """
    return df.withColumnRenamed(cmd["oldColumnName"], cmd["newColumnName"])

@MethodsManager.register("core/column-removal")
def core_column_removal(cmd, df, **kwargs):
    """
    remove column by name
    """
    return df.drop(cmd["columnName"])

@MethodsManager.register("core/column-move")
def core_column_move(cmd, df, **kwargs):
    """
    move column to index by name
    """
    columns = df.columns[:]
    current_index = columns.index(cmd["columnName"])
    columns.insert(cmd["index"], columns.pop(current_index))

    replace_order = [i for i in range(len(columns))]
    replace_order.insert(cmd["index"], replace_order.pop(current_index))

    rdd_moved = df.rdd.map(lambda row: [row[i] for i in replace_order])
    return df.sql_ctx.createDataFrame(rdd_moved, columns)

@MethodsManager.register("core/row-removal")
def core_row_removal(cmd, df=None, **kwargs):
    """
    remove rows selected by facet filter
    """
    facet_filter = get_facet_filter(cmd, df)
    result = df.rdd.filter(lambda e: facet_filter(e) is False)
    return df.sql_ctx.createDataFrame(result, df.columns)

@MethodsManager.register("core/column-split")
def core_column_split(cmd, df=None, **kwargs):
    """
    split column by separator or field length
    """
    column_names = df.columns[:]
    pos = column_names.index(cmd["columnName"])

    before_columns = column_names[:pos]
    after_columns = column_names[pos + 1:]

    if "fieldLengths" in cmd:
        func = lambda e: \
            e[:pos + 1] + \
            tuple(to_grel_object(e[pos]).splitByLengths(*cmd["fieldLengths"])) + \
            e[pos + 1:]
    else:
        # max column logic
        if "maxColumns" in cmd:
            max_column = cmd["maxColumns"]
            if max_column == 1:
                return df
            if max_column > 1:
                max_column -= 1
        else:
            max_column = 0

        # if max column doesn't defined analyse first 20 column und select maximal column count
        if max_column < 1:
            max_column = 2
            for row in df.head(20):
                if hasattr(row[pos], "split"):
                    if cmd.get("regex") is True:
                        max_column = max(len(re.split(cmd["separator"], row[pos])), max_column)
                    else:
                        max_column = max(len(row[pos].split(cmd["separator"])), max_column)
            max_column -= 1

        # generate split callback
        add_to = ["" for _ in range(max_column + 1)]
        if cmd.get("regex") is True:
            func = lambda e: \
                e[:pos + 1] + \
                tuple((re.split(cmd["separator"], e[pos], max_column) + add_to)[:max_column + 1]) + \
                e[pos + 1:]
        else:
            func = lambda e: \
                e[:pos + 1] + \
                tuple((e[pos].split(cmd["separator"], max_column) + add_to)[:max_column + 1]) + \
                e[pos + 1:]

    result = df.sql_ctx.createDataFrame(df.rdd.map(func))

    # generate new column names
    new_column_names = (
        before_columns +
        [cmd["columnName"]] +
        ["%s %s" % (
            cmd["columnName"], i + 1) for i in range(len(result.columns) - len(df.columns))] +
        after_columns)

    for index, name in enumerate(new_column_names):
        result = result.withColumnRenamed("_%d" % (index + 1), name)

    if cmd.get("removeOriginalColumn") is True:
        result = result.drop(cmd["columnName"])
    return result

@MethodsManager.register("core/column-addition")
def core_column_addition(cmd, df, **kwargs):
    """
    create new column based on existing one
    """
    names = df.columns[:]
    position_of_column = df.columns.index(cmd["baseColumnName"])

    before_columns = df.columns[:position_of_column + 1]
    after_columns = df.columns[position_of_column + 1:]

    facet_fitler = get_facet_filter(cmd, df)

    # generate spark callback
    result_rdd = df.rdd.map(lambda e: (
        e[:position_of_column + 1] +
        ((eval_expression(e,
                          position_of_column,
                          cmd["expression"],
                          names=names),) if facet_fitler(e) else ("",)) +
        e[position_of_column + 1:]))

    return df.sql_ctx.createDataFrame(
        result_rdd,
        before_columns + [cmd["newColumnName"]] + after_columns)

@MethodsManager.register("core/text-transform")
def core_text_transform(cmd, df, **kwargs):
    """
    transform row values of selected column
    """
    names = df.columns[:]
    pos_of_column = df.columns.index(cmd["columnName"])
    facet_fitler = get_facet_filter(cmd, df)

    result_rdd = df.rdd.map(lambda e: (
        e[:pos_of_column] +
        ((eval_expression(e,
                          pos_of_column,
                          cmd["expression"],
                          names=names),) if facet_fitler(e) else (e[pos_of_column],)) +
        e[pos_of_column + 1:]))

    return df.sql_ctx.createDataFrame(result_rdd, df.columns)

@MethodsManager.register("core/mass-edit")
def core_mass_edit(cmd, df, **kwargs):
    """
    change row values of selected column using filter
    """
    pos_of_column = df.columns.index(cmd["columnName"])

    def core_mass_edit_callback(e):
        current_value = e[pos_of_column]
        new_value = None
        for edit in cmd["edits"]:
            if current_value in edit["from"]:
                new_value = edit["to"]
                break
        if new_value is None:
            new_value = current_value
        return (e[:pos_of_column] +
                (new_value,) +
                e[pos_of_column + 1:])

    return df.sql_ctx.createDataFrame(df.rdd.map(core_mass_edit_callback), df.columns)

@MethodsManager.register("core/fill-down")
def core_fill_down(cmd, df, **kwargs):
    """
    dummy function
    """
    return df


from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import *
from .forms import *

def index(request):
    pets = Pet.objects.all()
    context = {'pets':pets}
    return render(request,'list.html',context)

def addPet(request):
    pets = Pet.objects.all()
    form = FormPet()
    context = {'pets':pets,'form':form}
    if request.method == "POST":
        form = FormPet(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    return render(request,'add.html',context)

def detailPet(request,pk):
    context = {}
    context["pet"] = Pet.objects.get(id=pk)
    return render(request,'detail.html',context)

def deletePet(request,pk):
    pet = Pet.objects.get(id=pk)
    if request.method == "POST":
        pet.delete()
        return redirect('/')
    context = {'pet':pet}
    return render(request,'delete.html',context)

def updatePet(request,pk):
    pet = Pet.objects.get(id=pk)
    form = FormPet(instance=pet)
    if request.method == "POST":
        form = FormPet(request.POST, instance=pet)
        if form.is_valid():
            form.save()
            return redirect('/')
    context = {'form':form}
    return render(request,'update.html',context)

def adotPet(request,pk):
    pet = Pet.objects.get(id=pk)
    if request.method == "POST":
        pet.adotado = True
        pet.save()
        return redirect('/adotado')
    context = {'pet':pet}
    return render(request,'adot.html',context)

def adotado(request):
    return render(request,'adotado.html')


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

"""模型代码。"""

from __future__ import print_function, division, absolute_import

import tensorflow as tf
import collections

EPS = 1e-12
Model = collections.namedtuple("Model",
                               "outputs, predict_real, predict_fake, discrim_loss, discrim_grads_and_vars, gen_loss_GAN, gen_loss_L1, gen_grads_and_vars, train")

def discrim_conv(batch_input, out_channels, stride):
    padded_input = tf.pad(batch_input, [[0, 0], [1, 1], [1, 1], [0, 0]], mode="CONSTANT")
    return tf.layers.conv2d(padded_input, out_channels, kernel_size=4, strides=(stride, stride), padding="valid",
                            kernel_initializer=tf.random_normal_initializer(0, 0.02))

def gen_conv(batch_input, out_channels, separable_conv=False):
    """生成器的 encoder 部分。"""
    # [batch, in_height, in_width, in_channels] => [batch, out_height, out_width, out_channels]
    initializer = tf.random_normal_initializer(0, 0.02)
    if separable_conv:  # 深度可分卷积
        return tf.layers.separable_conv2d(batch_input, out_channels, kernel_size=4, strides=(2, 2), padding="same",
                                          depthwise_initializer=initializer, pointwise_initializer=initializer)
    else:
        return tf.layers.conv2d(batch_input, out_channels, kernel_size=4, strides=(2, 2), padding="same",
                                kernel_initializer=initializer)

def gen_deconv(batch_input, out_channels, separable_conv=False):
    """生成器的 decoder 部分。"""
    # [batch, in_height, in_width, in_channels] => [batch, out_height, out_width, out_channels]
    initializer = tf.random_normal_initializer(0, 0.02)
    if separable_conv:
        _b, h, w, _c = batch_input.shape
        resized_input = tf.image.resize_images(batch_input, [h * 2, w * 2],
                                               method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
        return tf.layers.separable_conv2d(resized_input, out_channels, kernel_size=4, strides=(1, 1), padding="same",
                                          depthwise_initializer=initializer, pointwise_initializer=initializer)
    else:
        return tf.layers.conv2d_transpose(batch_input, out_channels, kernel_size=4, strides=(2, 2), padding="same",
                                          kernel_initializer=initializer)

def lrelu(x, a):
    with tf.name_scope("lrelu"):
        # adding these together creates the leak part and linear part
        # then cancels them out by subtracting/adding an absolute value term
        # leak: a*x/2 - a*abs(x)/2
        # linear: x/2 + abs(x)/2

        # this block looks like it has 2 inputs on the graph unless we do this
        x = tf.identity(x)
        return (0.5 * (1 + a)) * x + (0.5 * (1 - a)) * tf.abs(x)

def batchnorm(inputs):
    return tf.layers.batch_normalization(inputs, axis=3, epsilon=1e-5, momentum=0.1, training=True,
                                         gamma_initializer=tf.random_normal_initializer(1.0, 0.02))

def create_generator(generator_inputs, generator_outputs_channels, ngf=64):
    """输入和输出都是 [batch_size, 256, 256, 3] 的 tensor.
    ngf 是第一层卷积层的深度。
    """
    layers = []

    # ngf 表示生成器的第一层的深度
    # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf]
    with tf.variable_scope("encoder_1"):
        output = gen_conv(generator_inputs, ngf)
        layers.append(output)

    layer_specs = [
        ngf * 2,  # encoder_2: [batch, 128, 128, ngf] => [batch, 64, 64, ngf * 2]
        ngf * 4,  # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]
        ngf * 8,  # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8]
        ngf * 8,  # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8]
        ngf * 8,  # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8]
        ngf * 8,  # encoder_7: [batch, 4, 4, ngf * 8] => [batch, 2, 2, ngf * 8]
        ngf * 8,  # encoder_8: [batch, 2, 2, ngf * 8] => [batch, 1, 1, ngf * 8]
    ]

    for out_channels in layer_specs:
        with tf.variable_scope("encoder_%d" % (len(layers) + 1)):
            rectified = lrelu(layers[-1], 0.2)
            # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2, out_channels]
            convolved = gen_conv(rectified, out_channels)
            output = batchnorm(convolved)
            layers.append(output)

    layer_specs = [
        (ngf * 8, 0.5),  # decoder_8: [batch, 1, 1, ngf * 8] => [batch, 2, 2, ngf * 8 * 2]
        (ngf * 8, 0.5),  # decoder_7: [batch, 2, 2, ngf * 8 * 2] => [batch, 4, 4, ngf * 8 * 2]
        (ngf * 8, 0.5),  # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2]
        (ngf * 8, 0.0),  # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2]
        (ngf * 4, 0.0),  # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2]
        (ngf * 2, 0.0),  # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2]
        (ngf, 0.0),  # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2]
    ]

    num_encoder_layers = len(layers)
    for decoder_layer, (out_channels, dropout) in enumerate(layer_specs):
        skip_layer = num_encoder_layers - decoder_layer - 1
        with tf.variable_scope("decoder_%d" % (skip_layer + 1)):
            if decoder_layer == 0:  # decoder 的第一层用的是 encoder 最后的输出
                # first decoder layer doesn't have skip connections
                # since it is directly connected to the skip_layer
                input = layers[-1]
            else:  # decoder 的每一层和 encoder 的每一层 拼接在一起
                input = tf.concat([layers[-1], layers[skip_layer]], axis=3)

            rectified = tf.nn.relu(input)
            # [batch, in_height, in_width, in_channels] => [batch, in_height*2, in_width*2, out_channels]
            output = gen_deconv(rectified, out_channels)
            output = batchnorm(output)

            if dropout > 0.0:
                output = tf.nn.dropout(output, keep_prob=1 - dropout)

            layers.append(output)

    # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels]
    with tf.variable_scope("decoder_1"):
        input = tf.concat([layers[-1], layers[0]], axis=3)
        rectified = tf.nn.relu(input)
        output = gen_deconv(rectified, generator_outputs_channels)
        output = tf.tanh(output)
        layers.append(output)

    return layers[-1]

def create_discriminator(discrim_inputs, discrim_targets, ndf=64):
    """判别器的输入是两个模态的图片。输出  [batch, 30, 30, 1]"""
    n_layers = 3
    layers = []

    # 第一步是把两个模态的图片在深度上拼在一起
    # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2]
    input = tf.concat([discrim_inputs, discrim_targets], axis=3)

    # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf]
    with tf.variable_scope("layer_1"):
        convolved = discrim_conv(input, ndf, stride=2)
        rectified = lrelu(convolved, 0.2)
        layers.append(rectified)

    # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2]
    # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4]
    # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8]
    for i in range(n_layers):
        with tf.variable_scope("layer_%d" % (len(layers) + 1)):
            out_channels = ndf * min(2 ** (i + 1), 8)
            stride = 1 if i == n_layers - 1 else 2  # last layer here has stride 1
            convolved = discrim_conv(layers[-1], out_channels, stride=stride)
            normalized = batchnorm(convolved)
            rectified = lrelu(normalized, 0.2)
            layers.append(rectified)

    # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1]
    with tf.variable_scope("layer_%d" % (len(layers) + 1)):
        convolved = discrim_conv(rectified, out_channels=1, stride=1)
        output = tf.sigmoid(convolved)
        layers.append(output)
    """注意 D 的输出不是 1 个值，而是一个 30 * 30 的矩阵，对应每个 patch 是否是真实的。
    最后一层的输出用的是 sigmoid 激活函数。
    """
    return layers[-1]

def create_model(inputs, targets, gan_weight=1.0, l1_weight=100.0, lr=0.0002, beta1=0.5):
    with tf.variable_scope("generator"):
        out_channels = int(targets.get_shape()[-1])
        outputs = create_generator(inputs, out_channels)  # outputs 是生成的图片

    # create two copies of discriminator, one for real pairs and one for fake pairs
    # they share the same underlying variables
    with tf.name_scope("real_discriminator"):
        with tf.variable_scope("discriminator"):
            # 2x [batch, height, width, channels] => [batch, 30, 30, 1]
            predict_real = create_discriminator(inputs, targets)

    with tf.name_scope("fake_discriminator"):
        with tf.variable_scope("discriminator", reuse=True):
            # 2x [batch, height, width, channels] => [batch, 30, 30, 1]
            predict_fake = create_discriminator(inputs, outputs)

    with tf.name_scope("discriminator_loss"):
        # minimizing -tf.log will try to get inputs to 1
        # predict_real => 1
        # predict_fake => 0
        """我们对每个patch进行判断真假，然后取平均值作为结果。
        predict_real 越大越好； 1 - predict_fake 越小越好"""
        discrim_loss = tf.reduce_mean(-(tf.log(predict_real + EPS) + tf.log(1 - predict_fake + EPS)))

    with tf.name_scope("generator_loss"):
        # predict_fake => 1
        # abs(targets - outputs) => 0
        """生成器包含两部分的损失函数：
        一部分是想让生成的图片越真实越好；另一部分是越接近目标图片越好。
        因为在本例中是监督学习。
        gan_weight：1， l1_weight: 100
        """
        gen_loss_GAN = tf.reduce_mean(-tf.log(predict_fake + EPS))
        gen_loss_L1 = tf.reduce_mean(tf.abs(targets - outputs))
        gen_loss = gen_loss_GAN * gan_weight + gen_loss_L1 * l1_weight

    with tf.name_scope("discriminator_train"):
        discrim_tvars = [var for var in tf.trainable_variables() if var.name.startswith("discriminator")]
        discrim_optim = tf.train.AdamOptimizer(lr, beta1)
        discrim_grads_and_vars = discrim_optim.compute_gradients(discrim_loss, var_list=discrim_tvars)
        discrim_train = discrim_optim.apply_gradients(discrim_grads_and_vars)

    with tf.name_scope("generator_train"):
        with tf.control_dependencies([discrim_train]):
            gen_tvars = [var for var in tf.trainable_variables() if var.name.startswith("generator")]
            gen_optim = tf.train.AdamOptimizer(lr, beta1)
            gen_grads_and_vars = gen_optim.compute_gradients(gen_loss, var_list=gen_tvars)
            gen_train = gen_optim.apply_gradients(gen_grads_and_vars)

    """对损失函数进行指数平均, 但是 num_updates=None，实际上并没有什么效果，只是把这3个损失拼在一起罢了。"""
    ema = tf.train.ExponentialMovingAverage(decay=0.99)
    update_losses = ema.apply([discrim_loss, gen_loss_GAN, gen_loss_L1])

    global_step = tf.train.get_or_create_global_step()
    incr_global_step = tf.assign(global_step, global_step + 1)

    return Model(
        predict_real=predict_real,
        predict_fake=predict_fake,
        discrim_loss=ema.average(discrim_loss),
        discrim_grads_and_vars=discrim_grads_and_vars,
        gen_loss_GAN=ema.average(gen_loss_GAN),
        gen_loss_L1=ema.average(gen_loss_L1),
        gen_grads_and_vars=gen_grads_and_vars,
        outputs=outputs,
        train=tf.group(update_losses, incr_global_step, gen_train),
    )


import os
import shutil
import argparse
import time
import logging
from pathlib import Path
import sys

LOG_FILE_PATH = './logs/synch.log'

def _get_logger():

    logger = logging.getLogger('synch folder')
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    stdout_handler.setFormatter(formatter)

    file_handler = logging.FileHandler(LOG_FILE_PATH)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)
    logger.addHandler(stdout_handler)
    return logger

LOGGER = _get_logger() # TO TEST

def sync_copy(source_path, replica_path, test_mode=False):
    if not os.path.exists(replica_path):
        os.makedirs(replica_path)

    for root, _, files in os.walk(source_path):
        replica_root = root.replace(source_path, replica_path, 1)
        if not os.path.exists(replica_root):
            os.makedirs(replica_root)
        for file in files:
            source_file = os.path.join(root, file)
            replica_file = os.path.join(replica_root, file)
            if os.path.exists(replica_file):
                if os.path.samefile(source_file, replica_file):
                    continue
                os.remove(replica_file)
            shutil.copy2(source_file, replica_root)
            if not test_mode:
                LOGGER.info(f"Copied {source_file} to {replica_file}")

def sync_remove(source_path, replica_path, test_mode=False):

    for root, _, files in os.walk(replica_path):
        source_root = root.replace(replica_path, source_path, 1)
        for file in files:
            replica_file = os.path.join(root, file)
            source_file = os.path.join(source_root, file)
            if not os.path.exists(source_file):
                os.remove(replica_file)
                if not test_mode:
                    LOGGER.info(f"Removed {replica_file}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Sync two folders.')
    parser.add_argument('--source_path', type=str, default='./source_folder', help='Path of source folder.')
    parser.add_argument('--replica_path', type=str, default='./replica_folder', help='Path of replica folder.')
    parser.add_argument('--log_path', type=str, default='./logs/synch.log', help='Path of replica folder.')
    parser.add_argument('--period', type=int, default=10, help='Sync period in seconds.')
    args = parser.parse_args()
    if args.log_path:
            LOG_FILE_PATH = args.log_path
            LOGGER = _get_logger()
    while True:

        sync_copy(args.source_path, args.replica_path)
        sync_remove(args.source_path, args.replica_path)
        time.sleep(args.period)


"""
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false.
He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).

You are given a string answerKey, where answerKey[i] is the original answer to the ith question.
In addition, you are given an integer k, the maximum number of times you may perform the following operation:

    Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').

Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.

Example 1:

Input: answerKey = "TTFF", k = 2
Output: 4
Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".
There are four consecutive 'T's.

Example 2:

Input: answerKey = "TFFT", k = 1
Output: 3
Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".
Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".
In both cases, there are three consecutive 'F's.

Example 3:

Input: answerKey = "TTFTTFTT", k = 1
Output: 5
Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"
Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT".
In both cases, there are five consecutive 'T's.

Constraints:

    n == answerKey.length
    1 <= n <= 5 * 104
    answerKey[i] is either 'T' or 'F'
    1 <= k <= n
"""
import sys, collections
###############################################################
def maxConsecutiveAnswers(answerKey: str, k: int) -> int:
  options = ["T", "F"]
  res = []

  for op in options:
    windowStart = 0
    curLen, maxLen = 0, -sys.maxsize
    curK = 0
    for windowEnd in range(len(answerKey)):
        if answerKey[windowEnd] == op:
          curLen += 1
        else:
          curLen += 1
          curK += 1

        while curK > k:

          if answerKey[windowStart] != op:
            curK -= 1
          windowStart += 1
          curLen -= 1
        maxLen = max(maxLen, curLen)
    res.append(maxLen)
  return max(res)

###############################################################
def maxConsecutiveAnswers2(answerKey: str, k: int) -> int:
  max_size = k
  count = collections.Counter(answerKey[:k])

  windowStart = 0
  for windowEnd in range(k, len(answerKey)):
    count[answerKey[windowEnd]] += 1

    while min(count["T"], count["F"]) > k:
      count[answerKey[windowStart]] -= 1
      windowStart += 1

    max_size = max(max_size, windowEnd - windowStart + 1)

  return max_size

###############################################################
def maxConsecutiveAnswers3(answerKey: str, k: int) -> int:
  n = len(answerKey)
  left, right = k, n

  def isValid(size):
    counter = collections.Counter(answerKey[:size])
    if min(counter["T"], counter["F"]) <= k:
      return True
    for i in range(size, n):
      counter[answerKey[i]] += 1
      counter[answerKey[i - size]] -= 1
      if min(counter["T"], counter["F"]) <= k:
        return True
    return False

  while left < right:
    mid = (left + right + 1) // 2

    if isValid(mid):
      left = mid
    else:
      right = mid - 1

  return left

###############################################################
answerKey1 = "TTFF"       # Output: 4
k1 = 2
answerKey3 = "TFFT"       # Output: 3
k2 = 1
answerKey2 = "TTFTTFTT"   # Output: 5
k3 = 1

print("Result 1:")
print(maxConsecutiveAnswers(answerKey1, k1))
print(maxConsecutiveAnswers(answerKey2, k2))
print(maxConsecutiveAnswers(answerKey3, k3))
print("Result 2:")
print(maxConsecutiveAnswers2(answerKey1, k1))
print(maxConsecutiveAnswers2(answerKey2, k2))
print(maxConsecutiveAnswers2(answerKey3, k3))
print("Result 3:")
print(maxConsecutiveAnswers3(answerKey1, k1))
print(maxConsecutiveAnswers3(answerKey2, k2))
print(maxConsecutiveAnswers3(answerKey3, k3))


titleScreenLayout1 = [
  "                                              ",
  "                                              ",
  "                 MAZE MASSACRE                ",
  "        Copyright © Z&S Productions 2020      ",
  "                                              ",
  "                   NEW SAVE   ◄               ",
  "                  LOAD  SAVE                  ",
  "                                              ",
]
titleScreenLayout2 = [
  "                                              ",
  "                                              ",
  "                 MAZE MASSACRE                ",
  "        Copyright © Z&S Productions 2020      ",
  "                                              ",
  "                   NEW SAVE                   ",
  "                  LOAD  SAVE  ◄               ",
  "                                              ",
]
def printTitleScreen(position):
  from Maingame import stdscr
  from Maingame import curses
  from Maingame import nextLine
  curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
  if position == 1:
    for lineno, line in enumerate(titleScreenLayout1):
     stdscr.addstr (titleScreenLayout1[lineno], curses.color_pair(1))
     nextLine()
  elif position == 2:
    for lineno, line in enumerate(titleScreenLayout2):
     stdscr.addstr (titleScreenLayout2[lineno], curses.color_pair(1))
     nextLine()

def saveScreen():
  from Maingame import stdscr
  from Maingame import curses
  curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
  stdscr.addstr ("saving... Wait 10 seconds before closing ", curses.color_pair(1))


from model.group import Group

def test_delete_first_group(app):
    # группа добавляется на случай если нет ни одной группы
    if app.group.count() == 0:
        app.group.create(Group(name="group4", header="header4", footer="footer4"))
    app.group.delete_first_group()

def test_delete_all_groups(app):
    # группа добавляется на случай если нет ни одной группы
    if app.group.count() < 2:
        app.group.create(Group(name="group5", header="header5", footer="footer5"))
        app.group.create(Group(name="group6", header="header6", footer="footer6"))
    app.group.delete_all_groups()


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

import urllib.request
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
driver = webdriver.Chrome(chrome_options=chrome_options) # 打开浏览器
driver.get("http://www.pbc.gov.cn/zhengcehuobisi/125207/125213/125431/125475/17081/index1.html") #用webdriver打开人行政策货币司
source = driver.page_source #获取网页源代码 str
driver.close()  #回收资源

# pat_str = "/zhengcehuobisi/125207/125213/125431/125475/[0-9]+/[index[1-9]+.html|index.html]"
pat_str = 'totalpage="...'
linklist = re.compile(pat_str).findall(source)

# for link in linklist:
#     print(link)
#
# url = "http://www.pbc.gov.cn/zhengcehuobisi/125207/125213/125431/125475/index.html"
#
# req = urllib.request.Request(url)
#
# data = str(urllib.request.urlopen(req).read(),encoding="utf-8")
#
# pat = "/zhengcehuobisi/125207/125213/125431/125475/[0-9]+/[index.html]"
#
# ##### 测试用
# string = "/zhengcehuobisi/125207/125213/125431/125475/3844768/index.html"
# result = re.match(pat,string)
# print(result)
# ######
#
# # result = re.compile(pat).findall(data)
# # print(result)

# def getlink(url_str,pat_str):
#     #模拟成浏览器
#     headers = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")
#     opener = urllib.request.build_opener()
#     opener.addheaders = [headers]
#     #将opener安装为全局
#     urllib.request.install_opener(opener)
#     data = str(urllib.request.urlopen(url_str).read(), encoding="utf-8")
#     link = re.compile(pat_str).findall(data)
#     link = list(set(link))
#     return link
#
# url_str = "http://www.pbc.gov.cn/zhengcehuobisi/125207/125213/125431/125475/index.html"
# pat_str = "/zhengcehuobisi/125207/125213/125431/125475/[0-9]+/[index.html]"
#
# linklist = getlink(url_str, pat_str)
#
# print(linklist)


from bin.service import Environment
from bin.service import Logger
from bin.service import CardTransfer
from pymongo import MongoClient
import urllib.request
import json
import time

class Gitlab:

    def __init__(self):
        self.environment = Environment.Environment()
        self.mongo = MongoClient(self.environment.get_endpoint_mongo_db_cloud())
        self.logger = Logger.Logger()
        self.card_transfer = CardTransfer.CardTransfer()

    def sync_commits(self, wait):
        private_token = self.environment.get_endpoint_git_private_token()
        url = self.environment.get_endpoint_git_projects()
        git_ids = []
        cached_total = 0
        page = 0
        run = True
        while run:
            page += 1
            parsed_url = url.format(private_token, page)
            projects = self.git_request(parsed_url)
            if len(projects) > 0:
                for project in projects:
                    start = float(time.time())
                    commits = {}
                    try:
                        project_commits = self.get_project_commits(project['id'])
                    except Exception as err:
                        self.logger.add_entry(self.__class__.__name__, str(err) + "; with space " + project['id'])
                        project_commits = []
                    for project_commit in project_commits:
                        exists = self.commit_exists(project_commit['id'])
                        if exists is True:
                            continue
                        commit = {
                            'id': project_commit['id'],
                            'title': project_commit['title'],
                            'body': project_commit['message'],
                            'created': project_commit['authored_date'],
                            'project': project['id']
                        }
                        git_ids.append(project_commit['id'])
                        commits[project_commit['id']] = commit
                    self.store_commits(commits)
                    cached_current = len(commits)
                    cached_total += cached_current
                    stop = float(time.time())
                    seconds = (stop - start)
                    print('>>> cached {} gitlab entries of {} entries total after {} seconds'.format(cached_current, cached_total, seconds))
                    time.sleep(wait)
            else:
                run = False
        self.transfer_entries(git_ids)

    def transfer_entries(self, git_ids=None):
        cached_commits = self.load_cached_commits(git_ids)
        created_card_ids = self.card_transfer.transfer_git(cached_commits)
        created_current = len(created_card_ids)
        print('>>> gitlab synchronization completed, {} new cards created'.format(created_current))

    def commit_exists(self, git_id):
        phoenix = self.mongo.phoenix
        gitlab_storage = phoenix.gitlab_storage
        commit = gitlab_storage.find_one({'id': git_id})
        return commit is not None

    def get_project_commits(self, project_id):
        private_token = self.environment.get_endpoint_git_private_token()
        url = self.environment.get_endpoint_git_commits()

        commits = []
        page = 0
        run = True
        while run:
            page += 1
            parsed_url = url.format(project_id, private_token, page)
            project_commits = self.git_request(parsed_url)
            if len(project_commits) > 0:
                for project_commit in project_commits:
                    commits.append(project_commit)
            else:
                run = False

        return commits

    @staticmethod
    def git_request(url):
        f = urllib.request.urlopen(url)
        json_raw = f.read().decode('utf-8')
        return json.loads(json_raw)

    def load_cached_commits(self, git_ids=None):
        phoenix = self.mongo.phoenix
        gitlab_storage = phoenix.gitlab_storage
        if git_ids is None:
            return gitlab_storage.find()
        else:
            return gitlab_storage.find({'id': {'$in': git_ids}})

    def store_commits(self, commits):
        phoenix = self.mongo.phoenix
        gitlab_storage = phoenix.gitlab_storage
        for commit_id in commits:
            stored_commit = gitlab_storage.find_one({'id': commit_id})
            if stored_commit is not None:
                gitlab_storage.replace_one({'id': commit_id}, commits[commit_id])
            else:
                gitlab_storage.insert_one(commits[commit_id])


import argparse
import json
import os
import re

from wedc.domain.core.data import loader

WEBPAGE_SOURCE = '_source'  # list
WEBPAGE_NAME = 'name'   # list
WEBPAGE_URI = 'uri' # string
WEBPAGE_DESC = 'description'    # string

def generate_jsonlines(input, output):
    import jsonlines

    pn_file = open(input, 'rU')
    raw = json.load(pn_file)
    pn_file.close()
    hits = raw['hits']['hits']

    obj = jsonlines.open(output, mode='w')
    for hit in hits:
        source = hit[WEBPAGE_SOURCE]
        obj.dump(source)

if __name__ == '__main__':

    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("-i","--input",help = "input file path",required=True)
    arg_parser.add_argument("-o","--output",help = "output file path",required=True)
    args = arg_parser.parse_args()

    generate_jsonlines(input, output)


import rsa
import hashlib
from Crypto.Signature.pkcs1_15 import PKCS115_SigScheme
from Crypto.Hash import BLAKE2b

class Asymetric_Crypto:

    def __init__(self, content: str, public_key: str, crypto_algorithm: str):
        self.content = content.encode("utf-8")
        self.crypto_algorithm = crypto_algorithm
        self.public_key = public_key

    def get_signature(self, private_key):
        signer = PKCS115_SigScheme(private_key)
        return signer.sign(self.content)

    def get_content(self):
        return self.content.decode("utf-8")

    def encrypt(self):
        try:
            hash = BLAKE2b.new()
            hash.update(self.content)
            self.content = hash
        except Exception as exception:
            print(exception)

    def decrypt(self, private_key):
        try:
            self.content = rsa.decrypt(self.content, private_key)
        except Exception as exception:
            print(exception)
            return False

    def verify_signature(self, private_key):
        try:
            check = PKCS115_SigScheme(private_key).verify(self.content, self.get_signature(private_key))
            return check
        except Exception as exception:
            print(exception)
            return False


'''
@Descripttion: 多源D点
@Author: daxiong
@Date: 2019-08-27 20:37:40
@LastEditors: daxiong
@LastEditTime: 2019-09-06 14:28:54
'''
T = input().strip().split(' ')
n, m, d = int(T[0]), int(T[1]), int(T[2])
T = input().strip()
limited = [int(x) for x in T.split(' ')]
T = input().strip()
temp = [int(x) for x in T.split(' ')]
n, m, d = 6, 2, 3
limited = [1, 2]
temp = [3, 4, 5, 6, 1]

res = list()
res.append(2)
while len(res) < n:
    x = res[-1]
    res.append(temp[x - 2])

for i in range(m):
    limited[i] = res.index(limited[i]) + 1

limited.sort()
if m == 1:
    print(min(2*d + 1, n))
if m >= 2:
    dis = limited[-1] - limited[0]
    if dis > 2 * d:
        print(0)
    else:
        print(min(2*d - dis + 1, n))
# 6 2 3
# 2 1
# 3 4 5 6 1


from django.shortcuts import render, redirect
from .models import Venta
from .forms import VentaForm
from productos.models import Producto

# Create your views here.

def ventas(request):
    ventas = Venta.objects.all()
    context = {"ventas": ventas}
    return render(request, "ventas/ventas.html", context)

def createVenta(request):
    form = VentaForm()
    if request.method == "POST":
        form = VentaForm(request.POST)
        pk = form["producto"].value()
        cantidad_vendida = int(form["cantidad_vendida"].value())
        cantidad_stock = Producto.objects.get(pk=pk).cantidad_stock
        a = Producto.objects.get(pk=pk)

        a.cantidad_stock = cantidad_stock - cantidad_vendida
        a.save()

    if form.is_valid():
        form.save()
        return redirect("/ventas")
    context = {
        "form": form,
    }
    return render(request, "ventas/ventas_form.html", context)


from flask import Flask, flash, redirect, render_template, request, session, url_for, send_file, jsonify, make_response
from flask_session import Session
from tempfile import mkdtemp
from bokeh.embed import components
from bokeh.plotting import figure, output_file, save
from graphIt import get_CGPA
from SGPA import get_SGPA
from subject import get_subject
import numpy as np
import json
from forms import FirstForm

app = Flask(__name__)

def apology(message, code=400):
	"""Render message as an apology to user."""
	def escape(s):
		"""
		Escape special characters.

		https://github.com/jacebrowning/memegen#special-characters
		"""
		for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
						 ("%", "~p"), ("#", "~h"), ("/", "~s"), ("\"", "''")]:
			s = s.replace(old, new)
		return s
	return render_template("apology.html", top=code, bottom=escape(message)), code

def getSGPA_allBranch(year = 16):
	val = get_SGPA(year)
	scripts = []
	divs = []
	k = 0
	for value in val:
		if k == len(val)-3:
			break
		p = figure(plot_width=400, plot_height=400, sizing_mode='scale_width')
		#p.y_range.end=60
		p.xaxis.axis_label='Semester '+str(int(k+1))
		temp_SGPA=[]
		temp_roll=[]
		temp_name=[]
		for idx,i in enumerate(val[len(val)-2]):
			temp_SGPA.append(value[idx])
			temp_roll.append(val[len(val)-2][idx])
			temp_name.append(val[len(val)-1][idx])
		if not temp_SGPA or len(temp_SGPA)==0:
			values = []
			return values, val
		m=max(temp_SGPA)
		t=[i for i, j in enumerate(temp_SGPA) if j == m]
		l=[i for i in range(0,len(temp_SGPA))]
		hist, edges = np.histogram(temp_SGPA, density=True, bins=10, weights=l)
		hist=[int(i*100) for i in hist]
		p.quad(top=hist, bottom=0,
			   left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649")
		script, div = components(p)
		scripts.append(script)
		divs.append(div)
		k=k+1
	values = list(zip(scripts, divs))
	return values, val

def getCGPA_allBranch(year=16):
	val = get_CGPA(year)
	scripts = []
	divs = []
	k = 0
	for value in val:
		if k == len(val)-3:
			break
		p = figure(plot_width=400, plot_height=400, sizing_mode='scale_width')
		#p.y_range.end=60
		p.xaxis.axis_label='Semester '+str(int(k+1))
		temp_CGPA=[]
		temp_roll=[]
		temp_name=[]
		highs=[]
		for idx,i in enumerate(val[len(val)-2]):
			temp_CGPA.append(value[idx])
			temp_roll.append(val[len(val)-2][idx])
			temp_name.append(val[len(val)-1][idx])
		if not temp_CGPA or len(temp_CGPA)==0:
			values = []
			return values, val
		m=max(temp_CGPA)
		t=[i for i, j in enumerate(temp_CGPA) if j == m]
		for x in t:
			highs.append((temp_name[x],temp_roll[x],temp_CGPA[x]))
		l=[i for i in range(0,len(temp_CGPA))]
		hist, edges = np.histogram(temp_CGPA, density=True, bins=10, weights=l)
		hist=[int(i*100) for i in hist]
		p.quad(top=hist, bottom=0,
			   left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649")
		script, div = components(p)
		scripts.append(script)
		divs.append(div)
		k=k+1
	values = list(zip(scripts, divs))
	return values, val, highs

def getCGPA_branchwiseValues(year=16, branch = "EC"):
	val=get_CGPA(year)
	scripts=[]
	divs=[]
	k=0
	highs=[]
	print(len(val))
	for value in val:
		if k==len(val)-3:
			break
		p=figure(plot_width=400,plot_height=400,sizing_mode='scale_width')
		p.xaxis.axis_label='Semester '+str(k+1)
		temp_CGPA=[]
		temp_roll=[]
		temp_name=[]
		for idx,i in enumerate(val[len(val)-2]):
			if i[2:4]==branch:
				temp_CGPA.append(value[idx])
				temp_roll.append(val[len(val)-2][idx])
				temp_name.append(val[len(val)-1][idx])
		if not temp_CGPA or len(temp_CGPA)==0:
			values = []
			highs=[]
			return values, highs
		m=max(temp_CGPA)
		t=[i for i, j in enumerate(temp_CGPA) if j == m]
		for v in t:
			highs.append("Semester "+str(k+1)+": "+temp_name[v]+","+temp_roll[v]+","+str(temp_CGPA[v]))
		l=[i for i in range(0,len(temp_CGPA))]
		hist, edges = np.histogram(temp_CGPA, density=True, bins=10, weights=l)
		hist=[int(i*100) for i in hist]
		p.quad(top=hist, bottom=0,
			   left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649")
		script, div = components(p)
		scripts.append(script)
		divs.append(div)
		k=k+1
	values = list(zip(scripts, divs))
	return values, highs

def getSGPA_branchwiseValues(year=16, branch="EC"):
	val=get_SGPA(year)
	scripts=[]
	divs=[]
	k=0
	highs=[]
	for value in val:
		if k==len(val)-3:
			break
		p=figure(plot_width=400,plot_height=400,sizing_mode='scale_width')
		p.xaxis.axis_label='Semester '+str(k+1)
		temp_SGPA=[]
		temp_roll=[]
		temp_name=[]
		for idx,i in enumerate(val[len(val)-2]):
			if i[2:4]==branch:
				temp_SGPA.append(value[idx])
				temp_roll.append(val[len(val)-2][idx])
				temp_name.append(val[len(val)-1][idx])
		if not temp_SGPA or len(temp_SGPA)==0:
			values = []
			highs=[]
			return values, highs
		m=max(temp_SGPA)
		t=[i for i, j in enumerate(temp_SGPA) if j == m]
		for v in t:
			highs.append("Semester "+str(k+1)+": "+temp_name[v]+","+temp_roll[v]+","+str(temp_SGPA[v]))
		l=[i for i in range(0,len(temp_SGPA))]
		hist, edges = np.histogram(temp_SGPA, density=True, bins=10, weights=l)
		hist=[int(i*100) for i in hist]
		p.quad(top=hist, bottom=0,
			   left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649")
		script, div = components(p)
		scripts.append(script)
		divs.append(div)
		k=k+1
	values = list(zip(scripts, divs))
	return values, highs

# Ensure responses aren't cached
@app.after_request
def after_request(response):
	response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
	response.headers["Expires"] = 0
	response.headers["Pragma"] = "no-cache"
	return response

app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['SECRET_KEY'] = 'you-will-never-guess'
Session(app)

with open('subject_list.json') as f:
	text=f.read()
	r=json.loads(text)
suggestions=r["values"]

@app.route("/", methods=['GET', 'POST'])
def index():
	form = FirstForm()
	if request.method == 'POST':
		if form.validate() == False:
			flash('All fields are necessary')
			return render_template('firstform.html', form=form)
		else:
			yearentry = form.year.data
			branchentry = form.branch.data
			formatentry = form.format.data
			if yearentry == "14" and branchentry =="EC":
				print("ECE 14");
				flash('ECE branch does not exist in year 14')
				return render_template('firstform.html',form = form)
			elif branchentry == "ALL":
				if formatentry == "C":
					values,val,highs = getCGPA_allBranch(yearentry)
					flash (' '.join(val[len(val)-3]))
					return render_template("cgpa.html", values=values)
				else:
					values,val = getSGPA_allBranch(yearentry)
					flash (' '.join(val[len(val)-3]))
					return render_template("sgpa.html",values=values)
			else:
				if formatentry == "S":
					values, highs = getSGPA_branchwiseValues(yearentry,branchentry)
					if not values or not highs:
						flash('Could not find any entry that met your specification')
						return render_template("sgpa.html", values=values)
					flash (' '.join(highs))
					return render_template("sgpa.html", values=values)
				else:
					values, highs = getCGPA_branchwiseValues(yearentry, branchentry)
					if not values or not highs:
						flash('Could not find any entry that met your specification')
						return render_template("cgpa.html", values=values)
					flash (' '.join(highs))
					return render_template("cgpa.html", values=values)
	elif request.method == 'GET':
		return render_template('firstform.html', form = form)

@app.route("/cgpa/branch",methods=["GET"])
def cgpa_branchwise(year=16, branch="EC"):
	if request.args.get('year'):
		year=request.args.get('year')
	if request.args.get('branch'):
		branch=request.args.get('branch')
	if int(year) not in [14,16,17]:
		return apology("Sorry, no data for that year");
	values, highs = getCGPA_branchwiseValues(year, branch)
	flash (' '.join(highs))
	return render_template("cgpa.html", values=values)

@app.route("/cgpa",methods=["GET"])
def cgpa_dist():
	year=16
	if request.args.get('year'):
		year=request.args.get('year')
	if int(year) not in [14,16,17]:
		return apology("Sorry, no data for that year");
	values,val,highs = getCGPA_allBranch(year)
	flash (' '.join(val[len(val)-3]))
	return render_template("cgpa.html", values=values)

@app.route("/sgpa",methods=["GET"])
def sgpa_dist():
	year=16
	if request.args.get('year'):
		year=request.args.get('year')
	if int(year) not in [14,16,17]:
		return apology("Sorry, no data for that year");
	values,val = getSGPA_allBranch(year)
	flash (' '.join(val[len(val)-3]))
	return render_template("sgpa.html", values=values)

@app.route("/sgpa/branch",methods=["GET"])
def sgpa_branchwise(year=16, branch="EC"):
	if request.args.get('year'):
		year=request.args.get('year')
	if request.args.get('branch'):
		branch=request.args.get('branch')
	if int(year) not in [14,16,17]:
		return apology("Sorry, no data for that year");
	values,highs = getSGPA_branchwiseValues(year,branch)
	flash (' '.join(highs))
	return render_template("sgpa.html", values=values)

@app.route("/subject",methods=["GET","POST"])
def subject():
	"""TODO: Implement error checking, display suitable messages if:
	a)Some argument is missing in the get request
	b)Invalid subcode"""
	sub="ID1T001"
	if request.method=="GET":
		if request.args.get("sub"):
			sub=request.args.get("sub")
	elif request.method=="POST":
		if not request.form.get("names"):
			return apology("Sorry, must provide subcode")
		sub=request.form.get("names").split("-")[0]
	scripts=[]
	divs=[]
	x=get_subject(sub)
	for key,value in x.items():
		p=figure(plot_width=400,plot_height=400,sizing_mode='scale_width')
		p.xaxis.axis_label='Batch '+str(key)
		l=[i for i in range(0,len(value))]
		#p.line(l,value,line_width=2)
		hist, edges = np.histogram(value, density=True, bins=10, weights=l)
		p.quad(top=hist, bottom=0,
			   left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649")
		script, div = components(p)
		scripts.append(script)
		divs.append(div)
	values = list(zip(scripts, divs))
	#r = make_response(render_template('subject.html',values=values))
	#print(r.data)
	return render_template('subject.html',values=values)

@app.route("/<string:box>")
def process(box):
	query = request.args.get('query')
	if query is not None:
		query=query.lower()
		print(query)
		global suggestions
		#suggestions = [{'label': 'mathematics first_year maths','value': 'MA1L001-Mathematics 1'}, {'label': 'jim','value': 'jim'}]
		'''TODO: Add keywords in label to describe the subject and set value to subject code
		by replacing the second entry with something like first entry.
		Link this field to subject table so that user can click to go to that page
		Also maybe add subject name with suitable delimiter (say: MA1L001-Mathematics 1)
		and parse it in File side. Currently delimiter is -'''
		temp=[]
		for val in suggestions:
			#print(val)
			k=val['label'].split(' ')
			for i in k:
				print(i)
				if i.lower().startswith(query):
					temp.append(val)
					break
		k=temp
		return jsonify({"suggestions":k})
	else:
		return jsonify({"suggestions":[{}]})


# Given an integer array nums, find the contiguous subarray
# (containing at least one number)
# which has the largest sum and return its sum.
# A subarray is a contiguous part of an array.
from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        sums = []
        tmp_sum = 0
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                sums.append(tmp_sum)
                tmp_sum = 0
                continue
            else:
                tmp_sum += nums[i]
        return max(sums)

s = Solution()
print(s.maxSubArray([-2, 3, 4, 5]))
print(s.maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))