class Solution:
    # Time = O(sqrt(N))
    # Space = O(1)
    def consecutiveNumbersSum(self, n: int) -> int:
        count = 0
        k = 1
        # Let n = a + k
        # Then we have to find all k's such that
        # N = a + (a+1) + (a+2) + ... + (a+k-1)
        while (n - (k*(k-1)/2)) > 0:
            # Check if the k value is legal such that n is reachable
            if (n - (k*(k-1))/2) % k == 0:
                count += 1
            k += 1

        return count


import os
from bpemb import BPEmb
from dateutil.parser import parse
import util

multibpemb = BPEmb(lang="multi", vs=1000000, dim=300)

folderPath = '/Users/markolazic/Desktop/exjobb/project/data/gcn'
maxDate = parse('2020-03-15')
minDate = parse('2005-01-01')

def create(receipts, testFilePaths):
  testIndex = 0
  trainIndex = 0
  for receipt in receipts:
    receipt.filterWordsForGraph()
    receipt.createGraph()
    graph = receipt.graph
    if receipt.path in testFilePaths:
      with open(os.path.join(folderPath,'test', 'test'+ str(testIndex) + '.connections'), "w") as f:
        for key in graph.keys():
          t_id = str(key)
          for neighbourKey in graph[key]:
            other_id = str(graph[key][neighbourKey][1]['id'])
            f.write(t_id+ ' ' + other_id + '\n')
      with open(os.path.join(folderPath,'test', 'test' + str(testIndex) + '.values'), "w") as f:
        for word in receipt.graphWords:
          t_id = str(word['id'])
          t_value = word['text']
          t_features = feature_creation(t_value) + getNeighboursDistances(graph[int(t_id)])
          features = ' '.join([str(x) for x in t_features])
          t_label = word['label']
          f.write(t_id + ' ' + features + ' ' + t_label + '\n')
      testIndex+=1

    else:
      with open(os.path.join(folderPath,'train', 'train' + str(trainIndex) + '.connections'), "w") as f:
        for key in graph.keys():
          t_id = str(key)
          for neighbourKey in graph[key]:
            other_id = str(graph[key][neighbourKey][1]['id'])
            f.write(t_id+ ' ' + other_id + '\n')
      with open(os.path.join(folderPath,'train', 'train' + str(trainIndex) + '.values'), "w") as f:
        for word in receipt.graphWords:
          t_id = str(word['id'])
          t_value = word['text']
          t_features = feature_creation(t_value) + getNeighboursDistances(graph[int(t_id)])
          features = ' '.join([str(x) for x in t_features])
          t_label = word['label']
          f.write(t_id + ' ' + features + ' ' + t_label + '\n')
      trainIndex +=1
  return 0

def feature_creation(word):
  features = []
  features.append(1 if isDate(word) else 0)
  features.append(1 if isCity(word) else 0)
  features.append(1 if isCurrency(word) else 0)
  features.append(1 if isCountry(word) else 0)
  features.append(1 if isAlphabetic(word) else 0)
  features.append(1 if isNumeric(word) else 0)
  features.append(1 if isAlphaNumeric(word) else 0)
  features.append(1 if isNumberwithDecimal(word) else 0)
  for v in multibpemb.embed(word)[0]:
    features.append(v)
  return features

def isDate(word):
  if len(word) < 3 or util.isPriceFormat(word) or ':' in word or word.count('-') == 1 or word.count('/') == 1 or 'st' in word:
    return False
  try:
    date = parse(word)
    if date < minDate or date > maxDate:
      return False
    return True
  except:
    return False

def isCity(word):
  return word.lower() in util.cities

def isCountry(word):
  return word.lower() in util.countries

def isAlphabetic(word):
  for c in word:
    if not c.isalpha():
      return False
  return True

def isNumeric(word):
  for c in word:
    if not c.isdigit():
      return False
  return True

def isAlphaNumeric(word):
  for c in word:
    if not c.isdigit() and not c.isalpha():
      return False
  return True

def isNumberwithDecimal(word):
  return util.isPriceFormat(word, onlyFloats=True)

def isCurrency(word):
  return word.upper() in util.currencyList

def getNeighboursDistances(neighbours):
  RDt = 1
  RDl = 1
  RDr = 1
  RDb = 1
  if 'top' in neighbours:
    RDt = neighbours['top'][0]
  if 'left' in neighbours:
    RDl = neighbours['left'][0]
  if 'right' in neighbours:
    RDr = -neighbours['right'][0]
  if 'bottom' in neighbours:
    RDb = -neighbours['bottom'][0]
  return [RDt, RDl, RDr, RDb]


"""Tests for Third Reality quirks."""

import pytest
from zigpy.zcl.clusters.security import IasZone

import zhaquirks
import zhaquirks.thirdreality.night_light

from tests.common import ClusterListener

zhaquirks.setup()

@pytest.mark.parametrize("quirk", (zhaquirks.thirdreality.night_light.Nightlight,))
async def test_third_reality_nightlight(zigpy_device_from_quirk, quirk):
    """Test Third Reality night light forwarding motion attribute to IasZone cluster."""

    device = zigpy_device_from_quirk(quirk)

    ias_zone_cluster = device.endpoints[1].ias_zone
    ias_zone_listener = ClusterListener(ias_zone_cluster)

    ias_zone_status_id = IasZone.AttributeDefs.zone_status.id

    third_reality_cluster = device.endpoints[1].in_clusters[0xFC00]

    # 0x0002 is also used on manufacturer specific cluster for motion events
    third_reality_cluster.update_attribute(0x0002, IasZone.ZoneStatus.Alarm_1)

    assert len(ias_zone_listener.attribute_updates) == 1
    assert ias_zone_listener.attribute_updates[0][0] == ias_zone_status_id
    assert ias_zone_listener.attribute_updates[0][1] == IasZone.ZoneStatus.Alarm_1

    # turn off motion alarm
    third_reality_cluster.update_attribute(0x0002, 0)

    assert len(ias_zone_listener.attribute_updates) == 2
    assert ias_zone_listener.attribute_updates[1][0] == ias_zone_status_id
    assert ias_zone_listener.attribute_updates[1][1] == 0


from typing import Sequence, Union

import click

from lhotse.bin.modes import prepare
from lhotse.recipes.csj import prepare_csj
from lhotse.utils import Pathlike

__all__ = ["csj"]

@prepare.command(context_settings=dict(show_default=True))
@click.argument("corpus_dir", type=click.Path(exists=True, dir_okay=True))
@click.argument("transcript_dir", type=click.Path())
@click.argument("manifest_dir", type=click.Path())
@click.option(
    "-c",
    "--configs",
    type=click.Path(exists=True, file_okay=True),
    default=None,
    multiple=True,
    help=(
        "List of .ini config files to use when parsing transcripts. "
        "Pass each with `-c`. Example: "
        "`-c local/config/disfluent.ini -c local/config/fluent.ini` "
        "NOTE: Only the segment specifications in the first config file are "
        "used. The remaining config files that come after will inherit "
        "the segment boundaries of the first config file. "
    ),
)
@click.option(
    "-p",
    "--dataset-parts",
    type=str,
    default=None,
    multiple=True,
    help=(
        "List of dataset parts to prepare. "
        "To prepare multiple parts, pass each with `-p` "
        "Example: `-p eval1 -p eval2`"
    ),
)
@click.option(
    "-j",
    "--num-jobs",
    type=int,
    default=1,
    help="How many threads to use (can give good speed-ups with slow disks).",
)
def csj(
    corpus_dir: Pathlike,
    transcript_dir: Pathlike,
    manifest_dir: Pathlike,
    configs: Union[Pathlike, Sequence[Pathlike]],
    dataset_parts: Union[str, Sequence[str]],
    num_jobs: int,
):
    "Prepare Corpus of Spontaneous Japanese"

    prepare_csj(
        corpus_dir=corpus_dir,
        transcript_dir=transcript_dir,
        manifest_dir=manifest_dir,
        dataset_parts=dataset_parts,
        configs=configs,
        nj=num_jobs,
    )


import os
from fpdf import FPDF

from data import SAVE_FOLDER

class Save:
    @staticmethod
    def make_dir(path):
        """Создать папку если нет"""
        if not os.path.exists(path):
            os.makedirs(path)

    @staticmethod
    def get_one_path(category):
        """Получить путь для 1х этикеток"""
        return os.path.join(SAVE_FOLDER, category, '1')

    @staticmethod
    def get_three_path(category):
        """Получить путь для 3х этикеток"""
        return os.path.join(SAVE_FOLDER, category, '3')

    @staticmethod
    def get_category_path(category):
        return os.path.join(SAVE_FOLDER, category)

    @classmethod
    def make_category_dir(cls, category):
        # Создаем главную папку save
        cls.make_dir(SAVE_FOLDER)

        # Создаем папку внутри для категории
        cls.make_dir(cls.get_category_path(category))

        # Создаем папки 1 и 3
        cls.make_dir(cls.get_one_path(category))
        cls.make_dir(cls.get_three_path(category))

    @classmethod
    def save_template(cls, template, category, save_name):
        cls.make_category_dir(category)
        image_path = os.path.join(cls.get_category_path(category), save_name + '.jpg')
        pdf_path = os.path.join(cls.get_one_path(category), save_name + '.pdf')
        pdf_three_path = os.path.join(cls.get_three_path(category), save_name + '.pdf')
        template.save(image_path, 'JPEG', quality=100)
        template.save(pdf_path, 'PDF', resolution=100.0)

        pdf = FPDF()
        pdf.add_page()
        # Координаты все подогнаны
        pdf.image(image_path, 25.66875, 10.63316582, 161.25445544, 90.712209302)
        pdf.image(image_path, 25.66875, 102.23316582, 161.25445544, 90.712209302)
        pdf.image(image_path, 25.66875, 193.83316582, 161.25445544, 90.712209302)
        pdf.output(pdf_three_path, 'F')


from os import path
import shlex

def splat(f):
    return lambda kwds: f(**kwds)

def is_empty(x):
    return x is None or x == ''

def hook_dest(src, dest_dir):
    if is_empty(src):
        return None

    filename = path.basename(src)
    if filename.endswith('.j2'):
        filename = filename[:-3]

    return path.join(dest_dir, filename)

def hook_value(dest, config, iface):
    '''Produce a coresponding "hook" config value (`PreUp`, `PostDown`, etc.)
    for a hook scrip that is to be coppied or templated onto the target host.

    What is returned here becomes the default for the coreponsing `[Interface]`
    value.

    If `dest` is `None` or '', simply returns `None`.

    If `dest` is not `None`, it must be the path on the target host to the
    hook script. An invocation line for the script is returned, passing `config`
    and `iface` in for use, like:

        >>> hook_value('/etc/wireguard/hooks/post_up.sh', 'wg0', 'eth0')
        /etc/wireguard/hooks/post_up.sh wg0 eth0

    '''
    if is_empty(dest):
        return None
    return shlex.join((dest, config, iface))

def local_client_config_dest(
    dir,
    client_name,
    config_name,
    hostname,
    add_wg0=False,
):
    if config_name is None or (config_name == 'wg0' and not add_wg0):
        filename = f"{hostname}.conf"
    else:
        filename = f"{config_name}@{hostname}.conf"

    return path.join(dir, client_name, filename)

