from plover_vim.shared.util import addCommandSyntax
from plover_vim.shared.builtins import BaseLookup
from plover_vim.command_letter.util import (
        getEscape, getSymbols, getCharacters
        )
from plover_vim.Emily_modifier.config import LONGEST_KEY
from plover_vim.Emily_modifier.util import getEnder, getModifiedChars
from plover_vim.Emily_modifier.defaults import defaults

class Lookup(BaseLookup):
    def __init__(self, opts={}):
        super().__init__(defaults, opts)
        self.dictionary = self.getDictionary()
        assert self.dictionary.longest_key == LONGEST_KEY

    def getLeftCommands(self):
        unique_ender = getEnder(self.opts["unique_ender"])
        escape = getEscape(self.opts["escape"])
        symbols = getSymbols(self.opts['symbols'], self.opts['shifted'])
        characters = getModifiedChars(
                getCharacters(self.opts['spelling'], symbols)
                )
        return (escape * unique_ender * characters)

    def getDictionary(self):
        return self.getLeftCommands().map(addCommandSyntax(self.opts["command_suffix"]))

    def __call__(self, chord):
        assert len(chord) <= LONGEST_KEY
        return super().__call__(chord)

EmilyLookup = Lookup()

escapedLookup = Lookup({
    "escape": "escape",
    "unique_ender": "#-LTZ"
   })


import sys, re, datetime

assert len(sys.argv) > 1, "Please specify the name of your post!"

now = datetime.datetime.now()
name = sys.argv[1:].copy()

print(sys.argv[-1])
if sys.argv[-1] in ['md', 'html']:
  print(name)
  name = name[:-1]
  print(name)

name = " ".join(name)
file_name = now.strftime('%Y-%m-%d-') + re.sub(r"[-' !]", '-', name.lower())

if sys.argv[-1] in ['md', 'html']:
  file_name += '.' + sys.argv[-1]

elif not (file_name.endswith('.md') or file_name.endswith('.markdown') or file_name.endswith('.html')):
  file_name += '.md'

print(name)
print(file_name)
with open("./_posts/" + file_name, "w") as file:
  file.write('\n'.join([
    '---',
    'layout: post',
    'title: "' + name + '"',
    'date: ' + now.strftime("%Y-%m-%d %H:%M:%S -0600"),
    '---'
  ]))


#pip install pyinstaller
#pip install xlrd ## xlrd는 정책변경으로 xls 만 읽을 수 있어서 openpyxl 로 교체.
#pip install openpyxl

#import xlrd
import openpyxl

import sys
import os
import timeit
import enum

#------------------------------------------------------------------------
# 시간 체크.
#------------------------------------------------------------------------
timer_stack_ = list()
def BeginTimer(tag : str):
	start_time = timeit.default_timer()
	timer_stack_.append((tag, start_time))
def EndTimer() -> (str, float):
	stack_count = len(timer_stack_)
	if stack_count > 0:
		last_time = timer_stack_.pop()
		tag = str(last_time[0])
		start_time = float(last_time[1])
		end_time = timeit.default_timer()
		return (("\t" * (stack_count - 2)) + tag, end_time - start_time)
	return ("", 0.0)
def PrintTimer():
	print(end())
def PrintTimer(data : (str, float)):
	tag = data[0]
	pass_time = data[1]
	print(f"{tag} : {pass_time:.4f}s")

#------------------------------------------------------------------------
# C# 에서 사용중인 키워드 (전체).
# 팁 : 최소한의 검사용으로 작성 해놓았지만 C#의 버전업시 어떻게 바뀔지는 모르기 때문에...
# 가급적이면 필드명 등에서 대소문자를 적절히 혼용해서 키워드와의 중복을 피할 것.
#------------------------------------------------------------------------
csharp_strong_keyword_list_ = [ "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "lock", "long", "namespace", "new", "null", "object", "function", "declare", "define", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" ]

