# encoding=utf-8
'''
Created on 2016年4月18日

@author: lenovo
'''

import re
import csv
import pickle
from multiprocessing import Pool
from collections import Counter
from functools import partial
from math import fabs, log
import jieba

jieba.initialize()

def calAccuracy(devs, outs):
    n = len(outs)
    equ = 0
    fake_true = 0
    fake_false = 0
    ftrue = open("logs/fake_true.txt", "w")
    ffalse = open("logs/fake_false.txt", "w")
    fclose = open("logs/close.txt", "w")
    # assert len(devs) == len(outs)
    for i in range(n):
        if int(devs[i][1]) == outs[i][0]:
            equ += 1
        elif devs[i][1] == '0':
            fake_true += 1
            print(devs[i][0], devs[i][1], outs[i][0], outs[i][1], file=ftrue)
        else:
            fake_false += 1
            print(devs[i][0], devs[i][1], outs[i][0], outs[i][1], file=ffalse)
        if fabs(outs[i][1]) < 0.2:
            print(devs[i][0], devs[i][1], outs[i][0], outs[i][1], file=fclose)
    print("fake true = %f(%d), fake false = %f(%d)" %
          (fake_true/n, fake_true, fake_false/n, fake_false))
    return equ/n

def joinmaps(lst):
    ret = {}
    cnt = 0
    for d in lst:
        for k, v in d.items():
            ret[k] = ret.get(k, 0) + v
            cnt += v
    return ret, cnt

class BayesSpam:
    def __init__(self):
        self.norm_file_len = 0
        self.spam_file_len = 0
        self.norm_dict = {}
        self.spam_dict = {}
        self.words_dict = {}
        self.stop_list = []
        self.words_list = []

        with open("stoplist.txt", encoding='utf-8') as sl:
            for line in sl:
                self.stop_list.append(line)

    def train(self, data):
        spams = []
        normals = []
        for line in data:
            if line[1] == '1':
                spams.append(line[0])
            else:
                normals.append(line[0])
        self.norm_file_len = len(normals)
        self.spam_file_len = len(spams)
        print("normal email number: ", self.norm_file_len)
        print("spam email number: ", self.spam_file_len)
        self.norm_dict = self._update_words_to_dict(normals)
        self.spam_dict = self._update_words_to_dict(spams)

    def predict(self, data):
        pool = Pool()
        return pool.map(self._test_line, data)

    def _update_words_to_dict(self, emails):
        pool = Pool()
        dicts = pool.map(self._load_email, emails)
        return joinmaps(dicts)[0]

    def _test_line(self, email):
        text = email[0]
        rule = re.compile(r"[^\u4e00-\u9fa5]")
        text = rule.sub("", text)
        wl = self._load_email(text)
        p = self._dict_to_prob(wl)
        if(p > 0):
            return 1, p
        else:
            return 0, p

    def _dict_to_prob(self, testDict):
        ret = log(self.spam_file_len/self.norm_file_len)
        # print(spamDict, normDict)
        # print(normFilelen, spamFilelen)
        default = 1/(1e30)
        # default = 0.00001
        for word in testDict:
            pw_s = self.spam_dict.get(word, default)/self.spam_file_len
            pw_n = self.norm_dict.get(word, default)/self.norm_file_len
            ps_w = pw_s/pw_n
            # ps_w = log(ps_w)*num
            ps_w = log(ps_w)
            ret += ps_w
        # wordProbList = sorted(wordProbList.items(),key=lambda d:d[1],reverse=True)[0:15]
        return ret

    def _load_email(self, normal):
        word_list = []
        word_dict = {}
        line = normal
        rule = re.compile(r"[^\u4e00-\u9fa5]")
        line = rule.sub("", line)
        res_list = list(jieba.cut(line))
        for i in res_list:
            if i not in self.stop_list and i.strip() != '' and i != None:
                word_dict[i] = word_dict.get(i, 0) + 1

        return word_dict

    def _add_to_dict(self, wordsList, wordsDict):
        for item in wordsList:
            wordsDict[item] = wordsDict.get(item, 0) + 1

def dump(rets):
    with open('answer.txt', 'w') as f:
        print("\n".join(map(str, map(lambda x: x[0], rets))), file=f)

def main():
    with open("../data/train.csv", 'r', encoding='utf-8') as f:
        train_raw = list(csv.reader(f))

    with open("../data/dev.csv", 'r', encoding='utf-8') as f:
        dev_raw = list(csv.reader(f))

    with open("../data/test.csv", 'r', encoding='utf-8') as f:
        test_raw = list(csv.reader(f))[1:]

    bs = BayesSpam()

    print("_______bayes________")
    bs.train(train_raw)

    result_train = bs.predict(train_raw)
    result_dev = bs.predict(dev_raw)
    result_test = bs.predict(test_raw)
    print("test completed")

    devAccuracy = calAccuracy(dev_raw, result_dev)
    trainAccuracy = calAccuracy(train_raw, result_train)
    print("train acc =", trainAccuracy)
    print("dev acc =", devAccuracy)
    print("_______bayes________")

    print("work completed")
    dump(result_test)

if __name__ == '__main__':
    main()


from __future__ import print_function
import glob # for glob
import os.path # for dirname, join, isfile

env=Environment()
env['PROGSUFFIX']='.elf'

for x in glob.glob("*/SConstruct"):
	if not os.path.isfile(os.path.join(os.path.dirname(x), 'SKIP.txt')):
		print('doing [{0}]'.format(x))
		SConscript(x, exports=['env'])
	else:
		print('skipping [{0}]'.format(x))


def water_plants(plants, capacity):
    n_plants = len(plants)
    n = 0
    def water_next(plants_left, n, n_plants, capacity, current_water):
        # debug
        print('plants left: {}, current_water: {}, n_steps: {}'.format(str(plants_left), current_water, n))
        # base return
        if plants_left == []:
            return n
        # reload water?
        if plants_left[0] > current_water:
            current_water = capacity
            n += (n_plants - len(plants_left))*2
        # base case
        current_water -= plants_left.pop(0)
        # ah shit... here we go again
        return water_next(plants_left, n+1, n_plants, capacity, current_water)
    n = water_next(plants, n, n_plants, capacity, capacity)
    return n

# test
plants = [2, 4, 5, 1, 2]
capacity = 6
print('test with plants: {} and capacity {}'.format(plants, capacity))
print('TOTAL STEPS: {}'.format(water_plants(plants,capacity)))


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
from statsmodels.tsa.arima_model import ARMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from data import load_earth_quake_data

def searching_over_model_order(df):
    # Create empty list to store search results
    order_aic_bic = []

    # Loop over p values from 0-2
    for p in range(3):
        # Loop over q values from 0-2
        for q in range(3):
            # create and fit ARMA(p,q) model
            model = SARIMAX(df, order=(p, 0, q))
            results = model.fit()

            # Append order and results tuple
            order_aic_bic.append((p, q, results.aic, results.bic))

    # Construct DataFrame from order_aic_bic
    order_df = pd.DataFrame(order_aic_bic,
                            columns=["p", "q", "AIC", "BIC"])

    # Print order_df in order of increasing AIC
    print(order_df.sort_values(by="AIC"))

    # Print order_df in order of increasing BIC
    print(order_df.sort_values(by="BIC"))

def aic_and_bic(earthquake):
    # Loop over p values from 0-2
    for p in range(3):
        # Loop over q values from 0-2
        for q in range(3):
            try:
                # create and fit ARMA(p,q) model
                model = SARIMAX(earthquake, order=(p, 0, q))
                results = model.fit()

                # Print order and results
                print(p, q, results.aic, results.bic)
            except:
                print(p, q, None, None)

if __name__ == "__main__":
    sns.set()

    warnings.filterwarnings('ignore', '.*CONVERGENCE.*')

    # searching_over_model_order(df)
    earthquake = load_earth_quake_data()
    aic_and_bic(earthquake)


