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

# In[4]:

from __future__ import division, print_function
from env import CartPole, Physics
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import lfilter

def initialize_mdp_data(num_states):

    transition_counts = np.zeros((num_states, num_states, 2))
    transition_probs = np.ones((num_states, num_states, 2)) / num_states
    reward_counts = np.zeros((num_states, 2))
    reward = np.zeros(num_states)
    value = np.random.rand(num_states) * 0.1

    return {
        'transition_counts': transition_counts,
        'transition_probs': transition_probs,
        'reward_counts': reward_counts,
        'reward': reward,
        'value': value,
        'num_states': num_states,
    }

def choose_action(state, mdp_data):

    expect_value = mdp_data['value'].dot(mdp_data['transition_probs'][state])
    if expect_value[0] == expect_value[1]:
        return np.random.randint(2)
    else:
        return np.argmax(expect_value)

def update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, reward):

    mdp_data['transition_counts'][state, new_state, action] += 1

    if reward == -1:
        mdp_data['reward_counts'][new_state, 0] += 1

    mdp_data['reward_counts'][new_state, 1] += 1

    return

def update_mdp_transition_probs_reward(mdp_data):

    transition_counts = mdp_data['transition_counts']
    num_counts = transition_counts.sum(axis=1)
    num_states = transition_counts.shape[0]
    for i in range(num_states):
        for a in range(2):
            if  num_counts[i, a]  != 0:
                mdp_data['transition_probs'][i, :, a] = transition_counts[i, :, a] / num_counts[i, a]

    reward_counts = mdp_data['reward_counts']
    for k in range(num_states):
        sum_count = reward_counts[k, 1]
        if sum_count != 0:
            mdp_data['reward'][k] = -reward_counts[k, 0] / sum_count

    return

def update_mdp_value(mdp_data, tolerance, gamma):

    iters = 0
    transition_probs = mdp_data['transition_probs']

    while True:
        iters += 1

        value = mdp_data['value']
        new_value = mdp_data['reward'] + gamma * value.dot(transition_probs).max(axis=1)
        mdp_data['value'] = new_value

        if np.max(np.abs(value - new_value)) < tolerance:
            break

    return iters==1

def main(plot=True):
    # Seed the randomness of the simulation so this outputs the same thing each time
    seed = 0
    np.random.seed(seed)

    # Simulation parameters
    pause_time = 0.0001
    min_trial_length_to_start_display = 100
    display_started = min_trial_length_to_start_display == 0

    NUM_STATES = 163
    GAMMA = 0.995
    TOLERANCE = 0.01
    NO_LEARNING_THRESHOLD = 20

    # Time cycle of the simulation
    time = 0

    # These variables perform bookkeeping (how many cycles was the pole
    # balanced for before it fell). Useful for plotting learning curves.
    time_steps_to_failure = []
    num_failures = 0
    time_at_start_of_current_trial = 0

    # You should reach convergence well before this
    max_failures = 500

    # Initialize a cart pole
    cart_pole = CartPole(Physics())

    # Starting `state_tuple` is (0, 0, 0, 0)
    # x, x_dot, theta, theta_dot represents the actual continuous state vector
    x, x_dot, theta, theta_dot = 0.0, 0.0, 0.0, 0.0
    state_tuple = (x, x_dot, theta, theta_dot)

    # `state` is the number given to this state, you only need to consider
    # this representation of the state
    state = cart_pole.get_state(state_tuple)
    # if min_trial_length_to_start_display == 0 or display_started == 1:
    #     cart_pole.show_cart(state_tuple, pause_time)

    mdp_data = initialize_mdp_data(NUM_STATES)

    # This is the criterion to end the simulation.
    # You should change it to terminate when the previous
    # 'NO_LEARNING_THRESHOLD' consecutive value function computations all
    # converged within one value function iteration. Intuitively, it seems
    # like there will be little learning after this, so end the simulation
    # here, and say the overall algorithm has converged.

    consecutive_no_learning_trials = 0
    while consecutive_no_learning_trials < NO_LEARNING_THRESHOLD:

        action = choose_action(state, mdp_data)

        # Get the next state by simulating the dynamics
        state_tuple = cart_pole.simulate(action, state_tuple)
        # x, x_dot, theta, theta_dot = state_tuple

        # Increment simulation time
        time = time + 1

        # Get the state number corresponding to new state vector
        new_state = cart_pole.get_state(state_tuple)
        # if display_started == 1:
        #     cart_pole.show_cart(state_tuple, pause_time)

        # reward function to use - do not change this!
        if new_state == NUM_STATES - 1:
            R = -1
        else:
            R = 0

        update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, R)

        # Recompute MDP model whenever pole falls
        # Compute the value function V for the new model
        if new_state == NUM_STATES - 1:

            update_mdp_transition_probs_reward(mdp_data)

            converged_in_one_iteration = update_mdp_value(mdp_data, TOLERANCE, GAMMA)

            if converged_in_one_iteration:
                consecutive_no_learning_trials = consecutive_no_learning_trials + 1
            else:
                consecutive_no_learning_trials = 0

        # Do NOT change this code: Controls the simulation, and handles the case
        # when the pole fell and the state must be reinitialized.
        if new_state == NUM_STATES - 1:
            num_failures += 1
            if num_failures >= max_failures:
                break
            print('[INFO] Failure number {}'.format(num_failures))
            time_steps_to_failure.append(time - time_at_start_of_current_trial)
            # time_steps_to_failure[num_failures] = time - time_at_start_of_current_trial
            time_at_start_of_current_trial = time

            if time_steps_to_failure[num_failures - 1] > min_trial_length_to_start_display:
                display_started = 1

            # Reinitialize state
            # x = 0.0
            x = -1.1 + np.random.uniform() * 2.2
            x_dot, theta, theta_dot = 0.0, 0.0, 0.0
            state_tuple = (x, x_dot, theta, theta_dot)
            state = cart_pole.get_state(state_tuple)
        else:
            state = new_state

    if plot:
        # plot the learning curve (time balanced vs. trial)
        log_tstf = np.log(np.array(time_steps_to_failure))
        plt.plot(np.arange(len(time_steps_to_failure)), log_tstf, 'k')
        window = 30
        w = np.array([1/window for _ in range(window)])
        weights = lfilter(w, 1, log_tstf)
        x = np.arange(window//2, len(log_tstf) - window//2)
        plt.plot(x, weights[window:len(log_tstf)], 'r--')
        plt.xlabel('Num failures')
        plt.ylabel('Log of num steps to failure')
        plt.title('seed = {}'.format(seed))
        plt.savefig('output/control_{}.png'.format(seed))

    return np.array(time_steps_to_failure)

if __name__ == '__main__':
    main()

# In[ ]:


from tkinter import *

sc=Tk()
sc.geometry("350x400")
sc.title("Sorathiya")
sc.configure(bg="#17161b")

equation =""

def show(value):
    global equation
    equation+=value
    label_result.config(text = equation)

def clear():
    global equation
    equation = ""
    label_result.config(text = equation)

def calculat():
    global equation
    result=""
    if equation!="":
        try:
            result=eval(equation)
        except:
            result="Error"
            equation=""
    label_result.config(text = result)

label_result=Label(sc,text = "",width = 25,height = 2,font = "Arial 30")
label_result.pack()

Button(sc,text = "C",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#3697f5",command = lambda :clear()).place(x=10,y=100)
Button(sc,text = "%",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("%")).place(x=90,y=100)
Button(sc,text = "/",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("/")).place(x=170,y=100)
Button(sc,text = "*",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("*")).place(x=250,y=100)

Button(sc,text = "7",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("7")).place(x=10,y=150)
Button(sc,text = "8",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("8")).place(x=90,y=150)
Button(sc,text = "9",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("9")).place(x=170,y=150)
Button(sc,text = "-",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("-")).place(x=250,y=150)

Button(sc,text = "4",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("4")).place(x=10,y=200)
Button(sc,text = "5",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("5")).place(x=90,y=200)
Button(sc,text = "6",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("6")).place(x=170,y=200)
Button(sc,text = "+",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("+")).place(x=250,y=200)

Button(sc,text = "1",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("1")).place(x=10,y=250)
Button(sc,text = "2",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("2")).place(x=90,y=250)
Button(sc,text = "3",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("3")).place(x=170,y=250)
Button(sc,text = "=",font = "Arial 15 bold",width = 5,height = 3,bd = 2,fg = "#fff",bg = "#fe9037",command = lambda :calculat()).place(x=250,y=250)

Button(sc,text = "0",font = "Arial 15 bold",width = 11,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show("0")).place(x=15,y=300)
Button(sc,text = ".",font = "Arial 15 bold",width = 5,height = 1,bd = 2,fg = "#fff",bg = "#2a2b36",command = lambda :show(".")).place(x=170,y=300)

sc.mainloop()


import time

class Timer:
  def __init__(self):
    self.record = False
    self.ptime  = float('nan')

  def tic(self, message=None):
    if message is not None:
      print(message)
    self.record = True
    self.ptime  = time.time()

  def toc(self, quiet=False):
    if not self.record:
      print('tic is not called')
      return self.ptime

    etime = time.time() - self.ptime
    self.record = False
    self.ptime  = float('nan')
    if not quiet:
      print('Elapsed time: {:.2f} [sec]'.format(etime))
    return etime


"""
Data Sonification Class
"""

from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'

import pandas as pd
import matplotlib.pyplot as plt
from audiolazy import str2midi
from midiutil import MIDIFile
import pygame
from utils import map_value

class Sonification:
    def __init__(self, dataframe, class_name, graph = 'Line Plot'):
        self.dataframe = dataframe
        self.class_name = class_name

    def make_sonifications(self, vars = []):
        x_axis_name = vars[0]
        y_axis_name = vars[1]

        no_of_classes = self.dataframe[self.class_name].unique()

        for class_name in no_of_classes:
            y_axis = self.dataframe[self.dataframe[self.class_name] == class_name][y_axis_name].values
            x_axis = self.dataframe[self.dataframe[self.class_name] == class_name][x_axis_name].values

            n_impacts = len(x_axis)

            duration_beats = n_impacts
            bpm = 60
            y_scale = 0.5
            note_names = ['C1','C2','G2', 'C3','E3','G3','A3','B3', 'D4','E4','G4','A4','B4', 'D5','E5','G5','A5','B5','D6','E6','F#6','G6','A6']
            vel_min,vel_max = 35, 127

            t_data = map_value(x_axis, min(x_axis), max(x_axis), duration_beats, 0)
            duration_sec = max(t_data)*60/bpm

            y_data = map_value(y_axis, min(y_axis), max(y_axis), 0, 1)
            y_data = y_data**y_scale

            note_midis = [str2midi(n) for n in note_names]
            n_notes = len(note_midis)

            midi_data = []
            vel_data = []
            for i in range(n_impacts):
                note_index = round(map_value(y_data[i], 0, 1, n_notes-1, 0))
                midi_data.append(note_midis[note_index])

                note_velocity = round(map_value(y_data[i], 0, 1, vel_min, vel_max))
                vel_data.append(note_velocity)

            my_midi_file = MIDIFile(1)
            my_midi_file.addTempo(track=0, time=0, tempo=bpm)

            for i in range(n_impacts):
                my_midi_file.addNote(track=0, channel=0, pitch=midi_data[i], time=t_data[i] , duration=2, volume=vel_data[i])

            filename = class_name
            with open(filename + '.mid', "wb") as f:
                my_midi_file.writeFile(f)

        return no_of_classes

    def play_plot(self, class_name):
        pygame.init()
        pygame.mixer.music.load(class_name + '.mid')
        pygame.mixer.music.play()

        while pygame.mixer.music.get_busy():
            pygame.time.wait(1000)


from keras import backend as K
from keras.callbacks import EarlyStopping
from keras.datasets import cifar10
from keras.layers import BatchNormalization, Conv2D, Dense, Dropout, Flatten, Input, MaxPool2D
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical

def preprocess(X):
    return X.astype('float32') / 255 * 2 - 1

class_num = 10
batch_size = 128
epochs = 300

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
X_train, X_test = preprocess(X_train), preprocess(X_test)
y_train, y_test = to_categorical(y_train), to_categorical(y_test)
_, img_rows, img_cols, channels = X_train.shape

if K.image_data_format() == 'channels_first':
    X_train = X_train.reshape(X_train.shape[0], channels, img_rows, img_cols)
    X_test = X_test.reshape(X_test.shape[0], channels, img_rows, img_cols)
else:
    X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, channels)
    X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, channels)

