# /usr/bin/python3.6
# -*- coding:utf-8 -*-
import heapq

class Solution(object):
    def openLock(self, deadends, target):
        """
        :type deadends: List[str]
        :type target: str
        :rtype: int
        """
        heap = []
        heapq.heappush(heap, (0, "0000"))
        visited = set(deadends)

        m_plus = {}
        m_minus = {}
        for i in range(10):
            m_minus[str(i)] = str((i-1+10)%10)
            m_plus[str(i)] = str((i+1)%10)

        while heap:
            step, cur = heapq.heappop(heap)
            if cur in visited:
                continue
            visited.add(cur)
            if cur == target:
                return step
            # 个位变化
            for i in range(4):
                buff = cur[:i] + m_minus[cur[i]] + cur[i+1:]
                if buff not in visited:
                    heapq.heappush(heap, [step+1, buff])
                buff = cur[:i] + m_plus[cur[i]] + cur[i+1:]
                if buff not in visited:
                    heapq.heappush(heap, [step+1, buff])
        return -1

def main():
    s = Solution()
    print(s.openLock(deadends = ["0201","0101","0102","1212","2002"], target = "0202"))
    print(s.openLock( deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"))

if __name__ == "__main__":
    main()


""" Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado, peça a digitação novamente até ter um valor correto. """

sexo = str(input('Sexo [M/F]: ')).upper().strip()
while sexo not in 'MF':
    print('Opção invalida, tente novamente!\n')
    sexo = str(input('Sexo [M/F]: ')).upper().strip()
print(f'Sexo {sexo} registrado com sucesso!\n')
#OU
"""
if sexo == 'M' or sexo == 'F':
        print('Opção VALIDA! Siga.')
while sexo != 'M' and sexo != 'F':
    print('Opção invalida, tente novamente!\n')
    sexo = str(input('Sexo [M/F]: ')).upper()
    if sexo == 'M' or sexo == 'F':
        print('Opção VALIDA! Siga.') """


import six
from sse.exceptions import SseException

__all__ = ['MethodNotAllowed', 'NotFound']

class StreamProtocolException(SseException):
    """
    To avoid confusing with class naming or maybe I need some brain surgery
    """
    def __init__(self, **kwargs):
        for key, value in six.iteritems(kwargs):
            if not hasattr(self, key):
                raise TypeError("%s() received an invalid keyword %r."
                                "only accepts arguments that are already "
                                "attributes of the exception class." % (self.__class__.__name__, key))
            setattr(self, key, value)

class MethodNotAllowed(StreamProtocolException):
    status = 405

    def __init__(self, methods, **kwargs):
        self.headers = (
                        ('Allow', '/'.join(m.upper() for m in methods)),
                        )
        super().__init__(**kwargs)

class NotFound(StreamProtocolException):
    status = 404


import numpy as np
from abc import ABC, abstractmethod

class Agent(ABC):

    """
    Base agent class.
    Represents the concept of an autonomous agent.

    Attributes
    ----------
    name: str
        Name for identification purposes.

    observation: np.ndarray
       The most recent observation of the environment

    Methods
    -------
    see(observation)
        Collects an observation

    action(): int
        Abstract method.
        Returns an action, represented by an integer
        May take into account the observation (numpy.ndarray).

    References
    ----------
    ..[1] Michael Wooldridge "An Introduction to MultiAgent Systems - Second
    Edition", John Wiley & Sons, p 44.

    """

    def __init__(self, name: str, n_agents: int, agent_id):
        """
        Initialize the agent
        """

        self.agent_id = agent_id
        self.name = name
        self.n_agents = n_agents

        self.coords = None
        self.turn_dir = None
        self.diagonal_square = None

        self.observation = None
        self.vector = None
        self.front_square = None
        self.turning_square = None
        self.turned = False

    def reset(self):
        """
        Reset variables
        """

        self.coords = None
        self.turn_dir = None
        self.diagonal_square = None

        self.observation = None
        self.vector = None
        self.front_square = None
        self.turning_square = None
        self.turned = False

    def split_observations(self):
        """
        Split the full observation into the 9 squares of vision
        """

        dx = len(self.observation)//9
        return [self.observation[i*dx : i*dx + dx] for i in range(9)]

    def split_square_observation(self, obs):
        """
        Split the square observation into usable values
        """

        _id = obs[ : self.n_agents]
        coords = obs[self.n_agents : self.n_agents + 2]
        dir = obs[self.n_agents + 2 :]

        _id = np.argmax(_id) + 1 if np.any(_id) else 0

        return _id, list(coords), np.argmax(dir)

    def see(self, observation: np.ndarray):
        """
        Get the observation
        """

        self.observation = observation

    def calculate_direction(self, coords):
        """
        Calculate the direction that the agent is moving when it starts
        """

        if coords[0] == 13: self.vector = (-1, 0) #bottom
        if coords[0] == 0: self.vector = (1, 0)   #top
        if coords[1] == 0: self.vector = (0, 1)   #left
        if coords[1] == 13: self.vector = (0, -1) #right

    def update_direction(self, turning_dir):
        """
        After reaching the turning square, update the direction vector
        """
        self.turned = True

        if turning_dir == 0: return
        if turning_dir == 1: # Dir
            mult = 1 if self.vector[0] == 0 else -1
            self.vector = (self.vector[1], mult * self.vector[0])
        else: # Esq
            mult = 1 if self.vector[1] == 0 else -1
            self.vector = (mult * self.vector[1], self.vector[0])

    def calculate_turning_square(self, coords, turning_dir):
        """
        Calculate the square where the car will make the turn
        """

        cx, cy = coords
        steps = 7 if turning_dir == 2 else 6
        self.turning_square = [cx + steps * self.vector[0], cy + steps * self.vector[1]]

    def calculate_diagonal_square(self):
        """
        Calculate the observation square in the front-left square of the car
        """

        if self.vector == (-1, 0): self.diagonal_square = 0
        if self.vector == (1, 0): self.diagonal_square = 8
        if self.vector == (0, 1): self.diagonal_square = 2
        if self.vector == (0, -1): self.diagonal_square = 6

    def calculate_forward_square(self):
        """
        Calculate the observation square in front of the car
        """

        if self.vector == (-1, 0): self.front_square = 1
        if self.vector == (1, 0): self.front_square = 7
        if self.vector == (0, 1): self.front_square = 5
        if self.vector == (0, -1): self.front_square = 3

    def update_information(self):
        obs = self.split_observations()
        _, self.coords, self.turn_dir = self.split_square_observation(obs[4])

        # If agent is in the game
        if not self.vector and self.coords != [0, 0]:
            self.calculate_direction(self.coords)
            self.calculate_forward_square()
            self.calculate_turning_square(self.coords, self.turn_dir)

        # If agent reached the turning square
        if self.coords == self.turning_square and not self.turned:
            self.update_direction(self.turn_dir)
            self.calculate_forward_square()
            self.calculate_diagonal_square()

        # print(self.name, self.agent_id+1, self.coords, self.turn_dir, self.vector, self.front_square, self.diagonal_square)

    def calculate_next_coords(self, intention):
        if intention or not self.vector: # == 1
            return self.coords
        else:
            return (self.coords[0] + self.vector[0], self.coords[1] + self.vector[1])

    @abstractmethod
    def action(self, intentions) -> int:
        raise NotImplementedError()

    @abstractmethod
    def intention(self, intentions) -> int:
        raise NotImplementedError()

Autonomous Agents and Multi Agent Systems/Code/aasma/agent.py


import numpy as np
from dptb.utils.tools import j_must_have
from dptb.utils.make_kpoints  import ase_kpath, abacus_kpath, vasp_kpath
from ase.io import read
import ase
import matplotlib.pyplot as plt
import matplotlib
import logging
log = logging.getLogger(__name__)
from matplotlib.ticker import MultipleLocator, FormatStrFormatter

class bandcalc(object):
    def __init__ (self, apiHrk, run_opt, jdata):
        self.apiH = apiHrk
        if isinstance(run_opt['structure'],str):
            self.structase = read(run_opt['structure'])
        elif isinstance(run_opt['structure'],ase.Atoms):
            self.structase = run_opt['structure']
        else:
            raise ValueError('structure must be ase.Atoms or str')

        self.band_plot_options = jdata
        self.results_path = run_opt.get('results_path')
        self.apiH.update_struct(self.structase)

        self.ref_band = self.band_plot_options.get("ref_band", None)
        self.use_gui = self.band_plot_options.get("use_gui", False)

    def get_bands(self):
        kline_type = self.band_plot_options['kline_type']

        if kline_type == 'ase':
            kpath = self.band_plot_options['kpath']
            nkpoints = self.band_plot_options['nkpoints']
            self.klist, self.xlist, self.high_sym_kpoints, self.labels = ase_kpath(structase=self.structase,
                                                 pathstr=kpath, total_nkpoints=nkpoints)
        elif kline_type == 'abacus':
            kpath = self.band_plot_options['kpath']
            self.labels = self.band_plot_options['klabels']
            self.klist, self.xlist, self.high_sym_kpoints  = abacus_kpath(structase=self.structase, kpath=kpath)

        elif kline_type == 'vasp':
            kpath = self.band_plot_options['kpath']
            high_sym_kpoints_dict = self.band_plot_options['high_sym_kpoints']
            number_in_line = self.band_plot_options['number_in_line']
            self.klist, self.xlist, self.high_sym_kpoints, self.labels = vasp_kpath(structase=self.structase,
                                                 pathstr=kpath, high_sym_kpoints_dict=high_sym_kpoints_dict, number_in_line=number_in_line)
        else:
            log.error('Error, now, kline_type only support ase_kpath, abacus, or vasp.')
            raise ValueError

        all_bonds, hamil_blocks, overlap_blocks = self.apiH.get_HR()
        self.eigenvalues, self.estimated_E_fermi = self.apiH.get_eigenvalues(self.klist)

        if self.band_plot_options.get('E_fermi',None) != None:
            self.E_fermi = self.band_plot_options['E_fermi']
            log.info(f'set E_fermi from jdata: {self.E_fermi}, While the estimated value in line-mode is {self.estimated_E_fermi}')
        else:
            self.E_fermi = 0.0
            log.info(f'set E_fermi = 0.0, While the estimated value in line-mode is {self.estimated_E_fermi}')

        eigenstatus = {'klist': self.klist,
                        'xlist': self.xlist,
                        'high_sym_kpoints': self.high_sym_kpoints,
                        'labels': self.labels,
                        'eigenvalues': self.eigenvalues,
                        'E_fermi': self.E_fermi }

        np.save(f'{self.results_path}/bandstructure',eigenstatus)

        return  eigenstatus

    def get_HR(self):
        all_bonds, hamil_blocks, overlap_blocks = self.apiH.get_HR()

        return all_bonds, hamil_blocks, overlap_blocks

    def band_plot(self):
        matplotlib.rcParams['font.size'] = 7
        matplotlib.rcParams['pdf.fonttype'] = 42
        # plt.rcParams['font.sans-serif'] = ['Times New Roman']

        emin = self.band_plot_options.get('emin')
        emax = self.band_plot_options.get('emax')

        fig = plt.figure(figsize=(4.5,4),dpi=100)

        ax = fig.add_subplot(111)

        band_color = '#5d5d5d'
        # plot the line

        if self.ref_band:
            ref_eigenvalues = np.load(self.ref_band)
            if len(ref_eigenvalues.shape) == 3:
                ref_eigenvalues = ref_eigenvalues.reshape(ref_eigenvalues.shape[1:])
            elif len(ref_eigenvalues.shape) != 2:
                log.error("Reference Eigenvalues' shape mismatch.")
                raise ValueError

            if ref_eigenvalues.shape[0] != self.eigenvalues.shape[0]:
                log.error("Reference Eigenvalues' should have sampled from the sample kpath as model's prediction.")
                raise ValueError
            ref_eigenvalues = ref_eigenvalues - (np.min(ref_eigenvalues) - np.min(self.eigenvalues))

            nkplot = (len(np.unique(self.high_sym_kpoints))-1) * 7
            nintp = len(self.xlist) // nkplot
            if nintp == 0:
                nintp = 1
            band_ref = ax.plot(self.xlist[::nintp], ref_eigenvalues[::nintp] - self.E_fermi, 'o', ms=4, color=band_color, alpha=0.8, label="Ref")
            band_pre = ax.plot(self.xlist, self.eigenvalues - self.E_fermi, color="tab:red", lw=1.5, alpha=0.8, label="DeePTB")

        else:
            ax.plot(self.xlist, self.eigenvalues - self.E_fermi, color="tab:red",lw=1.5, alpha=0.8)

        # add verticle line
        for ii in self.high_sym_kpoints[1:-1]:
            ax.axvline(ii, color='gray', lw=1,ls='--')

        # add shadow
        # for i in range(self.eigenvalues.shape[1]):
        #     ax.fill_between(self.xlist, self.eigenvalues[:,i] - self.E_fermi, -2, alpha=0.05, color=band_color)
        # add ticks

        if not (emin is None or emax is None):
            ax.set_ylim(emin,emax)

        ax.set_xlim(self.xlist.min()-0.03,self.xlist.max()+0.03)
        ax.set_ylabel('E - EF (eV)',fontsize=12)
        ax.yaxis.set_minor_locator(MultipleLocator(1.0))
        ax.tick_params(which='both', direction='in', labelsize=12, width=1.5)
        ax.tick_params(which='major', length=6)
        ax.tick_params(which='minor', length=4, color='gray')

        # ax.set_yticks(None, fontsize=12)
        ax.set_xticks(self.high_sym_kpoints, self.labels, fontsize=12)

        ax.grid(color='gray', alpha=0.2, linestyle='-', linewidth=1)
        ax.set_axisbelow(True)

        fig.patch.set_facecolor('#f2f2f2')
        fig.patch.set_alpha(1)
        for spine in ax.spines.values():
            spine.set_edgecolor('#5d5d5d')
            spine.set_linewidth(1.5)

        if self.ref_band:
            plt.legend(handles=[band_pre[0], band_ref[0]], loc="best")

        plt.tight_layout()
        # remove the box around the plot
        ax.set_frame_on(False)
        plt.savefig(f'{self.results_path}/band.png',dpi=300)
        if self.use_gui:
            plt.show()


import os
import cv2
import json
import random
import itertools
import numpy as np
import argparse
import cv2

from time import gmtime, strftime

def predict(image, predictor, list_labels):
    outputs = predictor(image)

    boxes = outputs['instances'].pred_boxes
    scores = outputs['instances'].scores
    classes = outputs['instances'].pred_classes

    list_boxes = []
    # list_paths = []
    # list_vehicles = []
    list_scores = []
    list_classes = []

    for i in range(len(classes)):
        if (scores[i] > 0.6):
            for j in boxes[i]:
                x1 = int(j[0])
                y1 = int(j[1])
                x2 = int(j[2])
                y2 = int(j[3])

            print("min: ", (x1, y1))
            print("max: ", (x2, y2))

            score = float(scores[i])
            class_id = list_labels[int(classes[i])]

            list_boxes.append([x1, y1, x2, y2])
            list_scores.append(score)
            list_classes.append(class_id)

    return list_boxes, list_scores, list_classes


import os
from flask import Flask, make_response, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from database import app

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = { 'png', 'jpg', 'mp3' } #to change for music files

app.config['UPLOAD_FOLDER'] = os.path.join(os.getcwd(), "file_transfer/uploads")

print(os.getcwd())

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/file/<filename>', methods = ['GET'])
def file_download(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

@app.route('/file', methods = ['POST'])
def file_upload():
    if 'file' not in request.files:
        return "ERROR : No file part", 404
    file = request.files['file']
    if file.filename == '':
        return "ERROR : No selected file", 401
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return "File Successfully Uploaded"
    #request.files

@app.route('/file/<filename>', methods = ['DELETE'])
def delete_items(filename):
    os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return "File Successfully Deleted"

@app.errorhandler(401)
@app.errorhandler(404)
@app.errorhandler(500)
def ma_page_erreur(error):
    return "Error {}".format(error.code), error.code

if __name__ == "__main__":
    app.run()


# -*- coding: utf-8 -*-
import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino
import time
import gc
# この中の変数は処理終了後に消えない/////////////////////////////////////////////////
if 'count_loop' not in sc.sticky:
	sc.sticky['count_loop'] = 0# 何個目の壁なのか示す数字
if 'dict_distance' not in sc.sticky:
	sc.sticky['dict_distance'] = {}# 下記
if 'dict_combi' not in sc.sticky:
	sc.sticky['dict_combi'] = {}# 壁に関する情報を格納する辞書
if 'count_error' not in sc.sticky:
	sc.sticky['count_error'] = 0# ×の曲線が違う時に数字が増える
if 'list_usedindex' not in sc.sticky:
	sc.sticky['list_usedindex'] = []# 使用済みのインデックス
if 'list_history' not in sc.sticky:
	sc.sticky['list_history'] = []# 操作の記録

# 初回だけ距離計算をする/////////////////////////////////////////////////
# 辞書(キー:曲線のインデックス 値:距離の近いものを順番に並べたリスト)を生成する
def Findclosestpt(crvs):
	dict_dist = {}
	list_midpt = [rs.CurveMidPoint(crv) for crv in crvs]
	count = 0
	while count != len(crvs):
		list_distance = [int(rs.Distance(list_midpt[count], i)) for i in list_midpt]
		dict_dist[count] = sorted(range(len(list_distance)), key=lambda k: list_distance[k])
		count += 1
	return dict_dist

start = time.time()
if sc.sticky['count_loop'] == 0:# ここで初回かどうか判断
	print("Start Calculate")
	sc.sticky['dict_distance'] = Findclosestpt(curve)
	print("End Calculate")

else:
	print("Skip Calculate")
end = time.time() - start
print("calculatetime = " + str(end))

# ２つのインデックスを求める/////////////////////////////////////////////////
for remain in range(len(curve)):
	if remain in sc.sticky['list_usedindex']:
		pass
	else:
		index_o = remain#２つのうちの片方のインデックス
		break
list_loft_x = sc.sticky['dict_distance'].values()[index_o]
index_x = list_loft_x[1 + sc.sticky['count_error']]#もう片方のインデックス

# 辞書に登録する情報を作成/////////////////////////////////////////////////
class Info():
	def __init__(self, crvs, ind_o, ind_x, num_loop, mode, thick, height):#コンストラクタ
		self.crvs = crvs
		self.ind_o = ind_o
		self.ind_x = ind_x
		self.num_loop = num_loop
		self.mode = mode
		self.thick = thick
		self.height = height

	def get_wall(self):# 壁のインデックスを返却
		return self.num_loop
	def get_o(self):# 曲線のインデックス１を返却
		return self.ind_o
	def get_x(self):# 曲線のインデックス2を返却
		return self.ind_x
	def get_thick(self):# 壁の厚みを返却
		return self.thick
	def get_height(self):# 壁の高さを返却
		return self.height
	def get_adjust(self):# 曲線の長さ調整の仕方を返却
		if self.mode == "extend":# 長い方に揃える
			if rs.CurveLength(self.crvs[self.ind_o]) >= rs.CurveLength(self.crvs[self.ind_x]):
				pattern = 1
			else:
				pattern = 2
		else:# 短い方に揃える
			if rs.CurveLength(self.crvs[self.ind_o]) >= rs.CurveLength(self.crvs[self.ind_x]):
				pattern = 3
			else:
				pattern = 4
		return pattern
data = Info(curve, index_o, index_x, sc.sticky["count_loop"], mode, thickness, height)
sc.sticky["dict_combi"][data.get_wall()] = (data.get_o(), data.get_x(), data.get_adjust(), data.get_thick(), data.get_height(),)

# プレビューを作成/////////////////////////////////////////////////
def Previewwall(dict, index, crvs, zoommode):# 壁を作る
	# get_adjustの中身で処理を決める
	if dict[index][2] == 1:
		A = crvs[dict[index][0]]
		B = rs.OffsetCurve(crvs[dict[index][0]], rs.CurveMidPoint(crvs[dict[index][1]]), dict[index][3])
	elif dict[index][2] == 2:
		A = rs.OffsetCurve(crvs[dict[index][1]], rs.CurveMidPoint(crvs[dict[index][0]]), dict[index][3])
		B = crvs[dict[index][1]]
	elif dict[index][2] == 3:
		A = rs.OffsetCurve(crvs[dict[index][1]], rs.CurveMidPoint(crvs[dict[index][0]]), dict[index][3])
		B = crvs[dict[index][1]]
	elif dict[index][2] == 4:
		A = crvs[dict[index][0]]
		B = rs.OffsetCurve(crvs[dict[index][0]], rs.CurveMidPoint(crvs[dict[index][1]]), dict[index][3])

	obj_srf = rs.AddLoftSrf([A, B])
	obj_height = rs.AddLine((0,0,0), (0,0,dict[index][4]))
	obj_wall = rs.ExtrudeSurface(obj_srf, obj_height)

	if zoommode:# 壁と曲線で箱を作り、箱をズーム
		obj_zoom = rs.BoundingBox([obj_wall, crvs[dict[index][0]], crvs[dict[index][1]]])
		rs.ZoomBoundingBox(obj_zoom)

	return obj_wall

def Previewmark(crvs, dict, index):# 線の目印を作る
	pt_o = rs.DivideCurve(crvs[dict[index][0]], 10)
	pt_x = rs.DivideCurve(crvs[dict[index][1]], 10)
	mark_o = [rs.AddCircle(cen, mark) for cen in pt_o]
	mark_x1 = [rs.AddLine((cen[0] - mark,cen[1],cen[2]), (cen[0] + mark,cen[1],cen[2])) for cen in pt_x]
	mark_x2 = [rs.AddLine((cen[0],cen[1] - mark,cen[2]), (cen[0],cen[1] + mark,cen[2])) for cen in pt_x]
	a = mark_o
	b = mark_x1 + mark_x2
	return (a, b)

start = time.time()
if next or loft_o or loft_x or undo or bake == True:# ボタンを押した瞬間はプレビュー省略
	print("preview pass")
else:
	if past == False:# 最後の壁だけ表示
		print("preview only one")
		preview_wall = Previewwall(sc.sticky["dict_combi"], data.get_wall(), curve, zoom)
	else:# 全部の壁を表示
		print("preview all")
		preview_wall = [Previewwall(sc.sticky["dict_combi"], i, curve, zoom) for i in sc.sticky["dict_combi"]]
preview_o = Previewmark(curve, sc.sticky["dict_combi"], data.get_wall())[0]
preview_x = Previewmark(curve, sc.sticky["dict_combi"], data.get_wall())[1]
end = time.time() - start
print("previewtime = " + str(end))

# ボタンが押されたときは以下の操作を行う/////////////////////////////////////////////////
if next:# 次の組み合わせを探す
	print("Input Key = next")
	if len(curve) - len(sc.sticky['list_usedindex']) <= 2:
		bake = True
		print("Start Bake")
	else:
		sc.sticky['count_loop'] += 1
		sc.sticky['count_error'] = 0
		if data.get_o() not in sc.sticky['list_usedindex']:# 使用済みインデックスが重複しないように
			sc.sticky['list_usedindex'].append(data.get_o())
		if data.get_x() not in sc.sticky['list_usedindex']:
			sc.sticky['list_usedindex'].append(data.get_x())
		sc.sticky['list_history'].append(2)

if loft_o:# ロフト元が違う場合
	print("Input Key = loft_o")
	if len(curve) - len(sc.sticky['list_usedindex']) <= 2:
		bake = True
		print("Start Bake")
	else:
		sc.sticky['list_usedindex'].append(index_o)
		del sc.sticky['dict_combi'][sc.sticky['count_loop']]
		sc.sticky['count_loop'] += 1
		sc.sticky['count_error'] = 0
		sc.sticky['list_history'].append(1)

if loft_x:# ロフト先が違う場合
	print("Input Key = loft_x")
	del sc.sticky['dict_combi'][sc.sticky['count_loop']]
	if sc.sticky['count_error'] == len(list_loft_x) - 2:
		sc.sticky['count_error'] = 0
	elif sc.sticky['count_error'] == 14:# 15個目の候補まで表示
		sc.sticky['count_error'] = 0
	else:
		sc.sticky['count_error'] += 1

def Undo():# アンドゥ
	print("Input Key = Undo")
	if sc.sticky['count_loop'] == 0:
		sc.sticky['list_usedindex'] = []
		sc.sticky['list_history'] = []
		sc.sticky['count_error'] = 0

	else:
		if sc.sticky['list_history'][-1] == 2:
			del sc.sticky['dict_combi'][sc.sticky['count_loop']]
			del sc.sticky['dict_combi'][sc.sticky['count_loop'] - 1]
			del sc.sticky['list_usedindex'][-1]
			del sc.sticky['list_usedindex'][-1]

		else:
			del sc.sticky['list_usedindex'][-1]
		del sc.sticky['list_history'][-1]
		sc.sticky['count_error'] = 0
		sc.sticky['count_loop'] = sc.sticky['count_loop'] - 1

if undo:
	Undo()

def Reset():# リセットするときの挙動
	print("Input Key = Undo")
	sc.sticky['count_loop'] = 0
	sc.sticky['count_error'] = 0
	sc.sticky['dict_distance'] = {}
	sc.sticky['dict_combi'] = {}
	sc.sticky['preview'] = []
	sc.sticky['list_usedindex'] = []
	sc.sticky['list_history'] = []
	gc.collect()# メモリ解放

if bake:# ベイクする
	print("Input Key = bake")
	obj_bake = [Previewwall(sc.sticky["dict_combi"], i, curve, zoom) for i in sc.sticky["dict_combi"]]
	sc.doc = Rhino.RhinoDoc.ActiveDoc
	doc_layer = rs.GetLayer("ベイク先のレイヤーを選択", None, True, True)# ベイクするレイヤーを選択
	sc.doc = ghdoc
	for wall in obj_bake:
		doc_obj = rs.coercerhinoobject(wall)
		doc_attributes = doc_obj.Attributes
		doc_geometry = doc_obj.Geometry
		sc.doc = Rhino.RhinoDoc.ActiveDoc
		rhino_obj = sc.doc.Objects.Add(doc_geometry, doc_attributes)
		rs.ObjectLayer(rhino_obj, doc_layer)
		sc.doc = ghdoc
	Reset()

O = data.ind_o
X = data.ind_x
count_error = "✕は" + str(sc.sticky['count_error'] + 1) + "番目の候補です"
len_index = len(sc.sticky['list_usedindex'])


from defaults import *  # noqa

SECRET_KEY = open(SECRET_KEY_FILE).read()
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['.tutorons.com']
STATICFILES_DIRS += ((os.path.join(os.path.abspath(os.sep), 'var', 'www', 'tutorons')),)
STATIC_ROOT = os.path.join(os.path.abspath(os.sep), 'usr', 'local', 'tutorons', 'static')

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
        # We store expensive computations that will be performed infrequently
        # So, we'll just save the results for all computations indefinitely.
        'TIMEOUT': None,
    }
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S",
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '/var/log/tutorons.log',
            'formatter': 'verbose',
        }
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'tutorons': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }
}


