import random
from flask import request, redirect, Flask, render_template
import time
app = Flask(__name__)

card_group = ["spade", "plum", "square", "heart"]
card_number = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "K", "Q"]
cards = []
for g in card_group:
    for n in card_number:
        cards.append(g + "_" + n)

def new_card():
    rtn = []
    for card in cards:
        rtn.append(card)
    return rtn

class Player:
    def __init__(self, name):
        self.name = name
        self.card = []
        self.credit = 0
        self.balance = 2720
        self.current_bet = 0
        self.is_discard = False
        self.show_card = False
        self.last_ping = time.time()

    def win(self, money):
        self.balance += (self.current_bet + money)
        self.current_bet = 0

    def lose(self):
        self.current_bet = 0

    def add_bet(self, addition):
        self.current_bet += addition
        self.balance -= addition

    def show_now(self):
        self.show_card = True

    def reset_state(self):
        self.is_discard = False
        self.show_card = False

    def discard(self):
        self.is_discard = True

    def reset(self):
        self.credit += (self.balance - 2720)
        self.balance = 2720

START = "进行中"
END = "结束"

class Game:
    def __init__(self):
        self.players = []
        self.showing_cards = []
        self.state = END
        self.code = "hdnb"
        self.card_pool = []
        self.hash = time.time()

    def join(self, name, code):
        print(self.hash)
        if self.state == START:
            return {"success": False, "msg": "当前正在进行中，请稍后加入"}
        if self.code != code:
            return {"success": False, "msg": "邀请码错误"}
        for player in self.players:
            if player.name == name:
                return {"success": True, "msg": "欢迎回来"}
        self.players.append(Player(name))
        return {"success": True, "msg": "欢迎加入"}

    def remove_player(self, name):
        new_list = []
        for player in self.players:
            if player.name != name:
                new_list.append(player)
        self.players = new_list

    def ping(self, name):
        now = time.time()
        in_list = False
        for player in self.players:
            # if now - player.last_ping > 10:
            #     self.remove_player(player.name)
            if player.name == name:
                in_list = True
                player.last_ping = now
        if not in_list:
            return {"success": False}
        return {"success": True}

    def get_player(self, name):
        for player in self.players:
            if player.name == name:
                return player
        return None

    def add_bet(self, name, addition):
        addition = int(addition)
        p = self.get_player(name)
        if p.balance < addition:
            return {"success": False, "msg": "当前筹码不足"}
        p.add_bet(addition)
        return {"success": True, "msg": "加注成功"}

    def _pop_card(self):
        n = random.randint(0, len(self.card_pool) - 1)
        card = self.card_pool[n]
        self.card_pool.remove(card)
        return card

    def start(self):
        self.card_pool = new_card()
        self.state = START
        for p in self.players:
            p.reset_state()
            c1 = self._pop_card()
            c2 = self._pop_card()
            p.card = [c1, c2]
        self.showing_cards = []

    def next_card(self):
        if len(self.showing_cards) == 0:
            c1 = self._pop_card()
            c2 = self._pop_card()
            c3 = self._pop_card()
            self.showing_cards = [c1, c2, c3]
        elif len(self.showing_cards) < 5:
            self.showing_cards.append(self._pop_card())

    def reset(self):
        for p in self.players:
            p.reset()

class ChatRoom:
    def __init__(self):
        self.last_message = ""
        self.message_cache = []
        self.cnt = 0

    def _add_message(self, content):
        self.cnt += 1

    def send(self, content):
        pass

game = Game()

@app.route('/')
def index():
    name = request.args.get("username")
    if name is None:
        return redirect("/login")
    return render_template('index.html')

@app.route("/login")
def login():
    print("?")
    return render_template('login.html')

@app.route("/showing_card")
def showing_card():
    return {"success": True, "card": game.showing_cards}

@app.route("/my_card")
def my_card():
    name = request.args.get("username")
    p = game.get_player(name)
    if p is None:
        return {"success": False}
    return {"success": True, "card": p.card}

@app.route("/player_info")
def player_info():
    rtn = []
    for player in game.players:
        rtn.append({
            "card": player.card if player.show_card else [],
            "name": player.name,
            "credit": player.credit,
            "current_bet": player.current_bet,
            "balance": player.balance,
            "is_discard": player.is_discard
        })
    return {"success": True, "players": rtn}

@app.route("/join")
def join():
    username = request.args.get("username")
    code = request.args.get("code")
    return game.join(username, code)

@app.route("/ping")
def ping():
    username = request.args.get("username")
    return game.ping(username)

@app.route("/discard")
def discard():
    username = request.args.get("username")
    game.get_player(username).discard()
    return {"success": True}

@app.route("/show")
def show():
    username = request.args.get("username")
    game.get_player(username).show_now()
    return {"success": True}

@app.route("/add_bet")
def add_bet():
    username = request.args.get("username")
    add = request.args.get("add")
    return game.add_bet(username, add)

@app.route("/start")
def start():
    game.start()
    return {"success": True}

@app.route("/next")
def next():
    game.next_card()
    return {"success": True}

@app.route("/end")
def end():
    winnerRaw = request.args.get("winner")
    ps = winnerRaw.split(",")
    if len(ps) == 0 or winnerRaw == '':
        return {"success": False, "msg": "必须选择至少一个赢家"}

    pool_balance = 0
    for p in game.players:
        is_winner = False
        for name in ps:
            if p.name == name:
                is_winner = True
                break
        if not is_winner:
            pool_balance += p.current_bet
            p.lose()

    for name in ps:
        p = game.get_player(name)
        p.win(pool_balance / len(ps))
    game.state = END
    print(game.hash)
    return {"success": True}

@app.route("/reset")
def reset():
    game.reset()
    return {"success": True}

@app.route("/game_state")
def game_state():
    return {"success": True, "state": game.state}

@app.route("/remove")
def remove():
    username = request.args.get("username")
    game.remove_player(username)
    return {"success": True}


struct_dict = dict()
current_struct = ""
acc = 0
reg_list2 = []

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False

def pstruct(A):
    global current_struct
    struct_dict[A] = (A, 0, [])
    current_struct = A
    wr("// {A}'s structure")
    acc = 0

def e(A, T="", comment=""):
    global current_struct
    if len(comment) > 3:
        comment = comment[2:]
    T = int(T) if T != "" else 1
    struct_dict[current_struct][2].append((A, T, comment))
    wr("//   {current_struct}_{A} - {T} {comment}")
    acc += T

def endpstruct():
    global current_struct
    nameu = current_struct.upper()
    rep[current_struct] = inter("[{nameu}_W-1:0]")

def defparam_pstruct(A):
    cur = struct_dict[A][0]
    len = struct_dict[A][1]
    wr("parameter {cur}_W = {len};")

def decompose(A, B, comment=""):
    construct(A, B)
    l = comp(A, B)
    wr("assign {l} = {B};{comment}")

def construct(A, B):
    (cur, len, L) = struct_dict[A]
    for entry in L:
        (N, T, _) = entry
        u = T - 1
        if N in reg_list2:
            wr("reg [{u}:0] {B}_{N};")
        wr("wire [{u}:0] {B}_{N};")

def comp(A, B):
    l = ""
    (cur, len, L) = struct_dict[A]
    for entry in L:
        (N, T, _) = entry
        l += " {B}_{N},"
    l = "{" + l[:-1] + "}"
    return l

def compose_always(A, B):
    l = comp(A, B)
    wr("{B} = {l}")

def compose_assign(A, B):
    l = comp(A, B)
    wr("assign {B} = {l}")

def pr_entry(entry, V, end=","):
    (N, T, _) = entry
    if N in V:
        if is_number(V[N]):
            wr("\t{T}'h" + hex(int(V[N]))[2:] + "{end} // {N}")
        else:
            wr("\t" + V[N] + "{end} // {N}")
    else:
        wr("\t {T}'" + 'x'*T + "{end} // {N}")

def pr_entry2(entry, V, end=","):
    (N, T, _) = entry
    if is_number(V):
        wr("\t{T}'h" + hex(int(V))[2:] + "{end} // {N}")
    else:
        wr("\t" + V + "{end} // {N}")

def value(A, B, V):
    (cur, length, L) = struct_dict[A]
    if V == 0:
        wr("{B} = 0")
    elif V == 'x':
        wr("{B} = {length}'" + 'x'*len)
    elif type(V) == dict:
        wr("{B} = {")
        for entry in L:
            pr_entry(entry ,V)
        pr_entry(L[-1] , V, end="")
        wr("}")
    elif type(V) == list:
        wr("{B} = {")
        for entry, v in zip(L,V):
            pr_entry2(entry,v)
        pr_entry2(L[-1],V[-1], end="")
        wr("}")

def value_virtual(A, B, V):
    value(A, comp(A,B), V)


import subprocess

in_code = False
code = []
with open('orb.lpy', 'r') as f:
    for line in f:
        if line.strip()[:3] == '```':
            # Toggle between in and out of code
            in_code = not in_code
            continue

        if in_code:
            code.append(line)

with open('orb.py', 'w') as f:
      f.write(''.join(code))

subprocess.Popen(['python', 'orb.py', 'compile', 'orb.lpy']).wait()


from BlinkyTape import BlinkyTape
import time

import GlobalSettings as G

def sendColorPixel(blinky):
    blinky.sendPixel(G.color[0],G.color[1],G.color[2])

def sendBlackPixel(blinky):
    blinky.sendPixel(0,0,0)

def start(blinky):
    while G.keepGoing is False:
        continue
    while True:
        for i in range(0,150):
            for x in range(0,i):
                sendBlackPixel(blinky)
            sendColorPixel(blinky)
            if i<149:
                for y in range(i+1,150):
                    sendBlackPixel(blinky)
            blinky.show()
            time.sleep(1/float(G.speed))
            if G.keepGoing is False:
                G.keepGoing = True
                return

def startSnake(blinky):
    while G.keepGoing is False:
        continue
    length = 10
    while True:
        leftover = 0
        for i in range(0,150):
            if i+length+1 < 150:
                for x in range(0,i):
                    sendBlackPixel(blinky)
                for x in range(i,i+length+1):
                    sendColorPixel(blinky)
                for x in range(i+length+1,150):
                    sendBlackPixel(blinky)
            else:
                leftover = length-(150-i)
                for x in range(0,leftover+1):
                    sendColorPixel(blinky)
                for x in range(leftover+1,i):
                    sendBlackPixel(blinky)
                for x in range(i,150):
                    sendColorPixel(blinky)
            blinky.show()
            time.sleep(1/float(G.speed))
            if G.keepGoing is False:
                G.keepGoing = True
                return

def outsideIn(blinky):
    while G.keepGoing is False:
        continue
    while True:
        for i in range(0,150):
            if i < 75:
                for x in range(0,i):
                    sendColorPixel(blinky)
                for x in range(i,150-i):
                    sendBlackPixel(blinky)
                for x in range(150-i,150):
                    sendColorPixel(blinky)
            else:
                for x in range(0,i-75):
                    sendBlackPixel(blinky)
                for x in range(i-75,150-(i-75)):
                    sendColorPixel(blinky)
                for x in range(150-(i-75),150):
                    sendBlackPixel(blinky)
            blinky.show()
            time.sleep(1/float(G.speed))
            if G.keepGoing is False:
                G.keepGoing = True
                return