def gen_model():
    # refer to http://torch.ch/blog/2015/07/30/cifar.html
    img_input = Input(shape=(img_rows, img_cols, channels))

    h = img_input

    h = Conv2D(64, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.3)(h)
    h = Conv2D(64, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = MaxPool2D((2, 2), strides=(2, 2))(h)

    h = Conv2D(128, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(128, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = MaxPool2D((2, 2), strides=(2, 2))(h)

    h = Conv2D(256, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(256, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(256, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = MaxPool2D((2, 2), strides=(2, 2))(h)

    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = MaxPool2D((2, 2), strides=(2, 2))(h)

    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = Dropout(0.4)(h)
    h = Conv2D(512, (3, 3), activation='relu', padding='same')(h)
    h = BatchNormalization()(h)
    h = MaxPool2D((2, 2), strides=(2, 2))(h)

    h = Flatten()(h)

    h = Dropout(0.5)(h)
    h = Dense(512, activation='relu')(h)
    h = BatchNormalization()(h)

    h = Dropout(0.5)(h)
    h = Dense(class_num, activation='softmax')(h)

    model = Model(img_input, h)
    return model

model = gen_model()
model.compile(
    loss='categorical_crossentropy',
    optimizer='rmsprop',
    metrics=['accuracy'],
)

datagen = ImageDataGenerator(
    zoom_range=0.05,
    width_shift_range=0.1,
    height_shift_range=0.1,
    horizontal_flip=True,
)

datagen.fit(X_train)

model.fit_generator(
    datagen.flow(X_train, y_train, batch_size=batch_size),
    steps_per_epoch=X_train.shape[0] // batch_size,
    epochs=epochs,
    validation_data=(X_test, y_test),
    callbacks=[
        EarlyStopping(patience=20),
    ],
)

score = model.evaluate(X_test, y_test)

print('test accuracy: ', score[1])

# re-compile model
# not to save optimizer variables in model data
model.compile(
    loss='categorical_crossentropy',
    optimizer='rmsprop',
    metrics=['accuracy'],
)
model.save('model_raw.h5')


def DoThing(numeroExpediente):
    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions
    from selenium.webdriver.common.by import By
    import time
    import pandas as pd

    options = webdriver.ChromeOptions()
    options.add_argument('--start-maximized')
    options.add_argument('--disable-extensions')

    driver_path = 'C:\\Users\\Menem Lo Hizo\\Desktop\\Scripts\\Scraping\\chromedriver.exe'

    driver = webdriver.Chrome(driver_path, chrome_options=options)

    driver.get('https://www.justiciacordoba.gob.ar/marcopolo/menu/index.aspx')

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, 'txtUserName'))).send_keys('#')

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, 'txtUserContrasenia'))).send_keys('#')

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, 'cmdLogin'))).click()

    driver.get('https://www.justiciacordoba.gob.ar/marcopolo/_Expedientes/ExpedientesAlta.aspx')

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, 'input#txtNumeroExpediente'))).send_keys(numeroExpediente)

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.ID, 'btnBuscar'))).click()

    WebDriverWait(driver, 10).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, 'img#grdExpedientes_Row_0_column7_control_0'))).click()

    driver.implicitly_wait(10)
    texto_columnas = driver.find_element_by_xpath('//*[@id="grdOperaciones_Row_0_column3"]/div')
    texto_columnas = texto_columnas.text

    print(texto_columnas)
    input("dsadsa")

def main():
    DoThing('6798347')

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ("sp_app", "0033_changelogging_until"),
    ]

    operations = [
        migrations.CreateModel(
            name="WardType",
            fields=[
                (
                    "id",
                    models.AutoField(
                        verbose_name="ID",
                        serialize=False,
                        auto_created=True,
                        primary_key=True,
                    ),
                ),
                ("name", models.CharField(max_length=20, verbose_name="Name")),
                ("callshift", models.BooleanField(verbose_name="Call shift")),
                (
                    "company",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="ward_types",
                        to="sp_app.Company",
                    ),
                ),
            ],
        ),
        migrations.AlterField(
            model_name="changelogging",
            name="continued",
            field=models.BooleanField(
                default=True,
                help_text="If False the change is valid for one day.",
            ),
        ),
        migrations.AlterField(
            model_name="changelogging",
            name="until",
            field=models.DateField(
                help_text="The last day the change is valid. Can be blank.",
                null=True,
                blank=True,
            ),
        ),
        migrations.AddField(
            model_name="ward",
            name="ward_type",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="wards",
                default=None,
                to="sp_app.WardType",
                null=True,
            ),
        ),
    ]


import sys
input = sys.stdin.readline
from collections import deque

dix = {
    '-': [(0, 1), (0, -1)],
    '|': [(-1, 0), (1, 0)],
    '+': [(0, 1), (0, -1), (1, 0), (-1, 0)]
}

def bfs():
    visited = [[0 for _ in range(M)] for _ in range(N)]
    visited[0][0] = 1
    q = deque()
    q.append((0, 0))
    while q:
        x, y = q.popleft()
        for dx, dy in dix.get(pan[x][y]):
            nx, ny = x + dx, y + dy
            if N > nx >= 0 and M > ny >= 0 and not visited[nx][ny] and pan[nx][ny] != '*':
                if nx == N-1 and ny == M-1:
                    return visited[x][y]+1
                visited[nx][ny] = visited[x][y] + 1
                q.append((nx, ny))
    return -1

for _ in range(int(input().strip())):
    N = int(input().strip())
    M = int(input().strip())
    pan = [list(input().strip()) for _ in range(N)]
    if N == M == 1:
        print(1)
        continue
    print(bfs())


import pygame
import random
SCREEN_RECT = pygame.Rect(0,0,480,700)
CREAT_ENEMY_EVENT = pygame.USEREVENT
HERO_FIRE_EVENT = pygame.USEREVENT + 1

class GameSprite(pygame.sprite.Sprite):

	def __init__(self,image_name,speed=1):
		super().__init__()
		self.image = pygame.image.load(image_name)
		self.rect = self.image.get_rect()
		self.speed = speed

	def update(self):
		self.rect.y += self.speed

class Background(GameSprite):

	def update(self):
		super().update()
		if self.rect.y >= SCREEN_RECT.height:
			self.rect.y = -self.rect.height

class Enemy(GameSprite):

	def __init__(self):
		super().__init__("./images/enemy1.png")
		self.speed = random.randint(1, 3)
		self.rect.bottom = 0
		max_x = SCREEN_RECT.width - self.rect.width
		self.rect.x = random.randint(0, max_x)

	def update(self):
		super().update()
		if self.rect.y >= SCREEN_RECT.height:
			print("敌机飞出屏障")
			self.kill()

	def __del__(self):
		print("敌机挂掉了%s"%self.rect)

class Hero(GameSprite):

	def __init__(self):
		super().__init__("./images/me1.png",0)

		self.rect.centerx = SCREEN_RECT.centerx
		self.rect.bottom = SCREEN_RECT.bottom - 120

		self.bullets_group = pygame.sprite.Group()

		self.up = False
		self.down = False
		self.left = False
		self.right = False

	def update(self):

		if self.up == True:
			self.rect.y -= 5
		elif self.down == True:
			self.rect.y += 5
		elif self.left == True:
			self.rect.x -= 5
		elif self.right == True:
			self.rect.x += 5

		self.rect.x += self.speed
		if self.rect.left < 0:
			self.rect.left = 0
		elif self.rect.right > SCREEN_RECT.right:
			self.rect.right = SCREEN_RECT.right
		elif self.rect.top < 0:
			self.rect.top = 0
		elif self.rect.bottom > SCREEN_RECT.bottom:
			self.rect.bottom = SCREEN_RECT.bottom

	def fire(self):
		print("发射子弹")

		for i in (1,2,3):
			bullet = Bullet()
			bullet.rect.bottom = self.rect.y - 20*i
			bullet.rect.centerx = self.rect.centerx
			self.bullets_group.add(bullet)
