"""Opta event stream data to SPADL converter."""
from typing import Any, Dict, Tuple, cast

import pandas as pd  # type: ignore
from pandera.typing import DataFrame

from . import config as spadlconfig
from .base import (
    _add_dribbles,
    _fix_clearances,
    _fix_direction_of_play,
    min_dribble_length,
)
from .schema import SPADLSchema

def convert_to_actions(events: pd.DataFrame, home_team_id: int) -> DataFrame[SPADLSchema]:
    """
    Convert Opta events to SPADL actions.

    Parameters
    ----------
    events : pd.DataFrame
        DataFrame containing Opta events from a single game.
    home_team_id : int
        ID of the home team in the corresponding game.

    Returns
    -------
    actions : pd.DataFrame
        DataFrame with corresponding SPADL actions.

    """
    actions = pd.DataFrame()

    actions['game_id'] = events.game_id
    actions['original_event_id'] = events.event_id.astype(object)
    actions['period_id'] = events.period_id

    actions['time_seconds'] = (
        60 * events.minute
        + events.second
        - ((events.period_id > 1) * 45 * 60)
        - ((events.period_id > 2) * 45 * 60)
        - ((events.period_id > 3) * 15 * 60)
        - ((events.period_id > 4) * 15 * 60)
    )
    actions['team_id'] = events.team_id
    actions['player_id'] = events.player_id

    for col in ['start_x', 'end_x']:
        actions[col] = events[col].clip(0, 100) / 100 * spadlconfig.field_length
    for col in ['start_y', 'end_y']:
        actions[col] = events[col].clip(0, 100) / 100 * spadlconfig.field_width

    actions['type_id'] = events[['type_name', 'outcome', 'qualifiers']].apply(_get_type_id, axis=1)
    actions['result_id'] = events[['type_name', 'outcome', 'qualifiers']].apply(
        _get_result_id, axis=1
    )
    actions['bodypart_id'] = events.qualifiers.apply(_get_bodypart_id)

    actions = _fix_recoveries(actions, events.type_name)
    actions = _fix_unintentional_ball_touches(actions, events.type_name, events.outcome)
    actions = (
        actions[actions.type_id != spadlconfig.actiontypes.index('non_action')]
        .sort_values(['game_id', 'period_id', 'time_seconds'])
        .reset_index(drop=True)
    )
    actions = _fix_owngoals(actions)
    actions = _fix_direction_of_play(actions, home_team_id)
    actions = _fix_clearances(actions)
    actions['action_id'] = range(len(actions))
    actions = _add_dribbles(actions)

    return cast(DataFrame[SPADLSchema], actions)

def _get_bodypart_id(qualifiers: Dict[int, Any]) -> int:
    if 15 in qualifiers or 3 in qualifiers or 168 in qualifiers:
        b = 'head'
    elif 21 in qualifiers:
        b = 'other'
    elif 20 in qualifiers:
        b = 'foot_right'
    elif 72 in qualifiers:
        b = 'foot_left'
    elif 21 in qualifiers:
        b = 'other'
    else:
        b = 'foot'
    return spadlconfig.bodyparts.index(b)

def _get_result_id(args: Tuple[str, bool, Dict[int, Any]]) -> int:
    e, outcome, q = args
    if e == 'offside pass':
        r = 'offside'  # offside
    elif e == 'foul':
        r = 'fail'
    elif e in ['attempt saved', 'miss', 'post']:
        r = 'fail'
    elif e == 'goal':
        if 28 in q:
            r = 'owngoal'  # own goal, x and y must be switched
        else:
            r = 'success'
    elif e == 'ball touch':
        r = 'fail'
    elif outcome:
        r = 'success'
    else:
        r = 'fail'
    return spadlconfig.results.index(r)

def _get_type_id(args: Tuple[str, bool, Dict[int, Any]]) -> int:  # noqa: C901
    eventname, outcome, q = args
    fairplay = 238 in q
    if fairplay:
        a = 'non_action'
    elif eventname in ('pass', 'offside pass'):
        cross = 2 in q
        freekick = 5 in q
        corner = 6 in q
        throw_in = 107 in q
        goalkick = 124 in q
        if throw_in:
            a = 'throw_in'
        elif freekick and cross:
            a = 'freekick_crossed'
        elif freekick:
            a = 'freekick_short'
        elif corner and cross:
            a = 'corner_crossed'
        elif corner:
            a = 'corner_short'
        elif cross:
            a = 'cross'
        elif goalkick:
            a = 'goalkick'
        else:
            a = 'pass'
    elif eventname == 'take on':
        a = 'take_on'
    elif eventname == 'foul' and outcome is False:
        a = 'foul'
    elif eventname == 'tackle':
        a = 'tackle'
    elif eventname in ('interception', 'blocked pass'):
        a = 'interception'
    elif eventname in ['miss', 'post', 'attempt saved', 'goal']:
        if 9 in q:
            a = 'shot_penalty'
        elif 26 in q:
            a = 'shot_freekick'
        else:
            a = 'shot'
    elif eventname == 'save':
        a = 'keeper_save'
    elif eventname == 'claim':
        a = 'keeper_claim'
    elif eventname == 'punch':
        a = 'keeper_punch'
    elif eventname == 'keeper pick-up':
        a = 'keeper_pick_up'
    elif eventname == 'clearance':
        a = 'clearance'
    elif eventname == 'ball touch' and outcome is False:
        a = 'bad_touch'
    else:
        a = 'non_action'
    return spadlconfig.actiontypes.index(a)

def _fix_owngoals(actions: pd.DataFrame) -> pd.DataFrame:
    owngoals_idx = (actions.result_id == spadlconfig.results.index('owngoal')) & (
        actions.type_id == spadlconfig.actiontypes.index('shot')
    )
    actions.loc[owngoals_idx, 'end_x'] = (
        spadlconfig.field_length - actions[owngoals_idx].end_x.values
    )
    actions.loc[owngoals_idx, 'end_y'] = (
        spadlconfig.field_width - actions[owngoals_idx].end_y.values
    )
    actions.loc[owngoals_idx, 'type_id'] = spadlconfig.actiontypes.index('bad_touch')
    return actions

def _fix_recoveries(df_actions: pd.DataFrame, opta_types: pd.Series) -> pd.DataFrame:
    """Convert ball recovery events to dribbles.

    This function converts the Opta 'ball recovery' event (type_id 49) into
    a dribble.

    Parameters
    ----------
    df_actions : pd.DataFrame
        Opta actions dataframe
    opta_types : pd.Series
        Original Opta event types

    Returns
    -------
    pd.DataFrame
        Opta event dataframe without any ball recovery events
    """
    df_actions_next = df_actions.shift(-1)
    df_actions_next = df_actions_next.mask(
        df_actions_next.type_id == spadlconfig.actiontypes.index('non_action')
    ).bfill()

    selector_recovery = opta_types == 'ball recovery'

    same_x = abs(df_actions["end_x"] - df_actions_next["start_x"]) < min_dribble_length
    same_y = abs(df_actions["end_y"] - df_actions_next["start_y"]) < min_dribble_length
    same_loc = same_x & same_y

    df_actions.loc[selector_recovery & ~same_loc, "type_id"] = spadlconfig.actiontypes.index(
        "dribble"
    )
    df_actions.loc[selector_recovery & same_loc, "type_id"] = spadlconfig.actiontypes.index(
        "non_action"
    )
    df_actions.loc[selector_recovery, ['end_x', 'end_y']] = df_actions_next.loc[
        selector_recovery, ['start_x', 'start_y']
    ].values

    return df_actions

def _fix_unintentional_ball_touches(
    df_actions: pd.DataFrame, opta_type: pd.Series, opta_outcome: pd.Series
) -> pd.DataFrame:
    """Discard unintentional ball touches.

    Passes that are deflected but still reach their target are registered as
    successful passes. The (unintentional) deflection is not recored as an
    action, because players should not be credited for it.

    Parameters
    ----------
    df_actions : pd.DataFrame
        Opta actions dataframe
    opta_type : pd.Series
        Original Opta event types
    opta_outcome : pd.Series
        Original Opta event outcomes

    Returns
    -------
    pd.DataFrame
        Opta event dataframe without any unintentional ball touches.
    """
    df_actions_next = df_actions.shift(-2)
    selector_deflected = (opta_type.shift(-1) == 'ball touch') & (opta_outcome.shift(-1))
    selector_same_team = df_actions["team_id"] == df_actions_next["team_id"]
    df_actions.loc[selector_deflected, ['end_x', 'end_y']] = df_actions_next.loc[
        selector_deflected, ['start_x', 'start_y']
    ].values
    df_actions.loc[
        selector_deflected & selector_same_team, "result_id"
    ] = spadlconfig.results.index("success")
    return df_actions


#Get weight and height from user

weight = float(input("Enter your weight in kg: "))
height = float(input("Enter your height in m: "))

#set BMI formula as a variable for following if statements

BMI = (weight) / ((height)*(height))

#if your BMI is >=30, then

if BMI >= 30:
    print(f"Your BMI of {BMI} indicates that you are obese")

#if your BMI is >=25, then

elif BMI >= 25:
    print(f"Your BMI of {BMI} indicates that you are overweight")

#if your BMI is >=18.5, then

elif BMI >= 18.5:
    print(f"Your BMI of {BMI} indicates that you are normal")

#or if your BMI is <18.5, then

else:
    print(f"Your BMI of {BMI} indicates that you are underweight")


# IMPORT THE NECESSARY FUNCTIONS
import random
import time

# DEFINTE THE FUNCTIONS THAT TURN THE CUBES
def L(cube):
    i = []
    i.append(cube[3])
    i.append(cube[2])
    i.append(cube[6])
    i.append(cube[7])
    i.append(cube[0])
    i.append(cube[1])
    i.append(cube[5])
    i.append(cube[4])
    return i

def R(cube):
    i = []
    i.append(cube[4])
    i.append(cube[5])
    i.append(cube[1])
    i.append(cube[0])
    i.append(cube[7])
    i.append(cube[6])
    i.append(cube[2])
    i.append(cube[3])
    return i

def U(cube):
    i = []
    i.append(cube[4])
    i.append(cube[0])
    i.append(cube[3])
    i.append(cube[7])
    i.append(cube[5])
    i.append(cube[1])
    i.append(cube[2])
    i.append(cube[6])
    return i

def D(cube):
    i = []
    i.append(cube[1])
    i.append(cube[5])
    i.append(cube[6])
    i.append(cube[2])
    i.append(cube[0])
    i.append(cube[4])
    i.append(cube[7])
    i.append(cube[3])
    return i

# DEFINE A PRINT CUBE FUNCTION
def print_cube(i):
    print( """
      %s-----%s
     /|    /|
    %s-----%s |
    | %s---|-%s
    |/    |/
    %s-----%s
    """ % (i[5], i[6], i[1], i[2], i[4], i[7], i[0], i[3]))

# THE ENCRYPT AND DECRYPT FUNCTIONS
def encrypt(cubes, key):
    encrypted_cubes = {}
    counter = 1
    for cube in cubes:
        time.sleep(1)
        print("""
This is the %ist cube: """ % counter), print_cube(cubes[cube])
        counter += 1
        if cube in key:
            key_list = key[cube]
            target = cubes[cube]
            for command in key_list:

                if command == 'L':
                    target = L(target)
                if command == 'R':
                    target = R(target)
                if command == "U":
                    target = U(target)
                if command == "D":
                    target = D(target)
            encrypted_cubes[cube] = target
    time.sleep(2)
    print("""
I'm going to encrypt these cubes using the following key: """, key)

    word = ''

    for cube in encrypted_cubes:
        word = word + ''.join(encrypted_cubes[cube])
    time.sleep(2)
    print("""
The resulting encrypted string is: """, word)

    return encrypted_cubes

def decrypt(cubes, key):
    decrypted_cubes = {}

    counter = 1
    for cube in cubes:
        time.sleep(1)
        print("""
This is the %ist encrypted cube: """ % counter), print_cube(cubes[cube])
        counter += 1
        if cube in key:
            key_list = key[cube]

            key_list = key_list[::-1]

            target = cubes[cube]
            for command in key_list:

                if command == 'L':
                    target = R(target)
                if command == 'R':
                    target = L(target)
                if command == "U":
                    target = D(target)
                if command == "D":
                    target = U(target)
            decrypted_cubes[cube] = target

    word = ''

    for cube in decrypted_cubes:
        word = word + ''.join(decrypted_cubes[cube])

    while word[-1] == '*':
        word = word[:-1]
    time.sleep(2)
    print("""
Decrypting the above cubes with the given key provides:
""", word)

    return decrypted_cubes