class FilterModule:
    def filters(self):
        return dict(
            cfg_hook_dest=hook_dest,
            cfg_hook_value=hook_value,
            cfg_local_client_config_dest=splat(local_client_config_dest),
        )


""" This test filename has 'a' prefix because this test should run before running other tests """
import nose

from PyKomoran.jvm import *

global jvm_gateway
if jvm_gateway is not None:
    jvm_gateway.shutdown()
test_jvm1 = None

def test_to_before_init_Jvm():
    """
    JVM Test: before jvm_init(), jvm_gateway should be None
    :return:
    """
    global jvm_gateway

    assert jvm_gateway is None

def test_to_get_Jvm_before_init():
    """
    JVM Test: before jvm_init(), get_jvm() should be None
    :return:
    """
    global test_jvm1

    test_jvm1 = get_jvm()

    assert test_jvm1 is None

def test_to_init_Jvm():
    """
    JVM Test: when call jvm_init() first time, jvm object should be returned
    :return:
    """
    global test_jvm1

    test_jvm1 = init_jvm(1024)

    assert test_jvm1 is not None

def test_to_duplicate_init_Jvm():
    """
    JVM Test: when call jvm_init() more than once, None should be returned
    :return:
    """
    global test_jvm1

    test_jvm2 = init_jvm(1024)
    test_jvm3 = init_jvm(1024)

    assert test_jvm1 is not None
    assert test_jvm2 is None
    assert test_jvm3 is None

def test_to_get_Jvm_after_init():
    """
    JVM Test: when call get_jvm() after init_jvm(), jvm object should be returned
    :return:
    """
    test_jvm2 = get_jvm()

    assert test_jvm2 is not None

def test_to_duplicate_get_Jvm_after_init():
    """
    JVM Test: when call get_jvm() after init_jvm() more than once, returned values should be same
    :return:
    """
    global test_jvm1

    test_jvm2 = get_jvm()
    test_jvm3 = get_jvm()

    assert test_jvm1 is not None
    assert test_jvm2 is not None
    assert test_jvm3 is not None
    assert id(test_jvm1) == id(test_jvm2)
    assert id(test_jvm1) == id(test_jvm3)

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


"""Test constraint solver."""

from gaphas.constraint import EqualsConstraint, EquationConstraint, LessThanConstraint
from gaphas.solver import REQUIRED, MultiConstraint, Solver, Variable
from gaphas.solver.constraint import Constraint, ContainsConstraints

def test_solver_implements_constraint_protocol():
    solver = Solver()

    assert isinstance(solver, Constraint)
    assert isinstance(solver, ContainsConstraints)

def test_weakest_list_order():
    solver = Solver()
    a = Variable(1, 30)
    b = Variable(2, 10)
    c = Variable(3, 10)
    c_eq = EquationConstraint(lambda a, b, c: a + b + c, a=a, b=b, c=c)
    solver.add_constraint(c_eq)
    a.value = 4

    b.value = 5
    assert c_eq.weakest() == c

    b.value = 6
    assert c_eq.weakest() == c

    # b changed above, now change a - all weakest variables changed return the
    # oldest changed variable
    c.value = 6
    assert c_eq.weakest() == b

    b.value = 6
    assert c_eq.weakest() == c

def test_minimal_size_constraint():
    solver = Solver()
    v1 = Variable(0)
    v2 = Variable(10)
    v3 = Variable(10)
    c1 = EqualsConstraint(a=v2, b=v3)
    c2 = LessThanConstraint(smaller=v1, bigger=v3, delta=10)
    solver.add_constraint(c1)
    solver.add_constraint(c2)

    # Check everything is ok on start
    solver.solve()
    assert 0 == v1
    assert 10 == v2
    assert 10 == v3

    # Change v1 to 2, after solve it should be 0 again due to LT constraint
    v1.value = 2
    solver.solve()

    assert 0 == v1
    assert 10 == v2
    assert 10 == v3

    # Change v3 to 20, after solve v2 will follow thanks to EQ constraint
    v3.value = 20
    solver.solve()

    assert 0 == v1
    assert 20 == v2
    assert 20 == v3

    # Change v3 to 0, after solve it should be 10 due to LT.delta = 10, v2
    # should also be 10 due to EQ constraint
    v3.value = 0
    solver.solve()

    assert 0 == v1
    assert 10 == v2
    assert 10 == v3

def test_constraints_can_not_be_resolved():
    solver = Solver()
    a = Variable()
    b = Variable()
    c = Variable(40, strength=REQUIRED)
    d = Variable(30, strength=REQUIRED)

    solver.add_constraint(EqualsConstraint(a, b))
    solver.add_constraint(EqualsConstraint(a, c))
    solver.add_constraint(EqualsConstraint(b, d))

    solver.solve()

    assert a.value == 40.0
    assert b.value == 30.0

def test_notify_for_nested_constraint():
    events = []
    solver = Solver()
    a = Variable()
    b = Variable()
    nested = EqualsConstraint(a, b)
    multi = MultiConstraint(nested)

    solver.add_constraint(multi)
    solver.solve()

    def handler(constraint):
        events.append(constraint)

    solver.add_handler(handler)

    a.value = 10

    solver.solve()

    assert multi in events
    assert nested not in events

def test_notify_for_double_nested_constraint():
    events = []
    solver = Solver()
    a = Variable()
    b = Variable()
    nested = EqualsConstraint(a, b)
    multi = MultiConstraint(nested)
    outer = MultiConstraint(multi)

    solver.add_constraint(outer)
    solver.solve()

    def handler(constraint):
        events.append(constraint)

    solver.add_handler(handler)

    a.value = 10

    solver.solve()

    assert outer in events

def test_needs_solving():
    solver = Solver()
    a = Variable()
    b = Variable()
    eq = EqualsConstraint(a, b)

    solver.add_constraint(eq)
    assert solver.needs_solving

    solver.solve()
    assert not solver.needs_solving

    a.value = 3
    assert solver.needs_solving

    solver.solve()
    assert not solver.needs_solving


from django.core.cache import cache
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse

from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view

from main.models import Story, UserAnswer

@login_required(login_url='/login/')
def likeStory(request, story_id):
    if request.method == 'POST':
        key = f'user_likes_{request.user.id}'
        rate_limit = 150
        rate_limit_time = 60

        num_requests = cache.get(key, 0)
        if num_requests > rate_limit:
            return JsonResponse({'error': 'Rate limit exceeded'}, status=429)
        cache.set(key, num_requests + 1, rate_limit_time)

        user_profile = request.user.profile
        story = Story.objects.get(id=story_id)

        if story in user_profile.liked_stories.all():
            user_profile.liked_stories.remove(story)
            story.likes_number -= 1
        else:
            user_profile.liked_stories.add(story)
            story.likes_number += 1

        user_profile.save()
        story.save()
        return JsonResponse({'success': True})

@login_required(login_url='/login/')
def saveStory(request, story_id):
    if request.method == 'POST':
        key = f'user_saves_{request.user.id}'
        rate_limit = 150
        rate_limit_time = 60

        num_requests = cache.get(key, 0)
        if num_requests > rate_limit:
            return JsonResponse({'error': 'Rate limit exceeded'}, status=429)
        cache.set(key, num_requests + 1, rate_limit_time)

        user_profile = request.user.profile
        story = Story.objects.get(id=story_id)

        if story in user_profile.saved_stories.all():
            user_profile.saved_stories.remove(story)
        else:
            user_profile.saved_stories.add(story)

        user_profile.save()

        return JsonResponse({'success': True})

@login_required(login_url='/login/')
def deleteAnswers(request, story_id):
    #if request.method == 'POST':
    profile = request.user.profile
    story = Story.objects.get(pk=story_id)
    story_answers = UserAnswer.objects.filter(user_profile=profile, story=story)
    story_answers.delete()

    return JsonResponse({'message': 'success', 'action': 'story answers objects deleted'})


container_file = "output_container.txt"
device_file = "output_device.txt"
relationship_file = "output_connect.txt"

objects_name = []
for file_path in [container_file,device_file]:
    with open(file_path,'r',encoding='utf-8') as file:
        for line in file:
            parts = line.strip().split()
            if len(parts) > 0:
                table_name = str(parts[1])
                if table_name.endswith("基本信息表"):
                    objects_name.append(table_name[:-5])

relationship_list = []
with open(relationship_file,'r',encoding='utf-8') as file:
    for line in file:
        parts = line.strip().split()
        if len(parts) > 0:
            table_name = str(parts[1])
            if table_name.endswith("关系表"):
                table_name = table_name[:-3]
            elif table_name.endswith("关联关系"):
                table_name = table_name[:-4]

            relationship_list.append(table_name)

relationship = []
for obj1 in objects_name:
    for obj2 in objects_name:
        if obj1 == obj2:
            continue
        for relationship_str in relationship_list:
            if obj1 in relationship_str and obj2 in relationship_str:
                if (obj2,obj1) not in relationship:
                    relationship.append((obj1,obj2))

# print(objects_name)
# print('\n')
# print(relationship)

output_file = "output_relationship.txt"
with open(output_file,'w',encoding='utf-8') as file:
    for _tuple in relationship:
        for _ in _tuple:
            file.write(_ + " ")
        file.write('\n')


"""Add token table

Revision ID: 64cd427acbcd
Revises: beca80bb9250
Create Date: 2021-04-14 14:35:53.579417

"""
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "64cd427acbcd"
down_revision = "beca80bb9250"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "tokens",
        sa.Column("token", sa.String(), nullable=False),
        sa.Column("email", sa.String(), nullable=True),
        sa.PrimaryKeyConstraint("token"),
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("tokens")
    # ### end Alembic commands ###


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

from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score

train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
original_train = train.copy()
full_data = [train,test]

train['Has_Cabin'] = train['Cabin'].apply(lambda x: 0 if type(x)==float else 1)
test['Has_Cabin'] = test['Cabin'].apply(lambda x: 0 if type(x)==float else 1)

for dataset in full_data:
    dataset['Family_Size'] = dataset['SibSp'] + dataset['Parch'] + 1

for dataset in full_data:
    dataset['IsAlone'] = 0
    dataset.loc[dataset['Family_Size']==1, 'IsAlone'] = 1

for dataset in full_data:
    dataset['Embarked'] = dataset['Embarked'].fillna('S')
    dataset['Fare'] = dataset['Fare'].fillna(train['Fare'].median())

for dataset in full_data:
    avg_age = dataset['Age'].mean()
    avg_std = dataset['Age'].std()
    age_null_count = dataset['Age'].isnull().sum()
    random_list = np.random.randint(avg_age-avg_std,avg_age+avg_std,age_null_count)
    dataset.loc[np.isnan(dataset['Age']),'Age'] = random_list
    dataset['Age'] = dataset['Age'].astype(int)

def get_title(name):
    title_search = re.search(' ([A-Za-z]+)\.', name)
    # If the title exists, extract and return it.
    if title_search:
        return title_search.group(1)
    return ""

for dataset in full_data:
    dataset['Title'] = dataset['Name'].apply(get_title)