'''
class Hero2(GameSprite):
	def __init__(self):
		super().__init__("./images/me2.png",0)
		self.rect.centerx = SCREEN_RECT.centerx
		self.rect.bottom = SCREEN_RECT.bottom - 240

		self.bullets_group = pygame.sprite.Group()

		self.w = False
		self.s = False
		self.a = False
		self.d = False

	def update(self):
		if self.w == True:
			self.rect.y -= 5
		elif self.s == True:
			self.rect.y += 5
		elif self.a == True:
			self.rect.x -= 5
		elif self.d == True:
			self.rect.x += 5

		self.rect.x += self.speed
		if self.rect.left < 0:
			self.rect.left = 0
		elif self.rect.right > SCREEN_RECT.right:
			self.rect.right = SCREEN_RECT.right
		elif self.rect.top < 0:
			self.rect.top = 0
		elif self.rect.bottom > SCREEN_RECT.bottom:
			self.rect.bottom = SCREEN_RECT.bottom

	def fire(self):
		print("发射子弹")

		for i in (1,2,3):
			bullet = Bullet()
			bullet.rect.bottom = self.rect.y - 20*i
			bullet.rect.centerx = self.rect.centerx
			self.bullets_group.add(bullet)
'''

class Bullet(GameSprite):

	def __init__(self):
		super().__init__("./images/bullet1.png",-5)
		#super().__init__("./images/bullet2.png",-5)

	def update(self):
		super().update()

		if self.rect.bottom < 0:
			self.kill()


from clustering import KMeans_Clustering
from utils.logger import App_Logger
from utils.main_utils import Main_Utils

class Run:
    """
    Description :   This class is used for running the clustering service

    Version     :   1.2
    Revisions   :   Moved to setup to cloud
    """

    def __init__(self):
        self.utils = Main_Utils()

        self.log_writer = App_Logger()

        self.kmeans_op = KMeans_Clustering("clustering")

        self.class_name = self.__class__.__name__

    def run_clustering(self):
        """
        Method Name :   run_clustering
        Description :   This method performs the clustering operation on training data

        Output      :   An elbow plot figure saved to input files container
        On Failure  :   Write an exception log and then raise an exception

        Version     :   1.2
        Revisions   :   Moved to setup to cloud
        """
        method_name = self.run_clustering.__name__

        self.log_writer.start_log("start", self.class_name, method_name, "clustering")

        try:
            X = self.utils.get_training_data("features", "clustering")

            self.log_writer.log(
                "Read the features file for training from feature store container",
                "clustering",
            )

            Y = self.utils.get_training_data("targets", "clustering")

            self.log_writer.log(
                "Read the labels for training from feature store container",
                "clustering",
            )

            num_clusters = self.kmeans_op.draw_elbow_plot(X)

            X = self.kmeans_op.create_clusters(X, num_clusters)

            X["Labels"] = Y

            list_of_clusters = X["Cluster"].unique()

            self.log_writer.log(
                f"Got the {list_of_clusters} unique clusters", "clustering"
            )

            for i in list_of_clusters:
                cluster_data = X[X["Cluster"] == i]

                cluster_features = cluster_data.drop(["Labels", "Cluster"], axis=1)

                cluster_label = cluster_data["Labels"]

                self.utils.upload_cluster_data(
                    i, cluster_features, "clustering", key="features"
                )

                self.utils.upload_cluster_data(
                    i, cluster_label, "clustering", key="targets"
                )

            self.log_writer.start_log(
                "exit", self.class_name, method_name, "clustering"
            )

        except Exception as e:
            self.log_writer.exception_log(e, self.class_name, method_name, "clustering")

if __name__ == "__main__":
    try:
        run = Run()

        run.run_clustering()

    except Exception as e:
        raise e

    finally:
        utils = Main_Utils()

        utils.upload_logs()


import time
from rtree import index

class Point:
	def __init__(self,x,y):
		self.x = x
		self.y = y

class Polygon:
	def __init__(self,points):
		self.points = points
		self.nvert = len(points)

	def contains(self,pt):
		firstX = self.points[0].x
		firstY = self.points[0].y
		testx = pt.x
		testy = pt.y
		c = False
		j = 0
		i = 1
		nvert = self.nvert
		while (i < nvert) :
			vi = self.points[i]
			vj = self.points[j]

			if(((vi.y > testy) != (vj.y > testy)) and (testx < (vj.x - vi.x) * (testy - vi.y) / (vj.y - vi.y) + vi.x)):
				c = not(c)

			if(vi.x == firstX and vi.y == firstY):
				i = i + 1
				if (i < nvert):
					vi = self.points[i];
					firstX = vi.x;
					firstY = vi.y;
			j = i
			i = i + 1
		return c

def simplePolygonTest(poly, pt):
	# print("Point in polygon test")
	# Create a simple polygon
	# poly = Polygon([Point(0.0, 0.0),Point(0.0, 4.0),Point(3.0, 4.0),Point(3.0, 0.0)])

	# Create two points
	# pt1 = Point(1,1)
	# pt2 = Point(4,1)

	# Test if the polygon contains the two points
	if poly.contains(pt):
		# print("Point ("+ str(pt.x)+", "+str(pt.y)+") is within the polygon")
		return True
	else:
		return False
		# print("Point ("+ str(pt.x)+", "+str(pt.y)+") is outside the polygon")

def simpleRTree_insert(pts):
	# print("R-tree test")
	idx = index.Index()

	for i, pt in enumerate(pts):
		# Insert the points into the R-tree index
		idx.insert(i+1,(pt.x,pt.y,pt.x,pt.y))
	return idx

def intersection(idx, leftBottom, rightTop):
	results = list(idx.intersection((leftBottom.x,leftBottom.y,rightTop.x,rightTop.y)))
	# print "time to calculate points using R-tree:", time.time() - t1
	# print("Query result:")
	return len(results)

# simplePolygonTest()
# simpleRTree()


from tkinter import *
from tkinter import ttk
import tkinter.font as tkfont
import pandas as pd
from DataModifier import DataModifier

