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

import sys
from contextlib import contextmanager

from fabric.api import cd, env, show, hide
from .. import signal, configuration
from ..utils import run

def init():
    configuration.setdefault('curl_url', '')
    configuration.setdefault('curl_output', '')
    configuration.setdefault('curl_options', '')
    configuration.setdefault('curl_extract_tar', '')
    configuration.setdefault('curl_extract_tgz', '')
    configuration.setdefault('curl_user', '')
    configuration.setdefault('curl_postinstall_script', '')
    configuration.setdefault('curl_postinstall_output', True)
    signal.register('deploy.updating', download_artifact)

class StreamFilter(object):

    def __init__(self, filter, stream):
        self.stream = stream
        self.filter = filter

    def write(self,data):
        if not self.filter:
            self.stream.write(data)
            self.stream.flush()
        else:
            user = self.filter[:self.filter.index(':')]
            data = data.replace(self.filter, '%s:**************' % user)
            self.stream.write(data)
            self.stream.flush()

    def flush(self):
        self.stream.flush()

@contextmanager
def credential_output():
    sys_stdout = sys.stdout
    credential_stdout = StreamFilter(env.curl_user, sys_stdout)

    sys.stdout = credential_stdout
    yield
    sys.stdout = sys_stdout

def download_artifact(**kwargs):
    with cd(env.release_path), credential_output():
        cmd = 'curl --max-time 30 --retry 3 %(curl_url)s' % env
        if env.curl_user:
            cmd += ' --user %(curl_user)s' % env
        if env.curl_output:
            cmd += ' -o %(curl_output)s' % env
        if env.curl_options:
            cmd += ' %(curl_options)s' % env
        if env.curl_extract_tar:
            cmd += ' | tar -x'
        elif env.curl_extract_tgz:
            cmd += ' | tar -xz'
        run(cmd)
        if env.curl_postinstall_script:
            output = show if env.curl_postinstall_output else hide
            with output('output'):
                run(env.curl_postinstall_script)


string1 = 'Hello world'
string2 = " Hello world"
print(string1 + string2)
'''
This string is on
multiple lines
within three single
quotes on either side.
'''

"""
This string is on
multiple lines
within three double
quotes on either side.
"""


'''

'''
#%%import packages and set directories
import os

from functions_triplet import *
from flow_function_Triplet import *

WD = r'C:\Users\msvanesch\Documents\08-Python_Scripts\PySeawaTriplet'
os.chdir(WD)       # Set the proper working directory (WD)

'''Define input files'''
swtexe_name = 'swt_v4x64.exe'
wellfile = 'wells.csv'
demandfile = 'demand.csv'
subsurffile = 'sub-surface.csv'
monitoringfile = 'monitoring.csv'

#%%create the objects needed
well_obj_list = createobjfromCSV(PyWell,wellfile) #creates well object from  data in csv file
form_obj_list = createobjfromCSV(PySystem,subsurffile)
mon_obj_list = createobjfromCSV(PySystem,monitoringfile) # creates list of monitoring points in your grid where you can track the temperature

nmon = len(mon_obj_list)
nform = len(form_obj_list)
nW=len(well_obj_list)         # numer of wells
T_amb = form_obj_list[0].s1   # Ambient Temperature of the subsurface
PEFF = form_obj_list[0].por   # porosity [-]

#%% B: settings for model run

'''Set name for run'''
naam = 'test'
case = '2'
name = naam + case

dirs = WD+'/output/'+name
if os.path.exists(dirs)==False:
    os.makedirs(dirs)

'''main time setting parameters'''
perlen = 1    # (DAYS)
years = 5        # set the minimum #years that a system will run
ppy = 365/perlen

startwinter = 1 # simulation starts in winter (1) or summer (0). for distribution of flows of wells and surface temperature

nper = 1      # Number of Modflow stress periods per coupled simulation period
nstp = 1      # Number of Modflow time steps per stress period
timprs = np.array([perlen])
nprs = len(timprs)

repeatrun = 0     # repeatrun starts the run with the last temperature file of the previous run as initial conditions
finaltimestep = 365/perlen*years-1

'''Model flow input'''
flowtype = 2     # choise between 0 and 4, see readme
gwflow_x = -0.   # Groundwater flowvelocity in x direction [m/y]
gwflow_y = -0.   # Groundwater flowvelocity in y direction [m/y]

densflow = 1     # turn densityflow off or on by switching the VDF packages off or on
WaterDensON = 1  # Calculation of parameters standard =1

'''correction factors determine the recharge of the wells by multiplying the needed flow to meet the demand by the factor'''
corr_w = 1.5      # correction factor hot well
corr_1 = corr_w   # startup correction factor, only applied to hot well.
corr_c = 1.0      # correction factor cold well

Thmin = 5          #Thmin is the temperature difference in the hot well between the injection temperature and the cutoff temperature

for i in well_obj_list:       # Update each active Python well object with the temperature and head at its grid location
    if i.type == 'warm':
        print(i.T_inj)
        cutofftemp_h = i.T_inj-Thmin

cutofftemp_c = T_amb-2   # Temperature when the heating turns off, thus no more discharge from the hot well

T_room = 20                 # Room temperature in building, used for return temperature groundwater after heat exchanger
T_loss_building = 2         # degrees that the return temperature deviates from room temperature. The higher, the bigger the losses in the HVAC system.

'''grid settings '''
AXI = 1              # axial symmetric grid or not. | 1=AXI, 0 = 3D |
LIN = 0              # Linear (1) or logarithmic (0) cell sizes buildup around the center of the modelgrid
ICBUND_Up = -1       # TOP:: -1 = boundary has constant temperature (NO Flow, YES Temperature boundary), 1 = NO Flow, No Tempertature boundary
ICBUND_Down = -1     # BOTTOM: -1 = boundary has constant temperature (NO Flow, YES Temperature boundary), 1 = NO Flow, No Tempertature boundary
OutsideAirBound = 0  # 1 = ON, 0=OFF, if ON: the temperature boundary at model top is adjusted following outside air temperature
steady = True        # Switch for steady-state/transient Modflow simulation

dmin = 1              # smallest cel size at well [m]
dmin_bound = 200      # total distance from well with 'dmin' sized cells [m]
dmax = 200            # largest cell size at model boundary [m]
aroundAll = 1000      # normal=1500 [m] size of grid around well.
nstep = 20            # minimum number of steps that gridfunctions must add  to acquire the dmax size requirement [-]
grid_extents = None   # example:[-300,300,-300,300] #set model boundaries [m]
dz = 1                # vertical gridlayer thickness [m]  important to syncronize with layer thicknesses in csv file!
#%%

exec(open('PySeawaTriplet.py').read())


# -*- coding: utf-8 -*-
# @Time     :2020/5/27 21:33
# @Author   :12257
# @SoftWare :PyCharm
from django.conf import settings
from django.utils.safestring import mark_safe

class MyPagenation():

    def __init__(self, page, total_count, per_page_num, page_num_show, base_url, get_data=None):
        """

        :param page: 当前页
        :param total_count: 数据总数量
        :param per_page_num: 每页数据
        :param page_num_show: 显示的页码数
        :param base_url: 基本路径
        :param get_data: 查询数据_Query_dict?
        """
        self.base_url = base_url
        self.get_data = get_data
        per_page_num = settings.PER_PAGE_NUM  # 每页显示多少数据
        page_num_show = settings.PAGE_NUM_SHOW  # 显示的页码数
        customer_count = total_count
        div, mod = divmod(customer_count, per_page_num)
        if mod:
            page_num_count = div + 1
        else:
            page_num_count = div
        try:
            self.page = int(page)
        except Exception as e:
            self.page = 1
        if self.page <= 0:
            self.page = 1
        elif self.page > page_num_count:
            self.page = page_num_count
        self.page_num_count = page_num_count
        start_num = (self.page - 1) * per_page_num
        end_num = self.page * per_page_num
        page_num_half_show = page_num_show // 2
        page_num_start_show = self.page - page_num_half_show
        page_num_end_show = self.page + page_num_half_show + 1
        if page_num_start_show <= 0:  # 异常分页判断
            page_num_start_show = 1
            page_num_end_show = page_num_show + 1
        elif page_num_end_show > page_num_count:
            page_num_start_show = page_num_count - page_num_show + 1
            page_num_end_show = page_num_count + 1
        if page_num_count < page_num_end_show:
            page_num_end_show = page_num_count + 1
        self.start_num = start_num
        self.end_num = end_num
        self.page_num_start_show = page_num_start_show
        self.page_num_end_show = page_num_end_show

    @property
    def start_num_show(self):
        return self.start_num

    @property
    def end_num_show(self):
        return self.end_num

    def page_html(self):
        page_num_range = range(self.page_num_start_show, self.page_num_end_show)
        page_html = ''
        first_page_html = f'

首页
'
        page_html += first_page_html
        page_pre = ''
        page_html += page_pre
        if self.page <= 1:
            pre_page = f'
«
'
        else:
            pre_page = f'
«
'
        page_html += pre_page
        for i in page_num_range:
            if i == self.page:
                page_html += f'
{i}
'
            else:
                page_html += f'
{i}
'
        if self.page >= self.page_num_count:
            page_next_html = f'
»
 '
        else:
            page_next_html = f'
»
'
        page_html += page_next_html
        last_page_html = f'
尾页

'
        page_html += last_page_html
        return mark_safe(page_html)


dividend = int(input())
divisor = int(input())
control = ''
count = 0
if dividend < 0 and divisor > 0:
    control = '-'
    dividend = 0 - dividend
if dividend > 0 and divisor < 0:
    control = '-'
    divisor = 0 - divisor
while dividend >= divisor:
    dividend = dividend - divisor
    count = count + 1
print(control + str(count))


from pathlib import Path
from dataclasses import dataclass, field
from typing import Iterator
import math
from os import system, name
from time import sleep
import copy
from termcolor import colored

def highlight(text: str, color: str = "white", on_color: str = "on_blue"):
    return colored(text, color, on_color)

def clear():
    # for windows
    if name == "nt":
        _ = system("cls")

    # for mac and linux
    else:
        _ = system("clear")

@dataclass
class Instruction:
    @classmethod
    def from_str(cls, line: str) -> "Instruction":
        if line.startswith("noop"):
            return Noop()
        elif line.startswith("addx"):
            _, value = line.split(" ")
            return AddX(value=int(value))
        else:
            raise ValueError(f"Unknown instruction: {line}")

@dataclass
class AddX(Instruction):
    value: int

@dataclass
class Noop(Instruction):
    ...

def initial_state_visualization() -> list[list[str]]:
    return [[" " for _ in range(40)] for _ in range(6)]

@dataclass
class State:
    instruction: Instruction
    register_x: int
    cycle_number: int
    visualization: list[list[str]] = field(
        default_factory=initial_state_visualization, repr=False, compare=False
    )

    @property
    def pointer(self) -> int:
        return self.cycle_number - 1

    def position_to_x_y(self, position: int) -> tuple[int, int]:
        x = position % 40
        y = math.floor(position / 40)
        return x, y

    def __post_init__(self):
        if self.has_to_print():
            position = self.position_to_x_y(self.pointer)
            self.visualization[position[1]][position[0]] = highlight(
                " ", color="white", on_color="on_white"
            )

    def has_to_print(self) -> bool:
        row = self.position_to_x_y(self.pointer)[1]
        slice_pointer = self.register_x + row * 40
        if self.pointer in [slice_pointer, slice_pointer + 1, slice_pointer - 1]:
            return True
        return False

    def print(self, debug: bool = False) -> str:
        matrix = copy.deepcopy(self.visualization)
        if debug is True:
            pointer = self.position_to_x_y(self.pointer)
            matrix[pointer[1]][pointer[0]] = highlight(
                matrix[pointer[1]][pointer[0]],
                color="white",
                on_color="on_red",
            )
            row = self.position_to_x_y(self.pointer)[1]
            slice_pointer = self.register_x + row * 40
            sprint_0 = self.position_to_x_y(slice_pointer - 1)
            sprit_1 = self.position_to_x_y(slice_pointer)
            spirit_2 = self.position_to_x_y(slice_pointer + 1)
            matrix[sprint_0[1]][sprint_0[0]] = highlight(
                matrix[sprint_0[1]][sprint_0[0]]
            )
            if sprit_1[0] <= 39 and sprit_1[1] <= 5:
                matrix[sprit_1[1]][sprit_1[0]] = highlight(
                    matrix[sprit_1[1]][sprit_1[0]]
                )
            if spirit_2[0] <= 39 and spirit_2[1] <= 5:
                matrix[spirit_2[1]][spirit_2[0]] = highlight(
                    matrix[spirit_2[1]][spirit_2[0]]
                )
        repr = "\n".join(["".join(i) for i in matrix])
        return repr

    @property
    def signal_strength(self) -> int:
        return self.register_x * self.cycle_number

    def repr(self):
        return "\n".join(["".join(row) for row in self.visualization])