# GENERATING THE ENCRYPTION KEY
def generate_key(cubes):

    # Define the amount of cubes
    cubes_amt = len(cubes) - 1

    # Create an empty dict to store the encryption commands in for each cube
    key = {}

    # Loop over each of the cubes
    while cubes_amt >= 0:

        # Clear the encryption command
        command = []

        # Define the number of commands given to each cube, minimum of 2, maximum of 10
        i = random.randint(3, 7)

        while i > 0:

            # Randomly choose a command and add it to the list
            c = random.choice(['U', 'D', 'L', 'R'])
            command.append(c)

            i -= 1

        # Add all commands for each cube
        key[cubes_amt] = command

        cubes_amt -= 1

    return key

# ASK FOR USER INPUT
word = list(input("""
Welcome! I am going to encrypt anything you want. Please enter any string that you wish for me to secure:  """))

# CREATE NECESSARY AMOUNT OF CUBES DEPENDENT ON INPUT
cubes= {}
n = 0
cubes_amt = len(word) / 8
string = word

while cubes_amt >= 1:
    cube = string[0:8]
    string = string[8:]
    cubes[n] = cube
    cubes_amt -= 1
    n += 1

if cubes_amt < 1 and cubes_amt > 0:
    while len(string) < 8:
        string.append('*')
    cubes[n] = string

key = generate_key(cubes)

time.sleep(1)
print("""
I'm going to divide all of that up in cubes.
""")
encrypted = encrypt(cubes, key)

answer = input("""
Do you wish for me to decrypt this string again?
""")

if answer == 'yes':
    decrypt(encrypted, key)
else:
    print("""
This secret is lost forever...
""")


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the kangaroo function below.
def kangaroo(x1, v1, x2, v2):
    if (v1 - v2)==0:
        return "NO"
    e = (x2 - x1) / (v1 - v2)                        # Calculating number of jumps to meet, if that number is an integer, then meeting is possible
    if (x2>x1) and (v2>v1):                          # Returning NO if one kangaroo is ahead of another and its speed is also more than the previous kangaroo
        return "NO"
    if (x1>x2) and (v1>v2):
        return "NO"
    if e-int(e) == 0:                                # Returning YES if number of jumps is an integer
        return "YES"
    return "NO"                                      # else returning NO

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    x1V1X2V2 = input().split()

    x1 = int(x1V1X2V2[0])

    v1 = int(x1V1X2V2[1])

    x2 = int(x1V1X2V2[2])

    v2 = int(x1V1X2V2[3])

    result = kangaroo(x1, v1, x2, v2)

    fptr.write(result + '\n')

    fptr.close()

Hackerrank/Number Line Jumps/Number Line Jumps.py


#!/usr/bin/python3

#The simulation is performed on top of the casper simulation codes available from the Stanford project. (https://github.com/omoindrot/simple_casper)

import os
import numpy as np

from parameters import *
from block import Block
from utils import exponential_latency
from network import Network
from validator import VoteValidator
#from plot_graph import plot_node_blockchains
from collections import Counter
from tqdm import tqdm
from pandas import DataFrame
import random
import networkx as nx

def fraction_justified_and_finalized(validator):
    """Compute the fraction of justified and finalized checkpoints in the main chain.

    From the genesis block to the highest justified checkpoint, count the fraction of checkpoints
    in each state.
    """
    # Get the main chain
    checkpoint = validator.highest_justified_checkpoint

    count_justified = 0
    count_finalized = 0
    count_total = 0
    while checkpoint is not None:
        count_total += 1
        if checkpoint.hash in validator.justified:
            count_justified += 1
        if checkpoint.hash in validator.finalized:
            count_finalized += 1
        checkpoint = validator.get_checkpoint_parent(checkpoint)

    fraction_justified = float(count_justified) / float(count_total)
    fraction_finalized = float(count_finalized) / float(count_total)
    count_forked_justified = len(validator.justified) - count_justified
    fraction_forked_justified = float(count_forked_justified) / float(count_total)
    return fraction_justified, fraction_finalized, fraction_forked_justified

def delay_throughput(network):
    delay = {}
    Edelay = 0.0
    E2delay = 0.0
    delay_array = np.array([])
    for block_hash in network.global_finalized_time_absolute :
        delay[block_hash] = network.global_finalized_time_absolute[block_hash]  - network.first_proposal_time[block_hash]
    for block_hash in delay :
        delay_array = np.append(delay_array,delay[block_hash])
        Edelay += delay[block_hash]
        E2delay += delay[block_hash]**2
    if len(delay)>0:
        Edelay = Edelay/len(delay)
        E2delay = E2delay/len(delay)
    else:
        Edelay = Edelay
        E2delay = E2delay
    min_time = BLOCK_PROPOSAL_TIME*EPOCH_SIZE*NUM_EPOCH
    max_time = 1
    max_epoch=0
    for block_hash in network.global_finalized_time_absolute:
        if(network.global_finalized_time_absolute[block_hash]>=max_time):
            max_time = network.global_finalized_time_absolute[block_hash]
    for block_hash in network.global_finalized_time_absolute:
        if(network.first_proposal_time[block_hash]<=min_time):
            min_time = network.first_proposal_time[block_hash]
    for block_hash in network.global_finalized_time_absolute:
        if((network.processed[block_hash].height)/EPOCH_SIZE>=max_epoch):
            max_epoch = (network.processed[block_hash].height)/EPOCH_SIZE

    if len(network.global_finalized_time)>0:
        throughput = max_epoch/(max_time)       #Removed min_time
    else:
        throughput = 0  #max_time - min_time

    return Edelay, E2delay, throughput, len(network.global_finalized_time), delay_array

def timing_chain(network):
    timing = {}
    sum_timing = [0,0,0,0,0,0,0,0]
    timing_count = [0,0,0,0,0,0,0,0]
    for blockhash in network.global_finalized_time:
        timing[blockhash] = [network.first_justification_time.get(blockhash,-1), network.global_justified_time.get(blockhash,-1), \
        network.first_justified_time.get(blockhash,-1), network.last_justified_time.get(blockhash,-1), network.first_finalization_time.get(blockhash,-1), \
        network.global_finalized_time.get(blockhash,-1), network.first_finalized_time.get(blockhash,-1), network.last_finalized_time.get(blockhash,-1)  ]
    for blockhash in timing:
        for i in range(len(timing[blockhash])):
            if timing[blockhash][i] == -1:
                pass
            else:
                sum_timing[i] = sum_timing[i] + timing[blockhash][i]
                timing_count[i] = timing_count[i] + 1

    return np.array(sum_timing), np.array(timing_count)

'''

def depth_calculator(validator):
    depth_finalized = 0
    num_depth_finalized =0
    main_chain_size = validator.main_chain_size
    max_epoch=0
    for blockhash in validator.finalized:
        if validator.processed[blockhash].height > max_epoch:
            max_epoch = validator.processed[blockhash].height
        num_depth_finalized = 1
    depth_finalized = (main_chain_size - max_epoch)/EPOCH_SIZE
    return depth_finalized, num_depth_finalized

'''

def finalization_quartiles(network):
    sumquartiles = [0.0,0.0,0.0,0.0]
    sumsquarequartiles = [0.0,0.0,0.0,0.0]
    len_valid_sums = [0.0,0.0,0.0,0.0]

    Equartiles = [0.0,0.0,0.0,0.0]
    E2quartiles = [0.0,0.0,0.0,0.0]
    stdquartiles = [0.0,0.0,0.0,0.0]

    for blockhash in network.final_quartiles:
        for i in range(4):
            if len(network.final_quartiles[blockhash])>i:
                sumquartiles[i] = sumquartiles[i] + network.final_quartiles[blockhash][i]
                sumsquarequartiles[i] += network.final_quartiles[blockhash][i]**2
                len_valid_sums[i] +=1
    '''
    for i in range(4):
        if len_valid_sums[i]>0:
            Equartiles[i] = Equartiles[i]/len_valid_sums[i]
            E2quartiles[i] = E2quartiles[i]/len_valid_sums[i]
            stdquartiles[i] = E2quartiles[i] - Equartiles[i]**2
            stdquartiles[i] = np.sqrt(stdquartiles[i])
        else:
            Equartiles[i] = None
            stdquartiles[i] = None
    '''
    print(len_valid_sums)
    return sumquartiles,sumsquarequartiles,len_valid_sums

def main_chain_size(validator):
    """Computes the number of blocks in the main chain."""
    return validator.highest_justified_checkpoint.height + 1

def blocks_under_highest_justified(validator):
    """Computes the height of blocks below the checkpoint of highest height."""
    res = 0
    for bhash, b in validator.processed.items():
        if isinstance(b, Block):
            if b.height <= validator.highest_justified_checkpoint.height:
                res += 1
    return res

def total_height_blocks(validator):
    """Total height of blocks processed by the validator.
    """
    res = 0
    for bhash, b in validator.processed.items():
        if isinstance(b, Block):
            res += 1
    return res

def count_forks(validator):
    """Compute the height of forks of each size.

    Returns a dict {1: 24, 2: 5, 3: 2} for instance.
    Compute forks up until the highest justified checkpoint.
    """
    # Compute a list of the block hashes in the main chain, up to the highest justified checkpoint.
    block = validator.highest_justified_checkpoint
    block_hash = block.hash
    main_blocks = [block_hash]

    # Stop when we reach the genesis block
    while block.height > 0:
        block_hash = block.prevhash
        block = validator.processed[block_hash]
        main_blocks.append(block_hash)

    # Check that we reached the genesis block
    assert block.height == 0
    assert len(main_blocks) == validator.highest_justified_checkpoint.height + 1

    # Now iterate through the blocks with height below highest_justified
    longest_fork = {}
    for block_hash, block in validator.processed.items():
        if isinstance(block, Block):
            if block.height <= validator.highest_justified_checkpoint.height:
                # Get the closest parent of block from the main blockchain
                fork_length = 0
                while block_hash not in main_blocks:
                    fork_length += 1
                    block_hash = block.prevhash
                    block = validator.processed[block_hash]
                assert block_hash in main_blocks
                longest_fork[block_hash] = max(longest_fork.get(block_hash, 0), fork_length)

    count_forks = {}
    for block_hash in main_blocks:
        l = longest_fork[block_hash]
        count_forks[l] = count_forks.get(l, 0) + 1

    assert sum(count_forks.values()) == validator.highest_justified_checkpoint.height + 1
    return count_forks