# Class in charge of importing the data given the user inputs
class DataImporter:
    def __init__(self, root):
        self.__root = root
        self.__root.geometry('700x275')

        # Font objects to be used on the section
        self.__label_font = tkfont.Font(family="Times New Roman", size=12)
        self.__button_font = tkfont.Font(family="Times New Roman", size=10)
        self.__title_font = tkfont.Font(family="Times New Roman", size=14)

        # Data frame that will contain the loaded data
        self.__data_set = pd.DataFrame()
        self.__project_title = 'Generic project'

        # Main frame of the Data importer (Step 1)
        self.__step1_frame = Frame(self.__root)

        # First section of the page - Project description and name
        self.__wrapper1 = LabelFrame(self.__step1_frame, text='Welcome to the ML APP',
                                     font=tkfont.Font(family="Times New Roman", size=16))

        description = 'We are here to assist you explore and analyze your data. ' + \
                      'Our Machine Learning models will help you out.'
        description_label = Label(self.__wrapper1, text=description, font=self.__label_font)
        project_label = Label(self.__wrapper1, text='What is your project name?', font=self.__label_font)
        self.__project_entry = Entry(self.__wrapper1, width=50)

        # Packing of elements into the first section
        description_label.pack(anchor=W, padx=3)
        project_label.pack(side=LEFT, anchor=W, padx=3, pady=10)
        self.__project_entry.pack(side=LEFT, padx=3)

        # Second section of the page - Data set importer
        self.__wrapper2 = LabelFrame(self.__step1_frame, text='Step 1: Let\'s import the data:', font=self.__title_font)

        frame1 = Frame(self.__wrapper2)
        file_path_label = Label(frame1, text='Filepath:', font=self.__label_font)
        self.file_path_entry = Entry(frame1, width=75)
        self.file_path_entry.bind("<KeyRelease-Return>", self.load_data)

        delimiter_label = Label(frame1, text='Delimiter: ', font=self.__label_font)
        self.delimiter_combo = ttk.Combobox(frame1, width=3)
        self.delimiter_combo.state(["readonly"])
        self.delimiter_combo["values"] = [",", ";", ":", "|", "\\t"]
        self.delimiter_combo.set(",")

        # Importing options like header column and duplicate removal
        option_label = Label(self.__wrapper2, text='Options:', font=self.__label_font)
        self.option1_var, self.option2_var = IntVar(), IntVar()
        option_button1 = Checkbutton(self.__wrapper2, text="Data has headers",
                                     font=self.__button_font, variable=self.option1_var)
        option_button2 = Checkbutton(self.__wrapper2, text="Remove duplicates",
                                     font=self.__button_font, variable=self.option2_var)
        load_button = Button(self.__wrapper2, text='Load Data', font=self.__button_font, width=14,
                             command=self.load_data)

        # Packing of elements into the second section
        file_path_label.pack(side=LEFT, padx=3, pady=5)
        self.file_path_entry.pack(side=LEFT, padx=3)
        delimiter_label.pack(side=LEFT, padx=3)
        self.delimiter_combo.pack(side=LEFT)

        frame1.pack(side=TOP, anchor=W)
        option_label.pack(side=LEFT, padx=2, pady=5)
        option_button1.pack(side=LEFT)
        option_button2.pack(side=LEFT)
        load_button.pack(side=RIGHT, padx=21)

        # Third section of the page - Data set row sample
        self.__wrapper3 = LabelFrame(self.__step1_frame, text='Experiment dataset: ', font=self.__title_font)

        data_label = Label(self.__wrapper3, text='No data found', font=self.__label_font)

        # Packing of elements into the section
        data_label.pack(anchor=W, padx=3)

        # Packing of elements into step1_frame
        self.__wrapper1.pack(fill='x', expand='no', padx=20, pady=5)
        self.__wrapper2.pack(fill='x', expand='no', padx=20, pady=5)
        self.__wrapper3.pack(fill='both', expand='yes', padx=20, pady=5)

    def load_data(self, event=None):
        # Reset data set
        self.__data_set = pd.DataFrame()

        # Get importing set up variables
        file_path = self.file_path_entry.get()
        str_separator = self.delimiter_combo.get()
        int_header = self.option1_var.get()
        int_duplicates = self.option2_var.get()

        # Check if a title is in the project name entry box
        if len(str(self.__project_entry.get())) > 0:
            self.__project_title = str(self.__project_entry.get())

        # Check if a success/error message is packed
        if len(self.__step1_frame.pack_slaves()) == 4:
            self.__step1_frame.pack_slaves()[-1].destroy()
        if len(self.__step1_frame.pack_slaves()) == 5:
            self.__step1_frame.pack_slaves()[-1].destroy()
            self.__step1_frame.pack_slaves()[-1].destroy()

        try:
            self.__root.geometry('700x440')

            # Check if the header option was selected
            if int_header == 1:
                int_header = 0
            else:
                int_header = None

            # Load the file on the data set variable
            self.__data_set = pd.read_table(file_path, sep=str_separator, header=int_header)

            # Check if the remove duplicate option was selected
            if int_duplicates == 1:
                self.__data_set = self.__data_set.drop_duplicates()

            # Getting column names and its width
            columns, col_width = list(self.__data_set.columns), []
            for col in columns:
                width = self.__data_set.head()[col].astype('str').str.len().max()
                if width >= len(str(col)):
                    col_width.append(width * 6 + 15)
                else:
                    col_width.append(len(str(col)) * 6 + 25)

            # Create table widget to show the first 5 rows of the data set
            data_table = ttk.Treeview(self.__wrapper3, columns=tuple(columns), show="headings", height=5)

            rows = self.__data_set.head().values
            for row in rows:
                data_table.insert('', 'end', values=tuple(row))

            for i, col in enumerate(columns):
                data_table.heading(i, text=col, anchor=W)
                data_table.column(col, width=col_width[i], stretch=NO, anchor=W)

            hsb = ttk.Scrollbar(self.__wrapper3, orient="horizontal", command=data_table.xview)
            data_table.configure(xscrollcommand=hsb.set)

            rows, columns = self.__data_set.shape[0], self.__data_set.shape[1]

            # Create success message
            text = '*' + str(columns) + ' columns with ' + str(rows) + ' rows were loaded successfully'
            success_label = Label(self.__step1_frame, text=text, font=self.__label_font)

            next_button = Button(self.__step1_frame, text='Next step', font=self.__button_font,
                                 command=self.unpack_frame, width=14)

            for element in self.__wrapper3.pack_slaves():
                element.destroy()

            # Packing of elements into the third section
            data_table.pack(padx=5, anchor=W)
            hsb.pack(fill='x', padx=5, pady=5)
            success_label.pack(side=LEFT, anchor=W, padx=20, pady=5)
            next_button.pack(side=RIGHT, padx=45)

        except Exception:
            self.__root.geometry('700x300')
            for element in self.__wrapper3.pack_slaves():
                element.destroy()

            # Create error message
            data_label = Label(self.__wrapper3, text='No data found', font=self.__label_font)
            data_label.pack(anchor=W, padx=3)
            error_label = Label(self.__step1_frame, text='Error: please provide a valid file path or delimiter',
                                font=self.__label_font, fg='red')
            error_label.pack(side=LEFT, anchor=W, padx=20, pady=5)

    def pack_frame(self):
        # Pack the data importer main frame
        self.__step1_frame.pack(fill='both')

    def unpack_frame(self):
        # Check if a title is in the project name entry box
        if len(str(self.__project_entry.get())) > 0:
            self.__project_title = str(self.__project_entry.get())

        # Unpack the data importer main frame
        self.__step1_frame.pack_forget()

        # Call the next step class (Data modifier)
        DataModifier(self.__root, self.__data_set, self.__project_title,  self.__step1_frame).pack_frame()


"""
    Cookies调度整理所有功能
date: 18-10-21 上午11:30
"""
import multiprocessing

import 爬虫.Cookies池.Cookies池_生成模块 as Generator
import 爬虫.Cookies池.Cookies池_检测模块 as Tester
import 爬虫.Cookies池.Cookies池_接口模块 as Apier

# 周期
CYCLE = 20
# 检测模块开关
TESTER_ENABLED = True
# 获取模块开关 -- 一般第一次获取Cookies即可, 过时时间不会很短
GETTER_ENABLED = True
# 接口模块开关
API_ENABLED = True

class Scheduler(object):
    """
        调度整理Cookies池中基本模块的所有功能 -- 多进程
    因为Cookies的时效较长, 一般需要只需要循环数据库数据一次即可, 不用死循环数据库数据
    """

    @staticmethod
    def schedule_generator():
        """
            调度 Generator
        :return:
        """
        while True:
            Generator.main(CYCLE)

    @staticmethod
    def schedule_tester():
        """
            调度 Tester
        :return:
        """
        while True:
            Tester.main(CYCLE)

    @staticmethod
    def schedule_apier():
        """
            调度 Apier
        :return:
        """
        Apier.start_flask()

    def run(self):
        """
            运行调度
        :return:
        """
        # 进程池
        pool = multiprocessing.Pool()
        # 获取模块
        if GETTER_ENABLED:
            # 开启进程 指向 Generator
            # generator_process = Process(target=self.schedule_generator)
            # 开启进程
            # generator_process.start()

            # 添加进程
            pool.apply_async(self.schedule_generator)
        # 检测模块
        if TESTER_ENABLED:
            # 开启进程 指向 Tester
            # tester_process = Process(target=self.schedule_tester)
            # 开启进程
            # tester_process.start()

            # 添加进程
            pool.apply_async(self.schedule_tester)
        # 接口模块
        if API_ENABLED:
            # 开启进程 指向 Apier
            # api_process = Process(target=self.schedule_apier)
            # 开启进程
            # api_process.start()

            # 添加进程
            pool.apply_async(self.schedule_apier)
        # 关闭进程
        pool.close()
        # 阻塞进程 -- 等待所有进程关闭
        pool.join()

if __name__ == '__main__':
    # 开始调度
    Scheduler().run()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from captcha.models import CaptchaStore
from django.db.models import Q
from django.http import JsonResponse
from django.utils import timezone

from Account.models import User, PhoneCaptcha, EmailCaptcha
from Dic.models import CoinType
from .exceptions import *
from .models import BalanceWithDraw, CoinTypeProperty

def fail(code=10001, message='请求参数格式错误'):
    return JsonResponse({'result': False, 'code': code, 'msg': message})

def success(data=None, **kwargs):
    if data is None:
        return JsonResponse({'result': True, 'data': {'status': 1}})
    else:
        response = dict({'result': True, 'data': data}, **kwargs)
        return JsonResponse(response)

def check_coin_type(coin_type):
    try:
        ct = CoinType.objects.get(id=coin_type)
        return ct.code
    except:
        raise CoinTypeNotFoundException(code=10033, message='找不到此币种，请确认币种信息')

def check_captcha(key, value):
    if value:
        CaptchaStore.remove_expired()
        try:
            CaptchaStore.objects.get(response=value, hashkey=key,
                                     expiration__gt=timezone.now()).delete()
        except CaptchaStore.DoesNotExist as e:
            raise CaptchaFailException(code=10007, message='验证码校验失败')
    else:
        raise CaptchaFailException(code=10008, message='验证码不能为空')

def check_phone_captcha(phone_number, captcha):
    if not User.objects.filter(phone_number=phone_number, is_phone_verified=True).exists():
        raise PhoneCaptchaFailException(code=10019, message='手机号码未注册或未通过认证')

    if captcha:
        PhoneCaptcha.remove_expired()
        try:
            PhoneCaptcha.objects.get(response=captcha,
                                     phone_number=phone_number,
                                     expiration__gt=timezone.now()).delete()
        except PhoneCaptcha.DoesNotExist:
            raise PhoneCaptchaFailException(code=10007, message='验证码校验失败')
    else:
        raise PhoneCaptchaFailException(code=10008, message='验证码不能为空')

def check_email_captcha(email, captcha):
    if not User.objects.filter(email=email, is_email_verified=True).exists():
        raise EmailCaptchaFailException(code=10019, message='电子邮件未注册或未通过认证')

    if captcha:
        EmailCaptcha.remove_expired()
        try:
            EmailCaptcha.objects.get(response=captcha,
                                     email=email,
                                     expiration__gt=timezone.now()).delete()
        except EmailCaptcha.DoesNotExist:
            raise EmailCaptchaFailException(code=10007, message='验证码校验失败')
    else:
        raise EmailCaptchaFailException(code=10008, message='验证码不能为空')

def check_withdraw_upper_limit(user, coin_type, amount):
    time_range = (timezone.now().date(), timezone.now())
    status_not = 14
    AMOUNTCOINTYPELIMIT = dict([(p.coin_type, p.day_limit) for p in CoinTypeProperty.objects.all()])
    bwds = BalanceWithDraw.objects.filter(
        address__user__id=user.id,
        address__coin_type=coin_type,
        create_time__range=time_range
    ).filter(~Q(status=status_not))
    if not len(bwds):
        return
    amount_sum = 0
    for bwd in bwds:
        amount_sum += bwd.amount
    if amount_sum + amount > AMOUNTCOINTYPELIMIT[coin_type]:
        raise AmountExceededLimitException(code=10073, message='今日提币金额已达上限')


class Solution:
    def reverseDLL(self, head):
        #return head after reversing
        if head is None or head.next is None:
            return head
        temp=None
        curr=head
        forward=head
        while forward:
            forward=curr.next
            curr.next=temp
            curr.prev=forward
            temp=curr
            curr=forward
        return temp