def generate_cycles(instructions: Iterator[Instruction]) -> Iterator[State]:
    cycle_number = 1
    register_x = 1
    s = State(
        instruction=Noop(),
        cycle_number=cycle_number,
        register_x=register_x,
    )
    for instruction in instructions:
        if isinstance(instruction, AddX):
            s = State(
                instruction=instruction,
                cycle_number=cycle_number,
                register_x=register_x,
                visualization=s.visualization,
            )
            yield s
            cycle_number += 1
            s = State(
                instruction=instruction,
                cycle_number=cycle_number,
                register_x=register_x,
                visualization=s.visualization,
            )
            yield s
            register_x += instruction.value
            cycle_number += 1
        elif isinstance(instruction, Noop):
            s = State(
                instruction=instruction,
                cycle_number=cycle_number,
                register_x=register_x,
                visualization=s.visualization,
            )
            yield s
            cycle_number += 1

def problem_1(input_path: Path) -> int:
    signal_strength = 0
    with open(input_path) as f:
        instructions = map(Instruction.from_str, f)
        cycles = generate_cycles(instructions)
        print()
        for c in cycles:
            if (c.cycle_number - 20) % 40 == 0 or c.cycle_number == 20:
                signal_strength += c.signal_strength
    return signal_strength

def problem_2(input_path: Path) -> Iterator[State]:
    with open(input_path) as f:
        instructions = map(Instruction.from_str, f)
        cycles = generate_cycles(instructions)
        for c in cycles:
            yield c

def print_day_10(input_path: Path):
    p1 = problem_1(input_path)
    p2 = problem_2(input_path)
    for c in p2:
        clear()
        print(highlight(" " * 40, color="white", on_color="on_white"))
        print(f"Problem 1: {p1}")
        print("Problem 2:")
        print(highlight(" " * 40, color="white", on_color="on_white"))
        print()
        print(c.print(debug=True))
        print()
        print(highlight(" " * 40, color="white", on_color="on_white"))
        sleep(0.1)

def main():
    # input_path = Path("files/day10/test_input.txt")
    input_path = Path("files/day10/input.txt")
    print_day_10(input_path)

if __name__ == "__main__":
    main()


import pandas as pd
import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2,f_regression
from sklearn.ensemble import ExtraTreesClassifier
import matplotlib.pyplot as plt
import os.path
import re

"""

This file calls inbuilt functions from a range of different feature selection related libraries and modules in order to output a set of features
deriving from the Z-Alizadeh data set.

Robustness: Both functions first check for the existence of an appropriate csv file which will contain the
dataset intended for the features to be selected from. If this file does not exist the functions will exit.

Scalability: These functions will work with other databases of larger sizes as long as they are properly formatted
and the right target feature is specified within the code.

"""

def chiSquared():

    """
    Funtion calls feature selection methods in the using a chiSquared module to determine the best features using the chi
    sq method.
    :return: returns an array of feature names with the 16 best scores
    """

    if os.path.isfile('Zasd.csv') != True:
        raise Exception("File not exist")

        # read data from csv file
    dataframe = pd.read_csv('Zasd.csv')

    if dataframe.empty:
        raise Exception('CSV file is empty')

    datfile = open('Zasd.csv','r')
    dat = [line.split(',') for line in datafile.readlines()]

    for i in dat[1:]:
        if len(i) > len(dat[0]):
            raise Exception("There is data row that is longer then the header row.")

    for i in dat[0]:
        if blank.match(i).end() == len(i):
            raise Exception("Empty header column found")

    # drop target columns
    drop_cols = ['Cath']
    X = dataframe.drop(drop_cols, axis=1)  # define the independent columns
    y = dataframe['Cath']  # set y as the target column for the model (what should be predicted)

    # initialize SelectKBest to dind 16 best features
    best_features = SelectKBest(chi2, k=16)
    fit = best_features.fit(X, y)
    df_scores = pd.DataFrame(fit.scores_) # fit dataframe into list
    df_columns = pd.DataFrame(X.columns)

    feature_scores = pd.concat([df_columns, df_scores], axis=1)
    feature_scores.columns = ['Feature_Name', 'Score']

        # export the selected features to a .csv file
    df_univ_feat = feature_scores.nlargest(16, 'Score')
    df_univ_feat.to_csv('feature_selection_UNIVARIATE.csv', index=False)

    return (feature_scores.nlargest(16,'Score'))

def treeClassifier():

    """
    Funtion calls feature selection methods in the using a decision tree module to determine the best features using the tree classifier method.
    :return: returns an array of feature names with the 16 best scores
    """

    if os.path.isfile('Zasd.csv') != True:
        raise Exception("File not exist")

        # read data from csv file
    dataframe = pd.read_csv('Zasd.csv')

    if dataframe.empty:
        raise Exception('CSV file is empty')

    datfile = open('Zasd.csv','r')
    dat = [line.split(',') for line in datafile.readlines()]

    for i in dat[1:]:
        if len(i) > len(dat[0]):
            raise Exception("There is data row that is longer then the header row.")

    for i in dat[0]:
        if blank.match(i).end() == len(i):
            raise Exception("Empty header column found")

    dataframe = pd.read_csv("Zasd.csv")

    X = dataframe.iloc[:,0:54]  #set independent columns
    y = dataframe.iloc[:,-1]    #set target column in this case- 'Cath'
    model = ExtraTreesClassifier()
    model.fit(X,y)

    #plot graph of features
    feat_importances = pd.Series(model.feature_importances_, index=X.columns)
    feat_importances.nlargest(16).plot(kind='barh')

    # plt.show()
    # print(feat_importances.nlargest(20))
    return (feat_importances.nlargest(16))

# chiSquared()
# treeClassifier()


T=int(input())
li=[]
nums=[[0] for _ in range(101)]
mx=0
mx_li=[]
for tc in range(1,T+1):
    t=int(input())
    scores=list(map(int,input().split()))
    for ele in scores:
        if ele not in li:
            li.append(ele)
        elif ele in li:
            nums[100-ele]=scores.count(ele)
    # print(nums)
    print(f'#{tc} {100-nums.index(max(nums))}')

SWEA/D2/1204. ［S／W 문제해결 기본］ 1일차 － 최빈수 구하기/［S／W 문제해결 기본］ 1일차 － 최빈수 구하기.py

［S／W 문제해결 기본］ 1일차 － 최빈수 구하기.py


from dataclasses import replace
from sqlite3 import Cursor
from typing import List, Optional

from .utils import data_to_address
from ..models import Prefecture, City, Address

def fetch_address_by_zip_code(cursor: Cursor, zip_code: str) -> List[Address]:
    cursor.execute(f"SELECT p.*, c.*, a.* FROM addresses AS a "
                   f"JOIN cities AS c ON c.id = a.city_id "
                   f"JOIN prefectures AS p ON p.id = c.prefecture_id "
                   f"WHERE a.zip_code=?", (zip_code,))
    data = cursor.fetchall()

    return [data_to_address(v) for v in data]

def fetch_addresses_from_city(cursor: Cursor, city: City) -> List[Address]:
    cursor.execute(f"SELECT * FROM addresses "
                   f"WHERE city_id=?", (city.id,))
    data = cursor.fetchall()
    addresses = []
    for v in data:
        addresses.append(replace(Address(*v), city=city))

    return addresses

def fetch_address_by_id(cursor: Cursor, id_: int) -> Optional[Address]:
    cursor.execute((f"SELECT p.*, c.*, a.* FROM addresses AS a "
                    f"JOIN cities AS c ON c.id = a.city_id "
                    f"JOIN prefectures AS p ON p.id = c.prefecture_id "
                    f"WHERE a.id=?"), (id_,))
    data = cursor.fetchone()
    return data_to_address(data) if data else None

def search_addresses(cursor: Cursor, query: str, prefecture: Prefecture, city: City, type_: str) -> List[Address]:
    query = [f"SELECT p.*, c.*, a.* FROM addresses AS a "
             f"JOIN cities AS c ON c.id = a.city_id "
             f"JOIN prefectures AS p ON p.id = c.prefecture_id "
             f"WHERE a.{type_} LIKE '%{query}%'", []]
    if prefecture:
        query[0] += ' AND p.id = ?'
        query[1].append(prefecture.id)
    if city:
        query[0] += ' AND c.id = ?'
        query[1].append(city.id)
    cursor.execute(*query)
    data = cursor.fetchall()

    return [data_to_address(v) for v in data]

__all__ = [
    'fetch_address_by_zip_code',
    'fetch_addresses_from_city',
    'fetch_address_by_id',
    'search_addresses',
]


from logigear.core.elements.element import Element
from logigear.core.utilities import utils
from logigear.core.helpers import page_object_helper, logger

def get_defined_element(pageNames, locatorName, targetClass=None):
    locator = None
    for pageName in pageNames:
        locator = get_defined_locator(pageName, locatorName)
        if locator is not None:
            break;

    if locator is None:
        msg = "Cannot find locator for '%s' in '%s'." % (locatorName, pageName)
        raise Exception(msg)

    if targetClass:
        return targetClass(get_locator(locator["locators"]))
    return Element(get_locator(locator["locators"]))

def get_defined_locator(pageName, locatorName):
    pageLocators = page_object_helper.get_page_locators(pageName)

    if pageLocators is None:
        logger.warn("Cannot find %s page" % pageName)
        return None

    locator = next((l for l in pageLocators if l["name"] == locatorName), None)
    return locator

def get_locator(locators):
    platform, browser = utils.get_environment()
    platform, browser = (platform.lower(), browser.lower())

    sKey1 = "%s.%s" % (browser, platform);
    sKey2 = "%s._" % browser;
    sKey3 = "_.%s" % platform;
    sKey4 = "_._";

    sValue = [e for e in locators if e.startswith(sKey1)]
    if len(sValue) == 0:
        sValue = [e for e in locators if e.startswith(sKey2)]
    if len(sValue) == 0:
        sValue = [e for e in locators if e.startswith(sKey3)]
    if len(sValue) == 0:
        sValue = [e for e in locators if e.startswith(sKey4)]

    if len(sValue) == 0:
        msg = "Cannot find locator in " + locators
        print (msg)
        raise Exception(msg)

    return sValue[0].split(':', 1)[1]


from fastapi import FastAPI
from pydantic import BaseModel
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import uvicorn

app = FastAPI()

# Load the drivers' data from the CSV file
travel_df = pd.read_csv('Travel.csv')
users_df = pd.read_csv('Users.csv')

# Define the request data structure
class UserRequestBody(BaseModel):
    startPlace_latitude: float
    startPlace_longitude: float
    endPlace_latitude: float
    endPlace_longitude: float

# ... [Include the haversine_distance and find_best_match_for_user functions here] ...
def find_best_match_for_user (user, df, users_df):
    X_match = pd.DataFrame()

    X_match['x_lat'] = df['startPlace.latitude']
    X_match['x_long'] = df['startPlace.longitude']
    X_match['y_lat'] = df['endPlace.latitude']
    X_match['y_long'] =  df['endPlace.longitude']

    y_balance = pd.DataFrame()
    y_balance['balance'] = df['priceBalance']

    model_balance = LinearRegression()
    model_balance.fit(X_match, y_balance)

    result_balance = model_balance.predict([user])
    result_balance_1 = (result_balance[0][0])
    result_balance_good = int(result_balance_1)

    users_df['balance'] = abs(users_df['balance'])

    for j in range(100):
        for i in range(1000):
            if users_df.iloc[i]['balance'] == result_balance_good+j:
                return users_df.iloc[i]['id']

# Endpoint to match a user with a driver
@app.post('/match_driver')
def match_driver(data: UserRequestBody):
    # Convert the request data to a pandas Series (to be compatible with our existing function)

    test_data_match = [
            data.startPlace_latitude,
            data.startPlace_longitude,
            data.endPlace_latitude,
            data.endPlace_longitude
    ]

    user_series = pd.Series(test_data_match) ############## Only not sure

    # Use the matching function to get the matched driver's ID
    matched_driver_id = find_best_match_for_user(user_series, travel_df, users_df)

    # Return the matched driver's ID
    return {'matched_driver_id': matched_driver_id}