# Given a number sequence, find the length of its Longest Increasing Subsequence (LIS).
# In an increasing subsequence, all the elements are in increasing order (from lowest to highest).

# Input: {4,2,3,6,10,1,12}
# Output: 5
# Explanation: The LIS is {2,3,6,10,12}.

def find_LIS(arr):
    return find_LIS_rec(arr, 0, -1)

def find_LIS_rec(arr, current_index, prev_index):
    if current_index == len(arr):
        return 0
    c1 = 0
    if prev_index == -1 or arr[current_index] > arr[prev_index]:
        c1 = 1 + find_LIS_rec(arr, current_index+1, current_index)

    c2 = find_LIS_rec(arr, current_index+1, prev_index)

    return max(c1, c2)

def find_LIS_length(arr):
    n1 = len(arr)
    dp = [1 for _ in range(n1)]

    max_length = 0

    for i in range(1, n1):
        for j in range(i):
            if arr[i] > arr[j] and dp[i] < dp[j]+1:
                dp[i] = dp[j] + 1
                max_length = max(max_length, dp[i])
    return max_length

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

def main():
    print(find_LIS_length([4, 2, 3, 6, 10, 1, 12]))
    print(find_LIS_length([-4, 10, 3, 7, 15]))
    print(find_LIS([4, 2, 3, 6, 10, 1, 12]))
    print(find_LIS([-4, 10, 3, 7, 15]))
    print("********")
    print(longest_increasing_subsequence([4, 2, 3, 6, 10, 1, 12]))
    print(longest_increasing_subsequence([-4, 10, 3, 7, 15]))
    print(longest_increasing_subsequence([4, 2, 3, 6, 10, 1, 12]))
    print(longest_increasing_subsequence([-4, 10, 3, 7, 15]))