GeekForGeek/Problem Of The Day/Reverse a Doubly Linked List.py


from __future__ import annotations
from time import perf_counter
from typing import Any, Dict
from uuid import uuid4

from traffic_agent.sumo import Simulation

MAX_ALLOWED_STEPS = 5000
PRINT_EVERY = 250
# MAX_ALLOWED_STEPS = 100 # For testing

class TrafficAgent():

    def __init__(
        self,
    ):
        self._id = uuid4()

    def execute(self, simulation: Simulation) -> Dict[str, float]:
        steps = 0
        simulation_times = 0.0
        agent_times = 0.0
        while not simulation.complete():
            steps += 1
            if steps % PRINT_EVERY == 0:
                print(f"Step {steps}")
                print(f"Average of {simulation_times/PRINT_EVERY}s per simulation step and {agent_times/PRINT_EVERY}s per agent step")
                simulation_times = 0.0
                agent_times = 0.0
            if steps >= MAX_ALLOWED_STEPS:
                print(f"Exceeded max steps allowed - {MAX_ALLOWED_STEPS}")
                break
            start_simulation = perf_counter()
            simulation.step()
            end_simulation = perf_counter()
            self.step(simulation)
            end_agent = perf_counter()

            simulation_times += end_simulation - start_simulation
            agent_times += end_agent - end_simulation

        simulation.stop()
        stats = simulation.get_stats()
        print("STATS", stats)
        simulation.shutdown()

        return stats

    def step(self, simulation: Simulation):
        raise NotImplemented

    def __eq__(self, other: TrafficAgent) -> bool:
        if other is None:
            return False
        return self._id == other._id

    def __le__(self, other: TrafficAgent) -> bool:
        if other is None:
            return False
        return self._id < other._id


import sys
import asyncio
import time

from bleak import BleakClient

ADDRESS = "A1379F49-AA6C-D07E-5B6B-C7971F54AC85"
GENERAL_CHAR = "0000ee02-0000-1000-8000-00805f9b34fb"
STEP = 16
DELAY = 42

def toRGB(c, a):
    return bytearray([0x69, 0x96, 0x5, 0x2, c[0], c[1], c[2], a])

def calcTime(s):
    time_obj = time.gmtime(s)
    return time.strftime("%H:%M:%S", time_obj)

async def main(address):
    print("ok wait")
    async with BleakClient(address) as client:
        total = STEP * DELAY
        print("seconds: " + str(total))
        for i in range(STEP, -1, -1):
            color = [i, 0, round(i/2)]
            alpha = 0
            converted = toRGB(color, alpha)
            print(color)
            await client.write_gatt_char(GENERAL_CHAR, converted)
            print("SET ok: " + str(i))
            for j in range(DELAY, 0, -1):
                total = total - 1
                print("\r" + str(j) + "s until next jump ( " + calcTime(total) + " til finish)               ", end="")
                time.sleep(1)

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1] if len(sys.argv) == 2 else ADDRESS))


# Wack.py
# Whack-a-mole game using pygame

import pygame, random, sys, time
from pygame.locals import *
from pygame.font import *

pygame.init()

# some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
DARKGRAY = (47, 79, 79)

RED = (255, 0, 0)
GREEN = (0, 255, 0)
DARKGREEN = (0, 155, 0)
BLUE = (0, 0, 255)

WINDOWWIDTH = 1547
WINDOWHEIGHT = 1000
WALDOWIDTH = 30
WALDOHEIGHT = 50
CURSORHEIGHT = 32
CURSORWIDTH = 32
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
points = 0
BASICFONTSIZE = 40
ENDFONTSIZE = 160
BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)
ENDFONT = pygame.font.Font('freesansbold.ttf', ENDFONTSIZE)
ENDSURF = ENDFONT.render('GAME OVER', True, RED)
soundEffect = pygame.mixer.Sound('ha-got-eeem.wav')
FPS = 60

background = pygame.transform.scale(pygame.image.load("background.jpg"), (WINDOWWIDTH, WINDOWHEIGHT))

def main():
    global startTime, searchTime, wack, cursor, FPSCLOCK
    FPSCLOCK = pygame.time.Clock()
    startTime = time.time()
    searchTime = 60
    wack = Waldo()
    cursor = MagnifyingGlass()
    pygame.display.set_caption('Wack')
    isPlaying = True
    pygame.mouse.set_visible(False)

    while True:

        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if isPlaying:
                if event.type == MOUSEMOTION:
                    cursor.moveGlass(event.pos)
                if event.type == MOUSEBUTTONUP:
                    if wack.waldoRect.colliderect(cursor.cursorRect):
                        wack.reincarnate()

        if( time.time() - startTime>= searchTime):
            isPlaying = False
            DISPLAYSURF.blit(ENDSURF, (325, 400))

        if(isPlaying):
            updateScreen()
            updatePoints()
            updateTime()
        FPSCLOCK.tick(FPS)
        pygame.display.update()

class Waldo():

    def __init__(self):
        self.waldoImage = pygame.transform.scale(pygame.image.load("waldo.png"), (WALDOWIDTH, WALDOHEIGHT))
        self.waldoRect = self.waldoImage.get_rect()
        self.xpos = random.randrange(WINDOWWIDTH - WALDOWIDTH)
        self.ypos = random.randrange(100, WINDOWHEIGHT - WALDOHEIGHT)
        self.waldoRect.topleft = (self.xpos, self.ypos)

    def reincarnate(self):
        resetSearch()
        self.xpos = random.randrange(WINDOWWIDTH - WALDOWIDTH)
        self.ypos = random.randrange(WINDOWHEIGHT - WALDOHEIGHT)
        self.waldoRect.topleft = (self.xpos, self.ypos)
        soundEffect.play()

class MagnifyingGlass():

    def __init__(self):
        self.glassImg = pygame.transform.scale(pygame.image.load("glass.png"), (CURSORWIDTH, CURSORHEIGHT))
        self.cursorRect = self.glassImg.get_rect()

    def moveGlass(self, center):
        self.cursorRect.center = center

def resetSearch():
    global points, startTime, searchTime
    points += 1
    startTime = time.time()
    if (points > 20):
        searchTime = 15
    elif (points > 15):
        searchTime = 20
    elif (points > 10):
        searchTime = 30
    elif (points > 5):
        searchTime = 45
    else:
        searchTime = 60

def updateScreen():

    DISPLAYSURF.blit(background, (0, 0))
    DISPLAYSURF.blit(wack.waldoImage, wack.waldoRect)
    DISPLAYSURF.blit(cursor.glassImg, cursor.cursorRect)

def updatePoints():
    POINTS_SURF = BASICFONT.render("Points: " + str(points) , True, BLACK)
    DISPLAYSURF.blit(POINTS_SURF, (500, 30))

def updateTime():
    POINTS_SURF = BASICFONT.render("Time Remaining: " + str(int(searchTime - (time.time() - startTime))), True, BLACK)
    DISPLAYSURF.blit(POINTS_SURF, (750, 30))

main()


"""A module containing a TextIngestor class."""

from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel

from typing import List

class TextIngestor(IngestorInterface):
    """A class TextIngestor representing a strategy object which realizes IngestorInterface."""

    allowed_extensions = ['txt']

    @classmethod
    def parse(cls, path:str) -> List[QuoteModel]:
        """Parse a .txt file at the passed destination and output the content as a collection of QuoteModel objects."""
        quotes = []

        with open(path, 'r') as infile:
            for line in infile.readlines():
                line = line.strip('\n\r').strip()
                if len(line) > 0:
                    parse = line.split('-')
                    quote = QuoteModel(parse[0], parse[1])
                    quotes.append(quote)

        return quotes


import os
import random

def Wait():
    k = input("Press enter to continue")

## Exercicios Fáceis
# Fatorial
def Fatorial():
    n = int(input("Digite um número: "))
    fat = 1
    while ( n > 0):
        fat *= n
        n -= 1

    print(fat)

# Triângulo
def Triangulo():
    ladoA = float(input("Digite o valor do primeiro lado: "))
    ladoB = float(input("Digite o valor do segundo lado: "))
    ladoC = float(input("Digite o valor do terceiro lado: "))

    def verificarSoma(A, B, C):
        y = 0
        if (A > B + C):
            x = ("False")
            y = 1
        elif (B > A + C):
            x = ("False")
            y = 1
        elif (C > A + B):
            x = ("False")
            y = 1
        else:
            x = ("True")
        print("É um triângulo: " + x)
        return y

    def equilatero(A, B, C):
        if (A == B and B == C):
            print("É equilátero? True")
        else:
            print("É equilátero? False")

    def isoceles(A, B, C):
        if (A == B or B == C):
            print("É isóceles? True")
        else:
            print("É isóceles? False")

    def escaleno(A, B, C):
        if (A != B and B != C):
            print("É escaleno? True")
        else:
            print("É escaleno? False")

    tri = verificarSoma(ladoA, ladoB, ladoC)
    if (tri != 1):
        equilatero(ladoA, ladoB, ladoC)
        isoceles(ladoA, ladoB, ladoC)
        escaleno(ladoA, ladoB, ladoC)

# Exercício eleição
def Election():
    expectedPeopleNumber = int(input("Digite o número de eleitoes esperados: "))
    colectedPeopleNumber = int(input("Digite o número de votos coletados: "))
    peopleVoteWhite = int(input("Digite o número de votos em branco: "))
    peopleVoteNull = int(input("Digite o número de votos em nulo: "))

    print("Dos", expectedPeopleNumber, "eleitores esperados,", colectedPeopleNumber,
          "eleitores compareceram, isso sendo", colectedPeopleNumber/expectedPeopleNumber*100, "% dos eleitores esperados.")
    print("Desses eleitores,", peopleVoteWhite/colectedPeopleNumber*100,
          "% votaram em branco e", peopleVoteNull/colectedPeopleNumber*100, "% votaram nulo.")