#!/usr/bin/python

import csv
import operator
from string import punctuation
from nltk.corpus import stopwords

#########################################################
#                                                       #
#   Reads the probabilties associated with the classes  #
#   from the csv files written with "scripter.py".      #
#   Computes the probability, makes the predictions     #
#   and write them in a csv file, using the format      #
#   required by Kaggle                                  #
#                                                       #
#########################################################

global eng_stopwords
eng_stopwords = stopwords.words("english")

def main(input_strings, train_output, valid_output, alpha):
    classes = ['cs','stat','math','physics']
    word_probs = dict()
    class_count = class_counter(train_output)
    results = list()
    for classe in classes:
        word_probs[classe] = get_probs(classe)
    for i in range(len(input_strings)):
    	#print("Predicting abstract {}".format(i))
        result = predict(word_probs,input_strings[i], class_count, alpha)
        results.append(result)
    #write_prediction('output.csv',results)
    print(error_counter(results, valid_output))
    return error_counter(results, valid_output)

def predict(word_probs,string,class_count, alpha):
    prob = dict()
    abstract = string.split()
    for i in range(len(abstract)):
        for classe in list(word_probs.keys()):
        	if not classe in prob:
        		prob[classe] = 1
        	if abstract[i] in word_probs[classe]:
        		prob[classe] = (float)(prob[classe])*(float)((word_probs[classe])[abstract[i]])
        	else:
        		prob[classe] = (float)(prob[classe])*(float)(alpha/(class_count[classe]+ alpha*(float)(len(list(word_probs[classe].keys())))))
    return max(prob, key=prob.get)

# Gets the entry of one column into a list
def get_csv_content(title,category):
    input_file = list(csv.DictReader(open(title)))
    entry = list()
    for i in range(len(input_file)):
        entry.append(input_file[i][category])
    return entry

def error_counter(result, answer):
	error_count = 0
	for i in range(len(result)):
		if result[i] != answer[i]:
			error_count += 1
	return error_count

# sanatize one string
# NOT USED
def sanatizer(abstract):
    abstract = ''.join(c for c in abstract if c not in punctuation)
    abstract = abstract.lower()
    abstract = ' '.join([word for word in abstract.split() if word not in eng_stopwords])
    return abstract

def get_probs(classe):
	title = classe+".csv"
	myfile = csv.DictReader(open(title))
	for row in myfile:
		result = row
	return result

# Counts the occurence of each class from a list of strings (the strings are the name of the classes)
def class_counter(dict_classes):
    class_count = dict()
    for classe in dict_classes:
        if classe in class_count:
            class_count[classe] =  class_count[classe] + 1
        elif classe != 'category':
            class_count[classe] = 1
    return class_count

# Write into csv files named 'title' the results in the category column
def write_prediction(title,results):
    field_names = ['id','category']
    writer = csv.DictWriter(open(title,'w'), fieldnames=field_names)
    writer.writeheader()
    for i in range(len(results)):
    	dic = dict()
    	dic['id'] = i
    	dic['category'] = results[i]
    	writer.writerow(dic)

if __name__ == "__main__":
    input_strings = get_csv_content('train_in2.csv','abstract')
    output = get_csv_content('train_out.csv','category')
    main(input_strings, output, output, 0.5)


from flask import Flask, jsonify, request

app = Flask(__name__)

stores = [
    {
        'name': 'Complete Life Optimization',
        'items': [
            {
                'name': 'Bulletproof Coffe',
                'price': 20.99
            }
        ]
    }
]

@app.route('/store', methods=['POST'])
def create_store():
    request_data = request.get_json()
    new_store = {
        'name': request_data['name'],
        'items': []
    }
    stores.append(new_store)
    return jsonify(new_store)

def find_target_store(target_store_name):
    def find(store):
        return store['name'] == target_store_name
    return find

@app.route('/store/<string:name>')
def get_store(name):
    target_store = list(filter(find_target_store(name), stores))
    return jsonify({'store': target_store}) if target_store else jsonify({'message': 'No store found with that name.'})

@app.route('/stores')
def get_stores():
    return jsonify({'stores': stores})

@app.route('/store/<string:name>/item')
def create_item_in_store(name):
    request_data = request.get_json()
    for store in stores:
        if store['name'] == name:
            new_item = {
                'name': request_data['name'],
                'price': request_data['price']
            }
            store['items'].append(new_item)
            jsonify({'new_item': new_item})
    return jsonify({'message': 'store not found'})

@app.route('/store/<string:name>/item')
def get_items_in_store(name):
    for store in stores:
        if name == store['name']:
            return jsonify({'store': store['items']})
    return jsonify({ message: 'No store found with that name.' })

app.run(port=5000)


import numpy as np
from keras.models import model_from_json

def num_captured(board):
	return 12 - np.sum(board < 0)

def num_branches(board, x, y):
	count = 0
	if (board[x, y] >= 1 and x < 6):
		if (y < 6):
			if (board[x+1, y+1] < 0 and board[x+2, y+2] == 0):
				board[x+2, y+2] = board[x, y]
				board[x, y] = 0
				temp = board[x+1, y+1]
				board[x+1, y+1] = 0
				count += num_branches(board, x+2, y+2) + 1
				board[x+1, y+1] = temp
				board[x, y] = board[x+2, y+2]
				board[x+2, y+2] = 0
		if (y > 1):
			if (board[x+1, y-1] < 0 and board[x+2, y-2] == 0):
				board[x+2, y-2] = board[x, y]
				board[x, y] = 0
				temp = board[x+1, y-1]
				board[x+1, y-1] = 0
				count += num_branches(board, x+2, y-2) + 1
				board[x+1, y-1] = temp
				board[x, y] = board[x+2, y-2]
				board[x+2, y-2] = 0
	if (board[x, y] == 3 and x > 0):
		if (y < 6):
			if (board[x-1, y+1] < 0 and board[x-2, y+2] == 0):
				board[x-2, y+2] = board[x, y]
				board[x, y] = 0
				temp = board[x-1, y+1]
				board[x-1, y+1] = 0
				count += num_branches(board, x-2, y+2) + 1
				board[x-1, y+1] = temp
				board[x, y] = board[x-2, y+2]
				board[x-2, y+2] = 0
		if (y > 1):
			if (board[x-1, y-1] < 0 and board[x-2, y-2] == 0):
				board[x-2, y-2] = board[x, y]
				board[x, y] = 0
				temp = board[x-1, y-1]
				board[x-1, y-1] = 0
				count += num_branches(board, x-2, y-2) + 1
				board[x-1, y-1] = temp
				board[x, y] = board[x-2, y-2]
				board[x-2, y-2] = 0
	return count

def possible_moves(board):
	count = 0
	for i in range(0, 8):
		for j in range(0, 8):
			if (board[i, j] > 0):
				count += num_branches(board, i, j)
	if (count > 0):
		return count
	for i in range(0, 8):
		for j in range(0, 8):
			if (board[i, j] >= 1 and i < 7):
				if (j < 7):
					count += (board[i+1, j+1] == 0)
				if (j > 0):
					count += (board[i+1, j-1] == 0)
			if (board[i, j] == 3 and i > 0):
				if (j < 7):
					count += (board[i-1, j+1] == 0)
				elif (j > 0):
					count += (board[i-1, j-1] == 0)
	return count

def game_winner(board):
	if (np.sum(board < 0) == 0):
		return 1
	elif (np.sum(board > 0) == 0):
		return -1
	if (possible_moves(board) == 0):
		return -1
	elif (possible_moves(reverse(board)) == 0):
		return 1
	else:
		return 0

def at_enemy(board):
	count = 0
	for i in range(5, 8):
		count += np.sum(board[i] == 1) + np.sum(board[i] == 3)
	return count

def at_middle(board):
	count = 0
	for i in range(3, 5):
		count += np.sum(board[i] == 1) + np.sum(board[i] == 3)
	return count

def num_men(board):
	return np.sum(board == 1)

def num_kings(board):
	return np.sum(board == 3)

def capturables(board): # possible number of unsupported enemies
	count = 0
	for i in range(1, 7):
		for j in range(1, 7):
			if (board[i, j] < 0):
				count += (board[i+1, j+1] >= 0 and board[i+1, j-1] >= 0 and  board[i-1, j+1] >= 0 and board[i-1, j-1] >= 0)
	return count

def semicapturables(board): # number of own units with at least one support
	return (12 - uncapturables(board) - capturables(reverse(board)))

def uncapturables(board): # number of own units that can't be captured
	count = 0
	for i in range(1, 7):
		for j in range(1, 7):
			if (board[i, j] > 0):
				count += ((board[i+1, j+1] > 0 < board[i+1, j-1]) or (board[i-1, j+1] > 0 < board[i-1, j-1]) or (board[i+1, j+1] > 0 < board[i-1, j+1]) or (board[i+1, j-1] > 0 < board[i-1, j-1]))
	count += np.sum(board[0] == 1) + np.sum(board[0] == 3) + np.sum(board[1:7, 0] == 1) + np.sum(board[1:7, 0] == 3) + np.sum(board[7] == 1) + np.sum(board[7] == 3) + np.sum(board[1:7, 7] == 1) + np.sum(board[1:7, 7] == 3)
	return count

def reverse(board):
	b = -board
	b = np.fliplr(b)
	b = np.flipud(b)
	return b

def get_metrics(board): # returns [label, 10 labeling metrics]
	b = expand(board)

	capped = num_captured(b)
	potential = possible_moves(b) - possible_moves(reverse(b))
	men = num_men(b) - num_men(-b)
	kings = num_kings(b) - num_kings(-b)
	caps = capturables(b) - capturables(reverse(b))
	semicaps = semicapturables(b)
	uncaps = uncapturables(b) - uncapturables(reverse(b))
	mid = at_middle(b) - at_middle(-b)
	far = at_enemy(b) - at_enemy(reverse(b))
	won = game_winner(b)

	score = capped + potential + men + kings + caps + semicaps + uncaps + mid + far + won
	if (score < 0):
		return np.array([-1, capped, potential, men, kings, caps, semicaps, uncaps, mid, far, won])
	else:
		return np.array([1, capped, potential, men, kings, caps, semicaps, uncaps, mid, far, won])

def np_board():
	return np.array(get_board())

def get_board():
	return [1, 1, 1, 1,  1, 1, 1, 1,  1, 1, 1, 1,  0, 0, 0, 0,  0, 0, 0, 0,  -1, -1, -1, -1,  -1, -1, -1, -1,  -1, -1, -1, -1]

def expand(board):
	b = np.zeros((8, 8), dtype='b')
	for i in range(0, 8):
		if (i%2 == 0):
			b[i] = np.array([0, board[i*4], 0, board[i*4 + 1], 0, board[i*4 + 2], 0, board[i*4 + 3]])
		else:
			b[i] = np.array([board[i*4], 0, board[i*4 + 1], 0, board[i*4 + 2], 0, board[i*4 + 3], 0])
	return b

def compress(board):
	b = np.zeros((1,32), dtype='b')
	for i in range(0, 8):
		if (i%2 == 0):
			b[0, i*4 : i*4+4] = np.array([board[i, 1], board[i, 3], board[i, 5], board[i, 7]])
		else:
			b[0, i*4 : i*4+4] = np.array([board[i, 0], board[i, 2], board[i, 4], board[i, 6]])
	return b