for dataset in full_data:
    dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col','Don',
                            'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')

    dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
    dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
    dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')

for dataset in full_data:
    sex_map = {'female':0, 'male':1}
    dataset['Sex'] = dataset['Sex'].map(sex_map).astype(int)

    emb_map = {'S':0, 'C':1, 'Q':2}
    dataset['Embarked'] = dataset['Embarked'].map(emb_map).astype(int)

    title_mapping = {"Mr": 1, "Master": 2, "Mrs": 3, "Miss": 4, "Rare": 5}
    dataset['Title'] = dataset['Title'].map(title_mapping)
    dataset['Title'] = dataset['Title'].fillna(0)

    dataset.loc[ dataset['Fare'] <= 7.91, 'Fare'] = 0
    dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1
    dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare']  = 2
    dataset.loc[ dataset['Fare'] > 31, 'Fare'] = 3
    dataset['Fare'] = dataset['Fare'].astype(int)

    dataset.loc[ dataset['Age'] <= 16, 'Age']  = 0
    dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1
    dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2
    dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3
    dataset.loc[ dataset['Age'] > 64, 'Age'];

drop_elements = ['PassengerId','Name','Ticket','Cabin','SibSp']
train = train.drop(drop_elements,axis=1)
test = test.drop(drop_elements,axis=1)

cv = KFold(n_splits=10)
accuracies = list()
max_attributes = len(list(test))
depth_range = range(1,max_attributes+1)

for depth in depth_range:
    fold_acc = []
    tree_model = tree.DecisionTreeClassifier(max_depth = depth)

    for train_fold,valid_fold in cv.split(train):
        f_train = train.loc[train_fold]
        f_valid = train.loc[valid_fold]

        model = tree_model.fit(X = f_train.drop(['Survived'],axis=1),
                               y = f_train['Survived'])

        valid_acc = model.score(X = f_valid.drop(['Survived'],axis=1),
                                y = f_valid['Survived'])

        fold_acc.append(valid_acc)

    avg = sum(fold_acc)/len(fold_acc)
    accuracies.append(avg)

x_train = train.drop(['Survived'],axis=1).values
y_train = train['Survived']
x_test = test.values

best_acc = 0
best_depth = 0
for i in range(len(accuracies)):
    if(accuracies[i]>best_acc):
        best_acc = accuracies[i]
        best_depth = i+1

decision_tree = tree.DecisionTreeClassifier(max_depth=best_depth)
decision_tree.fit(x_train,y_train)

y_pred = decision_tree.predict(x_test)
submission = pd.DataFrame({"PassengerId": PassengerId,
        "Survived": y_pred})
submission.to_csv('submission.csv', index=False)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

df = pandas.DataFrame(np.c_[dataset['general_card_yellow'],dataset['general_card_red']], index=dataset['Team'])
my_colors = 'yr'
df.plot(kind='bar', color=my_colors)

red_patch = mpatches.Patch(color='yellow', label='Yellow Cards')
orange_patch = mpatches.Patch(color='red', label = 'Red Cards')
plt.legend(handles=[orange_patch, red_patch])

plt.xticks(rotation=90)

plt.show()


from lib.project import Project
from lib.releasedefinition import ReleaseDefinition
import pprint, time, logging, sys, os, util
from lib.RuntimeConfiguration import RuntimeConfiguration

logging.basicConfig(level=logging.INFO, format='%(message)s')
config = RuntimeConfiguration("config.json")
personal_access_token=os.environ["VSTS_PAT_TOKEN"]

def validation (release, release_client, config):
    util.check_if_tagged_release_exists (release, release_client, config)

def main():
    project = Project(config.vsts_project_name)
    release = ReleaseDefinition()
    release_client = util.get_release_client(project, release, personal_access_token, config)

    validation(release, release_client, config)
    release_summary_status_list = util.loop_through_release_definitions_to_trigger_release(release, release_client, config)

    util.output_release_status(release_summary_status_list)

if __name__ == "__main__":
    main()


load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
load(
   "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
   "feature",
   "flag_group",
   "flag_set",
   "tool_path",
)

all_link_actions = [
   ACTION_NAMES.cpp_link_executable,
   ACTION_NAMES.cpp_link_dynamic_library,
   ACTION_NAMES.cpp_link_nodeps_dynamic_library,
]
all_compile_actions = [
   ACTION_NAMES.c_compile,
   ACTION_NAMES.cpp_compile,
   ACTION_NAMES.cpp_module_compile,
]

def _impl(ctx):
    path_prefix = "/usr/bin/arm-none-eabi-"

    tool_paths = [
        tool_path(
            name = "gcc",
            path = path_prefix + "gcc",
        ),
        tool_path(
            name = "ld",
            path = path_prefix + "ld",
        ),
        tool_path(
            name = "ar",
            path = path_prefix + "ar",
        ),
        tool_path(
            name = "objcopy",
            path = path_prefix + "objcopy",
        ),
        tool_path(
            name = "cpp",
            path = "/bin/false",
        ),
        tool_path(
            name = "gcov",
            path = "/bin/false",
        ),
        tool_path(
            name = "nm",
            path = "/bin/false",
        ),
        tool_path(
            name = "objdump",
            path = "/bin/false",
        ),
        tool_path(
            name = "strip",
            path = "/bin/false",
        ),
    ]

    features = [
       feature(
           name = "default_linker_flags",
           enabled = True,
           flag_sets = [
               flag_set(
                   actions = all_link_actions,
                   flag_groups = ([
                       flag_group(
                           flags = [
                            "-Wl,--gc-sections",
                            "-mcpu=cortex-m4",
                            "-mfloat-abi=hard",
                            "-mfpu=fpv4-sp-d16",
                            "-mthumb",
                            "-nostartfiles",
                           ],
                       ),
                   ]),
               ),
               flag_set(
                   actions = all_compile_actions,
                   flag_groups = ([
                       flag_group(
                           flags = [
                            "-mcpu=cortex-m4",
                            "-mfloat-abi=hard",
                            "-mfpu=fpv4-sp-d16",
                            "-mthumb",
                           ],
                       ),
                   ]),
               ),
           ],
       ),
    ]
    return cc_common.create_cc_toolchain_config_info(
        ctx = ctx,
        features = features,
        cxx_builtin_include_directories = [
            "/usr/arm-none-eabi/include",
            "/usr/lib/gcc/arm-none-eabi/10.2.0/include",
            "/usr/lib/gcc/arm-none-eabi/10.2.0/include-fixed",
        ],
        toolchain_identifier = "k8-toolchain",
        host_system_name = "local",
        target_system_name = "stm32f4",
        target_cpu = "k8",
        target_libc = "unknown",
        compiler = "arm-none-eabi",
        abi_version = "unknown",
        abi_libc_version = "unknown",
        tool_paths = tool_paths,
    )

cc_toolchain_config = rule(
    implementation = _impl,
    attrs = {},
    provides = [CcToolchainConfigInfo],
)