if __name__ == "__main__":
    main()


def filter(lines, val0, val1):
    for i in range(len(lines[0])):
        count = [0, 0]
        for line in lines:
            count[int(line[i])] += 1

        if count[0] > count[1]:
            lines = [line for line in lines if line[i] == val0]
        else:
            lines = [line for line in lines if line[i] == val1]

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

from sys import stdin

lines = [line.strip() for line in stdin]

oxygen = filter(lines[:], '0', '1')
co2 = filter(lines[:], '1', '0')

print(int(oxygen, base=2) * int(co2, base=2))


from typing import List

file = "input02.txt"

with open(file, "rt") as f:
    ids = f.readlines()

# Part 1

doubles = 0
triples = 0

for id in ids:
    double_found = False
    triple_found = False
    for c in id:
        reps = id.count(c)
        if reps == 2 and not double_found:
            doubles += 1
            double_found = True
        if reps == 3 and not triple_found:
            triples += 1
            triple_found = True
        if double_found and triple_found:
            break

print(f"Number of doubles: {doubles}")
print(f"Number of triples: {triples}")
print(f"Checksum: {doubles*triples}")

# Part 2

def check(x: str, y: str) -> bool:
    """
    Whether two strings differ at most at one position
    """
    if not x:
        return not y
    x0, x_tail = x[0], x[1:]
    y0, y_tail = y[0], y[1:]
    return (x_tail == y_tail) or (x0 == y0 and check(x_tail, y_tail))

def find_ids(ids: List[str]) -> str:
    for i, x in enumerate(ids[:-1]):
        for y in ids[i + 1:]:
            found = check(x, y)
            if found:
                print(f"The found ids: {x}, {y}")
                common_sub = ""
                for i, c in enumerate(x):
                    if y[i] == c:
                        common_sub += c
                return(common_sub)
    raise ValueError("No correct ids were found")

res = find_ids(ids)
print(f"The common substring: {res}")


import torch
import numpy as np
import matplotlib.pyplot as plt

print("PyTorch Version:", torch.__version__)

if torch.backends.mps.is_available():
    mps_device = torch.device("mps")
    print(mps_device)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

X, Y = np.mgrid[-4.0:4:0.01, -4.0:4:0.01]

x = torch.Tensor(X)
y = torch.Tensor(Y)

x = x.to(device)
y = y.to(device)

z = torch.sin(3*x + y) * torch.exp(-(x**2+y**2)/2.0)

plt.imshow(z.numpy())
plt.tight_layout()
plt.show()


from django import template
register = template.Library()

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

@register.filter
def first_letter_word(value):
    stop_words = set(stopwords.words('english'))
    word_tokens = word_tokenize(value)
    filtered_sentence = [w for w in word_tokens if not w.lower() in stop_words]
    removetable = str.maketrans('', '', '!@#$%^&*()_+-=[]{};:\"\',./<>?\|')
    final = [s.translate(removetable) for s in filtered_sentence]
    final = [s for s in final if s != '']
    chindex=1
    arr = []
    for letter in final:
        if chindex==1:
            arr.append(letter[0].upper())
        else:
            arr.append(letter)
    out = "".join(arr)
    return out


import numpy as np
import matplotlib.pyplot as plt

sp_LL=np.loadtxt('spline_LL.txt')
sp_LH=np.loadtxt('spline_LH.txt')
sp_HT=np.loadtxt('spline_HT.txt')
sp_R=np.loadtxt('spline_R.txt')
##
AA=np.loadtxt('HT_p_T_c')
BB=np.loadtxt('LH_p_T_c')
CC=np.loadtxt('R_p_T_c')
DD=np.loadtxt('LL_p_T_c')
EE=np.loadtxt('TP_T-x-Perr-p-u-v.txt')

###%%% Top %%%
#Top = np.zeros((10,2))
#Top[:,0] = np.linspace(0.0088,0.1706,num=10);
#Top[:,1] = 68569;

u_HT_A = AA[:,0]
v_HT_A = AA[:,1]
#p_HT_A = AA[:,2]
T_HT_A = AA[:,3]
t_HT_A = AA[:,3]

u_LH_B = BB[:,0]
v_LH_B = BB[:,1]
#p_LH_B = BB[:,2]
T_LH_B = BB[:,3];

u_R_C = CC[:,0];
v_R_C = CC[:,1];
#p_R_C = CC(:,3);
T_R_C = CC[:,3];

u_LL_D = DD[:,0];
v_LL_D = DD[:,1];
#p_LL_D = DD(:,3);
T_LL_D = DD[:,3];

u_TP_E = EE[:,4]
v_TP_E = EE[:,5]
#p_TP_E = EE[:,3]
T_TP_E = EE[:,0]