def generate_branches(board, x, y):
	bb = compress(board)
	if (board[x, y] >= 1 and x < 6):
		temp_1 = board[x, y]
		if (y < 6):
			if (board[x+1, y+1] < 0 and board[x+2, y+2] == 0):
				board[x+2, y+2] = board[x, y]
				if (x+2 == 7):
					board[x+2, y+2] = 3
				temp = board[x+1, y+1]
				board[x+1, y+1] = 0
				if (board[x, y] != board[x+2, y+2]):
					board[x, y] = 0
					bb = np.vstack((bb, compress(board)))
				else:
					board[x, y] = 0
					bb = np.vstack((bb, generate_branches(board, x+2, y+2)))
				board[x+1, y+1] = temp
				board[x, y] = temp_1
				board[x+2, y+2] = 0
		if (y > 1):
			if (board[x+1, y-1] < 0 and board[x+2, y-2] == 0):
				board[x+2, y-2] = board[x, y]
				if (x+2 == 7):
					board[x+2, y-2] = 3
				temp = board[x+1, y-1]
				board[x+1, y-1] = 0
				if (board[x, y] != board[x+2, y-2]):
					board[x, y] = 0
					bb = np.vstack((bb, compress(board)))
				else:
					board[x, y] = 0
				bb = np.vstack((bb, generate_branches(board, x+2, y-2)))
				board[x+1, y-1] = temp
				board[x, y] = temp_1
				board[x+2, y-2] = 0
	if (board[x, y] == 3 and x > 0):
		if (y < 6):
			if (board[x-1, y+1] < 0 and board[x-2, y+2] == 0):
				board[x-2, y+2] = board[x, y]
				board[x, y] = 0
				temp = board[x-1, y+1]
				board[x-1, y+1] = 0
				bb = np.vstack((bb, generate_branches(board, x-2, y+2)))
				board[x-1, y+1] = temp
				board[x, y] = board[x-2, y+2]
				board[x-2, y+2] = 0
		if (y > 1):
			if (board[x-1, y-1] < 0 and board[x-2, y-2] == 0):
				board[x-2, y-2] = board[x, y]
				board[x, y] = 0
				temp = board[x-1, y-1]
				board[x-1, y-1] = 0
				bb = np.vstack((bb, generate_branches(board, x-2, y-2)))
				board[x-1, y-1] = temp
				board[x, y] = board[x-2, y-2]
				board[x-2, y-2] = 0
	return bb

def generate_next(board):
	bb = np.array([get_board()])
	for i in range(0, 8):
		for j in range(0, 8):
			if (board[i, j] > 0):
				bb = np.vstack((bb, generate_branches(board, i, j)[1:]))
	if (len(bb) > 1):
		return bb[1:]
	for i in range(0, 8):
		for j in range(0, 8):
			if (board[i, j] >= 1 and i < 7):
				temp = board[i, j]
				if (j < 7):
					if (board[i+1, j+1] == 0):
						board[i+1, j+1] = board[i, j]
						if (i+1 == 7):
							board[i+1, j+1] = 3
						board[i, j] = 0
						bb = np.vstack((bb, compress(board)))
						board[i, j] = temp
						board[i+1, j+1] = 0
				if (j > 0):
					if (board[i+1, j-1] == 0):
						board[i+1, j-1] = board[i, j]
						if (i+1 == 7):
							board[i+1, j-1] = 3
						board[i, j] = 0
						bb = np.vstack((bb, compress(board)))
						board[i, j] = temp
						board[i+1, j-1] = 0
			if (board[i, j] == 3 and i > 0):
				if (j < 7):
					if (board[i-1, j+1] == 0):
						board[i-1, j+1] = board[i, j]
						board[i, j] = 0
						bb = np.vstack((bb, compress(board)))
						board[i, j] = board[i-1, j+1]
						board[i-1, j+1] = 0
				elif (j > 0):
					if (board[i-1, j-1] == 0):
						board[i-1, j-1] = board[i, j]
						board[i, j] = 0
						bb = np.vstack((bb, compress(board)))
						board[i, j] = board[i-1, j-1]
						board[i-1, j-1] = 0
	return bb[1:]

json_file = open('rl.json', 'r') # disc = rl
disc_json = json_file.read()
json_file.close()

meta_model = model_from_json(disc_json)
meta_model.load_weights('rl.h5')
meta_model.compile(optimizer='nadam', loss='mean_squared_error')

base_model = model_from_json(disc_json)
base_model.load_weights('rl.h5')
base_model.compile(optimizer='nadam', loss='mean_squared_error')

data = np.zeros((1, 32))
labels = np.zeros(1)
win = lose = draw = 0
for gen in range(0, 150):
	for game in range(0, 200):
		temp_data = np.zeros((1, 32))
		board = expand(np_board())
		player = np.sign(np.random.random() - 0.5)
		turn = 0
		while (True):
			moved = False
			boards = np.zeros((0, 32))
			if (player == 1):
				boards = generate_next(board)
			else:
				boards = generate_next(reverse(board))

			score = meta_model.predict_on_batch(boards) if (player == 1)  else base_model.predict_on_batch(boards)

			max = [0, score[0, 0]]
			for i, x in enumerate(score[:, 0]):
				if (x >= max[1] and np.random.random() > 0.1) or not moved:
					moved = True
					max = [i, x]

			if (player == 1):
				board = expand(boards[max[0]])
				temp_data = np.vstack((temp_data, compress(board)))
			else:
				board = reverse(expand(boards[max[0]]))

			if (game == 199 and gen > 145):
				print('\nTurn player: %d - Confidence = %f' %(player, max[1]))
				print(board)
			player = -player

			# punish losers more for short games, reward winners more for longer games
			winner = game_winner(board)
			if (winner == 1):
				win = win + 1
				temp_labels = meta_model.predict_on_batch(temp_data[1:]) + (np.reshape(np.linspace(0.0001, 0.001, temp_data.shape[0] - 1), (temp_data.shape[0]-1, 1)) * (turn))
				data = np.vstack((data, temp_data[1:]))
				labels = np.vstack((labels, temp_labels))
				break
			elif (turn >= 200 or winner == -1):
				if (winner == - 1):
					lose = lose + 1
				else:
					draw = draw + 1
				temp_labels = meta_model.predict_on_batch(temp_data[1:]) - (np.reshape(np.linspace(0.0001, 0.001, temp_data.shape[0] - 1), (temp_data.shape[0]-1, 1)) * (201 - turn))
				data = np.vstack((data, temp_data[1:]))
				labels = np.vstack((labels, temp_labels))
				break
			turn = turn + 1
		print(np.array([gen*200 + game, win, lose, draw]))
		if ((game+1) % 100 == 0):
			meta_model.fit(data[1:], labels[1:], epochs=32, batch_size=256, verbose=0)
			if ((game+1) % 10 == 0 and np.random.random() > 0.5):
				data = np.zeros((1, 32))
				labels = np.zeros(1)

	meta_model.save_weights('rl.h5')

	base_model.load_weights('rl.h5')
	base_model.compile(optimizer='nadam', loss='mean_squared_error')


# =============================================================================
# Author: Xianyuan Liu, xianyuan.liu@outlook.com
# =============================================================================

"""
Define the feature extractor for video including I3D, R3D_18, MC3_18 and R2PLUS1D_18 w/o SELayers.
"""

import logging

from kale.embed.video_i3d import i3d_joint
from kale.embed.video_res3d import mc3, r2plus1d, r3d
from kale.embed.video_se_i3d import se_i3d_joint
from kale.embed.video_se_res3d import se_mc3, se_r2plus1d, se_r3d
from kale.loaddata.video_access import get_image_modality

def get_video_feat_extractor(model_name, image_modality, attention, num_classes):
    """
    Get the feature extractor w/o the pre-trained model and SELayers. The pre-trained models are saved in the path
    ``$XDG_CACHE_HOME/torch/hub/checkpoints/``. For Linux, default path is ``~/.cache/torch/hub/checkpoints/``.
    For Windows, default path is ``C:/Users/$USER_NAME/.cache/torch/hub/checkpoints/``.
    Provide four pre-trained models: "rgb_imagenet", "flow_imagenet", "rgb_charades", "flow_charades".

    Args:
        model_name (string): The name of the feature extractor. (Choices=["I3D", "R3D_18", "R2PLUS1D_18", "MC3_18"])
        image_modality (string): Image type. (Choices=["rgb", "flow", "joint"])
        attention (string): The attention type. (Choices=["SELayerC", "SELayerT", "SELayerCoC", "SELayerMC",
        "SELayerCT", "SELayerTC", "SELayerMAC"])
        num_classes (int): The class number of specific dataset. (Default: No use)

    Returns:
        feature_network (dictionary): The network to extract features.
        class_feature_dim (int): The dimension of the feature network output for ClassNet.
                            It is a convention when the input dimension and the network is fixed.
        domain_feature_dim (int): The dimension of the feature network output for DomainNet.
    """
    rgb, flow = get_image_modality(image_modality)

    attention_list = ["SELayerC", "SELayerT", "SELayerCoC", "SELayerMC", "SELayerCT", "SELayerTC", "SELayerMAC"]
    model_list = ["I3D", "R3D_18", "MC3_18", "R2PLUS1D_18"]

    if attention in attention_list:
        att = True
    elif attention == "None":
        att = False
    else:
        raise ValueError("Wrong MODEL.ATTENTION. Current: {}".format(attention))

    if model_name not in model_list:
        raise ValueError("Wrong MODEL.METHOD. Current:{}".format(model_name))

    # Get I3D w/o SELayers for RGB, Flow or joint input
    if model_name == "I3D":
        rgb_pretrained_model = flow_pretrained_model = None
        if rgb:
            rgb_pretrained_model = "rgb_imagenet"  # Options=["rgb_imagenet", "rgb_charades"]
        if flow:
            flow_pretrained_model = "flow_imagenet"  # Options=["flow_imagenet", "flow_charades"]

        if rgb and flow:
            class_feature_dim = 2048
            domain_feature_dim = class_feature_dim / 2
        else:
            class_feature_dim = 1024
            domain_feature_dim = class_feature_dim

        if not att:
            logging.info("{} without SELayer.".format(model_name))
            feature_network = i3d_joint(
                rgb_pt=rgb_pretrained_model, flow_pt=flow_pretrained_model, num_classes=num_classes, pretrained=True
            )
        else:
            logging.info("{} with {}.".format(model_name, attention))
            feature_network = se_i3d_joint(
                rgb_pt=rgb_pretrained_model,
                flow_pt=flow_pretrained_model,
                attention=attention,
                num_classes=num_classes,
                pretrained=True,
            )

    # Get R3D_18/R2PLUS1D_18/MC3_18 w/o SELayers for RGB, Flow or joint input
    elif model_name in ["R3D_18", "R2PLUS1D_18", "MC3_18"]:
        if rgb and flow:
            class_feature_dim = 1024
            domain_feature_dim = class_feature_dim / 2
        else:
            class_feature_dim = 512
            domain_feature_dim = class_feature_dim

        if model_name == "R3D_18":
            if not att:
                logging.info("{} without SELayer.".format(model_name))
                feature_network = r3d(rgb=rgb, flow=flow, pretrained=True)
            else:
                logging.info("{} with {}.".format(model_name, attention))
                feature_network = se_r3d(rgb=rgb, flow=flow, pretrained=True, attention=attention)

        elif model_name == "R2PLUS1D_18":
            if not att:
                logging.info("{} without SELayer.".format(model_name))
                feature_network = r2plus1d(rgb=rgb, flow=flow, pretrained=True)
            else:
                logging.info("{} with {}.".format(model_name, attention))
                feature_network = se_r2plus1d(rgb=rgb, flow=flow, pretrained=True, attention=attention)

        elif model_name == "MC3_18":
            if not att:
                logging.info("{} without SELayer.".format(model_name))
                feature_network = mc3(rgb=rgb, flow=flow, pretrained=True)
            else:
                logging.info("{} with {}.".format(model_name, attention))
                feature_network = se_mc3(rgb=rgb, flow=flow, pretrained=True, attention=attention)

    return feature_network, int(class_feature_dim), int(domain_feature_dim)


# coding:utf-8
'''
**************************************************
@File   ：python_dp -> 打家劫舍
@IDE    ：PyCharm
@Author ：Small_wind
@Date   ：2020/9/8 15:41
**************************************************
'''
'''
你是一个专业的小偷，计划偷窃沿街的房屋。每间房内都藏有一定的现金，影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统，
如果两间相邻的房屋在同一晚上被小偷闯入，系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组，计算你 不触动警报装置的情况下 ，一夜之内能够偷窃到的最高金额。
来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/house-robber
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
'''
'''
考虑3种情况，
情况1，如果房屋只有1个，则直接返回这个房屋
情况2，如果房屋有两个，则返回最大的那个
情况3，如果房屋有2个以上，则dp[i] = max{dp[i-2]+a[i],dp[i-1]}，边界条件为，dp[0]=a[0],dp[1] = max(a[0],a[1])
'''
from typing import List
class Solution:
    def rob(self, nums: List[int]) -> int:
        if len(nums)==0:
            return 0
        if len(nums)==1:
            return nums[0]
        if len(nums) == 2:
            return max(nums[1],nums[0])

        dp = [];dp.append(nums[0]);dp.append(max(nums[1],nums[0]))
        for i in range(2,len(nums)):
            dp.append(max(dp[i-2]+nums[i],dp[i-1]))

        return dp[len(nums)-1]
'''
dp = [0]*len(nums)
if not nums <==> len(nums)==0
'''
s = Solution
list = [2,7,9,3,1]
print(s.rob(self=None,nums=list))

动态规划/（动态规划）打家劫舍.py