import os
import subprocess

from launcher.commands.build import build

def run(
    init: bool = False,
    repo: str = "origin",
    branch: str = "main",
    do_update: bool = False,
    test: bool = False,
    clear: bool = False,
    update_prod: bool = False,
    production: bool = False,
    skip_services_check: bool = False,  # not used here
):
    """ðŸš€ Launch Icare"""
    skyportal_start = True
    if init or do_update or update_prod:
        skyportal_start = build(
            init=init,
            repo=repo,
            branch=branch,
            do_update=do_update,
            clear=clear,
            update_prod=update_prod,
        )

    # create common docker network (if it does not exist yet)
    if skyportal_start:
        if test:
            cmd = subprocess.Popen(["make", "run_testing"], cwd="patched_skyportal")
            cmd.communicate()
        elif production:
            # we want to run all of the following:
            # export NPM_CONFIG_LEGACY_PEER_DEPS=true && make system_setup && ./node_modules/.bin/webpack --mode=production && make run_production
            # but we need to run them in the patched_skyportal directory
            env = os.environ.copy()
            env["NPM_CONFIG_LEGACY_PEER_DEPS"] = "true"
            cmd = subprocess.Popen(
                ["make", "system_setup"],
                cwd="patched_skyportal",
                env=env,
            )
            cmd.communicate()
            print("\nBuilding webpack, this may take a while...")
            cmd = subprocess.Popen(
                ["./node_modules/.bin/webpack", "--mode=production"],
                cwd="patched_skyportal",
                env=env,
            )
            cmd.communicate()
            cmd = subprocess.Popen(
                ["make", "run_production"],
                cwd="patched_skyportal",
                env=env,
            )
            cmd.communicate()
        else:
            # we just run make run
            env = os.environ.copy()
            env["NPM_CONFIG_LEGACY_PEER_DEPS"] = "true"
            cmd = subprocess.Popen(["make", "run"], cwd="patched_skyportal", env=env)
            cmd.communicate()
    else:
        print("App will not start as the extensions need to be updated")


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

def plot_boundary(classifier, features, targets, title, x1_n_values=100,
                  x2_n_values=100):

    condition = features.shape[1] == 2
    if not condition:
        print(f"__n_features should be 2d to visualize")
        print(f"self.__n_features = {features.shape[1]}")
        return

    fig = plt.figure(figsize=(6, 5))

    left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
    ax = fig.add_axes([left, bottom, width, height])

    scale_factor = 0.25
    x1_start, x1_stop = features['x1'].min(), features['x1'].max()
    x1_start += scale_factor * x1_start
    x1_stop += scale_factor * x1_stop

    x2_start, x2_stop = features['x2'].min(), features['x2'].max()

    x2_start += scale_factor * x2_start
    x2_stop += scale_factor * x2_stop

    x1_vals = np.linspace(x1_start, x1_stop, x1_n_values)
    x2_vals = np.linspace(x2_start, x2_stop, x2_n_values)
    X1, X2 = np.meshgrid(x1_vals, x2_vals)

    m = x1_n_values
    n = x2_n_values
    Z = np.zeros((m, n))

    for i in range(m):
        for j in range(n):
            x = np.array([X1[i, j], X2[i, j]])
            Z[i, j] = classifier.predict(np.array([x]))

    contour = plt.contour(X1, X2, Z, levels=[0])
    # plt.clabel(contour, colors='k', fmt='%2.1f', fontsize=12)

    ax.set_title('Boundary line')
    ax.set_xlabel('X1')
    ax.set_ylabel('X2')

    # add points
    plot_points(features, targets, title + " Descition boundary")
    plt.show()

def plot_points(features, targets, title):
    admitted = features[targets.to_numpy() == 1]
    rejected = features[targets.to_numpy() == -1]

    plt.scatter(admitted['x1'], admitted['x2'],
                s=25, color='cyan', edgecolor='k')
    plt.scatter(rejected['x1'], rejected['x2'],
                s=25, color='red', edgecolor='k')
    plt.xlabel('x1')
    plt.ylabel('x2')
    plt.title(title)


"""
Дано целое число 1≤n≤10^5 и массив A[1…n],
содержащий неотрицательные целые числа, не превосходящие 10^9.
Найдите наибольшую невозрастающую подпоследовательность в A.
В первой строке выведите её длину k, во второй — её индексы
1≤i1<i2<…<ik≤n1≤i1<i2<…<ik≤n
(таким образом, A[i1]≥A[i2]≥…≥A[in]A[i1]≥A[i2]≥…≥A[in]).
"""
# it fucking works!
# O(n log n)
from bisect import bisect_right

def non_increasing_sub(vec):
    # O(n log n) complexity
    # 1 >= 2 >= 3 >= ...
    ancestors = [-1] * len(vec)
    original_numbers = [-1] * len(vec)
    subsequence = [vec[0]]
    original_numbers[0] = 0
    for i, v in enumerate(vec[1:], 1):
        if v >= subsequence[-1]:
            subsequence.append(v)
            original_numbers[len(subsequence)-1] = i
            ancestors[i] = original_numbers[len(subsequence)-2]
        else:
            # bisect_left ?
            pos = bisect_right(subsequence, v)
            subsequence[pos] = v
            original_numbers[pos] = i
            try:
                ancestors[i] = original_numbers[pos-1]
            except IndexError:
                pass
    answer = []
    index = original_numbers[len(subsequence)-1]
    for _ in range(len(subsequence)):
        answer.append(index)
        index = ancestors[index]
    return tuple(reversed(answer))

def main():
    n = int(input())
    # save -x to keep list sorted (we use builtin bisect)
    vec = tuple(map(lambda x: -int(x), input().split()))
    indexes = non_increasing_sub(vec)
    print(len(indexes))
    [print(index+1, end=' ') for index in indexes]

if __name__ == '__main__':
    main()


import argparse
import json
import socket
import time

import settings

def send_data(connection, data):
    js_message = json.dumps(data)
    message = js_message.encode(settings.ENCODING_VAR)
    connection.send(message)

def receive_data(connection):
    """
    receive data from server
    :param
    connection: connection to server
    :return:
    json_data: json
        return json data
    """
    data = connection.recv(settings.MAX_DATA_LENGTH)
    json_data = json.loads(data.decode(settings.ENCODING_VAR))
    return json_data

def create_presence(account_name):
    """
    :param
    account_name: str
        username for presence message
    :return:
    msg: dict
        return presence message
    """
    msg = {
        "action": "presence",
        "time": time.time(),
        "type": "status",
        "user": {"account_name": account_name, "status": "Yep, I am here!"},
    }
    return msg

def process_data(data):
    """
    :param
    data: json
        answer from server
    :return: str
        decode answer from server
    """
    if "response" in data:
        if data["response"] == 200:
            return "200, OK"
        return f"{data['response']}, {data['error']}"
    return "Can't decode server answer"