def quickSort(arr,low,high):
 if low>=high:
     return
 pivot=arr[(low+high)//2]
 index=partition(arr,pivot,low,high)
 quickSort(arr,low,index-1)
 quickSort(arr,index,high)
 return arr

def partition(arr,pivot,low,high):
    while low<=high:
        while arr[low]<pivot:
            low+=1
        while arr[high]>pivot:
            high-=1
        if low<=high:
            swap(arr,low,high)
            low+=1
            high-=1
    return low

def swap(arr,low,high):
     temp=arr[low]
     arr[low]=arr[high]
     arr[high]=temp
     return

l=[98,20,78,1,44,67,90]
size=len(l)-1
print(quickSort(l,0,size))


"""
An example of a PyGame game. Excluding comments, it contains 91 line,
and challenges the user to survive as long as possible avoiding the "bullets"
comining towards them. This is identical to example1.py but written more OO.
@author Kieran Vickers
"""
import math
import sys
from datetime import datetime
from random import randrange
from typing import List, Any

import pygame

# Set the constants for pygame
SIZE = WIDTH, HEIGHT = (800, 600)
CAPTION = "Workshop1 Task2"
BACKGROUND_COLOUR = (64, 0, 64)

# Initialise the game
FRAMES_PER_SECOND = 30
FRAMES_BETWEEN_BULLET_SPAWN = FRAMES_PER_SECOND / 5  # 5 bullets per second
BULLET_SPEED = int(SIZE[0] / (FRAMES_PER_SECOND * 10))  # 10 seconds to cross
PLAYER_RADIUS = 20
BULLET_RADIUS = 10
PLAYER_COLOUR = (255, 255, 255)
BULLET_COLOUR = (255, 0, 0)

# Define a general "thing"
class Thing:
    def on_event(self, event):
        pass

    def update(self):
        pass

    def draw(self, surface):
        pass

# Define a circle
class Circle(Thing):
    def __init__(self, starting_x, starting_y, radius, colour):
        self.position = (starting_x, starting_y)
        self.radius = radius
        self.colour = colour

    def draw(self, surface):
        pygame.draw.circle(surface, self.colour, self.position, self.radius)

# Define a Bullet object
class Bullet(Circle):
    """
    A Bullet is an object in the game, which can travel in one of four
    directions, starts from the end of the screen and continues forever.
    """
    # Define the different directions (as number 0 to 3)
    DIRECTIONS = RIGHT, DOWN, LEFT, UP = range(4)

    def __init__(self, direction):
        """
        Create a bullet object (initialise) given the direction it will
        travel in.
        @param direction: An integer representing the direction the bullet
        should travel in.
        """
        # Define the starting position and the amount to move given the
        # direction.
        if direction == Bullet.RIGHT:
            starting_x, starting_y = (0, randrange(HEIGHT))
            self.movement = (BULLET_SPEED, 0)
        elif direction == Bullet.DOWN:
            starting_x, starting_y = (randrange(WIDTH), 0)
            self.movement = (0, BULLET_SPEED)
        elif direction == Bullet.LEFT:
            starting_x, starting_y = (WIDTH, randrange(HEIGHT))
            self.movement = (-BULLET_SPEED, 0)
        else:
            starting_x, starting_y = (randrange(WIDTH), HEIGHT)
            self.movement = (0, -BULLET_SPEED)

        super().__init__(starting_x, starting_y, BULLET_RADIUS, BULLET_COLOUR)

    def update(self):
        """
        Update the position of the object.
        """
        old_x, old_y = self.position
        move_x, move_y = self.movement
        self.position = old_x + move_x, old_y + move_y

    def collision_test(self, user_position):
        """
        Test to see if this bullet has collided with the user.
        The distance between two pixels can be calculated using Pythagoras,
        as it can be considered a right angle triangle: the distance
        between the xs, and the distance between the ys as the two known
        edges, sqrt(x^2 + y^2).
        @param user_position: The x, y position of the user
        @return: A boolean, true if a collision has occurred.
        """
        x, y = self.position
        other_x, other_y = user_position
        return \
            math.sqrt(abs(x - other_x) ** 2 + abs(y - other_y) ** 2) < \
            PLAYER_RADIUS + BULLET_RADIUS

class Player(Circle):
    def __init__(self):
        super().__init__(WIDTH / 2, HEIGHT / 2,
                         PLAYER_RADIUS, PLAYER_COLOUR)

    def on_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            # If the mouse has moved at all...
            # (in this case, we now know this `event` will have a `.pos`
            # attribute), saying here the mouse is now
            self.position = event.pos  # Store the mouse position

# Define the game
class ExampleGameTwo:
    """
    An example pygame game.
    """

    def __init__(self):
        # Create a list of all children. As long as these are all "Thing"s
        # then we can call on_event, update and draw regardless of inheritance.
        self.children = []

        # Initiate pygame and a screen to display to, using the constants
        pygame.init()
        pygame.font.init()  # Line isn't needed unless you write text to screen.
        pygame.display.set_caption(CAPTION)

        self.frames_since_last_bullet = 0  # Count the number of frames between
        # bullet spawns
        self.player = Player()
        self.children.append(self.player)  # Add player to children
        self.bullets = []

        self.start_time = datetime.now()

        # Store some pygame variables to the game too
        self.running = True
        self.screen = pygame.display.set_mode(SIZE)
        self.clock = pygame.time.Clock()

    def event_handler(self, event):
        """
        The event handler for this game, called once for every (non QUIT)
        event, after a draw and before the update. Currently handles
        MOUSEMOTION only.
        @param event: Any pygame event.
        """
        for child in self.children:
            child.on_event(event)

    def update(self):
        """
        Update the state of the game, called each frame after events handled
        before drawing to the screen.
        This function moves all bullets, checks for collisions (end game),
        and adds new bullets.
        """
        for child in self.children:
            child.update()

        for bullet in self.bullets:
            if bullet.collision_test(self.player.position):
                self.running = False
                print("Game over.")
                time = (datetime.now() - self.start_time).total_seconds()
                print("Your score was:", time)

        # Add new bullets if time to
        # Add one to the counter of number of frames since last bullet
        self.frames_since_last_bullet += 1
        # FRAMES_PER_SECOND / NEW_BULLETS_PER_SECOND is the calculation of
        # frames between bullet spawns, given these constants, if the number
        if self.frames_since_last_bullet >= FRAMES_BETWEEN_BULLET_SPAWN:
            # If the number of frames since last bullet is the number of frames
            # between each bullet spawn:
            # Reset the counter,
            self.frames_since_last_bullet = 0
            # and add a new bullet to each direction
            for direction in Bullet.DIRECTIONS:
                new_bullet = Bullet(direction=direction)
                self.bullets.append(new_bullet)
                self.children.append(new_bullet)

    def draw(self, surface: pygame.Surface):
        """
        Draw all this game to the surface.
        @param surface: A surface to draw the game to.
        """
        for child in self.children:
            child.draw(surface)

    def run_game(self):
        """
        Run the game, this function is independent of the game logic,
        and therefore might not need changed.
        """
        # Run the game loop
        while self.running:
            # Handle any event that occur
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    # If the event is a "QUIT" event, quit the game
                    self.running = False
                else:
                    # Otherwise, allow the event handler to handle the event
                    self.event_handler(event)

            # Update the game state
            self.update()

            # Draw the game to the screen
            self.screen.fill(BACKGROUND_COLOUR)  # Fill background
            self.draw(self.screen)

            # Update and wait
            pygame.display.update()  # Display what we have drawn
            self.clock.tick(FRAMES_PER_SECOND)
        # If no longer running, quit pygame and exit.
        pygame.quit()
        sys.exit(0)

if __name__ == '__main__':
    game = ExampleGameTwo()
    game.run_game()


TEMPERATURE = "Temperature"
SOC = "SOC"
CHARGE_RATE = "ChargeRate"
TEST_PARAM = "Test Param"
MIN_TEMP = 0
MAX_TEMP = 45
MIN_SOC = 20
MAX_SOC = 80
MAX_CHARGE_RATE = 0.8
CELSIUS = "°C"
FARENHEIT = "°F"
UNIT_CONVERSIONS = [{
    "From": FARENHEIT,
    "To": CELSIUS,
    "Formula": "(({}-32)*5)/9"
}]
ENGLISH = "English"
GERMAN = "German"
LANGUAGES_SUPPORTED = [ENGLISH, GERMAN]
INRANGE = "InRange"
OUT_OF_RANGE = "OutofRange"
IN_LOW_LIMIT = "InLowLimit"
OUT_OF_LOW_LIMIT = "OutofLowLimit"
IN_HIGH_LIMIT = "InHighLimit"
OUT_OF_HIGH_LIMIT = "OutofHighLimit"
LANGUAGE_TEMPLATES = {
    ENGLISH:{
        TEMPERATURE : TEMPERATURE,
        SOC : SOC,
        CHARGE_RATE : CHARGE_RATE,
        TEST_PARAM: TEST_PARAM,
        INRANGE : "{} is in range",
        OUT_OF_RANGE : "{} out of range",
        IN_LOW_LIMIT : "{} is in low limit",
        OUT_OF_LOW_LIMIT : "{} is too low",
        IN_HIGH_LIMIT : "{} is in high limit",
        OUT_OF_HIGH_LIMIT : "{} is too high"
    },
    GERMAN:{
        TEMPERATURE : "Temperatur",
        SOC : SOC,
        CHARGE_RATE : "Ladestrom",
        TEST_PARAM: "Testparam",
        INRANGE :  "{} ist im Bereich",
        OUT_OF_RANGE : "{} außerhalb des Bereichs",
        IN_LOW_LIMIT : "Die {} ist im unteren Bereich",
        OUT_OF_LOW_LIMIT : "Die {} ist zu niedrig",
        IN_HIGH_LIMIT : "Die {} ist im oberen Bereich",
        OUT_OF_HIGH_LIMIT : "Die {} ist zu hoch"
    }

    }


"""
Core of the DeltaSNOW model. This module provides the public function
:func:`deltasnow_snowpack_evolution` which implements the algorithm of the
deltaSNOW model with numba but does not validate input data. Users are
discouraged to use this function and should rather use the
:func:`pydeltasnow.main.swe_deltasnow` function instead.

Significant parts of the code in this module are based on the work of Manuel
Theurl: https://github.com/manueltheurl/snow_to_swe

"""
import numpy as np
from numba import njit

from pydeltasnow import __version__

__author__ = "Johannes Aschauer"
__copyright__ = "Johannes Aschauer"
__license__ = "GPL-2.0-or-later"

G = 9.81  # gravitational acceleration on earth
PRECISION = 10e-10  # floating point precision

@njit
def _assign_H(
        h_dd,
        swe_dd,
        age_dd,
        h,
        swe,
        age,
        H,
        SWE,
        t,
        day_tot,
):
    """
    Assign snowpack properties of the next timestep.
    """
    if t < day_tot:
        h[:, t + 1] = h_dd
        swe[:, t + 1] = swe_dd
        age[:, t + 1] = age_dd
        H[t + 1] = np.sum(h[:, t + 1])
        SWE[t + 1] = np.sum(swe[:, t + 1])

    return h, swe, age, H, SWE

@njit
def _compact_H(
        h,
        swe,
        swe_hat,
        age,
        ts,
        eta_null,
        k,
        rho_max,
):
    """
    Compaction of individual snow layers without additional load
    Values of today are compacted to values of tomorrow.
    """
    age_d = 0 if h == 0 else age
    h_dd = h / (1 + (swe_hat * G * ts) / eta_null * np.exp(-k * swe / h))
    h_dd = swe / rho_max if swe / h_dd > rho_max else h_dd
    h_dd = 0 if h == 0 else h_dd
    swe_dd = swe
    age_dd = 0 if h == 0 else age_d + 1
    rho_dd = 0 if h == 0 else swe_dd / h_dd
    rho_dd = rho_max if rho_max - rho_dd < PRECISION else rho_dd
    return h_dd, swe_dd, age_dd, rho_dd

@njit
def _drench_H(
        t,
        ly,
        ly_tot,
        day_tot,
        Hobs,
        h,
        swe,
        age,
        H,
        SWE,
        ts,
        eta_null,
        k,
        rho_max
):
    """
    Drenching of the snowpack if the observed snowdepth decreased significantly.
    """
    Hobs_d = Hobs[t]
    h_d = h[:, t]
    swe_d = swe[:, t]
    age_d = age[:, t]

    # distribute mass top-down
    # reversed not working in numba
    for i in range(ly - 1, -1, -1):
        # for i in reversed(range(ly)):
        if np.sum(np.array([element for j, element in enumerate(h_d) if j != i])) + swe_d[
            i] / rho_max - Hobs_d >= PRECISION:
            # layers is densified to rho_max
            h_d[i] = swe_d[i] / rho_max
        else:
            # layer is densified as far as possible
            # but doesnt reach rho_max
            h_d[i] = swe_d[i] / rho_max + np.abs(
                np.sum(np.array([element for j, element in enumerate(h_d) if j != i])) + swe_d[i] / rho_max - Hobs_d)
            break

    true_false_list = np.ones(ly, dtype="bool")
    for i, (swe_d_val, h_d_val) in enumerate(zip(swe_d[:ly], h_d[:ly])):
        true_false_list[i] = rho_max - swe_d_val / h_d_val <= PRECISION

    if np.all(true_false_list):
        # no further compaction, runoff
        scale = Hobs_d / np.sum(h_d)
        h_d = h_d * scale  # all layers are compressed (and have rho_max) [m]
        swe_d = swe_d * scale

    h[:, t] = h_d
    swe[:, t] = swe_d
    age[:, t] = age_d
    H[t] = np.sum(h[:, t])
    SWE[t] = np.sum(swe[:, t])

    # no further compaction possible
    h_dd, swe_dd, age_dd, rho_dd = _dry_metamorphism(
        h[:, t],
        swe[:, t],
        age[:, t],
        ly_tot,
        ly,
        ts,
        eta_null,
        k,
        rho_max)

    # set values for next day
    h, swe, age, H, SWE = _assign_H(h_dd, swe_dd, age_dd, h, swe, age, H, SWE, t, day_tot)

    return h, swe, age, H, SWE, rho_dd

@njit
def _dry_metamorphism(
        h_d,
        swe_d,
        age_d,
        ly_tot,
        ly,
        ts,
        eta_null,
        k,
        rho_max
):
    """
    Compaction of dry snowpack.
    """
    # overburden of current day (swe_hat_d)
    swe_hat_d = np.zeros(ly_tot)
    for i in range(ly_tot):
        swe_hat_d[i] = np.sum(swe_d[i:ly_tot])

    h_dd = h_d.copy()
    swe_dd = swe_d.copy()
    age_dd = age_d.copy()
    rho_dd = np.zeros(ly_tot)

    for i, (h, swe, swe_hat, age) in enumerate(zip(h_d[:ly], swe_d[:ly], swe_hat_d[:ly], age_d[:ly])):
        h_dd[i], swe_dd[i], age_dd[i], rho_dd[i] = _compact_H(
            h,
            swe,
            swe_hat,
            age,
            ts,
            eta_null,
            k,
            rho_max
        )

    return h_dd, swe_dd, age_dd, rho_dd

@njit
def _scale_H(
        t,
        ly,
        ly_tot,
        day_tot,
        deltaH,
        Hobs,
        h,
        swe,
        age,
        H,
        SWE,
        ts,
        eta_null,
        k,
        rho_max,
):
    """
    Scale snowpack if the settling was assumed a bit too strong or too weak.
    """
    Hobs_d = Hobs[t - 1]
    Hobs_dd = Hobs[t]
    h_d = h[:, t - 1]
    swe_d = swe[:, t - 1]
    age_d = age[:, t]

    # todays overburden
    swe_hat_d = np.zeros(ly_tot)
    for i in range(ly_tot):
        swe_hat_d[i] = np.sum(swe_d[i:ly_tot])

    # analytical solution for layerwise adapted viskosity eta
    # assumption: recompaction ~ linear height change of yesterdays layers (see paper)
    eta_cor = np.zeros(ly_tot)
    for i in range(ly_tot):
        if swe_d[i] == 0. or h_d[i] == 0:
            eta_cor[i] = 0.
        else:
            rho_d = swe_d[i] / h_d[i]
            x = ts * G * swe_hat_d[i] * np.exp(-k * rho_d)  # yesterday
            P = h_d[i] / Hobs_d  # yesterday
            eta_cor[i] = Hobs_dd * x * P / (h_d[i] - Hobs_dd * P) if (h_d[i] - Hobs_dd * P) != 0 else np.inf

    h_dd_cor = np.zeros(ly_tot)
    for i in range(ly_tot):
        if h_d[i] == 0 or eta_cor[i] == 0:
            h_dd_cor[i] = 0.
        else:
            h_dd_cor[i] = h_d[i] / (1 + (swe_hat_d[i] * G * ts) / eta_cor[i] * np.exp(-k * swe_d[i] / h_d[i]))
    h_dd_cor[np.isnan(h_dd_cor)] = 0
    H_dd_cor = np.sum(h_dd_cor)

    # and check, if Hd.cor is the same as Hobs.d
    if np.abs(H_dd_cor - Hobs_dd) > PRECISION:
        print("WARNING: error in exponential re-compaction: H.dd.cor-Hobs.dd")

    # which layers exceed rho.max?
    idx_max_arr = np.zeros(ly_tot, dtype='bool')
    for i, (swe_e_val, h_dd_cor_val) in enumerate(zip(swe_d, h_dd_cor)):
        try:
            idx_max_arr[i] = np.divide(swe_e_val, h_dd_cor_val) - rho_max > PRECISION
        except:
            idx_max_arr[i] = False
    idx_max_arr[np.isnan(idx_max_arr)] = False

    if np.any(idx_max_arr):
        if np.count_nonzero(idx_max_arr) < ly:
            # collect excess swe in those layers
            swe_excess = swe_d[idx_max_arr] - h_dd_cor[idx_max_arr] * rho_max

            # set affected layer(s) to rho.max
            swe_d[idx_max_arr] = swe_d[idx_max_arr] - swe_excess

            # distribute excess swe to other layers top-down
            lys = range(ly)
            lys_non_max = []
            for e in lys:
                if e not in np.nonzero(idx_max_arr)[0]:
                    lys_non_max.append(e)

            i = lys_non_max[-1]
            swe_excess_all = np.sum(swe_excess)

            while swe_excess_all > 0:
                # layer tolerates this swe amount to reach rho.max
                swe_res = h_dd_cor[i] * rho_max - swe_d[i]
                if swe_res > swe_excess_all:
                    swe_res = swe_excess_all

                swe_d[i] = swe_d[i] + swe_res
                swe_excess_all = swe_excess_all - swe_res
                i = i - 1
                if i < 0 < swe_excess_all:
                    # runoff
                    break
        else:
            # if all layers have density > rho.max
            # remove swe.excess from all layers (-> runoff)
            # (this sets density to rho.max)
            swe_excess = swe_d[idx_max_arr] - h_dd_cor[idx_max_arr] * rho_max
            swe_d[idx_max_arr] = swe_d[idx_max_arr] - swe_excess

    h[:, t] = h_dd_cor
    swe[:, t] = swe_d
    age[:, t] = age_d
    H[t] = np.sum(h[:, t])
    SWE[t] = np.sum(swe[:, t])

    # compact actual day
    h_dd, swe_dd, age_dd, rho_dd = _dry_metamorphism(
        h[:, t],
        swe[:, t],
        age[:, t],
        ly_tot,
        ly,
        ts,
        eta_null,
        k,
        rho_max,
    )

    # set values for next day
    h, swe, age, H, SWE = _assign_H(
        h_dd,
        swe_dd,
        age_dd,
        h,
        swe,
        age,
        H,
        SWE,
        t,
        day_tot,
    )
    return h, swe, age, H, SWE, rho_dd

@njit
def deltasnow_snowpack_evolution(
        Hobs,
        rho_max,
        rho_null,
        c_ov,
        k_ov,
        k,
        tau,
        eta_null,
        resolution,
):
    """
    This is the main loop in the delta snow model. Should be called on HS chunks
    of consecutive nonzeros.

    Parameters
    ----------
    Hobs : 1D :class:`numpy.ndarray` of floats
        Measured snow height. Needs to be in [m].
        Must comply to the following constraints:
            - no nans
            - continuous entries (no missing dates)
    rho_max : float, optional
        Maximum density of an individual snow layer produced by the deltasnow
        model in [kg/m3], rho_max needs to be positive. The default is 401.2588.
    rho_null : float, optional
        Fresh snow density for a newly created layer [kg/m3], rho_null needs to
        be positive. The default is 81.19417.
    c_ov : float, optional
        Overburden factor due to fresh snow [-], c_ov needs to be positive. The
        default is 0.0005104722.
    k_ov : float, optional
        Defines the impact of the individual layer density on the compaction due
        to overburden [-], k_ov need to be in the range [0,1].
        The default is 0.37856737.
    k : float, optional
        Exponent of the exponential-law compaction [m3/kg], k needs to be
        positive. The default is 0.02993175.
    tau : float, optional
        Uncertainty bound [m], tau needs to be positive.
        The default is 0.02362476.
    eta_null : float, optional
        Effective compactive viscosity of snow for "zero-density" [Pa s].
        The default is 8523356.
    resolution : float
        Timedelta in hours between snow observations.

    Raises
    ------
    RuntimeError
        If the snowpack evolution has somehow gone wrong.

    Returns
    -------
    SWE : 1D :class:`numpy.ndarray` of floats
        Calculated SWE in [mm]. Same shape as Hobs.

    """

    ly_tot = np.count_nonzero(Hobs)  # maximum number of layers [-]
    day_tot = len(Hobs)  # total days from first to last snowfall [-]

    # preallocate output arrays
    H = np.zeros(day_tot)  # modeled total height of snow at any day [m]
    SWE = np.zeros(day_tot)  # modeled total SWE at any day [kg/m2]

    # preallocate matrix as days X layers
    h = np.zeros((ly_tot, day_tot))  # modeled height of snow in all layers [m]
    swe = np.zeros((ly_tot, day_tot))  # modeled swe in all layers [kg/m2]
    age = np.zeros((ly_tot, day_tot))  # age in all layers

    ly = 1  # layer number [-]
    ts = resolution * 3600

    for t in range(day_tot):
        # snowdepth = 0, no snow cover
        if Hobs[t] == 0:
            H[t] = 0
            SWE[t] = 0
            h[:, t] = 0
            swe[:, t] = 0

        # there is snow
        elif Hobs[t] > 0:  # redundant if, cause can snow height be negative?
            # first snow in/during season
            if Hobs[t - 1] == 0:
                ly = 1
                age[ly - 1, t] = 1
                h[ly - 1, t] = Hobs[t]
                H[t] = Hobs[t]
                swe[ly - 1, t] = rho_null * Hobs[t]
                SWE[t] = swe[ly - 1, t]

                # compact actual day
                h_dd, swe_dd, age_dd, rho_dd = _dry_metamorphism(
                    h[:, t],
                    swe[:, t],
                    age[:, t],
                    ly_tot,
                    ly,
                    ts,
                    eta_null,
                    k,
                    rho_max,
                )

                h, swe, age, H, SWE = _assign_H(
                    h_dd,
                    swe_dd,
                    age_dd,
                    h,
                    swe,
                    age,
                    H,
                    SWE,
                    t,
                    day_tot,
                )

            elif Hobs[t - 1] > 0:
                deltaH = Hobs[t] - H[t]
                if deltaH > tau:
                    sigma_null = deltaH * rho_null * G
                    epsilon = c_ov * sigma_null * np.exp(-k_ov * rho_dd / (rho_max - rho_dd))
                    h[:, t] = (1 - epsilon) * h[:, t]
                    swe[:, t] = swe[:, t - 1]
                    age[:ly, t] = age[:ly, t - 1] + 1
                    H[t] = np.sum(h[:, t])
                    SWE[t] = np.sum(swe[:, t])

                    # only for new layer
                    ly = ly + 1
                    h[ly - 1, t] = Hobs[t] - H[t]
                    swe[ly - 1, t] = rho_null * h[ly - 1, t]
                    age[ly - 1, t] = 1

                    # recompute
                    H[t] = np.sum(h[:, t])
                    SWE[t] = np.sum(swe[:, t])

                    # compact actual day
                    h_dd, swe_dd, age_dd, rho_dd = _dry_metamorphism(
                        h[:, t],
                        swe[:, t],
                        age[:, t],
                        ly_tot,
                        ly,
                        ts,
                        eta_null,
                        k,
                        rho_max,
                    )

                    # set values for next day
                    h, swe, age, H, SWE = _assign_H(
                        h_dd,
                        swe_dd,
                        age_dd,
                        h,
                        swe,
                        age,
                        H,
                        SWE,
                        t,
                        day_tot,
                    )

                # no mass gain or loss, but scaling
                elif -tau <= deltaH <= tau:
                    h, swe, age, H, SWE, rho_dd = _scale_H(
                        t,
                        ly,
                        ly_tot,
                        day_tot,
                        deltaH,
                        Hobs,
                        h,
                        swe,
                        age,
                        H,
                        SWE,
                        ts,
                        eta_null,
                        k,
                        rho_max,
                    )

                elif deltaH < -tau:
                    h, swe, age, H, SWE, rho_dd = _drench_H(
                        t,
                        ly,
                        ly_tot,
                        day_tot,
                        Hobs,
                        h,
                        swe,
                        age,
                        H,
                        SWE,
                        ts,
                        eta_null,
                        k,
                        rho_max,
                    )

                else:
                    raise RuntimeError("no valid calculated HS deviation.")
    return SWE


# Напишите программу, которая принимает на вход цифру, обозначающую день недели,
# и проверяет, является ли этот день выходным.
# Пример:
# - 6 -> да
# - 7 -> да
# - 1 -> нет

while True:
    try:
        input_day = int(input('input number of day: '))
        if 5 < input_day < 8:
            print('yeah! hollydays')
            break
        elif 0 < input_day < 6:
            print('just another working day...')
            break
        else:
            print('input number greather than 0 and less than 8')
    except:
        print('input a digit')


m1 = [[0 for _ in range(10)] for _ in range(10)]
m2 = [[i for i in range(10)] for _ in range(10)]

def printM(m):
    for row in m:
        for value in row:
            print(value,end="")
        print()

def copy_matrixes(m1, m2):
    '''
    copies the contents of m1 onto m2
    '''
    for i, row in enumerate(m1):
            for j, value in enumerate(row):
                m2[i][j] = value

copy_matrixes(m1, m2)

printM(m1)
printM(m2)


from pyspark.sql import DataFrame
from pyspark.sql.functions import lit, to_timestamp, to_date
from datetime import datetime

class FormatDataFrame:

    @staticmethod
    def parse_nyse2012(df: DataFrame, types: str) -> DataFrame:
        """
        :param types: Column types
        :param df: Dataframe to be transformed
        :return: Dataframe transformed
        """
        types = types.split(',')
        col_list = df.columns
        col_date = []  # Saves columns with datetime type

        try:
            """ Column cast """
            for i in range(len(col_list)):
                if types[i] == 'datetime' or types[i] == 'date':
                    types[i] = 'string'
                    col_date.append(col_list[i])
                df = df.withColumn(col_list[i], df[i].cast(types[i]))

            """ Cast DateType """
            for i in range(len(col_date)):
                df = df.withColumn(col_date[i], to_date(df[col_date[i]], 'dd-MMM-yyyy').alias(col_date[i]))

            """ New column """
            now = datetime.now()
            df = df.withColumn('partition_date', lit(now))
        except Exception as e:
            print("Error transforming nyse_2012")
            print(e)

        return df

    @staticmethod
    def parse_nyse2012TS(df: DataFrame, names: str, sizes: str, types: str) -> DataFrame:
        """
        :param types: Column types
        :param df: Dataframe to be transformed
        :param names: Column names
        :param sizes: column sizes in chars
        :return: Dataframe transformed
        """
        names = names.split(',')
        sizes = sizes.split(',')
        types = types.split(',')
        init = init_array(sizes)
        col_list = []  # Saves query for each column
        col_date = []  # Saves columns with timestamp type

        try:
            """ Fixed width & Column cast """
            for i in range(len(names)):
                if types[i] == 'timestamp':
                    types[i] = 'string'
                    col_date.append(names[i])
                col_list.append(df['_c0'].substr(init[i], int(sizes[i])).cast(types[i]).alias(names[i]))

            df = df.select(col_list)

            """ Cast TimestampType """
            for i in range(len(col_date)):
                df = df.withColumn(col_date[i], to_timestamp(df[col_date[i]], 'd/m/Y HH:MM:S').alias(col_date[i]))
        except Exception as e:
            print("Error transforming nyse_2012_ts")
            print(e)

        return df

def init_array(sizes):
    """
    :param sizes: Array with column sizes
    :return: Beginning of the columns (position)
    """
    aux = 1
    init = [1]
    for i in sizes:
        j = aux + int(i) + 1
        aux = j
        init.append(aux)
        if len(init) == len(sizes):
            return init


from ArrayManager.ArrayManager import TickArrayManager

class StrategyDoubleMA(object):
    def __init__(self):
        self.tam = TickArrayManager(frequency=60, size=20)
        # 策略参数
        self.adj_factor = 0.999
        self.units = 200
        # 策略变量
        self.posLong = 0
        self.posShort = 0

    def return_signal(self, ask, bid):
        signal = [0, 0]

        tam = self.tam
        tam.update_bar(ask=float(ask), bid=float(bid))

        ma_5 = []
        ma_11 = []

        if len(tam.close) > 11:
            ma_5 = tam.sma(5, array=True)
            ma_11 = tam.sma(11, array=True)

        # 检查数据完整性
        if len(ma_11) >= 5:
            diff0_cross = ma_5[-5] - ma_11[-5]
            diff1_cross = ma_5[-4] - ma_11[-4]
            diff2_cross = ma_5[-3] - ma_11[-3]
            diff3_cross = ma_5[-2] - ma_11[-2]
            diff4_cross = ma_5[-1] - ma_11[-1]

            # golden_cross = diff2_cross < 0 < diff3_cross
            # death_cross = diff3_cross < 0 < diff2_cross

            if self.posLong == 1:
                # if death_cross:
                #     signal = [-1, self.units]
                #     self.posLong = 0
                if tam.last_price() <= ma_11[-1] * self.adj_factor:
                    signal = [-1, self.units]
                    self.posLong = 0

            elif self.posShort == 1:
                # if golden_cross:
                #     signal = [1, self.units]
                #     self.posShort = 0
                if tam.last_price() >= ma_11[-1] * (1/self.adj_factor):
                    signal = [1, self.units]
                    self.posShort = 0

            elif self.posLong == 0 and self.posShort == 0:
                long = diff4_cross > diff3_cross > diff2_cross > diff1_cross > 0 > diff0_cross
                short = diff4_cross < diff3_cross < diff2_cross < diff1_cross < 0 < diff0_cross
                long_filter = ma_5[-1] > ma_5[-2] > ma_5[-3] > ma_5[-4] and ma_11[-1] >= ma_11[-2]
                short_filter = ma_5[-1] < ma_5[-2] < ma_5[-3] < ma_5[-4] and ma_11[-1] <= ma_11[-2]

                if long and long_filter:
                    signal = [1, self.units]
                    self.posLong = 1

                elif short and short_filter:
                    signal = [-1, self.units]
                    self.posShort = 1

            else:
                print('Unexpected error, please interrupt the program immediately.')

        else:
            pass

        return signal


from collections.abc import AsyncGenerator
from datetime import timedelta

from litestar.contrib.sqlalchemy.plugins import SQLAlchemyAsyncConfig
from litestar.exceptions import ClientException
from litestar.status_codes import HTTP_409_CONFLICT
from sqlalchemy import func, select
from sqlalchemy.exc import IntegrityError, NoResultFound
from sqlalchemy.ext.asyncio import AsyncSession
from src.models import Event
from src.settings import PostgresSettings

db_config = SQLAlchemyAsyncConfig(connection_string=PostgresSettings().postgres_dsn)

async def provide_transaction(db_session: AsyncSession) -> AsyncGenerator[AsyncSession, None]:
    try:
        async with db_session.begin():
            yield db_session
    except IntegrityError as exc:
        raise ClientException(
            status_code=HTTP_409_CONFLICT,
            detail=str(exc),
        ) from exc

async def get_repositories_more_than_1_pr_event(session: AsyncSession) -> list[Event]:
    query = (
        select(Event.repo_id)
        .where(Event.event_type == "PullRequestEvent", Event.action == "opened")
        .group_by(Event.repo_id)
        .having(func.count() > 1)
        .order_by(func.count().desc())
    )
    result: list[Event] = await session.execute(query)
    try:
        return result
    except NoResultFound:
        return None

async def get_average_time_between_prs(session: AsyncSession, repo_id: int) -> timedelta:
    query = (
        select((func.max(Event.created_at) - func.min(Event.created_at)) / (func.count(1) - 1).label("avg_time"))
        .where(Event.repo_id == repo_id, Event.action == "opened")
        .group_by(Event.repo_id)
    )
    result = await session.execute(query)
    try:
        return result.scalar_one()
    except NoResultFound:
        return None

async def get_num_of_events_per_type(session: AsyncSession, offset: int) -> dict[int]:
    # The complex subqueries are to ensure that we get a count of 0 for event types that have not occurred in the last offset minutes
    event_types_subquery = select(Event.event_type).distinct().subquery()

    event_count_subquery = (
        select(Event.event_type, func.count().label("count"))
        .where(
            Event.created_at.between(func.current_timestamp() - timedelta(minutes=offset), func.current_timestamp())
        )
        .group_by(Event.event_type)
    ).subquery()

    query = select(
        event_types_subquery.c.event_type, func.coalesce(event_count_subquery.c.count, 0).label("count")
    ).outerjoin(event_count_subquery, event_types_subquery.c.event_type == event_count_subquery.c.event_type)

    result = await session.execute(query)
    return result


import json
import time
import requests as r

class DataRecord:
    """to record the data about xingtong"""
    def __init__(self, url, filename):
        self.url = url
        self.filename = filename
        self.record = {}

    def get_follower(self):
        response = r.get(self.url)
        if response.status_code == 200:
            response_dict = response.json()
            response_dict = response_dict['data']['follower']
            return response_dict
        else:
            return 0

    def time_follower_dict(self):
        follower = DataRecord.get_follower(self)
        if len(self.record) != 0:
            self.record = {}
        self.record[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())] = follower
        return self.record

