import random
from dal.persistentVar import getSessionInstance

class Pokemon:
    def __init__(self, id=1, name='', height=0, weight=0, description='no descriptions', image='', hp=0, maxHp=0, pokemonType = {}, nbGame=0):
        self.id = id
        self.name = name
        self.height = height
        self.weight = weight
        self.description = description
        self.image = image
        self.hp = hp
        self.maxHp = maxHp
        self.type = pokemonType
        self.nbGame = nbGame

    def setPokemonHp(self, nbGame):
        self.maxHp = int(self.maxHp * random.uniform(0.4, 1.4)) + nbGame
        self.hp = self.maxHp

    def updatePokemon(self):
        global_var = getSessionInstance().get()
        for pokemon in global_var['userTeam']:
            if pokemon == str(self.id):
                global_var['userTeam'][pokemon] = self

    def doHeal(self, heal):
        pkmHeal = heal
        hpfinal = self.hp + pkmHeal
        if hpfinal > self.maxHp:
            hpToThrow = hpfinal - self.maxHp
            pkmHeal = pkmHeal - hpToThrow
        self.hp += pkmHeal

    def isGameOver(self):
        global_var = getSessionInstance().get()
        if self.hp <= 0:
            countPokemon = len(global_var['userTeam']) #Nombre de pokemon que possède le joueur dans son équipe
            countPokemonKo = 0
            #Gestion du game Over
            for pokemon in global_var['userTeam']:
                if global_var['userTeam'][pokemon].hp == 0:
                    countPokemonKo += 1

            if countPokemon == countPokemonKo:
                print("Game Over")
            else:
                return False
        else:
            return None

    def changePokemonPos(self):
        global_var = getSessionInstance().get()
        for pokemon in global_var['userTeam']:
            if global_var['userTeam'][pokemon].hp != 0:
                tampon = global_var['userTeam'][pokemon]
                global_var['userTeam'][pokemon] = global_var['userTeam']['1']
                global_var['userTeam']['1'] = tampon
                break


import argparse
import json
import logging
import platform
import traceback
import sys
from robocorp_dialog import dialog

LOGGER = logging.getLogger(__name__)

BACKENDS = {
    "Windows": ["edgechromium", "edgehtml", "cef"],
    "Linux": ["qt", "gtk"],
    "Darwin": ["cocoa", "qt"],
}.get(platform.system(), [])

def error(message: str) -> None:
    print(json.dumps({"error": f"Unhandled error: {message}"}), flush=True)

def main() -> None:
    try:
        parser = argparse.ArgumentParser()

        parser.add_argument("elements")
        parser.add_argument("--title", default="Dialog")
        parser.add_argument("--width", default=480, type=int)
        parser.add_argument("--height", default=640, type=int)
        parser.add_argument("--auto_height", action="store_true")
        parser.add_argument("--on_top", action="store_true")
        parser.add_argument("--debug", action="store_true")
        parser.add_argument("--gui", choices=BACKENDS)

        args = parser.parse_args()

        log_level = logging.INFO if not args.debug else logging.DEBUG

        logger = logging.getLogger("pywebview")
        for handler in logger.handlers:
            logger.removeHandler(handler)

        logger.setLevel(log_level)
        logging.basicConfig(
            level=log_level,
            format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
        )

        elements = json.loads(args.elements)
        if not isinstance(elements, list):
            raise ValueError("Elements should be a list")

        dialog.run(
            elements=elements,
            title=args.title,
            width=args.width,
            height=args.height,
            auto_height=args.auto_height,
            on_top=args.on_top,
            debug=args.debug,
            gui=args.gui,
        )
    except Exception:  # pylint: disable=broad-except
        error(traceback.format_exc())
        sys.exit(1)

if __name__ == "__main__":
    main()


N = int(input("Número: "))
acuDivisores = 0
cont = 1

while cont < N:
	if N % cont == 0:
		acuDivisores = acuDivisores + cont
	cont = cont + 1

if acuDivisores == N:
	print("O número {0} é perfeito".format(N))
else:
	print("O número {0} não é perfeito".format(N))


from app import app
from unittest import TestCase, mock
import json
from game_builder import GameBuilder

class TestApp(TestCase):
    def setUp(self):
        self.client = app.test_client()

    @mock.patch('app.nhl_api.get_game', return_value=GameBuilder().build())
    def test_get_games(self, mock_get):
        data = {
            'gameIds': [2017020003]
        }
        response = self.client.post('/api/games', data=json.dumps(data), content_type="application/json")
        self.assertEqual(200, response.status_code)
        result = json.loads(response.data.decode('utf-8'))

        game = result[0]
        self.assertEqual('Edmonton Oilers - Calgary Flames', result[0]['title'])
        self.assertEqual('EDM', game['teams']['home'])
        self.assertEqual('CGY', game['teams']['away'])
        self.assertEqual('3-0', result[0]['result'])
        self.assertEqual('Final', result[0]['status'])
        self.assertEqual(2017020003, game['gamePk'])
        self.assertEqual('02:00', game['startTime'])
        self.assertEqual(3, len(game['goals']))
        self.assertEqual('Connor McDavid (1) Wrist Shot, assists: Leon Draisaitl (1), Patrick Maroon (1)', game['goals'][0]['description'])
        self.assertEqual('EDM', game['goals'][0]['team'])
        self.assertEqual('11:01', game['goals'][0]['time'])
        self.assertEqual('48:07', game['goals'][1]['time'])

    @mock.patch('app.nhl_api.get_game', return_value=GameBuilder().live_game().build())
    def test_live_game(self, mock_get):
        data = {
            'gameIds': [2017020003]
        }
        response = self.client.post('/api/games', data=json.dumps(data), content_type="application/json")
        self.assertEqual(200, response.status_code)
        result = json.loads(response.data.decode('utf-8'))

        game = result[0]
        self.assertEqual('Live', game['status'])


import os

config = dict()
config["channels"] = 1
config["batch_size"] = 2
config["GT_class"] = 2 # 0,1
config["input_shape"] = [24, 48, 48, 1]
config["downsize_nb_filters_factor"] = 1
config["pool_size"] = [2,2,2]
config["initial_learning_rate"] = 0.00001
config["model_file"] =  os.path.abspath("./3d_unet_model.h5")
config["learning_rate_drop"] = 0.5
config["decay_learning_rate_every_x_epochs"] = 10
config["n_epochs"] = 50


#!/usr/bin/python3
#-*- coding: utf-8 -*-

"""

Module dependencies: tkinter, serial, struct

"""

# TODO keyboard shortcuts; most
# TODO port auto-detection
# TODO saving recent few
# big optional TODO PS/2 keyboard sniffer

# TODO TEST NEW FEATURES 2021-01-08

import sys, os, time, serial, struct
import tkinter as tk
from tkinter import messagebox

## == error handling with a graphical message box ==

def myerr(exc_type, exc_value, tb):
    import traceback
    message = '\r'.join(traceback.format_exception(exc_type, exc_value, tb))
    print(message)
    messagebox.showerror(title=exc_value, message=message)
sys.excepthook = myerr

## == settings loading == {{{
def load_settings_from_file(infile='settings.txt'):
    #infile = os.path.realpath(__file__)
    #print("DEBUG: infile = ", infile)
    settings = {}
    with open(infile) as f:
        for l in f.readlines():
            l = l.split('#')[0] # ignore comments
            k,v = [s.strip() for s in l.split('=', 1)]  # split at first '=' sign
            settings[k] = v
    return settings
settings = load_settings_from_file()# }}}

## == Serial port init == {{{
## Port prefix is specified in settings.txt; typically one uses '/dev/ttyUSB' on Linux and 'COM' on Windows.
## Note that none of the serial module attributes (like rtscts, dsrdtr, xonxoff, setDTR(), setRTS()) could solve this

serial_port_names = settings['serialport_posix' if os.name=='posix' else 'serialport_nt'].split(',')
for serial_port_name in serial_port_names:
    try:
        if os.name == 'posix':
            import termios
            with open(serial_port_name) as f: #
                attrs = termios.tcgetattr(f)
                ## On Linux one needs first to disable the "hangup" signal, to prevent ESP32 randomly resetting.
                ## A command-line solution is: stty -F /dev/ttyUSB0 -hup
                attrs[2] = attrs[2] & ~termios.HUPCL
                termios.tcsetattr(f, termios.TCSAFLUSH, attrs)

        # Standard serial port settings, as hard-coded in the hardware
        port = serial.Serial(port=serial_port_name, baudrate=921600, bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout= 0.01)
        if not port.isOpen(): port.open()
        break
    except IOError:
        pass        # termios is not available on Windows, but probably also not needed
assert port
    # }}}

NANOSTEP_PER_MICROSTEP = 256
MINIMUM_POS = -2**22
CMD_MOVE_SYMBOL = 1
MONO_MOTOR_ID = 0
VERT_MOTOR_ID = 1

## == Hardware-communication routines =={{{
def vmotor(choice):
    settings = load_settings_from_file()

    ## send the message to the hardware
    if choice == MINIMUM_POS:
        target_micropos = MINIMUM_POS
    else:
        target_micropos = int(settings['vpos_'+choice])
    values = struct.pack(r'<BBii', CMD_MOVE_SYMBOL, VERT_MOTOR_ID, target_micropos*NANOSTEP_PER_MICROSTEP, 64)
    port.write(values)

    ## receive response from the hardware
    time.sleep(0.01)
    total = 0
    while total < 10:
        try:
            print(ord(port.read(1)))
        except TypeError:
            break
        total=total+1

    ## visual GUI feedback (todo indicate that the movement was really finished)
    for k,v in button_dict.items(): v.config(relief=tk.SUNKEN if k == choice else tk.RAISED)
    for k,v in frame_dict.items():  v.config(bg='green2' if k == choice else BGCOLOR)
    lbl_wavelength.config(bg='green2' if choice=='monochro' else BGCOLOR)
    ent_wavelength.config(state=tk.NORMAL if choice=='monochro' else tk.DISABLED)
    btn_wavelength.config(state=tk.NORMAL if choice=='monochro' else tk.DISABLED)

def mmotor(target_micropos):
    port.write(struct.pack(r'<BBii', CMD_MOVE_SYMBOL, MONO_MOTOR_ID, target_micropos*NANOSTEP_PER_MICROSTEP, 1*256))

def mmotor_by_wl(target_wavelength_nm):
    ## (re)load the monochromator calib
    settings = load_settings_from_file()
    nm1, nm2  = float(settings['calib1_nm']), float(settings['calib2_nm']),
    s1, s2    = float(settings['calib1_stepper']), float(settings['calib2_stepper'])
    target_micropos = int((target_wavelength_nm-nm1)/(nm2-nm1)*(s2-s1)+s1)
    print("DEBUG: target_micropos = ", target_micropos)
    mmotor(target_micropos)

def mmotor_by_entry(*args):
    try:
        print("DEBUG: ent_wavelength = ", ent_wavelength.get())
        target_wavelength_nm = float(ent_wavelength.get())
        print("DEBUG: target_wavelength_nm = ", target_wavelength_nm)
        ent_wavelength.config(bg='#ffffff')
    except:
        ent_wavelength.config(bg='#ff8800')
    print("DEBUG: target_wavelength_nm = ", target_wavelength_nm)
    print( settings['min_limit_nm']  + settings['max_limit_nm'])
    target_wavelength_nm = min(max(target_wavelength_nm, float(settings['min_limit_nm'])), float(settings['max_limit_nm']))
    txt_wavelength.set('{:6.2f}'.format(target_wavelength_nm))
    mmotor_by_wl(target_wavelength_nm)