def print_metrics_latency (G, num_tries, latencies,
                          wait_fractions, vote_as_block, immediate_vote,
                          wait_for_majority, vote_confidence, validator_set=VALIDATOR_IDS):
    # metrics for analysis
    tp      = []
    delay   = []
    depth   = []
    mcf     = []

    for latency in latencies:

        #fcsum = {}
        new_delay_list      = []
        old_delay_list      = []
        tp_list             = []
        depth_list          = []
        wait_fraction_list  = []
        MCF_list            = []

        for wf in wait_fractions:

            print('wait_fraction: {}'.format(wf))

            sum_type_1_vote         = 0
            sum_type_2_vote         = 0
            mining_ids              = [i for i in range(NUM_VALIDATORS)]
            jfsum                   = 0.0
            squarejfsum             = 0.0
            ffsum                   = 0.0
            squareffsum             = 0.0
            jffsum                  = 0.0
            squarejffsum            = 0.0
            mcsum                   = 0.0
            squaremcsum             = 0.0
            busum                   = 0.0
            squarebusum             = 0.0
            delaysum                = 0.0
            squaredelaysum          = 0.0
            throughputsum           = 0.0
            squarethroughputsum     = 0.0
            total_finalized         = 0.0
            num_finalized_tries     = 0.0
            finalization_achieved   = True
            Equartiles              = [0.0,0.0,0.0,0.0]
            E2quartiles             = [0.0,0.0,0.0,0.0]
            stdquartiles            = [0.0,0.0,0.0,0.0]
            len_valid_sums          = [0.0,0.0,0.0,0.0]
            Etiming                 = np.zeros((8))
            timing_count            = np.zeros((8))
            sml_stats               = {}
            depth_finalized         = 0
            num_depth_finalized     = 0
            delay_array = np.array([])
            mcf_hist_array = np.array([])
            prev_mc_sum = 0

            for i in range(num_tries):
                network = Network(G.adj, latency)
                validators = [VoteValidator(network,latency,wf, i,vote_as_block, immediate_vote, wait_for_majority, vote_confidence) for i in validator_set]

                for t in tqdm(range(BLOCK_PROPOSAL_TIME * EPOCH_SIZE * NUM_EPOCH)):
                #for t in range(3):
                    network.tick(sml_stats)
                    # The code below does random shuffling of mining order
                    if t%BLOCK_PROPOSAL_TIME*NUM_VALIDATORS ==0:
                        random.shuffle(mining_ids)
                        for val in validators:
                            val.mining_id = mining_ids[val.id]

                    # if t % (BLOCK_PROPOSAL_TIME * EPOCH_SIZE) == 0:
                    #     filename = os.path.join(LOG_DIR, 'plot_{:03d}.png'.format(t))
                    #     plot_node_blockchains(validators, filename)

                for val in validators:
                    jf, ff, jff = fraction_justified_and_finalized(val)
                    jfsum += jf
                    squarejfsum += jf**2
                    ffsum += ff
                    squareffsum += ff**2
                    jffsum += jff
                    squarejffsum += jff**2
                    mcsum += main_chain_size(val)
                    squaremcsum += main_chain_size(val)**2
                    busum += blocks_under_highest_justified(val)
                    squarebusum += blocks_under_highest_justified(val)**2
                    temp_depth_finalized = val.depth_finalized
                    temp_num_depth_finalized = val.num_depth_finalized
                    num_depth_finalized += temp_num_depth_finalized
                    depth_finalized += temp_depth_finalized
                    sum_type_1_vote += val.type_1_vote
                    sum_type_2_vote += val.type_2_vote

                    #fc = count_forks(val)
                    #for l in fc.keys():
                        #fcsum[l] = fcsum.get(l, 0) + fc[l]

                Edelay,E2delay,throughput,num_finalized, temp_delay_array = delay_throughput(network)
                delay_array = np.append(delay_array,temp_delay_array)
                delaysum += Edelay*num_finalized
                squaredelaysum += E2delay*num_finalized
                if num_finalized>0:
                    throughputsum +=throughput
                    num_finalized_tries = num_finalized_tries + 1
                    squarethroughputsum += throughput**2
                total_finalized += num_finalized

                tempEquartiles,tempE2quartiles,templen_valid_sums = finalization_quartiles(network)
                for i in range(4):
                    if templen_valid_sums[i]>0 :
                        Equartiles[i] += tempEquartiles[i]
                        E2quartiles[i] += tempE2quartiles[i]
                        len_valid_sums[i] += templen_valid_sums[i]

                temp_timing,temp_timing_count = timing_chain(network)
                Etiming += temp_timing
                timing_count += temp_timing_count

                mcf_hist_array = np.append(mcf_hist_array, (mcsum-prev_mc_sum)/len(validators)/NUM_EPOCH/EPOCH_SIZE)
                prev_mc_sum = mcsum

            sd_delay = 0
            if total_finalized > 0 :
                Edelay = delaysum/total_finalized
                E2delay = squaredelaysum/total_finalized
                vardelay = E2delay - Edelay**2
                sd_delay = np.sqrt(vardelay)
                Ethroughput = throughputsum/num_finalized_tries
                E2throughput = squarethroughputsum/num_finalized_tries
                varthroughput = E2throughput - Ethroughput**2
            else:
                finalization_achieved = False
                #print('No finalization Achieved')

            for i in range(4):
                if len_valid_sums[i]>0:
                    Equartiles[i] = Equartiles[i]/len_valid_sums[i]
                    E2quartiles[i] = E2quartiles[i]/len_valid_sums[i]
                    stdquartiles[i] = E2quartiles[i] - Equartiles[i]**2
                    stdquartiles[i] = np.sqrt(stdquartiles[i])
                else:
                    Equartiles[i] = None
                    stdquartiles[i] = None

            Ejf = jfsum/len(validators)
            E2jf = squarejfsum/len(validators)
            Ejff = jffsum/len(validators)
            E2jff = squarejffsum/len(validators)
            Eff = ffsum/len(validators)
            E2ff = squareffsum/len(validators)
            Emc = mcsum/len(validators)
            E2mc = squaremcsum/len(validators)
            Ebu = busum/len(validators)
            E2bu = squarebusum/len(validators)
            varjf = E2jf - Ejf**2
            varjff = E2jff - Ejff**2
            varff = E2ff - Eff**2
            varmc = E2mc - Emc**2
            varbu = E2bu - Ebu**2

            depth_finalized = depth_finalized/num_depth_finalized

            Etiming = Etiming/timing_count

            tp += [Ethroughput]
            delay += [Edelay/(Emc/(EPOCH_SIZE*NUM_EPOCH + 1))]
            depth += [depth_finalized]
            mcf += [Emc/(EPOCH_SIZE*NUM_EPOCH + 1)]

            delay_array = delay_array/(Emc/(EPOCH_SIZE*NUM_EPOCH + 1))

            delay_quartiles = [np.percentile(delay_array,25),np.percentile(delay_array,50),np.percentile(delay_array,75),np.percentile(delay_array,100)]

            print("MCF hist array:{}".format(mcf_hist_array))
            mcf_hist = np.histogram(mcf_hist_array, bins = 10, density=True)
            print("MCF hist:{}".format(mcf_hist))
            print('=== Statistics ===')
            print('Latency: {}'
                    .format(latency))
            print('Timing: {}'
                    .format(Etiming))
            print('Bar_graph: {}'
                    .format([Etiming[1], (Etiming[2]-Etiming[1]),
                            (Etiming[4]-Etiming[2]),(Etiming[5]-Etiming[4]),
                            (Etiming[6]-Etiming[5]),(Etiming[7]-Etiming[6])]))
            print('Justified in forks: {}'
                    .format([Ejff,np.sqrt(varjff)]))
            print('Main chain size (root included): {}'
                    .format([Emc,np.sqrt(varmc)]))
            print('Probability of death: {}'
                    .format(1.0 - Emc/(EPOCH_SIZE*NUM_EPOCH + 1)))  # include ROOT
            print('Blocks under main justified: {}'
                    .format([Ebu,varbu]))
            print('finalization_quartiles:{}'
                    .format([Equartiles,stdquartiles]))
            print('Main chain fraction:{}'
                    .format([Emc/(EPOCH_SIZE*NUM_EPOCH + 1),        # include ROOT
                            np.sqrt(varmc)/EPOCH_SIZE/NUM_EPOCH ]))
            print('type_1_vote: {}'.format(sum_type_1_vote))
            print('type_2_vote: {}'.format(sum_type_2_vote))

            if finalization_achieved :
                print('---new, incld. dead blocks---')
                print('Delay:{}'
                        .format(Edelay/(Emc/(EPOCH_SIZE*NUM_EPOCH + 1))))
                print('Delay:{}'.format(np.mean(delay_array)))
                print('delay_quartiles: {}'.format(delay_quartiles))
                print('sd_delay:{}'.format(sd_delay/(Emc/(EPOCH_SIZE*NUM_EPOCH + 1))))
                print('Throughput:{}'
                        .format(Ethroughput))
                print('depth:{}'
                        .format(depth_finalized))
                print('---old, ignoring dead blocks---')
                print('Delay:{}'
                        .format([Edelay,vardelay]))
                print('Throughput:{}'
                        .format([Ethroughput,varthroughput]))
            else:
                print('No finalization achieved')
            print('supermajority link stats: {}'
                    .format(dict(Counter(sml_stats.values()))))
            print('=== END === ')

            wait_fraction_list.append(wf)
            new_delay_list.append(Edelay/(Emc/(EPOCH_SIZE*NUM_EPOCH + 1)))
            old_delay_list.append(Edelay)
            tp_list.append(Ethroughput)
            depth_list.append(depth_finalized)
            MCF_list.append(Emc/(EPOCH_SIZE*NUM_EPOCH + 1))

        print('wait_fraction_list: {}'.format(wait_fraction_list))
        print('new_delay_list: {}'.format(new_delay_list))
        print('tp_list: {}'.format(tp_list))
        print('depth_list: {}'.format(depth_list))
        print('MCF_list: {}'.format(MCF_list))
        print('old_delay_list: {}'.format(old_delay_list))

        return (tp, delay, depth, mcf)

if __name__ == '__main__':
    # LOG_DIR = 'metrics'
    # if not os.path.exists(LOG_DIR):
        # os.makedirs(LOG_DIR)

    # Uncomment to have fractions of disconnected nodes
    # fractions = np.arange(0.0, 0.4, 0.05)
    # fractions = [0.31, 0.32, 0.33]
    fractions = [0.0]
    vote_as_block = False
    immediate_vote = True
    wait_for_majority = False
    vote_confidence = False

    print('``````````````````')
    print("""running test
            PROTOCOL: vote-on-majority-after-delay
            NUM_EPOCH: {}
            SUPER_MAJORITY: {}
            NUM_VALIDATORS: {}
            D_REGULAR: {}
            Vote_as_block: {}
            Immediate_vote: {}
            Wait_for_majority: {}
            Vote_confidence: {}""".
            format(NUM_EPOCH,
                   SUPER_MAJORITY,
                   NUM_VALIDATORS,
                   D_REGULAR,
                   vote_as_block,
                   immediate_vote,
                   wait_for_majority,
                   vote_confidence))
    print('``````````````````')

    for fraction_disconnected in fractions:
        num_validators = int((1.0 - fraction_disconnected) * NUM_VALIDATORS)
        validator_set = VALIDATOR_IDS[:num_validators]

        print("height of connected of nodes: {}".format(len(validator_set)))

        num_tries = 100
        #latencies = [i for i in range(10, 300, 20)] + [500, 750, 1000]
        latencies = [75]
        wait_fractions =  [0.0]

        # Graph
        # G = nx.complete_graph(num_validators)                # fully connected
        G = nx.random_regular_graph(D_REGULAR,num_validators)  # d-regular

        tp, delay, depth, mcf = print_metrics_latency(G, num_tries,latencies, \
                                                      wait_fractions,
                                                        vote_as_block,
                                                        immediate_vote,
                                                        wait_for_majority,
                                                        vote_confidence,
                                                        validator_set)

        # save data to test.xlsx
        df = DataFrame({"latency":latencies,
                        "throughput":tp,
                        "mcf": mcf,
                        "delay":delay,
                        "depth":depth
                        },
                        index = wait_fractions).T

        df.to_excel('test.xlsx',sheet_name='sheet1',index=False)


from __future__ import unicode_literals

from django.db import models
from mongoengine import *

from shopcart.models import CartItem

# Create your models here.
class Order(Document):
    user_id = LongField(required=True)
    status = StringField(required=True)
    cart_items = ListField(EmbeddedDocumentListField(CartItem))

    @classmethod
    def create_order(cls, user):
        user_id = user.id
        order = cls(user_id=user_id, status="active", cart_items=[])
        order.save()
        return order

    @classmethod
    def add_cart_item(cls, order, cart_item):
    	order.cart_items.push(cart_item)


from os import remove, makedirs
from os.path import join, dirname, expanduser, exists
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
from mycroft.messagebus.message import Message
from mycroft.util.log import LOG
import pickle
import time
import json
from threading import Thread

try:
    import face_recognition
    import cv2
    from shared_camera import Camera
except ImportError:
    # re-install yourself
    from py_msm import MycroftSkillsManager
    msm = MycroftSkillsManager()
    msm.install_by_url("https://github.com/JarbasAl/skill-face-recognition", True)
    # trigger reload
    msm.reload_skill("skill-face-recognition")

__author__ = 'jarbas'