###########################isobar single phase 8,5,2,1######################################
u_HT_isoT400 = []
v_HT_isoT400 = []
u_HT_isoT350 = []
v_HT_isoT350 = []
u_HT_isoT300 = []
v_HT_isoT300 = []
u_HT_isoT230 = []
v_HT_isoT230 = []
u_HT_isoT250 = []
v_HT_isoT250 = []
#
u_LH_isoT400 = []
v_LH_isoT400 = []
u_LH_isoT350 = []
v_LH_isoT350 = []
u_LH_isoT300 = []
v_LH_isoT300 = []
#
u_TP_isoT2166 = []
v_TP_isoT2166 = []
u_TP_isoT230 = []
v_TP_isoT230 = []
u_TP_isoT250 = []
v_TP_isoT250 = []
u_TP_isoT300 = []
v_TP_isoT300 = []
#
u_R_isoT230 = []
v_R_isoT230 = []
#
u_LL_isoT350 = []
v_LL_isoT350 = []
u_LL_isoT300 = []
v_LL_isoT300 = []
u_LL_isoT250 = []
v_LL_isoT250 = []
u_LL_isoT230 = []
v_LL_isoT230 = []
#
for i in range(len(u_HT_A)):
    if T_HT_A[i] <=6.03e2 and T_HT_A[i]>=5.99e2:
        u_HT_isoT400.append(u_HT_A[i]/1000)
        v_HT_isoT400.append(v_HT_A[i])
    if T_HT_A[i] <=3.51e2 and T_HT_A[i]>=3.48e2:
        u_HT_isoT350.append(u_HT_A[i]/1000)
        v_HT_isoT350.append(v_HT_A[i])
    if T_HT_A[i] <=3.01e2 and T_HT_A[i]>=2.95e2:
        u_HT_isoT300.append(u_HT_A[i]/1000)
        v_HT_isoT300.append(v_HT_A[i])
    if T_HT_A[i] <=2.31e2 and T_HT_A[i]>=2.21e2:
        u_HT_isoT230.append(u_HT_A[i]/1000)
        v_HT_isoT230.append(v_HT_A[i])
    if T_HT_A[i] <=2.51e2 and T_HT_A[i]>=2.45e2:
        u_HT_isoT250.append(u_HT_A[i]/1000)
        v_HT_isoT250.append(v_HT_A[i])
#
for i in range(len(u_LH_B)):
#    if T_LH_B[i] <=4.01e2 and T_LH_B[i]>=3.99e2:
#        u_LH_isoT400.append(u_LH_B[i]/1000)
#        v_LH_isoT400.append(v_LH_B[i])
    if T_LH_B[i] <=3.51e2 and T_LH_B[i]>=3.497e2:
        u_LH_isoT350.append(u_LH_B[i]/1000)
        v_LH_isoT350.append(v_LH_B[i])
    if T_LH_B[i] <=3.01e2 and T_LH_B[i]>=2.999e2:
        u_LH_isoT300.append(u_LH_B[i]/1000)
        v_LH_isoT300.append(v_LH_B[i])
#############################isobar two-phase####################################
for i in range(len(u_TP_E)):
    if T_TP_E[i] <=2.167e2 and T_TP_E[i]>=2.164e2:
#        print(T_TP_E[i])
        u_TP_isoT2166.append(u_TP_E[i]/1000)
        v_TP_isoT2166.append(v_TP_E[i])
    if T_TP_E[i] <=2.3001e2 and T_TP_E[i]>=2.298e2:
        u_TP_isoT230.append(u_TP_E[i]/1000)
        v_TP_isoT230.append(v_TP_E[i])
    if T_TP_E[i] <=2.5001e2 and T_TP_E[i]>=2.499e2:
        u_TP_isoT250.append(u_TP_E[i]/1000)
        v_TP_isoT250.append(v_TP_E[i])
    if T_TP_E[i] <=3.001e2 and T_TP_E[i]>=2.999e2:
        u_TP_isoT300.append(u_TP_E[i]/1000)
        v_TP_isoT300.append(v_TP_E[i])
#################################R#########################################
for i in range(len(u_R_C)):
    if T_R_C[i] <=2.301e2 and T_R_C[i]>=2.299e2:
        u_R_isoT230.append(u_R_C[i]/1000)
        v_R_isoT230.append(v_R_C[i])
#########################################################################
for i in range(len(u_LL_D)):
    if T_LL_D[i] <=2.301e2 and T_LL_D[i]>=2.299e2:
        u_LL_isoT230.append(u_LL_D[i]/1000)
        v_LL_isoT230.append(v_LL_D[i])
    if T_LL_D[i] <=2.5001e2 and T_LL_D[i]>=2.499e2:
        u_LL_isoT250.append(u_LL_D[i]/1000)
        v_LL_isoT250.append(v_LL_D[i])
    if T_LL_D[i] <=3.001e2 and T_LL_D[i]>=2.999e2:
        u_LL_isoT300.append(u_LL_D[i]/1000)
        v_LL_isoT300.append(v_LL_D[i])
    if T_LL_D[i] <=3.51e2 and T_LL_D[i]>=3.497e2:
        u_LL_isoT350.append(u_LL_D[i]/1000)
        v_LL_isoT350.append(v_LL_D[i])
########################################################################

plt.figure(figsize=(9,4))
#
plt.semilogx(sp_R[:,0],sp_R[:,2]/1e3,color='r',linewidth=2)
plt.semilogx(sp_R[:,1],sp_R[:,2]/1e3,color='k',linewidth=2)

plt.semilogx(sp_HT[:,0],sp_HT[:,2]/1e3,linestyle='--',color='k',linewidth=2)
plt.semilogx(sp_HT[:,1],sp_HT[:,2]/1e3,linestyle='--',color='k',linewidth=2)

plt.semilogx(sp_LH[:,0],sp_LH[:,2]/1e3,color='r',linewidth=2)
plt.semilogx(sp_LH[:,1],sp_LH[:,2]/1e3,linestyle='--',color='k',linewidth=2)

plt.semilogx(sp_LL[:,0],sp_LL[:,2]/1e3,linestyle='-',color='b',linewidth=2)
plt.semilogx(sp_LL[:,1],sp_LL[:,2]/1e3,linestyle='--',color='k',linewidth=2)
###############################################################################
plt.semilogx(v_HT_isoT400,u_HT_isoT400,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_HT_isoT350,u_HT_isoT350,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_HT_isoT300,u_HT_isoT300,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_HT_isoT250,u_HT_isoT250,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_HT_isoT230,u_HT_isoT230,color='k',linewidth=2,linestyle=':')
#
plt.semilogx(v_LH_isoT400,u_LH_isoT400,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_LH_isoT350,u_LH_isoT350,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_LH_isoT300,u_LH_isoT300,color='k',linewidth=2,linestyle=':')
#
plt.semilogx(v_R_isoT230,u_R_isoT230,color='k',linewidth=2,linestyle=':')
#
plt.semilogx(v_LL_isoT350,u_LL_isoT350,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_LL_isoT300,u_LL_isoT300,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_LL_isoT250,u_LL_isoT250,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_LL_isoT230,u_LL_isoT230,color='k',linewidth=2,linestyle=':')
#########################TWO-PHASE########################################
plt.semilogx(v_TP_isoT2166,u_TP_isoT2166,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_TP_isoT230,u_TP_isoT230,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_TP_isoT250,u_TP_isoT250,color='k',linewidth=2,linestyle=':')
plt.semilogx(v_TP_isoT300,u_TP_isoT300,color='k',linewidth=2,linestyle=':')

#####control des labels
ax = plt.gca()
#ax.set_xlim([0.015, 1e-1])
ax.set_ylim([-4.5e2, 3e2])
#plt.title('Isothermal curves',fontsize=17)
plt.ylabel('Internal Energy, e $[kJkg^{-1}]$',fontsize=15,position=(0,0.5),rotation = "vertical")
plt.xlabel('Specific Volume, v $[m^{-3}kg]$',fontsize=15,rotation = "horizontal")
plt.xticks(size = 12)
plt.yticks(size = 12)
plt.grid(True)
#plt.axis([-4,4,-0.3,1.5])
#plt.xlabel('X', color='C1')
#plt.ylabel('X', color='0.5')  # grayscale color
#ax.xaxis.set_label_coords(0.5,-0.05)
#ax.yaxis.set_label_coords(-0.08,0.5)
#####################################
ax.text(2.0e-2,200, '$600K$', fontsize=10)
ax.text(2.1e-2,-25, '$350K$', fontsize=10)
ax.text(2.8e-3,-200, '$300K$', fontsize=10)
ax.text(0.9e-2,-210, '$250K$', fontsize=10)
ax.text(2.0e-2,-210, '$230K$', fontsize=10)
ax.text(3.3e-2,-210, '$216.6K$', fontsize=10)
#############################################################################
plt.tight_layout()
plt.savefig("isotherm.pdf")
plt.show()


from sys import stdin
input = stdin.readline

intersections = int(input())
roads = {x: {} for x in range(1, intersections + 1)}
distance, adj, before = {}, {}, [0] * (intersections + 1)
queue = []
# print(roads)
num = int(input())
for _ in range(num):
    m, n, d, s = [int(x) for x in input().split()]
    time = float(d) / s * 60
    if n not in roads[m]:
        roads[m][n] = [time, d, s]
        roads[n][m] = [time, d, s]
    elif roads[m][n][0] > time:
        roads[m][n] = [time, d, s]
        roads[n][m] = [time, d, s]
# print(roads)
start = 1
for i in range(1, intersections + 1):
    distance[i] = 9999999999
    adj[i] = None
    queue.append(i)
distance[1] = 0
while queue:
    # find closest unvisited node
    keyMin = queue[0]
    minVal = distance[keyMin]
    for i in queue[1:]:
        if distance[i] < minVal:
            keyMin = i
            minVal = distance[i]
    current = keyMin
    queue.remove(current)
    # print(current)

    # get the closest paths connected to the current node
    for i in roads[current]:
        alt = roads[current][i][0] + distance[current]
        if distance[i] > alt:
            distance[i] = alt
            adj[i] = current
            before[i] = before[current] + 1
        elif distance[i] == alt:
            if before[current] + 1 < before[i]:
                distance[i] = alt
                adj[i] = current
                before[i] = before[current] + 1

# print(distance)
# print(adj)
# print(before)

total = 0
x = intersections
while True:
    y = adj[x]
    total += float(roads[y][x][1]) / (roads[y][x][2] * 0.75) * 60
    x = y
    if x == 1:
        break

print(before[intersections])
print(round(total - distance[intersections]))


class Solution:

    def isMatch(self, s: str, p: str) -> bool:
        cache={}
        lenS,lenP=len(s),len(p)

        def dfs(i,j):

            if (i,j) in cache:
                return cache[(i,j)]
            if i>=lenS and j>=lenP:
                return True
            if j>=lenP:
                return False

            match=i<lenS and (s[i]==p[j] or p[j]=='.')

            if (j+1)<lenP and p[j+1]=="*":
                cache[(i,j)]=dfs(i,j+2) or (match and dfs(i+1,j))
            elif match:
                cache[(i,j)]=dfs(i+1,j+1)
            else:
                cache[(i,j)]=False
            return cache[(i,j)]

        return dfs(0,0)