# Exercício média da nota
def Media():
    P1 = int(input('Digite a nota da primeira prova: '))
    A1 = int(input('Digite a nota da primeira atividade: '))
    P2 = int(input('Digite a nota da segunda prova: '))
    A2 = int(input('Digite a nota da segunda atividade: '))
    N1 = (P1*2 + A1) / 3
    N2 = (P2*2 + A2) / 3
    NF = (N1 + N2) / 2
    print("A média final dessa pessoa é:", NF)

# Mínimo multiplo comum
def Mdc():
    valor = int(input("Digite um número: "))
    divisor = int(input("Digite o valor do divisor: "))
    resto = 1
    while (resto != 0):
        resto = valor % divisor
        if (resto == 0):
            print("MDC = " + str(divisor))
        else:
            valor = divisor
            divisor = resto

# Operações com números primos
def Prime():
    def Primo(x):
        divisores = 0
        for y in range(1, x+1):
            if (x % y == 0):
                divisores += 1
        if (divisores == 2):
            return True
        else:
            return False

    def Divisivel(x,y):
        if (x % y == 0):
            return True
        else:
            return False

    def Primos(n):
        x = 1
        while (x <= n):
            if Primo(x):
                print(x, end = ', ')
            x += 1

    def info():
        print(" ")
        print("------------------/------------------")
        print("0. Exit")
        print("1. Número Primo")
        print("2. Divisibilidade de X por Y")
        print("3. Todos os números primos até N", end = '\n\n')

    while True:
        info()
        operacao = int(input("Digite a operação que deseja realizar: "))
        if (operacao == 0):
            exit()
        elif (operacao == 1):
            x = int(input("Digite o número: "))
            if Primo(x):
                print("É um número primo")
            else:
                print("Não é número primo")
        elif (operacao == 2):
            x = int(input("Digite o valor de X: "))
            y = int(input("Digite o valor de Y: "))
            if Divisivel(x,y):
                print(str(x) + " é divisível por " + str(y))
            else:
                print(str(x) + " não é divisível por " + str(y))
        elif (operacao == 3):
            n = int(input("Digite o valor de n: "))
            Primos(n)

## Exercicios Dificeis
# Leilão
def Auction():
    lances = []
    person = []
    maxNumber = 0

    while True:
        x = int(input("Digite o seu lance: "))
        lances.append(x)
        z = input("Quem fez esse lance? ")
        person.append(z)
        y = input("Acabaram os lances? <sim/nao> ").lower().strip()
        if y == 'sim':
            break
        else:
            continue

    while True:
        for x in range (len(lances)):
            if maxNumber < int(lances[x]):
                maxNumber = int(lances[x])
                personMaxNumber = person[x]
        print("O maior lance é:", maxNumber, "de", personMaxNumber)
        break

# Filas exército
def Soldiers():
    print("Esse programa foi desenvolvido com o intuito",
          " de demonstrar um posicionamento de um batalhao.", sep='\n')
    x = int(input("Digite um número de soldados: "))
    filas = 0
    n = 0

    while x > 0:
        n += 1
        x -= n
        filas += 1

    print("O número de fileiras formadas foi", filas)

    if x < 0:
        print("e restaram", x + n, "soldados na última fileira.")

# Fibonacci
def Fibonacci():
    n = int(input("Digite até que número deseja chegar na sequência Fibonacci: "))
    for x in range(0, n):
        if x == 0:
            y = 0
            print("fib(" + str(x)+") =", y)
            y2 = y
        elif x == 1:
            y += 1
            print("fib(" + str(x)+") =", y)
            y1 = y
        else:
            print("fib(" + str(x)+") =", y)
            y2 = y1
            y1 = y
            y = y1 + y2

# Conversor de data
def Data():

    def StringToArray(word):
        wordArray = []
        for x in word:
            wordArray.append(x)
        return wordArray

    def Mes(mes, ano):
        if mes == 1:
            return ["Janeiro", 31]
        elif mes == 2:
            if (ano % 4 == 0 and ano % 100 != 0) or (ano % 4 == 0 and ano % 400 == 0):
                return ["Fevereiro", 29, 1]
            else:
                return["Fevereiro", 28, 0]
        elif mes == 3:
            return ["Março", 31]
        elif mes == 4:
            return ["Abril", 30]
        elif mes == 5:
            return ["Maio", 31]
        elif mes == 6:
            return ["Junho", 30]
        elif mes == 7:
            return ["Julho", 31]
        elif mes == 8:
            return ["Agosto", 31]
        elif mes == 9:
            return ["Setembro", 30]
        elif mes == 10:
            return ["Outubro", 31]
        elif mes == 11:
            return ["Novembro", 30]
        elif mes == 12:
            return ["Dezembro", 31]
        else:
            return ["", 100]

    while True:
        os.system('cls')
        data = StringToArray(input("Digite uma data: <00/00/0000> "))
        dia = int(data[0]+data[1])
        mes = int(data[3]+data[4])
        ano = int(data[6] + data[7] + data[8] + data[9])

        Check = Mes(mes, ano)

        if mes > 12:
            print("Data inválida")
            Wait()
            continue
        elif dia > Check[1]:
            print("Data inválida")
            Wait()
            continue
        elif mes == 2:
            if int(Check[2]) == 0 and dia > 28:
                print("Data inválida")
                Wait()
                continue
            elif int(Check[2]) == 1 and dia > 29:
                print("Data inválida")
                Wait()
                continue

        print(dia, "de", Check[0], "de", ano)
        break

# Jogo Jokempo
def Jokempo():
    Cpontuacao = 0
    Jpontuacao = 0
    matches = 0
    while True:
        while True:
            os.system('cls')
            print("Placar: Você", Jpontuacao, "X", Cpontuacao, "Computador")
            print("1 - Pedra", "2 - Papel", "3 - Tesoura", "", sep='\n')
            x = input("Digite sua escolha: ")
            if x == "1" or x == "2" or x == "3":
                break
            else:
                print("Digite um número válido")

        y = str(random.randrange(1, 4))

        if x == y:
            print("Empate!!")

        elif (x == "1" and y == "2") or (y == "1" and x == "2"):
            if x == "1":
                print("O computador ganhou!!")
                Cpontuacao += 1
            else:
                print("Você ganhou!!")
                Jpontuacao += 1
            matches += 1

        elif (x == "2" and y == "3") or (y == "2" and x == "3"):
            if x == "2":
                print("O computador ganhou!!")
                Cpontuacao += 1
            else:
                print("Você ganhou!!")
                Jpontuacao += 1
            matches += 1

        else:
            if x == "3":
                print("O computador ganhou!!")
                Cpontuacao += 1
            else:
                print("Você ganhou!!")
                Jpontuacao += 1
            matches += 1

        if matches > 2 and Cpontuacao > Jpontuacao:
            print("O computador ganhou a melhor de 3!!!")
            break
        elif matches > 2 and Jpontuacao > Cpontuacao:
            print("Você ganhou a melhor de 3!!!")
            break
        Wait()

# Menu Para os executaveis
def Hub():
    while True:
        os.system('cls')
        print("1 - Exercicios Dificeis", "2 - Exercicios Faceis", "", "0 - Exit", sep="\n")
        x = input("Digite sua escolha: ").strip()

        if x == '0':
            exit()

        elif x == '1':
            while True:
                os.system('cls')
                print("1 - Leilão", "2 - Soldados", "3 - Fibonacci", "4 - Conversao de data", "5 - Jokempo", "", "0 - Exit", sep="\n")
                y = input("Digite sua escolha: ").strip()
                if y == "0":
                    exit()
                elif y == '1':
                    Auction()
                elif y == '2':
                    Soldiers()
                elif y == '3':
                    Fibonacci()
                elif y == '4':
                    Data()
                elif y == '5':
                    Jokempo()

                Wait()

        elif x == '2':
            while True:
                os.system('cls')
                print("1 - Fatorial", "2 - Triângulo", "3 - Eleição", "4 - Média Final", "5 - Mínimo Multiplo Comum", "6 - Números Primos", "0 - Exit", sep="\n")
                y = input("Digite sua escolha: ").strip()
                if y == "0":
                    exit()
                elif y == '1':
                    Fatorial()
                elif y == '2':
                    Triangulo()
                elif y == '3':
                    Election()
                elif y == '4':
                    Media()
                elif y == '5':
                    Mdc()
                elif y == '6':
                    Prime()
                Wait()

Hub()


import pygame, os, random
from math import sqrt

width, height = 800, 800
screen = pygame.display.set_mode((width, height))
running = True
screen.fill((255, 255, 255))
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname)
    if colorkey is not None:
        if colorkey == -1:
            colorkey = image.get_at((0, 0))
        image.set_colorkey(colorkey)
    return image

class Bomb(pygame.sprite.Sprite):
    image = load_image("g11.jpg", 1)
    w, h = 100, 100
    image = pygame.transform.scale(image, (w, h))

    def __init__(self, group):
        w, h = 100, 100
        # НЕОБХОДИМО вызвать конструктор родительского класса Sprite. Это очень важно!!!
        super().__init__(group)
        self.image = Bomb.image
        self.rect = self.image.get_rect()
        self.rect.x = 200
        self.rect.y = 200

class bullet(pygame.sprite.Sprite):
    image = load_image("g11.jpg", 1)

    image = pygame.transform.scale(image, (10, 10))

    def __init__(self, group, xy):
        # НЕОБХОДИМО вызвать конструктор родительского класса Sprite. Это очень важно!!!
        super().__init__(group)
        self.image = bullet.image
        self.rect = self.image.get_rect()
        self.rect.x = 200
        self.rect.y = 200
        self.speed = 1.0
        nx, ny = xy
        self.rast = sqrt((200 - nx) ** 2 + (200 - ny) ** 2)
        sin = (-200 + nx) / sqrt((200 - nx)**2 + (200 - ny)**2)
        cos = (-200 + ny) / sqrt((200 - nx) ** 2 + (200 - ny) ** 2)
        self.nx, self.ny = round(sin * 50.0), round(cos * 50.0)
        self.pr = 0
        print(1)

    def update(self):
        self.rect.x = self.rect.x + self.nx
        self.rect.y = self.rect.y + self.ny
        self.pr += self.speed
        if self.rast < self.pr:
            return False