class FaceRecognition(MycroftSkill):
    def __init__(self):
        super(FaceRecognition, self).__init__()
        self.last_user = "unknown"
        if "model_path" not in self.settings:
            self.settings["model_path"] = expanduser(
                "~/.face_recognition/face_encodings.fr")

        if "sensitivity" not in self.settings:
            self.settings["sensitivity"] = 0.5

        if "detect_interval" not in self.settings:
            self.settings["detect_interval"] = 1

        if "detect_timeout" not in self.settings:
            self.settings["detect_timeout"] = 10

        if "scan_faces" not in self.settings:
            self.settings["scan_faces"] = True

        if "hello_on_face" not in self.settings:
            self.settings["hello_on_face"] = True

        if "auto_train" not in self.settings:
            self.settings["auto_train"] = True

        if "goodbye_on_face" not in self.settings:
            self.settings["goodbye_on_face"] = True

        if "cascade" not in self.settings:
            self.settings["cascade"] = join(dirname(__file__),
                                            'haarcascade_frontalface_alt2.xml')

        if "unknown_count" not in self.settings:
            self.settings["unknown_count"] = 0

        if dirname(__file__) in self.settings["model_path"]:
            self.reload_skill = False
        if not exists(self.settings["model_path"].replace(
                "face_encodings.fr", "")):
            makedirs(self.settings["model_path"].replace(
                "face_encodings.fr", ""))

        self.vision = None
        self.last_detection = 0
        self.recognize = False
        self.known_faces = {}
        self.create_settings_meta()

    def create_settings_meta(self):
        meta = {
            "name": "Face Recognition Skill",
            "skillMetadata": {
                "sections": [
                    {
                        "name": "Model",
                        "fields": [
                            {
                                "type": "label",
                                "label": "This is where your personal face "
                                         "encodings model is saved"
                            },
                            {
                                "name": "model_path",
                                "type": "text",
                                "label": "model_path",
                                "value": "~/.face_recognition/face_encodings.fr"
                            },
                            {
                                "type": "label",
                                "label": "Threshold for considering faces "
                                         "unknown"
                            },
                            {
                                "name": "sensitivity",
                                "type": "text",
                                "label": "sensitivity",
                                "placeholder": "0.5",
                                "value": "0.5"
                            },
                            {
                                "type": "label",
                                "label": "Haar cascade for face detection"
                            },
                            {
                                "name": "cascade",
                                "type": "text",
                                "label": "cascade",
                                "value": self.settings["cascade"]
                            }
                        ]
                    },
                    {
                        "name": "Configuration",
                        "fields": [
                            {
                                "type": "checkbox",
                                "name": "auto_train",
                                "label": "Automatically add new faces to the model?",
                                "value": "true"
                            },
                            {
                                "type": "checkbox",
                                "name": "hello_on_face",
                                "label": "say hello on face departure",
                                "value": "true"
                            },
                            {
                                "type": "checkbox",
                                "name": "goodbye_on_face",
                                "label": "say goodbye on face departure",
                                "value": "true"
                            },
                            {
                                "type": "label",
                                "label": "Seconds between searching for faces"
                            },
                            {
                                "name": "detect_interval",
                                "type": "number",
                                "label": "detect_interval",
                                "placeholder": "1",
                                "value": "1"
                            },
                            {
                                "type": "label",
                                "label": "Seconds without finding a face "
                                         "needed to consider user gone"
                            },
                            {
                                "name": "detect_timeout",
                                "type": "number",
                                "label": "detect_timeout",
                                "placeholder": "10",
                                "value": "10"
                            }
                        ]
                    }

                ]
            }
        }
        meta_path = join(dirname(__file__), 'settingsmeta.json')
        if not exists(meta_path):
            with open(meta_path, 'w') as fp:
                json.dump(meta, fp)

    def initialize(self):

        def notify(text):
            self.emitter.emit(Message(text))

        self.camera = Camera(callback=notify)
        self.cascade = cv2.CascadeClassifier(self.settings["cascade"])

        self.load_encodings()

        self.detect_thread = Thread(target=self.face_detect_loop)
        self.detect_thread.setDaemon(True)
        self.detect_thread.start()

        self.detect_timer_thread = Thread(target=self.face_timer)
        self.detect_timer_thread.setDaemon(True)
        self.detect_timer_thread.start()

        LOG.info("Local Face recognition engine started")

        self.add_event("user.arrived", self.handle_arrival)
        self.add_event("user.departed", self.handle_departure)
        self.add_event("face.recognize",
                       self.handle_recognition_request)
        self.add_event("face.train",
                       self.handle_train_request)

    def handle_departure(self, message):
        if message.data["method"] != "face":
            return
        if self.settings["goodbye_on_face"]:
            name = message.data["user"]
            # TODO dialog file
            self.speak("goodbye " + name)

    def handle_arrival(self, message):
        if message.data["method"] != "face":
            return
        name = message.data["user"]
        if name in ["None", "unknown"]:
            self.settings["unknown_count"] += 1
            name = "unknown face number " + str(self.settings[
                                                    "unknown_count"])

        if self.settings["hello_on_face"]:
            # TODO dialog file
            self.speak("hello " + name)

        self.set_context("arrival_trigger")
        # auto train
        if self.vision is None:
            LOG.warning("camera feed error")
        elif self.settings["auto_train"]:
            pic = expanduser("~/tmp_face.jpeg")
            cv2.imwrite(pic, self.vision)
            result = self.recognize_encodings(pic)
            if not result["face_found_in_image"]:
                LOG.debug("possible false face detection")
            elif not result["recognized"]:
                person = self.get_response("who_are_you")
                if person:
                    self.last_user = person
                    self.train_user(person, pic)
                else:
                    self.last_user = name
                    self.train_user(name, pic)
            remove(pic)

    def get_feed(self):
        try:
            return self.camera.get().copy()
        except:
            return None

    def get_encodings(self, picture_path):
        # Load the image file
        img = face_recognition.load_image_file(picture_path)
        # Get face encodings for any faces in the uploaded image
        encodings = face_recognition.face_encodings(img)
        if len(encodings):
            return encodings[0]
        else:
            return None

    def recognize_encodings(self, picture_path, known_encodings=None):
        known_encodings = known_encodings or self.known_faces
        # Load the uploaded image file
        img = face_recognition.load_image_file(picture_path)
        # Get face encodings for any faces in the uploaded image
        unknown_face_encodings = face_recognition.face_encodings(img)

        face_found = False
        recognized = False
        person = "None"
        predictions = {}
        top_score = 0
        if len(unknown_face_encodings) > 0:
            face_found = True
            if len(known_encodings.keys()):
                known_enc = [known_encodings[enc] for enc in known_encodings]
                # See if the first face in the image matches the known face
                face_distances = face_recognition.face_distance(
                    known_enc, unknown_face_encodings[0])
                person = "unknown"
                for i, face_distance in enumerate(face_distances):
                    name = known_encodings.keys()[i]
                    score = 1 - face_distance
                    if top_score < score:
                        top_score = score
                        if score > float(self.settings["sensitivity"]):
                            person = name
                            recognized = True
                    predictions[name] = score

        # Return the result as json
        result = {
            "face_found_in_image": face_found,
            "recognized": recognized,
            "person": person,
            "score": top_score,
            "predictions": predictions
        }
        if not len(known_encodings.keys()):
            result["error"] = "no known users available"
        else:
            self.emitter.emit(Message("face.recognized", result))
        return result

    def load_encodings(self):
        try:
            with open(self.settings["model_path"], "r") as f:
                self.known_faces = pickle.load(f)
        except Exception as e:
            LOG.warning(str(e))

    def train_user(self, user, picture_path):
        if user in self.known_faces.keys():
            res = {"success": True,
                   "warning": "user already registered",
                   "user": user}
        else:
            res = {"success": True,
                   "user": user}
            try:
                self.known_faces[user] = self.get_encodings(picture_path)
                with open(self.settings["model_path"], "w") as f:
                    pickle.dump(self.known_faces, f)
            except Exception as e:
                res = {"success": False,
                       "error": "could not save face encodings",
                       "exception": str(e)}

        # emit result to internal bus
        self.emitter.emit(Message("face.trained",
                                  res))

        return res

    def handle_recognition_request(self, message):
        face = message.data.get("file")
        self.recognize_encodings(face)
        # emit result to internal bus

    def handle_train_request(self, message):
        face = message.data.get("file")
        user = message.data.get("user")
        self.train_user(user, face)

    @intent_handler(IntentBuilder("correct_name")
                    .require("my_name_is").require("arrival_trigger"))
    def handle_name_correction(self, message):
        name = message.utterance_remainder()
        if "not " in name:
            name = self.get_response("who_are_you")
            if not name:
                # TODO use dialog
                self.set_context("arrival_trigger")
                self.speak("say my name is . your name")
                return
        self.known_faces[name] = self.known_faces[self.last_user]
        self.known_faces.pop(self.last_user)
        self.last_user = name
        self.speak("i will now call you " + name)
        try:
            with open(self.settings["model_path"], "w") as f:
                pickle.dump(self.known_faces, f)
        except Exception as e:
            LOG.error("could not save face encodings: " + str(e))

    @intent_handler(IntentBuilder("recognize_face")
                    .require("recognize_my_face"))
    def handle_recognize_my_face(self, message):
        frame = self.get_feed()
        if frame is None:
            self.speak_dialog("camera.error")
        else:
            pic = expanduser("~/tmp_face.jpeg")
            cv2.imwrite(pic, frame)
            result = self.recognize_encodings(pic)
            if not result["face_found_in_image"]:
                self.speak_dialog("face.error")
            elif not result["recognized"]:
                person = self.get_response("who_are_you")
                if person:
                    self.train_user(person, pic)
                    self.set_context("arrival_trigger")
            else:
                self.speak(result["person"])
                self.set_context("arrival_trigger")
            remove(pic)

    def detect_faces(self):
        """ searches webcam for faces, returns bounding boxes """
        self.vision = self.get_feed()
        gray = cv2.cvtColor(self.vision, cv2.COLOR_BGR2GRAY)
        faces = self.cascade.detectMultiScale(gray, 1.3, 5)
        return faces

    def recognize_faces(self, faces):
        """ recognizes detected faces, notify of user arrival """
        if self.recognize:
            for (x, y, w, h) in faces:
                roi_color = self.vision[y:y + h, x:x + w]
                pic = expanduser("~/tmp.jpg")
                cv2.imwrite(pic, roi_color)
                result = self.recognize_encodings(pic)
                if not result["face_found_in_image"]:
                    LOG.error("face recognition requested in non face picture")
                    continue
                self.last_user = result["person"]
                self.emitter.emit(Message("user.arrived",
                                          {"method": "face",
                                           "user": self.last_user}))

                LOG.info("stopping face recognition")
                self.recognize = False

    def face_timer(self):
        while True:
            if not self.recognize and time.time() - self.last_detection > \
                    self.settings["detect_timeout"] and self.last_detection > 0:
                self.recognize = True
                LOG.info("face detect timeout, enabling face recognition")
                self.emitter.emit(Message("user.departed",
                                          {"method": "face",
                                           "user": self.last_user}))
            time.sleep(1)

    def face_detect_loop(self):
        while True:
            time.sleep(self.settings["detect_interval"])
            if self.settings["scan_faces"]:
                faces = self.detect_faces()
                if len(faces):
                    self.last_detection = time.time()
                    self.emitter.emit(Message("user.detected",
                                              {"method": "face",
                                               "timestamp": self.last_detection,
                                               "number": len(faces)}))
                    self.recognize_faces(faces)

    def shutdown(self):
        super(FaceRecognition, self).shutdown()
        self.detect_timer_thread.join(0)
        self.detect_thread.join(0)

def create_skill():
    return FaceRecognition()


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

# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.

import os

from fab.config.rsr.codebase import RSRCodebaseConfig