bili_url = 'https://api.bilibili.com/x/relation/stat?vmid=401315430'
file_path = 'D:/BVideoFiles/22886883-星瞳_Official/record_fans_num.json'
'''get返回dict: {'code': 0, 'message': '0', 'ttl': 1,
'data': {'mid': 401315430, 'following': 20, 'whisper': 0, 'black': 0,'follower': 160679}} '''

if __name__ == '__main__':
    count = 1
    Data = DataRecord(bili_url, file_path)
    while 1:
        if count:
            ctime = time.strftime("%S", time.localtime())
            if ctime == '00':
                count -= 1
        else:
            with open(file_path, 'r') as file:
                data_load = list(json.load(file))
                data_load.append(Data.time_follower_dict())
            with open(file_path, 'w') as f:
                json.dump(data_load, f, indent=4)
            time.sleep(600)


#!/usr/bin/env python3
__author__='DGideas';
import sys;
import fileinput;
import codecs;
r=codecs.open('weibo_result_data.txt','a','utf8');
i=1
with open('predict.txt') as f:
	for line in f:
		split=line.split('\t');
		r.write(split[0]+'\t'+split[1]+'\t'+'0,0,0'+'\n');
		print(i);
		i=i+1;


import os
import tempfile
import re
from .generic_manager import GenericManager, GenericManagerProperties
from .apt_parser import AptParser

