## By BingLi224
##
## 13:31 THA 01/06/2018
##
## Linear Regression Example
##
## Click a point. When got > 1 point, auto calculate linear regression line.

from tkinter import *
from tkinter import ttk

points = []

def add_point ( event ) :
	print ( str ( event.x ) + "\t" + str ( event.y ) )
	cv.create_rectangle (
			event.x - 1, event.y - 1,
			event.x + 1, event.y + 1
		)

	points.append ( [ event.x, event. y ] )

	if len ( points ) > 1 :
		## get the width of the canvas
		width = int ( cv.cget ( 'width' ) )

		## count the sum
		x_avg = 0
		y_avg = 0
		for p in points :
			x_avg += p [ 0 ]
			y_avg += p [ 1 ]

		## get the averages
		x_avg /= len ( points )
		y_avg /= len ( points )

		## calc the slope
		slope = 0
		slope_div = 0

		for p in points :
			slope += ( p [ 0 ] - x_avg ) * ( p [ 1 ] - y_avg )
			slope_div += ( p [ 0 ] - x_avg ) ** 2

		slope /= slope_div

		## show the regression line
		cv.delete ( 'regression' )
		cv.create_line (
			0, y_avg + slope * ( - x_avg ),
			width, y_avg + slope * ( width - x_avg ),
			tags = 'regression'
			)

root = Tk ()
cv = Canvas ( root, width = 500, height = 500 )
cv.pack ( expand = 1, fill = 'both', side = 'top' )
cv.bind ( '<1>', add_point )

root.mainloop ( )


# -*- coding: utf-8 -*-
#import legmoves
import calculs
import time

if __name__ == "__main__":
    print("Donner une direction au robot")
    #calculs.default_pos()

    i=160
    j=-80
    k=90
    a=0
    while True:
        t=2
        if a==0:
            calculs.set_leg_pos_robot_frame(t,i,j,k)
            j+=1
            k=k-1.125
            if j==0 and k==0:
                a=1

        if a==1:
            calculs.set_leg_pos_robot_frame(t,i,j,k)
            i=160
            j+=1
            k=k+1.125
            if j==80 and k==90:
                a=2

        if a==2:
            calculs.set_leg_pos_robot_frame(t,i,j,k)
            i=160
            j-=5
            if j==-80 and k==90:
                a=0
        time.sleep(0.005)


from django.test import TestCase, Client
from django.urls import reverse

from unittest.mock import patch
from rest_framework.test import APITestCase

class ViewsTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        self.home_url = reverse('home')

    def test_home_GET(self):
        response = self.client.get(self.home_url)

        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'core/home.html')

    def test_home_POST(self):
        with patch('core.views.convert') as mocked_convert:
            mocked_convert.return_value = 20
            response = self.client.post(self.home_url, data={
                'convert_from': 'USD',
                'convert_into': 'EUR',
                'amount': '10',
            })

            self.assertEquals(response.status_code, 200)
            self.assertTemplateUsed(response, 'core/home.html')
            self.assertEquals(response.context['amount'], 20)

class ConverterTestCase(TestCase):
    def test_convert(self):
        with patch('core.converter.get_rates') as mocked_get_rates:
            mocked_get_rates.return_value = {'CZK': 23.232026, 'EUR': 0.919583, 'PLN': 3.95897, 'USD': 1}
            response = self.client.post(reverse('home'), data={
                'convert_from': 'USD',
                'convert_into': 'EUR',
                'amount': '1',
            })
            self.assertEquals(response.context['amount'], 0.919583)

class ApiTestCase(APITestCase):
    def setUp(self):
        self.api_convert_url = reverse('api-convert')

    def test_api_convert(self):
        with patch('core.converter.get_rates') as mocked_get_rates:
            mocked_get_rates.return_value = {'CZK': 23.232026, 'EUR': 0.919583, 'PLN': 3.95897, 'USD': 1}
            data = {'convert_from': 'USD', 'convert_into': 'EUR', 'amount': '1'}
            response = self.client.get(self.api_convert_url, data)

            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.data['amount'], 0.919583)

    def test_api_convert_invalid_data(self):
        data = {'convert_from': 'USD', 'convert_into': 'EUR', 'amount': 'oops'}
        response = self.client.get(self.api_convert_url, data)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['Error'], 'Invalid data')

    def test_api_convert_unsupported_currency(self):
        data = {'convert_from': 'UDD', 'convert_into': 'RUB', 'amount': '1'}
        response = self.client.get(self.api_convert_url, data)

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data['Error'], 'Unsupported currency')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/21 9:34
# @Author  : sch
# @File    : 2017_12_21.py

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('ggplot')
plt.rcParams['font.sans-serif'] = ['SimHei']  #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  #用来正常显示负号

y_label = pd.read_csv('data_output/ZTmodule/EG_index_final_20171221.csv', encoding='gbk')
y_label = y_label[['client_name', 'year', 'credit_ratio', 'credit_rating']]
data = pd.read_excel('data_output/ZTmodule/rp.xlsx', encoding='gbk')

new_data = pd.merge(data, y_label, left_on=['year', 'name'], right_on=['year', 'client_name'], how='right')
new_data = new_data.drop('name', 1)
# new_data = new_data.rename(columns={'name': 'client_name'})

new_data.to_csv('data_output/ZTmodule/RP_index_1221V0.2.csv')


from tkinter import *
from tkinter.simpledialog import askstring
from bs4 import BeautifulSoup
import requests
import re

class WebCrawler:
    def __init__(self):
        self.url = ""

        # GUI Components
        self.root = Tk()
        self.root.iconbitmap(default='logo.ico')
        self.root.title("설정 - 알랴죠")
        self.root.resizable(width=False, height=False)
        self.root.minsize(width=700, height=500)

        self.labelURL = Label(self.root, text="아래 URL 열기를 눌러주세요!")
        self.labelURL.config(font=["나눔고딕", 10])
        self.labelURL.pack(fill=X)

        self.buttonOpenURL = Button(self.root, text="URL 열기", command=lambda: self.openurl())
        self.buttonOpenURL.config(font=["나눔고딕", 13])
        self.buttonOpenURL.pack(fill=X)

        self.textSource = Text(self.root)
        self.textSource.config(font=["Consolas", 10], state=DISABLED, height=30, width=100)
        self.textSource.config(font=["D2Coding", 10])
        self.textSource.pack(side=LEFT, fill=BOTH)

        self.scrollbar = Scrollbar(self.root, command=self.textSource.yview)
        self.textSource["yscrollcommand"] = self.scrollbar.set
        self.scrollbar.pack(side=RIGHT, fill=Y)

    def show(self):
        self.root.mainloop()

    def openurl(self):
        self.url = askstring("알랴죠 - 웹크롤러", "크롤링할 웹페이지의 URL을 입력해주세요")
        self.labelURL["text"] = self.url
        self.crawl(self.url)

    def crawl(self, url):
        html = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                                                        'AppleWebKit/537.36 (KHTML, like Gecko) '
                                                        'Chrome/63.0.3239.132 Safari/537.36'}).text
        soap = BeautifulSoup(html, "html.parser")

        self.textSource["state"] = NORMAL
        self.textSource.insert(END, ''.join([ch for ch in list(soap.prettify()) if ord(ch) in range(65536)]))
        self.textSource["state"] = DISABLED

    def find_flag(self):
        if self.url == "":
            return

        pattern = re.compile(self.get_setting("flagFormat"), re.IGNORECASE)
        result = pattern.findall(self.textSource.get())
        if len(result) == 0:    # When the result is empty
            showinfo("WebCrawler - 알랴죠", "Flag가 발견되지 않았습니다.")
        else:
            showinfo("WebCrawler - 알랴죠", "Flag가 발견되었습니다!\n\n"+"\n".join(result))


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

import pandas as pd
import statistics as st
import matplotlib.pyplot as plt
import plotly.offline as offline
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff

from web3 import Web3
web3 = Web3(Web3.HTTPProvider("https://mainnet.infura.io/v3/fbff721384cf4ceb95fcf8c18a249f95"))

def graf(text):
    x=[]
    for i in range(1000):
        x.append(i)
    fig1 = go.Figure(data=[go.Bar(
                             y=df[text],
                             x=x,
                             hovertext=['27% market share', '24% market share', '19% market share'])])
    fig1.update_traces(marker_color='rgb(158,202,225)', marker_line_color='rgb(8,48,107)',
                  marker_line_width=1.5, opacity=0.6)
    fig1.update_layout(title_text=text)
    fig1.show()
    fig1.write_html(text+'.html', auto_open=True)

St = 8921400
End = 8922400
allprice = []
allpercent = []
allcommission = []
allkontr = []

for i in range(St, St+End):
    block = web3.eth.getBlock(i)
    commission = 0
    kontr = 0
    for trans in block['transactions']:
        tr = web3.eth.getTransaction(trans)
        tr_r = web3.eth.getTransactionReceipt(trans)
        commission += web3.fromWei(tr_r['gasUsed']*tr['gasPrice'], 'ether')
        if tr['input'] != '0x':
            kontr += 1
    allkontr.append(kontr)
    allcommission.append(float(commission))
    price = 2+commission
    allprice.append(float(price)+2*len(block.uncles)/32)
    allpercent.append(float((commission/price)*100))

d = {'Commission': allcommission,'All Priсe': allprice, 'Percent': allpercent, 'All contracts': allkontr}
df = pd.DataFrame(d)

graf('Commission')
graf('Percent')

Result = {'Математическое ожидание': df.Commission.mean(),
          'Медиана': df.Commission.median(),
          'Среднеквадратичное отклонение': df.Commission.std(),
          'Дисперсия': df.Commission.var(),
          'Размах':max(df['Commission']) - min(df['Commission'])}


# -*- coding: utf-8 -*-
"""
Script for plotting basic softmax function.
"""

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

def softmax(x_0, x_1, x_2):
    u = np.exp(x_0) + np.exp(x_1) + np.exp(x_2)
    y_0 = np.exp(x_0)/u
    y_1 = np.exp(x_1)/u
    y_2 = np.exp(x_2)/u
    return y_0, y_1, y_2

n = 20
x_0 = np.linspace(-4, 4, n)
x_1 = np.linspace(-4, 4, n)

y = np.zeros((n, n, 3))
for i_0 in range(n):
    for i_1 in range(n):
        y[i_1, i_0, :] = softmax(x_0[i_0], x_1[i_1], 1)

xx_0, xx_1 = np.meshgrid(x_0, x_1)

plt.figure(figsize=(8, 3))
for i in range(2):
    axes = plt.subplot(1, 2, i+1, projection='3d')
    axes.plot_surface(xx_0, xx_1, y[:, :, i],
                      rstride=1, cstride=1, alpha=0.3,
                      color='blue', edgecolor='black')
    axes.set_xlabel('$x_0$', fontsize=14)
    axes.set_ylabel('$x_1$', fontsize=14)
    axes.view_init(40, -125)

plt.show()


# -*- coding: utf-8 -*-
"""
Created on Mon May 10 09:12:09 2021

@author: oislen
"""

import pandas as pd