#------------------------------------------------------------------------
# C#에서 사용중인 키워드 (데이터타입제외).
#------------------------------------------------------------------------
csharp_weak_keyword_list_ = [ "abstract", "as", "base", "break", "byte", "case", "catch", "checked", "class", "const", "delegate", "do", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "for", "foreach", "goto", "if", "implicit", "in", "interface", "internal", "lock", "namespace", "new", "null", "object", "function", "declare", "define", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sealed", "sizeof", "stackalloc", "static", "struct", "switch", "this", "throw", "true", "try", "typeof", "unchecked", "unsafe", "using", "virtual", "void", "volatile", "while" ]

#------------------------------------------------------------------------
# JSON 데이터 타입.
#------------------------------------------------------------------------
class DataKind(enum.Enum):
	UNKNOWN = enum.auto()
	BOOLEAN = enum.auto()
	NUMBER = enum.auto()
	REAL = enum.auto()
	TEXT = enum.auto()

#------------------------------------------------------------------------
# 절대 경로 반환.
#------------------------------------------------------------------------
def GetAbsPath(path : str = "") -> str:
	if os.path.isfile(path) or os.path.isdir(path):
		return os.path.abspath(path)

	if getattr(sys, 'frozen', False):
		return os.path.abspath(os.path.dirname(sys.executable) + path) # 응용프로그램 경로.
	elif __file__: # 현재 스크립트파일의 경로.
		return os.path.abspath(os.path.dirname(__file__) + path)

#------------------------------------------------------------------------
# 이름규칙에 알맞는지 확인.
#------------------------------------------------------------------------
def IsCorrectName(value : str):
	if not value:
		return False

	# 알파벳 ==> 숫자의 순으로 호출되어야하며 알파벳과 숫자 외의 문자열은 실패.
	is_correct = False
	for val in value:
		if val.isalpha():
			is_correct = True
		elif val.isnumeric():
			if not is_correct:
				return False
		elif val == "_":
			is_correct = True
		else:
			return False
	return True

#------------------------------------------------------------------------
# 필드 값을 JSON 값으로 변환.
#------------------------------------------------------------------------
def DataValueToJsonValue(value : str, kind : DataKind, is_array : bool):
	if kind == DataKind.TEXT:
		return f"\"{value}\""
	elif is_array:
		result = str()
		result += "["
		val_list = value.split(",")
		val_list_count = len(val_list)
		for val_index in range(val_list_count):
			result += f"{field_value}"
			if val_index + 1 < val_list_count:
				result += ", "
		result += "]"
	else:
		return f"{value}"

#------------------------------------------------------------------------
# 2차원 스트링배열 형태의 기본 테이블 정보.
#------------------------------------------------------------------------
class NativeTable:
	name_ : str
	row_list_ : list # row[col[]]
	def __init__(self):
		self.name_ = str()
		self.row_list_ = list()

#------------------------------------------------------------------------
# 필드 정보 (1개의 열에 해당).
#------------------------------------------------------------------------
class Field:
	name_  : str
	type_ : str
	kind_ : DataKind
	is_array_ : bool
	comment_ : str
	data_ : list
	def __init__(self):
		self.name_ = str()
		self.type_ = str()
		self.kind_ = DataKind.UNKNOWN
		self.is_array_ = bool()
		self.comment_ = str()
		self.data_ = list()

#------------------------------------------------------------------------
# 테이블 정보.
#------------------------------------------------------------------------
class Table:
	name_ : str
	field_dict_ : dict # key:index, value:Field
	data_count_ : int
	def __init__(self):
		self.name_ = str()
		field_dict_ = dict()
		data_count_ = int()

#------------------------------------------------------------------------
# 규격화된 XLSX 파일에서 네이티브테이블을 만들어냄.
#------------------------------------------------------------------------
def CreateNativeTableListFromXlsxFile(file_name : str, startswith = "#") -> list:
	nativetable_list = list()
	#xlrd은 더이상 사용하지 않음.
	#book = xlrd.open_workbook(file_name)
	#for sheet in book.sheets():
	#	if sheet.name.startswith(startswith):
	#		native_table = NativeTable()
	#		native_table.name_ = sheet.name.replace(startswith, "")
	#		for row_index in range(sheet.nrows):
	#			cell_list = sheet.row_values(row_index)
	#			cols = list()
	#			for cell in cell_list:
	#				cols.append(str(cell))
	#			native_table.row_list_.append(cols)
	#		native_table_list.append(native_table)
	#return native_table_list
	book = openpyxl.load_workbook(file_name)
	for sheetname in book.sheetnames:
		if not sheetname.startswith(startswith):
			continue;
		sheet = book[sheetname]
		if not sheet:
			continue;
		nativetable = NativeTable()
		nativetable.name_ = sheetname.replace(startswith, "")
		for row_index in range(1, sheet.max_row + 1):
			cols = list()
			for col_index in range(1, sheet.max_column + 1):
				cell = sheet.cell(row = row_index, column = col_index)
				if cell.value:
					cols.append(str(cell.value))
				else:
					cols.append("")
			nativetable.row_list_.append(cols)
		nativetable_list.append(nativetable)
	return nativetable_list

#------------------------------------------------------------------------
# 네이티브테이블을 가지고 테이블을 만들어냄.
#------------------------------------------------------------------------
def CreateTable(native_table : NativeTable):
	table = Table()
	table.name_ = native_table.name_
	table.data_count_ = 0
	table.field_dict_ = dict()

	# 맨 앞 셀의 이름을 찾으면 다 넣고 종료.
	# 문자열이 존재하면 해당 필드가 존재하는 것.
	for row in native_table.row_list_:
		rowtype = row[0].lower()
		if rowtype == "field":
			rowdata = row[1:]
			for col_index in range(len(rowdata)):

				# 값이 존재하는 컬럼만.
				value = rowdata[col_index]
				if value:
					# 전체 키워드 검사.
					if value == csharp_strong_keyword_list_ or not IsCorrectName(value):
						print(f"Error!! FieldName='{value}'")
						sys.exit(-1)

					field = Field()
					field.name_ = value
					table.field_dict_[col_index] = field

			break

	# 필드와 동일한 인덱스에서 내용을 다 채워넣음.
	for row in native_table.row_list_:
		rowtype = row[0].lower()
		if rowtype == "type" or rowtype == "comment" or rowtype == "data":
			row_columns = row[1:]
			for col_index in range(len(row_columns)):

				# 필드제목이 있어 필드로 인정되는 컬럼만.
				if col_index in table.field_dict_.keys():
					value = row_columns[col_index]
					field = table.field_dict_[col_index]
					if rowtype == "type":

						# 배열여부 판단하고 배열표시 삭제 (끝이 배열[]로 끝나면 배열).
						type_length = len(value)
						if type_length > 2 and value[type_length - 2] == "[" and value[type_length - 1] == "]":
							value = value[:-2]
							field.is_array_ = True

						# 타입명 제외 키워드 검사.
						if value == csharp_weak_keyword_list_ or not IsCorrectName(value):
							print(f"Error!! FieldType='{value}'")
							sys.exit(-1)

						field.type_ = value

						if field.type_ in ["char", "sbyte", "short", "int", "long", "byte", "ushort", "uint", "ulong"]:
							field.kind_ = DataKind.NUMBER
						elif field.type_ in ["float", "double"]:
							field.kind_ = DataKind.REAL
						elif field.type_ in ["bool"]:
							field.kind_ = DataKind.BOOLEAN
						else:
							field.kind_ = DataKind.TEXT
							field.is_array_ = False # 문자열타입은 배열일 수 없음.

					elif rowtype == "comment":
						field.comment_ = value
					elif rowtype == "data":
						field.data_.append(value)

	# 데이터 범위 체크....

	# 빈 데이터 기본값 설정 + 최대데이터 카운트 셋팅.
	for field in table.field_dict_.values():
		data_count = len(field.data_)
		if table.data_count_ < data_count:
			table.data_count_ = data_count

		for data_index in range(data_count):
			value = field.data_[data_index]

			# 값이 존재하지 않을 때.
			if value == "":
				# 정수형.
				if field.kind_ == DataKind.NUMBER:
					field.data_[data_index] = "0"
				# 실수형.
				elif field.kind_ == DataKind.REAL:
					field.data_[data_index] = "0.0"
				# 논리형.
				elif field.kind_ == DataKind.BOOLEAN:
					field.data_[data_index] = "false"
			else:
				if field.kind_ == DataKind.NUMBER:
					field.data_[data_index] = str(int(float(value)))
				elif field.kind_ == DataKind.REAL:
					field.data_[data_index] = str(float(value))
				elif field.kind_ == DataKind.BOOLEAN:
					field.data_[data_index] = "true" if value.lower() == "true" else "false"

	return table

#------------------------------------------------------------------------
# TABLE을 JSON 파일로 변환.
#------------------------------------------------------------------------
def CreateJsonFileFromTable(file_name : str, table : Table):
	result = str()
	result += "[\n"

	field_count = len(table.field_dict_)
	for row_index in range(table.data_count_):
		result += "\t{\n"
		field_index = 0
		for field in table.field_dict_.values():
			field_name = field.name_
			field_value = DataValueToJsonValue(field.data_[row_index], field.kind_, field.is_array_)

			result += f"\t\t\"{field_name}\": {field_value}"
			if field_index + 1 < field_count:
				result += ",\n"
			else:
				result += "\n"
			field_index += 1
		if row_index + 1 < table.data_count_:
			result += "\t},\n"
		else:
			result += "\t}\n"
	result += "]"
	with open(file_name, "w+", encoding = "utf8") as file:
		file.write(result)

#------------------------------------------------------------------------
# 테이블을 CS 파일로 변환.
#------------------------------------------------------------------------
def CreateCsFileFromTable(file_name : str, table : Table, make_enum_fields : list):
	table_name = table.name_
	result = str()

	#result += "using DagraacSystems;\n"
	#result += "using DagraacSystems.Table;\n"
	#result += "using DagraacSystems.TableExtension;\n"
	#result += "using System.Collections.Generic;\n"
	result += "\n"
	result += "\n"

	if make_enum_fields != None:
		for make_enum_field in make_enum_fields:
			result += f"public enum {table_name}_{make_enum_field}\n" # CommonTable_Name
			result += "{\n"
			for field in table.field_dict_.values():
				if field.name_ == make_enum_field and (field.kind_ == DataKind.NUMBER or field.kind_ == DataKind.TEXT):
					for data in field.data_:
						if data:
							result += f"\t{data},\n" # 열거체 작성을 원하는 필드의 모든 값은 서로 유니크여야함.
			result += "}\n"
			result += "\n"
			result += "\n"

	# 클래스.
	result += f"public class {table_name}Data : DagraacSystems.ITableData\n"
	result += "{\n"
	for field in table.field_dict_.values():
		field_name = field.name_
		field_type = field.type_
		field_comment = field.comment_
		if field_comment:
			result += f"\t/// <summary>{field_comment}</summary>\n"
		result += f"\tpublic {field_type} {field_name};\n\n"
	#result += "\n"

	#int ToFields();
	result += "\tpublic System.Collections.Generic.List<DagraacSystems.FieldInfo> ToFields()\n"
	result += "\t{\n"
	result += "\t\treturn new System.Collections.Generic.List<DagraacSystems.FieldInfo>()\n"
	result += "\t\t{\n"
	field_index = 0
	for field in table.field_dict_.values():
		field_name = field.name_
		result += f"\t\t\tnew DagraacSystems.FieldInfo(\"{field_name}\", {field_name}.GetType(), {field_name}),\n"
		field_index += 1
	result += "\t\t};\n"
	result += "\t}\n"
	result += "\n"

	#int GetFieldIndex(string name);
	result += "\tpublic int GetFieldIndex(string name)\n"
	result += "\t{\n"
	result += "\t\tswitch (name)\n"
	result += "\t\t{\n"
	field_index = 0
	for field in table.field_dict_.values():
		field_name = field.name_
		result += f"\t\t\tcase \"{field_name}\": return {field_index};\n"
		field_index += 1
	result += "\t\t}\n"
	result += "\t\treturn -1;\n"
	result += "\t}\n"
	result += "\n"

	#string GetFieldName(int index);
	result += "\tpublic string GetFieldName(int index)\n"
	result += "\t{\n"
	result += "\t\tswitch (index)\n"
	result += "\t\t{\n"
	field_index = 0
	for field in table.field_dict_.values():
		field_name = field.name_
		result += f"\t\t\tcase {field_index}: return \"{field_name}\";\n"
		field_index += 1
	result += "\t\t}\n"
	result += "\t\treturn string.Empty;\n"
	result += "\t}\n"
	result += "\n"

	#System.Type GetFieldType(int index);
	result += "\tpublic System.Type GetFieldType(int index)\n"
	result += "\t{\n"
	result += "\t\tswitch (index)\n"
	result += "\t\t{\n"
	field_index = 0
	for field in table.field_dict_.values():
		field_name = field.name_
		field_type = field.type_
		field_comment = field.comment_
		result += f"\t\t\tcase {field_index}: return {field_name}.GetType();\n"
		field_index += 1
	result += "\t\t}\n"
	result += "\t\treturn null;\n"
	result += "\t}\n"
	result += "\n"

	#object GetFieldValue(int index);
	result += "\tpublic object GetFieldValue(int index)\n"
	result += "\t{\n"
	result += "\t\tswitch (index)\n"
	result += "\t\t{\n"
	field_index = 0
	for field in table.field_dict_.values():
		field_name = field.name_
		field_type = field.type_
		field_comment = field.comment_
		result += f"\t\t\tcase {field_index}: return (object){field_name};\n"
		field_index += 1
	result += "\t\t}\n"
	result += "\t\treturn null;\n"
	result += "\t}\n"
	result += "\n"

	#int GetFieldCount();
	result += "\tpublic int GetFieldCount()\n"
	result += "\t{\n"
	field_count = len(table.field_dict_)
	result += f"\t\treturn {field_count};\n"
	result += "\t}\n"
	#result += "\n"
	result += "}"

	with open(file_name, "w+", encoding = "utf8") as file:
		file.write(result)

#------------------------------------------------------------------------
# 처리 시작.
#------------------------------------------------------------------------
def OnMain(args):
	print("TableExporter 0.0.4")
	print("made by dagraac")
	print()

	# 필수 인자.
	# 시트를 json과 cs로 익스포트.
	xlsx_file_name = GetAbsPath(str(args[1]))
	json_path = GetAbsPath(str(args[2]))
	cs_path = GetAbsPath(str(args[3]))

	# 추가 인자.
	make_enum_fields = None
	if len(args) > 4:
		make_enum_fields = str(args[4]).split(';')

	BeginTimer(f"\nTotal Time")
	native_table_list = CreateNativeTableListFromXlsxFile(xlsx_file_name)
	for native_table in native_table_list:
		if native_table:
			print(f"{native_table.name_}")
			table = CreateTable(native_table)

			if table:
				json_file_name = f"{json_path}\\{table.name_}.json"
				BeginTimer(f"\t{json_file_name}")
				CreateJsonFileFromTable(json_file_name, table)
				PrintTimer(EndTimer())

				cs_file_name = f"{cs_path}\\{table.name_}Data.cs"
				BeginTimer(f"\t{cs_file_name}")
				CreateCsFileFromTable(cs_file_name, table, make_enum_fields)
				PrintTimer(EndTimer())

	PrintTimer(EndTimer())

#------------------------------------------------------------------------
# 진입점.
#------------------------------------------------------------------------
if __name__ == "__main__":
	OnMain(sys.argv)

# 파일 xlsx json cs

# TableExporter^
#  "D:\Projects\Example\Design\Tables\ExampleTable.xlsx"^
#  "D:\Projects\Example\Client\Assets\Resources\Tables"^
#  "D:\Projects\Example\Client\Assets\Scripts\Tables\Data"

# TableExporter^
#  ".\ExampleTable.xlsx"^
#  "..\..\Client\Assets\Resources\Tables"^
#  "..\..\Client\Assets\Scripts\Tables\Data"


# https://www.acmicpc.net/problem/2961
import sys

read = sys.stdin.readline
N = int(read().rstrip())
data = []
for _ in range(N):
    a, b = map(int, read().split())
    data.append((a, b))

ans = float("inf")

def run(depth, sour, bitter):
    global ans
    if depth == N:
        if (sour, bitter) != (1, 0):
            ans = min(ans, abs(sour - bitter))
        return
    # 포함하는 경우
    run(depth + 1, sour * data[depth][0], bitter + data[depth][1])
    # 포함 안하는 경우
    run(depth + 1, sour, bitter)

run(0, 1, 0)
print(ans)

백준/브루트포스/2961.도영이가만든음식.py

2961.도영이가만든음식.py


# coding: utf-8

# In[29]:

import sys,math
from collections import defaultdict
from pprint import pprint

# In[108]:

def sign(number):
    if number>=0:
        return 1
    else:
        return -1

# In[116]:

class SGD():
    def __init__(self, f_name, iter_times_training=10):
        labels = []
        lines = []
        self.ws = defaultdict(int)

        # read lines and labels
        for line in open(f_name, "r", encoding="utf-8"):
            label, line_ = line.split("\t")
            labels.append(label)
            lines.append(line_)
            for w in line_.split():
                self.ws[w] = 0
        #pprint(self.ws)

        # train the model: update the weights
        for iter_ in range(iter_times_training):
            for label, line in zip(labels, lines):
                #print(label,line)
                phi_dict=self.phi(line)
                val=abs(self.sum_prod(phi_dict))
                if val<=10:
                    self.update_weight(label, phi_dict)

        # generate string showing the predicted value of line
        self.str = ""
        for line in lines:
            label = self.predict_one_line(line)
            predicted_line = "{label}\t{sentence}\n".format(
                label=label, sentence=line)
            self.str += predicted_line

    def predict_one_line(self, line):
        phi_dict = self.phi(line)
        sum_product= self.sum_prod(phi_dict)
        output=(math.e**sum_product)/float((1+math.e)**sum_product)
        print(sum_product,output)
        return sum_product

    def __str__(self):
        return self.str

    def update_weight(self, label, phi_dict, c=0.1,alpha=0.01):
        #phi_dict = self.phi(line)
        # print(phi_dict)
        for w in phi_dict:
            if abs(self.ws[w])<c:
                self.ws[w]=0
            else:
                self.ws[w]-=sign(self.ws[w])*c
        w__phi_x = self.sum_prod(phi_dict)
        coeff_phi = alpha * self.grad_P_coeff_phi(label, phi_dict)
        for w in phi_dict:
            self.ws[w] += coeff_phi * phi_dict[w]
            #print("coeff phi:\t{coeff}\n{weight}".format(coeff=coeff_phi,weight=self.ws[w]))
            #input()

    def grad_P_coeff_phi(self, label, phi_dict):
        #print(label,phi_dict,sep="\n")
        label=int(label)
        coeff = 0
        sum_prod = self.sum_prod(phi_dict)
        #print(sum_prod)
        if label == -1:
            coeff = -math.e**(sum_prod) / ((float(1 + math.e**(sum_prod)))**2)
        elif label == 1:
            coeff = math.e**(sum_prod) / ((float(1 + math.e**(sum_prod)))**2)
        #print(coeff)
        #input()
        return coeff

    def phi(self, line):
        phi_dict = defaultdict(int)
        for w in line.split():
            phi_dict[w] += 1
        return phi_dict

    def sum_prod(self, phi_dict):
        #print(phi_dict)
        output = 0
        for w in phi_dict:
            output += self.ws[w] * phi_dict[w]
        #input(output)
        return output

# In[117]:

training_file_path="../../data/titles-en-train.labeled"

# In[118]:

if __name__=="__main__":
    sgd=SGD(training_file_path)

# In[119]:

print(sgd)

# In[59]:

math.e**0

# In[ ]:


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

import funciones_feria as feria
import math as math
import random as rand

def mostrar_menu()->None:
    print("Opciones")
    print("1.", "Buscar la bolita")
    print("2.", "Tiro al blanco")

def opcion1()->None:
    print("-"*32)
    print("Buscar la bolita")
    print("-"*32)
    posicion_inicial = int(input("Por favor seleccione en cuál vaso debe iniciar la bolita: 1, 2 o 3 "))
    posicion_apuesta = int(input("Por favor seleccione en cuál vaso apuesta que va a quedar la bolita: 1, 2 o 3 "))
    resultado = feria.buscar_bolita(posicion_inicial, posicion_apuesta)
    if resultado:
        print("¡Victoria: encontraste la bolita!")
    else:
        print("¡Perdiste!")

def opcion2()->None:
    print("-"*32)
    print("Tiro al blanco")
    print("-"*32)
    print("Recuerde que el blanco se encuentra a 7 metros de distancia y tiene 40 centímetros de diámetro en total")
    velocidad = float(input("¿Con qué velocidad quiere lanzar la bola? (Km/h) "))
    alfa = float(input("¿A qué ángulo quiere enviar la bola con respecto al plano horizontal? "))
    beta = float(input("¿A qué ángulo quiere enviar la bola con respecto al centro de la mesa? "))

    puntos = feria.tiro_al_blanco(velocidad, alfa, beta)
    if puntos > 0:
        print("¡Le atinaste el blanco! Ganaste", puntos, "puntos")
    else:
        print("¡Fallaste!")
        velocidad = velocidad * 1000 / 3600
        distancia_tiro = round(feria.calcular_distancia_tiro(velocidad, alfa, beta), 1)
        x = round(feria.calcular_x_tiro(distancia_tiro, 7, beta), 0)
        y = round(feria.calcular_y_tiro(distancia_tiro, 7, beta), 0)
        error = math.sqrt(x**2 + y**2)

        print("Pero con esos valores la bola debería haber caído a", distancia_tiro, "metros de distancia, a ", error, "centímetros del centro de la mesa")

mostrar_menu()
opcion = int(input("Por favor seleccione una opción del menú: "))

if opcion == 1:
    opcion1()
elif opcion == 2:
    opcion2()
else:
    print("Por favor seleccione una opción válida")


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 20 10:13:03 2021

@author: staar
"""

#%%
#%%
# 6. You can use "json.dumps()" to pretty-print Python dicts
#    as an alternative to the "pprint" module

# The standard string repr for dicts is hard to read:
my_mapping = {'a': 23, 'b': 42, 'c': 0xc0ffee}
my_mapping
# {'b': 42, 'c': 12648430. 'a': 23}  #

# The "json" module can do a much better job:
import json
print(json.dumps(my_mapping, indent=4, sort_keys=True))
#{
#    "a": 23,
#    "b": 42,
#    "c": 12648430
#}

# Note this only works with dicts containing primitive types (check out the "pprint" module):
json.dumps({all: 'yup'}) #!!! TypeError: keys must be a string

## WHAT'S all TYPE ???

#%%
# In most cases I'd stick to the built-in "pprint" module though :-)
# https://pymotw.com/3/pprint/index.html
import pprint as pp

pp.pprint(my_mapping)
pp.pprint(my_mapping, indent=4, depth=1)  # ?
pp.pformat(my_mapping)  # ?

#%%
data = [
    (1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
    (2, {'e': 'E', 'f': 'F', 'g': 'G', 'h': 'H',
         'i': 'I', 'j': 'J', 'k': 'K', 'l': 'L'}),
    (3, ['m', 'n']),
    (4, ['o', 'p', 'q']),
    (5, ['r', 's', 't''u', 'v', 'x', 'y', 'z']),
]

pp.pprint(data)  # what the hell... ???!!!
pp.pprint(data, indent=4)

#%% 25. Palindrome

def palindrome(a):
    return a == a[::-1]

palindrome('mom')
palindrome('mama')
palindrome('kobylamamalybok')

#%% 2. Anagrams
"""
This method can be used to CHECK IF two strings are anagrams.
An anagram is a word or phrase formed by rearranging the letters
of a different word or phrase, typically using all the original letters
exactly once.
"""

from collections import Counter    #!!!

Counter("aabbbcddeeee")
Counter([1, 2, 1, 3, 2, 4, 3, 2, 1])

def anagram(first, second):
    return Counter(first) == Counter(second)

anagram("abcd3", "3acdb")
anagram("abcd3", "3acd")

#%%
#%% 5. Print a string N times without using loop

print("string"*2)

#%% 6. Capitalize first letters of every word

print("what the hell...!".title())

#%% 13. Decapitalize
"""
This method can be used to turn the first letter of the given string into lowercase.
"""
def decapitalize(ss):
    return ss[:1].lower() + ss[1:]

decapitalize('FooBar')

'FooBar'.lower()  # not the same!
'Foo Bar'.lower()
'Foo BAR'.lower()

#%% 11. Comma-separated
hobbies = ["basketball", "football", "swimming"]
print("My hobbies are:")
print(", ".join(hobbies))

#%% 12. Count vowels

import re  #!!!

def count_vowels(ss):
    return len(re.findall(r'[aeiouy]', ss, re.IGNORECASE))

count_vowels('foobar')
count_vowels('gym')

#%%
import re
len(re.findall('python','python is a programming language. python is python.'))

#%%


from django.urls import path
from app1  import views
from . import views

urlpatterns = [
   # path('app1/', views.app1, name='app1'),
     path('',views.login,name='login'),
     path('reg/',views.register,name='reg'),
     path('home/',views.home,name='home'),
     path('logout/',views.logoutpage,name='logout'),
     path('forgot/',views.forgot,name="forgot"),
     path('home/profile/', views.user_profile, name='user_profile'),
     path('updateprofile/',views.update_profile, name='updateprofile'),

]


from rest_framework import generics
from extraUserController.models import User

from .models import Candidate
from .serializers import CandidateModelSerializer

from rest_framework.decorators import api_view
from rest_framework.response import Response

from documentController.models import PDF
from documentController.serializers import PDFSerializer

from extraUserController.models import User
import os
from urllib.parse import unquote
from election_system_316 import settings

from django.http import FileResponse
import base64

# Create your views here.

class CandidateDetailsView(generics.RetrieveAPIView):
    queryset = Candidate.objects.all()
    serializer_class = CandidateModelSerializer
    lookup_field = 'pk'

candidate_details_view = CandidateDetailsView.as_view()

@api_view(["POST","GET"])
def candidate_list_view(request, *args, **kwargs):
    qs = Candidate.objects.all()
    result_data = CandidateModelSerializer(qs, many = True).data

    return Response(data=result_data)

@api_view(["POST","GET"])
def approved_candidate_list_view(request, *args, **kwargs):
    qs = Candidate.objects.all().filter(is_approved = True)
    result_data = CandidateModelSerializer(qs, many = True).data

    return Response(data=result_data)

@api_view(["POST","PUT"])
def create_candidate_view(request, *args, **kwargs):

    user = User.objects.get(studentNumber = request.data["studentid"])
    data = {
        "student_id": user.studentNumber,
        "name":user.name,
        "surname":user.surname,
        "department": user.department,
        "email":user.email,
        "grade": user.grade
        }

    serializer = CandidateModelSerializer(data=data)
    if(serializer.is_valid(raise_exception=True)):
        serializer.save()
        user.hasApplied = True
        user.save()

    candidate = Candidate.objects.get(student_id = user.studentNumber)
    for i in range(1,4):
        file = request.FILES[f"files{i}"]
        if(file):
            document = PDF(file=file, student=candidate)
            document.save()

    return Response(data={
        "status": "added"
    })

@api_view(["POST"])
def candidate_document_view(request, *args, **kwargs):

    studentNumber = request.data["studentid"]
    user = User.objects.get(studentNumber = studentNumber)
    if(user.hasApplied):
        candidate = Candidate.objects.get(student_id = studentNumber)
        qs = PDF.objects.all().filter(student = candidate)
        documents = PDFSerializer(qs,many = True).data
        document_array = []
        path_array = []
        print(settings.MEDIA_ROOT)
        for document in documents:
            file_path = unquote(document['file'])
            path_array.append(file_path)
            file_path = os.path.join(settings.MEDIA_ROOT, file_path[1::])
            with open(file_path, 'rb') as file:
                file_data = file.read()
                base64_data = base64.b64encode(file_data).decode('utf-8')
                document_array.append(base64_data)
        return Response(data={
            "documents": document_array,
            "paths": path_array
        })
    return Response(data={
        "message": f"The user with student id {studentNumber} has not applied"
    })


import numpy as np
from .op_unit import op_unit

class data_transfer(op_unit):
    def execute(self, cpu):
        decode = self.decode
        if decode[1] == 0x0: #LD
            if self.clock == 2:
                dest = decode[2]
                MAR = decode[3]
                if dest in cpu.retire_his:
                    dest = cpu.retire_his[dest]
                if MAR in cpu.retire_his:
                    MAR = cpu.get_value(cpu.retire_his[MAR])
                else:
                    MAR = cpu.get_value(MAR)
                if self.spec and MAR in cpu.spec_mem:
                    cpu.WBR[dest] = cpu.spec_mem[MAR]
                else:
                    cpu.WBR[dest] = cpu.mem[MAR]

                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1
        elif decode[1] == 0x1: #LDI
            dest = decode[2]
            self.store = False
            cpu.WBR[dest] = decode[3]
            cpu.instruct_per_cycle[cpu.cycle] += 1
            self.clear()
        elif decode[1] == 0x2: #ST
            if self.clock == 1:
                orig = cpu.get_value(decode[2])
                MAR = cpu.get_value(decode[3])
                if self.spec:
                    cpu.spec_mem[MAR] = orig
                else:
                    cpu.mem[MAR] = orig
                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1
        elif decode[1] == 0x3: #STO
            if self.clock == 1:
                offset = decode[3]
                orig = decode[2]
                dest = decode[4]

                if orig in cpu.retire_his:
                    orig = cpu.get_value(cpu.retire_his[orig])
                else:
                    orig = cpu.get_value(orig)

                if dest in cpu.retire_his:
                    MAR = cpu.get_value(cpu.retire_his[dest])
                else:
                    MAR = cpu.get_value(dest)
                if dest in cpu.retire_his:
                    MAR = cpu.get_value(cpu.retire_his[dest])
                else:
                    MAR = cpu.get_value(dest)
                if self.spec:
                    cpu.spec_mem[offset + MAR] = orig
                else:
                    cpu.mem[offset + MAR] = orig
                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1
        elif decode[1] == 0x4:
            if self.clock == 2:
                MAR = decode[4]
                offset = decode[3]
                dest = decode[2]
                if dest in cpu.retire_his:
                    dest = cpu.retire_his[dest]
                if MAR in cpu.retire_his:
                    MAR = cpu.get_value(cpu.retire_his[MAR])
                else:
                    MAR = cpu.get_value(MAR)
                if self.spec and MAR in cpu.spec_mem:
                    cpu.WBR[dest] = cpu.spec_mem[MAR + offset]
                else:
                    cpu.WBR[dest] = cpu.mem[MAR + offset]
                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1
        if decode[1] == 0x5: #VLD
            if self.clock == 2:
                dest = decode[2]
                MAR = decode[3]
                if dest in cpu.retire_his:
                    dest = cpu.retire_his[dest]
                #length = 3
                #stride = 3
                length = cpu.get_length(dest)
                stride = cpu.get_stride(dest)
                end = length * stride
                result = np.array([0]*64)

                if MAR in cpu.retire_his:
                    MAR = cpu.get_value(cpu.retire_his[MAR])
                else:
                    MAR = cpu.get_value(MAR)
                read_from = (range(MAR, (MAR + end)))[::stride]

                if self.spec:
                    i = 0
                    for addr in read_from:
                        if addr in cpu.spec_mem:
                            result[i] = cpu.spec_mem[addr]
                        else:
                            result[i] = cpu.mem[addr]
                        i += 1
                else:
                    result = cpu.mem[MAR:(MAR+end):stride]
                cpu.WBR[dest] = result

                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1
        elif decode[1] == 0x6: #ST
            if self.clock == 1:
                dest = decode[2]
                length = cpu.get_length(dest)
                orig = cpu.get_value(decode[2])
                MAR = cpu.get_value(decode[3])
                store_range = range(MAR, MAR+length)
                if self.spec:
                    raise Exception("")
                    i = 0
                    for addr in store_range:
                        cpu.spec_mem[addr] = orig[i]
                        i += 1
                else:
                    cpu.mem[MAR:(MAR+length)] = orig
                cpu.instruct_per_cycle[cpu.cycle] += 1
                self.clear()
            else:
                self.clock += 1


import sqlite3

from aiotg import Chat

from yubao import extendChat
from yubao.util.sqlite import Sqlite
from yubao.config import Config
config = Config().read_config()

dbfile = dbfile = config['score_db']

class Score():
    def __init__(self, chat:Chat) -> None:
        with Sqlite(dbfile) as sqliter:
            if not sqliter.check_table_exists("score"):
                sqliter.create_table("score","user_id TEXT PRIMARY KEY, first_name TEXT, username TEXT, score INTEGER")
        chat.__class__ = extendChat
        self.uid = chat.get_uid()
        self.first_name = chat.get_first_name()
        self.username = chat.get_username()
        pass

    async def total_score(self):
        with Sqlite(dbfile) as sqliter:
            cursor = await sqliter.execute_sql(f"SELECT * FROM score WHERE user_id='{self.uid}'")
            row = cursor.fetchone()
            if row is None:
                return 0
            else:
                return row[3]

    async def _exist(self):
        with Sqlite(dbfile) as sqliter:
            cursor = await sqliter.execute_sql(f"SELECT * FROM score WHERE user_id='{self.uid}'")
            row = cursor.fetchone()
            return False if row is None else True

    async def add_score(self, score:int):

        async with Sqlite(dbfile) as sqliter:
            if await self._exist():  # 存在这个人的记录，更新分数
                with Sqlite(dbfile) as sqliter:
                    cursor = await sqliter.execute_sql(f"SELECT * FROM score WHERE user_id='{self.uid}'")
                    old_score = cursor.fetchone()[3]
                    new_score = old_score + score
                    cursor1 = await sqliter.execute_sql(f"UPDATE score SET score={new_score}, first_name='{self.first_name}', username='{self.username}' WHERE user_id='{self.uid}'")
            else:  # 不存在记录，插入分数
                await sqliter.execute_sql(f"INSERT INTO score (user_id, first_name, username, score) VALUES ('{self.uid}','{self.first_name}','{self.username}','{score}')")
        return await self.total_score()


"""Allows rendering the content of the scene in the coco file format."""

import datetime
from itertools import groupby
import json
import os
from typing import Optional, Dict, Union, Tuple, List

import numpy as np
from skimage import measure
import cv2
import bpy

from blenderproc.python.utility.LabelIdMapping import LabelIdMapping

def write_coco_annotations(output_dir: str, instance_segmaps: List[np.ndarray],
                           instance_attribute_maps: List[dict],
                           colors: List[np.ndarray], color_file_format: str = "PNG",
                           mask_encoding_format: str = "rle", supercategory: str = "coco_annotations",
                           append_to_existing_output: bool = True,
                           jpg_quality: int = 95, label_mapping: Optional[LabelIdMapping] = None,
                           file_prefix: str = "", indent: Optional[Union[int, str]] = None):
    """ Writes coco annotations in the following steps:
    1. Locate the seg images
    2. Locate the rgb maps
    3. Locate the seg mappings
    4. Read color mappings
    5. For each frame write the coco annotation

    :param output_dir: Output directory to write the coco annotations
    :param instance_segmaps: List of instance segmentation maps
    :param instance_attribute_maps: per-frame mappings with idx, class and optionally supercategory/bop_dataset_name
    :param colors: List of color images. Does not support stereo images, enter left and right inputs subsequently.
    :param color_file_format: Format to save color images in
    :param mask_encoding_format: Encoding format of the binary masks. Default: 'rle'. Available: 'rle', 'polygon'.
    :param supercategory: name of the dataset/supercategory to filter for, e.g. a specific BOP dataset set
                          by 'bop_dataset_name' or any loaded object with specified 'cp_supercategory'
    :param append_to_existing_output: If true and if there is already a coco_annotations.json file in the output
                                      directory, the new coco annotations will be appended to the existing file.
                                      Also, the rgb images will be named such that there are no collisions.
    :param jpg_quality: The desired quality level of the jpg encoding
    :param label_mapping: The label mapping which should be used to label the categories based on their ids.
                          If None, is given then the `name` field in the csv files is used or - if not existing -
                          the category id itself is used.
    :param file_prefix: Optional prefix for image file names
    :param indent: If indent is a non-negative integer or string, then the annotation output
                   will be pretty-printed with that indent level. An indent level of 0, negative, or "" will
                   only insert newlines. None (the default) selects the most compact representation.
                   Using a positive integer indent indents that many spaces per level.
                   If indent is a string (such as "\t"), that string is used to indent each level.
    """

    if len(colors) > 0 and len(colors[0].shape) == 4:
        raise ValueError("BlenderProc currently does not support writing coco annotations for stereo images. "
                         "However, you can enter left and right images / segmaps separately.")

    # Create output directory
    os.makedirs(os.path.join(output_dir, 'images'), exist_ok=True)

    coco_annotations_path = os.path.join(output_dir, "coco_annotations.json")
    # Calculate image numbering offset, if append_to_existing_output is activated and coco data exists
    if append_to_existing_output and os.path.exists(coco_annotations_path):
        with open(coco_annotations_path, 'r', encoding="utf-8") as fp:
            existing_coco_annotations = json.load(fp)
        image_offset = max(image["id"] for image in existing_coco_annotations["images"]) + 1
    else:
        image_offset = 0
        existing_coco_annotations = None

    # collect all RGB paths
    new_coco_image_paths = []

    # for each rendered frame
    for frame in range(bpy.context.scene.frame_start, bpy.context.scene.frame_end):
        color_rgb = colors[frame - bpy.context.scene.frame_start]

        # Reverse channel order for opencv
        color_bgr = color_rgb.copy()
        color_bgr[..., :3] = color_bgr[..., :3][..., ::-1]

        if color_file_format == 'PNG':
            target_base_path = f'images/{file_prefix}{frame + image_offset:06d}.png'
            target_path = os.path.join(output_dir, target_base_path)
            cv2.imwrite(target_path, color_bgr)
        elif color_file_format == 'JPEG':
            target_base_path = f'images/{file_prefix}{frame + image_offset:06d}.jpg'
            target_path = os.path.join(output_dir, target_base_path)
            cv2.imwrite(target_path, color_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality])
        else:
            raise RuntimeError(f'Unknown color_file_format={color_file_format}. Try "PNG" or "JPEG"')

        new_coco_image_paths.append(target_base_path)

    coco_output = _CocoWriterUtility.generate_coco_annotations(instance_segmaps,
                                                               instance_attribute_maps,
                                                               new_coco_image_paths,
                                                               supercategory,
                                                               mask_encoding_format,
                                                               existing_coco_annotations,
                                                               label_mapping)

    print("Writing coco annotations to " + coco_annotations_path)
    with open(coco_annotations_path, 'w', encoding="utf-8") as fp:
        json.dump(coco_output, fp, indent=indent)

def binary_mask_to_rle(binary_mask: np.ndarray) -> Dict[str, List[int]]:
    """Converts a binary mask to COCOs run-length encoding (RLE) format. Instead of outputting
    a mask image, you give a list of start pixels and how many pixels after each of those
    starts are included in the mask.
    :param binary_mask: a 2D binary numpy array where '1's represent the object
    :return: Mask in RLE format
    """
    rle: Dict[str, List[int]] = {'counts': [], 'size': list(binary_mask.shape)}
    counts = rle.get('counts')
    for i, (value, elements) in enumerate(groupby(binary_mask.ravel(order='F'))):
        if i == 0 and value == 1:
            counts.append(0)
        counts.append(len(list(elements)))
    return rle

def rle_to_binary_mask(rle: Dict[str, List[int]]) -> np.ndarray:
    """Converts a COCOs run-length encoding (RLE) to binary mask.
    :param rle: Mask in RLE format
    :return: a 2D binary numpy array where '1's represent the object
    """
    binary_array = np.zeros(np.prod(rle.get('size')), dtype=bool)
    counts: List[int] = rle.get('counts')

    start = 0
    for i in range(len(counts) - 1):
        start += counts[i]
        end = start + counts[i + 1]
        binary_array[start:end] = (i + 1) % 2

    binary_mask = binary_array.reshape(*rle.get('size'), order='F')

    return binary_mask

class _CocoWriterUtility:

    @staticmethod
    def generate_coco_annotations(inst_segmaps, inst_attribute_maps, image_paths, supercategory,
                                  mask_encoding_format, existing_coco_annotations=None,
                                  label_mapping: LabelIdMapping = None):
        """Generates coco annotations for images

        :param inst_segmaps: List of instance segmentation maps
        :param inst_attribute_maps: per-frame mappings with idx, class and optionally supercategory/bop_dataset_name
        :param image_paths: A list of paths which points to the rendered images.
        :param supercategory: name of the dataset/supercategory to filter for, e.g. a specific BOP dataset
        :param mask_encoding_format: Encoding format of the binary mask. Type: string.
        :param existing_coco_annotations: If given, the new coco annotations will be appended to the given
                                          coco annotations dict.
        :param label_mapping: The label mapping which should be used to label the categories based on their ids.
                              If None, is given then the `name` field in the csv files is used or - if not existing -
                              the category id itself is used.
        :return: dict containing coco annotations
        """

        categories = []
        visited_categories = []
        instance_2_category_maps = []

        for inst_attribute_map in inst_attribute_maps:
            instance_2_category_map = {}
            for inst in inst_attribute_map:
                # skip background
                if int(inst["category_id"]) != 0:
                    # take all objects or objects from specified supercategory is defined
                    inst_supercategory = "coco_annotations"
                    if "bop_dataset_name" in inst:
                        inst_supercategory = inst["bop_dataset_name"]
                    elif "supercategory" in inst:
                        inst_supercategory = inst["supercategory"]

                    if supercategory in [inst_supercategory, 'coco_annotations']:
                        if int(inst["category_id"]) not in visited_categories:
                            cat_dict: Dict[str, Union[str, int]] = {'id': int(inst["category_id"]),
                                                                    'supercategory': inst_supercategory}
                            # Determine name of category based on label_mapping, name or category_id
                            if label_mapping is not None:
                                cat_dict["name"] = label_mapping.label_from_id(cat_dict['id'])
                            elif "name" in inst:
                                cat_dict["name"] = inst["name"]
                            else:
                                cat_dict["name"] = inst["category_id"]

                            categories.append(cat_dict)
                            visited_categories.append(cat_dict['id'])
                        instance_2_category_map[int(inst["idx"])] = int(inst["category_id"])
            instance_2_category_maps.append(instance_2_category_map)

        licenses = [{
            "id": 1,
            "name": "Attribution-NonCommercial-ShareAlike License",
            "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/"
        }]
        info = {
            "description": supercategory,
            "url": "https://github.com/waspinator/pycococreator",
            "version": "0.1.0",
            "year": 2020,
            "contributor": "Unknown",
            "date_created": datetime.datetime.utcnow().isoformat(' ')
        }

        images: List[Dict[str, Union[str, int]]] = []
        annotations: List[Dict[str, Union[str, int]]] = []

        for inst_segmap, image_path, instance_2_category_map in zip(inst_segmaps, image_paths,
                                                                    instance_2_category_maps):

            # Add coco info for image
            image_id = len(images)
            images.append(_CocoWriterUtility.create_image_info(image_id, image_path, inst_segmap.shape))

            # Go through all objects visible in this image
            instances = np.unique(inst_segmap)
            # Remove background
            instances = np.delete(instances, np.where(instances == 0))
            for inst in instances:
                if inst in instance_2_category_map:
                    # Calc object mask
                    binary_inst_mask = np.where(inst_segmap == inst, 1, 0)
                    # Add coco info for object in this image
                    annotation = _CocoWriterUtility.create_annotation_info(len(annotations) + 1,
                                                                           image_id,
                                                                           instance_2_category_map[inst],
                                                                           binary_inst_mask,
                                                                           mask_encoding_format)
                    if annotation is not None:
                        annotations.append(annotation)

        new_coco_annotations = {
            "info": info,
            "licenses": licenses,
            "categories": categories,
            "images": images,
            "annotations": annotations
        }

        if existing_coco_annotations is not None:
            new_coco_annotations = _CocoWriterUtility.merge_coco_annotations(existing_coco_annotations,
                                                                             new_coco_annotations)

        return new_coco_annotations

    @staticmethod
    def merge_coco_annotations(existing_coco_annotations, new_coco_annotations):
        """ Merges the two given coco annotation dicts into one.

        Currently, this requires both coco annotations to have the exact same categories/objects.
        The "images" and "annotations" sections are concatenated and respective ids are adjusted.

        :param existing_coco_annotations: A dict describing the first coco annotations.
        :param new_coco_annotations: A dict describing the second coco annotations.
        :return: A dict containing the merged coco annotations.
        """

        # Concatenate category sections
        for cat_dict in new_coco_annotations["categories"]:
            if cat_dict not in existing_coco_annotations["categories"]:
                existing_coco_annotations["categories"].append(cat_dict)

        # Concatenate images sections
        image_id_offset = max(image["id"] for image in existing_coco_annotations["images"]) + 1
        for image in new_coco_annotations["images"]:
            image["id"] += image_id_offset
        existing_coco_annotations["images"].extend(new_coco_annotations["images"])

        # Concatenate annotations sections
        if len(existing_coco_annotations["annotations"]) > 0:
            annotation_id_offset = max(annotation["id"] for annotation in existing_coco_annotations["annotations"]) + 1
        else:
            annotation_id_offset = 0
        for annotation in new_coco_annotations["annotations"]:
            annotation["id"] += annotation_id_offset
            annotation["image_id"] += image_id_offset
        existing_coco_annotations["annotations"].extend(new_coco_annotations["annotations"])

        return existing_coco_annotations

    @staticmethod
    def create_image_info(image_id: int, file_name: str, image_size: Tuple[int, int]) -> Dict[str, Union[str, int]]:
        """Creates image info section of coco annotation

        :param image_id: integer to uniquly identify image
        :param file_name: filename for image
        :param image_size: The size of the image, given as [W, H]
        """
        image_info: Dict[str, Union[str, int]] = {
            "id": image_id,
            "file_name": file_name,
            "width": image_size[1],
            "height": image_size[0],
            "date_captured": datetime.datetime.utcnow().isoformat(' '),
            "license": 1,
            "coco_url": "",
            "flickr_url": ""
        }

        return image_info

    @staticmethod
    def create_annotation_info(annotation_id: int, image_id: int, category_id: int, binary_mask: np.ndarray,
                               mask_encoding_format: str, tolerance: int = 2) -> Optional[Dict[str, Union[str, int]]]:
        """Creates info section of coco annotation

        :param annotation_id: integer to uniquly identify the annotation
        :param image_id: integer to uniquly identify image
        :param category_id: Id of the category
        :param binary_mask: A binary image mask of the object with the shape [H, W].
        :param mask_encoding_format: Encoding format of the mask. Type: string.
        :param tolerance: The tolerance for fitting polygons to the objects mask.
        """

        area = _CocoWriterUtility.calc_binary_mask_area(binary_mask)
        if area < 1:
            return None

        bounding_box = _CocoWriterUtility.bbox_from_binary_mask(binary_mask)

        if mask_encoding_format == 'rle':
            segmentation = binary_mask_to_rle(binary_mask)
        elif mask_encoding_format == 'polygon':
            segmentation = _CocoWriterUtility.binary_mask_to_polygon(binary_mask, tolerance)
            if not segmentation:
                return None
        else:
            raise RuntimeError(f"Unknown encoding format: {mask_encoding_format}")

        annotation_info: Dict[str, Union[str, int]] = {
            "id": annotation_id,
            "image_id": image_id,
            "category_id": category_id,
            "iscrowd": 0,
            "area": area,
            "bbox": bounding_box,
            "segmentation": segmentation,
            "width": binary_mask.shape[1],
            "height": binary_mask.shape[0],
        }
        return annotation_info

    @staticmethod
    def bbox_from_binary_mask(binary_mask: np.ndarray) -> List[int]:
        """ Returns the smallest bounding box containing all pixels marked "1" in the given image mask.

        :param binary_mask: A binary image mask with the shape [H, W].
        :return: The bounding box represented as [x, y, width, height]
        """
        # Find all columns and rows that contain 1s
        rows = np.any(binary_mask, axis=1)
        cols = np.any(binary_mask, axis=0)
        # Find the min and max col/row index that contain 1s
        rmin, rmax = np.where(rows)[0][[0, -1]]
        cmin, cmax = np.where(cols)[0][[0, -1]]
        # Calc height and width
        h = rmax - rmin + 1
        w = cmax - cmin + 1
        return [int(cmin), int(rmin), int(w), int(h)]

    @staticmethod
    def calc_binary_mask_area(binary_mask: np.ndarray) -> int:
        """ Returns the area of the given binary mask which is defined as the number of 1s in the mask.

        :param binary_mask: A binary image mask with the shape [H, W].
        :return: The computed area
        """
        return binary_mask.sum().tolist()

    @staticmethod
    def close_contour(contour: np.ndarray) -> np.ndarray:
        """ Makes sure the given contour is closed.

        :param contour: The contour to close.
        :return: The closed contour.
        """
        # If first != last point => add first point to end of contour to close it
        if not np.array_equal(contour[0], contour[-1]):
            contour = np.vstack((contour, contour[0]))
        return contour

    @staticmethod
    def binary_mask_to_polygon(binary_mask: np.ndarray, tolerance: int = 0) -> List[np.ndarray]:
        """Converts a binary mask to COCO polygon representation

         :param binary_mask: a 2D binary numpy array where '1's represent the object
         :param tolerance: Maximum distance from original points of polygon to approximated polygonal chain. If
                           tolerance is 0, the original coordinate array is returned.
        """
        polygons = []
        # pad mask to close contours of shapes which start and end at an edge
        padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
        contours = np.array(measure.find_contours(padded_binary_mask, 0.5))
        # Reverse padding
        contours -= 1
        for contour in contours:
            # Make sure contour is closed
            contour = _CocoWriterUtility.close_contour(contour)
            # Approximate contour by polygon
            polygon = measure.approximate_polygon(contour, tolerance)
            # Skip invalid polygons
            if len(polygon) < 3:
                continue
            # Flip xy to yx point representation
            polygon = np.flip(polygon, axis=1)
            # Flatten
            polygon = polygon.ravel()
            # after padding and subtracting 1 we may get -0.5 points in our segmentation
            polygon[polygon < 0] = 0
            polygons.append(polygon.tolist())

        return polygons


from typing import Tuple, Set, Dict
import sqlite3

from models import User, Relation
from utils import interp_value, recalculate_relations
from config import SQLITE_DB_PATH

conn = sqlite3.connect(str(SQLITE_DB_PATH))
cur = conn.cursor()

def get_karma_bounds() -> Tuple[float, float]:
    return cur.execute("""
        SELECT min(karma), max(karma)
        FROM user_karma
        JOIN users ON user_id = users.id
        WHERE chat_id = -1001399056118 AND users.username notnull
    """).fetchone()

def get_exchange_bounds(relations: Set[Relation]) -> Tuple[float, float]:
    key = lambda x: x.exchange
    return min(relations, key=key).exchange, max(relations, key=key).exchange

def get_users() -> Set[User]:
    cur.execute("""SELECT uk.user_id, u.username, u.first_name, u.last_name, uk.karma
                   FROM user_karma AS uk
                   JOIN users AS u ON uk.user_id = u.id
                   WHERE uk.chat_id = -1001399056118
                   AND u.username notnull""")
    users = set()
    for row in cur.fetchall():
        *data, karma = row
        user = User(*data, interp_value(karma, get_karma_bounds(), (10, 100)))
        users.add(user)

    print(f"Total users: {len(users)}")
    return users

def get_users_relations(users: Set[User]) -> Set[Relation]:
    relations_dict = dict()
    for user in users:
        user_relations = get_user_relations(user)

        if not user_relations:
            continue

        relations_dict[user.id] = user_relations

    return recalculate_relations(relations_dict)

def get_user_relations(user: User) -> Dict[int, Relation]:
    cur.execute("""SELECT sum(ke.how_match_change), u.id, u.username, u.first_name, u.last_name, uk.karma
                   FROM karma_events AS ke
                   JOIN users AS u  ON ke.user_to_id = u.id
                   JOIN user_karma AS uk ON ke.user_to_id = uk.user_id
                   WHERE ke.chat_id = -1001399056118
                   AND uk.chat_id = -1001399056118
                   AND ke.user_from_id = ?
                   AND u.username notnull
                   GROUP BY uk.user_id""", [user.id])

    user_relations = dict()
    for row in cur.fetchall():
        total_change, *to_user_data = row
        to_user = User(*to_user_data)
        rel = Relation(user, to_user, total_change)
        user_relations[to_user.id] = rel

    return user_relations


from unittest import mock

import pytest

from jrnl.os_compat import on_posix
from jrnl.os_compat import on_windows
from jrnl.os_compat import split_args

@pytest.mark.parametrize(
    "systems",
    [
        ["linux", False],
        ["win32", True],
        ["cygwin", False],
        ["msys", False],
        ["darwin", False],
        ["os2", False],
        ["os2emx", False],
        ["riscos", False],
        ["atheos", False],
        ["freebsd7", False],
        ["freebsd8", False],
        ["freebsdN", False],
        ["openbsd6", False],
    ],
)
def test_on_windows(systems):
    osname, expected_on_windows = systems[0], systems[1]
    with mock.patch("jrnl.os_compat.platform", osname):
        assert on_windows() == expected_on_windows

@pytest.mark.parametrize(
    "systems",
    [
        ["linux", True],
        ["win32", False],
        ["cygwin", True],
        ["msys", True],
        ["darwin", True],
        ["os2", True],
        ["os2emx", True],
        ["riscos", True],
        ["atheos", True],
        ["freebsd7", True],
        ["freebsd8", True],
        ["freebsdN", True],
        ["openbsd6", True],
    ],
)
def test_on_posix(systems):
    osname, expected_on_posix = systems[0], systems[1]
    with mock.patch("jrnl.os_compat.platform", osname):
        assert on_posix() == expected_on_posix

@pytest.mark.parametrize(
    "args",
    [
        ["notepad", ["notepad"]],
        ["subl -w", ["subl", "-w"]],
        [
            '"C:\\Program Files\\Sublime Text 3\\subl.exe" -w',
            ['"C:\\Program Files\\Sublime Text 3\\subl.exe"', "-w"],
        ],
    ],
)
def test_split_args_on_windows(args):
    input_arguments, expected_split_args = args[0], args[1]
    with mock.patch("jrnl.os_compat.on_windows", lambda: True):
        assert split_args(input_arguments) == expected_split_args

@pytest.mark.parametrize(
    "args",
    [
        ["vim", ["vim"]],
        [
            'vim -f +Goyo +Limelight "+set spell linebreak"',
            ["vim", "-f", "+Goyo", "+Limelight", '"+set spell linebreak"'],
        ],
    ],
)
def test_split_args_on_not_windows(args):
    input_arguments, expected_split_args = args[0], args[1]
    with mock.patch("jrnl.os_compat.on_windows", lambda: True):
        assert split_args(input_arguments) == expected_split_args


def word_search(key, filename):
    dict = {}
    with open(filename) as file:
        lines = file.readlines()
    for number, line in enumerate(lines, 1):
        if key in line:
            t = str(number)
            answer = (f'{key} : {t}')
            print(answer)
            # m = str(number)
            # dict.update({str(key) : list(m)})

            # dict[key] = dict.get(str(key), 0) + list(m)
    # print(dict)

import string
consonants = "bcdfghjklmnpqrstvwxyz"
vowel = "aeiou"
with open("C:/Users/zeu/Documents/Exam_First/exam.txt") as txt:
    text = txt.read()
from string import punctuation
text = text.lower()
for char in punctuation:
    text = text.replace(char, '')
uniq = []
words = text.split()
for i in words:
    if i not in words:
        uniq.append(i)
# print(uniq)
# print(words)
l = set(words)

d = {}
for w in words:
    if w in d:
        d[w] += 1
    else:
        d[w] = 1
# print(d)
x = d.keys()
print(x)

y = d.values()
# print(x)
# print(y)
# strings = input("Enter all the strings use to wish to search separated by space:\n")
# string_list = list(strings.split())
# print(string_list)
for item in x:
    z = word_search(item, "C:/Users/zeu/Documents/Exam_First/exam.txt")

# import csv

# k = ['twinkle', 'twinkle', 'little', 'stars', 'how', 'i', 'wonder', 'what', 'you', 'are', 'up', 'above', 'the', 'world',]
# for a in k:
#     f = a
#     print(f)
# header = ["unique word", "number appearance", "linenumbers"]
# footer = [f, y, z]
# # for row in words:
# #     footer.append(row)
# #     # print(j)
# with open("exam.csv", "w") as csvfile:
#     writer = csv.writer(csvfile)
#     writer.writerow(header)
#     writer.writerow(footer)


import sys

# * ========================================================
# * @Title       : 2748
# * @Path        : python\문제풀이\boj\z.분류별\2748_피보나치 수 2.py
# * @Link        : https://www.acmicpc.net/problem/2748
# * @Description : 피보나치 수 2
# * @Note        :
# * @Date        : 2021-08-13 22:20:44
# * --------------------------------------------------------
# * @Author      : Inseong-so(https://github.com/inseong-so)
# * ========================================================

# Solve 함수
def solution(N):
    dp = [0 for _ in range(91)]
    dp[1] = 1
    dp[2] = 1
    for i in range(3, N + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    print(dp[N])

# 입력
solution(int(input()))

def test_01(capfd):
    solution(10)
    out, err = capfd.readouterr()
    result = '55\n'
    assert out == result
    # assert solution() == 0

# def test_02(capfd):
    # solution()
    # out, err = capfd.readouterr()
    # result = '\n'
    # assert out == result

# def test_03(capfd):
    # solution()
    # out, err = capfd.readouterr()
    # result = '\n'
    # assert out == result

# def test_04(capfd):
    # solution()
    # out, err = capfd.readouterr()
    # result = '\n'
    # assert out == result


import pdb
import re, sys, os, getopt, string, codecs, fnmatch, shutil, struct, binascii

def usage ():
    sys.exit("Syntax:  %s 'bzImage' 'npcpu_boot.cfg' \n%s\n" %
    (os.path.basename(sys.argv[0]),
    """\nFunction:\n
    This utility takes in a bzImage and boot config file (npcpu_boot.cfg).
    It then appends a C little endian structure to be read by the BIOS that
    has the information about the size and location of both the bzImage and
    the boot config file. The BIOS can use this information to read the kernel
    comand line and launch the kernel at runtime.
    Required Arguments (for creation):
    'bzImage'          Path to the NPCPU kernel image.
    'npcpu_boot.cfg'   Path to the NPCPU kernel boot config file (contains kernel command line).
    'outputFile'       The output filename
    Required Arguments (to separate config from kernel):
    'Config+Kernel'    The file that has the kernel and the config file combined already.
    """))

def main(argv) :
    ##### Read input arguments and options
    try:
        opts, args = getopt.getopt(argv[0:],"")
    except getopt.GetoptError:
        usage()

    separateConfig = False

    # If we just have 2 args, we are separating the kernel from config file.
    if len(args) == 2:
        separateConfig = True
    elif len(args) == 4:
        bzImageFile = args[1]
        configFile = args[2]
        outputFile = args[3]
    else:
        usage()

    # This is the struct format used.
    s = struct.Struct('< 8s L L L L')

    #If we are separating config from kernel
    if separateConfig:
        print("Separating config file form kernel using file: " + args[1])
        dir = os.path.dirname(os.path.realpath(__file__))
        inputFilePath = os.path.join(dir, os.path.normpath(args[1]))
        file = open(inputFilePath,'rb')
        bytes = file.read()

        #Get the structure from the begining of the opened file.
        structVal = s.unpack_from(bytes)

        #Make sure we have a valid header signature
        if structVal[0] == b'$KRNLCFG':
            print("Found Header Signature! " + structVal[0].decode("utf-8"))
            print("KernelImageSize: " + str(structVal[1]))
            print("KernelImageOffset: " + str(structVal[2]))
            print("BootConfigFileSize: " + str(structVal[3]))
            print("BootConfigFileOffset: " + str(structVal[4]))
            outputFileDir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
            try:
                #Write out the kernel config file
                #Seek file to Config File offset
                file.seek(structVal[4])
                configOutputPath = os.path.join(outputFileDir, 'npcpu_boot.cfg')
                configOutFile = open(configOutputPath, 'wb');
                configOutFile.write(file.read(structVal[3]))
                configOutFile.close()
                print("Wrote npcpu_boot.cfg out to file: "+configOutputPath)

                #Write out the kernel bzImage
                #Seek file to Kernel File offset
                file.seek(structVal[2])
                bzImageOutputPath = os.path.join(outputFileDir, 'npcpu_bzImage')
                bzImageOutFile = open(bzImageOutputPath, 'wb');
                bzImageOutFile.write(file.read(structVal[1]))
                bzImageOutFile.close()
                print("Wrote bzImage out to file: "+bzImageOutputPath)
            except:
                print("ERROR! There is trouble writing out the file, do you have write permissions?")
                return 1
        else:
            print("Could not find header signature! Are you sure this kernel has a npcpu_boot.cfg file attached?")
            return 1

    #Else we are combining config to kernel
    else:
        ## Get the absolute path for each input.
        dir = os.path.dirname(os.path.realpath(__file__))
        bzImagePath = os.path.join(dir, os.path.normpath(bzImageFile))
        configFilePath = os.path.join(dir, os.path.normpath(configFile))
        outputFilePath = os.path.join(dir, os.path.normpath(outputFile))

        print("Using %s for the NPCPU kernel." % bzImagePath)
        print("Using %s for the npcpu_boot.cfg file." % configFilePath)
        print("Output file path is %s." % configFilePath)

        # Get the file size of the 2 input files.
        bzImageSize = os.path.getsize(bzImagePath)
        configFileSize = os.path.getsize(configFilePath)

        # The kernel is always right after the header. The header MUST be 512 bytes.
        bzImageOffset = 512

        # Calculate the offset of the configfile.
        configFileOffset = bzImageOffset + bzImageSize

        # Create the header to wrap the ARM kernel and config file
        # The BIOS needs this in little endian format and exactly how
        # The structure is as listed below.

        ## The size of the structure must be 512 bytes.
        ## define NPCPU_HEADER_SIGNATURE SIGNATURE_64('$', 'K', 'R', 'N', 'L', 'C', 'F', 'G')
        ## Create the struct the BIOS is expecting.
        ## typedef struct{
        ##    UINT64 Signature;
        ##    UINT32 KernelImageSize;      //The size of the kernel image
        ##    UINT32 KernelImageOffset;    //The offset in bytes relative to the begining of the partition.
        ##    UINT32 BootConfigFileSize;   //The size of the boot config file.
        ##    UINT32 BootConfigFileOffset; //The offset in bytes relative to the begining of the partition.
        ##    UINT8 Reserved[488]; //To allign this structure to 512 bytes EMMC block size.
        ## } NpcpuKernelHeader;

        ## Should be little endian, need to pack the struct with the proper values.
        values = (b'$KRNLCFG', bzImageSize, bzImageOffset, configFileSize, configFileOffset)

        #Create the structure to write to file.
        packed_data = s.pack(*values)

        #Open bzImage file to write it out.
        bzImageFileH = open(bzImagePath,'rb')
        #Open boot config file to write it out.
        configFileH = open(configFilePath,'rb')

        # Read in the data from the files
        bzImageData = bzImageFileH.read()
        configFileData = configFileH.read()

        # Open the output file and write out
        # the data in the following order.
        # Header(512 B) + ARM bzImage + npcpu_boot.cfg
        destination = open(outputFilePath,'wb')
        destination.write(packed_data+bytearray(488)+bzImageData+configFileData)

        print("")
        print("Finished creating %s output file!" % outputFilePath)

    return 0

if __name__ == '__main__' :
  print ("\nIntel NPCPU kernel and config image creation tool.\n")
  sys.exit(main(sys.argv))


#background.py

import pyglet,viewport
#background_batch=pyglet.graphics.Batch()

pyglet.resource.path.append('./images')
pyglet.resource.reindex()

background1_image=pyglet.resource.image('ocean_floor_background.png')
background2_image=pyglet.resource.image('jungle_background.jpg')
background3_image=pyglet.resource.image('space_background.jpg')

bg_map={1:background1_image,
        2:background2_image,
        3:background3_image}

class Background(pyglet.sprite.Sprite):
        def __init__(self,level,*args,**kwargs):
                super(Background,self).__init__(bg_map[level],*args,**kwargs)

                #self.scale=.999


#!/usr/bin/python3

import os
import sys

"""
Offline analysis by replaying logs
"""

# Import MobileInsight modules
from mobile_insight.monitor import OfflineReplayer
from mobile_insight.analyzer import MsgLogger, LteRrcAnalyzer, WcdmaRrcAnalyzer, LteNasAnalyzer, UmtsNasAnalyzer, LteMacAnalyzer, LteMeasurementAnalyzer

# Initialize a monitor
src = OfflineReplayer()
src.set_input_path("./logs/")
# src.enable_log_all()

src.enable_log("LTE_PHY_Serv_Cell_Measurement")
src.enable_log("5G_NR_RRC_OTA_Packet")
src.enable_log("LTE_RRC_OTA_Packet")
src.enable_log("LTE_NB1_ML1_GM_DCI_Info")

logger = MsgLogger()
logger.set_decode_format(MsgLogger.JSON)
logger.set_dump_type(MsgLogger.FILE_ONLY)
logger.save_decoded_msg_as("./mobileinsight.log")
logger.set_source(src)

# # Analyzers
# nr_rrc_analyzer = NrRrcAnalyzer()
# nr_rrc_analyzer.set_source(src)  # bind with the monitor

lte_rrc_analyzer = LteRrcAnalyzer()
lte_rrc_analyzer.set_source(src)  # bind with the monitor

# wcdma_rrc_analyzer = WcdmaRrcAnalyzer()
# wcdma_rrc_analyzer.set_source(src)  # bind with the monitor

# lte_nas_analyzer = LteNasAnalyzer()
# lte_nas_analyzer.set_source(src)

# umts_nas_analyzer = UmtsNasAnalyzer()
# umts_nas_analyzer.set_source(src)

# lte_mac_analyzer = LteMacAnalyzer()
# lte_mac_analyzer.set_source(src)

# lte_meas_analyzer = LteMeasurementAnalyzer()
# lte_meas_analyzer.set_source(src)

# print lte_meas_analyzer.get_rsrp_list()
# print lte_meas_analyzer.get_rsrq_list()

# Start the monitoring
src.run()

#The code above uses the mobile insight packages to decode the logs into a readable JSON-like format

#These system calls correct the formatting within the log so the python JSON decoder is able to interpret it correctly

os.system("echo \"{\" > log.json")
os.system("echo '\"log\": [' >> log.json")
os.system("sed -i 's/$/,/g' mobileinsight.log")  # add commas to the end of each line
os.system("sed -i '$ s/.$//' mobileinsight.log")  # remove the last comma
os.system("cat mobileinsight.log >> log.json")
os.system("echo \"]\" >> log.json")
os.system("echo \"}\" >> log.json")

import json
from datetime import datetime
from datetime import timedelta

with open("log.json", "r") as f:
    data = json.load(f)

log = data["log"]

def message_type_parsing(log):
    message_types = []
    for (i, entry) in enumerate(log): #iterate over each log entry
        type_id = entry['type_id']
        if type_id != 'LTE_RRC_OTA_Packet':
            message_types.append((i, type_id)) #only interested in parsing the LTE_RRC_OTA_Packets so skip the others
            continue
        cell_id = entry['Physical Cell ID']
        msg = entry['Msg']['msg']['packet']['proto'][5]['field']['field']
        if msg[1]['field'].__class__ != list: # paging messages
            message_types.append((i, type_id, cell_id, "paging"))
            continue
        msg_type = msg[1]['field'][1]['@showname']
        if msg_type == "c1: systemInformation (0)": #Handles SIB Info packets
            sib_types = msg[1]['field'][1]['field']['field'][1]['field']['field'][2]['field']
            if sib_types.__class__ != list:
                sib_types = [sib_type]
            sibs = []
            for sib_type in sib_types:
                sibs.append(sib_type['field'][2]['@showname'])
            message_types.append((i, type_id, cell_id, msg_type, sibs))
        else:
            message_types.append((i, type_id, cell_id, msg_type))
    return message_types

for line in message_type_parsing(log):
    print(line, file=open("message_types.txt", 'a'))

#The message_type_parsing function gives a high level overview of the type of information for each and every log entry
#This information is then stored in message_types.txt

rrcpackts = [entry for entry in log if entry["type_id"] == "LTE_RRC_OTA_Packet"]

releaseNsetup = []
for i, entry in enumerate(log):
    type_id = entry['type_id']
    if type_id != 'LTE_RRC_OTA_Packet':
        continue
    msg = entry["Msg"]["msg"]["packet"]["proto"][5]["field"]["field"]
    if msg[1]["field"].__class__ != list:  # paging messages
        continue
    msg_type = msg[1]["field"][1]["@showname"]
    if ( #want to extract only the connectionRelease and connectionSetupComplete log entries
        msg_type == "c1: rrcConnectionRelease (5)"
        or msg_type == "c1: rrcConnectionSetupComplete (4)"
    ):
        temp = dict(
            (k, entry[k]) for k in ["timestamp", "Physical Cell ID"] if k in entry
        )
        temp["msg_type"] = msg_type
        temp["index"] = i
        releaseNsetup.append(temp)

#releaseNsetup is a list of all the connection setup and releases and their associated timestamps

sum = 0

for i in range(len(releaseNsetup) - 1):
    entry1 = releaseNsetup[i]
    entry2 = releaseNsetup[i + 1]

    ts1 = entry1["timestamp"]
    ts2 = entry2["timestamp"]

    d1 = datetime.strptime(ts1, "%Y-%m-%d %H:%M:%S.%f")
    d2 = datetime.strptime(ts2, "%Y-%m-%d %H:%M:%S.%f")

    difference = timedelta.total_seconds(d2 - d1)

    if i > 0:
        sum += difference

for line in releaseNsetup:
    print(line, file=open("setupAndReleases.txt", 'a'))

average = sum / (len(releaseNsetup) - 2)
s = f'The average time difference between the two events is {average} seconds'

print(s, file=open("setupAndReleases.txt", 'a'))

#The contents of releaseNsetup as well as the average difference in timestamp is stored in setupAndReleases.txt


import os
import struct
import sys

import shlex
import settings

import ssl
import logging
import irc.client
import irc.bot
import irc.strings

from bs4 import UnicodeDammit
import re
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr

# Horrible hackyclass that I'm using to monkey-patch the line decoder. Unfortunately,
# short of subclassing ALL THE THINGS, I can't very easily override the decoder.
# As such, we just stick a patched decoder into the class at runtime.
class TolerantDecodingLineBuffer(object):

	line_sep_exp = re.compile(b'\r?\n')

	def __init__(self):
		self.buffer = b''

	def feed(self, inBytes):
		self.buffer += inBytes

	def __iter__(self):
		return self.lines()

	def __len__(self):
		return len(self.buffer)

	encodings = ['utf-8', "iso-8859-1", "latin-1"]
	errors = 'strict'

	def lines(self):
		lines = self.line_sep_exp.split(self.buffer)
		# save the last, unfinished, possibly empty line
		self.buffer = lines.pop()

		for line in lines:
			ret = UnicodeDammit(line, self.encodings).unicode_markup
			if not ret:
				raise UnicodeDecodeError("Could not decode '%s'" % line)
			yield ret

class TestBot(irc.bot.SingleServerIRCBot):
	def __init__(self, nickname, realname, server, port=9999):
		ssl_factory = irc.connection.Factory(wrapper=ssl.wrap_socket)

		# Horrible monkey-patch the ServerConnection instance so we can fix some encoding issues.
		print("Old buffer class", irc.client.ServerConnection.buffer_class)
		irc.client.ServerConnection.buffer_class = TolerantDecodingLineBuffer
		print("New buffer class", irc.client.ServerConnection.buffer_class)

		irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, realname, connect_factory=ssl_factory)

		self.log = logging.getLogger("Main.Manga.IRC<%s>" % server)
		self.received_bytes = 0

		self.welcomed = False

	def on_ctcp(self, c, e):
		"""Default handler for ctcp events.

		Replies to VERSION and PING requests and relays DCC requests
		to the on_dccchat method.
		"""

		print("On CTCP", e.arguments)
		nick = e.source.nick
		if e.arguments[0] == "VERSION":
			c.ctcp_reply(nick, "VERSION " + self.get_version())
		elif e.arguments[0] == "PING":
			if len(e.arguments) > 1:
				c.ctcp_reply(nick, "PING " + e.arguments[1])

		elif e.arguments[0] == "DCC":

			# Filenames are a giant PITA. Basically, we try to split the
			# CTCP command. If we get more then 5 items, the name must
			# have spaces, so we then try `shlex.split`. This works
			# around the issue that filenames without spaces
			# can have single quotation marks.
			args = e.arguments[1].strip().split()
			if len(args) != 5:
				args = shlex.split(e.arguments[1])
			if args[0] != "SEND":
				self.log.warning("Not DCC Send. Wat? '%s'", e.arguments)
				return

			self.log.info("Received DCC send command - '%s'", e)

			if hasattr(self, "get_filehandle"):
				self.file = self.get_filehandle(args[1])
				if not self.file:
					self.log.error("Could not get filehandle. XDCC is being dropped.")
					raise irc.client.DCCConnectionError
			else:
				self.filename = os.path.basename(args[1])

				self.log.info("Saving to '%s'", self.filename)

				if os.path.exists(self.filename):
					self.log.error("A file named '%s'", self.filename,)
					self.log.error("already exists. Refusing to save it.")
					# self.connection.quit()
				else:
					self.log.info("Saving item to '%s'", self.filename)
				self.file = open(self.filename, "wb")

			if hasattr(self, "xdcc_receive_start"):
				status = self.xdcc_receive_start()
				if not status:
					return

			peeraddress = irc.client.ip_numstr_to_quad(args[2])
			peerport = int(args[3])

			self.dcc = self.dcc_connect(peeraddress, peerport, "raw")
		else:
			print("Wut?", e)

	def on_dccmsg(self, connection, event):
		data = event.arguments[0]
		self.file.write(data)
		self.received_bytes = self.received_bytes + len(data)
		self.dcc.send_bytes(struct.pack("!I", self.received_bytes))

	def on_dcc_disconnect(self, connection, event):
		self.file.close()
		self.log.info("Received file - %d bytes." % (self.received_bytes))
		if hasattr(self, "xdcc_receive_finish"):
			self.xdcc_receive_finish()

	def on_nicknameinuse(self, connection, event):
		self.log.warning("Nickname %s is in use, adding a trailing '_'", connection.get_nickname() )
		connection.nick(connection.get_nickname() + "_")

	def on_welcome(self, c, e):
		self.log.info("On Welcome. Connected with nickname: %s.", c.get_nickname())
		self.welcomed = True
		if hasattr(self, "welcome_func"):
			self.welcome_func(c, e)

	def on_privmsg(self, c, e):
		self.log.info("On Privmsg = '%s', '%s'", c, e)
		self.say_command(e, e.arguments[0])

	def on_pubmsg(self, c, e):

		a = e.arguments[0].split(":", 1)
		self.log.info("Pubmessage = %s", e.arguments)
		if len(a) > 1 and irc.strings.lower(a[0]) == irc.strings.lower(self.connection.get_nickname()):
			self.log.info("Executing command '%s'", a[1])
			self.say_command(e, a[1].strip())
		return

	def on_dccchat(self, c, e):
		self.log.info("On DccChat")
		if len(e.arguments) != 2:
			return
		args = e.arguments[1].split()
		if len(args) == 4:
			try:
				address = ip_numstr_to_quad(args[2])
				port = int(args[3])
			except ValueError:
				return
			self.dcc_connect(address, port)

	def say_command(self, e, cmd, ):
		nick = e.source.nick
		c = self.connection

		if cmd.startswith(settings.ircBot["pubmsg_prefix"]):
			c.privmsg(e.channel, str(cmd[len(settings.ircBot["pubmsg_prefix"]):]))
		if cmd == "dcc":
			dcc = self.dcc_listen()
			self.log.info("Starting DCC - Command: '%s'", "CHAT chat %s %d" % (ip_quad_to_numstr(dcc.localaddress), dcc.localport))
			c.ctcp("DCC", nick, "CHAT chat %s %d" % (ip_quad_to_numstr(dcc.localaddress), dcc.localport))
		else:
			self.log.error("Unknown command = '%s'" % cmd)

	def say_in_channel(self, channel, message):
		self.log.info("Saygin %s in channel %s", message, channel)
		self.connection.privmsg(channel, message)

	def startup(self):
		self.log.info("Bot entering select loop")
		self.start()

def main():
	print("Sys argv length = ", len(sys.argv))
	if len(sys.argv) != 4:
		print("Usage: testbot <server[:port]> <channel> <nickname>")
		sys.exit(1)

	s = sys.argv[1].split(":", 1)
	server = s[0]
	if len(s) == 2:
		try:
			port = int(s[1])
		except ValueError:
			print("Error: Erroneous port.")
			sys.exit(1)
	else:
		port = 9999
	channel = sys.argv[2]
	nickname = sys.argv[3]

	bot = TestBot(channel, nickname, server, port)
	print("Bot created. Connecting")
	bot.start()

if __name__ == "__main__":
	main()


import glob as glob, shutil,os, json, mido
from os.path import join
from pypianoroll import Multitrack
from tqdm import tqdm
''' pypianoroll == 0.5.3!!!!'''

class MidiFileProcessor(Multitrack):
    def __init__(
        self,
        fldr,
        #savez,
    ) -> None:
        self.fldr = fldr # the folder where your midis are saved
        #self.savez = savez

    def get_items(
        self,
    ) -> None:
        files = glob.glob(join(self.fldr, '*[mM][iI][dD]'))
        str_files, clean_files = [], []

        progress_bar = tqdm(total=len(files), desc="Cleaning Files", unit="file", ncols=80)

        for f in files:
            try:
                gud_f =Multitrack(f)
                len(gud_f.tracks)
                str_files +=[f]
                clean_files += [gud_f]
            except (ValueError, IndexError, OSError, mido.midifiles.meta.KeySignatureError) as e:
                continue

            progress_bar.update(1)

        progress_bar.close()

        return str_files, clean_files

    def most_common(
        self,
        lst,
    ) -> None:
        return max(set(lst), key=lst.count)

    def get_listItems(
        self,
        n_tracks: int=0,
    ) -> None:
        #os.makedirs(self.savez, exist_ok=True)
        str_files, clean_files = self.get_items()

        tracks = [len(f.tracks) for f in clean_files]
        mc = self.most_common(tracks)
        ## support for own track input
        if n_tracks > 0:
            mc = n_tracks

        cocon = "The most common have {} tracks".format(mc)
        '''loop'''
        common = []
        for f, c in zip(str_files, clean_files):
            if len(c.tracks) == mc:
                common +=[f]
                #print('moving:', f, 'with no. of tracks ', len(m.tracks))
                #shutil.move(f, self.savez)
        os.makedirs('utilities', exist_ok=True)

        with open('utilities/common_files.json', 'w') as outfile:
            json.dump(common, outfile)

        with open('utilities/mc.txt', 'w') as mc_file:
            mc_file.write(cocon)


from .base import *  # noqa
from .base import env

# GENERAL
# ------------------------------------------------------------------------------
SECRET_KEY = env("DJANGO_SECRET_KEY")
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=["example.com"])

# DATABASES
# ------------------------------------------------------------------------------
DATABASES["default"]["CONN_MAX_AGE"] = env.int("CONN_MAX_AGE", default=60)  # noqa F405

# CACHES
# ------------------------------------------------------------------------------
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": env("REDIS_URL"),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "IGNORE_EXCEPTIONS": True,
        },
    }
}

# SECURITY
# ------------------------------------------------------------------------------
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
    "DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True
)
SECURE_HSTS_PRELOAD = env.bool("DJANGO_SECURE_HSTS_PRELOAD", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
    "DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True
)

# STORAGES
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["storages"]  # noqa F405
AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME")
AWS_QUERYSTRING_AUTH = False
# DO NOT change these unless you know what you're doing.
_AWS_EXPIRY = 60 * 60 * 24 * 7
AWS_S3_OBJECT_PARAMETERS = {
    "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate"
}
AWS_S3_MAX_MEMORY_SIZE = env.int(
    "DJANGO_AWS_S3_MAX_MEMORY_SIZE",
    default=100_000_000,  # 100MB
)
AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None)
AWS_S3_CUSTOM_DOMAIN = env("DJANGO_AWS_S3_CUSTOM_DOMAIN", default=None)
aws_s3_domain = AWS_S3_CUSTOM_DOMAIN or f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"

# STATIC
# ------------------------
STATICFILES_STORAGE = "fyra.utils.storages.StaticRootS3Boto3Storage"
COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy"
STATIC_URL = f"https://{aws_s3_domain}/static/"

# MEDIA
# ------------------------------------------------------------------------------
DEFAULT_FILE_STORAGE = "fyra.utils.storages.MediaRootS3Boto3Storage"
MEDIA_URL = f"https://{aws_s3_domain}/media/"

# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env(
    "DJANGO_DEFAULT_FROM_EMAIL",
    default="fyra <noreply@fyra.com>",
)
# https://docs.djangoproject.com/en/dev/ref/settings/#server-email
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
# https://docs.djangoproject.com/en/dev/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = env(
    "DJANGO_EMAIL_SUBJECT_PREFIX",
    default="[fyra]",
)

# ADMIN
# ------------------------------------------------------------------------------
ADMIN_URL = env("DJANGO_ADMIN_URL")
CSRF_TRUSTED_ORIGINS = ['https://*.YOUR_DOMAIN.COM']

# Anymail
# ------------------------------------------------------------------------------
INSTALLED_APPS += ["anymail"]  # noqa F405
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
ANYMAIL = {
    "MAILGUN_API_KEY": env("MAILGUN_API_KEY"),
    "MAILGUN_SENDER_DOMAIN": env("MAILGUN_DOMAIN"),
    "MAILGUN_API_URL": env("MAILGUN_API_URL", default="https://api.mailgun.net/v3"),
}

# Collectfast
# ------------------------------------------------------------------------------
INSTALLED_APPS = ["collectfast"] + INSTALLED_APPS  # noqa F405

# LOGGING
# ------------------------------------------------------------------------------
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(module)s %(process)d %(thread)d %(message)s'
        }
    },
    'handlers': {
        'gunicorn': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'formatter': 'verbose',
            'filename': 'gunicorn.errors',
            'maxBytes': 1024 * 1024 * 100,  # 100 mb
        }
    },
    'loggers': {
        'gunicorn.errors': {
            'level': 'DEBUG',
            'handlers': ['gunicorn'],
            'propagate': True,
        },
    }
}


"""
File Tasks
"""

from __future__ import division, print_function, absolute_import, unicode_literals
import re
import os
import time
import logging
import magic
from zg.util import config, url_valid, md5file, sha512file, to_bytes
from .helpers import TaskMapper
from zg.app import celery
from zg.task import image

logger = logging.getLogger('zg.task.file')

# map tasks by mimetype:
file_mapper = TaskMapper()
file_mapper.by_mimetype('image/*')(image.discover)

def gen_checksum(filename):
    return md5file(filename)

def gen_cryptohash(filename):
    return sha512file(filename)

def validate_file(tempfile):
    logger.debug('validate file: %s', tempfile)
    if not os.path.isfile(tempfile):
        logger.error('tempfile validation failure: no tempfile')
        return (None, None)

    max_size = to_bytes(config('upload.max_size'))
    filesize = os.path.getsize(tempfile)
    if filesize > max_size:
        logger.error('tempfile validation failure: tempfile is too large!')
        return (None, None)

    ma = magic.Magic(mime=True)
    mimetype = ma.from_file(tempfile)
    if mimetype not in config('upload.accept_mimetypes'):
        logger.error('tempfile validation failure: mimetype not allowed!')
        return (None, None)

    return (filesize, mimetype)

@celery.task
def discover(item_id, tempfile, **data):
    """Discover a local file."""
    logger.info('discover(item: {} tempfile: {} data: {})'.format(item_id, tempfile, data))
    url = data.pop('url', None)
    upload = data.pop('upload', None)
    try:
        filesize, mimetype = validate_file(tempfile)
        if not filesize: raise Exception('tempfile validation failure')
        task = file_mapper.get_task_for_mimetype(mimetype)
        if not task: raise Exception('no applicable task found!')
        task.delay(item_id, tempfile, mimetype=mimetype, url=url, upload=upload)
    except Exception as e:
        logger.error('file discover failure: ' + str(e))
        logger.error(e)
        os.remove(tempfile)
        logger.debug('temporary file deleted: ' + tempfile)


import tensorflow as td
from tensorflow import keras
import numpy as np

import numpy as np
# save np.load
np_load_old = np.load

# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)

# call load_data with allow_pickle implicitly set to true
data = keras.datasets.imdb
(train_data, train_labels), (test_data, test_labels) = data.load_data(num_words=88000)

# restore np.load for future normal usage
np.load = np_load_old

word_index = data.get_word_index()

# Make space for special tags in word index
word_index = {k:(v+3) for k, v in word_index.items()}
word_index["<PAD>"] = 0;
word_index["<START>"] = 1;
word_index["<UNK>"] = 2;
word_index["<UNUSED>"] = 3;

reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])

# Load in data
train_data = keras.preprocessing.sequence.pad_sequences(train_data, value=word_index["<PAD>"], padding="post", maxlen=250)
test_data = keras.preprocessing.sequence.pad_sequences(test_data, value=word_index["<PAD>"], padding="post", maxlen=250)

# Convert text back to readable text
def decode_review(text):
    return " ".join([reverse_word_index.get(i, "?") for i in text])

# print(len(test_data[0]), len(test_data[1]))

# Try to load in existing model, if not, re-train model
try:
    model = keras.models.load_model("model.h5")
except:

    # create, train, and fit the model
    model = keras.Sequential()
    model.add(keras.layers.Embedding(88000,16))
    model.add(keras.layers.GlobalAveragePooling1D())
    model.add(keras.layers.Dense(16, activation="relu"))
    model.add(keras.layers.Dense(1, activation="sigmoid")) # Sigmoid squishes values between 0-1

    model.summary()

    model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

    x_val = train_data[:10000]
    x_train = train_data[10000:]

    y_val = train_labels[:10000]
    y_train = train_labels[10000:]

    fitModel = model.fit(x_train, y_train, epochs=10, batch_size=512, validation_data=(x_val, y_val), verbose=1)

    # Use model to evaluate test data
    results = model.evaluate(test_data, test_labels)

    # Print the predictions
    test_review = test_data[0]
    predict = model.predict([test_review])
    print("Review: ")
    print(decode_review(test_review))
    print("Prediction: " + str(predict[0]))
    print("Actual: " + str(test_labels[0]))
    print(results)

    # Save model
    model.save("model.h5")

# Return encoded version of text
def review_encode(s):
    encoded = [1]

    for word in s:
        # If we have this word stored, append its index
        if word.lower() in word_index:
            encoded.append(word_index[word.lower()])
        else:
            # If we don't have this word in our index, append 2 to represent unknown tag
            encoded.append(2)

    return encoded

# Use model on test data to predict
with open("movieReview2.txt", encoding="utf-8") as f:
    for line in f.readlines():
        # Pre-process and encode input text
        nline = line.replace(",", "").replace(".", "").replace("(", "").replace(")", "").replace(":", "").replace(";", "").replace("\"", "").replace("—", "").replace("\'", "").replace("?", "").strip().split(" ")
        encode = review_encode(nline)
        encode = keras.preprocessing.sequence.pad_sequences([encode], value=word_index["<PAD>"], padding="post", maxlen=250)

        # Make a prediction with our model
        predict = model.predict(encode)

        # Print results
        print(line)
        print(encode)
        print(predict[0])