from ambari_commons.constants import AMBARI_SUDO_BINARY
from ambari_commons import shell
from resource_management.core.logger import Logger

def replace_underscores(function_to_decorate):
  def wrapper(*args, **kwargs):
    self = args[0]
    name = args[1].replace("_", "-")
    return function_to_decorate(self, name, *args[2:], **kwargs)
  return wrapper

class AptManagerProperties(GenericManagerProperties):
  """
  Class to keep all Package-manager depended properties
  """
  locked_output = "Unable to lock the administration directory"
  repo_error = "Failure when receiving data from the peer"

  repo_manager_bin = "/usr/bin/apt-get"
  repo_cache_bin = "/usr/bin/apt-cache"
  pkg_manager_bin = "/usr/bin/dpkg"
  repo_update_cmd = [repo_manager_bin, 'update', '-qq']

  available_packages_cmd = [repo_cache_bin, "dump"]
  installed_packages_cmd = ['COLUMNS=999', pkg_manager_bin, "-l"]

  repo_definition_location = "/etc/apt/sources.list.d"

  install_cmd = {
    True: [repo_manager_bin, '-o', "Dpkg::Options::=--force-confdef", '--allow-unauthenticated', '--assume-yes', 'install'],
    False: [repo_manager_bin, '-q', '-o', "Dpkg::Options::=--force-confdef", '--allow-unauthenticated', '--assume-yes', 'install']
  }

  remove_cmd = {
    True: [repo_manager_bin, '-y', 'remove'],
    False: [repo_manager_bin, '-y', '-q', 'remove']
  }

  verify_dependency_cmd = [repo_manager_bin, '-qq', 'check']

  install_cmd_env = {'DEBIAN_FRONTEND': 'noninteractive'}

  repo_url_exclude = "ubuntu.com"
  configuration_dump_cmd = [AMBARI_SUDO_BINARY, "apt-config", "dump"]

