def rgb_colours(red, green, blue):
  redF = toHex(red / 16)
  redS = toHex(red % 16)
  greenF = toHex(green / 16)
  greenS = toHex(green % 16)
  blueF = toHex(blue / 16)
  blueS = toHex(blue % 16)
  print('#',redF,redS,greenF,greenS,blueF,blueS,sep='');

def toHex(num):
  if(int(num) == 10):
    return 'A'
  if(int(num) == 11):
    return 'B'
  if(int(num) == 12):
    return 'C'
  if(int(num) == 13):
    return 'D'
  if(int(num) == 14):
    return 'E'
  if(int(num) == 15):
    return 'F'
  if(int(num) == 16):
    return '0'
  return int(num)

rgb_colours(65, 244, 244)


import logging
import random
import requests

def logerrors(func):
    from functools import wraps

    @wraps(func)
    def logged(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except requests.exceptions.Timeout:
            return "[timeout] The internet is problematic :sweetieskeptical:"
        except Exception as e:
            print("\n\n####\n\n")
            logging.exception("Error in " + func.__name__)
            print("\n\n####\n\n")
            return "[{}] My code is problematic :sweetieoops:".format(type(e).__name__)

    return logged

def randomstr():
    return "%08x" % random.randrange(16 ** 8)

def botcmd(*args, **kwargs):
    """Decorator for bot command functions
    based on http://sourceforge.net/p/pythonjabberbot/code/ci/master/tree/jabberbot.py
    """

    def decorate(func, hidden=False, name=None, thread=False):
        setattr(func, "_bot_command", True)
        setattr(func, "_bot_command_hidden", hidden)
        setattr(func, "_bot_command_name", name or func.__name__)
        return func

    if len(args):
        return decorate(args[0], **kwargs)
    else:
        return lambda func: decorate(func, **kwargs)


from typing import List
import pytest

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        dp = [1 for _ in nums]

        for i in range(1,len(nums)):
            for j in range(i):
                if nums[i]>nums[j]:
                    dp[i]=max(dp[i], dp[j]+1)

        result = 0
        for v in dp:
            result=max(result,v)

        return result

@pytest.mark.parametrize("nums, want", [
    ([10,9,2,5,3,7,101,18], 4),
])
def test_lengOfLIS(nums, want):
    assert Solution().lengthOfLIS(nums) == want


import numpy as np

import json
import traceback

def assertions_all(user_vals, expected_vals, test_name, rtol=1e-5, atol=1e-8):
    if not assertions(user_vals, expected_vals, 'type', test_name, rtol=rtol, atol=atol):
        return False
    if not assertions(user_vals, expected_vals, 'shape', test_name, rtol=rtol, atol=atol):
        return False
    if not assertions(user_vals, expected_vals, 'closeness', test_name, rtol=rtol, atol=atol):
        return False
    return True

def assertions(user_vals, expected_vals, test_type, test_name, rtol=1e-5, atol=1e-8):
    if test_type == 'type':
        try:
            assert type(user_vals) == type(expected_vals)
        except Exception as e:
            print('Type error, your type doesnt match the expected type.')
            print('Wrong type for %s' % test_name)
            print('Your type:   ', type(user_vals))
            print('Expected type:', type(expected_vals))
            return False
    elif test_type == 'shape':
        try:
            assert user_vals.shape == expected_vals.shape
        except Exception as e:
            print('Shape error, your shapes doesnt match the expected shape.')
            print('Wrong shape for %s' % test_name)
            print('Your shape:    ', user_vals.shape)
            print('Expected shape:', expected_vals.shape)
            return False
    elif test_type == 'closeness':
        try:
            assert np.allclose(user_vals, expected_vals, rtol=rtol, atol=atol)
        except Exception as e:
            print('Closeness error, your values dont match the expected values.')
            print('Wrong values for %s' % test_name)
            print('Your values:    ', user_vals)
            print('Expected values:', expected_vals)
            return False
    return True

def print_failure(cur_test, num_dashes=51):
    print('*' * num_dashes)
    print('The local autograder will not work if you do not pass %s.' % cur_test)
    print('*' * num_dashes)
    print(' ')

def print_name(cur_question):
    print(cur_question)

def print_outcome(short, outcome, point_value, num_dashes=51):
    score = point_value if outcome else 0
    if score != point_value:
        print("{}: {}/{}".format(short, score, point_value))
        print('-' * num_dashes)

def run_tests(tests, summarize=False):
    # calculate number of dashes to print based on max line length
    title = "AUTOGRADER SCORES"
    num_dashes = calculate_num_dashes(tests, title)

    # print title of printout
    print(generate_centered_title(title, num_dashes))

    # Print each test
    scores = {}
    for t in tests:
        if not summarize:
            print_name(t['name'])
        try:
            res = t['handler']()
        except Exception:
            res = False
            traceback.print_exc()
        if not summarize:
            print_outcome(t['autolab'], res, t['value'], num_dashes)
        scores[t['autolab']] = t['value'] if res else 0

    points_available = sum(t['value'] for t in tests)
    points_gotten = sum(scores.values())
    print("Total score: {}/{}\n".format(points_gotten, points_available))

    print("Summary:")
    print(json.dumps({'scores': scores}))

def calculate_num_dashes(tests, title):
    """Determines how many dashes to print between sections (to be ~pretty~)"""
    # Init based on str lengths in printout
    str_lens = [len(t['name']) for t in tests] + [len(t['autolab']) + 4 for t in tests]
    num_dashes = max(str_lens) + 1

    # Guarantee minimum 5 dashes around title
    if num_dashes < len(title) - 4:
        return len(title) + 10

    # Guarantee even # dashes around title
    if (num_dashes - len(title)) % 2 != 0:
        return num_dashes + 1

    return num_dashes

def generate_centered_title(title, num_dashes):
    """Generates title string, with equal # dashes on both sides"""
    dashes_on_side = int((num_dashes - len(title)) / 2) * "-"
    return dashes_on_side + title + dashes_on_side

def save_numpy_array(np_array, file_name):
    with open(file_name, 'wb') as f:
        np.save(f, np_array)

def load_numpy_array(file_path):
    with open(file_path, 'rb') as f:
        output = np.load(f, allow_pickle=True)
    return output

Building Autograd Engine PyTorch/autograder/helpers.py


from . import RES_PATH

stylesheet_instance = None

def get_stylesheet(name):
    global stylesheet_instance
    if not stylesheet_instance:
        stylesheet_instance = Stylesheets()
    return stylesheet_instance.get_stylesheet(name)

class Stylesheets(object):
    def __init__(self):
        self._stylesheets = {}
        self.make_stylesheet("main", str(RES_PATH / "stylesheets" / "main.css"))
        self.make_stylesheet("ribbon", str(RES_PATH / "stylesheets" / "ribbon.css"))
        self.make_stylesheet(
            "ribbonPane", str(RES_PATH / "stylesheets" / "ribbonPane.css")
        )
        self.make_stylesheet(
            "ribbonButton", str(RES_PATH / "stylesheets" / "ribbonButton.css")
        )
        self.make_stylesheet(
            "ribbonSmallButton", str(RES_PATH / "stylesheets" / "ribbonSmallButton.css")
        )

    def make_stylesheet(self, name, path):
        with open(path) as data_file:
            stylesheet = data_file.read()

        self._stylesheets[name] = stylesheet

    def get_stylesheet(self, name):
        stylesheet = ""
        try:
            stylesheet = self._stylesheets[name]
        except KeyError:
            print("stylesheet " + name + " not found")
        return stylesheet


import xdf_reader as xr
import PulseDataAdjuster as pda

exp = xr.xdfReader(file_path='exp12(head)/untitled2.xdf',show=False)
exp.findStreamName()
exp.samplingRateVerify()

eeg = exp.getSeriesAndStamps(streamName = 'Apstest',channel=1)
eeg_target = pda.DataAdjuster(timeSeries=eeg['timeSeries'],timeStamps=eeg['timeStamps'],srate=1000,minutes=10)
eeg_target.findpeak(order=400,show=False,diff_max=1.4,diff_min=0.5)

aux = exp.getSeriesAndStamps(streamName = 'Apstest',channel=2)
aux_target = pda.DataAdjuster(timeSeries=aux['timeSeries'],timeStamps=aux['timeStamps'],srate=1000,minutes=10)
aux_target.findpeak(order=400,show=False,diff_max=1.4,diff_min=0.5)

#pda.compareSignal(peakValidation=False,stamp1=eeg_target.getTimeStamp(),stamp2=aux_target.getTimeStamp(),data1=eeg_target.getOutput(),data2=aux_target.getOutput(),peak1=eeg_target.getPeakIndex(),peak2=aux_target.getPeakIndex())

sr1 = exp.getSeriesAndStamps(streamName = 'BioSigPressure',channel=1)
sr1_target = pda.DataAdjuster(timeSeries=sr1['timeSeries'],timeStamps=sr1['timeStamps'],srate=778,minutes=5)
sr1_target.straightOffsetDelete()
#sr1_target.bessel()
sr1_target.FIR(numtaps=701,show=False)
sr1_target.subFilAndOutput()
#sr1_target.FourierTransform()
sr1_target.movemean()
#sr1_target.movemean(show=False)
sr1_target.findpeak_easy(order=300,look=True,show=False,diff_max=1.5,diff_min=0.4)
#pda.compareSignal(peakValidation=True,stamp1=eeg_target.getTimeStamp(),stamp2=sr1_target.getTimeStamp(),data1=eeg_target.getOutput(),data2=sr1_target.getOutput(),peak1=eeg_target.getPeakIndex(),peak2=sr1_target.getPeakIndex())

sr2 = exp.getSeriesAndStamps(streamName = 'BioSigPressure',channel=2)
sr2_target = pda.DataAdjuster(timeSeries=sr2['timeSeries'],timeStamps=sr2['timeStamps'],srate=778,minutes=5)
sr2_target.straightOffsetDelete()
#sr2_target.reverseSignal()
sr2_target.FIR(numtaps=701,show=False)
sr2_target.subFilAndOutput()
sr2_target.movemean()
#sr2_target.movemean()
#sr2_target.FourierTransform()
sr2_target.findpeak_easy(order=300,look=False,show=False)

pda.compareSignal(show=False,data2_shift =0,peakValidation=True,stamp2=sr1_target.getTimeStamp(),stamp1=eeg_target.getTimeStamp(),data2=sr1_target.getOutput(),data1=eeg_target.getOutput(),peak2=sr1_target.getPeakIndex(),peak1=eeg_target.getPeakIndex())
pda.compareSignal(show=False,data2_shift =0,peakValidation=True,stamp2=sr2_target.getTimeStamp(),stamp1=eeg_target.getTimeStamp(),data2=sr2_target.getOutput(),data1=eeg_target.getOutput(),peak2=sr2_target.getPeakIndex(),peak1=eeg_target.getPeakIndex())
#pda.compareSignal(peakValidation=True,stamp1=sr1_target.getTimeStamp(),stamp2=sr2_target.getTimeStamp(),data1=sr1_target.getOutput(),data2=sr2_target.getOutput(),peak1=sr1_target.getPeakIndex(),peak2=sr2_target.getPeakIndex())
# --------------------------------------------------------

ptt = pda.PTTcalculater(data1=sr1_target.getPeakTime(),data2=sr2_target.getPeakTime())
ptt.calclatePTT()
ptt.movemean(show=False)
ptt1=ptt.getPTT()

ptt = pda.PTTcalculater(data1=eeg_target.getPeakTime(),data2=aux_target.getPeakTime())
ptt.calclatePTT()
ptt.movemean(show=False)
ptt2=ptt.getPTT()

cpptt = pda.comparePTT(ptt_target=ptt1,ptt_ref=ptt2,reverse=False,reverse2=True)
cpptt.showGraph()


#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import networkx as nx
import numpy as np

value = []

def createGraphDump(filename):
    G = nx.Graph()
    for file in filename:
        with open(file, 'r') as f:
            for line in f:
                tmp = line.split()
                for i in range(len(tmp)):
                    if tmp[i][1:-2] == 'block':
                        close_block = tmp[i+1][:-1]
                        block_l = i+1
                        break

                for i in range(block_l, len(tmp)):
                    if tmp[i][1:-2] == 'block':
                        open_block = tmp[i+1][:-1]
                        break
                if int(open_block) > 677167:
                    continue
                if close_block != 'null' and int(close_block) <= 677167:
                    continue  # not closed or closed after 2021-03-31 23:57

                cap = int(tmp[1])
                n1 = tmp[2][2:-2]
                n2 = tmp[3][1:-2]

                if cap <= 0:
                    continue
                if(G.has_edge(n1, n2)):
                    G[n1][n2]['capacity'] = G[n1][n2]['capacity'] + cap
                else:
                    G.add_edges_from([(n1, n2, {'capacity': cap})])

    return G

def createGraph(filename):
    G = nx.Graph()
    for file in filename:
        with open(file, 'r') as f:
            data = json.load(f)
            for i in range(len(data)):
                if data[i]['open']['block'] > 677167:
                    continue

                if data[i]['close']['block'] != None and data[i]['close']['block'] <= 677167:
                    continue  # not closed or closed after 2021-03-31 23:57

                n1 = data[i]['nodes'][0]
                n2 = data[i]['nodes'][1]
                cap = data[i]['satoshis']
                if cap <= 0:
                    continue
                if(G.has_edge(n1, n2)):
                    G[n1][n2]['capacity'] = G[n1][n2]['capacity'] + cap # merge the multiple channels between two users into one channel
                else:
                    G.add_edges_from([(n1, n2, {'capacity': cap})])

    return G

def graphStatics(graph):
    print('nodes:', len(graph.nodes()))
    print('edges:', len(graph.edges()))

    single_channel_user = 0
    for node in graph.nodes():
        if graph.degree(node) == 1:
            single_channel_user += 1
    print('number of single-channel user:', single_channel_user, len(graph.nodes()),
          single_channel_user / len(graph.nodes()))

    capacity = []
    for edge in graph.edges():
        capacity.append(graph[edge[0]][edge[1]]['capacity'])
    capacity = np.array(capacity)
    print('max, min, mean, median, var of capacity:', np.max(capacity), np.min(
        capacity), np.mean(capacity), np.median(capacity), np.var(capacity))

def reassignGraph(graph):
    # change the user's pubkey identifier to a numeric identifier
    nodes = sorted(graph.nodes())
    assign = {}
    for i in range(len(nodes)):
        assign[nodes[i]] = i
    return nx.relabel_nodes(graph, assign)

def main():

    G = createGraph(['channel_1_600000.json', 'channel_600001_677167.json'])
    graphStatics(G)

    nx.write_edgelist(G, 'lightning.edgelist', data=['capacity'])

    G_simplified = reassignGraph(G)
    nx.write_edgelist(
        G_simplified, 'lightning_simplified.edgelist', data=['capacity'])

    G_component = list(G.subgraph(c) for c in nx.connected_components(G))[
        0]  # the largest component
    nx.write_edgelist(reassignGraph(
        G_component), 'lightning_simplified_component.edgelist', data=['capacity'])

    graphStatics(G_component)

main()


from typing import cast
from Banco import Conexao

import sqlite3
from datetime import datetime

class Reuniao:

    # def __init__(self, reuniId=0, dateData=datetime, txtNome="", txtTema="", txtLocal=""):
    # self.reuni_id = reuniId
    # self.reuni_data = dateData
    # self.reuni_nome = txtNome
    # self.reuni_tema = txtTema
    # self.reuni_local = txtLocal

    def criar(self):
        conn = Conexao()

        conn.createTables()

    def insertReuniao(self, date, tema, local):

        self.reuni_tema = tema
        self.reuni_local = local
        self.reuni_data = date

        try:
            conn = Conexao()
            conexao = conn.conectar()
            cursor = conexao.cursor()
            sqlInsert = "insert into reuniao( reuni_data, reuni_tema, reuni_local) values ( '"+ self.reuni_data +"', '"+ self.reuni_tema +"', '"+ self.reuni_local +"' )"
            # dataTuple = (self.reuni_tema, self.reuni_local)

            cursor.execute( sqlInsert )

            conexao.commit()

            cursor.close()

            conexao.close()

            # return True

            return "Reunião cadastrada com sucesso!"
        except sqlite3.Error as erro:
            return "Ocorreu um erro na inserção da reunião.", erro

    def updateReuniao(self, id="", date="", tema="", local=""):

        self.reuni_id = id
        self.reuni_tema = tema
        self.reuni_local = local
        self.reuni_data = date

        banco = Conexao()

        try:
            # sqlUpdate = "update reuniao set reuni_data='"+self.reuni_data+"', reuni_tema='"+self.reuni_tema+"', reuni_local='"+self.reuni_local+"' where reuni_id='"+self.reuni_id+"'"
            sqlUpdate = "update reuniao set reuni_tema='"+self.reuni_tema+"' where reuni_id = '", self.reuni_id ,"'"
            # dataTuple = (self.reuni_data, self.reuni_tema, self.reuni_local, self.reuni_id)
            c = banco.conexao.cursor()
            c.execute(sqlUpdate)
            banco.conexao.commit()
            c.close()

            return "Reunião atualizada com sucesso!"
        except sqlite3.Error as erro:
            return "Ocorreu um erro na update da reunião.", erro

    def findAllReuniao():
        banco = Conexao()
        try:
            c = banco.conexao.cursor()
            c.execute(
                "select reuni_id, reuni_data, reuni_horario, reuni_nome, reuni_tema, reuni_local, reuni_condominio from reuniao")
            records = c.fetchall()
            reunioes = []
            for row in records:
                reunioes.append(
                    Reuniao(row[0], row[1], row[2], row[3],  row[4], row[5], row[6]))

            c.close()
        except sqlite3.Error as erro:
            return []

    def deleteReuniao(self):
        banco = Conexao()

        try:
            sqlUpdate = "delete from reuniao reuni_id=?"
            dataTuple = (self.reuni_id)
            c = banco.conexao.cursor()
            c.execute(sqlUpdate, dataTuple)
            banco.conexao.commit()
            c.close()

            return "Reunião apagada com sucesso!"
        except sqlite3.Error as erro:
            return "Ocorreu um erro na delete da reunião.", erro

    def consultar_reuniao(self):
        conn = Conexao()

        conexao = conn.conectar()

        cursor = conexao.cursor()

        sql = "SELECT * FROM reuniao"

        resultado = cursor.execute(sql).fetchall()

        cursor.close()

        conexao.close()

        return resultado


import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import pylab as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']   #设置显示中文
from Dynamic_SEIR_model import *
from helper_fun_epi_model import *
import warnings
warnings.filterwarnings('ignore')

## Some assumptions
China_population = 1400000000
Hubei_population = 58500000

df = pd.read_csv("DXYArea.csv")
"""
Data Cleaning
"""
df['date'] = pd.to_datetime(df['date'])
df = df[df['date'] > datetime.datetime(2019, 12, 7)]  # first day is 2019-12-08
df = df[df['date'] != df['date'].max()]    # remove todays' records (since it can be incompleted)
# print(df)

'''
Dataset preperation
'''
df['R'] = df['cured'] + df['dead']   # 模型中的R=治愈+死亡
SIR_data = df[['date', 'Days', 'countryCode','province', 'city', 'net_confirmed', 'suspected', 'R',
              ]].rename(columns={"net_confirmed": "I", "suspected": "E"})
#SIR_data.tail(3)

# China total全中国
# Use data before 2020-02-14 for train model，after this date for confirm
China_df = SIR_data[SIR_data['date'] < datetime.datetime(2020, 2, 14)]
China_total = get_China_total(China_df)
China_total.tail(2)
# print(China_total)
# print(China_df)
# print(China_total.tail(2))

Dynamic_SEIR1 = Train_Dynamic_SEIR(epoch = 10000, data = China_total,
                 population = 1400000000, rateAl = 1/7, rateIR=1/14, c = 1, b = -10, alpha = 0.08)

estimation_df = Dynamic_SEIR1.train()
est_beta = Dynamic_SEIR1.rateSI
est_alpha = Dynamic_SEIR1.alpha
est_b = Dynamic_SEIR1.b
est_c = Dynamic_SEIR1.c
population = Dynamic_SEIR1.numIndividuals

estimation_df.tail(2)
# print(estimation_df.tail(2))

Dynamic_SEIR1.plot_fitted_beta_R0(China_total)

Dynamic_SEIR1.plot_fitted_result(China_total)

## use the last observation as the initial point in the new SEIR model
# I is the net confirmed cases (total confirmed case - heal - died)
I0 = list(China_total['I'])[-1]
R0 = list(China_total['R'])[-1]
# suppose the total number of individuals within incubation period is 4 time of current suscepted cases
E0 = list(China_total['E'])[-1] *4
S0 = population - I0 - E0 - R0

seir_new = dynamic_SEIR(eons=50, Susceptible=S0, Exposed = E0,
                    Infected=I0, Resistant=R0, rateIR=1/14,
                    rateAl = 1/7, alpha = est_alpha, c = est_c, b = est_b, past_days = China_total['Days'].max())
result = seir_new.run(death_rate = 0.02) # assume death rate is 2%
seir_new.plot_noSuscep('Dynamic SEIR for China total', 'population', 'Date', starting_point = China_total['date'].max())

"""
Calculate MAPE test score using SEIR model result
"""
test = get_China_total(SIR_data[SIR_data['date'] >= datetime.datetime(2020, 2, 14)])
plot_test_data_with_MAPE(test, result,'Infected cases prediction for China total')


#!/usr/bin/python

from time import sleep
from sense_hat import SenseHat
import thread

sense = SenseHat()

image = 0
is_playing = False

def spin():
  global is_playing
  global image
  while is_playing:
    sense.load_image("led/fan{}.PNG".format(image))
    sleep(.05)
    image = image + 1
    if image > 4:
      image = 0

def play():
  global is_playing
  is_playing = True
  thread.start_new_thread(spin, ())

def stop():
  global is_playing
  is_playing = False
  sense.clear()


from math import ceil, sqrt
from random import randint
import matplotlib.pyplot as plt
from timeit import timeit
import time

def power(n, p, mod):
    if p == 1:
        return n
    n %= mod
    t = 1

    while p > 0:
        if p & 1:
            t = (t * n) % mod
        n = (n * n) % mod
        p = p >> 1

    return t

def trial_division(n):
    if n < 2:
        raise Exception('Value error: number must be greater than 1')
    if n % 2 == 0:
        return False

    for divisor in range(1, ceil(sqrt(n) + 1), 2):
        if n % divisor == 0:
            return False
    return True

def Miller_iteration(d, n):
    a = randint(3, n - 2)
    a_exp_d = power(a, d, n)

    if a_exp_d == 1 or a_exp_d == n - 1:
        return True

    while d != n - 1:
        a_exp_d = (a_exp_d ** 2) % n
        d *= 2
        if a_exp_d == 1:
            return False

        if a_exp_d == n - 1:
            return True
    return False

def Miller_Rabin(n, checks = 30):
    if n <= 1:
        return False

    if n <= 3:
        return True

    if n % 2 == 0:
        return False

    d = n - 1
    while d % 2 == 0:
        d //= 2

    for check in range(checks):
        if not Miller_iteration(d, n):
            return False

    return True

def gcd(a, b):
    while b:
        a %= b
        a, b = b, a
    return a

def extended_gcd(a, b):
    if a == 0:
        return b, 0, 1
    res, x1, y1 = extended_gcd(b % a, a)
    x = y1 - (b // a) * x1
    y = x1
    return res, x, y

def Jacobi(n, m):
    s = 1
    if gcd(n, m) != 1:
        return 0

    while True:
        n = n % m
        k = 0
        while n % 2 == 0:
            n = n >> 1
            k += 1
        k %= 2

        if k == 1 and (m % 8 == 3 or m % 8 == 5):
            s *= -1

        if n == 1 or (n == m - 1 and m % 4 == 1):
            return s

        if n == m - 1 and m % 4 == 3:
            return -s

        n, m = m, n
        if (n - 1) % 4 and (m - 1) % 4:
            s *= -1

def Solovay_Strassen(n, checks = 30):
    if n % 2 == 0:
        return False

    if n % 3 == 0:
        return False

    for _ in range(checks):
        a = randint(3, n - 1)
        if power(a, (n - 1) // 2, n) != (Jacobi(a, n) % n):
            return False
    return True

def rsa(bit_length, is_prime = Miller_Rabin):
    p, q = generate_prime(bit_length, is_prime), generate_prime(bit_length, is_prime)
    fi = (p - 1) * (q - 1)
    e = generate_public(fi)
    d = generate_secret(e, fi)
    n = p * q
    return (e, n), (d, n)

def generate_prime(bit_length, is_prime):
    num = randint(2 ** (bit_length - 1) + 1, 2 ** bit_length)
    while not is_prime(num):
        num = randint(2 ** (bit_length - 1), 2 ** bit_length)
    return num

def generate_public(fi):
    max_length = len(str(fi)) - 2
    while True:
        length = randint(max_length // 2, max_length)
        if length < 3:
            length = max_length
        one_bit_amount = length // 10
        if one_bit_amount < 3:
            one_bit_amount = 2

        num = (1 << length) + 1
        for i in range(one_bit_amount):
            num |= (1 << randint(1, length - 1))
            if gcd(num, fi) == 1:
                return num

def generate_secret(e, fi):
    d = extended_gcd(e, fi)[1]
    if d < 0:
        d += fi
    return d

def encode(message, public_key):
    result = ''
    for c in message:
        result += str(power(ord(c), public_key[0], public_key[1])) + ' '

    return result

def decode(message, private_key):
    result = ''
    for c in message.split():
        result += chr(power(int(c), private_key[0], private_key[1]))

    return result

def lineplot(ax, x_data, y_data, x_label="", y_label="", color="#539caf"):
    ax.plot(x_data, y_data, lw = 2, color=color, alpha = 1)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)

_range = range(5, 11)
_, ax = plt.subplots()
ax.set_title('RSA: comparasion of prime test algorithms')

def test(_range, ax, algorithm, color='blue'):
    times = []

    for i in _range:
        t = time.time()
        rsa(2 ** i, algorithm)
        times.append(time.time() - t)
    lineplot(ax, _range, times, y_label = 'seconds', x_label = 'length: 2^', color=color)

test(_range, ax, Miller_Rabin, 'red')
test(_range, ax, Solovay_Strassen, 'blue')
plt.show()


# src/Days/Day1.py

from src.Day import Day
from src.Puzzle import Puzzle

from datetime import datetime
import re

class Guard:
    """Guard class"""
    def __init__(self, guard_id=0):
        self.id = guard_id
        self.total_sleep_time = 0
        self.sleeping_minutes = {}

    def __repr__(self):
        return "<Guard.id {}>".format(self.id)

class Log:
    """Log class"""
    def __init__(self, log_line=None, guard_id=None):
        log_match = re.match(r"\[(.*?)\] (.*?)$", log_line)
        log_datetime = datetime.strptime(log_match.group(1), '%Y-%m-%d %H:%M')
        log_detail = log_match.group(2)

        if log_detail.startswith("Guard"):
            guard_match = re.match(r"Guard #(\d+)", log_detail)
            guard_id = guard_match.group(1)

        self.datetime = log_datetime
        self.detail = log_detail
        self.guard_id = guard_id

class Day4Puzzle1(Puzzle):
    """
    Day1 Puzzle1 class
    """
    def solve(self):
        print("Day4 - Puzzle1")
        log_lines = self.input.splitlines()

        guards = {}                             # keep the sleeping records for each guard
        guard_sleeping_most = None              # keep track of the guard sleeping most
        guard_on_duty = None                    # guard on duty at the moment
        sleep_starting = None                   # sleep starting time for the guard on duty

        for log_line in sorted(log_lines):      # sort the log lines before analysing them
            log = Log(log_line=log_line)

            if log.detail.startswith("Guard"):
                guard_on_duty = Guard(guard_id=log.guard_id)

            elif log.detail == "falls asleep":
                sleep_starting = log.datetime

            elif log.detail == "wakes up":
                sleep_ending = log.datetime

                # count the sleeping minutes in this shift
                sleep_time_in_mins = int((sleep_ending - sleep_starting).total_seconds() / 60.0)

                # add the sleeping minutes to the sleep time of the guard in duty
                # if not appeared yet, initialize the guard
                if guard_on_duty.id in guards:
                    guards[guard_on_duty.id].total_sleep_time += sleep_time_in_mins
                else:
                    guards[guard_on_duty.id] = guard_on_duty
                    guards[guard_on_duty.id].total_sleep_time = sleep_time_in_mins

                if guard_sleeping_most is None or \
                        guards[guard_on_duty.id].total_sleep_time > guard_sleeping_most.total_sleep_time:
                    guard_sleeping_most = guards[guard_on_duty.id]

                for minute in range(sleep_starting.minute, sleep_ending.minute):
                    if minute in guards[guard_on_duty.id].sleeping_minutes:
                        guards[guard_on_duty.id].sleeping_minutes[minute] += 1
                    else:
                        guards[guard_on_duty.id].sleeping_minutes[minute] = 1

        # analyse the sleeping minutes of the guard sleeping most.
        minute_slept_more = 0
        max_minute_count = 0
        for minute, minute_count in guard_sleeping_most.sleeping_minutes.items():
            if minute_count >= max_minute_count:
                max_minute_count = minute_count
                minute_slept_more = minute

        # the ID of the guard you chose multiplied by the minute you chose?
        coefficient = int(guard_sleeping_most.id) * int(minute_slept_more)

        print("Solution: {}".format(str(coefficient)))

class Day4Puzzle2(Puzzle):
    """
    Day4 Puzzle2 class
    """
    def solve(self):
        print("Day4 - Puzzle2")
        log_lines = self.input.splitlines()

        guards = {}                             # keep the sleeping time for each guard
        guard_sleeping_most_on_a_minute = None  # This time, the guard sleeping most on a specific minute
        max_sleeping_times_on_a_minute = 0      # The minute in which one of the guards slept more
        guard_on_duty = None                    # guard on duty at the moment
        sleep_starting = None                   # sleep starting time for the guard on duty

        for log_line in sorted(log_lines):      # sort the log lines before analysing them
            log = Log(log_line=log_line)

            if log.detail.startswith("Guard"):
                guard_on_duty = Guard(guard_id=log.guard_id)

            elif log.detail == "falls asleep":
                sleep_starting = log.datetime

            elif log.detail == "wakes up":
                sleep_ending = log.datetime

                for minute in range(sleep_starting.minute, sleep_ending.minute):
                    if guard_on_duty.id not in guards:
                        guards[guard_on_duty.id] = guard_on_duty

                    if minute in guards[guard_on_duty.id].sleeping_minutes:
                        guards[guard_on_duty.id].sleeping_minutes[minute] += 1
                    else:
                        guards[guard_on_duty.id].sleeping_minutes[minute] = 1

                    if guards[guard_on_duty.id].sleeping_minutes[minute] >= max_sleeping_times_on_a_minute:
                        max_sleeping_times_on_a_minute = guards[guard_on_duty.id].sleeping_minutes[minute]
                        guard_sleeping_most_on_a_minute = guards[guard_on_duty.id]

        # analyse the sleeping minutes of the guard who slept most on a given minute.
        minute_slept_most = 0
        max_count_on_a_minute = 0
        for minute, count in guard_sleeping_most_on_a_minute.sleeping_minutes.items():
            if count > max_count_on_a_minute:
                max_count_on_a_minute = count
                minute_slept_most = minute

        # the ID of the guard you chose multiplied by the minute you chose?
        coefficient = int(guard_sleeping_most_on_a_minute.id) * int(minute_slept_most)

        print("Solution: {}".format(str(coefficient)))

class Day4(Day):
    """
    Day4 Class with 2 puzzles.
    """
    def __init__(self):
        super(Day4, self).__init__(day_number=4)

    def puzzle(self, puzzle_number=0):
        """
        This method returns the puzzle instance

        :param puzzle_number: number of the puzzle
        :return: instance of the puzzle with the given number of puzzle.
        """
        puzzles_for_day = [
            Day4Puzzle1(puzzle_number=puzzle_number, day_number=self.day_number),
            Day4Puzzle2(puzzle_number=puzzle_number, day_number=self.day_number)
        ]

        return puzzles_for_day[puzzle_number-1]

    def __repr__(self):
        return "<Day4.day {}>".format(self.day_number)


"""
Tests for the map endpoint.
"""

from django.core.management import call_command
from django.test import TestCase
from vodabackend.vodaMainApp.views import map_endpoint
from vodabackend.vodaMainApp.models import State, Sources, Contaminants, SourceLevels, StateAvgLevels
import pytest

# inputs for http requests
mapRequest = '/map'

###############################################################################
# Helper functions.
###############################################################################
def request_map():
    """
    call for the map endpoint used by the map tests
    """
    # Send a request to the API server and store the response.
    return requests.get('http://0.0.0.0:8000/map')

@pytest.fixture(scope='session')
def django_db_setup(django_db_setup, django_db_blocker):

    with django_db_blocker.unblock():
        call_command('loaddata', 'testSources.json')

###############################################################################
# Tests.
###############################################################################
@pytest.mark.django_db
def test_map_status_code(rf):
    """
    test that the status_code of the map http response is 200
    """

    request = rf.get(mapRequest)
    response = map_endpoint(request)
    assert response.status_code == 200

@pytest.mark.django_db
def test_map_content(rf):
    """
    test that the map http response body returns the proper message
    """

    request = rf.get(mapRequest)
    response = map_endpoint(request)

    assert response.content == b'Returns a list of water supplies and a 1-10 value with the quality of the water.'


from __future__ import print_function, with_statement, absolute_import
import shutil
import keras
import logging
import os
import sys

from ..version import __version__, __registry__
from .deployer_utils import save_python_function
from ..exceptions import ClipperException

logger = logging.getLogger(__name__)

def create_endpoint(clipper_conn,
                    name,
                    input_type,
                    func,
                    model_path_or_object,
                    default_output="None",
                    version=1,
                    slo_micros=3000000,
                    labels=None,
                    registry=None,
                    base_image="default",
                    num_replicas=1,
                    batch_size=-1,
                    pkgs_to_install=None):
    """Registers an app and deploys the provided predict function with Keras model as
    a Clipper model.

    Parameters
    ----------
    clipper_conn : :py:meth:`clipper_admin.ClipperConnection`
        A ``ClipperConnection`` object connected to a running Clipper cluster.
    name : str
        The name to be assigned to both the registered application and deployed model.
    input_type : str
        The input_type to be associated with the registered app and deployed model.
        One of "integers", "floats", "doubles", "bytes", or "strings".
    func : function
        The prediction function. Any state associated with the function will be
        captured via closure capture and pickled with Cloudpickle.
    model_path_or_object : keras Model object or a path to a saved Model ('.h5')
    default_output : str, optional
        The default output for the application. The default output will be returned whenever
        an application is unable to receive a response from a model within the specified
        query latency SLO (service level objective). The reason the default output was returned
        is always provided as part of the prediction response object. Defaults to "None".
    version : str, optional
        The version to assign this model. Versions must be unique on a per-model
        basis, but may be re-used across different models.
    slo_micros : int, optional
        The query latency objective for the application in microseconds.
        This is the processing latency between Clipper receiving a request
        and sending a response. It does not account for network latencies
        before a request is received or after a response is sent.
        If Clipper cannot process a query within the latency objective,
        the default output is returned. Therefore, it is recommended that
        the SLO not be set aggressively low unless absolutely necessary.
        100000 (100ms) is a good starting value, but the optimal latency objective
        will vary depending on the application.
    labels : list(str), optional
        A list of strings annotating the model. These are ignored by Clipper
        and used purely for user annotations.
    registry : str, optional
        The Docker container registry to push the freshly built model to. Note
        that if you are running Clipper on Kubernetes, this registry must be accesible
        to the Kubernetes cluster in order to fetch the container from the registry.
    base_image : str, optional
        The base Docker image to build the new model image from. This
        image should contain all code necessary to run a Clipper model
        container RPC client.
    num_replicas : int, optional
        The number of replicas of the model to create. The number of replicas
        for a model can be changed at any time with
        :py:meth:`clipper.ClipperConnection.set_num_replicas`.
    batch_size : int, optional
        The user-defined query batch size for the model. Replicas of the model will attempt
        to process at most `batch_size` queries simultaneously. They may process smaller
        batches if `batch_size` queries are not immediately available.
        If the default value of -1 is used, Clipper will adaptively calculate the batch size for
        individual replicas of this model.
    pkgs_to_install : list (of strings), optional
        A list of the names of packages to install, using pip, in the container.
        The names must be strings.
    """

    clipper_conn.register_application(name, input_type, default_output,
                                      slo_micros)
    deploy_keras_model(clipper_conn, name, version, input_type, func,
                       model_path_or_object, base_image, labels,
                       registry, num_replicas, batch_size,
                       pkgs_to_install)

    clipper_conn.link_model_to_app(name, name)

def deploy_keras_model(clipper_conn,
                       name,
                       version,
                       input_type,
                       func,
                       model_path_or_object,
                       base_image="default",
                       labels=None,
                       registry=None,
                       num_replicas=1,
                       batch_size=-1,
                       pkgs_to_install=None):
    """Deploy a Python prediction function with a Keras Model object or model file ('.h5').

    Parameters
    ----------
    clipper_conn : :py:meth:`clipper_admin.ClipperConnection`
        A ``ClipperConnection`` object connected to a running Clipper cluster.
    name : str
        The name to be assigned to both the registered application and deployed model.
    version : str
        The version to assign this model. Versions must be unique on a per-model
        basis, but may be re-used across different models.
    input_type : str
        The input_type to be associated with the registered app and deployed model.
        One of "integers", "floats", "doubles", "bytes", or "strings".
    func : function
        The prediction function. Any state associated with the function will be
        captured via closure capture and pickled with Cloudpickle.
    model_path_or_object : keras Model object or a path to a saved Model ('.h5')
    base_image : str, optional
        The base Docker image to build the new model image from. This
        image should contain all code necessary to run a Clipper model
        container RPC client.
    labels : list(str), optional
        A list of strings annotating the model. These are ignored by Clipper
        and used purely for user annotations.
    registry : str, optional
        The Docker container registry to push the freshly built model to. Note
        that if you are running Clipper on Kubernetes, this registry must be accesible
        to the Kubernetes cluster in order to fetch the container from the registry.
    num_replicas : int, optional
        The number of replicas of the model to create. The number of replicas
        for a model can be changed at any time with
        :py:meth:`clipper.ClipperConnection.set_num_replicas`.
    batch_size : int, optional
        The user-defined query batch size for the model. Replicas of the model will attempt
        to process at most `batch_size` queries simultaneously. They may process smaller
        batches if `batch_size` queries are not immediately available.
        If the default value of -1 is used, Clipper will adaptively calculate the batch size for
        individual replicas of this model.
    pkgs_to_install : list (of strings), optional
        A list of the names of packages to install, using pip, in the container.
        The names must be strings.

    Example
    -------
    Deploy a Keras Model::

        from clipper_admin import ClipperConnection, DockerContainerManager
        from clipper_admin.deployers import keras as keras_deployer
        import keras

        # creating a simple Keras model
        inpt = keras.layers.Input(shape=(1,))
        out = keras.layers.multiply([inpt, inpt])
        model = keras.models.Model(inputs=inpt, outputs=out)

        clipper_conn = ClipperConnection(DockerContainerManager())

        # Connect to an already-running Clipper cluster
        clipper_conn.connect()

        def predict(model, inputs):
            return [model.predict(x) for x in inputs]

        keras_deployer.deploy_keras_model(clipper_conn=clipper_conn, name="pow", version="1", input_type="ints",
                                  func=predict,
                                  model_path_or_object=model,
                                  base_image='keras-container')

        # sending an inference request
        import requests
        import json

        req_json = json.dumps({
                "input": [1, 2, 4, 6]
            })

        headers = {"Content-type": "application/json"}
        response = requests.post("http://localhost:1337/keras-pow/predict", headers=headers,
                      data=req_json)

    """
    # save predict function
    serialization_dir = save_python_function(name, func)
    # save Keras model or copy the saved model into the image
    if isinstance(model_path_or_object, keras.Model):
        model_path_or_object.save(os.path.join(serialization_dir, "keras_model.h5"))
    elif os.path.isfile(model_path_or_object):
        try:
            shutil.copy(model_path_or_object,
                        os.path.join(serialization_dir, "keras_model.h5"))
        except Exception as e:
            logger.error("Error copying keras model: %s" % e)
            raise e
    else:
        raise ClipperException(
            "%s should be wither a Keras Model object or a saved Model ('.h5')" % model_path_or_object)

    py_minor_version = (sys.version_info.major, sys.version_info.minor)
    # Check if Python 2 or Python 3 image
    if base_image == "default":
        if py_minor_version < (3, 0):
            logger.info("Using Python 2 base image")
            base_image = "{}/keras-container:{}".format(
                __registry__, __version__)
        elif py_minor_version == (3, 5):
            logger.info("Using Python 3.5 base image")
            base_image = "{}/keras35-container:{}".format(
                __registry__, __version__)
        elif py_minor_version == (3, 6):
            logger.info("Using Python 3.6 base image")
            base_image = "{}/keras36-container:{}".format(
                __registry__, __version__)
        elif py_minor_version == (3, 7):
            logger.info("Using Python 3.7 base image")
            base_image = "{}/keras37-container:{}".format(
                __registry__, __version__)
        else:
            msg = (
                "Keras deployer only supports Python 2.7, 3.5, 3.6, and 3.7. "
                "Detected {major}.{minor}").format(
                major=sys.version_info.major, minor=sys.version_info.minor)
            logger.error(msg)
            # Remove temp files
            shutil.rmtree(serialization_dir)
            raise ClipperException(msg)

    # Deploy model
    clipper_conn.build_and_deploy_model(
        name, version, input_type, serialization_dir, base_image, labels,
        registry, num_replicas, batch_size, pkgs_to_install)

    # Remove temp files
    shutil.rmtree(serialization_dir)


#array fun & multi-dimensional array

"""
from numpy import *

arr1 = array([
                 [1,2,3],
                 [4,5,6]

              ])
print(arr1)
print(arr1.dtype)
print(arr1.ndim)
print(arr1.shape)
print(arr1.size)
#2d array to 1d array
arr2 = arr1.flatten()
print(arr2)
"""

#3d array
"""
from numpy import *
arr1 = array([
                 [1,2,3,6,2,9],
                 [4,5,6,7,5,3]

              ])

arr2 = arr1.flatten()
arr4 = arr1.reshape(3,4)
arr3 = arr1.reshape(2,2,3)
print(arr3)
print(arr4)
"""

#array to matrix
"""

from numpy import *
arr1 = array([
                 [1,2,3,6],
                 [4,5,6,7]

              ])

m = matrix(arr1)
print(m)
"""
#matrix operations
"""
from numpy import *
j = matrix('1 2 3 6 ; 4 5 6 7')
v = matrix('1 2 ; 3 6 ; 4 5 ; 6 7')
m = matrix('1 2 3; 6 4 5;1 6 7')
print(j)
print(v)
print(m)
print(diagonal(m))
print(m.min())
print(m.max())
"""

#matrix addition and multiplication
from numpy import *
m1 = matrix('1 2 3; 6 4 5;1 6 7')
m2 = matrix('1 2 3; 6 8 5;2 6 7')

m3 = m1 + m2
m4 = m1 * m2;

print(m3)
print(m4)


"""
Написать функцию calc_sum, которая принимает неограниченное количество целых
чисел и  возвращает их сумму

для расчета суммы можно воспользоваться функцией sum
"""

def calc_sum(*args):
    summa = 0
    for i in args:
        summa += i
    return summa
    # return sum(args)

if __name__ == '__main__':
    some_values = []
    while True:
        values = input('Введите число: ')
        if values == 'stop':
            break
        some_values.append(int(values))
    print(calc_sum(*some_values))


# copied from PR2 GRD on 2018/4/12
##################################################
#modified by m.nakano on 2017/11/03

import time
import math
from guardian import GuardState
from guardian import GuardStateDecorator
from guardian import NodeManager
import os
import sys
import subprocess
import VISfunction as vf
import cdslib
import sdflib
import kagralib

__,optic = SYSTEM.split('_')
OPTIC = optic

##################################################
# initialization values

# initial REQUEST state
request = 'SAFE'

# NOMINAL state, which determines when node is OK
nominal = 'ALIGNED'

##################################################

##################################################

WD = ['TM','IM','BF','SF']
BIO = ['TM','IM1','IM2','GAS','BFV','BFH']

# Tool for taking safe snapshot
reqfile = vf.req_file_path(optic)+'/autoBurt.req'
snapfile = '/opt/rtcds/userapps/release/vis/k1/burtfiles/'+vf.modelName(optic)+'_guardian_safe.snap'
##################################################
# STATE decorators

class watchdog_check(GuardStateDecorator):
    """Decorator to check watchdog"""
    def pre_exec(self):
        if vf.is_tripped(optic,WD,BIO):
            log("I_am_tripped.")
            #sa.sendmail("["+optic+"]Tripped",optic+" is tripped!")
            return 'TRIPPED'

class pre_wd(GuardStateDecorator):
    def pre_exec(self):
        if vf.is_pretripped(optic):
            log("I_am_pre-tripped.")
            return 'PRE_TRIPPED'

##################################################
class INIT(GuardState):
    index = 0
    goto = False

class TRIPPED(GuardState):
    redirect = False
    request = False
    def main(self):

        self.counter = 1
        self.TRAMP = ezca['VIS-'+optic+'_PAY'+'_SHUTDOWN_RAMPT'] # should look TWR too.
        self.timer['waiting'] = self.TRAMP
        self.counter = 1

        #Send alerts
        vf.vis_watchdog_tripped(optic)

    def run(self):
        log('waiting for all outputs turned off')

        if vf.all_off(optic,self):
            ezca.switch('VIS-' + optic + '_TM_DAMP_P','FMALL','OFF')
            ezca.switch('VIS-' + optic + '_TM_DAMP_Y','FMALL','OFF')
            ezca.get_LIGOFilter('VIS-%s_TM_OPLEV_SERVO_PIT'%optic).ramp_gain(0,0,False)
            ezca.get_LIGOFilter('VIS-%s_TM_OPLEV_SERVO_YAW'%optic).ramp_gain(0,0,False)
            log('Turning off the master switch')
            ezca['VIS-'+optic+'_MASTERSWITCH'] = 'OFF'
            return not vf.is_tripped(optic,WD,BIO)

#class PRE_TRIPPED(GuardState):
#    index = 10
#    redirect = False
#    request = False
#    @watchdog_check
#    def main(self):
#        vf.all_off(optic)
#        return True
#
#    @watchdog_check
#    def run(self):
#        if not vf.is_pretripped(optic):
#            return True

class SAFE(GuardState):
    """Safe state is with master switch off not to send any signal"""
    @watchdog_check
    def main(self):
        log('Turning off all the filters')
        self.counter = 1
        self.timer['waiting'] = 0
        self.TRAMP = 10
        # by Miyo
        if OPTIC != 'PRM':
            fec = cdslib.ezca_get_dcuid('K1VIS'+OPTIC)
            sdflib.restore(fec,'safe')
        else:
            for PART in ['P','T']:
                fec = cdslib.ezca_get_dcuid('K1VIS'+OPTIC+PART)
                sdflib.restore(fec,'safe')

    @watchdog_check
    def run(self):
        log('waiting for all outputs turned off')
        if vf.all_off(optic,self):
            ezca.switch('VIS-' + optic + '_TM_DAMP_P','FMALL','OFF')
            ezca.switch('VIS-' + optic + '_TM_DAMP_Y','FMALL','OFF')
            ezca.get_LIGOFilter('VIS-%s_TM_OPLEV_SERVO_PIT'%optic).ramp_gain(0,0,False)
            ezca.get_LIGOFilter('VIS-%s_TM_OPLEV_SERVO_YAW'%optic).ramp_gain(0,0,False)
            log('Turning off the master switch')
            ezca['VIS-'+optic+'_MASTERSWITCH'] = 'OFF'
            #subprocess.call(['burtrb', '-f', reqfile, '-o', snapfile, '-l','/tmp/controls.read.log', '-v'])
            return True

class OUTPUT_ON(GuardState):
    index = 41
    request = False

    @watchdog_check
    def main(self):
        log('Turning on the master switch')
        ezca['VIS-'+optic+'_MASTERSWITCH'] = 'ON'
        log('Setting off the offsets for misaligning')
        ezca.switch('VIS-'+optic+'_BF_TEST_Y','OFFSET','OFF')
        ezca.switch('VIS-'+optic+'_IM_TEST_P','OFFSET','OFF')
        ezca.switch('VIS-'+optic+'_IM_TEST_Y','OFFSET','OFF')

        log('Turning on the TEST filters')
	## GAS ##
        for DOF in ['BF','SF']:
            ezca['VIS-'+optic+'_%s_TEST_GAS_TRAMP'%DOF] = 5.0
            ezca['VIS-'+optic+'_%s_TEST_GAS_GAIN'%DOF] = 1.0
	## BF & IM ##
        for DOF in ['L','T','V','R','P','Y']:
            ezca['VIS-'+optic+'_BF_TEST_%s_TRAMP'%DOF] = 5.0
            ezca['VIS-'+optic+'_BF_TEST_%s_GAIN'%DOF] = 1.0

            ezca['VIS-'+optic+'_IM_TEST_%s_TRAMP'%DOF] = 5.0
            ezca['VIS-'+optic+'_IM_TEST_%s_GAIN'%DOF] = 1.0
        ## TM ##
        for DOF in ['L','P','Y']:
            ezca['VIS-'+optic+'_TM_TEST_%s_TRAMP'%DOF] = 5.0
            ezca['VIS-'+optic+'_TM_TEST_%s_GAIN'%DOF] = 1.0
        return True
#        for DOF in ['P','Y']:
#            ezca['VIS-'+optic+'_IM_OPTICALIGN_%s_TRAMP'%DOF] = 10.0
#            ezca['VIS-'+optic+'_IM_OPTICALIGN_%s_GAIN'%DOF] = 1.0

class UNDAMPED(GuardState):
    index = 50
    @watchdog_check
    def run(self):
        return True

class DAMPING_ON(GuardState):
    index = 51
    request = False
    @watchdog_check
    def main(self):
        self.TRAMP = 10
        self.counter = 1
        self.timer['waiting'] = 0
        log('Setting off the offsets for misaligning')

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            if self.counter == 1:
                ezca.switch('VIS-'+optic+'_BF_TEST_Y','OFFSET','OFF')
                ezca.switch('VIS-'+optic+'_IM_TEST_P','OFFSET','OFF')
                ezca.switch('VIS-'+optic+'_IM_TEST_Y','OFFSET','OFF')

                log('Turning on the damping filters')
                ## GAS ##
                for DOF in ['BF', 'SF']:
                    ezca.switch('VIS-'+optic+'_%s_DAMP_GAS'%DOF,'INPUT','ON')
                    ezca.switch('VIS-'+optic+'_%s_DAMP_GAS'%DOF,'OFFSET','ON')
#-- FIXME --#
                    ezca['VIS-'+optic+'_%s_DAMP_GAS_TRAMP'%DOF] = 30
                    ezca['VIS-'+optic+'_%s_DAMP_GAS_RSET'%DOF] = 2
                    ezca['VIS-'+optic+'_%s_DAMP_GAS_GAIN'%DOF] = 1.0
#-- until here written by YF on Sep30th 2019. please delete this sentence after modification --#
                ## BF ##
                for DOF in ['L','T','V','R','P','Y']:
                    ezca['VIS-'+optic+'_BF_DAMP_%s_TRAMP'%DOF] = self.TRAMP
                    ezca['VIS-'+optic+'_BF_DAMP_%s_RSET'%DOF] = 2
                    ezca['VIS-'+optic+'_BF_DAMP_%s_GAIN'%DOF] = 1.0
                    ## IM ##
                    ezca['VIS-'+optic+'_IM_DAMP_%s_TRAMP'%DOF] = self.TRAMP
                    ezca['VIS-'+optic+'_IM_DAMP_%s_RSET'%DOF] = 2
                    ezca['VIS-'+optic+'_IM_DAMP_%s_GAIN'%DOF] = 1.0
                self.timer['waiting'] = self.TRAMP
                self.counter += 1

            elif self.counter == 2:
                return True

class DAMPING_OFF(GuardState):
    index = 52
    request = False
    @watchdog_check
    def main(self):
        self.TRAMP = 10
        vf.im_offload_off(optic, self.TRAMP)
        log('Turning on the damping filters')
        vf.im_damp_off(optic)
        vf.bf_damp_off(optic)
        vf.gas_damp_off(optic)
        self.timer['waiting'] = 10

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            return True

class DAMPED(GuardState):
    index = 60
    @watchdog_check
    def main(self):
        log(optic+"damped")
        return True
    @watchdog_check
    def run(self):
        return True

class ENGAGE_MISALIGN(GuardState):
    index = 62
    request = False
    @watchdog_check
    def main(self):
        self.TRAMP = 10
        ezca['VIS-PRM_IM_TEST_P_TRAMP'] = self.TRAMP
        ezca['VIS-PRM_IM_TEST_Y_TRAMP'] = self.TRAMP
        ezca['VIS-PRM_BF_TEST_Y_TRAMP'] = self.TRAMP
        log( optic+"misaligning" )
        ezca.switch('VIS-'+optic+'_BF_TEST_Y','OFFSET','ON')
        ezca.switch('VIS-'+optic+'_IM_TEST_P','OFFSET','ON')
        ezca.switch('VIS-'+optic+'_IM_TEST_Y','OFFSET','ON')
        self.timer['waiting'] = self.TRAMP

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            return True

class MISALIGNED(GuardState):
    index = 800
    @watchdog_check
    def main(self):
        log(optic+"mis-aligned")

    @watchdog_check
    def run(self):
        return True

class MISALIGN_OFF(GuardState):
    index = 64
    request = False
    @watchdog_check
    def main(self):
        log("turning off"+optic+"misalignment" )
        ezca.switch('VIS-'+optic+'_BF_TEST_Y','OFFSET','OFF')
        ezca.switch('VIS-'+optic+'_IM_TEST_P','OFFSET','OFF')
        ezca.switch('VIS-'+optic+'_IM_TEST_Y','OFFSET','OFF')
        self.timer['waiting'] = 5

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            return True

class ENGAGE_OLDAMP(GuardState):
    index = 900
    request = False
    @watchdog_check
    def main(self):
        self.counter = 0
        self.timer['waiting'] = 0

        self.Target = {'P':ezca['VIS-'+optic+'_GOOD_OPLEV_PIT'],
                       'Y':ezca['VIS-'+optic+'_GOOD_OPLEV_YAW'],
                       }
        self.TMdampinitFMlist = {
        'PR3':{'L':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM6','FM7','FM9',),'P':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM6','FM9',),'Y':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM9',)},
        'PR2':{'L':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM3','FM4','FM9',),'P':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM3','FM4','FM9',),'Y':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM9',)},
        'PRM':{'L':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM3','FM4','FM9',),'P':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM3','FM4','FM9',),'Y':('INPUT','OUTPUT','LIMIT','FM1','FM2','FM9',)},
        }

        self.TMdampBSTFMlist = {
            'PR3':{'L':('FM8',),'P':('FM7','FM8',),'Y':('FM7','FM8',)},
            'PR2':{'L':('FM8',),'P':('FM8',),'Y':('FM8',)},
            'PRM':{'L':(),'P':('FM8',),'Y':('FM8',)},
            }
        self.TRAMP = 2
        self.IMlimit = 24000
        self.TMlimit = 8000
        log('Turning on the oplev controls')

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            if self.counter == 0:
                for DOF in ['P','Y']:
                    ezca['VIS-'+optic+'_TM_OLSET_%s_TRAMP'%DOF] = 0
                    ezca['VIS-'+optic+'_TM_OLSET_%s_OFFSET'%DOF] = self.Target[DOF]
                    ezca['VIS-'+optic+'_TM_OLSET_%s_GAIN'%DOF] = 1
                    ezca['VIS-'+optic+'_TM_OLSET_%s_TRAMP'%DOF] = 2
                    ezca.get_LIGOFilter('VIS-'+optic+'_TM_OLSET_%s'%DOF).only_on('INPUT','OUTPUT','OFFSET')

                for DOF in ['L','P','Y']:
                    ezca['VIS-'+optic+'_TM_DAMP_%s_TRAMP'%DOF] = self.TRAMP
                    ezca['VIS-'+optic+'_TM_DAMP_%s_LIMIT'%DOF] = self.TMlimit
                    ezca.get_LIGOFilter('VIS-'+optic+'_TM_DAMP_%s'%DOF).only_on(*self.TMdampinitFMlist[optic][DOF])
                    ezca['VIS-'+optic+'_TM_DAMP_%s_RSET'%DOF] = 2
                    ezca['VIS-'+optic+'_TM_DAMP_%s_GAIN'%DOF] = 1.0

                for DOF in ['PIT','YAW']:
                    ezca['VIS-'+optic+'_TM_OPLEV_SERVO_%s_OFFSET'%DOF] = 0
                    ezca['VIS-'+optic+'_TM_OPLEV_SERVO_%s_TRAMP'%DOF] = 0
                    ezca['VIS-'+optic+'_TM_OPLEV_SERVO_%s_GAIN'%DOF] = 1.0
                    ezca.get_LIGOFilter('VIS-'+optic+'_TM_OPLEV_SERVO_%s'%DOF).only_on('INPUT','OUTPUT')

                self.counter += 1
                self.timer['waiting'] = self.TRAMP

            elif self.counter == 1:
                # turn Boost on
                for DOF in ['P','Y']:
                    ezca.get_LIGOFilter('VIS-'+optic+'_TM_DAMP_%s'%DOF).switch_on(*self.TMdampBSTFMlist[optic][DOF])
                self.timer['waiting'] = self.TRAMP
                self.counter += 1

            elif self.counter == 2:
                return True

class OLDAMPED(GuardState):
    index = 333
    request = True

    @watchdog_check
    def run(self):
        return True

class OLDAMP_OFF(GuardState):
    index = 74
    request = False
    @watchdog_check
    def main(self):
        log('Turning off the oplev controls')
        self.TRAMP = 2
        self.timer['waiting'] = 0
        self.counter = 0
        self.TMdampBSTFMlist = {
            'PR2':{'L':('FM8',),'P':('FM8',),'Y':('FM8',)},
            'PR3':{'L':('FM8',),'P':('FM8',),'Y':('FM8',)},
            'PRM':{'P':('FM8',),'Y':('FM8',),'L':()},
            }

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            if self.counter == 0:
                # turn Boost off
                for DOF in ['L','P','Y']:
                    ezca.get_LIGOFilter('VIS-'+optic+'_TM_DAMP_%s'%DOF).switch_off(*self.TMdampBSTFMlist[optic][DOF])
                self.timer['waiting'] = self.TRAMP
                self.counter += 1

            if self.counter == 1:
                for DOF in ['P','Y','L']:
                    ezca['VIS-'+optic+'_TM_DAMP_%s_TRAMP'%DOF] = self.TRAMP
                    ezca['VIS-'+optic+'_TM_DAMP_%s_GAIN'%DOF] = 0
                self.timer['waiting'] = self.TRAMP
                self.counter += 1

            elif self.counter == 2:
                return True

class ENGAGE_OLDCCTRL(GuardState):
    index = 334
    request = False
    @watchdog_check
    def main(self):
        self.counter = 1
        self.timer['waiting'] = 0
        self.Target = {'P':ezca['VIS-'+optic+'_GOOD_OPLEV_PIT'],
                       'Y':ezca['VIS-'+optic+'_GOOD_OPLEV_YAW'],
                       }

        self.IMintFMlist = {
            'PR3':{'P':('OUTPUT','LIMIT','FM6','FM2','FM3','FM1'),'Y':('OUTPUT','LIMIT','FM1','FM2','FM6')},
            'PR2':{'P':('OUTPUT','LIMIT','FM6','FM2','FM3','FM1'),'Y':('OUTPUT','LIMIT','FM1','FM2','FM6')},
            'PRM':{'P':('OUTPUT','LIMIT','FM1','FM2','FM3','FM5'),'Y':('OUTPUT','LIMIT','FM1','FM2','FM3','FM5')},
            }
        self.TRAMP = 10
        self.IMlimit = 24000
        self.TMlimit = 8000
        log('Turning on the oplev controls')

    @watchdog_check
    def run(self):
        if self.timer['waiting']:
            if self.counter == 1:
                # turn integrator on
                for DOF in ['P','Y']:
                    ezca.get_LIGOFilter('VIS-'+optic+'_IM_OLDAMP_%s'%DOF).only_on(*self.IMintFMlist[optic][DOF])
                    ezca['VIS-'+optic+'_IM_OLDAMP_%s_LIMIT'%DOF] = self.IMlimit
                    if not ezca['VIS-'+optic+'_IM_OLDAMP_%s_GAIN'%DOF]:
                        ezca['VIS-'+optic+'_IM_OLDAMP_%s_RSET'%DOF] = 2
                        ezca['VIS-'+optic+'_IM_OLDAMP_%s_GAIN'%DOF] = 1
                    ezca.get_LIGOFilter('VIS-'+optic+'_IM_OLDAMP_%s'%DOF).switch_on('INPUT')
                self.timer['waiting'] = self.TRAMP
                self.counter += 1

            elif self.counter == 2:
                return True

class ALIGNED(GuardState):
    index = 1000
    #####  UNCOMMENT (see klog )
    # @watchdog_check
    # def main(self):
    #     for fec in get_dcuid(optic):
    #         restore(fec, "ALIGNED")

    @watchdog_check
    def run(self):
        log('All controlled')
        # Add DC alignment values with ramp time!
        return True

class DISABLE_OLDCCTRL(GuardState):
    index = 996
    def main(self):
        self.TRAMP = 5

        self.timer['waiting'] = 0
        self.counter = 1

    def run(self):
        if self.timer['waiting']:

            if self.counter == 1:
                for DOF in ['P','Y']:
                    ezca.get_LIGOFilter('VIS-'+optic+'_IM_OLDAMP_%s'%DOF).switch_off('INPUT')
                self.timer['waiting'] = 2
                self.counter += 1

            elif self.counter == 2:
                return True

class OBSERVATION(GuardState):
    index = 2000
    @watchdog_check
    def main(self):
        self.timer['waiting'] = 10
        log('Changing the filter configuration to low-noise mode')
    @watchdog_check
    def run(self):
        return self.timer['waiting']

class ENGAGE_LOCKACQUISITION_FILTER(GuardState):
    index = 1333
    request = False
    @watchdog_check
    def main(self):
        self.counter = 0
        self.timer['waiting'] = 0
        self.TRAMP = 2

        self.flag = {'PR3':True,'PR2':False,'PRM':False}
        self.initFMs = {'PR3':{'L':[],'P':['FM3','FM4'],'Y':['FM3','FM4']},
                        'PR2':False,
                        'PRM':False}
        self.bstFMs = {'PR3':{'L':[],'P':['FM5',],'Y':['FM5',]},
                        'PR2':False,
                        'PRM':False}

    @watchdog_check
    def run(self):
        if not self.flag[optic]:
            return True
        else:
            if self.timer['waiting']:
                if self.counter == 0:
                    # turn off the DCCTRL
                    for DOF in ['P','Y']:
                        ezca.get_LIGOFilter('VIS-'+optic+'_IM_OLDAMP_%s'%DOF).switch_off('INPUT')
                    self.timer['waiting'] = 2
                    self.counter += 1
                elif self.counter == 1:
                    # turn nominal damping off
                    for DOF in ['P','Y','L']:
                        if self.initFMs[optic][DOF]:
                            ezca.get_LIGOFilter('VIS-'+optic+'_TM_DAMP_' + DOF).ramp_gain(0,self.TRAMP,wait=False)
                    self.timer['waiting'] = self.TRAMP
                    self.counter += 1
                elif self.counter == 2:
                    for DOF in ['P','Y','L']:
                        kagralib.init_FB('VIS-'+optic+'_TM_DAMP_'+DOF, engaged_FM = self.initFMs[optic][DOF],
                                         gain = 1, ramptime = self.TRAMP,ramp = True)
                    self.counter += 1
                    self.timer['waiting'] = self.TRAMP

                elif self.counter == 3:
                    for DOF in ['P','Y','L']:
                        ezca.get_LIGOFilter('VIS-'+optic+'_TM_DAMP_'+DOF).turn_on(*self.bstFMs[optic][DOF])
                    self.counter += 1
                    self.timer['waiting'] = 2
                elif self.counter == 4:
                    return True

class LOCK_ACQUISITION(GuardState):
    index = 166
    @watchdog_check
    def run(self):
        notify('I am waiting for the lock!! Good Lock!!')
        return True

class DISABLE_LOCK_ACQUISITION_FILTERS(GuardState):
    index = 167

    @watchdog_check
    def main(self):
        self.counter = 0
        self.timer['waiting'] = 0
        self.TRAMP = 2

        self.flag = {'PR3':True,'PR2':False,'PRM':False}

    @watchdog_check
    def run(self):
        if not self.flag[optic]:
            return True
        else:
            if self.timer['waiting']:
                if self.counter == 0:
                    for DOF in ['P','Y','L']:
                        kagralib.init_FB('VIS-'+optic+'_TM_DAMP_'+DOF,
                                         gain = 0, ramptime = self.TRAMP,ramp = True)
                    self.counter += 1
                    self.timer['waiting'] = self.TRAMP

                elif self.counter == 1:
                    return True

##################################################
# Edges

edges = [
    ('INIT','SAFE'),
    ('TRIPPED','SAFE'),
    ('SAFE','OUTPUT_ON'),
    ('OUTPUT_ON','UNDAMPED'),
    ('UNDAMPED','DAMPING_ON'),
    ('DAMPING_ON','DAMPED'),
    ('DAMPED','DAMPING_OFF'),
    ('DAMPING_OFF','UNDAMPED'),
    # modified downstream by MN, 2019/09/12
    ('DAMPED','ENGAGE_OLDAMP'),
    ('ENGAGE_OLDAMP','OLDAMPED'),
    ('DAMPED', 'ENGAGE_MISALIGN'),
    ('ENGAGE_MISALIGN', 'MISALIGNED'),
    ('MISALIGNED','MISALIGN_OFF'),
    ('MISALIGN_OFF','DAMPED'),
    ('OLDAMPED','OLDAMP_OFF'),
    ('OLDAMP_OFF','DAMPED'),
    ('OLDAMPED','ENGAGE_OLDCCTRL'),
    ('ENGAGE_OLDCCTRL','ALIGNED'),
    ('UNDAMPED','SAFE'),
    ('ALIGNED','DISABLE_OLDCCTRL'),
    ('DISABLE_OLDCCTRL','OLDAMPED'),
    ('ALIGNED','OBSERVATION'),
    ('ALIGNED','ENGAGE_LOCKACQUISITION_FILTER'),
    ('ENGAGE_LOCKACQUISITION_FILTER','LOCK_ACQUISITION'),
    ('LOCK_ACQUISITION','DISABLE_LOCK_ACQUISITION_FILTERS'),
    ('DISABLE_LOCK_ACQUISITION_FILTERS','ENGAGE_OLDAMP'),
   ]


import pickle
import os
def write_file(events_l):
    '''
    Writes user data to a file

    param:
        events_l: user events object
    '''
    if(os.path.exists("calendar_data/user_data.pickle")):
        with open("calendar_data/user_data.pickle", 'rb') as user_data:
            try:
                old_list = pickle.load(user_data)
            except:
                old_list = ''  #catch error for empty file
        if old_list != events_l:
            with open("calendar_data/user_data.pickle", 'wb') as user_data:
                pickle.dump(events_l, user_data)
    else:
        with open('calendar_data/user_data.pickle', 'wb') as user_data:
            pickle.dump(events_l, user_data)

def read_file():
    """
    This functions reads the contents of the user_data.pickle file
    and returns the contents. The return value is a list of all the
    upcoming events in the user's calendar.
    """
    try:
        with open("calendar_data/user_data.pickle", 'rb') as data:
            events = pickle.load(data)
        return events
    except:
        print("Your events could not be retrieved!")


import unittest

from ast_tree_tracer.trace import trace_python
from ast_tree_tracer.trace_container import clear_trace, get_trace
from helpers.Logger import Logger
from slicing.code_from_slice import code_from_slice_ast
from slicing.slice import get_dynamic_slice
from ast_tree_tracer.augment import *

log = Logger()

class TestRefactoryNewFailures(unittest.TestCase):
    def tearDown(self):
        clear_trace()

    def test_for_else_end_token_minimized(self):
        # benchmark/refactory/data/question_3/code/wrong/wrong_3_212.py#1:

        code_block = """
def remove_extras(lst):

    def position(i):
        n = len(lst)
        for j in range(n):
            if lst[j] == i:
                return j

    def helper(start, i):
        for k in lst[start:]:
            if k == i:
                lst.remove(k)
        else:
            j = 1
    for i in lst:
        index = position(i)
        helper(index + 1, i)
    return lst
extras_result = remove_extras([1])
"""
        variable = 'extras_result'
        line_number = len(code_block.splitlines())
        trace_python(code_block)
        exec_trace = get_trace()
        log.print_trace(get_trace())

        computed_slice, rel_bool_ops, func_param_removal = get_dynamic_slice(exec_trace, variable, line_number)

        sliced_code = code_from_slice_ast(code_block, computed_slice, rel_bool_ops, exec_trace, func_param_removal)
        log.pretty_print_code(code_block)
        log.pretty_print_code(sliced_code)

        self.assertEqual(run_code(code_block, variable), run_code(sliced_code, variable))

def run_code(py_code, variable_name):
    globals_space = globals().copy()
    exec(compile(py_code, filename="", mode="exec"), globals_space)
    return globals_space[variable_name]


name = 'Errors'

NO_THREADS = ['No threads to display', 'Нет тредов для отображения']
NO_COMMENTS = ['No comments to display', 'Нет комментов для отображения']
NO_PUBLIC_MESSAGES = ['No public messages to display', 'Нет постов для отображения']
NO_AGENDA_POSTS = ['No agenda posts to display', 'Нет повесток для отображения']
NO_CHAT_ROOMS = ['No chat rooms to display', 'Нет комнат для отображения']

ILLEGAL_ACTION_THREAD_REMOVE = ['You cannot remove this thread', 'Вы не можете удалить этот тред']
ILLEGAL_ACTION_COMMENT_REMOVE = ['You cannot remove this comment', 'Вы не можете удалить этот комментарий']
ILLEGAL_ACTION_AGENDA_POST_REMOVE = ['You cannot remove this agenda post', 'Вы не можете удалить это объ']
ILLEGAL_ACTION_PUBLIC_MESSAGES_REMOVE = ['You cannot remove this public post', 'Вы не можете удалить этот пост']
ILLEGAL_ACTION_LANGUAGE_CODE = ['This is unsupported language code', 'Этот языковой код не поддерживается']
ILLEGAL_ACTION_FILE_TYPE = ['We don\'t use this file type', 'Мы не используем этот формат, бро']
ILLEGAL_ACTION_HOST_ONLY = ['Only hosts can do that', 'Действие доступно только хостам']
ILLEGAL_ACTION_ROOM_ALREADY_HIDDEN = ['The room is already hidden', 'Комната уже скрыта']
ILLEGAL_ACTION_AUTOPLAY_ALREADY_ON = ['The autoplay is already on', 'Автовоспроизведение уже включено']
ILLEGAL_ACTION_AUTOPLAY_ALREADY_OFF = ['The autoplay is already off', 'Автовоспроизведение уже выключено']
ILLEGAL_ACTION_TOLERANCE_ALREADY_OFF = ['The room is already media tolerant', 'Показ медиа уже запрещён']
ILLEGAL_ACTION_TOLERANCE_ALREADY_ON = ['The room is already media intolerant', 'Показ медиа уже разрешен']
ILLEGAL_ACTION_ROOM_USER_ABSENT = ['Selected user is not present in the room', 'Выбранный пользователь не в комнате']

REF_KEY_NOT_EXISTING = ['This key doesn\'t exist', 'Введённый ключ не существует']
REF_KEY_OUTDATED = ['This key is outdated', 'Ключ устарел']
# move the one below to the reg section when ready V
REF_KEY_SUCCESS = ['Key used successfully', 'Ключ использован']


#!/bin/python3

import sys
sys.path.append('../')

import adt

def deleteDuplicates(head):
  if head is None:  return None

  # dummy head node
  dummy = adt.ListNode('0')
  dummy.next = head

  prev = dummy
  while prev.next:
    # set up window of same values
    end = curr = prev.next
    val = curr.val

    # move pointer until end or values differ
    while end.next and end.next.val == val:
      end = end.next

    if curr == end:
      # no deletion - move to next
      prev = curr
    else:
      # delete [curr, end]
      prev.next = end.next

  return dummy.next

if __name__ == "__main__":
  print("Enter space-separated numbers: ", end="")
  nums = sorted(list(map(int, input().strip().split(' '))))

  head = adt.array_to_list(nums)
  print(head)

  head = deleteDuplicates(head)
  print(head)


from sourpea.primitives import *
from sourpea.util import *
import pandas as pd
import os
_dir=os.path.dirname(__file__)
### REGULAR FACTORS
PQtkJAd_C2Q=[Level("M5f YwhvoB6Up",2),'v}Q',"$vFDzKwzEwVMU"]
N99ft=Factor('yzVj[%cdkx',PQtkJAd_C2Q)

### EXPERIMENT
design=[N99ft]
crossing=[N99ft]
### APPENDIX
block=Block(design,crossing,[])
sequence_code_1=trials_from_csv(os.path.join(_dir, "out_code_1/3_1_1_0.csv"))
nr_factors=1
nr_levels=3
test_code_1=block.test(sequence_code_1)
try:
	sequence_code_2=trials_from_csv(os.path.join(_dir, "out_code_2/3_1_1_0.csv"))
	test_code_2=block.test(sequence_code_2)
except:
	test_code_2={"pValue":0}
df=pd.read_csv(os.path.join(_dir, "result_sour.csv"))
df.loc[len(df.index)] = [test_code_1["pValue"], test_code_2["pValue"], nr_factors, nr_levels]
df.to_csv(os.path.join(_dir, "result_sour.csv"), index=False)


import csv
import json
import os
import requests

from boto.s3.key import Key
from boto.s3.connection import S3Connection

AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
CSV_LOCATION = os.environ['CSV_LOCATION']

def get_csv(headers):
    url = CSV_LOCATION
    r = requests.get(url)
    rows = [line.encode('utf-8') for line in r.text.splitlines()]
    reader = csv.DictReader(rows, fieldnames=headers)
    return reader

def geojson_from_csv(csv_reader, order):
    categories = [
        'restaurants',
        'food',
        'shopping',
        'thingstodo',
        'parks',
        'ferries',
    ]
    geojson = {}
    for cat in categories:
        geojson[cat] = {
            'type': 'FeatureCollection',
            'features': []
        }
    csv_reader.next()
    for row in csv_reader:
        lat = float(row.pop('lat'))
        lon = float(row.pop('lon'))
        row.pop('source')
        category = row['parent_category']
        feature = {
            'type': 'Feature',
            'geometry': {'type': 'Point', 'coordinates': [lon, lat]},
            'properties': row
        }
        geojson[category]['features'].append(feature)
    return geojson

def write_geojson(geojson, filename):
    with open(filename, 'w') as f:
        f.write('{fn}({data})'.format(**{
            'fn': 'callback',
            'data': json.dumps(geojson)
        }))

def put_on_s3(filename):
    conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
    bucket = 'favorite-places'
    k = Key(conn.get_bucket(bucket))
    k.key = os.path.join('nyc', filename)
    k.set_contents_from_filename(filename)
    return 'https://s3.amazonaws.com/{bucket}/{key}'.format(**{
        'bucket': bucket,
        'key': k.key
    })

def update_geojson():
    filename = 'favorite-places.jsonp'
    headers = [
        'source',
        'name',
        'parent_category',
        'categories',
        'address',
        'neigborhoods',
        'lat',
        'lon',
        'rating',
        'url'
    ]
    reader = get_csv(headers)
    geojson = geojson_from_csv(reader, headers)
    write_geojson(geojson, filename)
    put_on_s3(filename)

if __name__ == '__main__':
    update_geojson()


import logging
import mmap
import shutil
import tempfile
import os

from fastapi import HTTPException
from turbinia import config as turbinia_config

log = logging.getLogger('turbinia:api_server:utils')

def create_zip(request_id: str, task_id: str):
  """Compress a Turbinia request or task's output directories into a zip file.

  Args:
    request_id (str): Turbinia request identifier.
    task_id (str): Turbinia task identifier.

  Returns:
    A zip compressed bytes stream

  Raises:
    HTTPException if the request/task output paths could not be found
        on the file system.
  """
  log_path = turbinia_config.toDict().get('OUTPUT_DIR')

  request_output_path = os.path.join(log_path, request_id)

  if task_id:
    try:
      request_dirs = os.listdir(request_output_path)
    except FileNotFoundError as exception:
      message = 'Output path {0:s} for task {1:s} could not be found.'.format(
          request_output_path, task_id)
      log.error(message)
      raise HTTPException(status_code=404, detail=message) from exception

    for request_dir in request_dirs:
      if task_id in request_dir:
        request_output_path = os.path.join(request_output_path, request_dir)
        break

  if not os.path.exists(request_output_path):
    message = 'Output path {0:s} for request {1:s} could not be found.'.format(
        request_output_path, request_id)
    log.error(message)
    raise HTTPException(status_code=404, detail=message)

  # Create a temporary directory to store the zip file
  # containing the request result files.
  # Directory and its contents deleted upon context exit.
  temp_directory = tempfile.TemporaryDirectory()
  with temp_directory as directory_name:
    if task_id:
      zip_path = os.path.join(directory_name, task_id)
    else:
      zip_path = os.path.join(directory_name, request_id)

    # Create the zip file
    zip_filename = shutil.make_archive(zip_path, 'zip', request_output_path)
    data = None

    # Read the zip using a memory-mapped file and return it
    with open(zip_filename, 'rb') as zip_obj:
      mm = mmap.mmap(zip_obj.fileno(), 0, access=mmap.ACCESS_READ)
      data = mm.read()

    return data


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

"""
pandas 使用示例
pandas ：pannel data analysis（面板数据分析）。
pandas是基于numpy构建的，为时间序列分析提供了很好的支持。
pandas中有两个主要的数据结构，一个是Series，另一个是DataFrame。
"""

import matplotlib.pyplot as plt
import os
import pandas as pd

from common import logcm
from pandas import DataFrame

# Mac下加载CSV文件的方法
path = os.getcwd() + '/data/file_analysis.csv'
data = pd.read_csv(path)

# DataFrame是一个类似表格的数据结构，
# 索引包括列索引和行索引，包含有一组有序的列，
# 每列可以是不同的值类型（数值、字符串、布尔值等）。
# DataFrame的每一行和每一列都是一个Series，
# 这个Series的name属性为当前的行索引名/列索引名。

df1 = DataFrame(data)
logcm.print_obj(df1, 'df1')

# 按分数排倒序，取前20名
dfSort = df1.sort_values(by='score', ascending=False)
dfHead = dfSort.head(20)
logcm.print_obj(dfHead, 'dfHead')

# 取倒数20名
dfTail = dfSort.tail(20)
logcm.print_obj(dfTail, 'dfTail')

# 按code，对平均分排序
dfGroupSortMean = DataFrame(data, columns=['code', 'score']).groupby('code').mean().sort_values(by='score',
                                                                                ascending=False)
logcm.print_obj(dfGroupSortMean, 'dfGroupSortMean')

# 按code，对平均分排序
dfGroupSortCount = DataFrame(data, columns=['code', 'score']).groupby('code').count().sort_values(by='score',
                                                                                ascending=False)
logcm.print_obj(dfGroupSortCount, 'dfGroupSortCount')

# 按照Code，统计：平均值,合计值，总件数
dfSub = DataFrame(data, columns=['code', 'name', 'score'])
logcm.print_obj(dfSub, 'dfSub')

# 组合Groupby统计，每个列可以有一个函数
dfGroupMulti = dfSub.groupby('code').agg({'score': 'mean', 'name': 'count'})
logcm.print_obj(dfGroupMulti, 'dfGroupMulti')

# 修改显示的列名
dfGroupMulti = dfGroupMulti.rename(columns={'name': 'count', 'score': 'mean'})
# 排序
dfGroupSortMulti = dfGroupMulti.sort_values(by='mean', ascending=False)
logcm.print_obj(dfGroupSortMulti, 'dfGroupSortMulti')

# Series 类似于一维数组与字典(map)数据结构的结合。
# 它由一组数据和一组与数据相对应的数据标签（索引index）组成。
# 这组数据和索引标签的基础都是一个一维ndarray数组。
# 可将index索引理解为行索引。
# Series的表现形式为：索引在左，数据在右。

seriesCode = dfHead['code']
logcm.print_obj(seriesCode, 'seriesCode')

seriesScore = dfTail['score']
logcm.print_obj(seriesScore, 'seriesScore')

# 绘制报告图
# 多子图绘制
fig, axes = plt.subplots(2, 2, sharex=True)
# 设置图片尺寸
# fig.set_size_inches(10, 6)
# 总标题
fig.suptitle(u'分数分布报表')
# 设置标题(中文字体)
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

df2 = DataFrame(data, columns=['code', 'score']).groupby('code').mean().rename(columns={'score': 'mean'})
df2.plot(kind='bar', ax=axes[0][0], title='mean')

df3 = DataFrame(data, columns=['code', 'score']).groupby('code').max().rename(columns={'score': 'max'})
df3.plot(kind='bar', ax=axes[1][0], title='max')

df4 = DataFrame(data, columns=['code', 'score']).groupby('code').std().rename(columns={'score': 'std'})
df4.plot(kind='bar', ax=axes[1][1], title='std')

df5 = DataFrame(data, columns=['code', 'score']).groupby('code').count().rename(columns={'score': 'count'})
df5.plot(kind='bar', ax=axes[0][1], title='count')

# 保存图片
plt.savefig('images/file_analysis_csv_result.jpg')
# 显示绘制后的图片
plt.show()


import string

class ScrambleEncryption():
    """ScrambleEncryption is a two way Encryption method that implements the
     a caesar which will 'shift'. .
     A `salt` is added to the message to allow for extra abstraction/prefixing
     of encoded messages.

    :param salt: the salt for the derivation.
    :param salt_multiplier: multiply the salt for extra security.
    :param message_encoding: allows for different text encodings to be used.
                             Defsults to utf-8.
    """

    def __init__(
        self,
        salt: str = "XX",
        salt_multiplier: int = 1,
        shift: int = 7,
    ) -> None:
        super().__init__()
        self.salt = salt * salt_multiplier
        self.shift = shift

    def encrypt(self, message: str) -> str:
        """Change provided message into a secret code (system of letters, numbers, and/or symbols) that people
           cannot understand

        Args:
            message (_type_): a string that we wish to encode/encrypt so that people cannot understand it

        Returns:
            str: An encoded secret code (system of letters, numbers, and/or symbols) that people cannot understand
        """

        encrypted_message = self.caesar(f"{self.salt}|{message}", self.shift)

        return encrypted_message

    def decrypt(self, encoded_message: str) -> str:
        """make (a coded or unclear message) intelligible.

        Args:
            message (str): an encoded string that we wish to decode/decrypt so that people can understand it

        Returns:
            str: An decoded message code (string) that people can understand again
        """

        decoded_data = self.caesar(encoded_message, -self.shift)
        decoded_data_without_salt = decoded_data.replace(f"{self.salt}|", "")

        return decoded_data_without_salt

    def caesar(self, plaintext: str, shift: int):

        numbers = string.digits
        shifted_numbers = numbers[shift:] + numbers[:shift]
        table = str.maketrans(numbers, shifted_numbers)
        plaintext = plaintext.translate(table)

        punctuation = string.punctuation
        shifted_punctuation = punctuation[shift:] + punctuation[:shift]
        table = str.maketrans(punctuation, shifted_punctuation)
        plaintext = plaintext.translate(table)

        alphabet = string.ascii_uppercase
        shifted_alphabet = alphabet[shift:] + alphabet[:shift]
        table = str.maketrans(alphabet, shifted_alphabet)
        plaintext = plaintext.translate(table)

        alphabet = string.ascii_lowercase
        shifted_alphabet = alphabet[shift:] + alphabet[:shift]
        table = str.maketrans(alphabet, shifted_alphabet)

        return plaintext.translate(table)


import torch
import esm
import gc
from typing import List, Dict

class ESM2_Embeddings:
    def __init__(self, model_variant: str):

        if model_variant == 't36':
            embedding_model, alphabet = esm.pretrained.esm2_t36_3B_UR50D()
        elif model_variant == 't33':
            embedding_model, alphabet = esm.pretrained.esm2_t33_650M_UR50D()
        elif model_variant == 't30':
            embedding_model, alphabet = esm.pretrained.esm2_t30_150M_UR50D()
        elif model_variant == 't12':
            embedding_model, alphabet = esm.pretrained.esm2_t12_35M_UR50D()
        else:
            embedding_model, alphabet = esm.pretrained.esm2_t6_8M_UR50D()

        self.embedding_model = embedding_model
        self.alphabet = alphabet
        self.n_layers = int(model_variant[1:])

    def generate_embeddings(self, sequences: List[str], ids: List[str]) -> Dict[str, torch.tensor]:

        tokenizer = self.alphabet.get_batch_converter()
        device = torch.device("cpu")

        self.embedding_model.to(device)
        self.embedding_model.eval()

        sequence_ids = list(zip(ids, sequences))

        ind = 0
        batch_size = 16
        n_seqs = len(sequence_ids)
        embedding_ids = {}

        while ind < n_seqs:
            if ind + batch_size > n_seqs:
                batch_size = n_seqs - ind
            _, _, batch_tokens = tokenizer(sequence_ids[ind:ind + batch_size])
            batch_lens = (batch_tokens != self.alphabet.padding_idx).sum(1)
            with torch.no_grad():
                batch_tokens = batch_tokens.to(device)
                results = self.embedding_model(batch_tokens, repr_layers=[self.n_layers])
            token_representations = results["representations"][self.n_layers].to(device)

            for i, tokens_len in enumerate(batch_lens):
                embedding_ids[sequence_ids[ind + i][0]] = token_representations[i, 1:tokens_len - 1].cpu()
            ind += batch_size

        del self.embedding_model
        del tokenizer
        gc.collect()

        return embedding_ids


# ----------------------------  Class details ------------------------------------------
class Person :                                                # Convension : Class name's first letter is capital.
    def __init__(self, first_name, last_name, age) :
        print('Init method or constructor method')
        # Instance variables
        # Object(self).Instance Variable(first_name) = Local Variable(first_name)
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def full_name(self) :
        return f'{self.first_name} {self.last_name}'

    def is_above_18(self) :
        return self.age > 18

p1 = Person('Rezoan', 'Shakil', 22)

print(f'First name : {p1.first_name}')
print(f'Last name : {p1.last_name}')
print(f'Age : {p1.age}')
print()
print(p1.full_name())
print(p1.is_above_18())

# ------------------------------ Class variable -----------------------------------------------
class Circle :
    pi = 3.1416                                                 # Class variable or class attribute
    def __init__(self, radius) :
        self.radius = radius

    def calculate_circumference(self) :
        return Circle.pi * self.radius * self.radius            # Class Name(Circle).Class Variable(pi)

c1 = Circle(4)
print(c1.__dict__)                                              # The overview of all the variables in dictionary
print(c1.calculate_circumference())

# ----------------------------- Example : 01 -------------------------------------------------
# Counting total objects of the class

class Person2 :
    count_instance = 0
    def __init__(self) :
        Person2.count_instance += 1

    @classmethod                                                  # Class method using decorator
    def total_instances(cls) :                                    # 'cls' indicates 'Person2' class
        return f'I have created {cls.count_instance} instances of {cls.__name__} class'

P1 = Person2()
P2 = Person2()
print(Person2.count_instance)
print(Person2.total_instances())

# ------------------------------ Class method as a constructor and static method -----------------------------
class Person3 :
    def __init__(self, first_name, last_name, age) :
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    @classmethod
    def from_string(cls, string) :
        first_name, last_name, age = string.split(',')
        return cls(first_name, last_name, age)

    @staticmethod
    def hello() :                                                   # Static method
        print('Hello, Static method called')

# Own made object created by class method
P3 = Person3.from_string('Rezoan,Shakil,22')
print(f'First name : {P3.first_name}')
print(f'Last name : {P3.last_name}')
print(f'Age : {P3.age}')
print()

Person3.hello()


"""Marco Men
Adapted from:https://blog.dreamshire.com/project-euler-5-solution/
https://code.mikeyaworski.com/python/project_euler/problem_5"""

def factorial(n):
  if n==0:#Base case
     return 1
  else:
    return n*factorial(n-1)#Recursive call

def is_multiple(a,n):#checks if a is a multiple of every number from 1 to n
    for i in range (1,n):
      if a % i !=0:
        return False
    return True

def findSmallestMultiple(n):
    for i in range(n, factorial(n) + 1, n):
        if is_multiple(i, n):
            return i
    return -1 # finishes the function

print (findSmallestMultiple(10))
print(findSmallestMultiple(20))


import numpy as np

from regression_models import ml_weights
from regression_models import regularised_ml_weights
from regression_models import linear_model_predict

#determine which part is for training and which for testing
def train_and_test_split(N, test_fraction=None):
    """
    Randomly generates a train/test split for data of size N.

    parameters
    ----------
    N - the dataset size
    test_fraction - a fraction (between 0 and 1) specifying the proportion of
        the data to use as test data.
    """
    if test_fraction is None:
        test_fraction = 0.5
    #p is the probability of the column/ entry is true or false
    p = [test_fraction,(1-test_fraction)]
    #if you add np.random.seed(37), you will get the same result every time, otherwise you will get different results
    #however, you want to run your model on variety train and test set to check your model, so choose randomly
    train_part = np.random.choice([False,True],size=N, p=p)
    test_part = np.invert(train_part)
    return train_part, test_part

def train_and_test_partition(inputs, targets, train_part, test_part):
    """
    Splits a data matrix (or design matrix) and associated targets into train
    and test parts.

    parameters
    ----------
    inputs - design matric, where rows are the feature vectors for data points.
    targets - a 1d numpy array whose elements are the targets.
    train_part - A list (or 1d array) of N booleans, where N is the number of
        data points. If the ith element is true then the ith data point will be
        added to the training data.
    test_part - (like train_part) but specifying the test points.

    returns
    -------
    train_inputs - the training input matrix
    train_targets - the training targets
    test_inputs - the test input matrix
    test_targets - the test targtets
    """
    # get the indices of the train and test portion
    train_inputs = inputs[train_part,:]
    test_inputs = inputs[test_part,:]
    train_targets = targets[train_part]
    test_targets = targets[test_part]
    return train_inputs, train_targets, test_inputs, test_targets

def root_mean_squared_error(y_true, y_pred):
    """
    Evaluate how closely predicted values (y_pred) match the true values
    (y_true, also known as targets)

    Parameters
    ----------
    y_true - the true targets
    y_pred - the predicted targets

    Returns
    -------
    mse - The root mean squared error between true and predicted target
    """
    N = len(y_true)
    # be careful, square must be done element-wise (hence conversion
    # to np.array)
    mse = np.sum((np.array(y_true).flatten() - np.array(y_pred).flatten())**2)/N
    return np.sqrt(mse)

def train_and_test( train_inputs, train_targets, test_inputs, test_targets, reg_param=None):
    """
    Will fit a linear model with either least squares, or regularised least
    squares to the training data, then evaluate on both test and training data

    parameters
    ----------
    train_inputs - the input design matrix for training
    train_targets - the training targets as a vector
    test_inputs - the input design matrix for testing
    test_targets - the test targets as a vector
    reg_param (optional) - the regularisation strength. If provided, then
        regularised maximum likelihood fitting is uses with this regularisation
        strength. Otherwise, (non-regularised) least squares is used.

    returns
    -------
    train_error - the training error for the approximation
    test_error - the test error for the approximation
    """
    # Find the optimal weights (depends on regularisation)
    if reg_param is None:
        # use simple least squares approach
        weights = ml_weights(
            train_inputs, train_targets)
    else:
        # use regularised least squares approach
        weights = regularised_ml_weights(
          train_inputs, train_targets,  reg_param)
    # predictions are linear functions of the inputs, we evaluate those here
    train_predicts = linear_model_predict(train_inputs, weights)
    test_predicts = linear_model_predict(test_inputs, weights)
    # evaluate the error between the predictions and true targets on both sets
    train_error = root_mean_squared_error(train_targets, train_predicts)
    test_error = root_mean_squared_error(test_targets, test_predicts)
    return train_error, test_error


# problem: https://leetcode.com/problems/can-convert-string-in-k-moves/
# Runtime: 664 ms, faster than 5.83% of Python3 online submissions for Can Convert String in K Moves.
# Memory Usage: 15 MB, less than 91.75% of Python3 online submissions for Can Convert String in K Moves.

class Solution:
    def aux(self, x):
        if x[0] > x[1]:
            return 26 - x[0] + x[1]
        else:
            return x[1] - x[0]

    def canConvertString(self, s: str, t: str, k: int) -> bool:
        from collections import defaultdict
        if len(s) != len(t):
            return False
        m = defaultdict(int)
        for a, b in zip(s, t):
            m[self.aux((ord(a), ord(b)))] += 1
        m[0] = 0
        for i in range(1, 27):
            tmp = i % 26
            if m[tmp]:
                m[tmp] -= min(k // 26 + 1, m[tmp]
                              ) if k % 26 >= i else min(k // 26, m[tmp])
        return not any(list(m.values()))