def get_params():
    """
    return params from console
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(dest="port", type=int, help="Add port please", default=settings.DEFAULT_SERVER_PORT, nargs="?")
    parser.add_argument(dest="server_ip", type=str, help="Add server ip address please")
    args = parser.parse_args()
    if args.port < 1024 or args.port > 65535:
        parser.error("Error starting client. The port must be between 1024 and 65535")

    return args.port, args.server_ip

def main():
    """
    run client with python3 client.py -h
    """
    server_port, server_ip = get_params()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((server_ip, server_port))
        msg = create_presence("Nik")
        send_data(s, msg)
        data = process_data(receive_data(s))
        print(f"Received: {data}")

if __name__ == "__main__":
    main()


from PyQt6.QtWidgets import QPushButton, QComboBox, QMessageBox
from functions.db_Helper import Db_helper

class CustomButtonDell(QPushButton):
    def __init__(self, name, window, text = ''):
        super().__init__(text = text)
        self.window_ = window
        self.helper = Db_helper("Alpha.db")
        self.name = name
        self.clicked.connect(self.func)

    def func(self):
        self.helper.insert(f"""DELETE FROM AddProductTransaction WHERE name_product = '{self.name}'""")
        self.window_.drow_ingridients_transaction()

class CustomButtonAdd(QPushButton):
    def __init__(self, name, count, window, id_menu = None, text = ''):
        super().__init__(text = text)
        self.window_ = window
        self.helper = Db_helper("Alpha.db")
        self.count = count
        self.name = name
        self.id_menu = id_menu
        self.clicked.connect(self.func_add_product)

    def func_add_product(self):
        count = self.count.text()
        if count == "":
            count = 0
        self.helper.insert(f"""INSERT INTO AddProductTransaction (name_product, count) VALUES ('{self.name.custText}', {count})""")
        self.window_.drow_ingridients_transaction()

class CustomComboBox(QComboBox):
    def __init__(self):
        super().__init__()
        self.helper = Db_helper("Alpha.db")
        self.currentTextChanged.connect(self.func)
        self.ingridients = self.helper.get_list("""SELECT name FROM Stock;""")
        self.ingridients_transaction = self.helper.get_list("""SELECT name_product FROM AddProductTransaction;""")

        self.all_ingridients = []
        self.already_ingridients = []

        for i in self.ingridients:
            self.all_ingridients.append(i[0])

        for i in self.ingridients_transaction:
            self.already_ingridients.append(i[0])

        for i in self.all_ingridients:
            if i not in self.already_ingridients:
                self.addItem(i)
        self.custText = self.itemText(0)

    def func(self, e):
        self.custText = e

class CustomButtonDellProduct(QPushButton):
    def __init__(self, menu_id, menu_name, window, central_window, text = ''):
        super().__init__(text = text)
        self.window_ = window
        self.helper = Db_helper("Alpha.db")
        self.menu_id = menu_id
        self.menu_name = menu_name
        self.central_window = central_window
        self.clicked.connect(self.func)

    def func(self):
        msgBox = QMessageBox()
        msgBox.setText(f"Do you want delete product: '{self.menu_name}'?.")
        yes = QMessageBox.StandardButton.Ok
        msgBox.setStandardButtons(yes | QMessageBox.StandardButton.Cancel)
        msgBox.setDefaultButton(QMessageBox.StandardButton.Cancel)
        msgBox.setIcon(QMessageBox.Icon.Question)
        msgBox.setWindowTitle("Delete product")
        result = msgBox.exec()

        if result == yes:
            check_product = self.helper.get_list(f"""SELECT *
                                                    FROM OpenOrderView
                                                    WHERE id_menu = '{self.menu_id}'
                                                    GROUP BY table_id;""")
            if check_product == []:
                self.helper.insert(f"""DELETE FROM Menu WHERE id = '{self.menu_id}'""")
                self.central_window.drowAllwOrders()
            else:
                text = ""
                for i in check_product:
                    text += f"{i[0]}_{i[1]} " + ", "
                msgBox = QMessageBox()
                msgBox.setText(f"You can not delete: '{self.menu_name}' becouse some table/s has this product.")
                msgBox.setDetailedText(text)
                msgBox.exec()

        self.window_.drow_products()
        self.central_window.Main_widget.menuTabWidget.clear()
        self.central_window.Main_widget.menuTabWidget.create_full_menu()


# ----------------------------------------------------------------------------------
# Copyright ENS, INRIA, CNRS
# Contributors: Romain Brette (brette@di.ens.fr) and Dan Goodman (goodman@di.ens.fr)
#
# Brian is a computer program whose purpose is to simulate models
# of biological neural networks.
#
# This software is governed by the CeCILL license under French law and
# abiding by the rules of distribution of free software.  You can  use,
# modify and/ or redistribute the software under the terms of the CeCILL
# license as circulated by CEA, CNRS and INRIA at the following URL
# "http://www.cecill.info".
#
# As a counterpart to the access to the source code and  rights to copy,
# modify and redistribute granted by the license, users are provided only
# with a limited warranty  and the software's author,  the holder of the
# economic rights,  and the successive licensors  have only  limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading,  using,  modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean  that it is complicated to manipulate,  and  that  also
# therefore means  that it is reserved for developers  and  experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards their
# requirements in conditions enabling the security of their systems and/or
# data to be ensured and,  more generally, to use and operate it in the
# same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL license and that you accept its terms.
# ----------------------------------------------------------------------------------
#
'''
Threshold mechanisms
'''

import re
from random import sample # Python standard random module (sample is different)

from numpy import clip, Inf
from numpy.random import rand, randn
try:
    import weave
except ImportError:
    try:
        from scipy import weave
    except ImportError:
        weave = None
from scipy import random

from brian.clock import guess_clock
from brian.globalprefs import get_global_preference
from brian.inspection import namespace, get_identifiers
from brian.log import log_warn
from brian.units import check_units, second, msecond, mvolt
from brian.utils.approximatecomparisons import is_approx_equal

__all__ = ['Threshold', 'FunThreshold', 'VariableThreshold', 'NoThreshold',
          'EmpiricalThreshold', 'SimpleFunThreshold', 'PoissonThreshold',
          'HomogeneousPoissonThreshold', 'StringThreshold']

CThreshold = PythonThreshold = None

def select_threshold(expr, eqs, level=0):
    '''
    Automatically selects the appropriate Threshold object from a string.

    Matches the following patterns:

    var_name > or >= const : Threshold
    var_name > or >= var_name : VariableThreshold
    others : StringThreshold
    '''
    global CThreshold, PythonThreshold
    use_codegen = (get_global_preference('usecodegen') and
                   get_global_preference('usecodegenthreshold'))
    use_weave = (get_global_preference('useweave') and
                 get_global_preference('usecodegenweave'))
    if use_codegen:
        if CThreshold is None:
            from brian.experimental.codegen.threshold import (CThreshold,
                                                              PythonThreshold)
        if use_weave:
            log_warn('brian.threshold', 'Using codegen CThreshold')
            return CThreshold(expr, level=level + 1)
        else:
            log_warn('brian.threshold', 'Using codegen PythonThreshold')
            return PythonThreshold(expr, level=level + 1)
    # plan:
    # - see if it matches A > B or A >= B, if not select StringThreshold
    # - check if A, B both match diffeq variable names, and if so
    #   select VariableThreshold
    # - check that A is a variable name, if not select StringThreshold
    # - extract all the identifiers from B, and if none of them are
    #   callable, assume it is a constant, try to eval it and then use
    #   Threshold. If not, or if eval fails, use StringThreshold.
    # This misses the case of e.g. V>10*mV*exp(1) because exp will be
    # callable, but in general a callable means that it could be
    # non-constant.
    expr = expr.strip()
    eqs.prepare()
    ns = namespace(expr, level=level + 1)
    s = re.search(r'^\s*(\w+)\s*>=?(.+)', expr)
    if not s:
        return StringThreshold(expr, level=level + 1)
    A = s.group(1)
    B = s.group(2).strip()
    if A not in eqs._diffeq_names:
        return StringThreshold(expr, level=level + 1)
    if B in eqs._diffeq_names:
        return VariableThreshold(B, A)
    try:
        vars = get_identifiers(B)
    except SyntaxError:
        return StringThreshold(expr, level=level + 1)
    all_vars = eqs._eq_names + eqs._diffeq_names + eqs._alias.keys() + ['t']
    for v in vars:
        if v not in ns or v in all_vars or callable(ns[v]):
            return StringThreshold(expr, level=level + 1)
    try:
        val = eval(B, ns)
    except:
        return StringThreshold(expr, level=level + 1)
    return Threshold(val, A)

class Threshold(object):
    '''
    All neurons with a specified state variable above a fixed value fire a spike.

    **Initialised as:** ::

        Threshold([threshold=1*mV[,state=0])

    with arguments:

    ``threshold``
        The value above which a neuron will fire.
    ``state``
        The state variable which is checked.

    **Compilation**

    Note that if the global variable ``useweave`` is set to ``True``
    then this function will use a ``C++`` accelerated version which
    runs approximately 3x faster.
    '''

    def __init__(self, threshold=1 * mvolt, state=0):
        self.threshold = threshold
        self.state = state
        self._useaccel = get_global_preference('useweave')
        self._cpp_compiler = get_global_preference('weavecompiler')
        self._extra_compile_args = ['-O3']
        if self._cpp_compiler == 'gcc':
            self._extra_compile_args += get_global_preference('gcc_options') # ['-march=native', '-ffast-math']

    def __call__(self, P):
        '''
        Checks the threshold condition and returns spike times.
        P is the neuron group.

        Note the accelerated version runs 3x faster.
        '''
        if self._useaccel:
            spikes = P._spikesarray
            V = P.state_(self.state)
            Vt = float(self.threshold)
            N = int(len(P))
            code = """
                    int numspikes=0;
                    for(int i=0;i<N;i++)
                        if(V(i)>Vt)
                            spikes(numspikes++) = i;
                    return_val = numspikes;
                    """
            # WEAVE NOTE: set the environment variable USER if your username has a space
            # in it, say set USER=DanGoodman if your username is Dan Goodman, this is
            # because weave uses this to create file names, but doesn't correctly send these
            # values to the compiler, causing problems.
            numspikes = weave.inline(code, ['spikes', 'V', 'Vt', 'N'],
                                     compiler=self._cpp_compiler,
                                     type_converters=weave.converters.blitz,
                                     extra_compile_args=self._extra_compile_args)
            # WEAVE NOTE: setting verbose=True in the weave.inline function may help in
            # finding errors.
            return spikes[0:numspikes]
        else:
            return ((P.state_(self.state) > self.threshold).nonzero())[0]

    def __repr__(self):
        return '%s(threshold=%s, state=%s)' % (self.__class__.__name__,
                                               repr(self.threshold),
                                               repr(self.state))

    def __str__(self):
        return ('Threshold mechanism with value=' + str(self.threshold) +
                ' acting on state ' + str(self.state))

class StringThreshold(Threshold):
    '''
    A threshold specified by a string expression.

    Initialised with arguments:

    ``expr``
        The expression used to test whether a neuron has fired a spike.
        Should be a single statement that returns a value. For example,
        ``'V>50*mV'`` or ``'V>Vt'``.
    ``level``
        How many levels up in the calling sequence to look for
        names in the namespace. Usually 0 for user code.
    '''
    def __init__(self, expr, level=0):
        self._namespace, unknowns = namespace(expr, level=level + 1, return_unknowns=True)
        self._vars = unknowns
        self._expr = expr
        self._code = compile(expr, "StringThreshold", "eval")
        class Replacer(object):
            def __init__(self, func, n):
                self.n = n
                self.func = func
            def __call__(self):
                return self.func(self.n)
        self._Replacer = Replacer

    def __call__(self, P):
        for var in self._vars: # couldn't we do this just once?
            self._namespace[var] = P.state(var)
        self._namespace['rand'] = self._Replacer(rand, len(P))
        self._namespace['randn'] = self._Replacer(randn, len(P))
        return eval(self._code, self._namespace).nonzero()[0]

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, repr(self._expr))

    def __str__(self):
        return '%s using expression "%s"' % (self.__class__.__name__,
                                             str(self._expr))

class NoThreshold(Threshold):
    '''
    No thresholding mechanism.

    **Initialised as:** ::

        NoThreshold()
    '''
    def __init__(self):
        pass

    def __call__(self, P):
        return []

    def __repr__(self):
        return "NoThreshold()"

    def __str__(self):
        return "No threshold"

class FunThreshold(Threshold):
    '''
    Threshold mechanism with a user-specified function.

    **Initialised as:** ::

        FunThreshold(thresholdfun)

    where ``thresholdfun`` is a function with one argument,
    the 2d state value array, where each row is an array of
    values for one state, of length N for N the number of
    neurons in the group. For efficiency, data are numpy
    arrays and there is no unit checking.

    Note: if you only need to consider one state variable,
    use the :class:`SimpleFunThreshold` object instead.
    '''
    def __init__(self, thresholdfun):
        self.thresholdfun = thresholdfun # Threshold function

    def __call__(self, P):
        '''
        Checks the threshold condition and returns spike times.
        P is the neuron group.
        '''
        spikes = (self.thresholdfun(*P._S).nonzero())[0]
        return spikes

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self.thresholdfun)

    def __str__(self):
        return 'Functional threshold mechanism'

class SimpleFunThreshold(FunThreshold):
    '''
    Threshold mechanism with a user-specified function.

    **Initialised as:** ::

        FunThreshold(thresholdfun[,state=0])

    with arguments:

    ``thresholdfun``
        A function with one argument, the array of values for
        the specified state variable. For efficiency, this is
        a numpy array, and there is no unit checking.
    ``state``
        The name or number of the state variable to pass to
        the threshold function.

    **Sample usage:** ::

        FunThreshold(lambda V:V>=Vt,state='V')
    '''
    def __init__(self, thresholdfun, state=0):
        self.thresholdfun = thresholdfun # Threshold function
        self.state = state

    def __call__(self, P):
        '''
        Checks the threshold condition and returns spike times.
        P is the neuron group.
        '''
        spikes = (self.thresholdfun(P.state_(self.state)).nonzero())[0]
        #P.LS[spikes]=P.clock.t # Time of last spike (this line should be general)
        return spikes

class VariableThreshold(Threshold):
    '''
    Threshold mechanism where one state variable is compared to another.

    **Initialised as:** ::

        VariableThreshold([threshold_state=1[,state=0]])

    with arguments:

    ``threshold_state``
        The state holding the lower bound for spiking.
    ``state``
        The state that is checked.

    If ``x`` is the value of state variable ``threshold_state`` on neuron
    ``i`` and ``y`` is the value of state variable ``state`` on neuron
    ``i`` then neuron ``i`` will fire if ``y>x``.

    Typically, using this class is more time efficient than writing
    a custom thresholding operation.

    **Compilation**

    Note that if the global variable ``useweave`` is set to ``True``
    then this function will use a ``C++`` accelerated version.
    '''
    def __init__(self, threshold_state=1, state=0):
        self.threshold_state = threshold_state # State variable representing the threshold
        self.state = state
        self._useaccel = get_global_preference('useweave')
        self._cpp_compiler = get_global_preference('weavecompiler')
        self._extra_compile_args = ['-O3']
        if self._cpp_compiler == 'gcc':
            self._extra_compile_args += get_global_preference('gcc_options') # ['-march=native', '-ffast-math']

    def __call__(self, P):
        '''
        Checks the threshold condition, resets and returns spike times.
        P is the neuron group.
        '''
        if self._useaccel:
            spikes = P._spikesarray
            V = P.state_(self.state)
            Vt = P.state_(self.threshold_state)
            N = int(len(P))
            code = """
                    int numspikes=0;
                    for(int i=0;i<N;i++)
                        if(V(i)>Vt(i))
                            spikes(numspikes++) = i;
                    return_val = numspikes;
                    """
            numspikes = weave.inline(code, ['spikes', 'V', 'Vt', 'N'], \
                                     compiler=self._cpp_compiler,
                                     type_converters=weave.converters.blitz,
                                     extra_compile_args=self._extra_compile_args)
            return spikes[0:numspikes]
        else:
            return ((P.state_(self.state) > P.state_(self.threshold_state)).nonzero())[0]

    def __repr__(self):
        return '%s(threshold_state=%s, state=%s)' % (self.__class__.__name__,
                                                     repr(self.threshold_state),
                                                     repr(self.state))

    def __str__(self):
        return '%s comparing "%s" to the threshold "%s"' % (self.__class__.__name__,
                                                            self.state,
                                                            self.threshold_state)

class EmpiricalThreshold(Threshold):
    '''
    Empirical threshold, e.g. for Hodgkin-Huxley models.

    In empirical models such as the Hodgkin-Huxley method, after a spike
    neurons are not instantaneously reset, but reset themselves
    as part of the dynamical equations defining their behaviour. This class
    can be used to model that. It is a simple threshold mechanism that
    checks e.g. ``V>=Vt`` but it only does so for neurons that haven't
    recently fired (giving the dynamical equations time to reset
    the values naturally). It should be used in conjunction with the
    :class:`NoReset` object.

    **Initialised as:** ::

        EmpiricalThreshold([threshold=1*mV[,refractory=1*ms[,state=0[,clock]]]])

    with arguments:

    ``threshold``
        The lower bound for the state variable to induce a spike.
    ``refractory``
        The time to wait after a spike before checking for spikes again.
    ``state``
        The name or number of the state variable to check.
    ``clock``
        If this object is being used for a :class:`NeuronGroup` which doesn't
        use the default clock, you need to specify its clock here.
    '''
    @check_units(refractory=second)
    def __init__(self, threshold=1 * mvolt, refractory=1 * msecond, state=0, clock=None):
        self.threshold = threshold # Threshold value
        self.state = state
        clock = guess_clock(clock)
        self.refractory = int(refractory / clock.dt)
        # this assumes that if the state stays over the threshold, and say
        # refractory=5ms the user wants spiking at 0ms 5ms 10ms 15ms etc.
        if is_approx_equal(self.refractory * clock.dt, refractory) and self.refractory > 0:
            self.refractory -= 1

    def __call__(self, P):
        '''
        Checks the threshold condition, resets and returns spike times.
        P is the neuron group.
        '''
        #spikes=where((P._S[0,:]>self.Vt) & ((P.LS<P.clock.t-self.refractory) | (P.LS==P.clock.t)))[0]
        spikescond = P.state_(self.state) > self.threshold
        spikescond[P.LS[0:self.refractory]] = False
        return spikescond.nonzero()[0]
        #P.LS[spikes]=P.clock.t # Time of last spike (this line should be general)
        #return spikes

class PoissonThreshold(Threshold):
    '''
    Poisson threshold: a spike is produced with some probability S[0]*dt,
    or S[state]*dt.
    '''
    # TODO: check the state has units in Hz
    def __init__(self, state=0):
        self.state = state

    def __call__(self, P):
        return (random.rand(len(P)) < P.state_(self.state)[:] * P.clock.dt).nonzero()[0]

    def __repr__(self):
        return '%s(state=%s)' % (self.__class__.__name__,
                                 repr(self.state))

    def __str__(self):
        return '%s using state variable %s' % (self.__class__.__name__,
                                               str(self.state))

class HomogeneousPoissonThreshold(PoissonThreshold):
    '''
    Poisson threshold for spike trains with identical rates.
    The underlying NeuronGroup has only one state variable.
    N.B.: "homogeneous" is meant in the spatial (not temporal) sense,
    the rate may change in time.
    '''
    def __call__(self, P):
        # N.B.: is "float" necessary?
        # Other possibility to avoid sorting: use an exponential distribution
        n = random.poisson(float(len(P) * P.clock.dt * clip(P._S[self.state][0], 0, Inf))) # number of spikes
        if n > len(P):
            n = len(P)
            log_warn('brian.HomogeneousPoissonThreshold', 'HomogeneousPoissonThreshold cannot generate enough spikes.')
        spikes = sample(xrange(len(P)), n)
        spikes.sort() # necessary only for subgrouping
        return spikes


from django.conf.urls import url
from . import views

app_name="grab_data"

urlpatterns = [
    url(r'^$', views.Homepage,name="home"),
    url(r'^token/$', views.GetData,name="token"),
    url(r'^instructions/$', views.Instructions,name="instructions"),
    url(r'^about/$', views.About,name="about"),
    url(r'^developer/$', views.Developer,name="developer")
]


from typing import Optional, Union
import numpy as np
from sklearn.metrics import mean_squared_error, max_error, mean_absolute_error
from .MatrixGLMBase import MatrixGLMBase
from .utils import batch_mat_prod

# Regressor for regression problem
class MatrixRegressor(MatrixGLMBase):
    # init constructor
    def __init__(self,
                _lambda: Optional[float] = 1,
                _delta: Union[float, str, None] = 'auto',
                penalty: Optional[str] = "nuclear",
                loss: Optional[str] = "neg-loglike",
                max_steps: Optional[int] = 100,
                max_steps_epoch: Optional[int] = 20,
                eps: Optional[float] = 1e-8) -> None:
        """
        MatRegressor(self,
                     _lambda: Optional[float] = 1,
                     _delta: Union[float, str, None] = 'auto',
                     penalty: Optional[str] = "nuclear",
                     loss: Optional[str] = "neg-loglike",
                     max_steps: Optional[int] = 50,
                     max_steps_epoch: Optional[int] = 20,
                     eps: Optional[float] = 1e-8) -> None) -> None
            Nesterov Matrix Regressor

        Parameters
        ----------
        _lambda : float, optional
            Penalty parameter, default is `1.0`
        _delta : float, str, optional
            Provided Lipschitz constant `1 / L`, default is `'auto'`.\n
            When set to `'auto'`, it will use Fisher Imformation to estimate Lipschitz constant `L`
            and set initial `delta` one or two orders of magnitude larger than `1 / L`
        loss : str, optional
            Loss function, default is `'neg-loglike'`\n
            `L(B) = \\frac{1}{2n}\\cdot \\sum_{i=1}^{n} (y_i - X_i\\cdot B)^2 + J(B)`
        penalty : str, optional
            Penalty method, default is `'nuclear'`
        max_steps : int, optional
            The max iteration steps for model optimization, default is `50`
        max_steps_epoch : int, optional
            The max iteration steps for each epoch during Armijo line search, default is `25`
        eps : float, optional
            Convergence threshold of objective function, default is `1e-8`
        """
        super().__init__(_lambda, _delta, penalty, loss, max_steps, max_steps_epoch, eps)

        # set task
        self.task = 'regression'

    # predict
    def predict(self, X : np.ndarray) -> np.ndarray:
        # dimension check
        assert(len(X.shape) == 3)
        assert(X.shape[1] == self.coef_.shape[0] and X.shape[2] == self.coef_.shape[1])

        return batch_mat_prod(X,self.coef_)

    # compute loss
    def loss(self, X : np.ndarray, y : np.ndarray, coef : np.ndarray) -> float:
        if self.loss_ == "neg-loglike":
            return 0.5 * np.mean((y - batch_mat_prod(X,coef))**2)

    # compute gradient of loss at point S
    def gradients(self, S : np.ndarray, X : np.ndarray, y : np.ndarray) -> np.ndarray:
        # batch size
        B = X.shape[0]
        if self.loss_ == "neg-loglike":
            grad = np.mean((y - batch_mat_prod(X,S)).reshape((B,1,1)) * (-X),axis=0)
        return grad

    def score(self, X : np.ndarray, y : np.ndarray, metric : Optional[str]=None) -> float:
        metric = "mse" if metric == None else metric
        y_pred = self.predict(X)
        if metric in ["mse","MSE","mean_square_error"]:
            s = mean_squared_error(y,y_pred)
        elif metric in ["me","max_error"]:
            s = max_error(y,y_pred)
        elif metric in ["mae","mean_absolute_error"]:
            s = mean_absolute_error(y,y_pred)
        elif metric == "loss":
            s = self.loss(X,y,self.coef_)
        else:
            raise ValueError("Not supported for metric: %s"%(metric))
        return s


import os
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.style.use('ggplot')
import matplotlib
matplotlib.use('Agg')

def get_plot_data_from_single_experiment(exp_dir, file_name, column_x, column_y, start_index=1):
    try:
        data = pd.read_csv(os.path.join(exp_dir, file_name))
    except pd.errors.EmptyDataError:
        return [], []

    data_y = data[column_y]
    if options.column_y_transformation == "softplus":
        data_y = [np.log(np.exp(datum_y) + 1) for datum_y in data_y]

    if column_x == "Iteration":
        data_x = range(start_index, len(data_y) + start_index)
    else:
        data_x = data[column_x]
    return data_x, data_y

def add_curve_for_experiment(data_dir, label=None, start_index=1):
    plot_data = []
    plot_indices = []
    for sub_name in os.listdir(data_dir):
        sub_dir = os.path.join(data_dir, sub_name)
        if os.path.isdir(sub_dir) and "seed" in sub_name and os.path.exists(os.path.join(sub_dir, options.file_name)):
            print("=> Obtaining data from subdirectory %s"%sub_dir)
            plot_indices_single_exp, plot_data_single_exp = get_plot_data_from_single_experiment(
                sub_dir, options.file_name, options.column_x, options.column_y, start_index=start_index)
            plot_indices.append(plot_indices_single_exp)
            plot_data.append(plot_data_single_exp)
    add_curve(plot_data, plot_indices, label)

def create_plot():
    plt.figure()

def save_plot(exp_dir):
    plt.xlabel("Time steps")
    plt.ylabel("Average return")
    plt.savefig(os.path.join(exp_dir, options.save_fig_filename))
    plt.close()

def add_curve(data, indices, label):
    longest_length = len(data[0])
    longest_length_indices = indices[0]
    for i in range(1, len(data)):
        if len(data[i]) > longest_length:
            longest_length = len(data[i])
            longest_length_indices = indices[i]
    mean_data = []
    std_data = []
    for itr in range(longest_length):
        itr_values = []
        for curve_i in range(len(data)):
            if itr < len(data[curve_i]):
                itr_values.append(data[curve_i][itr])
        mean_data.append(np.mean(itr_values))
        std_data.append(np.std(itr_values))

    mean_data = np.array(mean_data)
    std_data = np.array(std_data)

    if label is None:
        plt.plot(longest_length_indices, mean_data)
    else:
        if label in COLORS:
            plt.plot(longest_length_indices, mean_data, label=label, color=COLORS[label])
        else:
            plt.plot(longest_length_indices, mean_data, label=label)
    if label in COLORS:
        plt.fill_between(longest_length_indices, mean_data + std_data, mean_data - std_data, alpha=0.3, color=COLORS[label])
    else:
        plt.fill_between(longest_length_indices, mean_data + std_data, mean_data - std_data, alpha=0.3)

def exptype_to_function(exp_type):
    def _transfer_name_to_label(name):
        alpha = sub_name[sub_name.rfind("_")+1:]
        dot = alpha.find("dot")
        if dot != -1:
            alpha = alpha[:dot] + "." + alpha[dot+3:]
        else:
            alpha = alpha
        return "alpha="+alpha
    def _transfer_name_to_label_beta(name):
        if "simple" in name:
            return "single"
        beta = sub_name[sub_name.rfind("_")+1:]
        dot = beta.find("dot")
        if dot != -1:
            beta = beta[:dot] + "." + beta[dot+3:]
        else:
            beta = beta
        return "beta="+beta

    dic = {
        "ablation": _transfer_name_to_label,
        "exploration": _transfer_name_to_label_beta,
    }
    return dic[exp_type] if exp_type in dic else lambda s: s

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Plot training curve with progress data")
    parser.add_argument("--parent_dir", type=str, default="/home/qzhou/data_copy/")
    parser.add_argument("--exp_name", type=str, default="ablation")
    parser.add_argument("--exp_type", type=str, default="ablation")
    parser.add_argument("--start_index", type=int, default=0)
    parser.add_argument("--file_name", type=str, default="progress.csv")
    parser.add_argument("--column_x", type=str, default="TotalSteps")
    parser.add_argument("--column_y", type=str, default="AverageReturn")
    parser.add_argument("--column_y_transformation", type=str, default=None)

    parser.add_argument("--save_fig_filename", type=str, default="plot.png")
    parser.add_argument("--x_max", type=int, default=200000)

    options = parser.parse_args()
    if options.exp_type=="exploration":
        COLORS = {"single":"deepskyblue", "beta=10":"salmon","beta=0":"deepskyblue"}
    elif options.exp_type=="ablation":
        COLORS = {
            "alpha=0":"orange",
            "alpha=0.25":"orchid",
            "alpha=0.5":"orangered",
            "alpha=0.75":"cornflowerblue",
            "alpha=1":"lightseagreen",
        }

    create_plot()
    sub_name_to_label = exptype_to_function(options.exp_type)
    exp_dir = os.path.join(options.parent_dir, options.exp_name)
    for sub_name in os.listdir(exp_dir):
        if "p_improve" in sub_name or sub_name=="alpha_0":
            continue
        sub_dir = os.path.join(exp_dir, sub_name)
        if os.path.isdir(sub_dir):
            print("current director: %s"%sub_dir)
            label = sub_name_to_label(sub_name)
            add_curve_for_experiment(sub_dir, label=label, start_index=options.start_index)
    plt.xlim(left=0, right=options.x_max)
    handles, labels = plt.gca().get_legend_handles_labels()

    key_dic = {
        "ablation": lambda item: eval(item[1][item[1].rfind("=")+1:]),
    }

    key = key_dic[options.exp_type] if options.exp_type in key_dic else lambda f: f[1]
    plt.legend((*zip(*sorted(zip(handles, labels),key=key))), loc="best")
    save_plot(exp_dir)


from qisys import ui
import qisys.parsers
import qitoolchain.parsers

def configure_parser(parser):
    """Configure parser for this action """
    qisys.parsers.worktree_parser(parser)
    qitoolchain.parsers.toolchain_parser(parser)
    parser.add_argument("package_name", metavar='NAME',
                        help="The name of the package to remove")

def do(args):
    """ Remove a project from a toolchain

    - Check that there is a current toolchain
    - Remove the package from the toolchain

    """
    package_name = args.package_name
    toolchain = qitoolchain.parsers.get_toolchain(args)
    ui.info(ui.green, "Removing package", ui.blue, package_name,
            ui.green, "from toolchain", ui.blue, toolchain.name)
    toolchain.remove_package(package_name)


"""
mapcache.py: a simple mapped object persistency model, with various backends.
"""
from __future__ import division, print_function

import pickle
from datetime import datetime
import os
import numpy as np

try:
    # Python 2
    from itertools import imap
except ImportError:
    imap = map

class MapCache(object):
    """Base Class for mapped object persistency"""
    def __init__(self, filename):
        raise NotImplementedError()

    def key_exists(self, key):
        raise NotImplementedError()

    def add_row(self, key, val, save=True):
        raise NotImplementedError()

    def get_row(self, key):
        raise NotImplementedError()

    def save(self):
        raise NotImplementedError()

    def load(self):
        raise NotImplementedError()

    def compute(self, func, key, *args, **kwargs):
        if self.key_exists(key):
            return self.get_row(key)
        else:
            return self.add_row(key, func(key, *args, **kwargs))

    def compute_iter(self, func, keys, *args, **kwargs):
        return [self.compute(func, key, *args, **kwargs)
                for key in keys]

class PickleCache(MapCache):
    """Pickle-backed Persistency Helper"""
    def __init__(self, filename):
        self.filename = filename
        self.dct = self.load() if os.path.exists(filename) else {}

    def __iter__(self):
        return iter(self.dct)

    def keys(self):
        return self.dct.keys()

    def values(self):
        return self.dct.values()

    def items(self):
        return self.dct.items()

    def key_exists(self, key):
        return key in self.dct

    def add_row(self, key, val, save=True):
        try:
            self.dct[key] = val
            return val
        finally:
            if save: self.save()

    def get_row(self, key):
        return self.dct[key]

    def save(self):
        with open(self.filename, 'wb') as f:
            pickle.dump(self.dct, f)

    def load(self):
        with open(self.filename, 'rb') as f:
            return pickle.load(f)

class NumpyCache(PickleCache):
    """Numpy storage-backed Persistency Helper"""
    def __init__(self, filename):
        if not filename.endswith('.npy'):
            filename += '.npy'
        PickleCache.__init__(self, filename)

    def save(self):
        np.save(self.filename, _dict_to_array(self.dct))

    def load(self):
        return _array_to_dict(np.load(self.filename))

#----------------------------------------------------------------------
# Utilities:

def _array_to_dict(arr):
    """Convert mapping array to a dictionary"""
    keys = arr['key']
    vals = arr['val']

    if keys.dtype.names is not None:
        names = keys.dtype.names
        keys = (tuple(key[name] for name in names) for key in keys)
    return dict(zip(keys, vals))

def _dtype_of_key(key):
    """Find dtype associated with the object or tuple"""
    dtypes = ['i8', 'f8', 'c16', '<U32']
    def get_type(val):
        for dtype in dtypes:
            if np.issubdtype(type(val), dtype):
                return dtype
        else:
            raise ValueError("Can't find type for {0}".format(val))

    if isinstance(key, tuple):
        return np.dtype(','.join(map(get_type, key)))
    else:
        return np.dtype(get_type(key))

def _dict_to_array(dct):
    """Convert dictionary to a mappint array"""
    keys, vals = map(list, zip(*dct.items()))

    keys_dtype = _dtype_of_key(keys[0])
    keys = np.array(keys, dtype=keys_dtype)

    vals = np.asarray(vals)
    vals_dtype = [('key', keys.dtype),
                  ('val', '{0}{1}'.format(vals.shape[1:],
                                          vals.dtype.name))]

    arr = np.zeros(len(keys), dtype=vals_dtype)
    arr['key'] = keys
    arr['val'] = vals
    return arr

#----------------------------------------------------------------------
# Tools for parallel computation
def compute_parallel(cache, func, keys, save_every=4,
                     func_args=None, func_kwargs=None,
                     parallel=True, client=None):
    """Do a parallel computation of a function"""
    keys = [key for key in keys]
    results = dict(cache.items())
    print(50 * '=')
    print("Starting parallel run of {0} results".format(len(keys)))
    print(" - parallel={0}".format(parallel))

    if results:
        print(" - found {0} previous results in {1}"
              "".format(len(results), cache.filename))
    keys_to_compute = [key for key in keys if key not in results]

    # default arguments
    def iter_function(key, func=func, func_args=func_args,
                      func_kwargs=func_kwargs):
        func_args = func_args or ()
        func_kwargs = func_kwargs or {}
        return func(key, *func_args, **func_kwargs)

    print(" - computing {0} results".format(len(keys_to_compute)))

    # Set up the iterator over results
    if parallel:
        # Use interactive to prevent namespace issues
        from IPython.parallel.util import interactive
        iter_function = interactive(iter_function)
        if client is None:
            from IPython.parallel import Client
            client = Client()
        lbv = client.load_balanced_view()
        results_iter = lbv.imap(iter_function, keys_to_compute,
                                ordered=False)
    else:
        results_iter = imap(iter_function, keys_to_compute)

    # Do the iteration, saving the results occasionally
    print(datetime.now())
    for i, (key, result) in enumerate(results_iter):
        print('{0}/{1}: {2}'.format(i + 1, len(keys_to_compute), result))
        print(' {0}'.format(datetime.now()))
        cache.add_row(key, result, save=((i + 1) % save_every == 0))
    cache.save()

    return np.array([cache.get_row(key) for key in keys])

#----------------------------------------------------------------------
# Unit tests:

def test_inputs_outputs():
    from numpy.testing import assert_equal, assert_allclose

    def check_class(Class, filename, compute, inputs):
        if os.path.exists(filename):
            os.remove(filename)

        # First time: make sure the function is called
        compute.count = 0
        db = Class(filename)
        res1 = db.compute_iter(compute, inputs)
        assert_equal(compute.count, 5)

        compute.count = 0
        res2 = db.compute_iter(compute, inputs)
        assert_equal(compute.count, 0)
        db.save()

        compute.count = 0
        db2 = Class(filename)
        res3 = db.compute_iter(compute, inputs)
        assert_equal(compute.count, 0)

        assert_allclose(res1, res2)
        assert_allclose(res2, res3)

        if os.path.exists(filename):
            os.remove(filename)
    def countevals(f):
        def g(*args, **kwargs):
            g.count += 1
            return f(*args, **kwargs)
        g.count = 0
        return g

    @countevals
    def compute_simple(i):
        return i ** 2

    @countevals
    def compute_simple_arr(i):
        return i ** np.arange(4)

    @countevals
    def compute_multikey(t):
        a, b, c = t
        return [a ** b, float(c)]
    inputs_multi = [(i, (i + 1) / 5, '{0}.{1}'.format(int(i), int(i + 2)))
                    for i in range(5)]

    for compute, inputs in [(compute_simple, range(5)),
                            (compute_simple_arr, range(5)),
                            (compute_multikey, inputs_multi)]:
        for c, f in [(PickleCache, 'tmp.pkl'), (NumpyCache, 'tmp.npy')]:
            yield check_class, c, f, compute, inputs

def test_utils():
    from numpy.testing import assert_equal
    D = {(1, 2.5, 'abc'): np.arange(0, 3),
         (2, 3.5, 'def'): np.arange(4, 7)}
    arr = _dict_to_array(D)
    D2 = _array_to_dict(arr)
    arr2 = _dict_to_array(D2)
    assert_equal(D, D2)
    assert_equal(arr, arr2)

if __name__ == '__main__':
    import nose; nose.runmodule()


# merge github and release

import random
from commands.command_link_remove import remove_link
from commands.command_waitinglist_list import get_waitinglist_list
import discord
import os
from modules.keep_alive import keep_alive
from discord.ext import commands
from discord.ext.commands import has_permissions
from commands.command_clan_list import get_clan_list
from commands.command_discord_list import get_discord_list
from commands.command_link_list import get_link_list
from commands.command_clan_update import update_clan_data
from commands.command_discord_update import update_discord_data
from commands.command_status import get_status
from commands.command_link_add import add_link
from commands.command_link_update import update_links
from modules.assign import assign_all

# VARIABLES
intents = discord.Intents().all()
bot = commands.Bot(command_prefix=['qs', 'Qs'], intents=intents)
embed_color = 0x790eab

# ⬇ STATUS COMMANDS ⬇
# ⬇ STATUS COMMANDS ⬇
# ⬇ STATUS COMMANDS ⬇

@bot.command(
    name='status',
    aliases=['tatus', 'st', 's'],
    description=
    'Shows new discord members, new clan members and if people left the clan')
async def status(ctx):
    # get and send status (maybe seperate this so no dependency in file)
    await get_status(ctx, embed_color)

# ⬇ DISCORD COMMANDS ⬇
# ⬇ DISCORD COMMANDS ⬇
# ⬇ DISCORD COMMANDS ⬇

@has_permissions(ban_members=True)
@bot.command(name='lsdi',
             aliases=['lsdc'],
             description='Show all clan members in discord')
async def show_all_discord_members(ctx):
    # update clan data
    await ctx.send(await update_discord_data(ctx))

    # get discord list
    msg_list = await get_discord_list(ctx)

    # send discord list
    embed1 = discord.Embed(description=msg_list[0], color=embed_color)
    embed2 = discord.Embed(description=msg_list[1], color=embed_color)
    await ctx.channel.send(embed=embed1)
    await ctx.channel.send(embed=embed2)

# ⬇ CLAN COMMANDS ⬇
# ⬇ CLAN COMMANDS ⬇ **
# ⬇ CLAN COMMANDS ⬇

@has_permissions(ban_members=True)
@bot.command(name='lscl', description='Show all ingame clan members')
async def show_all_clan_members(ctx):
    # update clan data
    await ctx.channel.send(update_clan_data(ctx))

    # get clan list
    msg_list = await get_clan_list(ctx)

    # send clan list
    embed1 = discord.Embed(description=msg_list[0], color=embed_color)
    embed2 = discord.Embed(description=msg_list[1], color=embed_color)
    await ctx.channel.send(embed=embed1)
    await ctx.channel.send(embed=embed2)

@bot.command(name='upcl', description='Manually updates clan data')
async def qsupcl(ctx):
    await ctx.channel.send(update_clan_data(ctx))

# ⬇ LINKING COMMANDS ⬇
# ⬇ LINKING COMMANDS ⬇
# ⬇ LINKING COMMANDS ⬇

@has_permissions(ban_members=True)
@bot.command(name='rmli', description='Remove a discord-brawlhalla link')
async def rmli(ctx, brawlhalla_id):
    # remove link from link list
    await remove_link(brawlhalla_id, bot, ctx)

@rmli.error
async def missing_question(ctx, error):
    await ctx.message.delete()
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(
            'format your message like the following\n`qsrmli brawlhalla_id`')

@bot.command(name='lsli', description='Show All Links')
@has_permissions(ban_members=True)
async def list_link(ctx):
    # update link list
    embed_name_changes = update_links(ctx, embed_color)

    # get link list
    msg_list = await get_link_list(ctx)

    # send link list
    embed1 = discord.Embed(description=msg_list[0], color=embed_color)
    embed2 = discord.Embed(description=msg_list[1], color=embed_color)
    await ctx.channel.send(embed=embed1)
    try:
        await ctx.channel.send(embed=embed2)
    except:
        print('less than 26 entries')

    # send name changes
    await ctx.channel.send(embed=embed_name_changes)

@has_permissions(ban_members=True)
@bot.command(
    name='adli',
    aliases=['addli', 'ali'],
    description='Create a link between a discord and brawlhalla account')
async def qsadli(ctx, brawlhalla_id, discord_id):
    # adds a link to link list
    await add_link(bot, ctx, brawlhalla_id, discord_id, embed_color)

@qsadli.error
async def missing_question(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(
            'format your message like the following\n`qsadli brawlhalla_id discord_id`'
        )

@bot.command(name='upli',
             description='manually updates all old brawlhalla names in links')
async def upli(ctx):
    await ctx.channel.send(embed=update_links(ctx, embed_color))

# ⬇ WAITING LIST COMAMNDS ⬇
# ⬇ WAITING LIST COMAMNDS ⬇
# ⬇ WAITING LIST COMAMNDS ⬇

@has_permissions(ban_members=True)
@bot.command(name='lswa', description='Shows Waiting List')
async def get_waiting_list(ctx):
    # delete command message
    await ctx.message.delete()
    # get and send waiting list
    await ctx.channel.send(embed=await get_waitinglist_list(ctx=ctx))

# ⬇ OTHER COMMANDS ⬇
# ⬇ OTHER COMMANDS ⬇
# ⬇ OTHER COMMANDS ⬇

@has_permissions(ban_members=True)
@bot.command(name='assignall')
async def assignall(ctx, role_name):
  await assign_all(ctx, role_name)

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    log_channel = bot.get_channel(973594560368373820)
    await log_channel.send("I'm back online!")

@bot.command(name='say')
async def say(ctx, arg):
    await ctx.message.delete()
    await ctx.channel.send(arg)

@bot.command(name='meme')
async def meme(ctx):
    memes = [
        'https://media.discordapp.net/attachments/973594560368373820/991113816299548753/unknown.png',
        'https://cdn.discordapp.com/attachments/973594560368373820/991114373366034512/unknown.png',
        'https://media.discordapp.net/attachments/973594560368373820/991115406716719144/unknown.png?width=589&height=670',
        'https://cdn.discordapp.com/attachments/973594560368373820/991116025158443019/unknown.png'
    ]
    meme = memes[random.randint(0, len(memes) - 1)]
    await ctx.channel.send(meme)

@bot.command(name='doc',
             aliases=['docs'],
             description="Send you to the GitHub page")
async def doc(ctx):
    await ctx.channel.send(
        'Queen Spy Documentation -> https://github.com/CrossyChainsaw/Queen-Spy'
    )

keep_alive()
bot.run(os.environ['BOT_KEY'])


#Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triangulo retangulo, calcule e mostre o comprimento da hipotenusa

co = float(input('Cateto oposto'))
ca = float(input('Cateto adjacente'))

hi = (co ** 2 + ca **2) ** (1/2)

print('Hipotenusa é {:.2f}'.format(hi))

#Outra solução

from math import hypot

h = hypot(co,ca)

print('Hipo é{:.2f} '.format(h))


import collections
from collections import OrderedDict
import contextlib
import copy
from datetime import datetime
import sys
import time

import six

try:
    # Even if we don't want import pycassa anymore. Only
    # CassandraDriverThrift should doing that. We have to because some
    # part of the code like db_manage.py is still refering some
    # pycassa objects.
    import pycassa.NotFoundException

    BaseExceptionClass = pycassa.NotFoundException
except ImportError:
    BaseExceptionClass = Exception

class NotFoundException(BaseExceptionClass):
    pass

def reset():
    CassandraFakeServer.__keyspaces__ = {}

# This is implementating a *kind* of Cassandra server to run tests, in
# future we should remove that and is real instamce of Cassandra.
class CassandraFakeServer(object):
    # The servers share the keyspaces
    __keyspaces__ = {}

    @classmethod
    def create_keyspace(cls, name):
        if name not in cls.__keyspaces__:
            cls.__keyspaces__[name] = _CassandraFakeServerKeyspace(name)
        return cls.__keyspaces__[name]

    @classmethod
    def drop_keyspace(cls, name):
        if name in cls.__keyspaces__:
            del cls.__keyspaces__[name]

    @classmethod
    @contextlib.contextmanager
    def patch_keyspace(cls, ks_name, ks_val=None):
        try:
            orig_ks_val = cls.__keyspaces__[ks_name]
            orig_existed = True
        except KeyError:
            orig_existed = False

        try:
            cls.create_keyspace(ks_name)
            cls.__keyspaces__[ks_name].__tables__ = ks_val
            yield
        finally:
            if orig_existed:
                cls.__keyspaces__[ks_name].__tables__ = orig_ks_val
            else:
                cls.drop_keyspace(ks_name)

class _CassandraFakeServerKeyspace(object):
    def __init__(self, name):
        self.name = name
        self.__tables__ = {}

    def create_table(self, name):
        if name not in self.__tables__:
            self.__tables__[name] = _CassandraFakeServerTable(
                self.name, name)
        return self.__tables__[name]

    def drop_table(self, name):
        if name in self.__tables__:
            del self.__tables__[name]

# This is adding CQL support to the server
class _TableCQLSupport(object):
    QueryType = collections.namedtuple('Query', (
        'method', 'conditions', 'timestamp'))

    class Prepare(object):

        def __init__(self, query):
            self.query = query

        def bind(self, args):
            self.args = args
            for idx, condition in enumerate(self.query.conditions):
                # Apply bindings
                condition['value'] = args[idx]
            return self

        def __str__(self):
            return "<prepared object {}>".format(self.query)

    def __init__(self, name):
        # CQL driver related
        self.cf_name = name

    def prepare(self, cql):
        query = self._parse_cql(cql)
        return _TableCQLSupport.Prepare(query)

    def add_insert(self, key, cql, args):
        return self.execute(cql, args)

    def add_remove(self, key, cql, args):
        return self.execute(cql, args)

    def execute_async(self, prepare, args=None):
        exc = self.execute

        class Future(object):
            def result(self):
                return exc(prepare, args)
        return Future()

    def execute(self, prepare, args=None):
        if not isinstance(prepare, _TableCQLSupport.Prepare):
            if args is not None:
                return self.execute(self.prepare(prepare).bind(args))
        query = prepare.query
        if query.method == "insert":
            return self.insert(
                key=prepare.args[0],
                col_dict={prepare.args[1]: prepare.args[2]})
        elif query.method == "remove":
            columns = None
            if len(prepare.args) > 1:
                columns = [prepare.args[1]]
            return self.remove(key=prepare.args[0], columns=columns)

        args = {}
        if query.conditions:
            for idx, condition in enumerate(query.conditions):
                if condition["key"] == "key":
                    args["key"] = prepare.args[idx]
                elif condition["operator"] == ">=":
                    args["column_start"] = prepare.args[idx]
                elif condition["operator"] == "<=":
                    args["column_finish"] = prepare.args[idx]
                elif condition["operator"] == "IN":
                    args["columns"] = prepare.args[idx:]

        if query.method == "get":
            args["include_timestamp"] = query.timestamp
            if "key" not in args:
                # get_gange
                def generator():
                    for key, col_dict in self.get_range(**args):
                        for column, value in six.iteritems(col_dict):
                            if query.timestamp:
                                yield key, column, value[0], value[1]
                            else:
                                yield key, column, value
                return generator()
            # get
            try:
                r = six.iteritems(self.get(**args))
                if query.timestamp:
                    return True, [(c, v[0], v[1])
                                  for c, v in r]
                return True, [(c, v)
                              for c, v in r]
            except NotFoundException:
                return True, []
        elif query.method == "get_count":

            class Result(object):

                def __init__(self, result):
                    self.result = result

                def one(self):
                    return self.result

            return Result([self.get_count(**args)])

    def _parse_cql(self, cql):
        method, conditions, timestamp = None, [], "WRITETIME" in cql.upper()

        def cql_select(it):
            while it:
                curr = next(it).strip()
                if curr.upper().startswith("FROM"):
                    return "get"
                if curr.upper().startswith("COUNT"):
                    return "get_count"

        def cql_from(it):
            return next(it).strip('"')

        def cql_condition(it):
            return {'key': next(it),
                    'operator': next(it),
                    'value': next(it)}

        it = iter(cql.split())
        while it:
            try:
                curr = next(it).strip()
            except StopIteration:
                break

            if "SELECT" in curr.upper():
                method = cql_select(it)
            if "INSERT" in curr.upper():
                method = "insert"
            if "DELETE" in curr.upper():
                method = "remove"
            if "WHERE" in curr.upper() or "AND" in curr.upper():
                conditions.append(cql_condition(it))

        return self.QueryType(method, conditions, timestamp)

class _CassandraFakeServerTable(_TableCQLSupport):

    ColumnFamilyDefType = collections.namedtuple(
        'ColumnFamilyDef', 'keyspace')

    def __init__(self, keyspace, name):
        super(_CassandraFakeServerTable, self).__init__(name)

        self.keyspace = keyspace
        self.name = name

        self.__rows__ = {}

        # Thrift related
        self._cfdef = self.ColumnFamilyDefType(keyspace)

    def send(self):
        pass

    def __len__(self):
        return 1

    def get(self, key, columns=None, column_start=None, column_finish=None,
            column_count=0, include_timestamp=False, include_ttl=False):
        if not isinstance(key, six.string_types):
            raise TypeError("A str or unicode value was expected, but %s "
                            "was received instead (%s)"
                            % (key.__class__.__name__, str(key)))
        if isinstance(key, six.binary_type):
            key = key.decode('utf-8')
        if key not in self.__rows__:
            raise NotFoundException
        if columns:
            col_dict = {}
            for col_name in columns:
                try:
                    col_value = self.__rows__[key][col_name][0]
                except KeyError:
                    if len(columns) > 1:
                        continue
                    else:
                        raise NotFoundException
                if include_timestamp or include_ttl:
                    ret = (col_value,)
                    if include_timestamp:
                        col_tstamp = self.__rows__[key][col_name][1]
                        ret += (col_tstamp,)
                    if include_ttl:
                        col_ttl = self.__rows__[key][col_name][2]
                        ret += (col_ttl,)
                    col_dict[col_name] = ret
                else:
                    col_dict[col_name] = col_value
        else:
            col_dict = {}
            for col_name in six.viewkeys(self.__rows__[key]):
                if not self._column_within_range(
                        col_name, column_start, column_finish):
                    continue

                col_value = self.__rows__[key][col_name][0]
                if include_timestamp or include_ttl:
                    ret = (col_value,)
                    if include_timestamp:
                        col_tstamp = self.__rows__[key][col_name][1]
                        ret += (col_tstamp,)
                    if include_ttl:
                        col_ttl = self.__rows__[key][col_name][2]
                        ret += (col_ttl,)
                    col_dict[col_name] = ret
                else:
                    col_dict[col_name] = col_value

        if len(col_dict) == 0:
            raise NotFoundException

        sorted_col_dict = OrderedDict(
            (k, col_dict[k]) for k in sorted(col_dict))
        return sorted_col_dict

    def multiget(
        self, keys, columns=None, column_start=None, column_finish=None,
            column_count=0, include_timestamp=False):
        result = {}
        for key in keys:
            try:
                col_dict = self.get(key, columns, column_start, column_finish,
                                    column_count, include_timestamp)
                result[key] = col_dict
            except NotFoundException:
                pass

        return result

    def insert(self, key, col_dict, ttl=None):
        if key not in self.__rows__:
            self.__rows__[key] = {}

        tstamp_sec = (datetime.utcnow() - datetime(1970, 1, 1)).total_seconds()
        tstamp = int(tstamp_sec * 1000)  # uint milliseconds
        for col_name in list(col_dict.keys()):
            self.__rows__[key][col_name] = (col_dict[col_name], tstamp, ttl)

    def remove(self, key, columns=None):
        try:
            if columns:
                # for each entry in col_name delete each that element
                for col_name in columns:
                    del self.__rows__[key][col_name]
            elif columns is None:
                del self.__rows__[key]
        except KeyError:
            # pycassa remove ignores non-existing keys
            pass

    def get_range(self, *args, **kwargs):
        columns = kwargs.get('columns', None)
        column_start = kwargs.get('column_start', None)
        column_finish = kwargs.get('column_finish', None)
        column_count = kwargs.get('column_count', 0)
        include_timestamp = kwargs.get('include_timestamp', False)

        for key in copy.copy(self.__rows__):
            try:
                col_dict = self.get(key, columns, column_start, column_finish,
                                    column_count, include_timestamp)
                yield (key, col_dict)
            except NotFoundException:
                pass

    def xget(self, key, column_start=None, column_finish=None,
             column_count=0, include_timestamp=False, include_ttl=False):
        try:
            col_dict = self.get(key,
                                column_start=column_start,
                                column_finish=column_finish,
                                column_count=column_count,
                                include_timestamp=include_timestamp,
                                include_ttl=include_ttl)
        except NotFoundException:
            col_dict = {}

        for k, v in six.iteritems(col_dict):
            yield (k, v)

    def get_count(self, key, column_start=None, column_finish=None):
        col_names = []
        if key in self.__rows__:
            col_names = six.viewkeys(self.__rows__[key])

        counter = 0
        for col_name in col_names:
            if self._column_within_range(
                    col_name, column_start, column_finish):
                counter += 1

        return counter

    def _column_within_range(self, column_name, column_start, column_finish):
        if type(column_start) is tuple:
            for i in range(len(column_start), len(column_name)):
                column_start = column_start + (column_name[i],)
        if type(column_finish) is tuple:
            for i in range(len(column_finish), len(column_name)):
                column_finish = column_finish + (column_name[i],)

        if column_start and column_name < column_start:
            return False
        if column_finish and column_name > column_finish:
            return False

        return True

    @contextlib.contextmanager
    def patch_cf(self, new_contents=None):
        orig_contents = CassandraFakeServer.__keyspaces__[self.keyspace].\
            __tables__[self.name].__rows__
        try:
            CassandraFakeServer.__keyspaces__[self.keyspace].\
                __tables__[self.name].__rows__ = new_contents
            yield
        finally:
            CassandraFakeServer.__keyspaces__[self.keyspace].\
                __tables__[self.name].__rows__ = orig_contents

    @contextlib.contextmanager
    def patch_row(self, key, new_columns=None):
        ctx = PatchContext(self)
        try:
            ctx.patch([('row', (key, new_columns))])
            yield
        finally:
            ctx.unpatch()

    @contextlib.contextmanager
    def patch_column(self, key, col_name, col_val=None):
        ctx = PatchContext(self)
        try:
            ctx.patch([('column', (key, col_name, col_val))])
            yield
        finally:
            ctx.unpatch()

    @contextlib.contextmanager
    def patches(self, patch_list):
        ctx = PatchContext(self)
        try:
            ctx.patch(patch_list)
            yield
        finally:
            ctx.unpatch()

class PatchContext(object):

    def __init__(self, cf):
        """Patch couple of rows in datastore."""
        self.cf = cf
        self.patches = []  # stack of patches

    def patch(self, patch_list):
        cf = self.cf
        for patch_type, patch_info in patch_list:
            patched = {}
            if patch_type == 'row':
                patched['type'] = 'row'
                row_key, new_columns = patch_info
                patched['row_key'] = row_key
                if row_key in cf.__rows__:
                    patched['row_existed'] = True
                    patched['orig_cols'] = copy.deepcopy(cf.__rows__[row_key])
                    if new_columns is None:
                        # simulates absence of key in cf
                        del cf.__rows__[row_key]
                    else:
                        cf.__rows__[row_key] = new_columns
                else:  # row didn't exist, create one
                    patched['row_existed'] = False
                    cf.insert(row_key, new_columns)
            elif patch_type == 'column':
                patched['type'] = 'column'
                row_key, col_name, col_val = patch_info
                patched['row_key'] = row_key
                patched['col_name'] = col_name
                if col_name in cf.__rows__[row_key]:
                    patched['col_existed'] = True
                    patched['orig_col_val'] = copy.deepcopy(
                        cf.__rows__[row_key][col_name])
                    if col_val is None:
                        # simulates absence of col
                        del cf.__rows__[row_key][col_name]
                    else:
                        cf.insert(row_key, {col_name: col_val})
                else:  # column didn't exist, create one
                    patched['col_existed'] = False
                    cf.insert(row_key, {col_name: col_val})
            else:
                raise Exception(
                    "Unknown patch type %s in patching" % patch_type)

            self.patches.append(patched)

    def unpatch(self):
        cf = self.cf
        for patched in reversed(self.patches):
            patch_type = patched['type']
            row_key = patched['row_key']
            if patch_type == 'row':
                if patched['row_existed']:
                    cf.__rows__[row_key] = patched['orig_cols']
                else:
                    del cf.__rows__[row_key]
            elif patch_type == 'column':
                col_name = patched['col_name']
                if patched['col_existed']:
                    cf.__rows__[row_key][col_name] = patched['orig_col_val']
                else:
                    del cf.__rows__[row_key][col_name]
            else:
                raise Exception(
                    "Unknown patch type %s in un-patching" % patch_type)

#
# This is to support modules that are still using pycassa (db_manage)
#

class FakePool(object):

    class AllServersUnavailable(Exception):  # noqa: D106
        pass

    class MaximumRetryException(Exception):  # noqa: D106
        pass

    class ConnectionPool(object):  # noqa: D106

        def __init__(*args, **kwargs):
            self = args[0]
            if "keyspace" in kwargs:
                self.keyspace = kwargs['keyspace']
            else:
                self.keyspace = args[1]

class FakeUtils(object):

    @staticmethod
    def convert_uuid_to_time(time_uuid_in_db):
        ts = time.mktime(time_uuid_in_db.timetuple())
        return ts

class FakeConnection(object):

    def __init__(*args, **kwargs):
        pass

    @staticmethod
    def default_socket_factory(*args, **kwargs):
        pass

class FakeSystemManager(CassandraFakeServer):

    SIMPLE_STRATEGY = 'SimpleStrategy'

    class SystemManager(object):  # noqa: D106

        def __init__(*args, **kwargs):
            pass

        def list_keyspaces(self):
            return list(CassandraFakeServer.__keyspaces__.keys())

        def get_keyspace_properties(self, ks_name):
            return {'strategy_options': {'replication_factor': '1'}}

        def get_keyspace_column_families(self, keyspace):
            return CassandraFakeServer.__keyspaces__.get(
                keyspace, {}).__tables__.keys()

        def create_column_family(self, keyspace, name, *args, **kwargs):
            CassandraFakeServer.__keyspaces__[keyspace].create_table(name)

class FakeColumnFamily(_CassandraFakeServerTable):

    def __init__(self, pool, name, *args, **kwargs):
        self._pool = pool
        self._name = name
        super(FakeColumnFamily, self).__init__(self._pool.keyspace, self._name)

        # We proxy pycassa and CassandraFakeServer
        ks = CassandraFakeServer.create_keyspace(self._pool.keyspace)
        self.__rows__ = ks.create_table(self._name).__rows__

class FakeBatch(object):

    class Mutator(object):  # noqa: D106
        def send(self):
            pass

class FakeTtypes(object):

    class InvalidRequestException(Exception):  # noqa: D106
        pass

    class ConsistencyLevel(object):  # noqa: D106
        QUORUM = 42

class FakePycassa(object):
    connection = FakeConnection
    ConnectionPool = FakePool.ConnectionPool
    ColumnFamily = FakeColumnFamily
    util = FakeUtils
    NotFoundException = NotFoundException

sys.modules["pycassa"] = FakePycassa
sys.modules["pycassa.batch"] = FakeBatch
sys.modules["pycassa.connection"] = FakeConnection
sys.modules["pycassa.system_manager"] = FakeSystemManager
sys.modules["pycassa.pool"] = FakePool
sys.modules["pycassa.cassandra"] = FakeTtypes
sys.modules["pycassa.cassandra.ttypes"] = FakeTtypes
sys.modules["pycassa.cassandra.ttypes.ConsistencyLevel"] =\
    FakeTtypes.ConsistencyLevel

class FakeThriftPackages(object):
    class TSSLSocket(object):  # noqa: D106
        pass

    class TTransport(object):  # noqa: D106
        pass

class FakeThrift(object):
    transport = FakeThriftPackages

sys.modules["thrift"] = FakeThrift
sys.modules["thrift.transport"] = FakeThriftPackages


import requests  # 통신하기 위해 제일 먼제 해야할 것!

# Crawling 하기 위해 해야할 것: 1.주소분석, 2.알고리즘(for문 돌면서 다운받는 것), 3.text/html 이기 때문에 parsing 하는 게 힘듦

# https://newsstand.naver.com/?list=&pcode=001 주소를 보니 url 이 아니라 uri 이다.
# 주소를 보니 source 를 request 하는 것이 아니라 identifier 이다
# 신문사 이름을 crawling
# 목적 : oid 수집
start_oid = 1
#oid_list = []
oid_names = []

for num in range(0, 2):
    start_oid_str = str(start_oid).zfill(3)
    uri = f"https://newsstand.naver.com/?list=&pcode={start_oid_str}"

    # requsets 해서 uri 를 받아준다
    response = requests.get(uri)

    # http status message
    # print(response.status_code)

    if(response.status_code == 200):
        # pcode 를 담아야 하는데, 이것을 담으려면 variable 로 만들어야 한다 -> start_oid = "001"
        # oid_list.append(start_oid_str)
        print(response.text)

    start_oid = start_oid + 1

    # print(f"oid 총 개수 : {len(oid_list)}")
    # print(oid_list)

# 001, 002, 003 ... 이것은 숫자가 아니라 문자인데 어떻게 하면 +1씩 증가할 수 있을까? oid_test.py 만들어서 test


from __future__ import print_function
from __future__ import absolute_import
from __future__ import division

from bs4 import BeautifulSoup
from string import Template
from datetime import date, timedelta

import scrapy
import re

# scrapy
from ABuFubon.items import StockMarginDataItem, SpiderErrItem
from ABuFubon.pipelines import StockHisMarginPipeline, SpiderErrPipeline

from abupy.MarketBu import ABuMarket
#from abupy.MarketBu.ABuMarket import all_trader
from abupy.UtilBu import ABuDateUtil
from abupy.CoreBu import ABuEnv

class StockHisMarginSpider(scrapy.Spider):
    name = "StockHisMarginSpider"
    allowed_domains = ['fubon-ebrokerdj.fbs.com.tw']

    # set post pipeline map table
    pipeline = set([
        SpiderErrPipeline,      # high prio
        StockHisMarginPipeline
    ])

    #ex: http://fubon-ebrokerdj.fbs.com.tw/z/zc/zcn/zcn.djhtm?a=2330&c=2021-2-1&d=2021-2-2
    URLStr = Template('http://fubon-ebrokerdj.fbs.com.tw/z/zc/zcn/zcn.djhtm?a=$SYMBOL&c=$CDATE&d=$DDATE')
    reDate = re.compile(r".*([0-9]*)\/([0-9]*)\/([0-9]*)", re.DOTALL | re.MULTILINE) # YY/MM/DD
    #reUnit = re.compile(r".*單位：張.*", re.DOTALL | re.MULTILINE)
    #reUint = #股/張 1張=1000股

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.symbols = ABuMarket.all_symbol()
        self.cdateiso = ABuEnv.g_cdataiso
        self.ddateiso = ABuEnv.g_ddateiso

    def start_requests(self):
        cdate = '-'.join(map(lambda x: str(int(x)), self.cdateiso.split("-")))
        ddate = '-'.join(map(lambda x: str(int(x)), self.ddateiso.split("-")))
        headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
        for symbol in self.symbols:
            url = self.URLStr.substitute({'SYMBOL': symbol, 'CDATE': cdate, 'DDATE': ddate})
            yield scrapy.Request(url=url, headers=headers, callback=self.parse, cb_kwargs={'symbol': symbol})

    def parse(self, response, symbol):
        to_float = lambda x: float(str(x.text).replace(',','').replace('%', '').replace(' ',''))
        to_str   = lambda x: str(x.text).replace(' ', '')
        try:
            text = response.body
            soup = BeautifulSoup(text, 'html.parser')
            table = soup.find_all('table', {'class': 't01'})[0]
            values = list(map(to_float, table.find_all('td', {'class': 't3n1'})))
            cdates = list(map(to_str, table.find_all('td', {'class': 't3n0'})))
            # DateUtil
            yy, mm, dd = cdates[1].split('/') # cdata[0] is new line
            cdate = ABuDateUtil.twtime_to_utc_str(yy, mm, dd)
        except Exception as e:
            yy, mm, dd = date.today().isoformat().split("-")[0:3]
            cdate = "{0}-{1}-{2}".format(yy, mm, dd)
            ERR = {
                'date': ABuDateUtil.str_to_datetime(cdate),
                'cls': self.name,
                'msg': "symbol:{0}, fetch html.table Error".format(symbol)
            }
            item = SpiderErrItem({'obj': ERR, 'pipeline': SpiderErrPipeline})
            self.logger.exception("[SPIDER] parser ABuFubon.StockHisMarginSpider symbol:{0} Error:{1}".format(symbol, e))
            yield(item)
            return

        # update latest one
        MarginItem = {
            'date': ABuDateUtil.str_to_datetime(cdate),
            'MagPurchBuy': values[0],     #融資 買進
            'MagPurchSell': values[1], #融資 賣出
            'MagPurchCashRepay': values[2], # 融資 現償
            'MagPurchBalance': values[3], #融資 餘額
            # values[4], 融資 增減
            'MagPurchLimit': values[5], #融資 限額
            'MagPurchRatio': values[6], #融資 使用率
            'ShortSaleSell': values[7], #融券 賣出
            'ShortSaleBuy':  values[8], #融券 買進
            'ShortSaleCashRepay': values[9], #融券 券償
            'ShortSaleBalance': values[10], #融券 餘額
            #values[11], 融券 增減
            'ShortDivMagRatio': values[12], #券資比
            'symbol': symbol
        }
        item = StockMarginDataItem({'obj': MarginItem, 'pipeline': StockHisMarginPipeline})
        self.logger.debug("[SPIDER] pass ABuFubon.StockHisMarginSpider symbol:{0} ShortDivMagRatio:{1}".format(symbol, MarginItem['ShortDivMagRatio']))
        yield(item)


#!/usr/bin/python
# -*- coding UTF-8 -*-

#author: ZHONGQI

from src.config.telnet_client import *
import time
import re

def ont_mac_learn(tn,ponid,ontid,ethid):
    #进入gpon视图下
    tn.read_until(b'OLT(config)# ', timeout=2)
    tn.write(b'interface gpon 0/0 ' + b'\n')
    tn.read_until(b'OLT(config-interface-gpon-0/0)# ',timeout=2)
    tn.write('show ont port learned-mac {} {} eth {} '.format(ponid,ontid,ethid).encode()+b'\n')
    time.sleep(2)
    result = tn.read_very_eager().decode('utf-8')
    print(result)
    tn.read_until(b'OLT(config-interface-gpon-0/0)# ', timeout=2)
    tn.write(b'exit ' + b'\n')
    mac_all = re.findall('\d+:\d+:\d+:\d+:\d+:\d+',result)
    return mac_all


import sqlite3

# Connect to the database (will create if not exists)
conn = sqlite3.connect('shows.db')
cursor = conn.cursor()

# Create the 'shows' table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS shows (
        id INTEGER PRIMARY KEY,
        title TEXT,
        year INTEGER
    )
''')

# Sample show data
shows_data = [
    (1, 'Stranger Things', 2016),
    (2, 'Game of Thrones', 2011),
    (3, 'Breaking Bad', 2008),
    (4, 'Friends', 1994),
    (5, 'The Office', 2005),
    (6, 'The Simpsons', 1989),
    (7, 'Black Mirror', 2011),
    (8, 'The Crown', 2016),
    (9, 'Sherlock', 2010),
    (10, 'Fargo', 2014),
    (11, 'The Mandalorian', 2019),
    (12, 'The Big Bang Theory', 2007),
    (13, 'Stranger Things', 2016),
    (14, 'Chernobyl', 2019),
    (15, 'Friends', 1994),
    (16, 'Money Heist', 2017),
    (17, 'Breaking Bad', 2008),
    (18, 'The Witcher', 2019),
    (19, 'Parks and Recreation', 2009),
    (20, 'Brooklyn Nine-Nine', 2013),
    (21, 'Rick and Morty', 2013),
    (22, 'Westworld', 2016),
    (23, 'The Office', 2005),
    (24, 'The Crown', 2016),
    (25, 'Narcos', 2015)
]

# Insert sample data into the table
cursor.executemany('INSERT INTO shows (id, title, year) VALUES (?, ?, ?)', shows_data)

# Commit changes and close the connection
conn.commit()
conn.close()

print("Database 'shows.db' created and populated with manual show data.")


from modules import *
from papercandy import *
from datasets import tfc2016

def evaluate(group_name: str, my_network: nn.Module = CNN()) -> str:
    my_config = new_config("test.cfg")
    my_config.set("group_name", group_name)
    CONFIG().CURRENT = my_config
    num_batches = 10000
    ds = tfc2016.TFC2016Image("data/img_test", 28).shuffle()
    my_dataloader = tfc2016.ClassificationDataloader(ds, num_works=my_config.get("num_works", required_type=int, default_val=1),
                                                  batch_size=1)
    nc = NetworkC(my_network)
    nc.load(f"models/{my_config.get('group_name', must_exist=True)}_model.pth")
    tester = Tester(my_dataloader)
    tester.set_network(nc)
    res = tester.test(num_batches)
    num_res = len(res)
    correct_counter = 0
    for i in range(num_res):
        if res[i].input_data.target.cpu()[0] == res[i].output.cpu().max(1, keepdim=True)[1][0].item():
            correct_counter += 1
    with open("results/acc.txt", "a") as fh:
        fh.write(f"{group_name}: {correct_counter * 100 / num_res}%\n")
    return f"Accuracy: {correct_counter * 100 / num_res}%."

if __name__ == '__main__':
    for j in range(1, 31):
        print(evaluate(f"G{j}"))
    for j in range(31, 61):
        print(evaluate(f"G{j}", LeNet5()))