"""

"""
import time

def print_execute_time(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        # 执行旧功能
        result = func(*args, **kwargs)
        stop = time.time()
        print("执行时间：", stop - start)
        return result

    return wrapper

@print_execute_time
def sum_data(n):
    sum_value = 0
    for number in range(n):
        sum_value += number
    return sum_value

print(sum_data(10))
print(sum_data(1000000))


# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 11:48:04 2020

@author: Paradeisios
"""
from utils.computeCost import computeCost
import numpy as np

def gradientDescent(X,y,theta,alpha, iterations):

    m = len(y)
    J_history = np.zeros((iterations,1))

    derivative = 0
    for i in range(iterations):
        derivative = (X.dot(theta) - y).dot(X)
        theta = theta - alpha*(1/m)*derivative

        J_history[i]= computeCost(theta,X,y)

    return(theta,J_history)


my_list = [1, 2, 3, 4, 5]
for i in my_list:
	print(i)
else:
	print('Hit the For\Else Statement')

print()
print('********************************')
print()

j = 1
while j <= 5:
	print(j)
	j += 1
	if j == 3:
		break
else:
	print('Hi the While\Else Statement')

print()
print('********************************')
print()

def find_index(to_search, target):

	for i, value in enumerate(to_search):
		if value == target:
			break
	else:
		return -1
	return i

my_list_1 = ['Manju', 'Thilak', 'Suu', 'Sharu', 'Paavan']
index_value = find_index(my_list_1, 'Paavan')
print(f'Location of the target is at index "{index_value}"')
print()
print('************************************************')
print()

lists = ['ABC', 'BCD', 'CDE', 'EFG']
print(f'Index of "BCD" found at: {lists.index("BCD")}')
print()

def index_to_search(index_search, value_target):

	for index, values in enumerate(index_search):
		if values == value_target:
			break
	else:
		return -1

	return index

search = index_to_search(lists, 'BCD')
print(f'Location found at index: {search}')


from flask import Flask, render_template, url_for, request, redirect
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import requests
import paralleldots
import stripe

app = Flask(__name__)

pub_key = ''
secret_key = ''

stripe.api_key = secret_key

class Analyze:
    report_key = ''
    sentiment_key = ''

    def __init__(self, company):
        self.company = company
        self.url = 'https://datafied.api.edgar-online.com/v2/corefinancials/ann?primarysymbols=' + \
            self.company + '&appkey=' + self.report_key

    def get_fin_report(self):
        URL = self.url
        PARAMS = {}
        r = requests.get(url=URL, params=PARAMS)
        self.data = r.json()

        return None

    def sentiment_analysis(self):
        paralleldots.set_api_key(self.sentiment_key)
        self.response = paralleldots.sentiment(self.data, 'en')
        return None

    def predict(self):
        self.get_fin_report()
        self.sentiment_analysis()
        goodornot = self.response['sentiment']
        result = max(goodornot, key=goodornot.get)
        return result

# Route for handling the login page logic
@app.route('/', methods=['GET', 'POST'])
def index():
    error = None
    if request.method == 'POST':
        return redirect(url_for('reallyobscurefilename'))
    return render_template('index.html', error=error, pub_key = pub_key)

@app.route('/reallyobscurefilename', methods=['POST', 'GET'])
def reallyobscurefilename():
    result = ''

    if request.method == 'POST':
        company = request.form['company']
        new_analysis = Analyze(company=company)
        ans = new_analysis.predict()
        if ans in ['positive', 'neutral', 'negative']:
            result = 'Our expert professional guidance is that this is a ' + \
                ans + ' investment.'
    return render_template('reallyobscurefilename.html', result = result)

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


from __future__ import annotations

from grammar import Grammar, reduce_left_recursion, chomsky_normal_form
from dacite import from_dict
import json

def main():
    filename = input("Input file name:") or "data.json"
    print(f'using file {filename}')
    with open(filename, "r") as f:
        data = json.load(f)
    g = from_dict(data_class=Grammar, data=data)

    print("--------- Input grammar -----------")
    g.print()

    print("--------- Left Recursion Elimination -----------")
    g = reduce_left_recursion(g)
    g.print()

    print("--------- Chomsky Normal Form -----------")
    g = chomsky_normal_form(g)
    g.print()

if __name__ == "__main__":
    main()


from consts import piConst, hwConst
from spa.serverside import CSocketProServer, CSocketProService,\
    CClientPeer, BaseServiceID, Plugin
from spa.clientside import CAsyncQueue, CStreamingFile, CMysql, COdbc, CSqlite, CSqlServer, CPostgres
from spa.udb import DB_CONSTS
from pub_sub.ps_server.hwpeer import CHelloWorldPeer
from webdemo.myhttppeer import CMyHttpPeer
import sys
from ctypes import *
from sys import platform as os

# bool U_MODULE_OPENED WINAPI SetSPluginGlobalOptions(const char *jsonUtf8Options);
sqlite_lib = None
if os == "win32":
    sqlite_lib = WinDLL("ssqlite.dll")
else:
    sqlite_lib = WinDLL("libssqlite.so")

SetSPluginGlobalOptions = sqlite_lib.SetSPluginGlobalOptions
SetSPluginGlobalOptions.argtypes = [c_char_p]
SetSPluginGlobalOptions.restype = c_bool

# int U_MODULE_OPENED WINAPI DoSPluginAuthentication(SPA::UINT64 hSocket,
#   const wchar_t *userId, const wchar_t *password, unsigned int nSvsId,
#   const wchar_t *options);
SQLite_Auth = sqlite_lib.DoSPluginAuthentication
SQLite_Auth.argtypes = [c_uint64, c_wchar_p, c_wchar_p, c_uint, c_wchar_p]
SQLite_Auth.restype = c_int

mysql_lib = None
MySQL_Auth = None
if os == "win32":
    mysql_lib = WinDLL("smysql.dll")
else:
    mysql_lib = WinDLL("libsmysql.so")
if mysql_lib:
    MySQL_Auth = mysql_lib.DoSPluginAuthentication
    MySQL_Auth.argtypes = [c_uint64, c_wchar_p, c_wchar_p, c_uint, c_wchar_p]
    MySQL_Auth.restype = c_int

odbc_lib = None
ODBC_Auth = None
if os == "win32":
    odbc_lib = WinDLL("sodbc.dll")
else:
    odbc_lib = WinDLL("libsodbc.so")
if odbc_lib:
    ODBC_Auth = odbc_lib.DoSPluginAuthentication
    ODBC_Auth.argtypes = [c_uint64, c_wchar_p, c_wchar_p, c_uint, c_wchar_p]
    ODBC_Auth.restype = c_int

mssql_lib = None
if os == "win32":
    mssql_lib = WinDLL("usqlsvr.dll")
else:
    mssql_lib = WinDLL("libusqlsvr.so")
MsSql_Auth = mssql_lib.DoSPluginAuthentication
MsSql_Auth.argtypes = [c_uint64, c_wchar_p, c_wchar_p, c_uint, c_wchar_p]
MsSql_Auth.restype = c_int

postgres_lib = None
Postgres_Auth = None
if os == "win32":
    postgres_lib = WinDLL("spostgres.dll")
else:
    postgres_lib = WinDLL("libspostgres.so")
if postgres_lib:
    Postgres_Auth = postgres_lib.DoSPluginAuthentication
    Postgres_Auth.argtypes = [c_uint64, c_wchar_p, c_wchar_p, c_uint, c_wchar_p]
    Postgres_Auth.restype = c_int

with CSocketProServer() as server:
    def OnClose(hSocket, errCode):
        bs = CSocketProService.SeekService(hSocket)
        if bs:
            sp = bs.Seek(hSocket)
            # ......
    server.OnClose = OnClose

    def OnIsPermitted(hSocket, userId, pwd, svsId):
        auth_res = Plugin.AUTHENTICATION_NOT_IMPLEMENTED
        if svsId == hwConst.sidHelloWorld or svsId == BaseServiceID.sidHTTP or svsId == piConst.sidPi or svsId == piConst.sidPiWorker:
            # give permission to known services without authentication
            auth_res = Plugin.AUTHENTICATION_OK
        elif svsId == CAsyncQueue.sidQueue or svsId == CStreamingFile.sidFile:
            # give permission to known services without authentication
            auth_res = Plugin.AUTHENTICATION_OK
        elif svsId == CPostgres.sidPostgres:
            auth_res = Postgres_Auth(hSocket, userId, pwd, svsId, 'server=localhost;timeout=45;max_SQLs_batched=16')
        elif svsId == CSqlServer.sidMsSql:
            auth_res = MsSql_Auth(hSocket, userId, pwd, svsId, 'server=localhost;timeout=45;max_SQLs_batched=16')
        elif svsId == COdbc.sidOdbc:
            auth_res = ODBC_Auth(hSocket, userId, pwd, svsId, 'DRIVER={ODBC Driver 13 for SQL Server};Server=windesk;database=sakila;max_sqls_batched=16')
        elif svsId == CMysql.sidMysql:
            auth_res = MySQL_Auth(hSocket, userId, pwd, svsId, 'server=windesk;max_sqls_batched=16')
        elif svsId == CSqlite.sidSqlite:
            auth_res = SQLite_Auth(hSocket, userId, pwd, svsId, 'usqlite.db')
            if auth_res == Plugin.AUTHENTICATION_PROCESSED:
                # give permission without authentication
                auth_res = Plugin.AUTHENTICATION_OK
        if auth_res >= Plugin.AUTHENTICATION_OK:
            print(userId + "'s connecting permitted, and DB handle opened and cached")
        elif auth_res == Plugin.AUTHENTICATION_PROCESSED:
            print(userId + "'s connecting denied: no authentication implemented but DB handle opened and cached")
        elif auth_res == Plugin.AUTHENTICATION_FAILED:
            print(userId + "'s connecting denied: bad password or user id")
        elif auth_res == Plugin.AUTHENTICATION_INTERNAL_ERROR:
            print(userId + "'s connecting denied: plugin internal error")
        elif auth_res == Plugin.AUTHENTICATION_NOT_IMPLEMENTED:
            print(userId + "'s connecting denied: no authentication implemented")
        else:
            print(userId + "'s connecting denied: unknown reseaon with res --" + str(auth_res))
        return auth_res >= Plugin.AUTHENTICATION_OK
    server.OnIsPermitted = OnIsPermitted

    def do_configuration():
        CSocketProServer.PushManager.AddAChatGroup(1, "R&D Department")
        CSocketProServer.PushManager.AddAChatGroup(2, "Sales Department")
        CSocketProServer.PushManager.AddAChatGroup(3, "Management Department")
        CSocketProServer.PushManager.AddAChatGroup(7, "HR Department")
        CSocketProServer.PushManager.AddAChatGroup(DB_CONSTS.CACHE_UPDATE_CHAT_GROUP_ID, "Subscribe/publish for front clients")
        return True # True -- ok; False -- no listening server
    server.OnSettingServer = do_configuration

    mapIdMethod = {
        hwConst.idSayHello: 'sayHello',
        hwConst.idSleep: ['sleep', True],  # or ('sleep', True)
        hwConst.idEcho: 'echo'
    }
    server.hw = CSocketProService(CHelloWorldPeer, hwConst.sidHelloWorld, mapIdMethod)

    # HTTP/WebSocket service
    server.HttpSvs = CSocketProService(CMyHttpPeer, BaseServiceID.sidHTTP, None)

    mapIdReq = {}
    server.Pi = CSocketProService(CClientPeer, piConst.sidPi, mapIdReq)
    server.PiWorker = CSocketProService(CClientPeer, piConst.sidPiWorker, mapIdReq)
    if not CSocketProServer.Router.SetRouting(piConst.sidPi, piConst.sidPiWorker):
        print('Setting routing failed')

    # load file streaming library at the directory ../bin/free_services/file
    # 16 * 1024 dequeue batch size in bytes
    server.aq = CSocketProServer.DllManager.AddALibrary('uasyncqueue', 16 * 1024)

    # load async sqlite library located at the directory ../bin/free_services/sqlite
    server.sqlite = CSocketProServer.DllManager.AddALibrary("ssqlite")
    if server.sqlite:
        # monitoring sakila.db table events (DELETE, INSERT and UPDATE) for
        # tables actor, language, category, country and film_actor
        jsonOptions = '{"global_connection_string":"usqlite.db","monitored_tables":\
"sakila.db.actor;sakila.db.language;sakila.db.category;sakila.db.country;sakila.db.film_actor"}'
        SetSPluginGlobalOptions(jsonOptions.encode('utf-8'))

    # load persistent message queue library at the directory ../bin/free_services/queue
    server.file = CSocketProServer.DllManager.AddALibrary('ustreamfile')

    # load MySQL/MariaDB server plugin library at the directory ../bin/free_services/mm_middle
    server.mysql = CSocketProServer.DllManager.AddALibrary("smysql")

    # load ODBC server plugin library at the directory ../bin/win or ../bin/linux
    server.odbc = CSocketProServer.DllManager.AddALibrary("sodbc")

    # load MS sql server plugin library at the directory ../bin/win or ../bin/linux
    server.mssql = CSocketProServer.DllManager.AddALibrary("usqlsvr")

    # load PostgreSQL plugin library at the directory ../bin/win/win64 or ../bin/linux
    server.postgres = CSocketProServer.DllManager.AddALibrary("spostgres")

    if not server.Run(20901):
        print('Error message = ' + CSocketProServer.ErrorMessage)
    print('Read a line to shutdown the application ......')
    line = sys.stdin.readline()


""" Helper functions used by tests for the locate subpackage."""

from pdf2gtfs.datastructures.gtfs_output.handler import GTFSHandler
from pdf2gtfs.datastructures.gtfs_output.stop_times import Time

def add_stops_to_handler(handler: GTFSHandler, n: int = 5) -> None:
    """ Add n unique stops to the given handler. """
    for i in range(n):
        handler.stops.add(f"stop_{i}")

def add_calendar_to_handler(handler: GTFSHandler) -> None:
    """ Add a calendar, with Tuesday and Wednesday as active days. """
    handler.calendar.add(["1", "2"], set())

def add_routes_to_handler(handler: GTFSHandler, n: int = 2) -> None:
    """ Add n unique routes to the given handler. """
    for i in range(n):
        handler.routes.add(str(i), f"route_{i}")

def add_stop_times_to_handler(handler: GTFSHandler, time_to_next: Time = None
                              ) -> None:
    """ Add stop_times to the given handler.
    Creates both trips and stop_times."""

    stops = handler.stops.entries
    routes = handler.routes.entries
    service_id = handler.calendar.entries[0].service_id
    for route_idx, route in enumerate(routes):
        # Create trip for route.
        trip = handler.trips.add(service_id, route.route_id)
        current_time = Time(6 * (route_idx + 1))
        route_stops = stops[route_idx:len(stops) - route_idx]

        for stop_idx, stop in enumerate(route_stops):
            handler.stop_times.add(trip.trip_id, stop.stop_id,
                                   stop_idx, current_time)
            if time_to_next is None:
                current_time += Time(minutes=1 + stop_idx * 1)

def create_handler() -> GTFSHandler:
    """ Create a dummy handler and adds some basic data to it. """
    handler = GTFSHandler()
    add_stops_to_handler(handler)
    add_calendar_to_handler(handler)
    add_routes_to_handler(handler)
    add_stop_times_to_handler(handler)
    return handler


import logging
import sys

def two_sum_sorting(numbers_set, range_start, range_end):
    logger.info('Started function that uses sorting')
    numbers_sorted = sorted(numbers_set)
    logger.info('Done sorting')
    start = 0
    end = len(numbers_set) - 1
    result = set()

    logger.info('Entering main while loop')
    while start < end:
        tmp = numbers_sorted[start] + numbers_sorted[end]
        if tmp > range_end:
            end -= 1
        elif tmp < range_start:
            start += 1
        else:
            result.add(tmp)
            for i in range(start + 1, end):
                t = numbers_sorted[i] + numbers_sorted[end]
                if check_in_range(t, range_start, range_end):
                    result.add(t)
                else:
                    break
            end -= 1
    logger.info('Done looping')  # approx 1.6s
    return len(result)

def two_sum_hash(numbers_set, range_start, range_end):
    logger.info('Started function that uses set lookup')
    result = set()
    for i in range(range_start, range_end):
        for n in numbers_set:
            if i - n in numbers_set and i - n != n:
                result.add(i)
    logger.info('Finished set lookup')  # more than 60min
    return len(result)

def check_in_range(number, range_start, range_end):
    if range_start < number < range_end:
        return True
    else:
        return False

if __name__ == '__main__':
    # initialize logging to console
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(name)s %(levelname)s %(message)s')
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    # actual start
    logger.info('Program started')
    nums = set()
    # load data
    with open('algo1-programming_prob-2sum.txt') as data:
        for line in data:
            raw = line.strip()
            if raw:
                i = int(raw)
                nums.add(i)
    logger.info('Data loaded from file')
    print(two_sum_sorting(nums, -10000, 10000))
    # print(two_sum_hash(nums, -10000, 10000))
    logger.info('Program end')


from __future__ import unicode_literals
import os
import unittest
import tempfile
import textwrap
import decimal
import shutil

import transaction as db_transaction

class TestAlembic(unittest.TestCase):

    def setUp(self):
        from sqlalchemy import create_engine
        from sqlalchemy.orm import scoped_session
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy.ext.declarative import declarative_base
        from zope.sqlalchemy import ZopeTransactionExtension
        from alembic.config import Config
        self.temp_dir = tempfile.mkdtemp()
        # init database
        default_sqlite_url = 'sqlite:///{}/billy.sqlite'.format(self.temp_dir)
        self.db_url = os.environ.get(
            'BILLY_FUNC_TEST_DB',
            default_sqlite_url,
        )
        # as these tests cannot work with in-memory sqlite, so, when it is
        # a sqlite URL, we use the one in temp folder anyway
        if self.db_url.startswith('sqlite:'):
            self.db_url = default_sqlite_url
        self.engine = create_engine(self.db_url, convert_unicode=True)
        self.declarative_base = declarative_base()
        self.declarative_base.metadata.bind = self.engine

        self.session = scoped_session(sessionmaker(
            autocommit=False,
            autoflush=False,
            bind=self.engine,
            extension=ZopeTransactionExtension()
        ))

        self.alembic_path = os.path.join(self.temp_dir, 'alembic.ini')
        with open(self.alembic_path, 'wt') as f:
            f.write(textwrap.dedent("""\
            [alembic]
            script_location = alembic
            sqlalchemy.url = {}

            [loggers]
            keys = root

            [handlers]
            keys =

            [formatters]
            keys =

            [logger_root]
            level = WARN
            qualname =
            handlers =

            """).format(self.db_url))
        self.alembic_cfg = Config(self.alembic_path)

    def tearDown(self):
        # drop all tables
        self.session.remove()
        self.declarative_base.metadata.drop_all()
        shutil.rmtree(self.temp_dir)

    def test_use_integer_column_for_amount(self):
        from sqlalchemy import Column
        from sqlalchemy import Integer
        from sqlalchemy import Numeric

        class Plan(self.declarative_base):
            __tablename__ = 'plan'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        class Subscription(self.declarative_base):
            __tablename__ = 'subscription'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        class Transaction(self.declarative_base):
            __tablename__ = 'transaction'
            guid = Column(Integer, primary_key=True)
            amount = Column(Numeric(10, 2))

        self.declarative_base.metadata.create_all()

        with db_transaction.manager:
            for amount in ['12.34', '55.66', '10']:
                amount = decimal.Decimal(amount)
                plan = Plan(amount=amount)
                subscription = Subscription(amount=amount)
                transaction = Transaction(amount=amount)
                self.session.add(plan)
                self.session.add(subscription)
                self.session.add(transaction)

        from alembic import command
        command.stamp(self.alembic_cfg, 'base')

        command.upgrade(self.alembic_cfg, 'b3d4192b123')
        # Notice: this with statement here makes sure the database transaction
        # will be closed after querying, otherwise, we have two connections
        # to postgresql (one by testing code, one by Alembic), when we are
        # doing following downgrade, there is table alter, it appears
        # there will be a deadlock when there is a overlap of two transaction
        # scope
        with db_transaction.manager:
            for table in [Plan, Subscription, Transaction]:
                amounts = self.session.query(table.amount).all()
                amounts = map(lambda item: float(item[0]), amounts)
                # make sure all float dollars are converted into integer cents
                self.assertEqual(set(amounts), set([1234, 5566, 1000]))

        command.downgrade(self.alembic_cfg, 'base')
        with db_transaction.manager:
            for table in [Plan, Subscription, Transaction]:
                amounts = self.session.query(table.amount).all()
                amounts = map(lambda item: item[0], amounts)
                self.assertEqual(
                    set(amounts),
                    set(map(decimal.Decimal, ['12.34', '55.66', '10']))
                )


from model.action.Action import Action
from model.action.Actions import Actions

class SendingMessageAction(Action):
    def __init__(self, _message: str, _agt_id: int):
        Action.__init__(self, "sending_message", Actions.Sending_message)
        self.message = _message
        self.agt_id = _agt_id


#!/usr/bin/env python3

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import os
import sys

import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
from colorama import Fore

import config
from dataloader import getDataloaders
from utils import getModel, save_checkpoint, get_optimizer, optimizer_device, create_save_folder, filter_fixed_params
from args import arg_parser, arch_resume_names
from train_val import Trainer
from tensorboardX import SummaryWriter

dev = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

def main():
    # parse arg and start experiment
    global args
    best_err1 = 100.
    best_epoch = 0
    now_epoch = 0

    args = arg_parser.parse_args()
    args.config_of_data = config.datasets[args.data]
    args.num_classes = config.datasets[args.data]['num_classes']

    # optionally resume from a checkpoint
    if args.resume:
        if args.resume and os.path.isfile(args.resume):
            print("=> loading checkpoint '{}'".format(args.resume))
            checkpoint = torch.load(args.resume)
            old_args = checkpoint['args']
            print('Old args:')
            print(old_args)
            # set args based on checkpoint
            if args.start_epoch <= 1:
                args.start_epoch = checkpoint['epoch'] + 1
            now_epoch = args.start_epoch - 1
            best_epoch = checkpoint['best_epoch']
            best_err1 = checkpoint['best_err1']
            print('pre best err1:{} @epoch{}'.format(best_err1, best_epoch))
            # for name in arch_resume_names:
            #     if name in vars(args) and name in vars(old_args):
            #         setattr(args, name, getattr(old_args, name))
            model = getModel(**vars(args))
            model.load_state_dict(checkpoint['model_state_dict'])
            model = nn.DataParallel(model) if torch.cuda.device_count() > 1 else model
            model = model.to(dev)
            training_params = filter_fixed_params(model, args.fixed_module_flags)
            optimizer = get_optimizer(training_params, args)

            if args.load_optimizer:
                optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
                optimizer_device(optimizer, dev)
                print('optimizer.state_dict():')
                print(optimizer.state_dict()["param_groups"])

            print("=> loaded checkpoint '{}' (epoch {})"
                  .format(args.resume, checkpoint['epoch']))
        else:
            print(
                "=> no checkpoint found at '{}'".format(
                    Fore.RED +
                    args.resume +
                    Fore.RESET),
                file=sys.stderr)
            return
    else:
        # create model
        print("=> creating model '{}'".format(args.arch))
        model = getModel(**vars(args))
        model = nn.DataParallel(model) if torch.cuda.device_count() > 1 else model
        model = model.to(dev)
        training_params = filter_fixed_params(model, args.fixed_module_flags)
        optimizer = get_optimizer(training_params, args)

    cudnn.benchmark = True
    # check if the folder exists
    create_save_folder(args.save, args.force)

    # define loss function (criterion) and pptimizer
    criterion = nn.CrossEntropyLoss().to(dev)

    # set random seed
    torch.manual_seed(args.seed)

    trainer = Trainer(model, criterion, optimizer, args)

    # create dataloader
    if args.evaluate == 'train':
        train_loader, _, _ = getDataloaders(
            splits=('train'), **vars(args))
        trainer.test(train_loader, now_epoch)
        return
    elif args.evaluate == 'val':
        _, val_loader, _ = getDataloaders(
            splits=('val'), **vars(args))
        trainer.test(val_loader, now_epoch)
        return
    elif args.evaluate == 'test':
        _, _, test_loader = getDataloaders(
            splits=('test'), **vars(args))
        trainer.test(test_loader, now_epoch, write=True)
        return
    else:
        train_loader, val_loader, _ = getDataloaders(
            splits=('train', 'val'), **vars(args))

    # set up logging
    global log_print, f_log
    f_log = open(os.path.join(args.save, 'log.txt'), 'w')

    def log_print(*args):
        print(*args)
        print(*args, file=f_log)

    log_print('args:')
    log_print(args)
    print('model:', file=f_log)
    print(model, file=f_log)
    log_print('# of params:',
              str(sum([p.numel() for p in model.parameters()])))
    f_log.flush()
    f_log.close()
    torch.save(args, os.path.join(args.save, 'args.pth'))
    scores = ['epoch\tlr\ttrain_loss\tval_loss\ttrain_err1'
              '\tval_err1\ttrain_err5\tval_err5']
    if args.tensorboard:
        writer = SummaryWriter(os.path.join(args.save, 'log_dir'))

    for epoch in range(args.start_epoch, args.epochs + 1):

        # simulate 10 fold validation
        if epoch % (args.epochs / 10) == 0:
            args.seed += 5
            train_loader, val_loader, _ = getDataloaders(
                splits=('train', 'val'), **vars(args))

        # train for one epoch
        train_loss, train_err1, train_err5, lr = trainer.train(
            train_loader, epoch)

        # evaluate on validation set
        val_loss, val_err1, val_err5 = trainer.test(val_loader, epoch)

        if args.tensorboard:
            writer.add_scalar('Lr', lr, epoch)
            writer.add_scalars('Err/err1', {'train_err1': train_err1,
                                            'val_err1': val_err1}, epoch)
            writer.add_scalars('Err/err5', {'train_err5': train_err5,
                                            'val_err5': val_err5}, epoch)
            writer.add_scalars('Loss', {'train_loss': train_loss,
                                        'val_loss': val_loss}, epoch)

        # save scores to a tsv file, rewrite the whole file to prevent
        # accidental deletion
        scores.append(('{}\t{}' + '\t{:.4f}' * 6)
                      .format(epoch, lr, train_loss, val_loss,
                              train_err1, val_err1, train_err5, val_err5))
        with open(os.path.join(args.save, 'scores.tsv'), 'w') as f:
            print('\n'.join(scores), file=f)

        # remember best err@1 and save checkpoint
        is_best = val_err1 < best_err1
        if is_best:
            best_err1 = val_err1
            best_epoch = epoch
        print(Fore.GREEN + 'Best var_err1 {} @ ep{}'.format(best_err1, best_epoch) +
              Fore.RESET)
        # test_loss, test_err1, test_err1 = validate(
        #     test_loader, model, criterion, epoch, True)
        # save test
        save_checkpoint({
            'args': args,
            'epoch': epoch,
            'best_epoch': best_epoch,
            'arch': args.arch,
            'model_state_dict': model.module.state_dict() if torch.cuda.device_count() > 1 else model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'best_err1': best_err1}, is_best, args.save)
        if not is_best and epoch - best_epoch >= args.patience > 0:
            break
    with open(os.path.join(args.save, 'scores.tsv'), 'a') as f:
        print('Best val_err1: {:.4f} at epoch {}'.format(best_err1, best_epoch), file=f)

if __name__ == '__main__':
    main()


from typing import List
from data_structures.list_node import ListNode
from heapq import *

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        min_heap = []
        for i in range(len(lists)):
            curr_list = lists[i]
            if curr_list:
                heappush(min_heap, (curr_list.val, i, curr_list))

        head, tail = None, None

        while min_heap:
            val, i, curr_list = heappop(min_heap)
            if curr_list.next:
                heappush(min_heap, (curr_list.next.val, i, curr_list.next))

            if not head:
                head = ListNode(val)
                tail = head
            else:
                if not head.next:
                    head.next = tail
                tail.next = ListNode(val)
                tail = tail.next

        return head


# Easy Python project  :P
# Random friend selector to decide who to FaceTime!

import random

friends =[
    'Arnab','Dipankar','Sandeep Sir','Aman','Virat','Pant'
]

selected = random.choice(friends)   #randomly choose a friend
print('Who should I facetime today? ')
print(selected)

# random.randint(1,5)
# random.choice(friends)


import time
import pandas as pd
import numpy as np
import sys

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york': 'new_york_city.csv',
              'washington': 'washington.csv' }

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """

    print('Hello! Let\'s explore some US bikeshare data!')

    # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
    while True:
        city = input("Please Choose a City : chicago, new york or washington: ").lower()
        if city in CITY_DATA.keys():
            break
        else:
            print("That\'s not a valid choice, Please try again : chicago, new york or washington")
    # TO DO: get user input for month (all, january, february, ... , june)
    months = ["january", "february", "march", "april", "may", "june", "all"]
    while True:
        month = input("PLease choose a month from january to june or just write 'all' if so: ").lower()
        if month in months:
            break
        else:
            print("That\'s not a valid choice, Please try again : Only first six months are available")
    # TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
    days = ["saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "all"]
    while True:
        day = input("Please choose a day or just write 'all' if so: ").lower()
        if day in days:
            break
        else:
            print("That\'s not a valid choice, Please try again with a valid day name")

    print('-'*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """
    print("Just Confirming your Choices: \n")
    df = pd.read_csv(CITY_DATA[city])
    print("For The City of {}".format(city).title())
    df['Start Time'] = pd.to_datetime(df['Start Time'])
    df['month'] = df['Start Time'].dt.month_name()
    df['day'] = df['Start Time'].dt.day_name()
    if month != 'all':
        df = df[df['month'] == month.title()]
        print("& The Month of {}".format(month).title())
    else:
        print("& All Months")
    if day != 'all':
        df = df[df['day'] == day.title()]
        print("& The Day of {}".format(day).title())
    else:
        print("& All Days")

    return df

def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    print('\nCalculating The Most Frequent Times of Travel...\n')
    start_time = time.time()

    # TO DO: display the most common month

    df['month'] = df['Start Time'].dt.month_name()
    popular_month = df['month'].mode()[0]
    print("Most common month is: {}".format(popular_month))

    # TO DO: display the most common day of week
    df['day'] = df['Start Time'].dt.day_name()
    popular_day = df['day'].mode()[0]
    print("Most common day is: {}".format(popular_day))

    # TO DO: display the most common start hour
    df['hour'] = df['Start Time'].dt.strftime('%I %p')
    popular_start_hour = df['hour'].mode()[0]
    print("Most common hour is: {}".format(popular_start_hour))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    print('\nCalculating The Most Popular Stations and Trip...\n')
    start_time = time.time()

    # TO DO: display most commonly used start station
    popular_start_station = df['Start Station'].mode()[0]
    print("Most Commonly Used Start Station is: ",popular_start_station)
    # TO DO: display most commonly used end station
    popular_end_station = df['End Station'].mode()[0]
    print("Most Commonly Used End Station is: ",popular_end_station)
    # TO DO: display most frequent combination of start station and end station trip
    #popular_combination = 'from' + df['Start Station'] + 'to' + df['End Station'].mode()[0]
    df['popular_comb'] = df['Start Station'].str.cat(df['End Station'],sep=' to ')
    popular_combination = df['popular_comb'].mode()[0]
    print("Most Commonly Used Combination of Start and End Stations is: ",popular_combination)
    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    print('\nCalculating Trip Duration...\n')
    start_time = time.time()

    # TO DO: display total travel time
    total_duration = df['Trip Duration'].sum()
    duration_hours = int(total_duration) / 3600
    print("Total Trips Duration  : {:,.2f} hours".format(duration_hours))

    # TO DO: display mean travel time
    df.fillna(0)
    travel_mean = df['Trip Duration'].mean()
    mean_minutes = int(travel_mean) / 60
    print("Mean of Trips Duration: {:,.2f} minutes".format(mean_minutes))

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)

def user_stats(df):
    """Displays statistics on bikeshare users."""

    print('\nCalculating User Stats...\n')
    start_time = time.time()

    # TO DO: Display counts of user types
    usr_type = df['User Type'].value_counts(dropna = True)
    print("User Types: \n ",usr_type)

    # TO DO: Display counts of gender
    try:
        gendr = df['Gender'].value_counts(dropna = True)
        print("Gender Types: \n",gendr)

    # TO DO: Display earliest, most recent, and most common year of birth
        earliest_birth = df['Birth Year'].min()
        print("Earliest Birth Year   : ",int(earliest_birth))
        recent_birth = df['Birth Year'].max()
        print("Most Recent Birth Year: ", int(recent_birth))
        most_common_year = df['Birth Year'].mode()[0]
        print("Most Common Birth Year: ", int(most_common_year))
    except:
        print("Gender and Birth Year Data Not Provided for Selected City")

    print("\nThis took %s seconds." % (time.time() - start_time))
    print('-'*40)
    #Asking user if they need to see rows of raw data 5 at a time
def raw_data(df):
    raw_data = input("Would you like to see 5 raw data rows ? Enter yes or no: ")
    start_loc = 0
    while True:
        if raw_data.lower() == 'yes':
            pd.set_option('display.max_columns',11)
            print(df.iloc[start_loc:start_loc+5])
            start_loc += 5
        raw_data = input("Would you like to see 5 more ?").lower()

        if raw_data.lower() == 'no':
            print("\n No More Data Requested Here .. Exiting This Analysis")
            break
        if raw_data.lower() not in ("yes", "no"):
            print("I Didn't Understand This, Please Type only yes or no")

def exit(df):
    print("Exiting")

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)
        raw_data(df)

        while True:
            restart = input('\nWould you like to restart? Enter yes or no.\n')
            if restart.lower() == 'yes':
                break
            elif restart.lower() == 'no':
                print("Exiting")
                sys.exit()
            else:
                print("I Didn't Understand This, Please Type only yes or no")
                continue

if __name__ == "__main__":
	main()


# https://www.hackerrank.com/challenges/bigger-is-greater/
# No such impl in Python lib: https://stackoverflow.com/questions/4223349

class strings:
    def next_permutation(w):
        stk=[]
        n=len(w)
        def nextperm(sc):
            i=0
            for x in stk:
                if x > sc:
                    stk[i] = sc
                    return x+''.join(stk)
                i+=1
            return ''.join(stk)+sc

        for i in range(n):
            k=n-1-i
            if stk and w[k]<stk[-1]:
                return w[:k] + nextperm(w[k])
            else:
                stk.append(w[k])
        # return 'no answer'
        return ''.join(stk)


import time, collections

class RateLimiter:
    def __init__(self, max_number, interval):
        self.timeStamp = collections.defaultdict(collections.deque)
        self.interval = interval
        self.max_number = max_number

    def call(self, id):
        currTime = time.time()
        if len(self.timeStamp[id]) < self.max_number:
            self.timeStamp[id].append(currTime)
            return True
        else:
            if currTime - self.timeStamp[id][0] > self.interval:
                self.timeStamp[id].popleft()
                self.timeStamp[id].append(currTime)
                return True
            else:
                return False

rateLimiter = RateLimiter(5, 2)
for i in range(10):
    print(rateLimiter.call(1))
time.sleep(1)
for i in range(5):
    print(rateLimiter.call(2))


# Advent of Code, Day 3, Part 2

testInput = '''\
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
'''
testResult = 230

def solve(input):
    lines = [line for line in input.split('\n') if line != '']

    def searchForRating(bitCriteria):
        remLines = lines

        for i in range(len(lines[0])):
            ones = sum(1 for line in remLines if line[i] == '1')
            zeros = sum(1 for line in remLines if line[i] == '0')
            maxBit = '1' if bitCriteria(ones, zeros) else '0'

            remLines = [line for line in remLines if line[i] == maxBit]

            if len(remLines) == 1:
                return int(remLines[0], 2)

    oxygen = searchForRating(lambda ones, zeros: ones >= zeros)
    co2 = searchForRating(lambda ones, zeros: ones < zeros)
    return oxygen * co2

assert solve(testInput) == testResult

with open('day3/input.txt', 'r') as file:
    print(solve(file.read()))


from django.shortcuts import HttpResponseRedirect
from django.http import JsonResponse
from urllib.parse import quote

class AuthRequiredMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before the view (and later middleware) are called.
        if not request.user.is_authenticated and request.path != "/login/":
            if request.headers.get("x-requested-with") == "XMLHttpRequest":
                return JsonResponse(
                    {
                        "status": "false",
                        "message": "You don't have permission to access this resource",
                    },
                    status=403,
                )
            path = quote(request.get_full_path())
            return HttpResponseRedirect(f"/login/?next={path}")

        # Code to be executed for each request/response after the view is called.
        response = self.get_response(request)
        return response


#存在重复
# 给定一个整数数组，判断是否存在重复元素。
# 如果任何值在数组中出现至少两次，函数返回 true。如果数组中每个元素都不相同，则返回 false。
#===============================================================================
# 输入: [1,2,3,1]
# 输出: true
#===============================================================================
from collections import Counter
class Solution:
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        c=Counter(nums)
        for i in c:
            if c[i]>1:
                return True

        return False

result=Solution().containsDuplicate([1,1,1,3,3,4,3,2,4,2])
print(result)


import re
from parsers.InsideParser.InsideParserBase import InsideParserBase
from parsers.RegexpBuilder import RegexpBuilder
from parsers.ValuesStriper import ValuesStripper

class InsideSetArrayParser(InsideParserBase):
	def __init__(self, fileExt):
		InsideParserBase.__init__(self, fileExt)

		self.values = None

	def parseLine(self, line):
		match = self.fetchMatchFor(line)

		filePath = match.group('file')
		key = match.group('key')
		valuesStr = match.group('values')

		self.values = self.parseValues(valuesStr)

		return filePath, key, valuesStr

	def getMatchInfo(self, line):
		assert line is not None

		keyRegexp = r'(?P<key>[a-zA-Z]+)'
		valueRegexp = r"'(?P<values>[^']+)'$"

		rb = RegexpBuilder()
		regexpSource = rb.startsWith('inside') + self.filePathRegexp + rb.keywordToken('set') + keyRegexp + \
					   rb.keywordToken('with') + rb.than('values') + valueRegexp
		regexp = re.compile(regexpSource, re.UNICODE)

		match = regexp.match(line)

		return match, regexpSource

	def parseValues(self, valuesStr):
		assert valuesStr is not None
		assert len(valuesStr) > 0

		vs = ValuesStripper()
		values = vs.strip(valuesStr)

		return values


import telebot
from telebot import types

bot = telebot.TeleBot('1507860102:AAH3y4nFwQgnYJCFP49PMRRqQVEvhIGrLmw')

user_dict = {}

class User:
    def __init__(self, name):
        self.name = name
        self.age = None
        self.sex = None

# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
    markup.add('Tak', 'Nie')
    msg = bot.reply_to(message,
        """\
            Cześć witam w quize.
            Kontynujemy?
        """,
        reply_markup=markup)
    bot.register_next_step_handler(msg, start_quiz_step)

def start_quiz_step(message):
    try:
        chat_id = message.chat.id
        answer = message.text
        if answer == "Tak":
            msg = bot.reply_to(message, 'Jak masz na imię?')
            bot.register_next_step_handler(msg, process_name_step)
        elif answer == "Nie":
            bot.send_message(chat_id, 'Miło było cię poznać')
        else:
            raise Exception("Unknown answer")
    except Exception as e:
        bot.reply_to(message, 'oooops')

def process_name_step(message):
    try:
        chat_id = message.chat.id
        name = message.text
        user = User(name)
        user_dict[chat_id] = user
        msg = bot.reply_to(message, 'Ile masz lat?')
        bot.register_next_step_handler(msg, process_age_step)
    except Exception as e:
        bot.reply_to(message, 'oooops')

def process_age_step(message):
    try:
        chat_id = message.chat.id
        age = message.text
        if not age.isdigit():
            msg = bot.reply_to(message, 'Age should be a number. How old are you?')
            bot.register_next_step_handler(msg, process_name_step)
            return
        user = user_dict[chat_id]
        user.age = age
        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
        markup.add('Male', 'Female')
        msg = bot.reply_to(message, 'What is your gender', reply_markup=markup)
        bot.register_next_step_handler(msg, process_sex_step)
    except Exception as e:
        bot.reply_to(message, 'oooops')

def process_sex_step(message):
    try:
        chat_id = message.chat.id
        sex = message.text
        user = user_dict[chat_id]
        if (sex == 'Male') or (sex == 'Female'):
            user.sex = sex
        else:
            raise Exception("Unknown sex")
        bot.send_message(chat_id, 'Nice to meet you ' + user.name + '\n Age:' + str(user.age) + '\n Sex:' + user.sex)
    except Exception as e:
        bot.reply_to(message, 'oooops')

# Enable saving next step handlers to file "./.handlers-saves/step.save".
# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
# saving will hapen after delay 2 seconds.
bot.enable_save_next_step_handlers(delay=2)

bot.polling(none_stop=True)


#!/usr/bin/python3
"""Graph data structure traversal"""

def canUnlockAll(boxes):
    """Check if all boxes can be recursively opened

    Function, by the help of helper function `recurse`, checks whether all
    boxes in `boxes` 2D list can be opened by begining with keys found on box
    at index 0.

    Args:
        boxes (list of list): 2D list with elements as boxes containing keys

    Returns: True if created set has all keys, false otherwise
    """
    keysSet = {0}
    recurse(0, boxes, keysSet)
    return list(keysSet) == list(range(len(boxes)))

def recurse(idx, boxes, keysSet):
    """Recurse through boxes and enumerate a set with found keys

    Args:
        idx (number): Position indicator for a box in `boxes`
        boxes (2D list): Original list of boxes
        keysSet (set): Data structure for holding unique keys in

    Returns:
        None
    """
    for key in boxes[idx]:
        if key not in keysSet and key < len(boxes):
            keysSet.add(key)
            recurse(key, boxes, keysSet)
    return None


from google.cloud import storage
from configparser import ConfigParser
from google.oauth2 import service_account
from googleapiclient.discovery import build
from utils.demo_io import (
    get_initial_slide_df_with_predictions_only,
    get_fovs_df,
    get_top_level_dirs,
    populate_slide_rows,
    get_histogram_df,
    list_blobs_with_prefix,
    get_combined_spots_df,
    crop_spots_from_slide,
)
import polars as pl
from gcsfs import GCSFileSystem

cutoff = 10  # how many slides to view cropped spot images from

# Parse in key and bucket name from config file
cfp = ConfigParser()
cfp.read("config.ini")

service_account_key_json = cfp["GCS"]["gcs_storage_key"]
gs_url = cfp["GCS"]["bucket_url"]

bucket_name = gs_url.replace("gs://", "")

# Define GCS file system so files can be read
gcs = GCSFileSystem(token=service_account_key_json)

# Authenticate using the service account key file
credentials = service_account.Credentials.from_service_account_file(
    service_account_key_json, scopes=["https://www.googleapis.com/auth/cloud-platform"]
)

client = storage.Client.from_service_account_json(service_account_key_json)

# Create a storage client
storage_service = build("storage", "v1", credentials=credentials)

slide_files_raw = list_blobs_with_prefix(
    client, bucket_name, prefix="patient_slides_analysis", cutoff=cutoff * 2
)["blobs"]

slides_of_interest = [
    slidefile.split("/")[-1].strip(".npy")
    for slidefile in slide_files_raw
    if slidefile.endswith(".npy")
]

for sl in slides_of_interest:
    spot_df = get_combined_spots_df(bucket_name, gcs, sl)

    print(spot_df)

    spot_df_top = spot_df.sort(pl.col("parasite output"), descending=True).head(20)

    spot_df_top = spot_df_top.with_columns(spot_df_top["r"].cast(pl.Int64) * 2)
    spot_coords = []

    for spot in spot_df_top.rows(named=True):
        spot_coords.append(
            (
                spot["FOV_row"],
                spot["FOV_col"],
                spot["FOV_z"],
                spot["x"],
                spot["y"],
                spot["r"],
            )
        )

    print(spot_df_top)

    spot_imgs = crop_spots_from_slide(storage_service, bucket_name, sl, spot_coords)

    for img in spot_imgs:
        img.show()