clock = pygame.time.Clock()

bomb_image = load_image("car2.png")
bomb_image = pygame.transform.scale(bomb_image, (100, 100))
all_sprites = pygame.sprite.Group()
bul = pygame.sprite.Group()
for _ in range(1):
    Bomb(all_sprites)
gh = False
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            gh = True
            bullet(bul, event.pos)
        if event.type == pygame.MOUSEBUTTONUP:
            gh = False
        if event.type == pygame.MOUSEMOTION:
            x, y = event.pos

    for i in bul:
        if i.update() == False:
            bul.remove(i)
    print(len(bul))
    if not gh:
        ji = 0
    if gh:
        ji += 1
        if ji % 10 == 0:
            bullet(bul, [x, y])

    screen.fill((255, 255, 255))
    all_sprites.draw(screen)
    bul.draw(screen)
    pygame.display.flip()
    clock.tick(60)
pygame.quit()


import settings
import requests
import re
import SecondReportTitle

# 管理中心url
url = 'https://service.account.weibo.com/index?type=5&status=0&page=%d'

def first_page():
    for i in range(0, 5):
        # 拼接翻页url
        url1 = url % i
        # 向管理中心发起请求获取响应
        response1 = requests.get(url=url1, headers=settings.headers).content\
            .decode('unicode-escape')

        # 提取管理中心里每个被举报人的拜访数
        visit_counts = re.findall(r'<td>(\d+)<\\/td>', response1)

        # 获取所有被举报人的url
        by_url = re.findall(r'a href="(.+)"\starget="_blank".+\n\s\s<td>\d+',
                            response1)

        # 获取所有被举报时间
        report_time = re.findall(r'<td>(.+)<\\/td>\n\t<\\/tr>', response1)

        # 获取所有举报标题url
        title_url = re.findall(r'class="m_table_tit"\s*><a\s*href="(.+)"+?\s',
                               response1)

        data_dict = {'visit_counts': visit_counts,
                     'by_url': by_url,
                     'report_time': report_time,
                     'title_url': title_url,
                     'page1': i
                     }

        # print(response1)
        #
        # print(len(by_url))
        # print(by_url)
        #
        # print(len(visit_counts))
        # print(visit_counts)
        #
        # print(len(report_time))
        # print(report_time)
        #
        # print(len(title_url))
        # print(title_url)

        # 举报标题界面数据爬取
        SecondReportTitle.second_page(data_dict)

if __name__ == "__main__":
    first_page()


# Find the maximum length subarray with GCD=1

# Difficulty -> Easy

# Asked in Zoho

# Approach:
# If a array has any two element GCD as 1 then the whole array has GCD=1
# using this logic, we will return the length of array as maximum subarray if it has
# any two elements with gcd 1

# Utility function to find gcd of two numbers
def gcd(a, b):
    if b:
        return gcd(b, a % b)
    else:
        return a

def gcd_1(arr1):
    # store the first element
    res = arr1[0]

    # loop through the array and calculate gcd with current res and current element
    for i in range(1, len(arr1)):
        res = gcd(res, arr1[i])

    # if gcd found to be 1 then return length of array else -1
    print(len(arr1) if (res == 1) else -1)

# Driver Code
arr1 = [2, 2, 4]
arr2 = [7, 2]

print(gcd_1(arr1))
print(gcd_1(arr2))

# Time Complexity : O(N)
# Space Complexity : O(1)


# Nama  : Muhammad Zhahnur Arif & Adil Firdausy Firmansyah
# NIM   : 1204210075 & 1204210048
# Kelas : IS 04-02

# Jump Search
print()
from timeit import default_timer as timer
start = timer()

import math
def jump_search (mylist, value, length) :
    step = int (math.sqrt(len(mylist)))
    prev = 0
    while (mylist[min(step, length) - 1] < value):
        prev = step
        step = step + int(math.sqrt(len(mylist)))
        if (prev >= length):
            return -1
    while (mylist[prev] < value):
        prev = prev + 1
        if(prev == min(step, length)):
            return -1
    if (mylist[prev] == value):
        return prev
    return -1

mylist = [0,8,7,8,5,0,8,6,6,1,8,2]
mylist.sort()
print(mylist)
number = 8
index = jump_search(mylist, number, len(mylist))
if(index != -1 ):
    print("Index ditemukan =", index)
else :
    print("Index tidak ditemukan!!!")

end = timer()
print("Waktu yang diperlukan :", end - start)
print()

UTS Take Home Soal 1/TakeHomeSoal1jump.py


# 손님은 엘레베이터에서 거리가 짧은 방을 선호
# 거리가 같을 경우, 저층을 선호
# 투숙 순서 : 101 -> 102 -> 103 -> .... -> (꼭대기 층) -> 201 -> 202 -> ...

# 테스트 케이스
T = int(input())

for tc in range(1, T+1):
    # H : 호텔의 층 수 / W : 각 층의 방 수 / V : 몇 번째 손님인지 표시
    H, W, V = map(int, input().split())

    # 최고층에 위치할 경우
    if V % H == 0:
        # V 번째 손님이 머무를 객실 번호
        # 최고 층 호수 + 엘레베이터로부터 거리
        room_num = H * 100 + V // H

    # 최고층이 아닐 경우
    else:
        room_num = (V % H) * 100 + V // H + 1

    print(room_num)


import os
from avocado import Test
from avocado.utils import archive, build, distro, linux_modules
from avocado.utils.software_manager.manager import SoftwareManager

class fscrypt(Test):

    """
    fscrypt-testsuite
    :avocado: tags=security,testsuite
    """

    def setUp(self):
        '''
        Install the basic packages to support fscrypt
        '''
        cfg_param = "CONFIG_FS_ENCRYPTION"
        ret = linux_modules.check_kernel_config(cfg_param)
        if ret == linux_modules.ModuleConfig.NOT_SET:
            self.cancel("%s not set." % cfg_param)
        else:
            self.log.info("%s set." % cfg_param)
        # Check for basic utilities
        smm = SoftwareManager()
        detected_distro = distro.detect()
        deps = ['gcc', 'make']
        if detected_distro.name in ['rhel', 'SuSE', 'fedora', 'centos']:
            deps.extend(["autoconf", "automake", "golang", "expect",
                         "keyutils", "e2fsprogs", "pam-devel"])
        else:
            self.cancel("Unsupported distro %s for fscrypt package"
                        % detected_distro.name)
        for package in deps:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel('%s is needed for the test to be run' % package)
        url = "https://github.com/google/fscrypt/archive/refs/heads/master.zip"
        tarball = self.fetch_asset(url, expire='7d')
        archive.extract(tarball, self.workdir)
        self.sourcedir = os.path.join(self.workdir, 'fscrypt-master')
        os.chdir(self.sourcedir)

    def test(self):
        '''
        Running tests from fscrypt
        '''
        count = 0
        output = build.run_make(self.sourcedir, extra_args="test",
                                process_kwargs={"ignore_status": True})
        if output.exit_status:
            self.fail("fscrypt-tests.py: 'make test' failed.")
        for line in output.stdout_text.splitlines():
            if 'not ok' in line:
                count += 1
                self.log.info(line)
        if count:
            self.fail("%s test(s) failed, please refer to the log" % count)


# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from decimal import Decimal
import scrapy
import json
import re
import logging
import os
from music import items

RECORDS_NEWER_THAN=os.environ.get(
    'RECORDS_NEWER_THAN',
    (datetime.utcnow().date() - timedelta(days=2)).isoformat()
)

def _music_uri(path):
    return 'tag:eric.moritz@gmail.com,2016:music/{}'.format(path)

def _pitchfork_uri(path):
    return _music_uri('pitchfork.com/{}'.format(path))

class PitchforkSpider(scrapy.Spider):
    name = "pitchfork"
    allowed_domains = ["pitchfork.com"]
    start_urls = (
        'http://pitchfork.com/api/v1/albumreviews/?format=json',
    )

    def parse(self, response):
        data = json.loads(response.body)
        nextPage = data.get('next')
        if nextPage:
            yield scrapy.Request(
                response.urljoin(nextPage),
                callback=self.parse
            )

        publisher = items.Organization(
            uri = "http://pitchfork.com/",
            name = 'Pitchfork'
        )

        for result in data['results']:
            date_published = _date(result['timestamp'])
            if date_published < RECORDS_NEWER_THAN:
                raise scrapy.exceptions.CloseSpider(
                    "{} < {}".format(
                        date_published,
                        RECORDS_NEWER_THAN
                    )
                )

            authors = [
                items.Person(
                    uri = _pitchfork_uri(x['url'].lstrip('/')),
                    url = 'http://pitchfork.com' + x['url'],
                    name = x['name']
                )
                for x in result['authors']
            ]
            for x in authors:
                yield x

            for i, album_json in enumerate(result['tombstone']['albums']):

                review_uri =  _pitchfork_uri(
                    'review/{}/{}'.format(result['id'],i)
                )

                artists = [
                    items.MusicGroup(
                        uri = _pitchfork_uri('artists/{}'.format(x['id'])),
                        name = x['display_name']
                    )
                    for x in album_json['album']['artists']
                ]
                for x in artists: yield x

                album = items.MusicAlbum(
                    uri = _pitchfork_uri('album/{}'.format(_album_id(album_json))),
                    name = album_json['album']['display_name'],
                    byArtist = [_link(x['uri']) for x in artists]
                )
                yield album

                rating = items.Rating(
                    uri = review_uri + "#reviewRating",
                    bestRating = 1000,
                    worstRating = 0,
                    ratingValue = int(Decimal(album_json['rating']['rating']) * 100)
                )
                yield rating

                labels = [
                    items.Organization(
                        uri=_pitchfork_uri('label/{}'.format(l['id'])),
                        name=l['name']
                    )
                    for x in album_json['labels_and_years']
                    for l in x['labels']
                ]

                for x in labels:
                    yield x

                year = min(
                    unicode(x['year']).split('/')[0]
                    for x in album_json['labels_and_years']
                )

                release = items.MusicRelease(
                    uri = review_uri + '#itemReviewed/{}'.format(i),
                    releaseOf = _link(album['uri']),
                    datePublished = year,
                    recordLabel = [_link(l['uri']) for l in labels]
                )

                yield release
                yield items.Review(
                    uri = review_uri,
                    url = "http://pitchfork.com" + result['url'],
                    datePublished = date_published,
                    itemReviewed = _link(release['uri']),
                    reviewRating = _link(rating['uri']),
                    publisher = _link(publisher['uri']),
                    author = [_link(x['uri']) for x in authors]
                )