"""
Django development settings for {{ project_name }} project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

import os

########## PATH CONFIGURATION
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
########## END PATH CONFIGURATION

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

########## SECRET CONFIGURATION
# SECURITY WARNING: keep the secret key used in production secret!
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#secret-key
SECRET_KEY = r"{{ secret_key }}"
########## END SECRET CONFIGURATION

########## DEBUG CONFIGURATION
# SECURITY WARNING: don't run with debug turned on in production!
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#debug
DEBUG = False

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION

########## MANAGER CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#admins
ADMINS = (
    ('Your Name', 'your_email@example.com'),
)
########## END MANAGER CONFIGURATION

########## DATABASE CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#databases
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
        }
}

# An instant no-brainer sqlite3 development database setup:
# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#         }
# }
########## END DATABASE CONFIGURATION

########## GENERAL CONFIGURATION
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#time-zone
TIME_ZONE = 'UTC'

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#site-id
SITE_ID = 1

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#use-i18n
USE_I18N = True

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#use-l10n
USE_L10N = True

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#use-tz
USE_TZ = True
########## END GENERAL CONFIGURATION

########## MEDIA CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#media-root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#media-url
MEDIA_URL = '/media/'
########## END MEDIA CONFIGURATION

########## STATIC FILE CONFIGURATION
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

APP_BASE_DIR = os.path.dirname(os.path.dirname((__file__)))

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#static-root
STATIC_ROOT = 'staticfiles'

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#static-url
STATIC_URL = '/static/'

# See: https://docs.djangoproject.com/en/1.7/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
    os.path.join(APP_BASE_DIR, 'static'),
)

# See: https://docs.djangoproject.com/en/1.7/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
########## END STATIC FILE CONFIGURATION

########## FIXTURE CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
    os.path.join(BASE_DIR, 'fixtures'),
)
########## END FIXTURE CONFIGURATION

########## TEMPLATE CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#template-context-processors
TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.static',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
)

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#template-loaders
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)
# Use the following for caching of templates:
# TEMPLATE_LOADERS = (
#     ('django.template.loaders.cached.Loader', (
#         'django.template.loaders.filesystem.Loader',
#         'django.template.loaders.app_directories.Loader',
#     )),
# )

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#template-dirs
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)
########## END TEMPLATE CONFIGURATION

########## MIDDLEWARE CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
########## END MIDDLEWARE CONFIGURATION

########## URL CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#root-urlconf
ROOT_URLCONF = '{{ project_name }}.urls'
########## END URL CONFIGURATION

########## APP CONFIGURATION
DJANGO_APPS = (
    # Default Django apps:
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Useful template tags:
    'django.contrib.humanize',
)

THIRD_PARTY_APPS = (
    # Static file management:
    # http://django-compressor.readthedocs.org/en/latest/
    'compressor',
    'newrelic',
)

LOCAL_APPS = (
)

# See: https://docs.djangoproject.com/en/1.7/ref/settings/#installed-apps
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
########## END APP CONFIGURATION

########## LOGGING CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#logging
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', 'console'],
            'level': 'ERROR',
            'propagate': True,
            },
        }
}
########## END LOGGING CONFIGURATION

########## WSGI CONFIGURATION
# See: https://docs.djangoproject.com/en/1.7/ref/settings/#wsgi-application
WSGI_APPLICATION = '{{ project_name}}.wsgi.application'
########## END WSGI CONFIGURATION

########## COMPRESSION CONFIGURATION
# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED
COMPRESS_ENABLED = True

# See: http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_HASHING_METHOD
COMPRESS_CSS_HASHING_METHOD = 'content'

# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_FILTERS
COMPRESS_CSS_FILTERS = [
    'compressor.filters.template.TemplateFilter',
    ]

# See: http://django_compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_JS_FILTERS
COMPRESS_JS_FILTERS = [
    'compressor.filters.template.TemplateFilter',
    ]
########## END COMPRESSION CONFIGURATION


from loderunnerclient.internals.actions import LoderunnerAction
from loderunnerclient.internals.board import Board
import math

def stupid(gcb: Board):
    res = gcb._line_by_line()
    #print(res)
    action_id = 0
    def point_to_list(point_list):
        out = []
        for point in point_list:
            out.append([point.get_x(), point.get_y()])
        return out

    def closest_ladder(ladder_list, robot, enemy_list):
        cls_ladder = [10000000000, -1]
        i = 0
        for enemy in enemy_list:
            for ladder in ladder_list:
                if (math.fabs(enemy[0]-ladder[0]) < math.fabs(robot[0]-ladder[0])) and (math.fabs(robot[0]-ladder[0])<cls_ladder[0]):
                    cls_ladder = ladder
                    i += 1
        return cls_ladder

    def only_on_brick(list, our_brick):
        filtered = []
        for element in list:
            if (element[0]>our_brick[0][0]) and (element[0]>our_brick[len(our_brick)-1][0]):
                filtered.append(element)
        return filtered

    robot = [gcb.get_my_position().get_x(), gcb.get_my_position().get_y()]
    robot_row = robot[1]
    enemy_position = point_to_list(gcb.get_enemy_positions())
    enemy_on_row = []
    # create the list of enemies in row of our character
    for enemy in enemy_position:
        if enemy[0] == robot_row:
            enemy_on_row.append(enemy)

    wall_position = point_to_list(gcb.get_wall_positions())
    wall_on_row = []
    our_flour = []

    # create the list of walls in row of our character
    for wall in wall_position:
        if wall[1] == robot_row:
            wall_on_row.append(wall)
        if wall[1] == (robot_row + 1):
            our_flour.append(wall)

    ladder_position = point_to_list(gcb.get_ladder_positions())
    ladder_on_row = []
    # create the list of enemies in row of our character
    for ladder in ladder_position:
        if ladder[0] == robot_row:
            ladder_on_row.append(ladder)

    # find brick coordinates
    bricks_under = []
    i = 0
    for brick in our_flour:
        i += 1
        bricks_under.append(brick)
        if brick[0] < robot[0]:
            if math.fabs(our_flour[i+1][0]-brick[0]) > 1:
                bricks_under = []
        elif brick[0] > robot[0]:
            if math.fabs(our_flour[i+1][0]-brick[0]) > 1:
                break
    near_ladder = closest_ladder(only_on_brick(ladder_on_row, bricks_under), robot, enemy_on_row)
    nearest_ladder = math.fabs(closest_ladder(only_on_brick(ladder_on_row, bricks_under), robot, enemy_on_row)[0]-robot[0])
    left_hole = math.fabs(bricks_under[0][0]-robot[0])
    right_hole = math.fabs(bricks_under[len(bricks_under)-1][0]-robot[0])

    if nearest_ladder == 0:
        action_id = 3
    elif ((right_hole <= left_hole) and (right_hole < nearest_ladder))or((nearest_ladder < left_hole) and (nearest_ladder < right_hole) and (near_ladder[0] > robot[0])):
        action_id = 1
    elif ((left_hole < right_hole) and (left_hole < nearest_ladder))or((nearest_ladder < left_hole) and (nearest_ladder < right_hole) and (near_ladder[0] < robot[0])):
        action_id = 0
    else:
        action_id = 2
    print(str(left_hole), " ", right_hole, " ", nearest_ladder)

    return list(LoderunnerAction)[action_id]


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

'''
    快速开始：30s上手Keras
    Keras的核心数据结构是“模型”，模型是一种组织网络层的方式。
    Keras中主要的模型是Sequential模型。
    Sequential是一系列网络层按顺序构成的栈。
    Sequential模型如下
'''
from keras.models import Sequential

model = Sequential

'''
    将一些网络层通过.add()堆叠起来，就构成了一个模型
'''
from keras.layers import Dense,Activation

model.add(Dense(units=64,input_dim=100))
model.add(Activation("relu"))
model.add(Dense(units=10))
model.add(Activation("softmax"))

'''
    完成模型的搭建后，我们需要使用.compile()方法来编译模型
'''
model.compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy'])

'''
    编译模型时必须指明损失函数和优化器
from keras.optimizers import SGD
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.01, momentum=0.9, nesterov=True))
'''

'''
    完成模型编译后，在训练数据上按batch进行一定次数的迭代来训练网络
'''
x_train = np.linspace(1,10000,2);
y_train = np.linspace(1,20000,4);
model.fit(x_train, y_train, epochs=5, batch_size=32)

'''
    也可以手动将一个个batch的数据送入网络中训练，这时候需要使用：
model.train_on_batch(x_batch, y_batch)
'''

'''
    随后，我们可以使用一行代码对我们的模型进行评估，看看模型的指标是否满足我们的要求
'''
x_test = np.linspace(1,1000,2);
y_test = np.linspace(1,2000,4);
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)

'''
    或者，我们可以使用我们的模型，对新的数据进行预测
'''

classes = model.predict(x_test, batch_size=128)


from collections.abc import Iterable
import logging
import os
import time
from typing import Sequence, Union
import warnings

import numpy as np
from omegaconf import DictConfig, OmegaConf
import pandas as pd
from torch.utils.data import Dataset
import xarray as xr

from poet.utils import insolation

logger = logging.getLogger(__name__)

VARIABLE_DICT = {}

def open_forecast_dataset(directory, variables, input_lead_times, target_lead_times, ):
    def get_file_name(path, var, t):
        return os.path.join(path, f"{var}_{t}h.zarr")

    def combine_datasets(lead_times, name, dim):
        datasets = []
        remove_attrs = ['step', 'isobaricInhPa', 'valid_time', 'surface']
        for variable in variables:
            for il in lead_times:
                file_name = get_file_name(directory, variable, il)
                logger.debug(f"open zarr dataset {file_name}")
                ds = xr.open_zarr(file_name)
                for attr in remove_attrs:
                    try:
                        ds = ds.drop(attr)
                    except ValueError:
                        pass
                # Rename variable
                ds = ds.rename({VARIABLE_DICT.get(variable, variable): f"{variable}_{il}"})
                datasets.append(ds)
        # Merge datasets
        ds = xr.merge(datasets)
        # Convert to a single input/target array by merging along the variables
        da = ds.to_array(dim, name=name).transpose('time', 'number', dim, 'latitude', 'longitude')
        return da

    result = xr.Dataset()
    merge_time = time.time()
    logger.info("merging input datasets")
    result['inputs'] = combine_datasets(input_lead_times, 'inputs', 'channel_in')
    result['targets'] = combine_datasets(target_lead_times, 'targets', 'channel_out')
    logger.info(f"merged datasets in {time.time() - merge_time:0.1f} s")

    return result

class ForecastDataset(Dataset):

    def __init__(self, dataset, shuffle=True, return_da=False, number_as_sample=False,
                 subsample_size=None):
        warnings.warn("ForecastDataset is deprecated as of poet==0.0.1 and will be removed in the future",
                      DeprecationWarning)
        self.ds = dataset
        self.shuffle = shuffle
        self.return_da = return_da
        self.number_as_sample = number_as_sample
        self.subsample_size = subsample_size

        self.indices = None
        self._unique_worker_id = 0

        self._init_indices()

    def _init_indices(self):
        self.indices = np.arange(0, len(self))
        if self.shuffle:
            np.random.shuffle(self.indices)

    def __len__(self):
        if self.number_as_sample:
            return self.ds.dims['time'] * self.ds.dims['number']
        else:
            return self.ds.dims['time']

    def __getitem__(self, item):
        if self.number_as_sample:
            sample = np.unravel_index(item, (self.ds.dims['time'], self.ds.dims['number']))
            sample = {'time': sample[0], 'number': sample[1]}
        else:
            sample = {'time': item}
            if self.subsample_size is not None and self.subsample_size < self.ds.dims['number']:
                members = np.random.choice(self.ds.dims['number'], size=self.subsample_size, replace=False)
                sample['number'] = members
        if self.return_da:
            return self.ds['inputs'].isel(**sample), self.ds['targets'].isel(**sample).mean('number')
        else:
            try:
                return self.ds['inputs'].isel(**sample).values, self.ds['targets'].isel(**sample).mean('number').values
            except RuntimeError as e:
                logger.error(f"encountered bad data sample at dataset index {sample}")
                logger.error(str(e))
                return self.__getitem__(item - 1)

def open_verified_ensemble_dataset(directory, input_variables, sample_lead_times, target_variable,
                                   prefix=None, suffix=None, constants=None, scaling=None):
    prefix = prefix or ''
    suffix = suffix or ''
    scaling = scaling or {}

    def get_file_name(path, var, t):
        return os.path.join(path, f"{prefix}{var}_{t}h{suffix}.zarr")

    merge_time = time.time()
    logger.info("merging input datasets")

    datasets = []
    remove_attrs = ['isobaricInhPa', 'valid_time', 'surface']
    for variable in input_variables:
        lead_ds = []
        for il in sample_lead_times:
            file_name = get_file_name(directory, variable, il)
            logger.debug(f"open zarr dataset {file_name}")
            ds = xr.open_zarr(file_name, chunks={})
            for attr in remove_attrs:
                try:
                    ds = ds.drop(attr)
                except ValueError:
                    pass
            # Rename variable
            ds = ds.expand_dims('step', axis=1)
            lead_ds.append(ds)
        ds = xr.concat(lead_ds, 'step')
        # Apply log scaling lazily
        if variable in scaling and scaling[variable].get('log_epsilon', None) is not None:
            ds[variable] = np.log(ds[variable] + scaling[variable]['log_epsilon']) \
                           - np.log(scaling[variable]['log_epsilon'])
        datasets.append(ds)
    # Merge datasets
    input_ds = xr.merge(datasets)
    # Convert to a single input/target array by merging along the variables
    input_da = input_ds.to_array('channel_in', name='inputs').transpose(
        'time', 'step', 'number', 'channel_in', 'latitude', 'longitude')

    # Get the target, if specified. If not specified, generate zeros
    if target_variable is not None:
        target_file = os.path.join(directory, f"{target_variable}.zarr")
        logger.debug(f"open target file {target_file}")
        target_ds = xr.open_zarr(target_file, chunks={}).rename({'time': 'obs_time'})
        try:
            target_ds = target_ds.drop('valid_time')
        except ValueError:
            pass
        variable = list(target_ds.data_vars.keys())[0]
        # Apply log scaling lazily
        if variable in scaling and scaling[variable].get('log_epsilon', None) is not None:
            target_ds[variable] = np.log(target_ds[variable] + scaling[variable]['log_epsilon']) \
                                  - np.log(scaling[variable]['log_epsilon'])
        target_da = target_ds.to_array('channel_out', name='targets').transpose(
            'obs_time', 'channel_out', 'latitude', 'longitude')
    else:
        logger.info("no target variable selected; generating zeros")
        expected_obs_times = pd.Series((input_ds.time + input_ds.step).values.flatten()).unique()
        target_da = xr.DataArray(
            np.zeros((len(expected_obs_times), 1, input_ds.dims['latitude'], input_ds.dims['longitude']),
                     dtype='float32'),
            dims=('obs_time', 'channel_out', 'latitude', 'longitude'),
            coords={
                'obs_time': expected_obs_times,
                'channel_out': ['zeros'],
                'latitude': input_ds.latitude,
                'longitude': input_ds.longitude
            }
        )

    result = xr.Dataset()
    result['inputs'] = input_da
    result['targets'] = target_da

    # Get constants
    if constants is not None:
        constants_ds = []
        for name, var in constants.items():
            constants_ds.append(xr.open_zarr(os.path.join(directory, f"{name}.zarr"))[var])
        constants_ds = xr.merge(constants_ds)
        constants_da = constants_ds.to_array('channel_c', name='constants').transpose(
            'channel_c', 'latitude', 'longitude')
        result['constants'] = constants_da

    logger.info(f"merged datasets in {time.time() - merge_time:0.1f} s")

    return result

class VerifiedEnsembleDataset(Dataset):
    def __init__(
            self,
            dataset: xr.Dataset,
            scaling: DictConfig,
            shuffle: bool = True,
            return_da: bool = False,
            subsample_size: Union[int, Sequence, None] = None,
            batch_size: int = 32,
            drop_last: bool = False,
            add_lead_time: bool = False,
            add_insolation: bool = False,
            check_nans: bool = True,
            target_clipping: Union[float, Sequence[float], None] = None
    ):
        self.ds = dataset
        self.scaling = OmegaConf.to_object(scaling)
        self.shuffle = shuffle
        self.return_da = return_da
        self.subsample_size = subsample_size
        self.batch_size = batch_size
        self.drop_last = drop_last
        self.add_lead_time = add_lead_time
        self.add_insolation = add_insolation
        self.check_nans = check_nans
        if target_clipping is None:
            self.target_clipping = None
        else:
            self.target_clipping = target_clipping if isinstance(target_clipping, Iterable) else (target_clipping, None)

        if self.drop_last:
            self._time_dim = self.ds.dims['time'] // batch_size
        else:
            self._time_dim = int(np.ceil(self.ds.dims['time'] / batch_size))
        self._step_dim = self.ds.dims['step']

        self._input_scaling = None
        self._target_scaling = None
        self._get_scaling_da()

        self._unique_worker_id = 0

    def _get_scaling_da(self):
        scaling_df = pd.DataFrame.from_dict(self.scaling).T
        scaling_df.loc['zeros'] = {'mean': 0., 'std': 1.}
        scaling_da = scaling_df.to_xarray().astype('float32')
        try:
            self._input_scaling = scaling_da.sel(index=self.ds.channel_in.values).rename({'index': 'channel_in'})
        except (ValueError, KeyError):
            raise KeyError(f"one or more of the input data variables f{list(self.ds.channel_in.values)} not found in "
                           f"the scaling config dict data.scaling ({list(self.scaling.keys())})")
        try:
            self._target_scaling = scaling_da.sel(index=self.ds.channel_out.values).rename({'index': 'channel_out'})
        except (ValueError, KeyError):
            raise KeyError(f"one or more of the target data variables f{list(self.ds.channel_out.values)} not found "
                           f"in the scaling config dict data.scaling ({list(self.scaling.keys())})")

    def __len__(self):
        return self._time_dim * self._step_dim

    def __get_valid_time(self, item):
        t, s = self.__get_time_step_index(item)
        return self.ds['time'][t].values + self.ds['step'][s].values

    def __get_time_step_index(self, item):
        t, s = np.unravel_index(item, (self._time_dim, self._step_dim))
        return slice(t * self.batch_size, (t + 1) * self.batch_size), s

    def __getitem__(self, item):
        time_slice, step_index = self.__get_time_step_index(item)
        logger.log(1, f"data sample time: {self.ds.time.values[time_slice]}, step: {self.ds.step.values[step_index]}")
        sample = {'time': time_slice, 'step': step_index}
        if isinstance(self.subsample_size, int) and self.subsample_size < self.ds.dims['number']:
            if self.shuffle:
                members = np.random.choice(self.ds.dims['number'], size=self.subsample_size, replace=False)
            else:
                members = np.arange(self.subsample_size)
            sample['number'] = members
        elif isinstance(self.subsample_size, Sequence):
            sample['number'] = self.subsample_size
        target_sample = {'obs_time': self.__get_valid_time(item)}
        inputs = (self.ds['inputs'].isel(**sample) - self._input_scaling['mean']) / self._input_scaling['std']
        # Get additional metadata added to inputs
        if any(['constants' in self.ds.data_vars, self.add_insolation, self.add_lead_time]):
            metadata = []
            if 'constants' in self.ds.data_vars:
                metadata.append(self.ds['constants'].rename({'channel_c': 'channel_in'}))
            if self.add_insolation:
                sol = insolation(self.__get_valid_time(item), self.ds.latitude.values, self.ds.longitude.values,
                                 enforce_2d=True, clip_zero=False)
                metadata.append(xr.DataArray(
                    sol[:, None],
                    dims=['time', 'channel_in', 'latitude', 'longitude'],
                    coords={
                        'time': inputs.time,
                        'channel_in': ['insolation'],
                        'latitude': self.ds.latitude,
                        'longitude': self.ds.longitude
                    }
                ))
            if self.add_lead_time:
                step = float(self.ds.step.values[step_index].astype('timedelta64[h]').astype('float')) / 168.
                metadata.append(xr.DataArray(
                    np.full((1, self.ds.dims['latitude'], self.ds.dims['longitude']), step, dtype='float32'),
                    dims=['channel_in', 'latitude', 'longitude'],
                    coords={
                        'channel_in': ['lead_time'],
                        'latitude': self.ds.latitude,
                        'longitude': self.ds.longitude
                    }
                ))
            inputs = xr.concat([inputs] + metadata, dim='channel_in')
        targets = (self.ds['targets'].sel(**target_sample) - self._target_scaling['mean']) / \
            self._target_scaling['std']
        if self.target_clipping is not None:
            targets = targets.clip(*self.target_clipping)
        if self.check_nans and np.isnan(inputs).sum() > 0:
            logger.error("found NaN data; logging occurence information")
            print(f"data sample time: {self.ds.time.values[time_slice]}, step: {self.ds.step.values[step_index]}")
            print(f"missing values per channel_in: "
                  f"{np.isnan(inputs).sum([d for d in inputs.dims if d != 'channel_in']).compute()}")
        if self.return_da:
            return inputs, targets
        try:
            return inputs.values, targets.values
        except RuntimeError:
            logger.error("an unexpected error occurred when computing data")
            logger.error(f"input dataarray: {inputs}")
            logger.error(f"target dataarray: {targets}")
            raise


"""