def filter_zero_item_prices(dataset):

    """

    Filter Zero Item Prices Documentation

    Function Overview

    This function removes item prices with zero recorded sales.

    Defaults

    filter_zero_item_prices(dataset)

    Parameters

    dataset - DataFrame, the data to remove item prices with zero sales from

    Returns

    filt_data - DataFrame, the filtered item price data

    """

    # load in pickled holdout item shop id combination
    #holdout_shop_item_id_comb = pk.load(open(cons.holdout_shop_item_id_comb, 'rb'))
    dataset['shop_item_id'].nunique()

    # create filters for item price and holdout shop item combination
    price_tab = pd.pivot_table(data = dataset,
                               index = 'date_block_num',
                               columns = ['shop_id', 'item_id'],
                               values = 'item_price'
                               )
    all_zero_price = (price_tab == 0).all()
    keep_shop_item_comb = all_zero_price[all_zero_price].reset_index().drop(columns = 0)
    keep_shop_item_comb_series = keep_shop_item_comb['shop_id'].astype(str) + '_' + keep_shop_item_comb['item_id'].astype(str)

    filt_shop_item_id = dataset['shop_item_id'].isin(keep_shop_item_comb_series)
    filt_default_price = dataset['item_price'] == 0

    filt_data = dataset[~filt_default_price | filt_shop_item_id]

    return filt_data


import copy
import random
from config import *

class KingsheepEnv:
    def __init__(self, player1, player2, map_name):
        self.player1 = player1
        self.player2 = player2
        self.ks = KsField(map_name, name1=self.player1.name, name2=self.player2.name)
        self.iteration = 0

    def step(self):
        self.iteration += 1
        iteration_summary, game_over = _kingsheep_iteration(i=self.iteration,
                                                            ks=self.ks,
                                                            player1=self.player1,
                                                            player2=self.player2)
        if self.iteration >= N_ITERATIONS:
            game_over = True

        return iteration_summary, game_over

class KsField:
    def __init__(self, filepath, name1='Player 1', name2='Player 2'):
        # initialize the field with empty cells.
        if filepath == "generator":
            self.field = generate_random_field(0.75, {
                CELL_FENCE: 3,
                CELL_RHUBARB: 1,
                CELL_GRASS: 8
            })
        else:
            self.field = [[CELL_EMPTY for x in range(FIELD_WIDTH)] for y in range(FIELD_HEIGHT)]
            self.read_field(filepath)
        self.score1 = 0
        self.score2 = 0
        self.grading1 = 0
        self.grading2 = 0
        self.name1 = name1
        self.name2 = name2

    # Field related functions
    def read_field(self, fp):
        file = open(fp, 'r')
        for lineno, line in enumerate(file, 1):
            # turn the line into a string, strip the tangling \n and then assign it to the field variable
            self.field[lineno - 1] = list(str(line).strip('\n'))

    def get_field(self):
        return copy.deepcopy(self.field)

    def get_position(self, figure):
        # Next statement is a list comprehension.
        # it first generated a list of all x's in self. field, where figure is in that particular x
        # it then returns the first element (which is the row that contaions the figure),
        # as we know that there is only one of each of these figures
        x = [x for x in self.field if figure in x]
        if x == []:
            return (0, 0)
        x = x[0]
        return (self.field.index(x), x.index(figure))

    def new_position(self, x_old, y_old, move):
        if move == MOVE_LEFT:
            return (x_old, y_old - 1)
        elif move == MOVE_RIGHT:
            return (x_old, y_old + 1)
        elif move == MOVE_UP:
            return (x_old - 1, y_old)
        elif move == MOVE_DOWN:
            return (x_old + 1, y_old)

    def valid(self, figure, x_new, y_new):
        if x_new > FIELD_HEIGHT - 1:
            return False
        elif x_new < 0:
            return False
        elif y_new > FIELD_WIDTH - 1:
            return False
        elif y_new < 0:
            return False

        # Neither the sheep nor the wolf, can enter a square with a fence on.
        if self.field[x_new][y_new] == CELL_FENCE:
            return False

        # Wolfs can not step on squares occupied by the opponents wolf (wolfs block each other).
        # Wolfs can not step on squares occupied by the sheep of the same player .
        if figure == CELL_WOLF_1:
            if self.field[x_new][y_new] == CELL_WOLF_2:
                return False
            elif self.field[x_new][y_new] == CELL_SHEEP_1:
                return False
        elif figure == CELL_WOLF_2:
            if self.field[x_new][y_new] == CELL_WOLF_1:
                return False
            elif self.field[x_new][y_new] == CELL_SHEEP_2:
                return False

        # Sheep can not step on squares occupied by the wolf of the same player.
        # Sheep can not step on squares occupied by the opposite sheep.
        if figure == CELL_SHEEP_1:
            if self.field[x_new][y_new] == CELL_SHEEP_2 or \
                    self.field[x_new][y_new] == CELL_WOLF_1:
                return False
        elif figure == CELL_SHEEP_2:
            if self.field[x_new][y_new] == CELL_SHEEP_1 or \
                    self.field[x_new][y_new] == CELL_WOLF_2:
                return False

        return True

    def award(self, figure):
        if figure == CELL_RHUBARB:
            return AWARD_RHUBARB
        elif figure == CELL_GRASS:
            return AWARD_GRASS
        else:
            return 0

    def move(self, figure, move):
        if move != MOVE_NONE:
            (x_old, y_old) = self.get_position(figure)
            (x_new, y_new) = self.new_position(x_old, y_old, move)

            if self.valid(figure, x_new, y_new):
                target_figure = self.field[x_new][y_new]

                # wolf of player1 catches the sheep of player2 the game ends immediately and player1 wins and
                # is awarded all the points for the current run and vice versa

                # If the sheep steps on a food object, the food object is consumed (removed from the map) and a score
                # is awarded.

                if figure == CELL_SHEEP_1:
                    if target_figure == CELL_WOLF_2:
                        self.field[x_old][y_old] = CELL_SHEEP_1_d
                        self.score2 += self.score1
                        self.score1 = -1
                        return True
                    else:
                        self.score1 += self.award(target_figure)

                elif figure == CELL_SHEEP_2:
                    if target_figure == CELL_WOLF_1:
                        self.field[x_old][y_old] = CELL_SHEEP_2_d
                        self.score1 += self.score2
                        self.score2 = -1
                        return True
                    else:
                        self.score2 += self.award(target_figure)

                # If the wolf steps on a food object, the food object gets removed but no score is awarded.

                elif figure == CELL_WOLF_1:
                    if target_figure == CELL_SHEEP_2:
                        self.field[x_new][y_new] = CELL_SHEEP_2_d
                        self.score1 += self.score2 + 100
                        self.score2 = -10
                        return True
                    else:
                        shp = self.get_position(CELL_SHEEP_2)
                        self.score1 -= (34 - manhattanDistance(shp, (x_old, y_old)))
                        self.score1 += (34 - manhattanDistance(shp, (x_new, y_new)))

                elif figure == CELL_WOLF_2:
                    if target_figure == CELL_SHEEP_1:
                        self.field[x_new][y_new] = CELL_SHEEP_1_d
                        self.score2 += self.score1 + 100
                        self.score1 = -10
                        return True
                    else:
                        shp = self.get_position(CELL_SHEEP_1)
                        self.score2 -= (34 - manhattanDistance(shp, (x_old, y_old)))
                        self.score2 += (34 - manhattanDistance(shp, (x_new, y_new)))

                # actual figure move
                self.field[x_new][y_new] = figure
                self.field[x_old][y_old] = CELL_EMPTY
                return False

            else:  # if move is not valid
                return False

        else:  # if move = none
            return False

def generate_random_field(entropy, cell_type_counts):
    """
    Generate a random kingsheep map.
    Usage:
    >>> default_counts = {
            CELL_FENCE: 3,
            CELL_RHUBARB: 1,
            CELL_GRASS: 8
        }
    >>> generate_random_field(0.5, default_counts)
    :param entropy: A value in the range(0,1]; how close to each other the elements of the same cell type are placed
    :param cell_type_counts: dictionary of cell_types with their count (divided by 4)
    :return: a 2d field array
    """
    field = [[CELL_EMPTY for _ in range(FIELD_WIDTH)] for _ in range(FIELD_HEIGHT)]

    def next_position(position, length, entropy):
        next_position = position + int(entropy * random.randrange(-position, length - position))
        assert next_position in range(length)
        return next_position

    def place_cells(field, cell_type, count, point_mirror=False, mirror_type=None):
        mirror_type = mirror_type or cell_type
        previous_x = random.randrange(0, round(FIELD_WIDTH / 2))
        previous_y = random.randrange(0, round(FIELD_HEIGHT / 2))
        for _ in range(count):
            for _ in range(int(10 / entropy)):
                x = next_position(previous_x, round(FIELD_WIDTH / 2), entropy)
                y = next_position(previous_y, round(FIELD_HEIGHT / 2), entropy)
                if field[y][x] == CELL_EMPTY:
                    field[y][x] = cell_type
                    if not point_mirror:
                        field[y][-(x+1)] = cell_type
                        field[-(y+1)][x] = cell_type
                    field[-(y+1)][-(x+1)] = mirror_type
                    previous_x, previous_y = x, y
                    break

    for cell_type, count in cell_type_counts.items():
        place_cells(field, cell_type, count)

    place_cells(field, CELL_SHEEP_1, 1, point_mirror=True, mirror_type=CELL_SHEEP_2)
    place_cells(field, CELL_WOLF_1, 1, point_mirror=True, mirror_type=CELL_WOLF_2)

    return field

def manhattanDistance(a, b):
    return (abs(a[0] - b[0]) + abs(a[1] - b[1]))

def _compute_move(f_move, ks, p_num, figure, game_over):
    move = f_move(p_num, ks.get_field())
    result_game_over = ks.move(figure, move)
    game_over = game_over or result_game_over

    return game_over, move

def _kingsheep_iteration(i, ks, player1, player2):
    game_over = False
    iteration_summary = {}

    # sheep1 move
    score_before = ks.score1
    iteration_summary['sheep1'] = {}
    iteration_summary['sheep1']['state'] = ks.get_field()
    game_over, move = _compute_move(f_move=player1.move_sheep,
                                    ks=ks,
                                    p_num=1,
                                    figure=CELL_SHEEP_1,
                                    game_over=game_over)
    iteration_summary['sheep1']['move'] = int(move) + 2
    iteration_summary['sheep1']['reward'] = ks.score1 - score_before
    iteration_summary['sheep1']['next_state'] = ks.get_field()

    if not game_over:
        # sheep2 move
        score_before = ks.score2
        iteration_summary['sheep2'] = {}
        iteration_summary['sheep2']['state'] = ks.get_field()
        game_over, move = _compute_move(f_move=player2.move_sheep,
                                        ks=ks,
                                        p_num=2,
                                        figure=CELL_SHEEP_2,
                                        game_over=game_over)
        iteration_summary['sheep2']['move'] = int(move) + 2
        iteration_summary['sheep2']['reward'] = ks.score2 - score_before
        iteration_summary['sheep2']['next_state'] = ks.get_field()

    if i % 2 == 0 and not game_over:
        # wolf1 move
        score_before = ks.score1
        iteration_summary['wolf1'] = {}
        iteration_summary['wolf1']['state'] = ks.get_field()
        game_over, move = _compute_move(f_move=player1.move_wolf,
                                        ks=ks,
                                        p_num=1,
                                        figure=CELL_WOLF_1,
                                        game_over=game_over)
        iteration_summary['wolf1']['move'] = int(move) + 2
        iteration_summary['wolf1']['reward'] = ks.score1 - score_before
        iteration_summary['wolf1']['next_state'] = ks.get_field()

    if i % 2 == 0 and not game_over:
        # wolf2 move
        score_before = ks.score2
        iteration_summary['wolf2'] = {}
        iteration_summary['wolf2']['state'] = ks.get_field()
        game_over, move = _compute_move(f_move=player2.move_wolf,
                                        ks=ks,
                                        p_num=2,
                                        figure=CELL_WOLF_2,
                                        game_over=game_over)
        iteration_summary['wolf2']['move'] = int(move) + 2
        iteration_summary['wolf2']['reward'] = ks.score2 - score_before
        iteration_summary['wolf2']['next_state'] = ks.get_field()

    return iteration_summary, game_over