class AptManager(GenericManager):

  def get_installed_package_version(self, package_name):
    r = shell.subprocess_executor("dpkg -s {0} | grep Version | awk '{{print $2}}'".format(package_name))
    return r.out.strip(os.linesep)

  @property
  def properties(self):
    return AptManagerProperties

  def installed_packages(self, pkg_names=None, repo_filter=None):
    """
    Return all installed packages in the system except packages in REPO_URL_EXCLUDE

    :type pkg_names list|set
    :type repo_filter str|None

    :return formatted list of packages
    """
    packages = []
    available_packages = self._available_packages_dict(pkg_names, repo_filter)

    with shell.process_executor(self.properties.installed_packages_cmd, error_callback=self._executor_error_handler,
                                strategy=shell.ReaderStrategy.BufferedChunks) as output:
      for package, version in AptParser.packages_installed_reader(output):
        if package in available_packages:
          packages.append(available_packages[package])

        if package not in available_packages:
          packages.append([package, version, "installed"])  # case, when some package not belongs to any known repo

    return packages

  def _available_packages(self, pkg_names=None, repo_filter=None):
    """
    Returning list of the installed packages with possibility to filter them by name

    :type pkg_names list|set
    :type repo_filter str|None
    """

    with shell.process_executor(self.properties.available_packages_cmd, error_callback=self._executor_error_handler,
                                strategy=shell.ReaderStrategy.BufferedChunks) as output:

      for pkg_item in AptParser.packages_reader(output):
        if repo_filter and repo_filter not in pkg_item[2]:
          continue
        if self.properties.repo_url_exclude in pkg_item[2]:
          continue
        if pkg_names and pkg_item[0] not in pkg_names:
          continue

        yield pkg_item

  def _available_packages_dict(self, pkg_names=None, repo_filter=None):
    """
    Same as available packages, but result returns as dict and package name as key

    :type pkg_names list|set
    :type repo_filter str|None
    """
    result = {}

    for item in self._available_packages(pkg_names, repo_filter):
      result[item[0]] = item

    return result

  def available_packages(self, pkg_names=None, repo_filter=None):
    """
    Returning list of the installed packages with possibility to filter them by name

    :type pkg_names list|set
    :type repo_filter str|None
    """
    return [item for item in self._available_packages(pkg_names, repo_filter)]

  def all_packages(self, pkg_names=None, repo_filter=None):
    return self.available_packages(pkg_names, repo_filter)

  def transform_baseurl_to_repoid(self, base_url):
    """
    Transforms the URL looking like proto://login:password@localhost/some/long/path to localhost_some_long_path

    :type base_url str
    :rtype str
    """
    url_proto_mask = "://"
    url_proto_pos = base_url.find(url_proto_mask)
    if url_proto_pos > 0:
      base_url = base_url[url_proto_pos+len(url_proto_mask):]

    if "@" in base_url:
      base_url = base_url.split("@", 1)[1]

    return base_url.replace("/", "_").replace(" ", "_")

  def get_available_packages_in_repos(self, repos):
    """
    Gets all (both installed and available) packages that are available at given repositories.
    :type repos resource_management.libraries.functions.repository_util.CommandRepository
    :return: installed and available packages from these repositories
    """

    filtered_packages = []
    packages = self.available_packages()
    repo_ids = []

    for repo in repos.items:
      repo_ids.append(self.transform_baseurl_to_repoid(repo.base_url))

    if repos.feat.scoped:
      Logger.info("Looking for matching packages in the following repositories: {0}".format(", ".join(repo_ids)))
      for repo_id in repo_ids:
        for package in packages:
          if repo_id in package[2]:
            filtered_packages.append(package[0])

      return filtered_packages
    else:
      Logger.info("Packages will be queried using all available repositories on the system.")

      # this is the case where the hosts are marked as sysprepped, but
      # search the repos on-system anyway.  the url specified in ambari must match the one
      # in the list file for this to work
      for repo_id in repo_ids:
        for package in packages:
          if repo_id in package[2]:
            filtered_packages.append(package[0])

      if len(filtered_packages) > 0:
        Logger.info("Found packages for repo {}".format(str(filtered_packages)))
        return filtered_packages
      else:
        return [package[0] for package in packages]

  def package_manager_configuration(self):
    """
    Reading apt configuration

    :return dict with apt properties
    """
    with shell.process_executor(self.properties.configuration_dump_cmd, error_callback=self._executor_error_handler) as output:
      configuration = list(AptParser.config_reader(output))

    return dict(configuration)

  def verify_dependencies(self):
    """
    Verify that we have no dependency issues in package manager. Dependency issues could appear because of aborted or terminated
    package installation process or invalid packages state after manual modification of packages list on the host

    :return True if no dependency issues found, False if dependency issue present
    :rtype bool
    """
    r = shell.subprocess_executor(self.properties.verify_dependency_cmd)
    pattern = re.compile("has missing dependency|E:")

    if r.code or (r.out and pattern.search(r.out)):
      err_msg = Logger.filter_text("Failed to verify package dependencies. Execution of '%s' returned %s. %s" % (self.properties.verify_dependency_cmd, r.code, r.out))
      Logger.error(err_msg)
      return False

    return True

  @replace_underscores
  def install_package(self, name, context):
    """
    Install package

    :type name str
    :type context ambari_commons.shell.RepoCallContext

    :raise ValueError if name is empty
    """
    from resource_management.core import sudo

    apt_sources_list_tmp_dir = None

    if not name:
      raise ValueError("Installation command was executed with no package name")
    elif not self._check_existence(name) or context.action_force:
      cmd = self.properties.install_cmd[context.log_output]
      copied_sources_files = []
      is_tmp_dir_created = False
      if context.use_repos:
        if 'base' in context.use_repos:
          use_repos = set([v for k, v in context.use_repos.items() if k != 'base'])
        else:
          cmd = cmd + ['-o', 'Dir::Etc::SourceList={0}'.format(self.properties.empty_file)]
          use_repos = set(context.use_repos.values())

        if use_repos:
          is_tmp_dir_created = True
          apt_sources_list_tmp_dir = tempfile.mkdtemp(suffix="-ambari-apt-sources-d")
          Logger.info("Temporary sources directory was created: {}".format(apt_sources_list_tmp_dir))

          for repo in use_repos:
            new_sources_file = os.path.join(apt_sources_list_tmp_dir, repo + '.list')
            Logger.info("Temporary sources file will be copied: {0}".format(new_sources_file))
            sudo.copy(os.path.join(self.properties.repo_definition_location, repo + '.list'), new_sources_file)
            copied_sources_files.append(new_sources_file)
          cmd = cmd + ['-o', 'Dir::Etc::SourceParts='.format(apt_sources_list_tmp_dir)]

      cmd = cmd + [name]
      Logger.info("Installing package {0} ('{1}')".format(name, shell.string_cmd_from_args_list(cmd)))
      shell.repository_manager_executor(cmd, self.properties, context, env=self.properties.install_cmd_env)

      if is_tmp_dir_created:
        for temporary_sources_file in copied_sources_files:
          Logger.info("Removing temporary sources file: {0}".format(temporary_sources_file))
          os.remove(temporary_sources_file)
        if apt_sources_list_tmp_dir:
          Logger.info("Removing temporary sources directory: {0}".format(apt_sources_list_tmp_dir))
          os.rmdir(apt_sources_list_tmp_dir)
    else:
      Logger.info("Skipping installation of existing package {0}".format(name))

  @replace_underscores
  def upgrade_package(self, name, context):
    """
    Install package

    :type name str
    :type context ambari_commons.shell.RepoCallContext

    :raise ValueError if name is empty
    """
    context.is_upgrade = True
    return self.install_package(name, context)

  @replace_underscores
  def remove_package(self, name, context, ignore_dependencies=False):
    """
    Remove package

    :type name str
    :type context ambari_commons.shell.RepoCallContext
    :type ignore_dependencies bool

    :raise ValueError if name is empty
    """
    if not name:
      raise ValueError("Installation command were executed with no package name passed")
    elif self._check_existence(name):
      cmd = self.properties.remove_cmd[context.log_output] + [name]
      Logger.info("Removing package {0} ('{1}')".format(name, shell.string_cmd_from_args_list(cmd)))
      shell.repository_manager_executor(cmd, self.properties, context)
    else:
      Logger.info("Skipping removal of non-existing package {0}".format(name))

  @replace_underscores
  def _check_existence(self, name):
    """
    For regexp names:
    If only part of packages were installed during early canceling.
    Let's say:
    1. install hbase-2-3-.*
    2. Only hbase-2-3-1234 is installed, but is not hbase-2-3-1234-regionserver yet.
    3. We cancel the apt-get

    In that case this is bug of packages we require.
    And hbase-2-3-*-regionserver should be added to metainfo.xml.

    Checking existence should never fail in such a case for hbase-2-3-.*, otherwise it
    gonna break things like removing packages and some other things.

    Note: this method SHOULD NOT use apt-get (apt.cache is using dpkg not apt). Because a lot of issues we have, when customer have
    apt-get in inconsistant state (locked, used, having invalid repo). Once packages are installed
    we should not rely on that.
    """
    # this method is more optimised than #installed_packages, as here we do not call available packages(as we do not
    # interested in repository, from where package come)
    cmd = self.properties.installed_packages_cmd + [name]

    with shell.process_executor(cmd, strategy=shell.ReaderStrategy.BufferedChunks, silent=True) as output:
      for package, version in AptParser.packages_installed_reader(output):
        return package == name

    return False