class RSRDeploymentConfig(object):

    DJANGO_LIB_PATH = 'lib/python2.7/site-packages/django'

    def __init__(self, deployment_host_paths, deployment_user, codebase_config):
        self.deployment_user = deployment_user

        self.repo_checkout_home = deployment_host_paths.repo_checkout_home
        self.repo_archives_dir  = os.path.join(self.repo_checkout_home, 'archives')

        self.rsr_archive_url            = codebase_config.rsr_archive_url
        self.unpacked_archive_dir_mask  = RSRCodebaseConfig.UNPACKED_RSR_ARCHIVE_DIR_MASK

        self.rsr_deployment_dir_name    = 'rsr_%s' % codebase_config.repo_branch_without_type
        self.rsr_deployment_home        = os.path.join(self.repo_checkout_home, self.rsr_deployment_dir_name)
        self.rsr_settings_home          = os.path.join(self.rsr_deployment_home, RSRCodebaseConfig.RSR_SETTINGS_HOME)
        self.rsr_media_root             = os.path.join(self.rsr_deployment_home, RSRCodebaseConfig.RSR_MEDIA_ROOT)
        self.current_rsr_media_root     = os.path.join(self.repo_checkout_home, 'current', RSRCodebaseConfig.RSR_MEDIA_ROOT)

        self.current_virtualenv_path    = os.path.join(deployment_host_paths.virtualenvs_home, 'current')
        self.django_media_admin_path    = os.path.join(self.current_virtualenv_path, self.DJANGO_LIB_PATH, 'contrib/admin/static/admin')
        self.rsr_static_media_home      = os.path.join(deployment_host_paths.static_media_home, 'akvo')
        self.static_media_db_path       = os.path.join(self.rsr_static_media_home, 'db')

        self.host_config_home                   = deployment_host_paths.config_home
        self.local_rsr_settings_file_name       = RSRCodebaseConfig.LOCAL_SETTINGS_FILE
        self.deployed_rsr_settings_file         = os.path.join(self.host_config_home, self.local_rsr_settings_file_name)
        self.log_file_path                      = os.path.join(deployment_host_paths.logging_home, RSRCodebaseConfig.LOG_FILE)

    @staticmethod
    def create_with(deployment_host_config, deployment_user=None):
        return RSRDeploymentConfig(deployment_host_config.host_paths,
                                   deployment_user,
                                   RSRCodebaseConfig(deployment_host_config.repository_branch))


import os

import pygame

pygame.init()

clock = pygame.time.Clock()

score = 0
sw = 800
sh= 500
win = pygame.display.set_mode((sw, sh))

walk_right = []
walk_left = []

dir = os.path.dirname(__file__)
filename = os.path.join(dir, 'media')
os.chdir(filename)

# attribute iamge files for animation
for i in range(1, 10):
    walk_right.append(pygame.image.load('R{}.png'.format(i)))

for k in range(1, 10):
    walk_left.append(pygame.image.load('L{}.png'.format(k)))
    print(k)

bg = pygame.image.load('bg.jpg')
char = pygame.image.load('standing.png')

bullet_sound = pygame.mixer.Sound("bullet.wav")
hit_sound = pygame.mixer.Sound("hit.wav")

music = pygame.mixer.music.load("music.mp3")

os.chdir(dir)

# play music forever
pygame.mixer.music.play(-1)