（动态规划）打家劫舍.py


# -*- coding:utf-8 -*-
import time
class Solution:
    def Fibonacci(self, n):
        # write code here
        # F(0) = 0,   F(1) = 1
        # F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

        indexs = []  # 保存下标的数组
        values = []  # 保存下标对应的值的数组
        if (n==0):
            return 0
        elif (n==1):
            return 1
        elif (n>1):
            if (n-1) not in indexs:
                indexs.append(n-1)
                values.append(self.Fibonacci(n-1))
            if (n-2) not in indexs:
                indexs.append(n-2)
                values.append(self.Fibonacci(n-2))
            if (n-1) in indexs and (n-2) in indexs:
                return values[indexs.index(n-1)]+values[indexs.index(n-2)]
        return None

    def Fibonacci1(self, n):
        # write code here
        # F(0) = 0,   F(1) = 1
        # F(N) = F(N - 1) + F(N - 2), 其中 N > 1.

        # indexs = []  # 保存下标的数组
        # values = []  # 保存下标对应的值的数组
        if (n==0):
            return 0
        elif (n==1):
            return 1
        elif (n>1):
            # if (n-1) not in indexs:
            #     indexs.append(n-1)
            #     values.append(self.Fibonacci(n-1))
            # if (n-2) not in indexs:
            #     indexs.append(n-2)
            #     values.append(self.Fibonacci(n-2))
            # if (n-1) in indexs and (n-2) in indexs:
            #     return values[indexs.index(n-1)]+values[indexs.index(n-2)]
            return self.Fibonacci1(n-1)+self.Fibonacci1(n-2)
        return None

    def xunhuan(self,n):

        a = 1  # 较大
        b = 0  # 较小
        for i in range(0,n-1):
            sum = a + b
            b = a
            a = sum

        return sum

if __name__ == "__main__":

    s = Solution()
    start_time = time.time()
    print(s.Fibonacci(30))   # 使用辅助数组
    end_time = time.time()
    print(end_time-start_time)

    print("=============================================")

    start_time1 = time.time()
    print(s.Fibonacci1(30))  # 直接递归
    end_time1 = time.time()
    print(end_time1-start_time1)

    print("=============================================")

    start_time2 = time.time()
    print(s.xunhuan(30))   #循环方法
    end_time2 = time.time()
    print(end_time2-start_time2)


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.decomposition import PCA

X = pd.read_csv('titanic.csv')

set_to_use = X
set_to_use = set_to_use.drop('Name', axis=1)
set_to_use = set_to_use.drop('Ticket', axis=1)
set_to_use = set_to_use.drop('Fare', axis=1)

set_to_use.fillna(0, inplace=True)
encoder = LabelEncoder()
encoded_sex = encoder.fit_transform(set_to_use.iloc[:, 3])

set_to_use['Sex'] = encoded_sex
features = set_to_use.iloc[:, 1:-1].values

reduction_pca = PCA(n_components=2)
reduced_features = reduction_pca.fit_transform(features)

cluster_distorsion = []
for i in range(1, 16):
    test_sklearn = KMeans(n_clusters=i)
    test_sklearn.fit(reduced_features)
    cluster_distorsion.append(test_sklearn.inertia_)
plt.plot(cluster_distorsion, marker='o', label='Distorsion for some number of clusters')
plt.legend()
plt.show()

kmeans = KMeans(n_clusters=3)
y_kmeans = kmeans.fit_predict(reduced_features)

plt.scatter(reduced_features[y_kmeans == 0, 0], reduced_features[y_kmeans == 0,1],s=100,c='red',label='Brand 1')
plt.scatter(reduced_features[y_kmeans == 1, 0], reduced_features[y_kmeans == 1,1],s=100,c='blue',label='Brand 2')
plt.scatter(reduced_features[y_kmeans == 2, 0], reduced_features[y_kmeans == 2,1],s=100,c='green',label='Brand 3')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c='yellow',label='Centroids')
plt.legend()
plt.show()


import numpy as np
from scipy import constants

#*Each Jicamarca raw data file is structured as blocks of data preceded by a header.
#*Each file starts off with a longer "first header", followed by a block of data,
# followed by a basic header, data, basic header, etc.:
# ----First header = Basic header + Long header
# ----Data block
# ----Basic header
# ----Data block
# ----Basic header
# ----Data block
# ----...
#*Each block of data consists of a number of "profiles" (data for a single pulse),
# each of which contains data from each of the sample "channels". The samples are
# arranged hierarchically in real/imaginary, then by channel, then by delay time (range):
# Data block----Profile 0----Delay 0----Channel 0----Real
#                                                ----Imag
#                                   ----Channel 1----Real
#                                                ----Imag
#                                         ...
#                                   ----Channel i----Real
#                                                ----Imag
#                        ----Delay 1----Channel 0----Real
#                                         ...
#                        ----Delay k
#                                         ...
#           ----Profile 1----Delay 0----Channel 0----Real
#                                         ...
#           ----Profile m
#*The basic headers give the number of the following block and the time at which
# the block begins.
#*The long header gives system parameters and describes the number of profiles, delays,
# and channels per block of data.
#*Detailed structures for the headers can be deduced from the functions for reading them
# given below.

# define flags that appear in headers with their interpretation/meaning
nDataType = dict(RAWDATA = np.uint32(0x00000000),
                 SPECTRA = np.uint32(0x00000001),
                 DIFF2_PROCESS_WIN = np.uint32(0x00001000),
                 DIFF3_PROCESS_WIN = np.uint32(0x00010000),
                 DIFF4_PROCESS_WIN = np.uint32(0x00011000),
                 SAVE_INCOH_INT_TIME_AVER = np.uint32(0x00100000))

RCfunction = dict(NONE = 0,
                  FLIP = 1,
                  CODE = 2,
                  SAMPLING = 3,
                  LIN6DIV256 = 4,
                  SYNCHRO = 5)

nCodeType = dict(NONE = 0,
                 USERDEFINE = 1,
                 BARKER2 = 2,
                 BARKER3 = 3,
                 BARKER4 = 4,
                 BARKER5 = 5,
                 BARKER7 = 6,
                 BARKER11 = 7,
                 BARKER13 = 8,
                 AC128 = 9,
                 COMPLEMENTARYCODE2 = 10,
                 COMPLEMENTARYCODE4 = 11,
                 COMPLEMENTARYCODE8 = 12,
                 COMPLEMENTARYCODE16 = 13,
                 COMPLEMENTARYCODE32 = 14,
                 COMPLEMENTARYCODE64 = 15,
                 COMPLEMENTARYCODE128 = 16,
                 CODE_BINARY28 = 17)

PROCFLAG = dict(COHERENT_INTEGRATION = np.uint32(0x00000001),
                DECODE_DATA = np.uint32(0x00000002),
                SPECTRA_CALC = np.uint32(0x00000004),
                INCOHERENT_INTEGRATION = np.uint32(0x00000008),
                POST_COHERENT_INTEGRATION = np.uint32(0x00000010),
                SHIFT_FFT_DATA = np.uint32(0x00000020),
                DATATYPE_CHAR = np.uint32(0x00000040),
                DATATYPE_SHORT = np.uint32(0x00000080),
                DATATYPE_LONG = np.uint32(0x00000100),
                DATATYPE_INT64 = np.uint32(0x00000200),
                DATATYPE_FLOAT = np.uint32(0x00000400),
                DATATYPE_DOUBLE = np.uint32(0x00000800),
                DATAARRANGE_CONTIGUOUS_CH = np.uint32(0x00001000),
                DATAARRANGE_CONTIGUOUS_H = np.uint32(0x00002000),
                DATAARRANGE_CONTIGUOUS_P = np.uint32(0x00004000),
                SAVE_CHANNELS_DC = np.uint32(0x00008000),
                DEFLIP_DATA = np.uint32(0x00010000),
                DEFINE_PROCESS_CODE = np.uint32(0x00020000),
                ACQ_SYS_NATALIA = np.uint32(0x00040000),
                ACQ_SYS_ECHOTEK = np.uint32(0x00080000),
                ACQ_SYS_ADRXD = np.uint32(0x000C0000),
                ACQ_SYS_JULIA = np.uint32(0x00100000),
                ACQ_SYS_XXXXXX = np.uint32(0x00140000),
                EXP_NAME_ESP = np.uint32(0x00200000),
                CHANNEL_NAMES_ESP = np.uint32(0x00400000),
                OPERATION_MASK = np.uint32(0x0000003F),
                DATATYPE_MASK = np.uint32(0x00000FC0),
                DATAARRANGE_MASK = np.uint32(0x00007000),
                ACQ_SYS_MASK = np.uint32(0x001C0000))

DINFLAG = dict(RC_L4_TXA_REF = np.uint32(0x00000001),
               RC_L4_TXB_REF = np.uint32(0x00000002),
               RC_L4_TXX_REF = np.uint32(0x00000003),
               RC_L5_TXA_REF = np.uint32(0x00000004),
               RC_L5_TXB_REF = np.uint32(0x00000008),
               RC_L5_TXX_REF = np.uint32(0x0000000C),
               RC_L6_TXA_REF = np.uint32(0x00000010),
               RC_L6_TXB_REF = np.uint32(0x00000020),
               RC_L6_TXX_REF = np.uint32(0x00000030),
               RC_L7_TXA_REF = np.uint32(0x00000040),
               RC_L7_TXB_REF = np.uint32(0x00000080),
               RC_L7_TXX_REF = np.uint32(0x000000C0),
               RC_RESERVED_REF = np.uint32(0x00000000),
               RC_MIDDLE_OF_SUB_BAUD_REF = np.uint32(0x00000100),
               RC_MIDDLE_OF_TX_REF = np.uint32(0x00000200),
               RC_BEGIN_OF_TX_REF = np.uint32(0x00000300),
               RC_SYNC_DELAY_ESP = np.uint32(0x00000400),
               RC_PULSE_AFTER_WINDOW = np.uint32(0x00000800),
               RC_CTRL_SWITCH1 = np.uint32(0x00001000),
               RC_CTRL_SWITCH2 = np.uint32(0x00002000),
               RC_CLK_DIV_ESP = np.uint32(0x00004000),
               RC_RANGE_TR_DYNAMIC = np.uint32(0x00008000),
               RC_RANGE_TXA_DYNAMIC = np.uint32(0x00010000),
               RC_RANGE_TXB_DYNAMIC = np.uint32(0x00020000),
               RC_SYNC_DIV_ESP = np.uint32(0x00040000),
               RC_EXT_SYNC_DELAY_ESP = np.uint32(0x00080000))

def read_basic_header(f):
    """Read/parse a basic header from the given file object at its current position."""
    basic_header_t = np.dtype([('nHeaderLength','<u4'),
                               ('nHeaderVER','<u2'),
                               ('nDataCurrentBlock','<u4'),
                               ('time_sec','<u4'),
                               ('time_msec','<u2'),
                               ('timezone','<i2'),
                               ('dstflag','<i2'),
                               ('nErrorCount','<u4')])
    # fromfile will silently not return the requested number of items if EOF is reached
    basic_header = np.fromfile(f, basic_header_t, 1)
    try:
        basic_header = basic_header.item() # make sure we got entry, convert to python types
    except ValueError:
        raise EOFError('End of file reached. Could not read header.')
    basic_header_dict = dict(zip(basic_header_t.names, basic_header))
    return(basic_header_dict)

def read_system_header(f):
    """Read/parse a system header from the given file object at its current position."""
    system_header_t = np.dtype([('nHeader_Sys_Length','<u4'),
                                ('nSamples','<u4'),
                                ('nProfiles','<u4'),
                                ('nChannels','<u4'),
                                ('nADCResolution','<u4'),
                                ('nPCIDIOBusWidth','<u4'),])
    # fromfile will silently not return the requested number of items if EOF is reached
    system_header = np.fromfile(f, system_header_t, 1)
    try:
        system_header = system_header.item() # make sure we got entry, convert to python types
    except ValueError:
        raise EOFError('End of file reached. Could not read header.')
    system_header_dict = dict(zip(system_header_t.names, system_header))
    return(system_header_dict)