import tkinter
from tkinter import*
import random
import time
root=Tk()
#canvas = Canvas(root,width=300,height=160)
#image=imageTK.PhotoImage(Image.open("C:\\Users\\92303\\Downloads\\images.jpeg"))
#canvas.create_image(0,0,ANCHOR=NW,image=image)
#canvas.pack()
root.geometry("1600x800+0+0")
root.title("Clustering People using Scrap Data")
Tops=Frame(root,width=1600,height=50,bg="powder blue", relief=SUNKEN)
Tops.pack(side=TOP)
#f1=Frame(root,width=800,height=700,bg="powder blue",relief=SUNKEN)
#f1.pack(side=LEFT)
#f2=Frame(root,width=300,height=700,bg="powder blue",relief=SUNKEN)
#f2.pack(side=RIGHT)
#=================================Time==========================
localtime=time.asctime(time.localtime(time.time()))
#=================================Info==========================
lblInfo=Label(Tops,font=('arial',50,'bold'),text="Clustering People using Scrap Data",fg="Steel Blue",bd=10,anchor='w')
lblInfo.grid(row=0,column=0)
lblInfo=Label(Tops,font=('arial',20,'bold'),text=localtime,fg="Steel Blue",bd=10,anchor='w')
lblInfo.grid(row=1,column=0)
#===============================Buttons===========================
def star_program():
    print("start")