class player(object):
    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.v = 5
        self.is_jump = False
        self.jump_count = 10
        self.left = False
        self.right = False
        self.walk_count = 0
        self.standing = True
        self.hitbox = (self.x + 17, self.y + 11, 29, 52)

    def draw(self, win):
        if self.walk_count + 1 >= 27:
            self.walk_count = 0
        if not(self.standing):
            if self.left:
                win.blit(walk_left[self.walk_count//3], (self.x, self.y))
                self.walk_count += 1
            elif self.right:
                win.blit(walk_right[self.walk_count//3], (self.x, self.y))
                self.walk_count += 1
        else:
            if self.right:
                win.blit(walk_right[0], (self.x, self.y))
            else:
                win.blit(walk_left[0], (self.x, self.y))
        self.hitbox = (self.x + 17, self.y + 11, 29, 52)

    def hit(self):
        self.is_jump = False
        self.jump_count = 10
        self.x = 60
        self.y = 420
        self.walk_count = 0
        font1 = pygame.font.SysFont('comicsans', 100)
        text = font1.render('-5', 1, (255, 0 ,0))
        win.blit(text, (sw // 2 - (text.get_width()), sh // 2 - (text.get_height()) ))
        pygame.display.update()
        i = 0
        while i < 100:
            pygame.time.delay(10)
            i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    i = 301
                    pygame.quit()

class projectile(object):
    def __init__(self, x, y, r, color, facing,):
        self.x = x
        self.y = y
        self.r = r
        self.color = color
        self.facing = facing
        self.v = 8
        # retain direction based on direction jeff is facing.
        if jeff.left:
            self.facing = -1
        else:
            self.facing = 1

    def draw(self, win):
        pygame.draw.circle(win, self.color, (self.x, self.y), self.r)

class enemy(object):
    # attribute image files specifically for enemy animation
    os.chdir(filename)
    walk_right = []
    walk_left = []

    for o in range(1,12):
        walk_right.append(pygame.image.load('R{}E.png'.format(o)))

    for j in range(1,12):
        walk_left.append(pygame.image.load('L{}E.png'.format(j)))

    os.chdir(dir)

    def __init__(self, x, y, w, h, end):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.end = end
        self.path = [self.x, self.end]
        self.walk_count = 0
        self.v = 3
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.health = 10
        self.visible = True

    def draw(self,win):
        self.move()
        if self.visible:
            if self.walk_count +1 >= 33:
                self.walk_count = 0

            if self.v > 0:
                win.blit(self.walk_right[self.walk_count //3], (self.x, self.y) )
                self.walk_count += 1
            else:
                win.blit(self.walk_left[self.walk_count //3], (self.x, self.y) )
                self.walk_count += 1
            self.hitbox = (self.x + 17, self.y + 2, 31, 57)
            pygame.draw.rect(win, (255, 0 ,0) , (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
            pygame.draw.rect(win, (0, 123, 0) , (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))

    def move(self):
        if self.v > 0:
            if self.x  + self.v < self.path[1]:
                self.x += self.v
            else:
                self.v = self.v * -1
                self.walk_count = 0
        else:
            if self.x - self.v > self.path[0]:
                self.x += self.v
            else:
                self.v = self.v * -1
                self.walk_count = 0

    def hit(self):
        if self.health > 0:
            self.health -= 1
        else:
            self.visible = False

def redrawGameWin():
    win.blit(bg, (0,0))
    text = font.render('Score: ' + str(score), 1, (255, 255, 255))
    win.blit(text , (20, 20))
    jeff.draw(win)
    goblin.draw(win)
    for bullet in bullets:
        bullet.draw(win)
    pygame.display.update()

# mainloop
font = pygame.font.SysFont('comicsans', 30, True)
bullets = []
goblin = enemy(100, 420, 64, 64, 700)
jeff = player(20,420, 64, 64)
shoot_loop = 0
run = True

while run:
    # set FPS
    clock.tick(27)

    # allow collision damage unless goblin is dead
    if goblin.visible == True:
        if jeff.hitbox[1] < goblin.hitbox[1] + goblin.hitbox[3] and jeff.hitbox[1] + jeff.hitbox[1] > goblin.hitbox[1]:
            if jeff.hitbox[0] + jeff.hitbox[2] > goblin.hitbox[0] and jeff.hitbox[0] < goblin.hitbox[0] + goblin.hitbox[2]:
                jeff.hit()
                score -= 5

    # delay to prevent multiple bullets being shot at a time
    if shoot_loop > 0:
        shoot_loop += 1
    if shoot_loop > 1:
        shoot_loop = 0

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    # bullet damage against goblin
    for bullet in bullets:
        if goblin.visible == True:
            if bullet.y - bullet.r < goblin.hitbox[1] + goblin.hitbox[3] and bullet.y + bullet.r > goblin.hitbox[1]:
                if bullet.x + bullet.r > goblin.hitbox[0] and bullet.x+ bullet.r < goblin.hitbox[0] + goblin.hitbox[2]:
                    hit_sound.play()
                    goblin.hit()
                    score += 1
                    bullets.pop(bullets.index(bullet))

        if bullet.x < sw and bullet.x > 0:
            bullet.x += bullet.v * bullet.facing
        else:
            bullets.pop(bullets.index(bullet))

    if jeff.left:
        facing = -1
    else:
        facing = 1

    #input data
    if keys[pygame.K_SPACE] and shoot_loop == 0:
       if len(bullets) < 5:
           bullet_sound.play()
           bullets.append(projectile(round(jeff.x + jeff.w // 2), round(jeff.y + jeff.h // 2), 5, (0,0,0), facing ))
    if keys[pygame.K_LEFT] and jeff.x > jeff.v:
        jeff.x -= jeff.v
        jeff.left = True
        jeff.right = False
        jeff.standing = False
    elif keys[pygame.K_RIGHT] and jeff.x < sw - jeff.w:
        jeff.x += jeff.v
        jeff.right = True
        jeff.left = False
        jeff.standing = False
    else:
        jeff.walk_count = 0
        jeff.standing = True

    if not(jeff.is_jump):
        if keys[pygame.K_UP] and jeff.is_jump is False:
            jeff.is_jump = True
            jeff.left = False
            jeff.right = False
    else:
        if jeff.jump_count >= -10:
            neg = 1
            if jeff.jump_count < 0:
                neg = -1
            jeff.y -= (jeff.jump_count ** 2) * 0.5 * neg
            jeff.jump_count -= 1
        else:
            jeff.is_jump = False
            jeff.jump_count = 10

    redrawGameWin()
pygame.quit


import os

Import('envgeoAutorift')
envgeogrid = envgeoAutorift.Clone()
package = envgeogrid['PACKAGE']
project = 'geogrid'
envgeogrid['PROJECT'] = project
install = envgeogrid['PRJ_SCONS_INSTALL'] + '/' + package + '/' + project
initFile = '__init__.py'
if not os.path.exists(initFile):
	fout = open(initFile,"w")
	fout.write("#!/usr/bin/env python3")
	fout.close()

listFiles = ['Geogrid.py','GeogridOptical.py',initFile]
envgeogrid.Install(install,listFiles)
envgeogrid.Alias('install',install)
Export('envgeogrid')

bindingsScons = 'bindings/SConscript'
SConscript(bindingsScons,variant_dir = envgeogrid['PRJ_SCONS_BUILD'] + '/' + package + '/'  + project + '/bindings')
includeScons = 'include/SConscript'
SConscript(includeScons)
srcScons = 'src/SConscript'
SConscript(srcScons,variant_dir = envgeogrid['PRJ_SCONS_BUILD'] + '/' + package + '/'  + project + '/src')

bindingsScons1 = 'bindings/SConscript1'
SConscript(bindingsScons1,variant_dir = envgeogrid['PRJ_SCONS_BUILD'] + '/' + package + '/'  + project + '/bindings')
includeScons1 = 'include/SConscript1'
SConscript(includeScons1)
srcScons1 = 'src/SConscript1'
SConscript(srcScons1,variant_dir = envgeogrid['PRJ_SCONS_BUILD'] + '/' + package + '/'  + project + '/src')


#https://www.cnblogs.com/liulinghua90/p/9935642.html

#https://blog.csdn.net/liuyq859/article/details/78387600
import pandas as pd
import math
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
from sklearn.cluster import KMeans
df = pd.read_excel('BIM3010_Fall_2019_Homework4th.xls')
data = np.array(df.values)
#data=format(data)
nonSaverage = [] # record average number of gene expression level for non-smoker
Saverage = [] # average gene expression level for smoker
FC = [] #record fold change of each gene
Pvalue=[]
logadjPvalue = [] #record statistical significance of gene expression difference between smoker and non-smoker
DEG = [] #record differencial expression genes
for i in range(len(data)):
    nonSaverage.append(sum(data[i][3:15])/12)
    Saverage.append(sum(data[i][15:25])/10)
    fc = math.log2((sum(data[i][15:25])/10)/(sum(data[i][3:15])/12))
    FC.append(fc) #calculate fold change of each gene
    #P = stats.ttest_ind(data[i][3:15],data[i][15:25],equal_var=False).pvalue
    P = stats.ttest_ind(data[i][3:15],data[i][15:25],equal_var=False).pvalue
    Pvalue.append(P)
rankp= sorted(Pvalue)

f = 'DEG.txt'
fil=open(f,'w')
f2 = 'DEGLabel.txt'
fil2=open(f2,'w')
f3 = 'detail.txt'
fil3 = open(f3,'w+')
fil3.write(str(np.matrix(['ID','log2FC','Pvalue', '-log10adjPvalue'])))
f4 = 'DEGinfor.txt'
fil4 = open(f4,'w+')
DEGdata = []
for i in range(len(data)):
    adjP = Pvalue[i]*len(data)/(rankp.index(Pvalue[i])+1)
    logadjPvalue.append(-math.log10(adjP))

    if abs(FC[i]) >= 1 and adjP < 0.05:
        DEGdata.append(data[i][3:25])
        DEG.append(data[i][0])
        fil.write(data[i][0])
        fil.write('\n')
        fil2.write(data[i][2])
        fil2.write('\n')
    detail = np.matrix([data[i][0], FC[i], Pvalue[i], logadjPvalue[i]])
    fil3.write(str(detail))
    fil3.write('\n')
    fil4.write(data[i][0]+''+str(data[i][3:25]))
    fil4.write('\n')
print(DEGdata)

# clustering
DEG = np.array(DEGdata)
kmeans = KMeans(n_clusters = 3, random_state=0).fit(DEG)
print(kmeans.labels_)

fil.close()
fil2.close()
fil3.close()
fil4.close()
#print(FC)
#print(logadjPvalue)
#len(data)*
x1=[-1,-1]
y1=[0,3]
x2=[1,1]
y2=[0,3]
x3=[-3,6]
y3=[-math.log10(0.05),-math.log10(0.05)]
plt.plot(x1,y1,x2,y2,x3,y3,color='black',linestyle='--')
print(len(FC))
plt.scatter(FC,logadjPvalue,s=2)
plt.show()


#!/usr/env/python3

import sys
import os
import json
from pathlib import Path
from monty.os import cd
from subprocess import getoutput
from time import sleep

from ase.calculators.abacus.create_input import AbacusInput
from math import ceil, pi
import numpy as np
from ase.io import read
from ase.io.abacus import write_input_stru

HELPER = r"/WORK/nscc-gz_material_1/ICSD_vasp/abacus_calc/scripts/abacus_helper/"

def yield_stru(path):
   for i in path.rglob("*"):
       if len(i.parts) == len(path.parts) + 1:
           yield i

def _write_input(path):
    with cd(path):
        os.system("cp SCF_KPT KPT")
        ntype = getoutput("ls *.orb |wc -l")
        input = AbacusInput()
        input.set(atom_file=path.name,
                  ntype=int(ntype),
                  kpoint_file='KPT',
                  pseudo_dir='./',
                  calculation='nscf',
                  nspin=2,
                  ecutwfc=60,
                  niter=50,
                  dr2=1.0e-9,
                  ethr=1.0e-7,
                  start_charge="file",
                  out_dos=1,
                  smearing='gaussian',
                  sigma=0.02,
                  ks_solver='genelpa',
                  basis_type='lcao',
                  mixing_type='pulay',
                  mixing_beta=0.4,
                  gamma_only=0)
        input.write_input_input()
        os.system('yhbatch -N 1 abacus.sh')
        sleep(1)

def make_band_inputs(scf):
    with cd(scf):
        os.system("mv *.out ./OUT.ABACUS/")
        os.system("mv OUT.ABACUS BAND_OUT.ABACUS")
        os.system("mv INPUT BAND_INPUT")
        os.system("mv KPT BAND_KPT")
    _write_input(scf)

if __name__ == "__main__":
    args = sys.argv

    scf = Path(args[1])
    for s in yield_stru(scf):
        s = s.absolute()
        #try:
        make_band_inputs(s)
        #except:
        #    os.system(f"echo {s} >> err_dos.log")


from random import randint
playername = input('What is your name?')
print('Welcome to ice, fire, earth, air',playername,'.My name is Coderbot')
player = input('Choose ice, fire, earth, water?')
print(player, 'vs', end=' ')

chosen = randint(1,3)
#print(chosen)

if(chosen == 1):
	computer = 'ice'

elif(chosen == 2):
	computer = 'fire'

elif(chosen == 3):
	computer = 'earth'
else:
	computer = 'air'

print(computer)

if(player == computer):
	print('DRAW!')

elif(player == 'fire' and computer == 'earth'):
	print(playername,'wins!')

elif(player == 'fire' and computer == 'water'):
	print('Coderbot wins!')

elif(player == 'paper' and computer == 'rock'):
	print(playername,'wins!')

elif(player == 'paper' and computer == 'scissors'):
	print('Coderbot wins!')

elif(player == 'scissors' and computer == 'paper'):
	print(playername,'wins!')

elif(player == 'scissors' and computer == 'rock'):
	print('Coderbot wins!')

elif(player == 'p' and computer == 'r'):
	print(playername,'wins!')

elif(player == 'p' and computer == 's'):
	print('Coderbot wins!')


from tkinter import *
import webbrowser

root=Tk()
root.title("Third url try")

root.geometry("400x400")

def openUrl():
    webbrowser.open("https://www.ecosia.org","_self")

wButton=Button(root, text="Open Ecosia", command=openUrl).grid(row=3, column=0)

root.mainloop()


import pygame

class Tourelle_1:

    def __init__(self):
        self.image = pygame.image.load('image/tour_de_get.jpg')
        self.image = pygame.transform.scale(self.image, (50, 50))
        self.rect = self.image.get_rect()
        self.rect.x = -10
        self.rect.y = -10
        self.vitesse = 5
        self.degat = 10

    def MouvementDroite(self):
        if self.rect.x <= 1030:
            self.rect.x += self.vitesse

    def MouvementGauche(self):
        if self.rect.x >= 0:
            self.rect.x -= self.vitesse

    def MouvementHaut(self):
        if self.rect.y >= 0:
            self.rect.y -= self.vitesse

    def MouvementBas(self):
        if self.rect.y <=  650:
            self.rect.y += self.vitesse

    def attaquer_les_monstres(self, jeu):
        distance = 1000000
        for monstre in jeu.tout_monstre:
            if monstre.distance_joueur < distance:
                distance = monstre.distance_joueur
        for monstre in jeu.tout_monstre:
            if monstre.distance_joueur == distance:
                monstre.vie -= self.degat


import time
from ev3dev2.motor import LargeMotor, OUTPUT_A, OUTPUT_B

x = int(input())
y = int(input())

print(f"Green X={x}")
print(f"Green Y={y}")

motor1 = LargeMotor(OUTPUT_A)
motor2 = LargeMotor(OUTPUT_B)

StartX = -50
StartY = 35

UnitsPerSecond = 26.316
SecondsPerUnit = 1.0 / UnitsPerSecond

goZero = False
Simple = False

if goZero:
    motor1.on_for_seconds(100, 1.9)
    motor2.on_for_seconds(100, 1.33)
    # Therefore horizontal is 50 / 1.9 = 26.316 units/second.
    # or 35 / 1.33 = 26.316 units/second.

else:
    # Find distance we need to travel
    DistanceX = abs(x - StartX)
    DistanceY = abs(y - StartY)
    print(f"Distance to travel right {DistanceX}")
    print(f"Distance to travel down {DistanceY}")

    if (Simple):
        motor1.on_for_seconds(100, DistanceX * SecondsPerUnit)
        # For 1D robots, rotate the robot here to face down.

        motor2.on_for_seconds(100, DistanceY * SecondsPerUnit)
    else:
        # Find ratio between
        RatioX = DistanceX / (DistanceX + DistanceY)
        RatioY = DistanceY / (DistanceX + DistanceY)
        print(f"Raw Speed Right {RatioX}")
        print(f"Raw Speed Down {RatioY}")

        # Set the largest value to 100, then push the lower one up
        if max(RatioX, RatioY) == RatioX:
            diff = 1 / RatioX
            RatioX = 1
            RatioY *= diff
        else:
            diff = 1 / RatioY
            RatioY = 1
            RatioX *= diff

        print(f"Max Speed Right {RatioX}")
        print(f"Max Speed Down {RatioY}")

        # Find direct time
        import math
        Time = math.sqrt(((DistanceX * SecondsPerUnit) ** 2) + (DistanceY * SecondsPerUnit) ** 2)
        print(Time)

        motor1.on_for_seconds(RatioX * 100, Time, block=False)
        motor2.on_for_seconds(RatioY * 100, Time)


import autocomplete

def getacc(s):
    print(s)

    preds = autocomplete.split_predict(s)
    print(preds)
    if(len(preds) == 0):
        # return s.trim().split(" ").splice(-1)
        return s.strip().split()[-1]
    return preds[0][0]

autocomplete.load()

print(getacc('I am a huge agi'))


import string
from ctypes import windll
from ctypes import wintypes as w
import ctypes

# Костыль для получения дисков. Сколько не искал, видимо это best practice
def getDrives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.ascii_uppercase:
        if bitmask & 1:
            drives.append(f'{letter}:\\')
        bitmask >>= 1
    return drives

# Получение информации о диске
def getInfo(drives):
    dll = ctypes.WinDLL('kernel32', use_last_error=True)
    dll.GetVolumeInformationW.argtypes = w.LPCWSTR, w.LPWSTR, w.DWORD, w.LPDWORD, w.LPDWORD, w.LPDWORD, w.LPWSTR, w.DWORD
    dll.GetVolumeInformationW.restype = w.BOOL

    volumeName = ctypes.create_unicode_buffer(w.MAX_PATH + 1)
    fileSystemName = ctypes.create_unicode_buffer(w.MAX_PATH + 1)

    serialNumber = w.DWORD()
    maxComponentLength = w.DWORD()
    fileSystemFlags = w.DWORD()

    dll.GetDiskFreeSpaceExW.argtypes = (ctypes.c_wchar_p,) + (ctypes.POINTER(ctypes.c_ulonglong),) * 3

    result = []

    for drive in drives:
        _ = ctypes.c_ulonglong()
        total = ctypes.c_ulonglong()
        free = ctypes.c_ulonglong()

        dll.GetDiskFreeSpaceExW(
            drive,
            ctypes.byref(_),
            ctypes.byref(total),
            ctypes.byref(free)
        )

        dll.GetVolumeInformationW(
            drive,
            volumeName,
            ctypes.sizeof(volumeName),
            ctypes.byref(serialNumber),
            ctypes.byref(maxComponentLength),
            ctypes.byref(fileSystemFlags),
            fileSystemName,
            ctypes.sizeof(fileSystemName)
        )

        # Текстовая информация
        result.append(
            f'Диск {drive}\n'
            f'\tМетка тома - {volumeName.value}\n'
            f'\tТип файловой системы - {fileSystemName.value}\n'
            f'\tРазмер - {maxComponentLength.value}\n'
            f'\tСвободное пространство - {free.value}\n'
        )
    return result

# Вывод информации
for driveInfo in getInfo(getDrives()):
    print(driveInfo)


from MainFuncs import prepare_train_input_for_C_Models as prep
from MainFuncs import get_list_of_dictionaries as dicts
from MainFuncs import make_vector_by_category as m
from CombinationModule import combine_text_to_network_vector as comb
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.optimizers import SGD
import numpy as np

input_data = []
output_data = []
seasons = ['winter', 'spring', 'summer', 'autumn']

countries = []
accomodation = ['hotel', 'hostel', 'luxury hotel', 'apartment', 'economy_hotel', 'camping']
transport = ['car', 'motorcycle', 'bus', 'train', 'public_transport', 'bicycle', 'hitch_hiking']

def make_train_output(text):
    result1 = [0] * len(countries)
    result2 = [0] * len(accomodation)
    result3 = [0] * len(transport)

    a = text.split(' ')
    country = a[0]
    acc = a[1]
    transp = a[2]

    for i in range(0, len(countries)):
        if country == countries[i]:
            result1[i] = 1
            break
    for i in range(0, len(accomodation)):
        if acc == accomodation[i]:
            result2[i] = 1
            break
    for i in range(0, len(transport)):
        if transp == transport[i]:
            result3[i] = 1
            break
    result = result1 + result2 + result3
    print('Output: ', result)
    return result

def vectorise_season(word):
    result = [0, 0, 0, 0]
    for i in range(0, len(seasons)):
        if word == seasons[i]:
            result[i] = 1
    return result

def make_train_input(path):
    x = ''
    element = ''
    for word in open(path).read():
        if word != '\n':
            element += word
        else:
            x += element + ' ,'
            element = ''
    a = x.split(' ,')
    del a[len(a) - 1]
    for i in range(0, len(a)):
        request = ''
        season = ''
        ans = ''
        inp = a[i]
        index = 0
        for j in range(1, len(inp)):
            if inp[j] == ']':
                index = j
                break
            else:
                ans += inp[j]
        for j in range(index + 1, len(inp)):
            if inp[j] != '(':
                request += inp[j]
            else:
                season = inp[j + 1:len(inp) - 1]
                break
        input_data.append(comb(request) + vectorise_season(season))
        print(comb(request) + vectorise_season(season))
        output_data.append(make_train_output(ans))

def prepare_countries():
    c = open('countries').read()
    x = ''
    element = ''
    for word in c:
        if word != '\n':
            element += word
        else:
            x += element + ' ,'
            element = ''
    a = x.split(' ,')
    del a[len(a) - 1]
    for v in a:
        countries.append(v)

prepare_countries()
make_train_input('Initial_response_Data')

X1 = np.array(input_data)
Y1 = np.array(output_data)
model1 = Sequential()
model1.add(Dense(50, input_dim=len(dicts()) + 4))
model1.add(Activation('relu'))
model1.add(Dense(len(countries) + len(transport) + len(accomodation)))
model1.add(Activation('sigmoid'))
sgd = SGD(lr=0.1)
model1.compile(loss='mean_squared_error', optimizer=sgd)
model1.fit(X1, Y1, batch_size=1, nb_epoch=10)
model1.save('Initial_Response_Model_Traveling')

def find_max(array):
    index = 0
    a = make_a(array)
    max = a[index]
    response = []
    for i in range(0, len(a)):
        if a[i] > max:
            max = a[i]
            index = i
    response.append(max)
    response.append(index)
    return response

def make_a(arrat):
    res = [0] * len(arrat)
    for i in range(0, len(arrat)):
        res[i] = arrat[i]
    return res

def compile_response(array):
    cntrs = array[:len(countries)]
    hotels = array[len(countries):len(accomodation) + len(countries)]
    transp = array[len(accomodation) + len(countries):]
    response = ''
    response += 'Good variant will be ' + countries[find_max(cntrs)[1]] \
                + ', suggest you living in a ' + accomodation[find_max(hotels)[1]] \
                + ' , and your transport is ' + transport[find_max(transp)[1]] + '.'
    return response


# CircuitPython demo - Dotstar
import time

import adafruit_fancyled.adafruit_fancyled as fancy

import adafruit_dotstar
import board

# Declare a 6-element RGB rainbow palette
palette = [fancy.CRGB(1.0, 0.0, 0.0),  # Red
           fancy.CRGB(0.5, 0.5, 0.0),  # Yellow
           fancy.CRGB(0.0, 1.0, 0.0),  # Green
           fancy.CRGB(0.0, 0.5, 0.5),  # Cyan
           fancy.CRGB(0.0, 0.0, 1.0),  # Blue
           fancy.CRGB(0.5, 0.0, 0.5)]  # Magenta

def rainbow_cycle(wait, num_pixels, pixels):
    offset = 0
    for j in range(255):
        for i in range(num_pixels):
            # Load each pixel's color from the palette using an offset, run it
            # through the gamma function, pack RGB value and assign to pixel.
            offset = j / 255.0
            color = fancy.palette_lookup(palette, offset + i / num_pixels)
            color = fancy.gamma_adjust(color, brightness=0.50)
            pixels[i] = color.pack()

        pixels.show()
        time.sleep(wait)


# %% [markdown]
# (imperative_workflow)=
#
# # Imperative Workflows
#
# ```{eval-rst}
# .. tags:: Basic
# ```
#
# Workflows are commonly created by applying the `@workflow` decorator to Python functions.
# During compilation, this involves processing the function's body and utilizing subsequent calls to
# underlying tasks to establish and record the workflow structure. This approach is known as declarative
# and is suitable when manually drafting the workflow.
#
# However, in cases where workflows are constructed programmatically, an imperative style is more appropriate.
# For instance, if tasks have been defined already, their sequence and dependencies might have been specified
# in textual form (perhaps during a transition from a legacy system).
# In such scenarios, you want to orchestrate these tasks.
# This is where Flyte's imperative workflows come into play, allowing you to programmatically construct workflows.
#
# To begin, import the necessary dependencies.
# %%
from flytekit import Workflow

# %% [markdown]
# We import the `slope` and `intercept` tasks from the `workflow.py` file.
# %%
from .workflow import intercept, slope

# %% [markdown]
# Create an imperative workflow.
# %%
imperative_wf = Workflow(name="imperative_workflow")

# %% [markdown]
# Add the workflow inputs to the imperative workflow.
# %%
imperative_wf.add_workflow_input("x", list[int])
imperative_wf.add_workflow_input("y", list[int])

# %% [markdown]
# ::: {note}
# If you want to assign default values to the workflow inputs,
# you can create a {ref}`launch plan <launch_plan>`.
# :::
#
# Add the tasks that need to be triggered from within the workflow.
# %%
node_t1 = imperative_wf.add_entity(slope, x=imperative_wf.inputs["x"], y=imperative_wf.inputs["y"])
node_t2 = imperative_wf.add_entity(
    intercept, x=imperative_wf.inputs["x"], y=imperative_wf.inputs["y"], slope=node_t1.outputs["o0"]
)

# %% [markdown]
# Lastly, add the workflow output.
# %%
imperative_wf.add_workflow_output("wf_output", node_t2.outputs["o0"])

# %% [markdown]
# You can execute the workflow locally as follows:
# %%
if __name__ == "__main__":
    print(f"Running imperative_wf() {imperative_wf(x=[-3, 0, 3], y=[7, 4, -2])}")

# %% [markdown]
# :::{note}
# You also have the option to provide a list of inputs and
# retrieve a list of outputs from the workflow.
#
# ```python
# wf_input_y = imperative_wf.add_workflow_input("y", list[str])
# node_t3 = wf.add_entity(some_task, a=[wf.inputs["x"], wf_input_y])
# ```
#
# ```python
# wf.add_workflow_output(
#     "list_of_outputs",
#     [node_t1.outputs["o0"], node_t2.outputs["o0"]],
#     python_type=list[str],
# )
# ```
# :::


#Ex05
# Altere o programa anterior permitindo ao usuário informar as populações e as taxas de crescimento iniciais. Valide a entrada e permita repetir a operação.

print("\nCálculo de crescimento populacional.")
print("Insira 2 (duas) populações e 2 (duas) taxas de crescimento.\n")
print("Obs: Para realizar a operação, a taxa de crescimento da menor população precisa ser maior.\n")

ano = 0

while True:
    pop1 = float(input("Informe a população do país com maior taxa de crescimento: "))
    taxapop1 = float(input("Informe a taxa de crescimento populacional do país acima: "))
    pop2 = float(input("Informe a população do segundo país: "))
    taxapop2 = float(input("Informe a taxa de crescimento populacional do país acima: "))

    if pop1 > pop2:
        print("Impossível calcular: a população do primeiro país já é maior.")
        print("Tente novamente.\n")
        continue
    elif taxapop1 < taxapop2:
        print("Impossível calcular: a taxa de crescimento populacional do primeiro país é menor.")
        print("Tente novamente.\n")
        continue
    else:
        while pop1 <= pop2:
            pop1 += pop1 * (taxapop1 * 0.01)
            pop2 += pop2 * (taxapop2 * 0.01)
            ano += 1
        print(f"A população do primeiro país vai ultrapassar a do segundo em {ano} anos.")
        break


# CONVEX HULL IMPLEMENTATION USING GRAHAM SCAN ALGORITHM.
# APPLICATION :
# SELF DRIVING CARS(COLLISION AVOIDANCE),OBJECT TRACKING , EPIDEMIC SPREAD EXTENT , CALCULATING THE AREA OF CONTAINMENT ZONE TO MITIGATE PANDEMICS
# , IMAGE PROCESSING , PACKAGING ETC.
#

import numpy as np
import matplotlib.pyplot as plt
import math
import matplotlib
class Hull:
    def __init__(self):
        self.points = [] #GRAPH POINTS
        self.stack = [] #MAINTING A STACK OF EXPLORED POINTS SATISFYING THE CCW CONDITION

    def insert(self,point):
        #INSERTING THE POINTS
        if not point is None:
            self.points.append(point)

    def sort(self):
        #THIS FUNCTION SORTS THE POINTS FIRST , BASED ON THE Y COORDINATE OF POINTS AND THEN BASED ON THE POLAR ANGLE MADE BY EVERY OTHER POINT
        #WITH THE POINT WITH LOWEST Y COORDINATE .
        def fun(x):
            return x[1]
        ar = sorted(self.points,key=fun)
        start = ar[0] #POINT WITH LOWEST Y COORDINATE POINT
        def fun2(x):
            return self.slope(start,x) #CALCULATING THE POLAR ANGLE OF REST OF POINT WITH RESPECT TO THE POINT WITH LOWEST Y COORDINATE
        return sorted(ar[1:],key=fun2),start

    def slope(self,point1,point2):
        return math.atan2((point2[1] - point1[1]),(point2[0] - point1[0])) #POLAR SLOPE OF THE POINTS
    def calc_slope_btw_last_three_points(self):

        #CALCULATING THE RELATIVE CCW ROTATION EXTENT
        length = len(self.stack)-1
        p = self.stack[length-2]
        q = self.stack[length-1]
        r = self.stack[length]
        return (q[1] - p[1])*(r[0] - q[0]) - (r[1] - q[1])*(q[0] - p[0])
        # return self.slope(self.stack[length-2],self.stack[length-1]) - self.slope(self.stack[length-1],self.stack[length])

    def hull(self):
        #MAIN FUNCTION
        sorted_array,start =self.sort()
        self.stack.append(start) #APPENDING THE START POINT INTO STACK
        for i in range(0,len(sorted_array)): #ITERATING OVER THE POINTS
            self.stack.append(sorted_array[i])
            # print(self.stack)
            while len(self.stack)>2 and not self.calc_slope_btw_last_three_points()<0: #CONTINUOUSLY ASSESING THE STACK POINTS FOR THE CCW ROTATION IF NOT DROPPING THE POINTS
                del self.stack[-2]
            yield self.stack #USED FOR ANIMATING DISPLAY USING MATPLOTLIB

    def animate(self,i):
        #FUNCTION FOR PLOTTING THE AS ALGORITHM INPUTS POINTS INTO STACK.

        plt.cla() #CLEARING THE PLOT EACH TIME SO AS TO CREATE A ANIMATING APPEAL

        plt.plot(np.array(self.points)[:,0],np.array(self.points)[:,1],'o') #PLOTTING THE GRAPH POINTS

        plt.plot(np.array(self.stack)[:,0],np.array(self.stack)[:,1],'k-') #PLOTTING THE LINE THROUGH THE POINTS IN THE STACK

        plt.title("Grapham Scan Algorithm , For Convex Hull") #TITLE

    def __str__(self):
        string = ""
        for i in self.stack:
            string+=str('('+str(i[0])+' '+str(i[1])+')')
        return string

hull = Hull()
points = np.random.rand(50, 2) #GENERATING SOME RANDOM DATA POINTS TO SURROUND THEM WITH CONVEX HULL

#INITIAL DATA USED FOR TESTING THE ALGORITHM PERFORMANCE

# points = [[0, 3], [1, 1], [2, 2], [4, 4], [0, 0], [1, 2], [3, 1], [3, 3]]

for i in points:
    hull.insert(i)#INSERTING THE DATA INTO CLASS'S POINTS LIST

ani = matplotlib.animation.FuncAnimation(plt.gcf(),hull.animate,hull.hull) #MATPLOTLIB FUNCTION USED FOR ANIMATING THE PLOTS.

plt.show()


countries = {"Казахстан":{"Численность":"17","Столица":"Астана","Площадь":"2725000"},"Россия":{"Численность":"144","Столица":"Москва","Площадь":"17100000"},"США":{"Численность":"325","Столица":"Вашингтон","Площадь":"29834000"}}

def main():
    while True:
        switch = input("Введите комманду:\nadd - добавить страну \ndelete - удалить страну\n")
        if switch == "add":
            add()
        if switch == "delete":
            delete()
        if switch == "print":
            print_dict()
        else:
            print("Error")
            main()

def add():
    country_name = input("Введите название страны")
    country_pupils = input("Введите численность")
    country_capital = input("Введите столицу")
    country_S = input("Введите площадь")
    countries[country_name] = {"Численность":country_pupils,"Столица":country_capital,"Площадь":country_S}

def delete():
    element = input("Введите страну которую хотите удалить")

def print_dict():
    for key, value in countries.items():
        print(key, "-", value)

main()


import pygame
import sound_stream
import sound_bank
import interactive
import keyboard
import sound_bank
pygame.font.init()

#Define the initial conditions and create presets
L = 0.66     #longitude
d = 0.15     #distance
h =0.1       #height
b = 0.008    #stiffnes
gamma = 1    #damping

conditions_guit1 = [L, d, h, b, gamma]
conditions_guit2 = [0.66, 0.33, 0.1, 0.02, 4]
conditions_bell = [0.66, 0.33, 0.1, 0.5, 3]
conditions_bass = [1, 0.33, 0.2, 0.005, 0.6]
conditions_violin = [0.4, 0.15, 0.1, 0, 0.2]

presets = [conditions_guit1, conditions_guit2, conditions_bell, conditions_bass, conditions_violin]
presets_names = {'Guitar 1': conditions_guit1,
				 'Guitar 2': conditions_guit2,
				 'Bell': conditions_bell,
				 'Bass':conditions_bass,
				 'Violin': conditions_violin,
				 }
instrument_index = 0

#Starting parameters
vol = 1
octav = 1
presicion = 25
time = 2

sound_synth = [conditions_guit1, vol, octav, presicion, time]  #Starting point

#Load all the images and buttons
WIDTH, HEIGHT = 350,200
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
WHITE = (255,255,255)
BLACK = (0,0,0)
WHITE_KEY_WIDTH = 25
WHITE_KEY_HEIGHT = 70
BLACK_KEY_WIDTH = 18
BLACK_KEY_HEIGHT = 40
KEYBOARD_POSITION = [20,110]
NUM_KEYS = 10  #White Keys

BACKGROUND = pygame.image.load('images/background.png')
BUTTON_IMAGE_UP = pygame.image.load('images/button_up.png').convert_alpha()
BUTTON_IMAGE_DOWN = pygame.image.load('images/button_down.png').convert_alpha()
BUTTON_IMAGE_UP_PRESS = pygame.image.load('images/button_up_press.png').convert_alpha()
BUTTON_IMAGE_DOWN_PRESS = pygame.image.load('images/button_down_press.png').convert_alpha()
LOADING_IMAGE = pygame.image.load('images/loading.png').convert_alpha()
UPDATE_IMAGE = pygame.image.load('images/button_upload.png').convert_alpha()
UPDATE_IMAGE_PRESS = pygame.image.load('images/button_upload_press.png').convert_alpha()
ICON = pygame.image.load('images/icon.png')

BUTTON_UP_1 = interactive.Button(82, 55, BUTTON_IMAGE_UP, BUTTON_IMAGE_UP_PRESS, 0.08)
BUTTON_UP_2 = interactive.Button(235, 55, BUTTON_IMAGE_UP, BUTTON_IMAGE_UP_PRESS, 0.08)

BUTTON_DOWN_1 = interactive.Button(82, 70, BUTTON_IMAGE_DOWN, BUTTON_IMAGE_DOWN_PRESS, 0.08)
BUTTON_DOWN_2 = interactive.Button(235, 70, BUTTON_IMAGE_DOWN, BUTTON_IMAGE_DOWN_PRESS, 0.08)

BUTTON_UPDATE = interactive.Button(310, 150, UPDATE_IMAGE, UPDATE_IMAGE_PRESS, 0.15)

LOADING = interactive.Loading(330,180, LOADING_IMAGE,0.15, 0)

SLIDER = interactive.Slider(310,40, 30,70)

font = pygame.font.Font('images/Closeness.ttf', 16)
font2 = pygame.font.Font('images/Closeness.ttf', 12)

pygame.display.set_caption('Synth')
pygame.display.set_icon(ICON)

#Loading objects
sound_state = sound_stream.Load()  #Handle loading the sounds

sound_state.load_sound(sound_synth)  #Load the starting sound

playing = sound_stream.Play_Sounds(256, 0, 20000)  #Create object to play the sounds

def draw_window(white_keys, black_keys,new_white, new_black, instrument, octave):
	WIN.blit(BACKGROUND, (0,0))

	#Draw the white keys
	for key in white_keys:
		pygame.draw.rect(WIN, WHITE, key)

	#Draw press white keys
	if len(new_white) != 0:
		for i in range(len(new_white)):
			pygame.draw.rect(WIN, (209, 209, 209), new_white[i])

	#Draw black keys
	for i in range(len(black_keys)):
		if i not in (2,6,9,12):  #Exception starting in do
			pygame.draw.rect(WIN, BLACK, black_keys[i])

	#Draw the borders
	pygame.draw.line(WIN, BLACK,KEYBOARD_POSITION, (KEYBOARD_POSITION[0] , KEYBOARD_POSITION[1] + WHITE_KEY_HEIGHT), width=2)
	pygame.draw.line(WIN, BLACK,(KEYBOARD_POSITION[0], KEYBOARD_POSITION[1] + WHITE_KEY_HEIGHT), (KEYBOARD_POSITION[0] + (WHITE_KEY_WIDTH * NUM_KEYS) , KEYBOARD_POSITION[1] + WHITE_KEY_HEIGHT), width=2)
	pygame.draw.line(WIN, BLACK,(KEYBOARD_POSITION[0] + (WHITE_KEY_WIDTH * NUM_KEYS), KEYBOARD_POSITION[1]), (KEYBOARD_POSITION[0] + (WHITE_KEY_WIDTH * NUM_KEYS) , KEYBOARD_POSITION[1] + WHITE_KEY_HEIGHT), width=2)
	for i in range(1,NUM_KEYS):
		pygame.draw.line(WIN, BLACK,(KEYBOARD_POSITION[0] + WHITE_KEY_WIDTH * i, KEYBOARD_POSITION[1]), (KEYBOARD_POSITION[0] + WHITE_KEY_WIDTH * i, KEYBOARD_POSITION[1] + WHITE_KEY_HEIGHT), width=2)

	#Draw press black key
	if len(new_black) != 0:
		for i in range(len(new_black)):
			pygame.draw.rect(WIN, (54, 54, 54), new_black[i])

	#Instrument selection
	actual_instrument = font.render(instrument, True, (255,255,255))
	WIN.blit(actual_instrument, (10,60))

	#Octave selection
	oct_name = font.render('Octave ' + str(octave), True, (255,255,255))
	WIN.blit(oct_name, (150,60))

	#Volume
	vol = font2.render('Volume', True, (255,255,255))
	WIN.blit(vol, (300,15))

def keys_press(keys_to_check):
	key_check = keys_to_check
	press = ''
	for key in key_check:
		if keyboard.is_pressed(key):
			press += key
	return press

def main():
	global sound_synth
	global presets
	global presets_names
	global instrument_index
	global vol

	#Draw black and white keys
	white_keys = []
	white_keys_position = [KEYBOARD_POSITION[0] + i * WHITE_KEY_WIDTH for i in range(NUM_KEYS)]
	for i in range(NUM_KEYS):
		white_keys.append(pygame.Rect(white_keys_position[i], KEYBOARD_POSITION[1], WHITE_KEY_WIDTH, WHITE_KEY_HEIGHT))

	black_keys = []
	for i in range(NUM_KEYS - 1):
		black_keys.append(pygame.Rect(white_keys_position[i] + WHITE_KEY_WIDTH//1.5, KEYBOARD_POSITION[1], BLACK_KEY_WIDTH, BLACK_KEY_HEIGHT))

	run = True
	while run:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False

		#Draw black and white keys when pressed
		keys_white = keys_press(['a', 's','d','f','g','h','j','k','l',';'])  #ENG Keyboard
		press_white_key = []

		notes_ref = {
				'a':[0,'do'],
				's':[1,'re'],
				'd':[2,'mi'],
				'f':[3,'fa'],
				'g':[4,'sol'],
				'h':[5,'la'],
				'j':[6,'si'],
				'k':[7,'doh'],
				'l':[8,'reh'],
				';':[9,'mih']}

		if len(keys_white) != 0:
			if len(keys_white) == 1:
				new_white = pygame.Rect(white_keys_position[notes_ref[keys_white][0]], KEYBOARD_POSITION[1], WHITE_KEY_WIDTH, WHITE_KEY_HEIGHT)
				press_white_key.insert(0, new_white)

			else:
				for i in range(len(keys_white)):
					new_white = pygame.Rect(white_keys_position[notes_ref[keys_white[i]][0]], KEYBOARD_POSITION[1], WHITE_KEY_WIDTH, WHITE_KEY_HEIGHT)
					press_white_key.insert(i, new_white)

		keys_black = keys_press(['w', 'e','t','y','u','o','p'])
		press_black_key = []

		notes_ref_b = {
					'w':[0,'do#'],
					'e':[1,'re#'],
					't':[3,'fa#'],
					'y':[4,'sol#'],
					'u':[5,'sib'],
					'o':[7,'do#h'],
					'p':[8,'re#h']}

		if len(keys_black) != 0:
			if len(keys_black) == 1:
				new_black = pygame.Rect(white_keys_position[notes_ref_b[keys_black][0]] + WHITE_KEY_WIDTH//1.5,KEYBOARD_POSITION[1], BLACK_KEY_WIDTH, BLACK_KEY_HEIGHT)
				press_black_key.insert(0, new_black)

			else:
				for i in range(len(keys_black)):
					new_black = pygame.Rect(white_keys_position[notes_ref_b[keys_black[i]][0]] + WHITE_KEY_WIDTH//1.5, KEYBOARD_POSITION[1], BLACK_KEY_WIDTH, BLACK_KEY_HEIGHT)
					press_black_key.insert(0, new_black)

		#Draw current octave and preset
		octave = sound_synth[2]

		for name_preset in presets_names:
			if sound_synth[0] == presets_names[name_preset]:
				instrument = name_preset

		draw_window(white_keys, black_keys, press_white_key, press_black_key, instrument, octave)

		#Change sound preset
		if BUTTON_UP_1.draw(WIN):
			instrument_index += 1
			if instrument_index >= len(presets):
				instrument_index = 0
			sound_synth[0] = presets[instrument_index]

		if BUTTON_DOWN_1.draw(WIN):
			instrument_index -= 1
			if instrument_index == -(len(presets)):
				instrument_index = 0
			sound_synth[0] = presets[instrument_index]

		#Change octave
		if BUTTON_UP_2.draw(WIN):
			sound_synth[2] += 1
			if sound_synth[2] > 3:
				sound_synth[2] = 3

		if BUTTON_DOWN_2.draw(WIN):
			sound_synth[2] -= 1
			if sound_synth[2] < 0:
				sound_synth[2] = 0

		#Change volume
		if SLIDER.draw(WIN):
			sound_synth[1] = 2 * vol * SLIDER.volume()

		#Add the changes made by the user
		if not sound_state.loading():
			if BUTTON_UPDATE.draw(WIN):
				sound_state.load_sound(sound_synth)
			text = font2.render('Update', True, (255,255,255))
			WIN.blit(text, (300,170))

		detect = ['a','w','s', 'e','d','f','t','g','y','h','u','j','k','o','l','p',';']
		keys = keys_press(detect)

		#Show animation while loading sounds
		if sound_state.loading():
			keys = ''  #While loading can't access the sound part of the program
			LOADING.draw(WIN,3)
			LOADING.angle += 1

		pygame.display.update()

		#Detect key press and play the sound
		letter_to_note = {
					'a' : 0,
					'w' : 1,
					's' : 2,
					'e' : 3,
					'd' : 4,
					'f' : 5,
					't' : 6,
					'g' : 7,
					'y' : 8,
					'h' : 9,
					'u' : 10,
					'j' : 11,
					'k' : 12,
					'o' : 13,
					'l' : 14,
					'p' : 15,
					';' : 16}

		notes = []

		if len(keys) == 1:
			notes.insert(0,letter_to_note[keys])
			if len(keys) == 1:
				audio_new = playing.buffer_segmentation(sound_state.pluck_sounds, notes)
				playing.play(audio_new)
				playing.step += 1
				keys = keys_press(detect)

		elif len(keys) > 1:
			for i in range(len(keys)):
				notes.insert(i, letter_to_note[keys[i]])
			if len(keys) > 1:
				audio_new = playing.buffer_segmentation(sound_state.pluck_sounds, notes)
				playing.play(audio_new)
				playing.step += 1
				keys = keys_press(detect)
		else:
			playing.step = 0

	pygame.quit()

if __name__ == '__main__':
	main()


import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img = cv.imread('toblur.jpg')
assert img is not None, "file could not be read, check with os.path.exists()"
blur = cv.GaussianBlur(img,(5,5), 0)
cv.imwrite('blur.png', blur)
plt.subplot(121),plt.imshow(img),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(blur),plt.title('Blurred')
plt.xticks([]), plt.yticks([])
plt.show()