## Converting PyTorch model to TorchScript model for C++ Inference
import sys
import os.path as osp
sys.path.append(osp.join('/'.join(osp.dirname(osp.abspath(__file__)).split('/')[:-1]), 'convnet'))

import argparse
import torch
import models

class Options:
    def __init__(self):
        p = osp.dirname(osp.abspath(__file__)).split('/')[:-1]
        self.proj_path = '/'.join(p)
        self.data_path = osp.join('/'.join(p[:-1]), 'dataset/')
        self.sample_path = osp.join(self.data_path, 'train-split.txt')
        self.img_height =  480
        self.img_width = 640
        self.n_class = 3
        self.output_scale = 8
        self.arch = ''

if __name__ == "__main__":
    model_choices = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152',
        'rfnet50', 'rfnet101', 'rfnet152', 'pspnet50', 'pspnet101', 'pspnet18', 'pspnet34']

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        '-a', '--arch', metavar='arch', default='', choices=model_choices,
        help='model architecture: ' + ' | '.join(model_choices) + ' (default: resnet18)'
    )
    parser.add_argument(
        '--checkpoint', required=True, help='model path',
    )
    parser.add_argument(
        '--output-path', default="", help='model path',
    )
    args = parser.parse_args()
    options = Options()

    rslt_path = osp.join(options.proj_path, "result") if args.output_path == "" else args.output_path

    print("loading model...")
    checkpoint = torch.load(args.checkpoint, map_location=torch.device('cpu'))
    options.arch = args.arch if args.arch != '' else checkpoint['arch']
    model = models.build_model(options.arch)
    model.load_state_dict(checkpoint['model_state_dict'])
    model.eval()

    # torch.save({
    #     'epoch': checkpoint['epoch'],
    #     'iteration': checkpoint['iteration'],
    #     'arch': args.arch,
    #     'optim_state_dict': checkpoint['optim_state_dict'],
    #     'model_state_dict': checkpoint['model_state_dict'],
    #     'best_mean_iu': checkpoint['best_mean_iu'],
    #     'best_prec': checkpoint['best_prec'],
    # }, args.checkpoint)

    # random input
    print("tracing model...")
    inp = torch.rand(1, 3, options.img_height, options.img_width)

    # generate a torch.jit.ScriptModule via tracing.
    traced_script_module = torch.jit.trace(model, (inp, inp))
    traced_script_module.save(osp.join(rslt_path, options.arch + "_converted.pt"))
    print("tracing done, model saved...")


from flask import Flask,request, url_for, redirect, render_template, jsonify
from pycaret.regression import *
import pandas as pd
import pickle
import numpy as np

app = Flask(__name__)

model = load_model('model')
cols = ['age', 'job', 'marital', 'education', 'housing', 'loan','contact', 'month', 'day_of_week',
        'duration', 'campaign', 'pdays', 'previous', 'poutcome','emp.var.rate', 'cons.price.idx', 'cons.conf.idx',
        'euribor3m', 'nr.employed']

@app.route('/')
def home():
    return render_template("home.html")

@app.route('/predict',methods=['POST'])
def predict():
    int_features = [x for x in request.form.values()]
    final = np.array(int_features)
    data_unseen = pd.DataFrame([final], columns = cols)
    prediction = predict_model(model, data=data_unseen, round = 0)
    prediction = int(prediction.Label[0])
    try:
        if int(prediction) == 0:
            prediction ='NO suscribe to term deposit'
        elif int(prediction) == 1:
            prediction = 'Suscribe to term deposit!!'
    except ValueError:
        prediction = 'Data Format Error'
    return render_template('result.html',pred='Expected conversion will be - {}'.format(prediction))

@app.route('/predict_api',methods=['POST'])
def predict_api():
    data = request.get_json(force=True)
    data_unseen = pd.DataFrame([data])
    prediction = predict_model(model, data=data_unseen)
    output = prediction.Label[0]
    return jsonify(output)

if __name__ == '__main__':
    app.run(debug=True)


from .base import FunctionalTest

import time

# test if once session is set for authentication
# there is no need to login
class MyListsTest(FunctionalTest):

    def test_logged_in_users_lists_are_saved_as_my_lists(self):
        # email = 'user@tdd.com'
        # self.browser.get(self.live_server_url)
        #
        # # check if email form for logging in exist
        # self.wait_to_be_logged_out(email)
        #
        # self.create_pre_authenticated_session(email)
        # self.browser.get(self.live_server_url)
        # # check if logged in, email should appear on the navbar
        # self.wait_to_be_logged_in(email)

        # Log in this user
        email = 'user@tdd.com'
        self.create_pre_authenticated_session(email)

        # access the server
        self.browser.get(self.live_server_url)

        # add item using helper methods
        self.add_list_item('item 1')
        self.add_list_item('item 2')

        # get the url of the first list
        first_list_url = self.browser.current_url

        # There should be `My lists` link somewhere on the page
        # click it
        self.browser.find_element_by_link_text('My Lists').click()
        # check if the items are there
        self.wait_for(
            lambda: self.browser.find_element_by_link_text('item 1')
        )
        # It should be clickable
        # once clicked it should show the complete list of items
        self.browser.find_element_by_link_text('item 1').click()

        # compare if first_list_url are equal once you click the item in the list
        self.wait_for(
            lambda: self.assertEqual(self.browser.current_url, first_list_url)
        )

        # Go for another list again
        self.browser.get(self.live_server_url)
        self.add_list_item('item 3')
        second_list_url = self.browser.current_url

        # Find My lists again
        self.browser.find_element_by_link_text('My Lists').click()
        # should be clickable
        self.wait_for(
            lambda: self.browser.find_element_by_link_text('item 3')
        )
        # check the current url should url for the second list
        self.wait_for(
            lambda: self.assertEqual(self.browser.current_url, second_list_url)
        )

        # log out and check if My lists disappears
        self.browser.find_element_by_link_text('Log out').click()
        self.wait_for(lambda: self.assertEqual(
            self.browser.find_elements_by_link_text('My Lists'),
            []
        ))


import numpy as np
import cv2
import matplotlib.pyplot as plt
import pandas as pd

pathName=r'Image\miao.jpg'
img=cv2.imread(pathName)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

sift = cv2.xfeatures2d.SIFT_create()
kp,des = sift.detectAndCompute(gray,None)
octave = np.zeros(3598)
for i in range(3598):
    octave[i] = kp[i].octave
rects=plt.bar(range(len(octave)),octave)
plt.show()