start_button = Button(root, text="IMPORT FILE",padx=16,pady=8,bd=16,fg="black",font=('arial',16,'bold'),width=10,bg="powder blue",command=star_program)

cancel_button = Button(root,text="CLUSTER VALUE",padx=16,pady=8,bd=16,fg="black",font=('arial',16,'bold'),width=10,bg="powder blue",command=quit)

center_button = Button(root,text="PROCESS ALGO",padx=16,pady=8,bd=16,fg="black",font=('arial',16,'bold'),width=10,bg="powder blue",command=quit)
start_button.pack(side=TOP)
cancel_button.pack(side=TOP)
center_button.pack(side=TOP)

root.mainloop();


from collections import defaultdict

from advent_of_code.basesolver import BaseSolver

class Computer:
    def __init__(self, pause_on_output=False):
        self.current_position = 0
        self.commands = defaultdict(int)

        self.current_input_position = 0
        self.inputs = []

        self.current_relative_position = 0

        self.outputs = []

        self.pause_on_output = pause_on_output

    def restart(self):
        self.current_position = 0
        self.commands = defaultdict(int)

        self.current_input_position = 0
        self.inputs = []

        self.current_relative_position = 0

        self.outputs = []

    def load_commands(self, commands):
        for i, command in enumerate(commands):
            self.commands[i] = command

    def load_inputs(self, inputs):
        self.current_input_position = 0
        self.inputs = inputs

    def change_cmd_at_pos_1_and_2(self, param1, param2):
        self.commands[1] = param1
        self.commands[2] = param2

    ADD = 1
    MULTIPLY = 2
    INPUT = 3
    OUTPUT = 4
    JUMP_IF_TRUE = 5
    JUMP_IF_FALSE = 6
    LESS_THAN = 7
    EQUALS = 8
    ADJUST_RELATIVE_POSITION = 9
    HALT = 99
    DESCRIPTION = {
        ADD: "ADD",
        MULTIPLY: "MULTIPLY",
        INPUT: "INPUT",
        OUTPUT: "OUTPUT",
        JUMP_IF_TRUE: "JUMP_IF_TRUE",
        JUMP_IF_FALSE: "JUMP_IF_FALSE",
        LESS_THAN: "LESS_THAN",
        EQUALS: "EQUALS",
        ADJUST_RELATIVE_POSITION: "ADJUST_RELATIVE_POSITION",
        HALT: "HALT",
    }

    POSITION_MODE = 0
    IMMEDIATE_MODE = 1
    RELATIVE_MODE = 2

    def read_params(self, num_of_params):
        params = []
        for i in range(1, num_of_params + 1):
            params.append(self.commands[self.current_position + i])
        return params

    def get_value_based_on_mode(self, mode, param):
        if mode == self.POSITION_MODE:
            return self.commands[param]
        elif mode == self.IMMEDIATE_MODE:
            return param
        elif mode == self.RELATIVE_MODE:
            return self.commands[self.current_relative_position + param]

    def get_save_at_based_on_mode(self, mode, param):
        save_at = param
        if mode == self.RELATIVE_MODE:
            save_at += self.current_relative_position
        return save_at

    def execute_opcode_action(self, opcode, modes):
        # print('\tOpcode: {} ({}) | Modes: {}'.format(opcode, self.DESCRIPTION[opcode], modes))
        if opcode == self.HALT:
            self.result = self.commands[0]
            # print('\tHALT')
        elif opcode == self.ADD:
            """
            Opcode 1 adds together numbers read from two positions and stores the result in a third position.
            The three integers immediately after the opcode tell you these three positions
            - the first two indicate the positions from which you should read the input values,
            and the third indicates the position at which the output should be stored.
            """
            num_of_params = 3
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])
            save_at = self.get_save_at_based_on_mode(modes[2], params[2])

            self.commands[save_at] = value0 + value1

            self.current_position += num_of_params + 1

        elif opcode == self.MULTIPLY:
            """
            Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them.
            Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.
            """
            num_of_params = 3
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])
            save_at = self.get_save_at_based_on_mode(modes[2], params[2])

            self.commands[save_at] = value0 * value1

            self.current_position += num_of_params + 1

        elif opcode == self.INPUT:
            """
            Opcode 3 takes a single integer as input and saves it to the address given by its only parameter.
            For example, the instruction 3,50 would take an input value and store it at address 50.
            """
            num_of_params = 1
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            save_at = self.get_save_at_based_on_mode(modes[0], params[0])

            self.commands[save_at] = self.inputs[self.current_input_position]
            self.current_input_position += 1

            self.current_position += num_of_params + 1

        elif opcode == self.OUTPUT:
            """
            Opcode 4 outputs the value of its only parameter.
            For example, the instruction 4,50 would output the value at address 50.
            """
            num_of_params = 1
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])

            self.outputs.append(value0)

            self.current_position += num_of_params + 1

        elif opcode == self.JUMP_IF_TRUE:
            """
            Opcode 5 is jump-if-true:
            if the first parameter is non-zero, it sets the instruction pointer to the value from the second parameter.
            Otherwise, it does nothing.
            """
            num_of_params = 2
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])

            if value0 != 0:
                self.current_position = value1
            else:
                self.current_position += num_of_params + 1

        elif opcode == self.JUMP_IF_FALSE:
            """
            Opcode 6 is jump-if-false:
            if the first parameter is zero, it sets the instruction pointer to the value from the second parameter.
            Otherwise, it does nothing.
            """
            num_of_params = 2
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])

            if value0 == 0:
                self.current_position = value1
            else:
                self.current_position += num_of_params + 1

        elif opcode == self.LESS_THAN:
            """
            Opcode 7 is less than:
            if the first parameter is less than the second parameter,
            it stores 1 in the position given by the third parameter.
            Otherwise, it stores 0.
            """
            num_of_params = 3
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])
            save_at = self.get_save_at_based_on_mode(modes[2], params[2])

            if value0 < value1:
                self.commands[save_at] = 1
            else:
                self.commands[save_at] = 0

            self.current_position += num_of_params + 1

        elif opcode == self.EQUALS:
            """
            Opcode 8 is equals:
            if the first parameter is equal to the second parameter,
            it stores 1 in the position given by the third parameter.
            Otherwise, it stores 0.
            """
            num_of_params = 3
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])
            value1 = self.get_value_based_on_mode(modes[1], params[1])
            save_at = self.get_save_at_based_on_mode(modes[2], params[2])

            if value0 == value1:
                self.commands[save_at] = 1
            else:
                self.commands[save_at] = 0

            self.current_position += num_of_params + 1

        elif opcode == self.ADJUST_RELATIVE_POSITION:
            """
            Opcode 9 adjusts the relative base by the value of its only parameter.
            The relative base increases (or decreases, if the value is negative)
            by the value of the parameter.
            """
            num_of_params = 1
            params = self.read_params(num_of_params)
            # print('\tParams: {}'.format(params))

            value0 = self.get_value_based_on_mode(modes[0], params[0])

            self.current_relative_position += value0

            self.current_position += num_of_params + 1

        else:
            print("INVALID OPCODE: {}".format(opcode))
            exit(-1)

    def extract_opcode(self, instruction):
        instruction_str = str(instruction).zfill(5)
        return int(instruction_str[-2:])

    def extract_modes(self, instruction):
        instruction_str = str(instruction).zfill(5)
        modes = [int(x) for x in instruction_str[:3]]
        modes.reverse()
        return modes

    def process_commands(self):
        while True:
            # commands_before = list(enumerate(self.commands))
            # print(commands_before)

            current_instruction = self.commands[self.current_position]
            # print('Position: {} | Instruction: {}'.format(self.current_position, current_instruction))
            current_opcode = self.extract_opcode(current_instruction)
            current_modes = self.extract_modes(current_instruction)

            self.execute_opcode_action(current_opcode, current_modes)

            if current_opcode == self.HALT:
                return self.HALT
            if current_opcode == self.OUTPUT and self.pause_on_output:
                return self.OUTPUT

            # commands_after = list(enumerate(self.commands))
            # print(set(commands_after) - set(commands_before))