This script provides
various exploration on onnx model
such as those operations:

- summary:
    this command will summarize model info mation such as:
    1. model opset version;
    2. if check pass;
    3. whether can be simplifiered or not;
    4. inputs node and outputs node;
    5. all nodes number;
    6. Initializers tensornumber and their index;

- search:
    1. search all nodes by OpType;
    2. search node by node name (ID);

- list:
    1. print out all nodes id
    2. list -hl will print all nodes and it's attribute

"""
import os
import sys
import argparse
import onnxruntime as ort
import onnx
# import onnx
# from onnx.onnx_ml_pb2 import ModelProto
from .proto.onnx_ml_pb2 import ModelProto, TensorProto, NodeProto
from typing import Optional, cast, Text, IO
from google import protobuf
from colorama import init, Fore, Style, Back
from .core import *
init()

class ONNXExplorer(object):

    def __init__(self):
        parser = argparse.ArgumentParser(
            description='ONNX Explorer',
            usage='''onnxexp <command> [<args>]

The most commonly used onnxexp commands are:
   ls          ls all model nodes
   search      search and print out certain commands
   summary     print out model summary

i.e.:
onnxexp model.onnx search -t 'Slice'
onnxexp model.onnx search -n '342654'
onnxexp model.onnx ls -hl
onnxexp model.onnx ls
''')
        parser.add_argument('model', help='model path')
        parser.add_argument('command', help='Subcommand to run')
        args = parser.parse_args(sys.argv[1:3])
        self.model_path = args.model
        if args.model != None and os.path.exists(args.model):
            print(Style.BRIGHT + 'Exploring on onnx model: ' +
                  Style.RESET_ALL + Fore.GREEN + self.model_path + Style.RESET_ALL)
            # self.model_proto = load_onnx_model(self.model_path, ModelProto())
            self.model_proto = onnx.load(self.model_path)
            if not hasattr(self, args.command):
                # summary
                print('unrecognized command.')
                exit(1)
            # use dispatch pattern to invoke method with same name
            getattr(self, args.command)()
        else:
            parser.print_help()
            print('{} does not exist or you should provide model path at first arg.'.format(
                args.model))

    def ls(self):
        parser = argparse.ArgumentParser(
            description='ls at any level about the model.')
        # prefixing the argument with -- means it's optional
        parser.add_argument('-hl', action='store_true')
        args = parser.parse_args(sys.argv[3:])
        print('Running onnxexp ls, hl=%s' % args.hl)
        if args.hl:
            list_nodes_hl(self.model_proto)
        else:
            list_nodes(self.model_proto)

    def search(self):
        parser = argparse.ArgumentParser(
            description='Download objects and refs from another repository')
        # NOT prefixing the argument with -- means it's not optional
        parser.add_argument('--name', '-n', help='name of to search node')
        parser.add_argument('--type', '-t', help='type of to search node')
        args = parser.parse_args(sys.argv[3:])
        if args.name != None:
            search_node_by_id(self.model_proto, args.name)
        elif args.type != None:
            search_nodes_by_type(self.model_proto, args.type)
        else:
            print('search should provide type name or id to search.')

    def summary(self):
        summary(self.model_proto, self.model_path)

def main():
    ONNXExplorer()

if __name__ == '__main__':
    main()


import socket
import struct

# Kig op på RAW_SOCKET
# Access point til rPi
# rdpcap
# gem med scapy
def main():

    host = socket.gethostbyname(socket.gethostname())
    print('IP: {}'.format(host))

    connection = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
    connection.bind(host)

    connection.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    connection.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

    while True:
        raw_data, addr = connection.recv(65536)

        dest_mac, src_mac, eth_proto, data = unpack_ethernet_frame(raw_data)

        print('\nEthernet Frame:')
        print('Destination MAC: {}, Source MAC: {}, Protocol: {}'.format(dest_mac, src_mac, eth_proto))

def unpack_ethernet_frame(data):
    dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
    return (get_formatted_mac_address(dest_mac), get_formatted_mac_address(src_mac),
            socket.htons(proto), data[14:])

def get_formatted_mac_address(bytes_address):
    bytes_string_list = map('{:02x}'.format, bytes_address)
    formatted_string = ':'.join(bytes_string_list).upper()
    return formatted_string

def get_protocol(bytes_protocol):
    bytes_str = map('{:02x}'.format, bytes_protocol)
    protocol = ''.join(bytes_str).upper()
    return protocol

if __name__ == '__main__':
    main()


from LowestCommonAncestorDAG import Node, dagLCA

class TestLowestCommonAncestorDAG:
    def test_simple(self):
        root = Node(1)
        r2 = Node(2)
        r3 = Node(3)
        r4 = Node(4)
        r5 = Node(5)
        r6 = Node(6)
        root.succ = [r2,r3,r4,r5]
        r2.succ = [r4]
        r2.pred = [root]
        r3.succ = [r4, r5]
        r3.pred = [root]
        r4.succ = [r5]
        r4.pred = [r2,r3,root]
        r5.pred = [r3,r4,root]
        r6.pred = [r4]

        lca = dagLCA(root, r4, r5)

        assert lca is 3

    def test_null(self):
        root = None

        lca = dagLCA(root, 4, 5)

        assert lca is None

    def test_root(self):
        root = Node(1)
        r2 = Node(2)
        r3 = Node(3)
        root.succ = [r2,r3]

        lca = dagLCA(root, root, r3)
        assert lca is 1
        lca = dagLCA(root, r3, root)
        assert lca is 1
        lca = dagLCA(root, r2, r2)
        assert lca is 2

    def test_no_immediate_lca(self):
        root = Node(1)
        r2 = Node(2)
        r3 = Node(3)
        r4 = Node(4)
        r5 = Node(5)
        r6 = Node(6)
        root.succ = [r2,r3]
        r2.succ = [r4]
        r2.pred = [root]
        r3.succ = [r4, r5]
        r3.pred = [root]
        r4.succ = [r5]
        r4.pred = [r2]
        r5.pred = [r3]
        r6.pred = [r4]

        lca = dagLCA(root, r4, r5)

        assert lca is 1

3rd Year/Software Engineering/Lowest Common Ancestor/test_LowestCommonAncestorDAG.py


# ********************************************************************
#
#  $Id: helloworld.py 32630 2018-10-10 14:11:07Z seb $
#
#  An example that show how to use a  Yocto-Color-V2
#
#  You can find more information on our web site:
#   Yocto-Color-V2 documentation:
#      https://www.yoctopuce.com/EN/products/yocto-color-v2/doc.html
#   Python API Reference:
#      https://www.yoctopuce.com/EN/doc/reference/yoctolib-python-EN.html
#
# *********************************************************************

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
# add ../../Sources to the PYTHONPATH
sys.path.append(os.path.join("..", "..", "Sources"))

from yocto_api import *
from yocto_colorledcluster import *

def usage():
    scriptname = os.path.basename(sys.argv[0])
    print("Usage:")
    print(scriptname + ' <serial_number>')
    print(scriptname + ' <logical_name>')
    print(scriptname + ' any  ')
    sys.exit()

def die(msg):
    sys.exit(msg + ' (check USB cable)')

def setcolor(led_cluster, nb_leds, color):
    if led_cluster.isOnline():
        # immediate transition for fist half of leds
        led_cluster.set_rgbColor(0, nb_leds / 2, color)
        # immediate transition for second half of leds
        led_cluster.rgb_move(nb_leds / 2, nb_leds / 2, color, 2000)
    else:
        print('Module not connected (check identification and USB cable)')

errmsg = YRefParam()

if len(sys.argv) < 2:
    usage()

target = sys.argv[1]

# Setup the API to use local USB devices
if YAPI.RegisterHub("usb", errmsg) != YAPI.SUCCESS:
    sys.exit("init error" + errmsg.value)

if target == 'any':
    # retreive any RGB led
    led_cluster = YColorLedCluster.FirstColorLedCluster()
    if led_cluster is None:
        die('No module connected')
else:
    led_cluster = YColorLedCluster.FindColorLedCluster(target + '.colorLedCluster')

if not led_cluster.isOnline():
    die('device not connected')

nb_leds = 2
led_cluster.set_activeLedCount(nb_leds)
led_cluster.set_ledType(YColorLedCluster.LEDTYPE_RGB)

print('r: set to red')
print('g: set to green')
print('b: set to blue')
print('x: exit')

try:
    input = raw_input  # python 2.x fix
except:
    pass

c = input("command:")

while c != 'x':
    if c == 'r':
        setcolor(led_cluster, nb_leds, 0xFF0000)
    elif c == 'g':
        setcolor(led_cluster, nb_leds, 0x00FF00)
    elif c == 'b':
        setcolor(led_cluster, nb_leds, 0x0000FF)
    c = input("command:")
YAPI.FreeAPI()


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome("C:\\Program Files (x86)\\chromedriver.exe")

### MONKEY TYPE ###

# driver.get("https://www.monkeytype.com/")
#
# ####### METHOD 1 #######
# words = []
# words_typed = []
#
# while True:
#     #add words
#     words_all = driver.find_elements_by_class_name("word")
#
#     for word in words_all:
#         if word in words:
#             continue
#         else:
#             try:
#                 if word.text =='':
#                     pass
#                 else:
#                     words.append(word.text)
#                     print(f"Word: {word.text}")
#             except Exception as e:
#                 print(e)
#
#     for i in range(0, len(words)):
#         if words[i] in words_typed:
#             continue
#         else:
#             print(words[i])
#             actions = ActionChains(driver)
#             actions.send_keys(words[i] + ' ')
#             actions.perform()
#             words_typed.append(words[i])
#
# ####### METHOD 2 #######
#
#
# driver.close()
# driver.quit()

# ### 10 fast fingers ###
#
# driver.get("https://10fastfingers.com/typing-test/english")
#
# highlighted = driver.find_element_by_xpath('''//*[@id="row1"]//span[class='highlight']''')
#
# word = []
#
# for words in highlighted:
#     word.append(words.text)
#     print(words)
#
# print(word)

###local hosted site lol ###

#threading to make it faster lul
import threading

driver.get('http://localhost:1010/')

def auto():
    for i in range(0, 500):
        word = driver.find_element_by_id('text')
        txtinput = driver.find_element_by_id('typing')

        txtinput.send_keys(word.text)
        txtinput.send_keys(Keys.ENTER)

threads = [];

for i in range(0, 10):
    thread = threading.Thread(target=auto)
    threads.append(thread)
    thread.start()
    for thread in threads:
        thread.join()


"""Python implementation of the Mader solver.