# kp = kp[825:835]
# des = des[825:835]
img=cv2.drawKeypoints(gray,kp,img,flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

cv2.imshow('img',img)
cv2.waitKey()


# sudo apt-get install bluez python-bluez
#
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/x232.html
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/c212.html

import bluetooth

def receiveMessages():
  server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

  port = 1
  server_sock.bind(("",port))
  server_sock.listen(1)

  client_sock,address = server_sock.accept()

  data = client_sock.recv(1024)

  client_sock.close()
  server_sock.close()

def sendMessageTo(targetBluetoothMacAddress):
  port = 1
  sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
  sock.connect((targetBluetoothMacAddress, port))
  sock.send("hello!!")
  sock.close()

def lookUpNearbyBluetoothDevices():
  nearby_devices = bluetooth.discover_devices()
  for bdaddr in nearby_devices:
    print(str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]")

lookUpNearbyBluetoothDevices()


print('-' * 30)
print('Sequencia de Fibonacci')
print('-' * 30)
t = int(input('Quantos termos voce quer mostrar? '))
print('~' * 30)
a = 0
b = 1
cont = 1
c = 0
while cont < t:
    if t > c:
        print('{} -> '.format(a), end='')
        c += 1
    if t > c:
        print('{} -> '.format(b), end='')
        c += 1
    else:
        cont = t
    a = a + b
    b = a + b
    cont += 1
print('Fim')
print('~' * 30)


import json
import random
from collection import Collection
from standard import Standard
from pprint import pprint

collection = None

def handle_card(list, golden, message):
    if message == 'LEGENDARY':
        choice = collection.get_legendary_not_in_collection(list)
    else:
        choice = random.choice(list)
    choice['isGolden'] = True if golden else False
    return choice

def generate_card(standard):
    rand = random.uniform(0, 100)
    if rand < 0.10:
        return handle_card(standard.legendary, True, 'LEGENDARY')
    elif rand < 1.06:
        return handle_card(standard.legendary, False, 'LEGENDARY')
    elif rand < 1.36:
        return handle_card(standard.epic, True, 'EPIC')
    elif rand < 5.56:
        return handle_card(standard.epic, False, 'EPIC')
    elif rand < 7.04:
        return handle_card(standard.rare, True, 'RARE')
    elif rand < 28.71:
        return handle_card(standard.rare, False, 'RARE')
    elif rand < 30.33:
        return handle_card(standard.common, True, 'COMMON')
    else:
        return handle_card(standard.common, False, 'COMMON')

def get_non_common_card(standard):
    c = generate_card(standard)
    while c['rarity'] != 'COMMON':
        c = generate_card(standard)
    return c

def generate_pack(standard):
    pack = [generate_card(standard) for x in range(5)]
    commons = [c for c in pack if c['rarity'] == 'COMMON']
    if len(commons) == 5:
        pack.pop()
        pack.append(get_non_common_card(standard))
    for c in pack:
        collection.add_to_collection(c, c['isGolden'])

def main():
    global collection
    cards = json.loads(open('cards.collectible.json', encoding='utf8').read())
    standard_lst = [c for c in cards if (c['set'] in ['GILNEAS', 'LOOTAPALOOZA',
                                                    'EXPERT1', 'ICECROWN', 'UNGORO'])]

    standard = Standard(standard_lst)
    runs = 100
    total = 0
    for i in range(0, runs):
        collection = Collection(standard)
        counter = 0
        while collection.dust_remaining() > 0:
            generate_pack(standard)
            counter += 1

        total += counter
        print(f'{i}/{runs}\t\t', end='\r')

    print(f'Average: {total/runs}')
    print(f'Cost: ${((total/runs)/60)*88:.2f} CAD')

if __name__ == '__main__': main()


def find_max_profit(stock):

    if stock is None or len(stock) < 2:
        return None

    buy = 0
    sell = 0

    memory = (buy, sell)

    for i in range(len(stock)):
        if stock[i] < stock[buy]:
            buy = i

        if stock[i] > stock[buy]:
            sell = i

        if sell > buy:
            if memory[1] < buy or stock[sell] > stock[memory[1]]:
                memory = (buy, sell)

    if buy > sell:
        return 0

    return stock[memory[1]] - stock[memory[0]]


#!/usr/bin/env python

# This script takes in a file consisting of 3 columns:
# ../data/annotations/germinalB/Bcells.GC.CB_450k_methylation.tsv.gz
#
# Chr   Pos     Beta
# chr1	15865	0.872831853992907
# chr1	18827	0.593831488421089
# chr1	29407	0.0518563054261236
# chr1	29425	0.119720029299259
# chr1	29435	0.0494004108738235

# The file above is originated in the script:
#
#

# From the above file it returns a new one:
# '../data/annotations/{}/{}_{}_450k_neighbor_naive.tsv'.format(bcell_type, bcell_type, bcell)
# which contains the methylation and distance to nearest CpG up- and down-stream
#
# Chr	Pos	dist_down	methyl_down	dist_up	methyl_up
# chr1	15865	2962	0.59	2962	0.59
# chr1	18827	10580	0.05	2962	0.87
# chr1	29407	18	    0.12	10580	0.59
# chr1	29425	10	    0.05	18	    0.05
# chr1	29435	39414	0.54	10	    0.12

# importing packages
import gzip
from sys import argv
from pathlib import Path
import subprocess
from zipfile import ZipFile

# Initializing variables
chr_start = int(argv[1])
chr_end = chr_start + 22

input_arr = Path(argv[2])
bcell = str(input_arr).split('/')[-1].split('_')[0]

bcell_type = argv[3]

chr_ls = []
arr_dct = {}
# Count that will keep track on how many lines there are in the input file
count_line = 0

for i in range(chr_start, chr_end):
    chr_ls.append('chr' + str(i))

# Save contents of 450k arr in a dictionary
with gzip.open(input_arr, "rt") as arr:
    next(arr) # skip de 1st line - header
    for line in arr:
        # print(line)
        line = line.rstrip()
        feat = line.split("\t")
        Chr = feat[0]
        Pos = int(float(feat[1]))
        methyl = round(float(feat[2]), 2)
        count_line += 1
        if Chr in chr_ls:
            if Chr not in arr_dct:
                arr_dct[Chr] = {}
            arr_dct[Chr][Pos] = methyl

# Check if the file belongs to a 450K or EPIC array
if count_line < 475000:
    meth_arr = '450k'
    arr_coord_path = Path('../data/annotations/coord_{}.tsv.gz'.format(meth_arr))
    # Chr	Pos
    # chr1	15865
    # chr1	18827
    # chr1	29407
    # chr1	29425
    # chr1	29435
elif count_line > 480000 and count_line < 875000:
    meth_arr = 'epic'
    # Define path of the array coordinate file
    arr_coord_path = Path('../data/annotations/coord_{}_mod.tsv.gz'.format(meth_arr))
    # Chr	Pos
    # chr1	15865
    # chr1	18827
    # chr1	29407
    # chr1	29425
    # chr1	29435

# Define name of the out file
file_out_arr_path = '../data/annotations/{}/{}_{}_{}_neighbor.tsv'.format(bcell_type, bcell_type, bcell, meth_arr)
file_out = open(Path(file_out_arr_path), "wt")
file_out.write("Chr\tPos\tdist_down\tmethyl_down\tdist_up\tmethyl_up\n")

# Write to file and each line is a position with the beta and distance of the nearest up and down-stream CpGs
with gzip.open(arr_coord_path, "rt") as arr:
    next(arr)
    for line in arr:
        line = line.rstrip()
        feat = line.split("\t")
        Chr = feat[0]
        Pos = int(float(feat[1]))
        if Chr in arr_dct:
            dif = [Pos - x for x in arr_dct[Chr].keys()]
            down_ls = [x for x in dif if x < 0]
            up_ls = [x for x in dif if x > 0]
            # Down stream
            if down_ls:
                down = max(down_ls)
            else:
                down = min(up_ls)
            dist_down = abs(down)
            pos_down = Pos - down
            methyl_down = arr_dct[Chr][pos_down]
            # methyl_down=0
            # Up stream
            if up_ls:
                up = min(up_ls)
            else:
                up = max(down_ls)
            dist_up = abs(up)
            pos_up = Pos - up
            methyl_up = arr_dct[Chr][pos_up]
            # methyl_up=0
            line_out = "{}\t{}\t{}\t{}\t{}\t{}\n".format(Chr, Pos, dist_down, methyl_down, dist_up, methyl_up)
            # print(line_out)
            file_out.write(line_out)

file_out.close()

file_out_arr_path_zip = "{}.gz".format(file_out_arr_path)
with ZipFile(file_out_arr_path_zip) as myzip:
    with myzip.open(file_out_arr_path) as myfile:
        print(myfile.read())


from django import forms
from .models import Prescription, DoctorProfile
from patient.models import PatientProfile

class PrescriptionCreationForm(forms.ModelForm):
    class Meta:
        model = Prescription
        fields = ['symptoms', 'prescription', 'pat']
        def __init__(self, *args, **kwargs):
            model = Prescription
            user = kwargs.pop('user','')
            super(PrescriptionCreationForm, self).__init__(*args, **kwargs)
            self.fields['pat']=forms.ModelChoiceField(queryset=PatientProfile.objects.all())


def fasctorization(n):
    arr = []
    tmp = n
    for i in range(2, int(-(-n**0.5//1)+1)):
        if tmp % i == 0:
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            arr.append([i,cnt])
    if tmp != 1:
        arr.append([tmp, 1])

    return arr

def nCr(n,r, mod = 10**9+7):
    r = min(n-r, r)
    nn = denom = 1
    for i in range(1,r+1):
        nn = nn * (n+1-i) % mod
        denom = denom * i % mod
    return nn * pow(denom, mod-2, mod) % mod

n,m = map(int, input().split())
fs = fasctorization(m)
mod = 10**9+7

ans = 1

for f,c in fs:
    pattern = nCr(c + n - 1, c)
    ans *= pattern
    ans %= mod
print(ans)


import subprocess as sp
import cgi
form=cgi.FieldStorage()
user=str(form.getvalue("User_Name"))
user=input("user")
storage=sp.getoutput("id {}".format(user))
lil=storage.split(" ")
if "no" in lil:
        print("user not exist")
else :
	print("wigfwief")


from core import *

def summary(team: dict) -> dict:
    team_name = team["name"]
    data = team["data"]
    info = team["info"]

    if data["average_sandstorm_hatch"].value - data["average_sandstorm_cargo"].value >= 0.25:
        if data["average_sandstorm_hatch"].value == 0:
            pass
        elif data["average_sandstorm_hatch"].value <= 0.5:
            info.append("Can sometimes do one sandstorm hatch")
        elif data["average_sandstorm_hatch"].value <= 0.9:
            info.append("Can mostly do one sandstorm hatch")
        elif data["average_sandstorm_hatch"].value <= 1.0:
            info.append("Can always do one sandstorm hatch")
    elif data["average_sandstorm_hatch"].value - data["average_sandstorm_cargo"].value <= -0.25:
        if data["average_sandstorm_cargo"].value == 0:
            pass
        elif data["average_sandstorm_cargo"].value <= 0.5:
            info.append("Can sometimes do one sandstorm cargo")
        elif data["average_sandstorm_cargo"].value <= 0.9:
            info.append("Can mostly do one sandstorm cargo")
        elif data["average_sandstorm_cargo"].value <= 1.0:
            info.append("Can always do one sandstorm cargo")
    else:
        if data["average_sandstorm_cargo"].value == 0:
            pass
        elif data["average_sandstorm_cargo"].value <= 0.5:
            info.append("Can sometimes do one sandstorm cargo")
        elif data["average_sandstorm_cargo"].value <= 0.9:
            info.append("Can mostly do one sandstorm cargo")
        elif data["average_sandstorm_cargo"].value <= 1.0:
            info.append("Can always do one sandstorm cargo")
        if data["average_sandstorm_hatch"].value == 0:
            pass
        elif data["average_sandstorm_hatch"].value <= 0.5:
            info.append("Can sometimes do one sandstorm hatch")
        elif data["average_sandstorm_hatch"].value <= 0.9:
            info.append("Can mostly do one sandstorm hatch")
        elif data["average_sandstorm_hatch"].value <= 1.0:
            info.append("Can always do one sandstorm hatch")
    if data["average_sandstorm_cargo"].value == 0 and data["average_sandstorm_hatch"].value == 0:
            info.append("Cannot do sandstorm")

    if data["max_piece"].value >= 4:
        info.append("Good gamepiece bot")
        if data["max_hatch"].value - data["max_cargo"].value > 1:
            info.append("Hatch bot")
        elif data["max_hatch"].value - data["max_cargo"].value < -1:
            info.append("Cargo bot")
        else:
            info.append("Can do both")
        if data["higher_level_rocket_average"] == 0:
            info.append("Cannot do higher level rocket")
        elif data["higher_level_rocket_average"] <= 1:
            info.append("Can somewhat do higher level rocket")
        else:
            info.append("Can do higher level rocket")
    else:
        info.append("Not very good gamepiece bot")

    if data["climb"].value < 0.85:
        info.append("Can't climb to level 1 consistently")
    elif data["climb"].value <= 1:
        info.append("Consistent level 1 climb")
    elif data["climb"].value <= 1.65:
        info.append("Sketchy level 2 climb")
    elif data["climb"].value <= 2:
        info.append("Consistent level 2 climb")
    elif data["climb"].value <= 2.65:
        info.append("Sketchy level 3 climb")
    else:
        info.append("Consistent level 3 climb")

    if data["penalty"].value < 1:
        info.append("Not very penalty prone")
    elif data["penalty"].value < 2:
        info.append("Be wary of penalties")
    else:
        info.append("VERY prone to penalties (maybe give copy of manual?)")

    team["info"] = info
    return team

if __name__ == "__main__":
    summary(red_team1)
    summary(red_team2)
    summary(red_team3)

    summary(blue_team1)
    summary(blue_team2)
    summary(blue_team3)

    print(red_team1["name"].value)
    for info in red_team1["info"]:
        print(info)
    print(red_team2["name"].value)
    for info in red_team2["info"]:
        print(info)
    print(red_team3["name"].value)
    for info in red_team3["info"]:
        print(info)
    print(blue_team1["name"].value)
    for info in blue_team1["info"]:
        print(info)
    print(blue_team2["name"].value)
    for info in blue_team2["info"]:
        print(info)
    print(blue_team3["name"].value)
    for info in blue_team3["info"]:
        print(info)


from flask import render_template
from nyceats import app
from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database
import pandas as pd
import psycopg2
from flask import request
import googlemaps
import json
from math import sin, cos, sqrt, atan2, radians

with open('nyceats/conf/gmaps_settings.json', 'r') as f:
    data = json.load(f)

gkey=data ['gmaps']['gkey']
gmaps = googlemaps.Client(key=gkey)

user = 'klapina'
host = 'localhost'
dbname = 'restr_db_all'
db = create_engine('postgres://%s%s/%s'%(user,host,dbname))
con = None
con = psycopg2.connect(database = dbname, user = user)

@app.route('/input')
@app.route('/')
@app.route('/index')
def input():
    return render_template("input.html" )

@app.route('/about')
def about():
    return render_template("about.html")

@app.route('/slides')
def slides():
    return render_template("slides.html")

@app.route('/output')
def nyc_output():
    R = 6373.0

    addr = request.args.get('addr')
    geocode_result = gmaps.geocode(address=addr, components={'locality': 'New York', 'country': 'US'})
    inlat = geocode_result[0]['geometry']['location']['lat']
    inlon = geocode_result[0]['geometry']['location']['lng']
    inlat = radians(inlat)
    inlon = radians(inlon)
    #just select restaurants from the  dtabase
    query = "SELECT name, address,zip,lat,lon,type FROM restr_table"
    query_results=pd.read_sql_query(query,con)

    dist=[]
    col=[]
    for index in range(0,query_results.shape[0]):
        lat1 = radians(query_results.iloc[index]['lat'])
        lon1 = radians(query_results.iloc[index]['lon'])
        dlon = lon1 - inlon
        dlat = lat1 - inlat
        a = sin(dlat / 2)**2 + cos(inlat) * cos(lat1) * sin(dlon / 2)**2
        c = 2 * atan2(sqrt(a), sqrt(1 - a))
        distance = 1000 *R * c
        dist.append(distance) # m
        mycolor="FFFF00"
        if query_results.iloc[index]['type']>1:
            mycolor="1D7BfD"
        if query_results.iloc[index]['type']==1:
            mycolor="FD1D7B"

        col.append(mycolor) # m

    query_results['dist']=dist
    query_results['color']=col

    all_names=query_results.sort_values(by='dist')

    return render_template("output.html",  all_names=all_names)

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


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

from django.conf import settings
from oneweekonething.utils import logger, cache
from .models import Category

def seo_processor(requests):
    key = 'seo_processor'
    value = cache.get(key)
    if value:
        logger.info('get processor cache.')
        return value
    else:
        logger.info('set processor cache.')
        value = {
            'SITE_NAME': settings.SITE_NAME,
            'nav_category_list': Category.objects.all(),
            'SITE_BASE_URL': requests.scheme + '://' + requests.get_host() + '/',

        }
        cache.set(key, value, 60 * 60 * 10)
        return value


# -*- coding: utf-8 -*-
"""
Created on Wed May 03 15:01:31 2017

@author: jdkern
"""
from __future__ import division
from sklearn import linear_model
import pandas as pd
import numpy as np

#==============================================================================

df_mwh1 = pd.read_csv('NEISO/mwh_1.csv',header=0)
df_mwh2 = pd.read_csv('NEISO/mwh_2.csv',header=0)
df_mwh3 = pd.read_csv('NEISO/mwh_3.csv',header=0)
df_gen = pd.read_excel('../Model_setup/NEISO_data_file/generators.xlsx',header=0)

last_hour = df_mwh1['Time'].iloc[-1]

zonal_prices = np.zeros((last_hour,8))

zones = ['CT','ME','NH','NEMA','RI','SEMA','VT','WCMA']

for z in zones:

    z_index = zones.index(z)

    z1 = df_mwh1.loc[df_mwh1['Zones']==z]
    z2 = df_mwh2.loc[df_mwh1['Zones']==z]
    z3 = df_mwh3.loc[df_mwh1['Zones']==z]

    for i in range(0,last_hour):

        h1 = z1.loc[z1['Time']==i+1]
        h2 = z2.loc[z1['Time']==i+1]
        h3 = z3.loc[z1['Time']==i+1]

        o1 = h1.loc[h1['Value']>0]
        o2 = h2.loc[h2['Value']>0]
        o3 = h3.loc[h3['Value']>0]

        m1 = np.max(o1.loc[:,'$/MWh'])
        m2 = np.max(o2.loc[:,'$/MWh'])
        m3 = np.max(o3.loc[:,'$/MWh'])

        if np.isnan(m1) > 0:
            m1 = 0
        if np.isnan(m2) > 0:
            m2 = 0
        if np.isnan(m3) > 0:
            m3 = 0

        zonal_prices[i,z_index] = np.max((m1,m2,m3))

no_hours = last_hour
no_days = int(no_hours/24)

daily_prices = np.zeros((no_days,8))

for i in range(0,no_days):

    for z in zones:

        z_index = zones.index(z)

        daily_prices[i,z_index] = np.mean(zonal_prices[i*24:i*24+24,z_index])

hourly = pd.DataFrame(zonal_prices)
hourly.columns = zones
hourly.to_excel('NEISO/sim_hourly_prices.xlsx')

daily = pd.DataFrame(daily_prices)
daily.columns = zones
daily.to_excel('NEISO/sim_daily_prices.xlsx')

##########################################################
##            Weight by zone and bias correct
##########################################################
#
##simulated prices
#df_prices = pd.read_csv('NEISO/prices_2010_2011.csv',header=0)
#num_days = int(len(df_prices)/24)
#
##regression
#X = df_prices.loc[:,:'WCMA']
#y = df_prices.loc[:,'ICE']
#reg = linear_model.LinearRegression(fit_intercept=False)
#reg.fit(X,y)
#
#sim_hourly = np.zeros((no_hours,1))
#sim_daily = np.zeros((no_days,1))
#
#for i in range(0,no_hours):
#
#    s = hourly.loc[i,:'WCMA'].values
#    s = s.reshape((1,len(s)))
#    sim_hourly[i] = reg.predict(s)
#
#for i in range(0,no_days):
#
#    s = daily.loc[i,:'WCMA'].values
#    s = s.reshape((1,len(s)))
#    sim_daily[i] = reg.predict(s)
#
#SD = pd.DataFrame(sim_daily)
#SD.columns = ['NEISO']
#SD.to_excel('NEISO/weighted_daily_prices.xlsx')
#
#SH = pd.DataFrame(sim_hourly)
#SH.columns = ['NEISO']
#SH.to_excel('NEISO/weighted_hourly_prices.xlsx')


from Acquisition import aq_inner
from Acquisition import aq_parent
from opengever.activity import ACTIVITY_TRANSLATIONS
from opengever.activity import base_notification_center
from opengever.activity.base import BaseActivity
from opengever.activity.model.notification import Notification
from opengever.activity.roles import TASK_OLD_RESPONSIBLE_ROLE
from opengever.activity.roles import TASK_REMINDER_WATCHER_ROLE
from opengever.activity.roles import WATCHER_ROLE
from opengever.base.model import get_locale
from opengever.ogds.base.actor import Actor
from opengever.ogds.base.actor import SYSTEM_ACTOR_ID
from opengever.task import _
from opengever.task import FINISHED_TASK_STATES
from opengever.task.response_description import ResponseDescription
from plone import api
from Products.CMFPlone import PloneMessageFactory
from Products.CMFPlone.utils import safe_unicode

class BaseTaskActivity(BaseActivity):

    CONTAINER_TITLE_MAX_LENGHT = 30

    @property
    def dossier_title(self):
        """If the task is in a subdossier, return its title, otherwise
        return the title of the main dossier (or inbox for a forwarding)"""

        # context can be a plone task or a task model
        dossier_title = self.context.get_containing_dossier_title()
        subdossier_title = self.context.get_containing_subdossier()

        container_title = safe_unicode(subdossier_title or dossier_title)
        return container_title

    @property
    def title(self):
        task_title = super(BaseTaskActivity, self).title

        if not self.dossier_title:
            # Just to be safe, but this should not happen, except in tests
            # where tasks are created directly on the site root.
            return task_title

        if len(self.dossier_title) > self.CONTAINER_TITLE_MAX_LENGHT:
            cropped_dossier_title = self.dossier_title[:self.CONTAINER_TITLE_MAX_LENGHT - 3] + u"..."
        else:
            cropped_dossier_title = self.dossier_title

        return {
            code: u"{dossier_title} - {task_title}".format(
                dossier_title=cropped_dossier_title, task_title=task_title[code]
            )
            for code in self._get_supported_languages()
        }

class TaskAddedActivity(BaseTaskActivity):
    """Activity representation for adding a task.
    """

    @property
    def kind(self):
        return PloneMessageFactory(u'task-added', default=u'Task added')

    @property
    def label(self):
        return self.translate_to_all_languages(
            _('transition_label_default', u'Task opened'))

    @property
    def summary(self):
        actor = Actor.lookup(self.context.Creator())
        msg = _('label_task_added', u'New task opened by ${user}',
                mapping={'user': actor.get_label(with_principal=False)})

        if self.context.is_private:
            msg = _('label_private_task_added',
                    default=u'New task (private) opened by ${user}',
                    mapping={'user': actor.get_label(with_principal=False)})

        return self.translate_to_all_languages(msg)

    @property
    def description(self):
        descriptions = {}
        for code in self._get_supported_languages():
            descriptions[code] = self.render_description_markup(
                self.collect_description_data(code), code)

        return descriptions

    def render_description_markup(self, data, language):
        msg = u'

'
        for label, value in data:
            msg = u'{}
{}	'.format(
                msg, self.translate(label, language))
            # Break lines correctly in the table rows
            if value:
                msg += u"
".join(value.splitlines())
            msg += u"
"
        return u'{}

'.format(msg)

    def collect_description_data(self, language):
        """Returns a list with [label, value] pairs.
        """
        informed_principals = [Actor.lookup(actorid).get_label() for actorid in
                               self.context.informed_principals]
        data = [
            [_('label_task_title', u'Task title'), self.context.title],
            [_('label_deadline', u'Deadline'),
             api.portal.get_localized_time(str(self.context.deadline))],
            [_('label_task_type', u'Task Type'),
             self.context.get_task_type_label(language=language)],
            [_('label_dossier_title', u'Dossier title'),
             self.dossier_title],
            [_('label_text', u'Text'),
             self.context.text if self.context.text else u'-'],
            [_('label_responsible', u'Responsible'),
             self.context.get_responsible_actor().get_label()],
            [_('label_issuer', u'Issuer'),
             self.context.get_issuer_actor().get_label()],
            [_('label_informed_principals', u'Info at'),
             ", ".join(informed_principals) or '-'],
        ]
        if self.context.get_is_subtask():
            parent = aq_parent(aq_inner(self.context))
            data.insert(
                4, [_('label_containing_task', u'Containing tasks'), parent.title]
            )
        return data

    def before_recording(self):
        self.center.add_task_responsible(self.context,
                                         self.context.responsible)
        self.center.add_task_issuer(self.context, self.context.issuer)
        for principal in self.context.informed_principals:
            self.center.add_watcher_to_resource(
                self.context, principal, omit_watcher_added_event=True)

    def after_recording(self):
        for principal in self.context.informed_principals:
            self.center.remove_watcher_from_resource(
                self.context, principal, WATCHER_ROLE)

class TaskWatcherAddedActivity(BaseTaskActivity):
    """Activity representation for a watcher being added to a task.
    """

    def __init__(self, context, request, watcherid):
        super(TaskWatcherAddedActivity, self).__init__(context, request)
        self.watcherid = watcherid

    @property
    def kind(self):
        return PloneMessageFactory(u'task-watcher-added', default=u'Watcher added to task')

    @property
    def summary(self):
        return self.translate_to_all_languages(
            _('summary_task_watcher_added', u'Added as watcher of the task by ${user}',
              mapping={'user': Actor.lookup(self.actor_id).get_link()}))

    @property
    def description(self):
        return {}

    @property
    def label(self):
        msg = _('label_task_watcher_added', u'Added as watcher of the task')
        return self.translate_to_all_languages(msg)

    def add_activity(self):
        return super(TaskWatcherAddedActivity, self).add_activity(
            notification_recipients=[self.watcherid])

class BaseTaskResponseActivity(BaseTaskActivity):
    """Abstract base class for all task-response related activities.

    The TaskResponseActivity class is a representation for every activity which
    can be done on a task. It provides every needed attribute/methods to
    record the activity in the notification center based on a response object.
    """

    def __init__(self, context, request, response):
        super(BaseTaskResponseActivity, self).__init__(context, request)
        self.response = response

    @property
    def summary(self):
        return self.translate_to_all_languages(
            ResponseDescription.get(response=self.response).msg())

    @property
    def label(self):
        return self.translate_to_all_languages(
            ResponseDescription.get(response=self.response).label())

    @property
    def description(self):
        return {get_locale(): self.response.text}

class TaskCommentedActivity(BaseTaskResponseActivity):
    """Activity representation for commenting a task.
    """
    @property
    def kind(self):
        return PloneMessageFactory(u'task-commented', default=u'Task commented')

class TaskTransitionActivity(BaseTaskResponseActivity):
    """Activity which represents a transition task transition change.
    """

    IGNORED_TRANSITIONS = [
        'transition-add-subtask',
        'transition-cancel-subtask',
        'transition-close-subtask',
        'task-transition-reassign',
        'task-transition-change-issuer',
        'forwarding-transition-reassign',
        'forwarding-transition-reassign-refused',
        'forwarding-transition-change-issuer',
    ]

    @property
    def kind(self):
        return self.response.transition

    def record(self):
        if self._is_ignored_transition():
            return

        return super(TaskTransitionActivity, self).record()

    def _is_ignored_transition(self):
        return self.response.transition in self.IGNORED_TRANSITIONS

class TaskChangeIssuerActivity(TaskTransitionActivity):

    def before_recording(self):
        change = ResponseDescription.get(response=self.response).get_change('issuer')
        if not change or change.get('before') == self.context.issuer:
            return

        self.center.add_task_issuer(self.context, self.context.issuer)
        self.center.remove_task_issuer(self.context, change.get('before'))

    def _is_ignored_transition(self):
        return False

class TaskReassignActivity(TaskTransitionActivity):
    """Updates the watcherlist for the current task because of the responsible
    change on the task.

    The issuer and the old and the new responsible should be notified.
    After recording the activity the old responsible should be removed from
    the watchers list.
    """

    def before_recording(self):
        """Adds new responsible to watchers list.
        And change roles for old responsible from TASK_RESPONSIBLE
        to OLD_RESPONSIBLE.
        """
        change = ResponseDescription.get(response=self.response).get_change('responsible')

        # If the `responsible` is not part of the response changes, it means
        # that the same responsible in another org unit has been selected. So
        # there is no need to manipulate the watcher list, everything stays
        # the same.
        if not change or change.get('before') == self.context.responsible:
            return

        self.center.add_task_responsible(self.context, self.context.responsible)
        self.center.remove_task_responsible(self.context, change.get('before'))
        self.center.add_watcher_to_resource(
            self.context, change.get('before'), TASK_OLD_RESPONSIBLE_ROLE)

    def after_recording(self):
        """Remove old responsible from watchers list.
        """
        change = ResponseDescription.get(response=self.response).get_change('responsible')
        self.center.remove_watcher_from_resource(
            self.context, change.get('before'), TASK_OLD_RESPONSIBLE_ROLE)

    def _is_ignored_transition(self):
        return False

class TaskReminderActivity(BaseTaskActivity):
    kind = 'task-reminder'
    IGNORED_STATES = FINISHED_TASK_STATES + ['task-state-resolved']
    system_activity = True

    def __init__(self, sql_context, request):
        super(TaskReminderActivity, self).__init__(sql_context, request)

        # A TaskReminderAcitivty requires a SQL-Object as a context because we
        # have no plone-object on activity-generation due to multi-admin setup.
        #
        # Thus we need to change the notification-center instance to the
        # default instead the PloneNotifiactionCenter
        self.center = base_notification_center()

    @property
    def summary(self):
        return self.translate_to_all_languages(
            _('task_reminder_activity_summary', u'Deadline is on ${deadline}',
              mapping={'deadline': self._deadline()}))

    @property
    def label(self):
        return self.translate_to_all_languages(ACTIVITY_TRANSLATIONS[self.kind])

    @property
    def description(self):
        return {}

    def _deadline(self):
        return api.portal.get_localized_time(
            self.context.deadline, long_format=True)

    def record(self, notify_for_user_id):
        """Adds the activity and the related notification for the given user-id.

        Let the notification-center handle creating the activity and
        notifications will not work. The notification-center would create
        notifications for all watchers of a given resource. But we only want
        to create one notification for the current acitvity-object and the given
        user-id.
        """

        if self.context.review_state in self.IGNORED_STATES:
            return

        activity = self.add_activity()
        notification = Notification(userid=notify_for_user_id, activity=activity)

        for dispatcher in self.center.dispatchers:
            if TASK_REMINDER_WATCHER_ROLE in dispatcher.get_dispatched_roles_for(
                    notification.activity.kind, notify_for_user_id):
                dispatcher.dispatch_notification(notification)

    def add_activity(self):
        # Because we use the default NotificationCenter, we need to provide
        # the oguid instead the object itself. See __init__ for more information.
        return self.center._add_activity(
            self.context.oguid,
            self.kind,
            self.title,
            self.label,
            self.summary,
            SYSTEM_ACTOR_ID if self.system_activity else self.actor_id,
            self.description)


import asyncio
import aiohttp
import sortedcontainers
import logging
import dateutil.parser
import collections
from typing import Dict

from hailtop.utils import time_msecs, secret_alnum_string, periodically_call
from hailtop import aiotools, aiogoogle
from gear import Database

from .instance import Instance
from .zone_monitor import ZoneMonitor

log = logging.getLogger('inst_collection')

class InstanceCollection:
    def __init__(self, app, name, machine_name_prefix, is_pool):
        self.app = app
        self.db: Database = app['db']
        self.compute_client: aiogoogle.ComputeClient = self.app['compute_client']
        self.zone_monitor: ZoneMonitor = self.app['zone_monitor']

        self.name = name
        self.machine_name_prefix = f'{machine_name_prefix}{self.name}-'
        self.is_pool = is_pool

        self.name_instance: Dict[str, Instance] = {}
        self.live_free_cores_mcpu_by_zone: Dict[str, int] = collections.defaultdict(int)

        self.instances_by_last_updated = sortedcontainers.SortedSet(key=lambda instance: instance.last_updated)

        self.n_instances_by_state = {'pending': 0, 'active': 0, 'inactive': 0, 'deleted': 0}

        # pending and active
        self.live_free_cores_mcpu = 0
        self.live_total_cores_mcpu = 0

        self.boot_disk_size_gb = None
        self.max_instances = None
        self.max_live_instances = None

        self.task_manager = aiotools.BackgroundTaskManager()

    async def async_init(self):
        self.task_manager.ensure_future(self.monitor_instances_loop())

    def shutdown(self):
        self.task_manager.shutdown()

    @property
    def n_instances(self):
        return len(self.name_instance)

    def generate_machine_name(self):
        while True:
            # 36 ** 5 = ~60M
            suffix = secret_alnum_string(5, case='lower')
            machine_name = f'{self.machine_name_prefix}{suffix}'
            if machine_name not in self.name_instance:
                break
        return machine_name

    def adjust_for_remove_instance(self, instance):
        assert instance in self.instances_by_last_updated

        self.instances_by_last_updated.remove(instance)

        self.n_instances_by_state[instance.state] -= 1

        if instance.state in ('pending', 'active'):
            self.live_free_cores_mcpu -= max(0, instance.free_cores_mcpu)
            self.live_total_cores_mcpu -= instance.cores_mcpu
            self.live_free_cores_mcpu_by_zone[instance.zone] -= max(0, instance.free_cores_mcpu)

    async def remove_instance(self, instance, reason, timestamp=None):
        await instance.deactivate(reason, timestamp)

        await self.db.just_execute('UPDATE instances SET removed = 1 WHERE name = %s;', (instance.name,))

        self.adjust_for_remove_instance(instance)
        del self.name_instance[instance.name]

    def adjust_for_add_instance(self, instance):
        assert instance not in self.instances_by_last_updated

        self.n_instances_by_state[instance.state] += 1

        self.instances_by_last_updated.add(instance)
        if instance.state in ('pending', 'active'):
            self.live_free_cores_mcpu += max(0, instance.free_cores_mcpu)
            self.live_total_cores_mcpu += instance.cores_mcpu
            self.live_free_cores_mcpu_by_zone[instance.zone] += max(0, instance.free_cores_mcpu)

    def add_instance(self, instance):
        assert instance.name not in self.name_instance

        self.name_instance[instance.name] = instance
        self.adjust_for_add_instance(instance)

    async def call_delete_instance(self, instance, reason, timestamp=None, force=False):
        if instance.state == 'deleted' and not force:
            return
        if instance.state not in ('inactive', 'deleted'):
            await instance.deactivate(reason, timestamp)

        try:
            await self.compute_client.delete(f'/zones/{instance.zone}/instances/{instance.name}')
        except aiohttp.ClientResponseError as e:
            if e.status == 404:
                log.info(f'{instance} already delete done')
                await self.remove_instance(instance, reason, timestamp)
                return
            raise

    async def check_on_instance(self, instance):
        active_and_healthy = await instance.check_is_active_and_healthy()
        if active_and_healthy:
            return

        try:
            spec = await self.compute_client.get(f'/zones/{instance.zone}/instances/{instance.name}')
        except aiohttp.ClientResponseError as e:
            if e.status == 404:
                await self.remove_instance(instance, 'does_not_exist')
                return
            raise

        if (instance.state == 'active'
                and instance.failed_request_count > 5
                and time_msecs() - instance.last_updated > 5 * 60 * 1000):
            log.exception(f'deleting {instance} with {instance.failed_request_count} failed request counts after more than 5 minutes')
            await self.call_delete_instance(instance, 'not_responding')
            return

        # PROVISIONING, STAGING, RUNNING, STOPPING, TERMINATED
        gce_state = spec['status']

        log.info(f'{instance} gce_state {gce_state}')

        if (
            gce_state == 'PROVISIONING'
            and instance.state == 'pending'
            and time_msecs() - instance.time_created > 5 * 60 * 1000
        ):
            log.exception(f'{instance} did not provision within 5m after creation, deleting')
            await self.call_delete_instance(instance, 'activation_timeout')

        if gce_state in ('STOPPING', 'TERMINATED'):
            log.info(f'{instance} live but stopping or terminated, deactivating')
            await instance.deactivate('terminated')

        if gce_state in ('STAGING', 'RUNNING'):
            last_start_timestamp = spec.get('lastStartTimestamp')
            assert last_start_timestamp is not None, f'lastStartTimestamp does not exist {spec}'
            last_start_time_msecs = dateutil.parser.isoparse(last_start_timestamp).timestamp() * 1000

            if instance.state == 'pending' and time_msecs() - last_start_time_msecs > 5 * 60 * 1000:
                log.exception(f'{instance} did not activate within 5m after starting, deleting')
                await self.call_delete_instance(instance, 'activation_timeout')

        if instance.state == 'inactive':
            log.info(f'{instance} is inactive, deleting')
            await self.call_delete_instance(instance, 'inactive')

        await instance.update_timestamp()

    async def monitor_instances(self):
        if self.instances_by_last_updated:
            # [:50] are the fifty smallest (oldest)
            instances = self.instances_by_last_updated[:50]

            async def check(instance):
                since_last_updated = time_msecs() - instance.last_updated
                if since_last_updated > 60 * 1000:
                    log.info(f'checking on {instance}, last updated {since_last_updated / 1000}s ago')
                    await self.check_on_instance(instance)

            await asyncio.gather(*[check(instance) for instance in instances])

    async def monitor_instances_loop(self):
        await periodically_call(1, self.monitor_instances)


# -*- coding: utf-8 -*-
"""
/***************************************************************************
 MizogeoDialog
                                 A QGIS plugin
 Mise au format Geostandard des cartes de bruit 2012 .
                             -------------------
        begin                : 2017-04-24
        git sha              : $Format:%H$
        copyright            : (C) 2017 by cerema
        email                : sandra.benelli@cerema.fr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os

from PyQt4 import QtGui, uic
import interfaceUtilisateur
#from interfaceUtilisateur import FenetreZbrCbs, FenetrePpbe, FenetreAgregation, FenetreConcatenation, MethodesPartagees

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'mizogeo_dialog_base.ui'))

################Definition des icones#####################################################
iconCerema=QtGui.QPixmap(os.path.join(os.path.dirname(os.path.abspath(__file__)),'icones', "iconCerema.gif"))
iconLogo = QtGui.QPixmap(os.path.join(os.path.dirname(os.path.abspath(__file__)),'icones',"logoMizogeo.gif"))
iconEcrito = QtGui.QPixmap(os.path.join(os.path.dirname(os.path.abspath(__file__)),'icones',"ecritoMizogeo.gif"))
###########################################################################################

class MizogeoDialog(QtGui.QDialog, FORM_CLASS, interfaceUtilisateur.MethodesPartagees):
    def __init__(self, parent=None):
        """Constructor."""
        super(MizogeoDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.ImageCerema.setPixmap(iconCerema)
        self.ImageCerema.setScaledContents(True)
        self.LienCerema.setText('''Visitez notre site internet''')
        self.LienCerema.setOpenExternalLinks(True)
        #self.ImageCerema.clicked.connect(http://www.cerema.fr/)
        self.ImageLogo.setPixmap(iconLogo)
        self.ImageLogo.setScaledContents(True)
        self.ImageEcrito.setPixmap(iconEcrito)
        self.ImageEcrito.setScaledContents(True)
        self.Btn_Aide.clicked.connect(lambda : self.OuvrirAide(1))
        self.BoutonZbrCbs.clicked.connect(self.OuvertureFenetreZbrCbs) #lien entre le bouton Btn_ZbrCbs du fichier Dialog, et la méthode fenetreZbrCbs definie dessous. principe du signal / slots
        self.BoutonPpbe.clicked.connect(self.OuvertureFenetrePpbe)
        self.BoutonAgregation.clicked.connect(self.OuvertureFenetreAgregation)
        self.BoutonAssemblage.clicked.connect(self.OuvertureFenetreAssemblage)
        self.Bonus.clicked.connect(self.EcouterMusiqueRads2011)

    def OuvertureFenetreZbrCbs(self):
        """
        ouverture de la fenetre de creation des ZBR et CBS
        """
        self.fenetre=interfaceUtilisateur.FenetreZbrCbs() #creation de l instance issue de la classe FenetreZbrCbs
        self.fenetre.show() #On utilise exec_() plutot que show() car il bloque la fenetre qui lance la deuxieme, alors que show() laisse la premiere fenetre active

    def OuvertureFenetrePpbe(self):
        """
        ouverture de la fenetre de creation des Ppbe
        """
        self.fenetre=interfaceUtilisateur.FenetrePpbe() #creation de l instance issue de la classe FenetrePpbe
        self.fenetre.show()

    def OuvertureFenetreAgregation(self):
        """
        ouverture de la fenetre d'agregation
        """
        self.fenetre=interfaceUtilisateur.FenetreAgregation()
        self.fenetre.show()

    def OuvertureFenetreAssemblage(self):
        self.fenetre=interfaceUtilisateur.FenetreAssemblage()
        self.fenetre.show()#lancer la fenetre suivante. On utilise exec_() plutot que show() car il bloque la fenetre qui lance la deuxieme, alors que show() laisse la premiere fenetre active


#!/bin/python3
'''
Python provides built-in sort/sorted functions that use timsort internally.
You cannot use these built-in functions anywhere in this file.

Every function in this file takes a comparator `cmp` as input which controls how the elements of the list should be compared against each other.
If cmp(a,b) returns -1, then a<b;
if cmp(a,b) returns  1, then a>b;
if cmp(a,b) returns  0, then a==b.
'''

import random

def cmp_standard(a,b):
    '''
    used for sorting from lowest to highest
    '''
    if a<b:
        return -1
    if b<a:
        return 1
    return 0

def cmp_reverse(a,b):
    '''
    used for sorting from highest to lowest
    '''
    if a<b:
        return 1
    if b<a:
        return -1
    return 0

def cmp_last_digit(a,b):
    '''
    used for sorting based on the last digit only
    '''
    return cmp_standard(a%10,b%10)

def _merged(xs, ys, cmp=cmp_standard):
    '''
    Assumes that both xs and ys are sorted,
    and returns a new list containing the elements of both xs and ys.
    Runs in linear time.
    '''

    newlist = []
    i = 0
    j = 0

    while i<len(xs) and j<len(ys):
        if cmp==cmp_standard:
            if cmp(xs[i],ys[j]) <= 0:
                newlist.append(xs[i])
                i+=1
            else:  #when cmp == 1
                newlist.append(ys[j])
                j+=1
        else: # when cmp = cmp_reverse
            if cmp(xs[i],ys[j]) <= 0:
                newlist.append(xs[i])
                i+=1
            else:  #when cmp == 1
                newlist.append(ys[j])
                j+=1
    return newlist + xs[i:] + ys[j:]

def merge_sorted(xs, cmp=cmp_standard):
    '''
    Merge sort is the standard O(n log n) sorting algorithm.
    Recall that the merge sort pseudo code is:

        if xs has 1 element
            it is sorted, so return xs
        else
            divide the list into two halves left,right
            sort the left
            sort the right
            merge the two sorted halves

    You should return a sorted version of the input list xs
    '''
    if len(xs) <= 1:
        return xs
    else:
        left = xs[0:len(xs)//2]
        right = xs[len(xs)//2:]
        sorted_left = merge_sorted(left, cmp) # sort the left
        sorted_right = merge_sorted(right, cmp) # sort the right
        return _merged(sorted_left, sorted_right, cmp)

def quick_sorted(xs, cmp=cmp_standard):
    '''
    Quicksort is like mergesort,
    but it uses a different strategy to split the list.
    Instead of splitting the list down the middle,
    a "pivot" value is randomly selected,
    and the list is split into a "less than" sublist and a "greater than" sublist.

    The pseudocode is:

        if xs has 1 element
            it is sorted, so return xs
        else
            select a pivot value p
            put all the values less than p in a list
            put all the values greater than p in a list
            sort both lists recursively
            return the concatenation of (less than, p, and greater than)

    You should return a sorted version of the input list xs
    '''
    list_less = []
    list_greater = []
    list_equal = []

    if len(xs) <= 1:
        return xs
    else:
        p = xs[0]
        for x in xs:
            if x<p:
                list_less.append(x)
            elif x>p:
                list_greater.append(x)
            else: # x == p
                list_equal.append(x)
        sorted_less = quick_sorted(list_less, cmp)
        sorted_greater = quick_sorted(list_greater, cmp)

        if cmp==cmp_standard:
            return sorted_less + list_equal + sorted_greater
        else: # if cmp=cmp_reverse
            return sorted_greater + list_equal + sorted_less

def quick_sort(xs, cmp=cmp_standard):
    '''
    EXTRA CREDIT:
    The main advantage of quick_sort is that it can be implemented in-place,
    i.e. with O(1) memory requirement.
    Merge sort, on the other hand, has an O(n) memory requirement.

    Follow the pseudocode of the Lomuto partition scheme given on wikipedia
    (https://en.wikipedia.org/wiki/Quicksort#Algorithm)
    to implement quick_sort as an in-place algorithm.
    You should directly modify the input xs variable instead of returning a copy of the list.
    '''
    if len(xs) <= 1:
        return xs
    def helper(xs,lo,hi):
        if lo<hi:
            p = partition(xs,lo,hi,cmp)
            helper(xs,lo,p-1)
            helper(xs,p+1,hi)
            return xs
    return helper(xs,0,len(xs)-1)

def partition(xs,lo,hi,cmp=cmp_standard):
    pivot = xs[hi]
    i = lo

    for j in range(lo,hi):
        if (xs[j] < pivot and cmp == cmp_standard) or (xs[j] > pivot and cmp==cmp_reverse):
            xs[i], xs[j] = xs[j], xs[i]
            i += 1
    xs[i],xs[hi] = xs[hi],xs[i]
    return i


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string

    returns: True if char is in aStr; False otherwise
    '''
    if len(aStr) == 0:
        return False
    elif len(aStr) == 1:
        return char == aStr
    else:
        midChar = aStr[len(aStr)//2]
        if midChar > char:
            return isIn(char, aStr[0:len(aStr)//2])
        elif midChar < char:
            return isIn(char, aStr[len(aStr)//2 + 1:len(aStr)])
        else:
            return True

print(isIn('z', 'defgil'))


def sortbyParity(A):
    odd = []
    i=0
    even = []
    j=0
    result = [0]*(len(A))
    print (result)
    k=0
    for num in A:
        if num % 2 ==0:
            even.append(num)
            print ('in even parity:',even)
        else:
            odd.append(num)
            print ('in odd parity:',odd)
    while (k<len(A)):
        print ('Value of K:',k)
        if k%2 == 0:
            result[k]=even[i]
            i=i+1
        else:
            result[k]=odd[j]
            j=j+1
        k=k+1
    return result

print (sortbyParity([4,2,5,7]))


#!/usr/bin/python
#
#  Delete the label image from an Aperio SVS file.
#
#  Original by CMU, modified Caleb Grenko
#  cagrenko@davidson.edu
#
#  (i/o,  porting to Python 3)
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation, version 2.1.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with this program. If not, see
#  <http://www.gnu.org/licenses/>.
#

import string
import struct
import sys
import os
import argparse

ASCII = 2
SHORT = 3
LONG = 4
LONG8 = 16

IMAGE_DESCRIPTION = 270
STRIP_OFFSETS = 273
STRIP_BYTE_COUNTS = 279

class TiffFile:
    def __init__(self, path):
        self.file = open(path, 'r+b')

        # Check header, decide endianness
        endian = self.file.read(2)
        if endian == 'II':
            self._fmt_prefix = '<'
        elif endian == 'MM':
            self._fmt_prefix = '>'
        else:
            raise IOError('Not a TIFF file')

        # Check TIFF version
        self._bigtiff = False
        version = self.read_fmt('H')
        if version == 42:
            pass
        elif version == 43:
            self._bigtiff = True
            magic2, reserved = self.read_fmt('HH')
            if magic2 != 8 or reserved != 0:
                raise IOError('Bad BigTIFF header')
        else:
            raise IOError('Not a TIFF file')

        # Read directories
        self.directories = []
        while True:
            in_pointer_offset = self.file.tell()
            directory_offset = self.read_fmt('Z')
            if directory_offset == 0:
                break
            self.file.seek(directory_offset)
            self.directories.append(TiffDirectory(self, in_pointer_offset))

    def _convert_format(self, fmt):
        # Format strings can have special characters:
        # y: 16-bit   signed on little TIFF, 64-bit   signed on BigTIFF
        # Y: 16-bit unsigned on little TIFF, 64-bit unsigned on BigTIFF
        # z: 32-bit   signed on little TIFF, 64-bit   signed on BigTIFF
        # Z: 32-bit unsigned on little TIFF, 64-bit unsigned on BigTIFF
        if self._bigtiff:
            fmt = fmt.translate(str.maketrans('yYzZ', 'qQqQ'))
        else:
            fmt = fmt.translate(str.maketrans('yYzZ', 'hHiI'))
        return self._fmt_prefix + fmt

    def fmt_size(self, fmt):
        return struct.calcsize(self._convert_format(fmt))

    def read_fmt(self, fmt, force_list=False):
        fmt = self._convert_format(fmt)
        vals = struct.unpack(fmt, self.file.read(struct.calcsize(fmt)))
        if len(vals) == 1 and not force_list:
            return vals[0]
        else:
            return vals

    def write_fmt(self, fmt, *args):
        fmt = self._convert_format(fmt)
        self.file.write(struct.pack(fmt, *args))

class TiffDirectory(object):
    def __init__(self, fh, in_pointer_offset):
        self.in_pointer_offset = in_pointer_offset
        self.entries = {}
        count = fh.read_fmt('Y')
        for _ in range(count):
            entry = TiffEntry(fh)
            self.entries[entry.tag] = entry
        self.out_pointer_offset = fh.tell()

class TiffEntry(object):
    def __init__(self, fh):
        self.start = fh.tell()
        self.tag, self.type, self.count, self.value_offset = \
                fh.read_fmt('HHZZ')
        self._fh = fh

    def value(self):
        if self.type == ASCII:
            item_fmt = 'c'
        elif self.type == SHORT:
            item_fmt = 'H'
        elif self.type == LONG:
            item_fmt = 'I'
        elif self.type == LONG8:
            item_fmt = 'Q'
        else:
            raise ValueError('Unsupported type')

        fmt = '%d%s' % (self.count, item_fmt)
        len = self._fh.fmt_size(fmt)
        if len <= self._fh.fmt_size('Z'):
            # Inline value
            self._fh.seek(self.start + self._fh.fmt_size('HHZ'))
        else:
            # Out-of-line value
            self._fh.seek(self.value_offset)
        items = self._fh.read_fmt(fmt, force_list=True)
        if self.type == ASCII:
            if items[-1] != '\0':
                raise ValueError('String not null-terminated')
            return ''.join(items[:-1])
        else:
            return items

def delete_aperio_label(filename):
    with TiffFile(filename) as fh:
        print("get")
        for directory in fh.directories:
            print(directory)
            # Check ImageDescription
            try:
                desc = directory.entries[IMAGE_DESCRIPTION].value()
            except KeyError:
                continue
            if not desc.startswith('Aperio'):
                # Not an Aperio directory
                continue
            lines = desc.splitlines()
            if len(lines) < 2 or not lines[1].startswith('label '):
                # Not the label
                continue

            # Get strip offsets/lengths
            try:
                offsets = directory.entries[STRIP_OFFSETS].value()
                lengths = directory.entries[STRIP_BYTE_COUNTS].value()
            except KeyError:
                raise IOError('Label is not stripped')

            # Wipe strips
            for offset, length in zip(offsets, lengths):
                fh.seek(offset)
                fh.write('\0' * length)

            # Delete directory
            fh.seek(directory.out_pointer_offset)
            out_pointer = fh.read_fmt('Z')
            fh.seek(directory.in_pointer_offset)
            fh.write_fmt('Z', out_pointer)

            # Done
            break
        else:
            raise IOError("Couldn't find Aperio label directory")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-manifest",
        "-m",
        help="path to a .csv containing a single column of paths to .svs files",
        type=str,
        default=None
    )

    parser.add_argument(
        "-folder",
        "-f",
        help="File/folder containing .svs files",
        type=str,
        default=None
    )

    if len(sys.argv) <= 1:
        print("You need some arguments")
        print("Either enter a manifest of file paths (-m), or point to a folder (-f) containing all slides you want anonymized")
        print("Alternatively, list all .svs files sequentally")
        print("... I feel like this is too many options")
        exit(1)

    paths = []
    if str(sys.argv[1]) is not None and str(sys.argv[1]).endswith(".svs"):
        for arg in sys.argv[1:]:
            if str(arg.endswith(".svs")):
                paths.append(arg)

    args = parser.parse_args()
    if args.folder is not None and args.manifest is not None:
        print("Please enter only a manifest or a folder, not both")
        exit(1)

    if args.folder is not None:
        if not str(args.folder).endswith("/"):
            args.folder += "/"
        for path in os.listdir(args.folder):
            if path.endswith(".svs"):
                paths.append(args.folder + path)

    elif args.manifest is not None:
        with open(args.manifest, "r") as manifest:
            for line in manifest:
                if line.strip().endswith(".svs"):
                    paths.append(line.strip)

    else:
        print("You need some arguments")
        print("Either enter a manifest of file paths (-m), or point to a folder (-f) containing all slides you want anonymized")
        print("Alternatively, list all .svs files sequentally")
        print("... I feel like this is too many options")
        exit(1)

    exit_code = 0
    for filename in paths:
        print(filename)
        try:
            delete_aperio_label(filename)
        except Exception as e:
            # print('%s: %s' % (filename, str(e)), file=sys.stderr)
            exit_code = 1

        sys.exit(exit_code)


# uncompyle6 version 3.6.7
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: /Users/bogdankyryliuk/src/oss/incubator-superset/superset/migrations/versions/b4a38aa87893_deprecate_database_expression.py
# Compiled at: 2020-01-16 13:27:41
# Size of source mod 2**32: 1345 bytes
__doc__ = 'deprecate database expression\n\nRevision ID: b4a38aa87893\nRevises: ab8c66efdd01\nCreate Date: 2019-06-05 11:35:16.222519\n\n'
revision = 'b4a38aa87893'
down_revision = 'ab8c66efdd01'
import sqlalchemy as sa
from alembic import op

def upgrade():
    with op.batch_alter_table('table_columns') as (batch_op):
        batch_op.drop_column('database_expression')

def downgrade():
    with op.batch_alter_table('table_columns') as (batch_op):
        batch_op.add_column(sa.Column('database_expression', sa.String(255)))


#!/usr/bin/env python

#
# Copyright (c) 2018 Intel Labs.
#
# authors: Bernd Gassmann (bernd.gassmann@intel.com)
#
"""
Classes to handle Carla sensors
"""
from abc import abstractmethod

import threading

import rospy

from geometry_msgs.msg import TransformStamped

from carla_ros_bridge.actor import Actor

import carla_ros_bridge.transforms as trans

class Sensor(Actor):

    """
    Actor implementation details for sensors
    """

    @staticmethod
    def create_actor(carla_actor, parent):
        """
        Static factory method to create vehicle actors

        :param carla_actor: carla sensor actor object
        :type carla_actor: carla.Sensor
        :param parent: the parent of the new traffic actor
        :type parent: carla_ros_bridge.Parent
        :return: the created sensor actor
        :rtype: carla_ros_bridge.Sensor or derived type
        """
        if carla_actor.type_id.startswith("sensor.camera"):
            return Camera.create_actor(carla_actor=carla_actor, parent=parent)
        if carla_actor.type_id.startswith("sensor.lidar"):
            return Lidar(carla_actor=carla_actor, parent=parent)
        if carla_actor.type_id.startswith("sensor.other.gnss"):
            return Gnss(carla_actor=carla_actor, parent=parent)
        else:
            return Sensor(carla_actor=carla_actor, parent=parent)

    def __init__(self, carla_actor, parent, topic_prefix=None, append_role_name_topic_postfix=True):
        """
        Constructor

        :param carla_actor: carla actor object
        :type carla_actor: carla.Actor
        :param parent: the parent of this
        :type parent: carla_ros_bridge.Parent
        :param topic_prefix: the topic prefix to be used for this actor
        :type topic_prefix: string
        :param append_role_name_topic_postfix: if this flag is set True,
            the role_name of the actor is used as topic postfix
        :type append_role_name_topic_postfix: boolean
        """
        if topic_prefix is None:
            topic_prefix = 'sensor'
        super(Sensor, self).__init__(carla_actor=carla_actor,
                                     parent=parent,
                                     topic_prefix=topic_prefix,
                                     append_role_name_topic_postfix=append_role_name_topic_postfix)

        self.current_sensor_data = None
        self.update_lock = threading.Lock()
        if self.__class__.__name__ == "Sensor":
            rospy.logwarn("Created Unsupported Sensor(id={}, parent_id={}"
                          ", type={}, attributes={}".format(
                              self.get_id(), self.get_parent_id(),
                              self.carla_actor.type_id, self.carla_actor.attributes))
        else:
            self.carla_actor.listen(self._callback_sensor_data)

    def destroy(self):
        """
        Function (override) to destroy this object.

        Stop listening to the carla.Sensor actor.
        Finally forward call to super class.

        :return:
        """
        rospy.logdebug("Destroy Sensor(id={})".format(self.get_id()))
        if self.carla_actor.is_listening:
            self.carla_actor.stop()
        if self.update_lock.acquire():
            self.current_sensor_data = None
        super(Sensor, self).destroy()

    def get_frame_id(self):
        """
        Function (override) to get the frame id of the sensor object.

        Sensor frames respect their respective parent relationship
        within the frame name to prevent from name clashes.

        :return: frame id of the sensor object
        :rtype: string
        """
        return self.parent.get_frame_id() + "/" + super(Sensor, self).get_frame_id()

    def _callback_sensor_data(self, carla_sensor_data):
        """
        Callback function called whenever new sensor data is received

        :param carla_sensor_data: carla sensor data object
        :type carla_sensor_data: carla.SensorData
        """
        if not rospy.is_shutdown():
            if self.update_lock.acquire(False):
                self.current_sensor_data = carla_sensor_data
                self.send_tf_msg()
                self.sensor_data_updated(carla_sensor_data)
                self.update_lock.release()

    def get_tf_msg(self):
        """
        Function (override) to create a ROS tf message of this sensor

        The reported transform of the sensor is in respect to the global
        frame.

        :return: the filled tf message
        :rtype: geometry_msgs.msg.TransformStamped
        """
        tf_msg = TransformStamped()
        tf_msg.header = self.get_msg_header()
        tf_msg.header.frame_id = "/map"
        tf_msg.child_frame_id = self.get_frame_id()
        tf_msg.transform = self.get_current_ros_transfrom()
        return tf_msg

    def get_current_ros_transfrom(self):
        """
        Function (override) to provide the current ROS transform

        In general sensors are also actors, therefore they contain a transform that is updated
        within each tick.
        But the TF beeing published should exactly match the transform received by SensorData.

        :return: the ROS transform of this actor
        :rtype: geometry_msgs.msg.Transform
        """
        return trans.carla_transform_to_ros_transform(
            self.current_sensor_data.transform)

    @abstractmethod
    def sensor_data_updated(self, carla_sensor_data):
        """
        Pure-virtual function to transform the received carla sensor data
        into a corresponding ROS message

        :param carla_sensor_data: carla sensor data object
        :type carla_sensor_data: carla.SensorData
        """
        raise NotImplementedError(
            "This function has to be implemented by the derived classes")

# these imports have to be at the end to resolve cyclic dependency
from carla_ros_bridge.camera import Camera  # noqa, pylint: disable=wrong-import-position
from carla_ros_bridge.lidar import Lidar   # noqa, pylint: disable=wrong-import-position
from carla_ros_bridge.gnss import Gnss   # noqa, pylint: disable=wrong-import-position


#!/usr/bin/env python

##################
#FUNCTIONS FOR PHOTOTRANSISTOR
#ANALOG VALUE, CONVERTED VALUE, PRINT VALUE FUNCTIONS#
##################

#must have imports in same directory
#import read ADC function
import constants
import mcp3008
import time
import RPi.GPIO as GPIO

#pin numbering system (relative to revision number)
GPIO.setmode(GPIO.BCM)

#instantiate SPI interface
GPIO.setup(constants.SPIMOSI, GPIO.OUT)
GPIO.setup(constants.SPIMISO, GPIO.IN)
GPIO.setup(constants.SPICLK, GPIO.OUT)
GPIO.setup(constants.SPICS, GPIO.OUT)

#outputs 0-1023 (2^10, 10 bits) analog value from phototransistor
def readPhototransistor(phototransPIN):
    phototransValue=mcp3008.readadc(phototransPIN, constants.SPICLK, constants.SPIMOSI,
                                        constants.SPIMISO, constants.SPICS)
    return phototransValue

#convert analog value to rough lumens (needs tuning)
def convertToLumens(phototransValue):
    lumens=abs((phototransValue-180)*1.99)


# coding:utf-8

from django.conf import settings

def common(request):

    settings_to_include = [
        'BASE_URL',
        'MEDIA_URL',
        'TITLE',
        'ALTERNATE_TITLE',
        'DESCRIPTION',
        'KEYWORDS',
        'AUTHOR',
        'SHARE_TITLE',
        'SHARE_DESCRIPTION',
    ]

    return {
        name: getattr(settings, name)
        for name in settings_to_include if hasattr(settings, name)
    }