# }}}

## == GUI init ==
root = tk.Tk()
root.geometry("300x330+300+300")
root.wm_title("CL control")
#root.pack_propagate(0) # don't shrink

btnkwarg = {'padx':100, 'pady':20}
frm_panchro = tk.Frame(root, height=32, width=32); frm_panchro.pack(padx=5, pady=5, side=tk.TOP)
btn_panchro = tk.Button(frm_panchro, text='Panchromatic imaging', command=lambda:vmotor('panchro'), **btnkwarg) # fill=tk.X, ipady=10,
btn_panchro.pack(padx=5, pady=5, side=tk.TOP)
BGCOLOR = btn_panchro.cget('bg')

frm_spectro = tk.Frame(root, height=32, width=32); frm_spectro.pack(padx=5, pady=5, side=tk.TOP)
btn_spectro = tk.Button(frm_spectro, text='Spectrometer', command=lambda:vmotor('spectro'),  **btnkwarg)
btn_spectro.pack(padx=5, pady=5, side=tk.TOP)

frm_monochro = tk.Frame(root, height=32, width=32); frm_monochro.pack(padx=5, pady=5, side=tk.TOP)
btn_monochro = tk.Button(frm_monochro, text='Monochromator imaging', command=lambda:vmotor('monochro'), **btnkwarg)
btn_monochro.pack(padx=5, pady=5, side=tk.TOP)
lbl_wavelength = tk.Label(text='Wavelength (nm)', master=frm_monochro ); lbl_wavelength.pack(padx=5, pady=5, side=tk.LEFT)
txt_wavelength = tk.StringVar()
ent_wavelength = tk.Entry(frm_monochro, text='nm', textvariable=txt_wavelength, width=10);
ent_wavelength.pack(padx=5, pady=5, side=tk.LEFT)
ent_wavelength.bind('<Return>', mmotor_by_entry)
btn_wavelength = tk.Button(frm_monochro, text='set!', command=mmotor_by_entry); btn_wavelength.pack(padx=5, pady=5, side=tk.LEFT)

frm_endstop = tk.Frame(root, height=22); frm_endstop.pack(padx=5, pady=5, side=tk.TOP)
btn_mgotovend = tk.Button(frm_endstop, text='Vertical zero', command=lambda:[vmotor(MINIMUM_POS)], bg='#eebbbb', padx=10, pady=2) # fill=tk.X, ipady=10,
btn_mgotovend.pack(padx=5, pady=5, side=tk.LEFT)
btn_mgotomend = tk.Button(frm_endstop, text='Monochromator zero', command=lambda:[mmotor(MINIMUM_POS)], bg='#eebbbb', padx=10, pady=2) # fill=tk.X, ipady=10,
btn_mgotomend.pack(padx=5, pady=5, side=tk.LEFT)

frame_dict = {'panchro':frm_panchro, 'spectro':frm_spectro, 'monochro':frm_monochro}
button_dict = {'panchro':btn_panchro, 'spectro':btn_spectro, 'monochro':btn_monochro}

## == responsive GUI loop and termination ==

tk.mainloop()
port.close()


#Calculates BMI
def calculateBMI(height,weight):
  return round(weight/(height/100)**2,2)

#Test Cases
assert calculateBMI(175,75)==24.49
assert calculateBMI(161,57)==21.99

#Seperates BMI in Category
def categoryRisk(bmi):
  if bmi <= 18.4:
    return('Underweight','Malnutrition Risk')
  elif 18.5 <= bmi <= 24.9:
    return('Normal Weight','Low Risk')
  elif 25 <= bmi <= 29.9:
    return('Overweight','Enhanced Risk')
  elif 30 <= bmi <= 34.9:
    return('Moderately Obese','Medium Risk')
  elif 35 <= bmi <= 39.9:
    return('Severely Obese','High Risk')
  elif bmi >= 40:
    return('Very severely Obese','Very High Risk')

 #Test Cases
assert categoryRisk(17.55) == ('Underweight','Malnutrition Risk')
assert categoryRisk(21.66) == ('Normal Weight','Low Risk')
assert categoryRisk(26.5) == ('Overweight','Enhanced Risk')
assert categoryRisk(32.7) == ('Moderately Obese','Medium Risk')
assert categoryRisk(37.6) == ('Severely Obese','High Risk')
assert categoryRisk(47) == ('Very severely Obese','Very High Risk')

# Update existing objects
def updateObject(obj):
 for n in obj:
   _bmi = calculateBMI(n['HeightCm'],n['WeightKg'])
   _temp = categoryRisk(_bmi)
   n.update({'BMI':_bmi})
   n.update({'BMI Category':_temp[0]})
   n.update({'Health Risk':_temp[1]})

#Processing the data
data = [{"Gender": "Male", "HeightCm": 171, "WeightKg": 96 }, { "Gender": "Male", "HeightCm": 161, "WeightKg":
85 }, { "Gender": "Male", "HeightCm": 180, "WeightKg": 77 }, { "Gender": "Female", "HeightCm": 166,
"WeightKg": 62}, {"Gender": "Female", "HeightCm": 150, "WeightKg": 70}, {"Gender": "Female",
"HeightCm": 167, "WeightKg": 82}]

updateObject(data)
print(data)


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import os
from collections import defaultdict

from pyramid import testing

from tokenserver.assignment import INodeAssignment
from tokenserver.assignment import fixednode
from mozsvc.config import load_into_settings
from mozsvc.exceptions import BackendError
from tokenserver.tests.support import unittest

DEFAULT_EMAIL = "alexis@mozilla.com"
DEFAULT_NODE = "https://example.com"
DEFAULT_SERVICE = "sync-1.0"

def restore_defaults():
    fixednode._UID = 0
    fixednode._USERS_UIDS = defaultdict(dict)

class TestFixedBackend(unittest.TestCase):

    def setUp(self):
        self.config = testing.setUp()
        self.ini = os.path.join(os.path.dirname(__file__),
                                'test_fixednode.ini')
        settings = {}
        load_into_settings(self.ini, settings)
        self.config.add_settings(settings)
        self.config.include("tokenserver")
        self.backend = self.config.registry.getUtility(INodeAssignment)

    def test_read_config(self):
        self.assertEqual(DEFAULT_NODE,
                self.backend.allocate_node(DEFAULT_EMAIL, DEFAULT_SERVICE,
                    )[1])

    def test_assignation(self):
        # restore the default values for testing
        restore_defaults()
        try:
            # getting the node assignation for an existing user should return
            # None and the service entry
            self.assertEquals(
                    self.backend.get_node(DEFAULT_EMAIL, DEFAULT_SERVICE,
                        ),
                    (None, DEFAULT_NODE, []))

            # Now allocate an user to a node
            self.assertEquals(
                    self.backend.allocate_node(DEFAULT_EMAIL, DEFAULT_SERVICE,
                        ),
                    (0, DEFAULT_NODE))

            # Trying to allocate it two times should raise a Backend error
            self.assertRaises(BackendError, self.backend.allocate_node,
                              DEFAULT_EMAIL, DEFAULT_SERVICE)

            # getting the value of it later should also work properly
            self.assertEquals(
                    self.backend.get_node(DEFAULT_EMAIL, DEFAULT_SERVICE,
                        ),
                    (0, DEFAULT_NODE, []))
        finally:
            restore_defaults()


from .animation import *