This is a Python re-implementation of the Fortran code from
`Frank Timmes' website <http://cococubed.asu.edu/research_pages/mader.shtml>`_.
Timmes' solution code is released under LA-CC-05-101.
"""

import numpy as np

def mader(t, x, p_cj, d_cj, gamma, u_piston):
    r"""Compute the rarefaction wave solution for an array of positions.

    Args:
        t (float): Time for desired solutioon (s)
        x (ndarray): Positions at which to compute the solution (cm)
        p_cj (float): Chapman-Jouget pressure (erg/cm**3)
        d_cj (float): Chapman-Jouget density (g/cm**3)
        gamma (float): ratio of specific heats :math:`\gamma \equiv c_p/c_v`
        u_piston (float): speed of piston (cm/s)

    Returns:
        tuple: A 5-tuple containing:
            - *ndarray*: u, Size nstep
            - *ndarray*: p, Size nstep
            - *ndarray*: c, Size nstep
            - *ndarray*: rho, Size nstep
            - *ndarray*: xdet, Size nstep
    """
    nstep = len(x)
    dx = (x[-1] - x[0]) / nstep
    u = np.zeros(nstep)
    p = np.zeros(nstep)
    c = np.zeros(nstep)
    rho = np.zeros(nstep)
    xdet = np.zeros(nstep)

    # There is no valid solution at t = 0
    if t <= 0:
        u[:] = np.nan
        p[:] = np.nan
        c[:] = np.nan
        rho[:] = np.nan
        xdet[:] = np.nan
    else:
        for i in range(nstep):
            xi = x[i]
            ui, pi, ci, rhoi, xdeti = rare(t, xi, dx, p_cj, d_cj, gamma, u_piston)
            u[i] = ui
            p[i] = pi
            c[i] = ci
            rho[i] = rhoi
            xdet[i] = xdeti

    return u, p, c, rho, xdet

def rare(time, xlab, dx, p_cj, d_cj, gam, u_piston):
    """Returns the rarefaction wave solution given on page 24 of fickett and
    davis.

    Args:
        time (float): Time for desired solutioon (s)
        xlab (float): Position in fixed lab frame, eularian frame (cm)
        dx (float): Width of grid cell (cm)
        p_cj (float): Chapman-jouget pressure (erg/cm**3)
        d_cj (float): Chapman-jouget density (g/cm**3)
        gam (float): Ratio of specific heats (dimensionless)
        u_piston (float): Speed of piston  (cm/s)

    Returns:
        tuple: A 5-tuple containing:
            - *float*: u, material speed (cm/s)
            - *float*: p, pressure (erg/cm**3)
            - *float*: c, sound speed (cm/s)
            - *float*: rho, mass density (g/cm**3)
            - *float*: xdet, position relative to detonation front, lagrangian
                frame (cm)
    """
    # some constants and factors
    gamp1 = gam + 1.0
    rho_0 = gamp1 * p_cj / d_cj**2
    rho_cj = rho_0 * gamp1 / gam
    c_cj = gam * d_cj / gamp1
    u_cj = d_cj / gamp1

    gamm1 = gam - 1.0
    aa = 1.0 / (2.0 * c_cj * time)
    bb = (2.0 - gamm1 * u_cj / c_cj) / gamp1
    b = 2.0 * gam / gamm1
    d = 2.0 / gamm1
    dd = 2.0 / (time*gamp1)
    ee = gamm1 * (u_cj - 2.0 * c_cj / gamm1) / gamp1
    bp1 = b + 1.0
    dp1 = d + 1.0

    um = gamm1 * (u_cj - 2.0 * c_cj / gamm1) / gamp1
    xp = 0.5 * gamp1 * time * (u_piston - um)
    xdet = d_cj * time - xlab
    dist = abs(xdet - xp)
    tol = 0.1 * dx

    # solution in the frame relative to detonation front, lagrangian frame
    x = xdet
    half = 0.5 * dx
    x1 = x - half

    # solution in the rarefaction fan
    if dist > tol and xdet > xp:
        u = dd * (x1 + half) + ee
        p = p_cj * ((aa * (x1 + dx) + bb)**bp1 - (aa * x1 + bb)**bp1) / (dx * aa * bp1)
        c = c_cj * (aa * (x1 + half) + bb)
        rho = rho_cj * ((aa * (x1 + dx) + bb)**dp1 - (aa * x1 + bb)**dp1) / (dx * aa * dp1)
    # solution if right at the transition point
    elif (dist <= tol):
        #  partial q's
        x2 = x1 + dx
        dxp = (x2 - xp)
        h = dxp / 2
        u = dd * (x1 + h) + ee
        p = p_cj * ((aa * (x1 + dxp) + bb)**bp1 - (aa * x1 + bb)**bp1) / (dxp * aa * bp1)
        c = c_cj * (aa * (x1 + h) + bb)
        rho = rho_cj * ((aa * (x1 + dxp) + bb)**dp1 - (aa * x1 + bb)**dp1) / (dxp * aa * dp1)

        # residual q's
        ur = u_piston
        pr = p_cj * (1 + gamm1 * (u - u_cj) / (2.0 * c_cj))**(2.0 * gam / gamm1)
        cr = c_cj * (1 + gamm1 * (u - u_cj) / (2.0 * c_cj))
        rhor = rho_cj * (p / p_cj)**(1.0 / gam)

        # avg q's
        u = ur + (u - ur) * 2.0 * h / dx
        p = pr + (p - pr) * 2.0 * h / dx
        c = cr + (c - cr) * 2.0 * h / dx
        rho = rho + (rho - rhor) * 2.0 * h / dx
    # solution in the constant state
    else:
        u = u_piston
        p = p_cj * (1 + gamm1 * (u - u_cj) / (2.0 * c_cj))**(2.0 * gam / gamm1)
        c = c_cj * (1 + gamm1 * (u - u_cj) / (2.0 * c_cj))
        rho = rho_cj * (p / p_cj)**(1.0 / gam)

    return u, p, c, rho, xdet


import cv2
from typing import Tuple
import os
cap = cv2.VideoCapture(0)

class ObjectsDetector:
    def __init__(self):
        self.detectors = []

    def add_classifier(self, xml_training_path: str, color: Tuple[int, int, int] ):
        self.detectors.append(
            (cv2.CascadeClassifier(xml_training_path), color)
        )

    def detect_in_image(self, img) -> None:
        # Convert into grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # Detect objects
        for detector, color in self.detectors:
            detected_objects = detector.detectMultiScale(gray, 1.1, 4)
            for (x, y, w, h) in detected_objects:
                cv2.rectangle(img, (x, y), (x+w, y+h), color, 2)

        # Display the output
        cv2.imshow('img', img)

blue  = (255, 0, 0)
red   = (0, 0, 255)
green = (0, 255, 0)

detector = ObjectsDetector()
detector.add_classifier(os.getenv("PRETRAIN") + "/lbpcascade_frontalface_improved.xml", red)
# detector.add_classifier('haarcascade_frontalface_default.xml', blue)
detector.add_classifier(os.getenv("PRETRAIN") + "/haarcascade_eye.xml", green)

while True:
    _, img = cap.read()
    detector.detect_in_image(img)

    pressed_key = cv2.waitKey(30) & 0xff
    if pressed_key == 27:
        break

cap.release()


from math import floor, pi, sqrt
import math
from random import randint, uniform
import pygame

# COLORS
BLACK = (0, 0, 0)  # background
GREY = (30, 30, 30)  # sensors
WHITE = (255, 255, 255)  # ant
YELLOW = (255, 191, 0)  # nest
GREEN = (0, 255, 0)  # food
RED = (255, 0, 0)  # trail - to nest
BLUE = (0, 0, 255)  # trail - to food

# CLOCK
CLOCK_SPEED = 100

# GRID
X_DIMENSION = 100
Y_DIMENSION = 100
RECT_SIZE = 6

# SCREEN SIZE
WIDTH = X_DIMENSION * RECT_SIZE
HEIGHT = Y_DIMENSION * RECT_SIZE

# UTIL FOR DRAWING A STARTING POSITION FOR COLONY AT POSITION
NEST_NUMBER = 1  # NUMBER OF AGENTS IN EACH NEST
NEST_SIZE = 4
# NEST_POSITION = (X_DIMENSION / 2, Y_DIMENSION / 2)
AGENTS_PER_NEST = 2  # NUMBER OF AGENTS IN EACH NEST
FOOD_CLUSTERS = 4  # NUMBER OF FOOD IN SIMULATION
FOOD_CLUSTERS_SIZE = 12  # NUMBER OF FOOD IN SIMULATION
EVAPORATION_RATE = 0.003
AGENT_ENERGY_COST = 0.99 # 1%
# DIRTY_RECTS = []
# NESTS = []
# AGENTS = []

# GENERAL METHODS

# UTIL TO CREATE A MATRIX WITH DIMENSION SIZE
def GenerateMatrix(x_dimension, y_dimension):
    return [[0 for j in range(y_dimension)] for i in range(x_dimension)]

SCREEN = pygame.display.set_mode((WIDTH, HEIGHT), vsync=1)

# UTIL TO DRAW A RECT AT AN ESPECIFIC POSITION WITH AN ESPECIFIC COLOR
def DrawRect(position, color):
    # position must be in screen domain size (and not matrix domain)
    # ie. x * RECT_SIZE
    pygame.draw.rect(
        SCREEN,
        color,
        pygame.Rect(position[0], position[1], RECT_SIZE, RECT_SIZE),
        floor(RECT_SIZE / 4),
        floor(RECT_SIZE / 2)
    )

def normalize(x, min_val, max_val):
    return 2 * (x - min_val) / (max_val - min_val) - 1

# helper for getting agent's next step
def getXYMagnitude(x, y):
    return sqrt(x**2 + y**2)

def degToRad(deg):
    return deg * pi / 180

def calculateAngle(A, B):
    # Calculate the dot product of A and B
    dotProduct = A[0] * B[0] + A[1] * B[1]

    # Calculate the magnitude of vector A
    magnitudeA = getXYMagnitude(A[0], A[1])

    # Calculate the magnitude of vector B
    magnitudeB = getXYMagnitude(B[0], B[1])

    # Calculate the cosine of the angle
    cosAngle = dotProduct / (magnitudeA * magnitudeB)

    # Calculate the angle in degrees using arccosine
    angle = degToRad(math.acos(max(-1, min(cosAngle, 1))))

    return angle

def LerpColor(color, intensity):
    # 0 - BLACK
    # 0/1 - linear interpolation
    # 1 - color
    r = BLACK[0] + min(intensity, 1) * (color[0] - BLACK[0])
    g = BLACK[1] + min(intensity, 1) * (color[1] - BLACK[1])
    b = BLACK[2] + min(intensity, 1) * (color[2] - BLACK[2])
    return (r, g, b)


import sys
from pytube import YouTube
from pytube import Playlist
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QPushButton, QLabel

count = 0

# function to name fix
def name_fix(name):
    # replace the invalid characters
    name = name.replace("/", "_")
    name = name.replace(":", "_")
    name = name.replace("?", "_")
    name = name.replace("*", "_")
    name = name.replace("<", "_")
    name = name.replace(">", "_")
    name = name.replace("|", "_")
    name = name.replace('"', "_")

    # return the new name
    return name

# function to rename the file
def new_name(name):
    # remove the file extension
    name = name.split(".")[0]

    # add the count to the file name
    name = str(count) + "_" + name

    # add the file extension
    name = name + ".mp3"

    # return the new name
    return name

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.text_box = QTextEdit(self)
        self.text_box.move(20, 20)
        self.text_box.resize(280, 40)

        self.result_label = QLabel(self)
        self.result_label.move(20, 80)
        self.result_label.resize(280, 40)
        self.result_label.setText("")

        button = QPushButton("Download", self)
        button.move(20, 120)
        button.clicked.connect(self.updateResult)

        self.setGeometry(300, 300, 320, 200)
        self.setWindowTitle("youtube playlist audio downloader")
        self.show()

        # function to download the audio playlist
    def download_audio_playlist(self, playlist_url):
        global count

        yt_playlist = Playlist(playlist_url)

        # get the playlist title
        playlist_title = yt_playlist.title

        # get the list of video URLs
        video_urls = yt_playlist.video_urls

        # loop through the list of video URLs
        for url in video_urls:
            # create a YouTube object
            yt = YouTube(url)

            # get the audio stream
            audio = yt.streams.filter(only_audio=True).first()

            # Downloading report
            self.result_label.setText("Downloading: " + yt.title)
            print("Downloading: " + yt.title)

            file = new_name(audio.default_filename)

            # download the audio file
            audio.download(name_fix(playlist_title), filename=file)

            self.result_label.setText("Downloaded")
            print("Downloaded: " + new_name(audio.default_filename))

            # increment the count
            count += 1
        print("Finshed: " + playlist_title)

        return name_fix(playlist_title)

    def updateResult(self):
        text = self.text_box.toPlainText()
        self.text_box.setEnabled(False)
        yt_tilte = self.download_audio_playlist(text)
        self.result_label.setText("Finshed: " + yt_tilte)
        self.text_box.setEnabled(True)

app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())


#!/usr/bin/env python3

"""