def read_rc_header(f):
    """Read/parse an rc header from the given file object at its current position."""
    # read the static part
    start_pos = f.tell()
    rc_static_header_t = np.dtype([('nHeader_RC_Length','<u4'),
                                   ('nEspType','<u4'),
                                   ('nNTX','<u4'),
                                   ('fIPP','<f4'),
                                   ('fTxA','<f4'),
                                   ('fTxB','<f4'),
                                   ('nNum_Windows','<u4'),
                                   ('nNum_Taus','<u4'),
                                   ('nCodeType','<u4'),
                                   ('nL6_Function','<u4'),
                                   ('nL5_Function','<u4'),
                                   ('fCLOCK','<f4'),
                                   ('nPrePulseBefore','<u4'),
                                   ('nPrePulseAfter','<u4'),
                                   ('sRango_TR','<a16'),
                                   ('nDinFlags','<u4'),
                                   ('sRango_TxA','<a20'),
                                   ('sRango_TxB','<a20')])
    # fromfile will silently not return the requested number of items if EOF is reached
    rc_static_header = np.fromfile(f, rc_static_header_t, 1)
    try:
        rc_static_header = rc_static_header.item() # make sure we got entry, convert to python types
    except ValueError:
        raise EOFError('End of file reached. Could not read header.')
    rc_header = dict(zip(rc_static_header_t.names, rc_static_header))

    # evaluate the controller flags
    rc_header['nDinFlags'] = dict(((k, rc_header['nDinFlags'] & v == v)
                                   for k,v in DINFLAG.iteritems()))

    # read the dynamic part
    sampwin_t = np.dtype([('sRC_fH0','<f4'),
                          ('sRC_fDH','<f4'),
                          ('sRC_nNSA','<u4')])
    sampwin = np.fromfile(f, sampwin_t, rc_header['nNum_Windows'])
    if len(sampwin) != rc_header['nNum_Windows']:
        raise EOFError('End of file reached. Could not read header.')
    rc_header['sRC_fH0'] = sampwin['sRC_fH0'].astype(np.float_)
    rc_header['sRC_fDH'] = sampwin['sRC_fDH'].astype(np.float_)
    rc_header['sRC_nNSA'] = sampwin['sRC_nNSA'].astype(np.int_)

    if rc_header['nNum_Taus'] != 0:
        rc_header['sfTau'] = np.fromfile(f, '<f4', rc_header['nNum_Taus']).astype(np.float_)
        if len(rc_header['sfTau']) != rc_header['nNum_Taus']:
            raise EOFError('End of file reached. Could not read header.')

    if rc_header['nCodeType'] != nCodeType['NONE']:
        try:
            num_codes = np.fromfile(f, '<u4', 1).item()
            num_bauds = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        size_bauds = num_bauds//32 + 1
        codes = np.fromfile(f, '<u4', num_codes*size_bauds).astype(np.int_)
        if len(codes) != num_codes*size_bauds:
            raise EOFError('End of file reached. Could not read header.')
        codes = codes.reshape(size_bauds, num_codes).transpose()
        rc_header['nNum_Codes'] = num_codes
        rc_header['nNum_Bauds'] = num_bauds
        rc_header['snCode'] = codes

    if rc_header['nL5_Function'] == RCfunction['FLIP']:
        try:
            rc_header['nFLIP1'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')

    if rc_header['nL6_Function'] == RCfunction['FLIP']:
        try:
            rc_header['nFLIP2'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')

    if rc_header['nL5_Function'] == RCfunction['SAMPLING']:
        try:
            rc_header['nL5_Num_Windows'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        L5sampwin_t = np.dtype([('sL5_fH0','<f4'),
                                ('sL5_fDH','<f4'),
                                ('sL5_nNSA','<u4')])
        L5sampwin = np.fromfile(f, L5sampwin_t, rc_header['nL5_Num_Windows'])
        if len(L5sampwin) != rc_header['nL5_Num_Windows']:
            raise EOFError('End of file reached. Could not read header.')
        rc_header['sL5_fH0'] = L5sampwin['sL5_fH0'].astype(np.float_)
        rc_header['sL5_fDH'] = L5sampwin['sL5_fDH'].astype(np.float_)
        rc_header['sL5_nNSA'] = L5sampwin['sL5_nNSA'].astype(np.int_)
    elif rc_header['nL5_Function'] == RCfunction['CODE']:
        try:
            num_codes = np.fromfile(f, '<u4', 1).item()
            num_bauds = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        size_bauds = num_bauds//32 + 1
        codes = np.fromfile(f, '<u4', num_codes*size_bauds).astype(np.int_)
        if len(codes) != num_codes*size_bauds:
            raise EOFError('End of file reached. Could not read header.')
        codes = codes.reshape(num_codes, size_bauds)
        rc_header['nL5_Num_Codes'] = num_codes
        rc_header['nL5_Num_Bauds'] = num_bauds
        rc_header['sL5_nCode'] = codes

    if rc_header['nL6_Function'] == RCfunction['SAMPLING']:
        try:
            rc_header['nL6_Num_Windows'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        L6sampwin_t = np.dtype([('sL6_fH0','<f4'),
                                ('sL6_fDH','<f4'),
                                ('sL6_nNSA','<u4')])
        L6sampwin = np.fromfile(f, L6sampwin_t, rc_header['nL6_Num_Windows'])
        if len(L6sampwin) != rc_header['nL6_Num_Windows']:
            raise EOFError('End of file reached. Could not read header.')
        rc_header['sL6_fH0'] = L6sampwin['sL6_fH0'].astype(np.float_)
        rc_header['sL6_fDH'] = L6sampwin['sL6_fDH'].astype(np.float_)
        rc_header['sL6_nNSA'] = L6sampwin['sL6_nNSA'].astype(np.int_)
    elif rc_header['nL6_Function'] == RCfunction['CODE']:
        try:
            num_codes = np.fromfile(f, '<u4', 1).item()
            num_bauds = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        size_bauds = num_bauds//32 + 1
        codes = np.fromfile(f, '<u4', num_codes*size_bauds).astype(np.int_)
        if len(codes) != num_codes*size_bauds:
            raise EOFError('End of file reached. Could not read header.')
        codes = codes.reshape(num_codes, size_bauds)
        rc_header['nL6_Num_Codes'] = num_codes
        rc_header['nL6_Num_Bauds'] = num_bauds
        rc_header['sL6_nCode'] = codes

    if rc_header['nDinFlags']['RC_SYNC_DELAY_ESP']:
        try:
            rc_header['nSynchro_Delay'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
    if rc_header['nDinFlags']['RC_SYNC_DIV_ESP']:
        try:
            rc_header['nExt_Synchro_Divisor'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
    if rc_header['nDinFlags']['RC_CLK_DIV_ESP']:
        try:
            rc_header['nExt_Clk_Divisor'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
    if rc_header['nDinFlags']['RC_EXT_SYNC_DELAY_ESP']:
        try:
            rc_header['nExt_Synchro_Delay'] = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
    if rc_header['nDinFlags']['RC_RANGE_TR_DYNAMIC']:
        try:
            range_len = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        range = np.fromfile(f, '<a1', range_len + 1)
        if len(range) != (range_len + 1):
            raise EOFError('End of file reached. Could not read header.')
        rc_header['nTR_RangeLen'] = range_len
        rc_header['nTR_Range'] = range.tostring()
    if rc_header['nDinFlags']['RC_RANGE_TXA_DYNAMIC']:
        try:
            range_len = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        range = np.fromfile(f, '<a1', range_len + 1)
        if len(range) != (range_len + 1):
            raise EOFError('End of file reached. Could not read header.')
        rc_header['nTXA_RangeLen'] = range_len
        rc_header['nTXA_Range'] = range.tostring()
    if rc_header['nDinFlags']['RC_RANGE_TXB_DYNAMIC']:
        try:
            range_len = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        range = np.fromfile(f, '<a1', range_len + 1)
        if len(range) != (range_len + 1):
            raise EOFError('End of file reached. Could not read header.')
        rc_header['nTXB_RangeLen'] = range_len
        rc_header['nTXB_Range'] = range.tostring()

    # verify that we read the correct amount of data
    end_pos = f.tell()
    #assert ((end_pos - start_pos) == rc_header['nHeader_RC_Length']), 'RC Header Parsed Incorrectly'
    f.seek(start_pos + rc_header['nHeader_RC_Length'])

    return(rc_header)

def read_proc_header(f):
    """Read/parse a proc header from the given file object at its current position."""
    # read the static part
    start_pos = f.tell()
    proc_static_header_t = np.dtype([('nHeader_PP_Length','<u4'),
                                     ('nDataType','<u4'),
                                     ('nSizeOfDataBlock','<u4'),
                                     ('nProfilesperBlock','<u4'),
                                     ('nDataBlocksperFile','<u4'),
                                     ('nData_Windows','<u4'),
                                     ('nProcessFlags','<u4'),
                                     ('nCoherentIntegrations','<u4'),
                                     ('nIncoherentIntegrations','<u4'),
                                     ('nTotalSpectra','<u4')])
    # fromfile will silently not return the requested number of items if EOF is reached
    proc_static_header = np.fromfile(f, proc_static_header_t, 1)
    try:
        proc_static_header = proc_static_header.item() # make sure we got entry, convert to python types
    except ValueError:
        raise EOFError('End of file reached. Could not read header.')
    proc_header = dict(zip(proc_static_header_t.names, proc_static_header))

    # evaluate the processing flags
    proc_header['nProcessFlags'] = dict(((k, proc_header['nProcessFlags'] & v == v)
                                         for k,v in PROCFLAG.iteritems()))

    # read the dynamic part
    sampwin_t = np.dtype([('sfH0','<f4'),
                          ('sfDH','<f4'),
                          ('snNSA','<u4')])
    sampwin = np.fromfile(f, sampwin_t, proc_header['nData_Windows'])
    if len(sampwin) != proc_header['nData_Windows']:
            raise EOFError('End of file reached. Could not read header.')
    proc_header['sfH0'] = sampwin['sfH0'].astype(np.float_)
    proc_header['sfDH'] = sampwin['sfDH'].astype(np.float_)
    proc_header['snNSA'] = sampwin['snNSA'].astype(np.int_)

    if proc_header['nTotalSpectra'] != 0:
        proc_header['nSpectraCombinations'] = np.fromfile(
            f, '<u2', proc_header['nTotalSpectra']).astype(np.int_)
        if len(proc_header['nSpectraCombinations']) != proc_header['nTotalSpectra']:
            raise EOFError('End of file reached. Could not read header.')

    if proc_header['nProcessFlags']['DEFINE_PROCESS_CODE']:
        try:
            num_codes = np.fromfile(f, '<u4', 1).item()
            num_bauds = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        size_bauds = num_bauds//32 + 1
        codes = np.fromfile(f, '<u4', num_codes*size_bauds).astype(np.int_)
        if len(codes) != num_codes*size_bauds:
            raise EOFError('End of file reached. Could not read header.')
        codes = codes.reshape(num_codes, size_bauds)
        proc_header['nProcessCodes'] = num_codes
        proc_header['nProcessBauds'] = num_bauds
        proc_header['sfProcessCode'] = codes

    if proc_header['nProcessFlags']['EXP_NAME_ESP']:
        try:
            name_len = np.fromfile(f, '<u4', 1).item()
        except ValueError:
            raise EOFError('End of file reached. Could not read header.')
        name = np.fromfile(f, '<a1', name_len + 1)
        if len(name) != (name_len + 1):
            raise EOFError('End of file reached. Could not read header.')
        proc_header['nExp_NameLen'] = name_len
        proc_header['sExp_Range'] = name.tostring()

    # verify that we read the correct amount of data
    end_pos = f.tell()
    #assert ((end_pos - start_pos) == proc_header['nHeader_PP_Length']), 'PROC Header Parsed Incorrectly'
    f.seek(start_pos + proc_header['nHeader_PP_Length'])

    return(proc_header)

def read_first_header(f):
    """Read/parse a 'first header' from the given file object at its current position."""
    # get the basic header that makes up the beginning of the first header
    basic_header = read_basic_header(f)

    # get the long header that makes up the rest of the first header
    # beginning with the system header
    system_header = read_system_header(f)
    # now the radar controller header
    rc_header = read_rc_header(f)
    # finally the processing header
    proc_header = read_proc_header(f)

    # merge them all into the first header
    first_header = dict(basic_header.items() + system_header.items() +
                        rc_header.items() + proc_header.items())

    return(first_header)

def parse_dtype(first_header):
    if first_header['nProcessFlags']['DATATYPE_CHAR']:
        raw_dtype = np.dtype([('real', '<i1'), ('imag', '<i1')])
        dtype = np.dtype(np.complex64)
    elif first_header['nProcessFlags']['DATATYPE_SHORT']:
        raw_dtype = np.dtype([('real', '<i2'), ('imag', '<i2')])
        dtype = np.dtype(np.complex64)
    elif first_header['nProcessFlags']['DATATYPE_LONG']:
        raw_dtype = np.dtype([('real', '<i4'), ('imag', '<i4')])
        dtype = np.dtype(np.complex128)
    elif first_header['nProcessFlags']['DATATYPE_INT64']:
        raw_dtype = np.dtype([('real', '<i8'), ('imag', '<i8')])
        dtype = np.dtype(np.complex128)
    elif first_header['nProcessFlags']['DATATYPE_FLOAT']:
        raw_dtype = np.dtype([('real', '<f4'), ('imag', '<f4')])
        dtype = np.dtype(np.complex64)
    elif first_header['nProcessFlags']['DATATYPE_DOUBLE']:
        raw_dtype = np.dtype([('real', '<f8'), ('imag', '<f8')])
        dtype = np.dtype(np.complex128)
    else:
        raw_dtype = np.dtype([('real', '<i2'), ('imag', '<i2')])
        dtype = np.dtype(np.complex64)

    return raw_dtype, dtype

def parse_time(header):
    secs = np.datetime64(header['time_sec'], 's')
    msecs = np.timedelta64(header['time_msec'], 'ms')
    time = secs + msecs
    return time

def parse_block_shape(first_header):
    nprofiles = int(first_header['nProfilesperBlock']) # convert to smaller int if possible
    nsamples = first_header['snNSA'][0] # [0] needed b/c we want first (only) "window"
    nchannels = int(first_header['nChannels']) # convert to smaller int if possible
    return nprofiles, nsamples, nchannels

def parse_ts(first_header):
    dr_km = first_header['sfDH']
    ts_s = 2*dr_km*1e3/3e8 # Jicamarca's km units for dr assume c = 3e8 m/s
    ts = np.round(1e9*ts_s).astype('timedelta64[ns]')

    if len(ts) == 1:
        return ts[0]
    return ts

def parse_ipp(first_header):
    ipp_km = first_header['fIPP']
    ipp_s = 2*ipp_km*1e3/3e8 # Jicamarca's km units for IPP assume c = 3e8 m/s
    ipp = np.round(1e9*ipp_s).astype('timedelta64[ns]')
    return ipp

def parse_range_index(first_header):
    ngates_win = first_header['snNSA']
    r0_win = first_header['sfH0']*1e3*constants.c/3e8 # m, correct for assumed c = 3e8 m/s
    dr_win = first_header['sfDH']*1e3*constants.c/3e8 # m, correct for assumed c = 3e8 m/s

    r = []
    for ngates, r0, dr in zip(ngates_win, r0_win, dr_win):
        r.append(r0 + np.arange(ngates)*dr)

    r = np.hstack(r)
    return r

def parse_pulse_codes(first_header):
    codes_decimal = first_header['snCode']

    codes = []
    for kcode in xrange(codes_decimal.shape[0]):
        code = []
        for kpart in xrange(codes_decimal.shape[1]):
            code_decimal = codes_decimal[kcode, kpart]
            code.append(np.asarray(list(np.binary_repr(code_decimal)), dtype=np.int8))
        codes.append(np.hstack(code))

    return codes

def read_data_block(f, first_header):
    raw_dtype, dtype = parse_dtype(first_header)
    block_shape = parse_block_shape(first_header)

    block = np.fromfile(f, raw_dtype, np.product(block_shape))
    try:
        block = block.reshape(block_shape)
    except ValueError: # reshape fails, we didn't get the number of samples we expected
        raise EOFError('End of file reached. Could not read block.')

    vlt = np.empty(block_shape, dtype=dtype)
    vlt.real = block['real']
    vlt.imag = block['imag']

    return vlt


from typing import Dict
from src.algorithm.DAO.TopUsersDAOFactory import TopUsersDAOFactory
from src.algorithm.process.TopUsers import TopUsers

class TopUsersActivity():
    """
    Get rid of inactive users.
    """
    def __init__(self, config: Dict):
        self.top_users = None

        self.configure(config)

    def configure(self, config: Dict):
        if config is not None:
            input_datastore = config["input-datastore"]
            input_cluster = input_datastore["Cluster"]
            input_wordfrequency = input_datastore["RelativeWordFrequency"]
            input_topwords = input_datastore["TopWords"]

            cluster_getter = TopUsersDAOFactory.create_cluster_getter(input_cluster)
            wordfrequency_getter = TopUsersDAOFactory.create_wordfrequency_getter(input_wordfrequency)
            topwords_getter = TopUsersDAOFactory.create_topwords_getter(input_topwords)

            output_datastore = config["output-datastore"]
            output_top_users = output_datastore["TopUsers"]

            top_users_setter = TopUsersDAOFactory.create_topusers_setter(output_top_users)

            top_users = TopUsers(cluster_getter, wordfrequency_getter, topwords_getter, top_users_setter)

            self.top_users = top_users

    def find_top_users(self, cluster_num, base_user, cluster_type):
        self.top_users.find_top_users(cluster_num, base_user, cluster_type)


import xso

from .variables import SV
from .forcings import IrradianceFromLat, StationForcingFromFile
from .fluxes.basic import LinearExchange, QuadraticExchange, QuadraticDecay

from .fluxes.mixing import (Mixing_K, SlabUpwelling_KfromGroup,
                            SlabMixing_KfromGroup, SlabSinking)

from .fluxes.growth import (EMPOWER_Growth_ML, EMPOWER_Monod_ML, EMPOWER_Eppley_ML,
                            EMPOWER_Smith_Anderson3Layer_ML,
                            EMPOWER_Smith_LambertBeer_ML)

from .fluxes.grazing import (HollingTypeIII_ResourcesListInput_Consumption2Group,
                             GrossGrowthEfficiency)

NPZDSlabOcean = xso.create({
    # State variables
    'Nutrient': SV,
    'Phytoplankton': SV,
    'Zooplankton': SV,
    'Detritus': SV,

    # Mixing:
    'K': Mixing_K,
    'Upwelling': SlabUpwelling_KfromGroup,
    'Mixing': SlabMixing_KfromGroup,
    'Sinking': SlabSinking,

    # Growth
    'Growth': EMPOWER_Growth_ML,
    'Nut_lim': EMPOWER_Monod_ML,
    'Light_lim': EMPOWER_Smith_LambertBeer_ML,
    'Temp_lim': EMPOWER_Eppley_ML,

    # Grazing
    'Grazing': HollingTypeIII_ResourcesListInput_Consumption2Group,
    'GGE': GrossGrowthEfficiency,

    # Mortality
    'PhytoLinMortality': LinearExchange,
    'PhytoQuadMortality': QuadraticExchange,
    'ZooLinMortality': LinearExchange,
    'HigherOrderPred': QuadraticDecay,
    'DetRemineralisation': LinearExchange,

    # Forcings
    'Irradiance': IrradianceFromLat,
    'Forcings': StationForcingFromFile,
})

NPZDSlabOcean_3layer = NPZDSlabOcean.update_processes({'Light_lim': EMPOWER_Smith_Anderson3Layer_ML})


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

"""
Print the list of triggered telescopes ID and geometry of the given simtel
file.

Example of output:

    Telescope 001: LSTCam (hexagonal pixels)
    Telescope 002: LSTCam (hexagonal pixels)
    Telescope 003: LSTCam (hexagonal pixels)
    Telescope 004: LSTCam (hexagonal pixels)
    Telescope 005: NectarCam (hexagonal pixels)
    Telescope 006: NectarCam (hexagonal pixels)
    ...
    Telescope 017: FlashCam (hexagonal pixels)
    Telescope 018: FlashCam (hexagonal pixels)
    ...
    Telescope 029: ASTRI (rectangular pixels)
    ...
    Telescope 053: GATE (rectangular pixels)
    ...

"""

import argparse

import ctapipe
from ctapipe.io.hessio import hessio_event_source

def list_telescopes_geometry(simtel_file_path):
    """Print the list of triggered telescopes ID and geometry of the
    'simtel_file_path' file.

    Parameters
    ----------
    simtel_file_path : str
        The path of the simtel file to process.
    """

    source = hessio_event_source(simtel_file_path)

    tel_id_set = set()

    for event in source:
        for tel_id in event.dl0.tels_with_data:
            tel_id_set.add(tel_id)

    for tel_id in tel_id_set:
        x, y = event.meta.pixel_pos[tel_id]
        foclen = event.meta.optical_foclen[tel_id]
        geom = ctapipe.io.CameraGeometry.guess(x, y, foclen)
        print("Telescope {:03d}: {} ({} pixels)".format(tel_id, geom.cam_id, geom.pix_type))

def main():
    """Parse command options (sys.argv)."""

    # PARSE OPTIONS ###########################################################

    desc = "Print the list of triggered telescopes ID and geometry of the given simtel file."
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument("fileargs", nargs=1, metavar="FILE",
                        help="The simtel file to process")

    args = parser.parse_args()

    simtel_file_path = args.fileargs[0]

    # PRINT THE LIST ##########################################################

    list_telescopes_geometry(simtel_file_path)

if __name__ == '__main__':
    main()


import numpy
import time
from random import randint
from rgbmatrix import Adafruit_RGBmatrix
#from random import randint

matrix = Adafruit_RGBmatrix(32,1)

x = numpy.zeros((50))
y = numpy.zeros((50))
r = numpy.zeros((50))
g = numpy.zeros((50))
b = numpy.zeros((50))
for s in range(0,100):
    for i in range(0,50):
        x[i] = randint(0,31)
        y[i] = randint(0,31)
        r[i] = randint(1,255)
        g[i] = randint(1,255)
        b[i] = randint(1,255)
        matrix.SetPixel(int(x[i]),int(y[i]),int(r[i]),int(g[i]),int(b[i]))
        time.sleep(0.0025)
    matrix.Clear()
    #time.sleep(1)

#for j in range(0,50):
#    matrix.SetPixel(x[j],y[j],r[j],g[j],b[j])
#    time.sleep(1)


import requests
from base64 import b64encode
from datetime import date, datetime

class TaskManager:
    def __init__(self, credentials):
        self.auth_header = None
        self.obtain_token(credentials['key'], credentials['secret'])

    def obtain_token(self, key, secret):
        credentials = b64encode('{}:{}'.format(key, secret).encode()).decode()
        header = {'Authorization': 'Basic ' + credentials,
                  'Content-Type': 'application/x-www-form-urlencoded'}
        params = {'grant_type': 'client_credentials'}

        resp = requests.post('https://api.vasttrafik.se/token',
                             headers=header,
                             params=params)

        token = resp.json()['access_token']
        self.auth_header = {'Authorization': 'Bearer ' + token}

    def send_request(self, url, params=None):
        params['format'] = 'json'
        resp = requests.get(url, headers=self.auth_header, params=params)
        return resp.json()

    def get_stop_id(self, stop):
        url = 'https://api.vasttrafik.se/bin/rest.exe/v2/location.name'
        resp = self.send_request(url, {'input': stop})

        id = resp['LocationList']['StopLocation'][0]['id']
        return id

    def get_first_trip(self, form):
        origin_id = self.get_stop_id(form['origin'])
        dest_id = self.get_stop_id(form['destination'])

        url = 'https://api.vasttrafik.se/bin/rest.exe/v2/trip'
        params = {'originId': origin_id,
                  'destId': dest_id,
                  'numTrips': 1}
        resp = self.send_request(url, params)
        trip = resp['TripList']['Trip'][0]['Leg']

        response = [
            trip['type'].lower(),
            trip['sname'],
            trip['Origin']['name'],
            trip['Destination']['name'],
            trip['direction'],
            trip['Origin']['time']
        ]
        return response

    def get_first_line(self, form):
        origin_id = self.get_stop_id(form['origin'])

        url = 'https://api.vasttrafik.se/bin/rest.exe/v2/departureBoard'
        params = {'id': origin_id,
                  'date': date.today().strftime("%Y%m%d"),
                  'time': form['time (hh:mm)'],
                  'timeSpan': 360,  # next 6 hours
                  'maxDeparturesPerLine': 1  # only one line-direction combination
                  }
        resp = self.send_request(url, params)

        departure_board = resp['DepartureBoard']['Departure']
        line_departures = [trip for trip in departure_board
                           if trip['sname'] == form['line']]

        responses = {}

        for i, departure in zip(range(len(line_departures)), line_departures):
            response = [
                departure['type'].lower(),
                departure['sname'],
                departure['direction'],
                departure['stop'],
                departure['time'],
                ''
            ]
            responses[i] = response

        return responses

    def get_average_trip_time(self, form):
        origin_id = self.get_stop_id(form['origin'])
        dest_id = self.get_stop_id(form['destination'])

        url = 'https://api.vasttrafik.se/bin/rest.exe/v2/trip'
        params = {'originId': origin_id,
                  'destId': dest_id,
                  'numTrips': 20}

        resp = self.send_request(url, params)
        trips = resp['TripList']['Trip']

        time_sum = 0
        counter = 0

        for trip in trips:
            trip = trip['Leg']

            if isinstance(trip, list):
                for alt_trip in trip:
                    time_sum += self.get_trip_time(alt_trip)
                counter += 1
                continue

            time_sum += self.get_trip_time(trip)
            counter += 1

        avg_time = time_sum / counter / 60  # minutes

        response = [
            int(avg_time),
            trips[0]['Leg']['Origin']['name'],
            trips[0]['Leg']['Destination']['name'],
            '',
            '',
            ''
        ]

        return response

    def get_trip_time(self, trip):
        origin_time = trip['Origin']['time']
        origin_time = datetime.strptime(origin_time, "%H:%M")

        dest_time = trip['Destination']['time']
        dest_time = datetime.strptime(dest_time, "%H:%M")

        trip_time = dest_time - origin_time

        return trip_time.seconds

    def create_query(self, form):
        choice = {
            1: self.get_first_trip,
            2: self.get_first_line,
            3: self.get_average_trip_time
        }

        action = choice.get(form['id'])
        response = action(form)

        return response


"""
Next Integer Permutation

my implementation sucks, but the logic is the following:

You iterate on the number from the right, finding the first digit that has a bigger digit than itself to its right.

Then, you find the smallest digit to its right that is bigger than it, you swap them and sort everything to its right.
"""
class Solution:
    def solve(self, num):
        mx=0
        s=str(num)
        idx=-1
        ref=-1
        for i in range(len(s)-1,-1,-1):
            n=int(s[i])
            if n < mx:
                idx=i
                ref=n
                break
            elif n > mx: mx = n
        mn=1e9
        nidx=-1
        for i in range(idx+1, len(s)):
            n=int(s[i])
            if n > ref and n < mn:
                mn = n
                nidx = i
        s = [c for c in s]
        s[idx],s[nidx] = s[nidx], s[idx]
        s = s[:idx+1] + sorted(s[idx+1:])
        ans= int("".join(s))
        if ans == num: return int("".join(sorted(s,key=int)))
        return ans


'''
Code to send and measure a pulse response in a discharge process of a 18650 li-ion battery
@ Authors Diego Fernández Arias and Juan J. Rojas
Laboratorio Delta

Only parameter that needs to be changed in according to necessity is
Carga.fijar_corriente(batt_capacity * x) in the pulse function
'''
import controller2 #Ponerlos en las mismas carpetas
import pyvisa
import pandas as pd
from datetime import date, datetime
import threading
import RPi.GPIO as GPIO
import board
import digitalio
import adafruit_max31855

rm = pyvisa.ResourceManager()

for i in range(3):
    if rm.list_resources()[i].find("DL3A21") > 0:
        carga = rm.open_resource(rm.list_resources()[i])
        print("Carga DL3A21 encontrada")
        print(carga.query("*IDN?"))
    elif rm.list_resources()[i].find("SPD13") > 0:
        fuente = rm.open_resource(rm.list_resources()[i])
        print("Fuente SPD1305X encontrada")

#Fuente = controller2.Fuente(fuente, "SPD1305", tipoFuente = True)
Carga = controller2.Carga(carga, "DL3021")

#Ser RPi outputs
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT) #CH2 para descarga
GPIO.output(18,GPIO.LOW)
GPIO.setup(17,GPIO.OUT) #Cierra CH1 por si estuviera activado
GPIO.output(17,GPIO.LOW)
GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #Shutdown Button

#Definición archivo csv de las mediciones
outputCSV = pd.DataFrame(columns = ["Timestamp", "Time", "Tag", "Voltage", "Current", "Capacity", "Temperature"])

#Global variables definition
state = "INIT"
init_flag = 1
timer_flag = 0
counter = 0
batt_capacity = 3.5 #Ah
seconds = 0
past_time = 0
volt = 0
current = 0
tempC = 0
end_flag = 0
curr_volt = 0
past_volt = 0
volt_counter = 0
prev_state = 0
tag = 0
capacity = 0
past_curr = 0
past_time = datetime.now()
file_date = datetime.now().strftime("%d_%m_%Y_%H_%M")
spi = board.SPI() #Estas pueden cambiarse para usar
cs = digitalio.DigitalInOut(board.D5) #RPi.GPIO
max31855 = adafruit_max31855.MAX31855(spi,cs)

def statemachine(entry):
    global state
    switch = {"INIT" : INIT,
              "PULSE" : PULSE,
              "REST" : REST,
              "END" : END,
    }
    func = switch.get(state)
    return func(entry)

def ISR(): #Interrupt Service Routine
    global timer_flag
    t = threading.Timer(1.00, ISR)
    t.start()
    timer_flag = 1 #timer_flag pasa a 1(flag up)

def poweroff(gpio): # NO ESTÁ FUNCIONANDO (takes 0 positional arguments but 1 was given)
    global state
    global end_flag
    GPIO.output(17, GPIO.LOW)
    GPIO.output(18, GPIO.LOW)
    Carga.apagar_carga()
    Carga.remote_sense(False)
    print("El sistema se ha detenido...")
    state = "END"
    end_flag = 1
GPIO.add_event_detect(22, GPIO.RISING, callback=poweroff, bouncetime=1000)

def measure():
    global past_time
    global past_curr
    global capacity
    global seconds
    global volt
    global current
    global tempC
    global max31855
    global outputCSV
    global file_date
    global past_volt
    global curr_volt
    global counter
    global tag

    tiempo_actual = datetime.now()
    deltat = (tiempo_actual - past_time).total_seconds()
    seconds += deltat
    volt,current = Carga.medir_todo()
    tempC = max31855.temperature

    if tempC >= 60:
        poweroff()
        print("CUIDADO! La celda ha excedido para Tmáx")

    capacity +=  deltat * ((current + past_curr) / 7.2) #documentar porque 7.2 sino se te va a olvidar
    past_time = tiempo_actual
    past_curr = current
    print("s = {:09.2f} tag = {:1d} V = {:06.3f} I = {:06.3f} Q = {:07.2f} T = {:06.3f}".format(seconds, tag, volt, current, capacity, tempC))
    #Añadir valores constantement en el csv
    outputCSV = outputCSV.append({"Timestamp":tiempo_actual,"Time":round(seconds,2), "Tag":tag, "Voltage":volt, "Current":current, "Capacity":capacity, "Temperature":tempC}, ignore_index=True)
    filename = '/home/pi/pulse_discharges/' + 'discharge_pulse' + file_date + '.csv' #For Windows: C:/Repositories/battery_characterizer/coulomb_tests/
    outputCSV.iloc[-1:].to_csv(filename, index=False, mode='a', header=False)

def relay_control(state):
    if state == "PULSE":
        GPIO.output(18, GPIO.HIGH)
        #time.sleep(0.5)
    elif state == "REST":
        GPIO.output(18, GPIO.LOW)
        #time.sleep(0.5)

def INIT(entry):
    global timer_flag
    global counter
    global state
    global init_flag
    global past_time
    global volt
    global past_volt
    Carga.remote_sense(True)
    d = str(input("¿Desea iniciar el proceso de pulsos de descarga a la batería? (y/n): \n"))
    if d == "y":
        print("Inicio...")
        state = "REST"
        init_flag = 1
        past_time = datetime.now()
        measure()
        past_volt = volt

    else:
        print("El proceso no comenzará. Si desea iniciar, digite 'y'.")
        state = "INIT"

def PULSE(entry):
    global state
    global batt_capacity
    global timer_flag
    global counter
    global volt
    global past_volt
    global current
    global file_date
    global seconds
    global init_flag
    global past_time
    global timer_flag
    global prev_state
    global seconds
    global tag
    dt = 120 #Discharge time (in seconds)

    if init_flag == 1:
        relay_control(state)
        Carga.set_range(40)
        Carga.fijar_corriente(batt_capacity * 1.5) #SET DISCHARGE RATE
        Carga.encender_carga()
        #past_time = datetime.now()
        #file_date = datetime.now().strftime("%d_%m_%Y_%H_%M")
        init_flag = 0
        #timer_flag = 0
        counter = 0
        timer_flag = 0
        tag = 1
        #seconds = 0 Interesa ver la gráfica desde que se empieza en el INIT

    if timer_flag == 1:
        timer_flag = 0
        counter += 1
        measure()
        if volt > 2.5:
            if counter >= dt:
                Carga.apagar_carga()
                prev_state = "PULSE"
                state = "REST"
                init_flag = 1
                past_volt = volt #Para la primera medición, past_volt = último valor medido de volt
                counter = 0
                tag = 0
        else:
            #Carga.fijar_voltaje(2.5)
#Lo siguiente debería ir en un función aparte?
            #if current <= (0.1):
            poweroff() # lo manda a END
            #state = "END"

def REST(entry):
    global timer_flag
    global counter
    global seconds
    global state
    global init_flag
    global past_volt
    global curr_volt
    global volt
    global tag

    if timer_flag == 1:
        timer_flag = 0
        counter += 1
        measure()
        curr_volt += volt # current_voltage is accumulating in the REST state
        #print("Debería acumularse:", curr_volt)
        if counter == 60: #Compare last 60 values
            curr_volt = curr_volt / 60
            print("curr_volt:", curr_volt)
            print("past_volt:", past_volt)
            deltavolt = abs(((curr_volt - past_volt) * 100) / past_volt)
            print("DeltaVolt:", deltavolt)
            counter = 0
            past_volt = curr_volt
            curr_volt = 0
            if deltavolt <= 0.01:
                print("Iniciando próximo pulso de descarga")
                state = "PULSE"
                init_flag = 1

def END(entry):
    global end_flag
    print("Se ha descarga la batería por completo...")
    end_flag = 1

#################### MAIN LOOP ####################
t = threading.Timer(1.0, ISR)
t.start()
while end_flag == 0:
    statemachine("INIT")
print("Terminó el programa...")


import pytest

from algo import VentilationStateMachine
from data import alerts
from data.thresholds import PressureRange
from drivers.driver_factory import DriverFactory

SIMULATION_SAMPLES = 1000
NO_BREATH_TIME = VentilationStateMachine.NO_BREATH_ALERT_TIME_SECONDS + 1

@pytest.fixture
def config(default_config):
    c = default_config
    # Adapt the threshold for the sinus simulation.
    c.thresholds.pressure = PressureRange(min=0, max=30)
    c.thresholds.volume.min = 0
    return c

@pytest.mark.usefixtures("config")
@pytest.mark.parametrize("data", ["sinus"])
def test_sinus_does_not_trigger_alert(sim_sampler, events, data):
    """Test that synthesized breath signal does not trigger the alert."""
    for _ in range(SIMULATION_SAMPLES):
        sim_sampler.sampling_iteration()

    assert len(events.alerts_queue) == 0,\
        f"Unexpected alerts: {events.alerts_queue.active_alerts}"

@pytest.mark.parametrize("data", ["dead", "noise"])
@pytest.mark.usefixtures("config")
def test_dead_man_alerts_when_no_breath(sim_sampler, events, data):
    """Test that no-breath alert is sent after time without breathing"""
    time_intervals = 1 / DriverFactory.MOCK_SAMPLE_RATE_HZ
    num_of_samples = int(NO_BREATH_TIME / time_intervals)
    for i in range(num_of_samples):
        sim_sampler.sampling_iteration()

    assert len(events.alerts_queue) > 0

    all_alerts = list(events.alerts_queue.active_alerts)
    assert any(a.code == alerts.AlertCodes.NO_BREATH for a in all_alerts),\
        f"NO_BREATH is not in {all_alerts}"


#! /usr/bin/python3
from random import randint

def solution(A):
    # write your code in Python 3.6
    # filter <= 0 first? might depend on the data
    A.sort()
    expected = 1
    for e in A:
        if e < expected:
            continue
        if e != expected:
            break
        expected = e+1
    return expected

def check_solution():
    A = [1,3,6,4,1,2]
    assert(solution(A) == 5)

    A = [1,3,2]
    assert(solution(A) == 4)

    A = [-1,-2]
    assert(solution(A) == 1)

    A = [randint(-100, 100) for _ in range(100000)]
    print("solution(A) is ", solution(A))

    print("All tests passed!")

check_solution()