def _date(x):
    return datetime.utcfromtimestamp(x / 1000).isoformat() + 'Z'

def _link(x):
    return {'@id': x}

def t(val):
    logging.info(repr(val))
    return val

ALBUM_ID_PAT = re.compile('.+/albums/(\d+)')
def _album_id(album_json):
    match = ALBUM_ID_PAT.match(album_json['album']['artwork']['default'])
    if match:
        return match.group(1)
    else:
        raise ValueError("Could not detect album id")


# 224. 基本计算器
# 实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。

class Solution:
    def calculate(self, s: str) -> int:
        nums = []
        operates = []
        n = len(s)
        index = 0
        def compute():
            while operates:
                ope = operates.pop()
                if ope == "(":
                    break
                num2 = nums.pop()
                num1 = nums.pop()
                res = None
                if ope == "+":
                    res = num1+num2
                if ope == "-":
                    res = num1-num2
                nums.append(res)
        while index < n:
            if s[index] == "(":
                operates.append(s[index])
            elif s[index] == "+":
                if operates and (operates[-1]=="+" or operates[-1]=="-"):
                    compute()
                operates.append(s[index])
            elif s[index] == "-":
                if operates and (operates[-1]=="+" or operates[-1]=="-"):
                    compute()
                operates.append(s[index])
            elif s[index].isdecimal():
                tmp = int(s[index])
                while index+1 < n and s[index+1].isdecimal():
                    index += 1
                    tmp = tmp*10+int(s[index])
                nums.append(tmp)
            elif s[index] == ")":
                compute()
            index+=1
        compute()
        return nums[-1]

sol = Solution()
s = "1-2+3"
print(sol.calculate(s))


import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.views.generic.base import TemplateView

from web_admin.exceptions import PermissionDeniedException
from web_admin.mixins import GetChoicesMixin
from web_admin.restful_methods import RESTfulMethods
from web_admin.api_settings import GET_REPORT_AGENT_BALANCE
from web_admin.api_settings import COMPANY_BALANCE_HISTORY
from web_admin.api_settings import COMPANY_BALANCE_ADD
from web_admin.api_settings import GET_AGENT_BALANCE
from web_admin import api_settings, setup_logger
from authentications.utils import get_correlation_id_from_username, check_permissions_by_user
from braces.views import GroupRequiredMixin

logger = logging.getLogger(__name__)

class CompanyBalanceView(GroupRequiredMixin, TemplateView, GetChoicesMixin, RESTfulMethods):
    group_required = "SYS_VIEW_COMPANY_BALANCE"
    login_url = 'web:permission_denied'
    raise_exception = False

    template_name = "company_balance.html"
    company_agent_id = 1
    company_agent_user_type = 2
    logger = logger

    def check_membership(self, permission):
        self.logger.info(
            "Checking permission for [{}] username with [{}] permission".format(self.request.user, permission))
        return check_permissions_by_user(self.request.user, permission[0])

    def dispatch(self, request, *args, **kwargs):
        correlation_id = get_correlation_id_from_username(self.request.user)
        self.logger = setup_logger(self.request, logger, correlation_id)
        return super(CompanyBalanceView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name,
                      self._build_context(request)
                      )

    def post(self, request, *args, **kwargs):
        if not check_permissions_by_user(request.user, 'SYS_ADD_COMPANY_BALANCE'):
            raise PermissionDeniedException()

        new_company_balance = request.POST.get('new_company_balance')
        amount = request.POST.get('adding_balance')
        string_amount = amount

        if isinstance(amount, str):
            amount = amount.replace(',', '')
        currency = request.POST.get('currency')

        data = {'amount': amount}

        response, success = self._add_company_balance(currency, data)

        if success:
            messages.add_message(
                request,
                messages.SUCCESS,
                'Added balance successfully'
            )
            return redirect(request.META['HTTP_REFERER'])
        else:
            messages.add_message(
                request,
                messages.ERROR,
                response
            )
            context = self._build_context(request)
            context['new_company_balance'] = new_company_balance
            context['string_amount'] = string_amount
            context['selected_currency'] = currency
            return render(request, self.template_name, context)

    def _get_company_balance(self, currency):
        url = GET_REPORT_AGENT_BALANCE
        body = {
            'user_id': self.company_agent_id,
            'currency': currency,
            'user_type': 2,
            "paging": False,
            "page_index": -1
        }
        func_description = "Getting balance by username: {} \
        ,agent id: {} and currency: {}".format(self.request.user.username,
                                               self.company_agent_id,
                                               currency, )
        return self._post_method(api_path=url,
                                 func_description=func_description,
                                 logger=logger,
                                 params=body)

    def _get_new_company_balance(self, data):
        def calculate_balance_after_change(x):
            x['balance_after_change'] = x['balance_before_change'] + x['changed_amount']
            return x

        return map(calculate_balance_after_change, data)

    def _get_company_balance_history(self, currency):
        url = COMPANY_BALANCE_HISTORY + currency
        return self._get_method(api_path=url,
                                func_description="company balance list by user",
                                logger=logger,
                                is_getting_list=True)

    def _add_company_balance(self, currency, body):
        url = COMPANY_BALANCE_ADD + currency
        return self._put_method(api_path=url,
                                func_description="add company balance",
                                logger=logger,
                                params=body)

    def _get_currency_choices_by_agent(self, agent_id, company_agent_user_type):
        url = GET_AGENT_BALANCE
        body = {'user_id': agent_id, 'user_type': company_agent_user_type, 'paging':False}
        data, success = self._post_method(api_path=url,
                                          func_description="currency list by agent",
                                          logger=logger,
                                          params=body)
        if success:
            currency_list = [i['currency'] for i in data['cash_sofs']]
            return currency_list, True
        else:
            return data, True

    def _get_currency_choices_list(self):
        url = api_settings.GET_ALL_CURRENCY_URL
        self.logger.info('Get currency choice list from backend')
        data, success = self._get_method(api_path=url,
                                         func_description="currency choice list",
                                         logger=logger,
                                         is_getting_list=False)
        if success:
            value = data.get('value', '')
            if isinstance(value, str):
                currency_list = map(lambda x: x.split('|'), value.split(','))
            else:
                currency_list = []
            result = currency_list, True
        else:
            result = data, False
        return result

    def sum_balance(self, balance_lst):
        return sum([balance['changed_amount'] for balance in balance_lst])

    def _build_context(self, request):
        default_decimal = 1
        currency_choices, success_currency = self._get_currency_choices_by_agent(self.company_agent_id,
                                                                                self.company_agent_user_type)
        if not success_currency:
            messages.add_message(
                request,
                messages.ERROR,
                message=currency_choices
            )
            currency_choices = []

        currency_list, success_currency = self._get_currency_choices_list()
        if not success_currency:
            messages.add_message(
                request,
                messages.ERROR,
                message=currency_list
            )
            currency_list = []

        currency_list = list(filter(lambda x: x[0] in currency_choices, currency_list))
        if currency_list:
            currency = request.GET.get('currency', currency_list[0][0])
            decimal = list(filter(lambda x: x[0] == currency, currency_list))[0][1]
        else:
            return {'objects': [],
                    'currency_list': [],
                    'decimal': None,
                    'company_balance': None,
                    'total_balance': None}

        totalData, success_total_balance = self._get_company_balance(currency)

        if not success_total_balance:
            messages.add_message(
                request,
                messages.ERROR,
                message=totalData
            )
            totalData = {}
        else:
            totalData = totalData['cash_sofs'][0]

        data, success_balance = self._get_company_balance_history(currency)
        if success_balance:
            data = self._get_new_company_balance(data)
        else:
            messages.add_message(
                request,
                messages.ERROR,
                message=data
            )
            data = []
        objs = list(data)
        return {
            'objects': objs,
            'currency_list': currency_list,
            'decimal': decimal,
            'company_balance': totalData,
            'total_balance': self.sum_balance(objs)
        }

company_balance = login_required(CompanyBalanceView.as_view(), login_url='authentications:login')


# -*- coding: utf-8 -*-
"""
Created on Tue Feb  2 01:40:51 2016

@author: Michy
@description:
    Given a two sided magnetic circuit, this script calculates the parameters of the mutual inductor
    The mutual inductor is assumed to be connected in series with a current source. The structure of the mutual inductor
    is assumed to have three iron cores and a set of windings on each of the external cores.
    You just need to provide the number of turns of each coil and the reluctances of each core of the structure.

    This script was written to double check some exercises in a course of electrical circuits.

@example: run the script.

"""

import numpy as np

# Magnetic reluctances
r1 = 3*10**6/(4*np.pi)
r2 = 10**6/(2*np.pi)
r3 = 10**6/(4*np.pi)

# Number of turns (windings)
N1 = 100
N2 = 200

# Magnetic permeances
g1 = 1/r1
g2 = 1/r2
g3 = 1/r3

# Sum of permeances
gsum = g1+g2+g3

# Self and mutual permeances
g11 = g1*(g2+g3)/gsum
g22 = g2*(g1+g3)/gsum
gm = -(g2*g1)/gsum

# Self and mutual inductances
l11 = g11*N1**2
l22 = g22*N2**2
lm = gm*N1*N2

# Equivalent inductances
print(l11 + l22 - 2*lm)
print(l11 + l22 + 2*lm)