class Hull:
    BLACK = 0
    WHITE = 1

    UP = "up"
    RIGHT = "right"
    DOWN = "down"
    LEFT = "left"

    TURN_LEFT = 0
    TURN_RIGHT = 1

    def __init__(self):
        self.robot_position = (0, 0)
        self.robot_looks = Hull.UP
        self.panel_colors = defaultdict(int)

    def paint_panel(self, color):
        self.panel_colors[self.robot_position] = color

    def turn_robot(self, turn):
        if (self.robot_looks == Hull.UP and turn == Hull.TURN_LEFT) or (
            self.robot_looks == Hull.DOWN and turn == Hull.TURN_RIGHT
        ):
            self.robot_looks = Hull.LEFT
        elif (self.robot_looks == Hull.UP and turn == Hull.TURN_RIGHT) or (
            self.robot_looks == Hull.DOWN and turn == Hull.TURN_LEFT
        ):
            self.robot_looks = Hull.RIGHT
        elif (self.robot_looks == Hull.RIGHT and turn == Hull.TURN_LEFT) or (
            self.robot_looks == Hull.LEFT and turn == Hull.TURN_RIGHT
        ):
            self.robot_looks = Hull.UP
        elif (self.robot_looks == Hull.RIGHT and turn == Hull.TURN_RIGHT) or (
            self.robot_looks == Hull.LEFT and turn == Hull.TURN_LEFT
        ):
            self.robot_looks = Hull.DOWN

    def move_robot(self):
        c_x = self.robot_position[0]
        c_y = self.robot_position[1]

        if self.robot_looks == Hull.UP:
            c_y += 1
        elif self.robot_looks == Hull.RIGHT:
            c_x += 1
        elif self.robot_looks == Hull.DOWN:
            c_y -= 1
        elif self.robot_looks == Hull.LEFT:
            c_x -= 1

        self.robot_position = (c_x, c_y)

    def get_max_min_x_y(self):
        min_x = [*self.panel_colors][0][0]
        min_y = [*self.panel_colors][0][1]
        max_x = [*self.panel_colors][0][0]
        max_y = [*self.panel_colors][0][1]

        for coords in [*self.panel_colors]:
            x = coords[0]
            y = coords[1]
            if x < min_x:
                min_x = x
            if y < min_y:
                min_y = y
            if x > max_x:
                max_x = x
            if y > max_y:
                max_y = y

        return min_x, min_y, max_x, max_y

    def draw(self):
        min_x, min_y, max_x, max_y = self.get_max_min_x_y()

        result = ""
        for y in reversed(list(range(min_y, max_y + 1))):
            for x in range(min_x, max_x + 1):
                result += "\u25a9" if self.panel_colors[(x, y)] else "."
            result += "\n"
        return "\n{}".format(result.strip())

def load_input(data):
    return [int(x.strip()) for x in data.split(",")]

class Y2019D11Solver(BaseSolver):
    def solve_part_a(self):
        input_list = load_input(self.data)

        computer = Computer(pause_on_output=True)
        computer.load_commands(input_list)

        hull = Hull()
        while True:
            current_color = hull.panel_colors[hull.robot_position]
            computer.load_inputs([current_color])

            res1 = computer.process_commands()
            if res1 == Computer.HALT:
                break
            res2 = computer.process_commands()
            if res2 == Computer.HALT:
                break

            color_to_paint = computer.outputs[-2]
            direction_to_turn = computer.outputs[-1]
            hull.paint_panel(color_to_paint)
            hull.turn_robot(direction_to_turn)
            hull.move_robot()

        return len(hull.panel_colors.keys())

    def solve_part_b(self):
        input_list = load_input(self.data)

        computer = Computer(pause_on_output=True)
        computer.load_commands(input_list)

        hull = Hull()
        hull.panel_colors[(0, 0)] = Hull.WHITE
        while True:
            current_color = hull.panel_colors[hull.robot_position]
            computer.load_inputs([current_color])

            res1 = computer.process_commands()
            if res1 == Computer.HALT:
                break
            res2 = computer.process_commands()
            if res2 == Computer.HALT:
                break

            color_to_paint = computer.outputs[-2]
            direction_to_turn = computer.outputs[-1]
            hull.paint_panel(color_to_paint)
            hull.turn_robot(direction_to_turn)
            hull.move_robot()

        result = hull.draw()

        return result


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

import os

from pathlib import Path
from sh import git, ErrorReturnCode_1, ErrorReturnCode_128

import pytest

paths = set()

def pytest_ignore_collect(collection_path, config):
    try:
        git("check-ignore", collection_path)
    except ErrorReturnCode_1:
        pass
    except ErrorReturnCode_128:
        if collection_path in paths:
            return True
        else:
            root = Path(config.rootdir)
            while not (root / ".gitignore").exists():
                root = root.parent
            for glob in (root / ".gitignore").read_text().split("\n"):
                glob = glob.strip()
                if glob and not glob.startswith("#"):
                    if glob.startswith("/"):
                        glob = glob.split("/")
                        paths.update(
                            set(
                                (root / glob[0]).rglob(
                                    os.sep.join(glob[1:]) if len(glob) > 1 else "*"
                                )
                            )
                        )
                    else:
                        paths.update(set(root.rglob(glob)))
            if collection_path in paths:
                return True
    else:
        return True


"""
core package documentation
"""
from sshexec import sshexec

class Core(object):
    """
    Provides core scripting capabilities for pyisac
    """
    def exec_command(self,host,username,command):
        """
        Executes a command on a remote system using SSH

        :param host: Host to run the command on (as string)
        :param username: Username for SSH connection (as string)
        :param command: Command to be run on the system (as string)

        :return: result of the command
        """
        sshcmd = sshexec(host, username, command)
        result = sshcmd.run()
        return result[0].rstrip()

    def get_node_facts(self, host, username):
        facts = {}
        kernel_version = self.exec_command(host, username, "uname -r")
        facts["kernel_version"] = kernel_version
        arch = self.exec_command(host, username, "uname -m")
        facts["arch"] = arch
        redhat_test = self.exec_command(host, username, "cat /etc/redhat-release")
        distro = "Unknown"
        if "no such file" not in redhat_test:
            distro = "RedHat"
        ubuntu_test = self.exec_command(host, username, "cat /etc/lsb-release | grep Ubuntu")
        if "Ubuntu" in ubuntu_test:
            distro = "Ubuntu"
        facts["distro"] = distro

        return facts


from django.contrib import admin
from django.conf.urls import url

from api.views import AccountView, AccountListView, ProductBuyView, WrongEndpointView

urlpatterns = [
    url('admin/', admin.site.urls),
    url(r'^api/account/$', AccountListView.as_view(), name='account-list'),
    url(r'^api/account/(?P<id>[0-9]+)/$', AccountView.as_view(), name='account'),
    url(r'^api/account/(?P<id>[0-9]+)/product_buy/(?P<price>(\d)+)/$', ProductBuyView.as_view(), name='account'),
    url(r'^api/.*', WrongEndpointView.as_view(), name='wrong-endpoint'),
]


try:
    print("1 || Compute Total Odds\n2 || Palindrome\n3 || Exit")
    input_module = int(input("Enter module number: ").strip())

    if input_module == 1:
        from computeodds import function

        user_input = int(input("\nEnter a number: ").strip())

        result = function(user_input)

        file = open("Compute_Total_Odd.txt", "w")
        file.write("Input: {}\n\nOdd Numbers: {}\n\nTotal: {}".format(result[0], result[1], result[-1]))
        file.close()

        file = open("Compute_Total_Odd.txt", "r")
        print("\n" + file.read())
        file.close()

    elif input_module == 2:
        from palindrome import function

        user_input = input("\nEnter any number or word: ").strip().lower()

        result = function(user_input)

        file = open("Palindrome.txt", "w")
        file.write("Input: {}\n\n{}\n\nThe last three characters are {}.".format(result[0],result[1],result[2]))
        file.close()

        file = open("Palindrome.txt", "r")
        print("\n" + file.read())
        file.close()

    elif input_module == 3:
        quit()

    else:
        print("\nInvalid input.")

except ValueError:
    print("\nInvalid input.")