This file contains the functionality to identify "other" strings

Note: This is the last categorization, so anything not already will been
classified as "other". In general this will be what is usually labeled as
special characters. E.g. '!@#$%^&....' but it is labeled other to support
different languages and encodings.

"""

def other_detection(section_list):
    """
    Finds other strings in the password

    Returns:

        other_list: A list of other strings that were detected

    """

    other_list = []

    ## Do a pass through and detect other strings
    #
    # Walk through each section and parse it individually
    # Using an index since it lets me split items up while parsing the
    # whole list
    #
    index = 0
    while index < len(section_list):

        # Skip sections that have been processed earlier, for example
        # by keyboard walk detection
        if section_list[index][1] is None:

            section_list[index] = (section_list[index][0],'O' + str(len(section_list[index][0])) )
            other_list.append(section_list[index][0])

        index += 1

    return other_list


import os
import sys
from imageio import imread

class DataLoader():
    def __init__(self, original_path, label_path=None):
        # original_path: thư mục chứa ảnh gốc
        # label_path: thư mục chứa ảnh nhãn

        self._original_path = original_path
        self.label_path = label_path
        self._next_frame_idx = 0

        original_files = os.listdir(original_path) # tên các file có trong original
        original_files.sort(key=lambda file: int(file[file.find('_') + 1:file.find('.')]))
        self._original_files = original_files

        if self._label_path is not None: # kiểm tra số lượng ảnh trong original và label
            label_files = os.listdir(label_path)
            label_files.sort(key=lambda file: int(file[file.rfind('_') + 1:file.find('.')]))
            self._label_files = label_files

            if len(self._original_files) != len(self._label_files):
                sys.exit(-1)

    def get_next_frame(self):
        if self._next_frame_idx < len(self._original_files):
            # tạo path dẫn đến frame
            path_to_original_frame = os.path.join(self._original_path, self._original_files[self._next_frame_idx])
            original_frame = imread(path_to_original_frame)

            if self._label_path is not None:
                path_to_label_frame = os.path.join(self._label_path, self._label_files[self._next_frame_idx])
                label_frame = imread(path_to_label_frame)
                self._next_frame_idx += 1
                return original_frame, label_frame

            self._next_frame_idx += 1

            return original_frame
        return None

    def set_next_frame_idx(self, idx):
        self._next_frame_idx = idx

    def get_next_frame_idx(self):
        return self._next_frame_idx

    def get_nr_of_frames(self): # số lượng khung ảnh
        return len(self._original_files)

    def __iter__(self): # tạo vòng lặp
        return self

    def __next__(self): # lấy frame tiếp theo và dừng nếu không còn frame.

        frame = self.get_next_frame()

        if frame is None:
            raise StopIteration()

        return frame


from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from flask_session import Session
from config import config
import os

# Init DB
db = SQLAlchemy()

# Init Sessions
sess = Session()

def create_app(config_name):
    # Create Flask app
    app = Flask(__name__, template_folder='../frontend_simple/templates', static_folder='../frontend_simple/static')

    # Configure Flask app from Config Object
    app.config.from_object(config[config_name])

    # Config Object won't import right configs -> solution: hardcode? (this doesn't even work...)
    # Working solution:
    # set FASK_ENV=development
    # set FLASK_DEBUG=1
    app.config['ENV'] = 'development'
    app.config['DEBUG'] = True
    app.config['TESTING'] = True

    # Call initialize app from Config Object
    config[config_name].init_app(app)

    # Connect DB to Flask App
    db.init_app(app)

    # Connect Session to Flask app
    sess.init_app(app)

    return app


import typing
import copy
from dataclasses import dataclass

EPS = 'eps'
END_MARKER = '$'

@dataclass(frozen = True)
class Production:
  lhs: str
  body: tuple[str]

class Grammar:
  start_symbol: str
  productions: list[Production]
  nonterminals: set[str]
  first: dict[str, set]
  follow: dict[str, set]

  def __init__(self):
    self.start_symbol = None
    self.productions = []
    self.nonterminals = set()
    self.first = {}
    self.follow = {}

  def parse(lines: typing.Iterable[str]):
    ans = Grammar()

    for line in lines:
      line = line.strip()
      if len(line) <= 0 or line.startswith("#"):
        continue

      ans.parse_single_production(line)

    return ans

  def parse_single_production(self, line):
    lhs, rhs = line.split('->', 1)
    lhs = lhs.strip()

    if self.start_symbol is None:
      self.start_symbol = lhs

    body = [x for x in map(str.strip, rhs.split(' ')) if len(x) > 0]

    self.productions.append(Production(lhs, tuple(body)))
    self.nonterminals.add(lhs)

  def compute_production_first(self, production_body):
    first = set()

    for sym in production_body:
      if sym in self.nonterminals:
        sym_first = self.first[sym]
        first.update(sym_first)
        if EPS not in sym_first:
          break
      else:
        first.add(sym)
        if sym != EPS:
          break

    return first

  def compute_first(self):
    self.first = {
      nonterminal: set()
      for nonterminal in self.nonterminals
    }

    change = True
    while change:
      change = False
      for prod in self.productions:
        lhs_first = self.first[prod.lhs]
        old_len = len(lhs_first)

        lhs_first.update(self.compute_production_first(prod.body))

        change = change or len(lhs_first) != old_len

  def compute_follow(self):
    self.follow = {
      nonterminal: set()
      for nonterminal in self.nonterminals
    }

    self.follow[self.start_symbol].add(END_MARKER)

    change = True
    while change:
      change = False
      for prod in self.productions:
        # B -> aAb => Follow(A) contains First(b)
        for i in range(len(prod.body) - 1):
          sym = prod.body[i]
          if sym not in self.nonterminals:
            continue

          sym_follow = self.follow[sym]

          next_sym = prod.body[i + 1]

          old_len = len(sym_follow)

          if next_sym in self.nonterminals:
            sym_follow.update(self.first[next_sym])
            if EPS in sym_follow:
              sym_follow.remove(EPS)

          elif next_sym != EPS:
            sym_follow.add(next_sym)

          change = change or len(sym_follow) != old_len

        # B -> aA or B -> aAb where eps in First(b) => Follow(A) contains Follow(B)
        for i in reversed(range(len(prod.body))):
          sym = prod.body[i]

          if sym in self.nonterminals:
            sym_follow = self.follow[sym]
            old_len = len(sym_follow)

            sym_follow.update(self.follow[prod.lhs])

            change = change or len(sym_follow) != old_len
          elif sym != EPS:
            break

  def get_augmented_grammar(self) -> 'Grammar':
    """ Returns a new grammar, formed by augmenting this grammar. """

    if self.start_symbol == None:
      raise Exception("Cannot augment a grammar which has no start symbol")

    # This crap generates a new nonterminal of the form S'*
    aug_start = "S"
    while aug_start in self.nonterminals:
      aug_start = aug_start + "'"

    g = Grammar()
    g.productions = self.productions
    g.start_symbol = self.start_symbol
    g.nonterminals = self.nonterminals

    g.parse_single_production(f"{aug_start} -> {g.start_symbol}")
    g.start_symbol = aug_start
    return g


verticesInstance = Vertices(["x", "y"])

verticesInstance.add(
    name="v1",
    coordinates={"x": 0, "y": 0},
    forces={"x": 0, "y": 0},
    displacements={"x": 0, "y": 0},
    isRestricted={"x": True, "y": True},
)
verticesInstance.add(
    name="v2",
    coordinates={"x": 3, "y": 0},
    forces={"x": 0, "y": 0},
    displacements={"x": 0, "y": 0},
    isRestricted={"x": True, "y": True},
)
verticesInstance.add(
    name="v3",
    coordinates={"x": 0, "y": 4},
    forces={"x": 4.8, "y": -6.4},
    displacements={"x": 0, "y": 0},
    isRestricted={"x": False, "y": False},
)
verticesInstance.add(
    name="v4",
    coordinates={"x": 3, "y": 4},
    forces={"x": 0, "y": -6},
    displacements={"x": 0, "y": 0},
    isRestricted={"x": False, "y": False},
)

dataVertices=verticesInstance.getData()
pprint.pprint(dataVertices)

edgesInstance = Edges(dataVertices)

edgesInstance.add(
    name="e1",
    vertexFrom="v1",
    vertexTo="v2",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)
edgesInstance.add(
    name="e2",
    vertexFrom="v3",
    vertexTo="v4",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)
edgesInstance.add(
    name="e3",
    vertexFrom="v1",
    vertexTo="v3",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)
edgesInstance.add(
    name="e4",
    vertexFrom="v2",
    vertexTo="v4",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)
edgesInstance.add(
    name="e5",
    vertexFrom="v1",
    vertexTo="v4",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)
edgesInstance.add(
    name="e6",
    vertexFrom="v2",
    vertexTo="v3",
    area=10 * 10**-4,
    elasticidad=2 * 10**7,
)

dataEdgesFullData = edgesInstance.getData()
dataEdges = edgesInstance.getData()['edges']

pprint.pprint(dataEdges)


'''
Created on 2019年7月18日

@author: qiao.gu
'''
import urllib.request

class GetXueQiu(object):
    '''
    classdocs
    '''

    def __init__(self):
        '''
        Constructor
        '''
        self.number = 0
    def function(self):
#         # 同花顺-个股行情
#         url = "http://q.10jqka.com.cn/"
#         response = urllib.request.urlopen(url)
#         print(response.read().decode('utf-8'))
#         print(type(response))
        # 同花财经-行情中心
        url = "http://quotes.money.163.com/old/#query=EQA&DataType=HS_RANK&sort=PERCENT&order=desc&count=24&page=0"
        response = urllib.request.urlopen(url)
        print(response.read().decode('utf-8'))
        print(type(response))
#         # 雪球-行情中心
#         url = "https://xueqiu.com/service/v5/stock/screener/quote/list?page=1&size=90&order=desc&order_by=percent&exchange=CN&market=CN&type=sha&_=1563443941511"
#         response = urllib.request.urlopen(url)
#         print(response.read())
#         print(response.read().decode('utf-8'))
#         print(type(response))

test = GetXueQiu()
test.function()


import sys

import pytest

sys.path.append("src")

from src import util

@pytest.mark.parametrize("symbol, result", [
    ("Я", True),
    ("", False),
    (123, False),
    ("_", False),
    ("T", False),
    ("Т", True)
])
def test_is_letter(symbol, result):
    assert util.is_letter(symbol) == result

@pytest.mark.parametrize("message, result", [
    ("як0рь", True),
    ("машина", False),
    ("вреmя", True),
    ("smart", False),
    ("T", False)
])
def test_is_valid_string(message, result):
    assert util.is_valid_string(message) == result


def climbStairs(n):
    if n == 1:
        return 1

    else:
        arr = []

        for i in range(n+1):
            arr.append(None)

        arr[n] = 0
        arr[n-1] = 1
        arr[n-2] = 2

        for i in range(n-3, -1, -1):
            arr[i] = arr[i+1] + arr[i+2]

        return arr[0]

n1 = 2
n2 = 3
n3 = 5
print(climbStairs(n1))
print(climbStairs(n2))
print(climbStairs(n3))


import pytest

from plenum.test.checkpoints.helper import checkRequestCounts
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.test_node import ensureElectionsDone
from plenum.test.view_change.helper import ensure_view_change
from stp_core.loop.eventually import eventually
from plenum.test.helper import sdk_send_batches_of_random_and_check

CHK_FREQ = 5

@pytest.fixture(scope='function',
                params=['greater_than_checkpoint', 'lesser_than_checkpoint', 'equal_to_checkpoint'])
def sent_batches(request, chkFreqPatched):
    # Test with number of sent batches greater than checkpoint,
    # lesser than checkpoint and equal to checkpont.
    if request.param == 'greater_than_checkpoint':
        return CHK_FREQ + 2
    if request.param == 'lesser_than_checkpoint':
        return CHK_FREQ - 2
    if request.param == 'equal_to_checkpoint':
        return CHK_FREQ

def test_checkpoint_across_views(sent_batches, chkFreqPatched, looper, txnPoolNodeSet,
                                 sdk_pool_handle, sdk_wallet_client):
    """
    Test checkpointing across views.
    This test checks that checkpointing and garbage collection works correctly
    no matter if view change happened before a checkpoint or after a checkpoint
    """
    batch_size = chkFreqPatched.Max3PCBatchSize
    sdk_send_batches_of_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client,
                                         batch_size * sent_batches, sent_batches)

    # Check that correct garbage collection happens
    non_gced_batch_count = (sent_batches - CHK_FREQ) if sent_batches >= CHK_FREQ else sent_batches
    looper.run(eventually(checkRequestCounts, txnPoolNodeSet, batch_size * non_gced_batch_count,
                          non_gced_batch_count, retryWait=1))

    ensure_view_change(looper, txnPoolNodeSet)
    ensureElectionsDone(looper=looper, nodes=txnPoolNodeSet)
    ensure_all_nodes_have_same_data(looper, nodes=txnPoolNodeSet)

    # Check that after view change, proper clean up is done
    for node in txnPoolNodeSet:
        for r in node.replicas.values():
            assert not r.checkpoints
            # No stashed checkpoint for previous view
            assert not [view_no for view_no in r.stashedRecvdCheckpoints if view_no < r.viewNo]
            assert r._h == 0
            assert r._lastPrePrepareSeqNo == 0
            assert r.h == 0
            assert r.H == r._h + chkFreqPatched.LOG_SIZE

    checkRequestCounts(txnPoolNodeSet, 0, 0)

    # Even after view change, chekpointing works
    sdk_send_batches_of_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client,
                                         batch_size * sent_batches, sent_batches)

    looper.run(eventually(checkRequestCounts, txnPoolNodeSet, batch_size * non_gced_batch_count,
                          non_gced_batch_count, retryWait=1))

    # Send more batches so one more checkpoint happens. This is done so that
    # when this test finishes, all requests are garbage collected and the
    # next run of this test (with next param) has the calculations correct
    more = CHK_FREQ - non_gced_batch_count
    sdk_send_batches_of_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client,
                                         batch_size * more, more)
    looper.run(eventually(checkRequestCounts, txnPoolNodeSet, 0, 0, retryWait=1))


with open("day6.input") as f:
    inputd = f.readlines()

nlines = len(inputd)
total = 0
registro = ""
for i, line in enumerate(inputd):
    registro += line
    if line == "\n" or i+1 == nlines:
        distintos = set(list(registro))
        distintos.discard("\n")
        total += len(distintos)
        registro = ""
print(total)

from functools import reduce

total = 0
registro = []
for i, line in enumerate(inputd):
    registro.append(line[:-1])
    if line == "\n" or i+1 == nlines:
        registro.pop()
        intersections = reduce(lambda x, y: x.intersection(y),
                        [ set(x) for x in registro])
        total += len(intersections)
        registro = []
print(total)