class swirl_to_pos(Animation):
    def __init__(self, translate=[0, 0, 0], rotate=-360, scale=[1, 1, 1], duration=1, stagger=0.1):
        super().__init__()
        self.translate = translate
        self.rotate = rotate
        self.scale = scale
        self.duration = duration
        self.stagger = stagger

    def animation(self):
        total_elements = len(self.elements) if isinstance(self.elements, Group) else 1
        elements_copy = self.elements.copy().scale(*self.scale).translate(*self.translate)
        for i in range(total_elements):
            element = self.elements[i] if isinstance(self.elements, Group) else self.elements
            element_copy = elements_copy[i] if isinstance(self.elements, Group) else elements_copy
            new_pos = element.to_relative_of(element_copy, [0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
            delay = 0 if i == 0 else self.stagger - self.duration
            self.timeline.add_animation(
                element, [translate(*new_pos),
                          rotate(-360), scale(*self.scale)],
                delay,
                self.duration,
                ease=self.ease)


import yaml
import os
import argparse

def parse_args():
    parser=argparse.ArgumentParser(description='Set Pod Count')
    parser.add_argument('--pods',required=False, default=8)
    parser.add_argument('--gpu',required=False, default=1)
    parser.add_argument('--yaml',required=False)
    args=parser.parse_args()
    return args

def main():
	args = parse_args()
	pod_count = args.pods
	gpu_per_pod = args.gpu

	yaml_path = args.yaml #'/mnt/yaml/jobservice_sniper.yaml' #'/home/ubuntu/redkube/nfs/yaml/jobservice_sniper.yaml'

	with open(yaml_path) as f:
		yam = yaml.load(f)

	yam['spec']['parallelism'] = int(pod_count)
	yam['spec']['template']['spec']['containers'][0]['resources']['limits']['nvidia.com/gpu'] = int(gpu_per_pod)

	filename = os.path.basename(yaml_path)
	dir_name = os.path.dirname(yaml_path)

	with open(yaml_path,'w') as fw:
		yaml.dump(yam,fw)

if __name__== "__main__":
	main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import re
import argparse

def get_bed_dict(bed_file):
    bed_dict = {}
    with open(bed_file, 'r') as f:
        lines = f.readlines()
        for line in lines:
            if re.match(r'^chr.*', line):
                line = line.strip()
                chrom = line.split('\t')[0]
                start = int(line.split('\t')[1])
                end = int(line.split('\t')[2]) + 1
                if chrom not in bed_dict:
                    bed_dict[chrom] = []
                for i in range(start, end):
                    bed_dict[chrom].append(i)
    return bed_dict

def get_hotspot(hotspot_file, bed_dict, out_prefix):
    r = open('{}.hotspot.txt'.format(out_prefix), 'w')
    r.write('Chr\tPos\tRef\tAlt\tGene\tAA\n')
    with open(hotspot_file, 'r') as f:
        lines = f.readlines()
        for line in lines:
            if re.match(r'^chr.*', line):
                chrom = line.split('\t')[0]
                pos = int(line.split('\t')[1])
                if chrom in bed_dict and pos in bed_dict[chrom]:
                    r.write(line)
    r.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Filter hotspot based on bed file')
    parser.add_argument('-s', '--spot', help='hotspot file')
    parser.add_argument('-b', '--bed', help='bed file')
    parser.add_argument('-o', '--out', help='out prefix')
    args = parser.parse_args()

    hotspot_file = args.spot
    bed_file = args.bed
    out_prefix = args.out

    bed_dict = get_bed_dict(bed_file)
    get_hotspot(hotspot_file, bed_dict, out_prefix)


import torch
from torch import nn
import torch.nn.functional as F

class Attention(nn.Module):
    def __init__(self, enc_hidden_dim, dec_hidden_dim):
        """Attention layer for seq2seq
        @param enc_hidden_dim (int): The hidden dimension for encoder
        @param dec_hidden_dim (int): The hidden dimension for decoder"""

        super(Attention, self).__init__()

        self.attn = nn.Linear((enc_hidden_dim * 2) + dec_hidden_dim, dec_hidden_dim)
        # enc_hidden_dim * 2 because of bidirectional in Encoder.

        self.v = nn.Linear(dec_hidden_dim, 1, bias=False)

    def forward(self, hidden, enc_outputs, masks):
        """Forward function for Attentional layer
        @param hidden (torch tensor): The hidden layer of the previous decoder output
        @param enc_outputs (torch tensor): The output from the encoder layer
        @param masks (torch tensor): Tensor to mask out the padded values in enc output
        returns attention (torch tensor): The attention values of the encoder outputs"""

        # hidden --> [batch size, dec hidden dim]
        # enc_outputs --> [src_len, batch_size, enc hidden dim * 2]

        batch_size = enc_outputs.shape[1]
        src_len = enc_outputs.shape[0]

        hidden = hidden.unsqueeze(1).repeat(1, src_len, 1) # Repeat the hidden state T times to match that of enc_output
        # hidden --> [batch size, src len, dec hidden dim]

        encoder_outputs = enc_outputs.permute(1, 0, 2) # Change enc_outputs as batch first to match with hidden
        # encoder_outputs --> [batch size, src len, enc hidden dim * 2]

        concat = torch.cat((hidden, encoder_outputs), dim=2) # concat the prev hidden state and current enc state
        # concat --> [batch size, src len, enc hidden dim * 2 + dec hidden dim]

        energy = torch.tanh(self.attn(concat))
        # energy --> [batch size, src len, dec hidden dim]

        attention = self.v(energy)
        # attention = [batch size, src len, 1]
        attention = attention.squeeze(2)
        # attention --> [batch size, src len]

        attention = attention.masked_fill(masks == 0, -1e10)

        return F.softmax(attention, dim=1)

class Decoder(nn.Module):
    def __init__(self, tgt_vocab, emb_dim, enc_hidden_dim, dec_hidden_dim, dropout=0.5):
        """Decoder layer for seq2seq model
        @param tgt_vocab (int): the vocabulary of the target
        @param emb_dim (int): the dimension of the embedding layer
        @param enc_hidden_dim (int): the hidden dimension of the encoder layer
        @param dec_hidden_dim (int): the hidden dimension of the decoder layer
        @param dropout (int): the value of the dropout must be between 0 and 1"""
        super(Decoder, self).__init__()

        self.output_dim = tgt_vocab

        self.hidden_attention = Attention(enc_hidden_dim, dec_hidden_dim)
        self.cell_attention = Attention(enc_hidden_dim, dec_hidden_dim)

        self.embedding = nn.Embedding(tgt_vocab, emb_dim)

        self.rnn = nn.LSTM((enc_hidden_dim * 4) + emb_dim, dec_hidden_dim, bidirectional=False)

        self.fc = nn.Linear((enc_hidden_dim * 4) + emb_dim + dec_hidden_dim, self.output_dim)

        self.dropout = nn.Dropout(dropout)

    def forward(self, dec_inputs, hidden, cell, enc_outputs, masks):
        """Forward function for the decoder layer
        @param dec_inputs (torch tensor): The value of the previous decoder outputs
        @param hidden (torch tensor): The hidden state of the previous decoder value
        @param cell (torch tensor): The cell state of the previous decoder value
        @param enc_outputs (torch tensor): The output value from the encoder
        @param masks (torch tensor): To mask out the padded values from encoder output
        returns decoder_output, (hidden, cell), attention : the decoder outputs along with the hidden state and cell state and attention for debugging"""

        # dec_inputs --> [batch size] (single word)
        # hidden --> [batch size, dec hidden dim]
        # cell --> [batch size, dec hidden dim]
        # enc_outputs --> [src len, batch size, enc hidden dim * 2]

        dec_inputs = dec_inputs.unsqueeze(0)    # as sequence length is of 1 (LSTM accepts sequence first)
        # dec_inputs --> [1, batch size]

        embedded = self.embedding(dec_inputs)
        #embedded --> [1, batch size, emb dim]

        hidden_a = self.hidden_attention(hidden, enc_outputs, masks)
        cell_a = self.cell_attention(cell, enc_outputs, masks)

        # hidden_a --> [batch size, src len]
        # cell_a --> [batch size, src len]

        hidden_a = hidden_a.unsqueeze(1)
        cell_a = cell_a.unsqueeze(1)
        #hidden_a --> [batch size, 1, src len]
        #cell_a --> [batch size, 1, src len]

        enc_outputs =enc_outputs.permute(1, 0, 2)
        # enc_outputs --> [batch size, src len, enc hidden dim * 2]

        hidden_weighted = torch.bmm(hidden_a, enc_outputs) # The reshaping was done so that the matrix multiplication could be done
        cell_weighted = torch.bmm(cell_a, enc_outputs)
        # hidden_weighted --> [batch size, 1, enc hidden dim * 2]
        # cell_weighted --> [batch size, 1, enc hidden dim * 2]

        hidden_weighted = hidden_weighted.permute(1, 0, 2)
        cell_weighted = cell_weighted.permute(1, 0, 2)
        # hidden_weighted --> [1, batch size, enc hidden dim * 2]
        # cell_weighted --> [1, batch size, enc hidden dim * 2]

        rnn_input = torch.cat((embedded, hidden_weighted, cell_weighted), dim=2)
        # rnn_input = torch.cat((embedded, hidden_weighted), dim=2)
        # rnn_input --> [1, batch size, (enc hidden dim * 2) + emb dim]

        output, (hidden, cell) = self.rnn(rnn_input, (hidden.unsqueeze(0), cell.unsqueeze(0)))

        # output --> [1, batch size, dec hidden dim]
        # hidden --> [1, batch size, dec hidden dim]
        # cell --> [1, batch size, dec hidden dim]

        assert (output == hidden).all()

        embedded = embedded.squeeze(0)
        output = output.squeeze(0)
        hidden_weighted = hidden_weighted.squeeze(0)
        cell_weighted = cell_weighted.squeeze(0)

        prediction = self.fc(torch.cat((embedded, output, hidden_weighted, cell_weighted), dim=1))
        # prediction = self.fc(torch.cat((embedded, output, hidden_weighted), dim=1))
        # prediction --> [batch size, output dim]

        return prediction, (hidden.squeeze(0), cell.squeeze(0)), hidden_a.squeeze(1)


import sys
from random import shuffle

n = int(sys.argv[1])

nums = list(range(- (n // 2), n // 2))
shuffle(nums)

with open("data.txt", "wt") as file:
    print(*nums, file=file)


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

BOT_NAME = 'shoujihao'

SPIDER_MODULES = ['shoujihao.spiders']
NEWSPIDER_MODULE = 'shoujihao.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'

# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
DOWNLOAD_DELAY = 3

# Configure item pipelines
ITEM_PIPELINES = {
    'shoujihao.pipelines.DuplicatesPipeline': 300,
    'scrapy_mongodb.MongoDBPipeline': 800,
}

# Scrapy mongodb databse configuration
MONGODB_URI = 'mongodb://localhost:27017'
MONGODB_DATABASE = 'scrapy'
MONGODB_COLLECTION = 'bj_58_com_shoujihao_items'


"""
Python tuples are sort of like lists, except they're immutable and
are usually used to hold heterogenous data, as opposed to lists
which are typically used to hold homogenous data. Tuples use
parens instead of square brackets.

More specifically, tuples are faster than lists. If you're looking
to just define a constant set of values and that set of values
never needs to be mutated, use a tuple instead of a list.

Additionally, your code will be safer if you opt to "write-protect"
data that does not need to be changed. Tuples enforce immutability
automatically.
"""

# Example:

import math

def dist(a, b):
    """Compute the distance between two x,y points."""
    x0, y0 = a  # Destructuring assignment
    x1, y1 = b

    return math.sqrt((x1 - x0)**2 + (y1 - y0)**2)

a = (2, 7)   # <-- x,y coordinates stored in tuples
b = (-14, 72)

# Prints "Distance is 66.94"
print("Distance is: {:.2f}".format(dist(a, b)))

# Write a function `print_tuple` that prints all the values in a tuple

# YOUR CODE HERE
def print_tuple(tuples):
    for tuple in tuples:
        print(tuple)

t = (1, 2, 5, 7, 99)
print_tuple(t)  # Prints 1 2 5 7 99, one per line

""" notes: set up function (def) named print_tuple, took the params of tuples
and set up a for loop to print out each number(t) on it's on own line
if you would print(t) it would show you the tuples on one line.
had to rename each number(t) to tuple to run thru to get each one by it's self.
"""

# Declare a tuple of 1 element then print it
u = (1,)  # What needs to be added to make this work?
print_tuple(u)
""" print(u) show yous (1,) which we don't want we want to see it by it's self not with it's syntax, same as calling a function that is just writen not working. """


# -*- coding: utf-8 -*-
"""
Created on Tue Jul  4 12:35:51 2017

@author: arash
"""
import scipy.io
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from scipy.special import expit

def sigmoid(z):
    g = np.zeros(z.shape)
    g = expit(z)
    return g

def displayData(X, example_width=None):
    m,n = X.shape
    plt.figure()
    if X.ndim == 1:
        X = np.reshape(X, (-1,m))
    if not example_width or not 'example_width' in locals():
        example_width = int(round(math.sqrt(X.shape[1])))
    plt.set_cmap("gray")
    example_height = n / example_width
    display_rows = int(math.floor(math.sqrt(m)))
    display_cols = int(math.ceil(m / display_rows))
    pad = 1
    display_array = -np.ones((pad + display_rows * int(example_height + pad),  pad + display_cols * int(example_width + pad)))
    curr_ex = 1
    for j in range(1,display_rows+1):
        for i in range (1,display_cols+1):
            if curr_ex > m:
                break
            max_val = max(abs(X[curr_ex-1, :]))
            rows = pad + (j - 1) * (int(example_height) + pad) + np.array(range(int(example_height)))
            cols = pad + (i - 1) * (int(example_width)  + pad) + np.array(range(int(example_width)))
            display_array[rows[0]:rows[-1]+1 , cols[0]:cols[-1]+1] = np.reshape(X[curr_ex-1, :], (int(example_height), int(example_width)), order="F") / max_val
            curr_ex += 1
            if curr_ex > m:
                break
    h = plt.imshow(display_array, vmin=-1, vmax=1)
    plt.axis('off')
    plt.show(block=False)
    return h, display_array

def costFunction(theta, X, y, lambda_reg, return_grad=False):
    m = len(y)
    J = 0
    grad = np.zeros(theta.shape)
    one = y * np.transpose(np.log( sigmoid( np.dot(X,theta) ) ))
    two = (1-y) * np.transpose(np.log( 1 - sigmoid( np.dot(X,theta) ) ))
    reg = ( float(lambda_reg) / (2*m)) * np.power(theta[1:theta.shape[0]],2).sum()
    J = -(1./m)*(one+two).sum() + reg
    grad = (1./m) * np.dot(sigmoid( np.dot(X,theta) ).T - y, X).T + ( float(lambda_reg) / m )*theta
    grad_no_regularization = (1./m) * np.dot(sigmoid( np.dot(X,theta) ).T - y, X).T
    grad[0] = grad_no_regularization[0]
    if return_grad == True:
        return J, grad.flatten()
    elif return_grad == False:
        return J

def oneVsAll(X, y, num_labels, lambda_reg):
    m, n = X.shape
    all_theta = np.zeros((num_labels, n + 1))
    X = np.column_stack((np.ones((m,1)), X))
    for c in range(num_labels):
        initial_theta = np.zeros((n + 1, 1))
        myargs = (X, (y%10==c).astype(int), lambda_reg, True)
        theta = minimize(costFunction, x0=initial_theta, args=myargs, options={'disp': True, 'maxiter':13}, method="Newton-CG", jac=True)
        all_theta[c,:] = theta["x"]
    return all_theta

def predictOneVsAll(all_theta, X):
    m = X.shape[0]
    num_labels = all_theta.shape[0]
    p = np.zeros((m, 1))
    X = np.column_stack((np.ones((m,1)), X))
    p = np.argmax(sigmoid( np.dot(X,all_theta.T) ), axis=1)
    return p

input_layer_size = 400
num_labels = 10
data = scipy.io.loadmat('hand_written_numbers.mat')
X=data["X"]
y=data["y"]
m,n=X.shape
y=y.flatten()
rand_indices = np.random.permutation(m)
random_images = X[rand_indices[:100],:]
displayData(random_images)

lambda_reg = 0.1
all_theta = oneVsAll(X, y, num_labels, lambda_reg)
pred = predictOneVsAll(all_theta, X)
print('Training Set Accuracy: {:f}'.format((np.mean(pred == y%10)*100)))
print('Training Set Accuracy for 1:  {:f}'.format(np.mean(pred[500:1000]  == y.flatten()[500:1000]%10)  * 100))
print('Training Set Accuracy for 2:  {:f}'.format(np.mean(pred[1000:1500] == y.flatten()[1000:1500]%10) * 100))
print('Training Set Accuracy for 3:  {:f}'.format(np.mean(pred[1500:2000] == y.flatten()[1500:2000]%10) * 100))
print('Training Set Accuracy for 4:  {:f}'.format(np.mean(pred[2000:2500] == y.flatten()[2000:2500]%10) * 100))
print('Training Set Accuracy for 5:  {:f}'.format(np.mean(pred[2500:3000] == y.flatten()[2500:3000]%10) * 100))
print('Training Set Accuracy for 6:  {:f}'.format(np.mean(pred[3000:3500] == y.flatten()[3000:3500]%10) * 100))
print('Training Set Accuracy for 7:  {:f}'.format(np.mean(pred[3500:4000] == y.flatten()[3500:4000]%10) * 100))
print('Training Set Accuracy for 8:  {:f}'.format(np.mean(pred[4000:4500] == y.flatten()[4000:4500]%10) * 100))
print('Training Set Accuracy for 9:  {:f}'.format(np.mean(pred[4500:5000] == y.flatten()[4500:5000]%10) * 100))
print('Training Set Accuracy for 10: {:f}'.format(np.mean(pred[0:500]     == y.flatten()[0:500]%10)     * 100))

#Randomize all the digits
rand_indices = np.random.permutation(m)
random_X = X[rand_indices[:m],:]
random_y = y[rand_indices[:m]]

num_digit=int(input("Input the index of the random image you want to predict "))
pred1=predictOneVsAll(all_theta, random_X[num_digit,:].reshape(1,-1))
print("Predicted digit ", pred1)
print("Actual digit ",random_y[num_digit])
plt.imshow((random_X[num_digit,:].reshape(20,20)).T)
plt.show()


import sys

from toolbox._common import RunAnsibleRole, AnsibleRole, AnsibleMappedParams, AnsibleConstant, AnsibleSkipConfigGeneration

class LoadAware:
    """
    Commands relating to Trimaran and LoadAware testing
    """

    @AnsibleRole("load_aware_deploy_trimaran")
    @AnsibleMappedParams
    def deploy_trimaran(self, log_level=1, plugin="TargetLoadPacking", default_requests_cpu="2000m", default_target_requests_multiplier="2", target_utilization=70, safe_variance_margin=1, safe_variance_sensitivity=2):
        """
        Role to deploy the Trimaran load aware scheduler

        Args:
            log_level: log verbosity to set the scheduler to run with,
            plugin: TargetLoadPacking or LoadVariationRiskBalancing
            default_requests_cpu: TargetLoadPacking setting
            default_target_requests_multiplier: TargetLoadPacking setting
            target_utilization: TargetLoadPacking setting,
            safe_variance_margin: LoadVariationRiskBalancing setting
            safe_variance_sensitivity: LoadVariationRiskBalancing setting
        """

        if plugin not in ("TargetLoadPacking", "LoadVariationRiskBalancing"):
            print(f"Can't deploy Trimaran with unknown plugin: {plugin}")
            sys.exit(1)

        print(f"Deploying Trimaran with plugin {plugin}")

        if plugin == "TargetLoadPacking":
            print(f"default_requests_cpu: {default_requests_cpu}")
            print(f"default_target_requests_multiplier: {default_target_requests_multiplier}")
            print(f"target_utilization: {target_utilization}")
        else:
            print(f"safe_variance_margin: {safe_variance_margin}")
            print(f"safe_variance_sensitivity: {safe_variance_sensitivity}")

        print(f"Deploying Trimaran with log level {log_level}")

        return RunAnsibleRole(locals())

    @AnsibleRole("load_aware_undeploy_trimaran")
    @AnsibleMappedParams
    def undeploy_trimaran(self):
        """
        Role to undeploy the Trimaran load aware scheduler

        Args:
            None
        """

        return RunAnsibleRole(locals())


from src.mlb_fantasy import GetData
from luigi import build
import pandas as pd
from sklearn.cluster import KMeans, MeanShift, DBSCAN, SpectralClustering
from sklearn.mixture import BayesianGaussianMixture, GaussianMixture
import matplotlib.pyplot as plt

colmap = {1: 'r', 2: 'g', 3: 'b'}

b_data = pd.read_csv(GetData(type='batting').output().open(), index_col=0)
p_data = pd.read_csv(GetData(type='pitching').output().open(), index_col=0)

df = pd.DataFrame({'x': p_data['G'], 'y': p_data['IP']})

fantasy_baseball_pitching_stats = ('ERA', 'WHIP', 'SO', 'SV', 'W')

def gaussian_clustering():
    p_data_filtered = p_data[(p_data.G > 20) | (p_data.IP > 50)]
    df = pd.DataFrame({'x': p_data_filtered['G'], 'y': p_data_filtered['IP']})
    labels = GaussianMixture(n_components=2).fit_predict(X=df.values)
    colors = list(map(lambda x: colmap[x + 1], labels))

    plt.scatter(p_data_filtered['G'], p_data_filtered['IP'], color=colors)
    plt.xlabel("Games Played")
    plt.ylabel("Innings Pitched")
    plt.title("Yearly Pitching Stats")
    plt.show()

p_data_filtered = p_data[(p_data.G > 20) | (p_data.IP > 50)]
df = pd.DataFrame({'x': p_data_filtered['G'], 'y': p_data_filtered['IP']})

gmix = GaussianMixture(n_components=2).fit(df)
p_data['Starter'] = gmix.predict(pd.DataFrame({
    'x': p_data['G'],
    'y': p_data['IP']
}))

list(p_data.columns.values)

hist(p_data['Pitches'])

plt.scatter(p_data['G'], p_data['IP'], color=list(map(lambda x: colmap[x + 1], p_data['Starter'])))
plt.xlabel("ERA")
plt.ylabel("# of Pitches")
plt.title("Yearly Pitching Stats")
plt.show()

sp = p_data[p_data.Starter == 1]
rp = p_data[p_data.Starter == 0]

scatter(sp.Age, sp.WHIP)
scatter(rp.Pitches, rp.WHIP)

hist(rp.Pitches)

plt.savefig('pitch.png')

if __name__ == "__main__":
    with open('./data/external/file.txt', 'w+') as f:
        f.write('Some text')
    build([GetData(type='pitching'), GetData(type='batting')], workers=1, local_scheduler=True)


import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
import numpy as np
import math
import os

#function takes folder path with chessboard images and analyze the images to return the image points
#and object points
def get_obj_image_points(path ,nx,ny):

    #lists to hold the current image obj points and imgpoints
    imgpoints = [] # 2d points in image plane.
    objpoints = [] # 3d point in real world space and and it will be based on chessboard dimensions 9*5

    #size variable
    size=[]

    #create object point array zeroed then fill with checss board coordinates
    objp = np.zeros((nx*ny,3),np.float32)
    objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2) #x and y coordinates

    #Loop over all images for calibration
    chessboard_images=os.listdir(path)

    for filename in chessboard_images:

      # find corners and undistort images
        #read chessboard image
        image = mpimg.imread(path+filename)

        # Convert to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        #update size variable
        size= gray.shape[::-1]

        # Find the chessboard corners
        ret, corners = cv2.findChessboardCorners(gray, (nx, ny), None)

        # If found, draw corners ( note 2 images were not captured due to loss of corners (imge 4 and 5))
        if ret == True:
            # Draw and display the corners
            imgpoints.append(corners)
            objpoints.append(objp)
            # Draw corners and save in output folder
            image_corners = cv2.drawChessboardCorners(image, (nx, ny), corners, ret)
            cv2.imwrite("camera_cal_output/"+filename[:-4]+"_01_Corners.jpg",image_corners)

    return objpoints,imgpoints,size

#function takes in image and returns the undistorted image based on image points and object points
def get_dist_parameters(objpoints, imgpoints,size):

    #get the distorsion coff.
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints,size , None, None)

    return mtx,dist

#compute the M matrix for prospective transform for easier processing
def compute_prespective_M(image ,src,dst):

    img_size = ( image.shape[1] , image.shape[0] )
    M = cv2.getPerspectiveTransform(src, dst)

    return M

#compute the inverse M matrix for prospective transform after processing to actual image
def compute_inverse_M (image,src,dst ):

    img_size = ( image.shape[ 1] , image.shape[ 0 ] )
    I_M = cv2.getPerspectiveTransform(dst, src)

    return I_M

#return the HLS color of image
def convert_hls(image):
    return cv2.cvtColor(image, cv2.COLOR_RGB2HLS)

#select white and yellow colors of image
def select_color(image ):

    # find colors that are in provided range and highlight it in red

    white_lo=    np.array([230,230,230])
    white_hi=    np.array([255,255,255])

    yellow_lo_RGB=   np.array([225,180,0])
    yellow_hi_RGB=   np.array([255,255,170])

    yellow_lo_HLS=   np.array([20,120,80])
    yellow_hi_HLS=   np.array([45,200,255])

    rgb_image = np.copy(image)
    hls_image = convert_hls(image)

    mask_1=cv2.inRange(rgb_image,white_lo,white_hi) #filter on rgb white
    mask_2=cv2.inRange(hls_image,yellow_lo_RGB,yellow_hi_RGB) #filter on rgb yellow
    mask_3=cv2.inRange(hls_image,yellow_lo_HLS,yellow_hi_HLS) #filter on hls yellow

    mask = mask_1+mask_2+mask_3

    result = cv2.bitwise_and(image,image, mask= mask)

    combined_binary = np.zeros_like(result)
    combined_binary[result>1] = 1

    combined_white = np.zeros_like(result)
    combined_white[result>1] = 255

    return combined_binary,combined_white

#Calculate the x gradient on specific channel and filter based on threshould
def x_gradient(channel, threshould ):

    # Sobel x
    sobelx = cv2.Sobel(channel, cv2.CV_64F, 1, 0) # Take the derivative in x
    abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal
    scaled_sobel = np.uint8((255*abs_sobelx)/(np.max(abs_sobelx)))
    # Threshold x gradient
    xbinary = np.zeros_like(scaled_sobel)
    xbinary[(scaled_sobel >= threshould[0]) & (scaled_sobel <= threshould[1])] = 1

    return xbinary

#function takes undistorted image and runs x gradient for v channel and l channel
#also runs color channel filter on s channel
def lane_filter(undist_img, s_thresh,l_thresh,b_thresh,x_thresh):

    #Convert to HSV
    hsv = cv2.cvtColor(undist_img, cv2.COLOR_RGB2HSV)
    #convert to LAB
    lab = cv2.cvtColor(undist_img, cv2.COLOR_RGB2LAB)

    v_channel = hsv[:,:,2]
    s_channel = hsv[:,:,1]
    l_channel = lab[:,:,0]
    b_channel = lab[:,:,2]

    #get gradient for both v and l channels
    vxbinary= x_gradient(v_channel,x_thresh)
    lxbinary= x_gradient(l_channel,x_thresh)

    # Threshold color channel s
    s_binary = np.zeros_like(s_channel)
    s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1

    # Threshold color channel l
    l_binary = np.zeros_like(l_channel)
    l_binary[(l_channel >= l_thresh[0]) & (l_channel <= l_thresh[1])] = 1
    # Threshold color channel b
    b_binary = np.zeros_like(b_channel)
    b_binary[(b_channel >= b_thresh[0]) & (b_channel <= b_thresh[1])] = 1

    combined_binary = np.zeros_like(lxbinary)
    #combined_binary[(vxbinary == 1)|(lxbinary==1)|(s_binary==1|(l_binary==1))] = 1
    combined_binary[(vxbinary == 1)|(lxbinary==1)|(s_binary==1)|(l_binary==1)|(b_binary==1)] = 1

    return combined_binary


#!/usr/bin/env python3

import argparse
import csv
import re
import sys
from datetime import datetime

ts_every = 1
timefmt = '%Y-%m-%d %H:%M'

xs = ['x']
bw_ups = ['bwup']
bw_dns = ['bwdn']
conns = ['conns']
targets = ['targets']
ports = ['ports']

def convert():
    parser = argparse.ArgumentParser()
    parser.add_argument("out")
    args = parser.parse_args()

    i = 0
    reader = csv.reader(sys.stdin)
    for (ts, bw_up, bw_dn, conn, target, port) in reader:
        if i%ts_every == 0:
            xs.append(datetime.utcfromtimestamp(int(ts)).strftime(timefmt))
        else:
            xs.append('')
        bw_ups.append(int(bw_up))
        bw_dns.append(int(bw_dn))
        conns.append(int(conn))
        targets.append(int(target))
        ports.append(int(port))
        i += 1

    make_output(args.out+'-bw.js', chart='chart_bw_'+args.out, data1=bw_ups, data2=bw_dns)
    make_output(args.out+'-conn.js', chart='chart_conn_'+args.out, data1=conns)
    make_output(args.out+'-target.js', chart='chart_target_'+args.out, data1=targets)
    make_output(args.out+'-port.js', chart='chart_port_'+args.out, data1=ports)

def make_output(filename, data1, data2=None, chart='chart'):
    with open(filename, 'w') as out:
        print("var %s = c3.generate({ bindto: '#%s', data: { x: 'x', xFormat: '%s', columns: [" % (chart, chart, timefmt), file=out)
        print(f"{xs},", file=out)
        if data2:
            print(f"{data1},", file=out)
            print(f"{data2}", file=out)
        else:
            print(f"{data1}", file=out)
        print("] }, axis: { x: { type: 'timeseries', tick: { format: '%s' } } } } );" % timefmt, file=out)

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(convert())


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

from numpy import *
import numpy as np
import math
import modules.var as v

def area_elem():

    # calculate area of elements and relate nodes to element numbers
    # calculate area of each element
    # loop for elements
    x = np.zeros(3, dtype=np.float64)
    y = np.zeros(3, dtype=np.float64)
    v.totalArea = 0.0

    for l in range(v.nElem):
        # calculate area of element
        x[0] = v.xCo[v.inn[l][0]]
        y[0] = v.yCo[v.inn[l][0]]
        x[1] = v.xCo[v.inn[l][1]]
        y[1] = v.yCo[v.inn[l][1]]
        x[2] = v.xCo[v.inn[l][2]]
        y[2] = v.yCo[v.inn[l][2]]
        v.area[l] = ((y[0]+y[1])*(x[0]-x[1])+(y[1]+y[2])*(x[1]-x[2])+(y[2]+y[0])*(x[2]-x[0]))*0.5
        v.area[l] = abs(v.area[l])
        v.totalArea = v.totalArea+v.area[l]

def isostasy():
    # calculates isostatic compensation after sediment load
    # AIRY model see example given by Eisbacher 1991, p. 219

    subiso = np.zeros(v.nNode, dtype=np.float64)
    for node in range(v.nNode):
        dummy = 0.0
        dumdens = 0.0
        dumpor = 0.0
    # dummy is the total amount deposited in jti time step
    # calculate sediment density
    # average density of all sedim. types
        for m in range(v.nTotalMat):
            for t in range(v.jti):
                dummy = dummy+v.grid[node][t][m]
                dumdens = dumdens+v.grid[node][t][m]*v.density[m]
                dumpor = dumpor+v.grid[node][t][m]*v.porosity[node][t][m]

        if dummy > 0.00005:
            dumdens = dumdens/dummy
            dumpor = dumpor/dummy
        # average with water
            densitySed = dumpor*v.density[v.nTotalMat+1]+(1-dumpor)*dumdens
            para = (v.density[v.nTotalMat+1]-v.density[v.nTotalMat])/(v.density[v.nTotalMat+1]-densitySed)
            subiso[node] = dummy-(dummy/para)
            newBasem = v.readBasem[node]-subiso[node]-v.subsidence[node]*v.totalTime/1000
            diffe = v.basem[node]-newBasem
            v.basem[node] = newBasem
            v.surface[node] = v.readBasem[node]+dummy
            for t in range(v.jti-1):
                v.surf[t][node] = v.surf[t][node]-diffe

def subsidence():

    # calculate subsidence for a defined timestep dt
    # subsidence comes in m/1000 y
    # downward movement is positive
    # upward movement is negative

    temps = v.dt/1000.0
    for node in range(v.nNode):
        for j in range(v.jti-1):
            v.surf[j][node] = v.surf[j][node]-(v.subsidence[node]*temps)

    v.surface = v.surface-v.subsidence*temps
    v.basem = v.basem-v.subsidence*temps

def slope(te):
    punt = np.zeros((3, 3), dtype=np.float64)
    u = np.zeros(3, dtype=np.float64)
    b = np.zeros(3, dtype=np.float64)
    n = np.zeros((v.nElem, 3), dtype=np.float64)
    medNormal = np.zeros(3, dtype=np.float64)
    # this calculates the slope of each element and node
    for i in range(v.nElem):
        # coordenates x,y,z of punt 1
        punt[0][0] = v.xCo[v.inn[i][0]]
        punt[0][1] = v.yCo[v.inn[i][0]]
        punt[0][2] = v.surface[v.inn[i][0]]
        # coordenates x,y,z of punt 2
        punt[1][0] = v.xCo[v.inn[i][1]]
        punt[1][1] = v.yCo[v.inn[i][1]]
        punt[1][2] = v.surface[v.inn[i][1]]
        # coordenates x,y,z of punt 3
        punt[2][0] = v.xCo[v.inn[i][2]]
        punt[2][1] = v.yCo[v.inn[i][2]]
        punt[2][2] = v.surface[v.inn[i][2]]
        # calcula el vector del 'punt 1' al 'punt 2'
        # (x2-x1,y2-y1,z2-z1)
        u[0] = punt[1][0]-punt[0][0]
        u[1] = punt[1][1]-punt[0][1]
        u[2] = punt[1][2]-punt[0][2]
        # calcula el vector del 'punt 1' al 'punt 3'
        # (x3-x1,y3-y1,z3-z1)
        b[0] = punt[2][0]-punt[0][0]
        b[1] = punt[2][1]-punt[0][1]
        b[2] = punt[2][2]-punt[0][2]
        # calcula el vector normal al pla format pels vectors 'u' i 'b'
        # n=u x b (producte escalar de dos vectors)
        n[i][0] = (u[1]*b[2])-(u[2]*b[1])
        n[i][1] = -((u[0]*b[2])-(u[2]*b[0]))
        n[i][2] = (u[0]*b[1])-(u[1]*b[0])
        if n[i][2] < 0.0:
            n[i][0] = -n[i][0]
            n[i][1] = -n[i][1]
            n[i][2] = -n[i][2]
        v.slope[te][i] = (math.acos(n[i][2]/(math.sqrt((n[i][0]**2.0)+(n[i][1]**2.0)+(n[i][2]**2.0))))) * \
                                                                                57.29577951308232  # 180/PI

    for i in range(v.nNode):
        if v.nodElems[i][6] == 1:
            medNormal[0] = n[v.nodElems[i][0]][0]
            medNormal[1] = n[v.nodElems[i][0]][1]
            medNormal[2] = n[v.nodElems[i][0]][2]
        elif v.nodElems[i][6] == 2:
            medNormal[0] = (n[v.nodElems[i][0]][0]+n[v.nodElems[i][1]][0])/2
            medNormal[1] = (n[v.nodElems[i][0]][1]+n[v.nodElems[i][1]][1])/2
            medNormal[2] = (n[v.nodElems[i][0]][2]+n[v.nodElems[i][1]][2])/2
        elif v.nodElems[i][6] == 3:
            medNormal[0] = (n[v.nodElems[i][0]][0] +
                           n[v.nodElems[i][1]][0] +
                           n[v.nodElems[i][2]][0])/3
            medNormal[1] = (n[v.nodElems[i][0]][1] +
                           n[v.nodElems[i][1]][1] +
                           n[v.nodElems[i][2]][1])/3
            medNormal[2] = (n[v.nodElems[i][0]][2] +
                           n[v.nodElems[i][1]][2] +
                           n[v.nodElems[i][2]][2])/3
        elif v.nodElems[i][6] == 6:
            medNormal[0] = (n[v.nodElems[i][0]][0] +
                          n[v.nodElems[i][1]][0] +
                          n[v.nodElems[i][2]][0] +
                          n[v.nodElems[i][3]][0] +
                          n[v.nodElems[i][4]][0] +
                          n[v.nodElems[i][5]][0])/6
            medNormal[1] = (n[v.nodElems[i][0]][1] +
                          n[v.nodElems[i][1]][1] +
                          n[v.nodElems[i][2]][1] +
                          n[v.nodElems[i][3]][1] +
                          n[v.nodElems[i][4]][1] +
                          n[v.nodElems[i][5]][1])/6
            medNormal[2] = (n[v.nodElems[i][0]][2] +
                          n[v.nodElems[i][1]][2] +
                          n[v.nodElems[i][2]][2] +
                          n[v.nodElems[i][3]][2] +
                          n[v.nodElems[i][4]][2] +
                          n[v.nodElems[i][5]][2])/6

        v.slopeNode[te][i] = (math.acos(medNormal[2]/(math.sqrt((medNormal[0]**2.0)+(medNormal[1]**2.0) +
                                                                (medNormal[2]**2.0)))))*57.29577951308232  # 180/PI

def sea_level():
    v.seaLevel = np.interp(v.totalTime, v.sl[0][:], v.sl[1][:])

def waderdepth():
    v.wDepth[:] = v.head[:]+v.seaLevel-v.surface[:]
    mask = v.wDepth < 0.0
    v.wDepth[mask] = v.wDepth[mask]*(-0.0)
    v.wDepthE = np.zeros(v.nElem, dtype=float64)
    for i in range(v.nElem):
        w = np.zeros(3, float)
        w[0] = v.wDepth[v.inn[i][0]]
        w[1] = v.wDepth[v.inn[i][1]]
        w[2] = v.wDepth[v.inn[i][2]]
        if min(w) > 0.0:
            v.wDepthE[i] = (w[0]+w[1]+w[2])/3.0

def boundary_conditions():
    import random
    # It checks the boun#  print 'cTime:',v.cTime,'dt:',v.dt, 'totalTime:',v.totalTime, 'stepTime',v.stepTimedary
    # conditions to move them when sealevel changes

    nCLE = np.zeros(v.nElem, int)
    proxNod = np.zeros(2, int)
    nLAN = np.zeros(v.nElem, int)
    dista = np.zeros(v.nNode, dtype=np.float64)
    distaT = np.zeros(v.nNode, dtype=np.float64)
    headd = np.zeros(v.nNode, dtype=np.float64)

    # Add sealevel change to initial head boundary condition
    headd = np.copy(v.head)
    # for i in range(v.nNode):
    # if v.typBC[i]==0:
    # v.head[i]=v.headBC[i]
    mask = v.typBC == 0
    v.head[mask] = v.headBC[mask]
    # Copy boundary conditions to local for move boundary

    v.typBC = np.copy(v.readtypBC)
    v.q = np.copy(v.readQ)
    v.clastQ = np.copy(v.readClastQ)
    v.conClastBC = np.copy(v.readConClastBC)

    someElem = 0
    dista = 10000000000.0
    proxNod = 0
    someLand = 0

    # look for coast line and land elements

    for el in range(v.nElem):
        wa = np.zeros(3, float)
        wa[0] = v.wDepth[v.inn[el][0]]-v.head[v.inn[el][0]]
        wa[1] = v.wDepth[v.inn[el][1]]-v.head[v.inn[el][1]]
        wa[2] = v.wDepth[v.inn[el][2]]-v.head[v.inn[el][2]]
        if max(wa) > 0.0 and min(wa) <= 0.0:
            nCLE[el] = el
            someElem += 1

        if (wa[0] <= 0.0) and (wa[1] <= 0.0) and (wa[2] <= 0.0):
            nLAN[el] = el
            someLand += 1

    if someElem > 0:
        for node in range(v.nNode):
            # if a node is over sea level and have BC look for the nearest nodes in the coastline
            if v.wDepth[node] <= 0.0:
                tempc = 0
                for j in range(v.nClsMat):
                    if v.clastQ[node][j] > 0.0:
                        tempc = tempc+1
                if v.q[node] > 0.0 or v.typBC[node] < 1 or tempc > 0:
                    dista = np.zeros(v.nNode, float)
                    # search nodes near input node over sea level
                    for el in range(v.nElem):
                        if nCLE[el] > 0:
                            for i in range(3):
                                if (v.wDepth[v.inn[el][i]]-v.head[v.inn[el][i]] > 0.0) and (v.dist[node][v.inn[el][i]]) > 0.0:
                                    dista[v.inn[el][i]] = v.dist[node][v.inn[el][i]]
                    for i in range(v.nNode):
                        if dista[i] > 0.0:
                            canvi = 0
                            for ii in range(6):
                                if v.connectNodes[i][ii] == 0.0:
                                    canvi = canvi+1
                                else:
                                    if v.wDepth[v.connectNodes[i][ii]]-v.head[v.connectNodes[i][ii]] <= 0.0:
                                        canvi = canvi+1
                            if canvi >= 3:
                                dista[i] = 0.0
                    for i in range(v.nNode):
                        if dista[i] <= 0.0:
                            dista[i] = 1000000000.0
                    aixxx1 = np.argmin(dista)
                    distaT = dista
                    distaT[aixxx1] = 1000000000.0
                    aixxx2 = np.argmin(distaT)

                    if dista[aixxx1] == distaT[aixxx2]:
                        rannum = random.random()
                        if rannum<0.5:
                            aixxx1 = aixxx2

                    v.q[aixxx1] = v.q[node]+v.q[aixxx1]
                    v.q[node] = 0.0
                    v.typBC[aixxx1] = v.typBC[node]
                    for j in range(v.nClsMat):
                        v.clastQ[aixxx1][j] = v.clastQ[node][j]+v.clastQ[aixxx1][j]
                        v.conClastBC[aixxx1][j] = v.conClastBC[node][j]+v.conClastBC[aixxx1][j]
                        v.clastQ[node][j] = 0.0
                        v.conClastBC[node][j] = 0.0

    if someLand > 0:
        for el in range(v.nElem):
            if nLAN[el] > 0:
                v.head[v.inn[el][0]] = 0.0
                v.head[v.inn[el][1]] = 0.0
                v.head[v.inn[el][2]] = 0.0
                for mat in range(v.nClsMat):
                    v.conClast[v.inn[el][0]][mat] = 0.0
                    v.conClast[v.inn[el][1]][mat] = 0.0
                    v.conClast[v.inn[el][2]][mat] = 0.0

def mass_balance(material, cc):

    # function to correct mass balance due to hyperbolic dominance in
    # transport equation from advective transport term and eulerian approach
    # in the transport algorithm (non moving grid)

  j = np.ones(v.nElem, dtype=np.float64)
  j *= -1.0
  elemTag = np.zeros(v.nElem, int)

  multiplicationFactor = 1
  additionFactor = 0
  j = -1.0
  newMassTotalCc = 0.0
  oldMassTotalConc = 0.0
  sedInFlow = 0.0
  sediOutFlow = 0.0
  sediOutFlow_2 = 0.0
  volTotal = 0.0

#  inflow mass
  for node in range(v.nNode):
    sedInFlow = sedInFlow+(v.clastQ[node][material]*v.dt)

  for elem in range(v.nElem):
    # mass in suspension before transport
    oldMassTotalConc = oldMassTotalConc+((v.conClast[v.inn[elem][0]][material]+
                     v.conClast[v.inn[elem][1]][material]+v.conClast[v.inn[elem][2]][material])/
                     3.0)*(v.area[elem]*v.wDepthE[elem])

#      new mass in suspension after trasnport
    newMassTotalCc = newMassTotalCc+((cc[v.inn[elem][0]]+cc[v.inn[elem][1]]+cc[v.inn[elem][2]])/
                                    3.0)*(v.area[elem]*v.wDepthE[elem])

#       Calculation of outflow mass in a dt

  for node in range(v.nNode):
    if v.typBC[node] == 1:
      for numElems in range(v.nodElems[node][6]):
        if elemTag[v.nodElems[node][numElems]] != 1:
          for k in range(3):
            alter = v.inn[v.nodElems[node][numElems]][k]
            if alter != node:
              if v.typBC[alter] == 1:
                elemTag[v.nodElems[node][numElems]] = 1
                x1 = v.xCo[node]
                x2 = v.xCo[alter]
                y1 = v.yCo[node]
                y2 = v.yCo[alter]
                z1 = v.wDepth[node]
                z2 = v.wDepth[alter]
                vx = x2-x1
                vy = y2-y1
                beta = math.atan2(vy,vx)*180.0/3.1415927
                dist12 = math.sqrt(vx*vx+vy*vy)
                gamma = v.velDi3[v.nodElems[node][numElems]]-beta
                gamma = gamma*3.1415927/180.0
                r1 = math.sin(gamma)
                dista = r1*dist12
                if dista < 0.0:
                    dista = -dista
                crossection = dista*(z1+z2)/2.0
                qq = crossection*v.ve3[v.nodElems[node][numElems]]
                sediOutFlow = sediOutFlow+qq*v.dt*((cc[node]+cc[alter])/2.0)

  if sediOutFlow < 0.0:
        sediOutFlow = -sediOutFlow

  mBalance = sedInFlow-sediOutFlow-newMassTotalCc+oldMassTotalConc

  if newMassTotalCc == 0.0 and sediOutFlow == 0.0:
      factor = 0.0
  else:
      factor = (sedInFlow+oldMassTotalConc)/(newMassTotalCc+sediOutFlow)

  cc *= factor

# Tornem a calcular la massa total del sistema per comprovar que el balan\8D de massa ha funcionat per un dt. Aquest calcul es nom\8Es de control, es pot el.liminar
  newMassTotalCc = 0.0;
  for elem in range(v.nElem):
#       calculated mass in suspension
    newMassTotalCc = newMassTotalCc+((cc[v.inn[elem][0]]+cc[v.inn[elem][1]]+cc[v.inn[elem][2]])/
                                     3.0)*(v.area[elem]*v.wDepthE[elem])

# We have to re-calculated the new mass that flows out of the model
# Calculation of outflow mass
  elemTag = np.zeros(v.nElem, int)
  sediOutFlow = 0.0
  for node in range(v.nNode):
    if v.typBC[node] == 1:
      for numElems in range(v.nodElems[node][6]):
        if elemTag[v.nodElems[node][numElems]] != 1:
          for k in range(3):
            alter = v.inn[v.nodElems[node][numElems]][k]
            if alter != node:
              if v.typBC[alter] == 1:
                elemTag[v.nodElems[node][numElems]] = 1
                x1 = v.xCo[node]
                x2 = v.xCo[alter]
                y1 = v.yCo[node]
                y2 = v.yCo[alter]
                z1 = v.wDepth[node]
                z2 = v.wDepth[alter]
                vx = x2-x1
                vy = y2-y1
                beta = math.atan2(vy,vx)*180.0/3.1415927
                dist12 = math.sqrt(vx*vx+vy*vy)
                gamma = v.velDi3[v.nodElems[node][numElems]]-beta
                gamma = gamma*3.1415927/180.0
                r1 = math.sin(gamma)
                dista = r1*dist12
                if dista < 0.0:
                    dista = -dista
                crossection = dista*(z1+z2)/2.0
                qq = crossection*v.ve3[v.nodElems[node][numElems]]
                sediOutFlow = sediOutFlow+qq*v.dt*((cc[node]+cc[alter])/2.0)

# New loop to calculate in a diferent way the material that flows out of the model
# The material that can flow out of the model is the material located in the element that has nodes with ouflow of sediment

  sediOutFlow_2 = 0.0;
  for elem in range(v.nElem):
    if (((v.typBC[v.inn[elem][0]] == 1)and(v.typBC[v.inn[elem][1]] == 1))or\
        ((v.typBC[v.inn[elem][0]] == 1)and(v.typBC[v.inn[elem][2]] == 1))or\
        ((v.typBC[v.inn[elem][1]] == 1)and(v.typBC[v.inn[elem][2]] == 1))):

      sediOutFlow_2 = sediOutFlow_2+((cc[v.inn[elem][0]]+cc[v.inn[elem][1]]+cc[v.inn[elem][2]])/3.0)*(v.area[elem]*v.wDepthE[elem])

  if sediOutFlow < 0.0:
        sediOutFlow = -sediOutFlow
  v.totalVolSedOut = v.totalVolSedOut+sediOutFlow/v.density[material]
  v.totalVolSedOut_2 = v.totalVolSedOut_2+sediOutFlow_2/v.density[material]


import serial
import csv
import time
import numpy as np
import warnings
import serial
import serial.tools.list_ports

arduino_ports = [
    p.device
    for p in serial.tools.list_ports.comports()
    if 'Arduino' in p.description
]
if not arduino_ports:
    raise IOError("No Arduino found")
if len(arduino_ports) > 1:
    warnings.warn('Multiple Arduinos found - using the first')

Arduino = serial.Serial(arduino_ports[0])
Arduino.flush()
Arduino.reset_input_buffer()

start_time=time.time()
Distance = 0.5 # This is how long the lever arm is in feet

while True:
    while (Arduino.inWaiting()==0):
        pass
    try:
        data = Arduino.readline()
        dataarray = data.decode().rstrip().split(',')
        Arduino.reset_input_buffer()
        Force = float(dataarray[0])
        RPM = float (dataarray[1])
        Torque = Force * Distance
        HorsePower = Torque * RPM / 5252
        Run_time = time.time()-start_time
        print (Force , 'Grams',"," , RPM ,'RPMs',"," ,Torque,"ft-lbs",",", HorsePower, "hp", Run_time, "Time Elasped")
    except (KeyboardInterrupt, SystemExit,IndexError,ValueError):
        pass
    with open('DynoData.csv', 'w') as outfile:
        outfileWrite = csv.writer(outfile)
        while True:
            outfileWrite.writerow([Force, RPM])


# coding: utf-8
import csv
import os

os.chdir("/mine/git/study/Python/dataentrepreneur/programming")

with open('in.csv', 'r') as f:
  dat = [k for k in csv.reader(f)]

with open('out.csv', 'w') as f:
  writer = csv.writer(f)
  writer.writerows(dat)


from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from status import models, forms
from django.contrib.auth.decorators import login_required

# Create your views here.

@login_required
def add_comment(request,pk):
    post = get_object_or_404(models.Post, pk=pk)
    if request.method == 'POST':
        form = forms.CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post_detail', pk=post.pk)
    else:
        form = forms.CommentForm()
    return render(request, 'status/comment_form.html', {'form':form})

@login_required
def comment_approval(request,pk):
    comment = get_object_or_404(models.Comment,pk=pk)
    comment.approve()
    return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request,pk):
    comment = get_object_or_404(models.Comment,pk=pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('post_detail', pk=post_pk)


import sys
sys.setrecursionlimit(30000)
# the above recursion limit should be sufficient to solve the problem
# add your code below
first_ln = input().split()
M = input().split()
for i in range(len(M)):
    M[i] = int(M[i])
P = input().split()
for j in range(len(P)):
    P[j] = int(P[j])
n = int(first_ln[0])
k = int(first_ln[1])

def maxprofits():
    count = [0]*n
    count [0] = P[0]
    result = 0
    for i in range(1,n):
        count[i] = P[i]
        for j in range(i-1,-1,-1):
            if M[i]-M[j] >= k:
                max_p = count[j]+P[i]
                count[i] = max(max_p,count[i])
                tem_result = max(max_p,count[i])
                result = max(result,tem_result)
                break
            else:
                count[i] = max(count[i],count[j])
                result = max(result,count[i])
    return result
print(maxprofits())


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

urlpatterns = [
# here are my routes that render pages
    url(r'^$', views.index, name='landing'),
    # url(r'^success$', views.success, name='success'), this is being removed due to the fact we can use a different route from the secrets app
# here are my routes that have to do with login/logout and registration
    url(r'^register$', views.register, name='register'),
    url(r'^login$', views.login, name='login'),
    url(r'^logout$', views.logout, name='logout'),
# here's the route that has to do with friends, + add route parameter: /(?P<id>\d+)
#(?P<id>\d+) means= ?=0-1 occurrence, P=indicates we are going to have a route parameter that matches the <variable>, d+ is at least 1 digit or more.
    url(r'^add-friend/(?P<id>\d+)$', views.addFriend, name='add-friend'),
    url(r'^remove-friend/(?P<id>\d+)$', views.removeFriend, name='remove-friend'),
    #need a catch all
    url(r'^', views.index, name='default'),
]

#Named Route Notes:
#if I want to use named routes they look like this: name='register'
#   url(r'^register$', views.register, name='register'),
#so now if I want to use this in my html I am going to use a url helper, which looks like this:
#   <form action="{% url 'register' %}"....


import sys
from collections import deque
from collections import defaultdict
from utils import str_to_program
import copy
ADD=1
MUL=2
READ=3
WRITE=4
JUMP_NZERO=5
JUMP_EQZERO=6
SET_LT=7
SET_EQ=8
SET_BASE=9
HALT=99

class Program:
    def __init__(self, prog_data):
        self.prog_idx = 0
        self.prog_data = copy.deepcopy(prog_data)
        self.inputQ = deque()
        self.outputQ = deque()
        self.relative_base = 0
        self.op_map = {ADD:self.add, \
                       MUL:self.mul, \
                       READ:self.read,\
                       WRITE:self.write, \
                       JUMP_NZERO:self.jump_nz, \
                       JUMP_EQZERO:self.jump_eq, \
                       SET_LT:self.set_lt,
                       SET_EQ:self.set_eq, \
                       SET_BASE:self.set_base}

    def get_opcode(self):
        v = self.prog_data[self.prog_idx]
        return v % 100, [(v // 100)%10, (v // 1000) % 10, (v // 10000) % 10]

    def check_idx(self, idx):
        if idx >= len(self.prog_data):
            self.prog_data.extend([0]*(idx*2))

    def get_idx(self, idx):
        self.check_idx(idx)
        return self.prog_data[idx]

    def add(self, modes):
        out_idx = self.prog_data[self.prog_idx + 3] + (self.relative_base if modes[2] == 2 else 0)
        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        #print(f"modes {modes} relbase {relbase} relative_base {self.relative_base} inp1 {inp1}")
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        self.check_idx(out_idx)

        self.prog_data[out_idx] = inp1 + inp2
        #print(f"ADD {out_idx} set to {inp1} + {inp2} = {inp1+inp2}")

        self.prog_idx += 4

    def mul(self, modes):
        out_idx = self.prog_data[self.prog_idx + 3] + (self.relative_base if modes[2] == 2 else 0)
        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        self.check_idx(out_idx)
        self.prog_data[out_idx] = inp1 * inp2
        #print(f"MUL {out_idx} set to {inp1*inp2}")
        #print(f"MUL {out_idx} set to {inp1} * {inp2} = {inp1*inp2}")

        self.prog_idx += 4

    def read(self, modes):
        out_idx = self.prog_data[self.prog_idx + 1] + (self.relative_base if modes[0] == 2 else 0)
        self.check_idx(out_idx)
        self.prog_data[out_idx] = self.inputQ.popleft()
        #print(f"READ {out_idx} len {len(self.inputQ)}")

        self.prog_idx += 2

    def write(self, modes):
        inp1 = self.prog_data[self.prog_idx + 1]
        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        self.outputQ.append(inp1)

        self.prog_idx += 2

    def jump_nz(self, modes):
        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        if inp1 != 0:
            self.prog_idx = inp2
            #print(f"Non-zero jump to {self.prog_idx}")
        else:
            self.prog_idx += 3
            #print(f"Non-zero jump Ingored")

    def jump_eq(self, modes):
        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        if inp1 == 0:
            self.prog_idx = inp2
            #print(f"Equals zero jump to {self.prog_idx}")
        else:
            #print(f"Equals zero jump Ingored")
            self.prog_idx += 3

    def set_lt(self, modes):
        out_idx = self.prog_data[self.prog_idx + 3] + (self.relative_base if modes[2] == 2 else 0)

        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        if inp1 < inp2:
            self.prog_data[out_idx] = 1
            #print(f"Prog LT {out_idx} set to 1")
        else:
            self.prog_data[out_idx] = 0
            #print(f"Prog LT ignored")
            pass

        self.prog_idx += 4

    def set_eq(self, modes):
        out_idx = self.prog_data[self.prog_idx + 3] + (self.relative_base if modes[2] == 2 else 0)

        inp1 = self.prog_data[self.prog_idx + 1]
        inp2 = self.prog_data[self.prog_idx + 2]

        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)
        relbase = 0 if modes[1] == 0 else self.relative_base
        inp2 = inp2 if modes[1] == 1 else self.get_idx(relbase + inp2)

        if inp1 == inp2:
            #print(f"Prog EQ {out_idx} set to 1")
            self.prog_data[out_idx] = 1
        else:
            self.prog_data[out_idx] = 0
            #print(f"Prog EQ ignored")
            pass

        self.prog_idx += 4

    def set_base(self, modes):
        inp1 = self.prog_data[self.prog_idx + 1]
        relbase = 0 if modes[0] == 0 else self.relative_base
        inp1 = inp1 if modes[0] == 1 else self.get_idx(relbase + inp1)

        self.relative_base += inp1
        self.extend_prog_data()

        self.prog_idx += 2

    def waitingForInput(self):
        op, _ = self.get_opcode()
        if op == READ and len(self.inputQ) == 0:
            #print(f"waitingForInput returning True {self.prog_idx}")
            return True
        #print(f"not waitingForInput")
        return False

    def evalInstruction(self):
        op, modes = self.get_opcode()
        self.op_map[op](modes)

    def pushInput(self, inputVal):
        self.inputQ.append(inputVal)

    def isHalted(self):
        op, _ = self.get_opcode()
        return op == HALT

    def eval(self):
        #print(f"len(self.inputQ): {len(self.inputQ)}")
        #print(f"Idx: {self.prog_idx} op {self.prog_data[self.prog_idx:self.prog_idx+4]}")
        while not self.waitingForInput() and not self.isHalted():
            #print(f"Idx: {self.prog_idx} op {self.prog_data[self.prog_idx:self.prog_idx+4]} {type(self.prog_data[0])}")
            self.evalInstruction()
        #print(f"eval() returning {self.prog_idx} op {self.prog_data[self.prog_idx:self.prog_idx+4]} returns {self.outputQ}")
        rv = list(self.outputQ)
        self.outputQ = deque()
        return rv

    def restart(self):
        self.prog_idx = 0

    def extend_prog_data(self):
        if (self.relative_base*2) >= len(self.prog_data):
            self.prog_data.extend([0] * ((self.relative_base * 2) - len(self.prog_data) + 1))


from Geometry import *

width = 640
height = 480
center = height // 2
white = (255, 255, 255)
item = 0
fp = Point(0, 0)
sp = Point(0, 0)

# def paint(event):
#     global fp, sp , item
#     fp.x, fp.y = event.x, event.y
#     sp.x,sp.y = event.x + 1, event.y + 1
#     item = cv.create_line(fp.x, fp.y, sp.x, sp.y, fill="black", width=2)
#
#
# def update_paint(event):
#     global fp, sp , item
#     sp.x, sp.y = event.x, event.y
#     cv.coords(item, fp.x, fp.y, sp.x, sp.y)
#     print(fp.x, fp.y ,sp.x, sp.y)

# root = Tk()
#
# cv = Canvas(root, width=width, height=height, bg='white')
# cv.pack()
#
# cv.pack(expand=YES, fill=BOTH)
# # cv.bind("<Button-1>", paint)
# # cv.bind("<B1-Motion>", update_paint)
def testPointRightOfLine():
    line = LineSegment(Point(0, 0), Point(0, 7))
    a = Point(5, 5);
    return is_point_right_of_line(line, a)  # true

def testPointLeftOfLine():
    line = LineSegment(Point(0, 0), Point(0, 7))
    a = Point(-5, 5)
    return is_point_right_of_line(line, a)  # false

def testPointOnLine1():
    line = LineSegment(Point(0, 0), Point(4, 4))
    a = Point(3, 3);
    return is_point_right_of_line(line, a)  # false

def testPointOnLine():
    line = LineSegment(Point(4, 4), Point(0, 0))
    a = Point(3, 3);
    return is_point_right_of_line(line, a)  # false

def mytest():
    l1 = LineSegment(Point(568, 119), Point(507, 246))
    l2 = LineSegment(Point(532, 398), Point(539, 398))
    print(get_line_intersection(l1, l2).x, get_line_intersection(l1, l2).y)
    return do_lines_intersect(l1, l2)

# print("first x - %s : first y - %s : second x - %s : second y - %s :" %(l1.first.x, l1.first.y, l1.second.x, l1.second.y))
print(testPointLeftOfLine())
print(testPointOnLine1())
print(testPointRightOfLine())
print(mytest())

# root.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 18 16:32:22 2021

@author: DELL
"""

from tkinter import *
import random

root=Tk()
root.title("Picnic bag list")
root.geometry("400x400")
list1=[]

entry=Entry(root)
entry.place(relx=0.5, rely=0.1, anchor=CENTER)
label_list=Label(root)
label_list.place(relx=0.5, rely=0.2, anchor=CENTER)
def add():
    list1.append(entry.get())
    label_list["text"]="The list of your items in the bag"+str(list1)

button2=Button(root, text="Add", command=add)
button2.place(relx=0.5, rely=0.3, anchor=CENTER)

label1=Label(root)

def random_number():
    random_no=random.randint(0, 4)
    print(random_no)
    random_lucky_friend=list1[random_no]
    label1["text"]="The item which you should is: "+random_lucky_friend

button1=Button(root, text="Which item should I pick", command=random_number)
button1.place(relx=0.5, rely=0.5, anchor=CENTER)
label1.place(relx=0.5, rely=0.74, anchor=CENTER)

root.mainloop()


import os

from django.core.wsgi import get_wsgi_application
from pprint import pprint

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "wat.settings")
os.environ.setdefault("SECRET_KEY", "wat.settings")

application = get_wsgi_application()

from wot_api.models import ExpectedWN8Values, VehicleStatisticItem

def calculate_wn8(stats: VehicleStatisticItem, expected: ExpectedWN8Values):
    battles = stats.all.get("battles")
    winrate = stats.all.get("wins") / battles * 100

    rWIN = winrate / expected.exp_win_rate
    rDAMAGE = stats.all.get("damage_dealt") / expected.exp_damage
    rSPOT = stats.all.get("spotted") / expected.exp_spot
    rFRAG = stats.all.get("frags") / expected.exp_frag
    rDEF = stats.all.get("dropped_capture_points") / expected.exp_def

    rWINc = max(0, (rWIN - 0.71) / (1 - 0.71))
    rDAMAGEc = max(0, (rDAMAGE - 0.22) / (1 - 0.22))
    rFRAGc = max(0, min(rDAMAGEc + 0.2, (rFRAG - 0.12) / (1 - 0.12)))
    rSPOTc = max(0, min(rDAMAGEc + 0.1, (rSPOT - 0.38) / (1 - 0.38)))
    rDEFc = max(0, min(rDAMAGEc + 0.1, (rDEF - 0.10) / (1 - 0.10)))

    wn8 = 980 * rDAMAGEc \
          + 210 * rDAMAGEc * rFRAGc \
          + 155 * rFRAGc * rSPOTc \
          + rSPOTc \
          + 75 * rDEFc * rFRAGc \
          + 145 * min( 1.8, rWINc)

    return wn8

stats = VehicleStatisticItem(
    all={
        "battles": 100,
        "damage_dealt": 3665,
        "spotted": 1.84,
        "frags": 1.88,
        "dropped_capture_points": 1.51,
        "wins": 70.5
    }
)

expected = ExpectedWN8Values(
    exp_damage=1840.29,
    exp_spot=1.41,
    exp_frag=0.93,
    exp_def=0.76,
    exp_win_rate=48.73
)

calculate_wn8(stats, expected)


from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput

from src.db.DbUtils import add_row

class AddRowCityPopup(Popup):
    ui_class = ObjectProperty()

    def add_value(self, obj):
        self.dismiss()
        model_obj = [
            {'name': str(self.name_input.text)}
        ]
        data = dict([
            ('model_class', self.ui_class.model_class),
            ('value', model_obj),
        ])
        add_row(data)
        self.ui_class.update_screen()

    def __init__(self, ui_class, **kwargs):
        super(AddRowCityPopup, self).__init__(**kwargs)
        self.size = [400, 400]
        self.size_hint = [None, None]
        self.auto_dismiss = False
        self.ui_class = ui_class

        main_layout = BoxLayout(orientation='vertical')
        self.name_input = TextInput()
        data_scroll = ScrollView(do_scroll_y=True, do_scroll_x=False)
        data_layout = Builder.load_string('''GridLayout:
                size:(root.width, root.height)
                size_hint_x: 1
                size_hint_y: None
                cols: 2
                height: self.minimum_height
                row_default_height: 50
                row_force_default: True''')

        data_layout.add_widget(Label(text='Наименование', size_hint_y=None, height=dp(30)))
        data_layout.add_widget(self.name_input)
        data_scroll.add_widget(data_layout)
        main_layout.add_widget(data_scroll)

        save = Button(size_hint=[1, 0.2], text='Сохранить')
        main_layout.add_widget(save)
        save.fbind('on_press', self.add_value)
        cancel = Button(size_hint=[1, 0.2], text='Отмена')
        main_layout.add_widget(cancel)
        cancel.bind(on_press=self.dismiss)

        self.add_widget(main_layout)


import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from vk_api.utils import get_random_id
from vk_api.keyboard import VkKeyboard, VkKeyboardColor
import random
import re
import urllib.request
import requests
from bs4 import BeautifulSoup
import xlrd
from datetime import*

def get_sch():
    page = requests.get('https://www.mirea.ru/schedule/')
    soup = BeautifulSoup(page.text, 'html.parser')
    result = soup.find('div', {'class' : 'rasspisanie'}).\
        find(string = 'Институт информационных технологий').\
        find_parent('div').\
        find_parent('div').\
        findAll(target = '_blank')
    ref_list = []
    for i in result:
        ref_list.append(i.attrs['href'])
    return ref_list

def download_link_save(group, list_links):
    group = group[8] + group[9]
    dl = -1
    if group == '21':
        dl = 0
    elif group == '20':
        dl = 1
    elif group == '19':
        dl = 2
    f = open('file.xlsx', 'wb')
    ulink = requests.get(list_links[dl])
    f.write(ulink.content)
    f.close()

def download_link_temp(group, list_links):
    group = group[8] + group[9]
    dl = -1
    if group == '21':
        dl = 0
    elif group == '20':
        dl = 1
    elif group == '19':
        dl = 2
    f = open('file2.xlsx', 'wb')
    ulink = requests.get(list_links[dl])
    f.write(ulink.content)
    f.close()

def xl_oneday(sheet, week, day, group, typeout):
    timenow = datetime.now()
    weekdays_dict = {
        1 : 'Понедельник',
        2 : 'Вторник',
        3 : 'Среда',
        4 : 'Четверг',
        5 : 'Пятница',
        6 : 'Суббота',
    }
    daysweek_dict = {
        'понедельник' : 0,
        'вторник' : 1,
        'среда' : 2,
        'четверг' : 3,
        'пятница' : 4,
        'суббота' : 5,
    }
    months_dict = {
        1 : 'января',
        2 : 'февраля',
        3 : 'марта',
        4 : 'апреля',
        5 : 'мая',
        6 : 'июня',
        7 : 'июля',
        8 : 'августа',
        9 : 'сентября',
        10 : 'октября',
        11 : 'ноября',
        12 : 'декабря'
    }
    column = None
    for i in range(sheet.ncols - 1):
        if sheet.cell_value(1, i) == group:
            column = i
            break
    if column == None:
        return 'Увы, вашей группы не существует'
    list_subj = []
    if typeout == 'dayweek':
        wd = 3 + 12 * daysweek_dict[week]
        list_subj.append('Нечётная неделя:')
        for i in range(1, 7):
            if sheet.cell_type(wd, column) == 0:
                list_subj.append('{}) —'.format(i))
            else:
                list_subj.append('{}) {}, {}, {}, {}'.format(i, sheet.cell_value(wd, column), sheet.cell_value(wd, column + 1), sheet.cell_value(wd, column + 2), sheet.cell_value(wd, column + 3)))
            wd += 2
        wd = 4 + 12 * daysweek_dict[week]
        list_subj.append('Чётная неделя:')
        for i in range(1, 7):
            if sheet.cell_type(wd, column) == 0:
                list_subj.append('{}) —'.format(i))
            else:
                list_subj.append('{}) {}, {}, {}, {}'.format(i, sheet.cell_value(wd, column), sheet.cell_value(wd, column + 1), sheet.cell_value(wd, column + 2), sheet.cell_value(wd, column + 3)))
            wd += 2
        outcome = '\n'.join(list_subj)
    elif typeout == 'day':
        timenow += timedelta(days = day)
        list_subj.append('Расписание на {} {}'.format(timenow.day, months_dict[timenow.month]))
        wd = (datetime.now()).weekday()
        wd = wd * 12 + 3 + 12 * day
        if week == 0:
            wd += 1
        for i in range(1, 7):
            if sheet.cell_type(wd, column) == 0:
                list_subj.append('{}) —'.format(i))
            else:
                list_subj.append('{}) {}, {}, {}, {}'.format(i, sheet.cell_value(wd, column), sheet.cell_value(wd, column + 1), sheet.cell_value(wd, column + 2), sheet.cell_value(wd, column + 3)))
            wd += 2
        outcome = '\n'.join(list_subj)
    if typeout == 'week':
        ots = 0
        if week == 0:
            ots += 1
        if day == 1:
            timenow += timedelta(days = 7)
        timenow -= timedelta(days = datetime.now().weekday())
        for i in range(1, 7):
            days = (i - 1) * 12 + 3 + ots
            list_subj.append('Расписание на {}, {} {}:'.format(weekdays_dict[i], timenow.day, months_dict[timenow.month]))
            for j in range(1, 7):
                if sheet.cell_type(days + (j - 1) * 2, column) == 0:
                    list_subj.append('{}) —'.format(j))
                else:
                    list_subj.append('{}) {}, {}, {}, {}'.format(j, sheet.cell_value(days + (j - 1) * 2, column), sheet.cell_value(days + (j - 1) * 2, column + 1), sheet.cell_value(days + (j - 1) * 2, column + 2), sheet.cell_value(days + (j - 1) * 2, column + 3)))
            list_subj.append('\n')
            timenow += timedelta(days = 1)
        outcome = '\n'.join(list_subj)
    return outcome

if __name__ == '__main__':
    print(get_sch())


'''
 Write a function called letter_counter() which accepts a string and
 returns a function. When the inner function is invoked, it should
 accept a paremeter, which is a letter, and the inner function should
 return the number of times that letter appears in the string.
 This inner function should be case insensitive.
'''

def letter_counter(input_string):
	# downcase the input string for simplicity
	input_string = input_string.lower()

	def char_count(char):
		# tally the number of chars in the input string.
		count = 0
		if char.lower() in input_string:
			count += input_string.count(char)
		return count
	return char_count

# counter = letter_counter('Amazing')
# print(counter('a')) # 2
# print(counter('m')) # 1

# counter2 = letter_counter('This Is Really Fun!')
# print(counter2('i')) # 2
# print(counter2('t')) # 1

counter3 = letter_counter('Keenan')
print(counter3('k')) # 1
print(counter3('e')) # 2
print(counter3('n')) # 2
print(counter3('a')) # 1