'\n\n employee_translations_of_body.unlink() # delete old translation, to test the creation now\n body_translation_vals['value'] = ''\n\n # admin can create\n new = Translation.create(body_translation_vals)\n new.unlink()\n\n # Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin\n with self.assertRaises(AccessError):\n Translation.with_user(self.user_employee).create(body_translation_vals)\n\n\n ### check qweb inline dynamic\n Translation.insert_missing(employee_template._fields['subject'], employee_template)\n employee_translations_of_subject = Translation.with_user(self.user_employee).search(\n [('res_id', '=', employee_template.id), ('name', '=', 'mail.template,subject'), ('lang', '=', 'fr_FR')],\n limit=1\n )\n # keep a copy to create new translation later\n subject_translation_vals = employee_translations_of_subject.read([])[0]\n\n # write on translation for template without dynamic code is allowed\n employee_translations_of_subject.value = 'non-qweb'\n\n # cannot write dynamic code on mail_template translation for employee without the group mail_template_editor.\n with self.assertRaises(AccessError):\n employee_translations_of_subject.value = '{{ object.foo }}'\n\n employee_translations_of_subject.unlink() # delete old translation, to test the creation now\n subject_translation_vals['value'] = '{{ object.foo }}'\n\n # admin can create\n new = Translation.create(subject_translation_vals)\n new.unlink()\n\n # Employee without mail_template_editor group cannot create dynamic translation for mail.render.mixin\n with self.assertRaises(AccessError):\n Translation.with_user(self.user_employee).create(subject_translation_vals)\n","repo_name":"anhjean/beanbakery_v15","sub_path":"addons/mail/tests/test_mail_template.py","file_name":"test_mail_template.py","file_ext":"py","file_size_in_byte":7638,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"}
+{"seq_id":"9101312215","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom Models.Filter import Filter\nfrom UI.Custom.JSONVar import JSONVar\nfrom UI.Custom.LabelInput import LabelInput\n\n\nclass SearchFrame(tk.Frame):\n def __init__(self, parent, lists: JSONVar):\n super().__init__(parent)\n\n self.bind()\n\n self.lists = lists\n self.lists.trace_add('write', self._update_lists)\n\n # List filter\n self.list_input_value = tk.StringVar()\n self.list_input_value.set(\"None\")\n self.list_input = LabelInput(self, \"List:\", self.list_input_value, ttk.Combobox,\n label_args={\"font\": \"Helvetica 14 bold\"},\n input_args={\"values\": self.lists.get()})\n self.list_input.place(relx=0.1, rely=0.03, relwidth=0.8, relheight=0.12)\n self.list_input.input.bind('<>', self.list_filter_changed)\n\n def show(self):\n self.tkraise()\n\n def _update_lists(self, *_):\n self.list_input.input[\"values\"] = self.lists.get()\n\n def get_filter(self):\n return Filter(self.list_input_value.get())\n\n def list_filter_changed(self, *_):\n self.master.event_generate(\"<>\")\n","repo_name":"MarcoB123456/BookTracker","sub_path":"UI/Widgets/SearchFrame.py","file_name":"SearchFrame.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"36447031836","text":"from gallery.db import create_image\nimport os\n\nUPLOADS_DIR = './uploads'\n\n\ndef upload_file(fileitem, title):\n if not os.path.isdir(UPLOADS_DIR):\n os.makedirs(UPLOADS_DIR)\n fileitem.save(os.path.join(UPLOADS_DIR, fileitem.filename))\n\n create_image(fileitem.filename, title)\n","repo_name":"sebbekarlsson/example-gallery-app","sub_path":"gallery/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"22466308287","text":"#!/usr/bin/env python\n\n##recreate figure 3\n\nimport sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport scipy\nfrom scipy.stats import pearsonr\n\nk562_model_predictions = [] ##predictions\nk562_observations = [] ##real\ngene_names = [] ##for read gene names\ndescriptions = [] ##for red globin gene names\n\n\nfor i, line in enumerate(open(sys.argv[1])) :\n if line.strip('\"').startswith(\"##\") :\n ##stripping the \"\" and only looking at things starting with ## which contains our header (pulling out the header into a list)\n header = np.array(line.strip('\"\\r\\n').split('\\t'))\n k562_obs_idx = np.where(header == \"E123\")[0][0]\n ##need index 0 so that we do not get back an array\n ##the column is 60\n ## double [0] so its not in a list and is just a number\n print(k562_obs_idx)\n #print(header)\n elif not line.strip('\"').startswith(\"#\"):\n ##pulling out the data points that don't have #\n fields = line.strip('\"\\r\\n').split('\\t')\n k562_model_predictions.append(float(fields[4]))\n ##line 4 and putting it in this list\n k562_observations.append(float(fields[k562_obs_idx]))\n gene_names.append(fields[1])\n descriptions.append(fields[2])\n \n##now we are making a scatter plot\n## we are first putting points on the graph\n\ngenesoi = [\"PIM1\", \"SMYD3\", \"FADS1\", \"PRKAR2B\", \"GATA1\", \"MYC\"]\ngenesoilocs = []\n\n\n##find gene of interest locations\n\nfor geneoi in genesoi:\n genesoilocs.append(np.where(np.array(gene_names) == geneoi)[0][0])\n\n##lopping through descriptions to find ones with hemoglobin subunit in descriptions\n\nfor i in range(len(descriptions)):\n if \"hemoglobin subunit\" in descriptions[i]:\n genesoi.append(gene_names[i])\n genesoilocs.append(i)\n\ncor = pearsonr(k562_model_predictions, k562_observations)\n##findingout r value\nfig, ax = plt.subplots()\nax.scatter(k562_model_predictions, k562_observations, color=\"blue\", s=0.25, alpha=1)\nax.set_xlabel(\"Predicted K562 expression level, \\n10-fold cross-validated\")\nax.set_ylabel(\"K562 expression level log(10)\")\nline_xs = np.linspace(max(min(k562_model_predictions) ,min(k562_observations) ), min(max(k562_model_predictions) ,max(k562_observations)), 100)\nline_ys = 0 + 1 * line_xs\nax.plot(line_xs, line_ys, color = \"maroon\")\n#where we put the r squared text in\nax.text(0.5, 3.75, \"r^2 =\" + str(round(cor.statistic**2, 2)) + \"\\nn = \" + str(len(k562_observations)))\n##this is us putting the gene names in for our guys of interest\nfor geneoi, idx in zip(genesoi, genesoilocs):\n ax.text(k562_model_predictions[idx], k562_observations[idx], geneoi, color=\"maroon\", fontweight=\"demi\")\n\n##put in our x and y spot to put in the text and then specify the text\n##now we add out n value \nax.spines.right.set_visible(False)\nax.spines.top.set_visible(False)\nfig.savefig( \"yay.abbys.plt\" + \".png\" )\nplt.tight_layout()\nplt.show()\n\n\n","repo_name":"amolnar1/qbb2022-answers","sub_path":"week10/week10.py","file_name":"week10.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"24045518444","text":"\"\"\"\r\nContains all crawlers for the project\r\n\r\n\"\"\"\r\n\r\nimport subprocess\r\nimport os\r\nimport time\r\nimport logging\r\n\r\nlogging.basicConfig(\r\n level=logging.INFO,\r\n format=\"%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s\",\r\n handlers=[\r\n logging.FileHandler(\r\n \"{0}/{1}.log\".format(os.getcwd(), \"screaming_frog\")),\r\n logging.StreamHandler()\r\n ])\r\n\r\n\r\nclass ScreamingFrogSpider(object):\r\n \"\"\"\r\n Make use of Screaming Frog (SF) (https://www.screamingfrog.co.uk/) via the subprocess module.\r\n It calls the Screaming Frog CLI, default url is based off of the default set up.\r\n param:seospiderconfig_absolute_pathname: str pathname to binary file containing all config set up using SF UI.\r\n mandatory parameter by design, so you remember to add the correct configuration every time\r\n param:output_folder:str where all output should be saved to.\r\n param:export_tabs:list of strings all exports under export, matching the UI. default extract Internal:All Name matches UI set up\r\n param:file_full_path:str path to list of urls to crawl if list mode.\r\n param:spider name:str\r\n param:override\r\n \"\"\"\r\n\r\n def __init__(self,\r\n seospiderconfig_absolute_pathname,\r\n cli_exe,\r\n file_full_path=None,\r\n name=\"screaming_frog\",\r\n override=False,\r\n output_folder=os.getcwd(),\r\n ):\r\n self.name = name\r\n self.seospiderconfig_absolute_pathname = seospiderconfig_absolute_pathname\r\n self.output_folder = output_folder\r\n self.cli_exe = cli_exe\r\n self.file_full_path = file_full_path\r\n self.override = override\r\n self.logger = logging.getLogger()\r\n\r\n def _define_overwrite_mode(self, override_switch):\r\n if override_switch == True:\r\n return \"--overwrite\"\r\n else:\r\n return \"--timestamped-output\"\r\n\r\n def start_list_crawl(self, *args):\r\n \"\"\"This function makes use of the subprocess module to call screaming frog for crawling\r\n lists of urls.\r\n See https://screamingfrog.co.uk/seo-spider/user-guide/general/#command-line\r\n \"\"\"\r\n now = time.time()\r\n\r\n list_crawl_configuration = [self.cli_exe,\r\n \"--crawl-list\",\r\n self.file_full_path,\r\n \"--headless\",\r\n \"--config\",\r\n self.seospiderconfig_absolute_pathname,\r\n \"--output-folder\",\r\n self.output_folder,\r\n\r\n ]\r\n\r\n self.logger.info(\"crawl configuration: %s\", repr(list_crawl_configuration))\r\n self.logger.info(\"parsing arguments\")\r\n\r\n for arg in args:\r\n self.logger.info(\"parsed %s\", arg)\r\n list_crawl_configuration.append(arg)\r\n\r\n list_crawl_configuration.append(self._define_overwrite_mode(self.override))\r\n\r\n file_list = os.listdir(self.output_folder)\r\n\r\n subprocess.run(list_crawl_configuration, shell=True)\r\n\r\n return None\r\n\r\n def start_spider_crawl(self, website, *args):\r\n \"\"\"This function makes use of the subprocess module to call screaming frog for crawling\r\n websites\r\n See https://screamingfrog.co.uk/seo-spider/user-guide/general/#command-line\r\n \"\"\"\r\n list_crawl_configuration = [self.cli_exe,\r\n \"--crawl\",\r\n website,\r\n \"--headless\",\r\n \"--config\",\r\n self.seospiderconfig_absolute_pathname,\r\n \"--output-folder\",\r\n self.output_folder,\r\n ]\r\n for arg in args:\r\n list_crawl_configuration.append(arg)\r\n\r\n list_crawl_configuration.append(\r\n self._define_overwrite_mode(self.override))\r\n\r\n logger.info(\"Crawling %s\", list_crawl_configuration[2])\r\n subprocess.run(list_crawl_configuration, shell=True)\r\n\r\n return None\r\n\r\n def __str__(self):\r\n return f\"\"\"ScreamingFrogSpider(name:{self.name},\r\n spider_config:{self.seospiderconfig_absolute_pathname},\r\n cli:{self.cli_exe},\r\n list_of_urls:{self.file_full_path},\r\n override_mode:{self.override}\r\n \"\"\"\r\n","repo_name":"RougeRedWired/screaming-frog-python-driver","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"6339995044","text":"import pytest\n\nfrom . import create_package, delete_package, run_from\n\n\n@pytest.fixture\ndef context():\n return {\n \"full_name\": \"John Doe\",\n \"email\": \"johndoe@domain.tld\",\n \"project_name\": \"Test Package\",\n \"version\": \"22.2.11\",\n }\n\n\n@pytest.fixture\ndef package(context, tmp_path):\n \"\"\"\n Create a new package, in a temporary directory, given the configuration\n given by the \"context\" fixture. Once done, clean it up.\n \"\"\"\n\n package = create_package(target=tmp_path, **context)\n yield package\n delete_package(package)\n\n\n@pytest.fixture(autouse=True)\ndef run_from_package(package):\n \"\"\"\n By default, all tests will run with the package as their working directory.\n \"\"\"\n\n with run_from(package.package):\n yield\n","repo_name":"enterthetag/pybase","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"70239981275","text":"#! /usr/bin/env python\n\n# Built-in imports\nimport unittest\nimport random\n\n# Local imports\nfrom sudoku.data.sudoku_solution_data import SudokuSolution\n\n\nclass TestSudokuSolution(unittest.TestCase):\n def setUp(self):\n self.sudoku_Solution = SudokuSolution(random)\n self.solution = self.sudoku_Solution.create()\n self.baseline = self.sudoku_Solution.baseline\n self.grid_len = self.sudoku_Solution.grid_len\n\n def test_create_compare_horizontal(self):\n \"\"\"Tests if the horizontal lines are valid in the sudoku board.\"\"\"\n\n for row in self.solution: self.assertEqual(sorted(row), list(range(1, self.grid_len + 1)))\n \n def test_create_compare_vertical(self):\n \"\"\"Tests if the vertical lines are valid in the sudoku board.\"\"\"\n \n for i in range(9): self.assertEqual(sorted([ row[i] for row in self.solution ]), list(range(1, self.grid_len + 1)))\n \n def test_create_compare_tiles(self):\n \"\"\"Tests if the tiles are valid in the sudoku board.\"\"\"\n\n y0 = lambda y: y // self.baseline * self.baseline # Pattern for vertical startpoint of each tile.\n x0 = lambda x: x * self.baseline % self.grid_len # Pattern for horizontal startpoint of each tile.\n\n for i in range(9): self.assertEqual(sorted([ self.solution[y][x] for y in range(y0(i), y0(i) + self.baseline)\n for x in range(x0(i), x0(i) + self.baseline) ]), \n list(range(1, self.grid_len + 1)))\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"DaMalle/Sudoku","sub_path":"sudoku/data/test/unittest_sudoku_solution.py","file_name":"unittest_sudoku_solution.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"73348307356","text":"# ---min24':00\" , 30':00\"------save in file:movie.txt-\n# --use postman software to know how is th Json or use wig IDE\nimport requests\n\ndef func_write(list1):\n with open (\"movie1.txt\",\"a+\") as file1: \n print(\"----------->>>>>>>>>>>><<<<<<<<<<<<<<<<<<--------------------\")\n print(\"file.tell(): \",file.tell())\n file1.write(\"----------->>>>>>>>>>>><<<<<<<<<<<<<<<<<<--------------------\\n\")\n for i in range(len(list1)):\n file1.write(\"{0:-<15d}{1}\".format(i+1,list1[i]))\n file1.write(\"\\n\")\n print(\"Writing the list------DONE!------------\")\n# ---------------------------------------------------------------------------------------\ntry:\n response = requests.get(\"http://moviesapi.ir/api/v1/movies?page=1\")\nexcept Exception as error:\n print(error)\nelse:\n print(\"\\n----->>>>>>>>>>-----------Connection DONE!------\")\n print(\"--response: \",response)\n print(\"-----requests.status_code: \", response.status_code)\n print(\"---------response.json: \",response.json)\n mydict = response.json()\n all_pages = mydict['metadata']['page_count']\n pages= int(input(\"\\n------WE HAVE %s pages.\\nHowmany pages do you want to see? \"%all_pages))\n with open (\"movie1.txt\",\"w+\") as file:\n list_movie = []\n for page in range(pages):\n try:\n response = requests.get(\"http://moviesapi.ir/api/v1/movies?page={}\".format(page+1))\n except Exception as error:\n print(error)\n else:\n print(\"\\n----->>>>>>>>>>-----------Connection DONE!------\")\n print(\"--response: \",response)\n print(\"-----requests.status_code: \", response.status_code)\n print(\"---------response.json: \",response.json)\n if response.status_code == 200:\n mydict = response.json()\n print(\"--------------------------------------\")\n for i in range (10):\n str_title = \"{0:-<10}{1}\".format((i+1+page*10),mydict['data'][i]['title'])\n print(str_title)\n list_movie.append(mydict['data'][i]['title'])\n file.write(str_title)\n file.write(\"\\n\")\n print(\"\\nlist_movie:\\n\",list_movie)\n func_write(list_movie)\n print(\"\\n--------Writing DONE!!!---------\")\n print(\"\\nfile.tell(): \",file.tell())\n file.seek(0)\n print(\"file.tell()after file.seek(0): \",file.tell())\n print(\"\\n------>>>>>>>>>>>>>-----file.read():----------------\\n{}\".format(file.read()))\n\n\n\n\n","repo_name":"patrickpink/API_01","sub_path":"K42_01_movie3.py","file_name":"K42_01_movie3.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"17856100208","text":"import asyncio\n\nimport websockets\nfrom aioconsole import ainput\n\n\nasync def send_message(ws):\n while True:\n await asyncio.sleep(0)\n message = await ainput(\"> \")\n await ws.send(message)\n\n\nasync def receive_message(ws):\n while True:\n await asyncio.sleep(1)\n async for res in ws:\n print(res)\n\n\nasync def connect(uri):\n async with websockets.connect(uri) as ws:\n await asyncio.gather(*[send_message(ws), receive_message(ws)])\n\n\ndef main():\n loop = asyncio.get_event_loop()\n asyncio.ensure_future(connect('ws://localhost:8765'))\n loop.run_forever()\n\n\nif name == 'main':\n main()\n \n","repo_name":"Nerevarsoul/chats","sub_path":"websockets_chat/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"34135353435","text":"\"\"\"Board creation functions\"\"\"\n\nfrom __future__ import annotations\nfrom typing import Final\nimport logging\nimport asyncio\n\nfrom homeassistant.const import (\n CONF_ENTITIES,\n CONF_MAC,\n CONF_NAME,\n)\nfrom homeassistant.helpers import discovery\n\nfrom dScriptModule import dScriptBoard\nfrom .const import (\n DATA_BOARDS,\n DEFAULT_AESKEY,\n DEFAULT_PORT,\n DEFAULT_PROTOCOL,\n DOMAIN,\n SUPPORTED_PLATFORMS,\n)\nfrom .utils import (\n async_getdSBoardByIP,\n async_getdSBoardByMAC,\n)\n\n_LOGGER: Final = logging.getLogger(__name__)\n\nasync def async_dSBoardPlatformSetup(hass, config, dSBoard=None) -> None:\n \"\"\"Setup different platforms supported by dScriptModule\"\"\"\n for platform in SUPPORTED_PLATFORMS:\n _LOGGER.debug(\"async_dSBoardPlatformSetup: discover platform: %s - %s\",DOMAIN, platform)\n hass.async_create_task(\n discovery.async_load_platform(hass, platform, DOMAIN, dSBoard, config))\n\nclass dScriptBoardHA(dScriptBoard):\n \"\"\"Custom variant of dScriptBoard object for HA\"\"\"\n available = None\n\ndef dSBoardSetup(hass, config, host, port=DEFAULT_PORT, protocol=DEFAULT_PROTOCOL, aeskey=DEFAULT_AESKEY, returnObj=False) -> bool | dScriptBoardHA | None:\n \"\"\"Connect to a new dScriptBoard\"\"\"\n try:\n _LOGGER.debug(\"%s - dSBoardSetup\", host)\n dSBoard = asyncio.run_coroutine_threadsafe(async_getdSBoardByIP(hass, host), hass.loop).result()\n if not dSBoard is None: \n _LOGGER.debug(\"%s - dSBoardSetup: already exists (%s)\", host, dSBoard.IP)\n if returnObj:\n return dSBoard\n else:\n return True\n\n #dSBoard = dScriptBoard(TCP_IP=host, TCP_PORT=port, PROTOCOL=protocol)\n dSBoard = dScriptBoardHA(TCP_IP=host, TCP_PORT=port, PROTOCOL=protocol)\n if len(aeskey) > 0:\n dSBoard.SetAESKey(aeskey)\n\n _LOGGER.debug(\"%s - dSBoardSetup: pre-init via protocol %s\", dSBoard._HostName, dSBoard._Protocol)\n dSBoard.InitBoard()\n dSBoard.available = True\n _LOGGER.info(\"%s - dSBoardSetup: initialized %s (%s)\", dSBoard._HostName, dSBoard._ModuleID, dSBoard.IP)\n\n _LOGGER.debug(\"%s - dSBoardSetup: MAC cleanup (%s)\", host, dSBoard._MACAddress)\n if len(dSBoard._MACAddress) < 17:\n mac=''\n for m in dSBoard._MACAddress.split(':'):\n while len(m) < 2:\n m = '0' + m\n mac = mac + ':' + m\n mac = mac.lstrip(':')\n _LOGGER.info(\"%s - dSBoardSetup: MAC %s updated to %s\", host, dSBoard._MACAddress, mac)\n dSBoard._MACAddress = mac\n\n _LOGGER.debug(\"%s - dSBoardSetup: Firmware: %s.%s | App: %s.%s | Custom: %s | MAC: %s | IP: %s | Protocol: %s\",\n dSBoard._HostName, dSBoard._SystemFirmwareMajor, dSBoard._SystemFirmwareMinor, \n dSBoard._ApplicationFirmwareMajor, dSBoard._ApplicationFirmwareMinor, dSBoard._CustomFirmeware, dSBoard._MACAddress, dSBoard.IP, dSBoard._Protocol)\n\n dSBoard2 = asyncio.run_coroutine_threadsafe(async_getdSBoardByMAC(hass, dSBoard._MACAddress), hass.loop).result()\n if not dSBoard2 is None: \n _LOGGER.debug(\"%s - dSBoardSetup: already exists (%s)\", host, dSBoard2._MACAddress)\n if returnObj:\n return dSBoard2\n else:\n return True\n\n manual_entities = config[DOMAIN].get(CONF_ENTITIES)\n if not manual_entities is None:\n _LOGGER.debug(\"%s - dSBoardSetup: setting friendly name\", dSBoard._HostName)\n for entity in manual_entities:\n for att in dir(entity):\n if entity[CONF_MAC].lower() == dSBoard._MACAddress.lower():\n dSBoard.friendlyname = entity[CONF_NAME]\n break\n _LOGGER.debug(\"%s - dSBoardSetup: MAC: %s | FriendlyName %s\", dSBoard._HostName, dSBoard._MACAddress, dSBoard.friendlyname)\n \n hass.data[DOMAIN][DATA_BOARDS].append(dSBoard)\n if returnObj:\n return dSBoard\n else:\n return True\n except Exception as e:\n _LOGGER.error(\"%s - dSBoardSetup: failed: %s (%s.%s)\", host, str(e), e.__class__.__module__, type(e).__name__)\n if returnObj:\n return None\n else:\n return False\n","repo_name":"mk-maddin/dScriptModule-HA","sub_path":"custom_components/dscriptmodule_old/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"74871840795","text":"#숫자 2개를 입력받아 곱하는 프로그램\r\nx = input(\"? \")\r\n#변수 x에 첫번째 입력을 함\r\na = int(x)\r\n#x값을 a라는 정수로 바꿈\r\n\r\nx = input(\"? \")\r\nb = int(x)\r\n#위와 똑같이 b에 입력\r\n\r\nprint(a*b)\r\n#a와 b를 곱한 값을 print(출력)\r\n","repo_name":"jennyshin01/python","sub_path":"#숫자 2개를 입력받아 곱하는 프로그램.py","file_name":"#숫자 2개를 입력받아 곱하는 프로그램.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"16662757065","text":"import os\nimport requests\nimport pandas as pd\nimport re\nimport time\nimport pandas_market_calendars as mcal\nimport datetime as datet\n\nfrom FinanceAndMl_libs import finance_ml as fm\nfrom pprint import pprint\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\nfrom termcolor import colored\n\n\n# Settings\npd.set_option('max_rows', 1_000)\npd.set_option('max_columns', 100)\npd.set_option('display.width', 1_200)\n\n\ncur_disc = os.getcwd().split('\\\\')[0]\nuser_name = 'kenney25@lmaritimen.com'\npassword = '329493'\nkey_words = \"dividend or per share or distribution\"\nsort_news = 'date' # hits\nkeyword_type = 'boolean' # boolean\n\nbase_url = 'https://www.stockwatch.com/'\nheaders = {\n 'Accept': \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': \"ru,en-US;q=0.9,en;q=0.8,ru-RU;q=0.7\",\n 'User-Agent': \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36\",\n}\n\n\ndef get_tiingo() -> pd.DataFrame:\n cur_disc = os.getcwd().split('\\\\')[0]\n tiingo_date = '2022-08-08'\n tiingo_week_ago = (pd.to_datetime(tiingo_date) - timedelta(days=7)).strftime('%Y-%m-%d')\n df = pd.read_csv(f'{cur_disc}\\Биржа\\Stocks. BigData\\Projects\\APIs\\API_Tiingo\\supported_tickers {tiingo_date}.csv')\n df = df[\n (df['priceCurrency'] == 'USD') & ~pd.isna(df['startDate']) & ~pd.isna(df['exchange']) &\n ~df['exchange'].isin(['LSE', 'SHE', 'ASX', 'SHG', 'NMFQS', 'CSE']) & (df['endDate'] > tiingo_week_ago)\n ]\n\n return df\n\n\ndef get_asset_type(df_tiingo: pd.DataFrame, ticker: str) -> str:\n cur_df = df_tiingo[df_tiingo['ticker'] == ticker]\n if len(cur_df) == 0:\n print(ticker, cur_df)\n print(colored('Нет тикера в Tiingo базе. Обработай вручную. Будет указан -', 'red'))\n return '-'\n elif len(cur_df) == 1:\n return cur_df['assetType'].iloc[0]\n elif len(cur_df['assetType'].unique()) == 1:\n return cur_df['assetType'].unique()[0]\n else:\n print(colored('Дубликаты в Tiingo базе. Обработай вручную. Будет указан -', 'red'))\n return '-'\n\n\ndef make_data_for_request(soup: BeautifulSoup, names_for_pop: list, data_change: dict) -> dict:\n data = {i['name']: i.get('value', '') for i in soup.select('input[name]')}\n\n for key in names_for_pop:\n data.pop(key)\n for key, value in data_change.items():\n data[key] = value\n\n return data\n\n\ndef time_converter(raw_data) -> (datetime, str):\n date = pd.to_datetime(raw_data.get_text()) + timedelta(hours=3)\n news_time = datetime.strptime(f\"{date.hour}-{date.minute}\", '%H-%M')\n if news_time > datetime.strptime(f\"15-50\", '%H-%M'):\n day_time = 'AMC'\n elif news_time < datetime.strptime(f\"9-30\", '%H-%M'):\n day_time = 'BMO'\n else:\n day_time = 'DAY'\n\n return date, day_time\n\n\ndef fill_news_file(soup: BeautifulSoup, dict_df: dict) -> dict:\n news_table = soup.find('table', border=1).find_all(\"tr\")\n for row in news_table:\n data = row.find_all('td')\n if len(data) == 0 or 'Page' in data[0].get_text():\n continue\n\n headline = data[4].get_text()\n if re.search('dividend', headline, re.IGNORECASE) or re.search('Per Share', headline, re.IGNORECASE) or \\\n re.search('distribution', headline, re.IGNORECASE):\n\n date, day_time = time_converter(data[0])\n ticker = data[1].get_text()\n link = 'https://www.stockwatch.com' + data[4].find('a')['href']\n dict_df['date'].append(date)\n dict_df['time'].append(day_time)\n dict_df['ticker'].append(ticker)\n dict_df['headline'].append(headline)\n dict_df['link'].append(link)\n\n return dict_df\n\n\ndef news_finder(s: requests.Session, key_words: str, sort_news: str, keyword_type: str, start_date: str, end_date: str):\n # Получение новостей ------------------------------------------------------------------------------------------\n dict_df = {'date': [], 'time': [], 'ticker': [], 'headline': [], 'link': []}\n\n r = s.get('https://www.stockwatch.com/News/Search.aspx')\n soup = BeautifulSoup(r.text, \"lxml\")\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$MainContent$bDate', 'ctl00$MainContent$bKeyword', 'ctl00$MainContent$bSymbol',\n 'ctl00$MainContent$bToday', 'ctl00$MainContent$bType'\n ]\n data_change = {\n 'ctl00$RadioRegion2': 'RadioUS2', 'ctl00$CheckQuote2': 'on', 'ctl00$CheckNews2': 'on',\n 'ctl00$MainContent$cSymbol': 'on', 'ctl00$MainContent$dTodayRegion': 'С',\n 'ctl00$MainContent$dSymbolFeed': 'C', 'ctl00$MainContent$dType': '200',\n 'ctl00$MainContent$tKeywords': key_words, 'ctl00$MainContent$dKeywordFeed': 'usbull',\n 'ctl00$MainContent$dKeywordSort': sort_news, 'ctl00$MainContent$dKeywordStemming': 'Y',\n 'ctl00$MainContent$dKeywordType': keyword_type, 'ctl00$MainContent$dKeywordFuzzy': '0',\n 'ctl00$MainContent$dKeywordPhonic': 'N', 'ctl00$MainContent$bKeyword.x': '41',\n 'ctl00$MainContent$bKeyword.y': '10', 'ctl00$MainContent$dEx': '',\n 'ctl00$MainContent$dDateSort': 'timedesc', 'ctl00$MainContent$dDateFeed': 'C',\n 'ctl00$MainContent$tKeywordFrom': start_date, 'ctl00$MainContent$tKeywordTo': end_date\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n r = s.post('https://www.stockwatch.com/News/Search.aspx', data=data)\n soup = BeautifulSoup(r.text, \"lxml\")\n\n # Заполенение таблицы с новостями ------------------------------------------------------------------------------\n dict_df = fill_news_file(soup, dict_df)\n print('Первая страница получена успешно')\n\n # Итератор по страницам\n td = [i for i in soup.select('td[colspan]')]\n if len(td) > 0:\n td = td[0]\n pages_dict = {}\n for a in td.findAll('a'):\n pages_dict[a.text] = re.findall(\"\\'(.*?)\\'\", a['href'])[0]\n last_page = a.text\n\n for page, link in pages_dict.items():\n print(f'Получаем {page} страницу из {last_page}')\n\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$ImageButton1'\n ]\n data_change = {\n '__EVENTTARGET': link, 'ctl00$CheckNews2': 'on', 'ctl00$CheckQuote2': 'on',\n 'ctl00$RadioRegion2': 'RadioUS2'\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n r = s.post('https://www.stockwatch.com/News/Search.aspx', data=data)\n soup = BeautifulSoup(r.text, \"lxml\")\n dict_df = fill_news_file(soup, dict_df)\n\n print(f'{page} страница получена успешно')\n\n # Сохраним\n final_df = pd.DataFrame.from_dict(dict_df)\n final_df.to_csv(f'data\\SpecDiv_{end_date}.csv', index=False)\n\n\ndef create_session(base_url: str, headers: dict, cur_disc: str = cur_disc):\n with requests.Session() as s:\n # Логин --------------------------------------------------------------------------------------------------------\n s.headers['User-Agent'] = headers['User-Agent']\n r = s.get(base_url)\n soup = BeautifulSoup(r.text, \"lxml\")\n\n # Куки для логина\n AntiXsrfToken = r.headers['Set-Cookie'].split(';')[0]\n pref = r.headers['Set-Cookie'].split(';')[2].split(',')[1] # .replace(\"%7cN%7cN%7\", \"%7cN%7cY%7\")\n s.headers = headers\n s.headers['Content-Length'] = '5107' # r.headers['Content-Length']\n s.headers['Referer'] = base_url\n s.headers['Cookie'] = ';'.join([AntiXsrfToken, pref])\n\n # Data для логина\n names_for_pop = [\n 'ctl00$CheckChart2', 'ctl00$CheckCloses2', 'ctl00$CheckDepth2', 'ctl00$GoButton2',\n 'ctl00$MainContent$HpIndexesChart4$bIndexRemove', 'ctl00$MainContent$HpIndexesChart5$bIndexRemove'\n ]\n data_change = {\n 'ctl00$RadioRegion2': 'RadioUS2', 'ctl00$CheckQuote2': 'on', 'ctl00$CheckNews2': 'on',\n 'ctl00$PowerUserName': user_name, 'ctl00$PowerRememberMe': 'on', 'ctl00$PowerPassword': password,\n 'ctl00$Login.x': '40', 'ctl00$Login.y': '9', 'ctl00$MainContent$cActive$ListEx': 'T',\n 'ctl00$MainContent$cActive$RadioTop10': 'RadioGain'\n }\n data = make_data_for_request(soup, names_for_pop, data_change)\n\n # Получение ключа\n r = s.post(base_url, data=data, allow_redirects=False)\n key_xxx = r.headers['Set-Cookie'].split(';')[0]\n headers = {'User-Agent': headers['User-Agent'], 'Cookie': '; '.join([s.headers['Cookie'], key_xxx])}\n s.headers = headers\n print(\"Логин-ключ получен\")\n time.sleep(3)\n\n # Получение новостей по определённому слову\n work_days = [datetime.now()]\n for end_date in work_days:\n start_date = mcal.get_calendar('NYSE').schedule(\n start_date=end_date-timedelta(days=7),\n end_date=end_date\n )\n start_date = start_date.index[-2]\n news_finder(\n s, key_words, sort_news, keyword_type, start_date.strftime('%Y%m%d'), end_date.strftime('%Y%m%d')\n )\n filter_news(end_date, start_date)\n\n # Закрываем сессию\n s.close()\n\n\ndef filter_news(today: datet.date, yesterday: datet.date):\n # today = datetime.now()\n # yesterday = today - timedelta(days=1) if today.weekday() != 0 else today - timedelta(days=3)\n df = pd.read_csv(f\"data\\SpecDiv_{today.strftime('%Y%m%d')}.csv\", parse_dates=['date'])\n df_tiingo = get_tiingo()\n\n # Удалим неактуальные (если новость была вчера на открытии или вчера в течении дня)\n df = df[\n (df['date'].dt.strftime('%Y%m%d') == today.strftime('%Y%m%d')) |\n ((df['date'].dt.strftime('%Y%m%d') == yesterday.strftime('%Y%m%d')) & (df['time'].isin(['AMC', 'DAY'])))\n ]\n\n # Удалим ETF\n idx_drop = []\n df['assetType'] = None\n for idx, row in df.iterrows():\n asset_type = get_asset_type(df_tiingo, row['ticker'])\n if asset_type not in ['Stock', '-']:\n idx_drop.append(idx)\n df.loc[idx, 'assetType'] = asset_type\n df.drop(idx_drop, axis=0, inplace=True)\n\n # Удалим не проходящие по объёму. Добавим данные.\n fm.download_tickers(df['ticker'], reload=False, threads=10)\n dict_data = fm.get_tickers(df['ticker'])\n idx_drop = []\n for idx, row in df.iterrows():\n ticker = row['ticker']\n if ticker not in dict_data.keys():\n idx_drop.append(idx)\n continue\n\n cur_yesterday = yesterday.strftime('%Y-%m-%d')\n cur_df = dict_data[ticker][:cur_yesterday]\n if cur_yesterday not in cur_df.index:\n print(f\"{ticker, cur_yesterday} нет данных на дату\")\n idx_drop.append(idx)\n continue\n\n prenews_price = cur_df['close'].iloc[-1]\n avg_vol = cur_df['volume'].iloc[-20:].mean()\n if (50_000 > avg_vol) or (avg_vol > 3_000_000):\n idx_drop.append(idx)\n else:\n df.loc[idx, 'AvgVol'] = avg_vol\n df.loc[idx, 'PrenewsPrice'] = prenews_price\n df.drop(idx_drop, axis=0, inplace=True)\n df['divAmount'] = None\n df['divToPrice'] = None\n df['recordDate'] = None\n df['dayDiff'] = None\n\n # Если финальный файл уже существует, то добвим к тему недостающие данные\n path = f\"data\\SpecDiv_{today.strftime('%Y%m%d')}_final.csv\"\n if os.path.exists(path):\n old_df = pd.read_csv(path)\n new_df = pd.concat([old_df, df], ignore_index=True)\n new_df.drop_duplicates(subset=['ticker', 'headline'], keep=False, inplace=True)\n new_df.sort_values('date').to_csv(path, mode='a', header=False, index=False)\n else:\n df.drop_duplicates(subset=['ticker', 'headline'], keep='first', inplace=True)\n df.sort_values('date').to_csv(path, index=False)\n\n print(pd.read_csv(path))\n print(\"Рассчитай вручную, чтобы до дня ex-div date было менее 20 дней и чтобы див был более 2.5% от цены.\")\n\n\nif __name__ == \"__main__\":\n create_session(base_url, headers)\n\n while datetime.now().hour < 10:\n hour = datetime.now().hour\n min = datetime.now().minute\n if (hour in [4, 5, 6, 7, 8, 9] and min == 1) or (hour == 9 and min in [10, 15]):\n print(f\"Работаем. {datetime.now()}\")\n create_session(base_url, headers)\n time.sleep(30)\n\n time.sleep(60)\n","repo_name":"apokrif333/SpecialDividends","sub_path":"04. NewsFinder.py","file_name":"04. NewsFinder.py","file_ext":"py","file_size_in_byte":13227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"10111673602","text":"import tkinter as tk\nfrom tkinter import ttk\nimport os.path\n\n\nclass List_selection_rect(tk.Frame):\n def __init__(self, master: tk.Frame, type: str):\n \"\"\"\n Création d'une liste dynamique\n qui change ces valeurs en fonction du type\n :param master: Frame Parent\n :param type: type de fichier\n \"\"\"\n super().__init__(master)\n self.master = master\n self.grid(row=3, column=0)\n self.type = type\n self.parent_dir = os.path.join(os.path.realpath(__file__), os.pardir, os.pardir, os.pardir)\n\n def affichage(self) -> None:\n \"\"\"\n Affichage de toute la liste\n :return: None\n \"\"\"\n self.tree = ttk.Treeview(master=self.master)\n self.tree.heading('#0', text='Zone de données importantes', anchor=tk.W)\n\n self.update_tree()\n self.tree.grid(row=3, column=0, padx=10)\n\n def update_tree(self) -> None:\n \"\"\"\n Recharge la liste avec les lignes et les sous-lignes:\n -ligne 1\n -sousligne 1\n :return: None\n \"\"\"\n for selected_item in self.tree.get_children():\n self.tree.delete(selected_item)\n dict_modele = self.get_tree_modele()\n nb_ligne = len(dict_modele)\n for i in range(0, nb_ligne):\n nom_ligne = f\"ligne {i}\"\n if nom_ligne in dict_modele:\n self.tree.insert('', tk.END, text=dict_modele[nom_ligne], iid=dict_modele[nom_ligne], open=False)\n nom_children = f\"subligne {i}\"\n if nom_children in dict_modele:\n tabchildren = dict_modele[nom_children]\n for j in range(0, len(tabchildren)):\n iid = dict_modele[nom_ligne] + \".\" + tabchildren[j]\n self.tree.insert('', tk.END, text=tabchildren[j], iid=iid, open=False)\n self.tree.move(iid, dict_modele[nom_ligne], j)\n nom_souschildren = f\"subsubligne {i}\"\n if nom_souschildren in dict_modele:\n tabsouschildren = dict_modele[nom_souschildren]\n for k in range(0, len(tabsouschildren)):\n idd_parent = dict_modele[nom_ligne] + \".\" + tabchildren[j]\n iid = dict_modele[nom_ligne] + \".\" + tabchildren[j] + \".\" + tabsouschildren[k]\n self.tree.insert('', tk.END, text=tabsouschildren[k], iid=iid, open=False)\n self.tree.move(iid, idd_parent, k)\n\n def get_tree_modele(self) -> None:\n \"\"\"\n Récupérer les paramètres dans le fichier 'Type_tree'\n :return: None\n \"\"\"\n type_path = os.path.join(self.parent_dir, \"Config_interface\", 'Type_tree')\n fichier = open(type_path, \"r\")\n tree_type = fichier.readlines()\n fichier.close()\n modele_trouve = False\n i = 0\n for ligne in tree_type:\n\n if ligne.find(self.type) != -1:\n modele_trouve = True\n if (modele_trouve == True and ligne.find(\"{\") != -1):\n debut = i\n if (modele_trouve == True and ligne.find(\"}\") != -1):\n fin = i\n break\n i += 1\n dict = \"\"\n for x in range(debut, fin + 1):\n dict += tree_type[x]\n dict = eval(dict.replace(\"'\", \"\\\"\"))\n return dict\n\n def set_type(self, type: str) -> None:\n \"\"\"\n :param type: Type du fichier\n :return: None\n \"\"\"\n self.type = type\n\n def get_selection_id(self) -> str:\n \"\"\"\n Permets de récupérer l'identifiant de la ligne sélectionner\n :return: id correspondant à la selection de l'utilisateur\n \"\"\"\n if len(self.tree.selection()) != 0:\n selected_item = self.tree.selection()[0]\n if self.tree.parent(selected_item) == \"\":\n parent_id = selected_item\n else:\n parent_id = self.tree.parent(selected_item)\n if parent_id not in [\"personne\", \"adresse\", \"entreprise\"]:\n id = selected_item + \".\" + \"flottant\"\n return id\n elif parent_id != \"\":\n id = selected_item\n return id\n","repo_name":"itsax404/OCRganiz","sub_path":"Interface/Classe/Tree_selection.py","file_name":"Tree_selection.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"73873142874","text":"import os\nfrom datetime import datetime\nfrom gettext import gettext as _\nfrom typing import Optional\n\nimport pycurl\n\nfrom bottles.backend.logger import Logger\nfrom bottles.backend.models.result import Result\nfrom bottles.backend.state import SignalManager, Signals, Notification\n\nlogging = Logger()\n\n\nclass ConnectionUtils:\n \"\"\"\n This class is used to check the connection, pinging the official\n Bottle's website. If the connection is offline, the user will be\n notified and False will be returned, otherwise True.\n \"\"\"\n _status: Optional[bool] = None\n last_check = None\n\n def __init__(self, force_offline=False, **kwargs):\n super().__init__(**kwargs)\n self.force_offline = force_offline\n self.do_check_connection = True\n self.aborted_connections = 0\n SignalManager.connect(Signals.ForceStopNetworking, self.stop_check)\n\n @property\n def status(self) -> Optional[bool]:\n return self._status\n\n @status.setter\n def status(self, value: bool):\n if value is None:\n logging.error(\"Cannot set network status to None\")\n return\n self._status = value\n SignalManager.send(Signals.NetworkStatusChanged, Result(status=self.status))\n\n def __curl_progress(self, _download_t, _download_d, _upload_t, _upload_d):\n if self.do_check_connection:\n return pycurl.E_OK\n else:\n self.aborted_connections+=1\n return pycurl.E_ABORTED_BY_CALLBACK\n\n def stop_check(self, res: Result):\n if res.status:\n self.do_check_connection = False\n\n def check_connection(self, show_notification=False) -> bool:\n \"\"\"check network status, send result through signal NetworkReady and return\"\"\"\n if self.force_offline or \"FORCE_OFFLINE\" in os.environ:\n logging.info(\"Forcing offline mode\")\n self.status = False\n return False\n\n try:\n c = pycurl.Curl()\n c.setopt(c.URL, 'https://ping.usebottles.com')\n c.setopt(c.FOLLOWLOCATION, True)\n c.setopt(c.NOBODY, True)\n c.setopt(c.NOPROGRESS, False)\n c.setopt(c.XFERINFOFUNCTION, self.__curl_progress) \n c.perform()\n\n if c.getinfo(pycurl.HTTP_CODE) != 200:\n raise Exception(\"Connection status: offline …\")\n\n self.last_check = datetime.now()\n self.status = True\n except Exception:\n logging.warning(\"Connection status: offline …\")\n if show_notification:\n SignalManager.send(Signals.GNotification, Result(True, Notification(\n title=\"Bottles\",\n text=_(\"You are offline, unable to download.\"),\n image=\"network-wireless-disabled-symbolic\"\n )))\n self.last_check = datetime.now()\n self.status = False\n finally:\n self.do_check_connection = True\n return self.status\n","repo_name":"bottlesdevs/Bottles","sub_path":"bottles/backend/utils/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":5464,"dataset":"github-code","pt":"50"}
+{"seq_id":"29039777904","text":"import gi\ngi.require_versions({\"Gtk\": \"3.0\", \"AppIndicator3\": \"0.1\"})\n\nfrom configuration import Configuration\nfrom desktop_entry import DesktopEntry\nfrom key_binder import KeyBinder\nfrom ui.main_window import MainWindow\n\nfrom gi.repository import Gtk, AppIndicator3\n\n\nclass TrayIcon:\n\n def __init__(self, configuration: Configuration, key_binder: KeyBinder):\n self._configuration = configuration\n self._key_binder = key_binder\n\n def show(self):\n self._indicator = AppIndicator3.Indicator.new('MonKey', str(DesktopEntry.ICON_PATH),\n AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)\n self._indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)\n self._indicator.set_menu(self._build_app_indicator_menu())\n\n def _build_app_indicator_menu(self):\n menu = Gtk.Menu()\n configuration_item = Gtk.MenuItem(label='Configure hotkeys')\n configuration_item.connect('activate', self._open_main_window)\n menu.append(configuration_item)\n menu.append(Gtk.SeparatorMenuItem())\n quit_item = Gtk.MenuItem(label='Quit')\n quit_item.connect('activate', self._quit_app)\n menu.append(quit_item)\n menu.show_all()\n return menu\n\n def _open_main_window(self, _):\n MainWindow(self._configuration, self._key_binder).show()\n\n def _quit_app(self, _):\n Gtk.main_quit()\n","repo_name":"adi-benz/mon-key","sub_path":"ui/tray_icon.py","file_name":"tray_icon.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"71515203354","text":"from selenium import webdriver\n\ndriver=webdriver.Firefox()\ndriver.get(\"file:///C:/Users/ADMIN/PycharmProjects/7_Class_16_2_2018/HTML/Table.html\")\ndriver.maximize_window()\ndriver.implicitly_wait(30)\n\nele=driver.find_elements_by_xpath(\"//*[@id='Employe']/thead/tr/th\")\nprint(len(ele))\n#first_part=\"//[@id='Employe']/thead/tr/th[\"\n#econd_part=\"]\"","repo_name":"dongeorge77/Selenium-Automation-3_Web_Table_Handle","sub_path":"5_WebTableHandleHTML.py","file_name":"5_WebTableHandleHTML.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"7336604963","text":"\n\n\"\"\"\nModule to preprocess the data and filter unuseful cols or reformat the data in\ncolumn-wise way.\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport datetime\nfrom itertools import product\n\n\n############################## GLOBAL VARIABLES ###############################\n###############################################################################\ntypes = ['Act', 'ActC', 'Pasfijo', 'Pasliq', 'Trab', 'Va', 'Vtas']\nyears = [2006, 2007, 2008, 2009, 2010, 2011, 2012]\nyears_key = ['06', '07', '08', '09', '10', '11', '12']\n## Column info transformation\nmain_cols = ['Nom', 'nif', 'cnae', 'cp', 'localidad', 'ES-X', 'ES-Y',\n 'apertura', 'cierre']\nmapping_manu = {'localitat': 'localidad', 'ESX': 'ES-X', 'ESY': 'ES-Y',\n 'esx': 'es-x', 'esy': 'es-y'}\ntypes_m = ['Act', 'ActC', 'Pasfijo', 'Pasliq', 'Treb', 'Va', 'Vdes']\n# Variables to store\nvars_atemporal = ['nom', 'nif', 'cp', 'ca', 'es-x', 'es-y', 'sector', 'cnae',\n 'apertura', 'cierre']\n#vars_temporal = product(year_key, types)\nvars_atemporal2 = ['nif', 'cp', 'ca', 'es-x', 'es-y', 'sector', 'cnae',\n 'apertura', 'cierre']\n\n\n###############################################################################\n############################### JOINING EMPRESAS ##############################\n###############################################################################\ndef join_empresas_atemporal(servicios, manufactures, ca_name):\n \"\"\"\"\"\"\n manu_ca = manufactures[manufactures['ca'].apply(lambda x: x == ca_name)]\n empresas =\\\n pd.concat([servicios[vars_atemporal], manu_ca[vars_atemporal]], axis=0)\n return empresas\n\n\ndef join_and_store_empresas_atemporal(empresas, pathdata):\n namefile = 'empresas'\n pathfold = os.path.join(pathdata, 'atemporal')\n pathfile = os.path.join(pathfold, namefile)\n empresas = pd.concat(empresas, axis=0)\n ## Reindices\n empresas.indices = range(len(empresas))\n ## Cp correct\n f_cp = lambda x: (5-len(str(int(x))))*'0'+str(int(x))\n empresas.loc[:, 'cp'] = empresas['cp'].apply(f_cp)\n# ##### DEBUG: temporal\n# try:\n# empresas.loc[:, 'cp'] = empresas['cp'].apply(f_cp)\n# except:\n# for i in range(len(empresas)):\n# f_cp(empresas.loc[i, 'cp'])\n# ################################\n ## Apertura y cierre\n empresas.loc[:, 'apertura'] =\\\n empresas['apertura'].apply(lambda x: x.strftime('%F'))\n empresas.loc[:, 'cierre'] =\\\n empresas['cierre'].apply(lambda x: x.strftime('%F'))\n ## Store\n empresas[vars_atemporal2].to_csv(pathfile, sep=';')\n empresas[['nom', 'nif']].to_excel(os.path.join(pathfold, 'empresas.xlsx'))\n\n\ndef store_empresas_atemporal_years(empresas, ca_name, pathdata):\n \"\"\"\"\"\"\n pathfold_locs = os.path.join(pathdata, 'locations')\n pathfold_sector = os.path.join(pathdata, 'sector')\n\n apertura = empresas['apertura'].apply(lambda x: x.strftime('%F'))\n apertura = apertura.apply(lambda x: int(x[:4])).as_matrix()\n cierre = empresas['cierre'].apply(lambda x: x.strftime('%F'))\n cierre = cierre.apply(lambda x: int(x[:4])).as_matrix()\n\n for i in range(len(years)):\n logi = np.logical_and(years[i] <= cierre, years[i] >= apertura)\n locs_year = empresas[['nif', 'es-x', 'es-y']][logi]\n sector_year = empresas[['nif', 'sector', 'cnae']][logi]\n locs_year.indices = range(len(locs_year))\n sector_year.indices = range(len(sector_year))\n\n namefile = ca_name+'_'+years_key[i]+'.csv'\n locs_year.to_csv(os.path.join(pathfold_locs, namefile), sep=';')\n sector_year.to_csv(os.path.join(pathfold_sector, namefile), sep=';')\n\n\ndef join_and_store_empresas_temporal(servicios, manufactures, ca_name,\n pathdata):\n logi = manufactures['ca'].apply(lambda x: x == ca_name).as_matrix()\n manu_ca = manufactures[logi]\n for year_key in years_key:\n vars_temporal_year = [year_key+type_.lower() for type_ in types]\n servicios_year = servicios[['nif']+vars_temporal_year]\n manu_ca_year = manu_ca[['nif']+vars_temporal_year]\n servicios_year, manu_ca_year, collapsed =\\\n filter_unique_nif(servicios_year, manu_ca_year)\n empresas = pd.concat([servicios_year, manu_ca_year, collapsed], axis=0)\n namefile = ca_name+'_'+year_key+'.csv'\n pathfile = os.path.join(os.path.join(pathdata, 'temporal'), namefile)\n logi = check_year_open(empresas, year_key)\n empresas.columns = ['nif'] + types\n empresas[logi].to_csv(pathfile, sep=';')\n\n\n###############################################################################\n############################### DATES FORMATTING ##############################\n###############################################################################\ndef compute_apertura_cierre(df):\n apertura = obtain_open_aperture_date(df)\n cierre = obtain_close_date(df)\n if 'apertura' in df.columns:\n del df['apertura']\n if 'cierre' in df.columns:\n del df['cierre']\n df.index = range(len(df))\n df = pd.concat([df, pd.DataFrame({'apertura': apertura}),\n pd.DataFrame({'cierre': cierre})], axis=1)\n# df.loc[:, 'apertura'] = apertura\n# df.loc[:, 'cierre'] = cierre\n return df\n\n\ndef obtain_open_aperture_date(df):\n \"Obtain the date of aperture of the each company.\"\n\n m_y = len(years)\n ## Obtain bool arrays\n bool_m = np.zeros((df.shape[0], m_y)).astype(bool)\n for i in range(m_y):\n bool_m[:, i] = check_year_open(df, years[i])\n\n ## Obtain date\n dates = np.zeros(bool_m.shape[0])\n for i in range(m_y):\n logi = bool_m[:, i]\n dates[np.logical_and(dates == 0, logi)] = i+1\n ## Format dates\n dates = dates + years[0]-1\n dates = dates.astype(int)\n aux = np.zeros(dates.shape).astype(datetime.date)\n for i in range(aux.shape[0]):\n aux[i] = datetime.date(int(dates[i]), 1, 1)\n dates = aux\n return dates\n\n\ndef obtain_close_date(df):\n \"Obtain close date\"\n m_y = len(years)\n ## Obtain bool arrays\n bool_m = np.zeros((df.shape[0], m_y)).astype(bool)\n for i in range(m_y):\n bool_m[:, i] = check_year_open(df, years[i])\n\n ## Obtain date\n dates = np.zeros(bool_m.shape[0])\n for i in range(m_y):\n logi = bool_m[:, i]\n dates[logi] = i\n\n ## Format dates\n dates = dates + years[0]\n dates = dates.astype(int)\n aux = np.zeros(dates.shape).astype(datetime.date)\n for i in range(aux.shape[0]):\n aux[i] = datetime.date(int(dates[i]), 12, 31)\n dates = aux\n return dates\n\n\ndef check_year_open(df, year):\n \"\"\"Function to check if there is any variables not none to check if there\n was opened the selected year.\n \"\"\"\n if type(year) == int:\n i = years.index(year)\n else:\n assert(year in years_key)\n i = years_key.index(year)\n year_key = [years_key[i]]\n comb = product(year_key, types)\n comb = [''.join(e).lower() for e in comb]\n\n logis = np.logical_not(df[comb].isnull().as_matrix())\n m = logis.shape[1]\n\n logi = np.zeros(logis.shape[0]).astype(bool)\n for i in range(m):\n logi = np.logical_or(logi, logis[:, i])\n return logi\n\n\n###############################################################################\n############################# CREATE EXTRA COLUMNS ############################\n###############################################################################\ndef create_CA_column(empresas, ca_cp_dict):\n def f(x):\n try:\n return ca_cp_dict[(5-len(str(int(x))))*'0'+str(int(x))]\n except:\n return ca_cp_dict[((2-len(str(int(x))))*'0'+str(int(x)))[:2]]\n# f = lambda x: ca_cp_dict[(5-len(str(int(x))))*'0'+str(int(x))]\n empresas['ca'] = empresas['cp'].apply(f)\n return empresas\n\n\ndef create_sector_columns(empresas, sector):\n sector = sector.lower().strip()\n assert(sector in ['manufactures', 'servicios'])\n empresas.loc[:, 'sector'] = sector\n return empresas\n\n\n###############################################################################\n############################ COLUMNS STANDARIZATION ###########################\n###############################################################################\ndef clean_colnames_manu(cols):\n \"Clean names of the manufactures.\"\n # Format properly\n cols = [e.strip() for e in cols]\n # Replace the Financial variables\n cols_f = ['y'+''.join(e) for e in product(years_key, types_m)]\n cols_f += ['y'+''.join(e).strip().lower()\n for e in product(years_key, types_m)]\n cols_f_g = [''.join(e).lower().strip() for e in product(years_key, types)]\n replace_f = dict(zip(cols_f, 2*cols_f_g))\n cols = replace_colnames(cols, replace_f)\n # Replace the main\n cols = replace_colnames(cols, mapping_manu)\n return cols\n\n\ndef replace_colnames(cols, replaces):\n \"Replace the names keeping the order in the list of colnames.\"\n for c in cols:\n if c in replaces.keys():\n cols[cols.index(c)] = replaces[c]\n return cols\n\n\n###############################################################################\n#################################### OTHERS ###################################\n###############################################################################\ndef filter_unique_nif(servicios, manufactures):\n nif_servicios, nif_manu = list(servicios['nif']), list(manufactures['nif'])\n assert(len(nif_servicios) == len(set(nif_servicios)))\n assert(len(nif_manu) == len(set(nif_manu)))\n cols_serv = [c for c in servicios.columns if c != 'nif']\n cols_manu = [c for c in manufactures.columns if c != 'nif']\n ncols = len(servicios.columns)\n logi_serv, logi_manu, new_rows = [], [], []\n for i in range(len(nif_servicios)):\n if nif_servicios[i] in nif_manu:\n j = nif_manu.index(nif_servicios[i])\n# print i, j, cols_serv, cols_manu\n# print servicios.iloc[i, range(1, ncols)].as_matrix(), manufactures.iloc[j, range(1, ncols)].as_matrix()\n logi_serv.append(i)\n logi_manu.append(j)\n fin = collapse_finance(servicios.iloc[i, range(1, ncols)],\n manufactures.iloc[j, range(1, ncols)])\n new_rows.append([nif_servicios[i]]+list(fin))\n\n new_rows = pd.DataFrame(new_rows, columns=servicios.columns)\n logi_serv = [i not in logi_serv for i in range(len(servicios))]\n logi_manu = [i not in logi_manu for i in range(len(manufactures))]\n servicios = servicios[logi_serv]\n manufactures = manufactures[logi_manu]\n return servicios, manufactures, new_rows\n\n\ndef collapse_finance(servicios, manufactures):\n f_corr = lambda x: np.logical_not(np.logical_or(np.isnan(x), x == 0))\n servicios = np.array(servicios).astype(float)\n manufactures = np.array(manufactures).astype(float)\n# print servicios, manufactures, type(servicios)\n corr_serv = f_corr(servicios)\n collapsed = []\n for i in range(len(servicios)):\n if corr_serv[i]:\n collapsed.append(servicios[i])\n else:\n collapsed.append(manufactures[i])\n collapsed = np.array(collapsed)\n return collapsed\n\n\ndef collapse_pfeatures_nif(pfeatures):\n if len(pfeatures.shape) == 1:\n return pfeatures\n f_corr = lambda x: np.logical_not(np.logical_or(np.isnan(x), x == 0))\n correctness = f_corr(pfeatures)\n new_pfeatures = []\n for col in range(pfeatures.shape[1]):\n if correctness[:, col].sum():\n i = np.where(correctness[:, col])[0][0]\n else:\n i = 0\n new_pfeatures.append(pfeatures[i, col])\n new_pfeatures = np.array(new_pfeatures)\n return new_pfeatures\n\n\n\ndef filtercols_empresas(empresas, filtercolsinfo):\n \"TODO:\"\n return empresas\n\n\ndef categorize_cols(df):\n df = cp2str(df)\n df = cnae2str(df)\n return df\n\n\ndef generate_replace(type_vals):\n \"Generate the replace for use indices and save memory.\"\n repl = {}\n for v in type_vals.keys():\n repl[v] = dict(zip(type_vals[v], range(len(type_vals[v]))))\n return repl\n\n\ndef transform_cnae_col(cnae_col, lvl):\n \"\"\"\"\"\"\n lvl_n = len(cnae_col[1])\n if lvl >= lvl_n:\n return cnae_col\n else:\n return cnae_col.apply(lambda x: x[:lvl])\n\n\n############################# Particular columns ##############################\n###############################################################################\ndef cp2str(df):\n \"\"\"Retransform cp to string.\"\"\"\n def cp2str_ind(x):\n try:\n x = str(int(x))\n x = (5-len(x))*'0'+x\n except:\n pass\n return x\n if 'cp' in df.columns:\n df.loc[:, 'cp'] = df['cp'].apply(cp2str_ind)\n return df\n\n\ndef cnae2str(df):\n \"\"\"Transforming cnae code to string.\"\"\"\n def cnae2str_ind(x):\n try:\n x = str(int(x))\n except:\n pass\n return x\n if 'cnae' in df.columns:\n df.loc[:, 'cnae'] = df['cnae'].apply(cnae2str_ind)\n return df\n\n\ndef to_float(df):\n ## Columns which has to be numbers\n cols = ['06Act', '07Act', '08Act', '09Act', '10Act', '11Act', '12Act',\n '13Act', '06ActC', '07ActC', '08ActC', '09ActC', '10ActC',\n '11ActC', '12ActC', '13ActC', '06Pasfijo', '07Pasfijo',\n '08Pasfijo', '09Pasfijo', '10Pasfijo', '11Pasfijo', '12Pasfijo',\n '13Pasfijo', '06Pasliq', '07Pasliq', '08Pasliq', '09Pasliq',\n '10Pasliq', '11Pasliq', '12Pasliq', '13Pasliq', '06Va', '07Va',\n '08Va', '09Va', '10Va', '11Va', '12Va', '13Va', '06Vtas', '07Vtas',\n '08Vtas', '09Vtas', '10Vtas', '11Vtas', '12Vtas', '13Vtas']\n ## Transformation\n columns = df.columns\n for col in columns:\n if col in cols:\n df.loc[:, col] = df[col]\n return df\n\n\ndef to_int(df):\n cols = ['06Trab', '07Trab', '08Trab', '09Trab', '10Trab', '11Trab',\n '12Trab', '13Trab']\n ## Transformation\n columns = df.columns\n for col in columns:\n if col in cols:\n df.loc[:, col] = df[col].astype(int)\n return df\n","repo_name":"tgquintela/FirmsLocations","sub_path":"FirmsLocations/Preprocess/preprocess_cols.py","file_name":"preprocess_cols.py","file_ext":"py","file_size_in_byte":14106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"12007241319","text":"from matplotlib import pyplot as plt\nimport pickle\n\nwith open(\"decoded_imgs.pkl\", 'rb') as f:\n decoded_imgs = pickle.load(f)\nwith open(\"x_test.pkl\", 'rb') as f:\n x_test = pickle.load(f)\n\nn = 10\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n # display original\n ax = plt.subplot(2, n, i+1)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\n #plt.show()\n #ax.get_xaxis().set_visible(False)\n #ax.get_yaxis().set_visible(False)\n\n\n # display reconstruction\n ax = plt.subplot(2, n, i + n+1)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n #ax.get_xaxis().set_visible(False)\n #ax.get_yaxis().set_visible(False)\n #plt.show()\n\nplt.show()\n\n\"\"\"\n# plotting images as their encodings:\nn = 10\nplt.figure(figsize=(20, 8))\nfor i in range(n):\n ax = plt.subplot(1, n, i)\n plt.imshow(encoded_imgs[i].reshape(4, 4 * 8).T)\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n\"\"\"","repo_name":"noahthurston/Hierarchical_MC","sub_path":"src/practice/plot_decoded_imgs.py","file_name":"plot_decoded_imgs.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"18162020383","text":"import sys\nfrom argparse import ArgumentParser\nfrom os import path\n\nfrom indexer import Indexer\nfrom indexer_bm25 import IndexerBM25\nfrom indexer_lnc_ltc import IndexerLncLtc\nfrom query import Query\nfrom tokenizer import Tokenizer\n\n\nclass Main:\n data_path: str\n stopwords_path: str\n minimum_word_size: int\n stemmer_enabled: bool\n use_positions: bool\n parser: ArgumentParser\n tokenizer: Tokenizer\n indexer: Indexer\n\n def __init__(self):\n\n # Main Mode\n self.mode = ''\n\n # Indexer mode\n self.index_type = ''\n self.data_path = ''\n self.stopwords_path = 'content/stopwords.txt'\n self.minimum_word_size = 3\n self.stemmer_enabled = True\n self.disable_positions = False\n self.max_post = 1000000\n\n # searcher mode\n self.data = ''\n self.search_type = ''\n self.loop = False\n self.query_file = ''\n self.dump_results_file = False\n self.cmd_results = False\n self.disable_boost = False\n self.span_size = 4\n\n self.parser = ArgumentParser()\n self.tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n self.indexer = Indexer(tokenizer=self.tokenizer,\n max_postings_per_temp_block=self.max_post,\n use_positions= not self.disable_positions)\n\n def parse_args(self):\n parser = ArgumentParser()\n # Set the mode\n parser.add_argument('--mode', help='Set the main mode', required=True,\n type=str, metavar='indexer/searcher')\n\n # IF IS INDEXER MODE\n # set method\n parser.add_argument('--method', help='Set the method',\n type=str, metavar='raw/lnc.ltc/bm25')\n # path to new data file\n parser.add_argument('--data_path', help='Set the path to the data',\n type=str, metavar='(path to data file (.gz))')\n # do not use stopwords list\n parser.add_argument('--nostopwords', help='Disable stop words',\n action='store_false')\n # path to new stopwords\n parser.add_argument('--stopwords',\n help='Set the path to stop words List',\n type=str, metavar='(path to stopwords list)')\n # minimum word size\n parser.add_argument('--word_size',\n help='Set the maximum for the word size filter',\n type=int, metavar='(integer number)')\n # no minimum word size\n parser.add_argument('--no_word_size', help='Disable word size filter',\n action='store_false')\n # do not use stemmer\n parser.add_argument('--no_stemmer', help='Disable stemmer',\n action='store_false')\n # do not use positions\n parser.add_argument('--disable_positions',\n help='Disable positions indexing',\n action='store_true')\n # maximum postings per block for the SPIMI\n parser.add_argument('--max_post',\n help='Set the maximum postings per block',\n type=int)\n\n # IF IS QUERY MODE\n # set folder name\n parser.add_argument('--data', help=\"Folder that contains the index files for query mode\",\n type=str)\n # set the search mode\n parser.add_argument('--search_type', help=\"Choose the search mode, 'file (file-path)' to use a file with a list of queries as input, 'loop' to insert queries in a loop through the terminal (empty query to end loop) or 'evaluation (file-path)' to use a file with a list of relevant queries as input\",\n nargs='+', metavar='file (file-path) / loop / evaluation (file_path)')\n\n parser.add_argument('--dump_file',\n help='Enable to generate file with results',\n action='store_true')\n\n parser.add_argument('--cmd_results',\n help='Enable to show the results on terminal',\n action='store_true')\n \n parser.add_argument('--disable_boost',\n help='Disable boost query',\n action='store_true')\n\n parser.add_argument('--span_size',\n help='Set span size to booster',\n type=int, metavar='(integer number)')\n\n # Set the query file\n #parser.add_argument('--query_file', help='Choose the path to search', type=str, metavar='(txt file)')\n\n return parser\n\n def check_arguments(self, parser, args):\n\n if args.mode == 'indexer':\n # indexer\n self.mode = args.mode\n # method\n if args.method:\n if args.method == 'bm25' or args.method == 'lnc.ltc' or args.method == 'raw':\n self.index_type = args.method\n else:\n parser.error(\n '--method requires 3 options (raw / lnc.ltc / bm25).')\n sys.exit()\n else:\n parser.error('Indexer mode requires --method and --data_path.')\n sys.exit()\n\n # data_path\n if args.data_path:\n self.data_path = args.data_path\n if not path.exists(self.data_path) or not self.data_path.endswith('.gz'):\n print(\n 'File does not exist or does not have the correct extension! ')\n print(parser.parse_args(['-h']))\n sys.exit()\n else:\n parser.error('Indexer mode requires --method and --data_path.')\n sys.exit()\n\n # if stopwords are disabled but a stopwords path is still defined by the user\n if (not args.nostopwords) and (args.stopwords != None):\n print(parser.parse_args(['-h']))\n sys.exit()\n\n if not args.nostopwords:\n self.stopwords_path = ''\n\n if args.stopwords:\n self.stopwords_path = args.stopwords\n\n # if word size is disabled but a size is still defined by the user\n if (not args.no_word_size) and (args.word_size != None):\n print(parser.parse_args(['-h']))\n sys.exit()\n\n if args.word_size:\n self.minimum_word_size = args.word_size\n\n if not args.no_word_size:\n self.minimum_word_size = 0\n\n if not args.no_stemmer:\n self.stemmer_enabled = False\n\n #disable positions\n self.disable_positions = args.disable_positions\n\n if args.max_post:\n self.max_post = args.max_post\n\n elif args.mode == 'searcher':\n # searcher\n self.mode = 'searcher'\n\n # data_path\n if args.data:\n self.data = args.data\n if not path.exists(self.data):\n print('Folder does not exist!')\n sys.exit()\n else:\n parser.error('Search mode requires --data and --search_type.')\n sys.exit()\n\n #disable boost\n self.disable_boost = args.disable_boost\n\n #span size\n if args.span_size:\n self.span_size = args.span_size\n\n # search_type\n if args.search_type:\n if args.search_type[0] == 'loop':\n self.loop = True\n elif args.search_type[0] == 'file':\n if not args.search_type[1]:\n parser.error(\n 'Type of search by file required the file path (txt)')\n sys.exit()\n self.query_file = args.search_type[1]\n if not path.exists(self.query_file):\n print('Query file does not exist!')\n sys.exit()\n elif args.search_type[0] == 'evaluation':\n self.evaluation = True\n if not args.search_type[1]:\n parser.error(\n 'Type of search \"evaluation\" required the file path (txt)')\n sys.exit()\n self.query_file = args.search_type[1]\n if not path.exists(self.query_file):\n print('Queries Relevant file does not exist!')\n sys.exit()\n else:\n parser.error(\n 'Search type requires one of three options: file / loop / evaluation.')\n sys.exit()\n else:\n parser.error(\n 'Search type requires one of three options: file / loop / evaluation.')\n sys.exit()\n\n if not args.dump_file and not args.cmd_results:\n parser.error(\n 'Search type requires at least one of two options: --dump_file / --cmd_results')\n sys.exit()\n\n self.dump_results_file = args.dump_file\n self.cmd_results = args.cmd_results\n else:\n print(parser.parse_args(['-h']))\n\n def read_query_file(self):\n\n with open(self.query_file, 'r') as file:\n lines = file.readlines()\n return lines\n\n def main(self):\n\n # create and check all arguments\n parser = self.parse_args()\n args = parser.parse_args()\n self.check_arguments(parser, args)\n\n if self.mode == 'indexer':\n if self.index_type == 'bm25':\n tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n indexer = IndexerBM25(\n tokenizer, use_positions= not self.disable_positions)\n indexer.index_data_source(self.data_path)\n statistics = indexer.get_statistics()\n for statistic in statistics:\n print(f'{statistic}: {statistics[statistic]}')\n elif self.index_type == 'lnc.ltc':\n tokenizer = Tokenizer(stopwords_path=self.stopwords_path,\n stemmer_enabled=self.stemmer_enabled,\n size_filter=self.minimum_word_size)\n indexer = IndexerLncLtc(\n tokenizer, use_positions= not self.disable_positions)\n indexer.index_data_source(self.data_path)\n statistics = indexer.get_statistics()\n for statistic in statistics:\n print(f'{statistic}: {statistics[statistic]}')\n\n elif self.mode == 'searcher':\n query = Query(\n data_path=self.data, dump_results_file=self.dump_results_file, cmd_results=self.cmd_results, \n positional_boost_enabled = not self.disable_boost, span_size = self.span_size)\n if self.loop:\n print('Words to search:')\n to_search = input()\n while (to_search != ''):\n #query = Query(data_path = self.data)\n query_result, total_time = query.process_query(to_search)\n if self.cmd_results:\n print()\n self.show_results(to_search, query_result)\n print('Time used: {:0.3f}s \\n'.format(total_time))\n\n print('Words to search:')\n to_search = input()\n elif self.evaluation:\n evaluation = query.evaluate_system(self.query_file)\n if self.cmd_results:\n query.show_evaluation_results(evaluation)\n if self.dump_results_file:\n query.dump_evaluation_result(evaluation)\n else:\n lines = self.read_query_file()\n for line in lines:\n query_result, total_time = query.process_query(line)\n if self.cmd_results:\n print()\n self.show_results(line.replace(\"\\n\", \"\"), query_result)\n print('Time used: {:0.3f}s \\n'.format(total_time))\n\n\n def show_results(self, query, results):\n i = 0\n print('Q: {}'.format(query))\n if len(results) == 0:\n print('Nothing found!')\n else:\n for result in results:\n if i < 10:\n res = tuple(result)\n print(res[0] + \" -> \" + res[1])\n i += 1\n print()\n\n\nif __name__ == '__main__':\n\n Main().main()\n","repo_name":"joaopedropereiraPP/IR-Project1","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"40864786477","text":"import json\n\nfrom sqlalchemy import insert, update\nfrom sqlalchemy.exc import IntegrityError\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom src.address_schema import Address\nfrom src.database_utils.base_query import BaseQuery\nfrom src.university_module.database.university.university_models import UniversityModels\n\n\nclass UniversityQuery(BaseQuery):\n _models: UniversityModels = UniversityModels()\n\n _schema_create_class: type = _models.create_class\n _schema_update_class: type = _models.update_class\n _schema_read_class: type = _models.read_class\n _model: type = _models.database_table\n\n async def create(\n self, model_create: _schema_create_class, session: AsyncSession\n ) -> IntegrityError | None:\n try:\n model_create.fix_time()\n await session.execute(insert(self._model).values(**model_create.dict()))\n await session.commit()\n except IntegrityError as e:\n return e\n\n def _convert_model_to_schema(self, model: _model) -> _schema_read_class | None:\n if type(model[0].address) is str:\n address = Address(**json.loads(model[0].address))\n else:\n address = model[0].address\n schema = self._schema_read_class(\n id=model[0].id,\n name=model[0].name,\n url=model[0].url,\n phone=model[0].phone,\n email=model[0].email,\n address=address,\n description=model[0].description,\n reg_date=model[0].reg_date,\n image=model[0].image,\n )\n return schema\n\n async def update(\n self, model_update: _schema_update_class, session: AsyncSession\n ) -> IntegrityError | None:\n try:\n model_update.fix_time()\n await session.execute(\n update(self._model)\n .values(**model_update.dict())\n .where(self._model.id == model_update.id)\n )\n await session.commit()\n except IntegrityError as e:\n return e\n","repo_name":"ONEPANTSU/EducationTourBackend","sub_path":"src/university_module/database/university/university_query.py","file_name":"university_query.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"32404698822","text":"import sys\n\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n\ndef avg_of_5_elements_brute_force(arr, k=5):\n result = []\n for i in range(len(arr) - k + 1):\n sum = 0.0\n for j in range(i, i + k):\n sum += arr[j]\n result.append(sum / k)\n return result\n\n\ndef sum_of_avg_5_elements(arr, k=5):\n window_sum = 0\n window_start = 0\n result = []\n\n for window_end in range(len(arr)):\n window_sum += arr[window_end]\n\n if window_end >= k - 1:\n result.append(window_sum / k)\n window_sum -= arr[window_start]\n window_start += 1\n return result\n\n\nresult = avg_of_5_elements_brute_force(arr, 5)\nprint(result)\nresult = sum_of_avg_5_elements(arr, 4)\nprint(result)\n\n\ndef max_sum_in_window(arr, k=3):\n max_sum = 0\n running_sum = 0\n window_start = 0\n max_sum_array = []\n\n for window_end in range(len(arr)):\n running_sum += arr[window_end]\n\n if window_end >= k - 1:\n max_sum = max(max_sum, running_sum)\n max_sum_array.append(max_sum)\n running_sum -= arr[window_start]\n window_start += 1\n return max_sum_array\n\n\narr = [2, 1, 5, 1, 3, 2]\nresult = max_sum_in_window(arr, 3)\nprint(result)\n\n\ndef smallest_array_sum(arr, s):\n window_sum = 0\n min_length = sys.maxsize\n window_start = 0\n\n for window_end in range(len(arr)):\n window_sum += arr[window_end]\n\n while window_sum >= s:\n min_length = min(min_length, window_end - window_start + 1)\n window_sum -= arr[window_start]\n window_start += 1\n if min_length == sys.maxsize:\n return 0\n return min_length\n\n\narr = [2, 1, 5, 2, 3, 2]\nresult = smallest_array_sum(arr, 7)\nprint(result)\n","repo_name":"sudhirsinghshekhawat/problem_solving","sub_path":"slidingwindow/slidingwindowproblems.py","file_name":"slidingwindowproblems.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"13552737741","text":"from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field\n\nfrom .models import *\n\n# class TopicForm(forms.ModelForm):\n# def clean_topic_field(self):\n# fields = self.cleaned_data['fields']\n# return fields\n\n# class Meta:\n# model = TopicAction\n# fields = ['name', 'image',]\n# labels = {'name': ''}\n# widgets = {'name': forms.TextInput(\n# attrs={'rows': 4, 'cols': 40, 'placeholder': 'Type your topic here'})}\n\n\n\nclass FeedForm(forms.ModelForm):\n def clean_post_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n class Meta:\n model = Feed\n fields = ['text', 'image',]\n \n helper = FormHelper()\n helper.form_class = 'form-group'\n helper.layout = Layout(\n Field('text',rows=\"2\", css_class='input-xlarge form-control form-rounded mt-2 mb-3 col-xs-7 '),\n Field('image'),\n )\n helper.add_input(Submit('submit', 'Post Feed', css_class='btn btn-primary rounded-pill'))\n\n\nclass CommentForm(forms.ModelForm):\n \"\"\"docstring for CommentForm\"\"\"\n def clean_comment_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n # this function will be used for the validation\n # def clean(self):\n # #data from the form is fetched using super function \n # super(CommentForm, self).clean()\n # fields = self.cleaned_data['fields']\n\n # if len(fields) < 25:\n # self._errors['fields'] = self.error_class([\n # 'Comment should contain a minimum of 25 characters'])\n # #return any errors if found \n # return self.cleaned_data \n\n class Meta:\n model = Comment\n fields = ['content']\n # labels = {'comment': ''}\n widgets = {'comment': forms.Textarea(\n attrs={'rows': '2', \n 'cols': '8', \n 'placeholder': 'Say something...', \n 'class': 'form-control'\n })\n }\n\nclass ReplyForm(forms.ModelForm):\n \"\"\"docstring for CommentForm\"\"\"\n def clean_reply_field(self):\n fields = self.cleaned_data['fields']\n return fields\n\n class Meta:\n model = Reply\n fields = ['content']\n # labels = {'reply': ''}\n widgets = {'reply': forms.Textarea(\n attrs={'rows': '2', \n 'cols': '8', \n 'placeholder': 'Replying...', \n 'class': 'form-control'\n })\n }\n","repo_name":"paulBit3/Tekit","sub_path":"feed/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"12172606379","text":"import argparse\r\nimport os\r\nfrom datetime import datetime\r\n\r\nimport torch\r\nfrom torch import nn, optim\r\n\r\nfrom datasets import mnist_loader\r\nfrom models import MNISTNet\r\nfrom trainers import Trainer\r\nfrom utils import load_json, save_json\r\n\r\n\r\ndef main():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--config', type=str, default='configs/config.json')\r\n parser.add_argument('--no-cuda', action='store_true')\r\n parser.add_argument('--parallel', action='store_true')\r\n args = parser.parse_args()\r\n args.cuda = torch.cuda.is_available() and not args.no_cuda\r\n print(args)\r\n\r\n device = torch.device('cuda' if args.cuda else 'cpu')\r\n\r\n config = load_json(args.config)\r\n\r\n model = MNISTNet()\r\n if args.parallel:\r\n model = nn.DataParallel(model)\r\n model.to(device)\r\n\r\n optimizer = optim.Adam(model.parameters(), **config['adam'])\r\n scheduler = optim.lr_scheduler.StepLR(optimizer, **config['steplr'])\r\n\r\n train_loader, valid_loader = mnist_loader(**config['dataset'])\r\n\r\n trainer = Trainer(model, optimizer, train_loader, valid_loader, device)\r\n\r\n output_dir = os.path.join(config['output_dir'], datetime.now().strftime('%Y%m%d_%H%M%S'))\r\n os.makedirs(output_dir, exist_ok=True)\r\n\r\n # save config to output dir\r\n save_json(config, os.path.join(output_dir, 'config.json'))\r\n\r\n for epoch in range(config['epochs']):\r\n scheduler.step()\r\n\r\n train_loss, train_acc = trainer.train()\r\n valid_loss, valid_acc = trainer.validate()\r\n\r\n print('epoch: {}/{},'.format(epoch + 1, config['epochs']),\r\n 'train loss: {:.4f}, train acc: {:.2f}%,'.format(train_loss, train_acc * 100),\r\n 'valid loss: {:.4f}, valid acc: {:.2f}%'.format(valid_loss, valid_acc * 100))\r\n\r\n torch.save(model.state_dict(), os.path.join(output_dir, 'model_{:04d}.pt'.format(epoch + 1)))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"PeterXiaoGuo/pytorch-template","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"50"}
+{"seq_id":"15546533458","text":"import sys\nfrom pathlib import Path\n\nimport pkg_resources\nfrom grpc_tools import protoc\n\nargs = []\n\nfor e in [\n \"cosmos-sdk/proto\",\n \"cosmos-proto/proto\",\n \"gogoproto\",\n \"googleapis\",\n]:\n args += [f\"--proto_path=third_party/{e}\"]\n\nargs += [\"--python_out=.\"]\nargs += [\"--grpc_python_out=.\"]\n\nfor e in [\"cosmos-sdk/proto\", \"cosmos-proto/proto\", \"gogoproto/gogoproto\"]:\n args += list(map(str, Path(f\"third_party/{e}\").rglob(\"*.proto\")))\n\n\ndef main():\n proto_include = pkg_resources.resource_filename(\"grpc_tools\", \"_proto\")\n return protoc.main([\"\"] + args + [f\"-I{proto_include}\"])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"rnbguy/cosmos-sdk-python","sub_path":"cosmos_sdk/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"70249338715","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 14 19:32:53 2018\n\n@author: Tejaswini Nardella, Anusha Balaji, Shashikant Jaiswal\n\"\"\"\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk.tokenize import word_tokenize,sent_tokenize\nfrom nltk.corpus import stopwords\nfrom collections import OrderedDict\n#from rouge import Rouge\nfrom rougescore import rougescore\nimport glob\nimport os\n\n#Retreive news articles from training data set\n\npath_train = 'C:\\\\SHASHI_DATA\\\\3_NLP\\\\Coding\\\\Final_Code\\\\data\\\\train'\npath_test = 'C:\\\\SHASHI_DATA\\\\3_NLP\\\\Coding\\\\Final_Code\\\\data\\\\test'\n\ncorpus_train=[]\ni=0\nfor filename in sorted(glob.glob(os.path.join(path_train, '*.sent'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n #corpus[filename]=text\n corpus_train.append(text)\n i+=1\n\n#Retreive news articles from test data set\ncorpus_test=[]\ni=0\nfor filename in sorted(glob.glob(os.path.join(path_test, '*.sent'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n #corpus[filename]=text\n corpus_test.append(text)\n i+=1\n\n#Retreive summary of news articles from test data set\ncorpus_test_summary=[]\nfor filename in sorted(glob.glob(os.path.join(path_test, '*.summ'))):\n file=open(filename,\"r\",encoding=\"utf8\")\n text=file.read()\n #print(text)\n print(i)\n corpus_test_summary.append(text)\n i+=1 \n\n#Initialize vectorizer\nvectorizer = TfidfVectorizer(stop_words='english')\n# tokenize and build vocab from training corpus\nvectorizer.fit(corpus_train)\n#print(vectorizer.vocabulary)\nstop_words=set(stopwords.words('english'))\n#Initialize total rscore value\nrscore_total=0.0\n#Itereate over list of news articles in test corpus and generate corresponding summary for each article\nfor i in range(len(corpus_test)):\n # transform document into vector\n vector= vectorizer.transform([corpus_test[i]]).toarray()\n # Sort the weights from highest to lowest: sorted_tfidf_weights\n #sorted_tfidf_weights = sorted(vector, key=lambda w: w[1], reverse=True)\n #build sentence score dictionary\n sentScore=dict() \n #Iterate over all sentences to compute sentence score of each sentence in text\n for sent in sent_tokenize(corpus_test[i]):\n for w in word_tokenize(sent):\n if w not in stop_words:\n index=vectorizer.vocabulary_.get(w)\n if(index!=None):\n w_score=vector[0][index]\n print(index)\n if sent[0:15] in sentScore:\n sentScore[sent]+=w_score\n else:\n sentScore[sent]=w_score\n #sort the items in dictionary based on sentence score \n sorted_dict = OrderedDict(sorted(sentScore.items(), key=lambda x: x[1],reverse=True))\n\n #print(\"\\n\\nSummary:\\n\")\n count=1\n summ=\"\"\n \n #retreive top 5 highest score sentences and generate summary\n for k, v in sorted_dict.items():\n if(count>3):\n break \n #print(\"%s. %s\" % ((i), ''.join(k)))\n summ+=k\n count+=1\n #print(\"The system generated summary:\")\n #print(summ)\n predicted_summary=summ\n #retreive the actual summary of corresponding news article\n actual_summary=corpus_test_summary[i]\n #print(\"The Reference summary:\")\n #print(actual_summary)\n #print(\"The model generated summary:\")\n #print(predicted_summary)\n\n #compute precision and recall\n rscore= rougescore.rouge_n(predicted_summary,actual_summary,1,0.0)\n rscore_total+=rscore\n\navg_rscore= rscore_total/len(corpus_test)\n\nprint(\"\\n\\n\")\nprint(\"Test corpus length :\"+str(len(corpus_test)))\n#print(\"total Rscore is :\"+str(rscore_total))\nprint(\"Rouge score for summarization is :\"+str(avg_rscore))\n \n \n\n \n\n","repo_name":"Shashikant-Jaiswal/Text_Summarizer_NLP","sub_path":"textSummarizer.py","file_name":"textSummarizer.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"39835681250","text":"def count(t):\n pituus = len(t)\n laskuri = 0\n\n vasen_puoli = [0]*pituus\n vasen_puoli[0] = t[0]\n edellinen = vasen_puoli[0]\n for i in range(0, pituus):\n if t[i] > edellinen:\n vasen_puoli[i] = t[i]\n edellinen = t[i]\n else:\n vasen_puoli[i] = edellinen\n\n oikea_puoli = [0]*pituus\n oikea_puoli[pituus-1] = t[pituus-1]\n edellinen_o = oikea_puoli[pituus-1]\n for i in range(pituus-1, -1, -1):\n if t[i] < edellinen_o:\n oikea_puoli[i] = t[i]\n edellinen_o = t[i]\n else:\n oikea_puoli[i] = edellinen_o \n for i in range(0, pituus-1):\n if oikea_puoli[i+1] > vasen_puoli[i]:\n laskuri += 1\n return laskuri\n \nif __name__ == \"__main__\":\n print(count([1, 2, 3, 4, 5])) # 4\n print(count([5, 4, 3, 2, 1])) # 0\n print(count([2, 1, 2, 5, 7, 6, 9])) # 3\n print(count([5, 6, 6, 7, 8, 10, 3])) #0\n print(count([2, 1, 2, 6, 3, 4, 9, 12])) #3","repo_name":"Jenniemilia/Algoritmi_harjoituksia","sub_path":"splitlist.py","file_name":"splitlist.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"30291725339","text":"from django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST\nfrom django.core.exceptions import PermissionDenied\nfrom django.http.response import HttpResponse\nfrom xmlrpc import AccountService\nimport cPickle as pickle\nfrom django.conf import settings\n\nuserdb = AccountService()\n\n@csrf_exempt\n@require_POST\ndef service(req):\n if req.META['REMOTE_ADDR'] not in ('127.0.0.1',):\n raise PermissionDenied\n response = HttpResponse(mimetype='application/hackers-edge')\n if 'HTTP_X_HACKER_TOKEN' not in req.META.keys():\n raise PermissionDenied\n if req.META['HTTP_X_HACKER_TOKEN'] != settings.HACKER_TOKEN:\n raise PermissionDenied\n request = req.body.split(chr(0))\n if request[0] == 'ping':\n data = 'pong'\n elif request[0] == 'user':\n udata = userdb.get_user(request[1])\n data = 'udata'+chr(0)+pickle.dumps(udata)\n elif request[0] == 'last_login':\n data = 'last_login'+chr(0)+pickle.dumps(userdb.get_last_login(request[1]))\n else:\n data = 'ERR'\n response.write(data+chr(255))\n return response\n","repo_name":"kveroneau/HackersEdge","sub_path":"trunk/accounts/game_service.py","file_name":"game_service.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"17778972448","text":"# I TRIED DOING WITH THE SAME CODE WHICH I USED IN AOC-2021 AS THE QUESTION LOOKED SAME\n# file_input = open(\"day-15-input.txt\", \"r\")\n\n# # file_input = open(\"day-15-test.txt\", \"r\")\n# for i in file_input:\n# a = [int(_) for _ in i.strip()]\n# _mapp.append(a)\n# # print(a) \n# file_input.close()\nimport math\n_mapp = []\n'''\ndef find_short(mapp):\n start = (0, 0) # y, x\n end = (len(mapp)-1, len(mapp[0])-1) # y, x\n\n # print(start, end)\n neww = []\n for i in range(len(mapp)):\n arr = []\n for j in range(len(mapp[0])):\n arr.append(0)\n neww.append(arr)\n # print(\"new arr\\n\", neww)\n neww[0][0] = mapp[0][0]\n\n # visited = []\n\n for i in range(1, len(mapp)):\n neww[i][0] = mapp[i][0] + neww[i-1][0]\n\n for j in range(1, len(mapp[0])):\n neww[0][j] = mapp[0][j] + neww[0][j-1]\n\n # print(mapp)\n # print(neww)\n\n for i in range(1, len(mapp)):\n for j in range(1, len(mapp[0])):\n neww[i][j] = mapp[i][j] + min(neww[i-1][j], neww[i][j-1])\n\n # for i in range(len(mapp)):\n # print([_ for _ in neww[i]])\n \n # print(neww[0][0], neww[-1][-1])\n # print(\"Ans = \", neww[-1][-1]-neww[0][0])\n print(neww[-1][-1])\n'''\ndef neighbors(xy):\n (x, y) = xy\n return [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]\n\n\ndef traverse_cost(start, end, c):\n steps = 1\n cost = { start: 0 }\n active = set([start])\n visited = set([])\n \n while active:\n steps+=1\n current = min(active, key=cost.get)\n\n if current == end:\n return cost[current]\n\n active.remove(current)\n visited.add(current)\n for xy in neighbors(current):\n if xy in c and xy not in active:\n n_cost = cost.get(current, 0) + c[xy]\n if n_cost < cost.get(xy, math.inf):\n cost[xy] = n_cost\n active.add(xy)\n # print(steps, end=\"\\r\")\n # updated_mapp(c, visited, steps)\n\n\n\n# c1 = C\n\n\n# print(\"\\nAns :\",cos)\nif __name__ ==\"__main__\":\n \n testcases = int(input())\n for i in range(testcases):\n n,m = map(int, input().split())\n for i in range(n):\n _mapp.append(list(map(int, input().split())))\n C = {}\n for i in range(len(_mapp)):\n for j in range(len(_mapp[0])):\n C[(j, i)] = _mapp[i][j]\n start = (0, 0)\n end = (len(_mapp[0])-1, len(_mapp)-1)\n cos = traverse_cost(start, end, C)\n print(cos+_mapp[0][0])\n # find_short(_mapp)\n","repo_name":"HappyBravo/Tirutsava-2022","sub_path":"Run From Orochimaru/Run From Orochimaru_mysol.py","file_name":"Run From Orochimaru_mysol.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"1016476865","text":"from flask import Flask, request, render_template\nimport pandas\nfrom sklearn.linear_model import LinearRegression\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route(\"/calc/\")\ndef calc(): \n return render_template(\"calc.html\")\n\n\n\ndef PredictionModel(years_education:int, hours_per_week:int) -> float:\n df = pandas.read_csv(\"census-income.csv\")\n\n years_education = abs(int(years_education))\n hours_per_week = abs(int(hours_per_week))\n \n X = df[[\" education-num\", \" hours-per-week\"]]\n y = df[\" \"].map({\" <=50K\":1, \" >50K\":0})\n\n linear_regression_model = LinearRegression()\n linear_regression_model.fit(X.values, y)\n \n prediction = linear_regression_model.predict([[years_education, hours_per_week]])\n\n final_output = round(float(prediction[0]))\n\n if final_output < 0:\n final_output = 0\n return final_output\n elif final_output > 1:\n final_output = 1\n return final_output\n else:\n return final_output\n\n\n\n@app.route(\"/calc/prediction\", methods=[\"POST\"])\ndef predict():\n if request.method == 'POST':\n edu_num = request.form['edu']\n hrs = request.form['hrs']\n x = PredictionModel(edu_num, hrs)\n if x == 0:\n return f'Prediction \\\n Final Output = {x}
Income is likely >$50K (Lower risk of poverty)
'\n else:\n return f'Prediction \\\n Final Output = {x}
Income is likely <=$50K (Higher risk of poverty)
'\n\n\n\n\n@app.route(\"/about/\")\ndef about():\n return render_template(\"about.html\")\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"dcodecrzft/incomcalc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"40776038115","text":"import re\n\nfrom .Runner import resolve_argument\nfrom .ToolRunner import ToolRunner\nimport cgatcore.pipeline as P\n\n\nclass run_tool_LDSC(ToolRunner):\n name = \"ldsc\"\n output = \"log\"\n path = \"/home/steven/ldsc/ldsc.py\"\n expected = [\"input_sumstats\"]\n\n def get_version(self):\n return \"1.0.0\"\n\n def run(self, outfile, params):\n options = params.options\n outdir = re.sub(r\".*outdir \", \"\", options)\n options = re.sub(r\"--outdir (.*)\", \"\", options)\n\n other_sumstats = re.sub(r\".*--rg \", \"\", options)\n if other_sumstats == options:\n other_sumstats = \"\"\n options = re.sub(r\"--rg .*sumstats.gz\", \"--rg\", options)\n\n outputfile = outfile\n outputfile = re.sub(r\"(.*)/\", r\"\\1/\" + outdir, outputfile)\n\n retval = P.run(\". ../env/bin/activate; \"\n \"{params.path} \"\n \"{options} \"\n \"{params.input_sumstats}\"\n \"{other_sumstats} \"\n \"--out {outputfile}\"\n .format(**locals()))\n\n return retval\n","repo_name":"cgat-developers/cgat-daisy","sub_path":"src/daisy/tasks/LDSC.py","file_name":"LDSC.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"73961194395","text":"import unicodedata\nimport re\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"\", 1: \"\",2:'',3:''}\n self.n_words = 4 # Count SOS and EOS and unk and pad \n self.pad_token_id=3\n self.unk_token_id=2\n self.embeddings=None\n def addSentence(self, sentence):\n for word in sentence.split(' '):\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.word2count[word] = 1\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\ndef unicodeToAscii(s):\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n\n# Lowercase, trim, and remove non-letter characters\n\n\ndef normalizeString(s):\n s = unicodeToAscii(s.lower().strip())\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n return s\n\n","repo_name":"tejasvi96/graph-federated-learning","sub_path":"LanguageClass.py","file_name":"LanguageClass.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"471673852","text":"from genericpath import exists\nfrom django.shortcuts import render, redirect\nfrom django.conf import settings\nfrom django.http import JsonResponse\nfrom .usp import *\nimport pymysql\nimport hashlib\nfrom apps.dashboard.controllers.roles.usp import fc_get_permisos\nfrom django.contrib import messages\nfrom apps.helpers import request_session\n\n\n# Create your views here.\ndef getClientesPage(request):\n data = {\n 'id' : 5,\n 'meta_title': 'Dashboard - Clientes',\n 'breadcrumb': \"Clientes\",\n 'title': 'Lista de Clientes',\n 'subtitle': 'Lista completa de Clientes del sistema',\n 'button_add': 'Añadir Cliente',\n }\n a = helpers.session_user_exist(request)\n if (a == False):\n messages.add_message(request, messages.ERROR, 'No haz Iniciado Sesión.')\n return redirect (\"loginDashboard\")\n \n b = helpers.session_user_role(request)\n if (b == True):\n del request.session['usuario']\n messages.add_message(request, messages.ERROR, 'No tienes Permiso.')\n return redirect (\"loginDashboard\")\n \n c = helpers.request_module(request, data)\n if (c == True):\n return render(request, \"clientes.html\", data)\n\n# OBTENER TODOS LOS CLIENTES\ndef getAllClientes(request):\n data_clientes = list(fc_get_all_clientes())\n data_to_array = []\n # Convertir TUPLA a Array Modificable\n for i in data_clientes:\n data_to_array.append({\n \"rut_cliente\": i[0],\n \"contrasena_cliente\": i[1],\n \"n1_cliente\": i[2],\n \"n2_cliente\": i[3],\n \"ap_cliente\": i[4],\n \"am_cliente\": i[5],\n \"correo_cliente\": i[6],\n \"telefono_cliente\": i[7],\n \"rut_empresa_cliente\": i[8],\n \"nombre_empresa\": i[9],\n \"id_rol\": i[10],\n \"status_cliente\": i[11],\n })\n\n for i in data_to_array:\n i['options'] = \"\"\"\n \n \"\"\" % (i['rut_cliente'],i['rut_cliente'])\n\n return JsonResponse(data_to_array, safe=False, json_dumps_params={'ensure_ascii': False})\n\n# OBTENER UN CLIENTE\ndef dashboard_get_cliente(request):\n v_rut_cliente = request.GET.get('rutCliente')\n if (v_rut_cliente != \"\"):\n data_cliente = list(fc_get_cliente_dash(v_rut_cliente))\n data_to_array = []\n if (data_cliente != ()):\n for i in data_cliente:\n data_to_array.append({\n \"rut_cliente\": i[0],\n \"contrasena_cliente\": i[1],\n \"n1_cliente\": i[2],\n \"n2_cliente\": i[3],\n \"ap_cliente\": i[4],\n \"am_cliente\": i[5],\n \"correo_cliente\": i[6],\n \"telefono_cliente\": i[7],\n \"rut_empresa_cliente\": i[8],\n \"nombre_empresa\": i[9],\n })\n return JsonResponse(data_to_array, safe=False, json_dumps_params={'ensure_ascii': False})\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\n# UPDATE CLIENTE\ndef dashboard_update_cliente(request):\n if (request.method == 'POST'):\n try:\n cx = get_connection()\n with cx.cursor() as cursor:\n v_rut_cliente = request.POST.get(\"rutCliente\")\n v_contrasena_cliente = request.POST.get(\"txtContrasenaCliente\")\n v_correo_cliente = request.POST.get(\"txtCorreoCliente\")\n v_telefono_cliente = request.POST.get(\"txtTelefonoCliente\")\n v_nombre_empresa = request.POST.get(\"txtNombreEmpresaCliente\")\n\n cursor.execute(\"SELECT * FROM nma_cliente WHERE rut_cliente = '%s'\" % (v_rut_cliente))\n exist = cursor.fetchall()\n\n if (exist != ()):\n cursor.execute(\"\"\"UPDATE nma_cliente SET contrasena_cliente = '%s', \n correo_cliente = '%s', telefono_cliente = %s, nombre_empresa = '%s' WHERE rut_cliente = '%s' \"\"\" % \n (v_contrasena_cliente, v_correo_cliente, v_telefono_cliente, v_nombre_empresa, v_rut_cliente))\n\n cx.commit()\n return redirect(\"getClientesPage\")\n\n else:\n messages.add_message(request, messages.ERROR, 'Ha ocurrido un error inesperado, vuelva a intentarlo!')\n return redirect(\"getClientesPage\")\n\n except Exception as ex:\n messages.add_message(request, messages.ERROR, 'Ha ocurrido un error inesperado, vuelva a intentarlo!')\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_insert_cliente(request):\n \"\"\"\n Si el método de solicitud es POST, entonces comprueba si el cliente existe, si no existe, entonces inserta el cliente,\n si existe, entonces actualiza el Cliente.\n\n :param request: El objeto de solicitud es un objeto HttpRequest\n :return: una redirección a la página getClientesPage.\n \"\"\"\n if request.method == \"POST\":\n rut_cliente = request.POST.get(\"txtRut\")\n exist = fc_get_cliente_dash(rut_cliente)\n if (exist == ()):\n # INSERTAR Cliente\n # v_contrasena_cliente = request.POST.get(\"txtContraseña\") -> Por ahora no se utiliza ya que se genera la contraseña automáticamente en la variable \"vaa\"\n v_n1_cliente = request.POST.get(\"txtPrimerNombre\")\n v_n2_cliente = request.POST.get(\"txtSegundoNombre\")\n v_ap_cliente = request.POST.get(\"txtApellidoPaterno\")\n v_am_cliente = request.POST.get(\"txtApellidoMaterno\")\n v_correo_cliente = request.POST.get(\"txtCorreoElectronico\")\n # Creating a hash of the second name, the @ symbol and the user's rut.\n vaa = v_n1_cliente + '@' + rut_cliente # la contraseña corresponde al nombre del cliente + @ + rut\n v_password = hashlib.sha256(vaa.encode('utf-8')).hexdigest()\n \n v_telefono_cliente = request.POST.get(\"txtTelefono\")\n v_rut_empresa_cliente = request.POST.get(\"txtRutEmpresa\")\n v_nombre_empresa = request.POST.get(\"txtNombreEmpresa\")\n v_status_Cliente = 0 \n\n fc_insert_cliente(rut_cliente, v_password, v_n1_cliente, v_n2_cliente, v_ap_cliente,\n v_am_cliente, v_correo_cliente, v_telefono_cliente, v_rut_empresa_cliente, v_nombre_empresa, v_status_Cliente)\n messages.add_message(request, messages.SUCCESS, 'Usuario ingresado Exitosamente!')\n return redirect(\"getClientesPage\")\n\n else:\n # ACTUALIZAR Cliente\n exist = fc_get_cliente_dash(rut_cliente)\n if (exist != ()):\n v_rut_Cliente = request.POST.get(\"txtRut\")\n v_contrasena_cliente = sha256(request.POST.get(\"txtContraseña\"))\n v_n1_cliente = request.POST.get(\"txtPrimerNombre\")\n v_n2_cliente = request.POST.get(\"txtSegundoNombre\")\n v_ap_cliente = request.POST.get(\"txtApellidoPaterno\")\n v_am_cliente = request.POST.get(\"txtApellidoMaterno\")\n v_correo_cliente = request.POST.get(\"txtCorreoElectronico\")\n \n v_telefono_cliente = request.POST.get(\"txtTelefono\")\n v_rut_empresa_cliente = request.POST.get(\"txtDireccion\")\n v_nombre_empresa = request.POST.get(\"txtDireccion\")\n v_status_Cliente = 0 \n\n fc_update_cliente(v_rut_Cliente, v_contrasena_cliente, v_n1_cliente, v_n2_cliente,\n v_ap_cliente, v_am_cliente, v_telefono_cliente, v_rut_empresa_cliente, v_rut_empresa_cliente,v_nombre_empresa, v_status_Cliente)\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_delete_cliente(request):\n if request.method == \"GET\":\n v_rut_Cliente = request.GET.get(\"txtRut\")\n exist = fc_get_cliente_dash(v_rut_Cliente)\n if (exist != ()):\n fc_delete_cliente(v_rut_Cliente)\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n else:\n return redirect(\"getClientesPage\")\n\ndef dashboard_status_cliente (request):\n if (request.method == \"POST\"):\n try:\n cx = get_connection()\n\n with cx.cursor() as cursor:\n cursor.execute(\"UPDATE nma_cliente SET contrasena_cliente WHERE rut_cliente = 0\")\n cx.commit()\n return redirect(\"getClientesPage\")\n\n except Exception as ex:\n print (ex)\n return redirect(\"getClientesPage\")\n\n else:\n return redirect(\"getClientesPage\")\n","repo_name":"DeveloperFlack/portafolio_ingenieria_2022","sub_path":"apps/dashboard/controllers/clientes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9384,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"38100456479","text":"# import unittest\nimport datetime\nfrom django.test import TestCase, Client\nfrom .models import Movie\n\n# Create your tests here.\n\n# Testing the Movie Model\nclass MovieTestCase(TestCase):\n def setUp(self):\n Movie.objects.create(\n title=\"Independence Day\",\n released_date=\"1996-03-10\",\n production_company=\"Centropolis Entertainment\"\n )\n\n def test_movies_exist(self):\n movie = Movie.objects.get(title=\"Independence Day\")\n self.assertEqual(movie.title, \"Independence Day\")\n self.assertEqual(movie.released_date, datetime.date(1996, 3, 10))\n self.assertEqual(movie.production_company, \"Centropolis Entertainment\")\n\n\n# Testing the views\nclass ViewsTest(TestCase):\n def setUp(self):\n self.client = Client()\n\n def test_movies_index(self):\n response = self.client.get('/api/v1/movies')\n self.assertEqual(response.status_code, 200)\n\n def test_movies_detail_with_no_content(self):\n response = self.client.get('/api/v1/movies/1')\n self.assertEqual(response.status_code, 404)\n\n def test_movies_detail_with_content(self):\n movie = Movie.objects.create(\n title=\"Armageddon\",\n released_date=\"1998-07-01\",\n production_company=\"Touchstone Pictures\"\n )\n url = '/api/v1/movies/' + str(movie.id)\n # import pdb; pdb.set_trace()\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)","repo_name":"nsingh1981/movie-list-code-challenge","sub_path":"api/movies/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"6592680194","text":"#####################################################\n# --- Day 1: The Tyranny of the Rocket Equation --- #\n#####################################################\n\nimport AOCUtils\n\ndef reqFuel(m):\n return (m // 3) - 2\n\n#####################################################\n\nmasses = AOCUtils.loadInput(1)\n\nfuelSum = sum(reqFuel(m) for m in masses)\nprint(\"Part 1: {}\".format(fuelSum))\n\nfuelSum = 0\nfor m in masses:\n fuel = reqFuel(m)\n while fuel >= 0:\n fuelSum += fuel\n fuel = reqFuel(fuel)\n\nprint(\"Part 2: {}\".format(fuelSum))\n\nAOCUtils.printTimeTaken()","repo_name":"KanegaeGabriel/advent-of-code-2019","sub_path":"01_rocket_equation.py","file_name":"01_rocket_equation.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"6742324778","text":"from multiprocessing.connection import Client\nimport socket\n\nclass Network:\n def __init__(self, data):\n self.client = None\n # self.server = \"172.104.158.227\"\n self.server = server = socket.gethostbyname(socket.gethostname())\n self.port = 5555\n self.addr = (self.server, self.port)\n self.p = self.connect(data)\n\n def get_p(self):\n return self.p\n\n def connect(self, data):\n try:\n self.client = Client(self.addr)\n self.client.send(data)\n return self.client.recv()\n except:\n pass\n\n def send(self, data):\n try:\n self.client.send(data)\n return self.client.recv()\n except:\n print(\"conn failed\")\n","repo_name":"LooneyLychee/Checkers","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"1269568313","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 13 19:51:21 2021\r\n\r\n@author: z5158936\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\nimport scipy.optimize as spo\r\nimport scipy.interpolate as spi\r\n\r\ndef f_minPoly(X,*args):\r\n Xs,Ys = args\r\n # f_inter = spi.interp1d(Xs, Ys, kind='cubic',fill_value='extrapolate')\r\n f_inter = spi.interp1d(Xs, Ys, kind='quadratic',fill_value='extrapolate')\r\n return f_inter(X)\r\n\r\n\r\nfile_rslts = 'Optim_TPR_all.csv'\r\nfldr_rslts = 'Optim_Results/'\r\n\r\n###########################################\r\n#%%% DIFFERENT HEIGHT, FIX RADIATION FLUX\r\n###########################################\r\n#FIGURE 1\r\n\r\nQ_av = 1.00\r\nQ_avs = np.arange(0.50,1.51,0.5)\r\n\r\nms = ['o','s','d']\r\n\r\ni=0\r\nfor Q_av in Q_avs:\r\n \r\n file_rslts = 'Optim_TPR_0D_quick.csv'\r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.Q_avg_i==Q_av)].copy()\r\n df.sort_values(['zf','Prcv'],inplace=True)\r\n \r\n zfs = df.zf.unique()\r\n \r\n ###########################################\r\n #FIGURE 3\r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n mins = []\r\n fs = 18\r\n for zf in zfs:\r\n df2 = df[(df.zf==zf)].copy()\r\n \r\n df2.drop_duplicates(subset=['Prcv','zf','Q_avg_i'],inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,lw=1.5,label=str(zf)+' m')\r\n \r\n bounds = (df2.Prcv.min(),df2.Prcv.max())\r\n args = (df2.Prcv,df2.LCOH)\r\n res = spo.minimize_scalar(f_minPoly, bounds=bounds, args=args, method='bounded')\r\n Prcv_min = res.x\r\n LCOH_min = f_minPoly(Prcv_min,*args)\r\n Nhel_min = spi.interp1d(df2.Prcv, df2.N_hel, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n etaSF_min = spi.interp1d(df2.Prcv, df2.eta_SF, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n fzv_min = spi.interp1d(df2.Prcv, df2.fzv, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min])\r\n \r\n mins = pd.DataFrame(mins,columns=('zf','Prcv','LCOH','Nhel','eta_SF','fzv'))\r\n mins.sort_values(by='zf',inplace=True)\r\n \r\n args = (mins.Prcv,mins.LCOH)\r\n Prcvs = np.arange(mins.Prcv.min(),mins.Prcv.max(),0.1)\r\n ax1.plot(mins.Prcv,mins.LCOH,c='mediumblue',lw=3,marker='s',markersize=10,label='min')\r\n ax1.set_ylim(20,35)\r\n ax1.set_xlim(0,40)\r\n # ax1.set_title('LCOH for different receiver powers and tower heights with $Q_{{avg}}={:.2f}$'.format(Q_av),fontsize=fs)\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.legend(loc=1,bbox_to_anchor=(1.25, 0.98),fontsize=fs-2)\r\n ax1.grid()\r\n fig.savefig(fldr_rslts+'Prcv_zf_LCOH_Qavg_{:.2f}_fig3.png'.format(Q_av), bbox_inches='tight')\r\n plt.show()\r\n \r\n ###########################################\r\n # TOWER HEIGHT VS RECEIVER POWER\r\n \r\n def func1(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n \r\n X = mins.zf\r\n Y = mins.Prcv\r\n p0 = (1., 0.05)\r\n coefs, covariance = spo.curve_fit( func1, X, Y, maxfev=10000, p0=p0)\r\n Yc = func1(X,*coefs)\r\n r2 = 1 - (np.sum((Y - Yc)**2) / np.sum((Y-np.mean(Y))**2))\r\n Xc = np.linspace(20,75,100)\r\n Yc = func1(Xc,*coefs)\r\n A,b = coefs\r\n \r\n \r\n def func3(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\n X3 = mins.zf\r\n Y3 = mins.LCOH\r\n p0 = (10., 0.05, 20.)\r\n coefs_LCOH, covariance = spo.curve_fit( func3, X3, Y3, maxfev=10000, p0=p0)\r\n Yc3 = func3(X3,*coefs_LCOH)\r\n r2 = 1 - (np.sum((Y3 - Yc3)**2) / np.sum((Y3-np.mean(Y3))**2))\r\n A3,b3,c3 = coefs_LCOH\r\n print(A3,b3,c3,r2)\r\n \r\n figb, ax1b = plt.subplots(figsize=(9,6))\r\n ax2b = ax1b.twinx()\r\n fs=18\r\n cLCOH = 'mediumblue'\r\n cPrcv = 'orangered'\r\n # print(mins)\r\n # ax1b.plot(mins.zf,mins.LCOH,lw=3,c='mediumblue',marker=ms[i],markersize=10,label='{:.2f}'.format(Q_av))\r\n ax1b.scatter(mins.zf, mins.LCOH, c=cLCOH, marker=ms[i], s=200, label='LCOH')\r\n ax2b.scatter(mins.zf,mins.Prcv,c=cPrcv,marker=ms[i],s=200,label=r'$P_{rcv}$')\r\n \r\n ax2b.plot(Xc,Yc,c=cPrcv,lw=2,ls=':')\r\n ax1b.plot(X3,Yc3,lw=3, c=cLCOH, ls=':')\r\n \r\n ax2b.annotate(r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A,b),(Xc[-1]-18,Yc[-1]),c=cPrcv,fontsize=fs)\r\n \r\n ax1b.annotate(r'${:.1f}+{:.1f}e^{{-{:.2f}z_f}}$'.format(c3,A3,b3),(X3.iloc[-1]-20,Yc3.iloc[-1]+1),c=cLCOH,fontsize=fs-2)\r\n \r\n ax1b.scatter([],[],lw=3,c=cPrcv,marker='s',s=200,label=r'$P_{rcv}$')\r\n \r\n # ax1b.plot([],[],c='C1',lw=2,ls=':',label=r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A,b))\r\n \r\n ax1b.legend(loc=2,fontsize=fs)\r\n ax1b.set_ylim(20,35)\r\n ax1b.grid()\r\n # ax1b.set_title('LCOH and optimal receiver power for different tower heights with $Q_{{avg}}={:.2f}$'.format(Q_av),fontsize=fs)\r\n ax1b.set_xlabel(r'Tower height $(m)$',fontsize=fs)\r\n ax1b.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax2b.set_ylabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax2b.spines['left'].set_color('mediumblue')\r\n ax2b.spines['right'].set_color('C1')\r\n ax1b.tick_params(axis='y', colors=cLCOH,size=10)\r\n ax2b.tick_params(axis='y', colors=cPrcv,size=10)\r\n ax1b.yaxis.label.set_color(cLCOH)\r\n ax2b.yaxis.label.set_color(cPrcv)\r\n ax1b.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax2b.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax2b.set_yticks(np.linspace(ax2b.get_yticks()[0], ax2b.get_yticks()[-1], len(ax1b.get_yticks())))\r\n ax2b.set_yticks(np.linspace(0, 35, len(ax1b.get_yticks())))\r\n plt.show()\r\n \r\n i+=1\r\n figb.savefig(fldr_rslts+'zf_Prcv_min_Qavg_{:.2f}.png'.format(Q_av), bbox_inches='tight')\r\n \r\n \r\n# sys.exit()\r\n \r\n#%%% INFLUENCE OF RADIATION FLUX\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\nzfs = np.arange(20,76,5)\r\n# zfs = [30,40,50,60]\r\nmins = []\r\n\r\nfor zf in zfs:\r\n \r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.zf==zf)].copy()\r\n df.sort_values(['Q_av','Prcv'],inplace=True)\r\n \r\n idx_min = df.LCOH.idxmin()\r\n Prcv_min = df.loc[idx_min]['Prcv']\r\n LCOH_min = df.loc[idx_min]['LCOH']\r\n Nhel_min = df.loc[idx_min]['N_hel']\r\n etaSF_min = df.loc[idx_min]['eta_SF']\r\n fzv_min = df.loc[idx_min]['fzv']\r\n Q_av = df.loc[idx_min]['Q_avg_i']\r\n Arcv = df.loc[idx_min]['Arcv']\r\n eta_rcv = df.loc[idx_min]['eta_rcv']\r\n S_HB = df.loc[idx_min]['S_HB']\r\n S_TOD = df.loc[idx_min]['S_TOD']\r\n S_land = Prcv_min * 1e4 / df.loc[idx_min]['land_prod']\r\n mins.append([idx_min,zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av,Arcv, eta_rcv,S_TOD,S_HB,S_land])\r\n \r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n Qavgs = np.arange(0.5,2.1,0.25)\r\n for Q_av in Qavgs:\r\n df2 = df[(df.Q_avg_i==Q_av)]\r\n df2.drop_duplicates(subset=['Prcv','zf','fzv','Q_avg_i'],inplace=True)\r\n # df2.drop_duplicates(inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,lw=3, label=r'${:.2f} MW/m^2$'.format(Q_av))\r\n \r\n ax1.scatter([Prcv_min],[LCOH_min],lw=3,c='red',marker='*',s=200,label='Design')\r\n y1,y2 = 20,30\r\n ax1.plot([Prcv_min,Prcv_min],[y1,y2],lw=2,c='red',ls=':')\r\n # ax1.set_title(r'Min LCOH for tower $z_{{f}}={:.1f}$'.format(zf),fontsize=fs)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.set_xlim(0,40)\r\n ax1.set_ylim(y1,y2)\r\n # ax1.plot(Prcvs,LCOHs,lw=3,c='mediumblue',ls='--',label='min(LCOH)')\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.legend(loc=1,bbox_to_anchor=(1.35, 1.00),fontsize=fs-2)\r\n ax1.grid()\r\n plt.show()\r\n fig.savefig(fldr_rslts+'LCOH_Prcv_Qavg_zf_{:.0f}m.png'.format(zf), bbox_inches='tight')\r\n\r\nmins = pd.DataFrame(mins,columns=('idx_min', 'zf', 'Prcv', 'LCOH', 'Nhel', 'eta_SF', 'fzv', 'Q_av', 'Arcv', 'eta_rcv', 'S_TOD', 'S_HB', 'S_land'))\r\n\r\n# mins.loc[7,'Prcv'] = 21\r\n# mins.loc[8,'Prcv'] = 23\r\n\r\ndef func1_2var(X, *params):\r\n zf, Q_av = X['zf'],X['Q_av']\r\n A,b = params\r\n return A*Q_av*np.exp(b*zf)\r\n\r\nX = mins[['zf','Q_av']]\r\nY = mins.Prcv\r\np0 = (1., 0.05)\r\ncoefs, covariance = spo.curve_fit( func1_2var, X, Y, maxfev=10000, p0=p0)\r\nYc = func1_2var(X,*coefs)\r\nr2 = 1 - (np.sum((Y - Yc)**2) / np.sum((Y-np.mean(Y))**2))\r\nA,b = coefs\r\nprint(A,b,r2)\r\n\r\n\r\ndef func2(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n\r\nX2 = mins.zf\r\nY2 = mins.Prcv\r\np0 = (1., 0.05)\r\ncoefs, covariance = spo.curve_fit( func2, X2, Y2, maxfev=10000, p0=p0)\r\nYc2 = func2(X2,*coefs)\r\nr2 = 1 - (np.sum((Y2 - Yc2)**2) / np.sum((Y2-np.mean(Y2))**2))\r\nA2,b2 = coefs\r\nprint(A2,b2,r2)\r\n\r\n\r\ndef func3(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\n\r\nX3 = mins.zf\r\nY3 = mins.LCOH\r\np0 = (10., 0.05, 20.)\r\ncoefs_LCOH, covariance = spo.curve_fit( func3, X3, Y3, maxfev=10000, p0=p0)\r\nYc3 = func3(X3,*coefs_LCOH)\r\nr2 = 1 - (np.sum((Y3 - Yc3)**2) / np.sum((Y3-np.mean(Y3))**2))\r\nA3,b3,c3 = coefs_LCOH\r\nprint(A3,b3,c3,r2)\r\n\r\nQavs = mins.Q_av\r\nmsizes = 100*mins.Q_av**2\r\nsmin = 30\r\nsmax = 300\r\nQmin = 0.5\r\nQmax = 1.25\r\nmsizes = [smin+(smax-smin)*(aux-Qmin)/(Qmax-Qmin) for aux in Qavs]\r\n\r\nfig, ax1 = plt.subplots(figsize=(9,6))\r\nax2 = ax1.twinx()\r\n# ax1.plot(mins.zf,mins.LCOH,lw=3, c='mediumblue',marker='o',markersize=15,label='LCOH')\r\nax1.scatter(mins.zf, mins.LCOH,lw=3, c=cLCOH, marker='o', s=150, label='LCOH')\r\nax1.plot([],[],lw=3, c=cPrcv, marker='s',markersize=15,label='Receiver Power')\r\nax2.scatter(mins.zf,mins.Prcv, c=cPrcv, marker='s', s=150)\r\n\r\nax2.plot(X2,Yc2,lw=3, c=cPrcv, ls=':')\r\nax1.plot(X3,Yc3,lw=3, c=cLCOH, ls=':')\r\n\r\nax2.annotate(r'$P_{{rcv}}={:.1f}e^{{{:.3f}z_f}}$'.format(A2,b2),(Xc[-1]-20,Yc.iloc[-1]-2),c=cPrcv,fontsize=fs)\r\nax1.annotate(r'${:.1f}+{:.1f}e^{{-{:.3f}z_f}}$'.format(c3,A3,b3),(X3.iloc[-1]-20,Yc3.iloc[-1]+1),c=cLCOH,fontsize=fs-2)\r\n\r\n# ax2.scatter([],[],s=msizes[0], c=cPrcv,marker='s', label=r'$0.75 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[1], c=cPrcv,marker='s', label=r'$1.00 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[3], c=cPrcv,marker='s', label=r'$1.25 MW/m^2$')\r\n# ax2.scatter([],[],s=msizes[11], c=cPrcv, marker='s', label=r'$1.50 MW/m^2$')\r\n\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Minimum LCOH $(USD/MW_{th})$',fontsize=fs)\r\nax2.set_ylabel(r'Optimal Receiver Power $(MW_{th})$',fontsize=fs)\r\n\r\nax2.spines['left'].set_color(cLCOH)\r\nax2.spines['right'].set_color(cPrcv)\r\nax1.tick_params(axis='y', colors=cLCOH,size=10)\r\nax2.tick_params(axis='y', colors=cPrcv,size=10)\r\nax1.yaxis.label.set_color(cLCOH)\r\nax2.yaxis.label.set_color(cPrcv)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax2.tick_params(axis='both', which='major', labelsize=fs-2)\r\n\r\n# ax1.set_title(r'Min LCOH for towers heights and average radiation flux. FINAL!',fontsize=fs)\r\n# ax1.set_xlim(25,65)\r\nax1.set_ylim(y1,y2)\r\n# ax2.set_ylim(0,30)\r\nax1.legend(bbox_to_anchor=(0.0,-0.25), loc=\"lower left\",fontsize=fs-2,ncol=2)\r\n# ax2.legend(bbox_to_anchor=(0.4,-0.35), loc=\"lower left\",fontsize=fs-4,ncol=2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_Prcv.png', bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n# Function for Q_av\r\ndef func4(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c - A*np.exp(-x*b)\r\nX4 = mins.zf\r\nY4 = mins.Q_av\r\np0 = (1., 0.05, 1.)\r\ncoefs, covariance = spo.curve_fit( func4, X4, Y4, maxfev=10000, p0=p0)\r\nYc4 = func4(X4,*coefs)\r\nr2 = 1 - (np.sum((Y4 - Yc4)**2) / np.sum((Y4-np.mean(Y4))**2))\r\nA4,b4,c4 = coefs\r\nprint(A4,b4,c4,r2)\r\n\r\ncQavg = 'darkgreen'\r\nfig, ax1 = plt.subplots(figsize=(6,4))\r\nax1.scatter(mins.zf,mins.Q_av,s=100,c=cQavg)\r\nax1.plot(X4,Yc4,lw=3, c=cQavg, ls=':',label=r'${:.2f}-{:.2f}e^{{-{:.3f}z_f}}$'.format(c4,A4,b4))\r\nax1.legend(loc=0,fontsize=fs-2)\r\n\r\nax1.set_xlim(18,77)\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Optimal $Q_{avg} (MW_{th}/m^2)$',fontsize=fs)\r\nax1.spines['left'].set_color(cQavg)\r\nax1.tick_params(axis='y', colors=cQavg,size=10)\r\nax1.yaxis.label.set_color(cQavg)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_Qavg.png', bbox_inches='tight')\r\nplt.show()\r\n\r\n# Function for fzv\r\ndef func5(x, *params):\r\n A,b,c = params\r\n # return c+A/x**b\r\n return c+A*np.exp(-x*b)\r\nX5 = mins.zf\r\nY5 = mins.fzv\r\np0 = (10., 0.05, 20.)\r\ncoefs, covariance = spo.curve_fit( func5, X5, Y5, maxfev=10000, p0=p0)\r\nYc5 = func5(X5,*coefs)\r\nr2 = 1 - (np.sum((Y5 - Yc5)**2) / np.sum((Y5-np.mean(Y5))**2))\r\nA5,b5,c5 = coefs\r\nprint(A5,b5,c5,r2)\r\n\r\ncfzv = 'darkviolet'\r\nfig, ax1 = plt.subplots(figsize=(6,4))\r\nax1.scatter(mins.zf,mins.fzv,s=100,c=cfzv)\r\nax1.plot(X5,Yc5,lw=3, c=cfzv, ls=':',label=r'${:.2f}+{:.2f}e^{{-{:.3f}z_f}}$'.format(c5,A5,b5))\r\nax1.legend(loc=0,fontsize=fs-2)\r\n\r\nax1.set_xlim(18,77)\r\nax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\nax1.set_ylabel(r'Optimal $f_{zv} (-)$',fontsize=fs)\r\nax1.spines['left'].set_color(cfzv)\r\nax1.tick_params(axis='y', colors=cfzv,size=10)\r\nax1.yaxis.label.set_color(cfzv)\r\nax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\nax1.grid()\r\nfig.savefig(fldr_rslts+'FINAL_LCOH_zf_fzv.png', bbox_inches='tight')\r\nplt.show()\r\n\r\nzf = 50\r\nPrcv = func2(zf, *[A2,b2])\r\nLCOH = func3(zf, *[A3,b3,c3])\r\nQavg = func4(zf, *[A4,b4,c4])\r\nfzv = func5(zf, *[A5,b5,c5])\r\nprint(zf,Prcv,LCOH,Qavg,fzv)\r\n\r\n### ADDITIONAL CORRELATIONS\r\ndef func6(x, *params):\r\n A,b = params\r\n return A*np.exp(b*x)\r\n\r\nylabs = {'Nhel':'$N_{hel} (-)$','S_TOD':'$S_{TOD} (m^2)$','S_HB':'$S_{HB} (m^2)$','Arcv':'$A_{rcv} (m^2)$','S_land':'$S_{land} (m^2)$'}\r\n\r\nfor vary in ['Nhel','S_TOD','S_HB','Arcv','S_land']:\r\n X6 = mins.zf\r\n Y6 = mins[vary]\r\n p0 = (1., 0.05)\r\n coefs, covariance = spo.curve_fit( func6, X6, Y6, maxfev=10000, p0=p0)\r\n Yc6 = func2(X6,*coefs)\r\n r2 = 1 - (np.sum((Y6 - Yc6)**2) / np.sum((Y6-np.mean(Y6))**2))\r\n A6,b6 = coefs\r\n \r\n fig, ax1 = plt.subplots(figsize=(6,4))\r\n ax1.scatter(mins.zf,mins[vary],s=100,c=cLCOH)\r\n ax1.plot(X6,Yc6,lw=3, c=cLCOH, ls=':',label=r'${:.2f}e^{{{:.3f}z_f}}$'.format(A6,b6))\r\n ax1.legend(loc=0,fontsize=fs-2)\r\n\r\n ax1.set_xlim(18,77)\r\n ax1.set_xlabel('Tower height $(m)$',fontsize=fs)\r\n ax1.set_ylabel(r'Optimal {}'.format(ylabs[vary]),fontsize=fs)\r\n ax1.spines['left'].set_color(cLCOH)\r\n ax1.tick_params(axis='y', colors=cLCOH,size=10)\r\n ax1.yaxis.label.set_color(cLCOH)\r\n ax1.tick_params(axis='both', which='major', labelsize=fs-2)\r\n ax1.grid()\r\n # fig.savefig(fldr_rslts+'FINAL_LCOH_zf_fzv.png', bbox_inches='tight')\r\n plt.show()\r\n \r\n print(vary,A6,b6,r2)\r\n\r\nsys.exit()\r\n#####################################\r\n#%%% LCOH MAP\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\n\r\n\r\n\r\n\r\n#%%% INFLUENCE OF RADIATION FLUX (OLD)\r\n\r\nfile_rslts = 'Optim_TPR_0D_quick.csv'\r\ndf = pd.read_csv(file_rslts,index_col=0)\r\ndf = df.round({'Q_av':2})\r\nzfs = [50]\r\nfor zf in zfs:\r\n df = pd.read_csv(file_rslts,index_col=0)\r\n df = df.round({'Q_av':2})\r\n pd.set_option('display.max_columns', None)\r\n df = df[(df.zf==zf)]\r\n df.sort_values(['Q_av','Prcv'],inplace=True)\r\n \r\n \r\n mins = []\r\n fig, ax1 = plt.subplots(figsize=(9,6))\r\n Q_avgs = df.Q_avg_i.unique()[:-2]\r\n for Q_av in Q_avgs:\r\n df2 = df[(df.Q_avg_i==Q_av)]\r\n df2.drop_duplicates(subset=['Prcv','zf','Q_avg_i'],inplace=True)\r\n # df2.drop_duplicates(inplace=True)\r\n ax1.plot(df2.Prcv,df2.LCOH,label=r'${:.2f} MW/m^2$'.format(Q_av))\r\n \r\n idx_min = df2.LCOH.idxmin()\r\n Prcv_min = df2.loc[idx_min]['Prcv']\r\n LCOH_min = df2.loc[idx_min]['LCOH']\r\n Nhel_min = df2.loc[idx_min]['N_hel']\r\n etaSF_min = df2.loc[idx_min]['eta_SF']\r\n fzv_min = df2.loc[idx_min]['fzv']\r\n mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av])\r\n \r\n # bounds = (df2.Prcv.min(),df2.Prcv.max())\r\n # args = (df2.Prcv,df2.LCOH)\r\n # res = spo.minimize_scalar(f_minPoly, bounds=bounds, args=args, method='bounded')\r\n # Prcv_min = res.x\r\n # LCOH_min = f_minPoly(Prcv_min,*args)\r\n # Nhel_min = spi.interp1d(df2.Prcv, df2.N_hel, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # etaSF_min = spi.interp1d(df2.Prcv, df2.eta_SF, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # fzv_min = spi.interp1d(df2.Prcv, df2.fzv, kind='cubic',fill_value='extrapolate')(Prcv_min)\r\n # mins.append([zf,Prcv_min,LCOH_min,Nhel_min,etaSF_min,fzv_min,Q_av])\r\n \r\n # mins = df.loc[mins]\r\n mins = pd.DataFrame(mins,columns=('zf','Prcv','LCOH','Nhel','eta_SF','fzv','Q_av'))\r\n mins.sort_values(by='Q_av',inplace=True)\r\n # args = (mins.Prcv,mins.LCOH)\r\n # Prcvs = np.arange(mins.Prcv.min(),mins.Prcv.max(),0.1)\r\n # LCOHs = f_minPoly(Prcvs,*args)\r\n ax1.plot(mins.Prcv,mins.LCOH,c='k',lw=2,marker='s',label='min(LCOH)')\r\n ax1.scatter(mins.Prcv,mins.LCOH,c='mediumblue',marker='s',s=100)\r\n \r\n ax1.set_ylim(20,35)\r\n # ax1.plot(Prcvs,LCOHs,lw=3,c='mediumblue',ls='--',label='min(LCOH)')\r\n ax1.set_ylabel(r'LCOH $(USD/MW_t)$',fontsize=fs)\r\n ax1.set_xlabel('Receiver Power $(MW_t)$',fontsize=fs)\r\n ax1.legend(loc=1)\r\n ax1.grid()\r\n plt.show()\r\n # fig.savefig('LCOH_Prcv_Qavg_zf_{:.0f}m.png'.format(zf), bbox_inches='tight')\r\n\r\n","repo_name":"DavidSaldivia/BDR_MCRT","sub_path":"6_Thermal_Subsys_Optim/0-BD-TPR_Optim_Plots_Thesis_vF.py","file_name":"0-BD-TPR_Optim_Plots_Thesis_vF.py","file_ext":"py","file_size_in_byte":17687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"440200961","text":"from django.shortcuts import render, HttpResponse, redirect\nimport datetime\nfrom django.contrib import messages\nfrom .models import Show\n\n# Create your views here.\ndef index(request):\n return redirect('/shows')\n\ndef shows(request):\n context = {\n \"shows\" : Show.objects.all()\n }\n return render(request, \"shows.html\", context)\n\ndef new_show(request):\n\n return render(request, \"shows_new.html\")\n\ndef show_create(request):\n errors = Show.objects.basic_validator(request.POST)\n if len(errors) > 0:\n for k, v in errors.items():\n messages.error(request, v)\n return redirect(\"/shows/new\")\n else:\n show = Show.objects.create(\n title = request.POST['title'],\n network = request.POST['network'],\n release_date = request.POST['release_date'],\n description = request.POST['description'],\n )\n return redirect(f\"/shows/{show.id}\")\n\ndef show_display(request, show_id):\n context = {\n \"show\": Show.objects.get(id=show_id)\n }\n return render(request, \"show_display.html\", context)\n\ndef show_update(request, show_id):\n errors = Show.objects.basic_validator(request.POST)\n if len(errors) > 0:\n for k, v in errors.items():\n messages.error(request, v)\n return redirect(f\"/shows/{show_id}/edit\")\n else:\n show = Show.objects.filter(pk=show_id).update(\n title = request.POST['title'],\n network = request.POST['network'],\n release_date = request.POST['release_date'],\n description = request.POST['description'],\n )\n return redirect(f\"/shows/{show_id}\")\n\ndef show_edit(request, show_id):\n show = Show.objects.get(id=show_id)\n show.release_date = show.release_date.strftime('%Y-%m-%d')\n context = {\n \"show\" : show\n }\n return render(request, \"shows_edit.html\", context)\n\ndef show_delete(request, show_id):\n show = Show.objects.get(id=show_id).delete()\n return redirect(\"/shows\")","repo_name":"stormysea22/semi_restful_tv_shows","sub_path":"show_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72324638245","text":"#!/usr/bin/env python3\nimport os\n\nfrom sys import argv\nfrom subprocess import run\n\ndef create_and_go_to_folder(folder: str):\n os.makedirs(folder, exist_ok=True)\n os.chdir(folder)\n\ndef create(filename: str = None, data: str = None) -> None:\n print(f\"creating {filename}...\")\n with open(filename, 'w') as writer:\n writer.write(data)\n print(f'displaying contents of {filename}...')\n with open(filename) as reader:\n print(reader.read())\n\ndef create_module_main_tf():\n create(\n 'main.tf',\n '''provider \"aws\" {\n region = var.region\n}\n\nresource \"aws_vpc\" \"this\" {\n cidr_block = \"10.0.0.0/16\"\n}\n\nresource \"aws_subnet\" \"this\" {\n vpc_id = aws_vpc.this.id\n cidr_block = \"10.0.1.0/24\"\n}\n\ndata \"aws_ssm_parameter\" \"this\" {\n name = \"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2\"\n}''')\n\ndef create_module_variables_tf():\n create(\n 'variables.tf',\n '''variable \"region\" {\n type = \"string\"\n default = \"us-east-1\"\n}''')\n\ndef create_module_outputs_tf():\n create(\n 'outputs.tf',\n '''output \"subnet_id\" {\n value = aws_subnet.this.id\n}\n\noutput \"ami_id\" {\n value = data.aws_ssm_parameter.this.value\n}''')\n\ndef create_project_main_tf():\n create(\n 'main.tf',\n '''provider \"aws\" {\n region = var.main_region\n}\n\nmodule \"vpc\" {\n source = \"./modules/vpc\"\n region = var.main_region\n}\n\nresource \"aws_instance\" \"my-instance\" {\n ami = module.vpc.ami_id\n subnet_id = module.vpc.subnet_id\n instance_type = \"t2.micro\"\n}''')\n\ndef create_project_variables_tf():\n create(\n 'variables.tf',\n '''variable \"main_region\" {\n type = string\n default = \"us-east-1\"\n}'''\n )\n\ndef create_project_outputs_tf():\n create(\n 'outputs.tf',\n '''output \"PrivateIP\" {\n description = \"Private IP of EC2 instance\"\n value = aws_instance.my-instance.private_ip\n}''')\n\ndef terraform(command: str) -> None:\n print(\n run(\n f'terraform {command}', shell=True,\n #capture_output=True\n )\n )\n\ndef directory():\n return f'{argv[1]}/modules/vpc'\n\nif __name__ == \"__main__\":\n print(f\"Creating structure {directory()}\")\n create_and_go_to_folder(directory())\n print(os.getcwd())\n create_module_main_tf()\n create_module_variables_tf()\n create_module_outputs_tf()\n print(os.getcwd())\n os.chdir('../..')\n print(os.listdir())\n print('Writing Main Terraform Project Code')\n create_project_main_tf()\n create_project_variables_tf()\n create_project_outputs_tf()\n terraform('fmt -recursive')\n terraform('init')\n terraform('validate')\n terraform('plan')","repo_name":"jadecobra/terraform","sub_path":"associate/25_create_terraform_module.py","file_name":"25_create_terraform_module.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1034658765","text":"#https://www.hackerrank.com/challenges/strange-advertising/problem?isFullScreen=true\n\nimport sys\n\nn = int(sys.stdin.readline())\n\nshared=5\nliked=0\ncumulative=0\n\nfor i in range(n):\n liked = shared//2\n cumulative+=liked\n shared = liked *3\n \nprint(cumulative)","repo_name":"JeongHooon-Lee/Hackerrank_Python","sub_path":"Easy/CPTango/Day15/Day15-9.py","file_name":"Day15-9.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27032319784","text":"import matplotlib\nimport yaml\n\nmatplotlib.use('Agg')\nmatplotlib.rcParams['font.size'] = 10\nmatplotlib.rcParams['font.family'] = 'serif'\nimport pandas as pd\nfrom scipy import stats\nimport os\nfrom utils.ParameterParser import ParameterParser\nfrom utils.CellOverlaps import CellOverlaps\nfrom utils.bayes_gate import ModelTree\nfrom utils.input import *\nimport utils.utils_load_data as dh\nimport torch.nn as nn\n\ndefault_hparams = {\n 'logistic_k': 100,\n 'logistic_k_dafi': 10000,\n 'regularization_penalty': 0,\n 'negative_box_penalty': 0.0,\n 'negative_proportion_default': 0.0001,\n 'positive_box_penalty': 0.0,\n 'corner_penalty': .0,\n 'feature_diff_penalty': 0.,\n 'gate_size_penalty': .0,\n 'gate_size_default': (0.5, 0.5),\n 'load_from_pickle': True,\n 'dafi_init': False,\n 'optimizer': \"Adam\", # or Adam, SGD\n 'loss_type': 'logistic', # or MSE\n 'n_epoch_eval': 100,\n 'n_mini_batch_update_gates': 50,\n 'learning_rate_classifier': 0.05,\n 'learning_rate_gates': 0.05,\n 'batch_size': 10,\n 'n_epoch': 1000,\n 'seven_epochs_for_gate_motion_plot': [0, 50, 100, 200, 300, 400, 500],\n 'test_size': 0.20,\n 'experiment_name': 'default',\n 'random_state': 123,\n 'n_run': 2,\n 'init_type': 'random_corner',\n 'corner_init_deterministic_size': .75,\n 'train_alternate': True,\n 'run_logistic_to_convergence': False,\n 'output': {\n 'type': 'full'\n },\n 'annealing': {\n 'anneal_logistic_k': False,\n 'final_k': 1000,\n 'init_k': 1\n },\n 'two_phase_training': {\n 'turn_on': False,\n 'num_only_log_loss_epochs': 50\n },\n 'plot_params': {\n 'figsize': [10, 10],\n 'marker_size': .01,\n },\n 'use_out_of_sample_eval_data': False,\n 'dictionary_is_broken': True\n}\n\ncolumn_names = ['random_state',\n 'train_accuracy',\n 'eval_accuracy',\n 'overall_accuracy',\n 'train_accuracy_dafi',\n 'eval_accuracy_dafi',\n 'overall_accuracy_dafi',\n 'train_tracker.acc_opt'\n 'eval_tracker.acc_opt',\n 'train_logloss',\n 'eval_logloss',\n 'overall_logloss',\n 'train_logloss_dafi',\n 'eval_logloss_dafi',\n 'overall_logloss_dafi',\n 'train_auc',\n 'eval_auc',\n 'overall_auc',\n 'train_auc_dafi',\n 'eval_auc_dafi',\n 'overall_auc_dafi',\n 'train_brier_score',\n 'eval_brier_score',\n 'overall_brier_score',\n 'train_brier_score_dafi',\n 'eval_brier_score_dafi',\n 'overall_brier_score_dafi',\n 'run_time']\n\n# generate scatter plots of a method and dafi gates\nmetric_dict = ['accuracy', 'logloss', 'auc', 'brier_score']\n# model_dict = ['default', 'dafi_init', 'dafi_regularization', 'default_non_alternate', 'emp_regularization_off',\n# 'gate_size_regularization_off']\nmodel_dict = ['default']\n\n\n# load from csv\ndef scatter_vs_dafi_feature(dataname, method_name, metric_name, ax):\n filename = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name)\n if metric_name not in metric_dict:\n raise ValueError('%s is not in metric_dict.' % metric_name)\n df = pd.read_csv(filename, header=None, names=column_names)\n # stats test\n print(stats.ttest_rel(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name]))\n print(stats.ks_2samp(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name]))\n\n ax.scatter(df['eval_%s' % metric_name], df['eval_%s_dafi' % metric_name], s=5)\n ax.set_xlim(min(min(df['eval_%s' % metric_name]), min(df['eval_%s_dafi' % metric_name])), \\\n max(max(df['eval_%s' % metric_name]), max(df['eval_%s_dafi' % metric_name])))\n ax.set_ylim(min(min(df['eval_%s' % metric_name]), min(df['eval_%s_dafi' % metric_name])), \\\n max(max(df['eval_%s' % metric_name]), max(df['eval_%s_dafi' % metric_name])))\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n return ax\n\n\ndef scatter_methods(dataname, method_name_1, method_name_2, metric_name):\n # todo: need to make df of different methods to plot of same length\n \"\"\"\n\n :param dataname:\n :param method_name_1:\n :param method_name_2:\n :param metric_name:\n :return:\n \"\"\"\n filename_1 = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name_1)\n filename_2 = '../output/%s/results_cll_4D.csv' % (dataname + '_' + method_name_2)\n if metric_name not in metric_dict:\n raise ValueError('%s is not in metric_dict.' % metric_name)\n df_1 = pd.read_csv(filename_1, header=None, names=column_names)\n df_2 = pd.read_csv(filename_2, header=None, names=column_names)\n\n figname_train = '../fig/%s/%s_vs_%s_%s_train.png' % (dataname, method_name_1, method_name_2, metric_name)\n fig = plt.figure(figsize=(3, 3))\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(df_1['train_%s' % metric_name], df_2['train_%s' % metric_name], s=5)\n ax.set_xlabel(method_name_1)\n ax.set_ylabel(method_name_2)\n if metric_name in ['accuracy', 'auc', 'brier_score']:\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n elif metric_name == 'logloss':\n ax.set_xlim(0.0, 5.0)\n ax.set_ylim(0.0, 5.0)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n fig.tight_layout()\n plt.savefig(figname_train)\n\n figname_test = '../fig/%s/%s_vs_%s_%s_test.png' % (dataname, method_name_1, method_name_2, metric_name)\n fig = plt.figure(figsize=(3, 3))\n ax = fig.add_subplot(1, 1, 1)\n ax.scatter(df_1['eval_%s' % metric_name], df_2['eval_%s' % metric_name], s=5)\n ax.set_xlabel(method_name_1)\n ax.set_ylabel(method_name_2)\n if metric_name in ['accuracy', 'auc', 'brier_score']:\n ax.set_xlim(0.0, 1.0)\n ax.set_ylim(0.0, 1.0)\n ax.plot()\n elif metric_name == 'logloss':\n ax.set_xlim(0.0, 5.0)\n ax.set_ylim(0.0, 5.0)\n ax.plot(ax.get_xlim(), ax.get_ylim(), ls=\"--\", c=\".3\")\n ax.set_title(metric_name)\n fig.tight_layout()\n plt.savefig(figname_test)\n\n\ndef combine_results_into_one_csv(directory_prefix, output_dir, y_data_path, corner_reg_grid=[0., .1, .2, .3, .4, .5],\n gate_size_reg_grid=[0., .1, .2, .3, .4, .5], decimal_points_in_dir_name=2):\n # Looks like the data is not shuffled assuming the test_size hparam is set to 0\n # Other wise this wont be matched up properly\n # I have two sets of results: one with corner reg 0->.5 and the other with corner reg\n # taking values in [.001, .050]\n str_identifiers = []\n features_list = []\n avg_results_dicts = []\n weights_list = []\n for c, corner_reg in enumerate(corner_reg_grid):\n for gate_size_reg in gate_size_reg_grid:\n if directory_prefix == '../output/logreg_to_conv_grid_search':\n if decimal_points_in_dir_name == 2:\n str_identifier = '_corner=%.2f_gate_size=%.2f' % (corner_reg, gate_size_reg)\n else:\n str_identifier = '_corner=%.3f_gate_size=%.3f' % (corner_reg, gate_size_reg)\n elif directory_prefix == '../output/two_phase_logreg_to_conv_grid_search_gate_size=':\n str_identifier = '%.2f' % gate_size_reg\n directory = directory_prefix + str_identifier\n # include Dafi results as the first column\n if c == 0:\n # dafi_features = get_features(os.path.join(directory, 'features_dafi.csv'))\n # str_identifiers.append('DAFI')\n # features_list.append(dafi_features)\n # get DAFI outputs here\n # avg_results_dicts.append(None)\n # weights_list.append(None)\n pass\n\n avg_results_dict = avg_results(os.path.join(directory, 'results_cll_4D.csv'))\n features = get_features(os.path.join(directory, 'features_model.csv'))\n weights = get_weights(os.path.join(directory, 'model_classifier_weights.csv'))\n\n avg_results_dicts.append(avg_results_dict)\n features_list.append(features)\n weights_list.append(weights)\n\n str_identifiers.append(str_identifier)\n with open(y_data_path, 'rb') as f:\n labels = pickle.load(f)\n write_concatenated_results(output_dir, avg_results_dicts, features_list, weights_list, str_identifiers, labels)\n fig, axes = plt.subplots(1, 2, sharey=True)\n feats_noreg = np.array(features_list[0])\n labels = np.array(labels)\n features_pos = feats_noreg[labels == 0]\n features_neg = feats_noreg[labels == 1]\n axes[0].boxplot(features_pos)\n axes[1].boxplot(features_neg)\n plt.savefig(os.path.join(output_dir, 'feats_box_plot_noreg.png'))\n\n\ndef write_concatenated_results(output_dir, avg_results_dicts, features_list, weights_list, str_identifiers, labels):\n with open(os.path.join(output_dir, 'concatenated_results.csv'), 'w') as f:\n # get the column labels which correspond to different settings\n col_labels = ''\n for s, string in enumerate(str_identifiers):\n if s == len(str_identifiers) - 1:\n col_labels += string + ', label' + '\\n'\n continue\n col_labels += string + ','\n f.write(col_labels)\n num_samples = len(features_list[0]) # each feature is one sample in this case\n for row in range(num_samples):\n for column in range(len(features_list)):\n feature = features_list[column][row]\n if column == len(features_list) - 1:\n f.write(str(feature) + ',%s' % (labels[row]) + '\\n') # assumes labels are matched up\n continue\n f.write(str(feature) + ',')\n\n\ndef get_weights(weights_path):\n with open(weights_path, 'r') as f:\n last_run_weights = f.readlines()[-1][0:-2] # get rid of newline char\n last_run_weights = [float(last_run_weights.split(',')[0]), float(last_run_weights.split(',')[1])]\n return last_run_weights\n\n\ndef get_features(features_path):\n with open(features_path, 'r') as f:\n lines = f.readlines()\n # only giving Padhraic the last run for now\n # have 35 features/samples, and the last line is blank\n lines_last_run = lines[-36:-1]\n feats = [float(feat_str[0:-1]) for feat_str in lines_last_run]\n\n return feats\n\n\ndef avg_results(results_path):\n with open(results_path, 'r') as f:\n lines = f.readlines()\n # only want odd lines which have actual integers\n lines_with_results = [line.split(',') for l, line in enumerate(lines) if l % 2 == 1]\n accs = [float(split_line[1]) for split_line in lines_with_results]\n log_losses = [float(split_line[2]) for split_line in lines_with_results]\n\n return {'avg_acc': sum(accs) / len(accs),\n 'avg_log_loss': sum(log_losses) / len(log_losses)}\n\n\ndef make_and_write_concatenated_8d_data_with_dafi_gate_flags_and_ids(path_to_hparams, savepath=None):\n concatenated_data = make_data_with_dafi_gate_flags_and_ids(path_to_hparams)\n if savepath:\n savepath = savepath\n else:\n savepath = '../data/concatenated_8d_data_with_dafi_filtering_indicators.csv'\n write_concatenated_8d_data_with_dafi_gate_flags_and_ids(concatenated_data, savepath)\n\n\ndef make_and_write_catted_data(path_to_x_list, path_to_y_list, savepath):\n catted_data = make_catted_data(path_to_x_list, path_to_y_list)\n write_catted_data(catted_data, savepath)\n return catted_data\n\n\ndef write_catted_data(catted_data, savepath):\n COL_NAMES = (\n 'FSC-A',\n 'SSC-H',\n 'CD45',\n 'SSC-A',\n 'CD5',\n 'CD19',\n 'CD10',\n 'CD79b',\n 'sample_ids',\n 'labels'\n )\n\n with open(savepath, 'w') as f:\n f.write('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n' % COL_NAMES)\n for cell_row in catted_data:\n f.write('%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f\\n' % tuple(cell_row))\n\n\ndef make_catted_data(path_x_list, path_y_list):\n with open(path_x_list, 'rb') as f:\n x_list = pickle.load(f)\n with open(path_y_list, 'rb') as f:\n y_list = pickle.load(f)\n\n for sample_id, (x, y) in enumerate(zip(x_list, y_list)):\n x_with_sample_id = np.hstack([x, sample_id * np.ones([x.shape[0], 1])])\n x_with_sample_id_and_label = np.hstack([x_with_sample_id, y * np.ones([x.shape[0], 1])])\n if sample_id == 0.:\n catted_data = x_with_sample_id_and_label\n else:\n catted_data = np.concatenate([catted_data, x_with_sample_id_and_label])\n return catted_data\n\n\ndef write_concatenated_8d_data_with_dafi_gate_flags_and_ids(concatenated_data, savepath):\n COL_NAMES = (\n 'FSC-A',\n 'SSC-H',\n 'CD45',\n 'SSC-A',\n 'CD5',\n 'CD19',\n 'CD10',\n 'CD79b',\n 'sample_ids',\n 'labels',\n 'cell_ids',\n 'In Dafi Gate1',\n 'In Dafi Gate2',\n 'In Dafi Gate3',\n 'In Dafi Gate4',\n )\n with open(savepath, 'w') as f:\n f.write('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s\\n' % COL_NAMES)\n for cell_row in concatenated_data:\n for i in range(4):\n if cell_row[-(i + 1)] == True:\n cell_row[-(i + 1)] = 1\n else:\n cell_row[-(i + 1)] = 0\n f.write(\n '%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %d, %d, %d, %d\\n' % tuple(cell_row))\n\n\ndef parse_hparams(path_to_hparams):\n hparams = default_hparams\n with open(path_to_hparams, \"r\") as f_in:\n yaml_params = yaml.safe_load(f_in)\n hparams.update(yaml_params)\n hparams['init_method'] = \"dafi_init\" if hparams['dafi_init'] else \"random_init\"\n if hparams['train_alternate']:\n hparams['n_epoch_dafi'] = hparams['n_epoch'] // hparams['n_mini_batch_update_gates'] * (\n hparams['n_mini_batch_update_gates'] - 1)\n else:\n hparams['n_epoch_dafi'] = hparams['n_epoch']\n\n print(hparams)\n return hparams\n\n\ndef load_output(path_to_hparams):\n output = {}\n hparams = ParameterParser(path_to_hparams).parse_params()\n output['hparams'] = hparams\n exp_name = hparams['experiment_name']\n model_checkpoint_path = '../output/%s/model_checkpoints.pkl' \\\n % hparams['experiment_name']\n\n with open(model_checkpoint_path, 'rb') as f:\n model_checkpoint_dict = pickle.load(f)\n # note that the initial cuts stored in this input\n # object are not the cuts that this function uses\n # this input object is only used here because the dafi gates\n # are saved inside it\n output['cll_1p_full_input'] = Cll8d1pInput(hparams)\n\n output['dafi_tree'] = ModelTree(output['cll_1p_full_input'].reference_tree,\n logistic_k=hparams['logistic_k_dafi'],\n negative_box_penalty=hparams['negative_box_penalty'],\n positive_box_penalty=hparams['positive_box_penalty'],\n corner_penalty=hparams['corner_penalty'],\n gate_size_penalty=hparams['gate_size_penalty'],\n init_tree=None,\n loss_type=hparams['loss_type'],\n gate_size_default=hparams['gate_size_default'])\n\n output['models_per_iteration'] = [\n model_checkpoint_dict[iteration]\n for iteration in\n hparams['seven_epochs_for_gate_motion_plot']\n ]\n # Checkpoint dictionary is messed up when saving\n # since str(id(node)) for each node is changed\n # (pickling is out of place and makes a new object with a\n # new id. This only works with a chain graph to make the ids match\n # the saved object ids\n fixed_models_per_iteration = []\n for model in output['models_per_iteration']:\n cur_node = model.root\n fixed_children_dict = {}\n num_nodes = len(model.children_dict.keys())\n for key, item in model.children_dict.items():\n fixed_children_dict[str(id(cur_node))] = nn.ModuleList(item)\n if not len(model.children_dict[key]) == 0:\n cur_node = model.children_dict[key][0]\n model.children_dict = nn.ModuleDict(fixed_children_dict)\n\n print('root id is: ', str(id(output['models_per_iteration'][0].root)))\n keys = [key for key in output['models_per_iteration'][0].children_dict.keys()]\n print('keys are: ', output['models_per_iteration'][0].children_dict.keys())\n print('id of root in new dict is: ', str(id(output['models_per_iteration'][0].children_dict[keys[0]])))\n print('init model is: ', output['models_per_iteration'][0])\n # call split on input here if theres a bug\n return output\n\n\ndef write_ranked_features_model_dafi(path_to_hparams):\n output = load_output(path_to_hparams)\n hparams = output['hparams']\n model = output['models_per_iteration'][-1]\n dafi = output['dafi_tree']\n x_list = output['cll_1p_full_input'].x_train\n labels = output['cll_1p_full_input'].y_train\n features_model = []\n feature_dafi = []\n for idx, x in enumerate(x_list):\n print(x.shape)\n model_results = model(x)\n dafi_results = dafi(x)\n features_model.append([model_results['leaf_probs'][0], idx, labels[idx]])\n features_dafi.append([dafi_results['leaf_probs'][0], idx, labels[idx]])\n features_model = np.array(features_model).sort(axis=0)\n features_dafi = np.array(features_dafi).sort(axis=0)\n savepath = '../output/%s/ranked_features_table' % hparams['experiment_name']\n with open(savepath, 'w') as f:\n f.write(\n 'ranked features from model, sample id, matching label, ranked features from dafi, sample id, matching label\\n')\n for idx, label in enumerate(labels):\n row = (\n features_model[idx][0], features_model[idx][1],\n features_model[idx][2],\n features_dafi[idx][0], features_dafi[idx][1],\n features_dafi[idx][2]\n\n )\n f.write('%.4f, %.4f, %.4f, %.4f, %.4f, %.4f\\n' % row)\n\n\ndef load_from_pickle(path_to_file):\n with open(path_to_file, 'rb') as f:\n loaded_object = pickle.load(f)\n return loaded_object\n\n\ndef make_data_with_dafi_gate_flags_and_ids(path_to_hparams):\n hparams = ParameterParser(path_to_hparams).parse_params()\n\n cll_1p_full_input = Cll8d1pInput(hparams)\n dafi_tree = make_dafi_tree(hparams, cll_1p_full_input)\n x_list = cll_1p_full_input.unnormalized_x_list_of_numpy\n y_list = cll_1p_full_input.y_numpy\n for sample_id, (x, y) in enumerate(zip(x_list, y_list)):\n x_with_sample_id = np.hstack([x, sample_id * np.ones([x.shape[0], 1])])\n x_with_sample_id_and_label = np.hstack([x_with_sample_id, y * np.ones([x.shape[0], 1])])\n # wrote a function to get unique cell ids in this class already\n\n x_with_sample_ids_cell_ids_and_labels = \\\n CellOverlaps(dafi_tree, dafi_tree, [x_with_sample_id_and_label]).data_list_with_ids[0]\n\n # filtered_data = dafi_tree.filter_data(x_with_sample_ids_cell_ids_and_labels)\n flat_gates = [\n [102., 921., 2048., 3891.],\n [921., 2150., 102., 921.],\n [1638., 3891., 2150., 3891.],\n [0, 1228., 0., 1843.]\n ]\n\n flat_ids = dafi_tree.get_flat_ids()\n filtered_data = filter_data(\n x_with_sample_ids_cell_ids_and_labels,\n flat_gates,\n flat_ids\n )\n print(x_with_sample_ids_cell_ids_and_labels[:, -1])\n print(y)\n print(filtered_data[0].shape, x.shape)\n print(filtered_data[1].shape)\n print(filtered_data[2].shape)\n print(filtered_data[3].shape)\n print(filtered_data[4].shape)\n gate_1_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[1][:, -1])\n gate_2_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[2][:, -1])\n gate_3_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[3][:, -1])\n gate_4_flags = np.isin(x_with_sample_ids_cell_ids_and_labels[:, -1], filtered_data[4][:, -1])\n\n x_all_cols = np.hstack(\n [\n x_with_sample_ids_cell_ids_and_labels,\n gate_1_flags[:, np.newaxis], gate_2_flags[:, np.newaxis], gate_3_flags[:, np.newaxis],\n gate_4_flags[:, np.newaxis]\n ]\n )\n\n if sample_id == 0:\n catted_data = x_all_cols\n else:\n catted_data = np.concatenate([catted_data, x_all_cols])\n\n return catted_data\n\n\ndef filter_single_flat_gate(data, gate, ids):\n print(ids)\n filtered_data = dh.filter_rectangle(\n data, ids[0],\n ids[1], gate[0], gate[1],\n gate[2], gate[3]\n )\n return filtered_data\n\n\ndef filter_data(data, flat_gates, flat_ids):\n filtered_data = [data]\n for gate, ids in zip(flat_gates, flat_ids):\n filtered_data.append(\n filter_single_flat_gate(filtered_data[-1], gate, ids)\n )\n return filtered_data\n\n\ndef make_dafi_tree(hparams, cll_1p_full_input):\n dafi_tree = ModelTree(cll_1p_full_input.get_unnormalized_reference_tree(),\n logistic_k=hparams['logistic_k_dafi'],\n negative_box_penalty=hparams['negative_box_penalty'],\n positive_box_penalty=hparams['positive_box_penalty'],\n corner_penalty=hparams['corner_penalty'],\n gate_size_penalty=hparams['gate_size_penalty'],\n init_tree=None,\n loss_type=hparams['loss_type'],\n gate_size_default=hparams['gate_size_default'])\n return dafi_tree\n\n\n# def test_filtered_data_matches_overlap_results():\n# filtered_path = '../output/'\n# overlap_path = ''\n# with open(filtered_path, 'r') as f:\n# cell_rows = f.readlines()\n# with open(overlap_path, 'r') as f:\n# pass\n\n\ndef save_feats_panel1_in_sample(OOS_hparams, model_path, dafi_path):\n with open(model_path, 'rb') as f:\n model = pickle.load(f)\n with open(dafi_path, 'rb') as f:\n dafi = pickle.load(f)\n if torch.cuda.is_available():\n model.cuda(OOS_hparams['device'])\n dafi.cuda(OOS_hparams['device'])\n\n input = Cll8d1pInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model_soft = model.forward_4chain(input.x_train, input.y_train)['leaf_probs'].detach().cpu().numpy()\n feats_model_hard = model.forward_4chain(input.x_train, input.y_train, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi = dafi.forward_4chain(input.x_train, input.y_train, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n\n save_array_feats = np.concatenate(\n [input.y_train.detach().cpu().numpy()[:, np.newaxis], feats_model_soft, feats_model_hard, feats_dafi], axis=1)\n\n header = 'Label,Soft Features Model, Hard Features Model, Hard Features DAFI'\n\n np.savetxt('../output/%s/feats_model_hard_and_soft_IS.csv' % OOS_hparams['experiment_name'], save_array_feats,\n delimiter=',', header=header)\n\n\ndef save_feats_panel1_OOS(OOS_hparams, model_path, dafi_path):\n with open(model_path, 'rb') as f:\n model = pickle.load(f)\n with open(dafi_path, 'rb') as f:\n dafi = pickle.load(f)\n if torch.cuda.is_available():\n model.cuda(OOS_hparams['device'])\n dafi.cuda(OOS_hparams['device'])\n\n input = Cll8d1pInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model_soft = model.forward_4chain(input.x_eval, input.y_eval)['leaf_probs'].detach().cpu().numpy()\n feats_model_hard = model.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi = dafi.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True)[\n 'leaf_probs'].detach().cpu().numpy()\n\n save_array_feats = np.concatenate(\n [input.y_eval.detach().cpu().numpy()[:, np.newaxis], feats_model_soft, feats_model_hard, feats_dafi], axis=1)\n\n header = 'Label,Soft Features Model, Hard Features Model, Hard Features DAFI'\n\n np.savetxt('../output/%s/feats_model_hard_and_soft_OOS.csv' % OOS_hparams['experiment_name'], save_array_feats,\n delimiter=',', header=header)\n\n\ndef save_feats_both_all_data(OOS_hparams, model_both_checkpoints_path, dafi_both_path):\n with open(model_both_checkpoints_path, 'rb') as f:\n model_checkpoints_both = pickle.load(f)\n\n model_both = model_checkpoints_both[hparams['n_epoch']]\n\n with open(dafi_both_path, 'rb') as f:\n dafi_both = pickle.load(f)\n if torch.cuda.is_available():\n model_both.cuda(OOS_hparams['device'])\n dafi_both.cuda(OOS_hparams['device'])\n\n input = CllBothPanelsInput(OOS_hparams)\n # y_train and x_train are all the in sample data for this hparams setting\n feats_model = model_both(input.x_train, input.y_train, device=OOS_hparams['device'])[\n 'leaf_probs'].detach().cpu().numpy()\n print(model_both.linear.weight, model_both.linear.bias)\n print('dafi weights for logistic regressor')\n print(dafi_both.linear.weight, dafi_both.linear.bias)\n feats_dafi = dafi_both(input.x_train, input.y_train, use_hard_proportions=True, device=OOS_hparams['device'])[\n 'leaf_probs'].detach().cpu().numpy()\n\n feats_model_with_labels = np.concatenate([input.y_train.detach().cpu().numpy()[:, np.newaxis], feats_model], axis=1)\n feats_dafi_with_labels = np.concatenate(\n [input.y_train.detach().cpu().numpy()[:, np.newaxis], np.squeeze(feats_dafi)], axis=1)\n np.savetxt('../output/%s/feats_model.csv' % OOS_hparams['experiment_name'], feats_model_with_labels, delimiter=',',\n header='Label, Panel1, Panel2, Panel2')\n np.savetxt('../output/%s/feats_dafi.csv' % OOS_hparams['experiment_name'], feats_dafi_with_labels, delimiter=',',\n header='Label, Panel1, Panel2, Panel2')\n\n\ndef save_correct_dafi_hard_thresh_accs_regular_CV(CV_hparams):\n SEEDS = np.concatenate([np.arange(73, 74), np.arange(29) + 1, np.arange(51, 72)], axis=0)\n RESULTS_DIR_PREFIX = '../output/CV_neg=0.001_diff=0.001'\n # will save seed, and accuracy for model/dafi\n te_accs_per_seeds = -1 * np.ones([SEEDS.shape[0], 2])\n for s, seed in enumerate(SEEDS):\n input = Cll8d1pInput(hparams, random_state=seed)\n seed_results_dir = RESULTS_DIR_PREFIX + '_seed%d' % seed\n # path_to_model_chekpoints = seed_results_dir + '/model_checkpoints.pkl'\n # path_to_dafi_model = seed_results_dir + '/dafi_model.pkl'\n dafi_path = seed_results_dir + '/dafi_model.pkl'\n with open(dafi_path, 'rb') as f:\n dafi_model = pickle.load(f)\n dafi_model.cuda(0)\n feats_dafi = dafi_model.forward_4chain(input.x_eval, input.y_eval, use_hard_proportions=True, device=0)[\n 'leaf_probs'].detach().cpu().numpy()\n feats_dafi_p1 = feats_dafi\n preds = feats_dafi_p1 > 0.0001\n acc_updated_thresh_dafi = np.sum(\n np.array([preds[i] == y.cpu().detach().numpy() for i, y in enumerate(input.y_eval)])) / preds.shape[0]\n\n te_accs_per_seeds[s] = [seed, acc_updated_thresh_dafi]\n\n header = 'seed, dafi te acc threshold at 0.0001'\n savepath = RESULTS_DIR_PREFIX + '/accs_updated_thresh=0.0001_dafi.csv'\n np.savetxt(savepath, te_accs_per_seeds, header=header, fmt='%.4f', delimiter=',')\n\n\ndef avg_both_CV_te_results():\n SEEDS = np.concatenate([np.arange(73, 74), np.arange(29) + 1, np.arange(51, 72)], axis=0)\n RESULTS_DIR_PREFIX = '../output/Both_Panels_CV_neg=0.001_diff=0.001'\n # will save seed, and accuracy for model/dafi\n te_accs_per_seeds = -1 * np.ones([SEEDS.shape[0], 3])\n for s, seed in enumerate(SEEDS):\n seed_results_dir = RESULTS_DIR_PREFIX + '_seed%d' % seed\n # path_to_model_chekpoints = seed_results_dir + '/model_checkpoints.pkl'\n # path_to_dafi_model = seed_results_dir + '/dafi_model.pkl'\n eval_tracker_m_path = seed_results_dir + '/tracker_eval_m.pkl'\n eval_tracker_d_path = seed_results_dir + '/tracker_eval_d.pkl'\n with open(eval_tracker_m_path, 'rb') as f:\n eval_tracker_m = pickle.load(f)\n\n with open(eval_tracker_d_path, 'rb') as f:\n eval_tracker_d = pickle.load(f)\n\n te_accs_per_seeds[s] = [seed, eval_tracker_m.acc[-1], eval_tracker_d.acc[-1]]\n\n variances = (np.var(te_accs_per_seeds, axis=0) ** (1 / 2))\n print('variance: model %.4f, dafi %.4f' % (variances[1], variances[2]))\n print('Avg model both te acc: %.4f' % (np.mean(te_accs_per_seeds, axis=0)[1]))\n print('Avg Dafi both te acc: %.4f' % (np.mean(te_accs_per_seeds, axis=0)[2]))\n header = 'seed, model te acc, dafi te acc logreg'\n savepath = RESULTS_DIR_PREFIX + '/accs_both.csv'\n np.savetxt(savepath, te_accs_per_seeds, header=header, fmt='%.4f', delimiter=',')\n\n\nif __name__ == '__main__':\n # yaml_filename = '../configs/OOS_both_panels.yaml' #for both panels\n yaml_filename = '../configs/OOS_Final_Model.yaml'\n hparams = default_hparams\n with open(yaml_filename, \"r\") as f_in:\n yaml_params = yaml.safe_load(f_in)\n hparams.update(yaml_params)\n\n ## For single panel feat generation trained on all 102\n # Note I accidentally mislabelled the save results with CV in the front\n model_path = '../output/CV_neg=0.001_diff=0.001_FINAL_OOS_seed0/model.pkl'\n dafi_path = '../output/CV_neg=0.001_diff=0.001_FINAL_OOS_seed0/dafi_model.pkl'\n save_feats_panel1_OOS(hparams, model_path, dafi_path)\n save_feats_panel1_in_sample(hparams, model_path, dafi_path)\n\n ## for both panels feat generation\n # OOS_model_both_checkpoint_path = '../output/OOS_both_panels_seed0/model_checkpoints.pkl'\n # OOS_dafi_both_path = '../output/OOS_both_panels_seed0/dafi_model.pkl'\n # save_feats_both_all_data(hparams, OOS_model_both_checkpoint_path, OOS_dafi_both_path)\n\n # combine_results_into_one_csv('../output/logreg_to_conv_grid_search', '../output/agg_results_logreg_to_conv_gs1', '../data/cll/y_dev_4d_1p.pkl')\n # combine_results_into_one_csv('../output/logreg_to_conv_grid_search', '../output/agg_results_logreg_to_conv_gs2', '../data/cll/y_dev_4d_1p.pkl', corner_reg_grid=[0.001, 0.050], gate_size_reg_grid=[0.25, 0.5], decimal_points_in_dir_name=3)\n # combine_results_into_one_csv('../output/two_phase_logreg_to_conv_grid_search_gate_size=', '../output/agg_results_two_phase', '../data/cll/y_dev_4d_1p.pkl', corner_reg_grid=[0.00], gate_size_reg_grid= [0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2.])\n path_to_hparams = '../configs/baseline_plot.yaml'\n savepath = '../data/cll/8d_FINAL/x_all.csv'\n # make_and_write_concatenated_8d_data_with_dafi_gate_flags_and_ids(path_to_hparams, savepath)\n # write_ranked_features_model_dafi(path_to_hparams)\n\n # avg_both_CV_te_results()\n\n # Get dafi accs with updated threshold\n## yaml_filename = '../configs/CV_runs.yaml'\n# hparams = default_hparams\n# with open(yaml_filename, \"r\") as f_in:\n# yaml_params = yaml.safe_load(f_in)\n# hparams.update(yaml_params)\n# save_correct_dafi_hard_thresh_accs_regular_CV(hparams)\n\n\n# dataname = 'cll_4d_1p'\n# for method_name in model_dict:\n# figname = '../output/%s/comparison.pdf' % (dataname + '_' + method_name)\n# f, axarr = plt.subplots(1, len(metric_dict), figsize=(10, 2))\n# for i, metric_name in enumerate(metric_dict):\n# axarr[i] = scatter_vs_dafi_feature(dataname, method_name, metric_name, axarr[i])\n# axarr[i].set_xlabel('Model gates')\n# axarr[0].set_ylabel('Expert gates')\n# f.savefig(figname, bbox_inches='tight')\n\n\n# for i in range(len(model_dict)):\n# for j in range(i + 1, len(model_dict)):\n# for metric_name in metric_dict:\n# scatter_methods(dataname, model_dict[i], model_dict[j], metric_name)\n","repo_name":"disiji/fc_differentiable","sub_path":"src/result_analysis.py","file_name":"result_analysis.py","file_ext":"py","file_size_in_byte":32477,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"71536025764","text":"import matplotlib.pylab as plt\nimport numpy as np\nfrom astropy.io import fits as pf\n\n\ndef ifscube_slicer(cube):\n pars = pf.getdata(cube, \"PARNAMES\")\n print(f\"Parnames: {len(pars)}\")\n print(pars)\n solution = pf.getdata(cube, \"SOLUTION\")\n flux = pf.getdata(cube, \"FLUX_M\")\n eqw = pf.getdata(cube, \"EQW_M\")\n\n i = 0 # indice do solution\n j = 0 # indice do flux e do eqw\n #\n # PARA O PLOT - Tu pode remover tudo isso, mas eh para poder conferir se o que esta sendo salvo esta certo.\n plots = int(len(pars) / 3) # para controlar os plots\n k = 1 # contador dos plots\n plt.figure(figsize=(50, 50)) # Fazendo uma figura bem grande (pode dar zoom)\n\n map_names = []\n for p in pars:\n p = np.asarray(p)\n if p[1] == \"A\":\n save_name_flux = \"Flux_\" + p[0] # nome para salvar o mapa de fluxo (usei no label do plot)\n save_flux = flux[j] # array (44,44) com os valores do mapa de flux a serem salvos\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_flux, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_flux) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_flux)\n\n save_name_ew = \"Ew_\" + p[0] # nome para salvar o mapa de eqw (usei no label do plot)\n save_ew = -1 * eqw[j] # array (44,44) com os valores do mapa de ew a serem salvos\n plt.subplot(\n plots, 4, k\n ) # NOTA: O EW precisa ser multiplicado por -1 para inverter o sinal (nao pode usar abs)\n k = k + 1\n plt.imshow(\n save_ew, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_ew) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_ew)\n j = j + 1 # contador de indice de flux e eqw\n\n elif p[1] == \"v\":\n save_name_vel = \"Vel_\" + p[0] # nome para salvar o mapa de velocidades (usei no label do plot)\n save_vel = solution[i] # array (44,44) com os valores do mapa de velocidade a serem salvos\n\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_vel, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_vel) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_vel)\n\n elif p[1] == \"s\":\n save_name_sig = \"Sigma_\" + p[0] # nome para salvar o mapa de sigma (usei no label do plot)\n save_sig = solution[i] # array (44,44) com os valores do mapa de sigma a serem salvos\n plt.subplot(plots, 4, k)\n k = k + 1\n plt.imshow(\n save_sig, origin=\"lower\"\n ) # plot para tu poder conferir (note o origim do matplotlib que precisa ser lower para o 0,0 ser no canto inferior esquerdo)\n plt.gca().set_title(save_name_sig) # titulo do plot\n plt.colorbar() # barra de cores\n\n map_names.append(save_name_sig)\n\n i = i + 1 # contador para o solution (note que eu pulo o A ao salvar por que salvo o Flux e EW no lugar)\n plt.tight_layout() # deixando o plot mais elegante...\n plt.savefig(\"teste.png\")\n print(f\"Plots: {k}\")\n print(f\"Names: {map_names} [{len(map_names)}]\")\n\n\ncube = \"images/manga-9894-3701-MEGACUBE.fits\" # lista de cubos, pode usar num for...\n\nifscube_slicer(cube)\n","repo_name":"linea-it/manga","sub_path":"backend/ifscube_slicer.py","file_name":"ifscube_slicer.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35335462090","text":"from flask import Blueprint, jsonify, request\nfrom models import returnDBConnection, authenticate_token\n\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nchallenge_bp = Blueprint('challenge_bp', __name__)\n\n@challenge_bp.route(\"/request_music_notation_data\")\ndef request_music_notation_data():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tconn, cur = returnDBConnection()\n\n\tcourseID = request.args.get(\"courseID\")\n\tchallengeID = request.args.get(\"challengeID\")\n\n\tcur.execute(f\"SELECT musicData, svgIndexes, challengeTitle, challengeMessage, challengeSvgURL FROM challenges WHERE courseID = '{courseID}' AND challengeID = '{challengeID}'\")\n\tmusic_notation_data = cur.fetchone()\n\n\tconn.close()\n\n\treturn jsonify(music_notation_data)\n\n@challenge_bp.route(\"/get_next_challengeID\")\ndef get_next_challenge_id():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tconn, cur = returnDBConnection()\n\n\tuserID = request.args.get(\"userID\")\n\tcourseID = request.args.get(\"courseID\")\n\tchallengeID = request.args.get(\"challengeID\")\n\n\tcur.execute(f\"SELECT lastChallengeCompleted FROM coursesEnrolled WHERE userID='{userID}' AND courseID='{courseID}'\")\n\tlastChallengeCompleted = cur.fetchone()[0]\n\n\tif challengeID != None:\n\t\tlastChallengeCompleted += 1\n\t\tcur.execute(f\"UPDATE coursesEnrolled SET lastChallengeCompleted = {lastChallengeCompleted}\")\n\t\tconn.commit()\n\n\tcur.execute(f\"SELECT challengeID FROM challenges WHERE courseID = '{courseID}' AND challengeNo={lastChallengeCompleted+1}\")\n\tnextChallengeID = cur.fetchone()\n\n\tconn.close()\n\n\tif nextChallengeID == None:\n\t\treturn jsonify(\"Finished\")\n\n\treturn jsonify(nextChallengeID[0])\n\n@challenge_bp.route(\"/request_midi_notes_to_drum_name\")\ndef request_midi_notes_to_drum_name():\n\tif not authenticate_token(request.headers):\n\t\treturn \"Invalid API key\", 403\n\n\tmidiNotesToDrumName = {\n\t\t35: \"bass-drum\",\n\t\t36: \"bass-drum\",\n\t\t37: \"side-stick\",\n\t\t38: \"snare\",\n\t\t40: \"snare\",\n\t\t41: \"floor-tom\",\n\t\t42: \"closed hi-hat\",\n\t\t43: \"floor-tom\",\n\t\t44: \"pedal hi-hat\",\n\t\t45: \"mid-tom\",\n\t\t46: \"open hi-hat\",\n\t\t47: \"high-tom\",\n\t\t49: \"crash\",\n\t\t51: \"ride\",\n\t\t53: \"ride-bell\",\n\t\t57: \"crash\"\n\t}\n\n\treturn jsonify(midiNotesToDrumName)","repo_name":"davidliebs/DrumProject","sub_path":"api/challenge/challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28733943754","text":"import importlib\n\nimport pytorch_lightning as pl\nimport torch.utils.data\nimport wandb\n\nfrom utils.loss import VGGPerceptualLoss\nfrom visualization import *\n\n\nclass Model(pl.LightningModule):\n def __init__(self, **kwargs):\n super().__init__()\n self.save_hyperparameters()\n self.encoder = importlib.import_module('models.' + self.hparams.encoder).Encoder(self.hparams)\n self.decoder = importlib.import_module('models.' + self.hparams.decoder).Decoder(self.hparams)\n self.batch_size = self.hparams.batch_size\n self.test_func = importlib.import_module('datasets.' + self.hparams.dataset).test_epoch_end\n\n self.vgg_loss = VGGPerceptualLoss()\n\n def forward(self, x):\n return self.encoder(x)\n\n def training_step(self, batch, batch_idx):\n self.vgg_loss.eval()\n out_batch = self.decoder(self.encoder(batch))\n\n perceptual_loss = self.vgg_loss(out_batch['img'], batch['img'])\n\n self.log(\"perceptual_loss\", perceptual_loss)\n self.log(\"alpha\", self.decoder.alpha.detach().cpu())\n return perceptual_loss\n\n def validation_step(self, batch, batch_idx):\n return batch\n\n def validation_epoch_end(self, outputs):\n self.log(\"val_loss\", -self.global_step)\n imgs = denormalize(outputs[0]['img']).cpu()\n recon_batch = self.decoder(self.encoder(outputs[0]))\n scaled_kp = recon_batch['keypoints'] * self.hparams.image_size / 2 + self.hparams.image_size / 2\n\n heatmap = recon_batch['heatmap'].cpu()\n heatmap_overlaid = torch.cat([heatmap] * 3, dim=1) / heatmap.max()\n heatmap_overlaid = torch.clamp(heatmap_overlaid + imgs * 0.5, min=0, max=1)\n\n self.logger.experiment.log({'generated': [wandb.Image(draw_img_grid(denormalize(outputs[0]['img']).cpu()), caption='original_image'),\n wandb.Image(draw_img_grid(denormalize(recon_batch['img']).cpu()), caption='reconstructed'),\n wandb.Image(draw_img_grid(heatmap_overlaid.cpu()), caption='heatmap_overlaid'),\n wandb.Image(draw_kp_grid_unnorm(recon_batch['heatmap'], scaled_kp), caption='heatmap'),\n wandb.Image(wandb.Image(draw_kp_grid(imgs, scaled_kp)), caption='keypoints'),\n wandb.Image(draw_matrix(recon_batch['skeleton_scalar_matrix'].detach().cpu().numpy()), caption='skeleton_scalar')]})\n\n def test_step(self, batch, batch_idx, dataloader_idx=0):\n kp = self.encoder(batch)['keypoints']\n out_batch = batch.copy()\n out_batch['det_keypoints'] = kp\n return out_batch\n\n def test_epoch_end(self, outputs):\n outputs = self.test_func(outputs)\n self.print(\"test_loss\", outputs['val_loss'])\n self.log(\"test_loss\", outputs['val_loss'])\n\n def configure_optimizers(self):\n optimizer = torch.optim.AdamW(self.parameters(), lr=self.hparams.lr, weight_decay=1e-3)\n return optimizer\n","repo_name":"ck624/AutoLink-Self-supervised-Learning-of-Human-Skeletons-and-Object-Outlines-by-Linking-Keypoints","sub_path":"models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"3630834170","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import deque\n\n\n# Complete the knightlOnAChessboard function below.\ndef try_next(i, j, visited, q, n):\n if i == n - 1 and j == n - 1:\n return True\n # check if outbounded\n if i < 0 or j < 0 or i >= n or j >= n:\n # don't do anything\n return False\n if visited[i][j]:\n return False\n\n visited[i][j] = True\n q.append((i, j))\n return False\n\n\ndef get_count(i, j):\n ret = -1\n # Use Dijkstra algorithm.\n visited = [[False] * n for _ in range(n)]\n step_count = -1\n # put (0,0) into the deque\n q = deque([(0, 0)])\n done = False\n while len(q) > 0:\n sz = len(q)\n step_count += 1\n for _ in range(sz):\n start = q.popleft()\n visited[start[0]][start[1]] = True\n # try all 8 different moves\n # +i, +j\n done = try_next(start[0] + i, start[1] + j, visited, q, n)\n # +i, -j\n done = done or try_next(start[0] + i, start[1] - j, visited, q, n)\n # -i, + j\n done = done or try_next(start[0] - i, start[1] + j, visited, q, n)\n # -i, -j\n done = done or try_next(start[0] - i, start[1] - j, visited, q, n)\n # +j, +i\n done = done or try_next(start[0] + j, start[1] + i, visited, q, n)\n # +j, -i\n done = done or try_next(start[0] + j, start[1] - i, visited, q, n)\n # -j, + i\n done = done or try_next(start[0] - j, start[1] + i, visited, q, n)\n # -j, -i\n done = done or try_next(start[0] - j, start[1] - i, visited, q, n)\n\n if done:\n break\n\n if done:\n break\n\n ret = step_count + 1 if done else -1\n return ret\n\n\ndef knightlOnAChessboard(n):\n counts = [[0] * (n - 1) for _ in range(n - 1)]\n for i in range(1, n):\n for j in range(1, i):\n counts[i - 1][j - 1] = counts[j - 1][i - 1]\n\n for j in range(i, n):\n counts[i - 1][j - 1] = get_count(i, j)\n\n return counts\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n result = knightlOnAChessboard(n)\n\n fptr.write('\\n'.join([' '.join(map(str, x)) for x in result]))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"encgoo/hackerrank","sub_path":"Search/knightl_on_a_chessboard.py","file_name":"knightl_on_a_chessboard.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39847799716","text":"from django.test import TestCase\nfrom .models import AlumPost\n\n\nclass TestUserTypesModel(TestCase):\n\n def test_create_alumni_post(self):\n alum_post = AlumPost(title='Alumni Test', content='Some test content.')\n alum_post.save()\n self.assertEqual(alum_post.title, \"Alumni Test\")\n self.assertEqual(alum_post.content, \"Some test content.\")\n self.assertFalse(alum_post.image)\n","repo_name":"hschafer2017/PCSwimming","sub_path":"alumni/tests_models.py","file_name":"tests_models.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"44461184686","text":"numeros = [1, 2, 3, 4, 5]\nprint(numeros)\n\nnovos_numeros = []\nfor numero in numeros:\n novos_numeros.append(numero * 4)\nprint(novos_numeros)\n\n# List Comprehension\nnovos_numeros = [numero / 2 for numero in novos_numeros]\nprint(novos_numeros)\n\n# Condicionais\nnovos_numeros = [\n numero\n if numero != 3 else 30\n for numero in numeros\n if numero % 2 != 0\n]\nprint(novos_numeros)\n\n# string\nstring = 'Otávio Miranda'\nnova_string = [letra for letra in string]\nprint(nova_string)\n\nnumero_letras = 1\nnova_string = '.'.join([\n string[indice:indice + numero_letras]\n for indice in range(0, len(string), numero_letras)\n])\nprint(nova_string)\n\nnomes = ['luiz', 'MARIA', 'Helena', 'Joana']\nnovos_nomes = [\n nome.lower().title()\n for nome in nomes\n]\nprint(novos_nomes)\n\nnovos_nomes = [\n f'{nome[:-1].lower()}{nome[-1].upper()}'\n for nome in nomes\n]\nprint(novos_nomes)\n\nnumeros = [(numero, numero ** 2) for numero in range(10)]\nprint(numeros)\n# FLAT\nflat = [y for x in numeros for y in x] \nprint(flat)\n","repo_name":"cesar-augusto-costa/Python_Avancado_Udemy","sub_path":"Python_Avancado_Udemy/Projeto/aula085cadd.py","file_name":"aula085cadd.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9042640641","text":"\n\nfrom django.views.generic import FormView, TemplateView\nfrom .forms import SignModelForm\nfrom django.urls import reverse_lazy\nfrom .models import Sign\nfrom datetime import datetime\n\n\nclass SignFormView(FormView):\n template_name = 'index.html'\n form_class = SignModelForm\n success_url = reverse_lazy('index')\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.db = Sign.objects.all()\n self.each_sign_first_month_days = (\n range(22, 32), range(21, 32), range(19, 32), range(21, 32), range(21, 32), range(21, 32),\n range(21, 32), range(23, 32), range(23, 32), range(23, 32), range(23, 32), range(22, 32)\n )\n\n self.each_sign_second_month_days = (\n range(1, 21), range(1, 19), range(1, 21), range(1, 21), range(1, 21), range(1, 21),\n range(1, 23), range(1, 23), range(1, 23), range(1, 23), range(1, 22), range(1, 22)\n )\n\n self.each_sign_first_month = (12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)\n\n self.each_sign_second_month = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)\n\n self.signs: tuple = (\n 'Capricórnio', 'Aquário', 'Peixes', 'Aries', 'Touro', 'Gêmeos',\n 'Câncer', 'Leão', 'Virgem', 'Libra', 'Escorpião', 'Sagitário'\n )\n\n if len(self.db) != 0:\n self.the_input = self.get_last_object_data()\n self.last_input_array = self.last_object_split_data()\n self.birthday_datetime = self.generate_birthday_datatime()\n self.person_age_in_days = self.calculate_lifetime()\n self.person_sign = self.find_sign()\n else:\n self.the_input = '01/01/2000'\n self.last_input_array = {'day': 1, 'month': 1, 'year': 2000}\n self.birthday_datetime = self.generate_birthday_datatime()\n self.person_age_in_days = self.calculate_lifetime()\n self.person_sign = self.find_sign()\n\n # print(dir(Sign.objects.get(birthday='16/07/1992').birthday))\n\n def form_valid(self, form):\n form.save()\n return super(SignFormView, self).form_valid(form)\n\n def form_invalid(self, form):\n return super(SignFormView, self).form_invalid(form)\n\n def get_last_object_data(self) -> str:\n db_size = len(self.db) - 1\n last_object_from_db = None\n\n for index, object_ in enumerate(self.db):\n # Se chegar no último índice do banco, pegar o atributo deste objeto neste índice\n if index == db_size:\n last_object_from_db = self.db[index].birthday\n\n # ANTES: .get(birthday=last_object_from_db).birthday (gera erro se há múltiplos objetos [repetidos])\n # SOLUÇÃO: trocar por \"filter\" e pegar o primeiro registro repitido encontrado\n last_input = Sign.objects.filter(birthday=last_object_from_db)[0].birthday\n return last_input\n\n def last_object_split_data(self) -> dict:\n last_object_array = [int(number) for number in self.the_input.split('/')]\n return {\n 'day': last_object_array[0],\n 'month': last_object_array[1],\n 'year': last_object_array[2]\n }\n\n def generate_birthday_datatime(self):\n\n # Coletar o dado de data do aniversário p/ ser subtraído pela data de hoje na função \"calculate_lifetime\"\n the_birthday = datetime(\n day=self.last_input_array['day'],\n month=self.last_input_array['month'],\n year=self.last_input_array['year'])\n\n return the_birthday\n\n def calculate_lifetime(self):\n\n # P/ o cálculo, é preciso a data atual p/ subtrair com a data no aniversário do usuário\n right_now = datetime.today()\n today_datetime = datetime(year=right_now.year, month=right_now.month, day=right_now.day)\n\n # Subtração das datas p/ saber o tempo de vida do usuário\n person_existance = today_datetime - self.birthday_datetime\n\n # Formatar dados do cálculo p/ adquirir o dado numérico\n person_existance = f'{str(person_existance).split()[0]} dias'\n\n return person_existance\n\n def find_sign(self):\n\n # O signo é encontrado pela satisfação de 2 das 4 condições\n # O signo é achado caso: 2 primeiras condições satisfeitas, ou as 2 últimas\n for index in range(len(self.signs)):\n\n if self.last_input_array['day'] in tuple(self.each_sign_first_month_days)[index] \\\n and self.last_input_array['month'] == tuple(self.each_sign_first_month)[index] \\\n or self.last_input_array['day'] in tuple(self.each_sign_second_month_days)[index] \\\n and self.last_input_array['month'] == tuple(self.each_sign_second_month)[index]:\n\n return self.signs[index]\n\n def get_context_data(self, **kwargs):\n context = super(SignFormView, self).get_context_data(**kwargs)\n context['db'] = self.db\n context['birthday'] = self.the_input\n context['age_in_days'] = self.person_age_in_days\n context['person_sign'] = self.person_sign\n return context\n\n\nclass SampleView(TemplateView):\n template_name = 'sample.html'\n","repo_name":"lucas1farias/django_sign_identifier_app","sub_path":"sign_identifier_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18795458914","text":"import socket\nimport sys\n\ndef scan(host, timer):\n if len(sys.argv) > 4:\n ports = range(int(sys.argv[2]), int(sys.argv[3]))\n t = sys.argv[4]\n\n if t == \"t1\":\n timer = 0.1\n elif t == \"t2\":\n timer = 0.4\n elif t == \"t3\":\n timer = 0.7\n elif t == \"t4\":\n timer = 1\n else:\n timer = 2\n\n elif len(sys.argv) > 3:\n ports = range(int(sys.argv[2]), int(sys.argv[3]))\n\n else:\n ports = range(1, 3307)\n\n\n print(\" PORTA | STATUS\")\n\n for porta in ports:\n client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client.settimeout(timer)\n\n code = client.connect_ex((host, porta))\n\n if code == 0:\n print(f' {porta}/tcp | OPEN')\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) >= 2:\n host = sys.argv[1]\n ports = 0\n timer = 1\n scan(host, timer)\n else:\n print(\"Usage: python3 host\")\n print(\"or\")\n print(\"Usage: python3 host starting_port end_port timer\")\n","repo_name":"mcavalcan7i/port-scan","sub_path":"port_scan.py","file_name":"port_scan.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"24694685403","text":"__author__ = \"Vanessa Sochat\"\n__copyright__ = \"Copyright 2022, Vanessa Sochat\"\n__license__ = \"MPL 2.0\"\n\n\nclass WrapperTransformer:\n def __init__(self, width, indent=2):\n self._width = width\n self._indent = indent\n\n def __call__(self, s):\n res = []\n for line in s.splitlines():\n if len(line) > self._width and \" \" in line:\n idx = 0\n while line[idx] == \" \":\n idx += 1\n line, rest = line.rsplit(\" \", 1)\n res.append(line)\n res.append(\" \" * (idx + self._indent) + rest)\n continue\n res.append(line)\n return \"\\n\".join(res) + \"\\n\"\n","repo_name":"vsoch/action-updater","sub_path":"action_updater/utils/custom_yaml.py","file_name":"custom_yaml.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"4130905081","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport argparse\nimport numpy as np\nimport ROOT\nROOT.PyConfig.IgnoreCommandLineOptions = True\nROOT.gROOT.SetBatch(True)\n\ndef _RooAbsCollection__iter__(self):\n it = self.iterator()\n obj = it.Next()\n while obj != None:\n yield obj\n obj = it.Next()\n\nROOT.RooAbsCollection.__iter__ = _RooAbsCollection__iter__\n\n# because RooAbsCollection uses operator= for assignment :(\ndef rooAssign(target, other):\n if target == other:\n return\n for el in target:\n theirs = other.find(el)\n if not theirs:\n continue\n el.setVal(theirs.getVal())\n el.setError(theirs.getError())\n el.setAsymError(theirs.getErrorLo(), theirs.getErrorHi())\n el.setAttribute(\"Constant\", theirs.isConstant())\n\n\ndef finitediff(f, x, y, dx, dy):\n x0 = x.getVal()\n y0 = y.getVal()\n\n # stencil\n def s(i, j):\n x.setVal(x0 + i*dx)\n y.setVal(y0 + j*dy)\n return f.getVal()\n\n out = 0.\n if x is y:\n # https://en.wikipedia.org/wiki/Five-point_stencil\n out += -s(2,2) + 16*s(1,1) - 30*s(0,0) + 16*s(-1,-1) - s(-2,-2)\n out /= 12*dx*dy\n else:\n # Following http://www.holoborodko.com/pavel/2014/11/04/computing-mixed-derivatives-by-finite-differences/\n out += 8*( s(1,-2) + s(2,-1) + s(-2,1) + s(-1,2) )\n out -= 8*( s(-1,-2) + s(-2,-1) + s(1,2) + s(2,1) )\n out -= ( s(2,-2) + s(-2,2) - s(-2,-2) - s(2,2) )\n out += 64*( s(-1,-1) + s(1,1) - s(1,-1) - s(-1,1) )\n out /= 144*dx*dy\n\n x.setVal(x0)\n y.setVal(y0)\n return out\n\n\ndef compute_hessian(args):\n fws, wsname = args.workspace.split(':')\n fin = ROOT.TFile.Open(fws)\n w = fin.Get(wsname)\n\n ffit, fitname = args.fit.split(':')\n fin2 = ROOT.TFile.Open(ffit)\n fit = fin2.Get(fitname)\n\n model = w.obj(args.model)\n pdf = model.GetPdf()\n nll = pdf.createNLL(w.data(\"data_obs\"), ROOT.RooLinkedList())\n params = pdf.getParameters(model.GetObservables())\n rooAssign(params, fit.constPars())\n rooAssign(params, fit.floatParsFinal())\n\n floatparams = [p for p in params if fit.floatParsFinal().find(p)]\n npar = len(floatparams)\n hess = np.zeros(shape=(npar, npar))\n for ix in range(npar):\n x = floatparams[ix]\n dx = args.scale*x.getError()\n for iy in range(ix, npar):\n y = floatparams[iy]\n dy = args.scale*y.getError()\n hess[ix, iy] = finitediff(nll, x, y, dx, dy)\n\n ilow = np.tril_indices(npar, -1)\n hess[ilow] = hess.T[ilow]\n return hess, floatparams, nll\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Compute hessian by hand.\")\n parser.add_argument(\"-w\", \"--workspace\", metavar=\"ROOTFILE:WORKSPACE\", help=\"Workspace to load\", required=True)\n parser.add_argument(\"-f\", \"--fit\", metavar=\"ROOTFILE:FIT_NAME\", help=\"Fit result to load\", required=True)\n parser.add_argument(\"-m\", \"--model\", help=\"Model to load\", default=\"ModelConfig\")\n parser.add_argument(\"-s\", \"--scale\", help=\"Scale (multiplier of parameter error) to use for finite difference\", default=0.5, type=float)\n parser.add_argument(\"--cond\", help=\"Regularize the inversion by adding identity times this factor to the Hessian\", default=0., type=float)\n\n args = parser.parse_args()\n hess, param, nll = compute_hessian(args)\n param = np.array(param)\n param_fit_err = np.fromiter((p.getError() for p in param), dtype='d')\n\n hess += np.eye(param.size) * args.cond\n cond = np.linalg.cond(hess)\n print(\"Condition number of hessian:\", cond)\n hess_eig, hess_eigv = np.linalg.eigh(hess)\n\n normed_eigv = hess_eigv[0]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Shallowest direction (eigenvalue %r, top 10):\" % hess_eig[0])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n normed_eigv = hess_eigv[-1]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Steepest direction (eigenvalue %r, top 10):\" % hess_eig[-1])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n covar = np.linalg.inv(hess)\n cov_eig, cov_eigv = np.linalg.eigh(covar)\n print(\"Largest eigenvalue of covariance matrix:\", cov_eig[-1])\n print(\"Smallest eigenvalue of covariance matrix:\", cov_eig[0])\n\n std = np.sqrt(np.diag(covar))\n print(\"Largest standard deviation:\", std.max(), \"at\", param[std.argmax()])\n print(\"Smallest standard deviation:\", std.min(), \"at\", param[std.argmin()])\n\n corr = covar / std[:,None] / std[None,:]\n corr_eig, corr_eigv = np.linalg.eigh(corr)\n\n normed_eigv = corr_eigv[-1]\n order = np.abs(normed_eigv).argsort()[:-10:-1]\n print(\"Largest correlation vector (eigenvalue %r, top 10):\" % corr_eig[-1])\n for mag, par in zip(normed_eigv[order], param[order]):\n print(\" %6.3f %r\" % (mag, par.GetName()))\n\n","repo_name":"ParticleChef/jieun_mtop_decaf","sub_path":"analysis/macros/hessian.py","file_name":"hessian.py","file_ext":"py","file_size_in_byte":4968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9997168403","text":"from project1_model import project1_model\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import transforms\n# from torch.utils.data import SubsetRandomSampler\n# from sklearn.model_selection import train_test_split\nimport os\nimport matplotlib.pyplot as plt\n\n# -------------------------------- #\n\ntrans_train = transforms.Compose([\n # transforms.Grayscale(num_output_channels=1),\n transforms.RandomCrop(32, padding=4),\n # Flip horizontal\n transforms.RandomHorizontalFlip(),\n# transforms.GaussianBlur(kernel_size=3, sigma=(2.0, 2.0)),\n transforms.ToTensor(),\n transforms.Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n # transform_random,\n])\n\ntrans_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.491, 0.482, 0.447], [0.247, 0.243, 0.262]),\n])\n\nbatch_size = 128\nepochs = 48\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ntrainData = torchvision.datasets.CIFAR10('./cifar-10-data/',train=True,download=True, transform=trans_train)\ntrainDataLoader = torch.utils.data.DataLoader(trainData, batch_size = batch_size, shuffle = True) # , num_worker = 1\n\ntestData = torchvision.datasets.CIFAR10('./cifar-10-data/',train=False,download=True, transform=trans_test)\ntestDataLoader = torch.utils.data.DataLoader(testData, batch_size = batch_size, shuffle = True)\n\n# -------------------------------- #\n\nprint(len(trainData))\nprint(len(testData))\n# image, label = trainData[2]\n# datasize = image.shape\nlabel = 10\n# print(datasize, label)\n# labelNum = label\n\n# -------------------------------- #\n\nres18 = project1_model().to(device)\n\nprint('model structure: ', res18)\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\n# -------------------------------- #\n\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import ExponentialLR, StepLR\n\n# init optimizer\noptimizer = torch.optim.Adam(res18.parameters(), lr=1e-3) # , weight_decay=1e-4\n# optimizer = torch.optim.SGD(res18.parameters(), lr=1e-2, momentum=0.9, weight_decay=5e-4)\n\n# scheduler = ExponentialLR(optimizer, gamma=0.6)\nscheduler = StepLR(optimizer, step_size=20, gamma=0.1)\n\n# set loss function\ncriterion = nn.CrossEntropyLoss()\n\n\ndef train(model, epochs):\n # train_loss = []\n epoch_loss_i = []\n\n correct = 0\n\n for batch_idx, (data, target) in enumerate(trainDataLoader):\n # data, target = Variable(data).to(device), Variable(target).to(device) # to device\n data, target = data.to(device), target.to(device)\n train_pred = model(data)\n\n # Accuracy\n pred = train_pred.argmax(dim=1)\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n # Loss\n train_loss_i = criterion(train_pred, target)\n epoch_loss_i.append(train_loss_i)\n\n # Backpropagation\n optimizer.zero_grad()\n train_loss_i.backward()\n optimizer.step()\n\n # print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(batch_idx, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n epoch_loss = sum(epoch_loss_i) / len(epoch_loss_i)\n # trainAcc = correct / len(epoch_loss_i)\n trainAcc = correct / (len(trainDataLoader.dataset))\n # print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(epochs, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n\n # get learing rate\n print(get_lr(optimizer))\n\n return epoch_loss, trainAcc\n\n\n# print('Train epoch: {} | [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(i, batch_idx * len(data), len(trainDataLoader), 100. * batch_idx/len(trainDataLoader), epoch_loss))\n\n\ndef test(model):\n # model.eval()\n # test_loss = []\n # for i in epochs:\n test_loss_i = []\n correct = 0\n testAcc = 0\n total = 0\n\n for data, target in testDataLoader:\n data, target = data.to(device), target.to(device) # (rm , volatile=True) .to(device)\n test_pred = model(data)\n test_loss_i.append(criterion(test_pred, target))\n\n pred = test_pred.argmax(dim=1)\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n\n total += target.size(0)\n\n # test_loss_i = test_loss_i / len(testDataLoader.dataset) # len(testDataLoader.dataset)\n test_loss = sum(test_loss_i) / len(test_loss_i)\n testAcc = correct / total # len(testDataLoader.dataset)\n\n print('Test set: Average Loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'.format(test_loss, correct,\n len(testDataLoader.dataset),\n 100. * correct / len(\n testDataLoader.dataset)))\n\n return test_loss, testAcc\n\n\n# -------------------------------- #\n\ndef save(net, path):\n \"\"\"\n save parameters into files after training\n :param: net model, model save path\n :return: None\n \"\"\"\n stats = {\n # 'epoch': epoch,\n 'model': net.state_dict()\n }\n if not os.path.exists(path):\n os.mkdir(path)\n\n savePath = os.path.join(path, 'res18') ##### model_res18 / model_CNN / model_wasteCNN\n torch.save(stats, savePath)\n print(\"Final model checkpoints in {}\".format(savePath))\n\n# -------------------------------- #\n\nimport datetime\n\ntrain_loss = []\ntest_loss = []\ntrain_acc = []\ntest_acc = []\n\nfor epoch in range(epochs):\n starttime = datetime.datetime.now()\n trainLoss, trainAcc = train(res18, epoch)\n train_loss.append(trainLoss)\n train_acc.append(trainAcc)\n\n traintime = datetime.datetime.now()\n\n # if epoch % 5 == 0:\n scheduler.step()\n\n scheduletime = datetime.datetime.now()\n print('Train set: Epoch: {} Loss: {:.6f} Accuracy: {:.2f}'.format(epoch, trainLoss, trainAcc))\n\n with torch.no_grad():\n testLoss, testAcc = test(res18) # .detach()\n test_loss.append(testLoss)\n test_acc.append(testAcc)\n print('Test set: Epoch: {} Loss: {:.6f} Accuracy: {:.2f}'.format(epoch, testLoss, testAcc))\n endtime = datetime.datetime.now()\n print(\"train time:\", traintime - starttime, \"test time:\", endtime - scheduletime, \"total time:\",\n endtime - starttime, \"\\n\")\n\nsave(res18, './project1_model')\n\n# -------------------------------- #\n\n# print(len(train_loss), len(test_loss))\nx_axis = np.arange(epochs) # epochs\nplt.plot(x_axis, train_loss, label='train loss')\nplt.plot(x_axis, test_loss, label='test loss')\nplt.legend()\nplt.savefig('loss_pic.png')\nplt.show()\n\n# -------------------------------- #\n\nx_axis = np.arange(epochs)\n# train_acc_array = [x/50000 for x in train_acc]\n# plt.plot(x_axis, train_acc_array, label='train accuracy')\nplt.plot(x_axis, train_acc, label='train accuracy')\nplt.plot(x_axis, test_acc, label='test accuracy')\nplt.legend()\nplt.savefig('accuracy_pic.png')\nplt.show()\nprint(max(test_acc), test_acc.index(max(test_acc)))\n\n# -------------------------------- #\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n # torch.numel() returns number of elements in a tensor\n\nprint(count_parameters(res18)/1000000, \"M\")\n\n","repo_name":"Guojiacheng2017/Mini_Project_DL","sub_path":"Mini_Project_1/mini_project_1.py","file_name":"mini_project_1.py","file_ext":"py","file_size_in_byte":7404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"8436010756","text":"import os\nfrom .mailchimp import mc\nfrom flask import Flask\nfrom .routes import bp\nfrom urllib.parse import unquote\nfrom dotenv import load_dotenv\nload_dotenv()\n\n\n# manually decode from '%9Z' to '%0A'\n# (since IIS servers will error out when it sees '%0A's)\ndef decode(text):\n if text:\n return unquote(text.replace('', '%0A'))\n else:\n return ''\n\n\ndef create_app(\n package_name=__name__,\n static_folder='static',\n template_folder='templates',\n **config_overrides):\n\n # initialize app\n app = Flask(package_name,\n static_url_path='/assets',\n static_folder=static_folder,\n template_folder=template_folder)\n\n # set mailchimp settings\n mc_user = os.getenv('MAILCHIMP_USERNAME')\n mc_key = os.getenv('MAILCHIMP_KEY')\n mc_list_id = os.getenv('MAILCHIMP_LIST_ID')\n\n # load mailchimp credentials\n mc.set_credentials(mc_user, mc_key)\n mc.set_list_id(mc_list_id)\n\n # custom decoder for '%0A' and '%0U' as these\n # characters are not supported in iis servers\n app.jinja_env.globals.update(decode=decode)\n\n # Apply overrides\n app.config.update(config_overrides)\n\n # Register Routes in routes.py\n app.register_blueprint(bp)\n\n return app\n\n","repo_name":"organizejs/brandnewroman","sub_path":"app/brandnewroman/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9807813923","text":"from unittest import mock\nfrom discord_ritoman.lol.stats.team import TeamStat\nimport discord_ritoman.lol.stats.team\n\n\ndef team_stat(team_id: int = 100, participant_id: int = 1):\n def decorator(func):\n @mock.patch.object(discord_ritoman.lol.stats.team, \"get_stat\")\n def wrapper(mock_get_stat):\n stat_table = {\n \"participant_ids\": {\n \"A1\": participant_id,\n \"user\": participant_id,\n }\n }\n\n mock_get_stat.side_effect = lambda x: stat_table[x]\n\n data = {\n \"participants\": [\n {\"participantId\": participant_id, \"teamId\": team_id}\n ]\n }\n response = TeamStat.obj.process(data, {}, \"A1\")\n func(response)\n\n return wrapper\n\n return decorator\n\n\n@team_stat()\ndef test_team_stat(response):\n \"\"\"\"\"\"\n assert response == 100\n","repo_name":"stephend017/discord_ritoman","sub_path":"tests/test_stats/test_team_stat.py","file_name":"test_team_stat.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18002724161","text":"import logging\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gio\nfrom gettext import gettext as _\n\nfrom . import repo\n\nclass Updates(Gtk.Box):\n\n distro_codename = repo.get_os_codename()\n os_name = repo.get_os_name()\n repo_descriptions = {\n f'{distro_codename}-security': _('Important security updates'),\n f'{distro_codename}-updates': _('Recommended updates'),\n f'{distro_codename}-backports': _('Unsupported updates')\n }\n\n def __init__(self, parent):\n Gtk.Box.__init__(self, False, 0)\n\n self.log = logging.getLogger(\"repoman.Updates\")\n self.log.debug('Logging established')\n\n self.parent = parent\n self.system_repo = parent.system_repo\n self.handlers = {}\n\n updates_grid = Gtk.Grid()\n updates_grid.set_margin_left(12)\n updates_grid.set_margin_top(24)\n updates_grid.set_margin_right(12)\n updates_grid.set_margin_bottom(12)\n updates_grid.set_hexpand(True)\n updates_grid.set_halign(Gtk.Align.CENTER)\n self.add(updates_grid)\n\n updates_title = Gtk.Label(_(\"Update Sources\"))\n updates_title.set_halign(Gtk.Align.START)\n Gtk.StyleContext.add_class(updates_title.get_style_context(), \"h2\")\n updates_grid.attach(updates_title, 0, 0, 1, 1)\n\n updates_label = Gtk.Label(_(\"These sources control how %s checks for updates. It is recommended to leave these sources enabled.\") % self.os_name)\n updates_label.set_line_wrap(True)\n updates_label.set_justify(Gtk.Justification.FILL)\n updates_label.set_halign(Gtk.Align.START)\n Gtk.StyleContext.add_class(updates_label.get_style_context(), \"description\")\n updates_grid.attach(updates_label, 0, 1, 1, 1)\n\n self.checks_grid = Gtk.VBox()\n self.checks_grid.set_margin_left(12)\n self.checks_grid.set_margin_top(24)\n self.checks_grid.set_margin_right(12)\n self.checks_grid.set_margin_bottom(12)\n self.checks_grid.set_spacing(12)\n updates_grid.attach(self.checks_grid, 0, 2, 1, 1)\n self.checks_grid.show()\n\n self.create_switches()\n self.set_suites_enabled(self.parent.setting.checks_enabled)\n if self.system_repo:\n self.show_updates()\n \n # Watch the config directory for changes, so we can reload if so\n self.file = Gio.File.new_for_path('/etc/apt/sources.list.d/')\n self.monitor = self.file.monitor_directory(Gio.FileMonitorFlags.NONE)\n self.monitor.connect('changed', self.on_config_changed)\n self.log.debug('Monitor Created: %s', self.monitor)\n self.show_all()\n\n def block_handlers(self):\n for widget in self.handlers:\n if widget.handler_is_connected(self.handlers[widget]):\n widget.handler_block(self.handlers[widget])\n\n def unblock_handlers(self):\n for widget in self.handlers:\n if widget.handler_is_connected(self.handlers[widget]):\n widget.handler_unblock(self.handlers[widget])\n\n def get_new_switch(self, suite, description=None):\n \"\"\" Creates a Box with a new switch and a description.\n\n If the name of the suite matches one of the normal default\n suites, include the description of the suite. Otherwise use the\n supplied description (if given) or the name of the suite.\n\n Arguments:\n suite (str): The name of a distro suite to bind to the switch\n description (str): An optional description to use if the suite\n isn't of the predefinied normal sources.\n\n Returns:\n A Gtk.Box with the added switch and label description\n \"\"\"\n\n switch = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 6)\n switch.set_hexpand(True)\n if suite in self.repo_descriptions:\n description = self.repo_descriptions[suite]\n\n label_text = suite\n if description:\n label_text = f'{description} ({suite})'\n label = Gtk.Label.new(label_text)\n label.set_halign(Gtk.Align.START)\n switch.label = label\n switch.add(label)\n toggle = Gtk.Switch()\n toggle.set_halign(Gtk.Align.END)\n toggle.set_hexpand(True)\n toggle.suite = switch.suite = suite\n switch.toggle = toggle\n switch.add(toggle)\n\n return switch\n\n def create_switches(self):\n \"\"\" Create switches for all of the suites which can be toggled. \"\"\"\n for switch in self.checks_grid.get_children():\n self.checks_grid.remove(switch)\n\n for repo in self.repo_descriptions:\n switch = self.get_new_switch(repo)\n\n self.handlers[switch.toggle] = switch.toggle.connect(\n 'state-set',\n self.on_suite_toggled\n )\n self.checks_grid.add(switch)\n switch.show_all()\n \n if self.system_repo:\n for suite in self.system_repo.suites:\n if suite in self.repo_descriptions:\n continue\n if 'proposed' in suite:\n # This is handled on the settings page.\n continue\n if self.distro_codename == suite:\n # Skip the standard distro suite.\n continue\n switch = self.get_new_switch(suite)\n self.handlers[switch.toggle] = switch.toggle.connect(\n 'state-set',\n self.on_suite_toggled\n )\n self.checks_grid.add(switch)\n switch.show_all()\n\n def show_updates(self):\n \"\"\" Initialize the state of all of the switches. \"\"\"\n self.log.debug(\"init_distro\")\n self.create_switches()\n self.block_handlers()\n \n for suite in self.checks_grid.get_children():\n if suite.suite in self.system_repo.suites:\n suite.toggle.set_active(True)\n else:\n suite.toggle.set_active(False)\n \n self.unblock_handlers()\n\n def set_suites_enabled(self, enabled):\n for suite in self.checks_grid.get_children():\n suite.set_sensitive(enabled)\n\n def on_suite_toggled(self, switch, state):\n \"\"\" state-set handler for suite switches. \"\"\"\n suites = self.system_repo.suites\n if state:\n if switch.suite not in suites:\n suites.append(switch.suite)\n else:\n if switch.suite in suites:\n suites.remove(switch.suite)\n self.system_repo.suites = suites\n try:\n self.system_repo.file.save()\n except Exception as err:\n self.log.error(\n 'Could not set suite: %s', str(err)\n )\n err_dialog = repo.get_error_messagedialog(\n self.parent.parent,\n f'Could not set suite',\n err,\n 'The system suite could not be changed'\n )\n err_dialog.run()\n err_dialog.destroy()\n\n def on_config_changed(self, monitor, file, other_file, event_type):\n self.log.debug('Installation changed, regenerating list')\n if self.system_repo:\n self.show_updates()\n self.set_suites_enabled(self.parent.setting.checks_enabled)\n","repo_name":"PikaOS-Linux/pkgs-baseos","sub_path":"repoman/archive/repoman/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":7336,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"52"}
+{"seq_id":"13208745856","text":"from Qt import QtGui\nfrom PyFlow.UI import RESOURCES_DIR\nfrom PyFlow.UI.Canvas.UINodeBase import UINodeBase\nfrom Qt.QtWidgets import QLabel\n\n\nclass UIImageDisplayNode(UINodeBase):\n def __init__(self, raw_node):\n super(UIImageDisplayNode, self).__init__(raw_node)\n self.resizable = True\n self.Imagelabel = QLabel(\"test3\")\n self.pixmap = QtGui.QPixmap(RESOURCES_DIR + \"/wizard-cat.png\")\n self.addWidget(self.Imagelabel)\n self.updateSize()\n self._rawNode.loadImage.connect(self.onLoadImage)\n\n def onLoadImage(self, imagePath):\n self.pixmap = QtGui.QPixmap(imagePath)\n self.updateSize()\n\n def paint(self, painter, option, widget):\n self.updateSize()\n super(UIImageDisplayNode, self).paint(painter, option, widget)\n\n def updateSize(self):\n scaledPixmap = self.pixmap.scaledToWidth(\n self.customLayout.geometry().width())\n self.Imagelabel.setPixmap(scaledPixmap)\n","repo_name":"wonderworks-software/PyFlow","sub_path":"PyFlow/Packages/PyFlowBase/UI/UIImageDisplayNode.py","file_name":"UIImageDisplayNode.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":2099,"dataset":"github-code","pt":"52"}
+{"seq_id":"37206623216","text":"import json\nimport optparse\nimport sys\nimport os\nfrom collections import OrderedDict\n\nimport xml.etree.cElementTree as ET\n\ndef strip_tag(tag):\n strip_ns_tag = tag\n split_array = tag.split('}')\n if len(split_array) > 1:\n strip_ns_tag = split_array[1]\n tag = strip_ns_tag\n return tag\n\n\ndef elem_to_internal(elem, strip_ns=1, strip=1):\n \"\"\"Convert an Element into an internal dictionary (not JSON!).\"\"\"\n\n d = OrderedDict()\n elem_tag = elem.tag\n if strip_ns:\n elem_tag = strip_tag(elem.tag)\n for key, value in list(elem.attrib.items()):\n d['@' + key] = value\n\n # loop over subelements to merge them\n for subelem in elem:\n v = elem_to_internal(subelem, strip_ns=strip_ns, strip=strip)\n\n tag = subelem.tag\n if strip_ns:\n tag = strip_tag(subelem.tag)\n\n value = v[tag]\n\n try:\n # add to existing list for this tag\n d[tag].append(value)\n except AttributeError:\n # turn existing entry into a list\n d[tag] = [d[tag], value]\n except KeyError:\n # add a new non-list entry\n d[tag] = value\n text = elem.text\n tail = elem.tail\n if strip:\n # ignore leading and trailing whitespace\n if text:\n text = text.strip()\n if tail:\n tail = tail.strip()\n\n if tail:\n d['#tail'] = tail\n\n if d:\n # use #text element if other attributes exist\n if text:\n d[\"#text\"] = text\n else:\n # text is the value if no attributes\n d = text or None\n return {elem_tag: d}\n \n\ndef elem2json(elem, options, strip_ns=1, strip=1):\n\n \"\"\"Convert an ElementTree or Element into a JSON string.\"\"\"\n\n if hasattr(elem, 'getroot'):\n elem = elem.getroot()\n \"\"\"\n if options.pretty:\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), indent=4, separators=(',', ': '))\n else:\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip))\n \"\"\"\n return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip)) \n\ndef xml2json(xmlstring, options, strip_ns=1, strip=1):\n\n \"\"\"Convert an XML string into a JSON string.\"\"\"\n\n elem = ET.fromstring(xmlstring)\n return elem2json(elem, options, strip_ns=strip_ns, strip=strip)","repo_name":"iconmix/skins-addons","sub_path":"script.iconmixtools/resources/lib/xml2json.py","file_name":"xml2json.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"26343946099","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# SPDX-License-Identifier: MIT\n\n\"\"\" Contains Edit Class to edit things in the store.\nStore is equivalent to owlready2 World \"\"\"\n\n# general imports\nfrom logging import Logger\nimport owlready2\nfrom typing import Union\n# causalgraph imports\nimport causalgraph.utils.owlready2_utils as owlutils\nfrom causalgraph.utils.misc_utils import strict_types\nfrom causalgraph.utils.logging_utils import init_logger\n\n\nclass Edit():\n \"\"\" Contains all methods to edit resources in the store\"\"\"\n def __init__(self, store: owlready2.World, logger: Logger = None, validate_domain_range: bool = True) -> None:\n self.store = store\n self.validate_domain_range = validate_domain_range\n if logger is not None:\n self.logger = logger\n else:\n self.logger = init_logger(\"Edit\")\n self.logger.info(\"Initialized the 'edit' functionalities.\")\n\n\n @strict_types\n def rename_individual(self, old_name_obj: Union[str, owlready2.Thing], new_name: str) -> bool:\n \"\"\"This method changes the name of an individual. To change it, pass the old name or the\n the individual it self as well as the new desired name. The return value is True if the\n change was successful, False if not.\n\n :param old_name_obj: The object of the individual to be changed or its name as str.\n :type old_name_obj: Union[str, owlready2.Thing],\n :param new_name: Desired new name of the individual\n :type new_name: str\n :return: True if renaming was successful, False if not.\n :rtype: bool\n \"\"\"\n indi_old_name_name, ind_old_name_obj = owlutils.get_name_and_object(old_name_obj, self.store)\n\n # If a Thing was passed, then check if it (still) exists\n if ind_old_name_obj is None:\n self.logger.warning(f\"Name change not successful because the individual '{indi_old_name_name}'\" +\n \" does not exist.\")\n return False \n # Check if new_name is already taken\n indi_new_name_obj = owlutils.get_entity_by_name(new_name, self.store, suppress_warn=True)\n if indi_new_name_obj is not None:\n self.logger.warning(f\"Name change not successful because the new name '{new_name}'\" +\n \" is already taken.\")\n return False\n # Renaming individuals and check success\n ind_old_name_obj.name = new_name\n # Success check not absolutely necessary, but in there for safety's sake.\n ind_old_name_obj = owlutils.get_entity_by_name(indi_old_name_name, self.store, suppress_warn=True)\n indi_new_name_obj = owlutils.get_entity_by_name(new_name, self.store, suppress_warn=True)\n self.store.save()\n if ind_old_name_obj is None and indi_new_name_obj is not None:\n self.logger.info(f\"Renaming individual '{indi_old_name_name}' to '{new_name}' has been successful.\")\n return True\n self.logger.warning(f\"Something went wrong while renaming '{indi_old_name_name}' to '{new_name}'\" +\n \" although the required name is not taken.\")\n return False\n\n\n @strict_types\n def type_to_subtype(self, entity: Union[str, owlready2.Thing], new_type: Union[str, owlready2.EntityClass]) -> bool:\n \"\"\"This method changes the type of an individual. Only subtypes are allowed as new types.\n To change the type, pass the name of the individual and the new desired (sub)type.\n The return value is True if the type change was successful, False if not or the new\n type is the same as the current one.\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param new_type: The name of the new (sub)type or the owlready EntityClass object.\n :type new_type: Union[str, owlready2.EntityClass]\n :return: True if type change was successful, False if not or type didn't change\n :rtype: bool\n \"\"\"\n individual_name, individual_obj = owlutils.get_name_and_object(entity, self.store)\n # Exit func if individual does not exist\n if individual_obj is None:\n self.logger.error(f\"Changing subtype failed. Entity '{individual_name}' does not exist.\")\n return False\n # Initiate empty lists for collecting types that should (not) be changed\n types_to_keep = []\n types_to_update = []\n\n # Get new subtype object and check if it exists\n new_subtype_name, new_subtype_obj = owlutils.get_name_and_object(new_type, self.store)\n if new_subtype_obj == None:\n self.logger.warning(f'Changing subtype failed. New subtype {new_type} does not ' +\n 'exist in the Ontology.')\n return False\n # Check if subtype is valid for passed individual\n for current_type in individual_obj.is_a:\n current_type_subtypes = owlutils.get_subclasses(current_type, self.store)\n # If new type is a valid subtype of the old type: substitute old type, else: keep type\n if [new_subtype_obj] in current_type_subtypes:\n types_to_update.append(current_type)\n else:\n types_to_keep.append(current_type)\n # The list \"types_to_update\" will be empty if there is currently no type that is related to\n # \"new_type\" and therefore also not allowed to be specialized in the subtype \"new_type\"\n if types_to_update == []:\n self.logger.warning(f\"None of the current types of '{individual_name}' is allowed to be\" +\n f\"changed to the subtype {new_subtype_name}\")\n return False\n # Generate list of new types from types_to_keep and new_subtype_obj\n new_types = types_to_keep\n new_types.append(new_subtype_obj)\n # Swap current types of individual with new ones\n individual_obj.is_a = new_types\n self.store.save()\n types_to_update_names = [i.name for i in types_to_update]\n self.logger.info(f'Changing type(s) { {*types_to_update_names} } to {new_subtype_name} successful.')\n return True\n\n\n @strict_types\n def properties(self, entity: Union[str, owlready2.Thing], prop_dict: dict) -> bool:\n \"\"\"Updates the properties of an individual with the properties\n and values given in the dictionary.\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param prop_dict: Dictionary containing properties and their new values\n :type prop_dict: dict\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n update_prop_result = owlutils.update_properties_of_individual(individual=individual_name,\n logger=self.logger,\n store=self.store,\n prop_dict=prop_dict,\n validate_domain_range=self.validate_domain_range)\n return update_prop_result\n\n\n @strict_types\n def property(self, entity: Union[str, owlready2.Thing], property: Union[str, owlready2.PropertyClass], value) -> bool:\n \"\"\"Updates one property of an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param property: The property name or the owlready PropertyClass object.\n :type property: Union[str, owlready2.PropertyClass]\n :param value: New value of the property\n :type value: _type_\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n property_name, _ = owlutils.get_name_and_object(property, self.store)\n prop_dict = {property_name: value}\n return self.properties(individual_name, prop_dict)\n\n\n @strict_types\n def delete_property(self, entity: Union[str, owlready2.Thing], property: Union[str, owlready2.PropertyClass]) -> bool:\n \"\"\"Deletes a property from an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param property_name: Property to be deleted, passed as name string or the owlready PropertyClass object.\n :type property_name: Union[str, owlready2.PropertyClass]\n :return: True if deletion successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n property_name, _ = owlutils.get_name_and_object(property, self.store)\n prop_dict = {property_name: None}\n return self.properties(individual_name, prop_dict)\n\n\n @strict_types\n def description(self, entity: Union[str, owlready2.Thing], new_comment: list) -> bool:\n \"\"\"Sets/changes the description (comment) of an individual\n\n :param entity: The individual object to be changed or its name.\n :type entity: Union[str, owlready2.Thing]\n :param new_comment: New description as a list of strings\n :type new_comment: list\n :return: True if update successful, else False\n :rtype: bool\n \"\"\"\n individual_name, _ = owlutils.get_name_and_object(entity, self.store)\n return self.property(individual_name, 'comment', new_comment)\n ","repo_name":"causalgraph/causalgraph","sub_path":"causalgraph/store/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":9741,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"52"}
+{"seq_id":"33639072590","text":"# Databricks notebook source\n# MAGIC %md\n# MAGIC ## Overview: Evaluating risk for loan approvals using a gradient boosted tree classifier\n# MAGIC ### Data: Public data from Lending Club including all funded loans from 2012 to 2017\n\n# COMMAND ----------\n\n# DBTITLE 1,Imports\nfrom pyspark.sql.functions import regexp_replace, substring, trim, round, col\nfrom pyspark.ml.classification import GBTClassifier\nfrom pyspark.mllib.evaluation import BinaryClassificationMetrics\nfrom pyspark.ml.linalg import Vectors\n\n# COMMAND ----------\n\n# DBTITLE 1,Functions\ndef extract(row):\n return (row.net,) + tuple(row.probability.toArray().tolist()) + (row.label,) + (row.prediction,)\n\ndef score(model,data):\n pred = model.transform(data).select(\"net\", \"probability\", \"label\", \"prediction\")\n pred = pred.rdd.map(extract).toDF([\"net\", \"p0\", \"p1\", \"label\", \"prediction\"])\n return pred \n\ndef auc(pred):\n metric = BinaryClassificationMetrics(pred.select(\"p1\", \"label\").rdd)\n return metric.areaUnderROC\n\n# COMMAND ----------\n\n# DBTITLE 1,Load Data\n# location of loanstats_2012_2017.parquet\nSOURCE = \"/databricks-datasets/samples/lending_club/parquet/\"\n\n# Read parquet\ndf = spark.read.parquet(SOURCE)\n\n# split the data\n(loan_sample, loan_other) = df.randomSplit([0.025, 0.975], seed=123)\n\n# Select only the columns needed\nloan_col = [\"loan_status\", \"int_rate\", \"revol_util\", \"issue_d\", \"earliest_cr_line\", \"emp_length\", \"verification_status\", \"total_pymnt\",\n \"loan_amnt\", \"grade\", \"annual_inc\", \"dti\", \"addr_state\", \"term\", \"home_ownership\", \"purpose\", \"application_type\", \"delinq_2yrs\", \"total_acc\"]\nloan_sample = loan_sample.select(loan_col)\n\n# COMMAND ----------\n\n# Print out number of loans\nprint(str(loan_sample.count()) + \" available loans\")\n\n# COMMAND ----------\n\ndisplay(loan_sample)\n\n# COMMAND ----------\n\n# DBTITLE 1,Munge Data\n# Create bad loan label, this will include charged off, defaulted, and late repayments on loans\nloan_sample_categorical = (loan_sample\n .filter(col('loan_status').isin([\"Default\", \"Charged Off\", \"Fully Paid\"]))\n .withColumn(\"bad_loan\", (col('loan_status') != \"Fully Paid\").cast(\"string\"))\n )\n# Map multiple categories into one\nloan_stats_categorical = loan_sample_categorical.withColumn('verification_status', trim(regexp_replace('verification_status', 'Source Verified', 'Verified')))\n\n# Turning string interest rate and revoling util columns into numeric columns\nloan_sample_numeric = (loan_sample_categorical\n .withColumn('int_rate', regexp_replace('int_rate', '%', '').cast('float'))\n .withColumn('revol_util', regexp_replace('revol_util', '%', '').cast('float'))\n .withColumn('issue_year', substring('issue_d', 5, 4).cast('double') )\n .withColumn('earliest_year', substring('earliest_cr_line', 5, 4).cast('double'))\n )\nloan_sample_numeric = loan_sample_numeric.withColumn('credit_length_in_years', (col('issue_year') - col('earliest_year')))\n\n# Converting emp_length column into numeric\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"([ ]*+[a-zA-Z].*)|(n/a)\", \"\") ))\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"< 1\", \"0\") ))\nloan_sample_numeric = loan_sample_numeric.withColumn('emp_length', trim(regexp_replace('emp_length', \"10\\\\+\", \"10\") ).cast('float'))\n\n# Calculate the total amount of money earned or lost per loan\nloan_stats = loan_sample_numeric.withColumn('net', round(col('total_pymnt') - col('loan_amnt'), 2))\n\n# COMMAND ----------\n\ndisplay(loan_stats)\n\n# COMMAND ----------\n\n# DBTITLE 1,Train/Test Split\n# Create train/test split\nmyY = \"bad_loan\"\ncategorical_col = [\"term\", \"home_ownership\", \"purpose\", \"addr_state\",\n \"verification_status\",\"application_type\"]\nnumeric_col = [\"loan_amnt\",\"emp_length\", \"annual_inc\", \"dti\", \"delinq_2yrs\",\n \"revol_util\", \"total_acc\", \"credit_length_in_years\"]\nmyX = categorical_col + numeric_col\n\nloan_stats2 = loan_stats.select(myX + [myY, \"int_rate\", \"net\", \"issue_year\"])\ntrain = loan_stats2.filter(col('issue_year') <= 2015).cache()\nvalid = loan_stats2.filter(col('issue_year') > 2015).cache()\n\n# COMMAND ----------\n\n# DBTITLE 1,Build GBT Pipeline\n# Establish stages for our GBT model\nindexers = map(lambda c: StringIndexer(inputCol=c, outputCol=c+\"_idx\", handleInvalid = 'keep'), categorical_col)\nimputers = Imputer(inputCols = numeric_col, outputCols = numeric_col)\nfeatureCols = list(map(lambda c: c+\"_idx\", categorical_col)) + numeric_col\n\n# Define vector assemblers\nmodel_matrix_stages = (list(indexers) + [imputers] +\n [VectorAssembler(inputCols=featureCols, outputCol=\"features\"), StringIndexer(inputCol=\"bad_loan\", outputCol=\"label\")])\n\n# Define a GBT model\ngbt = GBTClassifier(featuresCol=\"features\",\n labelCol=\"label\",\n lossType = \"logistic\",\n maxBins = 52,\n maxIter=20,\n maxDepth=5)\n\n# Chain indexer and GBT in a Pipeline\npipeline = Pipeline(stages=model_matrix_stages+[gbt])\n\n# Train model\ngbt_model = pipeline.fit(train)\n\n# COMMAND ----------\n\n# DBTITLE 1,Score Data\ngbt_train = score(gbt_model, train)\ngbt_valid = score(gbt_model, valid)\n\nprint (\"GBT Training AUC :\" + str(auc(gbt_train)))\nprint (\"GBT Validation AUC :\" + str(auc(gbt_valid)))\n\n# COMMAND ----------\n\ndisplay(gbt_valid)\n\n# COMMAND ----------\n\n\n","repo_name":"jsbellamy/Pyspark","sub_path":"ML_pipeline/loan_risk_classifier.py","file_name":"loan_risk_classifier.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"36848215868","text":"from django.urls import path\nfrom .views import userView, loginUser, logoutUser, registerUser, editUser, deleteUser\n\n\nurlpatterns = [\n path('', userView, name='user'),\n path('login/', loginUser, name='login'),\n path('logout/', logoutUser, name='logout'),\n path('register/', registerUser, name='register'),\n path('edit/', editUser, name='edit_user'),\n path('delete/', deleteUser, name='delete_user')\n]\n","repo_name":"twergi/red_an","sub_path":"red_an/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"43695137252","text":"#!/usr/bin/env python\n\n\"\"\"\nThis script downloads weather buoy data\nand stores it into csv files, one for each buoy.\n\"\"\"\n\nfrom ndbc import Station\nfrom datetime import datetime\nimport numpy as np\n\n\ndef write_buoy_to_csv(buoyid, startyear, endyear):\n s = Station(buoyid, datetime(startyear, 1, 1), datetime(endyear, 1, 1))\n\n s.atmp[s.atmp > 900] = np.nan\n s.dewp[s.dewp > 900] = np.nan\n s.wtmp[s.wtmp > 900] = np.nan\n s.wvht[s.wvht > 90] = np.nan\n s.apd[s.apd > 90] = np.nan\n\n with open('buoy_' + str(buoyid) + '.csv', 'w') as f:\n for n in range(s.time.size):\n record = [\n s.time[n].strftime('%Y-%m-%d_%H:%M:%S'),\n '%5.1f' % s.wspd[n],\n '%7.1f' % s.pres[n],\n '%5.1f' % s.atmp[n],\n '%5.1f' % s.dewp[n],\n '%5.1f' % s.wtmp[n],\n '%7.2f' % s.wvht[n],\n '%7.2f' % s.apd[n],\n ]\n f.write(','.join(record) + '\\n')\n\n\nbuoys = [42001, 42002, 42003, 42020, 42035, 42036, 42039, 42040, 42055]\n\nfor buoy in buoys:\n print('processing buoy:', buoy)\n write_buoy_to_csv(buoy, 2005, 2017)\n","repo_name":"modern-fortran/weather-buoys","sub_path":"data/get_buoy.py","file_name":"get_buoy.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"}
+{"seq_id":"7896853969","text":"T = int(input())\nfor t in range(1, T+1):\n pat = input()\n txt = input()\n N, M = len(txt), len(pat)\n result = 0\n is_terminate = False\n for i in range(N-M+1):\n for j in range(M):\n if txt[i+j] != pat[j]:\n break\n elif txt[i+j] == pat[j] and j == M-1:\n result = 1\n is_terminate = True\n if is_terminate:\n break\n print(f\"#{t} {result}\")","repo_name":"Going777/Algorithm","sub_path":"SWEA/D2/4864_문자열 비교.py","file_name":"4864_문자열 비교.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"69867148965","text":"from urllib.request import urlopen\nimport re\nimport time\n\n\n# Create our results file and add headers\noutfile = open('docker_hiera.csv', 'w')\noutfile.write(\"Name,Parent,Parent2\\n\")\n\n# Open list of repos to check\nwith open('docker_images.csv') as master_list:\n\trepo_list = master_list.read().splitlines()\n\n# Iterate through list of repos and find parent images (only does one level atm)\nfor repo in repo_list:\n\trepo = repo.rstrip()\n\toutfile.write(repo)\n\toutfile.write(\",\")\n\t# outfile.write(repo)\n\tcurrent_url = \"https://raw.githubusercontent.com/{}/master/Dockerfile\".format(repo)\n\ttry:\n\t\tdockerfile = urlopen(current_url).read().decode(\"utf-8\")\n\t\tresults = re.findall(r'FROM.*\\n',str(dockerfile))\n\t\tfor image in results:\n\t\t\toutfile.write(results[0][5:-1])\n\t\t\toutfile.write(\",\")\n\t\toutfile.write(\"\\n\")\n\t\t# outfile.write(results[5:-1])\n\texcept:\n\t\toutfile.write(\"\\n\")\n\t# Pause for 1 second to avoid hitting GitHub read limits\n\ttime.sleep(1)\n","repo_name":"jsfillman/image_hiera","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5393919350","text":"# 进程\n#\n# 一个程序的执行实例就是一个进程。每一个进程提供执行程序所需的所有资源(进程本质上是资源的集合)。\n# 一个进程有一个虚拟的地址空间、可执行的代码、操作系统的接口、安全的上下文(记录启动该进程的用户和权限等)、\n# 唯一的进程ID、环境变量、优先级类、最小和最大的工作空间(内存空间),还要至少一个进程。\n#\n# 与进程相关的资源包括:\n# 内存页(同一个进程中的所有线程共享同一个内存空间)\n# 文件描述符(e.g.open sockets)\n# 安全凭证(e.g.启动该进程的用户ID)\n# 每启动一个子进程就从父进程克隆一份数据,进程之间的数据本身是不能共享的。\nfrom multiprocessing import Process\nimport time, os\n\n\ndef func(title):\n print(title)\n print(\"modle_name: \", __name__)\n print(\"parent_name: \", os.getppid()) # 获取父进程ID\n print(\"process_id: \", os.getpid()) # 获取自己的进程ID\n\n\ndef f(name):\n func(\"\\033[31;1m function f\\033[0m\")\n print(time.time())\n print(\"hello\", name)\n\n\nif __name__ == '__main__':\n func('\\033[32;1m main process line \\033[0m')\n name_list = (\"jack\", \"bob\")\n for item in name_list:\n p = Process(target=f, args=(item,))\n p.start()\n p.join()\n\"\"\"\n main process line\nmodle_name: __main__\nparent_name: 15876\nprocess_id: 9992\n function f\nmodle_name: __mp_main__\nparent_name: 9992\nprocess_id: 12044\n1557472080.023705\nhello jack\n function f\nmodle_name: __mp_main__\nparent_name: 9992\nprocess_id: 4988\n1557472080.232705\nhello bob\n\"\"\"\n","repo_name":"johnsonliu33/myPythonProject","sub_path":"utils/multithreading_Multiprocess/multiprocess.py","file_name":"multiprocess.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34406180065","text":"import base64\nfrom random import sample\n\nSAMPLE_MAIL_URL_STR = \"https://mail.google.com/mail?authuser=EMAILADDRESS#all/MESSAGEID\"\n\n\ndef _get_from_base64(base64_message):\n return base64.urlsafe_b64decode(base64_message)\n\n\ndef get_participant_email(service):\n user_details = service.users().getProfile(userId='me').execute()\n return user_details.get(\"emailAddress\", None)\n\n\ndef read_emails(service, fro, to):\n email_list = []\n emails = service.users().messages().list(userId=\"me\",\n q=\"after:\" +\n fro.strftime(\n \"%Y/%m/%d\") + \" before:\" + to.strftime(\"%Y/%m/%d\"),\n maxResults=1000\n ).execute()\n progress = 0\n for email in emails[\"messages\"]:\n email_dict = {}\n email_dict[\"id\"] = email[\"id\"]\n email_info = service.users().messages().get(\n userId=\"me\", id=email[\"id\"]).execute()\n email_dict[\"labels\"] = email_info[\"labelIds\"]\n for header in email_info[\"payload\"][\"headers\"]:\n if header[\"name\"] == \"To\":\n email_dict[\"to\"] = header[\"value\"]\n elif header[\"name\"] == \"Date\":\n email_dict[\"timestamp\"] = header[\"value\"]\n elif header[\"name\"] == \"From\":\n email_dict[\"from\"] = header[\"value\"]\n elif header[\"name\"] == \"Subject\":\n email_dict[\"subject\"] = header[\"value\"]\n try:\n if email_info[\"payload\"][\"body\"].get(\"data\"):\n email_dict[\"body\"] = str(_get_from_base64(\n email_info[\"payload\"][\"body\"][\"data\"]))\n elif len(email_info[\"payload\"][\"parts\"]) > 0:\n for part in email_info[\"payload\"][\"parts\"]:\n if part[\"mimeType\"] == \"text/plain\" or part[\"mimeType\"] == \"text/html\":\n email_dict[\"body\"] = str(\n _get_from_base64(part[\"body\"][\"data\"]))\n else:\n email_dict[\"body\"] = None\n except KeyError as _:\n email_dict[\"body\"] = None\n\n # thread information\n thread_info = service.users().threads().get(\n userId=\"me\", id=email[\"threadId\"]).execute()\n email_dict[\"thread\"] = []\n for message in thread_info[\"messages\"]:\n minimal_cur_thread_info = {}\n for header in message[\"payload\"][\"headers\"]:\n if header[\"name\"] == \"To\":\n minimal_cur_thread_info[\"to\"] = header[\"value\"]\n elif header[\"name\"] == \"Date\":\n minimal_cur_thread_info[\"timestamp\"] = header[\"value\"]\n elif header[\"name\"] == \"From\":\n minimal_cur_thread_info[\"from\"] = header[\"value\"]\n email_dict[\"thread\"].append(minimal_cur_thread_info)\n email_list.append(email_dict)\n progress += 1\n print(f\"INFO: Fetched {progress} out of {len(emails['messages'])} emails\", end=\"\\r\", flush=True)\n return email_list\n\n\ndef get_sample_each_type(label_list, num_samples, participant_email):\n sample_mail_url = SAMPLE_MAIL_URL_STR.replace(\n \"EMAILADDRESS\", participant_email)\n all_tracking = set([x for x in range(len(label_list))])\n with_tracking = set()\n for ind in range(len(label_list)):\n if label_list[ind][\"has_open_tracking\"] or label_list[ind][\"has_click_tracking\"]:\n with_tracking.add(ind)\n without_tracking = all_tracking - with_tracking\n tracked = []\n non_tracked = []\n try:\n tracked = sample(with_tracking, num_samples)\n non_tracked = sample(without_tracking, num_samples)\n except ValueError:\n pass\n tracked = [sample_mail_url.replace(\n \"MESSAGEID\", label_list[x][\"id\"]) for x in tracked]\n non_tracked = [sample_mail_url.replace(\n \"MESSAGEID\", label_list[x][\"id\"]) for x in non_tracked]\n return tracked, non_tracked\n","repo_name":"thealphadollar/Blink","sub_path":"blink/collector.py","file_name":"collector.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"38920285031","text":"import operator\nfrom random import shuffle\n\n\nclass Node:\n\n def __init__(self, data) -> None:\n self.data = data\n self.next = None\n\n def __repr__(self):\n return f'Node({self.data!r})'\n\n def __str__(self):\n return f'{self.data!r}'\n\n\nclass LinkedList:\n\n all: list[\"LinkedList\"] = []\n\n def __init__(self, head) -> None:\n try:\n iter(head)\n except TypeError:\n raise NotImplementedError('head must be iterable')\n self.__nodes = self.__nodize(head)\n LinkedList.all.append(self)\n\n def __repr__(self):\n cls_name = type(self).__name__\n return f\"{cls_name}({' -> '.join([str(node) for node in self][:5])} -> ...)\"\n\n def __str__(self):\n return ' -> '.join([str(node) for node in self]) + ' -> None'\n\n def __len__(self):\n return len(self.__nodes)\n\n def __iter__(self):\n return iter(self.__nodes)\n\n def __getitem__(self, key):\n if isinstance(key, slice):\n cls = type(self)\n return cls(self.__nodes[key])\n key = operator.index(key)\n return self.__nodes[key]\n\n def __setitem__(self, key, new_node):\n if not isinstance(new_node, Node):\n new_node = Node(new_node)\n self.__nodes[key] = new_node\n self.__nodize(self.__nodes)\n\n def __delitem__(self, key):\n del self.__nodes[key]\n self.__nodize(self.__nodes)\n\n def __iadd__(self, other):\n cls = type(self)\n if isinstance(other, cls):\n self.__nodes.extend(other)\n else:\n try:\n self.__nodes.extend(other)\n except TypeError:\n msg = (\n f\"right operand in += must be '{cls.__name__}' or an iterable\")\n raise TypeError(msg) from None\n self.__nodize(self.__nodes)\n return self\n\n def __add__(self, other):\n cls = type(self)\n if isinstance(other, cls):\n return cls(self.__nodize(self.__nodes + other.__nodes))\n else:\n return NotImplemented\n\n def reverse(self):\n self.__nodes = self.__nodes[::-1]\n self.__nodize(self.__nodes)\n\n def shuffle(self):\n shuffle(self.__nodes)\n self.__nodize(self.__nodes)\n\n def insert_node(self, key, new_node):\n if not isinstance(new_node, Node):\n new_node = Node(new_node)\n self.__nodes.insert(key, new_node)\n self.__nodize(self.__nodes)\n\n def __nodize(self, iterable):\n nodes = list(iterable)\n nodes = [node if isinstance(node, Node) else Node(node)\n for node in nodes]\n self.head = nodes[0]\n current_node = self.head\n for i in range(1, len(nodes)):\n current_node.next = nodes[i]\n current_node = current_node.next\n return nodes\n\n @classmethod\n def from_file(cls, filename):\n with open(filename, 'r') as file:\n lines = file.readlines()\n for line in lines:\n head = ''.join(char for char in line if char.isalnum())\n if head:\n cls(head)\n","repo_name":"shadowy-pycoder/learning_python","sub_path":"LinkedList2.py","file_name":"LinkedList2.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18677593957","text":"# library\n\nimport gensim\nimport pandas as pd\nimport numpy as np\nimport random\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.utils.data as Data\n\ndata=pd.read_table('train.tsv',sep='\\t')\n# texts=data['Phrase'].tolist()\ndata_y=data[\"Sentiment\"]\ndata_y=np.array(data_y)\nN=len(data_y)\n\ndel(data)\n\nwords_ls=pd.read_table('words_ls.txt',header=None)[0]\nwords_ls=[eval(words) for words in words_ls]\n\nword_maxlen=0\nfor words in words_ls:\n word_maxlen=max(word_maxlen,len(words))\n\nword2vec = gensim.models.KeyedVectors.load_word2vec_format(\"GoogleNews-vectors-negative300.bin.gz\", binary=True)\n\n# Hyper Parameters\nLEN_SEN = word_maxlen\nVEC_LEN = 300\n\n# CNN Architecture\nclass CNN(nn.Module):\n def __init__(self,n_window = 3,vec_len=300):\n self.window = n_window\n self.vec_len = vec_len\n super(CNN, self).__init__()\n self.conv1 = nn.Sequential( # input shape (1, 28, 28)\n nn.Conv2d(\n in_channels=1, # input height\n out_channels=16, # n_filters\n kernel_size=(self.window,self.vec_len), # filter size\n stride=(1,self.vec_len), # filter movement/step\n \n ), # output shape (16, 28, 28)\n nn.ReLU(), # activation\n nn.MaxPool2d(kernel_size=(LEN_SEN-self.window+1,1),stride=(LEN_SEN-self.window+1,1)), \n )\n\n self.out = nn.Linear(16, 5) # fully connected layer, output 10 classes\n\n def forward(self, x):\n x = self.conv1(x)\n x = x.view(x.size(0), -1) # flatten the output of conv2 to (batch_size, 32 * 7 * 7)\n output = self.out(x)\n return output, x # return x for visualization\n \n# Word Vectors Generation (to tensor)\ndef wv_to_tensor(inds,t_height=word_maxlen,v_length=VEC_LEN,WV=word2vec):\n l=len(inds)\n wordvec=np.zeros([l,1,t_height,v_length]) # dimension \n for i in range(l):\n words=words_ls[inds[i]]\n n=len(words)\n if n>0: \n try:\n wordvec[i,0,:n,:]=WV[words]\n except KeyError:\n for h in range(n):\n try:\n wordvec[i,0,h,:]=WV[words[h]].reshape(1,v_length)\n except KeyError:\n wordvec[i,0,h,:]=np.random.randn(1,v_length)/10\n # 到此 wordvec的type还是np.array, need to convert to torch.tensor\n return torch.from_numpy(wordvec).to(torch.float32)\n\n\n\ndef train(EPOCH = 2 ,BATCH_SIZE = 200,LR = 0.01,n_window = 3,wv=word2vec):\n \n cnn = CNN(n_window)\n optimizer = torch.optim.Adam(cnn.parameters(), lr=LR) # optimize all cnn parameters\n loss_func = nn.CrossEntropyLoss() # the target label is not one-hotted\n\n train_inds=random.sample(range(N),np.int(np.floor(N*0.8)))\n test_inds=list(set(range(N))-set(train_inds))\n\n mat=np.concatenate((np.arange(N).reshape(N,1),data_y.reshape(N,1)),axis=1)\n train_loader = Data.DataLoader(dataset=mat[train_inds,:], batch_size=BATCH_SIZE, shuffle=True)\n test_x=wv_to_tensor(inds=mat[test_inds,0],WV=wv)\n test_y=torch.from_numpy(mat[test_inds,1])\n\n for epoch in range(EPOCH):\n for step, batch_data in enumerate(train_loader): # gives batch data, normalize x when iterate train_loader\n b_x_ind = batch_data[:,0] # batch x\n b_y = batch_data[:,1] # batch y\n b_x = wv_to_tensor(inds=b_x_ind,WV=wv)\n\n output = cnn(b_x)[0] # cnn output\n loss = loss_func(output, b_y) # cross entropy loss\n optimizer.zero_grad() # clear gradients for this training step\n loss.backward() # backpropagation, compute gradients\n optimizer.step() # apply gradients\n\n if step % 100 == 0:\n test_output, last_layer = cnn(test_x)\n pred_y = torch.max(test_output, 1)[1].data.squeeze()\n accuracy = (pred_y == test_y).sum().item() / float(test_y.size(0))\n print('Epoch: ', epoch, '| Step: ', step, '| train loss: %.4f' % loss.data, '| test accuracy: %.2f' % accuracy)\n return (cnn,accuracy)\n\n\ncnn10,acc10=train(n_window=10,wv=word2vec)\nprint('test accuracy: %.2f' % accuracy)\ntorch.save(cnn10, 'cnn-w10.pkl') # save entire net","repo_name":"AllenLI20/NLP-Basic-Tasks","sub_path":"Task2/cnn_train.py","file_name":"cnn_train.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40617475969","text":"# Merge k sorted linked lists and return it as one sorted list.\n##############################################################################################################################################\nfrom queue import PriorityQueue\n\n\nclass Node:\n def __init__(self, initdata):\n self.data = initdata\n self.next = None\n\n def getData(self):\n return self.data\n\n def getNext(self):\n return self.next\n\n def setData(self, newdata):\n self.data = newdata\n\n def setNext(self, newnext):\n self.next = newnext\n\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n def insert(self, data):\n new_node = Node(data)\n new_node.setNext(\n self.head) # set new_node tro den phan tu dau tien (self.head tro den phan tu dau tien cua list)\n self.head = new_node # head of the list tro den new_node\n\n def size(self):\n current = self.head # bat dau tu phan tu dau tien\n count = 0\n while current: # break when current=None, tuc la phan tu cuoi cung\n count += 1\n current = current.getNext()\n return count\n\n def search(self, item):\n current = self.head\n found = False\n while current is not None and not found:\n if (current.getData() != item):\n current = current.getNext()\n else:\n found = True\n return found\n\n def remove(self, item):\n current = self.head\n previous = None\n found = False\n while current is not None and not found:\n if (current.getData() != item):\n previous = current\n current = current.getNext()\n else:\n found = True\n if current == None: # if item is not in the list\n raise ValueError(\"Data is not in the list\")\n # if item is the first element\n if previous == None:\n self.head = current.getNext()\n else: # cho du current la phan tu cuoi cung thi current.getNext() se return None\n previous.setNext(current.getNext())\n\n def insert_tail(self, item):\n current = self.head\n previous = None\n while current:\n previous = current\n current = current.getNext()\n # after the while, the previous will be the last element\n new_node = Node(item) # new_node will have default Next =None\n previous.setNext(new_node)\n\n def listall(self):\n current = self.head\n while current:\n print(current.getData())\n current = current.getNext()\n\n\nclass Solution(object):\n def MergeKLists(self, linkedlist1, linkedlist2, linkedlist3):\n self.q = []\n iter1 = linkedlist1.head\n while iter1:\n self.q.append(iter1.getData())\n iter1 = iter1.getNext()\n iter2 = linkedlist2.head\n while iter2:\n self.q.append(iter2.getData())\n iter2 = iter2.getNext()\n iter3 = linkedlist3.head\n while iter3:\n self.q.append(iter3.getData())\n iter3 = iter3.getNext()\n # for i in kwargs:\n # iter = i.head\n # while iter:\n # self.nodes.append(iter.getData())\n # iter = iter.getNext()\n print(self.q)\n self.q = sorted(self.q)\n head = point = LinkedList()\n for i in self.q:\n point.insert(i)\n point.listall()\n\n ##############################################################################################################################################\n # using PriorityQueue.\n # from queue import PriorityQueue\n def MergeKLists2(self, linkedlist1, linkedlist2, linkedlist3):\n q = PriorityQueue()\n iter1 = linkedlist1.head\n while iter1:\n q.put((iter1.getData(), iter1))\n iter1 = iter1.getNext()\n iter3 = linkedlist3.head\n while iter3:\n q.put((iter3.getData(), iter3))\n iter3 = iter3.getNext()\n iter2 = linkedlist2.head\n while iter2:\n q.put((iter2.getData(), iter2))\n iter2 = iter2.getNext()\n print(q)\n head = point = LinkedList()\n while not q.empty():\n data, Node = q.get()# why\n print(data)\n point.insert(LinkedList(data))\n point.listall()\n\n\nlinkedlist1 = LinkedList()\nlinkedlist1.insert(1)\nlinkedlist1.insert(3)\nlinkedlist1.insert(6)\nlinkedlist1.insert(12)\nlinkedlist1.insert(25)\nlinkedlist1.insert(67)\nprint(\"list1\", linkedlist1.listall())\nlinkedlist2 = LinkedList()\nlinkedlist2.insert(3)\nlinkedlist2.insert(5)\nlinkedlist2.insert(15)\nlinkedlist2.insert(18)\nlinkedlist2.insert(25)\nlinkedlist2.insert(69)\nprint(\"list2\", linkedlist2.listall())\nlinkedlist3 = LinkedList()\nlinkedlist3.insert(9)\nlinkedlist3.insert(17)\nlinkedlist3.insert(25)\nlinkedlist3.insert(28)\nlinkedlist3.insert(29)\nlinkedlist3.insert(49)\nprint(\"list3\", linkedlist3.listall())\n\nsolution = Solution()\nsolution.MergeKLists2(linkedlist1, linkedlist2, linkedlist3)\n","repo_name":"KennyTC/Algorithm","sub_path":"LinkedList/MergeKList.py","file_name":"MergeKList.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23785637734","text":"import time\n\nimport numpy as np\n\nfrom environment.vksp import VisualKspEnv\nfrom agent.random import RandomAgent\nimport analysis.plot as analysis_plot\n\nprint('Creating environment data ...')\nstart = time.time()\n\n# reproducibility\nnp.random.seed(0)\n\n# n must be a perfect square\nenv = VisualKspEnv(n=9, k=2, T=1000, is_render=True)\nagent = RandomAgent(env.k, is_plot=True)\n\n# analysis parameters\nreward_data, R = [], []\nacc_rew_size = 100\n\n# start agent-env interaction\nfor t in range(env.T):\n\n if env.is_render:\n env.render()\n\n a = agent.policy()\n o, r, done = env.step(a)\n\n # compute the accumulated reward\n reward_data.append(r)\n _, div = divmod(t, acc_rew_size)\n\n if div == 0:\n acc_rew = sum(reward_data)\n print('ep: {} reward (mean): {}'.format(t, acc_rew))\n if agent.is_plot:\n agent.plot_reward(t, acc_rew)\n reward_data.clear()\n\n if done:\n acc_rew = np.sum(reward_data)\n print('ep: {} reward (mean): {}'.format(t, acc_rew))\n if agent.is_plot:\n agent.plot_reward(t, acc_rew)\n R.append(acc_rew)\n\n\nfinish = time.time() - start\nprint('Running time {} sec'.format(finish))\n\nanalysis_plot.plot_accumulated_reward(R)\n","repo_name":"ramonlins/kserver","sub_path":"run_random_vksp.py","file_name":"run_random_vksp.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"969054962","text":"class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n history = set()\n pre = 0\n for i, n in enumerate(nums): \n cur = (pre + n) % k\n if i > 0 and (cur == 0 or n % k == 0 and nums[i - 1] % k == 0 or n % k != 0 and cur in history): \n return True\n \n history.add(cur)\n pre = cur\n \n return False","repo_name":"mathewhany/leetcode-solutions","sub_path":"0523-continuous-subarray-sum/0523-continuous-subarray-sum.py","file_name":"0523-continuous-subarray-sum.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"13802824376","text":" # incremental build model\n #https://github.com/ksmielke/python-w12\n# kimberly mielke\n # CSCI 102 – Section A \n# Week 12 - Part A \n\n\n\n#1\ndef PrintOutput(x):\n print('OUTPUT', x)\n\n#2\ndef LoadFile(x):\n lis = []\n txt = open(x, 'r')\n #print(txt)\n doc = txt.readlines()\n #print(doc)\n for n in doc:\n lis.append(n.strip())\n return (lis)\n\n#3\ndef UpdateString(x, y, z):\n k = ''\n for i in range(len(x)):\n if i != z:\n k += x[i]\n else:\n k += y\n return (k)\n #print(k)\n\n#4\ndef FindWordCount(x, y):\n a = LoadFile(x)\n i = 0\n m = []\n for k in a:\n m += k.split()\n #print(m)\n for p in m:\n if p == y:\n i += 1\n return (i)\n\n#5\ndef ScoreFinder(x, y):\n \n \n return PrintOutput\n\n#6\ndef Union(x, y):\n k = []\n k = x + y\n return PrintOutput(k)\n\n#7\ndef Intersection(x, y):\n k = []\n for n in x:\n for m in y:\n if n == m:\n k.append(n)\n #print(k)\n return (k)\n\n#8\ndef NotIn(x, y):\n k = []\n for n in x:\n if n not in y:\n k.append(n)\n #print(k)\n return (k)\n","repo_name":"ksmielke/python-w12","sub_path":"Week12a-utility.py","file_name":"Week12a-utility.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35616752699","text":"from typing import Optional\n\nfrom pydantic import BaseModel, validator\nfrom virtool_core.models.enums import MessageColor\nfrom virtool_core.models.instancemessage import InstanceMessage\nfrom virtool_core.models.validators import prevent_none\n\n\nclass CreateMessageRequest(BaseModel):\n color: MessageColor\n message: str\n\n\nclass UpdateMessageRequest(BaseModel):\n color: Optional[MessageColor]\n message: Optional[str]\n active: Optional[bool]\n\n _prevent_none = prevent_none(\"*\")\n\n @validator(\"active\")\n def active_must_be_false(cls, active: bool) -> bool:\n if active:\n raise ValueError(\"active can only be `False` when updating\")\n return active\n\n\nclass MessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 1,\n \"active\": True,\n \"color\": \"red\",\n \"message\": \"Administrative instance message\",\n \"created_at\": \"2021-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2021-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n\n\nclass CreateMessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 3,\n \"active\": True,\n \"color\": \"yellow\",\n \"message\": \"Third instance message\",\n \"created_at\": \"2022-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2022-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n\n\nclass UpdateMessageResponse(InstanceMessage):\n class Config:\n schema_extra = {\n \"example\": {\n \"id\": 3,\n \"active\": True,\n \"color\": \"red\",\n \"message\": \"Changed the third instance message\",\n \"created_at\": \"2022-11-24T19:40:03.320000Z\",\n \"updated_at\": \"2022-11-24T19:40:03.320000Z\",\n \"user\": {\"id\": \"ian\", \"handle\": \"ianboyes\", \"administrator\": True},\n }\n }\n","repo_name":"virtool/virtool","sub_path":"virtool/messages/oas.py","file_name":"oas.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"}
+{"seq_id":"23196479139","text":"from dz.cars.database import create_db, Session\nfrom dz.cars.cars_title import Title\nfrom dz.cars.car_models import Models\n\n\ndef create_database():\n create_db()\n load_data(Session())\n\n\ndef load_data(session):\n cars = [\"BMW\", \"Ford\", \"Opel\"]\n models = [{\"model\": \"x5\", \"color\": \"black\", \"price\": 1000},\n {\"model\": \"mondeo\", \"color\": \"blue\", \"price\": 2000},\n {\"model\": \"insigma\", \"color\": \"red\", \"price\": 3000}\n ]\n\n for item in cars:\n title = Title(title=item)\n session.add(title)\n\n for item in models:\n model = Models(model=item[\"model\"])\n session.add(model)\n color = Models(color=item[\"color\"])\n session.add(color)\n price = Models(price=item[\"price\"])\n session.add(price)\n\n session.commit()\n session.close()","repo_name":"Helen-prog/Python327","sub_path":"dz/db_creator.py","file_name":"db_creator.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11065545029","text":"#!/usr/bin/env python3\nimport pandas as pd\nimport argparse\nfrom pathlib import Path\nfrom AmpliconPE import (\n MasterRead,\n BarcodeSet,\n get_PE_FASTQs,\n pairedFASTQiter,\n logPrint,\n)\n\n\n# AGCTTGTGGAAAGGACGAAACACCG GGGGACGGATCCTGGACATG\n# TTTTAGAGCTAGAAATAGCAAGTTAAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGTATTATAAATCTAAGTCTTTAAA\nfull_amplicon = (\n \"AGCTTGTGGAAAGGACGAAACACCG\"\n + 20 * \"N\"\n + \"TTTTAGAGCTAGAAATAGCAAGTTAAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGTATTATAAATCTAAGTCTTTAAA\"\n)\n\nFLANK_LENGTH = 12\n\ndefault_master_read = full_amplicon[\n full_amplicon.find(\"N\")\n - FLANK_LENGTH : full_amplicon.rindex(\"N\")\n + 1\n + FLANK_LENGTH\n]\n\nparser = argparse.ArgumentParser(\n description=\"\"\"Determines sgRNA counts from Paired-End Brunello library reads.\"\"\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n)\n\n############################## Input #########################################\nIO_group = parser.add_argument_group(\"IO\", \"Input/Output Optional Arguments\")\n\nIO_group.add_argument(\n \"--FASTQ_directory\",\n type=Path,\n default=Path(\"FASTQs\"),\n help=\"Iterates over all FASTQs in directory\",\n)\n\nIO_group.add_argument(\n \"--sgRNA_file\",\n type=Path,\n default=\"broadgpp-brunello-library-contents.txt\",\n help=\"All sgRNAs used and their corresponding identifiers.\",\n)\n\nIO_group.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Output more Info\")\n\nIO_group.add_argument(\n \"--output\", type=Path, default=Path(\"output.h5\"), help=\"Name of HDF5 output store.\"\n)\n\nIO_group.add_argument(\n \"--master_read\",\n type=str,\n default=default_master_read,\n help=\"Non-degenerate amplicon sequence expected\",\n)\n\nOP_group = parser.add_argument_group(\"OP\", \"Optional arguments affecting operation\")\n\nOP_group.add_argument(\n \"--min_align_score\",\n type=float,\n default=0.75,\n help=\"Minimum alignment score needed to keep read, Range [0, 1).\",\n)\n\nOP_group.add_argument(\n \"--mismatches_tolerated\",\n type=int,\n default=1,\n help=\"# of mismatches tolerated in sgRNA\",\n)\n\nOP_group.add_argument(\n \"-p\", \"--parallel\", action=\"store_true\", help=\"Parallelize operation.\"\n)\n\nargs = parser.parse_args()\n\nLog = logPrint(args)\nif args.parallel:\n from pmap import pmap as map\n\n\ndirectories = [name for name in args.FASTQ_directory.iterdir() if name.is_dir()]\n\n\n## Setup sgRNA_map\n\n# Data Table can be found at: https://www.addgene.org/static/cms/filer_public/8b/4c/8b4c89d9-eac1-44b2-bb2f-8fea95672705/broadgpp-brunello-library-contents.txt\n#\n# Sample data:\n#\n# Target Gene ID 1.0 1.0 ... NaN NaN\n# Target Gene Symbol A1BG A1BG ... Non-Targeting Control Non-Targeting Control\n# Target Transcript NM_130786.3 NM_130786.3 ... NaN NaN\n# Genomic Sequence NC_000019.10 NC_000019.10 ... NaN NaN\n# Position of Base After Cut (1-based) 58351502.0 58350637.0 ... NaN NaN\n# Strand sense antisense ... NaN NaN\n# sgRNA Target Sequence CATCTTCTTTCACCTGAACG CTCCGGGGAGAACTCCGGCG ... TTTTTAATACAAGGTAATCT TTTTTCTCACCCGATGAATC\n# Target Context Sequence ATCGCATCTTCTTTCACCTGAACGCGGTGG CCGGCTCCGGGGAGAACTCCGGCGCGGGCA ... NaN NaN\n# PAM Sequence CGG CGG ... NaN NaN\n# Exon Number 5.0 6.0 ... NaN NaN\n# Rule Set 2 score 0.617\n\nko_library = pd.read_csv(\n args.sgRNA_file, sep=\"\\t\", index_col=[\"sgRNA Target Sequence\"]\n)[\"Target Gene Symbol\"]\n\n\nsgRNA_map = BarcodeSet(\n ko_library.index\n + \"_\"\n + ko_library, # Hard to mint simple names...Gene Symbol are non-unique & target sequences are uninformative\n n_mismatches=args.mismatches_tolerated,\n robust=True,\n)\n\noverlapping = sum(map(lambda v: len(list(v)) > 1, sgRNA_map.values()))\n\nLog(\n f\"{overlapping} of {len(sgRNA_map) - len(ko_library)} sgRNA mismatches overlap ({overlapping/(len(sgRNA_map) - len(ko_library)):.2%}).\"\n)\n\nmaster_read = MasterRead(args.master_read)\n\n\ndef derep_barcodes(directory):\n import numpy as np\n from collections import Counter\n\n pileups = Counter()\n scores = np.zeros(master_read.max_score + 1, dtype=np.int64)\n min_int_score = int(args.min_align_score * master_read.max_score)\n\n file_pair = get_PE_FASTQs(directory)\n fastq_iter = pairedFASTQiter(*file_pair)\n for fwd_dna, rev_dna in fastq_iter:\n\n double_alignment = master_read.align(fwd_dna, rev_dna)\n double_alignment.print_cigars()\n scores[double_alignment.score] += 1\n if double_alignment.score <= min_int_score:\n continue\n\n sgRNA = double_alignment.extract_barcode()\n if sgRNA == \"Length Mismatch\":\n continue\n\n print(fwd_dna)\n print(rev_dna)\n print(sgRNA)\n # print(f\"extracted {sgRNA} -> {sgRNA_map.get(sgRNA, 'Unknown')}\")\n pileups[sgRNA_map.get(sgRNA, \"Unknown Target\")] += 1\n\n poor_alignment = scores[:min_int_score].sum()\n lost = {\n \"Poor Alignment\": poor_alignment,\n \"Length Mismatch\": pileups.sum() - poor_alignment,\n \"Index Mismatch\": fastq_iter.index_mismatch,\n }\n return pileups, lost, pd.Series(scores)\n\n\noutputs = map(derep_barcodes, directories)\n\n\noutput_dfs = [\n pd.concat(\n {\n str(name): output_S\n for name, output_S in zip(directories, output_set)\n if len(output_S) > 0\n },\n names=[\"Sample\"],\n axis=0,\n )\n for output_set in zip(*list(outputs))\n]\n\n\n###############################################################################\n# Output\n###############################################################################\n\nstore = pd.HDFStore(args.output, \"w\", complevel=9)\nfor name, df in zip([\"pileups\", \"lost\", \"scores\"], output_dfs):\n if name == \"pileups\":\n df.index.names = \"Sample\", \"target\", \"barcode\"\n store.put(name, df)\nstore.close()\n","repo_name":"cancerevo/AmpliconPE","sub_path":"bin/old/Brunello.py","file_name":"Brunello.py","file_ext":"py","file_size_in_byte":6777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9265569188","text":"#!/usr/bin/env python3\nimport argparse\nfrom core.colours import green, end, bad, yellow, white, sarcastic\nfrom core.simple import * \nfrom core.simplewithpic import maininfogather\n\n\nversion = '0.0.1'\n\ndef args_func():\n parser = argparse.ArgumentParser(description=\"The Loki Framework v\" + version, epilog=\"Automate Sock Puppet Creation\")\n parser.add_argument('-s','--simple',help='Simple Information Generator', dest='simple', action='store_true')\n parser.add_argument('-sp','--simplewithpic',help='Simple Information Generation with Pic', dest='simplewithpic', action='store_true')\n parser.add_argument('-p','--profession',help='Specify the Profession beforehand', dest='profession')\n parser.add_argument('-soc','--social-create',help='Simple Information Generation with Pic & Create Profiles on Facebook, Instagram, TikTok', dest='socialmedia', action='store_true')\n parser.add_argument('-g','--gender',choices=['male', 'female'], help='Specify the gender of the sock puppet', dest='gender')\n parser.add_argument('-b', help='Print the banner', dest='bannerfunction', action='store_true')\n return parser.parse_args()\n\ndef bannerfunction():\n banner()\n\ndef banner():\n print('''%s\n The %s _____ _ _ _____\n | | | |____/ | %s\n |_____ |_____| | \\_ __|__\n %sFramework v%s %s\\n''' % (white, green, yellow, white, version, end))\n\ndef main():\n args = args_func()\n \n if args.simple == True:\n if args.gender == 'male':\n if args.profession is not None:\n banner()\n simpleinfogathermalewithprofession(args.profession)\n else:\n banner()\n simpleinfogathermale()\n \n elif args.gender == 'female':\n if args.profession is not None:\n banner()\n simpleinfogatherfemalewithprofession(args.profession)\n else:\n banner()\n simpleinfogatherfemale()\n\n elif args.profession is not None:\n banner()\n simplewithprofession(args.profession)\n \n else:\n banner()\n simpleinfogather()\n\n elif args.simplewithpic == True:\n banner()\n maininfogather() \n \n elif args.profession is not None:\n banner()\n simplewithprofession(args.profession)\n\n elif args.bannerfunction == True:\n bannerfunction()\n elif args.socialmedia == True:\n banner()\n print('This feature is coming soon !!')\n\n else:\n banner()\n help_statement = \"Use '-h' or '--help' to see the options\"\n exit('\\n%s No argument(s) specified. ' % bad + help_statement + '\\n')\n \n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n exit('\\n%sExiting\\n' % sarcastic)\n","repo_name":"malwaredojo/loki","sub_path":"loki/loki.py","file_name":"loki.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"}
+{"seq_id":"5798363453","text":"import warnings\nfrom abc import ABC, abstractmethod\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Type, Union\n\nimport gensim.downloader as api\nimport numpy as np\nimport spacy\nfrom gensim.models import Word2Vec\nfrom numpy.linalg import norm\nfrom scipy.spatial.distance import cdist\nfrom sentence_transformers import SentenceTransformer\nfrom spacy.cli import download as spacy_download\nfrom tqdm import tqdm\n\nfrom relatio.supported_models import LANGUAGE_MODELS\nfrom relatio.utils import count_words\n\n\nclass EmbeddingsBase(ABC):\n @abstractmethod\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n pass\n\n\nclass Embeddings(EmbeddingsBase):\n \"\"\"\n If sentences is used in the constructor the embeddings are weighted by the smoothed inverse frequency of each token.\n For further details, see: https://github.com/PrincetonML/SIF\n\n Args:\n embeddings_type: The type of embeddings to use. Supported types are: \"SentenceTransformer\", \"GensimWord2Vec\", \"GensimPretrained\", \"spaCy\"\n embeddings_model: The model to use. Supported models are: \"all-MiniLM-L6-v2\", \"distiluse-base-multilingual-cased-v2\", \"whaleloops/phrase-bert\", \"fasttext-wiki-news-subwords-300\", \"word2vec-google-news-300\", \"glove-wiki-gigaword-50\", \"glove-wiki-gigaword-100\", \"glove-wiki-gigaword-200\", \"glove-wiki-gigaword-300\", \"glove-twitter-25\", \"glove-twitter-50\", \"glove-twitter-100\", \"glove-twitter-200\", \"en_core_web_sm\", \"en_core_web_md\", \"en_core_web_lg\", \"fr_core_news_sm\", \"fr_core_news_md\", \"fr_core_news_lg\"\n normalize: Whether to normalize the vectors to unit length\n sentences: A list of sentences to use for weighting the embeddings by the smoothed inverse frequency of each token\n alpha: The smoothing parameter for the smoothed inverse frequency of each token\n\n Examples:\n >>> model = Embeddings(\"spaCy\", \"en_core_web_md\")\n >>> np.isnan(model.get_vector(\"\")).any()\n True\n >>> model.get_vector(\"hello world\").shape\n (300,)\n >>> norm(model.get_vector(\"hello world\")) < 1.001\n True\n >>> model = Embeddings(\"spaCy\", \"en_core_web_md\", normalize=False)\n >>> norm(model.get_vector(\"hello world\")) < 1.001\n False\n >>> model = Embeddings(\"GensimPretrained\", \"glove-twitter-25\")\n >>> model.get_vector(\"world\").shape\n (25,)\n >>> model = Embeddings(\"GensimPretrained\", \"glove-twitter-25\", sentences = [\"this is a nice world\",\"hello world\",\"hello everybody\"])\n >>> model.get_vector(\"hello world\").shape\n (25,)\n \"\"\"\n\n def __init__(\n self,\n embeddings_type: str,\n embeddings_model: Union[Path, str],\n normalize: bool = True,\n sentences: Optional[List[str]] = None,\n alpha: float = 0.001,\n **kwargs,\n ) -> None:\n EmbeddingsClass: Union[\n Type[GensimWord2VecEmbeddings],\n Type[GensimPreTrainedEmbeddings],\n Type[spaCyEmbeddings],\n Type[SentenceTransformerEmbeddings],\n ]\n if embeddings_type == \"SentenceTransformer\":\n EmbeddingsClass = SentenceTransformerEmbeddings\n elif embeddings_type == \"GensimWord2Vec\":\n EmbeddingsClass = GensimWord2VecEmbeddings\n elif embeddings_type == \"GensimPretrained\":\n EmbeddingsClass = GensimPreTrainedEmbeddings\n elif embeddings_type == \"spaCy\":\n EmbeddingsClass = spaCyEmbeddings\n else:\n raise ValueError(f\"Unknown embeddings_type={embeddings_type}\")\n\n self._embeddings_model = EmbeddingsClass(embeddings_model, **kwargs)\n self._normalize: bool = normalize\n if sentences is not None:\n self._sif_dict = self.compute_sif_weights(sentences=sentences, alpha=alpha)\n self._use_sif = True\n else:\n self._sif_dict = {}\n self._use_sif = False\n\n if embeddings_type != \"GensimWord2Vec\":\n self._size_vectors = LANGUAGE_MODELS[embeddings_model][\"size_vectors\"]\n else:\n self._size_vectors = self._embeddings_model.size_vectors\n\n @property\n def normalize(self) -> bool:\n return self._normalize\n\n @property\n def use_sif(self) -> bool:\n return self._use_sif\n\n @property\n def size_vectors(self) -> int:\n return self._size_vectors\n\n # One cannot add a setter since it is added next to the child classes\n def get_vector(self, phrase: str) -> Optional[np.ndarray]:\n tokens = phrase.split()\n\n if self.use_sif:\n for token in tokens:\n if token not in self._sif_dict:\n warnings.warn(\n f\"No frequency information for token: {token}. Its corresponding weight is 1.0.\",\n RuntimeWarning,\n )\n res = np.sum(\n [\n self._sif_dict[token] * self._get_default_vector(token)\n for token in tokens\n ],\n axis=0,\n )\n else:\n res = self._get_default_vector(phrase)\n\n # In case the result is fishy it will return a vector of np.nans and raise a warning\n if np.isnan(res).any() or np.count_nonzero(res) == 0:\n warnings.warn(\n f\"Unable to compute an embedding for phrase: {phrase}.\", RuntimeWarning\n )\n a = np.empty((self.size_vectors,))\n a[:] = np.nan\n\n return a\n\n if self.normalize:\n return res / norm(res)\n else:\n return res\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return self._embeddings_model._get_default_vector(phrase)\n\n # This will require refactoring for speed (in the case of spacy and USE)\n def get_vectors(self, phrases: str, progress_bar: bool = False) -> np.ndarray:\n if progress_bar:\n print(\"Computing phrase embeddings...\")\n phrases = tqdm(phrases)\n\n vectors_list = []\n for i, phrase in enumerate(phrases):\n vector = self.get_vector(phrase)\n vectors_list.append(np.array([vector]))\n vectors = np.concatenate(vectors_list)\n return vectors\n\n @staticmethod\n def compute_sif_weights(sentences: List[str], alpha: float) -> Dict[str, float]:\n \"\"\"\n A function that computes smooth inverse frequency (SIF) weights based on word frequencies.\n (See \"Arora, S., Liang, Y., & Ma, T. (2016). A simple but tough-to-beat baseline for sentence embeddings.\")\n The sentences are used to build the counter dictionary {\"word\": frequency} which is further used to compute the sif weights. If the word is not in the dictionary, 1 is returned.\n Args:\n sentences: a list of sentences\n alpha: regularization parameter\n Returns:\n A dictionary {\"word\": SIF weight}\n \"\"\"\n words_counter = count_words(sentences)\n\n sif_dict = defaultdict(lambda: 1.0)\n\n for word, count in words_counter.items():\n sif_dict[word] = alpha / (alpha + count)\n\n return sif_dict\n\n\nclass spaCyEmbeddings(EmbeddingsBase):\n def __init__(self, model: str) -> None:\n if not spacy.util.is_package(model):\n spacy_download(model)\n self._nlp = spacy.load(\n model, disable=[\"tagger\", \"parser\", \"attribute_ruler\", \"lemmatizer\", \"ner\"]\n )\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return np.array(self._nlp(phrase).vector)\n\n\nclass SentenceTransformerEmbeddings(EmbeddingsBase):\n \"\"\"\n Choose your favorite model from https://www.sbert.net/docs/pretrained_models.html\n\n Args:\n path: path to the model\n \"\"\"\n\n def __init__(self, path: str = \"all-MiniLM-L6-v2\") -> None:\n self._model = SentenceTransformer(path)\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n return self._model.encode(phrase)\n\n\nclass GensimWord2VecEmbeddings(EmbeddingsBase):\n def __init__(self, path: str):\n self._model = self._load_keyed_vectors(path)\n self._vocab = self._model.key_to_index\n self.size_vectors = self._model[list(self._vocab)[0]].shape[0]\n\n def _load_keyed_vectors(self, path):\n return Word2Vec.load(path).wv\n\n def _get_default_vector(self, phrase: str) -> np.ndarray:\n tokens = phrase.split()\n embeddable_tokens = []\n for token in tokens:\n if token in self._vocab:\n embeddable_tokens.append(token)\n else:\n warnings.warn(\n f\"No vector for token: {token}. It is not used to compute the embedding of: {phrase}.\",\n RuntimeWarning,\n )\n res = np.mean([self._model[token] for token in embeddable_tokens], axis=0)\n return res\n\n\nclass GensimPreTrainedEmbeddings(GensimWord2VecEmbeddings, EmbeddingsBase):\n\n \"\"\"\n A class to call a pre-trained embeddings model from gensim's library.\n # The list of pre-trained embeddings may be browsed by typing:\n import gensim.downloader as api\n list(api.info()['models'].keys())\n \"\"\"\n\n def __init__(self, model: str):\n self._model = self._load_keyed_vectors(model)\n self._vocab = self._model.key_to_index\n\n def _load_keyed_vectors(self, model):\n return api.load(model)\n\n\ndef _compute_distances(vectors1, vectors2):\n \"\"\"\n Compute pairwise distances of columns between two numpy arrays.\n \"\"\"\n distances = cdist(vectors1, vectors2, metric=\"euclidean\")\n return distances\n\n\ndef _get_min_distances(distances):\n \"\"\"\n Returns the minimum distance per column.\n \"\"\"\n return np.min(distances, axis=1)\n\n\ndef _get_index_min_distances(distances):\n \"\"\"\n Returns the index of the minimum distance per column.\n \"\"\"\n return np.argmin(distances, axis=1)\n\n\ndef _embeddings_similarity(vectors1, vectors2, threshold: float = 100):\n \"\"\"\n Computes the pairwise distances between two numpy arrays,\n keeps minimum distances which are below the threshold and returns\n two arrays of indices:\n - index are the columns which satisfy the threshold requirement\n - index_min_distances are their associated index for the minimum distance\n \"\"\"\n distances = _compute_distances(vectors1, vectors2)\n index_min_distances = _get_index_min_distances(distances)\n min_distances = _get_min_distances(distances)\n index = list(np.where(min_distances <= threshold))[0]\n index_min_distances = index_min_distances[index]\n return index, index_min_distances\n","repo_name":"relatio-nlp/relatio","sub_path":"relatio/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"52"}
+{"seq_id":"12591323789","text":"import time\nimport msvcrt\nimport threading\nfrom pynput import mouse\nfrom threading import Timer\n\nimport maus\n\n\ndef exists(var):\n return var in globals()\n\n\ndef wait_func(t=5):\n print(f'Wait {t:.1f} sec')\n for i in range(round(t*10), 0, -1):\n if msvcrt.kbhit():\n # key = msvcrt.getch()\n pressed = True\n break\n print(f'\\b\\b\\b{i/10:.1f}', end='')\n time.sleep(0.1)\n print('\\b\\b\\b', end='')\n\n # if pressed:\n # print('Wait for key press')\n # k = False\n # while not k:\n # k = msvcrt.kbhit()\n\n\ndef solver_human(matrix):\n \"\"\"\n Передает управление человеку, если нет ходов\n :param matrix:\n :return:\n \"\"\"\n\n\n def on_click(x, y, button, pressed):\n nonlocal t\n # pressed = True при нажатии кнопики мыщи и\n # pressed = False при отпускании\n if not pressed:\n # Когда мы возвращаем False, когда хотим остановить listener thread:\n # конструкция with listener: завершается\n global xx, yy, bb\n xx = x\n yy = y\n bb = button\n\n print('User click mouse', f'{xx}, {yy}, {bb}')\n\n point = (xx, yy)\n cell = matrix.cell_by_abs_coords(point)\n if cell:\n return False\n else:\n print('Click out of field')\n t.cancel()\n t = Timer(5, mouse_thread.stop)\n t.start()\n\n def on_move(x, y):\n # print('Pointer moved to {0}'.format((x, y)))\n pass\n\n def on_scroll(x, y, dx, dy):\n # print('Scrolled {0} at {1}'.format('down' if dy < 0 else 'up', (x, y)))\n pass\n\n def win32_event_filter(msg, data):\n # msg = 512 move\n # msg = 513 left click\n # msg = 516 right click\n # data.pt.x and y - coordinates\n # data has unknown but probably useful flag attribute\n if msg in [513, 516]:\n # Тут мы смотрим на все события мыши.\n # Если событие - это нажатие кнопки, то мы его не передаем дальше в систему (suppress)\n mouse_thread.suppress_event()\n\n # x = threading.Thread(target=wait_func(), args=(), daemon=True)\n # x.start()\n\n print('Start mouse listen: wait your move 5 sec')\n\n mouse_thread = mouse.Listener(\n on_move=on_move,\n on_click=on_click,\n on_scroll=on_scroll,\n win32_event_filter=win32_event_filter\n )\n\n def showing():\n print('.')\n\n my_thread = threading.Thread(target=showing, args=())\n with mouse_thread:\n t = Timer(5, mouse_thread.stop)\n t.start()\n mouse_thread.join()\n my_thread.start()\n\n\n\n\n\n # t.cancel()\n\n if exists('xx'):\n\n print('User click mouse', f'{xx}, {yy}, {bb}')\n\n point = (xx, yy)\n cell = matrix.cell_by_abs_coords(point)\n if cell:\n if bb == mouse.Button.left:\n action = maus.OPEN\n elif bb == mouse.Button.right:\n action = maus.FLAG\n else:\n exit('Error: That mouse button is not assigned.')\n return [cell], action\n else:\n print('Нажато за пределами поля')\n\n else:\n\n print('No action from human')\n from .solver_R1 import solver_R1\n return solver_R1(matrix)\n\n\n\n # exit()\n # return [], None\n\n\n\n\n","repo_name":"swasher/minesweeper","sub_path":"solver/solver_human_almost_work.py","file_name":"solver_human_almost_work.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34649829509","text":"import tensorflow as tf\nimport numpy as np\nimport sys\nsys.path.append('../models')\nimport math\nfrom deep_learning.cnns.simple_cnn import SimpleCNNModel\nfrom deep_learning.cnns.dehaze_net import DehazeNetModel\nfrom deep_learning.cnns.AQP_vgg import AQPVGGModel\nfrom deep_learning.cnns.AQP_ResNet import AQPResNetModel\nfrom tensorflow.contrib.data import Dataset, Iterator\nimport tensorflow.contrib.slim as slim\n\nIMG_HEIGHT = 240\nIMG_WIDTH = 320\n\nmeta_data_names = ['filePath', 'webcamId', 'webcamLat', 'webcamLong', 'year', 'date', 'hour', 'range', 'pmValue']\ndark_channel_names = ['Dark_Channel_' + str(i) for i in range(0, 100)]\natmospheric_light_names = ['Atmospheric_Light_' + str(i) for i in range(0, 3)]\ntransmission_names = ['Transmission_' + str(i) for i in range(0, 100)]\nsaturation_names = ['Saturation_1','Saturation_2','Saturation_3','Saturation_4','Saturation_5','Saturation_6','Saturation_7','Saturation_8','Saturation_9','Saturation_10']\ncontrast_names = ['Contrast_1']\npower_spectrum_names = ['PS_1','PS_2','PS_3','PS_4','PS_5','PS_6','PS_7','PS_8','PS_9','PS_10']\nweather_features = ['dir', 'spd', 'temp', 'dewpt', 'slp', 'rhx']\ncolumn_names_with_weather_features = meta_data_names + weather_features\ncolumn_names_with_haze_features = meta_data_names + dark_channel_names + atmospheric_light_names + transmission_names + saturation_names + contrast_names + power_spectrum_names\nall_column_names = meta_data_names + dark_channel_names + atmospheric_light_names + transmission_names + saturation_names + contrast_names + power_spectrum_names + weather_features\n\ndef parse_example(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224+15, 224+15]), [224+15, 224+15, 3])\n\treturn rgb_image, pmValue\n\ndef parse_example_vgg(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224, 224]), [224, 224, 3])\n\treturn rgb_image, pmValue\n\ndef parse_example_ResNet(example_proto):\n\tfeature_dict = {\n\t\t'filePath': tf.FixedLenFeature([], tf.float32),\n\t\t'image': tf.FixedLenFeature([], tf.string),\n\t\t'orig_height': tf.FixedLenFeature([], tf.int64),\n\t\t'orig_width': tf.FixedLenFeature([], tf.int64)}\n\tparsed_features = tf.parse_single_example(example_proto, features=feature_dict)\n\tpmValue = parsed_features['filePath']\n\trgb_image = tf.decode_raw(parsed_features['image'], tf.float64)\n\theight = tf.cast(parsed_features['orig_height'], tf.int32)\n\twidth = tf.cast(parsed_features['orig_width'], tf.int32)\n\trgb_image = tf.reshape(rgb_image, [1, height, width, 3])\n\trgb_image = tf.image.resize_image_with_crop_or_pad(rgb_image, target_height=480, target_width=480) * 255\n\trgb_image = tf.reshape(tf.image.resize_area(rgb_image, [224, 224]), [224, 224, 3])\n\treturn rgb_image, pmValue\n\nclass AQPModel(object):\n\tdef __init__(self,\n\t\t\t\t\tsess,\n\t\t\t\t\tbatch_size,\n\t\t\t\t\tstage_of_development,\n\t\t\t\t\tlearning_rate_decay_factor,\n\t\t\t\t\ttype_of_model,\n\t\t\t\t\tsummary_dir,\n\t\t\t\t\texperiment_folder, \n\t\t\t\t\ttype_of_optimizer,\n\t\t\t\t\tnum_of_classes,\n\t\t\t\t\ttotal_num_of_training_examples,\n\t\t\t\t\tdropout=0.5,\n\t\t\t\t\tmodel_path=None,\n\t\t\t\t\tbeta1=0.9,\n\t\t\t\t\tbeta2=0.999,\n\t\t\t\t\tmin_bins=None,\n\t\t\t\t\tmax_bins=None,\n\t\t\t\t\tlist_of_tfrecords_for_training=None,\n\t\t\t\t\tlist_of_tfrecords_for_evaluation=None,\n\t\t\t\t\ttraining_with_eval=False,\n\t\t\t\t\tdict_of_filePath_to_num_of_examples_in_tfrecord=None):\n\n\t\tself.training_batch_size = 0\n\t\tself.batch_size = batch_size\n\t\tself.list_of_tr_datasets = []\n\t\tself.list_of_eval_datasets = []\n\t\tprint(\"Training with dev\", training_with_eval)\n\t\tprint(sorted(list(dict_of_filePath_to_num_of_examples_in_tfrecord.keys())))\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor tfrecord_for_training_example_ in list_of_tfrecords_for_training:\n\t\t\t\tcurrent_tr_data = tf.contrib.data.TFRecordDataset(tfrecord_for_training_example_)\n\t\t\t\tif type_of_model == 'VGG':\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example_vgg)\n\t\t\t\telif type_of_model == 'ResNet':\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example_ResNet)\n\t\t\t\telse:\n\t\t\t\t\tcurrent_tr_data = current_tr_data.map(parse_example)\n\t\t\t\tcurrent_tr_data = current_tr_data.shuffle(buffer_size=20000)\n\t\t\t\tcurrent_tr_data = current_tr_data.repeat()\n\t\t\t\tcurrent_tfrecord_batch_size = math.ceil(((float(dict_of_filePath_to_num_of_examples_in_tfrecord[tfrecord_for_training_example_]) * 1.0) / (float(total_num_of_training_examples) * 1.0)) * self.batch_size)\n\t\t\t\tself.training_batch_size += current_tfrecord_batch_size\n\t\t\t\tcurrent_tr_data = current_tr_data.batch(current_tfrecord_batch_size)\n\t\t\t\tprint(tfrecord_for_training_example_, dict_of_filePath_to_num_of_examples_in_tfrecord[tfrecord_for_training_example_], current_tfrecord_batch_size)\n\t\t\t\tself.list_of_tr_datasets.append(current_tr_data)\n\n\t\tif stage_of_development == \"training\":\n\t\t\tself.batch_size = self.training_batch_size\n\n\t\tself.single_eval_data = None\n\t\tif stage_of_development != \"training\":\n\t\t\tself.single_eval_data = tf.contrib.data.TFRecordDataset(list_of_tfrecords_for_evaluation)\n\t\t\tif type_of_model == 'VGG':\n\t\t\t\tself.single_eval_data = self.single_eval_data.map(parse_example_vgg)\n\t\t\telif type_of_model == 'ResNet':\n\t\t\t\tself.single_eval_data = self.singe_eval_data.map(parse_example_ResNet)\n\t\t\telse:\n\t\t\t\tself.single_eval_data = self.single_eval_data.map(parse_example)\n\t\t\tself.single_eval_data = self.single_eval_data.shuffle(buffer_size=10000)\n\t\t\tself.single_eval_data = self.single_eval_data.repeat(1)\n\t\t\tself.single_eval_data = self.single_eval_data.batch(self.batch_size)\n\n\n\t\t\t#for tfrecord_for_evaluation_example_ in list_of_tfrecords_for_evaluation:\n\t\t\t#\tcurrent_eval_data = tf.contrib.data.TFRecordDataset(tfrecord_for_evaluation_example_)\n\t\t\t#\tif type_of_model == 'VGG':\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example_vgg)\n\t\t\t#\telif type_of_model == 'ResNet':\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example_ResNet)\n\t\t\t#\telse:\n\t\t\t#\t\tcurrent_eval_data = current_eval_data.map(parse_example)\n\t\t\t#\tcurrent_eval_data = current_eval_data.shuffle(buffer_size=10000)\n\t\t\t#\tcurrent_eval_data = current_eval_data.repeat(1)\n\t\t\t#\tcurrent_eval_data = current_eval_data.batch(self.batch_size)\n\t\t\t#\tself.list_of_eval_datasets.append(current_eval_data)\n\n\t\tself.list_of_handles = []\n\t\tself.list_of_iterators = []\n\t\tself.list_of_batch_imgs = []\n\t\tself.list_of_batch_labels = []\n\t\tself.list_of_batch_imgs_and_batch_labels = []\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor idx_ in range(len(list_of_tfrecords_for_training)):\n\t\t\t\tself.list_of_handles.append(tf.placeholder(tf.string, shape=[]))\n\t\t\t\tself.list_of_iterators.append(Iterator.from_string_handle(self.list_of_handles[idx_], self.list_of_tr_datasets[0].output_types, self.list_of_tr_datasets[0].output_shapes))\n\t\t\t\tbatched_imgs, batched_labels = self.list_of_iterators[idx_].get_next()\n\t\t\t\tif type_of_model == 'DehazeNet':\n\t\t\t\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224+15, 224+15, 3]))\n\t\t\t\telse:\n\t\t\t\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224, 224, 3]))\n\t\t\t\tself.list_of_batch_labels.append(tf.reshape(batched_labels, [-1, 1]))\n\t\telse:\n\t\t\tself.single_eval_handle = tf.placeholder(tf.string, shape=[])\n\t\t\tself.single_eval_iterator = Iterator.from_string_handle(self.single_eval_handle, self.single_eval_data.output_types, self.single_eval_data.output_shapes)\n\t\t\tself.eval_batched_imgs, self.eval_batched_labels = self.single_eval_iterator.get_next()\n\t\t\tif type_of_model == 'DehazeNet':\n\t\t\t\tself.eval_batched_imgs = tf.reshape(self.eval_batched_imgs, [-1, 224+15, 224+15, 3])\n\t\t\telse:\n\t\t\t\tself.eval_batched_imgs = tf.reshape(self.eval_batched_imgs, [-1, 224, 224, 3])\n\t\t\tself.eval_batched_labels = tf.reshape(self.eval_batched_labels, [-1, 1])\n\n\n\t\t\t#for idx_ in range(len(list_of_tfrecords_for_evaluation)):\n\t\t\t#\tself.list_of_handles.append(tf.placeholder(tf.string, shape=[]))\n\t\t\t#\tself.list_of_iterators.append(Iterator.from_string_handle(self.list_of_handles[idx_], self.list_of_eval_datasets[0].output_types, self.list_of_eval_datasets[0].output_shapes))\n\t\t\t#\tbatched_imgs, batched_labels = self.list_of_iterators[idx_].get_next()\n\t\t\t#\tif type_of_model == 'DehazeNet':\n\t\t\t#\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224+15, 224+15, 3]))\n\t\t\t#\telse:\n\t\t\t#\t\tself.list_of_batch_imgs.append(tf.reshape(batched_imgs, [-1, 224, 224, 3]))\n\t\t\t#\tself.list_of_batch_labels.append(tf.reshape(batched_labels, [-1, 1]))\n\n\t\tself.list_of_training_iterators = []\n\t\tself.single_eval_iterator = None\n\n\t\tif stage_of_development == \"training\":\n\t\t\tfor tr_dataset_example_ in self.list_of_tr_datasets:\n\t\t\t\tvalidation_iterator = tr_dataset_example_.make_one_shot_iterator()\n\t\t\t\tself.list_of_training_iterators.append(validation_iterator)\n\n\t\tif stage_of_development == \"evaluation\":\n\t\t\tself.single_eval_iterator = self.single_eval_data.make_one_shot_iterator()\n\n\t\tself.row_indices = tf.placeholder(tf.int32, (self.batch_size,))\n\t\tself.row_indices_reshaped = tf.reshape(self.row_indices, [self.batch_size, 1])\n\n\n\t\tif stage_of_development == \"training\":\n\t\t\tself.batch_inputs = tf.gather_nd(tf.concat(self.list_of_batch_imgs, 0), self.row_indices_reshaped)\n\t\t\tself.batch_targets = tf.gather_nd(tf.concat(self.list_of_batch_labels, 0), self.row_indices_reshaped)\n\t\telse:\n\t\t\tself.batch_inputs = tf.gather_nd(self.eval_batch_imgs, self.row_indices_reshaped)\n\t\t\tself.batch_targets = tf.gather_nd(self.eval_batched_labels, self.row_indices_reshaped)\n\n\t\tself.stage_of_development = stage_of_development\n\t\tself.model_path = model_path\n\t\tself.type_of_optimizer = type_of_optimizer\n\t\tself.model = None\n\t\tself.beta1 = beta1\n\t\tself.beta2 = beta2\n\t\tself.pm_values = tf.gather_nd(tf.concat(self.list_of_batch_labels, 0), self.row_indices_reshaped)\n\n\t\t#if num_of_classes > 1:\n\t\t#\tdiscrete_targets = tf.cast(self.batch_targets, dtype=tf.float32)\n\t\t#\tdiscrete_targets = tf.reshape(discrete_targets, [-1, 1])\n\t\t#\tmin_bins = tf.reshape(tf.cast(min_bins, dtype=tf.float32), [1, -1])\n\t\t#\tmax_bins = tf.reshape(tf.cast(max_bins, dtype=tf.float32), [1, -1])\n\t\t#\tc_1 = tf.subtract(discrete_targets, min_bins)\n\t\t#\tc_1 = tf.add(tf.cast(c_1 < 0, c_1.dtype) * 10000, tf.nn.relu(c_1))\n\t\t#\tc_2 = tf.subtract(discrete_targets * -1, max_bins)\n\t\t#\tc_2 = tf.add(tf.cast(c_2 < 0, c_2.dtype) * 10000, tf.nn.relu(c_2))\n\t\t#\tc = tf.add(c_1, c_2)\n\t\t#\tself.batch_targets = tf.reshape(tf.argmin(c, 1), [-1, 1])\n\n\t\tself.is_training = tf.placeholder(tf.bool, shape=[])\n\n\t\tif type_of_model == 'DehazeNet':\n\t\t\tself.model = DehazeNetModel(sess,\n\t\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\t\tmax_bins=max_bins)\n\t\telif type_of_model == \"VGG\":\n\t\t\tself.model = AQPVGGModel(sess,\n\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\tself.model_path,\n\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\tself.is_training,\n\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\tmax_bins=max_bins)\n\t\telif type_of_model == \"ResNet\":\n\t\t\tself.model = AQPResNetModel(sess,\n\t\t\t\t\t\t\t\t\t\tself.batch_inputs,\n\t\t\t\t\t\t\t\t\t\tself.batch_targets,\n\t\t\t\t\t\t\t\t\t\tself.stage_of_development,\n\t\t\t\t\t\t\t\t\t\tself.model_path,\n\t\t\t\t\t\t\t\t\t\tnum_of_classes,\n\t\t\t\t\t\t\t\t\t\tmin_bins=min_bins,\n\t\t\t\t\t\t\t\t\t\tmax_bins=max_bins) \n\t\telse:\n\t\t\tself.model = SimpleCNNModel(sess, self.batch_inputs, self.batch_targets, self.stage_of_development)\n\n\t\tdef return_predictions():\n\t\t\treturn self.model.predictions\n\t\tdef return_validation_predictions():\n\t\t\treturn self.model.validation_predictions\n\n\t\tdef return_MAE():\n\t\t\treturn tf.reduce_mean(tf.abs(tf.subtract(self.model.predictions, self.model.labels)))\n\t\tdef return_validation_MAE():\n\t\t\treturn tf.reduce_mean(tf.abs(tf.subtract(self.model.validation_predictions, self.model.labels)))\n\n\t\tdef return_MSE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(self.model.predictions, self.model.labels)))\n\t\tdef return_validation_MSE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(self.model.validation_predictions, self.model.labels)))\n\n\t\tdef return_MSLE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(tf.log(tf.add(self.model.predictions, 1.0)), tf.log(tf.add(self.model.labels, 1.0)))))\n\t\tdef return_validation_MSLE():\n\t\t\treturn tf.reduce_mean(tf.square(tf.subtract(tf.log(tf.add(self.model.validation_predictions, 1.0)), tf.log(tf.add(self.model.labels, 1.0)))))\n\n\t\tdef return_R2_score():\n\t\t\tnumerator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, self.model.predictions))) #Unexplained Error\n\t\t\tdenominator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, tf.reduce_mean(self.model.labels)))) # Total Error\n\t\t\treturn tf.subtract(1.0, tf.divide(numerator, denominator))\n\t\tdef return_validation_R2_score():\n\t\t\tnumerator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, self.model.validation_predictions))) #Unexplained Error\n\t\t\tdenominator = tf.reduce_sum(tf.square(tf.subtract(self.model.labels, tf.reduce_mean(self.model.labels)))) # Total Error\n\t\t\treturn tf.subtract(1.0, tf.divide(numerator, denominator))\n\n\t\tself.learning_rate = tf.placeholder(tf.float32, shape=[])\n\t\tself.partial_learning_rate = tf.placeholder(tf.float32, shape=[])\n\t\tself.global_step = tf.Variable(0, trainable=False)\n\t\tself.predictions = tf.cond(self.is_training, return_predictions, return_validation_predictions)\n\t\tself.MAE_ = tf.cond(self.is_training, return_MAE, return_validation_MAE)\n\t\tself.R2_score_ = tf.cond(self.is_training, return_R2_score, return_validation_R2_score)\n\t\tself.MSE_ = tf.cond(self.is_training, return_MSE, return_validation_MSE)\n\t\tself.MSLE_ = tf.cond(self.is_training, return_MSLE, return_validation_MSLE)\n\t\t\n\t\tif self.stage_of_development == \"training\":\n\t\t\tself.global_eval_step = tf.Variable(0, trainable=False)\n\t\t\tself.global_eval_update_step_variable = tf.assign(self.global_eval_step, self.global_eval_step+1)\n\t\t\ttf.summary.scalar('MAE', self.MAE_)\n\t\t\ttf.summary.scalar('MSE', self.MSE_)\n\t\t\ttf.summary.scalar('MSLE', self.MSLE_)\n\t\t\ttf.summary.scalar('R2 Coefficient', self.R2_score_)\n\n\t\tif self.stage_of_development == \"training\" or self.stage_of_development == \"resume_training\":\n\t\t\tif type_of_model == 'DehazeNet' or type_of_model == 'VGG':\n\t\t\t\tpartial_opt = None\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\tpartial_opt = tf.train.AdamOptimizer(learning_rate=self.partial_learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\tpartial_opt = tf.train.GradientDescentOptimizer(learning_rate=self.partial_learning_rate)\n\t\t\t\tpartial_gradient = tf.gradients(self.MAE_, self.model.variables_trained_from_scratch)\n\t\t\t\tself.partial_train_op = partial_opt.apply_gradients(zip(partial_gradient, self.model.variables_trained_from_scratch), global_step=self.global_step)\n\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\tfull_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\tfull_opt = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n\t\t\t\tfull_gradient = tf.gradients(self.MAE_, self.model.all_variables)\n\t\t\t\tself.train_op = full_opt.apply_gradients(zip(full_gradient, self.model.all_variables), global_step=self.global_step)\n\t\t\telif type_of_model == 'ResNet':\n\t\t\t\tpartial_opt = tf.train.AdamOptimizer(learning_rate=self.partial_learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\tself.partial_train_op = slim.learning.create_train_op(self.MAE_, partial_opt, global_step=self.global_step, variables_to_train=self.model.variables_trained_from_scratch)\n\n\t\t\t\tfull_opt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\tself.train_op = slim.learning.create_train_op(self.MAE_, full_opt, global_step=self.global_step, variables_to_train=self.model.all_variables)\n\t\t\telse:\n\t\t\t\tif self.type_of_optimizer == 'adam':\n\t\t\t\t\topt = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=self.beta1, beta2=self.beta2)\n\t\t\t\telse:\n\t\t\t\t\topt = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)\n\t\t\t\tgradient = tf.gradients(self.MAE_, self.model.all_variables)\n\t\t\t\tself.train_op = opt.apply_gradients(zip(gradient, self.model.all_variables), global_step=self.global_step)\n\n\t\tself.merged = tf.summary.merge_all()\n\t\tself.train_writer = tf.summary.FileWriter(summary_dir + '/' + experiment_folder + '/train', sess.graph)\n\t\tself.saver = tf.train.Saver(tf.global_variables(), max_to_keep=4)","repo_name":"cemanuel/air_pollution","sub_path":"models/aqp_model_template.py","file_name":"aqp_model_template.py","file_ext":"py","file_size_in_byte":17554,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"}
+{"seq_id":"40376355311","text":"import random\nfrom dataclasses import dataclass\n\nimport discord\n\n\n@dataclass\nclass ModdyEmbed(discord.Embed):\n def __init__(self, title: str, description: str = \"\", **kwargs):\n super().__init__(**kwargs)\n self.color = 0x00B3EC\n self.title = title\n self.description = description\n\n\nclass ModdyError(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0x8F003C\n\n\nclass ModdySuccess(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0x7DEB34\n\n\nclass ModdyWarning(ModdyEmbed):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.color = 0xD1CA3B\n\n\ndef ping_embed(latency: int, elapsed: int):\n return ModdySuccess(\n \"Pong 🏓 !!\",\n f\"latency: {round(latency * 1000, 3)}ms\\nAPI: {elapsed}s\",\n )\n\n\ndef command_not_allowed(command: str, permission: str) -> ModdyEmbed:\n title = \"You are not allowed to perform this action\"\n desc = (\n f\"You are not allowed to use command `{command}` because\"\n f\" of the missing permission **{permission}**\"\n )\n return ModdyError(title, desc)\n\n\nprovide_query = ModdyError(\n \"How the hell will you expect a result without a query?\",\n \"Please provide a query to get results\",\n)\n\n\nreload_embed = ModdyEmbed(\"Reread all instructions 💥 \")\n\n\ndef google_embed(query: str, answer: str, *, img=None) -> ModdyEmbed:\n phrases = [\n \"Here you go sir 🎀🕴️...\",\n \"It's good that I had a magnifiying glass 🔎 🔍\",\n \"I search all over the world just for u 🗺️🌏\",\n \"I get exhauseted too mate 😮💨🤬\",\n \"Don't use this command that much. I'm very tired 😡\",\n \"Why did you call me, I was going to the washroom. ⚰️🧟♀️\",\n \"Oh man pls give me break ❤️🔥❤️🔥❤️🔥\",\n ]\n title = random.choice(phrases)\n embed = ModdyEmbed(title, f'**Results for \"{query}\"**\\n\\n{answer}')\n if img:\n embed.set_thumbnail(url=img)\n # embed.set\n # embed.add_field(name=query, value=\"\")\n return embed\n","repo_name":"Hyperx837/Moddy","sub_path":"moddy/embeds.py","file_name":"embeds.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"133917555","text":"\"\"\"Point cloud operations.\"\"\"\n\nimport numpy as np\n\n\ndef embed_point_in_rn(point, n):\n r\"\"\"\n Embed an m-dimensional point in :math:`\\mathbb{R}^n, m < n` by adding zeros for the missing coordinates.\n\n :param point: Point (m:d vector).\n :type point: :class:`Numpy array `\n :param int n: Dimension of the space we want to embed in.\n :return: The same point embedded in :math:`\\mathbb{R}^n`.\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> embed_point_in_rn(np.array([1, 1]), 3)\n array([1., 1., 0.])\n \"\"\"\n assert point.ndim == 1\n m = len(point)\n assert n > m\n return np.concatenate((point, np.zeros(n - m)))\n\n\ndef embed_point_cloud_in_rn(points, n):\n r\"\"\"\n Embed an m-dimensional point cloud in :math:`\\mathbb{R}^n, m < n` by adding zeros for the missing coordinates.\n\n :param points: Points in the point cloud (num points by m array).\n :type points: :class:`Numpy array `\n :param int n: Dimension of the space we want to embed in.\n :return: The same point cloud embedded in :math:`\\mathbb{R}^n`.\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> embed_point_cloud_in_rn(np.array([[0, 0], [1, 1]]), 3)\n array([[0., 0., 0.],\n [1., 1., 0.]])\n \"\"\"\n assert points.ndim == 2\n q, m = points.shape\n assert n > m\n points = np.concatenate((points, np.zeros((q, n - m))), axis=1)\n return np.reshape(points, (-1, n))\n\n\ndef mean(points):\n r\"\"\"\n Compute the mean, or centroid, of a point cloud in :math:`\\mathbb{R}^m`.\n\n .. math:: \\frac{1}{N} \\sum_{i = 1}^N x_i,\n\n where N is the number of points in the point cloud.\n\n :param points: Points in the point cloud (N by m array).\n :type points: :class:`Numpy array `\n :return: Mean of the point cloud along each axis (length m array).\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> mean(np.array([1.0, 3.0, 5.0]))\n 3.0\n >>> mean(np.array([[1.0, 2.0], [3.0, 4.0]]))\n array([2., 3.])\n \"\"\"\n return np.mean(points, axis=0)\n\n\ndef median(points):\n r\"\"\"\n Compute the median of a point cloud in :math:`\\mathbb{R}^m`.\n\n The i:th entry of the median is the median of the i:th component of the points in the point cloud.\n\n :param points: Points in the point cloud (num points by m array).\n :type points: :class:`Numpy array `\n :return: Median of the point cloud along each axis (length m array).\n :rtype: :class:`Numpy array `\n\n .. rubric:: Examples\n\n >>> median(np.array([1.0, 3.25, 5.0]))\n 3.25\n >>> median(np.array([[1.0, 2.0], [3.0, 4.0]]))\n array([2., 3.])\n \"\"\"\n return np.median(points, axis=0)\n\n\ndef principal_component_axis(points):\n r\"\"\"\n Get the principal component axis of a point cloud in :math:`\\mathbb{R}^m`.\n\n The principal component axis is the direction in which the point cloud is most spread out, i.e. the unit vector\n w which maximizes\n\n .. math:: \\sum_{i = 1}^N \\langle x_i - \\bar{x}, w \\rangle,\n\n where N is the number of points in the point cloud and :math:`\\bar{x}` is the mean of the point cloud.\n\n :param points: Points in the point cloud (N by m array).\n :type points: :class:`Numpy array `\n :return: Principal component axis of the point cloud (length m array).\n :rtype: :class:`Numpy array `\n \"\"\"\n x = points - mean(points)\n xtx = np.dot(x.T, x)\n w, v = np.linalg.eigh(xtx)\n return v[:, -1]\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"FAndersson/polynomials_on_simplices","sub_path":"polynomials_on_simplices/geometry/mesh/point_clouds.py","file_name":"point_clouds.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"5628753574","text":"class EntityComboMethods:\n Sum = 'sum'\n Multiply = 'multiply'\n\nclass LLParams:\n def __init__(self, ctx_vocab_size=0, ctx_dim=0,\n entity_vocab_size=0, entity_dim=0,\n secondary_entity_vocab_size=0, secondary_entity_dim=0,\n window_size=0, max_num_entities=0, max_mention_size=0,\n entity_combo_method=EntityComboMethods.Sum,\n using_mention=False):\n self._ctx_vocab_size = ctx_vocab_size\n self._ctx_dim = ctx_dim\n self._entity_vocab_size = entity_vocab_size\n self._entity_dim = entity_dim\n self._secondary_entity_vocab_size = secondary_entity_vocab_size\n self._secondary_entity_dim = secondary_entity_dim\n self._window_size = window_size\n self._max_num_entities = max_num_entities\n self._max_mention_size = max_mention_size\n self._entity_combination = entity_combo_method\n self._using_mention = using_mention\n","repo_name":"OSU-slatelab/JET","sub_path":"experiments/entitylinking/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"}
+{"seq_id":"31095629261","text":"from helpers import download\nimport re\nimport numpy as np\n\n\ndef printGrid(grid):\n for line in grid:\n for char in line:\n print(char, end='')\n print()\n\n\ndef expandGrid(grid, shiftX, shiftY, coords):\n # Allow padding in the x direction since water can travel 1 space past each solid surface\n newMinX = min(coords['x']) - 1\n newMaxX = max(coords['x']) + 1\n newMinY = min(coords['y'])\n newMaxY = max(coords['y'])\n\n # The first time, initialise the as-yet-unknown shiftY to the correct value\n if shiftY == -1:\n shiftY = newMinY\n\n curMinX = shiftX\n curMaxX = len(grid[0]) + shiftX\n curMinY = shiftY\n curMaxY = len(grid) + shiftY\n\n # Prepend free space onto each row to expand in the -x direction\n if newMinX < curMinX:\n for k, v in enumerate(grid):\n grid[k] = ['.' for _ in range(newMinX, curMinX)] + v\n shiftX = newMinX\n\n # Append free space onto each row to expand in the +x direction\n if newMaxX > curMaxX:\n for k, v in enumerate(grid):\n grid[k] = v + ['.' for _ in range(curMaxX, newMaxX + 1)]\n\n # Prepend rows of free space to the grid to expand in the -y direction\n if newMinY < curMinY:\n grid = [['.' for _ in range(min(curMinX, newMinX), max(curMaxX, newMaxX + 1))] for _ in range(newMinY, curMinY)] + grid\n shiftY = newMinY\n\n # Append rows of free space to the grid to expand in the +y direction\n if newMaxY > curMaxY:\n grid = grid + [['.' for _ in range(min(curMinX, newMinX), max(curMaxX, newMaxX + 1))] for _ in range(curMaxY, newMaxY + 1)]\n\n return grid, shiftX, shiftY\n\n\ndef getData():\n r = download('https://adventofcode.com/2018/day/17/input')\n regex = re.compile(r'^([xy])=(\\d+), ([xy])=(\\d+)..(\\d+)$')\n\n grid = [['.']]\n shiftX = 500\n shiftY = -1\n\n for line in r.iter_lines():\n k1, v1, k2, v2start, v2end = regex.match(line.decode()).groups()\n # Store two lists of the same length, so that the zip below creates the correct amount of coordinate pairs\n coords = {k1: [int(v1) for _ in range(int(v2start), int(v2end) + 1)], k2: [x for x in range(int(v2start), int(v2end) + 1)]}\n\n # Expand the grid if necessary\n grid, shiftX, shiftY = expandGrid(grid, shiftX, shiftY, coords)\n\n # Input all the clay pieces\n for x, y in zip(coords['x'], coords['y']):\n grid[y - shiftY][x - shiftX] = '#'\n\n return np.array(grid), shiftX\n\n\ndef checkRow(grid, x, y):\n # Walk left and right, checking to see if we're bounded by walls or if there's free space left to flow into\n for ddx in [-1, 1]:\n dx = ddx\n while grid[y][x + dx] == '|':\n dx += ddx\n if grid[y][x + dx] == '.':\n return False\n\n return True\n\n\ndef solidifyRow(grid, x, y):\n returnSet = set()\n\n # Handle the current location\n grid[y][x] = '~'\n if grid[y - 1][x] == '|':\n returnSet.add((x, y - 1))\n\n # Walk left and right changing flowing water to standing water, and tracking input flows\n for ddx in [-1, 1]:\n dx = ddx\n while grid[y][x + dx] == '|':\n grid[y][x + dx] = '~'\n if grid[y - 1][x + dx] == '|':\n returnSet.add((x + dx, y - 1))\n\n dx += ddx\n\n return returnSet\n\n\ndef simulate(grid, shiftX):\n # The initial node is under the spring at (500, 0)\n currentLayer = {(500 - shiftX, 0)}\n\n # Simulate in pseudo-real-time: progress one step from all frontiers at each timestep\n # This isn't the most efficient way, but it looks cool if you watch it\n while len(currentLayer) > 0:\n newLayer = set()\n\n for x, y in currentLayer:\n # Set this location to \"running water\"\n grid[y][x] = '|'\n\n # Check for falling off the bottom of the grid\n if y + 1 < len(grid):\n objBelow = grid[y + 1][x]\n if objBelow in ['#', '~']:\n # The object below is solid, so check to see if we've filled up the row\n if checkRow(grid, x, y):\n # Turn all the flowing water into standing water\n newNodes = solidifyRow(grid, x, y)\n # Add nodes that are flowing into the current row to be checked\n for node in newNodes:\n newLayer.add(node)\n else:\n # We haven't filled up the row, so flow sideways if there's space\n for dx in [-1, 1]:\n if grid[y][x + dx] == '.':\n newLayer.add((x + dx, y))\n else:\n # There's empty space below, so flow down into it\n newLayer.add((x, y + 1))\n\n currentLayer = newLayer\n\n return grid\n\n\ndef puzzle1(grid):\n numWet = np.count_nonzero(grid == '~')\n numDamp = np.count_nonzero(grid == '|')\n print('Answer: {}'.format(numWet + numDamp))\n\n\ndef puzzle2(grid):\n numWet = np.count_nonzero(grid == '~')\n print('Answer: {}'.format(numWet))\n\n\nif __name__ == '__main__':\n inputData = getData()\n finalGrid = simulate(*inputData)\n puzzle1(finalGrid)\n puzzle2(finalGrid)\n","repo_name":"sherlockmatt/aoc2018","sub_path":"day17.py","file_name":"day17.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"15424044248","text":"import wx\nimport time\n\nclass HexGridWindow(wx.ScrolledWindow):\n def __init__(self, *args, **kwargs):\n wx.ScrolledWindow.__init__ (self, *args, **kwargs)\n self.SetAutoLayout(True)\n\n self.top = HexGridColHeader(self, 40, 40)\n self.left = HexGridRowHeader(self, 40, 40)\n self.main = HexGridDataWindow(self, 40, 40)\n sizer = wx.FlexGridSizer(2,2,0,0)\n self.corner = sizer.Add(5, 5, 0, wx.EXPAND)\n sizer.Add(self.top, 0, wx.EXPAND)\n sizer.Add(self.left, 0, wx.EXPAND)\n sizer.Add(self.main, 0, wx.EXPAND)\n sizer.AddGrowableCol(1)\n sizer.AddGrowableRow(1)\n self.SetSizer(sizer)\n self.SetTargetWindow(self.main)\n self.SetScrollRate(20,20)\n self.Bind(wx.EVT_SCROLLWIN, self.on_scroll_window)\n self.Bind(wx.EVT_LEFT_UP, self.on_left_up)\n \n def on_left_up(self, event):\n print()\n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition()))\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n event.Skip()\n \n def set_pane_sizes(self, width, height, left_width, top_height):\n \"\"\"\n Set the size of the 3 panes as follow:\n - main = width, height\n - top = width, 40\n - left = 80, height\n \"\"\"\n self.main.SetVirtualSize(wx.Size(width,height))\n #(wt, ht) = self.top.GetSize()\n self.top.SetVirtualSize(wx.Size(width, top_height))\n #(wl, hl) = self.left.GetSize()\n self.left.SetVirtualSize(wx.Size(left_width, height))\n self.corner.SetMinSize(left_width, top_height)\n #self.Layout()\n \n def on_scroll_window(self, event):\n \"\"\"\n OnScrollWindow Event Callback. This should let the main panel scroll in\n both direction but transmit the vertical scrolling to the left panel\n and the horizontal scrolling to the top window\n \"\"\"\n sx,sy = self.GetScrollPixelsPerUnit()\n if event.GetOrientation() == wx.HORIZONTAL:\n dx = event.GetPosition()\n dy = self.GetScrollPos(wx.VERTICAL)\n else:\n dx = self.GetScrollPos(wx.HORIZONTAL)\n dy = event.GetPosition()\n \n pos = (dx ,dy)\n print(\"scrolling...\" + str(pos) + str(event.GetPosition()))\n # self.main.Scroll(dx, dy)\n # self.top.Scroll(dx, 0)\n # self.left.Scroll(0, dy)\n event.Skip()\n\n\nclass HexGridHeader(wx.ScrolledCanvas):\n use_x = 1\n use_y = 1\n\n def __init__(self, parent, width, height):\n wx.ScrolledCanvas.__init__(self, parent, -1)\n self.parent = parent\n self.SetBackgroundColour(wx.RED)\n self.SetSize(width, height)\n self.SetVirtualSize(width, height)\n self.Bind(wx.EVT_LEFT_DOWN, self.on_left_up)\n self.Bind(wx.EVT_PAINT, self.on_paint)\n self.Bind(wx.EVT_SIZE, self.on_size)\n\n def on_size(self, event ):\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n size = self.GetSize()\n vsize = self.GetVirtualSize()\n if self.use_x and self.use_y:\n # main window, no adjustment\n pass\n elif self.use_x:\n # scrolls in X dir\n self.SetVirtualSize(vsize.x, size.y)\n else:\n self.SetVirtualSize(size.x, vsize.y)\n\n #self.Layout()\n\n def on_paint(self, event):\n\n dc = wx.PaintDC(self)\n #self.parent.PrepareDC(dc)\n size = self.GetVirtualSize()\n\n s = \"Size: %d x %d\"%(size.x, size.y)\n vbX, vbY = self.parent.GetViewStart()\n posX, posY = self.parent.CalcUnscrolledPosition (0, 0)\n vbX, vbY = vbX * self.use_x, vbY * self.use_y\n posX, posY = posX * self.use_x, posY * self.use_y\n # vbX, vbY = self.GetViewStart()\n # posX, posY = self.CalcUnscrolledPosition (0, 0)\n upd = wx.RegionIterator(self.GetUpdateRegion()) # get the update rect list\n r = []\n while upd.HaveRects():\n rect = upd.GetRect()\n\n # Repaint this rectangle\n #PaintRectangle(rect, dc)\n r.append(\"rect: %s\" % str(rect))\n upd.Next()\n print(s, (posX, posY), (vbX, vbY), \" \".join(r))\n dc.SetLogicalOrigin(posX, posY)\n\n dc.SetFont(wx.NORMAL_FONT)\n w, height = dc.GetTextExtent(s)\n height += 3\n dc.SetBrush(wx.WHITE_BRUSH)\n dc.SetPen(wx.WHITE_PEN)\n dc.DrawRectangle(0, 0, size.x, size.y)\n dc.SetPen(wx.LIGHT_GREY_PEN)\n dc.DrawLine(0, 0, size.x, size.y)\n dc.DrawLine(0, size.y, size.x, 0)\n dc.DrawText(s, (size.x-w)/2, (size.y-height*5)/2)\n \n def on_left_up(self, event):\n print()\n print(\"Title \" + str(self))\n print(\"Position \" + str(self.GetPosition()))\n print(\"ViewStart \" + str(self.GetViewStart()))\n print(\"Size \" + str(self.GetSize()))\n print(\"VirtualSize \" + str(self.GetVirtualSize()))\n\n\nclass HexGridColHeader(HexGridHeader):\n use_x = 1\n use_y = 0\n\n\nclass HexGridRowHeader(HexGridHeader):\n use_x = 0\n use_y = 1\n\n\nclass HexGridDataWindow(HexGridHeader):\n pass\n\n\nclass MyApp(wx.App):\n \"\"\"\n Simple Application class for testing\n \"\"\"\n def OnInit(self):\n \"\"\"\n Initialize the Application\n \"\"\"\n #This is the frame as I want to use it, with a tri-pane scroll window\n #However, the information sent to the sub-window is incorrect, so the\n #on_paint callback draws the wrong area on screen...\n id = wx.NewId()\n frame = wx.Frame(None, id, \"Test Tri-pane frame\" )\n scroll = HexGridWindow(frame, wx.NewId())\n scroll.set_pane_sizes(3000, 1000, 80, 20)\n scroll.SetScrollRate(20,20)\n #(width, height) = dc.GetTextExtent(\"M\")\n frame.Show()\n # self.SetTopWindow(frame)\n \n print(\"wx.VERSION = \" + wx.VERSION_STRING)\n return True\n \n#For testing\nif __name__ == '__main__':\n app = MyApp(False)\n app.MainLoop()\n","repo_name":"robmcmullen/wx4demos","sub_path":"scrolltarget2.py","file_name":"scrolltarget2.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10333047174","text":"from core.type import metadata_t, parserInput_t\n\ndef parse(input: parserInput_t):\n\tdescription = input.description\n\ttitle = input.title\n\tuploader = input.uploader\n\tid = input.id\n\n\tm = metadata_t\n\tm.genre = 'Eurobeat'\n\tm.artist = 'Turbo'\n\tif ' _ ' in title or ' - ' in title or ' / ' in title:\n\t\tfor split in (' _ ', ' / ', ' - '):\n\t\t\tif len(title.split(split)) > 1:\n\t\t\t\tm.title = title.split(split)[0]\n\t\t\t\tbreak\n\treturn(m)","repo_name":"DucksAndNetherwort/advanced_downloader_MKII","sub_path":"src/core/descriptionParsers/turbo.py","file_name":"turbo.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27016327561","text":"#5 Write a program that creates a list ['a','b','c'] then create a tuple and again create a list from it. \nL1=[]\nlenght=int(input(\"Enter the lenght of the list \"))\nfor i in range(0,lenght):\n element=input(\"Enter the element \")\n L1.append(element)\nprint(L1)\nL1=tuple(L1)\nprint(L1)\nL1=list(L1)\nprint(L1)\n\n\n\n\n\n\n\n\n\n","repo_name":"Hikmatullah-Nasiri/LPU-Lectures","sub_path":"6th Semester/Practice/Python/#16 lec 18 Tuples/Solution 5 list then create a tuple and again create a list from it .py","file_name":"Solution 5 list then create a tuple and again create a list from it .py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"29179873036","text":"from django.urls import path\nfrom .views import DashAPIView,get_pacakges,create_investment,end_user_investment,WithdrawApiview,TransactionApiview,SettingsApiview\n\n\nurlpatterns = [\n path('dashboard/',DashAPIView.as_view()),\n path('packages/',get_pacakges),\n path('create-investment/',create_investment),\n path('end-investment/',end_user_investment),\n path('withdrawal/',WithdrawApiview.as_view()),\n path('transactions/',TransactionApiview.as_view()),\n path('settings/',SettingsApiview.as_view()),\n]\n","repo_name":"devla-d/earnalipayapi","sub_path":"userdashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3233698623","text":"import pymongo\r\n\r\nmyClient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\nmydb = myClient[\"FootballDBMongo\"]\r\n\r\nprint(\"Herzlich Willkommen\")\r\nuserInputClub = input(\"----------Enter the name of the club---------: \")\r\n\r\nquery1 = {\"name\": userInputClub}\r\nquery2 = {\"TitlesWon\": 1, \"_id\" : 0}\r\n\r\ndatabaseCollection = mydb.clubStats.find(query1,query2)\r\n\r\nhasValue = True if mydb.clubStats.count_documents({\"name\":userInputClub}) > 0 else False\r\n\r\nif hasValue:\r\n for titles in mydb.clubStats.find({\"name\":userInputClub},{\"TitlesWon\": 1, \"_id\" : 0}):\r\n print(\" Number of titles won by the club are/is:\")\r\n print(\" Year Title\")\r\n title = titles[\"TitlesWon\"]\r\n for k in title:\r\n for a in k: \r\n print(\" {} \".format(k[a]),end=\"\")\r\n print()\r\n \r\nelse:\r\n print(\"No data found\")\r\n\r\n","repo_name":"chinmay81192/Information-Systems","sub_path":"Story2a.py","file_name":"Story2a.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41639135284","text":"\"\"\" Exemplo de uso da Biblioteca PeasyCam\n * documentação em http://mrfeinberg.com/peasycam/\n No menu do IDE Processing: Sketch > Import Library... > Add Library.. > [search for PeasyCam & install]\n depois Import Library... > PeasyCam\n - Clique e arraste o mouse (mouseDragged) para orbitar\n - Scroll Wheel = Zoom\n - Command = Translate\n\"\"\"\nadd_library('peasycam')\n\ndef setup():\n global camera\n size(200, 200, P3D) # note o setup do canvas 3D\n camera = PeasyCam(this, 100)\n camera.setMinimumDistance(50)\n camera.setMaximumDistance(500)\n\ndef draw():\n rotateX(-.5)\n rotateY(-.5)\n background(0)\n fill(255, 0, 0)\n box(30)\n with pushMatrix():\n translate(0, 0, 20)\n fill(0, 0, 255)\n box(5)\n camera.beginHUD() # para desenhar relativo ao ponto de vista da câmera\n fill(255)\n rect(30,30,30,30)\n camera.endHUD() # se usou .beginHUD() no esqueça de .endHUD() sempre!\n\n \n","repo_name":"villares/py.processing-play","sub_path":"3D/PeasyCam/basic_PeasyCam_with_HUD/basic_PeasyCam_with_HUD.pyde","file_name":"basic_PeasyCam_with_HUD.pyde","file_ext":"pyde","file_size_in_byte":962,"program_lang":"python","lang":"pt","doc_type":"code","stars":23,"dataset":"github-code","pt":"52"}
+{"seq_id":"21272736486","text":"from ctypes import sizeof\r\nfrom matplotlib import pyplot as plt\r\nfrom matplotlib import style\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom numba import jit, cuda\r\nimport pandas as pd\r\n\r\n'''The data has been divided into 4 sub-dataset due to computational'''\r\n\r\nX,Y = np.loadtxt('C:/path/to/first/subset/0.txt', \r\n dtype= int,skiprows=(4), unpack= True, delimiter='\\t') \r\n \r\nZ,S = np.loadtxt('C:/path/to/second/subset/1.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n \r\nA,B = np.loadtxt('C:/path/to/third/subset/2.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n \r\nC,D = np.loadtxt('C:/path/to/fourth/subset/3.txt', \r\n dtype= int, unpack= True, delimiter='\\t') \r\n\r\n\r\n#use cuda for better performance when possible\r\n@jit(target_backend='cuda')\t\r\ndef numberOfInstances(v, X):\r\n i=0\r\n for z in X:\r\n if(v==z): i= i+1\r\n \r\n return i\r\n\r\n@jit(target_backend='cuda')\t\r\ndef arrayNoDup(X):\r\n result = []\r\n \r\n print(\"Creazione array senza doppioni\")\r\n\r\n for v in tqdm(X):\r\n if v not in result:\r\n result.append(v)\r\n \r\n print(\"Array senza doppioni creato\")\r\n\r\n return result\r\n\r\n\r\ndef visualize(X,Y):\r\n plt.plot(X,Y)\r\n\r\n plt.title('Prova Visual')\r\n plt.ylabel('Y Riceventi')\r\n plt.xlabel('X Mandanti')\r\n\r\n plt.show()\r\n\r\ndef createHistogram(X):\r\n #X_No_Dup= arrayNoDup(X) \r\n \r\n '''for v in X_No_Dup:\r\n X_num.append(numberOfInstances(v,X))\r\n i=i+1'''\r\n\r\n plt.hist(X, density=False, bins = 400) # density=False would make counts \r\n\r\n plt.ylabel('Degree')\r\n plt.xlabel('Node')\r\n plt.show()\r\n \r\n\r\n\r\ndef saveArrayNoDup(X,name):\r\n X_num = []\r\n X_No_Dup= arrayNoDup(X) \r\n i = 0\r\n for v in X_No_Dup:\r\n X_num.append(numberOfInstances(v,X))\r\n i=i+1\r\n\r\n i = 0\r\n \r\n with open(name+'RoadNoDupCount.txt', 'w') as f:\r\n for y in X_No_Dup:\r\n line = [str(X_No_Dup[i]),str(X_num[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n f.close\r\n\r\n\r\n''' \r\nvisualize(X_No_Dup,X_num) \r\nprint(X[0],Y[0]) \r\n'''\r\n#createHistogram(X)\r\n\r\n'''caricare un .txt direttamente in un dizionario con chiave il nodo e valore il numIstanze ''' \r\ndef createDict(d,txt,i):\r\n\r\n print(\"Creazione dizionario \"+i)\r\n\r\n with open(txt) as f:\r\n for line in f:\r\n (key, val) = line.split()\r\n d[int(key)] = val\r\n \r\n print(\"Dizionario \"+i+\" creato \\n\")\r\n \r\n return d\r\n\r\n#@jit(target_backend='cuda',nopython=True)\t\r\ndef mergeDict(dx,dy,n,m):\r\n \r\n Degree = []\r\n Nodes = []\r\n\r\n print(\"Merging dizionari \"+n+\" e \"+m+\" \\n\")\r\n for j in tqdm(dx.keys()):\r\n #for j in dx.keys(): \r\n if j in dy.keys(): \r\n Nodes.append(j) \r\n val = int(dx[int(j)])\r\n val2 = int(dy[int(j)])\r\n \r\n Degree.append(val+val2)\r\n \r\n else:\r\n Nodes.append(j)\r\n Degree.append(int(dx[int(j)]))\r\n\r\n \r\n\r\n for k in tqdm(dy.keys()):\r\n if k not in Nodes:\r\n Nodes.append(k)\r\n Degree.append(int(dy[int(k)])) \r\n \r\n\r\n print(\"Merging dizionari completo \\n Salvataggio...\")\r\n return Nodes,Degree\r\n\r\n\r\n\r\ndef mergeAndSave():\r\n \r\n Degree = []\r\n Nodes = []\r\n Degree1 = []\r\n Nodes1 = []\r\n Degree2 = []\r\n Nodes2 = []\r\n \r\n saveArrayNoDup(A,'0')\r\n saveArrayNoDup(C,'1')\r\n saveArrayNoDup(A,'2')\r\n saveArrayNoDup(C,'3')\r\n\r\n d0 = {}\r\n\r\n d0 = createDict(d0,\"C:/path/to/0RoadNoDupCount.txt\",'0')\r\n \r\n d1 = {}\r\n\r\n d1 = createDict(d1,\"C:/path/to/1RoadNoDupCount.txt\",'1')\r\n\r\n d2 = {}\r\n \r\n d2 = createDict(d2,\"C:/path/to/2RoadNoDupCount.txt\",'2')\r\n\r\n d3 = {}\r\n\r\n d3 = createDict(d3,\"C:/path/to/3RoadNoDupCount.txt\",'3')\r\n \r\n \r\n Nodes,Degree = mergeDict(d0,d1,'0','1')\t\t#merge first two subset and save the result\r\n \r\n i = 0\r\n with open('1provaRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes):\r\n line = [str(Nodes[i]),str(Degree[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario completo\")\r\n\r\n \r\n Nodes1,Degree1 = mergeDict(d2,d3,'2','3') \t#merge last two subset and save the result\r\n\r\n i = 0\r\n with open('2HalfRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes1):\r\n line = [str(Nodes1[i]),str(Degree1[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario completo\")\r\n\r\n \r\n\r\n dh1 = {}\r\n\r\n dh1 = createDict(dh1,\"C:/Users/danil/Downloads/magistrale/Social Network Analysis/Project/1HalfRoadNoDupCount.txt\",'H-1')\r\n\r\n dh2 = {}\r\n \r\n dh2 = createDict(dh2,\"C:/Users/danil/Downloads/magistrale/Social Network Analysis/Project/2HalfRoadNoDupCount.txt\",'H-2')\r\n\r\n Nodes2,Degree2 = mergeDict(dh1,dh2,'H-1','H-2')\t#merge intermediate subset and save the result\r\n\r\n i = 0\r\n with open('FullRoadNoDupCount.txt', 'w') as f:\r\n for y in tqdm(Nodes2):\r\n line = [str(Nodes2[i]),str(Degree2[i])]\r\n tab = '\\t' \r\n lines = tab.join(line)\r\n f.write(lines + '\\n')\r\n i = i+1\r\n print(\"Salvataggio dizionario totale completo\")\r\n \r\n \r\nmergeAndSave() ","repo_name":"DaniMe98/California-Road-Network-Analysis","sub_path":"dataUtils.py","file_name":"dataUtils.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70438358886","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport urllib,urllib2\nimport re\nimport os\nimport emblemas\n\ndef main():\n\tos.system('clear');\n\tprint(emblemas.emblemas());\n\tglobal target;\n\tglobal pattern;\n\tglobal alphabet;\n\tglobal fieldsInTable;\n\tglobal disableTables;\n\ttry:\n\t\tfieldsInTable={};\n\t\ttarget=raw_input('#'*50+'\\nTarget (http://www.target.com/poc?id=5): ');\n\t\tpattern=raw_input('#'*50+'\\nPatron a buscar para considerar False: ');\n\t\talphabet=raw_input('#'*50+'\\nAlfabeto a considerar: ');\n\t\trunBlindSqlInjection();\n\texcept:\n\t\traw_input('Hubo un error...\\n');\n\t\tmain();\n\ndef runBlindSqlInjection():\n\tgetTablesUsingDictionary();\n\troughNumTables=getRoughNumTables();\n\tnumTables=getNumTables(roughNumTables)-1;\n\tnumTablesLetters=getNumTablesLetters();\n\tlengthsTablesNames=getLengthsTablesNames(numTablesLetters);\n\ttablesNames=getTablesNames(numTablesLetters,lengthsTablesNames);\n\tfieldsInTable=getFieldsInTable(tablesNames);\n\tdata=[numTables,fieldsInTable];\n\tprintData(data);\n\ndef getTablesUsingDictionary():\n\tdictionary=open('tables_dictionary.txt','r');\n\tglobal disableTables;\n\tdisableTables=\"+AND+\";\n\tfor table in dictionary:\n\t\ttable=re.sub(r\"\\s\",\"\",table,flags=re.I);\n\t\tquery=target+\"+and+(select+count(table_name)+from+information_schema.tables+where+table_name='\"+table+\"')>=1--\"\n\t\tif(table!=\"*\"):\n\t\t\tdisableTables=disableTables+\"table_name!='\"+table+\"'+AND+\";\n\t\telse:\n\t\t\tdisableTables=disableTables+\"table_name!='\"+table+\"'\";\n\t\tif(isTrue(query)):\n\t\t\tfieldsInTable[table]=[];\n\t\t\tnumColumns=getNumFieldsInTable(table);\n\t\t\tindexColumn=0;\n\t\t\twhile(indexColumn=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn chr(center);\n\t\telse:\n\t\t\tquery=target+\"+and+(select+ascii(substring(column_name,\"+str(indexChar)+\",1))+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter='_';\n\treturn er;\n\t\ndef getLengthFieldInTable(tableName,indexField,inf=0,sup=1000):\n\twhile(inf<=sup):\n\t\tprint(emblemas.loader());\n\t\tcenter=((sup-inf)/2)+inf;\n\t\tquery=target+\"+and+(select+length(column_name)+between+\"+str(center)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn center;\n\t\telse:\n\t\t\tquery=target+\"+and+(select+length(column_name)+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"'+limit+\"+str(indexField)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter=0;\n\treturn 0;\n\ndef getNumFieldsInTable(tableName,inf=0,sup=10000):\n\twhile(inf<=sup):\n\t\tprint(emblemas.loader());\n\t\tcenter=((sup-inf)/2)+inf;\n\t\tquery=target+\"+and+(select+count(column_name)+between+\"+str(center)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"')>=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn center;\n\t\telse:\n\t\t\tquery=target+\"+and+(select+count(column_name)+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.columns+where+table_name='\"+tableName+\"')>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter=0;\n\treturn 0;\n\t\ndef getTablesNames(numTablesLetters,lengthTablesNames):\n\ti=0;\n\ttablesNames={};\n\twhile(i=1--\"\n\t\tif(isTrue(query)):\n\t\t\treturn chr(center);\n\t\telse:\n\t\t\tquery=target+\"+and+(select+ascii(substring(table_name,\"+str(indexChar)+\",1))+between+\"+str(inf)+\"+AND+\"+str(center)+\"+from+information_schema.tables+where+table_name+LIKE+'\"+letter+\"%'\"+disableTables+\"+limit+\"+str(indexTable)+\",1)>=1--\"\n\t\t\tif(isTrue(query)):\n\t\t\t\tsup=center-1;\n\t\t\telse:\n\t\t\t\tinf=center+1;\n\ter='_';\n\treturn er;\n\ndef getLengthsTablesNames(numTablesLetters):\n\ti=0;\n\tlengthsTablesNames={};\n\twhile(i0):\n\t\t\tlengthsTablesNames[alphabet[i]]=[];\n\t\t\twhile(j=\"+str(length)+\"--\"\n\tif(isTrue(newTarget)):\n\t\tlength=length+1;\n\t\treturn getLengthTableName(letter,index,length);\n\telse:\n\t\treturn length;\n\t\ndef getNumTables(rough):\n\tprint(emblemas.loader())\n\ttotal=rough;\n\tnewTarget=target+\"+and+(select+count(table_name)+from+information_schema.tables)>=\"+str(rough)+\"--\"\n\tif(isTrue(newTarget)):\n\t\trough=rough+1;\n\t\treturn getNumTables(rough);\n\telse:\n\t\treturn total;\n\ndef getRoughNumTables(count=10):\n\tprint(emblemas.loader())\n\tnewTarget=target+\"+and+(select+count(table_name)+between+0+AND+\"+str(count+10)+\"+from+information_schema.tables)>=1--\"\n\tif(isTrue(newTarget)):\n\t\treturn count;\n\telse:\n\t\tcount=count+15;\n\t\treturn getRoughNumTables(count);\n\ndef getNumTablesLetters():\n\ti=0;\n\tnumTablesLetter={};\n\twhile(i=\"+str(count)+\"--\"\n\tif(isTrue(newTarget)):\n\t\tcount=count+1;\n\t\treturn getNumTablesLetter(letter,count);\n\telse:\n\t\treturn total;\n\t\ndef isTrue(newTarget):\n\tprint(newTarget);\n\tpath=re.match('https?://(([a-zA-Z]+)?\\.?[a-zA-Z]+\\.[a-zA-Z]+)(\\/.*)?',newTarget,re.I);\n\tpath=path.group(3);\n\tpath=path if path!=None else '/';\n\tconnection=urllib2.urlopen(newTarget);\n\tresponse=connection.read();\n\tconnection.close();\n\tmatches=re.findall(pattern,response,flags=re.I);\n\tif(len(matches)==0):\n\t\treturn True;\n\telse:\n\t\treturn False;\n\t\t\nif __name__=='__main__': \n\tmain();\n","repo_name":"0v3rflow1/python","sub_path":"AutomaticBlindSqlInjection.py","file_name":"AutomaticBlindSqlInjection.py","file_ext":"py","file_size_in_byte":8982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9063665768","text":"import argparse\nimport os\nimport lightgbm as lgbm\nimport catboost as ctb\n\nfrom typing import Optional\nfrom urllib.request import urlretrieve\nfrom ml_investment.utils import load_config\nfrom ml_investment.features import QuarterlyFeatures, BaseCompanyFeatures, \\\n FeatureMerger, DailyAggQuarterFeatures, \\\n QuarterlyDiffFeatures\nfrom ml_investment.targets import DailyAggTarget\nfrom ml_investment.models import TimeSeriesOOFModel, EnsembleModel, LogExpModel\nfrom ml_investment.metrics import median_absolute_relative_error, down_std_norm\nfrom ml_investment.pipelines import Pipeline\nfrom ml_investment.download_scripts import download_sf1, download_commodities\n\nconfig = load_config()\n\n\nURL = 'https://github.com/fartuk/ml_investment/releases/download/weights/marketcap_down_std_sf1.pickle'\nOUT_NAME = 'marketcap_down_std_sf1'\nDATA_SOURCE='sf1'\nCURRENCY = 'USD'\nVERBOSE = True\nTARGET_HORIZON = 90\nMAX_BACK_QUARTER = 20\nMIN_BACK_QUARTER = 0\nBAGGING_FRACTION = 0.7\nMODEL_CNT = 20\nFOLD_CNT = 20\nQUARTER_COUNTS = [2, 4, 10]\nCOMPARE_QUARTER_IDXS = [1, 4]\nAGG_DAY_COUNTS = [100, 200, 400, 800]\nSCALE_MARKETCAP = [\"4 - Mid\", \"5 - Large\", \"6 - Mega\"]\nDAILY_AGG_COLUMNS = [\"marketcap\", \"pe\"]\nCAT_COLUMNS = [\"sector\", \"sicindustry\"]\nQUARTER_COLUMNS = [\n \"revenue\",\n \"netinc\",\n \"ncf\",\n \"assets\",\n \"ebitda\",\n \"debt\",\n \"fcf\",\n \"gp\",\n \"workingcapital\",\n \"cashneq\",\n \"rnd\",\n \"sgna\",\n \"ncfx\",\n \"divyield\",\n \"currentratio\",\n \"netinccmn\"\n ]\n\n\n\ndef _check_download_data():\n if not os.path.exists(config['sf1_data_path']):\n print('Downloading sf1 data')\n download_sf1.main()\n\n\ndef _create_data():\n if DATA_SOURCE == 'sf1':\n from ml_investment.data_loaders.sf1 import SF1BaseData, SF1DailyData, \\\n SF1QuarterlyData\n elif DATA_SOURCE == 'mongo':\n from ml_investment.data_loaders.mongo import SF1BaseData, SF1DailyData, \\\n SF1QuarterlyData \n data = {}\n data['quarterly'] = SF1QuarterlyData()\n data['base'] = SF1BaseData()\n data['daily'] = SF1DailyData()\n \n return data\n\n\n\ndef _create_feature():\n fc1 = QuarterlyFeatures(data_key='quarterly',\n columns=QUARTER_COLUMNS,\n quarter_counts=QUARTER_COUNTS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n\n fc2 = BaseCompanyFeatures(data_key='base',\n cat_columns=CAT_COLUMNS,\n verbose=VERBOSE)\n \n fc3 = QuarterlyDiffFeatures(data_key='quarterly',\n columns=QUARTER_COLUMNS,\n compare_quarter_idxs=COMPARE_QUARTER_IDXS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n \n fc4 = DailyAggQuarterFeatures(daily_data_key='daily',\n quarterly_data_key='quarterly',\n columns=DAILY_AGG_COLUMNS,\n agg_day_counts=AGG_DAY_COUNTS,\n max_back_quarter=MAX_BACK_QUARTER,\n min_back_quarter=MIN_BACK_QUARTER,\n verbose=VERBOSE)\n\n feature = FeatureMerger(fc1, fc2, on='ticker')\n feature = FeatureMerger(feature, fc3, on=['ticker', 'date'])\n feature = FeatureMerger(feature, fc4, on=['ticker', 'date'])\n\n return feature\n\n\ndef _create_target():\n target = DailyAggTarget(data_key='daily',\n col='marketcap',\n horizon=TARGET_HORIZON,\n foo=down_std_norm)\n return target\n\n\ndef _create_model():\n base_models = [LogExpModel(lgbm.sklearn.LGBMRegressor()),\n LogExpModel(ctb.CatBoostRegressor(verbose=False))]\n \n ensemble = EnsembleModel(base_models=base_models, \n bagging_fraction=BAGGING_FRACTION,\n model_cnt=MODEL_CNT)\n\n model = TimeSeriesOOFModel(base_model=ensemble,\n time_column='date',\n fold_cnt=FOLD_CNT)\n\n return model\n \n\n\ndef MarketcapDownStdSF1(max_back_quarter: int=None,\n min_back_quarter: int=None,\n data_source: Optional[str]=None,\n pretrained: bool=True,\n verbose: bool=None) -> Pipeline:\n '''\n Model is used to predict future down-std value.\n Pipeline consist of time-series model training( \n :class:`~ml_investment.models.TimeSeriesOOFModel` )\n and validation on real marketcap down-std values(\n :class:`~ml_investment.targets.DailyAggTarget` ).\n Model prediction may be interpreted as \"risk\" for the next quarter.\n :mod:`~ml_investment.data_loaders.sf1`\n is used for loading data.\n\n Note:\n SF1 dataset is paid, so for using this model you need to subscribe \n and paste quandl token to `~/.ml_investment/secrets.json`\n ``quandl_api_key``\n\n Parameters\n ----------\n max_back_quarter:\n max quarter number which will be used in model\n min_back_quarter:\n min quarter number which will be used in model\n data_source:\n which data use for model. One of ['sf1', 'mongo'].\n If 'mongo', than data will be loaded from db,\n credentials specified at `~/.ml_investment/config.json`.\n If 'sf1' - from folder specified at ``sf1_data_path``\n in `~/.ml_investment/secrets.json`.\n pretrained:\n use pretreined weights or not. \n Downloading directory path can be changed in\n `~/.ml_investment/config.json` ``models_path``\n verbose:\n show progress or not\n '''\n if data_source is not None:\n global DATA_SOURCE \n DATA_SOURCE = data_source\n \n if max_back_quarter is not None:\n global MAX_BACK_QUARTER \n MAX_BACK_QUARTER = max_back_quarter\n\n if min_back_quarter is not None:\n global MIN_BACK_QUARTER \n MIN_BACK_QUARTER = min_back_quarter\n\n if verbose is not None:\n global VERBOSE \n VERBOSE = verbose\n\n if DATA_SOURCE == 'sf1':\n _check_download_data()\n \n data = _create_data()\n feature = _create_feature()\n target = _create_target()\n model = _create_model()\n\n pipeline = Pipeline(feature=feature, \n target=target, \n model=model,\n data=data,\n out_name=OUT_NAME)\n \n core_path = '{}/{}.pickle'.format(config['models_path'], OUT_NAME)\n\n if pretrained:\n if not os.path.exists(core_path):\n urlretrieve(URL, core_path) \n pipeline.load_core(core_path)\n\n return pipeline\n\n\n \n\n\ndef main(data_source):\n '''\n Default model training. Resulted model weights directory path \n can be changed in `~/.ml_investment/config.json` ``models_path``\n '''\n pipeline = MarketcapDownStdSF1(pretrained=False, data_source=data_source) \n base_df = pipeline.data['base'].load()\n tickers = base_df[(base_df['currency'] == CURRENCY) &\\\n (base_df['scalemarketcap'].apply(lambda x: x in SCALE_MARKETCAP))\n ]['ticker'].values\n result = pipeline.fit(tickers, median_absolute_relative_error)\n print(result)\n path = '{}/{}'.format(config['models_path'], OUT_NAME)\n pipeline.export_core(path) \n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n arg = parser.add_argument\n arg('--data_source', type=str)\n args = parser.parse_args()\n main(args.data_source)\n \n \n","repo_name":"fartuk/ml_investment","sub_path":"ml_investment/applications/marketcap_down_std_sf1.py","file_name":"marketcap_down_std_sf1.py","file_ext":"py","file_size_in_byte":8134,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"52"}
+{"seq_id":"9238472732","text":"import serial\nfrom time import sleep\nimport time\n\ndef wirte_time(serial):\n ti = 0\n \n while True:\n serial.write(b\"CLS(3);\\r\\n\")\n serial.write(\"DS48(1,2,'action \".encode('utf-8')+str(ti).encode('utf-8')+\"s',1);\\r\\n\".encode('utf-8'))\n time.sleep(0.5)\n ti = ti +0.5\n\n\ndef recv(serial):\n while True:\n data = serial.read_all()\n if data == '':\n continue\n else:\n break\n sleep(0.02)\n return data\n\nif __name__ == '__main__':\n serial = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.5) #/dev/ttyUSB0\n if serial.isOpen() :\n print(\"open success\")\n else :\n print(\"open failed\")\n #serial.write(\"CLS(3);\\r\\n\".encode('utf-8'))\n wirte_time(serial)\n \n","repo_name":"HuyCui/ACsystem","sub_path":"actionPI/screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72887030884","text":"from django.shortcuts import render\nfrom django.views import generic,View\nfrom django.http import JsonResponse\nfrom cash.forms import CashForm,CashIncrementForm,CashDecrementForm\nfrom custom.views import (JSONCreateView,JSONUpdateView,\n JSONQueryView,JSONDeleteView)\nfrom cash.models import Cash,CashIncrement,CashDecrement\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom cash.helpers import (group_by_day,sort_time,\n prepare_changes_data,historate_cash)\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.utils.decorators import method_decorator\nfrom custom.decorators import access_required\n# from django.db.models import Sum\nfrom pos.models import CashSale,CashSalesReturn\nfrom pop.models import CashPurchase,CashPurchaseReturn\nfrom django.db.models import Sum,F,FloatField\nimport datetime\n# This view loads in the app\n@method_decorator(access_required('cash'), name='dispatch')\nclass AppInit(LoginRequiredMixin,generic.base.TemplateView):\n template_name = 'cash/index.html'\n\nclass Systems(JSONQueryView):\n model = Cash\n\n def make_query(self,ask=None):\n cashs = super().make_query(ask)\n data = []\n for cash in cashs:\n data.append({'id':cash['id'],\n 'value':cash['system']+\" ~ \"+cash['currency'],\n 'currency':cash['currency'],\n 'system':cash['system'],\n })\n return data\n#Views for Cash model\n#create view\nclass CreateCash(JSONCreateView):\n form = CashForm\n#update view\nclass UpdateCash(JSONUpdateView):\n form = CashForm\n model = Cash\n#delete view\nclass DeleteCash(JSONDeleteView):\n model = Cash\n#query view\nclass Cashs(JSONQueryView):\n model = Cash\n\n# Views for cashincrement model\n#create cashincrement\nclass CreateCashIncrement(JSONCreateView):\n form = CashIncrementForm\n model = CashIncrement\n user_required = True\n#query cashincrement\nclass CashIncrements(JSONQueryView):\n model = CashIncrement\n#Views for cashdecrement model\n#create cashdecrement\nclass CreateCashDecrement(JSONCreateView):\n form = CashDecrementForm\n model = CashDecrement\n user_required = True\n#query cashdecrement\nclass CashDecrements(JSONQueryView):\n model = CashDecrement\n\nclass CashTracker(View):\n\n def get(self, request, *args, **kwargs):\n if request.GET:\n b = request.GET['b']\n e = request.GET['e']\n p = request.GET['p']\n data = {}\n data['summary'] = self.process_summary(request,b,e,p)\n gdat = self.process_graph(request,b,e,p)\n # raise Exception(\"Break\")\n prepare_changes_data(gdat['inc'])\n data['inc'] = gdat['inc']\n prepare_changes_data(gdat['dec'])\n data['dec'] = gdat['dec']\n data['chart'] = gdat['chart']\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def post(self, request, *args, **kwargs):\n if request.POST:\n b = request.POST['b']\n e = request.POST['e']\n p = request.POST['p']\n data = {}\n data['summary'] = self.process_summary(request,b,e,p)\n gdat = self.process_graph(request,b,e,p)\n prepare_changes_data(gdat['inc'])\n data['inc'] = gdat['inc']\n prepare_changes_data(gdat['dec'])\n data['dec'] = gdat['dec']\n data['chart'] = gdat['chart']\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def process_summary(self,request,b,e,p):\n\n if p=='all':\n inc = CashIncrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n dec = CashDecrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n else:\n inc = CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n dec = CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n end = Cash.objects.filter(pk=p).aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n inc['total'] = inc['total'] if inc['total'] is not None else 0\n dec['total'] = dec['total'] if dec['total'] is not None else 0\n end['total'] = end['total'] if end['total'] is not None else 0\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end['total']=end['total']-today_end_inc['total']+today_end_dec['total']\n start = end['total'] - inc['total'] + dec['total']\n\n data = [\n {'id':1,'a':start,'b':'','c':'','desc':'Cash on hand at the beginning of the period'},\n {'id':2,'a':inc['total'],'b':'','c':'','desc':'Add all increments in cash'},\n {'id':3,'a':'','b':start+inc['total'],'c':'','desc':''},\n {'id':4,'a':'','b':dec['total'],'c':'','desc':'Subtract all decrements in cash'},\n {'id':5,'a':'','b':'','c':end['total'],'desc':'Cash on hand at the end of the period'},\n ]\n\n return data\n\n def process_graph(self,request,b,e,p):\n \n if p=='all':\n tinc = CashIncrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n tdec = CashDecrement.objects.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n inc = list(CashIncrement.objects.filter(timestamp__range=(b,e)).order_by('-timestamp').values())\n dec = list(CashDecrement.objects.filter(timestamp__range=(b,e)).order_by('-timestamp').values())\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n else:\n tinc = CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n tdec = CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).aggregate(total=Sum('amount'))\n inc = list(CashIncrement.objects.filter(timestamp__range=(b,e),cash_id=p).order_by('-timestamp').values())\n dec = list(CashDecrement.objects.filter(timestamp__range=(b,e),cash_id=p).order_by('-timestamp').values())\n end = Cash.objects.filter(pk=p).aggregate(total=Sum('balance'))\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = CashIncrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n today_end_dec = CashDecrement.objects.filter(timestamp__range=(e,today),cash_id=p).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n tinc['total'] = tinc['total'] if tinc['total'] is not None else 0\n tdec['total'] = tdec['total'] if tdec['total'] is not None else 0\n end['total'] = end['total'] if end['total'] is not None else 0\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end['total']=end['total']-today_end_inc['total']+today_end_dec['total']\n start = end['total'] - tinc['total'] + tdec['total']\n dinc = group_by_day(inc,'inc')\n ddec = group_by_day(dec,'dec')\n bdi = dinc\n bdi.extend(ddec)\n bdi.sort(key=sort_time)\n idb = historate_cash(start,bdi)\n data = {'inc':inc,'dec':dec,'chart':idb}\n return data\n # Get increment and decremet for each day\n\nclass CashSummaryTracker(View):\n\n def get(self, request, *args, **kwargs):\n if request.GET:\n b = request.GET['b']\n e = request.GET['e']\n data = {}\n data['summary'] = self.process_summary(request,b,e)\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def post(self, request, *args, **kwargs):\n if request.POST:\n b = request.POST['b']\n e = request.POST['e']\n data = {}\n data['summary'] = self.process_summary(request,b,e)\n data['status'] = True\n else:\n data = {'status':False}\n return JsonResponse(data)\n\n def process_summary(self,request,b,e):\n \n prod = Cash.objects.all()\n data = []\n for pro in prod:\n inc = pro.cashincrement_set.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n purch = pro.cashdecrement_set.filter(content_type__model=\"cashpurchase\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n pr = pro.cashincrement_set.filter(content_type__model=\"cashpurchasereturn\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n sr = pro.cashdecrement_set.filter(content_type__model=\"cashsalesreturn\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n dec = pro.cashdecrement_set.filter(timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n sales = pro.cashincrement_set.filter(content_type__model=\"cashsale\",timestamp__range=(b,e)).aggregate(total=Sum('amount'))\n end = pro.balance\n today = str(datetime.datetime.today().date())\n if today > e:\n today = str((datetime.datetime.today()+datetime.timedelta(days=1)).date())\n today_end_inc = pro.cashincrement_set.filter(timestamp__range=(b,today)).aggregate(total=Sum('amount'))\n today_end_dec = pro.cashdecrement_set.filter(timestamp__range=(b,today)).aggregate(total=Sum('amount'))\n else:\n today_end_inc = {'total':None}\n today_end_dec = {'total':None}\n\n today_end_inc['total'] = today_end_inc['total'] if today_end_inc['total'] is not None else 0\n today_end_dec['total'] = today_end_dec['total'] if today_end_dec['total'] is not None else 0\n end=end-today_end_inc['total']+today_end_dec['total']\n\n inc['total'] = inc['total'] if inc['total'] is not None else 0\n dec['total'] = dec['total'] if dec['total'] is not None else 0\n purch['total'] = purch['total'] if purch['total'] is not None else 0\n pr['total'] = pr['total'] if pr['total'] is not None else 0\n sr['total'] = sr['total'] if sr['total'] is not None else 0\n sales['total'] = sales['total'] if sales['total'] is not None else 0\n initial = end - inc['total'] + dec['total']\n data.append({\n 'system':pro.system+\" ~ \"+pro.currency,\n 'init':initial,\n 'inc':inc['total'],\n 'purchases':purch['total'],\n 'pr':pr['total'],\n 'sr':sr['total'],\n 'dec':dec['total'],\n 'sales':sales['total'],\n 'end':end\n })\n end = Cash.objects.all().aggregate(total=Sum('balance'))\n return data\n","repo_name":"baahkusi/caretaker","sub_path":"cash/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12989,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"29617382887","text":"import os\nimport sys\n\nif __package__ == \"\" or __name__ == \"__main__\":\n sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom app.libs.file import urldownload\n\nfile_dir = \"./app/static/images/book/\"\ndir_list = os.listdir(file_dir)\nheaders = {\n \"referer\": \"http://127.0.0.1:5000/\",\n \"user-agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.175\",\n}\nfor cur_file in dir_list:\n # 获取文件的绝对路径\n path = os.path.join(file_dir, cur_file)\n abspath=os.path.abspath(path)\n if os.path.isfile(abspath):\n print(abspath)\n file_name = str.split(path, \"/\")[-1]\n urldownload(\"https://img3.doubanio.com/lpic/\" + file_name, abspath, headers)\n\n","repo_name":"yancey92/fisher","sub_path":"test/test_file.py","file_name":"test_file.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"13323264626","text":"'''\nSupport for pkgng\n'''\n\nimport os \n\ndef __virtual__():\n '''\n Pkgng module load on FreeBSD only.\n '''\n if __grains__['os'] == 'FreeBSD':\n return 'pkgng'\n else:\n return False\n\n\ndef parse_config(file_name='/usr/local/etc/pkg.conf'):\n '''\n Return dict of uncommented global variables.\n\n CLI Example::\n\n salt '*' pkgng.parse_config\n *NOTE* not working right\n '''\n ret = {}\n l = []\n if not os.path.isfile(file_name):\n return 'Unable to find {0} on file system'.format(file_name)\n\n with open(file_name) as f:\n for line in f.readlines():\n if line.startswith(\"#\") or line.startswith(\"\\n\"):\n pass\n else:\n k, v = line.split('\\t')\n ret[k] = v\n l.append(line)\n ret['config_file'] = file_name\n return ret\n\n\ndef version():\n '''return the version of pkgng'''\n cmd = 'pkg -v'\n return __salt__['cmd.run'](cmd)\n\n\ndef update_package_site(new_url):\n '''\n Updates remote package repo url, PACKAGESITE var to be exact.\n\n Must be using http://, ftp://, or https// protos\n\n CLI Example::\n salt '*' pkgng.update_package_site http://127.0.0.1/\n '''\n config_file = parse_config()['config_file']\n __salt__['file.sed'](config_file,'PACKAGESITE.*', \\\n 'PACKAGESITE\\t : {0}'.format(new_url))\n\n # add change return later\n return True\n\n\ndef stats():\n '''\n Return pkgng stats.\n\n CLI Example::\n salt '*' pkgng.stats\n '''\n\n cmd = 'pkg stats'\n res = __salt__['cmd.run'](cmd)\n res = [ x.strip(\"\\t\") for x in res.split(\"\\n\") ]\n return res\n\n\ndef backup(file_name):\n '''\n Export installed packages into yaml+mtree file\n\n CLI Example::\n salt '*' pkgng.backup /tmp/pkg\n '''\n cmd = 'pkg backup -d {0}'.format(file_name)\n res = __salt__['cmd.run'](cmd)\n return res.split('...')[1]\n\n\ndef restore(file_name):\n '''\n Reads archive created by pkg backup -d and recreates the database.\n '''\n cmd = 'pkg backup -r {0}'.format(file_name)\n res = __salt__['cmd.run'](cmd)\n return res\n\n\ndef add(pkg_path):\n '''\n Adds files from remote or local package\n\n CLI Example::\n salt '*' pkgng.add /tmp/package.txz\n '''\n if not os.path.isfile(pkg_path) or pkg_path.split(\".\")[1] != \"txz\":\n return '{0} could not be found or is not a *.txz \\\n format'.format(pkg_path)\n cmd = 'pkg add {0}'.format(pkg_path)\n res = __salt__['cmd.run'](cmd)\n return res\n\n\ndef info(pkg=None):\n '''\n Returns info on packages installed on system\n\n CLI Example::\n salt '*' pkgng.info\n\n For individual info\n\n salt '*' pkgng.info sudo\n '''\n if pkg:\n cmd = 'pkg info {0}'.format(pkg)\n else:\n cmd = 'pkg info'\n\n res = __salt__['cmd.run'](cmd)\n\n if not pkg:\n res = res.split('\\n')\n\n return res\n","repo_name":"autumnw/saltswift","sub_path":"salt/salt/modules/pkgng.py","file_name":"pkgng.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41208006469","text":"import numpy as np\nimport torch\n\nfrom Experiment_Engine.networks import TwoLayerFullyConnected, weight_init\nfrom Experiment_Engine.util import *\n\nclass NeuralNetworkFunctionApproximation:\n \"\"\" Parent class for all the neural networks \"\"\"\n def __init__(self, config, gates, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n num_actions int 3 Number of actions available to the agent\n gamma float 1.0 discount factor\n epsilon float 0.1 exploration parameter\n state_dims int 2 number of dimensions of the environment's states\n optim str 'sgd' optimization method. Choices: 'sgd', 'adam',\n 'rmsprop'\n lr float 0.001 learning rate\n store_summary bool False store the summary of the agent\n (cumulative_loss_per_episode)\n \"\"\"\n assert isinstance(config, Config)\n self.num_actions = check_attribute_else_default(config, 'num_actions', 3)\n self.gamma = check_attribute_else_default(config, 'gamma', 1.0)\n self.epsilon = check_attribute_else_default(config, 'epsilon', 0.1)\n self.state_dims = check_attribute_else_default(config, 'state_dims', 2)\n self.optim = check_attribute_else_default(config, 'optim', 'sgd', choices=['sgd', 'adam', 'rmsprop'])\n self.lr = check_attribute_else_default(config, 'lr', 0.001)\n self.store_summary = check_attribute_else_default(config, 'store_summary', False)\n if self.store_summary:\n assert isinstance(summary, dict)\n self.summary = summary\n check_dict_else_default(self.summary, 'cumulative_loss_per_episode', [])\n\n self.h1_dims = 32\n self.h2_dims = 256\n self.cumulative_loss = 0\n self.net = TwoLayerFullyConnected(self.state_dims, h1_dims=self.h1_dims, h2_dims=self.h2_dims,\n output_dims=self.num_actions, gates=gates)\n self.net.apply(weight_init)\n\n if self.optim == 'sgd': self.optimizer = torch.optim.SGD(self.net.parameters(), lr=self.lr)\n elif self.optim == 'adam': self.optimizer = torch.optim.Adam(self.net.parameters(), lr=self.lr)\n elif self.optim == 'rmsprop': self.optimizer = torch.optim.RMSprop(self.net.parameters(), lr=self.lr)\n\n def compute_return(self, reward, state, action, termination):\n # Computes the Sarsa(0) return. It assumes reward, action, and termination are all a single number.\n with torch.no_grad():\n av_function = self.net.forward(state)[action]\n next_step_bool = (1 - int(termination))\n sarsa_zero_return = reward + next_step_bool * self.gamma * av_function\n return sarsa_zero_return\n\n def choose_action(self, state):\n p = np.random.rand()\n if p > self.epsilon:\n with torch.no_grad():\n optim_action = self.net.forward(state).argmax().numpy()\n return np.int64(optim_action)\n else:\n return np.random.randint(self.num_actions)\n\n def save_summary(self):\n if not self.store_summary:\n return\n self.summary['cumulative_loss_per_episode'].append(self.cumulative_loss)\n self.cumulative_loss = 0\n\n\nclass VanillaNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Vanilla neural network with the option of selecting gate functions and applying l1 or l2 regularization to all the\n parameters of the network.\n \"\"\"\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n gates str relu-relu types of gates for the network\n reg_factor float 0.1 factor for the regularization method\n reg_method string 'none' regularization method. Choices: 'none', 'l1', 'l2'\n \"\"\"\n self.gates = check_attribute_else_default(config, 'gates', 'relu-relu')\n super(VanillaNeuralNetwork, self).__init__(config, gates=self.gates, summary=summary)\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', 0.1)\n self.reg_method = check_attribute_else_default(config, 'reg_method', 'none',\n choices=['none', 'l1', 'l2'])\n if self.reg_method == 'l1':\n self.reg_function = torch.abs\n elif self.reg_method == 'l2':\n self.reg_function = lambda z: torch.pow(z, 2)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # Performs an update to the parameters of the nn. It assumes action, reward, next_action, and termination are\n # a single number / boolean\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n loss = (self.net(state)[action] - sarsa_zero_return) ** 2\n reg_loss = 0\n if self.reg_method != 'none':\n for name, param in self.net.named_parameters():\n reg_loss += torch.sum(self.reg_function(param))\n loss += self.reg_factor * reg_loss\n loss.backward()\n self.optimizer.step()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n\nclass RegPerLayerNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Neural network with regularization and the option of setting different regularization factors for\n the parameters of each layer\n \"\"\"\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n reg_factor tuple (0.1, 0.1, 0.1) factor for the regularization method per layer\n reg_method string 'none' regularization method. Choices: 'none', 'l1', 'l2'\n \"\"\"\n super(RegPerLayerNeuralNetwork, self).__init__(config, gates='relu-relu', summary=summary)\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', (0.1, 0.1, 0.1))\n self.reg_method = check_attribute_else_default(config, 'reg_method', 'l1',\n choices=['l1', 'l2'])\n if self.reg_method == 'l1':\n self.reg_function = torch.abs\n else:\n self.reg_function = lambda z: torch.pow(z, 2)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # Performs an update to the parameters of the nn. It assumes action, reward, next_action, and termination are\n # a single number / boolean.\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n loss = (self.net(state)[action] - sarsa_zero_return) ** 2\n reg_loss = 0\n for name, param in self.net.named_parameters():\n if '1' in name: # parameters of the first layer\n factor = self.reg_factor[0]\n elif '2' in name: # parameters of the second layer\n factor = self.reg_factor[1]\n else: # parameters of the output layer\n factor = self.reg_factor[2]\n reg_loss += factor * torch.sum(self.reg_function(param))\n loss += reg_loss\n loss.backward()\n self.optimizer.step()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n\nclass DistRegNeuralNetwork(NeuralNetworkFunctionApproximation):\n \"\"\"\n Neural network with distributional regularizers. This is the implementation of the ReLu + SKL network from:\n \"The Utility of Sparse Representations for Control in Reinforcement Learning\"\n - Vincent Liu, Raksha Kumaraswamy, Lei Le, and Martha White\n \"\"\"\n def __init__(self, config, summary=None):\n super(DistRegNeuralNetwork, self).__init__(config, gates='relu-relu', summary=summary)\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n reg_factor float 0.1 \n beta float 0.1 average max activation\n ma_alpha float 0.1 decay rate parameter for the moving average\n use_gamma bool False whether to use a gamma distribution instead of beta\n \"\"\"\n self.reg_factor = check_attribute_else_default(config, 'reg_factor', 0.1)\n self.beta = check_attribute_else_default(config, 'beta', 0.1)\n self.ma_alpha = check_attribute_else_default(config, 'ma_alpha', 0.1)\n self.use_gamma = check_attribute_else_default(config, 'use_gamma', False)\n self.moving_average_layer1 = torch.zeros(self.h1_dims, dtype=torch.float32, requires_grad=False)\n self.moving_average_layer2 = torch.zeros(self.h2_dims, dtype=torch.float32, requires_grad=False)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n # this function assumes action, reward, next_action, and termination are a single number / boolean.\n sarsa_zero_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n x1, x2, x3 = self.net.forward(state, return_activations=True)\n loss = (x3[action] - sarsa_zero_return) ** 2\n if self.use_gamma:\n layer1_average = x1.mean()\n layer2_average = x2.mean()\n kld_layer1 = self.kld(layer1_average)\n kld_layer2 = self.kld(layer2_average)\n loss += self.reg_factor * (kld_layer1 + kld_layer2)\n loss.backward()\n self.optimizer.step()\n else:\n layer1_moving_average = (1 - self.ma_alpha) * self.moving_average_layer1 + self.ma_alpha * x1\n layer2_moving_average = (1 - self.ma_alpha) * self.moving_average_layer2 + self.ma_alpha * x2\n kld_layer1 = self.kld(layer1_moving_average)\n kld_layer2 = self.kld(layer2_moving_average)\n loss += self.reg_factor * (kld_layer1 + kld_layer2)\n loss.backward()\n self.optimizer.step()\n self.moving_average_layer1 = (1 - self.ma_alpha) * self.moving_average_layer1 + self.ma_alpha * x1.detach()\n self.moving_average_layer2 = (1 - self.ma_alpha) * self.moving_average_layer2 + self.ma_alpha * x2.detach()\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n\n def kld_derivative(self, beta_hats):\n # Note: you can use either kld_derivative or kld. Both results in the same gradient.\n positive_beta_hats = beta_hats[beta_hats > self.beta]\n first_term = 1 / positive_beta_hats\n second_term = torch.pow(first_term, 2) * self.beta\n kld_derivative = torch.sum((first_term - second_term))\n return kld_derivative\n\n def kld(self, beta_hats):\n positive_beta_hats = beta_hats[beta_hats > self.beta]\n # the original kl divergence is: log(beta_hat) + (beta / beta_hat) - log(beta) - 1\n # however, since beta doesn't depend on the parameters of the network, omitting the term -log(beta) - 1 doesn't\n # have any effect on the gradient.\n return torch.sum(torch.log(positive_beta_hats) + (self.beta / positive_beta_hats))\n\n\nclass ReplayBufferNeuralNetwork(NeuralNetworkFunctionApproximation):\n\n def __init__(self, config, summary=None):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n gates str relu-relu types of gates for the network\n batch_size int 32 minibatch size\n training_step_count int 0 number of training steps so far\n tnet_update_freq int 10 the update frequency of the target network\n \"\"\"\n assert isinstance(config, Config)\n self.config = config\n self.gates = check_attribute_else_default(self.config, 'gates', 'relu-relu')\n super(ReplayBufferNeuralNetwork, self).__init__(config, self.gates, summary)\n self.batch_size = check_attribute_else_default(config, 'batch_size', 32)\n self.training_step_count = check_attribute_else_default(config, 'training_step_count', 0)\n self.tnet_update_freq = check_attribute_else_default(config, 'tnet_update_freq', 10)\n self.replay_buffer = ReplayBuffer(config)\n self.target_net = TwoLayerFullyConnected(self.state_dims, h1_dims=self.h1_dims, h2_dims=self.h2_dims,\n output_dims=self.num_actions, gates=self.gates)\n self.target_net.apply(weight_init)\n\n def update(self, state, action, reward, next_state, next_action, termination):\n self.replay_buffer.store_transition(transition=(state, action, reward, next_state, next_action, termination))\n\n if self.replay_buffer.length < self.batch_size:\n return\n\n self.training_step_count += 1\n state, action, reward, next_state, next_action, termination = self.replay_buffer.sample(self.batch_size)\n qlearning_return = self.compute_return(reward, next_state, next_action, termination)\n self.optimizer.zero_grad()\n prediction = torch.squeeze(self.net(state).gather(1, torch.from_numpy(action).view(-1,1)))\n loss = (prediction - qlearning_return).pow(2).mean()\n loss.backward()\n self.optimizer.step()\n\n if self.store_summary:\n self.cumulative_loss += loss.detach().numpy()\n if (self.training_step_count % self.tnet_update_freq) == 0:\n self.target_net.load_state_dict(self.net.state_dict())\n\n def compute_return(self, reward, state, action, termination):\n with torch.no_grad():\n # av_function = torch.squeeze(self.target_net.forward(state).gather(1, torch.from_numpy(action).view(-1,1)))\n av_function = torch.max(self.target_net.forward(state), dim=1)[0]\n next_step_bool = torch.from_numpy((1 - np.int64(termination))).float()\n sarsa_zero_return = torch.from_numpy(reward).float() + next_step_bool * self.gamma * av_function\n return sarsa_zero_return\n\n\nclass ReplayBuffer:\n\n def __init__(self, config):\n \"\"\"\n Parameters in config:\n Name: Type: Default: Description: (Omitted when self-explanatory)\n state_dims int 2 number of dimensions of the environment's state\n buffer_size int 100 size of the buffer\n \"\"\"\n self.state_dims = check_attribute_else_default(config, 'state_dims', 2)\n self.buffer_size = check_attribute_else_default(config, 'buffer_size', 100)\n\n \"\"\" inner state \"\"\"\n self.start = 0\n self.length = 0\n\n self.state = np.empty((self.buffer_size, self.state_dims), dtype=np.float64)\n self.action = np.empty(self.buffer_size, dtype=int)\n self.reward = np.empty(self.buffer_size, dtype=np.float64)\n self.next_state = np.empty((self.buffer_size, self.state_dims), dtype=np.float64)\n self.next_action = np.empty(self.buffer_size, dtype=int)\n self.termination = np.empty(self.buffer_size, dtype=bool)\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n if idx < 0 or idx >= self.length:\n raise KeyError()\n elif isinstance(idx, np.ndarray):\n if (idx < 0).any() or (idx >= self.length).any():\n raise KeyError()\n shifted_idx = self.start + idx\n s = self.state.take(shifted_idx, axis=0, mode='wrap')\n a = self.action.take(shifted_idx, axis=0, mode='wrap')\n r = self.reward.take(shifted_idx, axis=0, mode='wrap')\n next_s = self.next_state.take(shifted_idx, axis=0, mode='wrap')\n next_a = self.next_action.take(shifted_idx, axis=0, mode='wrap')\n terminate = self.termination.take(shifted_idx, axis=0, mode='wrap')\n return s, a, r, next_s, next_a, terminate\n\n def store_transition(self, transition):\n if self.length < self.buffer_size:\n self.length += 1\n elif self.length == self.buffer_size:\n self.start = (self.start + 1) % self.buffer_size\n else:\n raise RuntimeError()\n\n storing_idx = (self.start + self.length - 1) % self.buffer_size\n state, action, reward, next_state, next_action, termination = transition\n self.state[storing_idx] = state\n self.action[storing_idx] = action\n self.reward[storing_idx] = reward\n self.next_state[storing_idx] = next_state\n self.next_action[storing_idx] = next_action\n self.termination[storing_idx] = termination\n\n def sample(self, sample_size):\n if sample_size > self.length or sample_size > self.buffer_size:\n raise ValueError(\"The sample size is to large.\")\n sampled_idx = np.random.randint(0, self.length, sample_size)\n return self.__getitem__(sampled_idx)\n","repo_name":"JFernando4/Online_SparseRepresentations","sub_path":"Experiment_Engine/function_approximators.py","file_name":"function_approximators.py","file_ext":"py","file_size_in_byte":17971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38246945837","text":"import datetime\nimport calendar\nimport json\n\n# File contains functions that are used within my other main functions\n\n\ndef week():\n week_data = {\n \"Monday\": 0,\n \"Tuesday\": 0,\n \"Wednesday\": 0,\n \"Thursday\": 0,\n \"Friday\": 0,\n \"Saturday\": 0,\n \"Sunday\": 0,\n }\n return week_data\n\n\ndef get_day():\n \"\"\"\n Function returns current day of the week, zero-indexed\n 0-6\n \"\"\"\n # Get current date and time.\n now = datetime.datetime.now()\n\n # Use datetime now, in calendar.weekday func to get day as 0 index.\n day_of_week = calendar.weekday(now.year, now.month, now.day)\n print(day_of_week)\n return int(day_of_week)\n\n\ndef write_data(week_number, data):\n \"\"\"\n Function will write data to specified week number\n \"\"\"\n with open(f\"user_details/weigh_in/week_{week_number}.json\", \"w\") as file:\n json.dump(data, file, indent=4)\n\n\n# Will open file replace this in other areas later\ndef open_week(week_number):\n \"\"\"\n Function will open specified week number\n \"\"\"\n with open(f\"user_details/weigh_in/week_{week_number}.json\") as file:\n data = json.load(file)\n return data\n","repo_name":"0xlvl3/oh-my-workout","sub_path":"files/utility_funcs.py","file_name":"utility_funcs.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"17988639143","text":"from django.db import models\n\nfrom datetime import datetime as date\n\n# Create your models here.\n\n\nclass Patient(models.Model):\n first_name = models.CharField(default=\"\",max_length=20);\n last_name = models.CharField(default=\"\",max_length=20);\n doctor = models.PositiveIntegerField(default=-1);\n gender = models.CharField(default=\"Male\",max_length=60);\n date_of_birth = models.CharField(default=str(date.now()), max_length= 10);\n chart_id = models.IntegerField(default=-1);\n id = models.IntegerField(max_length=12,primary_key=True);\n\n\n# python manage.py makemigrations\n# python manage.py migrate\n\nclass User(models.Model):\n user_name = models.CharField(max_length=20);\n access_token = models.CharField(max_length=100);","repo_name":"mohanmb91/DrChronoBirthDayApp","sub_path":"drchrono/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"25386768686","text":"# Aylon Ben Dvora class 8a\nprint (\"Aylon Ben Dvora\")\n\n\n# ex1\nprint (\"ex1 \\nwith elif\")\n\n# ask the user for an input of a year variable\nyear_elif = int(input(\"Please enter a year: \"))\n\n# if the year is a leap year the system prints that it is a leap year\nif (year_elif % 4 == 0 and year_elif % 100 != 0):\n print (f\"{year_elif} is a leap year\")\nelif (year_elif % 400 == 0):\n print (f\"{year_elif} is a leap year\")\n\n# if not the system prints it dose not a leap year\nelse:\n print (f\"{year_elif} isn't a leap year\")\n\nprint (\"ex1 \\nwithout elif\")\n\n# ask the user for an input of a year variable\nyear_noElif = int(input(\"Please enter a year: \"))\n\n# if the year is a leap year the system prints that it is a leap year\nif ((year_noElif % 4 == 0 and year_noElif % 100 != 0) or (year_noElif % 400 == 0)):\n print (f\"{year_noElif} is a leap year\")\n\n# if not the system prints it dose not a leap year\nelse:\n print (f\"{year_noElif} isn't a leap year\")\n\n\n\"\"\"\nused inputs ex1 (both)\n1900\n2000\n2100\n2016\n1998\n3456\n2333\n\"\"\"\n# ex2\nprint (\"ex2\")\n# ask the user for his age\nage = int(input(\"Please enter your year of birth: \"))\nage = 2020 - age\n# if his age is below 120 and grader then 18 the system prints out that he can vote for the kneset\n# and if his age is below 120 and below 18 the the system prints out how much more years he need to wait before he can vote\nif age >= 120:\n print (\"Your age is above 120 ?!?!?!\")\nelif age >= 18:\n print (f\"Your age is {age} , Oh your age is above 18 you can vote for the kneset\")\nelse:\n print (f\"Your age is {age}, unfortunately You need\", (age-18)*(-1),\"more years to vote for the kneset\")\n\"\"\"\nused inputs ex2\n1900\n1990\n2007\n1996\n\"\"\"\n\n# ex3\n\n# ask the user for the number of times he want to go to the pool this year\nentryNum = int(input(\"Please enter the number of time you want to go to the pool this year: \"))\n\n# the system prints out what subscription is better for the user\nif (200 + 45 * entryNum) < (400 + 30 * entryNum):\n print (\"The best subscription for you is The first subscription\")\nelse:\n print (\"The best subscription for you is The second subscription\")\n\n\"\"\"\nused inputs ex3\n1\n13\n14\n18\n19\n6\n11\n\"\"\"\n# ex4\nprint (\"ex4\")\nname = \"\"\nNumStudentGradeAbove95 = 0\n# starting a loop\nwhile name != \"FINISH\":\n # asking the user for a name input\n name = input(\"Please enter a name: \")\n if name != \"FINISH\": # if name is not FINISH the system asks for a grade input\n grade = int(input(\"Please enter the grade: \"))\n print (f\"the name is {name} and the grade is {grade}\") # system prints out the name and the grade\n if grade >= 95:\n NumStudentGradeAbove95 = NumStudentGradeAbove95 + 1\nprint (NumStudentGradeAbove95, \"students grade is above 95\") # system prints out the number of students that their grade is above 95 \n\"\"\"\nused inputs ex4\na - 12\nb - 95\nc - 90\nd - 100\nh - 98\nFINISH\n\na - 95 \nb - 85\nc - 90\nd - 99\nh - 100\n\"\"\"\n# ex5\nprint (\"ex5\")\nfactOfNum = 1\n# system asks for a number to do for him factorial\nnumForFact = int(input(\"Please enter a number that u want to calculate factorial for: \"))\n# in the loop system is calculating the factorial\nwhile numForFact != 0:\n factOfNum = numForFact * factOfNum\n numForFact = numForFact - 1\nprint(factOfNum) # system prints the factorial for the number\n\"\"\"\nused inputs ex5\n0\n4\n6\n12\n5\n16\n\"\"\"\n#ex6\nprint(\"ex6\")\n# setting def vars\nPNum = 1\nNumOfNum = 0\ntotalNum = 0\n# while the numbers are positive whe loop goes on\nwhile PNum > 0:\n PNum = float(input(\"Please enter a number: \"))\n # if the number is a positive number its adding him into the total and 1 to the count of nums\n if PNum > 0:\n NumOfNum = NumOfNum + 1\n totalNum = totalNum + PNum\n# calculating and printing the average and the number of nums inputted\nprint (f\"The number of numbers you entered are {NumOfNum} and the average of the numbers is\",totalNum/NumOfNum)\n\"\"\"\nused inputs ex6\n1\n4\n6\n-2\n\n1\n5\n7\n2\n56\n8\n0\n\"\"\"","repo_name":"ABDtheking/School","sub_path":"ex3_Aylon.BenDvora.py","file_name":"ex3_Aylon.BenDvora.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"22807717828","text":"#!/usr/bin/env python3\n\n\"\"\"\n restructure.py reorganizes files from an XQD card into an organized package. To be expanded\n to handle other card formats and to handle multiple cards in one package.\n Last Revised: 2023-04-26\n\"\"\"\n\nimport subprocess\nimport sys\nimport os\nimport shutil \n\n# drag in your package\n\ntry:\n rawpackage = sys.argv[1]\nexcept IndexError:\n print(f'usage: restructurerawfootage.py [package]')\n\n# create a camera logs metadata directory\n\ncamera_log_path_xdroot = os.path.join(rawpackage, \"metadata/logs/camera/XDROOT\")\n\ncamera_log_path_clip = os.path.join(rawpackage, \"metadata/logs/camera/XDROOT/Clip\")\n\n\nif not os.path.exists(camera_log_path_clip):\n os.makedirs(camera_log_path_clip)\n print(f'creating a folder called {camera_log_path_clip}')\nelse:\n print(f'{camera_log_path_clip} already exists')\n\n# Move camera logs into a metadata/logs/camera folder\n\nfor root, dirs, files in os.walk(rawpackage, topdown=False):\n\n for name in files:\n file_name = os.path.join(root, name)\n\n searchstring_cueup = 'CUEUP.XML'\n searchstring_discmeta = 'DISCMETA.XML'\n searchstring_mediapro = 'MEDIAPRO.XML'\n\n if searchstring_cueup in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n \n if searchstring_discmeta in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n \n if searchstring_mediapro in file_name:\n try:\n shutil.move(file_name, camera_log_path_xdroot)\n except shutil.Error:\n continue\n\n if file_name.endswith('.BIM'):\n try:\n shutil.move(file_name, camera_log_path_clip)\n except shutil.Error:\n continue\n \n searchstring_clip = 'Clip' \n\n if searchstring_clip in file_name:\n if file_name.endswith('.XML'):\n try:\n shutil.move(file_name, camera_log_path_clip)\n except shutil.Error:\n continue\n\n\n# create an objects directory if there isn't one. \n\nobjectspath = os.path.join(rawpackage, \"objects\")\n\nif not os.path.exists(objectspath):\n os.mkdir(objectspath)\n\n# move XDROOT folder if it is not in objects directory already\n\nxdroot_path = os.path.join(rawpackage, \"XDROOT\")\n\nif os.path.exists(objectspath) and os.path.exists(xdroot_path):\n shutil.move(xdroot_path, objectspath)\nelse:\n print(f'XDROOT folder was already in an objects folder. No need to move it')\n\n# Delete empty folders\n\nfor root, dirs, files in os.walk(rawpackage, topdown=False):\n\n for empty in dirs:\n if len(os.listdir(os.path.join(root, empty))) == 0:\n os.rmdir(os.path.join(root, empty))\n else:\n print(f'{(os.path.join(root,empty))} is not empty. These will not be removed')\n\n\n","repo_name":"cunytv/imm","sub_path":"restructurerawfootage.py","file_name":"restructurerawfootage.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21055408700","text":"import requests\nimport pandas as pd\nfrom time import sleep, time\n\nYEAR = 2022\n\nclass Scraper:\n def __init__(self):\n self.last_updated = int(time())\n\n self.df = pd.DataFrame()\n self.update_df()\n\n def start(self):\n print(\"Scraper started\")\n while True:\n sleep(1)\n self.update_df()\n\n def save_df(self):\n timestamp = int(time())\n self.df.to_csv(f\"times_{YEAR}.csv\")\n self.df.to_csv(f\"backup/times_{YEAR}_{timestamp}.csv\")\n print(f\"Saved df to csv on {timestamp}\")\n\n def fetch_data(self):\n # response = requests.get(f\"http://data.24urenloop.be/scores-{YEAR}.json\")\n try:\n response = requests.get(f\"http://127.0.0.1:8000/scores-{YEAR}.json\")\n except:\n print(\"Failed to connect\")\n return {'time': int(time())}\n\n if response.text:\n return response.json()\n else:\n return {'time': int(time())}\n\n def update_df(self):\n data = self.fetch_data()\n\n if data is None or'teams' not in data:\n return\n\n if data['time'] >= self.last_updated:\n self.last_updated = data['time']\n new_row = {team['name']:team['laps'] for team in data['teams']}\n new_row[\"time\"] = data['time']\n new_df = pd.DataFrame.from_records([new_row], index='time')\n self.df = pd.concat([self.df, new_df])\n\n if data['time'] % 60 == 0:\n self.save_df()\n\nif __name__ == '__main__':\n scraper = Scraper()\n scraper.start()\n\n\n","repo_name":"hiasr/24ul-analytics","sub_path":"scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"45113910496","text":"input_data = input()\n\nrow = int(input_data[1])\ncolumn = int(ord(input_data[0]))-int(ord('a')) + 1 \n#ord함수로 행의 값(문자)을 아스키코드값으로 변환하고 'a'의 아스키코드값을 뺀 값에 1을 더하면 인덱스값이 된다\n# 예) 'a'의 아스키코드 값은 97이므로 행값을'a'로 넣으면 97 - 97 + 1 = 1 이 된다. \n\n#ord(char)함수는 문자를 아스키코드값으로 변환시켜주는 함수이다\n#ord함수의 반대 함수는 chr(int)함수이다\n\ntypes = [(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1)]\n#types = [[-2,-1],[-1,-2],[1,-2],[2,-1],[2,1],[1,2],[-1,2],[-2,1]]\n\n#[]리스트, ()는 튜플이다\n#사용법은 거의 동일하지만 차이점은 튜플에서는 추가, 수정, 삭제가 불가능하다\n#즉, types같이 거의 변하지않는 상수같은 값을 정의할 때 사용한다\n#또한 반복문에서 리스트보다 빠르며, 보안(무결성)에 좋다 \n#추가로 {}는 딕셔너리인데 안에 항목의 순서는 정의가 되어있지않고 키:값으로 구성된다\n#딕셔너리에 append함수같은 순서랑 관련 된 함수를 사용하면 오류난다\n\ncount = 0\n\nfor type in types:\n v_row = row + type[0]\n v_column = column + type[1]\n\n if v_row < 1 or v_row > 8 or v_column < 1 or v_column > 8:\n continue\n count+=1\n\nprint(count)","repo_name":"nsy5687/codingteststudy.github.io","sub_path":"구현/왕실의 나이트.py","file_name":"왕실의 나이트.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12235861717","text":"#!/usr/bin/env python3\nnumbers = []\ntotal = 0\n\ndef get_mediana(value):\n x = 0\n mediana = int(value/2)\n while value > 0:\n if x == 0:\n x = 1\n elif x == 1:\n x = 0\n value -= 1\n if x == 1:\n mediana = numbers [mediana]\n if x == 0:\n x = numbers [mediana]\n y = numbers [mediana - 1]\n mediana = (x+y)/2\n return mediana\nwhile True:\n answer = input (\"Введите число или нажмите Enter для подсчета:\")\n if not answer:\n break\n try:\n number = int(answer)\n except ValueError as err:\n print(\"Неправильный ввод, пожалуйста введите целое число\")\n continue\n total += number\n numbers.append (number) \nhighest = numbers[0]\nfor highestcount in numbers:\n if highestcount > highest:\n highest = highestcount\n \nlowest = numbers[0]\nfor lowestcount in numbers:\n if lowestcount < lowest:\n lowest = lowestcount\ncount = total//len(numbers)\nprint (numbers)\nprint (\"Всего цифр:\", len(numbers))\nprint (\"Всего цифр:\", len(numbers),\"Наименьшее число:\", lowest,\"Наибольшее число:\", highest,\"Среднее значение:\", count, 'Медиана:', get_mediana(len(numbers)))","repo_name":"antikuz/Learning-and-Puzzles","sub_path":"python3_sammerfield_introduction/average2.py","file_name":"average2.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30705872557","text":"import datetime\nfrom datetime import datetime\ntry:\n date = input(\"please enter the date DD-MM-YY :\")\n date_obj = datetime.strptime(date, '%d-%m-%Y')\n print(date_obj.strftime('%A'))\n print(date_obj.strftime('%A %B %Y'))\n \nexcept ValueError:\n print(\"Invalid date.\")\n\n#########################################################\n\nimport pandas as pd\ntry:\n date = input(\"please enter the date DD-MM-YY :\")\n df = pd.Timestamp(date)\n print(df.dayofweek, df.day_name())\nexcept ValueError:\n print(\"Invalid date.\")\n######################################################\n\nfrom datetime import datetime\nweekDays = (\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\",\"Sunday\")\nwhile True:\n try:\n date1 = datetime.strptime(input('Please enter a date in \"Month/Day/Year\" format: '),'%m/%d/%Y')\n except:\n print('Your input is not a valid date')\n else:\n print(f\"{date1.date()} is {weekDays[date1.weekday()]}\")\n\n###################################################################\n\nimport datetime\ndef is_date_valid():\n try:\n date = input(\"Please enter a valid date (DD-MM-YYYY): \")\n conv_date = datetime.datetime.strptime( date, \"%d-%m-%Y\" )\n print(conv_date)\n except Exception as e:\n print ('Exception type is:', e.__class__.__name__)\n # print_exc()\n return print(\"Invalid Entry\")\n else:\n return print(conv_date.strftime(\"%A\"))\n\n\n\n","repo_name":"akkocah/Python","sub_path":"Pyhton Addict/30-weekofday.py","file_name":"30-weekofday.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"38163276166","text":"from django.template import Context, loader\nfrom django.shortcuts import render_to_response\nimport discogs_client as discogs\n\n# Create your views here.\ndef home(request):\n\tdiscogs.user_agent = 'TimeLP/0.1'\n\tcollection = discogs.User('neutralino1').collection(sort='year', order='desc')#, per_page=40)\n\tyears = []\n\tfor y in range(collection[0].year, collection[-1].year, -1):\n\t\tyears.append({'year': y, 'releases': [r for r in collection if r.year == y]})\n\treturn render_to_response('home.html', {'years':years})","repo_name":"neutralino1/TimeLP","sub_path":"timelp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"8449850725","text":"#!/usr/bin/python3\n\n\"\"\"\nSourceMod installer / updater script with cross-platform support and no external Python\ndependencies.\n\nThis requires Python 3.8+, as it uses the dirs_exist_ok kwarg in shutil.copytree() and\nf-strings.\n\"\"\"\n\nimport urllib.request\nimport tempfile\nimport shutil\nimport os\nimport pathlib\nimport contextlib\nimport sys\nimport functools\n\nLICENSE_PROMPT = \"\"\"\\\nSourceMod is licensed under GPLv3. For more information, see https://www.sourcemod.net/license.php\nYou must acknolwedge and comply with the license agreement to install and use SourceMod.\nProceed with installation?\"\"\"\n\n@contextlib.contextmanager\ndef deferred_file_remove(file, *args, **kwargs):\n\t\"\"\" Opens a file for access, deleting it once the context is closed. \"\"\"\n\tf = open(file, *args, **kwargs)\n\ttry:\n\t\tyield f\n\tfinally:\n\t\tf.close()\n\t\tos.remove(file)\n\n@functools.lru_cache()\ndef get_version_from_branch(branch):\n\t\"\"\"\n\tA really dumb scraping mechanism to identify the version associated with a branch.\n\tValid branches include 'stable' and 'dev' (alias of 'master').\n\t\n\tI'd prefer to not have to use this, but SourceMod hasn't implemented the functionality in\n\ttheir redirect script.\n\t\"\"\"\n\timport urllib.request\n\timport html.parser\n\t\n\tclass LinkExtractor(html.parser.HTMLParser):\n\t\tdef __init__(self):\n\t\t\tsuper(LinkExtractor, self).__init__()\n\t\t\tself.refs = set()\n\t\t\n\t\tdef handle_starttag(self, tag, attrs):\n\t\t\tif tag != 'a':\n\t\t\t\treturn\n\t\t\tfor name, value in attrs:\n\t\t\t\tif name == 'href':\n\t\t\t\t\tself.refs.add(value)\n\t\n\tparser = LinkExtractor()\n\tr = urllib.request.Request(\n\t\turl = f'https://www.sourcemod.net/downloads.php?branch={branch}',\n\t\theaders = { \"User-Agent\": \"SourceMod Update Utility\" }\n\t)\n\twith urllib.request.urlopen(r) as data:\n\t\tpage = data.read().decode(data.headers.get_content_charset())\n\t\tparser.feed(page)\n\t\n\t# find some downloadable file and return its directory name\n\tfor ref in filter(lambda l: '.zip' in l, parser.refs):\n\t\tpath = pathlib.PurePosixPath(ref)\n\t\treturn path.parent.name\n\treturn None\n\ndef confirm(*args, **kwargs):\n\t\"\"\"\n\tUtility function that prompts the user with a confirmation.\n\t\n\tReturns True / False if the user provided any input, None if not an interactive terminal or\n\tif the input is invalid.\n\t\n\tContains a 'default' kwarg that can be set to True to allow by default.\n\t\"\"\"\n\timport distutils.util\n\timport itertools\n\t\n\tif sys.stdin.isatty() and sys.stdout.isatty():\n\t\tconfirmation = '[Y/n]' if kwargs.pop(\"default\", False) else '[y/N]'\n\t\tprompt = ' '.join(itertools.chain(args, [ confirmation, '' ]))\n\t\ttry:\n\t\t\treturn distutils.util.strtobool(input(prompt))\n\t\texcept ValueError:\n\t\t\tpass\n\treturn None\n\ndef main():\n\timport platform\n\timport argparse\n\timport pydoc\n\t\n\tparser = argparse.ArgumentParser(description = \"Installs or upgrades SourceMod.\")\n\t\n\tparser.add_argument(\"directory\", help = \"the server's game directory\",\n\t\t\ttype = pathlib.Path)\n\t\n\t# autodetects platform (assumes this works correctly for windows / linux / mac)\n\tparser.add_argument(\"--platform\", help = \"the server's operating system\",\n\t\t\tdefault = platform.system())\n\t\n\tparser.add_argument(\"--version\", help = \"the SourceMod version to install\",\n\t\t\tdefault = \"1.10\")\n\tparser.add_argument(\"--branch\", help = \"the SourceMod branch to install (resolves version)\")\n\t\n\tparser.add_argument(\"--url\", help = \"a URL to a SourceMod package to install \"\n\t\t\t\"(ignores version / os / branch)\")\n\t\n\tparser.add_argument(\"--archive\", help = \"an existing package to install; \"\n\t\t\t\"either compressed file or directory \"\n\t\t\t\"(ignores version / os / branch / url)\", type = pathlib.Path)\n\t\n\tparser.add_argument(\"--no-upgrade-plugins\", help = \"plugins will not be copied from \"\n\t\t\t\"upgrade package (ignored if first time installing)\", action = \"store_true\")\n\t\n\targs = parser.parse_args()\n\t\n\tparams = {\n\t\t'version': args.version,\n\t\t'os': args.platform.lower()\n\t}\n\t\n\tif args.branch:\n\t\tresolved_version = get_version_from_branch(args.branch)\n\t\tif resolved_version:\n\t\t\tparams['version'] = resolved_version\n\t\t\tprint(f\"Resolved branch name {args.branch} to version {resolved_version}\")\n\t\telse:\n\t\t\traise ValueError(f\"Failed to resolve branch name {args.branch}\")\n\t\n\tr = urllib.request.Request(\n\t\turl = f'https://sourcemod.net/latest.php?{urllib.parse.urlencode(params)}',\n\t\theaders = { \"User-Agent\": \"SourceMod Update Utility\"}\n\t)\n\t\n\tif args.url:\n\t\tr.full_url = args.url\n\t\n\ttempname = None\n\tpackage = None\n\t\n\tif args.archive and args.archive.exists():\n\t\tif args.archive.is_file():\n\t\t\t# use local archive\n\t\t\twith tempfile.NamedTemporaryFile(delete = False, suffix = ''.join(args.archive.suffixes)) as local,\\\n\t\t\t\t\topen(args.archive, mode = 'rb') as remote:\n\t\t\t\tshutil.copyfileobj(remote, local)\n\t\t\t\ttempname = local.name\n\t\telif args.archive.is_dir():\n\t\t\t# use unpacked archive\n\t\t\tpackage = args.archive\n\telse:\n\t\t# download file from internet\n\t\twith urllib.request.urlopen(r) as remote:\n\t\t\tpkg = pathlib.Path(urllib.parse.urlsplit(remote.geturl()).path.split('/')[-1])\n\t\t\tprint('Downloading SourceMod package', pkg)\n\t\t\twith tempfile.NamedTemporaryFile(delete = False, suffix = ''.join(pkg.suffixes)) as local:\n\t\t\t\tshutil.copyfileobj(remote, local)\n\t\t\t\ttempname = local.name\n\t\n\twith contextlib.ExitStack() as es:\n\t\tif tempname:\n\t\t\tarchive_file = es.enter_context(deferred_file_remove(tempname, 'rb'))\n\t\t\tpackage = es.enter_context(tempfile.TemporaryDirectory())\n\t\t\tshutil.unpack_archive(archive_file.name, package)\n\t\t\n\t\tif not package:\n\t\t\tprint(\"No archive file specified\")\n\t\t\tsys.exit(1)\n\t\t\n\t\tpath_sm = pathlib.Path('addons', 'sourcemod')\n\t\t\n\t\tif not (args.directory / path_sm).exists():\n\t\t\t# first install, make sure that user acknowledges license\n\t\t\tprint(\"Performing full install of SourceMod.\")\n\t\t\twith open(package / path_sm / 'LICENSE.txt', 'rt') as license:\n\t\t\t\tpydoc.pager(license.read())\n\t\t\tprint()\n\t\t\tresult = confirm(LICENSE_PROMPT)\n\t\t\t\n\t\t\tif result:\n\t\t\t\tshutil.copytree(package, args.directory, dirs_exist_ok = True)\n\t\t\t\tprint(\"Installation complete.\");\n\t\t\t\tsys.exit(0)\n\t\t\telse:\n\t\t\t\tprint(\"Installation cancelled.\")\n\t\t\t\tsys.exit(1)\n\t\t\n\t\t# replace the contents of `bin/` and `configs/geoip/`\n\t\tfor d in { ('bin',), ('configs', 'geoip') }:\n\t\t\tsd = path_sm / pathlib.Path(*d)\n\t\t\tif (args.directory / sd).exists():\n\t\t\t\tshutil.rmtree(args.directory / sd)\n\t\t\tif (package / sd).exists():\n\t\t\t\tshutil.copytree(package / sd, args.directory / sd, dirs_exist_ok = False)\n\t\t\n\t\t# update the contents of `configs/sql-init-scripts/`, `extensions/`, `scripting/`,\n\t\t# `translations` without touching other existing files\n\t\tfor d in { ('configs', 'sql-init-scripts'), ('extensions',), ('scripting',), ('translations',) }:\n\t\t\tsd = path_sm / pathlib.Path(*d)\n\t\t\tif (package / sd).exists():\n\t\t\t\tshutil.copytree(package / sd, args.directory / sd, dirs_exist_ok = True)\n\t\t\n\t\tif args.no_upgrade_plugins:\n\t\t\tprint(\"Skipping install of plugins.\")\n\t\telse:\n\t\t\t# map installed plugin filenames to paths; copy unknown files to disabled\n\t\t\ttarget_plugin_dir = args.directory / path_sm / 'plugins'\n\t\t\tinstalled_plugins = { f.name: f.parent for f in target_plugin_dir.rglob(\"*.smx\") }\n\t\t\tfor plugin in (package / path_sm / 'plugins').rglob(\"*.smx\"):\n\t\t\t\ttarget = installed_plugins.get(plugin.name, target_plugin_dir / 'disabled')\n\t\t\t\tshutil.copyfile(plugin, target / plugin.name)\n\t\t\t\t\n\t\t\t\tprint(plugin.name, 'copied to', target.relative_to(args.directory / path_sm))\n\t\tprint(\"Upgrade complete.\")\n\nif __name__ == \"__main__\":\n\tmain()\n","repo_name":"nosoop/py-sourcemod-installer","sub_path":"sourcemod_installer/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":7370,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"70718844004","text":"#!/usr/bin/python3\n\nimport subprocess, argparse, shlex, re\nfrom time import sleep\nfrom misc_functions import print_then_exit\n\nrun_options = ['put','get','exist']\n\ndef run_tests(behaviour, args):\n try:\n print(f'Running bobp -b {str(behaviour)} {args.rstrip()}')\n p = subprocess.check_output(shlex.split(f'./bobp -b {behaviour} {args.rstrip()}')).decode('ascii')\n print(str(p))\n if behaviour in {'put', 'get'}:\n if not 'total err: 0' in str(p):\n print_then_exit(f'{behaviour} test failed, see output')\n elif behaviour == 'exist':\n found_exist = re.search(r'\\b[0-9]{1,}\\sof\\s[0-9]{1,}\\b', str(p))\n if not found_exist:\n print_then_exit(f\"No {behaviour} output captured, check output\")\n exists = found_exist.group(0).split(' of ')\n if exists[0] != exists[1]:\n print_then_exit(f\"{exists[0]} of {exists[1]} keys, {behaviour} test failed, see output\")\n else:\n print(f\"{exists[0]} of {exists[1]} keys\")\n else:\n print_then_exit('Unknown behaviour.') \n except subprocess.CalledProcessError as e:\n print_then_exit(str(e.stderr))\n except Exception as e:\n print_then_exit(str(e))\n\ndef make_args(raw_args):\n args_str = ''\n for key in raw_args:\n if raw_args.get(key) != None:\n args_str += f'{key} {raw_args.get(key)} '\n return args_str\n\ndef run_doubled_exist_test(run_args, expected_exist_keys):\n try:\n run_args['-c'] = expected_exist_keys * 2 + 1\n run_args['-s'] = 5001\n run_args['-t'] = 1\n args = make_args(run_args)\n print(f'Running bobp -b exist {args.rstrip()}')\n p = subprocess.check_output(shlex.split(f'./bobp -b exist {args.rstrip()}')).decode('ascii')\n print(str(p))\n found_exist = re.search(r'\\b[0-9]{1,}\\sof\\s[0-9]{1,}\\b', str(p))\n if not found_exist:\n print_then_exit(f\"No exist output captured, check output\")\n exists = found_exist.group(0).split(' of ')\n if int(exists[0]) != expected_exist_keys:\n print_then_exit(f\"{exists[0]} of {exists[1]} keys, expected {expected_exist_keys} of {exists[1]} instead, exist test failed, see output\")\n else:\n print(f\"{exists[0]} of {exists[1]} keys\")\n except subprocess.CalledProcessError as e:\n print_then_exit(str(e.stderr))\n except Exception as e:\n print_then_exit(str(e))\n\ndef get_run_args(mode, args, run_conf):\n return {'-c':args.count, '-l':args.payload, '-h':f'{args.node}', '-f':args.first, '-t':args.threads, '--mode':args.mode, '-k':args.keysize, '-p':run_conf.get(mode), \n '--user':args.user, '--password':args.password}\n\nparser = argparse.ArgumentParser(description='This script launches bob tests with given configuration.')\nparser.add_argument('-c', dest='count', type=int, help='amount of entries to process', required=True)\nparser.add_argument('-l', dest='payload', type=int, help='payload in bytes', required=True)\nparser.add_argument('-n', dest='node', type=str, help='target node address', required=True)\nparser.add_argument('-f', dest='first', type=int, help='first index', default=0)\nparser.add_argument('-t', dest='threads', type=int, help='amount of working threads', default=1)\nparser.add_argument('--mode', dest='mode', type=str, help='random or normal', choices=['random', 'normal'], default='normal')\nparser.add_argument('-k', dest='keysize', type=int, help='size of binary key (8 or 16)', choices=[8, 16], default=8)\nparser.add_argument('-nodes_amount', dest='nodes_amount', type=int, required=True, help='Amount of bob nodes.')\nparser.add_argument('-transport_min_port', dest='transport_min_port', type=int, required=True, help='Port of the first bob container.')\nparser.add_argument('--user', dest='user', type=str, help='Username for bob basic authentification')\nparser.add_argument('--password', dest='password', type=str, help='Password for bob basic authentification')\n\nparsed_args = parser.parse_args()\n\ntest_run_config = dict()\niter = 0\ntry:\n for item in run_options:\n test_run_config[item]=str(parsed_args.transport_min_port + (iter % int(parsed_args.nodes_amount))) #used in get_run_args()\n iter += 1\nexcept ValueError:\n print_then_exit('Args had unexpected values.')\n\n#run put/get/exist tests\nfor item in run_options:\n args_str = str()\n run_args = get_run_args(item, parsed_args, test_run_config)\n args_str = make_args(run_args)\n run_tests(item, args_str)\n\n#run doubled range exist\nrun_args = get_run_args(item, parsed_args, test_run_config)\nrun_doubled_exist_test(run_args, parsed_args.count)","repo_name":"qoollo/bob","sub_path":"integration-tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"}
+{"seq_id":"5807956167","text":"import threading;\n\nfrom .dxConfig import dxConfig;\nfrom .fDumpPythonFrame import fDumpPythonFrame;\n\noOutputLock = threading.RLock();\n\ndef fDumpTraceback(oTraceback, sPrefix = \"\", bExpand = True):\n oOutputLock.acquire();\n try:\n uIndex = 0;\n if bExpand:\n print(\"--[ Traceback ]\".ljust(80, \"-\"));\n while oTraceback:\n uIndex += 1;\n if oTraceback.tb_frame:\n print(\"%sTB#%d %s @ %s%s%d\" % (\n sPrefix, uIndex,\n oTraceback.tb_frame.f_code.co_name,\n oTraceback.tb_frame.f_code.co_filename,\n dxConfig[\"sLineNumberAfterPathPrefix\"],\n oTraceback.tb_lineno\n ));\n fDumpPythonFrame(oTraceback.tb_frame, sPrefix = sPrefix + \" \", bExpand = bExpand);\n else:\n print(\"%sTB#%d ???/%d\" % (sPrefix, oTraceback.tb_lineno));\n if not bExpand:\n return;\n oTraceback = oTraceback.tb_next;\n print(\"-\" * 80);\n finally:\n oOutputLock.release();","repo_name":"SkyLined/mDebugOutput","sub_path":"fDumpTraceback.py","file_name":"fDumpTraceback.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"37104701896","text":"class InformationCategorize:\n def __init__(self,txt):\n self.txt = txt\n self.judul_start = 1\n self.judul_end = 0\n self.nama = 0\n self.nim = 0\n self.keyword_end = len(txt)-1\n self.keyword_start = 0\n self.isi_start = 0\n self.isi_end = 0\n\n if self.judul_start >= len(txt):\n self.judul_start = 0\n self.keyword_end = 0\n else:\n self.process_information()\n\n\n def process_information(self):\n max_line = 5\n ln = []\n len_of_char = []\n i = self.judul_start+1\n for i in range(self.judul_start+1,len(self.txt)):\n split = self.txt[i]\n if \"oleh\" in split[0].lower() or \"by\" in split[0].lower():\n break\n\n #check the colon\n if len(split) == 2:\n if len(split[1]) == 1:\n break\n\n ln.append(i)\n len_of_char.append(len(\"\".join(split)))\n if i-self.judul_start > max_line:\n #most minimal\n i = ln[len_of_char.index(min(len_of_char))]\n break\n self.judul_end = i\n self.nama = self.judul_end+1\n self.nim = self.nama+1\n\n #keyword\n self.keyword_start = self.keyword_end\n if \"kata kunci\" not in \" \".join(self.txt[self.keyword_end]).lower() and \"keyword\" not in \" \".join(self.txt[self.keyword_end]).lower():\n if len(\"\".join(self.txt[self.keyword_end])) < len(\"\".join(self.txt[self.keyword_end-1])):\n self.keyword_start = self.keyword_end-1\n\n #isi\n self.isi_start = self.nim+1\n self.isi_end = self.keyword_start-1\n\n\n\n def get_all(self):\n return {\"judul_start\":self.judul_start,\"judul_end\":self.judul_end,\"nama\":self.nama,\"nim\":self.nim,\"isi_start\":self.isi_start,\"isi_end\":self.isi_end,\"keyword_start\":self.keyword_start,\"keyword_end\":self.keyword_end}\n","repo_name":"fajryhamzah/SVM-Skripsi-Abstract-Character-Recognition","sub_path":"SVM/information_categorize.py","file_name":"information_categorize.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39658969881","text":"# 녹화 파일 (lmp)에서 log 데이터를 뽑아줌\n\nimport os\nimport json\nimport numpy as np\nimport vizdoom as vzd\nimport matplotlib as plt\nimport matplotlib.pyplot as plt\n\nfrom time import *\nfrom time import sleep\nfrom datetime import datetime, timedelta\nfrom agent.banlencedAgent import *\nfrom agent.RunnerAgent import *\nfrom agent.HiderAgent import *\nfrom log.vizdoom_log_util import *\n\nRECORD_FILE_NAME = \"agent-aimer-1.lmp\"\nLOG_FILE_NAME = \"log.json\"\n\nheads = ['time', 'timestamp', 'ATTACK', 'SPEED', 'STRAFE', 'MOVE_RIGHT', 'MOVE_LEFT', 'MOVE_BACKWARD', 'MOVE_FORWARD', 'TURN_RIGHT', 'TURN_LEFT', 'USE', 'SELECT_WEAPON1', 'SELECT_WEAPON2', 'SELECT_WEAPON3', 'SELECT_WEAPON4', 'SELECT_WEAPON5', 'SELECT_WEAPON6', 'SELECT_NEXT_WEAPON', 'SELECT_PREV_WEAPON', 'LOOK_UP_DOWN_DELTA', 'TURN_LEFT_RIGHT_DELTA', 'MOVE_LEFT_RIGHT_DELTA', 'KILLCOUNT', 'HEALTH', 'ARMOR', 'SELECTED_WEAPON', 'SELECTED_WEAPON_AMMO']\nlog_data = []\n\nif __name__ == '__main__':\n game = vzd.DoomGame()\n\n # New render settings for replay\n game.set_screen_resolution(vzd.ScreenResolution.RES_800X600)\n game.set_render_hud(True)\n\n game.set_mode(vzd.Mode.SPECTATOR)\n game.load_config(os.path.join('../../../scenarios', \"deathmatch.cfg\"))\n game.set_screen_resolution(vzd.ScreenResolution.RES_640X480)\n game.set_window_visible(True)\n game.set_objects_info_enabled(True)\n game.set_sectors_info_enabled(True)\n game.set_labels_buffer_enabled(True)\n game.init()\n # Replays episodes stored in given file. Sending game command will interrupt playback.\n game.replay_episode(RECORD_FILE_NAME)\n\n t = 0\n while not game.is_episode_finished():\n game.advance_action()\n\n state = game.get_state()\n now_time = str(datetime.utcnow() + timedelta(hours=9))\n elp_time = time()-t\n\n last_action = game.get_last_action()\n variables = state.game_variables\n var = np.concatenate(([now_time], [elp_time], last_action, variables), axis=0)\n basic = {}\n for j, name in enumerate(heads):\n basic[name] = var[j]\n\n state_data = get_state_log(state)\n state_data[\"basic\"] = basic\n log_data.append(state_data)\n\n\n log_data = json.dumps(log_data)\n with open(LOG_FILE_NAME, \"w\") as f:\n f.write(log_data)\n\n game.close()\n","repo_name":"hoonisone/ViZDoom-Rule-Based-Player","sub_path":"examples/python/mh_test/extract_log_from_record.py","file_name":"extract_log_from_record.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"26100229316","text":"from pyforms.basewidget import BaseWidget\nfrom pyforms.controls import ControlFile\nfrom pyforms.controls import ControlText\nfrom pyforms.controls import ControlSlider\nfrom pyforms.controls import ControlPlayer\nfrom pyforms.controls import ControlButton\n\nclass ComputerVisionAlgorithm(BaseWidget):\n\n def __init__(self, *args, **kwargs):\n super().__init__('Computer vision algorithm example')\n\n #Definition of the forms fields\n self._videofile = ControlFile('Video')\n self._outputfile = ControlText('Results output file')\n self._threshold = ControlSlider('Threshold', default=114, minimum=0, maximum=255)\n self._blobsize = ControlSlider('Minimum blob size', default=110, minimum=100, maximum=2000)\n self._player = ControlPlayer('Player')\n self._runbutton = ControlButton('Run')\n\n #Define the function that will be called when a file is selected\n self._videofile.changed_event = self.__video_file_selection_event\n #Define the event that will be called when the run button is processed\n self._runbutton.value = self.run_event\n #Define the event called before showing the image in the player\n self._player.process_frame_event = self.__process_frame\n\n #Define the organization of the Form Controls\n self._formset = [\n ('_videofile', '_outputfile'),\n '_threshold',\n ('_blobsize', '_runbutton'),\n '_player'\n ]\n\n\n def __video_file_selection_event(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self._player.value = self._videofile.value\n\n def __process_frame(self, frame):\n \"\"\"\n Do some processing to the frame and return the result frame\n \"\"\"\n return frame\n\n def run_event(self):\n \"\"\"\n After setting the best parameters run the full algorithm\n \"\"\"\n print(\"The function was executed\", self._videofile.value)\n\n\nif __name__ == '__main__':\n\n from pyforms import start_app\n start_app(ComputerVisionAlgorithm)","repo_name":"UmSenhorQualquer/pyforms","sub_path":"example/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":609,"dataset":"github-code","pt":"52"}
+{"seq_id":"17087368179","text":"import torch\nfrom torch.utils.data import TensorDataset\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom train_parameters import *\nfrom src.normalization import Normalization\nfrom src.voigt_rotation import *\nfrom src.model_utils import CPU_Unpickler\n \ndef exportTensor(name,data,cols, header=True):\n df=pd.DataFrame.from_records(data.detach().numpy())\n if(header):\n df.columns = cols\n print(name)\n df.to_csv(name+\".csv\", header=header, index=False)\n\ndef exportList(name,data):\n arr=np.array(data)\n np.savetxt(name+\".csv\", [arr], delimiter=',')\n\ndef getNormalization(save_normalization=False):\n \n data = pd.read_csv(dataPath)\n # check for NaNs \n assert not data.isnull().values.any()\n \n F1_features = torch.tensor(data[F1_features_names].values)\n R2 = torch.tensor(data[R2_names].values)\n V = torch.tensor(data[V_names].values)\n C_ort = torch.tensor(data[C_ort_names].values)\n C = torch.tensor(data[C_names].values)\n\n a,b,c = torch.split(R2,[1,1,1],dim=1)\n R2_transposed = torch.cat((-a,b,c),dim=1)\n unrotatedlabelTensor = direct_rotate(C,R2_transposed)\n\n F1_features_scaling = Normalization(F1_features,F1_features_types,F1_features_scaling_strategy)\n V_scaling = Normalization(V,V_types,V_scaling_strategy)\n C_ort_scaling = Normalization(C_ort, C_ort_types,C_ort_scaling_strategy)\n C_scaling = Normalization(C,C_types,C_scaling_strategy)\n C_hat_scaling = Normalization(unrotatedlabelTensor,C_types,C_hat_scaling_strategy)\n\n # should only be activated if framework is retrained with different dataset\n if save_normalization:\n with open('src/normalization/F1_features_scaling.pickle', 'wb') as file_:\n pickle.dump(F1_features_scaling, file_, -1)\n with open('src/normalization/V_scaling.pickle', 'wb') as file_:\n pickle.dump(V_scaling, file_, -1)\n with open('src/normalization/C_ort_scaling.pickle', 'wb') as file_:\n pickle.dump(C_ort_scaling, file_, -1)\n with open('src/normalization/C_scaling.pickle', 'wb') as file_:\n pickle.dump(C_scaling, file_, -1)\n with open('src/normalization/C_hat_scaling.pickle', 'wb') as file_:\n pickle.dump(C_hat_scaling, file_, -1)\n return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling\n\ndef getSavedNormalization():\n \n F1_features_scaling = CPU_Unpickler(open(\"src/normalization/F1_features_scaling.pickle\", \"rb\", -1)).load()\n V_scaling = CPU_Unpickler(open(\"src/normalization/V_scaling.pickle\", \"rb\", -1)).load()\n C_ort_scaling = CPU_Unpickler(open(\"src/normalization/C_ort_scaling.pickle\", \"rb\", -1)).load()\n C_scaling = CPU_Unpickler(open(\"src/normalization/C_scaling.pickle\", \"rb\", -1)).load()\n C_hat_scaling = CPU_Unpickler(open(\"src/normalization/C_hat_scaling.pickle\", \"rb\", -1)).load()\n return F1_features_scaling, C_ort_scaling, C_scaling, V_scaling, C_hat_scaling\n\ndef getDataset(F1_features_scaling, V_scaling, C_ort_scaling, C_scaling):\n \n data = pd.read_csv(dataPath)\n \n print('Data: ',data.shape) \n # check for NaNs \n assert not data.isnull().values.any()\n \n F1_features = torch.tensor(data[F1_features_names].values)\n R1 = torch.tensor(data[R1_names].values)\n R2 = torch.tensor(data[R2_names].values)\n V = torch.tensor(data[V_names].values)\n C_ort = torch.tensor(data[C_ort_names].values)\n C = torch.tensor(data[C_names].values)\n\n F1_features = F1_features_scaling.normalize(F1_features)\n V = V_scaling.normalize(V)\n C_ort = C_ort_scaling.normalize(C_ort)\n C = C_scaling.normalize(C)\n \n dataset = TensorDataset(F1_features.float(), R1.float(), V.float(), R2.float(), C_ort.float(), C.float())\n l1 = round(len(dataset)*traintest_split)\n l2 = len(dataset) - l1\n print('train/test: ',[l1,l2],'\\n\\n')\n train_set, test_set = torch.utils.data.random_split(dataset, [l1,l2], generator=torch.Generator().manual_seed(42))\n return train_set, test_set\n\ndef getDataset_pred(C_scaling,E,dataPath_pred):\n \n data = pd.read_csv(dataPath_pred)\n \n print('Data: ',data.shape) \n # check for NaNs \n assert not data.isnull().values.any()\n \n C = torch.tensor(data[C_names].values)\n # normalize stiffness by Young's modulus of base material\n C = torch.div(C,E)\n C = C_scaling.normalize(C)\n dataset = C.float()\n return dataset","repo_name":"jhbastek/InvertibleTrussDesign","sub_path":"src/loadDataset.py","file_name":"loadDataset.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"}
+{"seq_id":"14344426380","text":"#http://effbot.org/tkinterbook/tkinter-classes.htm\nfrom tkinter import *\nimport logging, time\nfrom serial import Serial\nfrom common import get_logger_name, get_flash_id, read_vbatt\nfrom common import serial_port_best_guess, save_default_port\nfrom dev.set_rtc import set_rtc, read_rtc\n\n\nprint('Detected ports:')\nDEFAULT_PORT = serial_port_best_guess(prompt=True)\nprint('- - -')\nPORT = input('PORT=? (default={})'.format(DEFAULT_PORT)).strip()\n# empty input, use default\nif '' == PORT:\n PORT = DEFAULT_PORT\nprint(PORT)\n\nwith Serial(PORT, 115200, timeout=1) as ser:\n save_default_port(PORT)\n\n\nclass App:\n def __init__(self, master):\n \n row1 = Frame(master)\n row1.pack()\n\n row_status = Frame(master)\n row_status.pack()\n\n row_sensors = Frame(master)\n row_sensors.pack()\n \n row_memory = Frame(master)\n row_memory.pack()\n\n row_led = Frame(master)\n row_led.pack()\n\n row_config = Frame(master)\n row_config.pack()\n\n row_logging = Frame(master)\n row_logging.pack()\n\n self.label1 = StringVar()\n self.label = Label(row1, textvariable=self.label1)\n self.label.pack(side=LEFT)\n\n self.get_name = Button(row_status, text='GET NAME', command=self.get_name)\n self.get_name.pack(side=LEFT)\n\n self.get_id = Button(row_status, text='GET ID', command=self.get_id)\n self.get_id.pack(side=LEFT)\n\n self.get_vbatt = Button(row_status, text='READ BATTERY VOLTAGE', command=self.get_vbatt)\n self.get_vbatt.pack(side=LEFT)\n\n self.read_temperature = Button(row_sensors, text='READ TEMPERATURE', command=self.read_temperature)\n self.read_temperature.pack(side=LEFT)\n\n self.read_pressure = Button(row_sensors, text='READ PRESSURE', command=self.read_pressure)\n self.read_pressure.pack(side=LEFT)\n\n self.read_ambient_lx = Button(row_sensors, text='READ AMBIENT', command=self.read_ambient_lx)\n self.read_ambient_lx.pack(side=LEFT)\n\n self.read_memory = Button(row_memory, text='EXTRACT DATA', command=self.read_memory)\n self.read_memory.pack(side=LEFT)\n\n self.clear_memory = Button(row_memory, text='CLEAR MEMORY', command=self.clear_memory)\n self.clear_memory.pack(side=LEFT)\n\n self.red_led_on = Button(row_led, text='RED ON', fg='red', command=self.red_led_on)\n self.red_led_on.pack(side=LEFT)\n\n self.red_led_off = Button(row_led, text='RED OFF', command=self.red_led_off)\n self.red_led_off.pack(side=LEFT)\n\n self.green_led_on = Button(row_led, text='GREEN ON', fg='green', command=self.green_led_on)\n self.green_led_on.pack(side=LEFT)\n\n self.green_led_off = Button(row_led, text='GREEN OFF', command=self.green_led_off)\n self.green_led_off.pack(side=LEFT)\n\n self.blue_led_on = Button(row_led, text='BLUE ON', fg='blue', command=self.blue_led_on)\n self.blue_led_on.pack(side=LEFT)\n\n self.blue_led_off = Button(row_led, text='BLUE OFF', command=self.blue_led_off)\n self.blue_led_off.pack(side=LEFT)\n\n\n self.v = IntVar()\n self.v.set(2)\n self.radio1 = Radiobutton(row_config, text='0.2 second', variable=self.v, value=0)\n self.radio1.pack(anchor=W)\n self.radio2 = Radiobutton(row_config, text='1 second', variable=self.v, value=1)\n self.radio2.pack(anchor=W)\n self.radio3 = Radiobutton(row_config, text='60 second', variable=self.v, value=2)\n self.radio3.pack(anchor=W)\n\n self.set_logging_interval = Button(row_config, text='SET SAMPLING INTERVAL', command=self.set_logging_interval)\n self.set_logging_interval.pack(side=LEFT)\n \n self.set_clock = Button(row_logging, text='SET CLOCK', command=self.set_clock)\n self.set_clock.pack(side=LEFT)\n\n self.start_logging = Button(row_logging, text='START Logging', command=self.start_logging)\n self.start_logging.pack(side=LEFT)\n\n self.stop_logging = Button(row_logging, text='STOP Logging', command=self.stop_logging)\n self.stop_logging.pack(side=LEFT)\n\n #self.button = Button(row_status, text='QUIT', fg='red', command=row.quit)\n #self.button.pack(side=LEFT)\n\n #self.text = Text(row_logging)\n #self.text.pack(side=LEFT)\n\n def get_name(self):\n logging.debug('get_name')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(get_logger_name(ser))\n\n def get_id(self):\n logging.debug('get_id')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(get_flash_id(ser))\n \n def read_memory(self):\n logging.debug('read_memory')\n\n def clear_memory(self):\n logging.debug('clear_memory')\n\n def start_logging(self):\n logging.debug('start_logging')\n\n def stop_logging(self):\n logging.debug('stop_logging')\n\n def set_logging_interval(self):\n print(self.v.get())\n\n def get_vbatt(self):\n logging.debug('get_vbatt')\n with Serial(PORT, 115200, timeout=1) as ser:\n self.label1.set(str(read_vbatt(ser)) + 'V')\n\n def read_temperature(self):\n logging.debug('read_temperature')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_temperature')\n self.label1.set(ser.readline().decode().strip())\n\n def read_pressure(self):\n logging.debug('read_pressure')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_pressure')\n self.label1.set(ser.readline().decode().strip())\n\n def read_ambient_lx(self):\n logging.debug('read_ambient_lx')\n with Serial(PORT, 115200, timeout=1) as ser:\n ser.write(b'read_ambient_lx')\n r = ser.readline().decode().strip().split(',')[0]\n self.label1.set(r)\n\n def set_clock(self):\n logging.debug('set_rtc')\n with Serial(PORT, 115200, timeout=1) as ser:\n set_rtc(ser, time.time())\n self.label1.set(read_rtc(ser))\n\n def red_led_on(self):\n logging.debug('red_led_on')\n Serial(PORT, 115200, timeout=1).write(b'red_led_on')\n\n def red_led_off(self):\n logging.debug('red_led_off')\n Serial(PORT, 115200, timeout=1).write(b'red_led_off')\n\n def green_led_on(self):\n logging.debug('green_led_on')\n Serial(PORT, 115200, timeout=1).write(b'green_led_on')\n\n def green_led_off(self):\n logging.debug('green_led_off')\n Serial(PORT, 115200, timeout=1).write(b'green_led_off')\n\n def blue_led_on(self):\n logging.debug('blue_led_on')\n Serial(PORT, 115200, timeout=1).write(b'blue_led_on')\n\n def blue_led_off(self):\n logging.debug('blue_led_off')\n Serial(PORT, 115200, timeout=1).write(b'blue_led_off')\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\nroot = Tk()\n\napp = App(root)\n\nroot.mainloop()\n#root.destroy()\n\n\n\n\n","repo_name":"danshyles/plsworkshop","sub_path":"mesh-lab/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1812490920","text":"import time\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException, NoSuchElementException\n\nfrom utils.helpers import (\n log_error,\n log_run_begin,\n log_run_end,\n create_driver,\n examine_current_job_list,\n normalize_career_site_url,\n parse_url_for_uuid,\n)\n\nfrom utils.queries import (\n get_company_by_ats,\n insert_job,\n update_inactive_jobs,\n)\n\nfrom utils.models import Job\n\n\n# TODO: add tests, prints -> logging\n\n\nATS_TO_SCRAPE = \"Ashby\"\nATS_BASE_URL = \"https://jobs.ashbyhq.com\"\n\n\ndef get_job_details(job: Job) -> Job | None:\n driver = create_driver()\n try:\n driver.get(job.url)\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, \".ashby-job-posting-left-pane\")\n )\n )\n details = driver.find_elements(\n By.CSS_SELECTOR, \".ashby-job-posting-left-pane > div\"\n )\n for detail in details:\n if detail.find_element(By.CSS_SELECTOR, \"h2\").text == \"Location\":\n job.location = detail.find_element(By.CSS_SELECTOR, \"p\").text\n if job.location.lower() == \"remote\":\n job.remote = True\n if detail.find_element(By.CSS_SELECTOR, \"h2\").text == \"Compensation\":\n job.salary = detail.find_element(By.CSS_SELECTOR, \"ul > li > span\").text\n job.description = driver.find_element(By.ID, \"overview\").text\n except TimeoutException:\n log_error(scrape_run_id, f\"Timed out on {job.url}\")\n except NoSuchElementException as error:\n log_error(scrape_run_id, error)\n driver.close()\n return job\n\n\ndef get_current_job_list(career_site_url: str) -> list[Job]:\n job_list = []\n driver = create_driver()\n try:\n driver.get(career_site_url)\n WebDriverWait(driver, 10).until(\n EC.presence_of_element_located(\n (By.CSS_SELECTOR, \".ashby-job-posting-brief-list\")\n )\n )\n postings = driver.find_elements(\n By.CSS_SELECTOR, \".ashby-job-posting-brief-list > a\"\n )\n for posting in postings:\n try:\n job = Job()\n job.title = posting.find_element(By.CSS_SELECTOR, \"h3\").text\n job.url = posting.get_attribute(\"href\")\n job.id = parse_url_for_uuid(job.url, career_site_url)\n job_list.append(job)\n except ValueError as error:\n log_error(scrape_run_id, error)\n except TimeoutException:\n log_error(scrape_run_id, f\"Timed out on {career_site_url}\")\n except NoSuchElementException as error:\n log_error(scrape_run_id, error)\n driver.close()\n return job_list\n\n\ndef scrape_jobs() -> None:\n company_queryset = get_company_by_ats(ATS_TO_SCRAPE)\n for result in company_queryset:\n time.sleep(1)\n career_site_url = normalize_career_site_url(result[2])\n print(f\"{scrape_run_id} | {result[1]} | {career_site_url}\")\n current_job_list = get_current_job_list(career_site_url)\n if current_job_list:\n ids_to_add, ids_to_deactivate = examine_current_job_list(\n current_job_list, result[0]\n )\n if ids_to_add:\n print(f\"{len(ids_to_add)} jobs found to add\")\n for job in current_job_list:\n if job.id in list(ids_to_add):\n time.sleep(5)\n job = get_job_details(job)\n job.company_id = result[0]\n job.active = True\n job.new = True\n job.scrape_run_id = scrape_run_id\n insert_job(job)\n else:\n print(f\"No new jobs found for {career_site_url}\")\n if ids_to_deactivate:\n print(f\"{len(ids_to_deactivate)} jobs found to deactivate\")\n update_inactive_jobs(list(ids_to_deactivate), scrape_run_id)\n else:\n print(f\"No jobs found for {career_site_url}\")\n return\n\n\nif __name__ == \"__main__\":\n scrape_run_id, run_time = log_run_begin(ATS_TO_SCRAPE)\n scrape_jobs()\n log_run_end(scrape_run_id, ATS_TO_SCRAPE)\n","repo_name":"calicojackdev/Bonhomme-Richard","sub_path":"src/scrapers/ashby.py","file_name":"ashby.py","file_ext":"py","file_size_in_byte":4390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"86749743797","text":"def test(nums):\n global_sum = current_max = nums[0]\n for num in nums:\n current_max = max(num, current_max + num)\n global_sum = max(current_max, global_sum)\n return global_sum\n\n# Kadane's Algorithm\n# The idea is to calculate the previous best subarray and determining if the best subarray previous is better\n# Than the current local number if it is then that is the best sub array if not, then the best subarray will\n# Start from the local number and then (the following)\n\n# [-2, 1, 3]\n# [-2 ] is the current best (local)\n# 1 (local) vs (-2)current best + (1)local = since local is better than the combined previuos subarray then local becomes best\n# 3 (local) vs (1) current best + (3) local = since current+local is better it becomes the current best\n# Thus resulting in the best sum subarray = 4 = [1,3]\n\ntest([-2, 1])\n","repo_name":"SeanErvinson/leetcode","sub_path":"maximum-subarray/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"43724498596","text":"import numpy\n\nclass thumbnailext:\n\t\"\"\"\n\tthumbnailext description\n\t\"\"\"\n\tdef __init__(self, ownerComp):\n\t\t# The component to which this extension is attached\n\t\tself.ownerComp = ownerComp\n\t\tself.materialThumbCOMP = op('material_thumb')\n\t\tself.materialBgTOP = op('material_thumb/bg')\n\n\t\tself.meshThumbCOMP = op('mesh_thumb')\n\t\tself.meshBgTOP = op('mesh_thumb/bg')\n\n\t\tself.iblThumbTOP = op('ibl_thumb/bg')\n\t\tself.pointThumbTOP = op('pointlight_thumb/bg')\n\t\tself.spotThumbTOP = op('spotlight_thumb/bg')\n\n\t\tself.ThumbnailCOMPS = {\n\t\t\t0:op('mesh_thumb'), # mesh\n\t\t\t1:op('material_thumb'), # material\n\t\t\t2:op('null_thumb'), # null\n\t\t\t10:op('ibl_thumb'), # envlight\n\t\t\t11:op('pointlight_thumb'), # pointlight\n\t\t\t12:op('spotlight_thumb'), # spotlight\n\t\t\t100:op('instance_thumb'), # instance node\n\t\t\t202:op('camera_thumb'), # camera\n\t\t\t220:op('settingsmanager_thumb'), # settingsmanager node\n\t\t\t221:op('lightmanager_thumb'), # lightmanager node\n\t\t}\n\n\tdef Fetch_Outliner_Thumb_Path(self, sourceAssetCOMP):\n\t\tObjtype = sourceAssetCOMP.par.Objtype.eval()\n\t\tObj = self.ThumbnailCOMPS.get(Objtype,None)\n\n\t\tif Obj == None:\n\t\t\tdebug(f'{sourceAssetCOMP} not found in thumbnail creation modules, skipping...')\n\t\t\treturn None\n\t\t\n\t\treturn Obj.op('outliner')\n\n\n\tdef Create_Thumbnail(self, destinationScriptTOP, sourceAssetCOMP, resolution):\n\t\t'''\n\t\tA catch all function for returning a thumbnail of an object who's thumbnail is not dynamic.\n\t\tThe Objtype parameter determins the texture that is returned.\n\t\t'''\n\n\t\tObjtype = sourceAssetCOMP.par.Objtype.eval()\n\t\tObj = self.ThumbnailCOMPS.get(Objtype,None)\n\n\t\tif Obj == None:\n\t\t\tdebug(f'{sourceAssetCOMP} not found in thumbnail creation modules, skipping...')\n\t\t\treturn\n\n\t\tObj.par.Size = resolution\n\t\tObj.par.Comp = sourceAssetCOMP\n\t\tBg = Obj.op('bg')\n\t\tBg.cook(force=True)\n\n\t\timg = Bg.numpyArray(delayed=False, writable=True)\n\n\t\t# numpy image array comes from top as 32 bit always, covnert to 8 to save space.\n\t\timg *= 255\n\t\timg = img.astype(numpy.uint8)\n\t\t# img[0::, 0::, 3] = 255 # set alpha to 1\n\n\t\t# print(destinationScriptTOP)\n\n\t\tdestinationScriptTOP.copyNumpyArray(img)\n\t\tdestinationScriptTOP.cook(force=True)","repo_name":"weareenvoy/TD-Filament","sub_path":"tdfil/code/td-extensions/thumbnailext.py","file_name":"thumbnailext.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"36191984991","text":"from __future__ import print_function\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\ndef cv_2_tensor(img, dtype=np.float32, flagCuda=False):\n if ( 3 == len(img.shape) ):\n t = torch.from_numpy(img.astype(dtype)).permute(2,0,1).unsqueeze(0)\n\n if ( flagCuda ):\n t = t.cuda()\n \n return t\n elif ( 2 == len(img.shape) ):\n t = torch.from_numpy(img.astype(dtype)).unsqueeze(0).unsqueeze(0)\n\n if ( flagCuda ):\n t = t.cuda()\n\n return t\n else:\n raise Exception(\"img.shape must have length 3 or 2. len(img.shape) = {}. \".format(len(img.shape)))","repo_name":"huyaoyu/NewStereo","sub_path":"Components/TorchBridge.py","file_name":"TorchBridge.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"34614240719","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 15 08:21:12 2020\n\n@author: hhshhd\n\"\"\"\n# program to store class records and marks.\n\nlimit = 4\nvalues = [20,6,38,50,40]\nflag = True\nfor counter1 in range(limit-1):\n minimum = counter1\n \n for counter2 in range(counter1+1,limit):\n if values[counter2] < values[minimum]:\n minimum = counter2\n if minimum != counter1:\n temporary = values[minimum]\n values[minimum] = values[counter1]\n values[counter1] = temporary\n\n\nwhile flag == True:\n flag = False\n for counter in range(limit-1):\n if values[counter] > values[counter+1]:\n temporary = values[counter]\n values[counter] = values[counter+1]\n values[counter+1] = temporary\n flag = True\n\nfor i in range(limit):\n print(values[counter])\n\n\n","repo_name":"hhshhd/hhshhd","sub_path":"IB CS/Hw/2020.1.15report/Q15 program to records and marks.py","file_name":"Q15 program to records and marks.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"24467765245","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.io import wavfile\nfrom scipy import signal, fft\nfrom math import sin, pi, ceil\nimport math\n\nimport scipy\n\n\n#from fmStereoBlock import myBandpass, plotAndSavePSD\nfrom PLL.fmPll import fmPll\n\n# use fmDemodArctan and fmPlotPSD\nfrom fmSupportLib import fmDemodArctan, fmPlotPSD\n# for take-home add your functions\n\n# the radio-frequency (RF) sampling rate\n# this sampling rate is either configured on RF hardware\n# or documented when a raw file with IQ samples is provided\nrf_Fs = 2.4e6\n\n# the cutoff frequency to extract the FM channel from raw IQ data\nrf_Fc = 100e3\n\n# the number of taps for the low-pass filter to extract the FM channel\n# this default value for the width of the impulse response should be changed\n# depending on some target objectives, like the width of the transition band\n# and/or the minimum expected attenuation from the pass to the stop band\nrf_taps = 151\n\n# the decimation rate when reducing the front end sampling rate (i.e., RF)\n# to a smaller samping rate at the intermediate frequency (IF) where\n# the demodulated data will be split into the mono/stereo/radio data channels\nrf_decim = 10\n\n# audio sampling rate (we assume audio will be at 48 KSamples/sec)\naudio_Fs = 48e3\n# should be the same ∫as rf_Fs / rf_decim / audio_decim\n\n\n\n\n\nP=[\n [1,0,0,0,0,0,0,0,0,0], #0\n [0,1,0,0,0,0,0,0,0,0], #1\n [0,0,1,0,0,0,0,0,0,0], #2\n [0,0,0,1,0,0,0,0,0,0], #3\n [0,0,0,0,1,0,0,0,0,0], #4\n [0,0,0,0,0,1,0,0,0,0], #5\n [0,0,0,0,0,0,1,0,0,0], #6\n [0,0,0,0,0,0,0,1,0,0], #7\n [0,0,0,0,0,0,0,0,1,0], #8\n [0,0,0,0,0,0,0,0,0,1], #9\n [1,0,1,1,0,1,1,1,0,0], #10\n [0,1,0,1,1,0,1,1,1,0], #11\n [0,0,1,0,1,1,0,1,1,1], #12\n [1,0,1,0,0,0,0,1,1,1], #13\n [1,1,1,0,0,1,1,1,1,1], #14\n [1,1,0,0,0,1,0,0,1,1], #15\n [1,1,0,1,0,1,0,1,0,1], #16\n [1,1,0,1,1,1,0,1,1,0], #17\n [0,1,1,0,1,1,1,0,1,1], #18\n [1,0,0,0,0,0,0,0,0,1], #19\n [1,1,1,1,0,1,1,1,0,0], #20\n [0,1,1,1,1,0,1,1,1,0], #21\n [0,0,1,1,1,1,0,1,1,1], #22\n [1,0,1,0,1,0,0,1,1,1], #23\n [1,1,1,0,0,0,1,1,1,1], #24\n [1,1,0,0,0,1,1,0,1,1] #25\n]\n\n\n\nSyndromes={\n \"A\" :[1,1,1,1,0,1,1,0,0,0],\n \"B\" :[1,1,1,1,0,1,0,1,0,0],\n \"C\" :[1,0,0,1,0,1,1,1,0,0],\n \"C'\":[1,1,1,1,0,0,1,1,0,0],\n \"D\" :[1,0,0,1,0,1,1,0,0,0]\n}\n\n\n\n\ndef firwinImpl(Ntaps, Fc, Fs):\n\th = np.zeros(Ntaps)\n\tnorm_cutoff = 2 * (Fc/Fs)\n\tfor i in range(Ntaps):\n\t\tif (i == (Ntaps-1)/2):\n\t\t\th[i] = (norm_cutoff)\n\t\telse:\n\t\t\th[i] = (norm_cutoff * (sin(pi*norm_cutoff*(i-(Ntaps-1)/2))) /\n\t\t\t (pi*norm_cutoff*(i-(Ntaps-1)/2)))\n\n\t\th[i] = h[i] * (sin((i*pi)/Ntaps) * sin((i*pi)/Ntaps))\n\n\treturn h\n\n\ndef singlePassImpl(audioData, audioCoeff):\n\taudioOut = np.zeros(len(audioCoeff) + len(audioData) - 1)\n\n\tfor n in range(len(audioOut)):\n\t\tfor k in range(len(audioCoeff)):\n\t\t\tif n-k >= 0 and n-k < len(audioData):\n\t\t\t\taudioOut[n] += audioCoeff[k]*audioData[n-k]\n\treturn audioOut\n\n\ndef myBandPassFirwin(freqLow, freqHigh, Fs, tapAmount):\n\n\tfirwin_coeff = signal.firwin(\n\t\ttapAmount, [freqLow/(Fs/2), freqHigh/(Fs/2)], pass_zero=False)\n\t# freqzPlot(firwin_coeff, Fs, 'firwin for ' + str(int(Fc)) + ' Hz cutoff with ' + str(N_taps) + ' taps')\n\treturn firwin_coeff\n\n\ndef plotAndSavePSD(signal, name):\n\n\t# plot PSD of selected block after FM demodulation\n\tax0.clear()\n\tfmPlotPSD(ax0, signal, (rf_Fs/rf_decim)/1e3, subfig_height[0],\n\t\t\t\t'Demodulated FM (block ' + ')' + \" - Python \")\n\t# output binary file name (where samples are written from Python)\n\tfm_demod_fname = \"data/fm_demod\" + \".bin\"\n\t# create binary file where each sample is a 32-bit float\n\tfm_demod = np.asarray(signal, np.float32)\n\tfm_demod.astype('float32').tofile(fm_demod_fname)\n\n\t# save figure to file\n\tfig.savefig(\"data/fmMonoBlock\" + name + \".png\")\n\n\treturn\n\n\ndef logArray(array, arrayName):\n\tfileName = \"logs/\"+arrayName+\".txt\"\n\twith open(fileName, \"w\") as file:\n\t\tfor i in range(len(array)):\n\t\t\tline = \"[\"+str(i)+\"]\"+\": \"+str(array[i])\n\t\t\tfile.write(f\"{line}\\n\")\n\n\ndef myBandpass(fb, fe, fs, Ntaps):\n\n\tnormCenter = ((fe+fb)/2.0)/(fs/2.0)\n\tnormPass = (fe-fb)/(fs/2.0)\n\n\th = [0.0]*Ntaps\n\n\tfor i in range(Ntaps):\n\t\tif (i == ((Ntaps-1.0)/2.0)):\n\t\t\th[i] = normPass\n\n\t\telse:\n\t\t\tneum = normPass * \\\n\t\t\t\tmath.sin(math.pi*(normPass/2.0)*(i-(Ntaps-1.0)/2.0))\n\t\t\tdenom = math.pi*(normPass/2.0)*(i-(Ntaps-1)/2.0)\n\t\t\th[i] = neum/denom\n\t\th[i] = h[i]*math.cos(i*math.pi*normCenter)\n\t\th[i] = h[i]*(math.sin(i*math.pi/Ntaps)**2)\n\n\treturn h\n\n\ndef freqzPlot(coeff, Fs, msg):\n\n\t# find the frequency response using freqz from SciPy:\n\t# https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.freqz.html\n\tw, h = signal.freqz(coeff)\n\n\t# Reminder: np.pi rad/sample is actually the Nyquist frequency\n\tw = w * Fs/(2*np.pi) # needed to draw the frequency on the X axis\n\n\t# plots the magnitude response where the x axis is normalized in rad/sample\n\tfig, ax1 = plt.subplots()\n\tax1.set_title('Digital filter frequency response (' + msg + ')')\n\tax1.plot(w, 20 * np.log10(abs(h)), 'b')\n\tax1.set_ylabel('Amplitude [dB]', color='b')\n\tax1.set_xlabel('Frequency [Hz]')\n\n\ndef conv_resampler_fast(x,h,m,state,du,ds): #du is U ds is N\n #y=np.zeros(int((du*len(x)+len(h))//ds))\n y=np.zeros(int((len(x)*(du/ds))))\n\n for n in range(len(y)):\n #define phase for each value of y we want to calculate\n phase=int(((n*ds)%du))\n #k=phase\n for k in range(phase,len(h)):\n \n \n #concolve x by h\n j= int( ((n*ds-k)/du) )\n\n #convolve\n if(j>=0):\n y[n]+=h[k]*x[j] #Must use J for x here\n else:\n if(m==0):\n y[n] += h[k]*x[0]\n else:\n y[n] += h[k]*state[len(state)+j]\n \n \n k+=du\n\n \n # k+=du #must increment k by this much\n state=x[-(len(h)-1):]\n return y,state\n\ndef conv_downsample_fast(x,h,ds): #The fast way to compute convolution with downsampling\n y=np.zeros((1,len(x)+len(h))/2)\n for n in range(y):\n for k in range(h):\n N=ds*N\n if n-k>=0 and n-k max:\n max_i = i \n max = data[i]\n if data[i] < min:\n min_i = i\n min = data[i]\n if abs(max) > abs(min):\n return max_i\n else:\n return min_i \n\n\n\ndef matchSyndrome(block):\n blocks=[\"A\",\"B\",\"C'\",\"C\", \"D\"]\n for OffsetType in blocks:\n if(block==Syndromes[OffsetType]):\n return OffsetType\n return -1\n\ndef getSyndrome(block):\n matrix_col=[0]*26\n result=[0]*10\n\n for i in range(10):\n for j in range(26):\n matrix_col[j]=P[j][i]\n \n prod = np.array(block,dtype=bool) & np.array(matrix_col,dtype=bool)\n \n for elem in prod:\n result[i]^=elem\n\n #result[i] = '0b1' if prod.count(1) % 2 else '0b0'\n\n return result\n\n\nif __name__ == \"__main__\":\n\n\n in_fname = \"data/AudioIQsamples/iq_samples.raw\"\n\n raw_data = np.fromfile(in_fname, dtype='uint8')\n print(\"Read raw RF data from \\\"\" + in_fname + \"\\\" in unsigned 8-bit format\")\n # IQ data is normalized between -1 and +1 in 32-bit float format\n iq_data = (np.float32(raw_data) - 128.0)/128.0\n print(\"Reformatted raw RF data to 32-bit float format (\" +\n str(iq_data.size * iq_data.itemsize) + \" bytes)\")\n\n # coefficients for the front-end low-pass filter\n rf_coeff = signal.firwin(rf_taps, rf_Fc/(rf_Fs/2), window=('hann'))\n\n # filter to extract the FM channel (I samples are even, Q samples are odd)\n i_filt = signal.lfilter(rf_coeff, 1.0, iq_data[0::2])\n q_filt = signal.lfilter(rf_coeff, 1.0, iq_data[1::2])\n print(\"I/Q Filtered\")\n\n\n # downsample the FM channel\n i_ds = i_filt[::rf_decim]\n q_ds = q_filt[::rf_decim]\n\n fm_demod, dummy = fmDemodArctan(i_ds, q_ds)\n print(\"FM Demodulated\")\n\n\n###################### RF FRONT END DONE #########################\n\n\n##################### STARTING RDS PROCESSING ########################\n\n\n\n Fs = 240000.0 # sampling rate\n Fc = 16000.0 # cutoff frequency\n N_taps = 151 # number of taps for the FIR\n\n\n # FILTER RDS SIGNAL \n rds_coeff = myBandPassFirwin(54e3, 60e3, Fs, N_taps)\n rds_filt = signal.lfilter(rds_coeff, 1.0, fm_demod)\n print(\"Filtered RDS\")\n rds_symbol_rate = 11\n\n\n\n # SQUARE RDS SIGNAL & FILTER TO GENERATE CARRIER\n rds_carrier = rds_filt*rds_filt\n rds_carrier_coeff = myBandPassFirwin(113.5e3, 114.5e3, Fs, N_taps)\n rds_carrier_filt = signal.lfilter(rds_carrier_coeff, 1.0, rds_carrier)\n print(\"Filtered RDS Carrier\")\n\n\n pllOut, _ =fmPll(rds_carrier_filt,114e3,Fs,ncoScale=0.5) # Double check ncoScale\n rds_carrier_i = pllOut[:-1]\n print(\"Pll Done\")\n\n\n # PASS FILTERED RDS THROUGH ALLPASS BEFORE MIXING FOR DELAY\n all_pass_coeff = np.zeros(N_taps)\n all_pass_coeff[(N_taps-1)//2] = 1\n rds_delayed = signal.lfilter(all_pass_coeff, 1.0, rds_filt)\n print(\"Delayed rds_filt\")\n\n\n # MIXING\n rds_mixed_i = 2*rds_delayed*rds_carrier_i\n# rds_mixed_q = 2*rds_delayed*rds_carrier_q # FOR DEBUGGING ONLY\n\n\n\n\n\n # FILTER MIXED VALUE AT 3KHZ\n rds_demod_coeff = signal.firwin(N_taps, 3e3/(Fs/2), window=('hann')) #Low Pass filter 3kHz\n rds_mixed_filt_i = signal.lfilter(rds_demod_coeff, 1.0, rds_mixed_i)\n# rds_mixed_filt_q = signal.lfilter(rds_demod_coeff, 1.0, rds_mixed_q)\n\n\n Up = 209\n Down = 1920\n\n # Relational Resampler\n rds_resampled_i = signal.resample_poly(rds_mixed_filt_i, Up, Down)\n rds_resampled_i *=Up\n\n\n# rds_resampled_q = signal.resample_poly(rds_mixed_filt_q, Up, Down)\n# rds_resampled_q *=Up\n\n \n # RRC FILTERING \n cosine_coeff = impulseResponseRootRaisedCosine(11*2375, N_taps)\n rds_demod_i = signal.lfilter(cosine_coeff, 1.0, rds_resampled_i)\n# rds_demod_q = signal.lfilter(cosine_coeff, 1.0, rds_resampled_q)\n \n plt.plot(range(440),rds_demod_i[:440])\n plt.savefig(\"rds_cosine_i.png\")\n plt.clf()\n\n\n delay = int((N_taps)*Up/Down) + (N_taps-1)//2 \n rds_demod_i = rds_demod_i[delay:]\n# rds_demod_q = rds_demod_q[delay:]\n\n \n\n start_i = findLocalMaxMin(rds_demod_i, 11)\n start_q = findLocalMaxMin(rds_demod_q, 11)\n\n\n #rds_demod_i = rds_demod_i[start_i::11]\n #rds_demod_q = rds_demod_q[start_q::11]\n print(len(rds_demod_i), len(rds_demod_q))\n plt.scatter( rds_demod_i[:1000]/max(rds_demod_i[:1000]) ,rds_demod_q[:1000])\n plt.savefig(\"rds_demod.png\")\n plt.clf()\n\n plt.plot(range(440),rds_demod_i[:440])\n plt.savefig(\"rds_demod_i.png\")\n plt.clf()\n plt.plot(range(440),rds_demod_q[:440])\n plt.savefig(\"rds_demod_q.png\")\n plt.clf()\n \n\ndef decoding(toBeDecoded):\n i=0\n cdr = []\n while(i0 and toBeDecoded[i+1]>0) or (toBeDecoded[i]<0 and toBeDecoded[i+1]<0)):\n #cdr=[]\n #print(f\"clear cdr at i = {i} because of {toBeDecoded[i], toBeDecoded[i+1]}\")\n #i+=1\n #toBeDecoded=toBeDecoded[i+1:]\n #print(f\"remaining input {toBeDecoded}\")\n #i=0\n cdr.append(0)\n i+=2\n continue\n if (i+1 >= len(toBeDecoded)):\n break \n if(toBeDecoded[i]\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: vmware_vm_shell\nshort_description: Execute a process in VM\ndescription:\n - Start a program in a VM without the need for network connection\nversion_added: 2.1\nauthor: \"Ritesh Khadgaray (@ritzk)\"\nnotes:\n - Tested on vSphere 5.5\n - Only the first match against vm_id is used, even if there are multiple matches\nrequirements:\n - \"python >= 2.6\"\n - PyVmomi\noptions:\n datacenter:\n description:\n - The datacenter hosting the VM\n - Will help speed up search\n required: False\n default: None\n cluster:\n description:\n - The cluster hosting the VM\n - Will help speed up search\n required: False\n default: None\n folder:\n description:\n - Destination folder, absolute or relative path to find an existing guest or create the new guest.\n - The folder should include the datacenter. ESX's datacenter is ha-datacenter\n - 'Examples:'\n - ' folder: /ha-datacenter/vm'\n - ' folder: ha-datacenter/vm'\n - ' folder: /datacenter1/vm'\n - ' folder: datacenter1/vm'\n - ' folder: /datacenter1/vm/folder1'\n - ' folder: datacenter1/vm/folder1'\n - ' folder: /folder1/datacenter1/vm'\n - ' folder: folder1/datacenter1/vm'\n - ' folder: /folder1/datacenter1/vm/folder2'\n - ' folder: vm/folder2'\n - ' folder: folder2'\n default: /vm\n version_added: \"2.4\"\n vm_id:\n description:\n - The identification for the VM\n required: True\n vm_id_type:\n description:\n - The identification tag for the VM\n default: vm_name\n choices:\n - 'uuid'\n - 'dns_name'\n - 'inventory_path'\n - 'vm_name'\n required: False\n vm_username:\n description:\n - The user to connect to the VM.\n required: False\n default: None\n vm_password:\n description:\n - The password used to login to the VM.\n required: False\n default: None\n vm_shell:\n description:\n - The absolute path to the program to start. On Linux this is executed via bash.\n required: True\n vm_shell_args:\n description:\n - The argument to the program.\n required: False\n default: None\n vm_shell_env:\n description:\n - Comma separated list of envirnoment variable, specified in the guest OS notation\n required: False\n default: None\n vm_shell_cwd:\n description:\n - The current working directory of the application from which it will be run\n required: False\n default: None\nextends_documentation_fragment: vmware.documentation\n'''\n\nEXAMPLES = '''\n- name: shell execution\n local_action:\n module: vmware_vm_shell\n hostname: myVSphere\n username: myUsername\n password: mySecret\n datacenter: myDatacenter\n folder: /vm\n vm_id: NameOfVM\n vm_username: root\n vm_password: superSecret\n vm_shell: /bin/echo\n vm_shell_args: \" $var >> myFile \"\n vm_shell_env:\n - \"PATH=/bin\"\n - \"VAR=test\"\n vm_shell_cwd: \"/tmp\"\n\n'''\n\ntry:\n from pyVmomi import vim, vmodl\n HAS_PYVMOMI = True\nexcept ImportError:\n HAS_PYVMOMI = False\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.vmware import (connect_to_api, find_cluster_by_name, find_datacenter_by_name,\n find_vm_by_id, vmware_argument_spec)\n\n\n# https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/execute_program_in_vm.py\ndef execute_command(content, vm, vm_username, vm_password, program_path, args=\"\", env=None, cwd=None):\n\n creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)\n cmdspec = vim.vm.guest.ProcessManager.ProgramSpec(arguments=args, envVariables=env, programPath=program_path, workingDirectory=cwd)\n cmdpid = content.guestOperationsManager.processManager.StartProgramInGuest(vm=vm, auth=creds, spec=cmdspec)\n\n return cmdpid\n\n\ndef main():\n argument_spec = vmware_argument_spec()\n argument_spec.update(dict(datacenter=dict(default=None, type='str'),\n cluster=dict(default=None, type='str'),\n folder=dict(type='str', default='/vm'),\n vm_id=dict(required=True, type='str'),\n vm_id_type=dict(default='vm_name', type='str', choices=['inventory_path', 'uuid', 'dns_name', 'vm_name']),\n vm_username=dict(required=False, type='str'),\n vm_password=dict(required=False, type='str', no_log=True),\n vm_shell=dict(required=True, type='str'),\n vm_shell_args=dict(default=\" \", type='str'),\n vm_shell_env=dict(default=None, type='list'),\n vm_shell_cwd=dict(default=None, type='str')))\n\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=False,\n required_if=[['vm_id_type', 'inventory_path', ['folder']]],\n )\n\n if not HAS_PYVMOMI:\n module.fail_json(changed=False, msg='pyvmomi is required for this module')\n\n try:\n p = module.params\n datacenter_name = p['datacenter']\n cluster_name = p['cluster']\n folder = p['folder']\n content = connect_to_api(module)\n\n datacenter = None\n if datacenter_name:\n datacenter = find_datacenter_by_name(content, datacenter_name)\n if not datacenter:\n module.fail_json(changed=False, msg=\"datacenter not found\")\n\n cluster = None\n if cluster_name:\n cluster = find_cluster_by_name(content, cluster_name, datacenter)\n if not cluster:\n module.fail_json(changed=False, msg=\"cluster not found\")\n\n if p['vm_id_type'] == 'inventory_path':\n vm = find_vm_by_id(content, vm_id=p['vm_id'], vm_id_type=\"inventory_path\", folder=folder)\n else:\n vm = find_vm_by_id(content, vm_id=p['vm_id'], vm_id_type=p['vm_id_type'], datacenter=datacenter, cluster=cluster)\n\n if not vm:\n module.fail_json(msg='VM not found')\n\n msg = execute_command(content, vm, p['vm_username'], p['vm_password'],\n p['vm_shell'], p['vm_shell_args'], p['vm_shell_env'], p['vm_shell_cwd'])\n\n module.exit_json(changed=True, uuid=vm.summary.config.uuid, msg=msg)\n except vmodl.RuntimeFault as runtime_fault:\n module.fail_json(changed=False, msg=runtime_fault.msg)\n except vmodl.MethodFault as method_fault:\n module.fail_json(changed=False, msg=method_fault.msg)\n except Exception as e:\n module.fail_json(changed=False, msg=str(e))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhxfei/My-Admin","sub_path":"env/lib/python3.5/site-packages/ansible/modules/cloud/vmware/vmware_vm_shell.py","file_name":"vmware_vm_shell.py","file_ext":"py","file_size_in_byte":7502,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"}
+{"seq_id":"33994418901","text":"\"\"\"This solves problem #35 of Project Euler (https://projecteuler.net).\n\nCircular primes\n\nThe number, 197, is called a circular prime because all rotations of the digits: 197, 971,\nand 719, are themselves prime.\n\nThere are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.\n\nHow many circular primes are there below one million?\n\"\"\"\n\nfrom mathext import prime_number_generator\n\n\ndef find_primes(*, up_to=100):\n primes = []\n for p in prime_number_generator():\n if p >= up_to:\n break\n primes.append(p)\n return primes\n\n\ndef rotations(n):\n result = []\n digits = str(n)\n for _ in range(len(digits)):\n digits = digits[-1] + digits[:-1]\n result.append(int(digits))\n return result\n\n\ndef first_attempt():\n primes = set(find_primes(up_to=1_000_000))\n circular_primes = set()\n for p in primes:\n r = rotations(p)\n if any(map(lambda k: k in circular_primes, r)):\n continue\n if all(map(lambda k: k in primes, r)):\n circular_primes.update(r)\n print(sorted(circular_primes))\n print('Solution =', len(circular_primes))\n\n\ndef run_application():\n import time\n start = time.time()\n first_attempt()\n print('Runtime =', time.time() - start, 'seconds')\n\n\nif __name__ == '__main__':\n run_application()\n\n# last line of code\n","repo_name":"techrabbit58/ProjectEuler","sub_path":"problem_0035.py","file_name":"problem_0035.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"17566199031","text":"import torch\nfrom dataloader import prepare_data\nfrom model import Encoder, Attention, Decoder, Seq2Seq, init_weights\nfrom inferencer import Inferencer\nfrom config import *\n\n\"\"\" load data \"\"\"\ntrain_loader, val_loader, test_loader, m_dh = prepare_data(TRAIN_PATH, VAL_PATH, TEST_PATH, DH_PATH, LOAD_FROM_DUMP, 3) \n\n\"\"\" model setup \"\"\"\nINPUT_DIM, OUTPUT_DIM = len(m_dh.de_vocab), len(m_dh.en_vocab)\n\nenc = Encoder(INPUT_DIM, ENC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, ENC_DROPOUT)\nattn = Attention(ENC_HID_DIM, DEC_HID_DIM, ATTN_DIM)\ndec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, ENC_HID_DIM, DEC_HID_DIM, DEC_DROPOUT, attn)\n\nmodel = Seq2Seq(enc, dec)\n\n\"\"\" load model \"\"\"\nstate_dict = torch.load('ckpts/best.pt')\nmodel.load_state_dict(state_dict['model_state'])\nmodel.eval()\n\nen_infer = Inferencer(m_dh.en_vocab)\n\nsrc, trg = next(iter(test_loader))\n\n\"\"\" ______________ \"\"\"\nimport matplotlib.pyplot as plt\nimport numpy\n\ndef plot_head_map(mma, target_labels, source_labels):\n fig, ax = plt.subplots()\n heatmap = ax.pcolor(mma, cmap=plt.cm.Blues)\n # put the major ticks at the middle of each cell\n ax.set_xticks(numpy.arange(mma.shape[1]) + 0.5, minor=False) # mma.shape[1] = target seq 길이\n ax.set_yticks(numpy.arange(mma.shape[0]) + 0.5, minor=False) # mma.shape[0] = input seq 길이\n \n # without this I get some extra columns rows\n # http://stackoverflow.com/questions/31601351/why-does-this-matplotlib-heatmap-have-an-extra-blank-column\n ax.set_xlim(0, int(mma.shape[1]))\n ax.set_ylim(0, int(mma.shape[0]))\n \n # want a more natural, table-like display\n ax.invert_yaxis()\n ax.xaxis.tick_top()\n \n # source words -> column labels\n # ax.set_xticklabels(source_labels, minor=False)\n # target words -> row labels\n # ax.set_yticklabels(target_labels, minor=False)\n \n plt.xticks(rotation=45)\n \n # plt.tight_layout()\n plt.show()\n\nprint(len(src), len(trg))\nguess, attn = model(src, trg, teacher_forcing_ratio=0)\nguess = guess.max(2)[1]\nidx = 1\nvis_attn = attn[:,idx,:].T.detach().numpy()\nvis_trg, vis_guess = trg[:, idx], guess[:, idx]\nplot_head_map(vis_attn, vis_trg, vis_guess)\nprint(vis_attn.shape, vis_trg.shape, vis_guess.shape)\nprint(attn[:,0,:].shape)\n# print(en_infer.decode(guess))\n# print(en_infer.decode(trg))\n\n","repo_name":"5yearsKim/Seq2seq-text-Dream","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"6214433905","text":"class Solution(object):\n\n\tdef dedup(self, nums):\n\t\tif len(nums) == 0:\n\t\t\treturn 0\n\n\t\tlow = 0\n\t\thigh = 0\n\t\tcount = 0\n\t\tn = len(nums)\n\n\t\twhile high < n:\n\t\t\tif nums[high] == nums[low]:\n\t\t\t\tcount += 1\n\t\t\t\tif count > 2:\n\t\t\t\t\tnums.pop(high)\n\t\t\t\t\tn -= 1\n\t\t\t\t\tcount -= 1\n\t\t\t\telse:\n\t\t\t\t\thigh += 1\n\t\t\telse:\n\t\t\t\tlow = high\n\t\t\t\tcount = 0\n\n\t\treturn nums\n\nobj = Solution()\narr1 = [1, 1, 1, 2, 2, 3]\nprint(obj.dedup(arr1))\n","repo_name":"rush2catch/algorithms-leetcode","sub_path":"Basic Data Structures/array/leet_080_RemoveDeplicates.py","file_name":"leet_080_RemoveDeplicates.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72947338404","text":"#!/usr/bin/python\n\nimport os\nfrom random import randint\n\n#The text file to search for possible responces, seperated by new lines\nresponcesfile = r\"responces.txt\"\n\ndef main():\n\t#Reset the terminal\n\tos.system(\"reset\")\n\n\t#Make sure the responces file exists\n\tif not os.path.exists(responcesfile):\n\t\texit('Unable to locate \"' + responcesfile + '\"! Exiting...')\n\n\t#Extract each responce and place it in an array\n\twith open(responcesfile) as f:\n\t\tresponces = f.readlines()\n\n\t\n\tos.system('toilet -t \"Magic 8 Ball!\"')\n\tprint(\"##########################################################################################\")\n\tprint(\"\\nAsk me anything and then press ENTER!\")\n\n\n\twhile True:\n\t\t#Wait for the user to return an input\n\t\tx = input(\"\")\n\n\t\t#Clear the screen\n\t\tos.system(\"clear\")\n\n\t\t#Select a random responce\n\t\tres = randint(0, len(responces) - 1)\n\t\tresp = responces[res]\n\n\t\t#Display the responce\n\t\tos.system('toilet -t \"' + resp + '\"')\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"HarrisonTotty/scripts","sub_path":"magic8ball.py","file_name":"magic8ball.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"15484553109","text":"import time\nimport pygame\nfrom parameters4 import *\nfrom simulation import Agent, Arena\n\n# initialization\narena = Arena(width, height, text_font, obstacle_text_size, terminal_text_size, episode_text_size, text_color)\nagents = []\nnum_data_x = [red_buffer, green_buffer, red_buffer, green_buffer]\nfor agent, target in zip(range(number_of_agents), target_positions):\n agent_name = \"Agent \" + str(agent+1)\n agents.append(Agent(arena, agents, num_data_x[agent], width, height, agent_name, target[0], target[1], inner, outer, max_speed, max_length,\n starting_angle, obstacle_position, obstacle_radius, text_font, agent_text_size, white, radius, epsilon, learning_rate, \n discount_factor, separation_magnitude, alignment_magnitude, cohesion_magnitude))\ndynamics_attribute = [[Kp_red, Ki_red, a0_red, a1_red, b1_red],\n [Kp_green, Ki_green, a0_green, a1_green, b1_green],\n [Kp_red, Ki_red, a0_red, a1_red, b1_red],\n [Kp_green, Ki_green, a0_green, a1_green, b1_green]]\n\n# simulation\nfirst = True\nrun_simulation = True\nepisodes = number_of_episodes\nprint('\\n------------- Start Simulation -------------\\n')\n\nfor episode in range(episodes):\n run_episode = True\n time_limit = episode_time * frame_per_second\n\n # reset agent position\n for agent, starting_position in zip(agents, starting_positions):\n agent.reset(starting_position[0], starting_position[1])\n\n # get initial state and action\n for agent in agents:\n agent.get_first_state_action(agent)\n agent.show_output(episode)\n\n while run_episode:\n arena.render(frame_per_second)\n arena.draw_arena(black)\n arena.draw_circle(obstacle_color, terminal_color, obstacle_radius, terminal_radius, obstacle_position, start_position, target_position)\n arena.draw_text(obstacle_text_position, start_text_position, target_text_position, episode_text_position, episode_text_color, episode)\n\n # get old state and update acceleration based on behavior and action\n for agent in agents:\n agent.get_current_state(agent)\n agent.update_acceleration(agent, agents, wander_magnitude, avoid_magnitude, target_magnitude)\n\n # update position and velocity\n for agent, dynamic in zip(agents, dynamics_attribute):\n agent.update_kinematics(dynamic[0], dynamic[1], dynamic[2], dynamic[3], dynamic[4], delta_time)\n\n # get new state and new action, update Q-values, and draw agents\n is_terminal = number_of_agents\n for agent in agents:\n agent.get_next_state(agent)\n agent.get_next_action()\n agent.update_matrix_values(episode, track_version, obstacle_version)\n agent.draw_agent(red, green, black, yellow, blue, orange)\n is_terminal -= agent.is_terminal_state(agents)\n\n if is_terminal == 0:\n run_episode = False\n\n time_limit -= 1\n if time_limit == 0:\n run_episode = False\n\n # delay for dt\n time.sleep(loop_delay)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run_episode = False\n run_simulation = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n run_episode = False\n run_simulation = False\n if event.key == pygame.K_q:\n run_episode = False\n\n # save Q-values for each episode\n if first:\n for agent in agents:\n agent.df_Q_values()\n first = False\n else:\n for agent in agents:\n agent.append_Q_values()\n\n print('\\n------------- End of Episode {} -------------\\n'.format(episode+1))\n if not run_simulation:\n break\n\n# export Q-values to csv\nfor agent in agents:\n agent.save_Q_values(track_version, obstacle_version)\n\npygame.quit()","repo_name":"MosesHubert/swarm-robotics","sub_path":"train4.py","file_name":"train4.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"428434807","text":"from .vertex_edge import Vertex, Edge\nfrom ._parsing import *\n\n\nclass Graph:\n \"\"\"\n A class representing a graph.\n Data are stored as adjacency lists stored in a dictionnary\n Edges in the class graph are not oriented. For oriented edges, please use\n the class OrientedGraph\n \"\"\"\n\n def __init__(self, _graph_dict, _edges=None, _matrix=None):\n \"\"\"\n Initialization function. Is not meant to be called as it is.\n\n Parameters:\n self._dict : Vertex -> set of neighbours vertices\n self._edges : Vertex pair -> corresponding Edge\n self._matrix : adjacency matrix\n \"\"\"\n self._dict = _graph_dict\n self._edges = _edges\n self._matrix = _matrix\n\n def __eq__(self, other):\n return self._dict == other._dict\n\n def __str__(self):\n return str(self._dict)\n\n def __len__(self):\n \"\"\"\n Number of vertices in the graph\n \"\"\"\n return len(self._dict)\n\n # --------------- Initialization methods --------------------------\n\n @staticmethod\n def from_edge_list(l, vertex_data: str = None, edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an edge list\n\n Returns\n -------\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n\n edges = dict()\n if isinstance(l, str):\n # Load from a file\n with open(l, 'r') as f:\n for s in f.readlines():\n s = s.strip().split()\n xa, xb = int(s[0]), int(s[1])\n if vertex_data is None:\n a, b = Vertex(xa), Vertex(xb)\n else:\n a, b = vertex_data[xa], vertex_data[xb]\n if edge_data is None:\n edges[(a, b)] = Edge(a, b)\n edges[(b, a)] = Edge(b, a)\n else:\n e = edge_data.get((a, b), None)\n if e is None:\n e = edge_data.get((b, a), [Edge(a, b)])\n edges[(a, b)] = e[0]\n edges[(b, a)] = Edge.revert(e[0])\n else:\n for e in l:\n e = Edge(e)\n edges[(e[\"start\"], e[\"end\"])] = e\n edges[(e[\"end\"], e[\"start\"])] = e\n graph_dict = dict()\n for key in edges:\n edge = edges[key]\n if edge.start not in graph_dict:\n graph_dict[edge.start] = set([edge.end])\n else:\n graph_dict[edge.start].add(edge.end)\n if edge.end not in graph_dict:\n graph_dict[edge.end] = set([edge.start])\n else:\n graph_dict[edge.end].add(edge.start)\n return Graph(graph_dict, _edges=edges)\n\n @staticmethod\n def from_adjacency_dict(d, vertex_data: str = None, edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an adjacency list\n\n Returns\n -------\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n edges = None\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n edges = {e: edge_data[e][0] for e in edge_data}\n if isinstance(d, str): # Load from a file\n graph_dict = dict()\n with open(d, 'r') as f:\n for line in f.readlines():\n line = line.strip().split()\n v = Vertex(int(line[0]))\n adj_list = line[1:]\n for adj in adj_list:\n adj = Vertex(int(adj))\n if v in graph_dict:\n graph_dict[v].add(adj)\n else:\n graph_dict[v] = set([adj])\n if adj in graph_dict:\n graph_dict[adj].add(v)\n else:\n graph_dict[adj] = set([v])\n if edge_data is not None:\n return Graph(graph_dict, _edges=edges)\n return Graph(graph_dict)\n else:\n return Graph(d, _edges=edges)\n\n @staticmethod\n def from_adjacency_matrix(m, vertex_data: str = None,\n edge_data: str = None):\n \"\"\"\n Imports a graph from a txt file containing an adjacency matrx\n\n Returns:\n A new Graph object\n \"\"\"\n if vertex_data is not None:\n vertex_data = parse_node_data(vertex_data)\n if edge_data is not None:\n edge_data = parse_edge_data(edge_data)\n\n adj_mat = None\n if isinstance(m, str): # Load from a file\n with open(m, 'r') as f:\n adj_mat = [l.strip().split() for l in f.readlines()]\n else:\n adj_mat = m\n n = len(adj_mat)\n graph_dict = dict()\n edges = dict()\n for i in range(n):\n v = Vertex(i)\n graph_dict[v] = set()\n for i in range(n):\n for j in range(n):\n if vertex_data is None:\n vi, vj = Vertex(i), Vertex(j)\n else:\n vi, vj = vertex_data[i], vertex_data[j]\n if int(adj_mat[i][j]) != 0:\n graph_dict[vi].add(vj)\n graph_dict[vj].add(vi)\n if edge_data is not None:\n e = edge_data.get((vi, vj), None)\n if e is None:\n e = edge_data.get((vj, vi), [Edge(vi, vj)])\n edges[(i, j)] = e[0]\n edges[(j, i)] = Edge.revert(e[0])\n else:\n edges[(i, j)] = Edge(vi, vj)\n edges[(j, i)] = Edge(vj, vi)\n return Graph(graph_dict, _edges=edges)\n\n # ------------- Exportation methods -----------------\n\n def export_as_edge_list(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an edge list\n\n Parameters:\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n for e in self.edges():\n f.write(str(e.start)+\" \"+str(e.end)+\"\\n\")\n\n def export_as_adjacency_dict(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an adjacency list\n\n Parameters\n ----------\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n for v in self._dict:\n f.write(str(v)+\" \")\n for neigh in self._dict[v]:\n f.write(str(neigh)+\" \")\n f.write(\"\\n\")\n\n def export_as_adjacency_matrix(self, filename: str) -> None:\n \"\"\"\n Exports the graph in form of an adjacency matrix\n\n Parameters\n ----------\n 'filename' : string\n the relative path of the file to write back the data\n \"\"\"\n with open(filename, 'w') as f:\n mat = self.adjacency_matrix()\n n = len(mat)\n for i in range(n):\n string = \"\"\n for j in range(n):\n string += str(mat[i][j])+\" \"\n string += \"\\n\"\n f.write(string)\n\n def subgraph(self, vertices):\n \"\"\"\n Extract a subgraph of the graph, containing the relevant vertices\n and edges\n\n Parameters\n ----------\n 'vertices' : a container\n Contains the relevant vertices. If it is not a set, is converted\n into a set\n\n Returns\n -------\n A new Graph object\n \"\"\"\n vertices = set([Vertex(v) if isinstance(v, int)\n else v for v in vertices])\n graph_dict = {v: set() for v in vertices}\n edges = None\n if self._edges is not None:\n edges = dict()\n for v in vertices:\n for u in vertices:\n if v != u and u in self._dict[v]:\n graph_dict[v].add(u)\n graph_dict[u].add(v)\n if edges is not None:\n edges[(u, v)] = self._edges[(u, v)]\n edges[(v, u)] = self._edges[(v, u)]\n return Graph(graph_dict, _edges=edges)\n\n def renumber(self):\n \"\"\"\n Returns a copy of the graph where all the vertices have been renumbered\n from 0 to n. Does not copy edge or vertex data, but only\n the combinatorial structure\n\n Returns\n -------\n A Graph Object\n \"\"\"\n graph_dict = dict()\n vertices = {x: Vertex(i)\n for (i, x) in enumerate(list(self.vertices()))}\n for v in self._dict:\n graph_dict[vertices[v]] = set()\n for u in self._dict[v]:\n graph_dict[vertices[v]].add(vertices[u])\n return Graph(graph_dict)\n\n # ---------------- Getters and setters -----------------------------\n\n def vertices(self):\n \"\"\"\n Getter on the vertices of the graph\n\n Returns:\n An iterator over the vertices of the graph\n \"\"\"\n return self._dict.keys()\n\n def _generate_edges(self):\n \"\"\"\n Generates the set of edges of the graph.\n This set is then stored into the self._edges attribute\n \"\"\"\n self._edges = dict()\n for a in self.vertices():\n for b in self._dict[a]:\n if(hash(b) < hash(a)):\n continue\n self._edges[(a, b)] = Edge(a, b)\n self._edges[(b, a)] = Edge(b, a)\n\n def edges(self, erase_multiple=True):\n \"\"\"\n Getter on the edges of the graph\n\n Parameters\n ----------\n 'erase_multiple' : bool\n If set to True, will do not consider duplicate edges\n\n Returns\n -------\n An iterator over the edges of a the graph\n \"\"\"\n if self._edges is None:\n self._generate_edges()\n if erase_multiple:\n return set(self._edges.values())\n return list(self._edges.values())\n\n def _generate_adjacency(self):\n \"\"\"\n Generates the adjacency matrix of the graph.\n This matrix is then stored into the self._matrix attribute\n \"\"\"\n try:\n n = len(self._dict) # number of vertices\n # assign a number between 0 and n to all vertices\n self._matrix = [[0 for j in range(n)] for i in range(n)]\n for u in self._dict:\n for v in self._dict[u]:\n self._matrix[u.id][v.id] = 1\n self._matrix[v.id][u.id] = 1\n except Exception as e:\n self._matrix = None\n raise e\n\n def adjacency_matrix(self):\n \"\"\"\n Computes and return the adjacency matrix of the graph.\n\n Returns:\n A numpy array of shape (N*N) where N is the number of vertices\n in the graph\n \"\"\"\n if self._matrix is None:\n self._generate_adjacency()\n return self._matrix\n\n def get_neighbours(self, v):\n \"\"\"\n Returns the vertices that are adjacent to v\n\n Parameters:\n 'v' : A Vertex object or an integer (vertex id)\n The vertex from which to extract the neighbourhood\n\n Returns:\n The set of neighbours of v\n \"\"\"\n\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n return self._dict[v]\n\n def get_neighbours_edge(self, v):\n \"\"\"\n Returns the edges of the graph that are incident to v\n\n Parameters:\n 'v' : A Vertex object or an integer (vertex id)\n The vertex from which to extract the neighbourhood\n\n Returns:\n The set of neighbours of v\n \"\"\"\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if self._edges is None:\n return set([Edge(v, u) for u in self._dict[v]])\n else:\n output = set()\n for e in self.edges():\n if e.start == v or e.end == v:\n output.add(e)\n return output\n\n # --------------- Modification of the data ------------------------\n def add_vertex(self, v) -> None:\n \"\"\"\n Adds a new vertex to the graph\n\n Parameters:\n 'v' : a Vertex object or a integer for a Vertex id\n If an integer is provided, the method will build a Vertex\n with the id field being v.\n \"\"\"\n self._matrix = None # reset adjacency matrix\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if v not in self._dict:\n self._dict[v] = set()\n\n def remove_vertex(self, v) -> None:\n \"\"\"\n Removes a vertex from the graph. If the given vertex is not present,\n this method does not do anything.\n\n Parameters:\n 'v' : a Vertex object or a integer for a Vertex id\n If an integer is provided, the method will build a Vertex\n with the id field being v.\n \"\"\"\n self._edges = None # reset edges set\n self._matrix = None # reset adjacency\n if not isinstance(v, Vertex):\n assert isinstance(v, int)\n v = Vertex(v)\n if v in self._dict:\n self._dict.pop(v, None)\n for x in self._dict:\n self._dict[x].discard(v)\n\n def add_edge(self, *args):\n \"\"\"\n Adds an edge in the graph. If one or both ends of the edge are not\n present in the graph, the coresponding vertices are added.\n\n NOTE : If the edge is a loop (that is, links a vertex to itself),\n will raise an exception as loops are forbidden.\n\n Parameters:\n 'args' : Edge | (Vertex, Vertex) | (name, name)\n The data needed to generate the edge. Can be directly an Edge\n object, or any pair of Vertex or vertex names.\n \"\"\"\n e = Edge(args)\n if e.start == e.end:\n raise Exception(\"Loops are forbidden in the Graph class.\\\n Use the MultiGraph class instead.\")\n if e.start not in self._dict:\n self._dict[e.start] = set([e.end])\n else:\n self._dict[e.start].add(e.end)\n if e.end not in self._dict:\n self._dict[e.end] = set([e.start])\n else:\n self._dict[e.end].add(e.start)\n if self._edges is not None:\n self._edges[(e.start, e.end)] = e\n self._edges[(e.end, e.start)] = e\n\n def remove_edge(self, *args):\n \"\"\"\n Removes an edge from the graph.\n\n Parameters:\n 'args' : Edge | (Vertex, Vertex) | (name, name)\n The data needed to generate the edge. Can be directly an Edge\n object, or any pair of Vertex or vertex names.\n \"\"\"\n e = Edge(args)\n self._dict[e.start].discard(e.end)\n self._dict[e.end].discard(e.start)\n if self._edges is not None:\n self._edges.pop((e.start, e.end), None)\n self._edges.pop((e.end, e.start), None)\n\n # ---------------- Stats computations -----------------------------\n def vertex_degree(self):\n \"\"\"\n Returns the list of degrees of the vertices in the graph.\n\n Returns:\n A list of integers\n \"\"\"\n return [len(self._dict[v]) for v in self.vertices()]\n\n def degree_sequence(self):\n \"\"\"\n Returns the list of degrees of the vertices in the graph sorted in\n decreasing order\n\n Returns:\n A list of integers sorted in decreasing order\n \"\"\"\n degree_list = self.vertex_degree()\n degree_list.sort(reverse=True)\n return degree_list\n\n def find_isolated_vertices(self):\n \"\"\"\n Returns the list of isolated vertices, that is vertices with degree 0\n\n Returns:\n A list of the names of vertices that have zero degree\n \"\"\"\n return [v for v in self.vertices() if len(self._dict[v]) == 0]\n\n def density(self):\n \"\"\"\n Computes the density of the graph, defined as the proportion of edges\n = {number of edges}/{total possible number of edges}\n = 2*{number of edges}/(N(N-1))\n\n Returns:\n The density of the graph\n \"\"\"\n e_nb = len(self.edges())\n v_nb = len(self.vertices())\n possible_edges = v_nb*(v_nb-1)/2\n return e_nb / possible_edges\n","repo_name":"GCoiffier/graph_tools","sub_path":"graphtool/graph/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":17052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"2675714609","text":"from __future__ import absolute_import\nfrom __future__ import print_function\nimport networkx\nfrom . import (types, tri, dijkstra)\nfrom ...utils import pairwise\nimport itertools\nfrom tqdm import tqdm\nfrom shapely.geometry import (Point, Polygon, MultiPolygon, CAP_STYLE,\n JOIN_STYLE, box, LineString, MultiLineString, MultiPoint)\nfrom shapely.ops import unary_union\nfrom shapely.prepared import prep\n\n# Alpha is a parameter that shifts the balance between vias and\n# overall line length. It must be > 0 and < 1.\n# A larger value favors longer paths, whereas a smaller value\n# will bias towards more vias.\nALPHA = 0.1\n\n\ndef line_between(shape1, shape2):\n return LineString([shape1.centroid, shape2.centroid])\n\n\nclass NodeLayerAssignment(object):\n ''' Represents the layer assignment for a connectable '''\n\n def __init__(self, node):\n self.node = node\n self.available_layers = set(node.layers)\n self.configured_layers = set()\n\n\nclass SourceSinkNode(object):\n ''' one of the endpoints of a two net assignment graph '''\n\n def __init__(self, nla):\n assert isinstance(nla, NodeLayerAssignment)\n self.nla = nla\n\n\nclass InputTwoNet(object):\n def __init__(self, a, b):\n self.source = SourceSinkNode(a)\n self.sink = SourceSinkNode(b)\n self.g = self.build_graph()\n\n def build_graph(self, via_count=3):\n ''' Build a layer assignment graph for the path a->b. '''\n g = networkx.DiGraph()\n\n a = self.source.nla.node\n b = self.sink.nla.node\n\n if a.net != b.net:\n print('a.net', a.net)\n print('a', a)\n print('b.net', b.net)\n print('b', b)\n assert a.net == b.net\n\n via_points = []\n left = a.shape.centroid\n right = b.shape.centroid\n distance = left.distance(right) / (via_count + 1)\n for i in range(0, via_count):\n line = LineString([left, right])\n vp = line.interpolate(distance)\n via_points.append(vp)\n left = vp\n\n g.add_node(self.source)\n g.add_node(self.sink)\n\n nodes_by_layer = {}\n\n for layer in [types.FRONT, types.BACK]:\n if a.is_on_layer(layer):\n al = types.Branch(a.shape, net=a.net, layer=layer, proxy_for=a)\n g.add_node(al)\n g.add_edge(self.source, al)\n else:\n al = None\n\n if b.is_on_layer(layer):\n bl = types.Branch(b.shape, net=b.net, layer=layer, proxy_for=b)\n g.add_node(bl)\n g.add_edge(bl, self.sink)\n else:\n bl = None\n\n nodes_by_layer[layer] = [al, bl]\n\n last = al\n for pt in via_points:\n vl = types.Branch(pt, net=a.net, layer=layer)\n nodes_by_layer[layer].append(vl)\n if last:\n g.add_edge(last, vl, line=line_between(\n last.shape, vl.shape))\n last = vl\n\n if bl:\n g.add_edge(last, bl, line=line_between(last.shape, bl.shape))\n\n # Generate the short circuit branches. The purpose\n # of these is to avoid understimation of certain\n # paths through the graph. Each consecutive sequence\n # of nodes is connected together\n for i in range(2, via_count + 2):\n if nodes_by_layer[layer][i] is None:\n continue\n for seq_len in range(2, via_count):\n if i + seq_len < len(nodes_by_layer):\n t = nodes_by_layer[layer][i + seq_len]\n if t is not None:\n g.add_edge(nodes_by_layer[layer][i], t, line=line_between(\n nodes_by_layer[layer][i].shape, t.shape))\n\n for i, node in enumerate(nodes_by_layer[types.FRONT]):\n # Can traverse up or down\n other = nodes_by_layer[types.BACK][i]\n if node and other:\n g.add_edge(node, other, via=i > 1)\n g.add_edge(other, node, via=i > 1)\n\n return g\n\n\nclass Component(object):\n ''' Represents a component formed out of connected paths\n on a layer of a board '''\n\n def __init__(self, a, b):\n a = a.centroid\n b = b.centroid\n self.terminals = set([(a.x, a.y), (b.x, b.y)])\n self.lines = [LineString([(a.x, a.y), (b.x, b.y)])]\n self.shape = self.lines[0]\n\n def update_with(self, comp):\n ''' Extends self with the component info from comp '''\n self.terminals.update(comp.terminals)\n self.lines += comp.lines\n self.shape = MultiLineString(self.lines)\n\n def __str__(self):\n return '%d terminals %d lines' % (len(self.terminals), len(self.lines))\n\n def detour_cost(self, line):\n ''' computes the detour cost for the line (A->B).\n Precondition is that line intersects with this component!\n The detour cost is the smallest path around the shape represented\n by this component. In the simplest case this component is a line I->J\n that forms an X shape where it intersects with A->B. The detour is\n to form a square path around the outside. This generalizes to\n computing the convex hull of the combined component and line; the\n detour cost is then the smallest distance walking from A to B\n either clockwise or counter clockwise around the vertices of\n the hull '''\n joined = unary_union([self.shape, line])\n hull = joined.convex_hull\n if hasattr(hull, 'exterior'):\n hull = list(hull.exterior.coords)\n # the final coord loops back to the start; remove it\n hull.pop()\n else:\n hull = list(hull.coords)\n\n a, b = list(line.coords)\n\n # Since we buffered out the shapes, we need to make a pass to find\n # the closest points to our A and B points\n\n def closest(vert, exclude=None):\n best = None\n vert = Point(vert)\n for p in hull:\n if exclude and exclude == p:\n continue\n d = vert.distance(Point(p))\n if not best or d < best[0]:\n best = [d, p]\n return best[1]\n\n a_close = closest(a)\n b_close = closest(b, exclude=a_close)\n\n # Map those to indices\n for i in range(0, len(hull)):\n if hull[i] == a_close:\n a_pos = i\n if hull[i] == b_close:\n b_pos = i\n\n if a_pos == b_pos:\n print(line)\n print(hull)\n print('boom')\n from ... import svg\n doc = svg.SVG()\n doc.add(self.shape, stroke='red',\n stroke_width=0.01, fill_opacity=0)\n doc.add(line, stroke='blue', stroke_width=0.01, fill_opacity=0)\n doc.add(joined.convex_hull, stroke='grey',\n stroke_width=0.01, fill_opacity=0)\n doc.save('/tmp/gah.svg')\n assert a_pos != b_pos\n return 0\n\n # [A x y B] -> [A, x, y, B] and [B, A]\n # [x A y B] -> [A, y, B] and [B, x, A]\n # [B x A y] -> [A, y, B] and [B, x, A]\n\n a_path = hull[a_pos:] + hull[:-a_pos]\n a_cost = 0\n for i, j in pairwise(a_path):\n a_cost += LineString([i, j]).length\n if j == b:\n assert a_cost != 0\n break\n\n b_path = hull[b_pos:] + hull[:-b_pos]\n b_cost = 0\n for i, j in pairwise(b_path):\n b_cost += LineString([i, j]).length\n if j == a:\n assert b_cost != 0\n break\n\n base_detour = LineString([a, a_close]).length + \\\n LineString([b, b_close]).length\n return min(a_cost, b_cost) + base_detour\n\n\nclass ComponentList(object):\n ''' A list of components on a layer '''\n\n def __init__(self):\n self.comps = set()\n\n def component_for_vertex(self, vert):\n for comp in self.comps:\n if vert in comp.terminals:\n return comp\n return None\n\n def add(self, comp):\n ''' Adds a component, merging it if appropriate '''\n\n # Find the set of components that share vertices\n to_merge = set()\n for vert in comp.terminals:\n m = self.component_for_vertex(vert)\n if m:\n to_merge.add(m)\n # Remove it from the set; it will be merged\n # into the component we're adding in this call\n self.comps.remove(m)\n\n # Now merge them together\n for m in to_merge:\n comp.update_with(m)\n\n self.comps.add(comp)\n\n def intersects(self, shape):\n vert_a, vert_b = list(shape.coords)\n shape = prep(shape)\n for comp in self.comps:\n if vert_a in comp.terminals:\n continue\n if vert_b in comp.terminals:\n continue\n if shape.intersects(comp.shape):\n yield comp\n\n\nclass Path(object):\n ''' Holds some path related state '''\n\n def __init__(self, cost, input_2net, path):\n self.cost = cost\n self.input_2net = input_2net\n self.path = path\n\n\nclass Configuration(object):\n def __init__(self, two_nets):\n self.cost = None\n self.paths = []\n self.cost_cache = {}\n self.assignment_order = []\n self.components_by_layer = {\n types.FRONT: ComponentList(),\n types.BACK: ComponentList(),\n }\n self.two_nets = []\n self.raw_two_nets = two_nets\n\n nla_map = {}\n\n def nla_for_node(node):\n nla = nla_map.get(node)\n if not nla:\n nla = NodeLayerAssignment(node)\n nla_map[node] = nla\n return nla\n\n for net in two_nets:\n self.two_nets.append(InputTwoNet(nla_for_node(net[0]),\n nla_for_node(net[1])))\n\n def edge_weight(self, source, target, edgedata):\n key = (source, target)\n cost = self.cost_cache.get(key)\n if cost is None:\n detour_cost = 0\n basic_cost = 0\n is_via = edgedata.get('via', False)\n\n if isinstance(source, SourceSinkNode) or isinstance(target, SourceSinkNode):\n # Source/sink node traversal.\n\n if not isinstance(source, SourceSinkNode):\n # we can never have SourceSinkNode->SourceSinkNode, so we can\n # safely swap the values here to make the code simpler\n source, target = target, source\n\n # assert isinstance(source, SourceSinkNode)\n # assert not isinstance(target, SourceSinkNode)\n # assert len(target.layers) == 1\n\n layer = target.layers[0]\n if layer not in source.nla.available_layers:\n basic_cost = float('inf')\n elif (len(source.nla.configured_layers) > 0) and (\n layer not in source.nla.configured_layers):\n basic_cost = float('inf')\n\n elif not is_via:\n my_line = edgedata.get('line')\n if my_line:\n basic_cost = my_line.length\n\n # assert len(source.layers) == 1\n # assert len(target.layers) == 1\n layer = source.layers[0]\n\n # Compute the detour cost; this is minimum length of an alternate\n # path that we'd need to take to avoid intersecting segments\n\n for comp in self.components_by_layer[layer].intersects(my_line):\n d1 = comp.detour_cost(my_line)\n #tqdm.write('segment %s intersects with comp %s, cost %s' % (my_line, comp, d1))\n if detour_cost == 0:\n detour_cost = d1\n else:\n detour_cost = min(detour_cost, d1)\n\n cost = ((1 - ALPHA) * (basic_cost + detour_cost))\n if is_via:\n cost += ALPHA\n\n self.cost_cache[key] = cost\n return cost\n\n def _invalidate_cache_for_path(self, path):\n ''' Invalidate cached cost information for segments that intersect\n those in the newly added path '''\n if not self.paths or not self.cost_cache:\n return\n\n g = path.input_2net.g\n\n invalidated = set()\n for source, target in pairwise(path.path):\n if isinstance(source, SourceSinkNode) or isinstance(target, SourceSinkNode):\n continue\n my_line = g[source][target].get('line')\n if not my_line:\n continue\n for p in self.paths:\n for i, j in pairwise(p.path):\n if (i in invalidated) and (j in invalidated):\n continue\n\n if not (hasattr(i, 'shape') and hasattr(j, 'shape')):\n continue\n\n seg_line = p.input_2net.g[i][j].get('line')\n if seg_line and seg_line.intersects(my_line):\n invalidated.add(i)\n invalidated.add(j)\n\n for key in list(self.cost_cache.keys()):\n a, b = key\n if (a in invalidated) or (b in invalidated):\n del self.cost_cache[key]\n\n def add_path(self, path):\n self._invalidate_cache_for_path(path)\n self.paths.append(path)\n self.cost = None\n self.assignment_order.append(path.input_2net)\n\n # Track the layer assignments\n for a, b in pairwise(path.path):\n if isinstance(a, SourceSinkNode):\n source, node = a, b\n elif isinstance(b, SourceSinkNode):\n source, node = b, a\n else:\n if a.shape != b.shape:\n comp = Component(a.shape, b.shape)\n self.components_by_layer[a.layers[0]].add(comp)\n continue\n\n layer = node.layers[0]\n source.nla.configured_layers.add(layer)\n\n def compute_cost(self):\n if self.cost is None:\n self.cost = 0\n for path in tqdm(self.paths, desc='compute cost'):\n for a, b in pairwise(path.path):\n self.cost += self.edge_weight(a,\n b, path.input_2net.g[a][b])\n\n return self.cost\n\n def initial_assignment(self):\n ''' Assign 2net in ascending order of cost '''\n with tqdm(desc='initial 2net assignment', total=len(self.two_nets)) as pbar:\n free = set(self.two_nets)\n\n while len(free) > 0:\n pbar.update(1)\n best = None\n for n in free:\n cost, path = dijkstra.dijkstra(n.g, n.source, n.sink,\n edge_weight=self._make_edge_weight_func(),\n cutoff=best.cost if best is not None else None)\n\n if cost is None:\n # hit the cutoff\n continue\n\n if not best or cost < best.cost:\n best = Path(cost, n, path)\n\n free.remove(best.input_2net)\n self.add_path(best)\n #tqdm.write('best is cost=%r (overall %r)' % (cost, self.compute_cost()))\n\n return self\n\n def _make_edge_weight_func(self):\n def fn(v, u, e):\n return self.edge_weight(v, u, e)\n return fn\n\n def improve(self):\n improved = True\n best_cfg = self\n import time\n\n start = time.time()\n\n # Setting a deadline because there are a lot of combinations to\n # try and it is relatively expensive\n deadline = start + 10\n while improved and time.time() < deadline:\n improved = False\n\n best_order = [x for x in best_cfg.assignment_order]\n for i, node in enumerate(tqdm(best_order, desc='improving')):\n if time.time() >= deadline:\n break\n\n order = [x for x in best_order]\n order.insert(0, order.pop(i))\n\n if order == best_order:\n continue\n\n cfg = Configuration(self.raw_two_nets)\n cutoff = None\n failed = False\n for n in tqdm(order, desc='pass %d' % i):\n cost, path = dijkstra.dijkstra(\n n.g, n.source, n.sink, edge_weight=cfg._make_edge_weight_func(), cutoff=cutoff)\n if cost is None:\n # It's not possible to yield a better result\n # than the best we already have\n failed = True\n break\n cfg.add_path(Path(cost, n, path))\n cutoff = best_cfg.compute_cost() - cfg.compute_cost()\n if cutoff <= 0:\n # Can't do well enough to improve on this round\n failed = True\n break\n\n if not failed and cfg.compute_cost() < best_cfg.compute_cost():\n improved = True\n tqdm.write('Improved cost from %r to %r' %\n (best_cfg.compute_cost(), cfg.compute_cost()))\n best_cfg = cfg\n\n return cfg\n","repo_name":"wez/clacker","sub_path":"tools/circuitlib/router/layerassign.py","file_name":"layerassign.py","file_ext":"py","file_size_in_byte":17773,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"}
+{"seq_id":"41572076358","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nEditor de Spyder\r\n\r\nEste es un archivo temporal.\r\n\"\"\"\r\nfrom selenium import webdriver\r\nfrom time import sleep\r\nfrom numpy import random\r\nimport pandas as pd\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\n\r\n\r\n\r\n\r\n\r\ndef scraping():\r\n #funcion que recibe la categoria de waltmare\r\n #devuelve los productos en una lista llamada \"d\"\r\n driver = webdriver.Chrome('C:/Users/Tomas/Documents/GitHub/Waltmart_scrapper/chromedriver.exe')\r\n \r\n\r\n #obtiene el link (el path fue defindio al principio, y la categoria es la entrada de la funcion)\r\n driver.get(\"https://www.imperiumao.com.ar/es/eventdata.php?i=12&n=Experiencia%20x2\")\r\n #los try y except estan para evitar que se rompan el programa si falta algun dato\r\n try:\r\n estado1 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[6]/td[2]/p').text\r\n estado2 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[7]/td[2]/p').text\r\n estado3 = driver.find_element_by_xpath('//table[@width=\"90%\"]/tbody/tr[8]/td[2]/p').text\r\n print(estado1)\r\n print(estado2)\r\n print(estado3)\r\n if estado1 != estado2 or estado2 != estado3 or estado1 != estado3:\r\n print(\"NOTIFICACION DE ACTIVO ENVIAR WPP\")\r\n except:\r\n print(\"ENVIAR NOTIFICCION DE FALLO\")\r\n \r\n sleep(1500)\r\n \r\n\r\nwhile True:\r\n scraping() ","repo_name":"tomasruffo/imperiumscraper","sub_path":"imperium_scrapper.py","file_name":"imperium_scrapper.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"31444974265","text":"\"\"\"\nCommand-line scripts for Windowbox.\n\nThis file defines several custom commands for use with the `flask `\nutility. Broadly, these scripts can do the following:\n\n * Initialize, fill, and clear the development database.\n * Run development reports (style checks/unit tests).\n\nEach script tries to be a courteous command-line citizen, implementing exit\ncodes and responding to `flask --help` in useful ways.\n\nNOTE: The `flask` utility is sensitive to the current working directory. It\n*MUST* be run from /vagrant or one of the subdirectories beneath or the\napplication code will not be properly detected.\n\nAttributes:\n DEV_DB_SUFFIX: The expected value the database connection string should end\n with. If this suffix does not match, all scripts that manipulate the\n database will abort for safety.\n DEV_CLI_EMAIL_ADDRESS: Email address to use for the Sender in the\n `flask insert` command.\n DEV_CLI_DISPLAY_NAME: Display name to use for the Sender in the\n `flask insert` command.\n DEV_CLI_USER_AGENT: User-agent string to use for the Post in the\n `flask insert` command.\n FAKE_IMAGE_DIMENSIONS: Tuple containing the width, height of the \"full\"\n image in the `flask insert` command.\n CIRCLE_AREA: 4-tuple of (x1, y1, x2, y2) outlining the bounding box for the\n inner circle in the fake image (to visually verify cropping).\n\"\"\"\n\nimport click\nimport os\nimport shutil\nimport sys\nfrom subprocess import call\nfrom windowbox import app\nfrom windowbox.database import db\n\nDEV_DB_SUFFIX = '/dev.sqlite'\nDEV_CLI_EMAIL_ADDRESS = 'cli@localhost'\nDEV_CLI_DISPLAY_NAME = 'Development User'\nDEV_CLI_USER_AGENT = 'windowbox.cli'\nFAKE_IMAGE_DIMENSIONS = (2000, 1500)\nCIRCLE_AREA = (250, 0, 1750, 1499)\n\n\n@app.cli.command('create')\ndef cli_create(): # pragma: nocover\n \"\"\"\n Create all database tables defined by the app models.\n\n If the database already exists, this function is a no-op and will not harm\n any existing data that may be stored there.\n \"\"\"\n if not app.config['SQLALCHEMY_DATABASE_URI'].endswith(DEV_DB_SUFFIX):\n raise EnvironmentError('Refusing to create a non-dev database')\n\n db.create_all()\n\n print('Dev database created.')\n\n\n@app.cli.command('drop')\ndef cli_drop(): # pragma: nocover\n \"\"\"\n Drop all database tables defined by the app models AND clear storage files.\n\n If the database does not exist, this function will succeed quietly.\n \"\"\"\n if not app.config['SQLALCHEMY_DATABASE_URI'].endswith(DEV_DB_SUFFIX):\n raise EnvironmentError('Refusing to drop a non-dev database')\n\n db.drop_all()\n\n for d in (app.attachments_path, app.derivatives_path):\n shutil.rmtree(d)\n\n print('Dev database and storage files dropped.')\n\n\n@app.cli.command('insert')\n@click.argument('count', default=1, type=int)\ndef cli_insert(count): # pragma: nocover\n \"\"\"\n Generate COUNT Posts with Attachments and all other attributes filled in.\n\n If unspecified, COUNT defaults to 1.\n \"\"\"\n import sqlalchemy.orm.exc\n from PIL import Image, ImageDraw\n from random import randrange\n from windowbox.models.post import Post\n from windowbox.models.sender import Sender\n\n print(f'Generating {count} Post(s)...')\n\n try:\n sender = Sender.query.filter_by(email_address=DEV_CLI_EMAIL_ADDRESS).one()\n except sqlalchemy.orm.exc.NoResultFound:\n sender = Sender(\n email_address=DEV_CLI_EMAIL_ADDRESS,\n display_name=DEV_CLI_DISPLAY_NAME)\n db.session.add(sender)\n print(f'Sender {DEV_CLI_EMAIL_ADDRESS} was created.')\n\n for _ in range(count):\n color = (randrange(256), randrange(256), randrange(256))\n fake_caption = f'#{color[0]:0>2X}{color[1]:0>2X}{color[2]:0>2X}'\n fake_image = Image.new('RGB', FAKE_IMAGE_DIMENSIONS, color)\n draw = ImageDraw.Draw(fake_image)\n draw.ellipse(CIRCLE_AREA, fill=(color[2], color[1], color[0]))\n\n post = Post(\n sender=sender,\n caption=fake_caption,\n user_agent=DEV_CLI_USER_AGENT)\n db.session.add(post)\n\n attachment = post.new_attachment(mime_type='image/jpeg')\n db.session.add(attachment)\n db.session.flush()\n\n attachment.base_path = app.attachments_path\n attachment.set_storage_data_from_image(fake_image)\n attachment.populate_exif(exiftool_client=app.exiftool_client)\n\n attachment.geo_latitude = attachment.exif['Composite:GPSLatitude.num'] = 36\n attachment.geo_longitude = attachment.exif['Composite:GPSLongitude.num'] = -78.9\n attachment.geo_address = 'Command Line, USA'\n\n db.session.commit()\n\n print(f'Post {post.id}: {fake_caption}')\n\n print('Done.')\n\n\n@app.cli.command('lint')\ndef cli_lint(): # pragma: nocover\n \"\"\"\n Lint the Python code using flake8.\n \"\"\"\n retcode = call(['flake8'])\n\n if retcode == 0:\n print('No style problems found.')\n\n sys.exit(retcode)\n\n\n@app.cli.command('test', context_settings={'ignore_unknown_options': True})\n@click.argument('pytest_args', nargs=-1, type=click.UNPROCESSED)\ndef cli_test(pytest_args): # pragma: nocover\n \"\"\"\n Run the unit tests.\n\n If PYTEST_ARGS is provided, they will be passed to the test runner.\n \"\"\"\n os.environ['WINDOWBOX_CONFIG'] = 'configs/test.py'\n\n sys.exit(call(['pytest', *pytest_args]))\n","repo_name":"smitelli/windowbox","sub_path":"windowbox/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"16972193053","text":"from abc import ABC, abstractmethod\nimport os, datetime\n\n\ndef factory(classname):\n cls = globals()[classname]\n return cls\n\n\ndef get_config(name, config_env_name):\n return factory(name)(name, config_env_name)\n\n\nclass Config(ABC):\n def __init__(self, name, config_env_name):\n self.name = name\n self.config_env_name = config_env_name\n\n # output config\n self.output_path = \"results/{}-{}/\".format(name, config_env_name)\n self.output_path = self.output_path + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + \"/\"\n os.makedirs(self.output_path)\n\n self.model_output = self.output_path + \"model.weights/\"\n self.log_path = self.output_path + \"log.txt\"\n self.plot_output = self.output_path\n\n # general experiment settings\n self.record = True\n # self.record_path = self.output_path\n # self.record_freq = None\n self.summary_freq = 1\n self.show_plots = True\n\n # for evaluation\n self.eval_episodes = 1000 # how many episodes to sample from eval set.\n self.record_episodes = 100 # to compute stats when record is triggered\n self.plots_per_record = 10 # how many plots to save per recording\n\n self.build()\n\n @abstractmethod\n def build(self):\n raise NotImplementedError\n\nclass BaselineZero(Config):\n def build(self):\n self.controller_name = \"BaselineZero\"\n\n\nclass BaselineOne(Config):\n def build(self):\n self.controller_name = \"BaselineOne\"\n\n\nclass BaselineFeasible(Config):\n def build(self):\n self.controller_name = \"BaselineFeasible\"\n\n\nclass Random(Config):\n def build(self):\n self.controller_name = \"Random\"\n\n\nclass PG(Config):\n def build(self):\n self.controller_name = \"PG\"\n\n self.use_baseline = True\n self.normalize_advantage = True\n\n # model and training config\n self.num_batches = 100 # number of batches trained on\n self.batch_size = 4 * 24 * 100 # number of steps used to compute each policy update\n\n self.learning_rate = 0.03\n # self.gamma = 0.8 # the discount factor\n # self.gamma = 0.95 # the discount factor\n # self.gamma = 1 # the discount factor\n\n # parameters for the policy and baseline models\n self.layer_sizes = (512, 512, 256)\n\n # overwrite from general config:\n self.record = True\n self.record_freq = self.num_batches // 10\n\n\nclass PG_small(PG):\n def build(self):\n super().build()\n self.layer_sizes = (128, 128, 64)\n\n\nclass PG_nano(PG):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n\nclass PG_nano_long(PG):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n # model and training config\n self.num_batches = 10000 # number of batches trained on\n self.batch_size = 4 * 24 # number of steps used to compute each policy update\n\n self.learning_rate = 0.001\n self.record_freq = self.num_batches // 10\n\n\nclass PG_linear(PG):\n def build(self):\n super().build()\n self.layer_sizes = []\n\n\nclass ConfigQN(Config):\n def build(self):\n # env config\n self.render_train = False\n self.render_test = False\n\n # model and training config\n self.num_episodes_test = 50\n self.grad_clip = True\n self.clip_val = 10\n self.log_freq = 50\n self.soft_epsilon = 0.05\n\n # hyper params\n self.nsteps_train = 5e5\n self.batch_size = 32\n self.buffer_size = 200000\n self.target_update_freq = 10000\n # self.gamma = 0.8 # the discount factor\n # self.gamma = 0.95 # the discount factor\n # self.gamma = 1\n self.learning_freq = 1\n self.lr_begin = 0.003\n self.lr_end = 0.0003\n self.lr_nsteps = self.nsteps_train/2\n self.eps_begin = 1\n self.eps_end = 0.03\n self.eps_nsteps = self.nsteps_train/4\n self.learning_start = 50000\n\n # model and training config\n self.saving_freq = self.nsteps_train // 2\n self.log_freq = 50\n self.eval_freq = self.nsteps_train // 10\n\n # overwrite from general config:\n self.record_freq = self.nsteps_train // 5\n\n\nclass LinearQN(ConfigQN):\n def build(self):\n super().build()\n self.controller_name = \"LinearQN\"\n\n\nclass DeepQN(ConfigQN):\n def build(self):\n super().build()\n self.controller_name = \"DeepQN\"\n self.layer_sizes = (512, 512, 256)\n\n\nclass DeepQN_small(DeepQN):\n def build(self):\n super().build()\n self.layer_sizes = (128, 128, 64)\n\n\nclass DeepQN_nano(DeepQN):\n def build(self):\n super().build()\n self.layer_sizes = (64, 32, 16)\n\n\nclass QLearningMLP(Config):\n def build(self):\n self.controller_name = \"QLearningMLP\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\n\nclass SarsaMLP(Config):\n def build(self):\n self.controller_name = \"SarsaMLP\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\nclass QLearningMLPDouble(Config):\n def build(self):\n self.controller_name = \"QLearningMLPDouble\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\nclass SarsaMLPDouble(Config):\n def build(self):\n self.controller_name = \"SarsaMLPDouble\"\n self.hidden_layer_sizes = (700, 500, 300)\n self.lr = 0.001\n self.epsilon = 1\n\n self.num_batches = 1000 # number of batches trained on\n self.batch_size = 4 * 24 * 6 # number of steps used to compute each policy update\n self.record_freq = self.num_batches // 10\n\n","repo_name":"ourownstory/controller_ev_charging","sub_path":"config_controller.py","file_name":"config_controller.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"26673140047","text":"from nltk.tokenize import RegexpTokenizer\nfrom nltk.probability import FreqDist\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom PIL import Image\nimport numpy as np\nfrom nltk.corpus import stopwords\nimport os\nimport sys\nfrom textblob import TextBlob\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import accuracy_score, f1_score, confusion_matrix\n\nstop_words = set(stopwords.words(\"english\"))\n# Extend stopwords (see analysis below)\nextension = {\n 'trumps',\n 'trump',\n 'obama',\n 'donald',\n 'new',\n 'u'\n}\nstop_words.update(extension)\n\n# Import module\nmodule_path = os.path.abspath(os.path.join('./src'))\nif module_path not in sys.path:\n sys.path.append(module_path)\n \nfrom modules import preprocessing as pp\nfrom modules import graph, modelling \n\n\n\ntokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n\ndef get_vocab_length(Series, words=30, title=\"Word Frequency\", show_graph=True):\n \"\"\"\n Returns a frequency dictionary of the top words in the corpus\n \n \"\"\"\n corpus = \" \".join(Series.to_list())\n corpus = tokenizer.tokenize(corpus)\n freqdist = FreqDist(corpus)\n if show_graph:\n fig, ax = plt.subplots(nrows=1,ncols=1, figsize=(12,6))\n freqdist.plot(words, title= title)\n print(f\"Current Vocab size is = {len(freqdist)}\")\n return freqdist\n\n\ndef get_subjectivity(text):\n \"\"\"\n \n Returns subjectivity using the TextBlob Implementation\n \n \"\"\"\n blob = TextBlob(text)\n return blob.sentiment[1]\n\ndef get_polarity(text):\n \"\"\"\n Returns polarity score of a string using TextBlobs implementation\n \n \"\"\"\n blob = TextBlob(text)\n return blob.sentiment[0]\n\n\ndef countX(lst, x): \n \"\"\"\n \n Giving a list lst and an item, returns the frequency of that specific \n item in the list.\n \n \"\"\"\n return lst.count(x) \n\ndef freq_of_specific_words(tokenized_list, list_of_interest):\n \"\"\"\n tokenized_list: A tokenized cropus\n list_of_interst: A set of unique words in the corpus\n \n returns \n \n dictionary: str:int --> count of each word\n \"\"\"\n freqDict = {}\n for word in list_of_interest:\n freqDict[word] = countX(tokenized_list, word)\n return freqDict\n\ndef show_wordcloud(dictionary, title, min_font = 10):\n \"\"\"\n generates a word cloud from a frequency dictionary\n \n Returns \n \n Nothing. Just plots \n \"\"\"\n wordcloud = WordCloud(min_font_size=min_font).generate_from_frequencies(dictionary)\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\")\n if title:\n plt.title(title)\n else:\n plt.title(\"Word Cloud\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n\ndef show_class_imbalance(df, title='Class Imbalance', PATH=None):\n \"\"\"\n SPECIFIC FOR THE CURRENT PROJECT\n \n Given the df will show a bar plot demonstrating the class imbalance between \n clickbait and non clickbait.\n \n \n \"\"\"\n ax = sns.barplot(x=[\"Normal\", \"Clickbait\"], y=df.groupby(['target']).target.count())\n ax.set_title(title, size=20)\n plt.xticks([0,1],[\"Normal\", \"Clickbait\"], size = 20)\n ax.set_ylabel(\"Document Count\", size=17)\n ax.set_xlabel(\"Article Class\", size=20)\n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n return ax\n \n \n \n \n \n# ================================= Viz Average word length ================================= \ndef get_average_word_length(title):\n \"\"\"\n \n Returns the average word length in a document\n \n \"\"\"\n return np.mean([len(word) for word in title.split()])\n\n\ndef word_lengths(df, ax=None, content='title', title='data', x_lim = [0,10]):\n \"\"\"\n \n Creates a histogram showing the difference in the distribution in word length between class.\n optionally can be given a matplotlib axes object.\n \n Returns \n \n seaborn axes object \n \n \"\"\"\n click_len = df[df.target == 1][content].apply(get_average_word_length)\n non_len = df[df.target == 0][content].apply(get_average_word_length)\n \n if not ax:\n fig, ax = plt.subplots()\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=True, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Average Word Length\", size = 14)\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =17)\n return ax;\n else:\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=False, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Average Word Length\", size=14)\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =17)\n return ax;\n\n\n# ================================= Viz title Length ================================= \ndef get_len(string):\n \"\"\"\n \n Returns the number of words in the string\n \n \n \"\"\"\n return len(tokenizer.tokenize(string))\n\ndef title_lengths(df, ax, content='title', title='data', x_lim = [0,100]):\n \"\"\"\n Displays class difference in class document word count as a histogram\n \n Returns\n \n matplotlib Axes object.\n \n \"\"\"\n click_len = df[df.target == 1][content].apply(get_len)\n non_len = df[df.target == 0][content].apply(get_len)\n\n for a, b in zip([click_len, non_len], ['Clickbait', 'Non-clickbait']):\n sns.distplot(a, bins=50, ax=ax, kde=False, label=b)\n ax.legend()\n ax.set_xlim(x_lim)\n ax.set_xlabel(\"Length of Title (words)\")\n ax.set_title(f\"Distribution of Title Length Between \\n Clickbait and Non-Clickbait News Headlines {title}\", size =10)\n return ax\n\n# ================================= Viz stopword differences ================================= \n\n\ndef remove_stopwords_tokenized(title):\n return ([word.lower() for word in tokenizer.tokenize(title) if word.lower() not in stop_words])\n\ndef stopword_proportion(title):\n tokenized = tokenizer.tokenize(title)\n return (len(tokenized) + 1)/(len(remove_stopwords_tokenized(title)) + 1)\n\ndef stopword_hist(df, stop_words, ax):\n \"\"\"\n Shows a histogram of the classes proportion of stopwords. \n \n Stopword content is between 1-2:\n \n This is because I wanted to avoid zero division errors so I added a 1 to the numerator and the denominator.\n returns a matplotlib axes object\n \n \"\"\"\n click_props = df[df.target == 1].title.apply(stopword_proportion)\n non_props = df[df.target == 0].title.apply(stopword_proportion)\n for a, b in zip([non_props, click_props], ['Normal','Clickbait']):\n sns.distplot(a, bins=30, ax=ax, kde=True, label=b)\n ax.legend()\n ax.set_ylabel(\"Density\", size=20)\n ax.set_xlim([0.5,3])\n ax.set_xlabel(\"Ratio of Stopwords\", size=20)\n ax.set_title(f\"Ratio of Stopwords Between \\n Clickbait and Non-Clickbait News Headlines\", size =15)\n return ax\n\n\ndef stopword_bar(df, stop_words, ax):\n \n \"\"\"\n Shows a histogram of the classes proportion of stopwords. \n \n Stopword content is between 1-2:\n \n This is because I wanted to avoid zero division errors so I added a 1 to the numerator and the denominator.\n \n Returns \n \n matplotlib axes object\n \n \n \"\"\"\n df_test = df.copy()\n df_test['prop'] = df.title.apply(stopword_proportion)\n sns.barplot(data=df_test, x='target', y='prop', ax=ax, ci=False)\n ax.set_title(\"Ratio of Stopwords Between Classes\", size=20)\n ax.set_ylim([1,2])\n ax.set_ylabel(\"Ratio\", size=20)\n ax.set_xlabel(\"Article Class\", size=20)\n plt.xticks(ticks=range(2),labels=['Normal','Clickbait'], size=20)\n return ax\n\n# ================================= Viz title Cardinality ================================= \n\ndef contains_cardinal(title):\n return any(char.isdigit() for char in title)\n\ndef proportion_with_cardinals(df, PATH):\n\n \"\"\"\n Shows a histogram of the classes proportion of documents containing cardinal numbers.\n \n Returns \n \n matplotlib axes object\n \n \n \"\"\"\n \n df_test = df.copy()\n df_test['cardinal'] = df.title.apply(contains_cardinal)\n\n click = df_test[df_test.target == 1]\n non = df_test[df_test.target == 0]\n click = click.groupby(['cardinal']).target.count()\n non = non.groupby(['cardinal']).target.count()\n \n non = non[1]/non[0] * 100\n click = click[1]/click[0] * 100\n # plot the results\n fig, ax = plt.subplots(figsize=(12,6))\n sns.barplot(x=['Normal', \"Clickbait\"], y=[non, click], ax=ax)\n plt.title(\"Percent of Titles Containing Cardinal Numbers\", size = 24)\n plt.xlabel(\"Article Class\", size=24)\n plt.ylabel(\"Percent %\", size = 24)\n plt.ylim(0, 100)\n plt.xticks([0,1], label=[\"Normal\", \"Clickbait\"], size=24)\n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n \n return ax\n\n\n\n# ================================= Viz title false positives/negatives ================================= \n\ndef get_false_positives(predictions, y_test):\n \"\"\"\n Returns a numpy array of index matched false negatives\n predictions --> binary or bool\n y_test --> binary or bool\n theshold \n \n returns a np.array\n \"\"\"\n comparisons = list(zip(y_test, predictions))\n return np.array([1 if (true == 0 and prediction == 1) else 0 for true, prediction in comparisons])\n\ndef get_false_negatives(predictions, y_test):\n \"\"\"\n Returns a numpy array of index matched false negatives\n predictions --> binary or bool\n y_test --> binary or bool\n theshold \n \n returns a np.array\n \"\"\"\n comparisons = list(zip(y_test, predictions))\n return np.array([1 if (true == 1 and prediction == 0) else 0 for true, prediction in comparisons])\n\n\n\n\n# ================================= Viz word clouds ================================= \n\ndef generate_wordcloud(dict_, title='WordCloud', PATH=None):\n \n \"\"\"\n Displays a word cloud of the frequency dictionary\n \n No return object\n \n \"\"\"\n wordcloud = WordCloud(min_font_size=10).generate_from_frequencies(dict_)\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(title, size = 24)\n plt.tight_layout(pad = 0) \n if PATH:\n plt.savefig(PATH, bbox_inches=\"tight\", transparent=True)\n plt.show() \n \n\n \n \n# ================================= Viz Difference and Intersection Word Clouds ================================= \n\ndef get_intersect(df, get_numbers=False):\n \n \"\"\"\n Returns the intersect of words between the click bait corpus and the non clickbait corpus\n \n Returns:\n \n click_set.intersection(non_set), click_tokenized\n \n \"\"\"\n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n return click_set.intersection(non_set), click_tokenized\n\ndef get_difference(df, click_as_base=True):\n \n \"\"\"\n Given a dataframe, returns a set of words that are unique to the the clickbait data set and then a list of all the words \n used in the clickbait dataset\n \"\"\"\n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n if click_as_base:\n return click_set.difference(non_set), click_tokenized \n else: \n return non_set.difference(click_set), non_tokenized\n \ndef visualize_intersection(df):\n \n \"\"\"\n Generates two wordclouds, for the intersect and one for the difference between the classes words frequencies\n \n \"\"\"\n \n click_corpus = \" \".join(df[df.target==1].title.to_list())\n non_corpus = \" \".join(df[df.target==0].title.to_list())\n \n tokenizer = RegexpTokenizer(r'[a-zA-Z0-9]+')\n \n click_tokenized = tokenizer.tokenize(click_corpus)\n non_tokenized = tokenizer.tokenize(non_corpus)\n\n fil_click = [word.lower() for word in click_tokenized if word.lower() not in pp.stop_words]\n fil_non = [word.lower() for word in non_tokenized if word.lower() not in pp.stop_words]\n \n non_set = set(fil_non)\n click_set = set(fil_click)\n \n # Generate sets of words\n diff = non_set.difference(click_set)\n overlap = non_set.intersection(click_set)\n \n # Generate word clouds of each\n def countX(lst, x): \n return lst.count(x) \n def freq_of_specific_words(tokenized_list, list_of_interest):\n freqDict = {}\n for word in list_of_interest:\n freqDict[word] = countX(tokenized_list, word)\n\n\n non_diff = {}\n for word in diff:\n non_diff[word] = countX(list(non_set), word)\n difference_frequency = sorted(non_diff.items(), reverse=True, key = (lambda x: x[1]))\n \n wordcloud = WordCloud(min_font_size=10).generate_from_frequencies(dict(difference_frequency))\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(\"Difference Between Click-Bait and Normal Headlines\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n \n \n click_diff = {}\n for word in overlap:\n click_diff[word] = countX(fil_click, word)\n\n difference_frequency = sorted(click_diff.items(), reverse=True, key = (lambda x: x[1]))\n wordcloud = WordCloud(min_font_size=5).generate_from_frequencies(dict(difference_frequency))\n plt.figure(figsize = (8, 8), facecolor = None) \n plt.imshow(wordcloud) \n plt.axis(\"off\") \n plt.title(\"Intersection Between Click-Bait and Normal Headlines\")\n plt.tight_layout(pad = 0) \n\n plt.show() \n \n \n \n \n \n# ================================= Viz Evaluation Metrics ================================= \n \n \ndef plot_cmatrix(actual, predictions, model, PATH = None):\n '''Takes in arrays of actual binary values and model predictions and generates and plots a confusion matrix'''\n cmatrix = confusion_matrix(actual, predictions)\n\n fig, ax = plt.subplots(figsize = (12,6))\n sns.heatmap(cmatrix, annot=True, fmt='g', ax=ax, cmap='Blues')\n ax.set_xticklabels(['Normal', 'Clickbait'])\n ax.set_yticklabels(['Normal', 'Clickbait'])\n ax.set_ylabel('Actual', size=15)\n ax.set_xlabel('Predicted', size=15)\n ax.set_title(f'Confusion Matrix for {model} Predictions', size =18)\n if PATH:\n plt.savefig(PATH, bbox_inches = \"tight\", transparent=True)\n \n return plt.show()\n\ndef plot_roc_curve(actual, predictions, model = \"ROC Curve\", PATH=None):\n '''Takes in arrays of actual binary values and model predictions and generates and plots an ROC curve'''\n \n fpr, tpr, threshholds = roc_curve(actual, predictions)\n \n sns.set_style('darkgrid', {'axes.facecolor': '0.9'})\n \n print('AUC: {}'.format(auc(fpr, tpr)))\n plt.figure(figsize=(10, 8))\n lw = 2\n plt.plot(fpr, tpr, color='darkorange',\n lw=lw, label=model)\n plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n try:\n plt.ylim([0.0, 1.05])\n except:\n print(\"plt.ylim throwing an type error\")\n plt.yticks([i/20.0 for i in range(21)], size=17)\n plt.xticks([i/20.0 for i in range(21)], rotation=45, size=17)\n plt.xlabel('False Positive Rate', size=24)\n plt.ylabel('True Positive Rate', size=24)\n plt.title(f'{model} ROC Curve', size = 24)\n plt.legend(loc='lower right', prop = {\"size\" : 20})\n if PATH:\n plt.savefig(PATH, bbox_inches='tight', transparent=True)\n \n return plt.show()\n\n\n\n\n# ================================= Viz Final Evaluation Metrics ================================= \n\ndef generate_prediction_matrix(list_of_models, list_of_tfidf, X_test):\n \n \"\"\"\n This is a helper function that creates a prediction matrix to feed into either \n roc auc curve or a voting classifier\n \n \"\"\"\n n = len(X_test)\n m = len(list_of_models)\n \n prediction_matrix = np.ones((n,m))\n \n for i, model in enumerate(list_of_models):\n print(f\"Generating predictions for model: {i+1}\")\n model = list_of_models[i]\n tfidf = list_of_tfidf[i]\n try:\n X_test_tfidf = tfidf.transform(X_test)\n predictions = model.predict_proba(X_test_tfidf)[:,1]\n except Exception as e:\n print(str(e))\n print(predictions)\n prediction_matrix[:,i] *= predictions\n \n return prediction_matrix\n\n\ndef plot_final_roc(prediction_matrix, model_names, y_test, PATH = None):\n \"\"\"\n Given a prediction matrix generated using generate_prediction_matrix() and the matching\n model names, will return a roc auc curve containing all of the models predictions\n \n returns\n \n Nothing. Just shows an image. Don't be greedy.\n \n \"\"\"\n plt.figure(figsize=(10, 8))\n for i, model in enumerate(model_names): \n predictions = prediction_matrix[:,i]\n fpr, tpr, threshholds = roc_curve(y_test, predictions)\n sns.set_style('darkgrid', {'axes.facecolor': '0.9'})\n lw = 2\n plt.plot(fpr, tpr,\n lw=lw, label=f'{model_names[i]} AUC: {round(auc(fpr, tpr), 3)}')\n plt.plot([0, 1], [0, 1], lw=lw, linestyle='--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.yticks([i/20.0 for i in range(21)], size = 14)\n plt.xticks([i/20.0 for i in range(21)], rotation = 45, size = 14)\n plt.xlabel('False Positive Rate', size =16)\n plt.ylabel('True Positive Rate', size =16)\n plt.title('ROC Curve', size = 20)\n plt.legend(loc='lower right', prop = {\"size\" : 20})\n if PATH:\n plt.savefig(PATH, bbox_inches='tight', transparent = True)\n plt.show()","repo_name":"SlimHintz/bait-n-switch","sub_path":"src/modules/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":18621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38856241687","text":"from rest_framework import serializers\n\nfrom apps.core.serializers import DynamicFieldsModelSerializer\nfrom apps.about.models import FAQ, Company, ContactForm\n\n\nclass FAQSerializer(DynamicFieldsModelSerializer):\n\n\tclass Meta:\n\t\tmodel = FAQ\n\t\tfields = (\n\t\t\t\"company\", \"question\", \"answer\"\n\t\t)\n\n\nclass CompanySerializer(DynamicFieldsModelSerializer):\n\tstop_plan_pdf = serializers.FileField(use_url=True)\n\tfaqs = serializers.SerializerMethodField()\n\n\tdef get_faqs(self, instance: Company):\n\t\treturn FAQSerializer(\n\t\t\t\tinstance.faqs.all(),\n\t\t\t\texclude=(\"company\",),\n\t\t\t\tmany=True\n\t\t\t).data\n\t\n\tclass Meta:\n\t\tmodel = Company\n\t\tfields = (\n\t\t\t\"home_page_title\", \"home_page_text\",\n\t\t\t\"contact_number\", \"about_the_company\",\n\t\t\t\"help_number\",\n\t\t\t\"address\", \"faqs\", \"stop_plan_pdf\",\n\t\t\t\"terms_and_conditions\", \"privacy_policy\",\n\t\t\t\"banner_title\", \"banner_text\"\n\t\t)\n\n\nclass ContactFormSerializer(serializers.ModelSerializer):\n\n\tuser = serializers.HiddenField(default=serializers.CurrentUserDefault())\n\n\tclass Meta:\n\t\tmodel = ContactForm\n\t\tfields = (\n\t\t\t\"id\", \"user\", \"name\", \"email\",\n\t\t\t\"phone_number\", \"message\", \"created\"\n\t\t)\n","repo_name":"aarsh-zartek/prosit","sub_path":"apps/about/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73569315685","text":"#!/usr/bin/env python3\n\nimport shelve, pyperclip, sys\n\ndef usage():\n print('Usage: mcb.pyw [save [name]|list|key]')\n sys.exit(0)\n\nif len(sys.argv) < 2:\n usage()\n\nshelf = shelve.open('mcb')\n\ncommand = sys.argv[1]\nif len(sys.argv) == 3 and command == 'save':\n key = sys.argv[2]\n shelf[key] = pyperclip.paste()\n print(f'saved clipboard as {key}')\nelif command == 'list':\n print(str(list(shelf.keys())))\nelif len(sys.argv) == 3 and command == 'delete':\n key = sys.argv[2]\n del shelf[key]\n print(f'deleted \"{key}\"')\nelif command in shelf:\n pyperclip.copy(shelf[command])\n print(f'loaded {command}')\nelse:\n print(f'Unknown command or key {command}')\n\nshelf.close()\n\n","repo_name":"dave-burke/python-sample","sub_path":"mcb.pyw","file_name":"mcb.pyw","file_ext":"pyw","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11223560914","text":"from flask import render_template, flash, redirect, url_for, request\r\nfrom app import app\r\n\r\nfrom flask_bootstrap import Bootstrap\r\n\r\n# Redirect to \"next\" page\r\nfrom werkzeug.urls import url_parse\r\nimport plotly\r\nimport plotly.graph_objs as go\r\nimport plotly.express as px\r\n\r\nimport json\r\n\r\nimport pandas as pd\r\n\r\n\r\nx = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']#np.linspace(0, 1, N)\r\nunits = [1530, 5117, 9779, 9187, 13817, 10769, 5761, 15210, 9050, 19720, 17200, 20700] #np.random.randn(N)\r\ndf = pd.DataFrame({'x': x, 'units': units}) # creating a sample dataframe\r\ndf['earnings'] = 3*df['units']\r\n\r\nstores = ['Costco', 'Freshco', 'Metro', 'Food Basics', 'Shopers', 'Walmart']\r\nFoodWasted = ['47%', '30%', '52%', '37%', '43%', '32%']\r\nConsumers = [200, 400, 672, 987, 87, 176]\r\ndf_stores = pd.DataFrame({'Store': stores, 'Food Wasted': FoodWasted, 'Consumers': Consumers})\r\n\r\nHotProducts_name = ['Milk', 'Eggs', 'Yogurt', 'Almond Milk', 'Cheese', 'Ice Cream', 'Sour Cream']\r\nHotProducts_units = [470, 3000, 5290, 370, 413, 3221, 322]\r\nHotProducts_earnings = [2210, 4050, 6720, 987, 1817, 1769, 1761]\r\ndf_HotProducts = pd.DataFrame({'Product':HotProducts_name, 'Units': HotProducts_units, 'Earnings': HotProducts_earnings })\r\n\r\nsavings_Product = ['Milk', 'Eggs', 'Yogurt', 'Red Beans', 'Cheese', 'Ham', 'Tomatos']\r\nsavings_CAD = [22, 4, 2, 7, 8, 17, 11]\r\ndf_savings = pd.DataFrame({'Product': savings_Product, 'Savings (CAD)': savings_CAD})\r\n\r\nfoodDist_prod = ['Dairy', 'Vegetables', 'Fruit', 'Bakery', 'Meat', 'Others']\r\nfoodDist_value = [7, 30, 15, 9, 6, 20]\r\ndf_foodDist = pd.DataFrame({'Product': foodDist_prod, 'Value': foodDist_value})\r\n\r\nSavingsOv_product = [ 'Grain', 'Meat', 'Dairy', 'Produce']\r\nSavingsOv_consumer = [30, 50, 37, 20]\r\nSavingsOv_neigh = [15, 64, 23, 23]\r\nSavingsOv_city = [12, 53, 30, 55]\r\ndf_SavingsOverview = pd.DataFrame({'Product': SavingsOv_product, 'Consumer': SavingsOv_consumer, 'Neighbourhood': SavingsOv_neigh, 'City':SavingsOv_city })\r\n\r\n\r\n\r\n@app.route('/')\r\n@app.route('/index')\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n@app.route('/ConsumerView')\r\ndef ConsumerView():\r\n Fig01 = create_pieFoodDist()\r\n Fig02 = create_radar()\r\n return render_template('ConsumerView.html', user = 1, plot01=Fig01, plot02=Fig02)\r\n\r\n@app.route('/RetailerView')\r\ndef RetailerView():\r\n figure01 = create_plot()\r\n return render_template('RetailerView.html', user = 2, plot=figure01)\r\n\r\n@app.route('/ConsumerSavings')\r\ndef ConsumerSavings():\r\n figure01 = create_plotSavings()\r\n return render_template('ConsumerSavings.html', user = 1, plot=figure01)\r\n\r\n@app.route('/ConsumerProducts')\r\ndef ConsumerProducts():\r\n return render_template('ConsumerProducts.html', user = 1)\r\n\r\n@app.route('/ConsumerRewards')\r\ndef ConsumerRewards():\r\n return render_template('ConsumerRewards.html', user = 1)\r\n\r\n@app.route('/RetailerHotProducts')\r\ndef RetailerHotProducts():\r\n figure03 = create_pieProducts()\r\n figure04 = create_plotProducts()\r\n return render_template('RetailerHotProducts.html', user = 2 , plot01=figure03, plot02=figure04, df_HotProducts = df_HotProducts)\r\n\r\n@app.route('/RetailerPredictions')\r\ndef RetailerPredictions():\r\n figure01 = create_plot()\r\n return render_template('RetailerPredictions.html', user = 2, plot=figure01, dfPredicitons = df )\r\n\r\n@app.route('/RetailerStore')\r\ndef RetailerStore():\r\n figure02 = create_pie()\r\n return render_template('RetailerStore.html', user = 2, plot=figure02, df_stores = df_stores)\r\n\r\n\r\n@app.route('/Dashboard01')\r\ndef Dashboard01():\r\n return render_template('Dashboard01.html', user = 2)\r\n\r\n\r\n\r\ndef create_plot():\r\n fig01 = px.scatter(df, x='x', y='earnings', template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_xaxes(showgrid=False, zeroline=True)\r\n fig01.update_yaxes(showgrid=True, zeroline=False)\r\n fig01.update_traces(marker=dict(size=12, color='#ff8200'), hovertemplate=None )\r\n fig01.data[0].update(mode='markers+lines', line_shape='spline')\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n # hoverlabel=dict( bgcolor=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n \"\"\"\r\n fig01 = go.Scatter(x=df['x'], y=df['y'], mode='lines+markers',\r\n line=dict(color='#ff8200', width=4), line_shape='spline',\r\n marker=dict(color='#ff8200', size=10, symbol=0)\r\n\r\n )\r\n data = [fig01]\r\n\r\n data01 = go.Figure(\r\n data=[fig01],\r\n layout=go.Layout(\r\n title=go.layout.Title(text=\"A Figure Specified By A Graph Object\")\r\n )\r\n )\r\n\r\n\r\n data02 = go.Figure(\r\n data=[fig01],\r\n layout=go.Layout(\r\n xaxis= {'showgrid': False}\r\n )\r\n )\r\n \"\"\"\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\n\r\n\r\ndef create_pie():\r\n fig01 = px.pie(df_stores, values = 'Consumers', names='Store')#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_pieProducts():\r\n fig01 = px.pie(df_HotProducts, values = 'Units', names='Product', hover_data=[\"Earnings\"])#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_plotProducts():\r\n fig01 = px.bar(df_HotProducts, x='Product', y='Earnings', template=\"plotly_white\", color='Product')#labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"Earnings\"])\r\n #fig01.update_xaxes(showgrid=False, zeroline=True)\r\n #fig01.update_yaxes(showgrid=True, zeroline=False)\r\n #fig01.update_traces(marker=dict(size=12, color='#ff8200'), hovertemplate=None )\r\n #fig01.data[0].update(mode='markers+lines', line_shape='spline')\r\n #fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\ndef create_plotSavings():\r\n fig01 = px.bar(df_savings, x='Product', y='Savings (CAD)', template=\"plotly_white\", color='Product')#, labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"Earnings\"])\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n\r\n return graphJSON\r\n\r\n\r\ndef create_pieFoodDist():\r\n fig01 = px.pie(df_foodDist, values = 'Value', names='Product')#, template=\"plotly_white\", labels = {'x':'Month', 'earnings':'Earnings (CAD)'}, hover_data=[\"earnings\"])\r\n fig01.update_layout(hovermode=\"x\", hoverlabel=dict( font_color=\"white\", font_size=16, font_family=\"Rockwell\"))\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n\r\ndef create_radar():\r\n fig01 = px.line_polar(df_SavingsOverview, r='Consumer', theta='Product', line_close=True )\r\n fig01.update_traces(fill='toself', line=dict(color='blue'), name='Consumer', showlegend = True)\r\n\r\n fig02 = px.line_polar(df_SavingsOverview, r='Neighbourhood', theta='Product', line_close=True)\r\n fig02.update_traces(fill='toself', line=dict(color='green'), name='Neighbourhood', showlegend = True)\r\n\r\n fig03 = px.line_polar(df_SavingsOverview, r='City', theta='Product', line_close=True)\r\n fig03.update_traces(fill='toself', line=dict(color='#ff8200'), name='City', showlegend = True)\r\n\r\n fig01.add_trace(fig02.data[0])\r\n fig01.add_trace(fig03.data[0])\r\n\r\n\r\n\r\n graphJSON = json.dumps(fig01, cls=plotly.utils.PlotlyJSONEncoder)\r\n return graphJSON\r\n","repo_name":"smlopezza/Smartsito","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":8151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"15124367670","text":"from flask import Flask, request, Response\nimport jsonpickle\nimport numpy as np\nimport cv2\nimport os\nfrom datetime import datetime\nimport glob\n\n# Initialize the Flask application\napp = Flask(__name__)\n\n\n# Heart beat for checking is server is up.\n@app.route('/image/heart_beat', methods=['GET'])\ndef heat_beat():\n\tresponse = {\"message\": \"ok\"}\n\tpickled_response = jsonpickle.encode(response)\n\treturn Response(response=pickled_response, status=200, mimetype='application/json')\n\n\n# Function to create the time lapse video\n@app.route('/image/create_time_lapse', methods=['POST'])\ndef create_time_lapse():\n\n\timages = sorted(glob.glob('images/*.jpg'))\n\tprint(\"Total number of images: {}\".format(len(images)))\n\tmake_directory_if_missing(\"videos\")\n\t# Calculate frame rate in frames per second\n\t# if len(images) < 30:\n\t# \tframe_rate = 2\n\t# else:\n\t# \tframe_rate = 30\n\n\tframe_rate = 30\n\tdata = request.json\n\tif \"frame_rate\" in data.keys():\n\t\tframe_rate = data[\"frame_rate\"]\n\n\twidth, height = get_image_size(images[0])\n\tif \"width\" in data.keys():\n\t\twidth = data[\"width\"]\n\tif \"height\" in data.keys():\n\t\theight = data[\"height\"]\n\tfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\n\tvideo_name = \"videos/\" + get_video_name(\"\")\n\tif \"name_suffix\" in data.keys():\n\t\tvideo_name = \"videos/\" + get_video_name(\"_\" + data[\"name_suffix\"])\n\tprint(\"Generating video name: {}, width: {}, height: {}, frame rate: {}\".format(video_name, width, height, frame_rate))\n\tvideo = cv2.VideoWriter(video_name, fourcc, frame_rate, (width, height))\n\n\tfor ctr in range(len(images)):\n\t\t# Load image\n\t\timage = cv2.imread(images[ctr])\n\t\t# Match the size of the image.\n\t\timage = cv2.resize(image, (width, height))\n\t\tvideo.write(image)\n\n\tvideo.release()\n\tprint(\"Created time lapse.\")\n\n\tresponse = {\"message\": \"Created time lapse from {} images.\".format(len(images))}\n\tpickled_response = jsonpickle.encode(response)\n\treturn Response(response=pickled_response, status=200, mimetype='application/json')\n\n\n# route http posts to this method\n@app.route('/image/add', methods=['POST'])\ndef receive_image():\n\tr = request\n\t# Convert string of image data to unit8\n\tnp_array = np.frombuffer(r.data, np.uint8)\n\n\t# decode image\n\timage = cv2.imdecode(np_array, cv2.IMREAD_COLOR)\n\timage_name = get_image_name()\n\n\tmake_directory_if_missing(\"images\")\n\n\t# Save the image\n\tprint(\"Saving image as: {}\".format(\"images/\" + image_name))\n\tcv2.imwrite(\"images/\" + image_name, image)\n\n\t# Create the response\n\tresponse = {'message': 'image {} received. size={}x{}'.format(image_name, image.shape[1], image.shape[0])}\n\n\t# encode response using json pickle\n\tresponse_pickled = jsonpickle.encode(response)\n\n\treturn Response(response=response_pickled, status=200, mimetype='application/json')\n\n\ndef get_image_size(image_raw):\n\timage = cv2.imread(image_raw)\n\treturn image.shape[1], image.shape[0]\n\n\ndef make_directory_if_missing(name):\n\tif not os.path.exists(name):\n\t\tprint(\"Making new directory named {}\".format(name))\n\t\tos.makedirs(name)\n\n\ndef get_image_name():\n\t# Image name format TL_+\n\tnow = datetime.now()\n\tdate_string = now.strftime(\"%d-%m-%Y_%H-%M-%S\")\n\treturn \"TL_\" + date_string + \".jpg\"\n\n\ndef get_video_name(suffix):\n\tnow = datetime.now()\n\tdate_string = now.strftime(\"%d-%m-%Y_%H-%M\")\n\treturn \"TL_Video_\" + date_string + suffix + \".mp4\"\n\n\n# start flask app\napp.run(host=\"0.0.0.0\", port=5000)\n\n","repo_name":"ataffe/Remote-Time-Lapse","sub_path":"receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1138422740","text":"from django.db import models\nfrom django.conf import settings\nfrom django.shortcuts import reverse\n# Create your models here.\n\n\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=150, db_index=True)\n slug = models.SlugField(max_length=150, unique=True ,db_index=True)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('name', )\n verbose_name = 'category'\n verbose_name_plural = 'categories'\n\n def __str__(self):\n return self.name\n\n\n\nclass Item(models.Model):\n category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE)\n name = models.CharField(max_length=100, db_index=True)\n slug = models.SlugField(null=True, db_index=True)\n cost_price = models.DecimalField(max_digits=10, decimal_places=2)\n sealing_price = models.DecimalField(max_digits=10, decimal_places=2)\n discount_price = models.FloatField(blank=True, null=True)\n available = models.BooleanField(default=True)\n stock = models.PositiveIntegerField()\n description = models.TextField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n image = models.ImageField(upload_to=\"profile-images\", blank=True)\n\n class Meta:\n ordering = ('name',)\n verbose_name ='item'\n verbose_name_plural = 'items'\n index_together = (('id', 'slug'),)\n\n def __str__(self):\n return self.name\n\n def get_absolute_url(self):\n return reverse(\"item:detail\", kwargs={\n 'slug': self.slug\n })","repo_name":"vanperbles/Safowood_Supply_LTD","sub_path":"Product/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10480545168","text":"import neighbor as nb\nimport nodeFunction as nF\n\n\nclass Node:\n idNum = -1\n posX = 0\n posY = 0\n posZ = 0\n nbs = {}\n\n def setNode(self, idNum, posX, posY, posZ):\n self.idNum = idNum\n self.posX = posX\n self.posY = posY\n self.posZ = posZ\n\n def findNeighbor(self, neighborID):\n result = self.nbs.get(neighborID)\n if result is None:\n return False\n return True\n\n def calculatePos(self):\n totalMomentum = [0, 0]\n for nb in self.nbs:\n (nx, ny, _) = self.nbs[nb].getNeighborPos()\n (mx, my) = nF.calculateMomentum(self.posX, self.posY, nx, ny)\n totalMomentum[0] += mx\n totalMomentum[1] += my\n newPosX = self.posX + totalMomentum[0]\n newPosY = self.posY + totalMomentum[1]\n\n return newPosX, newPosY\n\n def moveNode(self):\n (newPosX, newPosY) = self.calculatePos()\n self.posX = newPosX\n self.posY = newPosY\n\n def updateNeighbor(self, neighbor):\n neighborID = neighbor.getNeighborID()\n (neighborPosX, neighborPosY, neighborPosZ) = neighbor.getNeighborPos()\n self.nbs[neighborID] = nb.Neighbor(neighborID, neighborPosX, neighborPosY, neighborPosZ)\n\n def getNodePos(self):\n return self.posX, self.posY, self.posZ\n\n def getNodeID(self):\n return self.idNum\n\n def clearNeighbors(self):\n self.nbs.clear()\n","repo_name":"SungJaeYu/SpreadNodes","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38441247316","text":"#!/usr/bin/python\n#\n# This file is part of Ansible\n#\n# Ansible 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 3 of the License, or\n# (at your option) any later version.\n#\n# Ansible is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Ansible. If not, see .\n#\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'network'}\n\n\nDOCUMENTATION = '''\n---\nmodule: nxos_igmp_interface\nextends_documentation_fragment: nxos\nversion_added: \"2.2\"\nshort_description: Manages IGMP interface configuration.\ndescription:\n - Manages IGMP interface configuration settings.\nauthor:\n - Jason Edelman (@jedelman8)\n - Gabriele Gerbino (@GGabriele)\nnotes:\n - Tested against NXOSv 7.3.(0)D1(1) on VIRL\n - When C(state=default), supported params will be reset to a default state.\n These include C(version), C(startup_query_interval),\n C(startup_query_count), C(robustness), C(querier_timeout), C(query_mrt),\n C(query_interval), C(last_member_qrt), C(last_member_query_count),\n C(group_timeout), C(report_llg), and C(immediate_leave).\n - When C(state=absent), all configs for C(oif_prefix), C(oif_source), and\n C(oif_routemap) will be removed.\n - PIM must be enabled to use this module.\n - This module is for Layer 3 interfaces.\n - Route-map check not performed (same as CLI) check when configuring\n route-map with 'static-oif'\n - If restart is set to true with other params set, the restart will happen\n last, i.e. after the configuration takes place.\noptions:\n interface:\n description:\n - The full interface name for IGMP configuration.\n e.g. I(Ethernet1/2).\n required: true\n version:\n description:\n - IGMP version. It can be 2 or 3.\n required: false\n default: null\n choices: ['2', '3']\n startup_query_interval:\n description:\n - Query interval used when the IGMP process starts up.\n The range is from 1 to 18000. The default is 31.\n required: false\n default: null\n startup_query_count:\n description:\n - Query count used when the IGMP process starts up.\n The range is from 1 to 10. The default is 2.\n required: false\n default: null\n robustness:\n description:\n - Sets the robustness variable. Values can range from 1 to 7.\n The default is 2.\n required: false\n default: null\n querier_timeout:\n description:\n - Sets the querier timeout that the software uses when deciding\n to take over as the querier. Values can range from 1 to 65535\n seconds. The default is 255 seconds.\n required: false\n default: null\n query_mrt:\n description:\n - Sets the response time advertised in IGMP queries.\n Values can range from 1 to 25 seconds. The default is 10 seconds.\n required: false\n default: null\n query_interval:\n description:\n - Sets the frequency at which the software sends IGMP host query\n messages. Values can range from 1 to 18000 seconds.\n he default is 125 seconds.\n required: false\n default: null\n last_member_qrt:\n description:\n - Sets the query interval waited after sending membership reports\n before the software deletes the group state. Values can range\n from 1 to 25 seconds. The default is 1 second.\n required: false\n default: null\n last_member_query_count:\n description:\n - Sets the number of times that the software sends an IGMP query\n in response to a host leave message.\n Values can range from 1 to 5. The default is 2.\n required: false\n default: null\n group_timeout:\n description:\n - Sets the group membership timeout for IGMPv2.\n Values can range from 3 to 65,535 seconds.\n The default is 260 seconds.\n required: false\n default: null\n report_llg:\n description:\n - Configures report-link-local-groups.\n Enables sending reports for groups in 224.0.0.0/24.\n Reports are always sent for nonlink local groups.\n By default, reports are not sent for link local groups.\n required: false\n choices: ['true', 'false']\n default: false\n immediate_leave:\n description:\n - Enables the device to remove the group entry from the multicast\n routing table immediately upon receiving a leave message for\n the group. Use this command to minimize the leave latency of\n IGMPv2 group memberships on a given IGMP interface because the\n device does not send group-specific queries.\n The default is disabled.\n required: false\n choices: ['true', 'false']\n default: false\n oif_routemap:\n description:\n - Configure a routemap for static outgoing interface (OIF).\n required: false\n default: null\n oif_prefix:\n description:\n - Configure a prefix for static outgoing interface (OIF).\n required: false\n default: null\n oif_source:\n description:\n - Configure a source for static outgoing interface (OIF).\n required: false\n default: null\n restart:\n description:\n - Restart IGMP.\n required: false\n choices: ['true', 'false']\n default: null\n state:\n description:\n - Manages desired state of the resource.\n required: false\n default: present\n choices: ['present', 'default']\n'''\nEXAMPLES = '''\n- nxos_igmp_interface:\n interface: ethernet1/32\n startup_query_interval: 30\n state: present\n username: \"{{ un }}\"\n password: \"{{ pwd }}\"\n host: \"{{ inventory_hostname }}\"\n'''\n\nRETURN = '''\nproposed:\n description: k/v pairs of parameters passed into module\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"router_id\": \"1.1.1.1\", \"vrf\": \"test\"}\nexisting:\n description: k/v pairs of existing BGP configuration\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"bestpath_always_compare_med\": false,\n \"bestpath_aspath_multipath_relax\": false,\n \"bestpath_compare_neighborid\": false,\n \"bestpath_compare_routerid\": false,\n \"bestpath_cost_community_ignore\": false,\n \"bestpath_med_confed\": false,\n \"bestpath_med_missing_as_worst\": false,\n \"bestpath_med_non_deterministic\": false, \"cluster_id\": \"\",\n \"confederation_id\": \"\", \"confederation_peers\": \"\",\n \"graceful_restart\": true, \"graceful_restart_helper\": false,\n \"graceful_restart_timers_restart\": \"120\",\n \"graceful_restart_timers_stalepath_time\": \"300\", \"local_as\": \"\",\n \"log_neighbor_changes\": false, \"maxas_limit\": \"\",\n \"neighbor_down_fib_accelerate\": false, \"reconnect_interval\": \"60\",\n \"router_id\": \"11.11.11.11\", \"suppress_fib_pending\": false,\n \"timer_bestpath_limit\": \"\", \"timer_bgp_hold\": \"180\",\n \"timer_bgp_keepalive\": \"60\", \"vrf\": \"test\"}\nend_state:\n description: k/v pairs of BGP configuration after module execution\n returned: always\n type: dict\n sample: {\"asn\": \"65535\", \"bestpath_always_compare_med\": false,\n \"bestpath_aspath_multipath_relax\": false,\n \"bestpath_compare_neighborid\": false,\n \"bestpath_compare_routerid\": false,\n \"bestpath_cost_community_ignore\": false,\n \"bestpath_med_confed\": false,\n \"bestpath_med_missing_as_worst\": false,\n \"bestpath_med_non_deterministic\": false, \"cluster_id\": \"\",\n \"confederation_id\": \"\", \"confederation_peers\": \"\",\n \"graceful_restart\": true, \"graceful_restart_helper\": false,\n \"graceful_restart_timers_restart\": \"120\",\n \"graceful_restart_timers_stalepath_time\": \"300\", \"local_as\": \"\",\n \"log_neighbor_changes\": false, \"maxas_limit\": \"\",\n \"neighbor_down_fib_accelerate\": false, \"reconnect_interval\": \"60\",\n \"router_id\": \"1.1.1.1\", \"suppress_fib_pending\": false,\n \"timer_bestpath_limit\": \"\", \"timer_bgp_hold\": \"180\",\n \"timer_bgp_keepalive\": \"60\", \"vrf\": \"test\"}\nupdates:\n description: commands sent to the device\n returned: always\n type: list\n sample: [\"router bgp 65535\", \"vrf test\", \"router-id 1.1.1.1\"]\nchanged:\n description: check to see if a change was made on the device\n returned: always\n type: boolean\n sample: true\n'''\n\nfrom ansible.module_utils.nxos import get_config, load_config, run_commands\nfrom ansible.module_utils.nxos import nxos_argument_spec, check_args\nfrom ansible.module_utils.basic import AnsibleModule\n\nimport re\n\ndef execute_show_command(command, module, command_type='cli_show'):\n if command_type == 'cli_show_ascii':\n cmds = [{\n 'command': command,\n 'output': 'text',\n }]\n else:\n cmds = [{\n 'command': command,\n 'output': 'json',\n }]\n\n return run_commands(module, cmds)\n\n\ndef get_interface_mode(interface, intf_type, module):\n command = 'show interface {0}'.format(interface)\n interface = {}\n mode = 'unknown'\n\n if intf_type in ['ethernet', 'portchannel']:\n body = execute_show_command(command, module)[0]\n interface_table = body['TABLE_interface']['ROW_interface']\n mode = str(interface_table.get('eth_mode', 'layer3'))\n if mode == 'access' or mode == 'trunk':\n mode = 'layer2'\n elif intf_type == 'loopback' or intf_type == 'svi':\n mode = 'layer3'\n return mode\n\n\ndef get_interface_type(interface):\n if interface.upper().startswith('ET'):\n return 'ethernet'\n elif interface.upper().startswith('VL'):\n return 'svi'\n elif interface.upper().startswith('LO'):\n return 'loopback'\n elif interface.upper().startswith('MG'):\n return 'management'\n elif interface.upper().startswith('MA'):\n return 'management'\n elif interface.upper().startswith('PO'):\n return 'portchannel'\n else:\n return 'unknown'\n\n\ndef apply_key_map(key_map, table):\n new_dict = {}\n for key, value in table.items():\n new_key = key_map.get(key)\n if new_key:\n value = table.get(key)\n if value:\n new_dict[new_key] = value\n else:\n new_dict[new_key] = value\n return new_dict\n\n\ndef flatten_list(command_lists):\n flat_command_list = []\n for command in command_lists:\n if isinstance(command, list):\n flat_command_list.extend(command)\n else:\n flat_command_list.append(command)\n return flat_command_list\n\n\ndef get_igmp_interface(module, interface):\n command = 'show ip igmp interface {0}'.format(interface)\n igmp = {}\n\n key_map = {\n 'IGMPVersion': 'version',\n 'ConfiguredStartupQueryInterval': 'startup_query_interval',\n 'StartupQueryCount': 'startup_query_count',\n 'RobustnessVariable': 'robustness',\n 'ConfiguredQuerierTimeout': 'querier_timeout',\n 'ConfiguredMaxResponseTime': 'query_mrt',\n 'ConfiguredQueryInterval': 'query_interval',\n 'LastMemberMTR': 'last_member_qrt',\n 'LastMemberQueryCount': 'last_member_query_count',\n 'ConfiguredGroupTimeout': 'group_timeout'\n }\n\n body = execute_show_command(command, module)[0]\n\n if body:\n resource = body['TABLE_vrf']['ROW_vrf']['TABLE_if']['ROW_if']\n igmp = apply_key_map(key_map, resource)\n report_llg = str(resource['ReportingForLinkLocal']).lower()\n if report_llg == 'true':\n igmp['report_llg'] = True\n elif report_llg == 'false':\n igmp['report_llg'] = False\n\n immediate_leave = str(resource['ImmediateLeave']).lower() # returns en or dis\n if immediate_leave == 'en' or immediate_leave == 'true':\n igmp['immediate_leave'] = True\n elif immediate_leave == 'dis' or immediate_leave == 'false':\n igmp['immediate_leave'] = False\n\n # the next block of code is used to retrieve anything with:\n # ip igmp static-oif *** i.e.. could be route-map ROUTEMAP\n # or PREFIX source , etc.\n command = 'show run interface {0} | inc oif'.format(interface)\n\n body = execute_show_command(\n command, module, command_type='cli_show_ascii')[0]\n\n staticoif = []\n if body:\n split_body = body.split('\\n')\n route_map_regex = ('.*ip igmp static-oif route-map\\s+'\n '(?P\\S+).*')\n prefix_source_regex = ('.*ip igmp static-oif\\s+(?P'\n '((\\d+.){3}\\d+))(\\ssource\\s'\n '(?P\\S+))?.*')\n\n for line in split_body:\n temp = {}\n try:\n match_route_map = re.match(route_map_regex, line, re.DOTALL)\n route_map = match_route_map.groupdict()['route_map']\n except AttributeError:\n route_map = ''\n\n try:\n match_prefix_source = re.match(\n prefix_source_regex, line, re.DOTALL)\n prefix_source_group = match_prefix_source.groupdict()\n prefix = prefix_source_group['prefix']\n source = prefix_source_group['source']\n except AttributeError:\n prefix = ''\n source = ''\n\n if route_map:\n temp['route_map'] = route_map\n if prefix:\n temp['prefix'] = prefix\n if source:\n temp['source'] = source\n if temp:\n staticoif.append(temp)\n\n igmp['oif_routemap'] = None\n igmp['oif_prefix_source'] = []\n\n if staticoif:\n if len(staticoif) == 1 and staticoif[0].get('route_map'):\n igmp['oif_routemap'] = staticoif[0]['route_map']\n else:\n igmp['oif_prefix_source'] = staticoif\n\n return igmp\n\n\ndef config_igmp_interface(delta, found_both, found_prefix):\n CMDS = {\n 'version': 'ip igmp version {0}',\n 'startup_query_interval': 'ip igmp startup-query-interval {0}',\n 'startup_query_count': 'ip igmp startup-query-count {0}',\n 'robustness': 'ip igmp robustness-variable {0}',\n 'querier_timeout': 'ip igmp querier-timeout {0}',\n 'query_mrt': 'ip igmp query-max-response-time {0}',\n 'query_interval': 'ip igmp query-interval {0}',\n 'last_member_qrt': 'ip igmp last-member-query-response-time {0}',\n 'last_member_query_count': 'ip igmp last-member-query-count {0}',\n 'group_timeout': 'ip igmp group-timeout {0}',\n 'report_llg': 'ip igmp report-link-local-groups',\n 'immediate_leave': 'ip igmp immediate-leave',\n 'oif_prefix_source': 'ip igmp static-oif {0} source {1} ',\n 'oif_routemap': 'ip igmp static-oif route-map {0}',\n 'oif_prefix': 'ip igmp static-oif {0}',\n }\n\n commands = []\n command = None\n\n for key, value in delta.items():\n if key == 'oif_source' or found_both or found_prefix:\n pass\n elif key == 'oif_prefix':\n if delta.get('oif_source'):\n command = CMDS.get('oif_prefix_source').format(\n delta.get('oif_prefix'), delta.get('oif_source'))\n else:\n command = CMDS.get('oif_prefix').format(\n delta.get('oif_prefix'))\n elif value:\n command = CMDS.get(key).format(value)\n elif not value:\n command = 'no {0}'.format(CMDS.get(key).format(value))\n\n if command:\n if command not in commands:\n commands.append(command)\n command = None\n\n return commands\n\n\ndef get_igmp_interface_defaults():\n version = '2'\n startup_query_interval = '31'\n startup_query_count = '2'\n robustness = '2'\n querier_timeout = '255'\n query_mrt = '10'\n query_interval = '125'\n last_member_qrt = '1'\n last_member_query_count = '2'\n group_timeout = '260'\n report_llg = False\n immediate_leave = False\n\n args = dict(version=version, startup_query_interval=startup_query_interval,\n startup_query_count=startup_query_count, robustness=robustness,\n querier_timeout=querier_timeout, query_mrt=query_mrt,\n query_interval=query_interval, last_member_qrt=last_member_qrt,\n last_member_query_count=last_member_query_count,\n group_timeout=group_timeout, report_llg=report_llg,\n immediate_leave=immediate_leave)\n\n default = dict((param, value) for (param, value) in args.items()\n if value is not None)\n\n return default\n\n\ndef config_default_igmp_interface(existing, delta, found_both, found_prefix):\n commands = []\n proposed = get_igmp_interface_defaults()\n delta = dict(set(proposed.items()).difference(existing.items()))\n if delta:\n command = config_igmp_interface(delta, found_both, found_prefix)\n\n if command:\n for each in command:\n commands.append(each)\n\n return commands\n\n\ndef config_remove_oif(existing, existing_oif_prefix_source):\n commands = []\n command = None\n if existing.get('routemap'):\n command = 'no ip igmp static-oif route-map {0}'.format(\n existing.get('routemap'))\n if existing_oif_prefix_source:\n for each in existing_oif_prefix_source:\n if each.get('prefix') and each.get('source'):\n command = 'no ip igmp static-oif {0} source {1} '.format(\n each.get('prefix'), each.get('source')\n )\n elif each.get('prefix'):\n command = 'no ip igmp static-oif {0}'.format(\n each.get('prefix')\n )\n if command:\n commands.append(command)\n command = None\n\n return commands\n\n\ndef main():\n argument_spec = dict(\n interface=dict(required=True, type='str'),\n version=dict(required=False, type='str'),\n startup_query_interval=dict(required=False, type='str'),\n startup_query_count=dict(required=False, type='str'),\n robustness=dict(required=False, type='str'),\n querier_timeout=dict(required=False, type='str'),\n query_mrt=dict(required=False, type='str'),\n query_interval=dict(required=False, type='str'),\n last_member_qrt=dict(required=False, type='str'),\n last_member_query_count=dict(required=False, type='str'),\n group_timeout=dict(required=False, type='str'),\n report_llg=dict(type='bool'),\n immediate_leave=dict(type='bool'),\n oif_routemap=dict(required=False, type='str'),\n oif_prefix=dict(required=False, type='str'),\n oif_source=dict(required=False, type='str'),\n restart=dict(type='bool', default=False),\n state=dict(choices=['present', 'absent', 'default'],\n default='present'),\n include_defaults=dict(default=True),\n config=dict(),\n save=dict(type='bool', default=False)\n )\n\n argument_spec.update(nxos_argument_spec)\n\n module = AnsibleModule(argument_spec=argument_spec,\n supports_check_mode=True)\n\n warnings = list()\n check_args(module, warnings)\n\n\n state = module.params['state']\n interface = module.params['interface']\n oif_prefix = module.params['oif_prefix']\n oif_source = module.params['oif_source']\n oif_routemap = module.params['oif_routemap']\n\n if oif_source:\n if not oif_prefix:\n module.fail_json(msg='oif_prefix required when setting oif_source')\n\n intf_type = get_interface_type(interface)\n if get_interface_mode(interface, intf_type, module) == 'layer2':\n module.fail_json(msg='this module only works on Layer 3 interfaces')\n\n if oif_prefix and oif_routemap:\n module.fail_json(msg='cannot use oif_prefix AND oif_routemap.'\n ' select one.')\n\n existing = get_igmp_interface(module, interface)\n existing_copy = existing.copy()\n end_state = existing_copy\n\n if not existing.get('version'):\n module.fail_json(msg='pim needs to be enabled on the interface')\n\n existing_oif_prefix_source = existing.get('oif_prefix_source')\n # not json serializable\n existing.pop('oif_prefix_source')\n\n if oif_routemap and existing_oif_prefix_source:\n module.fail_json(msg='Delete static-oif configurations on this '\n 'interface if you want to use a routemap')\n\n if oif_prefix and existing.get('oif_routemap'):\n module.fail_json(msg='Delete static-oif route-map configuration '\n 'on this interface if you want to config '\n 'static entries')\n\n args = [\n 'version',\n 'startup_query_interval',\n 'startup_query_count',\n 'robustness',\n 'querier_timeout',\n 'query_mrt',\n 'query_interval',\n 'last_member_qrt',\n 'last_member_query_count',\n 'group_timeout',\n 'report_llg',\n 'immediate_leave',\n 'oif_routemap',\n 'oif_prefix',\n 'oif_source'\n ]\n\n changed = False\n commands = []\n proposed = dict((k, v) for k, v in module.params.items()\n if v is not None and k in args)\n\n CANNOT_ABSENT = ['version', 'startup_query_interval',\n 'startup_query_count', 'robustness', 'querier_timeout',\n 'query_mrt', 'query_interval', 'last_member_qrt',\n 'last_member_query_count', 'group_timeout', 'report_llg',\n 'immediate_leave']\n\n if state == 'absent':\n for each in CANNOT_ABSENT:\n if each in proposed:\n module.fail_json(msg='only params: oif_prefix, oif_source, '\n 'oif_routemap can be used when '\n 'state=absent')\n\n # delta check for all params except oif_prefix and oif_source\n delta = dict(set(proposed.items()).difference(existing.items()))\n\n # now check to see there is a delta for prefix and source command option\n found_both = False\n found_prefix = False\n\n if existing_oif_prefix_source:\n if oif_prefix and oif_source:\n for each in existing_oif_prefix_source:\n if (oif_prefix == each.get('prefix') and\n oif_source == each.get('source')):\n found_both = True\n if not found_both:\n delta['prefix'] = oif_prefix\n delta['source'] = oif_source\n elif oif_prefix:\n for each in existing_oif_prefix_source:\n if oif_prefix == each.get('prefix') and not each.get('source'):\n found_prefix = True\n if not found_prefix:\n delta['prefix'] = oif_prefix\n\n if state == 'present':\n if delta:\n command = config_igmp_interface(delta, found_both, found_prefix)\n if command:\n commands.append(command)\n\n elif state == 'default':\n command = config_default_igmp_interface(existing, delta,\n found_both, found_prefix)\n if command:\n commands.append(command)\n elif state == 'absent':\n command = None\n if existing.get('oif_routemap') or existing_oif_prefix_source:\n command = config_remove_oif(existing, existing_oif_prefix_source)\n\n if command:\n commands.append(command)\n\n command = config_default_igmp_interface(existing, delta,\n found_both, found_prefix)\n if command:\n commands.append(command)\n\n if module.params['restart']:\n commands.append('restart igmp')\n\n cmds = []\n results = {}\n if commands:\n commands.insert(0, ['interface {0}'.format(interface)])\n cmds = flatten_list(commands)\n\n if module.check_mode:\n module.exit_json(changed=True, commands=cmds)\n else:\n load_config(module, cmds)\n changed = True\n end_state = get_igmp_interface(module, interface)\n if 'configure' in cmds:\n cmds.pop(0)\n\n results['proposed'] = proposed\n results['existing'] = existing_copy\n results['updates'] = cmds\n results['changed'] = changed\n results['warnings'] = warnings\n results['end_state'] = end_state\n\n module.exit_json(**results)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"zhxfei/My-Admin","sub_path":"env/lib/python3.5/site-packages/ansible/modules/network/nxos/nxos_igmp_interface.py","file_name":"nxos_igmp_interface.py","file_ext":"py","file_size_in_byte":25345,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"}
+{"seq_id":"73238199204","text":"import tkinter as tk\n\ndef show_entry_fields():\n x,y,z = 0,0,0\n for num in range(int(e1.get()),int(e2.get())):\n tk.Label(master, text=\"%s\" % num).grid(row=9, column=num+1)\n if num % 3==0 and num % 5 == 0:\n print('FizzBuzz')\n x = 1+x\n elif num % 3 == 0:\n print('Fizz')\n y = 1+y\n elif num % 5 == 0:\n print('Buzz')\n z = 1+z\n else:\n print(num)\n\n\n print(\"First Name: %s\\nLast Name: %s\" % (e1.get(), e2.get()))\n #master.insert(tk.end, x, y)\n print(\"\\nfizzbuzz count: %s\\n\" % x)\n print(\"fizz count: %s\\n\" % y)\n print(\"buzz count: %s\\n\" % z)\n tk.Label(master, text=\"fizzbuzz count: %s\" % x).grid(row=10)\n tk.Label(master, text=\"fizz count: %s\" % y).grid(row=11)\n tk.Label(master, text=\"buzz count: %s\" % z).grid(row=12)\n\n\n\n\n\nmaster = tk.Tk()\n\ntk.Label(master,text=\"First number\").grid(row=0)\ntk.Label(master,text=\"Last number\").grid(row=1)\nmaster.geometry(\"800x500\")\n\n\n\n\ne1 = tk.Entry(master).grid(row=0, column=1)\ne2 = tk.Entry(master).grid(row=1, column=1)\n\n\n\ntk.Button(master,text='Quit',command=master.quit).grid(row=3,column=0,sticky=tk.W,pady=4,padx=4)\n\ntk.Button(master,text='Show', command=show_entry_fields).grid(row=3,column=1,sticky=tk.W,pady=4,padx=4)\n\n\n\ntk.mainloop()\n\n\n\n\n","repo_name":"jdan37/Inventory","sub_path":"fbg.py","file_name":"fbg.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23374229140","text":"p1 = input(\"Player 1? \")\np2 = input(\"Player 2? \")\ntest = (p1, p2)\nr = 'rock'\ns = 'scissors'\np = 'paper'\n\nif p1 in (r, s, p) and p2 in (r, s, p):\n if(p1 == p2):\n print(\"Draw.\")\n elif test in ((r, s), (s, p), (p, r)):\n print(\"Player 1 wins.\")\n else:\n print(\"Player 2 wins.\")\nelse:\n print(\"Error.\")\n","repo_name":"tdthuan97/Myday001","sub_path":"rock_paper_scissors/rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21874941496","text":"import dill\n\nfrom pathlib import Path\n\ndef find_paths(G, node, length):\n '''\n Taken from: https://stackoverflow.com/questions/28095646/finding-all-paths-walks-of-given-length-in-a-networkx-graph/28103735#28103735\n '''\n if length == 0:\n return [[node]]\n\n paths = [[node] + path for neighbor in G.neighbors(node) for path in find_paths(G, neighbor, length - 1) if node not in path]\n\n return paths\n\ndef evaluate_path(path):\n for e, ((x1, y1), (x2, y2)) in enumerate(zip(path, path[1:]), 1):\n if e == 1:\n if x1 != x2:\n continue\n else:\n return False\n if e % 2 == 0:\n if x1 != x2:\n return False\n if y1 == y2:\n return False\n else:\n if x1 == x2:\n return False\n if y1 != y2:\n return False\n return True\n\ndef filter_found_paths(paths):\n return [i for i in paths if evaluate_path(i)]\n\ndef path_to_sequence(g, path):\n return [g.nodes[n]['label'] for n in path]\n\ndef check_solution(graph, target_paths, path):\n target_paths_copy = [i for i in target_paths]\n\n path = path_to_sequence(graph, path)\n\n for point in path:\n for e, t in enumerate(target_paths_copy):\n if t:\n if t[0] == point:\n target_paths_copy[e] = t[1:]\n\n return [False if len(t) else True for t in target_paths_copy]\n\ndef score_solutions(graph, target_paths, solutions):\n best = dict(path=None, score=0)\n\n for p in solutions:\n matches = check_solution(graph, target_paths, p)\n score = sum([m * w for m, w in zip(matches, [1, 2, 4])])\n\n if score == 6:\n best['path'] = p\n best['score'] = score\n best['sequence'] = path_to_sequence(graph, p)\n best['readable_path'] = [f\"{c}:{x + 1}-{y + 1}\" for c, (x, y) in zip(best['sequence'], p)]\n best['matched'] = [e for e, m in enumerate(matches, 1) if m]\n break\n\n if score > best['score']:\n best['path'] = p\n best['score'] = score\n best['sequence'] = path_to_sequence(graph, p)\n best['readable_path'] = [f\"{c}:{x + 1}-{y + 1}\" for c, (x, y) in zip(best['sequence'], p)]\n best['matched'] = [e for e, m in enumerate(matches, 1) if m]\n\n if best['path']:\n return best\n else:\n return None\n\ndef solve(puzzle):\n\n if puzzle.grid_shape == 5:\n\n try:\n fp = Path(f'solver/data/{puzzle.buffer_size}.dill')\n\n with open(fp, 'rb') as fp:\n all_paths = dill.load(fp)\n except FileNotFoundError:\n fp = Path(f'data/{puzzle.buffer_size}.dill')\n\n with open(fp, 'rb') as fp:\n all_paths = dill.load(fp)\n\n all_paths = filter_found_paths(all_paths)\n\n else:\n all_paths = []\n\n start_points = [(0, x) for x in range(puzzle.grid_shape)]\n\n for start_point in start_points:\n paths = find_paths(puzzle.graph,\n start_point,\n puzzle.buffer_size - 1)\n\n all_paths.extend(filter_found_paths(paths))\n\n return score_solutions(puzzle.graph, puzzle.targets, all_paths)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"alexanderrobertson/cyberpunk_breach_solver","sub_path":"solver/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30149935547","text":"from django.http import JsonResponse, HttpResponse\nfrom study.models import Teacher, Student, Content, Category, Curriculum\nimport json\nimport traceback\n\n\ndef get_body(request):\n \"\"\"\n :param request: Django http request instance\n :return: data from x-www-form-urlencoded or json body\n \"\"\"\n try:\n return json.loads(request.body)\n except:\n if request.method == 'POST':\n return request.POST\n elif request.method == 'PUT':\n return request.PUT\n return {}\n\n\ndef logged_in_student(request) -> Student or None:\n student_id = request.session.get('student')\n if student_id:\n try:\n student = Student.objects.get(id=student_id)\n return student\n except:\n return None\n return None\n\n\ndef logged_in_teacher(request) -> Teacher or None:\n teacher_id = request.session.get('teacher')\n if teacher_id:\n try:\n teacher = Teacher.objects.get(id=teacher_id)\n return teacher\n except:\n return None\n return None\n\n\ndef verify_data(data: dict, contains: list) -> str or None:\n \"\"\"\n :param data: body dict\n :param contains: contents must be contained in body\n :return: None if no problem, else return name of required content\n \"\"\"\n for c in contains:\n if c not in data:\n return c\n return None\n\n\ndef get_response(logger, request, code: int, data: dict or list = None, msg: str = None, teacher_id: int = None, student_id: int = None) -> HttpResponse:\n \"\"\"\n :param logger: logger\n :param request: original request for logging\n :param code: status code for response\n :param data: body for response or data included in message\n :param msg: message for error\n :param teacher_id: teacher id for logging\n :param student_id: student id for logging\n :return:\n \"\"\"\n response = {}\n if code == 200: # Success\n response = {\n 'status_code': code,\n 'message': 'Success'\n }\n if data is not None:\n response['data'] = data\n elif code == 400: # Unknown user error\n response = {\n 'status_code': code,\n 'message': msg,\n }\n elif code == 401: # Unknown user error\n response = {\n 'status_code': code,\n 'message': 'User is unauthorized.',\n }\n elif code == 405: # Method is not allowed\n response = {\n 'status_code': code,\n 'message': msg if msg else 'Method %s is not allowed. (%s)' % (data[0], ', '.join(data[1:]))\n }\n elif code == 500: # Unknown server error\n response = {\n 'status_code': code,\n 'message': msg if msg else 'Internal server error.'\n }\n\n logger.error(traceback.format_exc())\n\n logger.info('%(path)s\\t%(method)s\\t%(code)s\\t(%(teacher_id)s/%(student_id)s)\\t%(body)s\\t\"%(response)s\"' %{\n 'path': request.path,\n 'method': request.method,\n 'code': response['status_code'],\n 'teacher_id': teacher_id,\n 'student_id': student_id,\n 'body': get_body(request),\n 'response': response['message']\n })\n return HttpResponse(json.dumps(response, ensure_ascii=False), content_type=u\"application/json; charset=utf-8\")\n\n\ndef to_json(object: Teacher or Student or Content or Category or Curriculum) -> dict:\n \"\"\"\n :param object: instance of models\n :return: dict form json data\n \"\"\"\n if isinstance(object, Teacher):\n return {\n 'username': object.username,\n 'fullname': object.fullname,\n 'email': object.email,\n 'birthday': str(object.birthday)\n }\n elif isinstance(object, Student):\n return {\n 'username': object.username,\n 'fullname': object.fullname,\n 'email': object.email,\n 'birthday': str(object.birthday),\n 'image_id': object.image_id\n }\n elif isinstance(object, Content):\n return {\n 'id': object.id,\n 'title': object.title,\n 'level': object.level,\n 'teacher': {\n 'id': object.teacher_id,\n 'fullname': object.teacher.fullname\n }\n }\n elif isinstance(object, Category):\n return {\n 'id': object.id,\n 'english': object.english\n }\n elif isinstance(object, Curriculum):\n return {\n 'content_id': object.id,\n 'percentage': object.percentage,\n 'score': object.score,\n 'end_datetime': str(object.end_datetime)\n }\n\n\ndef get_detail_content(content: Content) -> dict:\n return {\n 'id': content.id,\n 'category': content.category.english,\n 'type': content.type,\n 'title': content.title,\n 'level': content.level,\n 'teacher': {\n 'id': content.teacher_id,\n 'fullname': content.teacher.fullname\n },\n 'content': content.content,\n 'res_image': content.res_image,\n 'res_sound': content.res_sound\n }","repo_name":"Earndu/EarnduServer","sub_path":"study/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"74199042725","text":"#!/usr/bin/env python3\r\n\"\"\"\"\r\nFor each molecule in test set we compare its descriptors\r\nwith the active descriptors and we compute a sum.\r\nIf we find descriptor in active descriptors we add to the sum +num1\r\nand if we do not find it we add -num2\r\ninput model_configuration should look like this:\r\n {\"model_name\": \"descriptors_model\", \"fragments\": \"ecfp.6\", \"active_parameter\": num1,\"inactive_parameter\": num2}\r\n where num1 and num2 are numbers\r\n\"\"\"\r\nimport json\r\n\r\nfrom model_interface import IModel\r\nfrom model_factory import register_model\r\nimport inputoutput_utils\r\n\r\n\r\nclass DescriptorsModel(IModel):\r\n model_name = \"descriptors_model\"\r\n\r\n def name(self):\r\n return self.model_name\r\n\r\n def create_model(self, active_fragments: str, inactive_fragments: str,\r\n active_descriptors: str, inactive_descriptors: str,\r\n model_configuration: str) -> dict:\r\n descriptors = []\r\n with open(active_descriptors, \"r\") as stream:\r\n line = stream.readline()\r\n line_parts = line.split(\",\")\r\n if line_parts[1] != \"index\":\r\n print(\"Wrong input, we want fragments descriptors not molecules\")\r\n exit(1)\r\n for line in stream:\r\n line_parts = line.split(\",\")\r\n descriptors.append(line_parts[2:])\r\n model = {\r\n \"configuration\": model_configuration,\r\n \"data\": descriptors\r\n }\r\n return model\r\n\r\n def save_to_json_file(self, output_file: str, model: dict):\r\n inputoutput_utils.save_to_json_file(output_file, model)\r\n\r\n def score_model(self, model_configuration: dict, fragments_file: str,\r\n descriptors_file: str, output_file: str):\r\n name_num = _read_molecules(fragments_file)\r\n inputoutput_utils.create_parent_directory(output_file)\r\n active_parameter = int(model_configuration[\"configuration\"][\"active_parameter\"])\r\n inactive_parameter = int(model_configuration[\"configuration\"][\"inactive_parameter\"])\r\n with open(output_file, \"w\") as streamo:\r\n first_write = True\r\n with open(descriptors_file, \"r\") as stream:\r\n next(stream)\r\n counter = 0\r\n molecule_num = 0\r\n sum = 0\r\n for line in stream:\r\n line_parts = line.split(\",\")\r\n parts = line_parts[2:]\r\n founded = False\r\n for descriptors in model_configuration[\"data\"]:\r\n if descriptors == parts:\r\n founded = True\r\n break\r\n\r\n if founded:\r\n sum += active_parameter\r\n else:\r\n sum -= inactive_parameter\r\n counter += 1\r\n if counter == name_num[molecule_num][\"fragments\"]:\r\n score = {\r\n \"name\": name_num[molecule_num][\"molecule\"],\r\n \"score\": sum / counter\r\n }\r\n counter = 0\r\n sum = 0\r\n molecule_num += 1\r\n if first_write:\r\n first_write = False\r\n else:\r\n streamo.write(\"\\n\")\r\n json.dump(score, streamo)\r\n\r\n\r\ndef _read_molecules(input_file: str):\r\n name_num = []\r\n with open(input_file, \"r\") as stream:\r\n for line in stream:\r\n molecule = json.loads(line)\r\n name = molecule[\"name\"]\r\n num_fragments = len(molecule[\"fragments\"])\r\n mol_frag = {\r\n \"molecule\": name,\r\n \"fragments\": num_fragments\r\n }\r\n name_num.append(mol_frag)\r\n return name_num\r\n\r\n\r\nregister_model(DescriptorsModel.model_name, lambda: DescriptorsModel())\r\n\r\n\r\n","repo_name":"LamprechtMatyas/MolecularSimilarity","sub_path":"model/descriptors_model.py","file_name":"descriptors_model.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"40418663451","text":"from re import search, match\n\ndef parse( regexp, line, method=search ):\n \"\"\"\n like what method does, but allows a single line \n \"\"\"\n m = method( regexp, line )\n if m:\n return m\n return None","repo_name":"SLAC/slac_utils","sub_path":"regexp.py","file_name":"regexp.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10995908818","text":"from operator_symbols import OPERATOR_SIGNS\nfrom truth_table import TruthTable\n\n\nclass NormalForm:\n def __init__(self, truth_table: TruthTable, results, nf_params):\n self.TT = truth_table\n self.TT_results = self.set_results(results)\n self.result = self.NF(*nf_params)\n\n def __str__(self):\n return self.result\n\n @staticmethod\n def set_results(results):\n if type(results) == str:\n return [int(val) for val in results]\n return results\n\n def NF(self, cdnf_else_ccnf: bool, inner_junction: str, outer_junction: str):\n if len(self.TT_results) != len(self.TT.table):\n raise Exception('Invalid Input (result and truth table rows do not match in length)')\n nf = []\n for i in range(len(self.TT.table)):\n if self.TT_results[i] == cdnf_else_ccnf:\n if nf:\n nf.append(outer_junction)\n nf.append('(')\n row = self.TT.table[i]\n for j in range(len(self.TT.variables)):\n if j:\n nf.append(inner_junction)\n var = self.TT.variables[j]\n if row[j] if cdnf_else_ccnf else not row[j]:\n nf.append(var)\n else:\n nf.append(OPERATOR_SIGNS['NOT'])\n nf.append(var)\n nf.append(')')\n return ''.join(nf)\n\n\nclass CDNF(NormalForm):\n def __init__(self, truth_table, results):\n super(CDNF, self).__init__(truth_table, results, [True, OPERATOR_SIGNS['AND'], OPERATOR_SIGNS['OR']])\n\n\nclass CCNF(NormalForm):\n def __init__(self, truth_table, results):\n super(CCNF, self).__init__(truth_table, results, [False, OPERATOR_SIGNS['OR'], OPERATOR_SIGNS['AND']])\n","repo_name":"MaxWolf-01/TruthTabler","sub_path":"src/normal_forms.py","file_name":"normal_forms.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"}
+{"seq_id":"43321544670","text":"import numpy as np\nimport random\nfrom scipy import linalg as la\nfrom scipy import matrix\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\nimport cv2\nfrom Camera import *\nfrom ImagePair import *\nfrom SingleImage import *\nfrom PhotoViewer import *\n\n\ndef computeDesignMatrix_Fundamental(pts1, pts2):\n \"\"\"\n return design matrix for Fundamental matrix computation given a set of homologic points\n :param pts1:\n :param pts2:\n :return: design matrix A for extracting the fundamental matrix\n \"\"\"\n A = np.zeros((len(pts1), 9))\n A[:, 0] = pts1[:, 0] * pts2[:, 0]\n A[:, 1] = pts1[:, 1] * pts2[:, 0]\n A[:, 2] = pts2[:, 0]\n A[:, 3] = pts1[:, 0] * pts2[:, 1]\n A[:, 4] = pts1[:, 1] * pts2[:, 1]\n A[:, 5] = pts2[:, 1]\n A[:, 6] = pts1[:, 0]\n A[:, 7] = pts1[:, 1]\n A[:, -1] = np.ones(A[:, -1].shape)\n return A\n\n\ndef normalizePoints(img_shape, pts1, pts2):\n \"\"\"\n return an array of the normalized points between -1, 1 given img and homologic points\n both images are presumed to be same size\n :param img:\n :param pts1:\n :param pts2:\n :return: the nomalizing matrix and normalized points\n \"\"\"\n xmax = img_shape[0]\n ymax = img_shape[1]\n xm = 0.5 * (0 + xmax)\n ym = 0.5 * (0 + ymax)\n dx = xmax\n dy = ymax\n S = np.array([[2 / dx, 0, -2 * (xm / dx)], [0, 2 / dy, -2 * (ym / dy)], [0, 0, 1]])\n pts1_normalized = []\n pts2_normalized = []\n for i in range(len(pts1)):\n pts1_normalized.append(np.dot(S, pts1[i]))\n pts2_normalized.append(np.dot(S, pts2[i]))\n\n pts1_normalized = np.vstack(pts1_normalized)\n pts2_normalized = np.vstack(pts2_normalized)\n\n return S, pts1_normalized, pts2_normalized\n\n\ndef findHomologicPoints(img1, img2, draw_images=0):\n \"\"\"\n use SIFT & opencv to locate points from img1 in img2\n :param img1: query image\n :param img2: train image\n :param draw_images: flag for drawing the homologic points found\n :return: pts1 & pts2\n \"\"\"\n # find homologic points\n MIN_MATCH_COUNT = 10\n\n # Initiate SIFT detector\n sift = cv2.xfeatures2d.SIFT_create()\n # find the keypoints and descriptors with SIFT\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, 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) # or pass empty dictionary\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1, des2, k=2)\n\n # Need to draw only good matches, so create a mask\n matchesMask = [[0, 0] for i in range(len(matches))]\n\n good = []\n pts1 = []\n pts2 = []\n # ratio test as per Lowe's paper\n for i, (m, n) in enumerate(matches):\n if m.distance < 0.5 * n.distance:\n matchesMask[i] = [1, 0]\n good.append(m)\n pts2.append(kp2[m.trainIdx].pt)\n pts1.append(kp1[m.queryIdx].pt)\n\n if len(good) > MIN_MATCH_COUNT and draw_images:\n draw_params = dict(matchColor=(0, 255, 0),\n singlePointColor=(255, 0, 0),\n matchesMask=matchesMask,\n flags=0)\n\n img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, matches, None, **draw_params)\n\n plt.imshow(img3, ), plt.show()\n\n return np.vstack(pts1), np.vstack(pts2)\n\n\ndef ransacFundamental(img1, pts1, pts2, tolerance=0.01, normalize=1):\n \"\"\"\n\n :param img1:\n :param pts1:\n :param pts2:\n :param tolerance:\n :param normalize:\n :return:\n \"\"\"\n\n def check_minCount(F, minCount, pts1, pts2):\n counter = 0\n for i in range(len(pts1)):\n if np.dot(np.dot(pts2[i].T, F), pts1[i]) <= tolerance:\n counter += 1\n print(counter, '/', len(pts1))\n if counter >= minCount:\n return False\n return True\n\n # setting desired count for matching points, in our case 85%\n n = len(pts1)\n good_pts1 = []\n good_pts2 = []\n MIN_MATCH_COUNT = np.int(0.85 * n)\n # initial value for the fundamental matrix\n F = np.ones((3, 3))\n while check_minCount(F, MIN_MATCH_COUNT, pts1, pts2):\n # select random 8 points - minimum for fundamental matrix extraction\n random_idx = []\n for i in range(8):\n random_idx.append(random.randrange(n))\n\n rand8_pts1 = np.vstack((pts1[random_idx[0]], pts1[random_idx[1]], pts1[random_idx[2]],\n pts1[random_idx[3]], pts1[random_idx[4]], pts1[random_idx[5]],\n pts1[random_idx[6]], pts1[random_idx[7]]))\n rand8_pts2 = np.vstack((pts2[random_idx[0]], pts2[random_idx[1]], pts2[random_idx[2]],\n pts2[random_idx[3]], pts2[random_idx[4]], pts2[random_idx[5]],\n pts2[random_idx[6]], pts2[random_idx[7]]))\n\n # normalizing pts between -1,1\n S, pts1_normalized, pts2_normalized = normalizePoints(img1.shape, rand8_pts1, rand8_pts2)\n # creating design matrix\n A = computeDesignMatrix_Fundamental(pts1_normalized, pts2_normalized)\n # solving homogeneous equation\n N = np.dot(A.T, A)\n egi_vals, egi_vect = np.linalg.eig(N)\n min_egi_val_index = np.argmin(egi_vals)\n v = egi_vect[:, min_egi_val_index]\n F = v.reshape((3, 3))\n # svd decomposition for setting one singular value to zero\n u, s, vh = la.svd(F)\n s[-1] = 0\n fixed_F = np.dot(np.dot(u, np.diag(s)), vh)\n # converting F back to the normal coordinates and normalizing to norm=1\n fixed_F = np.dot(np.dot(S.T, fixed_F), S)\n F = fixed_F / la.norm(fixed_F)\n\n # filtering out the bad points\n for i in range(len(pts1)):\n if np.dot(np.dot(pts2[i].T, F), pts1[i]) <= tolerance:\n good_pts1.append(pts1[i])\n good_pts2.append(pts2[i])\n # using rest of points to adjust the new and improved fundamental matrix\n # normalizing pts between -1,1\n S, pts1_normalized, pts2_normalized = normalizePoints(img1.shape, good_pts1, good_pts2)\n # creating design matrix\n A = computeDesignMatrix_Fundamental(pts1_normalized, pts2_normalized)\n # solving homogeneous equation\n N = np.dot(A.T, A)\n egi_vals, egi_vect = np.linalg.eig(N)\n min_egi_val_index = np.argmin(egi_vals)\n v = egi_vect[:, min_egi_val_index]\n F = v.reshape((3, 3))\n # svd decomposition for setting one singular value to zero\n u, s, vh = la.svd(F)\n s[-1] = 0\n fixed_F = np.dot(np.dot(u, np.diag(s)), vh)\n # converting F back to the normal coordinates and normalizing to norm=1\n fixed_F = np.dot(np.dot(S.T, fixed_F), S)\n F = fixed_F / la.norm(fixed_F)\n\n return F, np.vstack(good_pts1), np.vstack(good_pts2)\n\n\n# METHOD FROM OPENCV\ndef drawlines(img1, img2, lines, pts1, pts2):\n ''' img1 - image on which we draw the epilines for the points in img2\n lines - corresponding epilines '''\n r, c = img1.shape\n img1 = cv2.cvtColor(img1, cv2.COLOR_GRAY2BGR)\n img2 = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)\n for r, pt1, pt2 in zip(lines, pts1, pts2):\n color = tuple(np.random.randint(0, 255, 3).tolist())\n x0, y0 = map(int, [0, -r[2] / r[1]])\n x1, y1 = map(int, [c, -(r[2] + r[0] * c) / r[1]])\n img1 = cv2.line(img1, (x0, y0), (x1, y1), color, 1)\n img1 = cv2.circle(img1, tuple(pt1.astype(int)), 5, color, -1)\n img2 = cv2.circle(img2, tuple(pt2.astype(int)), 5, color, -1)\n return img1, img2\n\n\nif __name__ == '__main__':\n # computing K camera calibration matrix using cv2\n K, rvecs, tvecs = Camera.calibrateCamera_checkers()\n # print(pd.DataFrame(K))\n\n # loading images\n img1 = cv2.imread('images/20200622_140804.jpg', 0) # queryImage 'box'\n img2 = cv2.imread('images/20200622_140813.jpg', 0) # trainImage 'box-in-scene'\n\n # computing fundamental matrix\n # locating homologic points\n pts1, pts2 = findHomologicPoints(img1, img2)\n\n ##### TRY TO USE OPENCV FOR GETTING FUNDAMENTAL MATRIX AND DRAW EPIPOLAR LINES\n # opencv drawing\n F1, mask = cv2.findFundamentalMat(pts1, pts2, cv2.FM_RANSAC)\n F1 = F1 / la.norm(F1)\n\n # We select only inlier points\n pts1 = pts1[mask.ravel() == 1]\n pts2 = pts2[mask.ravel() == 1]\n\n # Find epilines corresponding to points in right image (second image) and\n # drawing its lines on left image\n # lines1 = cv2.computeCorrespondEpilines(pts2.reshape(-1, 1, 2), 2, F1)\n # lines1 = lines1.reshape(-1, 3)\n # img5, img6 = drawlines(img1, img2, lines1, pts1, pts2)\n # # Find epilines corresponding to points in left image (first image) and\n # # drawing its lines on right image\n # lines2 = cv2.computeCorrespondEpilines(pts1.reshape(-1, 1, 2), 1, F1)\n # lines2 = lines2.reshape(-1, 3)\n # img3, img4 = drawlines(img2, img1, lines2, pts2, pts1)\n # plt.subplot(121),\n # # plt.scatter(pts1[:, 0], pts1[:, 1])\n # plt.imshow(img5), plt.axis('off')\n # plt.subplot(122), plt.imshow(img3), plt.axis('off')\n # plt.show()\n\n ####\n\n # converting points to homogeneous presentation\n # f = np.mean(np.array([K[0, 0], K[1, 1]]))\n pts1 = np.hstack((pts1, np.ones((pts1.shape[0], 1))))\n pts2 = np.hstack((pts2, np.ones((pts2.shape[0], 1))))\n\n # correcting points to ideal camera\n K[0, 0] = -K[0, 0]\n K[1, 1] = -K[1, 1]\n xp = K[0, -1]\n yp = K[1, -1]\n ppa = np.array([xp, yp, 0])\n for i in range(len(pts1)):\n # pts1[i] = np.dot(la.inv(K), pts1[i])\n # pts2[i] = np.dot(la.inv(K), pts2[i])\n pts1[i] = pts1[i] - ppa\n pts2[i] = pts2[i] - ppa\n\n # ransac adjusting the fundamental matrix\n F, good_pts1, good_pts2 = ransacFundamental(img1, pts1, pts2, tolerance=0.01)\n\n # find epipole using null space\n # left null space is the 1st image epipole point\n epipole1 = la.null_space(matrix(F.T))\n # translate to image space\n epipole1 = (epipole1.T / epipole1.T[:, -1]) + ppa.T\n # show epipole on image\n # plt.imshow(img2, cmap='gray')\n # plt.scatter(epipole1.T[0], epipole1.T[1], s=200, c='g')\n # plt.axis('off')\n # plt.show()\n\n # computing epi-polar line for each homologic points and distance from it\n epi_lines = []\n distances = []\n for i, p in enumerate(good_pts2):\n epi_line = np.dot(p.T, F)\n epi_lines.append(epi_line)\n distances.append(np.abs(epi_line[0] * good_pts1[i, 0] + epi_line[1] * good_pts1[i, 1] + epi_line[-1]) / np.sqrt(\n epi_line[0] ** 2 + epi_line[1] ** 2))\n epi_lines = np.vstack(epi_lines)\n distances = np.vstack(distances)\n # filtering points above a certain distance from line\n idx = np.where(distances < 1)[0]\n good_pts1 = good_pts1[idx]\n good_pts2 = good_pts2[idx]\n good_epi_lines = epi_lines[idx]\n\n # for drawing purposes going back to image system\n good_pts1_image = []\n good_pts2_image = []\n for i in range(len(good_pts1)):\n good_pts1_image.append(good_pts1[i] + ppa)\n good_pts2_image.append(good_pts2[i] + ppa)\n\n good_pts1_image = np.vstack(good_pts1_image)\n good_pts2_image = np.vstack(good_pts2_image)\n\n # low_right_x = 2268.\n # upper_left_x = 0.\n # xs = (upper_left_x, low_right_x) # - ppa[0]\n # #\n #\n # plt.scatter(good_pts1[:, 0], good_pts1[:, 1], c='g')\n # for line in good_epi_lines:\n # y1 = (-line[0] * upper_left_x - line[-1]) / line[1]\n # y2 = (-line[0] * low_right_x - line[-1]) / line[1]\n # ys = (y1, y2) # - ppa[1]\n # # plt.scatter(xs, ys)\n # # plt.plot(xs, ys)\n # cv2.line(img1, (0, 2268), (int(y1), int(y2)), (0, 255, 0), thickness=2)\n # plt.imshow(img1, cmap='gray')\n # plt.show()\n\n # plt.subplot(121)\n # plt.axis('off')\n # plt.imshow(img1, cmap='gray')\n # plt.scatter(good_pts1_image[:, 0], good_pts1_image[:, 1])\n # plt.subplot(122)\n # plt.axis('off')\n # plt.imshow(img2, cmap='gray')\n # plt.scatter(good_pts2_image[:, 0], good_pts2_image[:, 1])\n # plt.show()\n\n # compute essential matrix using F\n E = np.dot(np.dot(K.T, F), K)\n u, s, vh = la.svd(E)\n s = np.array([1, 1, 0])\n E = np.dot(np.dot(u, np.diag(s)), vh)\n E = E / la.norm(E)\n\n # extracting mutual orientation parameters\n W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])\n b1 = u[:, -1]\n b2 = -u[:, -1]\n R1 = np.dot(np.dot(u, W), vh.T)\n R2 = np.dot(np.dot(u, W.T), vh.T)\n\n # defining image pair\n cam = Camera(-K[0, 0], [K[0, -1], K[1, -1]], None, None, None, 0.5)\n\n image1 = SingleImage(cam)\n image2 = SingleImage(cam)\n\n image_pair = ImagePair(image1, image2)\n image_pair.RotationMatrix_Image1 = np.eye(3)\n\n fig_orthographic = plt.figure()\n ax1 = fig_orthographic.add_subplot(221, projection='3d')\n ax2 = fig_orthographic.add_subplot(222, projection='3d')\n ax3 = fig_orthographic.add_subplot(223, projection='3d')\n ax4 = fig_orthographic.add_subplot(224, projection='3d')\n\n # try1\n ax1.set_title('R1, b1')\n image_pair.RotationMatrix_Image2 = R1\n image_pair.PerspectiveCenter_Image2 = b1\n\n model_points = image_pair.ImagesToModel(good_pts1[5:10, 0:2], good_pts2[5:10, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax1)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax1)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax1)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax1)\n drawRays(model_points[0], x1, ax1, 'r')\n drawRays(model_points[0], x2, ax1, 'g')\n\n ax1.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try2\n ax2.set_title('R2, b2')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b2\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax2)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax2)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax2)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax2)\n drawRays(model_points[0], x1, ax2, 'r')\n drawRays(model_points[0], x2, ax2, 'g')\n\n ax2.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try3\n ax3.set_title('R1, b2')\n image_pair.RotationMatrix_Image2 = R1\n image_pair.PerspectiveCenter_Image2 = b2\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax3)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax3)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax3)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax3)\n drawRays(model_points[0], x1, ax3, 'r')\n drawRays(model_points[0], x2, ax3, 'g')\n\n ax3.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # try4\n ax4.set_title('R2, b1')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b1\n\n model_points = image_pair.ImagesToModel(good_pts1[0:5, 0:2], good_pts2[0:5, 0:2], 'vector')\n\n x1 = image_pair.PerspectiveCenter_Image1[:, None]\n x2 = image_pair.PerspectiveCenter_Image2[:, None]\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image1, x1, -cam.focalLength / 10000, 1,\n ax4)\n drawImageFrame(cam.sensorSize, cam.sensorSize, image_pair.RotationMatrix_Image2, x2, -cam.focalLength / 10000, 1,\n ax4)\n drawOrientation(image_pair.RotationMatrix_Image1, x1, 0.5, ax4)\n drawOrientation(image_pair.RotationMatrix_Image2, x2, 0.5, ax4)\n drawRays(model_points[0], x1, ax4, 'r')\n drawRays(model_points[0], x2, ax4, 'g')\n\n ax4.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # draw all model points\n fig_orthographic = plt.figure()\n ax = fig_orthographic.add_subplot(111, projection='3d')\n image_pair.RotationMatrix_Image2 = R2\n image_pair.PerspectiveCenter_Image2 = b2\n model_points = image_pair.ImagesToModel(good_pts1[:, 0:2], good_pts2[:, 0:2], 'vector')\n ax.scatter(model_points[0][:, 0], model_points[0][:, 1], model_points[0][:, 2], marker='^')\n\n # distances -> size of e vector we got from vectoric intersection\n es = la.norm(model_points[1], axis=1)\n\n plt.show()\n\n print(pd.DataFrame(F))\n","repo_name":"shaul-s/Photogrammetry","sub_path":"Photo-2/Lab8/Lab8.py","file_name":"Lab8.py","file_ext":"py","file_size_in_byte":17335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"43538872462","text":"# Select journal - must be either \"ApJ\" or \"ApJL\"\njournal = \"ApJ\"\n\n# Name of output file\nfilename = \"out/\" + journal + \"_dates.csv\"\n\n# Number of articles to use from each issue\nnum_articles = 30\n\n\n# Input parameter validation\ndef valid(journal, num_articles):\n\ttry:\n\t\tif (int(num_articles) < 1):\n\t\t\treturn False # fails if num_articles < 1\n\texcept ValueError:\n\t\treturn False # fails if num_articles not an integer\n\n\tif journal not in {'APJ', 'APJL', 'apj', 'apjl'}:\n\t\treturn False\n\n\treturn True\n","repo_name":"phufbv/journal-stats","sub_path":"parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1010701538","text":"import os\nimport math\nimport torch\nimport argparse\nfrom sklearn import metrics\nfrom utils import getdata\nfrom DSAKT import DSAKT, Encoder, Decoder\nfrom SAKT import SAKT\n\ndef predict(window_size:int, model_path:str, data_path:str):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\");\n pre_data,N_val,E,unit_list_val = getdata(window_size=window_size,path=data_path,model_type='sakt')\n\n model = torch.load(model_path);\n assert model.window_size == window_size;\n model.to(device);\n model.eval();\n\n with torch.no_grad():\n predict = model(pre_data[0].to(device), pre_data[1].to(device)).squeeze(-1).to(\"cpu\");\n correctness = pre_data[2];\n \n pred = [];\n cort = [];\n for i in range(N_val):\n pred.extend(predict[i][0:unit_list_val[i]].cpu().numpy().tolist());\n cort.extend(correctness[i][0:unit_list_val[i]].numpy().tolist());\n \n pred = torch.Tensor(pred) > 0.5;\n cort = torch.Tensor(cort) == 1;\n acc = torch.eq(pred, cort).sum() / len(pred);\n \n pred = [];\n cort = [];\n for i in range(N_val):\n pred.extend(predict[i][unit_list_val[i]-1:unit_list_val[i]].cpu().numpy().tolist());\n cort.extend(correctness[i][unit_list_val[i]-1:unit_list_val[i]].numpy().tolist());\n \n rmse = math.sqrt(metrics.mean_squared_error(cort, pred));\n fpr, tpr, thresholds = metrics.roc_curve(cort, pred, pos_label=1);\n auc = metrics.auc(fpr, tpr);\n \n print('val_auc: %.3f mse: %.3f acc: %.3f' %(auc, rmse, acc));\n \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser();\n parser.add_argument(\"-ws\", \"--window_size\", required=True);\n parser.add_argument(\"-d\", \"--data_path\", required=True);\n parser.add_argument(\"-m\", \"--model_path\", required=True);\n args = parser.parse_args();\n \n assert os.path.exists(args.data_path);\n assert os.path.exists(args.model_path);\n \n predict(int(args.window_size), args.model_path, args.data_path);","repo_name":"Fusion4233919/DSAKT","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"}
+{"seq_id":"14259933478","text":"from django import forms\nfrom .models import Cliente\n#, Sitios_cliente\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Submit, Row, Column\n\nclass FormularioCliente(forms.ModelForm):\n\n class Meta:\n model = Cliente\n fields = ['nombre', 'direccion', 'telefono', 'email']\n\n labels = {\n 'nombre': 'Nombre',\n 'direccion': 'Dirección',\n 'telefono': 'Teléfono',\n 'email': 'Email',\n }\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Row(\n Column('nombre', css_class='form-group col-md-6 mb-0'),\n Column('direccion', css_class='form-group col-md-6 mb-0'),\n css_class='row-fluid'\n ), \n Row(\n Column('telefono', css_class='form-group col-md-6 mb-0'),\n Column('email', css_class='form-group col-md-6 mb-0'),\n css_class='row-fluid'\n ), \n Submit('submit', 'Enviar', css_class='d-grid gap-2 col-2 mx-auto')\n )\n\n# class FormularioSitioCliente(forms.ModelForm):\n\n# class Meta:\n# model = Sitios_cliente\n# fields = ['nombre', 'direccion', 'telefono', 'email', 'encargado']\n\n# def __init__(self, *args, **kwargs):\n# super().__init__(*args, **kwargs)\n# self.helper = FormHelper()\n# self.helper.layout = Layout(\n# Row(\n# Column('nombre', css_class='form-group col-md-6 mb-0'),\n# Column('direccion', css_class='form-group col-md-6 mb-0'),\n# css_class='row-fluid'\n# ), \n# Row(\n# Column('telefono', css_class='form-group col-md-4 mb-0'),\n# Column('email', css_class='form-group col-md-4 mb-0'),\n# Column('encargado', css_class='form-group col-md-4 mb-0'),\n# css_class='row-fluid'\n# ), \n# Submit('submit', 'Enviar', css_class='d-grid gap-2 col-2 mx-auto')\n# )\n","repo_name":"eorozco-c/sisrg","sub_path":"apps/clientes/formularios.py","file_name":"formularios.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74560028325","text":"from flask import Flask, render_template, jsonify, request\nfrom model import db, connect_to_db, Card\nimport time\n\napp = Flask(__name__) \n\n@app.route(\"/\")\ndef show_homepage():\n \"\"\"Show the application's homepage.\"\"\"\n\n return render_template(\"homepage.html\")\n\n@app.route(\"/cards\")\ndef show_cards():\n \"\"\"Show all trading cards.\"\"\"\n\n return render_template(\"cards.html\")\n\n# usually prefix with api, these are api routes \n# for communicating between the frontend and the backend\n# they're returning json (js object containing data you're asking for) not html \n # it's a js object; can think of it like dictionary\n # has an array of things in it\n # data is within the cards key\n# this route is created because you need to be able to ask for data from the url\n@app.route(\"/cards.json\")\ndef get_cards_json():\n \"\"\"Return a JSON response with all cards in DB.\"\"\"\n\n cards = Card.query.all()\n cards_list = []\n\n for c in cards:\n cards_list.append({\"skill\": c.skill, \"name\": c.name, \"imgUrl\": c.image_url})\n # use sleep to see how it loads\n time.sleep(2)\n\n return jsonify({\"cards\": cards_list}) \n # jsonify turns ^ into [{'cards': cards_list}]\n # jsonify is something that Flask gives you\n # converts python dictionary or list to valid json object\n # cards_list is a python list that contains dictionaries\n\n@app.route(\"/add-card\", methods=[\"POST\"])\ndef add_card():\n \"\"\"Add a new card to the DB.\"\"\"\n\n name = request.form.get('name')\n skill = request.form.get('skill')\n\n new_card = Card(name=name, skill=skill)\n db.session.add(new_card)\n db.session.commit()\n\n return jsonify({\"success\": True})\n\n@app.route(\"/cards-jquery\")\ndef show_cards_jquery():\n return render_template(\"cards-jquery.html\")\n\n\n\nif __name__ == \"__main__\":\n connect_to_db(app)\n app.run(debug=True, host='0.0.0.0')","repo_name":"kschlough/trading-cards-2","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"32511376346","text":"import logging\nimport re\nimport shutil\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nfrom urllib.parse import unquote, urlparse, urlunparse\n\nimport requests\n\nfrom DownloaderLock import DownloaderLock\nfrom Paths import DOWNLOADS_TEMP_PATH\n\n\nclass DownloadError(RuntimeError):\n def __init__(self, filename: str, orig_error: requests.exceptions.RequestException):\n super().__init__(f\"Error while downloading `{filename}`: {orig_error}\")\n\n\nclass DownloaderInitError(RuntimeError):\n def __init__(self, message: str, table_name: str):\n super().__init__(f\"{message} in table array `{table_name}`\")\n\n\ndef _github_api_request(url: str, token: Optional[str]) -> Optional[Dict[str, Any]]:\n if token is not None:\n headers = {\n \"Accept\": \"application/vnd.github+json\",\n \"Authorization\": f\"Bearer {token}\",\n \"X-GitHub-Api-Version\": \"2022-11-28\",\n }\n else:\n headers = None\n\n response = requests.get(url=url, headers=headers, timeout=5)\n\n if response.status_code != 200:\n print(f\"GitHub API Request failed. Status code: {response.status_code}\")\n return None\n\n return response.json()\n\n\ndef _get_latest_release(repo: str, token: Optional[str]) -> Optional[Dict[str, Any]]:\n url = f\"https://api.github.com/repos/{repo}/releases/latest\"\n return _github_api_request(url, token)\n\n\ndef _get_default_branch(repo: str, token: Optional[str]) -> Optional[str]:\n url = f\"https://api.github.com/repos/{repo}\"\n response = _github_api_request(url, token)\n return response.get(\"default_branch\") if response is not None else None\n\n\ndef _download_file_to(target_path: Path, url: str) -> Optional[Path]:\n filename = _get_file_name_from_url(url)\n\n try:\n response = requests.get(url, timeout=10, headers={\"cache-control\": \"no-cache\"})\n except requests.exceptions.RequestException as err:\n raise DownloadError(filename, err) from None\n\n if response.status_code != 200:\n print(f\"Failed to download `{filename}`. Status code: {response.status_code}\")\n return None\n\n target_path.mkdir(parents=True, exist_ok=True)\n\n file_path = target_path / filename\n with open(file_path, \"wb\") as file:\n file.write(response.content)\n return file_path\n\n\ndef _get_file_name_from_url(url: str) -> str:\n parsed_url = urlparse(unquote(url))\n path_url = urlunparse(\n (\n parsed_url.scheme,\n parsed_url.netloc,\n parsed_url.path,\n \"\",\n \"\",\n \"\",\n )\n )\n return Path(path_url).name\n\n\n@dataclass(frozen=True)\nclass GithubFile:\n _repo: str\n _file: str\n\n def download(\n self,\n token: Optional[str],\n ) -> Optional[Path]:\n print(f\"\\t{self._repo}: {Path(self._file).name}\")\n\n default_branch = _get_default_branch(self._repo, token)\n\n if default_branch is None:\n print(f\"Unable to get default branch for `{self._repo}`\")\n return None\n\n url = f\"https://raw.githubusercontent.com/{self._repo}/{default_branch}/{self._file}\"\n downloaded_file_path = _download_file_to(DOWNLOADS_TEMP_PATH, url)\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass GithubAsset:\n _repo: str\n _asset_name: Optional[str]\n _asset_regex: Optional[str]\n\n def _get_asset(self, assets: Any) -> Optional[Any]:\n for asset in assets:\n asset_name: str = asset[\"name\"]\n\n if self._asset_name is not None:\n if asset_name == self._asset_name:\n return asset\n elif self._asset_regex is not None:\n if re.search(self._asset_regex, asset_name) is not None:\n return asset\n\n return None\n\n def _get_cached_lock(\n self, lock_list: List[DownloaderLock]\n ) -> Optional[DownloaderLock]:\n for lock in lock_list:\n if lock.repo == self._repo:\n if self._asset_name is not None:\n if lock.asset_name == self._asset_name:\n return lock\n elif self._asset_regex is not None:\n if re.search(self._asset_regex, lock.asset_name) is not None:\n return lock\n return None\n\n def download(\n self,\n lock_list: List[DownloaderLock],\n token: Optional[str],\n ) -> Optional[Path]:\n latest_release = _get_latest_release(self._repo, token)\n\n if latest_release is None:\n print(f\"Unable to get latest release for `{self._repo}`\")\n return None\n\n asset = self._get_asset(latest_release[\"assets\"])\n\n if asset is None:\n print(f\"Unable to get matching asset for `{self._repo}`\")\n return None\n\n asset_name = asset[\"name\"]\n current_lock = DownloaderLock(\n self._repo,\n latest_release[\"tag_name\"],\n asset_name,\n asset[\"updated_at\"],\n )\n cached_lock = self._get_cached_lock(lock_list)\n\n if cached_lock is not None:\n cached_asset_path = cached_lock.cached_asset_path()\n\n if cached_lock == current_lock:\n print(f\"\\t{self._repo}: Already up to date\")\n return cached_asset_path\n\n shutil.rmtree(cached_asset_path.parent)\n logging.info(\"Removed `%s`\", cached_asset_path.parent)\n\n lock_list.remove(cached_lock)\n\n print(f\"\\t{self._repo}: {asset_name}\")\n\n url = asset[\"browser_download_url\"]\n\n downloaded_file_path = _download_file_to(\n current_lock.cached_asset_path().parent, url\n )\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n lock_list.append(current_lock)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass RawUrl:\n _url: str\n\n def download(\n self,\n ) -> Optional[Path]:\n print(f\"\\t{_get_file_name_from_url(self._url)}\")\n\n downloaded_file_path = _download_file_to(DOWNLOADS_TEMP_PATH, self._url)\n\n if downloaded_file_path is not None:\n logging.info(\"File downloaded to `%s`\", downloaded_file_path)\n\n return downloaded_file_path\n\n\n@dataclass(frozen=True)\nclass Downloader:\n _downloader_type: Union[GithubFile, GithubAsset, RawUrl]\n\n def download(\n self,\n lock_list: List[DownloaderLock],\n token: Optional[str],\n ) -> Optional[Path]:\n if isinstance(self._downloader_type, GithubAsset):\n downloaded_file_path = self._downloader_type.download(lock_list, token)\n elif isinstance(self._downloader_type, GithubFile):\n downloaded_file_path = self._downloader_type.download(token)\n elif isinstance(self._downloader_type, RawUrl):\n downloaded_file_path = self._downloader_type.download()\n else:\n raise AssertionError(\"This branch should be unreachable.\")\n\n return downloaded_file_path\n\n\ndef createDownloader(\n repo: Optional[str],\n asset_name: Optional[str],\n asset_regex: Optional[str],\n file: Optional[str],\n url: Optional[str],\n) -> Downloader:\n if (repo is None) == (url is None):\n raise RuntimeError(\"Either `repo` or `url` must be provided\")\n\n if (repo is not None) and (\n (asset_name is None) == (asset_regex is None) == (file is None)\n ):\n raise RuntimeError(\n \"Either `asset_name`, `asset_regex` or `file` must be provided\"\n )\n\n if (url is not None) and (\n asset_name is not None or asset_regex is not None or file is not None\n ):\n raise RuntimeError(\"`url` must be provided alone\")\n\n if repo and (asset_name or asset_regex):\n return Downloader(GithubAsset(repo, asset_name, asset_regex))\n\n if repo and file:\n return Downloader(GithubFile(repo, file))\n\n if url:\n return Downloader(RawUrl(url))\n\n raise AssertionError(\"This branch should be unreachable.\")\n","repo_name":"lucasaf04/Switch-Updater","sub_path":"src/Downloader.py","file_name":"Downloader.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"22568977545","text":"# -*- coding: utf-8 -*-\n\nimport units.predefined\nfrom units import unit, named_unit, scaled_unit, si_prefixed_unit\nfrom units.quantity import Quantity\nfrom units.compatibility import compatible as strictly_compatible, within_epsilon\nfrom units.exception import IncompatibleUnitsError\n\ndef no_converter(_ignored):\n raise IncompatibleUnitsError(\"No known conversion between classes\")\n\nclass RelatedUnitConveter(object):\n RELATIONSHIPS = {}\n\n @staticmethod\n def get_converter(source_unit, target_unit):\n return RelatedUnitConveter.RELATIONSHIPS.get((source_unit.canonical(), target_unit.canonical()))\n\n def __init__(self, source_unit, target_unit, forward_converter=no_converter, backward_converter=no_converter):\n self.source_unit = source_unit\n self.target_unit = target_unit\n self.key = (source_unit.canonical(), target_unit.canonical())\n self.reverse_key = tuple(reversed(self.key))\n self.forward_converter = forward_converter or no_converter\n self.backward_converter = backward_converter or no_converter\n if self.key not in self.RELATIONSHIPS and forward_converter is not None:\n self.RELATIONSHIPS[self.key] = self\n if self.reverse_key not in self.RELATIONSHIPS and backward_converter is not None:\n self.invert() # Will auto-register\n\n def translate(self, source_quantity, target_unit=None):\n if not isinstance(source_quantity, Quantity):\n source_quantity = Quantity(source_quantity, self.source_unit)\n target_unit = target_unit or self.target_unit\n converter_source_quantity = strict_convert_to_unit(source_quantity, self.source_unit)\n converter_target_quantity = Quantity(self.forward_converter(converter_source_quantity), self.target_unit)\n target_quantity = strict_convert_to_unit(converter_target_quantity, target_unit)\n return target_quantity\n\n def invert(self):\n return RelatedUnitConveter(self.target_unit, self.source_unit, self.backward_converter, self.forward_converter)\n\ndef related_unit_converter(source_unit, target_unit, forward_converter=None, backward_converter=None):\n converter = RelatedUnitConveter.get_converter(source_unit, target_unit)\n if converter:\n return converter\n if forward_converter is None and backward_converter is None:\n return None\n return RelatedUnitConveter(source_unit, target_unit, forward_converter=forward_converter, backward_converter=no_converter)\n\nunits.predefined.define_units()\n\n\"\"\"Temperature units.\"\"\"\ncelcius = unit(u'°C') # Celsius\nferenheit = unit(u'°F') # Ferenheit\nrelated_unit_converter(ferenheit, celcius, lambda f: (f - 32) * 5.0 / 9.0, lambda c: (c * 9.0 / 5.0) + 32)\n\ndef compatible(unit1, unit2):\n if strictly_compatible(unit1, unit2):\n return True\n return related_unit_converter(unit1, unit2) is not None\n\ndef strict_convert_to_unit(quantity, target_unit):\n if not isinstance(quantity, Quantity):\n IncompatibleUnitsError(\"No units defined for conversion\")\n return target_unit(quantity / target_unit(1.0))\n\ndef convert_to_unit(quantity, target_unit):\n if not isinstance(quantity, Quantity):\n IncompatibleUnitsError(\"No units defined for conversion\")\n try:\n return strict_convert_to_unit(quantity, target_unit)\n except IncompatibleUnitsError as e:\n try:\n converter = related_unit_converter(quantity.unit, target_unit)\n if not converter:\n raise e\n return converter.translate(quantity, target_unit)\n except IncompatibleUnitsError:\n raise e\n","repo_name":"MSeal/inkworks","sub_path":"octoprint_inkworks/dataunits.py","file_name":"dataunits.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7423325376","text":"import os\nimport random\nfrom typing import NamedTuple\n\nfrom dotenv import load_dotenv\nfrom game_enums import Color\n\nif os.path.exists(os.path.join(os.path.dirname(__file__), '.env')):\n load_dotenv(os.path.join(os.path.dirname(__file__), '.env'))\n\n\nclass Config(NamedTuple):\n game_field_size: int\n count_players: int\n bot_name: str\n player_symbols: list[str]\n colors: list[Color]\n\n\ndef get_config() -> Config:\n color_values = os.environ.get(\"COLORS\", \"yellow,red\").split(\",\")\n game_colors = []\n for color in color_values:\n game_colors.append(Color(color))\n game_symbols = os.environ.get(\"PLAYER_SYMBOLS\", \"X,O\").split(\",\")\n random.shuffle(game_symbols)\n return Config(\n game_field_size=os.environ.get(\"GAME_FIELD_SIZE\", 3),\n count_players=os.environ.get(\"COUNT_PLAYERS\", 2),\n bot_name=os.environ.get(\"BOT_NAME\", \"Бот\"),\n player_symbols=game_symbols,\n colors=game_colors,\n )\n","repo_name":"abirukov/tic_tac_toe","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"42171480900","text":"from django import template\n\nregister = template.Library()\n\n@register.filter(name=\"samplefunc\")\ndef sampleFunc(value):\n return value\n\n\n@register.filter(name=\"percen\")\ndef percen(value,args):\n ans = value\n su = ans.trust + ans.sadness + ans.disgust + ans.anticipation + ans.surprise + ans.joy + ans.fear + ans.anger\n \n if args==\"sadness\":\n return ans.sadness*100.0/su\n elif args==\"anger\":\n return ans.anger*100.0/su\n elif args==\"fear\":\n return ans.fear*100.0/su\n elif args==\"trust\":\n return ans.trust*100.0/su\n elif args==\"disgust\":\n return ans.disgust*100.0/su\n elif args==\"anticipation\":\n return ans.anticipation*100.0/su\n elif args==\"joy\":\n return ans.joy*100.0/su\n elif args==\"surprise\":\n return ans.surprise*100.0/su\n\n@register.filter(name=\"posinegi\")\ndef posinegi(value,args):\n ans = value\n su = ans.positive + ans.negative\n \n if args==\"up\":\n return ans.positive*100/su\n elif args==\"down\":\n return ans.negative*100/su\n","repo_name":"vishwerine/SentimentVis","sub_path":"sentimentvis/templatetags/temp_extras.py","file_name":"temp_extras.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23496279731","text":"import lightgbm as lgb\nimport os\nfrom sklearn.datasets import load_iris\nfrom lgbserver import LightGBMModel\nimport pandas as pd\nimport numpy\nfrom kserve.protocol.infer_type import InferInput, InferRequest\n\nmodel_dir = os.path.join(os.path.dirname(__file__), \"example_model\", \"model\")\nBST_FILE = \"model.bst\"\nNTHREAD = 1\n\n\ndef test_model():\n iris = load_iris()\n y = iris['target']\n X = pd.DataFrame(iris['data'], columns=iris['feature_names'])\n dtrain = lgb.Dataset(X, label=y)\n\n params = {\n 'objective': 'multiclass',\n 'metric': 'softmax',\n 'num_class': 3\n }\n lgb_model = lgb.train(params=params, train_set=dtrain)\n model_file = os.path.join(model_dir, BST_FILE)\n lgb_model.save_model(model_file)\n model = LightGBMModel(\"model\", model_dir, NTHREAD)\n model.load()\n\n request = {'sepal_width_(cm)': {0: 3.5}, 'petal_length_(cm)': {0: 1.4},\n 'petal_width_(cm)': {0: 0.2}, 'sepal_length_(cm)': {0: 5.1}}\n\n response = model.predict({\"inputs\": [request, request]})\n assert numpy.argmax(response[\"predictions\"][0]) == 2\n\n response = model.predict({\"instances\": [request, request]})\n assert numpy.argmax(response[\"predictions\"][0]) == 2\n # test v2 handler\n infer_input = InferInput(name=\"input-0\", shape=[2, 4], datatype=\"FP32\",\n data=[[6.8, 2.8, 4.8, 1.6], [6.0, 3.4, 4.5, 1.6]])\n infer_request = InferRequest(model_name=\"model\", infer_inputs=[infer_input])\n infer_response = model.predict(infer_request)\n assert infer_response.to_rest()[\"outputs\"] == \\\n [{'name': 'output-0', 'shape': [2, 3], 'datatype': 'FP64',\n 'data': [3.7899802486733807e-06, 0.9996982074114203, 0.00029800260833088297,\n 5.2172911836629736e-05, 0.99973341723876, 0.000214409849403366]}]\n","repo_name":"kserve/kserve","sub_path":"python/lgbserver/lgbserver/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","stars":2598,"dataset":"github-code","pt":"52"}
+{"seq_id":"27275086728","text":"import csv\r\nfrom modules.head import *\r\nfrom modules.DataPacket import DataPacket\r\n\r\ndef read_surveys(data_packet, admin_perms, courses):\r\n \"\"\" We are going to go through the list of DataPackets and translate it\r\n into something that can rendered into the templates\r\n \"\"\"\r\n renderable = [] # List to hold the information that can used by Jinja2\r\n data_list = data_packet.retrieve_data()\r\n course_list = []\r\n if courses:\r\n for course in courses:\r\n course_list.append(*course)\r\n\r\n for data in data_list:\r\n # Go through each data and translate it into just 3 strings that can\r\n # be stored in a list\r\n if not admin_perms:\r\n if data[1] in course_list:\r\n renderable.append([data[0], data[1], data[2], data[3]])\r\n else:\r\n renderable.append([data[0], data[1], data[2], data[3]])\r\n\r\n return renderable\r\n\r\ndef create_survey(data_packet, survey_id, course, question_list, state):\r\n \"\"\" We are going to get the raw data and convert it into a DataPacket\r\n object which we will return\r\n \"\"\"\r\n questions = ','.join(str(x) for x in question_list)\r\n data_packet.add_data([survey_id, course, questions, state])\r\n\r\n return data_packet\r\n\r\ndef get_course_list():\r\n information = []\r\n with open(\"storage/courses.csv\", \"r\") as csvfile:\r\n csvreader = csv.reader(csvfile)\r\n for row in csvreader:\r\n row_str = row[0] + ' ' + row[1]\r\n information.append(row_str)\r\n return information\r\n\r\ndef add_course(course):\r\n with open(\"storage/courses.csv\", \"a\") as csvfile:\r\n csvwriter = csv.writer(csvfile)\r\n csvwriter.write(course)\r\n","repo_name":"Jackson-Luu/Survey-Website-System","sub_path":"modules/SurveyManager.py","file_name":"SurveyManager.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"31160891440","text":"import mysql.connector\nimport requests\nimport json\n\n\n\n##########################################################################3\n## funciones\n#########################################################################3#\n\n############################\n# CONECTAR DB\ndef conectardb():\n mydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"Christian\",\n password=\"chinito2312\",\n database=\"binance\"\n )\n return mydb\n#############################\ndef getPrecio(Moneda):\n mydb=conectardb()\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT a.Precio FROM `ML_Localidades` a INNER JOIN ML_Partidos b ON a.IdPartido=b.Id where a.Id='\"+Localidad+\"'\")\n myresult = mycursor.fetchone()\n return(myresult)\n\n\n#############################\ndef insertarValores(valores):\n mydb=conectardb()\n mycursor = mydb.cursor()\n #sql = \"DELETE FROM `Recolector`.`Indicadores_BCRA` WHERE Metrica='\"+Metrica+\"'\"\n #mycursor.execute(sql)\n\n sql = \"INSERT INTO `binance`.`Precios` (fecha,Moneda,Precio) VALUES (%s,%s, %s)\"\n mycursor.executemany(sql, valores)\n mydb.commit()\n\n #print(mycursor.rowcount, \"was inserted.\")\n#############################\ndef insertarPromedios(valores):\n mydb=conectardb()\n mycursor = mydb.cursor()\n #sql = \"DELETE FROM `Recolector`.`Indicadores_BCRA` WHERE Metrica='\"+Metrica+\"'\"\n #mycursor.execute(sql)\n\n sql = \"INSERT INTO `binance`.`Promedios` (fecha,Moneda,Precio) VALUES (%s,%s, %s)\"\n mycursor.executemany(sql, valores)\n mydb.commit()\n\n #print(mycursor.rowcount, \"was inserted.\")\n\n#############################\ndef getUrl(url,head):\n r = requests.get(url,headers=head) \n valoresTemp = json.loads(r.text)\n print(\"Respuesta:\",valoresTemp)\n#############################\ndef getUrl2(url):\n r = requests.get(url) \n valoresTemp = json.loads(r.text)\n print(\"Respuesta:\",valoresTemp)\n############################################# \ndef UpdateValores(url):\n Hora=getHora()\n r = requests.get(url) \n Registros = json.loads(r.text)\n valores=[]\n valoresTemp=[]\n for Registro in Registros:\n\n valoresTemp=[Hora,Registro['symbol'],str(Registro['price'])]\n print(valoresTemp)\n valores.append(valoresTemp)\n insertarValores(valores)\n############################################# \ndef UpdateValor(url,Simbolos):\n valores=[]\n Hora=getHora()\n for Simbolo in Simbolos:\n \n r = requests.get(url+'?symbol='+Simbolo) \n Registro = json.loads(r.text)\n valoresTemp=[]\n valoresTemp=[Hora,Registro['symbol'],str(Registro['price'])]\n valores.append(valoresTemp)\n insertarValores(valores)\n print(valores) \n############################################# \ndef UpdatePromedio(url,Simbolos):\n valores=[]\n Hora=getHora()\n for Simbolo in Simbolos:\n \n r = requests.get(url+'?symbol='+Simbolo) \n Registro = json.loads(r.text)\n valoresTemp=[]\n valoresTemp=[Hora,Simbolo,str(Registro['price'])]\n valores.append(valoresTemp)\n insertarPromedios(valores)\n print(valores) \n############################################### \ndef getHora():\n r = requests.get(\"https://testnet.binanceops.com/vapi/v1/time\") \n valoresTemp = json.loads(r.text)\n #print(\"Respuesta:\",valoresTemp[\"data\"])\n return valoresTemp[\"data\"] \n###################################################3\n\n\n\n\n#TraerHora \n#getUrl(\"https://testnet.binanceops.com/vapi/v1/time\")\nHora=getHora()\nprint(Hora)\n\n#headers = {\"apikey\": \"22BjeOROKiXJ3NxbR3zjh3uoGcaflPu3VMyBXAg8Jj2J1xVSnY0eB4dzacdE9IWn\",\"secretKey\":\"YtP1BudNOWZE1ag5uzCkh4hIC7qSmQOu797r5EJBFGhxBYivjj8HIX0iiiPof5yG\"}\nheaders = {\"apikey\": \"ucGsCr6I9ehZn5i51MlOIXThWrM6bObvQ91nkpeiIaKMAgM8N7ZGPLbUXPbBdOuV\",\"secretKey\":\"kjTXifn9ny7kAthuWBuBnM6DOVLKTaHOxxldfWjLdK4dqMwrLLnQPh5ygmQ4y6m1\"}\n\nh2 = {\"prueba\": \"prueba\"}\n#getUrl(\"https://testnet.binanceops.com/vapi/v1/position?BTC-200730-9000-C&recvWindow=500000×tamp=\"+str(Hora),headers)\n#getUrl2(\"https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC&symbol=BTCUSDT\")\n#getUrl2('https://api.binance.com/api/v3/exchangeInfo?symbols=[\"BNBBTC\",\"BTCUSDT\",\"ETHUSDT\"]')\n#getUrl2('https://api.binance.com/api/v3/exchangeInfo?symbols=[\"ETHUSDT\"]')\n\n#Precio Actual\n#getUrl2('https://api.binance.com/api/v3/ticker/price?symbol=ETHUSDT')\n#getUrl2('https://api.binance.com/api/v3/ticker/price?symbol=ETHEUR')\ni=1\nwhile i>0:\n #UpdateValores('https://api.binance.com/api/v3/ticker/price')\n\n Monedas=['BTCUSDT','ETHUSDT','ETHEUR']\n UpdateValor('https://api.binance.com/api/v3/ticker/price',Monedas)\n UpdatePromedio('https://api.binance.com/api/v3/avgPrice',Monedas)\n#getUrl2('https://api.binance.com/api/v3/ticker/bookTicker')\n\n\n\n\n#Precio Promedio\n#getUrl2('https://api.binance.com/api/v3/avgPrice?symbol=ETHUSDT')\n\n#curl -v -H \"apikey:22BjeOROKiXJ3NxbR3zjh3uoGcaflPu3VMyBXAg8Jj2J1xVSnY0eB4dzacdE9IWn\" -H \"secretKey:YtP1BudNOWZE1ag5uzCkh4hIC7qSmQOu797r5EJBFGhxBYivjj8HIX0iiiPof5yG\" -X GET 'https://testnet.binanceops.com/vapi/v1/position?BTC-200730-9000-C&recvWindow=500000×tamp=1633710030'\n ","repo_name":"christianmoraga/pruebaDocker","sub_path":"AnalizarDatos.py","file_name":"AnalizarDatos.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3951280419","text":"import csv #imports the csv file\n\nfile = open('GUNS 2012 - Timeline1.csv') #change name of exported file each time, if needed\ncsv_file = csv.reader(file) #creates CSV object that's parsed\n\ntime_line = open(r'timeline_test_.txt', 'a') #opens a file and appends information inside\n\nnumber = 68\n\nfor row in csv_file:\n panel1 = \"\"\"\n \n \n
\n
%s
\n

\n \"\"\" % (row[0], str(number), str(number), row[1], row[0])\n time_line.write(panel1)\n if row[2] != \"None\":\n panel2 = \"\"\"

\n \"\"\" % (str(number), str(number), row[2], row[0])\n time_line.write(panel2)\n panel3 = \"\"\"
%s
\n
%s
\n
\n
\n
\n \\n\n \"\"\" % (row[3], row[4])\n time_line.write(panel3)\n number += 1\n \nfile.close()\n\ntime_line.close()","repo_name":"matthewpleasant/timeline_test","sub_path":"test_timeline_code.py","file_name":"test_timeline_code.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1036361537","text":"import requests\nimport json \n\nclass Stock:\n baseUrl = \"https://finnhub.io/api/v1/stock/\"\n key = \"bq4ih7frh5rbnj6k5l1g\"\n \n edgarKey = '9f4d11d4c5101b97f88db2d4a2bdd7c8'\n edgarBaseUrl = 'https://datafied.api.edgar-online.com/v2' \n \n def __init__(self, ticker):\n self.ticker = ticker\n \n def GetInsiderFiling(self):\n # from edgar \n queryUrl = self.edgarBaseUrl + '/insiders/filers?'\n params = {'issuetickers' : self.ticker, 'appkey' : self.edgarKey}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetCurrentIssueHolders(self):\n # from edgar \n queryUrl = self.edgarBaseUrl + '/ownerships/currentissueholders?'\n params = {'limit' : 9999, 'tickers' : self.ticker, 'appkey' : self.edgarKey}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetCurrentIssueHoldersSince(self):\n # from edgar - NOT WORKING \n queryUrl = 'https://datafied.api.edgar-online.com/v2/ownerships/currentissueholders?modifiedsince eq \"12/30/2019\"&appkey={9f4d11d4c5101b97f88db2d4a2bdd7c8}'\n r = requests.get(queryUrl)\n print(r.url)\n return r\n \n def GetCurrentIssueHolders2(self):\n # from edgar - NOT WORKING \n # https://datafied.api.edgar-online.com/v2/ownerships/currentownerholdings?filter=ticker eq \"BAC\"&appkey={APPKEY}\n #queryUrl = self.edgarBaseUrl + 'ownerships/currentownerholdings?'\n #filter = 'ticker eq ' + '\"{}\"'.format(self.ticker)\n #params = {'filter' : filter, 'appkey' : self.edgarKey}\n queryUrl = 'https://datafied.api.edgar-online.com/v2/ownerships/currentownerholdings?filter=ticker eq \"BAC\"&appkey={9f4d11d4c5101b97f88db2d4a2bdd7c8}'\n r = requests.get(queryUrl)\n print(r.url)\n return r\n \n def GetInvestorOwnership(self):\n #queryUrl = self.baseUrl + 'investor-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n #return requests.get(queryUrl)\n queryUrl = self.baseUrl + 'investor-ownership?'\n params = {'symbol' : self.ticker, 'token' : self.key}\n r = requests.get(queryUrl, params)\n print(r.url)\n return r\n \n def GetInvestorOwnershipYahoo(self):\n #queryUrl = self.baseUrl + 'investor-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n #return requests.get(queryUrl)\n url = \"https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-holders\"\n querystring = {\"symbol\":self.ticker}\n headers = {\n 'x-rapidapi-host': \"apidojo-yahoo-finance-v1.p.rapidapi.com\",\n 'x-rapidapi-key': \"e9b6a8fdf8msh9fbafd25ae17073p13647ejsnd27aee4ff878\"\n }\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\n print(response.text)\n return response\n \n def GetFundOwnership(self):\n queryUrl = self.baseUrl + 'fund-ownership?symbol={}&token={}'.format(self.ticker, self.key)\n return requests.get(queryUrl)\n def GetData(self):\n ''' this gets the entire data for a given ticket'''\n ''' Still need to validate the data '''\n ''' https://eodhistoricaldata.com/knowledgebase/stock-etfs-fundamental-data-feeds/'''\n queryUrl = \"https://eodhistoricaldata.com/api/fundamentals/AAPL.US?api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX\"\n return requests.get(queryUrl)\n def GetMostActive(self):\n queryUrl = \"https://financialmodelingprep.com/api/v3/company/rating/ONTX\"\n return requests.get(queryUrl)\n def GetRealTimePrice(self):\n queryUrl = 'https://financialmodelingprep.com/api/v3/real-time-price/AAPL'\n return requests.get(queryUrl)\n def GetSymbolList(self):\n baseUrl = 'https://financialmodelingprep.com/'\n queryUrl = baseUrl + 'api/v3/company/stock/list'\n return requests.get(queryUrl)\n def GetHistoricalData(self):\n baseUrl = 'https://financialmodelingprep.com/'\n queryUrl = baseUrl + 'api/v3/historical-price-full/AAPL?timeseries=244'\n return requests.get(queryUrl)\n \n \nstock = Stock(\"MITT\")\nresult = stock.GetHistoricalData()\nif (result.status_code == 200):\n print(\"success\")\n with open(\"data.json\", \"w\") as f:\n json.dump(result.json(), f, indent=4);\nelse:\n print (\"failed\") \n#result2 = stock.GetCurrentIssueHolders2()\n# result = stock.GetData()\n#result = stock.GetMostActive()\n#with open(\"data2.json\", \"w\") as f:\n #json.dump(result2.json(), f, indent=4);\n","repo_name":"batukuri/temp","sub_path":"GetData.py","file_name":"GetData.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16045894241","text":"import os\nimport torch\nimport numpy as np\nimport glob\nfrom torch_geometric.data import Data, InMemoryDataset\nfrom torch_geometric.utils import add_self_loops\nfrom utils import binvox_rw\n\n\nclass GraphDataset(InMemoryDataset):\n def __init__(self, root):\n super(GraphDataset, self).__init__(root)\n self.data, self.slices = torch.load(self.processed_paths[0])\n\n @property\n def raw_file_names(self):\n raw_v_filelist = glob.glob(os.path.join(self.root, '*_v.txt'))\n return raw_v_filelist\n\n @property\n def processed_file_names(self):\n return '{:s}_skeleton_data.pt'.format(self.root.split('/')[-1])\n\n def __len__(self):\n return len(self.raw_paths)\n\n def download(self):\n pass\n\n def sample_on_bone(self, p_pos, ch_pos):\n ray = ch_pos - p_pos\n bone_length = np.sqrt(np.sum((p_pos - ch_pos) ** 2))\n num_step = np.round(bone_length / 0.01)\n i_step = np.arange(1, num_step + 1)\n unit_step = ray / (num_step + 1e-30)\n unit_step = np.repeat(unit_step[np.newaxis, :], num_step, axis=0)\n res = p_pos + unit_step * i_step[:, np.newaxis]\n return res\n\n def inside_check(self, pts, vox):\n vc = (pts - vox.translate) / vox.scale * vox.dims[0]\n vc = np.round(vc).astype(int)\n ind1 = np.logical_and(np.all(vc >= 0, axis=1), np.all(vc < vox.dims[0], axis=1))\n vc = np.clip(vc, 0, vox.dims[0]-1)\n ind2 = vox.data[vc[:, 0], vc[:, 1], vc[:, 2]]\n ind = np.logical_and(ind1, ind2)\n pts = pts[ind]\n return pts, np.argwhere(ind).squeeze()\n\n def process(self):\n data_list = []\n i = 0.0\n for v_filename in self.raw_paths:\n print('preprecessing data complete: {:.4f}%'.format(100 * i / len(self.raw_paths)))\n i += 1.0\n v = np.loadtxt(v_filename)\n m = np.loadtxt(v_filename.replace('_v.txt', '_attn.txt'))\n v = torch.from_numpy(v).float()\n m = torch.from_numpy(m).long()\n tpl_e = np.loadtxt(v_filename.replace('_v.txt', '_tpl_e.txt')).T\n geo_e = np.loadtxt(v_filename.replace('_v.txt', '_geo_e.txt')).T\n tpl_e = torch.from_numpy(tpl_e).long()\n geo_e = torch.from_numpy(geo_e).long()\n tpl_e, _ = add_self_loops(tpl_e, num_nodes=v.size(0))\n geo_e, _ = add_self_loops(geo_e, num_nodes=v.size(0))\n y = np.loadtxt(v_filename.replace('_v.txt', '_j.txt'))\n num_joint = len(y)\n joint_pos = y\n if len(y) < len(v):\n y = np.tile(y, (round(1.0 * len(v) / len(y) + 0.5), 1))\n y = y[:len(v), :]\n elif len(y) > len(v):\n y = y[:len(v), :]\n y = torch.from_numpy(y).float()\n\n adj = np.loadtxt(v_filename.replace('_v.txt', '_adj.txt'), dtype=np.uint8)\n\n vox_file = v_filename.replace('_v.txt', '.binvox')\n with open(vox_file, 'rb') as fvox:\n vox = binvox_rw.read_as_3d_array(fvox)\n pair_all = []\n for joint1_id in range(adj.shape[0]):\n for joint2_id in range(joint1_id + 1, adj.shape[1]):\n dist = np.linalg.norm(joint_pos[joint1_id] - joint_pos[joint2_id])\n bone_samples = self.sample_on_bone(joint_pos[joint1_id], joint_pos[joint2_id])\n bone_samples_inside, _ = self.inside_check(bone_samples, vox)\n outside_proportion = len(bone_samples_inside) / (len(bone_samples) + 1e-10)\n pair = np.array([joint1_id, joint2_id, dist, outside_proportion, adj[joint1_id, joint2_id]])\n pair_all.append(pair)\n pair_all = np.array(pair_all)\n pair_all = torch.from_numpy(pair_all).float()\n num_pair = len(pair_all)\n\n name = int(v_filename.split('/')[-1].split('_')[0])\n data_list.append(Data(x=v[:, 3:6], pos=v[:, 0:3], name=name, mask=m, y=y, num_joint=num_joint,\n tpl_edge_index=tpl_e, geo_edge_index=geo_e, pairs=pair_all, num_pair=num_pair))\n data, slices = self.collate(data_list)\n torch.save((data, slices), self.processed_paths[0])\n","repo_name":"tonightio/rigme","sub_path":"RigNet_master/datasets/skeleton_dataset.py","file_name":"skeleton_dataset.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"52"}
+{"seq_id":"30709216225","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\nimport math\nimport re\nfrom tkinter import *\n\n\ncal_state = False\n\ndef showText0():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '0')\n if tmp.get() is not '':\n tmp.insert(END, '0')\n\n\ndef showText1():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '1')\n if tmp.get() is not '':\n tmp.insert(END, '1')\n\ndef showText2():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '2')\n if tmp.get() is not '':\n tmp.insert(END, '2')\n\ndef showText3():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '3')\n if tmp.get() is not '':\n tmp.insert(END, '3')\n\ndef showText4():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '4')\n if tmp.get() is not '':\n tmp.insert(END, '4')\n\ndef showText5():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '5')\n if tmp.get() is not '':\n tmp.insert(END, '5')\n\ndef showText6():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '6')\n if tmp.get() is not '':\n tmp.insert(END, '6')\n\ndef showText7():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '7')\n if tmp.get() is not '':\n tmp.insert(END, '7')\n\ndef showText8():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '8')\n if tmp.get() is not '':\n tmp.insert(END, '8')\n\ndef showText9():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '9')\n if tmp.get() is not '':\n tmp.insert(END, '9')\n\ndef showTextP():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '.')\n if tmp.get() is not '':\n tmp.insert(END, '.')\n\ndef showTextPG():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, '(')\n if tmp.get() is not '':\n tmp.insert(END, '(')\n\ndef showTextPD():\n global entry, cal_state, tmp\n if cal_state is True:\n entry.delete(0, END)\n cal_state = False\n entry.insert(END, ')')\n if tmp.get() is not '':\n tmp.insert(END, ')')\n\ndef Addition():\n global entry, cal_state, tmp\n entry.insert(END, '+')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '+')\n\ndef Soustraction():\n global entry, cal_state, tmp\n entry.insert(END, '-')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '-')\n\ndef Multiplication():\n global entry, cal_state, tmp\n entry.insert(END, '*')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '*')\n\ndef Division():\n global entry, cal_state, tmp\n entry.insert(END, '/')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '/')\n\ndef Puissance():\n global entry, cal_state, tmp\n entry.insert(END, '^')\n cal_state = False\n if tmp.get() is not '':\n tmp.insert(END, '^')\n\ndef Sin():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'sin(' + txt + ')')\n tmp.insert(END, 'math.sin(math.radians(' + txt + '))')\n cal_state = False\n\ndef Cos():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'cos(' + txt + ')')\n tmp.insert(END, 'math.cos(math.radians(' + txt + '))')\n cal_state = False\n\ndef Tan():\n global entry, cal_state, tmp\n txt = entry.get()\n entry.delete(0, END)\n entry.insert(END, 'tan(' + txt + ')')\n tmp.insert(END, 'math.tan(math.radians(' + txt + '))')\n cal_state = False\n\ndef effaceDernierChiffre():\n global entry, cal_state, tmp\n entry.delete(len(entry.get())-1, END)\n tmp.delete(len(tmp.get()) - 1, END)\n cal_state = False\n\ndef effaceTous():\n global entry, cal_state, tmp\n entry.delete(0, END)\n tmp.delete(0, END)\n cal_state = False\n\ndef calculate():\n global result, x, y, entry, cal_state, textnote, L_Note,tmp\n txt = entry.get()\n indicator_list = [\"sin\", \"cos\",\"tan\"]\n try:\n if '^' in txt:\n txt = txt.replace('^', '**')\n result = eval(txt)\n elif any(indicator in txt for indicator in indicator_list):\n txt = tmp.get()\n result = eval(txt)\n else:\n result = eval(txt)\n entry.delete(0, END)\n entry.insert(0, result)\n cal_state = True\n L_Note.configure(text=\"\")\n tmp.delete(0, END)\n\n except SyntaxError:\n assert L_Note.configure(text = \"Syntax Error !!!\"), \"Syntax Error !!\"\n\n\n\n\nfenetre = Tk()\n\nfenetre.title('Calculatrice')\nsw = fenetre.winfo_screenwidth()\nsh = fenetre.winfo_screenheight()\nww = 400\nwh = 570\nx = (sw - ww) / 2\ny = (sh - wh) / 2\nfenetre.geometry(\"%dx%d+%d+%d\" % (ww, wh, x, y))\nfenetre.resizable(0,0)\n\nmenuBar = Menu(fenetre)\nmenu = Menu(menuBar)\nfor item in ['Aide', 'Mode Basique', 'Mode Scientifique']:\n menu.add_command(label = item)\nmenuBar.add_cascade(label = \"Menu\", menu = menu)\nfenetre['menu'] = menuBar\n\n\n\nentry = Entry(fenetre, font=(20), bg=('grey'))\ntmp = Entry(fenetre)\nentry.grid(row = 0, column = 1, columnspan = 5, ipadx = 110, ipady = 10)\nB_Puissance = Button(fenetre, text='^', width = 10, height = 5, command = Puissance).grid(row = 1, column = 1)\nB_sin = Button(fenetre, text='sin', width = 10, height = 5, command = Sin).grid(row = 1, column = 2)\nB_cos = Button(fenetre, text='cos', width = 10, height = 5, command = Cos).grid(row = 1, column = 3)\nB_tan = Button(fenetre, text='tan', width = 10, height = 5, command = Tan).grid(row = 1, column = 4)\nB_1 = Button(fenetre, text='1', width = 10, height = 5, command = showText1).grid(row = 2, column = 1)\nB_2 = Button(fenetre, text='2', width = 10, height = 5, command = showText2).grid(row = 2, column = 2)\nB_3 = Button(fenetre, text='3', width = 10, height = 5, command = showText3).grid(row = 2, column = 3)\nB_4 = Button(fenetre, text='4', width = 10, height = 5, command = showText4).grid(row = 3, column = 1)\nB_5 = Button(fenetre, text='5', width = 10, height = 5, command = showText5).grid(row = 3, column = 2)\nB_6 = Button(fenetre, text='6', width = 10, height = 5, command = showText6).grid(row = 3, column = 3)\nB_7 = Button(fenetre, text='7', width = 10, height = 5, command = showText7).grid(row = 4, column = 1)\nB_8 = Button(fenetre, text='8', width = 10, height = 5, command = showText8).grid(row = 4, column = 2)\nB_9 = Button(fenetre, text='9', width = 10, height = 5, command = showText9).grid(row = 4, column = 3)\nB_0 = Button(fenetre, text='0', width = 10, height = 5, command = showText0).grid(row = 5, column = 1)\nB_P = Button(fenetre, text='.', width = 10, height = 5, command = showTextP).grid(row = 5, column = 2)\nB_E = Button(fenetre, text='=', width = 10, height = 5, command = calculate).grid(row = 5, column = 5)\nB_AC = Button(fenetre, text='AC', width = 10, height = 5, command = effaceTous).grid(row = 2, column = 5)\nB_PG = Button(fenetre, text='(', width = 10, height = 5, command = showTextPG).grid(row = 5, column = 3)\nB_PD = Button(fenetre, text=')', width = 10, height = 5, command = showTextPD).grid(row = 5, column = 4)\nB_C = Button(fenetre, text='C', width = 10, height = 5, command = effaceDernierChiffre).grid(row = 3, column = 5)\nB_Plus = Button(fenetre, text='+', width = 10, height = 5, command = Addition).grid(row = 2, column = 4)\nB_Moins = Button(fenetre, text='-', width = 10, height = 5, command = Soustraction).grid(row = 3, column = 4)\nB_Multiple = Button(fenetre, text='*', width = 10, height = 5, command = Multiplication).grid(row = 4, column = 4)\nB_Division = Button(fenetre, text='/', width = 10, height = 5, command = Division).grid(row = 4, column = 5)\nL_Note = Label(fenetre)\nL_Note.grid(row=6, column=1, columnspan=5)\n\nfenetre.mainloop()\n","repo_name":"GuoJulie/Python_TP","sub_path":"TP2_Tkinter_Calculatrice/Calculatrice.py","file_name":"Calculatrice.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72545230246","text":"\"\"\"\nHelper functions used in Project 2\n\"\"\"\nimport torch\nimport torchvision\nimport matplotlib.pyplot as plt\nimport random\nimport math\n\n\ndef hello_helper():\n \"\"\"\n This is a sample function that we will try to import and run to ensure that\n our environment is correctly set up on Google Colab.\n \"\"\"\n print(\"Hello from p2_helpers.py!\")\n \n \ndef reset_seed(number):\n \"\"\"\n Reset random seed to the specific number\n\n Inputs:\n - number: A seed number to use\n \"\"\"\n random.seed(number)\n torch.manual_seed(number)\n return\n\n\n\ndef get_toy_data(\n num_inputs=5,\n input_size=4,\n hidden_size=10,\n num_classes=3,\n dtype=torch.float32,\n device=\"cuda\",\n):\n \"\"\"\n Get toy data for use when developing a two-layer-net.\n\n Inputs:\n - num_inputs: Integer N giving the data set size\n - input_size: Integer D giving the dimension of input data\n - hidden_size: Integer H giving the number of hidden units in the model\n - num_classes: Integer C giving the number of categories\n - dtype: torch datatype for all returned data\n - device: device on which the output tensors will reside\n\n Returns a tuple of:\n - toy_X: `dtype` tensor of shape (N, D) giving data points\n - toy_y: int64 tensor of shape (N,) giving labels, where each element is an\n integer in the range [0, C)\n - params: A dictionary of toy model parameters, with keys:\n - 'W1': `dtype` tensor of shape (D, H) giving first-layer weights\n - 'b1': `dtype` tensor of shape (H,) giving first-layer biases\n - 'W2': `dtype` tensor of shape (H, C) giving second-layer weights\n - 'b2': `dtype` tensor of shape (C,) giving second-layer biases\n \"\"\"\n N = num_inputs\n D = input_size\n H = hidden_size\n C = num_classes\n\n # We set the random seed for repeatable experiments.\n reset_seed(0)\n\n # Generate some random parameters, storing them in a dict\n params = {}\n params[\"W1\"] = 1e-4 * torch.randn(D, H, device=device, dtype=dtype)\n params[\"b1\"] = torch.zeros(H, device=device, dtype=dtype)\n params[\"W2\"] = 1e-4 * torch.randn(H, C, device=device, dtype=dtype)\n params[\"b2\"] = torch.zeros(C, device=device, dtype=dtype)\n\n # Generate some random inputs and labels\n toy_X = 10.0 * torch.randn(N, D, device=device, dtype=dtype)\n toy_y = torch.tensor([0, 1, 2, 2, 1], device=device, dtype=torch.int64)\n\n return toy_X, toy_y, params\n\n\n################# Visualizations #################\n\n\ndef plot_stats(stat_dict):\n # Plot the loss function and train / validation accuracies\n plt.subplot(1, 2, 1)\n plt.plot(stat_dict[\"loss_history\"], \"o\")\n plt.title(\"Loss history\")\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Loss\")\n\n plt.subplot(1, 2, 2)\n plt.plot(stat_dict[\"train_acc_history\"], \"o-\", label=\"train\")\n plt.plot(stat_dict[\"val_acc_history\"], \"o-\", label=\"val\")\n plt.title(\"Classification accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n plt.legend()\n\n plt.gcf().set_size_inches(14, 4)\n plt.show()\n\n\ndef visualize_grid(Xs, ubound=255.0, padding=1):\n \"\"\"\n Reshape a 4D tensor of image data to a grid for easy visualization.\n\n Inputs:\n - Xs: Data of shape (N, H, W, C)\n - ubound: Output grid will have values scaled to the range [0, ubound]\n - padding: The number of blank pixels between elements of the grid\n \"\"\"\n (N, H, W, C) = Xs.shape\n # print(Xs.shape)\n grid_size = int(math.ceil(math.sqrt(N)))\n grid_height = H * grid_size + padding * (grid_size - 1)\n grid_width = W * grid_size + padding * (grid_size - 1)\n grid = torch.zeros((grid_height, grid_width, C), device=Xs.device)\n next_idx = 0\n y0, y1 = 0, H\n for y in range(grid_size):\n x0, x1 = 0, W\n for x in range(grid_size):\n if next_idx < N:\n img = Xs[next_idx]\n low, high = torch.min(img), torch.max(img)\n grid[y0:y1, x0:x1] = ubound * (img - low) / (high - low)\n next_idx += 1\n x0 += W + padding\n x1 += W + padding\n y0 += H + padding\n y1 += H + padding\n return grid\n\n\n# Visualize the weights of the network\ndef show_net_weights(net):\n W1 = net.params[\"W1\"]\n W1 = W1.reshape(3, 32, 32, -1).transpose(0, 3)\n plt.imshow(visualize_grid(W1, padding=3).type(torch.uint8).cpu())\n plt.gca().axis(\"off\")\n plt.show()\n\n\ndef plot_acc_curves(stat_dict):\n plt.subplot(1, 2, 1)\n for key, single_stats in stat_dict.items():\n plt.plot(single_stats[\"train_acc_history\"], label=str(key))\n plt.title(\"Train accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n\n plt.subplot(1, 2, 2)\n for key, single_stats in stat_dict.items():\n plt.plot(single_stats[\"val_acc_history\"], label=str(key))\n plt.title(\"Validation accuracy history\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Clasification accuracy\")\n plt.legend()\n\n plt.gcf().set_size_inches(14, 5)\n plt.show()\n\n\ndef sample_batch(\n X: torch.Tensor, y: torch.Tensor, num_train: int, batch_size: int\n):\n \"\"\"\n Sample batch_size elements from the training data and their\n corresponding labels to use in this round of gradient descent.\n \"\"\"\n batch = torch.randint(num_train, (batch_size, ))\n X_batch = X[batch]\n y_batch = y[batch]\n return X_batch, y_batch\n\n\ndef svm_loss(x, y):\n \"\"\"\n Computes the loss and gradient using for multiclass SVM classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth\n class for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label for x[i] and\n 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x\n \"\"\"\n loss = None\n dx = torch.zeros_like(x)\n \n #####################################################\n # TODO: Implement the SVM loss function. #\n #####################################################\n # Replace \"pass\" statement with your code\n N = x.shape[0]\n correct_class_scores = x[torch.arange(N), y]\n margins = (x - correct_class_scores[:, None] + 1.0).clamp(min=0.)\n margins[torch.arange(N), y] = 0.\n loss = margins.sum() / N\n num_pos = (margins > 0).sum(dim=1)\n \n dx[margins > 0] = 1.\n dx[torch.arange(N), y] -= num_pos.to(dx.dtype)\n dx /= N\n #####################################################\n # END OF YOUR CODE #\n #####################################################\n \n return loss, dx\n\n\ndef softmax_loss(x, y):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for\n the jth class for the ith input.\n - y: Vector of labels, of shape (N,) where y[i] is the label\n for x[i] and 0 <= y[i] < C\n Returns a tuple of:\n - loss: Scalar giving the loss\n - dx: Gradient of the loss with respect to x\n \"\"\"\n loss = None\n dx = torch.zeros_like(x)\n \n #####################################################\n # TODO: Implement the softmax loss function. #\n #####################################################\n # Replace \"pass\" statement with your code\n shifted_logits = x - x.max(dim=1, keepdim=True).values\n Z = shifted_logits.exp().sum(dim=1, keepdim=True)\n log_probs = shifted_logits - Z.log()\n probs = log_probs.exp()\n N = x.shape[0]\n loss = (-1.0 / N) * log_probs[torch.arange(N), y].sum()\n dx = probs.clone()\n dx[torch.arange(N), y] -= 1\n dx /= N\n #####################################################\n # END OF YOUR CODE #\n #####################################################\n \n return loss, dx\n","repo_name":"TomWang233/UMich_DeepRob","sub_path":"P2/rob599/p2_helpers.py","file_name":"p2_helpers.py","file_ext":"py","file_size_in_byte":7844,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"18924560254","text":"from typing import Dict\n\nfrom redbot.core import commands\n\nfrom ._tagscript import TagError\n\n\nclass TagScriptConverter(commands.Converter[str]):\n async def convert(self, ctx: commands.GuildContext, argument: str) -> str:\n try:\n await ctx.cog._validate_tagscript(argument) # type: ignore\n except TagError as e:\n raise commands.BadArgument(str(e))\n return argument\n\n\nclass TimeConverter(commands.Converter[int]):\n async def convert(self, ctx: commands.Context, argument: str) -> int:\n conversions: Dict[str, int] = {\n \"s\": 1,\n \"m\": 60,\n \"h\": 3600,\n \"d\": 86400,\n \"w\": 604800,\n \"mo\": 604800 * 30,\n }\n if str(argument[-1]) not in conversions:\n if not str(argument).isdigit():\n raise commands.BadArgument(\n f\"Unable to convert {argument} to a time.\",\n )\n return int(argument)\n\n multiplier = conversions[str(argument[-1])]\n argument = argument[:-1]\n\n if not str(argument).isdigit():\n raise commands.BadArgument(\n f\"Unable to convert {argument} to a time.\",\n )\n if int(argument) * multiplier <= 0:\n raise commands.BadArgument(\n \"You cannot have a time less than 0.\",\n )\n\n return int(argument) * multiplier\n\n\nclass BanLengthConverter(commands.Converter[int]):\n async def convert(self, ctx: commands.Context, argument: str) -> int:\n if not argument.isnumeric():\n raise commands.BadArgument(\n \"Please enter a valid time length.\",\n )\n elif int(argument) < 1:\n raise commands.BadArgument(\n \"You cannot set the time length to anything less than 1 day.\",\n )\n elif int(argument) > 7:\n raise commands.BadArgument(\n \"You cannot set the time length to anything greater than 7 days.\"\n )\n return int(argument)\n","repo_name":"japandotorg/Seina-Cogs","sub_path":"freeloadermode/converters.py","file_name":"converters.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"}
+{"seq_id":"36515858295","text":"from abc import ABCMeta, abstractmethod\nfrom typing import Generator, List\n\nfrom . import bot\nfrom discord import Embed, Message\nfrom enum import Enum, auto\n\n\nclass PageEntry(metaclass=ABCMeta):\n @abstractmethod\n def title(self) -> str:\n pass\n\n @abstractmethod\n def to_message(self) -> str:\n pass\n\n\nclass PageActionResult(Enum):\n PREVIOUS_PAGE = auto()\n NEXT_PAGE = auto()\n CANCEL = auto()\n\n @staticmethod\n def get_result(emoji):\n if emoji.name == Page.PREVIOUS_PAGE_EMOJI:\n return PageActionResult.PREVIOUS_PAGE\n if emoji.name == Page.NEXT_PAGE_EMOJI:\n return PageActionResult.NEXT_PAGE\n return PageActionResult.CANCEL\n\n\nclass Page:\n PREVIOUS_PAGE_EMOJI = \"\\U00002B05\"\n NEXT_PAGE_EMOJI = \"\\U000027A1\"\n CANCEL_EMOJI = \"\\U0000274E\"\n\n def __init__(self, size: int, generator: Generator) -> None:\n self.__size = size\n self.__page = 1\n self.__max_page_reached = False\n self.__max_page_size = 0\n self.__generator = generator\n self.__entries: List[PageEntry] = []\n\n async def __add_reaction(self, message, emoji):\n try:\n await message.add_reaction(emoji)\n except: pass\n\n async def __remove_reaction(self, message, emoji, user=None):\n try:\n await message.remove_reaction(emoji, user if user is not None else bot.user)\n except: pass\n\n async def __cancel(self, message: Message):\n try:\n await message.clear_reactions()\n except:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__remove_reaction(message, self.CANCEL_EMOJI)\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI)\n\n async def __handle_pages(self, message, channel, embed, user) -> PageActionResult:\n edit = True\n while True:\n if edit:\n for entry in self.__entries[(self.__page - 1) * self.__size:min(self.__page * self.__size,len(self.__entries))]:\n embed.add_field(name=entry.title(), value=entry.to_message(), inline=False)\n await message.edit(embed=embed)\n # await self.__cancel(message)\n # if self.show_previous_page:\n # await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n # await self.__add_reaction(message, self.CANCEL_EMOJI)\n # if self.show_next_page:\n # await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n payload = await bot.wait_for(\"raw_reaction_add\", check=lambda x: (x.guild_id is None and x.user_id == user.id) or (x.guild_id is not None and x.channel_id == channel.id and not x.member.bot and x.member == user))\n action = PageActionResult.get_result(payload.emoji)\n if action == PageActionResult.CANCEL:\n await self.__cancel(message)\n return action\n if action == PageActionResult.NEXT_PAGE:\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI, user)\n if self.show_next_page:\n self.__page += 1\n embed.clear_fields()\n edit = True\n else:\n edit = False\n elif action == PageActionResult.PREVIOUS_PAGE:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI, user)\n if self.show_previous_page:\n self.__page -= 1\n embed.clear_fields()\n edit = True\n else:\n edit = False\n if self.__page * self.__size > len(self.__entries) and edit:\n return PageActionResult.NEXT_PAGE\n\n async def show(self, ctx, title: str, colour):\n channel = ctx.message.channel\n message: Message = None\n embed = Embed(title=title, colour=colour)\n embed.set_footer(text=\"Made by CJMinecraft\")\n # While generating the results\n for result in self.__generator:\n self.__entries.append(result)\n embed.add_field(name=result.title(), value=result.to_message(), inline=False)\n if len(self.__entries) % (self.__size * self.__page) == 0:\n if message is None:\n # Will only happen once when the data is being generated\n message = await ctx.send(embed=embed)\n await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__add_reaction(message, self.CANCEL_EMOJI)\n await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n else:\n await message.edit(embed=embed)\n # await self.__cancel(message)\n # if self.show_previous_page:\n # await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n # await self.__add_reaction(message, self.CANCEL_EMOJI)\n # if self.show_next_page:\n # await self.__add_reaction(message, self.NEXT_PAGE_EMOJI)\n while True:\n payload = await bot.wait_for(\"raw_reaction_add\", check=lambda x: (x.guild_id is None and x.user_id == ctx.message.author.id) or (x.guild_id is not None and x.channel_id == channel.id and not x.member.bot and x.member == ctx.message.author))\n action = PageActionResult.get_result(payload.emoji)\n if action == PageActionResult.CANCEL:\n await self.__cancel(message)\n return\n if action == PageActionResult.NEXT_PAGE:\n await self.__remove_reaction(message, self.NEXT_PAGE_EMOJI, ctx.message.author)\n if self.show_next_page:\n self.__page += 1\n embed.clear_fields()\n break\n elif action == PageActionResult.PREVIOUS_PAGE:\n await self.__remove_reaction(message, self.PREVIOUS_PAGE_EMOJI, ctx.message.author)\n if self.show_previous_page:\n self.__page -= 1\n embed.clear_fields()\n if await self.__handle_pages(message, channel, embed, ctx.message.author) == PageActionResult.CANCEL:\n return\n break\n\n if message is None:\n if len(embed.fields) == 0:\n embed.description = \"No results found\"\n # Must not be enough results to fill one page\n await ctx.send(embed=embed)\n else:\n # await message.edit(embed=embed)\n # await self.__cancel(message)\n self.__max_page_reached = True\n self.__max_page_size = self.__page\n embed.clear_fields()\n await self.__add_reaction(message, self.PREVIOUS_PAGE_EMOJI)\n await self.__add_reaction(message, self.CANCEL_EMOJI)\n await self.__handle_pages(message, channel, embed, ctx.message.author)\n\n @property\n def show_previous_page(self):\n return self.__page > 1\n\n @property\n def show_next_page(self):\n return not self.__max_page_reached or self.__page < self.__max_page_size\n\n @property\n def size(self):\n return self.__size\n","repo_name":"CJMinecraft01/CJBot","sub_path":"bot/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"36733371523","text":"from Pagoda import PagodaClass\nfrom AVL_Tree_Implementation import AVLTree\nimport csv\nimport string \nimport time\nfrom memory_profiler import profile\n#import matplotlib.pyplot as plt\n\nclass Track:\n def __init__(self, Artist: string, Url_spotify: string, Name: string, Album: string, Tempo: int, Url_Youtube: string, Youtubeviews: int, Likes: int, Spotifystreams: int):\n self.Artist=Artist\n self.Name=Name\n self.Album=Album\n self.Tempo=Tempo\n self.Url_Youtube=Url_Youtube\n self.Url_Spotify=Url_spotify\n self.Likes=Likes\n self.YoutubeViews=Youtubeviews\n self.Spotifyviews=Spotifystreams\n self.left=None \n self.right=None\n\nTrackarchive=[]\n\nwith open(\"./Spotify and Youtube.csv\", 'r',encoding=\"utf8\") as file:\n csvreader = csv.reader(file)\n c = 0\n for row in csvreader:\n \n if c == 0 or row[7] == '':\n c+=1\n continue\n obj = Track(row[1],row[2],row[3],row[4],row[5],row[6],int(row[7]),row[8],row[9])\n c+=1\n Trackarchive.append(obj)\n\n # for line in file:\n # data.append(line.strip().split(\",\"))\n\n# startA=time.time()\n# avl_tree = AVLTree()\n# root = None\n# for row in data:\n# root = avl_tree.insert_node(root, row)\n# endA=time.time()\n# print(avl_tree.root)\n# # Print the tree\n# avl_tree.printHelper(root, \"\", True)\n\nstart=time.time()\nPagodaTree=PagodaClass()\nfor i in Trackarchive:\n PagodaTree.insert(i)\nend = time.time()\n\ntime_n=end-start\n# time_l=endA-startA\n\nprint(PagodaTree.root.trackobj.Name)\nprint(PagodaTree.root.trackobj.Artist)\n\nprint(time_n)\n# print(time_l)\n","repo_name":"Ur07589/DS-II-Pagoda-Project","sub_path":"src/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40743475566","text":"# x = int(input(\"enter the last number \"))\r\n# a = 1\r\n# while(x > 0) :\r\n# a = a * x\r\n# x = x - 1\r\n# else : \r\n# print(\"the factorial of x is \",a)\r\n \r\n# # /*Do-WHile\r\n# i = 0\r\n# while True :\r\n# print(i)\r\n# i = i + 1\r\n# if(i % 50 == 0) :\r\n# break\r\n# # Do while\r\n# s = 0\r\n# do : print(i)\r\n# i = i+ 1\r\n# while(i < 15):\r\n\r\n# defining list of strings\r\nlist1 = [\"geeksforgeeks\", \"C++\",\r\n\t\t\"Java\", \"Python\", \"C\", \"MachineLearning\"]\r\n\r\n# initialises a variable\r\ni = 0\r\n\r\nprint(\"Printing list items\\\r\nusing while loop\")\r\nsize = len(list1)\r\n# Implement while loop to print list items\r\nwhile(i < size):\r\n\tprint(list1[i])\r\n\ti = i+1\r\n\r\ni = 0\r\n\r\nprint(\"Printing list items\\\r\nusing do while loop\")\r\n\r\n# Implement do while loop to print list items\r\nwhile(True):\r\n\tprint(list1[i])\r\n\ti = i+1\r\n\tif(i < size and len(list1[i]) < 10):\r\n\t\tcontinue\r\n\telse:\r\n\t\tbreak\r\n","repo_name":"Vivekkumar121/Python","sub_path":"Basic/18 while .py","file_name":"18 while .py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"29098815451","text":"from types import SimpleNamespace\nimport pika\nimport json\nfrom db_and_event_definitions import ParkingEvent, BillingEvent, customers_database as db\nimport time\nimport logging\n\nfrom xprint import xprint\n\n\nclass CustomerEventConsumer:\n\n def __init__(self, customer_id):\n # Do not edit the init method.\n # Set the variables appropriately in the methods below.\n self.customer_id = customer_id\n self.connection = None\n self.channel = None\n self.temporary_queue_name = None\n self.parking_events = []\n self.billing_events = []\n self.ename = 'customer_app_events'\n\n def initialize_rabbitmq(self):\n # To implement - Initialize the RabbitMq connection, channel, exchange and queue here\n xprint(\"CustomerEventConsumer {}: initialize_rabbitmq() called\".format(self.customer_id))\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n self.channel = self.connection.channel()\n self.channel.exchange_declare(exchange=self.ename, exchange_type='topic')\n qname = self.channel.queue_declare('', exclusive=True)\n self.temporary_queue_name = qname.method.queue\n self.channel.queue_bind(exchange=self.ename, queue=self.temporary_queue_name, routing_key=self.customer_id)\n\n def handle_event(self, ch, method, properties, body):\n # To implement - This is the callback that is passed to \"on_message_callback\" when a message is received\n xprint(\"CustomerEventConsumer {}: handle_event() called\".format(self.customer_id))\n\n details = json.loads(body.decode('utf-8'))\n if details.get('customer_id'):\n be = BillingEvent(**details)\n self.billing_events.append(be)\n else:\n pe = ParkingEvent(**details)\n self.parking_events.append(pe)\n \n def start_consuming(self):\n self.channel.basic_consume(self.temporary_queue_name, on_message_callback=self.handle_event, auto_ack=True)\n self.channel.start_consuming()\n\n def close(self):\n # Do not edit this method\n try:\n if self.channel is not None:\n print(\"CustomerEventConsumer {}: Closing\".format(self.customer_id))\n self.channel.stop_consuming()\n time.sleep(1)\n self.channel.close()\n if self.connection is not None:\n self.connection.close()\n except Exception as e:\n print(\"CustomerEventConsumer {}: Exception {} on close()\"\n .format(self.customer_id, e))\n pass\n","repo_name":"GunnerUjjwol/Cloud-System-Software-Hands-on","sub_path":"exercise 5- RabbitMQ/exercise/customer_app.py","file_name":"customer_app.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"33421761115","text":"from backtracking.backtrack import Backtrack\nfrom boards.pick_board import pick_board\nfrom constraint import check_board\nfrom interface.helpers import btn_to_arr\nfrom interface.sudoku_state import store_state\nfrom exact_cover.algorithmx import AlgorithmX\n\n\ndef check_method(cells, king_check, knight_check, check_text):\n \"\"\"Checks if the board is correct or not.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n check_text: QTextEdit used to display information to the user.\n \"\"\"\n arr = btn_to_arr(cells)\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n correct = check_board(arr, king, knight)\n\n for line in arr:\n if 0 in line:\n\n if not correct:\n check_text.setText(\"Missing values and puzzle contains constraint mistakes.\")\n else:\n check_text.setText(\"Missing values.\")\n return\n\n if not correct:\n check_text.setText(\"Not correct.\")\n return\n\n check_text.setText(\"Correct.\")\n\n\ndef generate_method(cells, states, king_check, knight_check):\n \"\"\"Picks an example board which fits the constraint criteria.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n states: A list of the object SudokuState.\n \"\"\"\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n board = pick_board(king, knight)\n arr = btn_to_arr(cells)\n states.append(store_state(arr))\n\n for i in range(9):\n for j in range(9):\n if board[i][j] != 0:\n cells[i][j].setText(str(board[i][j]))\n\n\ndef clear_method(cells, states):\n \"\"\"Clear the entire Sudoku board.\n\n Clear the entire board by removing the text on the QPushButtons.\n In addition also updates the state so the undo action can be performed\n after clearing.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n states: A list of the object SudokuState.\n \"\"\"\n arr = btn_to_arr(cells)\n states.append(store_state(arr))\n\n for row in cells:\n for cell in row:\n cell.setText(\"\")\n\n\ndef solve_method(cells, king_check, knight_check, check_text, states, algorithm_x):\n \"\"\"Solve the given Sudoku Board.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n king_check: Boolean which represents if the king constraint is on.\n knight_check: Boolean which represents if the knight constraint is on.\n check_text: QTextEdit used to display information to the user.\n states: A list of the object SudokuState.\n algorithm_x: AlgorithmX object used to solve regular sudoku.\n \"\"\"\n arr = btn_to_arr(cells)\n king = king_check.isChecked()\n knight = knight_check.isChecked()\n\n states.append(store_state(arr))\n\n # If the board breaks constraints\n if not check_board(arr, king, knight):\n check_text.setText(\"Invalid Board\")\n return\n\n if not king and not knight:\n solved = algorithm_x.solve(arr)\n else:\n backtrack = Backtrack(arr)\n backtrack.king = king\n backtrack.knight = knight\n solved = backtrack.solve()\n\n if not solved:\n check_text.setText(\"No solution.\")\n return\n\n for y in range(9):\n for x in range(9):\n cells[y][x].setText(str(solved[y][x]))\n\n\ndef undo_method(cells, states):\n \"\"\"Undo the last action performed by going back to the previous state.\n\n Args:\n cells: Matrix of QPushButtons which represents the Sudoku board.\n states: A list of the object SudokuState.\n \"\"\"\n if len(states) == 0:\n return\n\n last_action = states[-1]\n states.pop()\n\n for i in range(len(last_action.val)):\n\n x = last_action.x[i]\n y = last_action.y[i]\n old = last_action.val[i]\n\n if old == 0:\n cells[x][y].setText(\"\")\n else:\n cells[x][y].setText(str(old))","repo_name":"JonOlav95/algorithm_x","sub_path":"interface/btn_methods.py","file_name":"btn_methods.py","file_ext":"py","file_size_in_byte":4281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"29130452360","text":"# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-\n#\n# This file is part of the LibreOffice project.\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n#\nfrom uitest.framework import UITestCase\nfrom uitest.uihelper.common import get_state_as_dict, get_url_for_data_file\n\nfrom libreoffice.uno.propertyvalue import mkPropertyValues\nfrom uitest.uihelper.common import select_pos\n\n\n# Chart Enable Axes dialog\nclass chartAxes(UITestCase):\n def test_chart_enable_grids_dialog(self):\n with self.ui_test.load_file(get_url_for_data_file(\"tdf98390.ods\")):\n xCalcDoc = self.xUITest.getTopFocusWindow()\n gridwin = xCalcDoc.getChild(\"grid_window\")\n\n gridwin.executeAction(\"SELECT\", mkPropertyValues({\"OBJECT\": \"Object 1\"}))\n gridwin.executeAction(\"ACTIVATE\", tuple())\n xChartMainTop = self.xUITest.getTopFocusWindow()\n xChartMain = xChartMainTop.getChild(\"chart_window\")\n xSeriesObj = xChartMain.getChild(\"CID/D=0:CS=0:CT=0:Series=0\")\n with self.ui_test.execute_dialog_through_action(xSeriesObj, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"InsertMenuAxes\"})) as xDialog:\n\n primaryX = xDialog.getChild(\"primaryX\")\n primaryY = xDialog.getChild(\"primaryY\")\n secondaryX = xDialog.getChild(\"secondaryX\")\n secondaryY = xDialog.getChild(\"secondaryY\")\n\n primaryX.executeAction(\"CLICK\", tuple())\n primaryY.executeAction(\"CLICK\", tuple())\n secondaryX.executeAction(\"CLICK\", tuple())\n secondaryY.executeAction(\"CLICK\", tuple())\n\n\n #reopen and verify Grids dialog\n gridwin.executeAction(\"SELECT\", mkPropertyValues({\"OBJECT\": \"Object 1\"}))\n gridwin.executeAction(\"ACTIVATE\", tuple())\n xChartMainTop = self.xUITest.getTopFocusWindow()\n xChartMain = xChartMainTop.getChild(\"chart_window\")\n xSeriesObj = xChartMain.getChild(\"CID/D=0:CS=0:CT=0:Series=0\")\n with self.ui_test.execute_dialog_through_action(xSeriesObj, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"InsertMenuAxes\"})) as xDialog:\n\n primaryX = xDialog.getChild(\"primaryX\")\n primaryY = xDialog.getChild(\"primaryY\")\n secondaryX = xDialog.getChild(\"secondaryX\")\n secondaryY = xDialog.getChild(\"secondaryY\")\n\n self.assertEqual(get_state_as_dict(primaryX)[\"Selected\"], \"false\")\n self.assertEqual(get_state_as_dict(primaryY)[\"Selected\"], \"false\")\n self.assertEqual(get_state_as_dict(secondaryX)[\"Selected\"], \"true\")\n self.assertEqual(get_state_as_dict(secondaryY)[\"Selected\"], \"true\")\n\n # Test Format -> Axis -> X Axis...: the child name is generated in\n # lcl_getAxisCIDForCommand().\n xAxisX = xChartMain.getChild(\"CID/D=0:CS=0:Axis=0,0\")\n with self.ui_test.execute_dialog_through_action(xAxisX, \"COMMAND\", mkPropertyValues({\"COMMAND\": \"DiagramAxisX\"})) as xDialog:\n xTabs = xDialog.getChild(\"tabcontrol\")\n # Select RID_SVXPAGE_CHAR_EFFECTS, see the SchAttribTabDlg ctor.\n select_pos(xTabs, \"6\")\n xFontTransparency = xDialog.getChild(\"fonttransparencymtr\")\n # Without the accompanying fix in place, this test would have failed, the\n # semi-transparent text UI was visible, but then it was lost on save.\n self.assertEqual(get_state_as_dict(xFontTransparency)[\"Visible\"], \"false\")\n\n\n# vim: set shiftwidth=4 softtabstop=4 expandtab:\n","repo_name":"LibreOffice/core","sub_path":"sc/qa/uitest/chart/chartAxes.py","file_name":"chartAxes.py","file_ext":"py","file_size_in_byte":3608,"program_lang":"python","lang":"en","doc_type":"code","stars":2194,"dataset":"github-code","pt":"52"}
+{"seq_id":"28037771850","text":"from .email import email_spec\n\njob_node = {\n \"type\": \"object\",\n \"description\": \"Represents a step or node (for DAGs) in a job.\",\n \"properties\": {\n \"id\": {\n \"description\": \"Unique identifier of the job node.\",\n \"type\": \"string\",\n },\n \"children\": {\n \"type\": \"array\",\n \"items\": {\n \"description\": \"ID of child node.\",\n \"type\": \"string\",\n },\n },\n \"task\": {\n \"description\": \"Name of task performed by this node.\",\n \"type\": \"string\",\n },\n \"status\": {\n \"description\": \"Status of this node.\",\n \"type\": \"string\",\n },\n \"start_time\": {\n \"description\": \"Start time of this node.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n \"stop_time\": {\n \"description\": \"Stop time of this node.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n },\n}\n\nalgorithm_parameter = {\n \"type\": \"object\",\n \"required\": [\"name\", \"value\"],\n \"properties\": {\n \"name\": {\n \"description\": \"Name of algorithm parameter\",\n \"type\": \"string\",\n },\n \"value\": {\n \"description\": \"Value of algorithm parameter\",\n \"oneOf\": [\n {\"type\": \"number\"},\n {\"type\": \"string\"},\n ],\n },\n },\n}\n\njob_spec = {\n \"type\": \"object\",\n \"required\": [\"algorithm_name\", \"media_ids\"],\n \"properties\": {\n \"algorithm_name\": {\n \"description\": \"Name of the algorithm to execute.\",\n \"type\": \"string\",\n },\n \"media_ids\": {\n \"description\": \"List of media IDs.\",\n \"type\": \"array\",\n \"items\": {\"type\": \"integer\"},\n },\n \"extra_params\": {\n \"description\": \"Extra parameters to pass into the algorithm\",\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/components/schemas/AlgorithmParameter\"},\n },\n \"success_email_spec\": {\n **email_spec,\n \"nullable\": True,\n },\n \"failure_email_spec\": {\n **email_spec,\n \"nullable\": True,\n },\n },\n}\n\njob = {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"description\": \"Unique identifier of the job generated by Argo.\",\n \"type\": \"string\",\n },\n \"uid\": {\n \"description\": \"Unique ID of the job.\",\n \"type\": \"string\",\n },\n \"gid\": {\n \"description\": \"Group ID of the job.\",\n \"type\": \"string\",\n },\n \"user\": {\n \"description\": \"Unique integer identifying user who submitted the job.\",\n \"type\": \"integer\",\n },\n \"project\": {\n \"description\": \"Unique integer identifying a project.\",\n \"type\": \"integer\",\n },\n \"nodes\": {\n \"type\": \"array\",\n \"items\": {\"$ref\": \"#/components/schemas/JobNode\"},\n },\n \"status\": {\n \"description\": \"Status of this job.\",\n \"type\": \"string\",\n },\n \"start_time\": {\n \"description\": \"Start time of this job.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n \"stop_time\": {\n \"description\": \"Stop time of this job.\",\n \"type\": \"string\",\n \"nullable\": True,\n \"format\": \"date-time\",\n },\n },\n}\n","repo_name":"cvisionai/tator","sub_path":"api/main/schema/components/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"52"}
+{"seq_id":"74785634403","text":"#!/usr/bin/env python2\n#\n# bricks.py prepares an SMT experiment from shell script templates and\n# a configuration file.\n#\n# File Paths\n# ----------\n# * Including config files\n# * relative path: key: @\"include.cfg\"\n# relative to the respective config file, or the working\n# directory if not itself included.\n# * absolute path: key: @\n# searched for in bricks/ and can be used from anywhere.\n#\n# * Jinja template files\n# Jinja2 has its own search path implementation. We add bricks/\n# to its search path.\n#\n# * Input and output files in Bricks\n# Brick inputs and outputs are symlinked relative to the Brick\n# working directory, e.g. input/src input/trg output/alignment\n#\n# Use absolute paths for Experiment input files residing somewhere\n# outside the experiment.\n# note: relative paths to input files are not resolved yet.\n# They currently are relative to the Brick working directory.\n#\n# Brick script execution\n# ----------------------\n# Happens via 'redo', each script is run in its Brick working directory.\n# 'bricks.py' sets up a hierarchy of working directories for Bricks,\n# with symlinks of inputs (and outputs for Bricks containing parts.)\n#\n# number of run (always 0 currently, incremental experiments not implemented)\n# |\n# v name of Brick (outermost Brick is always called Experiment)\n# 0/ v\n# Experiment/\n# input/rawCorpusSource -> /data/raw.corpus.en\n# input/rawCorpusTarget -> /data/raw.corpus.it\n# output/alignment -> WordAligner0/output/alignment\n#\n# PrepSrc/\n# input/raw -> ../../input/rawCorpusSource\n# output/truecased < not actually created by bricks.py\n# <...>\n#\n# PrepTrg/\n# input/raw -> ../../input/rawCorpusTarget\n# output/truecased < not actually created by bricks.py\n# <...>\n#\n# WordAligner0/\n# # links dangle (target doesn't exist) until actual run of Prep*\n# input/src -> ../../PrepSrc/output/truecased\n# input/trg -> ../../PrepTrg/output/truecased\n#\n# Giza12/\n# input/crp1 -> ../../input/src\n# <...>\n#\n# Templates\n# ---------\n# The idea of the shell script wrappers around programs, specified in Bricks\n# either directly as a Jinja template string using 'template:' or as a Jinja\n# template file name 'templateFile:', is to\n#\n# 1) specify both overridable and default configuration values to helpers,\n#\n# 2) coerce helper programs to take their input and produce their output\n# exactly in this filesystem structure. (Temporary files are often also\n# created, but should never be referred to by other Bricks).\n#\n#\n# incremental experiments\n# -----------------------\n# The idea for incremental experiments will be to check via 'redo' if targets\n# need to be run, and if they don't, we can symlink their input back to the\n# previous run.\n#\n\nfrom __future__ import print_function\n\nfrom brick_config import config\nimport logging\nimport os\nimport shutil\nimport sys\nimport jinja2\nimport argparse\n\n\nclass Brick(config.Mapping):\n \"\"\"\n Wrapper around config.Mapping with various utility functions for Bricks.\n \"\"\"\n def __init__(self, mapping):\n assert(isinstance(mapping, config.Mapping))\n config.Container.__init__(self, mapping.parent)\n object.__setattr__(self, 'path', mapping.path)\n object.__setattr__(self, 'data', mapping.data)\n object.__setattr__(self, 'order', mapping.order)\n object.__setattr__(self, 'comments', mapping.comments)\n object.__setattr__(self, 'resolving', set())\n\n # rudimentarily assert that this config level is indeed a Brick\n if not ('input' in self.data and 'output' in self.data):\n raise ValueError(\"Brick %s is missing an input: or output: block\" % self.path)\n\n def filesystemPath(self, configPath=None):\n \"\"\"\n Map the config path to a relative filesystem path of the experiment\n directory which will contain this Brick's data for the runner system.\n \"\"\"\n # replace .parts: shortens \"Experiment.parts.WordAligner0.parts.Giza12\"\n # into \"Experiment/WordAligner0/Giza12\"\n configPath = self.pathParts()\n path = ['0']\n path += [part for part in configPath if part != \"parts\"]\n return os.path.join(*path)\n\n def magicInputBrick(self, inputRef):\n \"\"\"\n For a given Brick input Reference, return the Brick which provides this input.\n @param inputRef: Reference from the input mapping of a Brick, referring to another Brick's output\n \"\"\"\n assert(type(inputRef) is config.Reference)\n\n # relative path to referenced Brick\n refBrickPathOrig = inputRef.relativePath(self)[:-2]\n refBrickPath = list(refBrickPathOrig)\n\n # absolute path of us\n ourPath = self.path.split('.')\n\n # TODO: see below comment with this wording: \"magicInputBrick() should have gone this route.\"\n # TODO: but need to remember parent in resolve2() since this may be a Reference itself, which\n # TODO: doesn't have a parent.\n\n # resolve relative _ walking upwards\n # (poor man's implementation)\n resPoint = self\n while len(refBrickPath) > 0 and refBrickPath[0] == '_':\n refBrickPath = refBrickPath[1:]\n ourPath = ourPath[:-1]\n resPoint = resPoint.parent\n\n #sys.stderr.write('resolved: %s\\n' % '.'.join(ourPath + refBrickPath))\n\n inputBrick = resPoint.getByPath('.'.join(refBrickPath)) if len(refBrickPath) > 0 else resPoint\n #sys.stderr.write('%s\\n' % str(inputBrick))\n\n return inputBrick\n\n def pwd(self):\n \"\"\"\n Absolute path to this Brick's working directory. Used from Jinja.\n \"\"\"\n return os.path.abspath(self.filesystemPath())\n\n def referenceDependencyPath(self, anyput, container, brickOnly=True, depth=0):\n \"\"\"\n Turns a config path referencing another Brick into a filesystem path.\n Used for adding dependencies to the runner system.\n @param relativePath list of node names along config path\n @param brickOnly only reference the brick itself, not the actual input/output file\n \"\"\"\n #print(brickOnly, relativePath)\n\n relativePath = anyput.relativePath(container)[depth:]\n\n # This should really, really be integrated in a recursive function which walks\n # the config tree. However, this is how it has grown. Feel free to replace this.\n\n # currently we only support dependencies of the form ...:\n\n # ['_', '_', 'Giza12', 'output', 'alignment']\n # used for input dependencies (of siblings)\n if len(relativePath) in [5, 6] and relativePath[0:2] == ['_', '_'] \\\n and relativePath[2] != '_' and relativePath[3] == 'output':\n if brickOnly:\n return os.path.join('..', relativePath[2], 'brick')\n else:\n return os.path.join(*(['..'] + relativePath[2:]))\n\n # ['_', '_', '_', 'input', 'src']\n # ['_', '_', '_', 'input', 'corpora', '0'] - for referencing input lists\n # used in referencing the Brick's input in parts\n if len(relativePath) in [5, 6] and relativePath[0:3] == ['_', '_', '_'] \\\n and relativePath[3] in ['output', 'input']:\n if brickOnly:\n return None\n else:\n return os.path.join(*(['..'] + relativePath[3:]))\n\n # ['_', 'parts', 'WordAligner0', 'output', 'alignment']\n # ['_', 'parts', 'Split0', 'output', 'texts', '0']\n # used for output dependencies\n if len(relativePath) in [5, 6] and relativePath[0:2] == ['_', 'parts'] \\\n and relativePath[3] == 'output':\n if brickOnly:\n return os.path.join(relativePath[2], 'brick')\n else:\n return os.path.join(*relativePath[2:])\n\n return None\n\n def dependencies(self, depType=None):\n \"\"\"\n Get all Bricks which we depend on, as a list of relative\n file paths for the runner system 'redo'.\n Either 'input' dependencies, or 'output' dependencies\n (the latter for Bricks with parts).\n Used from 'brick.do.jinja' to obtain dependencies for 'redo'.\n \"\"\"\n allDependencies = list()\n\n types = ['input', 'output'] if depType is None else [depType]\n\n # add input dependencies first:\n # >> Inputs need to be run before the outputs. <<\n #\n # To run parallelized, all inputs may be run in parallel, but must be\n # finished before the \"outputs\" (brick parts) are run.\n\n for inout in types:\n dependencies = set()\n mapping = self[inout]\n\n # walk this Brick's anyputs without resolving config keys\n for (key, anyput) in mapping.data.iteritems():\n if type(anyput) is config.Reference:\n # we may be referencing another Brick, which we then\n # need to add as a dependency.\n path = self.referenceDependencyPath(anyput, mapping)\n if path is not None:\n dependencies.add(path)\n elif isinstance(anyput, config.Sequence):\n # get dependencies from input Sequences\n for val in anyput.data:\n if type(val) is config.Reference:\n path = self.referenceDependencyPath(val, anyput, depth=1)\n if path is not None:\n dependencies.add(path)\n\n allDependencies += sorted(list(dependencies))\n\n return allDependencies\n\n def linkPaths(self, inout, apParent, anyput, key, linkSourcePref, linkTarget):\n \"\"\"\n Recursively walk inputs/outputs and create symlinks in the filesystem.\n \"\"\"\n inoutMapping = {'input': self.input, 'output': self.output}[inout]\n resultList = []\n linkSource = None\n\n if type(anyput) is config.Mapping:\n # walk this Brick's *puts without resolving config keys\n for (k, aput) in anyput.data.iteritems():\n resultList += self.linkPaths(inout, anyput, aput, k, os.path.join(linkSourcePref, '..'), os.path.join(linkTarget, k))\n elif isinstance(anyput, config.Sequence):\n for (i, aput) in enumerate(anyput.data):\n # anyput??\n resultList += self.linkPaths(inout, anyput, aput, i, os.path.join(linkSourcePref, '..'), os.path.join(linkTarget, str(i)))\n elif type(anyput) is config.Reference:\n # referencing another Brick\n linkSource = self.referenceDependencyPath(anyput, inoutMapping, brickOnly=False)\n elif type(anyput) is bool:\n # no specification at all, e.g. output: { trg }\n # here, config parser falls back to defining a bool trg=True\n # (not an output dependency)\n if inout == 'input':\n raise ValueError(\"input %s of Brick %s is neither connected nor defined as a file.\" % (key, self.path))\n else:\n # str, or config.Expression: a direct filename specification.\n #sys.stderr.write(\"STR %s\\n\" % inp)\n\n # potentially resolves config.Expression here\n # why pass apParent? because config.Expression doesn't have .parent\n linkSource = apParent[key]\n\n # for input, check if file exists in FS\n if inout == 'input' and not os.path.exists(linkSource):\n raise ValueError(\"input %s of Brick %s = %s does not exist in file system.\" % (key, self.path, anyput))\n\n if linkSource is not None:\n linkSource = os.path.join(linkSourcePref, linkSource)\n #sys.stderr.write(\"%s -> %s\\n\" % (linkSource, linkTarget))\n\n resultList.append((linkSource, linkTarget))\n\n return resultList\n\n def fsCreateSymlinks(self, links):\n for linkSource, linkTarget in links:\n # mkdir -p $(dirname linkTarget)\n if not os.path.exists(os.path.dirname(linkTarget)):\n os.makedirs(os.path.dirname(linkTarget))\n # ln -sf linkSource linkTarget\n if os.path.islink(linkTarget) or os.path.isfile(linkTarget):\n os.unlink(linkTarget)\n os.symlink(linkSource, linkTarget)\n\n def inoutSymlinks(self, inout):\n \"\"\"\n Create symlinks for all inputs/outputs.\n @param inout either 'input' or 'output'\n \"\"\"\n inoutMapping = {'input': self.input, 'output': self.output}[inout]\n\n fsPath = self.filesystemPath()\n\n # TODO: old stuff, remove.\n # ensure each Brick has an input/output directory\n if not os.path.exists(os.path.join(fsPath, inout)):\n os.makedirs(os.path.join(fsPath, inout))\n\n return self.linkPaths(inout, self, inoutMapping, inout, '', os.path.join(fsPath, inout))\n\n def symlinks(self):\n sym = []\n sym += self.inoutSymlinks('input')\n sym += self.inoutSymlinks('output')\n return sym\n\n\n# can we create this while copying the config tree for inheritance?\nclass InputWrap(object):\n \"\"\"\n Wraps a Brick input config for easy access from Jinja templates.\n \"\"\"\n def __init__(self, brick, magicInputBrick, fileStr):\n \"\"\"\n @param reference: config.Reference pointing to output, or str otherwise?\n \"\"\"\n self.brick = brick\n self.fileStr = fileStr\n self.mib = magicInputBrick\n\n def __str__(self):\n \"\"\"\n To easily obtain brick input filenames from Jinja, for example as {{ brick.input.corpus }}\n This could be written \"input/corpus\", but becomes more useful in loops over input lists.\n @return: absolute input file path for our Brick.\n \"\"\"\n return os.path.join(self.brick.pwd(), self.fileStr)\n\n def __repr__(self):\n return self.__str__()\n\n def __getattr__(self, item):\n \"\"\"\n Allow simplified access (easy syntax) to input Brick's config in\n Jinja templates. Syntax example: {{ brick.input.phraseTable.reorderingConfigSpec }}\n \"\"\"\n if item in self.mib:\n return self.mib[item]\n else:\n return object.__getattribute__(self, item)\n\n\nclass TemplateBrick(Brick):\n \"\"\"\n Wrapper around Brick to replace input and output with nice wrappers\n for access from templates.\n \"\"\"\n def __init__(self, brick):\n Brick.__init__(self, brick)\n\n def __getattribute__(self, item):\n if item != 'input':\n # resort to our parent with all other attributes\n return Brick.__getattribute__(self, item)\n\n # override the attribute input: make Jinja see a dict of InputWrap instances,\n # or lists of InputWraps for input lists.\n anyputMap = {}\n anyputs = self.data[item]\n for anyput in anyputs.keys():\n val = anyputs.data[anyput]\n resolved = anyputs[anyput]\n if isinstance(resolved, config.Sequence):\n # are we referencing something that is eventually a Sequence?\n # In this case, our input brick must be the same for all Sequence entries.\n if type(val) is config.Reference:\n magicInput = self.magicInputBrick(val)\n else:\n magicInput = None\n\n # wrap input list mapping\n l = []\n for i in range(len(resolved)):\n if type(resolved.data[i]) is config.Reference:\n # avoid resolving key in Sequence\n mib = magicInput if magicInput is not None else self.magicInputBrick(val.data[i])\n l.append(InputWrap(self, mib, os.path.join(item, anyput, str(i))))\n else:\n # potentially resolve key\n l.append(resolved[i])\n anyputMap[anyput] = l\n elif type(val) is config.Reference:\n # wrap plain input mapping\n # rather, put an fsPath() implementation on Reference?\n anyputMap[anyput] = InputWrap(self, self.magicInputBrick(val), os.path.join(item, anyput))\n # TODO: config.Reference does not necessarily mean this is a mapping to an output. It could be referring to a hardcoded filename.\n else:\n # resolve other keys if necessary (e.g. hardcoded filenames, pieced together)\n #anyputMap[anyput] = anyputs[anyput]\n anyputMap[anyput] = resolved\n # bla, bla. the usual input processing. why do I keep repeating it?\n # need recursion for resolving References in a Sequence\n\n # TODO: maybe a processing helper with a callback?\n # either callback, or map()-like interface (like here), ...\n return anyputMap\n\n\nclass ConfigGenerator(object):\n def __init__(self, cfgFileName, setupFileName=None, logLevel=logging.ERROR):\n # Logging\n ch = logging.StreamHandler()\n config.logger.addHandler(ch)\n config.logger.setLevel(logLevel)\n\n # Paths\n\n # search path for both global config includes @\n # and Jinja templates.\n try:\n appDir = os.path.dirname(os.path.realpath(__file__))\n except NameError:\n # for interactive Python use\n sys.stderr.write('warning: cannot resolve appDir, interactive mode in %s\\n' % os.getcwd())\n appDir = os.getcwd()\n self.appDir = appDir\n searchPath = os.path.join(appDir, 'bricks')\n\n self.searchPath = searchPath\n self.env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=searchPath))\n configSearchPath = config.ConfigSearchPath([searchPath])\n\n if setupFileName is None:\n setupFileName = '%s.cfg' % os.uname()[1].capitalize()\n # resolve relative path in bricks program root\n setupFileName = configSearchPath.searchGlobalFile('Setups/%s' % setupFileName)\n\n # Create basic Config (not instantiated, i.e. no inheritance or loops)\n self.cfg = config.Config(file(cfgFileName), searchPath=configSearchPath)\n setup = config.Config(setupFileName, parent=self.cfg, searchPath=configSearchPath)\n # implicit str $BRICKS: path to bricks program root directory\n if not 'BRICKS' in setup:\n setup.BRICKS = appDir\n\n # implicit Mapping $Setup: Experiment can inherit $Setup for machine-specific config keys\n self.cfg.Setup = setup\n\n def instantiate(self):\n # resolve inheritance\n self.cfg = self.cfg.instantiate()\n self.experiment = self.cfg.Experiment\n\n def replaceFileContents(self, fileName, newContents):\n \"\"\"\n Only replace fileName with newContents if the contents differ\n from what the file currently contains.\n This avoids changing mtime of the file and thus avoids the\n runner system re-running bricks which haven't changed.\n \"\"\"\n if os.path.exists(fileName):\n with open(fileName) as fi:\n oldContents = fi.read()\n if oldContents == newContents:\n # no need to update the file\n return\n\n # create directory if necessary\n if not os.path.exists(os.path.dirname(fileName)):\n os.makedirs(os.path.dirname(fileName))\n\n with open(fileName, 'w') as fo:\n fo.write(newContents)\n\n def generateRedoFile(self, brick):\n \"\"\"\n Generate a redo file from template for this Brick.\n \"\"\"\n if 'template' in brick:\n # short specification of Jinja template for {% block Work %}\n with open(os.path.join(self.searchPath, 'template.do.jinja')) as fi:\n # 1) Python string interpolation in %%s (from 'template:')\n # 2) Jinja template expansion\n template = self.env.from_string(fi.read() % brick.template)\n elif 'templateFile' in brick:\n # load specified Jinja template file\n template = self.env.get_template(brick.templateFile)\n else:\n # default fallback - nothing to do (but still checks dependencies)\n template = self.env.get_template('brick.do.jinja')\n\n # Render the Jinja template\n try:\n brickDo = template.render({'brick': TemplateBrick(brick)})\n except:\n logging.exception(\"Error while rendering Brick %s\" % brick.path)\n raise\n\n # create/replace redo file, if necessary\n targetFile = os.path.join(brick.filesystemPath(), 'brick.do')\n self.replaceFileContents(targetFile, brickDo)\n\n def generateBricks(self, cfgBrick):\n \"\"\"\n Recursively generate a config for this Brick and all\n its parts.\n @param cfgBrick config.Mapping entry for this Brick.\n \"\"\"\n # we know / assume that this config.Mapping is a Brick.\n brick = Brick(cfgBrick)\n\n # nice debug prints\n #sys.stderr.write('%s\\n' % cfgBrick.path)\n #if len(brick.inputDependencies()) > 0:\n # sys.stderr.write(' input %s\\n' % str(brick.inputDependencies()))\n #if len(brick.outputDependencies()) > 0:\n # sys.stderr.write(' output %s\\n' % str(brick.outputDependencies()))\n\n # TODO: move to self\n brick.fsCreateSymlinks(brick.symlinks())\n self.generateRedoFile(brick)\n\n if 'parts' in brick:\n for part in brick.parts.keys():\n self.generateBricks(brick.parts[part])\n\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--setup', help='Setup config file included as $Setup.', default=None)\n parser.add_argument('-v', '--verbose', help='Verbose mode for debugging.', action='store_true')\n parser.add_argument('config', help='Root Experiment config file.', nargs='?', default='experiment.cfg')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = parseArguments()\n\n logLevel = logging.DEBUG if args.verbose else logging.ERROR\n gen = ConfigGenerator(args.config, args.setup, logLevel)\n gen.instantiate()\n gen.generateBricks(gen.experiment)\n\n # create convenience default.do file\n shutil.copy(os.path.join(gen.appDir, 'bricks/default.do'), os.getcwd())\n","repo_name":"cidermole/bricks","sub_path":"bricks.py","file_name":"bricks.py","file_ext":"py","file_size_in_byte":22536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73689456486","text":"from guineapig import *\nimport sys\nimport gpextras\n\n# wordcount modified for mrs\n\n# supporting routines can go here\ndef tokens(line): \n for tok in line.split(): \n yield tok.lower()\n\n#always subclass Planner\nclass WordCount(Planner):\n\n wc = ReadLines('corpus.txt') | Flatten(by=tokens) | Group(by=lambda x:x, reducingTo=ReduceToCount())\n\n# always end like this\nif __name__ == \"__main__\":\n p = WordCount()\n p.registerCompiler('mrs',gpextras.MRSCompiler)\n p.main(sys.argv)\n\n","repo_name":"TeamCohen/GuineaPig","sub_path":"mrs_test/mrs-wordcount.py","file_name":"mrs-wordcount.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"}
+{"seq_id":"13415364845","text":"\"\"\" RHF-CCSD similarity transformed Hamiltonian \"\"\"\n\n__authors__ = \"Ashutosh Kumar\"\n__credits__ = [\n \"T. D. Crawford\", \"Daniel G. A. Smith\", \"Lori A. Burns\", \"Ashutosh Kumar\"\n]\n\n__copyright__ = \"(c) 2014-2018, The Psi4NumPy Developers\"\n__license__ = \"BSD-3-Clause\"\n__date__ = \"2017-05-17\"\n\nimport time\nimport numpy as np\nimport psi4\nfrom utils import ndot\n\n\nclass HelperCCHbar(object):\n \"\"\"\n This class builds pieces of the similarity transformed hamiltomian,\n Hbar = e^(-T)He^(T) = H + [H,T] + 1/2![[H,T],T] + 1/3![[[H,T],T],T] + 1/4![[[[H,T],T],T],T]\n which can be used quite conveniently to solve lambda equations, calculate excitation energies \n (EOM-CC sigma equations), CC response properties etc.. Spin orbitals expression of all Hbar \n components are written in einstein notation in the doctrings of functions below. Ofcourse, \n we are constructing (or beta) and \n
components here.\n\n References: \n 1. J. Gauss and J.F. Stanton, J. Chem. Phys., volume 103, pp. 3561-3577 (1995). \n \"\"\"\n\n def __init__(self, ccsd, memory=2):\n\n # Start of the cchbar class\n time_init = time.time()\n\n self.MO = ccsd.MO\n self.ndocc = ccsd.ndocc\n self.nmo = ccsd.nmo\n self.nocc = ccsd.ndocc\n self.nvirt = ccsd.nmo - ccsd.nocc\n\n self.slice_o = slice(0, self.nocc)\n self.slice_v = slice(self.nocc, self.nmo)\n self.slice_a = slice(0, self.nmo)\n self.slice_dict = {\n 'o': self.slice_o,\n 'v': self.slice_v,\n 'a': self.slice_a\n }\n\n self.F = ccsd.F\n self.Dia = ccsd.Dia\n self.Dijab = ccsd.Dijab\n self.t1 = ccsd.t1\n self.t2 = ccsd.t2\n\n print('\\nBuilding HBAR components ...')\n\n self.build_Loovv()\n self.build_Looov()\n self.build_Lvovv()\n\n self.build_Hov()\n self.build_Hoo()\n self.build_Hvv()\n self.build_Hoooo()\n self.build_Hvvvv()\n self.build_Hvovv()\n self.build_Hooov()\n self.build_Hovvo()\n self.build_Hovov()\n self.build_Hvvvo()\n self.build_Hovoo()\n\n print('\\n..HBAR Build completed !!')\n\n # occ orbitals i, j, k, l, m, n\n # virt orbitals a, b, c, d, e, f\n # all oribitals p, q, r, s, t, u, v\n\n def get_MO(self, string):\n if len(string) != 4:\n psi4.core.clean()\n raise Exception('get_MO: string %s must have 4 elements.' % string)\n return self.MO[self.slice_dict[string[0]], self.slice_dict[string[1]],\n self.slice_dict[string[2]], self.slice_dict[string[3]]]\n\n def get_F(self, string):\n if len(string) != 2:\n psi4.core.clean()\n raise Exception('get_F: string %s must have 2 elements.' % string)\n return self.F[self.slice_dict[string[0]], self.slice_dict[string[1]]]\n\n def build_Loovv(self):\n tmp = self.get_MO('oovv').copy()\n self.Loovv = 2.0 * tmp - tmp.swapaxes(2, 3)\n return self.Loovv\n\n def build_Looov(self):\n tmp = self.get_MO('ooov').copy()\n self.Looov = 2.0 * tmp - tmp.swapaxes(0, 1)\n return self.Looov\n\n def build_Lvovv(self):\n tmp = self.get_MO('vovv').copy()\n self.Lvovv = 2.0 * tmp - tmp.swapaxes(2, 3)\n return self.Lvovv\n\n def build_tau(self):\n self.ttau = self.t2.copy()\n tmp = np.einsum('ia,jb->ijab', self.t1, self.t1)\n self.ttau += tmp\n return self.ttau\n\n # F and W are the one and two body intermediates which appear in the CCSD\n # T1 and T2 equations. Please refer to helper_ccenergy file for more details.\n\n def build_Hov(self):\n \"\"\" = F_me = f_me + t_nf \"\"\"\n self.Hov = self.get_F('ov').copy()\n self.Hov += ndot('nf,mnef->me', self.t1, self.Loovv)\n return self.Hov\n\n def build_Hoo(self):\n \"\"\"\n = F_mi + 0.5 * t_ie F_me = f_mi + t_ie f_me\n + t_ne + tau_inef \n \"\"\"\n self.Hoo = self.get_F('oo').copy()\n self.Hoo += ndot('ie,me->mi', self.t1, self.get_F('ov'))\n self.Hoo += ndot('ne,mnie->mi', self.t1, self.Looov)\n self.Hoo += ndot('inef,mnef->mi', self.build_tau(), self.Loovv)\n return self.Hoo\n\n def build_Hvv(self):\n \"\"\"\n = F_ae - 0.5 * t_ma F_me = f_ae - t_ma f_me \n + t_mf - tau_mnfa \n \"\"\"\n self.Hvv = self.get_F('vv').copy()\n self.Hvv -= ndot('ma,me->ae', self.t1, self.get_F('ov'))\n self.Hvv += ndot('mf,amef->ae', self.t1, self.Lvovv)\n self.Hvv -= ndot('mnfa,mnfe->ae', self.build_tau(), self.Loovv)\n return self.Hvv\n\n def build_Hoooo(self):\n \"\"\" \n = W_mnij + 0.25 * tau_ijef = \n + P(ij) t_je + 0.5 * tau_ijef \n \"\"\"\n self.Hoooo = self.get_MO('oooo').copy()\n self.Hoooo += ndot('je,mnie->mnij', self.t1, self.get_MO('ooov'))\n self.Hoooo += ndot('ie,mnej->mnij', self.t1, self.get_MO('oovo'))\n self.Hoooo += ndot('ijef,mnef->mnij', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hoooo\n\n def build_Hvvvv(self):\n \"\"\"\n = W_abef + 0.25 * tau_mnab = \n - P(ab) t_mb + 0.5 * tau_mnab \n \"\"\"\n self.Hvvvv = self.get_MO('vvvv').copy()\n self.Hvvvv -= ndot('mb,amef->abef', self.t1, self.get_MO('vovv'))\n self.Hvvvv -= ndot('ma,bmfe->abef', self.t1, self.get_MO('vovv'))\n self.Hvvvv += ndot('mnab,mnef->abef', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hvvvv\n\n def build_Hvovv(self):\n \"\"\" = - t_na \"\"\"\n self.Hvovv = self.get_MO('vovv').copy()\n self.Hvovv -= ndot('na,nmef->amef', self.t1, self.get_MO('oovv'))\n return self.Hvovv\n\n def build_Hooov(self):\n \"\"\" = + t_if \"\"\"\n self.Hooov = self.get_MO('ooov').copy()\n self.Hooov += ndot('if,mnfe->mnie', self.t1, self.get_MO('oovv'))\n return self.Hooov\n\n def build_Hovvo(self):\n \"\"\" \n = W_mbej - 0.5 * t_jnfb = + t_jf \n - t_nb - (t_jnfb + t_jf t_nb) \n \"\"\"\n self.Hovvo = self.get_MO('ovvo').copy()\n self.Hovvo += ndot('jf,mbef->mbej', self.t1, self.get_MO('ovvv'))\n self.Hovvo -= ndot('nb,mnej->mbej', self.t1, self.get_MO('oovo'))\n self.Hovvo -= ndot('jnfb,nmfe->mbej', self.build_tau(),\n self.get_MO('oovv'))\n self.Hovvo += ndot('jnbf,nmfe->mbej', self.t2, self.Loovv)\n return self.Hovvo\n\n def build_Hovov(self):\n \"\"\" \n = - = + t_jf - t_nb \n - (t_jnfb + t_jf t_nb) \n \"\"\"\n self.Hovov = self.get_MO('ovov').copy()\n self.Hovov += ndot('jf,bmef->mbje', self.t1, self.get_MO('vovv'))\n self.Hovov -= ndot('nb,mnje->mbje', self.t1, self.get_MO('ooov'))\n self.Hovov -= ndot('jnfb,nmef->mbje', self.build_tau(),\n self.get_MO('oovv'))\n return self.Hovov\n\n def build_Hvvvo(self):\n \"\"\"\n = - F_me t_miab + t_if Wabef + 0.5 * tau_mnab \n - P(ab) t_miaf - P(ab) t_ma { - t_nibf }\n \"\"\"\n # \n\n self.Hvvvo = self.get_MO('vvvo').copy()\n\n # - Fme t_miab\n\n self.Hvvvo -= ndot('me,miab->abei', self.get_F('ov'), self.t2)\n tmp = ndot('mnfe,mf->ne', self.Loovv, self.t1)\n self.Hvvvo -= ndot('niab,ne->abei', self.t2, tmp)\n\n # t_if Wabef\n\n self.Hvvvo += ndot('if,abef->abei', self.t1, self.get_MO('vvvv'))\n tmp = ndot('if,ma->imfa', self.t1, self.t1)\n self.Hvvvo -= ndot('imfa,mbef->abei', tmp, self.get_MO('ovvv'))\n self.Hvvvo -= ndot('imfb,amef->abei', tmp, self.get_MO('vovv'))\n tmp = ndot('mnef,if->mnei', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('mnab,mnei->abei', self.t2, tmp)\n tmp = ndot('if,ma->imfa', self.t1, self.t1)\n tmp1 = ndot('mnef,nb->mbef', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('imfa,mbef->abei', tmp, tmp1)\n\n # 0.5 * tau_mnab \n\n self.Hvvvo += ndot('mnab,mnei->abei', self.build_tau(),\n self.get_MO('oovo'))\n\n # - P(ab) t_miaf \n\n self.Hvvvo -= ndot('imfa,mbef->abei', self.t2, self.get_MO('ovvv'))\n self.Hvvvo -= ndot('imfb,amef->abei', self.t2, self.get_MO('vovv'))\n self.Hvvvo += ndot('mifb,amef->abei', self.t2, self.Lvovv)\n\n # - P(ab) t_ma \n\n self.Hvvvo -= ndot('mb,amei->abei', self.t1, self.get_MO('vovo'))\n self.Hvvvo -= ndot('ma,bmie->abei', self.t1, self.get_MO('voov'))\n\n # P(ab) t_ma * t_nibf \n\n tmp = ndot('mnef,ma->anef', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('infb,anef->abei', self.t2, tmp)\n tmp = ndot('mnef,ma->nafe', self.Loovv, self.t1)\n self.Hvvvo -= ndot('nifb,nafe->abei', self.t2, tmp)\n tmp = ndot('nmef,mb->nefb', self.get_MO('oovv'), self.t1)\n self.Hvvvo += ndot('niaf,nefb->abei', self.t2, tmp)\n return self.Hvvvo\n\n def build_Hovoo(self):\n \"\"\" \n = - Fme t_ijbe - t_nb Wmnij + 0.5 * tau_ijef \n + P(ij) t_jnbe + P(ij) t_ie { - t_njbf }\n \"\"\"\n # \n\n self.Hovoo = self.get_MO('ovoo').copy()\n\n # - Fme t_ijbe\n\n self.Hovoo += ndot('me,ijeb->mbij', self.get_F('ov'), self.t2)\n tmp = ndot('mnef,nf->me', self.Loovv, self.t1)\n self.Hovoo += ndot('me,ijeb->mbij', tmp, self.t2)\n\n # - t_nb Wmnij\n\n self.Hovoo -= ndot('nb,mnij->mbij', self.t1, self.get_MO('oooo'))\n tmp = ndot('ie,nb->ineb', self.t1, self.t1)\n self.Hovoo -= ndot('ineb,mnej->mbij', tmp, self.get_MO('oovo'))\n self.Hovoo -= ndot('jneb,mnie->mbij', tmp, self.get_MO('ooov'))\n tmp = ndot('nb,mnef->mefb', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('ijef,mefb->mbij', self.t2, tmp)\n tmp = ndot('ie,jf->ijef', self.t1, self.t1)\n tmp1 = ndot('nb,mnef->mbef', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('mbef,ijef->mbij', tmp1, tmp)\n\n # 0.5 * tau_ijef \n\n self.Hovoo += ndot('ijef,mbef->mbij', self.build_tau(),\n self.get_MO('ovvv'))\n\n # P(ij) t_jnbe \n\n self.Hovoo -= ndot('ineb,mnej->mbij', self.t2, self.get_MO('oovo'))\n self.Hovoo -= ndot('jneb,mnie->mbij', self.t2, self.get_MO('ooov'))\n self.Hovoo += ndot('jnbe,mnie->mbij', self.t2, self.Looov)\n\n # P(ij) t_ie \n\n self.Hovoo += ndot('je,mbie->mbij', self.t1, self.get_MO('ovov'))\n self.Hovoo += ndot('ie,mbej->mbij', self.t1, self.get_MO('ovvo'))\n\n # - P(ij) t_ie * t_njbf \n\n tmp = ndot('ie,mnef->mnif', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('jnfb,mnif->mbij', self.t2, tmp)\n tmp = ndot('mnef,njfb->mejb', self.Loovv, self.t2)\n self.Hovoo += ndot('mejb,ie->mbij', tmp, self.t1)\n tmp = ndot('je,mnfe->mnfj', self.t1, self.get_MO('oovv'))\n self.Hovoo -= ndot('infb,mnfj->mbij', self.t2, tmp)\n return self.Hovoo\n\n\n# End HelperCCHbar class\n","repo_name":"psi4/psi4numpy","sub_path":"Coupled-Cluster/RHF/helper_cchbar.py","file_name":"helper_cchbar.py","file_ext":"py","file_size_in_byte":11774,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"}
+{"seq_id":"38459256865","text":"from . import core\nfrom .config import (\n Project,\n CURRENT_PYTHON_VERSION,\n DEFAULT_BZ2_VERSION,\n DEFAULT_SSL_VERSION,\n DEFAULT_XZ_VERSION,\n)\n\n\n# -----------------------------------------------------------------------------\n# UTILITY FUNCTIONS\n\n# returns default if k is not found in d or d[k] returns None\ndef get(d, k, default):\n return d[k] if k in d and d[k] else default\n\n\n# -----------------------------------------------------------------------------\n# FACTORY MANAGER\n\nclass FactoryManager:\n \"\"\"\n The builder.FactoryManager organizes production of custom Python builds and\n Python3 externals.\n\n It provides factory methods which dispatch to specialized builders\n which build a corresponding product.\n\n FM -> factories -> builders -> products.\n \"\"\"\n\n PYTHON_BUILDERS = dict(\n python_shared=core.SharedPythonBuilder,\n python_shared_ext=core.SharedPythonForExtBuilder,\n python_shared_pkg=core.SharedPythonForPkgBuilder,\n python_shared_tiny=core.TinySharedPythonBuilder,\n python_framework=core.FrameworkPythonBuilder,\n python_framework_ext=core.FrameworkPythonForExtBuilder,\n python_framework_pkg=core.FrameworkPythonForPkgBuilder,\n python_relocatable=core.RelocatablePythonBuilder,\n python_static=core.StaticPythonBuilder,\n python_static_tiny=core.TinyStaticPythonBuilder,\n python_beeware=core.BeewarePythonBuilder,\n python_cmake=core.PythonCmakeBuilder,\n )\n\n PYJS_BUILDERS = dict(\n pyjs_local_sys=(core.LocalSystemBuilder, []),\n pyjs_homebrew_ext=(core.HomebrewExtBuilder, []),\n pyjs_homebrew_pkg=(core.HomebrewPkgBuilder, []),\n pyjs_shared_ext=(core.SharedExtBuilder, [\"python_shared_ext\"]),\n pyjs_shared_tiny_ext=(core.SharedExtBuilder, [\"python_shared_tiny\"]),\n pyjs_shared_pkg=(core.SharedPkgBuilder, [\"python_shared_pkg\"]),\n pyjs_framework_ext=(core.FrameworkExtBuilder, [\"python_framework_ext\"]),\n pyjs_framework_pkg=(core.FrameworkPkgBuilder, [\"python_framework_pkg\"]),\n pyjs_relocatable_pkg=(core.RelocatablePkgBuilder, [\"python_relocatable\"]),\n pyjs_static_ext=(core.StaticExtBuilder, [\"python_static\"]),\n pyjs_static_tiny_ext=(core.StaticExtBuilder, [\"python_static_tiny\"]),\n pyjs_beeware_ext=(core.BeewareExtBuilder, [\"python_beeware\"]),\n )\n\n# -----------------------------------------------------------------------------\n# DEPENDENCY PRODUCTS\n\n def get_bzip2_product(self, bz2_version=DEFAULT_BZ2_VERSION, **settings):\n return core.Product(\n name=\"bzip2\",\n version=bz2_version,\n url_template=\"https://sourceware.org/pub/bzip2/{name}-{version}.tar.gz\",\n libs_static=[\"libbz2.a\"],\n )\n\n\n def get_ssl_product(self, ssl_version=DEFAULT_SSL_VERSION, **settings):\n return core.Product(\n name=\"openssl\",\n version=ssl_version,\n url_template=\"https://www.openssl.org/source/{name}-{version}.tar.gz\",\n libs_static=[\"libssl.a\", \"libcrypto.a\"],\n )\n\n\n def get_xz_product(self, xz_version=DEFAULT_XZ_VERSION, **settings):\n return core.Product(\n name=\"xz\",\n version=\"5.2.5\",\n url_template=\"http://tukaani.org/xz/{name}-{version}.tar.gz\",\n libs_static=[\"libxz.a\"],\n )\n\n\n# -----------------------------------------------------------------------------\n# DEPENDENCY BUILDERS\n\n\n def dependency_builder_factory(self, name, **settings):\n\n bz2_version = get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n ssl_version = get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n xz_version = get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n return {\n \"bz2\": core.Bzip2Builder(product=self.get_bzip2_product(bz2_version), **settings),\n \"ssl\": core.OpensslBuilder(product=self.get_ssl_product(ssl_version), **settings),\n \"xz\": core.XzBuilder(product=self.get_xz_product(xz_version), **settings),\n }[name]\n\n\n# -----------------------------------------------------------------------------\n# PYTHON BUILDERS\n\n\n def python_builder_factory(self, name, **settings):\n\n py_version = get(settings, \"python_version\", CURRENT_PYTHON_VERSION)\n bz2_version = get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n ssl_version = get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n xz_version = get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n _builder = self.PYTHON_BUILDERS[name]\n\n _dependencies = [\n core.Bzip2Builder(product=self.get_bzip2_product(bz2_version), **settings),\n core.OpensslBuilder(product=self.get_ssl_product(ssl_version), **settings),\n core.XzBuilder(product=self.get_xz_product(xz_version), **settings),\n ]\n\n product = core.Product(\n name=\"Python\",\n version=py_version,\n # build_dir=\"-\".join(name.split(\"_\")),\n build_dir=\"-\".join(name.split(\"_\")[:2]),\n url_template=\"https://www.python.org/ftp/python/{version}/Python-{version}.tgz\",\n libs_static=[f\"libpython{'.'.join(py_version.split('.')[:-1])}.a\"],\n )\n\n _independent_python_builders = [\n core.PythonCmakeBuilder,\n core.RelocatablePythonBuilder,\n ]\n\n if any(isinstance(_builder, i) for i in _independent_python_builders):\n return _builder(product=product, **settings)\n else:\n return _builder(product=product, depends_on=_dependencies, **settings)\n\n\n# -----------------------------------------------------------------------------\n# PYJS BUILDERS\n\n\n def pyjs_builder_factory(self, name, **settings):\n\n py_version = get(settings, \"python_version\", CURRENT_PYTHON_VERSION)\n get(settings, \"bz2_version\", DEFAULT_BZ2_VERSION)\n get(settings, \"ssl_version\", DEFAULT_SSL_VERSION)\n get(settings, \"xz_version\", DEFAULT_XZ_VERSION)\n\n _builder, dependencies = self.PYJS_BUILDERS[name]\n if dependencies:\n return _builder(\n product=core.Product(name=\"Python\", version=py_version),\n depends_on=[\n self.python_builder_factory(name, **settings) for name in dependencies\n ],\n **settings,\n )\n else:\n # no dep builder is a local builder therefore default_py_ver\n return _builder(\n product=core.Product(name=\"Python\", version=CURRENT_PYTHON_VERSION),\n **settings,\n )\n\n\n# -----------------------------------------------------------------------------\n# GENERIC BUILDERS\n\n\n def builder_factory(self, name, **settings):\n builder = None\n try:\n builder = self.pyjs_builder_factory(name, **settings)\n Project().record_variant(name)\n except KeyError:\n try:\n builder = self.python_builder_factory(name, **settings)\n except KeyError:\n try:\n builder = self.dependency_builder_factory(name, **settings)\n except KeyError:\n print(f\"builder type '{name}' not found in any factory.\")\n\n return builder\n\n\n# -----------------------------------------------------------------------------\n# RECIPES\n\n# An example of a recipe which can fix requirements to versions.\n\n\n def get_static_python_recipe(\n self,\n name,\n py_version=CURRENT_PYTHON_VERSION,\n bz2_version=DEFAULT_BZ2_VERSION,\n ssl_version=DEFAULT_SSL_VERSION,\n xz_version=DEFAULT_XZ_VERSION,\n **settings,\n ):\n return core.Recipe(\n name=name,\n builders=[\n core.StaticPythonBuilder(\n product=core.Product(\n name=\"Python\",\n version=py_version,\n build_dir=\"python-static\",\n url_template=\"https://www.python.org/ftp/python/{version}/Python-{version}.tgz\",\n libs_static=[f\"libpython{'.'.join(py_version.split('.')[:-1])}.a\"],\n ),\n depends_on=[\n core.Bzip2Builder(\n product=self.get_bzip2_product(bz2_version, **settings)\n ),\n core.OpensslBuilder(\n product=self.get_ssl_product(ssl_version, **settings)\n ),\n core.XzBuilder(product=self.get_xz_product(xz_version, **settings)),\n ],\n )\n ],\n )\n","repo_name":"shakfu/py-js","sub_path":"source/projects/py/builder/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":8709,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"52"}
+{"seq_id":"33534461360","text":"import collections\n\ns = \"bcabc\"\n\ncounter, stack = collections.Counter(s), collections.deque()\n\nfor char in s:\n counter[char] -= 1\n\n if char in stack:\n continue\n\n while stack and char < stack[-1] and counter[stack[-1]] > 0:\n stack.pop()\n stack.append(char)\n\nprint(''.join(stack))","repo_name":"mathjihun/Python","sub_path":"Algorithm/remove_duplicate_letters.py","file_name":"remove_duplicate_letters.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38393685427","text":"import logging\n\nwithFile = False\n\n\ndef log_with_file(logWithFile=False):\n global withFile\n withFile = logWithFile\n\n\ndef get_logger():\n if withFile:\n logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s', filename='main.log',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)\n else:\n logging.basicConfig(format='%(asctime)s - %(levelname)s : %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)\n return logging.getLogger()\n\n\ndef bounding_box_from_tuple(tuple_of_bbox):\n bbox = [float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[0].split(\" \")[0].split(\"(\")[1]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[0].split(\" \")[1]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[1].split(\" \")[0]),\n float(tuple_of_bbox[0][0].split(\"BOX\")[1].split(\",\")[1].split(\" \")[1].split(\")\")[0])]\n return bbox\n\n\ndef process_escape_character(data):\n if data is not None:\n return data.replace('\\'', '\\'\\'')\n return None\n\n\ndef build_string_for_solr(fields):\n result = ''\n for f in fields:\n if f is not None:\n result += ' ' + f + ' '\n return result\n","repo_name":"ifpb/SDI-Search-Engine","sub_path":"processing_engine/util/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"31505114512","text":"import copy\n\nimport autograd.numpy\nimport pytest\n\nimport pennylane as qml\nfrom pennylane import numpy as np\nfrom pennylane.measurements import ClassicalShadowMP, Shots\nfrom pennylane.measurements.classical_shadow import ShadowExpvalMP\n\n# pylint: disable=dangerous-default-value, too-many-arguments\n\n\ndef get_circuit(wires, shots, seed_recipes, interface=\"autograd\", device=\"default.qubit\"):\n \"\"\"\n Return a QNode that prepares the state (|00...0> + |11...1>) / sqrt(2)\n and performs the classical shadow measurement\n \"\"\"\n dev = qml.device(device, wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n qml.Hadamard(wires=0)\n\n for target in range(1, wires):\n qml.CNOT(wires=[0, target])\n\n return qml.classical_shadow(wires=range(wires), seed=seed_recipes)\n\n return circuit\n\n\ndef get_x_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |++..+> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n for wire in range(wires):\n qml.Hadamard(wire)\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\ndef get_y_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |+i>|+i>...|+i> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n for wire in range(wires):\n qml.Hadamard(wire)\n qml.RZ(np.pi / 2, wire)\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\ndef get_z_basis_circuit(wires, shots, interface=\"autograd\"):\n \"\"\"\n Return a QNode that prepares the |00..0> state and performs a classical shadow measurement\n \"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit():\n return qml.classical_shadow(wires=range(wires))\n\n return circuit\n\n\nwires_list = [1, 3]\n\n\nclass TestProcessState:\n \"\"\"Unit tests for process_state_with_shots for the classical_shadow\n and shadow_expval measurements\"\"\"\n\n def test_shape_and_dtype(self):\n \"\"\"Test that the shape and dtype of the measurement is correct\"\"\"\n mp = qml.classical_shadow(wires=[0, 1])\n res = mp.process_state_with_shots(np.ones((2, 2)) / 2, qml.wires.Wires([0, 1]), shots=100)\n\n assert res.shape == (2, 100, 2)\n assert res.dtype == np.int8\n\n # test that the bits are either 0 and 1\n assert np.all(np.logical_or(res[0] == 0, res[0] == 1))\n\n # test that the recipes are either 0, 1, or 2 (X, Y, or Z)\n assert np.all(np.logical_or(np.logical_or(res[1] == 0, res[1] == 1), res[1] == 2))\n\n def test_wire_order(self):\n \"\"\"Test that the wire order is respected\"\"\"\n state = np.array([[1, 1], [0, 0]]) / np.sqrt(2)\n\n mp = qml.classical_shadow(wires=[0, 1])\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000)\n\n assert res.shape == (2, 1000, 2)\n assert res.dtype == np.int8\n\n # test that the first qubit samples are all 0s when the recipe is Z\n assert np.all(res[0][res[1, ..., 0] == 2][:, 0] == 0)\n\n # test that the second qubit samples contain 1s when the recipe is Z\n assert np.any(res[0][res[1, ..., 1] == 2][:, 1] == 1)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([1, 0]), shots=1000)\n\n assert res.shape == (2, 1000, 2)\n assert res.dtype == np.int8\n\n # now test that the first qubit samples contain 1s when the recipe is Z\n assert np.any(res[0][res[1, ..., 0] == 2][:, 0] == 1)\n\n # now test that the second qubit samples are all 0s when the recipe is Z\n assert np.all(res[0][res[1, ..., 1] == 2][:, 1] == 0)\n\n def test_subset_wires(self):\n \"\"\"Test that the measurement is correct when only a subset of wires is measured\"\"\"\n mp = qml.classical_shadow(wires=[0, 1])\n\n # GHZ state\n state = np.zeros((2, 2, 2))\n state[np.array([0, 1]), np.array([0, 1]), np.array([0, 1])] = 1 / np.sqrt(2)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n\n assert res.shape == (2, 100, 2)\n assert res.dtype == np.int8\n\n # test that the bits are either 0 and 1\n assert np.all(np.logical_or(res[0] == 0, res[0] == 1))\n\n # test that the recipes are either 0, 1, or 2 (X, Y, or Z)\n assert np.all(np.logical_or(np.logical_or(res[1] == 0, res[1] == 1), res[1] == 2))\n\n def test_same_rng(self):\n \"\"\"Test results when the rng is the same\"\"\"\n state = np.ones((2, 2)) / 2\n\n mp1 = qml.classical_shadow(wires=[0, 1], seed=123)\n mp2 = qml.classical_shadow(wires=[0, 1], seed=123)\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100)\n\n # test recipes are the same but bits are different\n assert np.all(res1[1] == res2[1])\n assert np.any(res1[0] != res2[0])\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100, rng=456)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=100, rng=456)\n\n # now test everything is the same\n assert np.all(res1[1] == res2[1])\n assert np.all(res1[0] == res2[0])\n\n def test_expval_shape_and_val(self):\n \"\"\"Test that shadow expval measurements work as expected\"\"\"\n mp = qml.shadow_expval(qml.PauliX(0) @ qml.PauliX(1), seed=200)\n res = mp.process_state_with_shots(\n np.ones((2, 2)) / 2, qml.wires.Wires([0, 1]), shots=1000, rng=100\n )\n\n assert res.shape == ()\n assert np.allclose(res, 1.0, atol=0.05)\n\n def test_expval_wire_order(self):\n \"\"\"Test that shadow expval respects the wire order\"\"\"\n state = np.array([[1, 1], [0, 0]]) / np.sqrt(2)\n\n mp = qml.shadow_expval(qml.PauliZ(0), seed=200)\n res = mp.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=3000, rng=100)\n\n assert res.shape == ()\n assert np.allclose(res, 1.0, atol=0.05)\n\n res = mp.process_state_with_shots(state, qml.wires.Wires([1, 0]), shots=3000, rng=100)\n\n assert res.shape == ()\n assert np.allclose(res, 0.0, atol=0.05)\n\n def test_expval_same_rng(self):\n \"\"\"Test expval results when the rng is the same\"\"\"\n state = np.ones((2, 2)) / 2\n\n mp1 = qml.shadow_expval(qml.PauliZ(0) @ qml.PauliZ(1), seed=123)\n mp2 = qml.shadow_expval(qml.PauliZ(0) @ qml.PauliZ(1), seed=123)\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=100)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=200)\n\n # test results are different\n assert res1 != res2\n\n res1 = mp1.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=456)\n res2 = mp2.process_state_with_shots(state, qml.wires.Wires([0, 1]), shots=1000, rng=456)\n\n # now test that results are the same\n assert res1 == res2\n\n\n@pytest.mark.parametrize(\"wires\", wires_list)\nclass TestClassicalShadow:\n \"\"\"Unit tests for classical_shadow measurement\"\"\"\n\n shots_list = [1, 100]\n seed_recipes_list = [None, 74] # random seed\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_numeric_type(self, wires, seed):\n \"\"\"Test that the numeric type of the MeasurementProcess instance is correct\"\"\"\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n assert res.numeric_type == int\n\n @pytest.mark.parametrize(\"shots\", shots_list)\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_shape(self, wires, shots, seed):\n \"\"\"Test that the shape of the MeasurementProcess instance is correct\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n shots_obj = Shots(shots)\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n assert res.shape(dev, shots_obj) == (2, shots, wires)\n\n # test an error is raised when device is None\n msg = \"Shots must be specified to obtain the shape of a classical shadow measurement\"\n with pytest.raises(qml.measurements.MeasurementShapeError, match=msg):\n res.shape(dev, Shots(None))\n\n def test_shape_matches(self, wires):\n \"\"\"Test that the shape of the MeasurementProcess matches the shape\n of the tape execution\"\"\"\n shots = 100\n\n circuit = get_circuit(wires, shots, True)\n circuit.construct((), {})\n\n res = qml.execute([circuit.tape], circuit.device, None)[0]\n expected_shape = qml.classical_shadow(wires=range(wires)).shape(\n circuit.device, Shots(shots)\n )\n\n assert res.shape == expected_shape\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_measurement_process_copy(self, wires, seed):\n \"\"\"Test that the attributes of the MeasurementProcess instance are\n correctly copied\"\"\"\n res = qml.classical_shadow(wires=range(wires), seed=seed)\n\n copied_res = copy.copy(res)\n assert isinstance(copied_res, ClassicalShadowMP)\n assert copied_res.return_type == res.return_type\n assert copied_res.wires == res.wires\n assert copied_res.seed == res.seed\n\n @pytest.mark.all_interfaces\n @pytest.mark.parametrize(\"shots\", shots_list)\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n @pytest.mark.parametrize(\"device\", [\"default.qubit\", \"default.mixed\"])\n def test_format(self, wires, shots, seed, interface, device):\n \"\"\"Test that the format of the returned classical shadow\n measurement is correct\"\"\"\n import tensorflow as tf\n import torch\n\n circuit = get_circuit(wires, shots, seed, interface, device)\n shadow = circuit()\n\n # test shape is correct\n assert shadow.shape == (2, shots, wires)\n\n # test dtype is correct\n expected_dtype = np.int8\n if interface == \"tf\":\n expected_dtype = tf.int8\n elif interface == \"torch\":\n expected_dtype = torch.int8\n\n assert shadow.dtype == expected_dtype\n\n bits, recipes = shadow # pylint: disable=unpacking-non-sequence\n\n # test allowed values of bits and recipes\n assert qml.math.all(np.logical_or(bits == 0, bits == 1))\n assert qml.math.all(np.logical_or(recipes == 0, np.logical_or(recipes == 1, recipes == 2)))\n\n @pytest.mark.all_interfaces\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n @pytest.mark.parametrize(\n \"circuit_fn, basis_recipe\",\n [(get_x_basis_circuit, 0), (get_y_basis_circuit, 1), (get_z_basis_circuit, 2)],\n )\n def test_return_distribution(self, wires, interface, circuit_fn, basis_recipe):\n \"\"\"Test that the distribution of the bits and recipes are correct for a circuit\n that prepares all qubits in a Pauli basis\"\"\"\n # high number of shots to prevent true negatives\n np.random.seed(42)\n shots = 1000\n\n circuit = circuit_fn(wires, shots=shots, interface=interface)\n bits, recipes = circuit()\n\n # test that the recipes follow a rough uniform distribution\n ratios = np.unique(recipes, return_counts=True)[1] / (wires * shots)\n assert np.allclose(ratios, 1 / 3, atol=1e-1)\n\n # test that the bit is 0 for all X measurements\n assert qml.math.allequal(bits[recipes == basis_recipe], 0)\n\n # test that the bits are uniformly distributed for all Y and Z measurements\n bits1 = bits[recipes == (basis_recipe + 1) % 3]\n ratios1 = np.unique(bits1, return_counts=True)[1] / bits1.shape[0]\n assert np.allclose(ratios1, 1 / 2, atol=1e-1)\n\n bits2 = bits[recipes == (basis_recipe + 2) % 3]\n ratios2 = np.unique(bits2, return_counts=True)[1] / bits2.shape[0]\n assert np.allclose(ratios2, 1 / 2, atol=1e-1)\n\n @pytest.mark.parametrize(\"seed\", seed_recipes_list)\n def test_shots_none_error(self, wires, seed):\n \"\"\"Test that an error is raised when a device with shots=None is used\n to obtain classical shadows\"\"\"\n circuit = get_circuit(wires, None, seed)\n\n msg = \"not accepted for analytic simulation on default.qubit\"\n with pytest.raises(qml.DeviceError, match=msg):\n circuit()\n\n @pytest.mark.parametrize(\"shots\", shots_list)\n def test_multi_measurement_error(self, wires, shots):\n \"\"\"Test that an error is raised when classical shadows is returned\n with other measurement processes\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=0)\n\n for target in range(1, wires):\n qml.CNOT(wires=[0, target])\n\n return qml.classical_shadow(wires=range(wires)), qml.expval(qml.PauliZ(0))\n\n res = circuit()\n assert isinstance(res, tuple) and len(res) == 2\n assert qml.math.shape(res[0]) == (2, shots, wires)\n assert qml.math.shape(res[1]) == ()\n\n\ndef hadamard_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n for i in range(wires):\n qml.Hadamard(wires=i)\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef max_entangled_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n qml.Hadamard(wires=0)\n for i in range(1, wires):\n qml.CNOT(wires=[0, i])\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef qft_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n one_state = np.zeros(wires)\n one_state[-1] = 1\n\n @qml.qnode(dev, interface=interface)\n def circuit(obs, k=1):\n qml.BasisState(one_state, wires=range(wires))\n qml.QFT(wires=range(wires))\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\n@pytest.mark.autograd\nclass TestExpvalMeasurement:\n def test_measurement_process_numeric_type(self):\n \"\"\"Test that the numeric type of the MeasurementProcess instance is correct\"\"\"\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H)\n assert res.numeric_type == float\n\n @pytest.mark.parametrize(\"wires\", [1, 2])\n @pytest.mark.parametrize(\"shots\", [1, 10])\n def test_measurement_process_shape(self, wires, shots):\n \"\"\"Test that the shape of the MeasurementProcess instance is correct\"\"\"\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H)\n assert len(res.shape(dev, Shots(shots))) == 0\n\n def test_shape_matches(self):\n \"\"\"Test that the shape of the MeasurementProcess matches the shape\n of the tape execution\"\"\"\n wires = 2\n shots = 100\n H = qml.PauliZ(0)\n\n circuit = hadamard_circuit(wires, shots)\n circuit.construct((H,), {})\n\n res = qml.execute([circuit.tape], circuit.device, None)[0]\n expected_shape = qml.shadow_expval(H).shape(circuit.device, Shots(shots))\n\n assert res.shape == expected_shape\n\n def test_measurement_process_copy(self):\n \"\"\"Test that the attributes of the MeasurementProcess instance are\n correctly copied\"\"\"\n H = qml.PauliZ(0)\n res = qml.shadow_expval(H, k=10)\n\n copied_res = copy.copy(res)\n assert type(copied_res) == type(res) # pylint: disable=unidiomatic-typecheck\n assert copied_res.return_type == res.return_type\n assert qml.equal(copied_res.H, res.H)\n assert copied_res.k == res.k\n assert copied_res.seed == res.seed\n\n def test_shots_none_error(self):\n \"\"\"Test that an error is raised when a device with shots=None is used\n to obtain classical shadows\"\"\"\n circuit = hadamard_circuit(2, None)\n H = qml.PauliZ(0)\n\n msg = \"not accepted for analytic simulation on default.qubit\"\n with pytest.raises(qml.DeviceError, match=msg):\n _ = circuit(H, k=10)\n\n def test_multi_measurement_allowed(self):\n \"\"\"Test that no error is raised when classical shadows is returned\n with other measurement processes\"\"\"\n dev = qml.device(\"default.qubit\", wires=2, shots=10000)\n\n @qml.qnode(dev)\n def circuit():\n qml.Hadamard(wires=0)\n qml.CNOT(wires=[0, 1])\n return qml.shadow_expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(0))\n\n res = circuit()\n assert isinstance(res, tuple)\n assert qml.math.allclose(res, 0, atol=0.05)\n\n def test_obs_not_queued(self):\n \"\"\"Test that the observable passed to qml.shadow_expval is not queued\"\"\"\n with qml.queuing.AnnotatedQueue() as q:\n qml.PauliY(0)\n qml.shadow_expval(qml.PauliZ(0))\n\n tape = qml.tape.QuantumScript.from_queue(q)\n assert len(tape.operations) == 1\n assert tape.operations[0].name == \"PauliY\"\n assert len(tape.measurements) == 1\n assert isinstance(tape.measurements[0], ShadowExpvalMP)\n\n\nobs_hadamard = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n]\nexpected_hadamard = [1, 1, 1, 0, 0, 0, 0]\n\nobs_max_entangled = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliZ(2),\n qml.Identity(1) @ qml.PauliZ(2),\n qml.PauliZ(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliY(2),\n]\nexpected_max_entangled = [0, 0, 0, 0, 1, 0, 0, -1]\n\nobs_qft = [\n qml.PauliX(0),\n qml.PauliX(0) @ qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliZ(2),\n qml.PauliX(1) @ qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliX(2),\n qml.Identity(0) @ qml.PauliY(1) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.PauliY(2),\n qml.PauliY(0) @ qml.PauliX(1) @ qml.PauliX(2),\n]\nexpected_qft = [\n -1,\n 0,\n -1 / np.sqrt(2),\n -1 / np.sqrt(2),\n 0,\n 0,\n 1 / np.sqrt(2),\n 1 / np.sqrt(2),\n -1 / np.sqrt(2),\n 0,\n]\n\n\n@pytest.mark.autograd\nclass TestExpvalForward:\n \"\"\"Test the shadow_expval measurement process forward pass\"\"\"\n\n def test_hadamard_expval(self, k=1, obs=obs_hadamard, expected=expected_hadamard):\n \"\"\"Test that the expval estimation is correct for a uniform\n superposition of qubits\"\"\"\n circuit = hadamard_circuit(3, shots=100000)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_hadamard),)\n assert actual.dtype == np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n def test_max_entangled_expval(\n self, k=1, obs=obs_max_entangled, expected=expected_max_entangled\n ):\n \"\"\"Test that the expval estimation is correct for a maximally\n entangled state\"\"\"\n circuit = max_entangled_circuit(3, shots=100000)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_max_entangled),)\n assert actual.dtype == np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n def test_non_pauli_error(self):\n \"\"\"Test that an error is raised when a non-Pauli observable is passed\"\"\"\n circuit = hadamard_circuit(3)\n\n msg = \"Observable must be a linear combination of Pauli observables\"\n with pytest.raises(ValueError, match=msg):\n circuit(qml.Hadamard(0) @ qml.Hadamard(2))\n\n\n# pylint: disable=too-few-public-methods\n@pytest.mark.all_interfaces\nclass TestExpvalForwardInterfaces:\n @pytest.mark.parametrize(\"interface\", [\"autograd\", \"jax\", \"tf\", \"torch\"])\n def test_qft_expval(self, interface, k=1, obs=obs_qft, expected=expected_qft):\n \"\"\"Test that the expval estimation is correct for a QFT state\"\"\"\n import torch\n\n circuit = qft_circuit(3, shots=100000, interface=interface)\n actual = circuit(obs, k=k)\n\n assert actual.shape == (len(obs_qft),)\n assert actual.dtype == torch.float64 if interface == \"torch\" else np.float64\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n\nobs_strongly_entangled = [\n qml.PauliX(1),\n qml.PauliX(0) @ qml.PauliX(2),\n qml.PauliX(0) @ qml.Identity(1) @ qml.PauliX(2),\n qml.PauliY(2),\n qml.PauliY(1) @ qml.PauliZ(2),\n qml.PauliX(0) @ qml.PauliY(1),\n qml.PauliX(0) @ qml.PauliY(1) @ qml.Identity(2),\n]\n\n\ndef strongly_entangling_circuit(wires, shots=10000, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires, shots=shots)\n\n @qml.qnode(dev, interface=interface)\n def circuit(x, obs, k):\n qml.StronglyEntanglingLayers(weights=x, wires=range(wires))\n return qml.shadow_expval(obs, k=k)\n\n return circuit\n\n\ndef strongly_entangling_circuit_exact(wires, interface=\"autograd\"):\n dev = qml.device(\"default.qubit\", wires=wires)\n\n @qml.qnode(dev, interface=interface)\n def circuit(x, obs):\n qml.StronglyEntanglingLayers(weights=x, wires=range(wires))\n return [qml.expval(o) for o in obs]\n\n return circuit\n\n\nclass TestExpvalBackward:\n \"\"\"Test the shadow_expval measurement process backward pass\"\"\"\n\n @pytest.mark.autograd\n def test_backward_autograd(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the autograd interface\"\"\"\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"autograd\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"autograd\")\n\n def cost_exact(x, obs):\n return autograd.numpy.hstack(exact_circuit(x, obs))\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n actual = qml.jacobian(shadow_circuit)(x, obs, k=1)\n expected = qml.jacobian(cost_exact, argnum=0)(x, obs)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.jax\n def test_backward_jax(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the jax interface\"\"\"\n import jax\n from jax import numpy as jnp\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"jax\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"jax\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = jnp.array(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n )\n\n actual = jax.jacrev(shadow_circuit)(x, obs, k=1)\n expected = jax.jacrev(exact_circuit)(x, obs)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.tf\n def test_backward_tf(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the tensorflow interface\"\"\"\n import tensorflow as tf\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"tf\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"tf\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = tf.Variable(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n )\n )\n\n with tf.GradientTape() as tape:\n out = shadow_circuit(x, obs, k=10)\n\n actual = tape.jacobian(out, x)\n\n with tf.GradientTape() as tape2:\n out2 = qml.math.hstack(exact_circuit(x, obs))\n\n expected = tape2.jacobian(out2, x)\n\n assert qml.math.allclose(actual, expected, atol=1e-1)\n\n @pytest.mark.torch\n def test_backward_torch(self, obs=obs_strongly_entangled):\n \"\"\"Test that the gradient of the expval estimation is correct for\n the pytorch interface\"\"\"\n import torch\n\n shadow_circuit = strongly_entangling_circuit(3, shots=20000, interface=\"torch\")\n exact_circuit = strongly_entangling_circuit_exact(3, \"torch\")\n\n # make rotations close to pi / 2 to ensure gradients are not too small\n x = torch.tensor(\n np.random.uniform(\n 0.8, 2, size=qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=3)\n ),\n requires_grad=True,\n )\n\n actual = torch.autograd.functional.jacobian(lambda x: shadow_circuit(x, obs, k=10), x)\n expected = torch.autograd.functional.jacobian(lambda x: tuple(exact_circuit(x, obs)), x)\n\n assert qml.math.allclose(actual, qml.math.stack(expected), atol=1e-1)\n","repo_name":"PennyLaneAI/pennylane","sub_path":"tests/measurements/test_classical_shadow.py","file_name":"test_classical_shadow.py","file_ext":"py","file_size_in_byte":25628,"program_lang":"python","lang":"en","doc_type":"code","stars":1965,"dataset":"github-code","pt":"52"}
+{"seq_id":"1083737732","text":"#!/usr/bin/env python\n# coding=utf-8\nimport json\n\nfrom sqlalchemy import Column, ForeignKey\nfrom sqlalchemy.dialects.mysql import TINYINT, VARCHAR, INTEGER, TEXT\n\nimport util\nfrom models import BaseModel\n\n\nclass LogTradeMgr(object):\n @staticmethod\n def add(db, **kwargs):\n # We need to hash down the payload if there is one.\n if 'payload' in kwargs and kwargs['payload'] is not None:\n kwargs['payload'] = json.dumps(dict(kwargs.get('payload')))\n\n kwargs[\"inserted_at\"] = util.utcnow()\n log_trade = LogTrade(**kwargs)\n db.add(log_trade)\n db.commit()\n\n\nclass LogTrade(BaseModel):\n __tablename__ = 'log_trade'\n\n id = Column(INTEGER, autoincrement=True, primary_key=True)\n trade_id = Column(VARCHAR(64), nullable=False)\n component = Column(VARCHAR(50), nullable=False)\n payload = Column(TEXT)\n inserted_at = Column(INTEGER, nullable=False)","repo_name":"zivsu/alipay","sub_path":"alipay/models/logtrade.py","file_name":"logtrade.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21186823270","text":"\"\"\"\nmlperf inference benchmarking tool\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport argparse\nimport json\nimport logging\nimport os\nimport time\nimport sys\n\nimport tqdm\nimport numpy as np\n\nimport dataset\nimport imagenet\nimport coco\n\nfrom more_itertools import chunked\n\nlogging.basicConfig(level=logging.INFO)\nlog = logging.getLogger(\"main\")\n\nNANO_SEC = 1e9\nMILLI_SEC = 1000\n\n# pylint: disable=missing-docstring\n\n# the datasets we support\nSUPPORTED_DATASETS = {\n \"imagenet\": (\n imagenet.Imagenet,\n dataset.pre_process_vgg,\n dataset.PostProcessCommon(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"imagenet_mobilenet\": (\n imagenet.Imagenet,\n dataset.pre_process_mobilenet,\n dataset.PostProcessArgMax(offset=-1),\n {\"image_size\": [224, 224, 3]},\n ),\n \"imagenet_pytorch\": (\n imagenet.Imagenet,\n dataset.pre_process_imagenet_pytorch,\n dataset.PostProcessArgMax(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"coco-300\": (\n coco.Coco,\n dataset.pre_process_coco_mobilenet,\n coco.PostProcessCoco(),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-300-pt\": (\n coco.Coco,\n dataset.pre_process_coco_pt_mobilenet,\n coco.PostProcessCocoPt(False, 0.3),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-1200\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCoco(),\n {\"image_size\": [1200, 1200, 3]},\n ),\n \"coco-1200-onnx\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoPt(True, 0.05),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": True},\n ),\n \"coco-1200-pt\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoPt(True, 0.05),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": True},\n ),\n \"coco-1200-tf\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoTf(),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": False},\n ),\n #\n # furiosa golden pre/post-process\n #\n \"imagenet-golden\": (\n imagenet.Imagenet,\n dataset.pre_process_vgg,\n dataset.PostProcessArgMax(offset=0),\n {\"image_size\": [224, 224, 3]},\n ),\n \"coco-300-golden\": (\n coco.Coco,\n dataset.pre_process_coco_pt_mobilenet,\n coco.PostProcessCocoSSDMobileNetORT(False, 0.3),\n {\"image_size\": [300, 300, 3]},\n ),\n \"coco-1200-golden\": (\n coco.Coco,\n dataset.pre_process_coco_resnet34,\n coco.PostProcessCocoONNXNP(),\n {\"image_size\": [1200, 1200, 3], \"use_label_map\": False},\n ),\n}\n# pre-defined command line options so simplify things. They are used as defaults and can be\n# overwritten from command line\n\nSUPPORTED_PROFILES = {\n \"defaults\": {\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"cache\": 0,\n \"max-batchsize\": 32,\n },\n # resnet\n \"resnet50-tf\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"ArgMax:0\",\n \"dataset\": \"imagenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"resnet50\",\n },\n \"resnet50-onnxruntime\": {\n \"dataset\": \"imagenet\",\n \"outputs\": \"ArgMax:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"resnet50\",\n },\n # mobilenet\n \"mobilenet-tf\": {\n \"inputs\": \"input:0\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"dataset\": \"imagenet_mobilenet\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"mobilenet\",\n },\n \"mobilenet-onnxruntime\": {\n \"dataset\": \"imagenet_mobilenet\",\n \"outputs\": \"MobilenetV1/Predictions/Reshape_1:0\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"mobilenet\",\n },\n # ssd-mobilenet\n \"ssd-mobilenet-tf\": {\n \"inputs\": \"image_tensor:0\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"dataset\": \"coco-300\",\n \"backend\": \"tensorflow\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-300-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-mobilenet-onnxruntime\": {\n \"dataset\": \"coco-300\",\n \"outputs\": \"num_detections:0,detection_boxes:0,detection_scores:0,detection_classes:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NHWC\",\n \"model-name\": \"ssd-mobilenet\",\n },\n # ssd-resnet34\n \"ssd-resnet34-tf\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"dataset\": \"coco-1200-tf\",\n \"backend\": \"tensorflow\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-pytorch\": {\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"dataset\": \"coco-1200-pt\",\n \"backend\": \"pytorch-native\",\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime\": {\n \"dataset\": \"coco-1200-onnx\",\n \"inputs\": \"image\",\n \"outputs\": \"bboxes,labels,scores\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"max-batchsize\": 1,\n \"model-name\": \"ssd-resnet34\",\n },\n \"ssd-resnet34-onnxruntime-tf\": {\n \"dataset\": \"coco-1200-tf\",\n \"inputs\": \"image:0\",\n \"outputs\": \"detection_bboxes:0,detection_classes:0,detection_scores:0\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n #\n # furiosa golden model setting\n #\n \"ssd-resnet-golden\": {\n \"dataset\": \"imagenet-golden\",\n \"backend\": \"onnxruntime\",\n \"model-name\": \"resnet50\",\n },\n \"ssd-mobilenet-golden\": {\n \"dataset\": \"coco-300-golden\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-resnet34-golden\": {\n \"dataset\": \"coco-1200-golden\",\n \"backend\": \"onnxruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n #\n # furiosa npu runtime backend setting\n #\n \"resnet-golden-npu-legacy\": {\n \"inputs\": \"input_tensor:0\",\n \"outputs\": \"resnet_model/Squeeze:0_fused_dequantized\",\n \"dataset\": \"imagenet-golden\",\n \"backend\": \"npuruntime\",\n \"model-name\": \"resnet50\",\n },\n \"ssd-mobilenet-golden-npu-legacy\": {\n \"inputs\": \"image\",\n \"outputs\": \"class_logit_0_dequantized,class_logit_1_dequantized,class_logit_2_dequantized,\"\n \"class_logit_3_dequantized,class_logit_4_dequantized,class_logit_5_dequantized,\"\n \"box_regression_0_dequantized,box_regression_1_dequantized,box_regression_2_dequantized,\"\n \"box_regression_3_dequantized,box_regression_4_dequantized,box_regression_5_dequantized,\",\n \"dataset\": \"coco-300-golden\",\n \"backend\": \"npuruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-mobilenet\",\n },\n \"ssd-resnet34-golden-npu-legacy\": {\n \"inputs\": \"image:0\",\n \"outputs\": \"ssd1200/multibox_head/cls_0/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_1/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_2/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_3/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_4/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/cls_5/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_0/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_1/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_2/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_3/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_4/BiasAdd:0_dequantized,\"\n \"ssd1200/multibox_head/loc_5/BiasAdd:0_dequantized\",\n \"dataset\": \"coco-1200-golden\",\n \"backend\": \"npuruntime\",\n \"data-format\": \"NCHW\",\n \"model-name\": \"ssd-resnet34\",\n },\n}\n\nlast_timeing = []\n\n\ndef get_args():\n \"\"\"Parse commandline.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--dataset\", choices=SUPPORTED_DATASETS.keys(), help=\"dataset\")\n parser.add_argument(\"--dataset-path\", required=True, help=\"path to the dataset\")\n parser.add_argument(\"--dataset-list\", help=\"path to the dataset list\")\n parser.add_argument(\"--data-format\", choices=[\"NCHW\", \"NHWC\"], help=\"data format\")\n parser.add_argument(\"--profile\", choices=SUPPORTED_PROFILES.keys(), help=\"standard profiles\")\n parser.add_argument(\n \"-b\", \"--max-batchsize\", default=1, type=int, help=\"max batch size in a single inference\"\n )\n parser.add_argument(\"--model\", required=True, help=\"model file\")\n parser.add_argument(\"--output\", default=\"eval_result\", help=\"test results\")\n parser.add_argument(\"--inputs\", help=\"model inputs\")\n parser.add_argument(\"--outputs\", help=\"model outputs\")\n parser.add_argument(\"--backend\", help=\"runtime to use\")\n parser.add_argument(\"--model-name\", help=\"name of the mlperf model, ie. resnet50\")\n parser.add_argument(\"--threads\", default=os.cpu_count(), type=int, help=\"threads\")\n parser.add_argument(\"--qps\", type=int, help=\"target qps\")\n parser.add_argument(\"--cache\", type=int, default=0, help=\"use cache\")\n parser.add_argument(\n \"--cache_dir\", type=str, default=None, help=\"path to save preprocessed dataset\"\n )\n parser.add_argument(\n \"--accuracy\", default=True, action=\"store_true\", help=\"enable accuracy pass\"\n )\n parser.add_argument(\n \"--find-peak-performance\", action=\"store_true\", help=\"enable finding peak performance pass\"\n )\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"debug, turn traces on\")\n\n # file to use mlperf rules compliant parameters\n parser.add_argument(\"--mlperf_conf\", default=\"../../mlperf.conf\", help=\"mlperf rules config\")\n # file for user LoadGen settings such as target QPS\n parser.add_argument(\n \"--user_conf\",\n default=\"user.conf\",\n help=\"user config for user LoadGen settings such as target QPS\",\n )\n\n # below will override mlperf rules compliant settings - don't use for official submission\n parser.add_argument(\"--time\", type=int, help=\"time to scan in seconds\")\n parser.add_argument(\"-n\", \"--count\", type=int, help=\"dataset items to use\")\n parser.add_argument(\"--max-latency\", type=float, help=\"mlperf max latency in pct tile\")\n parser.add_argument(\n \"--samples-per-query\", type=int, help=\"mlperf multi-stream sample per query\"\n )\n args = parser.parse_args()\n\n # don't use defaults in argparser. Instead we default to a dict, override that with a profile\n # and take this as default unless command line give\n defaults = SUPPORTED_PROFILES[\"defaults\"]\n\n if args.profile:\n profile = SUPPORTED_PROFILES[args.profile]\n defaults.update(profile)\n for k, v in defaults.items():\n kc = k.replace(\"-\", \"_\")\n if getattr(args, kc) is None:\n setattr(args, kc, v)\n if args.inputs:\n args.inputs = args.inputs.split(\",\")\n if args.outputs:\n args.outputs = args.outputs.split(\",\")\n\n return args\n\n\ndef get_backend(backend):\n if backend == \"tensorflow\":\n from backend_tf import BackendTensorflow\n\n backend = BackendTensorflow()\n elif backend == \"onnxruntime\":\n from backend_onnxruntime import BackendOnnxruntime\n\n backend = BackendOnnxruntime()\n elif backend == \"null\":\n from backend_null import BackendNull\n\n backend = BackendNull()\n elif backend == \"pytorch\":\n from backend_pytorch import BackendPytorch\n\n backend = BackendPytorch()\n elif backend == \"pytorch-native\":\n from backend_pytorch_native import BackendPytorchNative\n\n backend = BackendPytorchNative()\n elif backend == \"tflite\":\n from backend_tflite import BackendTflite\n\n backend = BackendTflite()\n elif backend == \"npuruntime\":\n from backend_npuruntime import BackendNPURuntime\n\n backend = BackendNPURuntime()\n else:\n raise ValueError(\"unknown backend: \" + backend)\n return backend\n\n\nclass Item:\n \"\"\"An item that we queue for processing by the thread pool.\"\"\"\n\n def __init__(self, query_id, content_id, img, label=None):\n self.query_id = query_id\n self.content_id = content_id\n self.img = img\n self.label = label\n self.start = time.time()\n\n\nclass RunnerBase:\n def __init__(self, model, ds, threads, post_proc=None, max_batchsize=128):\n self.take_accuracy = False\n self.ds = ds\n self.model = model\n self.post_process = post_proc\n self.threads = threads\n self.take_accuracy = False\n self.max_batchsize = max_batchsize\n self.result_timing = []\n\n def handle_tasks(self, tasks_queue):\n pass\n\n def start_run(self, result_dict, take_accuracy):\n self.result_dict = result_dict\n self.result_timing = []\n self.take_accuracy = take_accuracy\n self.post_process.start()\n\n def run_one_item(self, qitem):\n # run the prediction\n try:\n results = self.model.predict({self.model.inputs[0]: qitem.img})\n processed_results = self.post_process(\n results, qitem.content_id, qitem.label, self.result_dict\n )\n if self.take_accuracy:\n self.post_process.add_results(processed_results)\n self.result_timing.append(time.time() - qitem.start)\n except Exception as ex: # pylint: disable=broad-except\n src = [self.ds.get_item_loc(i) for i in qitem.content_id]\n log.error(\"thread: failed on contentid=%s, %s\", src, ex)\n sys.exit(1)\n\n def enqueue(self, query_samples, pbar):\n query_id = idx = list(query_samples.keys())\n\n if len(query_samples) < self.max_batchsize:\n data, label = self.ds.get_samples(idx)\n self.run_one_item(Item(query_id, idx, data, label))\n pbar.update(len(query_samples))\n else:\n bs = self.max_batchsize\n for i in range(0, len(idx), bs):\n data, label = self.ds.get_samples(idx[i : i + bs])\n self.run_one_item(Item(query_id[i : i + bs], idx[i : i + bs], data, label))\n pbar.update(bs)\n\n def finish(self):\n pass\n\n\ndef add_results(final_results, name, count, result_dict, result_list, took, show_accuracy=False):\n percentiles = [50.0, 80.0, 90.0, 95.0, 99.0, 99.9]\n buckets = np.percentile(result_list, percentiles).tolist()\n buckets_str = \",\".join([\"{}:{:.4f}\".format(p, b) for p, b in zip(percentiles, buckets)])\n\n if result_dict[\"total\"] == 0:\n result_dict[\"total\"] = len(result_list)\n\n # this is what we record for each run\n result = {\n \"took\": took,\n \"mean\": np.mean(result_list),\n \"percentiles\": {str(k): v for k, v in zip(percentiles, buckets)},\n \"qps\": len(result_list) / took,\n \"count\": count,\n \"good_items\": result_dict[\"good\"],\n \"total_items\": result_dict[\"total\"],\n }\n acc_str = \"\"\n if show_accuracy:\n result[\"accuracy\"] = 100.0 * result_dict[\"good\"] / result_dict[\"total\"]\n acc_str = \", acc={:.3f}%\".format(result[\"accuracy\"])\n if \"mAP\" in result_dict:\n result[\"mAP\"] = 100.0 * result_dict[\"mAP\"]\n acc_str += \", mAP={:.3f}%\".format(result[\"mAP\"])\n\n # add the result to the result dict\n final_results[name] = result\n\n # to stdout\n print(\n \"{} qps={:.2f}, mean={:.4f}, time={:.3f}{}, queries={}, tiles={}\".format(\n name, result[\"qps\"], result[\"mean\"], took, acc_str, len(result_list), buckets_str\n )\n )\n\n\ndef main():\n global last_timeing\n args = get_args()\n\n log.info(args)\n\n # find backend\n backend = get_backend(args.backend)\n\n # override image format if given\n image_format = args.data_format if args.data_format else backend.image_format()\n\n # --count applies to accuracy mode only and can be used to limit the number of images\n # for testing. For perf model we always limit count to 200.\n count_override = False\n count = args.count\n\n # dataset to use\n wanted_dataset, pre_proc, post_proc, kwargs = SUPPORTED_DATASETS[args.dataset]\n ds = wanted_dataset(\n data_path=os.path.abspath(args.dataset_path),\n image_list=args.dataset_list,\n name=args.dataset,\n image_format=image_format,\n pre_process=pre_proc,\n use_cache=args.cache,\n cache_dir=args.cache_dir,\n count=count,\n **kwargs,\n )\n # load model to backend\n model = backend.load(args.model, inputs=args.inputs, outputs=args.outputs)\n final_results = {\n \"runtime\": model.name(),\n \"version\": model.version(),\n \"time\": int(time.time()),\n \"cmdline\": str(args),\n }\n\n if args.output:\n output_dir = os.path.abspath(args.output)\n os.makedirs(output_dir, exist_ok=True)\n os.chdir(output_dir)\n\n #\n # make one pass over the dataset to validate accuracy\n #\n count = ds.get_item_count()\n\n # warmup\n ds.load_query_samples([0])\n for _ in range(5):\n img, _ = ds.get_samples([0])\n _ = backend.predict({backend.inputs[0]: img})\n ds.unload_query_samples(None)\n\n scenario = \"model evaluation\"\n log.info(\"starting {}\".format(scenario))\n runner = RunnerBase(\n model, ds, args.threads, post_proc=post_proc, max_batchsize=args.max_batchsize\n )\n result_dict = {\"good\": 0, \"total\": 0}\n runner.start_run(result_dict, args.accuracy)\n\n with tqdm.tqdm(total=count, unit=\"image\") as pbar:\n for chunk in chunked(range(count), 1000):\n ds.load_query_samples(chunk)\n runner.enqueue(ds.image_list_inmemory, pbar)\n ds.unload_query_samples(None)\n\n last_timeing = runner.result_timing\n post_proc.finalize(result_dict, ds, output_dir=args.output)\n\n add_results(\n final_results,\n scenario,\n count,\n result_dict,\n last_timeing,\n time.time() - ds.last_loaded,\n args.accuracy,\n )\n\n runner.finish()\n\n #\n # write final results\n #\n file_name = os.path.basename(args.model).split(\".onnx\")[0]\n if args.output:\n with open(f\"{file_name}_n={count}.json\", \"w\") as f:\n json.dump(final_results, f, sort_keys=True, indent=4)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mlcommons/inference_results_v2.0","sub_path":"closed/FuriosaAI/code/quantization/mlperf_evaluation/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":18681,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"}
+{"seq_id":"17729046250","text":"#!/usr/bin/env python3\n\nimport os, sys, socket, socketutil\nimport random\n\nserver_host = None\nserver_port = 9000\n\nif len(sys.argv) < 4:\n print(\"usage:\")\n print(\" %s count size server_host [server_port]\" % (sys.argv[0]))\n exit()\n\ncount = int(sys.argv[1])\nsize = int(sys.argv[2])\nserver_host = sys.argv[3]\nif len(sys.argv) > 4:\n server_port = int(sys.argv[4])\nserver_addr = (server_host, server_port)\n\nprint(\"Sending %d messages of %d bytes each to server at %s:%d\" % (count, size, server_host, server_port))\n\nc = socketutil.socket(socket.AF_INET, socket.SOCK_STREAM)\nc.connect(server_addr)\n\nc.sendall(\"count:\" + str(count) + \"\\n\")\nc.sendall(\"size:\" + str(size) + \"\\n\")\n\nbuf = bytearray(random.getrandbits(8) for i in range(size))\n\nfor i in range(count):\n # send exactly size bytes of random data\n c.sendall(buf)\n # wait for a 1-byte reply\n reply = c.recv_exactly(1)\n if reply != b\"a\":\n break\n# server will send us a total count of all data received\ntotal = int(c.recv_line())\nc.close()\nprint(\"Done! Server got %d bytes total\" % (total))\n","repo_name":"kevinawalsh/csci356-p3-template","sub_path":"perf_client.py","file_name":"perf_client.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30504100946","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('udp_server')\nimport rospy\nfrom std_msgs.msg import Float32\nimport socket\nimport math\n\ndef talker():\n linear_pub = rospy.Publisher('/youbot_client/platform_vel_cmd/linear', Float32)\n angular_pub = rospy.Publisher('/youbot_client/platform_vel_cmd/angular', Float32)\n rospy.init_node('udp_server')\n UDP_IP = '0.0.0.0'\n UDP_PORT = 5555\n\n sock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n sock.bind((UDP_IP, UDP_PORT))\n print('Connected to address %s:%d' % (UDP_IP, UDP_PORT))\n while not rospy.is_shutdown():\n data_str, addr = sock.recvfrom(1024) # buffer size is 1024 bytes\n data = data_str.split(',')\n accx = float(data[2])\n accy = float(data[3])\n accz = float(data[4]) \n ang_turn = math.atan2(accy, accx)\n ang_acc = math.atan2(accz, accx)\n \n if (ang_acc < 0.4 * math.pi and ang_acc > -0.4 * math.pi and\n ang_turn < 0.4 * math.pi and ang_turn > -0.4 * math.pi):\n if ang_turn >= 0.1:\n ang_vel = (ang_turn - 0.1) * 2.0\n elif ang_turn <= -0.1:\n ang_vel = (ang_turn + 0.1) * 2.0\n else:\n ang_vel = 0.0\n \n if ang_acc >= 0.1:\n lin_vel = (ang_acc - 0.1) * 1.0\n elif ang_acc <= -0.1:\n lin_vel = (ang_acc + 0.1) * 1.0\n ang_vel = ang_vel * (-1.0);\n else:\n lin_vel = 0.0\n \n \n else:\n ang_vel = 0.0\n lin_vel = 0.0\n \n rospy.loginfo('angs: %f %f' % (lin_vel, ang_vel))\n linear_pub.publish(Float32(lin_vel))\n angular_pub.publish(Float32(ang_vel))\n #rospy.sleep(1.0)\n\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"DaniSagan/youbot-udp-controller","sub_path":"udp_server/scripts/udp_server_node.py","file_name":"udp_server_node.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73774150885","text":"#\n# For this is how God loved the world:
\n# he gave his only Son, so that everyone
\n# who believes in him may not perish
\n# but may have eternal life.\n# \n# John 3:16\n#\nimport numpy as np\nfrom OpenGL.GL import *\nfrom aRibeiro.window import *\n\nclass GLShader:\n def __init__(self, window:Window):\n self.window = window\n self.program_id = None\n self.v_shader = None\n self.f_shader = None\n \n def __del__(self):\n self.dispose()\n \n def dispose(self):\n if self.program_id == None:\n return\n if self.window.active():\n if glGetIntegerv(GL_CURRENT_PROGRAM) == self.program_id:\n glUseProgram(0)\n glDeleteProgram(self.program_id)\n self.program_id = None\n \n def compile(self, vertex, fragment):\n\n self.v_shader = glCreateShader(GL_VERTEX_SHADER)\n glShaderSource(self.v_shader, [vertex], None)\n glCompileShader(self.v_shader)\n status = glGetShaderiv(self.v_shader, GL_COMPILE_STATUS)\n if status != 1:\n print('VERTEX SHADER ERROR')\n print(glGetShaderInfoLog(self.v_shader).decode())\n raise Exception(\"VERTEX SHADER ERROR\")\n \n self.f_shader = glCreateShader(GL_FRAGMENT_SHADER)\n glShaderSource(self.f_shader, [fragment], None)\n glCompileShader(self.f_shader)\n status = glGetShaderiv(self.f_shader, GL_COMPILE_STATUS)\n if status != 1:\n print('FRAGMENT SHADER ERROR')\n print(glGetShaderInfoLog(self.f_shader).decode())\n raise Exception(\"FRAGMENT SHADER ERROR\")\n\n self.program_id = glCreateProgram()\n glAttachShader(self.program_id, self.v_shader)\n glAttachShader(self.program_id, self.f_shader)\n\n def bindAttribLocation(self, location, attrib_name):\n glBindAttribLocation(self.program_id, location, attrib_name)\n\n def link(self):\n glLinkProgram(self.program_id)\n status = glGetProgramiv(self.program_id, GL_LINK_STATUS)\n if status != 1:\n print('status', status)\n print('SHADER PROGRAM', glGetShaderInfoLog(self.program_id).decode())\n raise Exception(\"SHADER LINK ERROR\")\n\n glDetachShader(self.program_id, self.v_shader)\n glDetachShader(self.program_id, self.f_shader)\n\n glDeleteShader(self.v_shader)\n glDeleteShader(self.f_shader)\n\n self.v_shader = None\n self.f_shader = None\n\n def enable(self):\n glUseProgram(self.program_id)\n \n def disable(self):\n glUseProgram(0)\n\n def getAttribLocation(self, name):\n return glGetAttribLocation(self.program_id, name)\n \n def getUniformLocation(self, name):\n return glGetUniformLocation(self.program_id, name)\n \n\nclass PositionColorShader(GLShader):\n def __init__(self, window:Window):\n super().__init__(window)\n vertex_shader = \"\"\"\n # version 120\n attribute vec4 aPosition;\n attribute vec4 aColor;\n uniform mat4 uMVP;\n varying vec4 color;\n void main() {\n color = aColor;\n gl_Position = uMVP * aPosition;\n }\n \"\"\"\n fragment_shader = \"\"\"\n # version 120\n varying vec4 color;\n void main() {\n gl_FragColor = color;\n }\n \"\"\"\n self.compile(vertex_shader, fragment_shader)\n self.bindAttribLocation(0, \"aPosition\")\n self.bindAttribLocation(1, \"aColor\")\n self.link()\n self.uMVP = self.getUniformLocation(\"uMVP\")\n \n def setMVP_Matrix4x4(self, mvp:np.array):\n #aux = np.reshape(mvp,[16])\n #glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, aux)\n glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, mvp)\n \n\n\nclass TextureShader(GLShader):\n def __init__(self, window:Window):\n super().__init__(window)\n vertex_shader = \"\"\"\n # version 120\n attribute vec4 aPosition;\n attribute vec2 aUV;\n uniform mat4 uMVP;\n varying vec2 uv;\n void main() {\n uv = aUV;\n gl_Position = uMVP * aPosition;\n }\n \"\"\"\n fragment_shader = \"\"\"\n # version 120\n varying vec2 uv;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, uv);\n }\n \"\"\"\n self.compile(vertex_shader, fragment_shader)\n self.bindAttribLocation(0, \"aPosition\")\n self.bindAttribLocation(1, \"aUV\")\n self.link()\n self.uMVP = self.getUniformLocation(\"uMVP\")\n self.uTexture = self.getUniformLocation(\"uTexture\")\n \n def setMVP_Matrix4x4(self, mvp:np.array):\n #aux = np.reshape(mvp,[16])\n #glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, aux)\n glUniformMatrix4fv(self.uMVP, 1, GL_TRUE, mvp)\n def setTexture_SamplerUnit(self, texUnit):\n glUniform1i(self.uTexture, texUnit)\n\n","repo_name":"A-Ribeiro/ARibeiroPythonFramework","sub_path":"aRibeiro/opengl/GLShader.py","file_name":"GLShader.py","file_ext":"py","file_size_in_byte":5034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"8926222824","text":"favorite_lang = {\n 'jen':'python',\n 'sarah':'c',\n 'edward':'ruby',\n 'phil':'python',\n }\nfor name, lang in favorite_lang.items(): # выводим полностью словарь\n print(name.title() + \"s любимый язык программирования - \" +\n lang.title() + \".\")\n\nfor name in favorite_lang.keys(): # выводим только ключи словаря, без значений, на которые ключи указывают\n print(name.title())\n\nfor name in favorite_lang: # аналогична предыдущей записи, цикл по умолчанию перебирает ключи словаря\n print(name.title())\n\n\nfriends = ['phil', 'sarah']\nfor name in favorite_lang.keys():\n print(name.title())\n\n if name in friends:\n print(\" Hi \" + name.title() + \" Я вижу твой любимый язык программирования \" +\n favorite_lang[name].title() + \"!\")\n","repo_name":"alexDNR/Lessons","sub_path":"python_lessons/PythonLessons/DICT/dict_1.py","file_name":"dict_1.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"72896064806","text":"# Title: Generic Clean-Up - Remove value at the end of a targeted meta\n# Description: Get that value outta here!\n# Required data:\n# Parameters: targeted_metadata_name, removeValueAndWhatFollows\n\ndef get_safe_meta_data(meta_data_name):\n\tsafe_meta = ''\n\tmeta_data_value = document.get_meta_data_value(meta_data_name)\n\tif len(meta_data_value) > 0:\n\t\tsafe_meta = meta_data_value[-1]\n\treturn safe_meta\n\ndef removeThisAndWhatFollows(targeted_metadata_name, removeValueAndWhatFollows):\n try:\n targeted_meta = get_safe_meta_data(targeted_metadata_name)\n \n remove_value_position = targeted_meta.find(removeValueAndWhatFollows)\n\n if remove_value_position > -1:\n updated_meta = targeted_meta[0:remove_value_position]\n document.add_meta_data({targeted_metadata_name: updated_meta})\n\n except Exception as e:\n log(str(e), 'Error')\n \nif 'targeted_metadata_name' not in parameters:\n log('targeted_metadata_name has not been specified, please supply a parameter targeted_metadata_name')\n raise Exception('Supply a targeted_metadata_name in the parameters of ext')\nif 'removeValueAndWhatFollows' not in parameters:\n log('removeValueAndWhatFollows has not been specified, please supply a parameter removeValueAndWhatFollows')\n raise Exception('Supply a removeValueAndWhatFollows in the parameters of ext')\n \nremoveThisAndWhatFollows(parameters['targeted_metadata_name'],parameters['removeValueAndWhatFollows'])","repo_name":"coveo-labs/extensions-templates","sub_path":"extensions/GenericCleanUpRemoveValueAtTheEndOfATargetedMeta.py","file_name":"GenericCleanUpRemoveValueAtTheEndOfATargetedMeta.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"42782850737","text":"\"\"\"Restore command\n\nUsage:\n ltarchiver-restore \n\n\"\"\"\n\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport shlex\n\nfrom docopt import docopt\n\nfrom ltarchiver import common\n\nfrom ltarchiver.common import (\n error,\n file_ok,\n recordbook_checksum_file_path,\n recordbook_path,\n recordbook_file_name,\n get_file_checksum,\n get_records,\n recordbook_dir,\n record_of_file,\n)\n\n\ndef run():\n arguments = docopt(__doc__)\n backup_file_path = pathlib.Path(arguments[\"\"]).resolve()\n if pathlib.Path(arguments[\"\"]).is_dir():\n destination_path = (\n pathlib.Path(arguments[\"\"]) / backup_file_path.name\n )\n else:\n destination_path = pathlib.Path(arguments[\"\"])\n restore(backup_file_path, destination_path)\n\n\ndef restore(backup_file_path: pathlib.Path, destination_path: pathlib.Path):\n destination_path = destination_path.resolve()\n if destination_path == backup_file_path:\n common.error(\"Backup and destination are the same.\")\n file_ok(backup_file_path)\n print(\n f\"This program will check if there are any errors on the file {backup_file_path} and try to restore them if\"\n f\" necessary.\\nDestination: {destination_path}\"\n )\n if not common.DEBUG:\n input(\"Press ENTER to continue. Press Ctrl+C to abort.\")\n file_ok(recordbook_checksum_file_path)\n local_record_is_valid = (\n subprocess.call(shlex.split(f\"md5sum -c {recordbook_checksum_file_path}\")) == 0\n )\n dest_uuid, dest_root = common.get_device_uuid_and_root_from_path(backup_file_path)\n metadata_dir = (\n backup_file_path.parent / common.METADATA_DIR_NAME\n if common.DEBUG\n else dest_root / common.METADATA_DIR_NAME\n )\n backup_checksum_file = metadata_dir / \"checksum.txt\"\n\n backup_record_is_valid = False\n if backup_checksum_file.is_file() and os.access(backup_checksum_file, os.R_OK):\n backup_record_is_valid = (\n subprocess.call(shlex.split(f\"md5sum -c {backup_checksum_file}\")) == 0\n )\n backup_file_checksum = get_file_checksum(backup_file_path)\n # check if file is in either record\n local_record = record_of_file(\n recordbook_path, backup_file_checksum, backup_file_path\n )\n record_in_local = local_record is not None\n recordbook_backup_path = metadata_dir / recordbook_file_name\n backup_record = record_of_file(\n recordbook_backup_path, backup_file_checksum, backup_file_path\n )\n record_in_backup = backup_record is not None\n\n if record_in_local:\n if local_record_is_valid:\n record = local_record\n if not record_in_backup:\n try_copy_recordbook(recordbook_path, recordbook_backup_path)\n else:\n pass # Nothing to do since backup already has a copy of the record\n else:\n if record_in_backup:\n if backup_record_is_valid:\n record = backup_record\n try_copy_recordbook(recordbook_backup_path, recordbook_path)\n else:\n input(\n \"The file was found in both recordbooks but they (the recordbooks) don't match their checksums. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n input(\n \"The file was found only in the local recordbook but its checksum doesn't match. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n if record_in_backup:\n if backup_record_is_valid:\n record = backup_record\n try_copy_recordbook(recordbook_backup_path, recordbook_path)\n else:\n input(\n \"The file was only found in the backup recordbook but it doesn't match the checksum. Press CTR+C to\"\n \" abort or Enter to try continuing with the restoration.\"\n )\n else:\n error(\n f\"Neither {backup_file_path.name} or its checksum was found in the recordbooks\"\n )\n\n backup_md5 = get_file_checksum(backup_file_path)\n original_ecc_file_path = (metadata_dir / \"ecc\") / record.checksum\n original_ecc_checksum = get_file_checksum(original_ecc_file_path)\n if backup_md5 == record.checksum and original_ecc_checksum == record.ecc_checksum:\n print(\"No errors detected on the file. Beginning copy.\")\n shutil.copyfile(backup_file_path, destination_path)\n print(\"File was successfully copied. Goodbye.\")\n exit(0)\n elif backup_md5 == record.checksum and original_ecc_checksum != record.ecc_checksum:\n print(\n \"Only the ecc differs from what's stored in the recordbook. The fastest way to go is to call the restore\"\n \" routine on this file again.\"\n )\n exit(1)\n else:\n print(\n \"Checksum doesn't match. Attempting to restore the file onto destination.\"\n )\n new_ecc_file_path = recordbook_dir / \"temp_ecc.bin\"\n subprocess.check_call(\n [\n \"c-ltarchiver/out/ltarchiver_restore\",\n str(backup_file_path),\n str(destination_path),\n str(original_ecc_file_path),\n str(new_ecc_file_path),\n ]\n )\n print(\"Checking if the restoration succeeded...\")\n new_ecc_checksum = get_file_checksum(new_ecc_file_path)\n destination_checksum = get_file_checksum(destination_path)\n failed = False\n if new_ecc_checksum != record.ecc_checksum:\n print(\"The restored ECC doesn't match what was expected.\")\n failed = True\n if destination_checksum != record.checksum:\n print(\"The file doesn't match what was expected.\")\n failed = True\n if failed:\n print(\n \"Sorry! Failed to restore the requested file. You are on your own now.\"\n )\n exit(1)\n else:\n subprocess.check_call([\"cp\", new_ecc_file_path, original_ecc_file_path])\n os.remove(new_ecc_file_path)\n print(\"Restoration successful!\")\n exit(0)\n\n\ndef try_copy_recordbook(source, destination):\n destination_records = get_records(destination)\n source_records = get_records(source)\n destination_checksums = {record.checksum for record in destination_records}\n source_checksums = {record.checksum for record in source_records}\n destination_filename = {record.file_name for record in destination_records}\n source_filename = {record.file_name for record in source_records}\n has_more = False\n if destination_checksums - source_checksums:\n print(f\"{destination} has checksums that {source} doesn't\")\n has_more = True\n if destination_filename - source_filename:\n print(f\"{destination} has files that {source} doesn't\")\n has_more = True\n if has_more:\n while True:\n answer = input(\n f\"Do you want to overwrite {destination} with the contents of {source} (yes/no/abort)?\"\n ).lower()\n if answer == \"yes\":\n shutil.copy(source, destination)\n return\n elif answer == \"no\":\n return\n elif answer == \"abort\":\n exit(1)\n else:\n pass\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"marceloslacerda/ltarchiver","sub_path":"ltarchiver/check_and_restore.py","file_name":"check_and_restore.py","file_ext":"py","file_size_in_byte":7578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"290631577","text":"#!/usr/bin/python\n\nfrom ConfigParser import ConfigParser\nfrom argparse import ArgumentParser\nfrom flask import request, Flask\nfrom flask.ext.cache import Cache\nfrom operator import itemgetter\nfrom redis import Redis\nimport json\nimport os\nimport re\nimport sys\n\napp = Flask(__name__)\n\napp.config['CACHE_TYPE'] = 'simple'\napp.cache = Cache(app)\n\n# Read a configuration file\nconf_parser = ArgumentParser(add_help = False)\nconf_parser.add_argument(\n \"--conf\",\n help=\"Alternative Config File Location\",\n metavar=\"FILE\"\n)\n\n# Get the path to the root directory of the repo\nrootdir = os.path.realpath(os.path.join(os.path.dirname(sys.argv[0]), '..'))\n\nargs, args_rest = conf_parser.parse_known_args()\nconfig = ConfigParser()\nconfig.readfp(open(args.conf or '%s/config/hashtag_counter.cfg' % rootdir))\n\n# Get the default config values\ndefaults = {}\nfor section in config.sections():\n defaults = dict(defaults.items() + config.items(section))\n\nparser = ArgumentParser(parents=[conf_parser])\nparser.set_defaults(**defaults)\n\nargs = parser.parse_args(args_rest)\n\n\n\"\"\"\n############### ROUTES ###############\n\"\"\"\n# Get a count of hashtags from tweets that include\n# the word represented by the variable `tweet_filter`\n@app.route(\"/count/\", methods=[\"GET\"])\n@app.route(\"/count//\", methods=[\"GET\"])\n@app.cache.cached(timeout=10)\ndef count(tweet_filter, num_results=100):\n redis = Redis(\n host = args.redis_host,\n port = int(args.redis_port),\n db = 0\n )\n\n keys = redis.keys(\"%s:*\" % tweet_filter)\n values = redis.mget(keys)\n regex = re.compile(r':(.+)$')\n response = []\n\n # Check if \"num_results\" param exists and check if\n # the keys are less than num_results\n length = len(keys)\n\n for i in range(0, length):\n key = keys[i]\n value = values[i]\n\n match = re.search(regex, key)\n response.append(\n {\n 'hashtag' : match.group(1),\n 'count' : int(value)\n }\n )\n\n response = sorted(\n response,\n key = itemgetter('count'),\n reverse = True\n )\n\n # Trim the response appropriately\n num_results = int(num_results)\n if (length > num_results): length = num_results\n\n response = response[:length]\n\n return json.dumps(response)\n\n# Flush Redis stats by tweet filter\n@app.route(\"/reset/\", methods=[\"DELETE\"])\ndef reset(tweet_filter):\n redis = Redis(\n host = args.redis_host,\n port = int(args.redis_port),\n db = 0\n )\n\n if (not tweet_filter):\n return json.dumps(\n {\n 'response' : 'error',\n 'reason' : 'No tweet filter',\n }\n )\n\n keys = redis.keys(\"%s:*\" % tweet_filter)\n count = len(keys)\n\n redis.delete(*keys)\n\n return json.dumps(\n {\n 'response' : 'ok',\n 'debug' : 'Deleted %s keys' % count,\n }\n )\n\nif __name__ == '__main__':\n app.run(\n debug = True,\n host = args.api_host,\n port = int(args.api_port)\n )\n","repo_name":"davarisg/twitter-hashtag-count","sub_path":"api/hashtag_count_api.py","file_name":"hashtag_count_api.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"10410930745","text":"# -*- coding: utf-8 -*-\n# This file is licensed under the terms of the MIT License. See the LICENSE\n# file in the root of this repository for complete details.\n\nimport os\nimport sys\nimport tests\nimport click\nimport pytest\n\nfrom jotquote import api\n\nmy_args = ()\ndef test__write_quotes__should_write_to_temp_filename(monkeypatch, tmp_path):\n # Given a quote file with a few quotes in it\n quotefile = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quotefile)\n\n # And given the open_file() function wrapped with function that tracks args\n original_open_file = click.open_file\n def mock_open_file(*args, **kwargs):\n global my_args\n my_args = args\n return original_open_file(*args, **kwargs)\n monkeypatch.setattr(click, \"open_file\", mock_open_file)\n\n # When write_quotes() called\n api.write_quotes(quotefile, quotes)\n\n # Then check open_file() called with temporary filename\n assert my_args[0] != quotefile\n\n\ndef test__write_quotes__should_create_backup_file(tmp_path):\n # Given a quote file with a few quotes in it\n quotefile = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quotefile)\n\n # When write_quotes() called\n api.write_quotes(quotefile, quotes)\n\n # Then check open_file() called with temporary filename\n assert os.path.exists(os.path.join(str(tmp_path), '.quotes1.txt.jotquote.bak'))\n\n\ndef test__write_quotes__should_replace_backup_file(tmp_path):\n # Given a quote file with a few quotes in it\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quote_path)\n quote_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes2 = api.read_quotes(quote_path_2)\n\n # When write_quotes() called twice\n api.write_quotes(quote_path, quotes2)\n api.write_quotes(quote_path, quotes)\n\n # Then backup file has quotes2 content\n backup_quotes = api.read_quotes(os.path.join(str(tmp_path), '.quotes1.txt.jotquote.bak'))\n assert len(backup_quotes) == len(quotes2)\n assert backup_quotes[0] == quotes2[0]\n\n\ndef test__write_quotes__should_not_modify_quote_file_on_write_error(monkeypatch, tmp_path):\n # Given two quote files with a few quotes in each\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n quotes = api.read_quotes(quote_path)\n quote_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes2.txt\")\n quotes2 = api.read_quotes(quote_path_2)\n\n # And given fake writer\n class FakeWriter:\n def __init__(self, path):\n with open(path, 'w') as file:\n file.write('bad contents')\n\n def __enter__(self):\n return self\n\n def __exit__(self, arg1, arg2, arg3):\n pass\n\n def write(self, bytes):\n raise IOError(\"Fake write error\")\n\n # And given the open_file() function wrapped with function that tracks args\n def fake_open_file(*args, **kwargs):\n return FakeWriter(args[0])\n original_open_file = click.open_file\n monkeypatch.setattr(click, \"open_file\", fake_open_file)\n\n # When write_quotes() called\n with pytest.raises(click.ClickException) as excinfo:\n api.write_quotes(quote_path, quotes2)\n\n # Then check quote_path was not modified\n monkeypatch.setattr(click, \"open_file\", original_open_file)\n assert \"an error occurred writing the quotes. The file '{0}' was not modified.\".format(quote_path) == str(excinfo.value)\n assert tests.test_util.compare_quotes(quotes, api.read_quotes(quote_path))\n\n\ndef test__write_quotes__should_return_good_exception_when_backup_larger_than_quote_file(monkeypatch, tmp_path):\n # Given a quote file quotes5.txt with a single quote in it\n quote_path = tests.test_util.init_quotefile(str(tmp_path), \"quotes5.txt\")\n quotes = api.read_quotes(quote_path)\n\n # And given a backup file .quotes5.txt.jotquote.bak with 4 quotes in it\n quotes_path_2 = tests.test_util.init_quotefile(str(tmp_path), \"quotes1.txt\")\n backup_path = os.path.join(str(tmp_path), '.quotes5.txt.jotquote.bak')\n os.rename(quotes_path_2, backup_path)\n\n # When write_quotes() called to write quotes to quotes5.txt\n with pytest.raises(click.ClickException) as excinfo:\n api.write_quotes(quote_path, quotes)\n\n # Then an error message returned indicating backup file larger than new quotes5.txt\n assert \"the backup file '.quotes5.txt.jotquote.bak' is larger than the quote file 'quotes5.txt' would be after this operation. This is suspicious, the quote file was not modified. If this was expected, delete the backup file and try again.\" == str(excinfo.value)\n assert tests.test_util.compare_quotes(quotes, api.read_quotes(quote_path))\n\n\n@pytest.mark.parametrize(\"raw_quote, expected_quote, expected_author, expected_publication\",\n [\n (\"This is a quote. - Author\",\n \"This is a quote.\",\n \"Author\",\n None),\n (\"This is-a quote. - Author\",\n \"This is-a quote.\",\n \"Author\",\n None),\n (\"This is a quote. - Author-name\",\n \"This is a quote.\",\n \"Author-name\",\n None),\n (\"This is a quote.-Author\",\n \"This is a quote.\",\n \"Author\",\n None),\n (\"This is a quote with alternative-punctuation! - Author\",\n \"This is a quote with alternative-punctuation!\",\n \"Author\",\n None),\n (\"This is a quote. - Author(My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author (My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author,(My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author, (My Publication)\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication\"),\n (\"This is a quote. - Author,'My Publication-name'\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication-name\"),\n (\"This is a quote. - Author, 'My Publication-name'\",\n \"This is a quote.\",\n \"Author\",\n \"My Publication-name\"),\n (\"This is a quote. - Author, Publication\",\n \"This is a quote.\",\n \"Author\",\n \"Publication\")])\ndef test__parse_quote_simple__should_parse_out_author_and_publication(raw_quote, expected_quote, expected_author, expected_publication):\n quote, author, publication, tags = api._parse_quote_simple(raw_quote)\n\n assert quote == expected_quote\n assert author == expected_author\n assert publication == expected_publication\n assert tags == []\n\n\n@pytest.mark.parametrize(\"raw_quote, error_message\",\n [\n (\"This is a quote. - Author name (publication name) more stuff\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\"),\n (\"This is-a quote. - Author name, publication name, more stuff\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\"),\n (\"This-is-a quote-Author-name\", \"unable to determine which hyphen separates the quote from the author.\"),\n (\"This - is a quote - Author\", \"unable to determine which hyphen separates the quote from the author.\"),\n (\"This is a quote. - Author 'The-Rock' Last Name\", \"unable to parse the author and publication. Try 'Quote - Author (Publication)', or 'Quote - Author, Publication'\")])\ndef test__parse_quote_simple__should_raise_exception_if_not_parseable(raw_quote, error_message):\n try:\n quote, author, publication, tags = api._parse_quote_simple(raw_quote)\n pytest.fail('An exception was expected')\n except click.ClickException as exception:\n assert str(exception) == error_message\n","repo_name":"jakekugel/jotquote","sub_path":"tests/api_pytest_test.py","file_name":"api_pytest_test.py","file_ext":"py","file_size_in_byte":8129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"42445761459","text":"from sys import platform as sys_pf\nif sys_pf == 'darwin':\n import matplotlib\n matplotlib.use(\"TkAgg\")\n\nimport unittest\n\nimport numpy.testing as np_test\n\nfrom scripts.algorithms.arima import ARIMAForecast\n\nimport platform; print(platform.platform())\nimport sys; print(\"Python\", sys.version)\nimport os\nimport pandas as pd\nimport numpy as np; print(\"NumPy\", np.__version__)\nimport scipy; print(\"SciPy\", scipy.__version__)\nimport sklearn; print(\"Scikit-Learn\", sklearn.__version__)\nimport statsmodels; print(\"Statsmodels\", statsmodels.__version__)\n\n\nclass ArimaTests(unittest.TestCase):\n\n def test_non_float_sequence(self):\n time_series = [1, 1, 1, 1, 1]\n num_predicted_periods = 3\n\n with self.assertRaises(ValueError) as cm:\n ARIMAForecast(time_series, num_predicted_periods)\n\n self.assertEqual(cm.exception.args[0], 'Time series must be all float values')\n\n def test_static_sequence(self):\n time_series = [1.0, 1.0, 1.0, 1.0, 1.0]\n num_predicted_periods = 3\n expected_prediction = [1] * num_predicted_periods\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=4)\n\n def test_linear_sequence(self):\n time_series = [1.0, 2.0, 3.0, 4.0, 5.0]\n num_predicted_periods = 3\n expected_prediction = [6.0, 7.0, 8.0]\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=4)\n\n def test_flakey_sequence(self):\n time_series = [20.0, -20.0]\n num_predicted_periods = 3\n expected_prediction = [np.nan] * 3\n arima = ARIMAForecast(time_series, num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=1)\n\n def test_linearly_increasing_sequence_fuel_cell(self):\n time_series = pd.read_csv(os.path.join('data', 'fuel_cell_quarterly.csv')).values.tolist()\n time_series = [item for sublist in time_series for item in sublist]\n num_predicted_periods = 4\n expected_prediction = [333., 333., 334., 335.]\n arima = ARIMAForecast(np.array(time_series).astype(float), num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=0)\n\n def test_linearly_decreasing_sequence_image_data(self):\n time_series = pd.read_csv(os.path.join('data', 'image_data_quarterly.csv')).values.tolist()\n time_series = [item for sublist in time_series for item in sublist]\n num_predicted_periods = 4\n expected_prediction = [562., 561., 558., 556.]\n arima = ARIMAForecast(np.array(time_series).astype(float), num_predicted_periods)\n\n actual_prediction = arima.predict_counts()\n\n np_test.assert_almost_equal(actual_prediction, expected_prediction, decimal=0)\n","repo_name":"datasciencecampus/pygrams","sub_path":"tests/algorithms/test_arima.py","file_name":"test_arima.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"52"}
+{"seq_id":"5144854935","text":"import random\nfrom tkinter import *\n\n\n\n#Question 1.1\n\nclass Game:\n\n class Food:\n def __init__(self,game,foodSize,foodColor):\n self.game = game\n self.foodSize = foodSize\n self.foodColor = foodColor\n\n #Init first food\n self.obj = None\n self.newRandCoord()\n self.spawnFood()\n\n def newRandCoord(self):\n self.coord = (random.randint(0,self.game.width),random.randint(0,self.game.height))\n def spawnFood(self):\n self.game.gameCanvas.delete(self.obj)\n (x,y) = self.coord\n (sx,sy)=self.foodSize\n self.obj = self.game.gameCanvas.create_rectangle(x,y,x+sx,y+sy)\n self.game.gameCanvas.itemconfig(self.obj,fill=self.foodColor)\n def __del__(self):\n self.game.gameCanvas.delete(self.obj)\n class BodyPart :\n def __init__(self,coord,gameCanvas,playerSize,index):\n self.index = index\n self.gameCanvas = gameCanvas\n self.playerSize = playerSize\n #SPAWN PART\n (x,y,x2,y2) = coord\n self.obj = gameCanvas.create_rectangle(x,y,x2,y2)\n self.dirQueue = []\n def __del__(self):\n self.gameCanvas.delete(self.obj)\n\n def Enqueue(self,dir):\n #Ne pas dépasser la position de la partie dans la queue\n if(len(self.dirQueue) >= self.index):\n return\n self.dirQueue.append(dir)\n def Move(self,previousCoord):\n (dx,dy) = self.dirQueue.pop(0)\n (sx,sy) = self.playerSize\n (x1,y1,x2,y2) = previousCoord\n (gx,gy) = (dx*sx,sy*dy)\n self.gameCanvas.coords(self.obj,(x1-gx,y1-gy,x2-gx,y2-gy))\n return (dx,dy)\n\n\n def __init__(self,gameDimension,playerSize,foodSize,speed,refreshRate):\n #Assign Var\n self.foodSize = foodSize\n self.speed = speed\n self.dir = (0,0)\n self.playerSize = playerSize\n self.player = None\n self.parts = []\n self.refreshRate = refreshRate\n self.foodColor = 'red'\n\n #Init game windows and canvas\n (tempX,tempY) = gameDimension\n self.width = tempX\n self.height = tempY\n self.gameWindows = Tk()\n self.gameCanvas = Canvas(self.gameWindows,width=self.width,height=self.height)\n self.gameCanvas.pack()\n\n #Init Game\n self.ResetGame()\n\n #Event\n self.gameWindows.after(300,self.Move)\n\n #Bind Key\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n self.gameWindows.bind('',self.ChangeDirection)\n\n self.gameWindows.mainloop()\n\n def ResetGame(self):\n #Remove existant\n if(self.player != None):\n self.gameCanvas.delete(self.player)\n self.parts = []\n # Init Player\n (playerSizeX, playerSizeY) = self.playerSize\n self.player = self.gameCanvas.create_rectangle(self.width // 2, self.height // 2, self.width // 2 + playerSizeX,\n self.height // 2 + playerSizeY)\n\n # Init Food\n self.food = self.Food(self, self.foodSize,self.foodColor)\n def ChangeDirection(self,evt):\n if(evt.char == 'z'):\n self.dir = (0,-1)\n if(evt.char == 's'):\n self.dir = (0,1)\n if(evt.char == 'q'):\n self.dir = (-1,0)\n if(evt.char == 'd'):\n self.dir = (1,0)\n def Move(self):\n (dx,dy) = self.dir\n (x1, y1, x2, y2) = self.gameCanvas.coords(self.player)\n (x3, y3, x4, y4) = (x1 + self.speed * dx, y1 + self.speed * dy,x2 + self.speed * dx, y2 + self.speed * dy)\n self.gameCanvas.coords(self.player, (x3, y3, x4, y4))\n\n #Refresh Body Parts\n self.EnqueueBodyPartFrom((dx,dy))\n\n #Move body part\n #self.MoveBodyPart()\n\n #Try Eat Something\n self.TryEat((x1,y1,x2,y2))\n\n #CheckDeath\n if(self.CheckDeath()):\n self.ResetGame()\n\n self.gameCanvas.after(self.refreshRate,self.Move)\n def EnqueueBodyPartFrom(self, firstDir):\n firstCoord = self.gameCanvas.coords(self.player)\n dirs = [firstDir]\n for i in range(len(self.parts)):\n for dir in dirs:\n self.parts[i].Enqueue(dir)\n if(i==0):\n dirs.append( self.parts[i].Move(firstCoord))\n else:\n dirs.append(self.parts[i].Move(self.gameCanvas.coords(self.parts[i-1].obj)))\n def MoveBodyPart(self):\n for part in self.parts:\n part.Move()\n def TryEat(self,oldPos):\n (sx, sy) = self.playerSize\n if self.CheckDistanceBetweenTwoObj(self.player, self.food.obj,sx):\n self.food = self.Food(self,self.foodSize,self.foodColor)\n\n #ADD NEW BODY PART\n (x1, y1, x2, y2) = oldPos\n part = self.BodyPart((x1,y1,x2,y2),self.gameCanvas,self.playerSize,len(self.parts) +1)\n self.parts.append(part)\n pass\n def CheckDistanceBetweenTwoObj(self,id1,id2,threahold):\n (x, y, x2, y2) = self.gameCanvas.coords(id1)\n (xp1,yp1,xp2,yp2) = self.gameCanvas.coords(id2)\n if abs(((x + x2) / 2) - ((xp1 + xp2) / 2)) < threahold and abs(((y + y2) / 2) - ((yp1 + yp2) / 2)) < threahold:\n return True\n return False\n def CheckDeath(self):\n (x1,y1,x2,y2) = self.gameCanvas.coords(self.player)\n (x,y) = ((x1+x2)//2,(y1+y2)//2)\n if(x > self.width or x<0):\n return True\n if(y > self.height or y<0):\n return True\n for part in self.parts:\n (sx,sy)=self.playerSize\n if self.CheckDistanceBetweenTwoObj(self.player,part.obj,sx/2+0.001):\n return True\n return False\n\n #TOOL\n def getGap(self):\n (dx,dy) = self.dir\n (sx,sy) = self.playerSize\n return (dx*sx,dy*sy)\n\n\ngameInstance = Game((500,300),(7,7),(7,7),6,50)\n","repo_name":"volvicfanboy/cpbxS4","sub_path":"td2.py","file_name":"td2.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10395132380","text":"\"\"\"\n LINKED LIST\n dynamic list with links created automatically with programming approach\n\"\"\"\n\nclass song:\n pass\n\n def __init__(self,name = None,artist = None,duration = None):\n self.name = name\n self.artist = artist\n self.duration = duration\n\n # a self made function to print the song attribute in a better way\n # def show(self):\n # print(\"{name}\\t {artist}\\t {duration}\".format_map(vars(self)))\n\n # a built-in function used to print the song attributes in a better way\n def __str__(self):\n return \"{name}\\t {artist}\\t {duration}\".format_map(vars(self))\n\n\nclass LinkedList:\n\n # A variable made to calculate the size of linked list\n size = 0\n\n\n def __init__(self):\n self.head = None\n self.tail = None\n\n def append(self, object):\n\n # accessing the class attribute 'size' with the class name\n LinkedList.size += 1\n\n if self.head is None:\n\n self.head = object\n self.tail = object\n\n print(\"OBJECT ADDED AS HEAD AND TAIL\")\n\n else:\n self.tail.next = object\n object.previous = self.tail\n self.head.previous = object\n\n self.tail = object\n self.tail.next = self.head\n print(\"OBJECT ADDED AS TAIL\")\n\n\n def iterate_forward(self):\n temporary = self.head\n\n # jab tak yeh sahi h\n while True:\n # print(vars(temporary))\n\n # if using __str__ function, you have to write only variable name need not to access it.\n # it will executed automatically.\n print(temporary)\n\n # accessing show function\n # temporary.show()\n temporary = temporary.next #-> when it comes to temporary = song5.next,it goes to if loop and break bcoz song5.next = self.head\n\n if temporary is self.head:\n break\n\n # a function made to calculate the size of class Linked list\n def length(self):\n return LinkedList.size\n\n\n\ndef main():\n\n # object creation of class song\n song1 = song(\"1 Sach Keh Raha Hai\", \"John\", 4.5)\n song2 = song(\"2 Bimariyan\", \"kim\", 3.5)\n song3 = song(\"3 Permission to dance\", \"fionna\", 5.0)\n song4 = song(\"4 kal ho na ho\", \"jack\", 2.5)\n song5 = song(\"5 baarish\", \"nick\", 4.0)\n\n\n # object creation of class linked list\n play_list = LinkedList()\n print(vars(play_list))\n\n\n # add the object\n play_list.append(song1)\n play_list.append(song2)\n play_list.append(song3)\n play_list.append(song4)\n play_list.append(song5)\n\n print()\n\n # iterating the playlist to print the songs\n play_list.iterate_forward()\n\n print()\n\n # accessing length function to print the length of linked list\n print(\"Length of linked list:\", play_list.length())\n\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","repo_name":"dikshagautam74/DG2021PY","sub_path":"Session13.py","file_name":"Session13.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30790432707","text":"import argparse\nimport pickle\nfrom os import path as osp\nfrom rlkit.core import logger\nfrom rlkit.core.repeat_logger import RepeatLogger, RepeatPlotter\nfrom rlkit.samplers.rollout_functions import multitask_rollout\nfrom rlkit.torch import pytorch_util as ptu\nfrom rlkit.envs.vae_wrapper import VAEWrappedEnv\nimport numpy as np\nimport mujoco_py\nimport pickle as pkl\n\ndef simulate_policy(args):\n # # start a useless environment incase opengl version error\n # mujoco_py.MjViewer(mujoco_py.MjSim(mujoco_py.load_model_from_path(osp.join(osp.dirname(__file__), \"Dummy.xml\"))))\n\n logger.log(\"finish adding dummy context viewer, start loading file\")\n with open(args.file, \"rb\") as f:\n data = pickle.load(open(args.file, \"rb\"))\n policy = data['evaluation/policy']\n env = data['evaluation/env']\n logger.log(\"Policy and environment loaded\")\n if args.redump:\n # re-dump the data\n with open(args.file, \"wb\") as f:\n pickle.dump(data, f)\n logger.log(\"Finish redump\")\n if args.gpu:\n ptu.set_gpu_mode(True)\n policy.to(ptu.device)\n if isinstance(env, VAEWrappedEnv) and hasattr(env, 'mode'):\n env.mode(args.mode)\n if (args.enable_render or hasattr(env, 'enable_render')) and not args.hide:\n # some environments need to be reconfigured for visualization\n logger.log(\"Enable Rendering\")\n env.enable_render()\n if args.log_dir != None:\n # time to setup logger to dump recordings to file\n # It should be safer to use absolute directory\n logger.set_snapshot_dir(osp.abspath(args.log_dir))\n logger.add_tabular_output('rollouts.csv', relative_to_snapshot_dir=True)\n success_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'image_success.csv'))\n vae_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'vae_dist.csv'))\n ag_logger = RepeatLogger(osp.join(osp.abspath(args.log_dir), 'effector2goal_distance.csv'))\n logger.log(\"Setup loggers\")\n if hasattr(env, '_goal_sampling_mode') and env._goal_sampling_mode == 'custom_goal_sampler' and env.custom_goal_sampler == None:\n # This a deep hack, to make the sample directly from env wrapped by image_env\n # ---------------- change to use presampled goal for RIG_door algorithm -------------\n # env.custom_goal_sampler = env._customed_goal_sampling_func\n # logger.log(\"Change env.custom_goal_sampler to its _customed_goal_sampling_func\")\n env._goal_sampling_mode = \"presampled\"\n paths = []\n logger.log(\"Start Rollout\")\n for ite in range(64): # incase the testing takes too much physical memory\n paths.append(multitask_rollout(\n env,\n policy,\n max_path_length=args.H,\n render=not args.hide,\n observation_key=data['evaluation/observation_key'],\n desired_goal_key=data['evaluation/desired_goal_key'],\n ))\n logger.log(\"iter %d: Finish rollout\" % ite)\n if hasattr(env, \"log_diagnostics\"):\n env.log_diagnostics(paths)\n logger.log(\"iter %d: Log diagnostics\" % ite)\n if hasattr(env, \"get_diagnostics\"):\n for k, v in env.get_diagnostics(paths).items():\n logger.record_tabular(k, v)\n logger.log(\"iter %d: Get diagnostics\" % ite)\n if args.log_dir != None:\n # this data has to be chosen by specific path field.\n success_logger.record([paths[-1]['env_infos'][i]['image_success'] for i in range(len(paths[-1]['env_infos']))])\n vae_logger.record([paths[-1]['env_infos'][i]['vae_dist'] for i in range(len(paths[-1]['env_infos']))])\n if \"effector2goal_distance\" in paths[-1]['env_infos'][0].keys():\n goal_dist = [np.linalg.norm(paths[-1]['env_infos'][i]['effector2goal_distance']) for i in range(len(paths[-1]['env_infos']))]\n ag_logger.record(goal_dist)\n with open(args.log_dir + \"2goal_dist.pkl\", \"wb+\") as f:\n pkl.dump(goal_dist, f)\n logger.log(\"iter %d: Log into files\" % ite)\n\n logger.dump_tabular()\n logger.log(\"Rollout done: # %d\" % ite)\n\n logger.log(\"Testing learning result done...\")\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('file', type=str,\n help='path to the snapshot file')\n parser.add_argument('--H', type=int, default=300,\n help='Max length of rollout')\n parser.add_argument('--speedup', type=float, default=10,\n help='Speedup')\n parser.add_argument('--mode', default='video_env', type=str,\n help='env mode')\n parser.add_argument('--gpu', action='store_true')\n parser.add_argument('--enable_render', action='store_true')\n parser.add_argument('--hide', action='store_true')\n parser.add_argument('--log_dir', type=str, default= None,\n help='Specify the log directory, no logging if not')\n parser.add_argument('--redump', action='store_true', default=False,\n help='restore the data if you need to some modification (not recommended)')\n args = parser.parse_args()\n\n simulate_policy(args)\n","repo_name":"ZiwenZhuang/rlkit","sub_path":"scripts/run_goal_conditioned_policy.py","file_name":"run_goal_conditioned_policy.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"5936737053","text":"# Wipe content of files\n\n#with open(\"Filings/wipable.txt\", \"w\") as f:\n# f.write(\"\")\n\n#Renaming files \n\nimport os\n\noldFile = \"wipable.txt\"\nnewName = \"renamed.txt\"\n\nwith open(oldFile) as f:\n content = f.read()\n\nwith open(newName, \"w\") as f:\n f.write(content)\n\nos.remove(oldFile)\n","repo_name":"aliasar1/PythonLearning","sub_path":"Filings/WipeContentOfFileAndRename.py","file_name":"WipeContentOfFileAndRename.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34600989775","text":"import asyncio\nimport logging\nimport os\nimport random\nimport time\nfrom uuid import uuid4\n\nfrom censor import check_message_censorship\nfrom dotenv import load_dotenv\nfrom fastapi import (\n Depends,\n FastAPI,\n HTTPException,\n Request,\n Response,\n WebSocket,\n WebSocketDisconnect,\n)\nfrom fastapi.responses import RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\nfrom models import CensorRequest, Message, UserName\nfrom pydantic import ValidationError\nfrom ws import SocketManager\n\nload_dotenv()\n\nCENSOR_URL = os.getenv(\"CENSOR_URL\")\n\nif not CENSOR_URL:\n raise EnvironmentError(\"CENSOR_URL should be set\")\n\nlogger = logging.getLogger(\"uvicorn\")\napp = FastAPI()\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\nmanager = SocketManager()\n\n\n@app.get(\"/\")\ndef get_home(request: Request):\n return templates.TemplateResponse(\"home.html\", {\"request\": request})\n\n\n@app.get(\"/api/current_user\")\ndef get_user(request: Request):\n return request.cookies.get(\"X-Authorization\")\n\n\n@app.get(\"/chat\")\ndef get_chat(request: Request, login: str = Depends(get_user)):\n if not login:\n return RedirectResponse(url=\"/\", status_code=303)\n return templates.TemplateResponse(\"chat.html\", {\"request\": request, \"login\": login})\n\n\n@app.post(\"/api/register\")\ndef register_user(user: UserName, response: Response):\n response.set_cookie(key=\"X-Authorization\", value=user.username, httponly=True)\n\n\n@app.websocket(\"/api/chat\")\nasync def chat(websocket: WebSocket):\n sender = get_user(websocket) # type: ignore\n if sender:\n await manager.connect(websocket, sender)\n try:\n while True:\n json_data = await websocket.receive_json()\n message_id = str(uuid4())\n message = Message(content=json_data.get(\"message\"))\n try:\n # Validate the message data using the Message model\n # Broadcast the validated message\n data = {\n \"sender\": sender,\n \"message\": message.content,\n \"message_id\": message_id,\n \"censorship_status\": \"pending\",\n }\n await manager.broadcast(data)\n except (ValidationError, ValueError) as e:\n # Handle the validation or value error\n await websocket.send_json({\"error\": str(e)})\n # Update the censorship mark based on the response\n start_time = time.time()\n censorship_response = await check_message_censorship(\n message.content, CENSOR_URL\n )\n end_time = time.time()\n latency_ms = (end_time - start_time) * 1000 # Convert to milliseconds\n logger.info(f\"Censorship check latency: {latency_ms:.2f} ms\")\n logger.info(f\"Censorship status: {censorship_response}\")\n update_data = {\n \"message_id\": message_id,\n \"censorship_status\": censorship_response,\n }\n # Broadcast the update\n await manager.broadcast(update_data)\n except WebSocketDisconnect:\n manager.disconnect(websocket, sender)\n await manager.broadcast({\"sender\": sender, \"content\": \"left\"})\n\n\n@app.post(\"/api/censor\")\nasync def fake_censor(request: CensorRequest):\n response_choice = random.choices(\n [\"Good\", \"Bad\", \"Timeout\"], weights=[40, 40, 20], k=1\n )[0]\n\n if response_choice == \"Timeout\":\n # Simulate a timeout by sleeping longer than the client is willing to wait\n await asyncio.sleep(3)\n raise HTTPException(status_code=504, detail=\"Request timed out\")\n else:\n await asyncio.sleep(0.5)\n return response_choice\n","repo_name":"DanVerh/mlops-team50-chat","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34699723629","text":"import json\nimport pickle\nfrom argparse import ArgumentParser, Namespace\nfrom pathlib import Path\nfrom typing import Dict\nfrom time import time\nfrom tqdm import tqdm\nimport os\nimport sys\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom common.generators import ChunkedGenerator\nfrom common.model import EmotionClassifier\n\nTRAIN = 'train'\nVALID = 'validation'\n\ndef train(model, dataloader, optimizer, args):\n correct_train = 0\n N = 0\n progress = tqdm(total=dataloader.num_batches)\n for batch_mesh, batch_emotion in dataloader.next_epoch():\n inputs_mesh = torch.from_numpy(batch_mesh.astype('float32'))\n inputs_emotion = torch.from_numpy(batch_emotion.astype('float32'))\n inputs_mesh = inputs_mesh.to(args.device)\n inputs_emotion = inputs_emotion.to(args.device)\n optimizer.zero_grad()\n \n # train\n pred, loss = model(inputs_mesh, inputs_emotion)\n loss.backward()\n optimizer.step()\n \n # acc\n pred = pred.detach().cpu()\n gt = inputs_emotion.detach().cpu()\n \n correct_train += (pred == gt.view_as(pred)).sum().item()\n N += gt.size(0)\n progress.update(1)\n \n return correct_train / N\n\ndef evaluate(model_train_dict, model_eval, dataloader_eval, args):\n correct_eval = 0\n N = 0\n progress = tqdm(total=dataloader_eval.num_batches)\n with torch.no_grad():\n model_eval.load_state_dict(model_train_dict)\n model_eval.eval()\n for batch_mesh, batch_emotion in dataloader_eval.next_epoch():\n inputs_mesh = torch.from_numpy(batch_mesh.astype('float32'))\n inputs_emotion = torch.from_numpy(batch_emotion.astype('float32'))\n inputs_mesh = inputs_mesh.to(args.device)\n inputs_emotion = inputs_emotion.to(args.device)\n \n # evaluate\n pred, loss = model_eval(inputs_mesh, inputs_emotion)\n \n # acc\n pred = pred.detach().cpu()\n gt = inputs_emotion.detach().cpu()\n \n correct_eval += (pred == gt.view_as(pred)).sum().item()\n N += gt.size(0)\n progress.update(1)\n return correct_eval / N\n\ndef get_dataset(args, data, s):\n print(f\"processing {s} data...\")\n input = []\n gt = []\n for d in data:\n input.append(d['face_mesh'])\n gt.append(d['emotion'])\n return ChunkedGenerator(args.batch_size, input, gt, args.frame//2)\n\n\ndef main(args):\n data = np.load(args.dataset, allow_pickle=True)['data'].item()\n dataloader_train = get_dataset(args, data[TRAIN], TRAIN)\n dataloader_eval = get_dataset(args, data[VALID], VALID)\n \n model = EmotionClassifier(args.kp, args.feature_dim, args.hidden_dim, args.channels,\n args.out_dim, args.num_classes, args.using_trans).to(args.device)\n model_eval = EmotionClassifier(args.kp, args.feature_dim, args.hidden_dim, args.channels,\n args.out_dim, args.num_classes, args.using_trans).to(args.device)\n \n # number of params\n model_params = 0\n for parameter in model.parameters():\n model_params += parameter.numel()\n print('Trainable parameter count:', model_params)\n\n # init optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.1)\n\n acc_history_train = []\n acc_history_val = []\n lr = args.lr\n best_acc = 0.\n for epoch in range(args.num_epoch):\n start_time = time()\n model.train()\n \n # Training loop\n acc_train = train(model, dataloader_train, optimizer, args)\n acc_history_train.append(acc_train)\n \n # Evaluation loop\n acc_eval = evaluate(model.state_dict(), model_eval, dataloader_eval, args)\n acc_history_val.append(acc_eval)\n \n # Saving data\n elapsed = (time() - start_time) / 60\n print('[%d] time %.2f lr %f train %f eval %f' % (\n epoch + 1,\n elapsed,\n lr,\n acc_train,\n acc_eval))\n \n if acc_eval >= best_acc:\n best_acc = acc_eval\n chk_path = os.path.join(args.checkpoint_dir, 'best.bin')\n print('Saving best checkpoint to', chk_path)\n torch.save(model.state_dict(), chk_path)\n \n # update params\n lr *= args.lrd\n for param_group in optimizer.param_groups:\n param_group['lr'] *= args.lrd\n \n chk_path = os.path.join(args.checkpoint_dir, 'final.bin')\n torch.save(model.state_dict(), chk_path)\n \n if args.export_training_curves and epoch > 1:\n if 'matplotlib' not in sys.modules:\n import matplotlib\n\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n\n plt.figure()\n epoch_x = np.arange(1, len(acc_history_train)) + 1\n plt.plot(epoch_x, acc_history_train[1:], '--', color='C0')\n plt.plot(epoch_x, acc_history_val[1:], '--', color='C1')\n plt.legend(['train', 'eval'])\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.xlim((1, epoch+1))\n plt.savefig(os.path.join(args.checkpoint_dir, 'acc.png'))\n plt.close('all')\n\n\ndef parse_args() -> Namespace:\n parser = ArgumentParser()\n parser.add_argument(\n \"--dataset\",\n type=str,\n help=\"Dataset name.\",\n default=\"./dataset/data.npz\",\n )\n parser.add_argument(\n \"--checkpoint_dir\",\n type=Path,\n help=\"Directory to save the model file.\",\n default=\"./checkpoints/\",\n )\n \n # model\n parser.add_argument(\"--frame\", type=int, default=27)\n parser.add_argument(\"--kp\", type=int, default=34)\n parser.add_argument(\"--feature_dim\", type=int, default=3)\n parser.add_argument(\"--hidden_dim\", type=int, default=256)\n parser.add_argument(\"--channels\", type=int, default=1024)\n parser.add_argument(\"--out_dim\", type=int, default=64)\n parser.add_argument(\"--num_classes\", type=int, default=7)\n parser.add_argument('--using_trans', action='store_true')\n\n # optimizer\n parser.add_argument(\"--lr\", type=float, default=1e-3)\n parser.add_argument(\"--lrd\", type=float, default=0.95)\n\n # data loader\n parser.add_argument(\"--batch_size\", type=int, default=64)\n\n # training\n parser.add_argument(\n \"--device\", type=torch.device, help=\"cpu, cuda, cuda:0, cuda:1\", default=\"cuda\"\n )\n parser.add_argument(\"--num_epoch\", type=int, default=60)\n parser.add_argument(\"--export_training_curves\", type=bool, default=True)\n\n args = parser.parse_args()\n return args\n\nif __name__ == \"__main__\":\n args = parse_args()\n args.checkpoint_dir.mkdir(parents=True, exist_ok=True)\n main(args)\n","repo_name":"celt1125/3DCV-G18-final","sub_path":"emotion_cls/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"13498921721","text":"import csv\nimport json\nimport argparse\n\nparser = argparse.ArgumentParser(description='Simple CSV to JSON converter')\nparser.add_argument(\"-i\", \"--input\", dest=\"input\", help=\"csv input file\", required=True)\nparser.add_argument(\"-o\", \"--output\", dest=\"output\", help=\"json output file\", required=True)\nparser.add_argument(\"-d\", \"--delimiter\", dest=\"delimiter\", help=\"Delimiter char\", default=\",\")\nargs=parser.parse_args()\n\nwith open(args.input, encoding='utf-8-sig') as f:\n reader = csv.DictReader(f, delimiter=args.delimiter)\n data = list(reader)\n with open(args.output, 'w') as outfile:\n json.dump(data, outfile, indent = 4)\n","repo_name":"oscargaciaisbanuk/csv2json","sub_path":"csv2json.py","file_name":"csv2json.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16311703901","text":"#!/usr/bin/env python3\n\nimport sys, os, pwd, grp\nimport os.path\n\n_, owner, group, dirmod, mod, *targets = sys.argv\n\nuid = pwd.getpwnam(owner).pw_uid\ngid = grp.getgrnam(group).gr_gid\n\ndirmod =int(dirmod, base=8)\nmod = int(mod, base=8)\n\nc = 0\ndef progress():\n\tglobal c\n\tc += 1\n\tif c % 1000 == 0:\n\t\tprint('.', end='', flush=True)\n\tif c % 60000 == 0:\n\t\tprint()\n\n\t\t\n\nfor target in targets:\n\tprint(dict(uid=uid, gid=gid, dirmod=oct(dirmod), mod=oct(mod), target=target))\n\tp = target\n\tos.lchown(p, uid, gid)\n\tos.lchmod(p, dirmod)\t\n\tprogress()\n\tfor dirpath, dirnames, filenames in os.walk(target):\n\t\tfor f in filenames:\n\t\t\tp = os.path.join(dirpath, f)\n\t\t\tos.lchown(p, uid, gid)\n\t\t\tos.lchmod(p, mod)\t\n\t\t\tprogress()\n\t\tfor d in dirnames:\n\t\t\tp = os.path.join(dirpath, d)\n\t\t\tos.lchown(p, uid, gid)\n\t\t\tos.lchmod(p, dirmod)\t\n\t\t\tprogress()\n\tprint()\n","repo_name":"will0/chownmodr","sub_path":"chownmodr.py","file_name":"chownmodr.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28076069289","text":"import flask\nfrom flask import request, jsonify, g, current_app\nimport sqlite3\n\n######################\n# API USAGE\n# Caddy Web server route for this API: localhost:$PORT/messages/\n# Caddy Web server PORT is set to 2015\n# --------------------\n# Send a message: Send a POST request to route of send() fn\n# Example request:\n# curl -i -X POST -H 'Content-Type:application/json' -d\n# '{\"user_from\":\"ilovedog\", \"user_to\":\"ilovecat\", \"msg_content\":\"I think dogs are better\", \"msg_flag\":\"greetings\"}'\n# http://localhost:2015/messages/send;\n# --------------------\n# Delete a message: Send a DELETE request to route of delete() fn\n# Example request:\n# curl -i -X DELETE http://localhost:2015/messages/delete?msg_id=2;\n# --------------------\n# Favorite a message: Send a POST request to route of favorite() fn\n# Example request:\n# curl -i -X POST -H 'Content-Type:application/json' http://localhost:2015/messages/favorite?msg_id=1;\n\n\n# config variables\nDATABASE = 'data.db'\nDEBUG = True\n\n######################\napp = flask.Flask(__name__)\napp.config.from_object(__name__)\n\n######################\n# Database\n# app.config.from_envvar('APP_CONFIG')\n# db_name: data.db\n\n# table1: users\n# user_id\n# username\n# email\n# karma\n\n# table2: messages\n# msg_id\n# user_from\n# user_to\n# msg_time\n# msg_content\n# msg_flag\n\n######################\n# helper function used to convert each query result row into dictionary\ndef make_dicts(cursor, row):\n return dict((cursor.description[idx][0], value) for idx, value in enumerate(row))\n\n\n# helper function to generate a response with status code and message\ndef get_response(status_code, message):\n return {\"status_code\": str(status_code), \"message\": str(message)}\n\n\n# get db from flask g namespace\ndef get_db():\n if 'db' not in g:\n g.db = sqlite3.connect(\n current_app.config['DATABASE'],\n detect_types=sqlite3.PARSE_DECLTYPES\n )\n g.db.row_factory = make_dicts\n return g.db\n\n\n# initiate db with\n# $FLASK_APP=post_api.py\n# $flask init\n@app.cli.command('init')\ndef init_db():\n with app.app_context():\n db = get_db()\n with app.open_resource('data.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n# close db connection\n@app.teardown_appcontext\ndef close_db(e=None):\n if e is not None:\n print(f'Closing db: {e}')\n db = g.pop('db', None)\n if db is not None:\n db.close()\n\n\n# home page\n@app.route('/', methods=['GET'])\ndef home():\n return jsonify(get_response(status_code=200, message=\"Welcome to CSUF messages API.\"))\n\n\n# 404 page\n@app.errorhandler(404)\ndef page_not_found(status_code=404):\n error_json = get_response(status_code=status_code, message=\"Resource not found\")\n return jsonify(error_json), status_code\n\n\n# function to execute a single query at once\ndef query_db(query, args=(), one=False, commit=False):\n # one=True means return single record\n # commit = True for post and delete query (return boolean)\n conn = get_db()\n try:\n rv = conn.execute(query, args).fetchall()\n if commit:\n conn.commit()\n except sqlite3.OperationalError as e:\n print(e)\n return False\n close_db()\n if not commit:\n return (rv[0] if rv else None) if one else rv\n return True\n\n\n# function to execute multiple queries at once (also fn commits the transaction)\ndef transaction_db(query, args, return_=False):\n # return_=True if the transaction needs returns a result\n conn = get_db()\n if len(query) != len(args):\n raise ValueError('arguments dont match queries')\n try:\n rv = []\n conn.execute('BEGIN')\n for i in range(len(query)):\n rv.append(conn.execute(query[i], args[i]).fetchall())\n conn.commit()\n except (sqlite3.OperationalError, sqlite3.ProgrammingError) as e:\n conn.execute('rollback')\n print('Transaction failed. Rolled back')\n print(e)\n return False\n close_db()\n return True if not return_ else rv\n\n### WHAT TO DO ###\n# 1. Send message\n# 2. Delete message\n# 3. Favorite message\n\n@app.route('/send', methods=['POST'])\ndef send():\n params = request.get_json()\n user_from = params.get('user_from')\n user_to = params.get('user_to')\n msg_content = params.get('msg_content')\n msg_flag = params.get('msg_flag')\n\n if not user_from or not user_to:\n return jsonify(get_response(status_code=409, message=\"Sender / Recipient is not provided\")), 409\n\n query1 = 'SELECT username FROM users WHERE username = ?'\n args1 = (user_from,)\n q_sender = query_db(query1, args1)\n\n query2 = \"SELECT username FROM users WHERE username = ?\"\n args2 = (user_to,)\n q_receiver = query_db(query2, args2)\n\n if not q_sender:\n return jsonify(get_response(status_code=404, message=\"Sender not existed\")), 404\n if not q_receiver:\n return jsonify(get_response(status_code=404, message=\"Receiver not existed\")), 404\n\n query = 'INSERT INTO messages (user_from, user_to, msg_content, msg_flag) VALUES ((SELECT user_id FROM users WHERE username=?), (SELECT user_id FROM users WHERE username=?), ?, ?)'\n args = (user_from, user_to, msg_content, msg_flag)\n q = transaction_db(query=[query], args=[args], return_=True)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=201, message=\"Message sent\")), 201\n\n@app.route('/delete', methods=['DELETE'])\ndef delete():\n params = request.args\n msg_id = params.get('msg_id')\n if not msg_id:\n return jsonify(get_response(status_code=409, message=\"Message ID is not provided\")), 409\n\n query = 'SELECT msg_id FROM messages WHERE msg_id = ?'\n args = (msg_id,)\n q = query_db(query, args)\n\n if not q:\n return jsonify(get_response(status_code=404, message=\"Message not existed\")), 404\n\n query = 'DELETE FROM favorite WHERE msg_id = ?'\n args = (msg_id,)\n query1 = 'DELETE FROM messages WHERE msg_id = ?'\n\n q = transaction_db([query, query1], [args, args],)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=200, message=\"Message deleted\")), 200\n\n@app.route('/favorite', methods=['POST'])\ndef favorite():\n params = request.args\n msg_id = params.get('msg_id')\n if not msg_id:\n return jsonify(get_response(status_code=409, message=\"Message ID is not provided\")), 409\n query = 'SELECT msg_id FROM messages WHERE msg_id = ?'\n args = (msg_id,)\n q = query_db(query, args)\n\n if not q:\n return jsonify(get_response(status_code=404, message=\"Message not existed\")), 404\n\n query2 = 'SELECT msg_id FROM favorite WHERE msg_id = ?'\n args2 = (msg_id,)\n q1 = query_db(query2,args2)\n\n if q1:\n return jsonify(get_response(status_code=404, message=\"Message already favorited\")), 404\n\n query = 'INSERT INTO favorite (msg_ID) VALUES (?)'\n args = (msg_id,)\n q = query_db(query, args, commit=True)\n\n if not q:\n return page_not_found(404)\n\n return jsonify(get_response(status_code=201, message=\"Message favorited\")), 201\n\ndef main():\n app.run()\n\nif __name__ == '__main__':\n main()\n","repo_name":"tpham523/CPSC_449_Project_1","sub_path":"msg_api.py","file_name":"msg_api.py","file_ext":"py","file_size_in_byte":7153,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"11264906311","text":"import time\nimport json\nimport pandas\nfrom django.shortcuts import render, redirect\nfrom django.http import JsonResponse, StreamingHttpResponse\nfrom django.core import serializers\nfrom .models import CaronaData, Asset, SubmitedAssets\nfrom .graph import genarate_bar_graph, asset_graph, excel_data_to_graph\nfrom django_pandas.io import read_frame\nfrom users.decorators import my_login_required\nfrom django.template.loader import render_to_string\nfrom django.db import connection\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom .raw_querys import my_query\nfrom .excel_static import convert_df_to_html\n\n# Create your views here.\n@my_login_required\ndef index(request):\n carona = CaronaData.objects.all()\n # df = read_frame(carona)\n df, html = convert_df_to_html()\n context = {\n # \"data\" : CaronaData.objects.all(),\n # \"graph1\" : genarate_bar_graph(df),\n # \"graph2\" : genarate_bar_graph(df),\n \"graph\": asset_graph(),\n \"assets1\" : Asset.objects.all()[0:10],\n \"assets2\" : Asset.objects.all()[10:20],\n \"html\": html,\n \"excel_graph\": excel_data_to_graph(df),\n }\n return render(request, 'index.html', context)\n\n\n@my_login_required\ndef dynamic_graph(request):\n if request.method == 'POST':\n val = request.POST['graph-options']\n data = CaronaData.objects.all().order_by('-id')[0:50]\n df = read_frame(data)\n context = {\n \"graph\": genarate_bar_graph(df=df, option=val)\n }\n return JsonResponse(context, safe=False)\n\n@my_login_required\ndef dynamic_table(request):\n if request.method == 'POST':\n country = request.POST['country1']\n context = { \"data\" :CaronaData.objects.filter(country__icontains=country) }\n html = render_to_string(\"search_table_data.html\",context)\n return JsonResponse(html, safe=False)\n\n@my_login_required\ndef submit_asset(request, asset=None, timeremaining=None):\n print(timeremaining)\n if request.session.get('user', False):\n user = request.session.get('user')\n sa = SubmitedAssets(userid=user, asset_name=asset, timeremaining=timeremaining)\n sa.save()\n return redirect(index)\n else:\n return redirect('login')\n\n#streaming data\ndef event_stream():\n initial_data = \"\"\n while True:\n result = my_query()\n data = json.dumps(list(result),cls=DjangoJSONEncoder)\n # print(data)\n if not initial_data == data:\n yield \"\\ndata: {}\\n\\n\".format(data) \n initial_data = data\n # print(initial_data)\n time.sleep(1)\n\ndef caron_live_data(request):\n response = StreamingHttpResponse(event_stream())\n response['Content-Type'] = 'text/event-stream'\n # print(response.readable)\n return response\n\n\n\n#streaming data\ndef dash_event_stream():\n initial_data = \"\"\n while True:\n result = Asset.objects.all().values()\n data = json.dumps(list(result),cls=DjangoJSONEncoder)\n # print(data)\n # print(data)\n if not initial_data == data:\n yield \"\\ndata: {}\\n\\n\".format(data) \n initial_data = data\n # print(initial_data)\n time.sleep(1)\n\ndef dashboard_live_data(request):\n response = StreamingHttpResponse(dash_event_stream())\n response['Content-Type'] = 'text/event-stream'\n return response\n\n\ndef asset_graph_view(request):\n if request.method == \"GET\":\n value = request.GET[\"option\"]\n context = {\n \"graph\": asset_graph(value)\n }\n \n return JsonResponse(context, safe=False)\n\ndef excel_data_view(request):\n if request.method == \"GET\":\n value = request.GET[\"option\"]\n final_df, final_df_html = convert_df_to_html(field=value)\n context = {\n \"html\": final_df_html,\n \"graph\":excel_data_to_graph(final_df)\n }\n \n return JsonResponse(context, safe=False)","repo_name":"dorababu067/true-lancer1","sub_path":"app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11633901585","text":"import argparse\r\nimport os\r\n\r\nif __name__ == \"__main__\":\r\n\r\n parser = argparse.ArgumentParser(\r\n usage=\"%prog -b -d -g \",\r\n description='GC-bias adjustment for cell-free DNA based TSS coverage profile',\r\n epilog = \"Written by Han Bowei (hanbw0120@foxmail.com), 2020\\n\"\r\n )\r\n\r\n parser.add_argument('--bam', '-b', type=str, help='Input bam file', required=True)\r\n parser.add_argument('--bed', '-d', type=str, help='Reference bed file', required=True)\r\n parser.add_argument('--effectiveGenomeSize', '-s', type=int, default=2827437033, help='effectiveGenomeSize for deepTools (default(hg19): 2827437033)')\r\n parser.add_argument('--genome2bit', '-g', type=str, required=True,\r\n help='Genome 2bit file, download from http://hgdownload.cse.ucsc.edu/gbdb/')\r\n parser.add_argument('--fragment_size', '-f', type=int, default=167, help='Fragment size of cfDNA')\r\n parser.add_argument('--threads', '-t', type=int, default=1, help='Number of threads (default: 1)')\r\n parser.add_argument('--mode', '-m', type=str, default=\"SE\", help='Single-end(SE) or Paired-end(PE) (default: SE)')\r\n\r\n args = parser.parse_args()\r\n\r\n\r\n os.system(\"computeGCBias -b %s --effectiveGenomeSize %s -g %s -l %s --GCbiasFrequenciesFile %s.freq.txt -p %s\"\r\n % (args.bam, args.effectiveGenomeSize, args.genome2bit, args.fragment_size, args.bam, args.threads))\r\n os.system(\"python ./correctGCBias_for_bedtools.py -b %s --effectiveGenomeSize %s -g %s --GCbiasFrequenciesFile %s.freq.txt -o %s.gc.bam -p %s\"\r\n % (args.bam, args.effectiveGenomeSize, args.genome2bit, args.bam, args.bam, args.threads))\r\n os.system(\"python ./computeBEDcov.py -b %s.gc.bam -d %s -m %s\" % (args.bam, args.bed, mode))","repo_name":"hanbw0120/AECT","sub_path":"script/run_gc_adj.py","file_name":"run_gc_adj.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"8943148304","text":"# -*- coding:utf-8 -*-\nclass Solution:\n def VerifySquenceOfBST(self, sequence):\n # write code here\n if not sequence or len(sequence) == 0:\n return False\n root = sequence[-1]\n flag = 0\n while sequence[flag] < root:\n flag += 1\n for i in range(flag, len(sequence)-1):\n if sequence[i] < root:\n return False\n left = True\n right = True\n if flag > 0:\n left = self.VerifySquenceOfBST(sequence[:flag])\n if flag < len(sequence)-1:\n right = self.VerifySquenceOfBST(sequence[flag:len(sequence)-1])\n return left and right\n\n\nif __name__ == \"__main__\":\n s = Solution()\n print(s.VerifySquenceOfBST([1, 4, 7, 6, 3, 13, 14, 10, 8]))\n\n\n","repo_name":"zhengxiang1994/JIANZHI-offer","sub_path":"test1/demo23.py","file_name":"demo23.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"37559882180","text":"\"\"\"Support for Litter-Robot sensors.\"\"\"\nfrom typing import Optional\n\nfrom pylitterbot.robot import Robot\n\nfrom homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE\nfrom homeassistant.helpers.entity import Entity\n\nfrom .const import DOMAIN\nfrom .hub import LitterRobotEntity, LitterRobotHub\n\n\ndef icon_for_gauge_level(gauge_level: Optional[int] = None, offset: int = 0) -> str:\n \"\"\"Return a gauge icon valid identifier.\"\"\"\n if gauge_level is None or gauge_level <= 0 + offset:\n return \"mdi:gauge-empty\"\n if gauge_level > 70 + offset:\n return \"mdi:gauge-full\"\n if gauge_level > 30 + offset:\n return \"mdi:gauge\"\n return \"mdi:gauge-low\"\n\n\nclass LitterRobotPropertySensor(LitterRobotEntity, Entity):\n \"\"\"Litter-Robot property sensors.\"\"\"\n\n def __init__(\n self, robot: Robot, entity_type: str, hub: LitterRobotHub, sensor_attribute: str\n ):\n \"\"\"Pass coordinator to CoordinatorEntity.\"\"\"\n super().__init__(robot, entity_type, hub)\n self.sensor_attribute = sensor_attribute\n\n @property\n def state(self):\n \"\"\"Return the state.\"\"\"\n return getattr(self.robot, self.sensor_attribute)\n\n\nclass LitterRobotWasteSensor(LitterRobotPropertySensor, Entity):\n \"\"\"Litter-Robot sensors.\"\"\"\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return unit of measurement.\"\"\"\n return PERCENTAGE\n\n @property\n def icon(self):\n \"\"\"Return the icon to use in the frontend, if any.\"\"\"\n return icon_for_gauge_level(self.state, 10)\n\n\nclass LitterRobotSleepTimeSensor(LitterRobotPropertySensor, Entity):\n \"\"\"Litter-Robot sleep time sensors.\"\"\"\n\n @property\n def state(self):\n \"\"\"Return the state.\"\"\"\n if self.robot.sleep_mode_active:\n return super().state.isoformat()\n return None\n\n @property\n def device_class(self):\n \"\"\"Return the device class, if any.\"\"\"\n return DEVICE_CLASS_TIMESTAMP\n\n\nROBOT_SENSORS = [\n (LitterRobotWasteSensor, \"Waste Drawer\", \"waste_drawer_gauge\"),\n (LitterRobotSleepTimeSensor, \"Sleep Mode Start Time\", \"sleep_mode_start_time\"),\n (LitterRobotSleepTimeSensor, \"Sleep Mode End Time\", \"sleep_mode_end_time\"),\n]\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\"Set up Litter-Robot sensors using config entry.\"\"\"\n hub = hass.data[DOMAIN][config_entry.entry_id]\n\n entities = []\n for robot in hub.account.robots:\n for (sensor_class, entity_type, sensor_attribute) in ROBOT_SENSORS:\n entities.append(sensor_class(robot, entity_type, hub, sensor_attribute))\n\n if entities:\n async_add_entities(entities, True)\n","repo_name":"fpetillo/home-assistant","sub_path":"homeassistant/components/litterrobot/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"75226365284","text":"#!/usr/bin/env python3\nimport rospy\nfrom odometry_hw.msg import Pose2D\nimport matplotlib\n\nclass OdomGraph:\n def __init__(self):\n self.x_list = list()\n self.y_list = list()\n \n def pose_cb(self,msg):\n self.x_list.append(msg.x)\n self.y_list.append(msg.y)\n\n\nif __name__ == '__main__':\n try:\n rospy.init_node('odom_graph', anonymous=True)\n output_to_file = False\n if rospy.has_param('/output_to_file'):\n rospy.logwarn(\"Has output to file\")\n if rospy.get_param('/output_to_file') == True or rospy.get_param('/output_to_file') == \"true\":\n output_to_file=True\n if rospy.has_param('/only_output_to_file'):\n rospy.logwarn(\"Has only output to file\")\n if rospy.get_param('/only_output_to_file') == True or rospy.get_param('/only_output_to_file') == \"true\":\n rospy.logwarn(\"only outputting to PDF!\")\n output_to_file=True\n matplotlib.use(\"pdf\")\n folder = \".\"\n if rospy.has_param('output_folder'):\n folder = rospy.get_param('output_folder')\n \n import matplotlib.pyplot as plt\n og = OdomGraph()\n rospy.Subscriber(\"pose\", Pose2D, og.pose_cb)\n rate = rospy.Rate(10) # 10hz\n while not rospy.is_shutdown(): \n plt.plot(og.x_list, og.y_list,'ro-',)\n plt.axis([-0.5,5,-0.5,5])\n plt.xlabel('x (m)')\n plt.ylabel('y (m)')\n plt.title('Vehicle Odometry')\n if output_to_file:\n plt.savefig(folder + \"/output_plot.png\")\n plt.pause(0.05) \n rate.sleep()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"UML-EECE-5560/eece5560-base","sub_path":"eece5560/packages/odometry_hw/src/odom_graph.py","file_name":"odom_graph.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"26748196426","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\n\nclient = MongoClient(\"mongodb://yoonchaiyoung:9452@18.222.215.81\", 27017)\ndb = client.music_top100\nprint(db)\n# db 잘 작동하는 지 확인\n\ndef scrap_vibe_top100():\n URL = \"https://music.bugs.co.kr/chart\"\n headers = {\n 'User-Agent': \"Mozilla/5.0\"\n }\n\n data = requests.get(URL, headers=headers)\n # print(\"data는~~~\", data)\n # print(\"data.text는~~~\", data.text)\n # 데이터 잘 들어오는 지 확인완료\n\n soup = BeautifulSoup(data.text, 'html.parser')\n music_lst = soup.select(\"#CHARTrealtime > table > tbody > tr\")\n # print(music_lst)\n\n # 이제 밑의 데이터들을 하나씩 뽑아서 {} 딕서너리 형태 파일에 넣기\n # 데이터 : 순위, 제목, 앨범아트, 아티스트 목록, 앨범명\n\n for tr in music_lst:\n rank = tr.select_one(\"td > div > strong\").text\n # print(rank)\n title = tr.select_one(\"th > p > a\").text\n # print(title)\n album_art = tr.select_one(\"td > a > img\").get('src')\n # print(album_art)\n artist = tr.select_one(\"td > .artist > a\").text\n # print(artist)\n album_name = tr.select_one(\"td > .album\").text\n # print(album_name)\n\n doc = {\n \"rank\": rank,\n \"title\": title,\n \"album_art\": album_art,\n \"artist\": artist,\n \"album_name\": album_name\n }\n # print(doc)\n\n db.music.insert_one(doc)\n\nif __name__ == \"__main__\":\n scrap_vibe_top100()","repo_name":"yoonchaiyoung/music_top100_backend","sub_path":"music_scraper.py","file_name":"music_scraper.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70023163045","text":"\"\"\"another new field\n\nRevision ID: c17e4c1101de\nRevises: b7834f420599\nCreate Date: 2018-11-24 21:57:07.208365\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c17e4c1101de'\ndown_revision = 'b7834f420599'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user', sa.Column('scores_fn', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'scores_fn')\n # ### end Alembic commands ###\n","repo_name":"cgutwein/grocery-and-meal-assistant","sub_path":"flask/migrations/versions/c17e4c1101de_another_new_field.py","file_name":"c17e4c1101de_another_new_field.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70996358884","text":"from copy import deepcopy\n\nimport extractor\nfrom mutalyzer_mutator import mutate\nfrom mutalyzer_mutator.util import reverse_complement\nfrom mutalyzer_retriever.reference import get_reference_mol_type\nfrom mutalyzer_retriever.retriever import extract_feature_model\n\nimport mutalyzer.errors as errors\n\nfrom .converter import de_to_hgvs\nfrom .converter.extras import (\n convert_reference_model,\n convert_to_exons,\n get_gene_locations,\n)\nfrom .converter.to_hgvs_coordinates import to_hgvs_locations\nfrom .description import Description\nfrom .description_model import model_to_string\nfrom .reference import (\n get_coordinate_system_from_reference,\n get_coordinate_system_from_selector_id,\n get_internal_selector_model,\n get_only_selector_id,\n retrieve_reference,\n)\nfrom .util import slice_seq\n\n\ndef _get_description(de_hgvs_internal_indexing_variants, r_model, selector_id=None):\n reference = {\"id\": r_model[\"annotations\"][\"id\"]}\n if selector_id:\n reference[\"selector\"] = {\"id\": selector_id}\n c_s = get_coordinate_system_from_selector_id(r_model, selector_id)\n else:\n c_s = get_coordinate_system_from_reference(r_model)\n if c_s in [\"c\", \"n\"]:\n selector_id = r_model[\"annotations\"][\"id\"]\n\n de_hgvs_model = to_hgvs_locations(\n {\n \"reference\": reference,\n \"coordinate_system\": \"i\",\n \"variants\": de_hgvs_internal_indexing_variants,\n },\n {\"reference\": r_model, r_model[\"annotations\"][\"id\"]: r_model},\n c_s,\n selector_id,\n True,\n )\n return model_to_string(de_hgvs_model)\n\n\ndef _extract_hgvs_internal_model(obs_seq, ref_seq):\n de_variants = extractor.describe_dna(ref_seq, obs_seq)\n\n return de_to_hgvs(\n de_variants,\n {\"reference\": ref_seq, \"observed\": obs_seq},\n )\n\n\ndef _filter(variants, ref_seq1, ref_seq2):\n raw_de_variants = extractor.describe_dna(ref_seq1, ref_seq2)\n seq_variants = de_to_hgvs(\n raw_de_variants,\n {\"reference\": ref_seq1, \"observed\": ref_seq2},\n )\n return [v for v in variants if v not in seq_variants]\n\n\ndef map_description(\n description,\n reference_id,\n selector_id=None,\n slice_to=None,\n filter=False,\n len_max=100000,\n diff_max=1000,\n):\n # Get the observed sequence\n d = Description(description)\n d.normalize()\n if d.errors:\n return {\"errors\": d.errors, \"source\": \"input\"}\n if not d.references and not d.references.get(\"observed\"):\n return {\n \"errors\": [{\"details\": \"No observed sequence or other error occured.\"}],\n \"source\": \"input\",\n }\n obs_seq = d.references[\"observed\"][\"sequence\"][\"seq\"]\n\n to_r_model = retrieve_reference(reference_id, selector_id)[0]\n if to_r_model is None:\n return {\n \"errors\": [errors.reference_not_retrieved(reference_id, [])],\n \"source\": \"input\",\n }\n\n ref_seq_from = d.references[\"reference\"][\"sequence\"][\"seq\"]\n\n if d.only_equals() or d.no_operation():\n variants = []\n else:\n variants = d.delins_model[\"variants\"]\n\n if slice_to == \"transcript\":\n selector_model = d.get_selector_model()\n if selector_model:\n converted_variants, skipped_variants = convert_to_exons(\n variants,\n selector_model[\"exon\"],\n d.get_sequences(),\n )\n if skipped_variants:\n errs = []\n for v in skipped_variants:\n errs.append(\n errors.location_slice(\n d.corrected_model[\"variants\"][v][\"location\"]\n )\n )\n return {\"errors\": errs, \"source\": \"input\"}\n from_r_model = convert_reference_model(\n d.references[\"reference\"], d.get_selector_id(), slice_to\n )\n ref_seq_from = from_r_model[\"sequence\"][\"seq\"]\n obs_seq = mutate({\"reference\": ref_seq_from}, converted_variants)\n if (\n selector_id is None\n and get_coordinate_system_from_reference(to_r_model) == \"c\"\n and get_only_selector_id(to_r_model) == reference_id\n ):\n selector_id = reference_id\n elif slice_to == \"gene\":\n gene = extract_feature_model(\n d.references[\"reference\"][\"annotations\"], d.get_selector_id()\n )[0]\n if gene:\n new_r_model = {\"annotations\": deepcopy(gene)}\n g_l = get_gene_locations(new_r_model)\n ref_seq_from = slice_seq(\n d.references[\"reference\"][\"sequence\"][\"seq\"], [g_l]\n )\n converted_variants, skipped_variants = convert_to_exons(\n variants, [g_l], {\"reference\": ref_seq_from}\n )\n if skipped_variants:\n errs = []\n for v in skipped_variants:\n errs.append(\n errors.location_slice(\n d.corrected_model[\"variants\"][v][\"location\"]\n )\n )\n return {\"errors\": errs, \"source\": \"input\"}\n obs_seq = mutate({\"reference\": ref_seq_from}, converted_variants)\n elif slice_to is not None:\n return {\"errors\": [errors.slice_option(slice_to)], \"source\": \"input\"}\n\n if selector_id:\n s_model = get_internal_selector_model(\n to_r_model[\"annotations\"], selector_id, True\n )\n if s_model is None:\n return {\n \"errors\": [errors.no_selector_found(reference_id, selector_id, [])],\n \"source\": \"input\",\n }\n if d.get_selector_model() and (\n s_model[\"inverted\"] ^ d.get_selector_model()[\"inverted\"]\n ):\n obs_seq = reverse_complement(obs_seq)\n ref_seq_from = reverse_complement(ref_seq_from)\n if slice_to:\n to_r_model = convert_reference_model(to_r_model, selector_id, slice_to)\n\n ref_seq_to = to_r_model[\"sequence\"][\"seq\"]\n\n if len(ref_seq_to) > len_max:\n return {\n \"errors\": [errors.sequence_length(ref_seq_to, len_max)],\n \"source\": \"input\",\n }\n if len(obs_seq) > len_max:\n return {\"errors\": [errors.sequence_length(obs_seq, len_max)], \"source\": \"input\"}\n\n if (\n len(ref_seq_to) < len(obs_seq)\n and abs(len(ref_seq_to) - len(obs_seq)) > diff_max\n ):\n return {\n \"errors\": [\n errors.lengths_difference(abs(len(ref_seq_to) - len(obs_seq)), diff_max)\n ],\n \"source\": \"input\",\n }\n\n # Get the description extractor hgvs internal indexing variants\n variants = _extract_hgvs_internal_model(obs_seq, ref_seq_to)\n\n if filter:\n raw_de_variants = extractor.describe_dna(ref_seq_to, ref_seq_from)\n seq_variants = de_to_hgvs(\n raw_de_variants,\n {\"reference\": ref_seq_to, \"observed\": ref_seq_from},\n )\n if not (len(seq_variants) == 1 and seq_variants[0][\"type\"] == \"equal\") and [\n v for v in seq_variants if v not in variants\n ]:\n return {\n \"errors\": [\n {\"code\": \"EMAPFILTER\", \"details\": \"Unsuccessful filtering.\"}\n ],\n \"source\": \"input\",\n }\n variants = [v for v in variants if v not in seq_variants]\n\n mapped_description = _get_description(variants, to_r_model, selector_id)\n m_d = Description(mapped_description)\n m_d.to_delins()\n if m_d.errors:\n return {\"errors\": m_d.errors, \"source\": \"output\"}\n else:\n return {\"mapped_description\": mapped_description}\n","repo_name":"mutalyzer/mutalyzer","sub_path":"mutalyzer/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"52"}
+{"seq_id":"34900706891","text":"import threading \nimport redis\nimport uuid\nfrom package.module import *\n\n# connect redis\nr = redis.Redis(host='hank-001.bwwxt6.0001.use1.cache.amazonaws.com', port=6379, charset=\"utf-8\",decode_responses=True)\nr1 = redis.Redis(host='hank-003.bwwxt6.0001.use1.cache.amazonaws.com', port=6379, charset=\"utf-8\",decode_responses=True) \n\n# initial variable -- setting time for version and from_type\nversion_time = transfer(\"2019-8-8 6:30\")\nfrom_type_time = transfer(\"2019-8-8 6:30\")\n\n\ndef stresser(): \n global all_user \n index = 0 # \n last_time = 0 \n while True : \n # create token\n TOKEN = str(uuid.uuid4()) \n SCORE = 0\n\n user_response = { \"token\" : \"\",\"version\" : \"\",\"from_type\" : \"\" }\n\n if (time.time() - last_time) > 5:\n last_time = time.time()\n all_user = get_user(r1)\n\n # create User\n if(len(all_user)>0):\n user = User(username=\"\", endpoint=\"\")\n user.setUsername(all_user, index)\n user.setEndpoint(r1) \n \n # get header \n user_response = get_header(user_response,user.endpoint,TOKEN)\n \n # check header\n SCORE += check_header(0,TOKEN,user_response[\"token\"],0)\n SCORE += check_header(1,None,user_response[\"version\"],version_time)\n SCORE += check_header(2,None,user_response[\"from_type\"],from_type_time)\n user.score = SCORE\n user.setError(user_response,r)\n user.setScore(r)\n \n print(user.username)\n print(user.endpoint)\n print(user_response)\n print(user.error_ms)\n print(user.score)\n print(\"------------------------------------------------\")\n else:\n print(\"no user in Redis\")\n \n # loop user\n index+=1\n if(index>=len(all_user)):\n index=0\n\n\ndef _threads_(): \n c= threading.Thread(target=stresser) \n d= threading.Thread(target=stresser)\n a= threading.Thread(target=stresser)\n e= threading.Thread(target=stresser)\n z= threading.Thread(target=stresser)\n c.start()\n c.join()\n d.start()\n d.join()\n a.start()\n a.join()\n e.start()\n e.join()\n z.start()\n z.join()\n\ndef main():\n\ttime.sleep(1)\n\t_threads_() \n\nmain()\n","repo_name":"Hank-Kuo/client_server_flow_test","sub_path":"client/client_multi.py","file_name":"client_multi.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73716954726","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 18 14:19:48 2022\n\n@author: Baccouche, Asma.\n\"\"\"\nimport warnings\nimport pdb\n\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\nimport numpy as np\nimport tensorflow as tf\nfrom keras.models import Model\nfrom keras.layers import Input, concatenate, Conv2D, Add, MaxPooling2D, Activation, Dense, Reshape, GlobalAveragePooling2D, Multiply, Conv2DTranspose, BatchNormalization\n# from keras.optimizers import Adam\nfrom keras.optimizers import adam_v2\nfrom keras import backend as K\nK.set_image_data_format('channels_last') \n\nnp.random.seed(10101)\n\nimg_rows = 256\nimg_cols = 256\nsmooth = 1.\n\ndef dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\ndef iou_coef(y_true, y_pred, smooth=1):\n intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3])\n union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection\n iou = K.mean((intersection + smooth) / (union + smooth), axis=0)\n return iou\n\ndef dice_coef_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef focal_loss(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n BCE = K.binary_crossentropy(y_true_f, y_pred_f)\n BCE_EXP = K.exp(-BCE)\n focal_loss = K.mean(0.8 * K.pow((1-BCE_EXP), 2.) * BCE)\n return focal_loss\n\ndef loss(y_true, y_pred):\n return -(0.4*dice_coef(y_true, y_pred)+0.6*iou_coef(y_true, y_pred))\n\ndef aspp_block(x, num_filters, rate_scale=1):\n x1 = Conv2D(num_filters, (3, 3), dilation_rate=(6 * rate_scale, 6 * rate_scale), padding=\"same\")(x)\n x1 = BatchNormalization()(x1)\n\n x2 = Conv2D(num_filters, (3, 3), dilation_rate=(12 * rate_scale, 12 * rate_scale), padding=\"same\")(x)\n x2 = BatchNormalization()(x2)\n\n x3 = Conv2D(num_filters, (3, 3), dilation_rate=(18 * rate_scale, 18 * rate_scale), padding=\"same\")(x)\n x3 = BatchNormalization()(x3)\n\n x4 = Conv2D(num_filters, (3, 3), padding=\"same\")(x)\n x4 = BatchNormalization()(x4)\n\n y = Add()([x1, x2, x3, x4])\n y = Conv2D(num_filters, (1, 1), padding=\"same\")(y)\n return y \n\ndef squeeze_excite_block(inputs, ratio=8):\n init = inputs\n channel_axis = -1\n filters = init.shape[channel_axis]\n se_shape = (1, 1, filters)\n\n se = GlobalAveragePooling2D()(init)\n se = Reshape(se_shape)(se)\n se = Dense(filters // ratio, activation='relu', kernel_initializer='he_normal', use_bias=False)(se)\n se = Dense(filters, activation='sigmoid', kernel_initializer='he_normal', use_bias=False)(se)\n\n x = Multiply()([init, se])\n return x\n\ndef resnet_block(x, n_filter, strides=1):\n x_init = x\n\n ## Conv 1\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n x = Conv2D(n_filter, (3, 3), padding=\"same\", strides=strides)(x)\n ## Conv 2\n x = BatchNormalization()(x)\n x = Activation(\"relu\")(x)\n x = Conv2D(n_filter, (3, 3), padding=\"same\", strides=1)(x)\n\n ## Shortcut\n s = Conv2D(n_filter, (1, 1), padding=\"same\", strides=strides)(x_init)\n s = BatchNormalization()(s)\n\n ## Add\n x = Add()([x, s])\n x = squeeze_excite_block(x)\n return x\n\n\ndef get_rwnet(): \n inputs = Input((img_rows, img_cols, 3))\n conv1 = resnet_block(inputs,32 , strides=1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = resnet_block(pool1,64 , strides=1)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = resnet_block(pool2, 128, strides=1)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = resnet_block(pool3, 256, strides=1)\n pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)\n\n conv5 = aspp_block(pool4, 512)\n up6 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv5), conv4], axis=3)\n conv6 = resnet_block(up6, 256, strides=1)\n \n up7 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv6), conv3], axis=3)\n conv7 = resnet_block(up7, 128, strides=1)\n\n up8 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv7), conv2], axis=3)\n conv8 = resnet_block(up8, 64, strides=1)\n \n up9 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv8), conv1], axis=3)\n conv9 = resnet_block(up9, 32, strides=1)\n down10 = concatenate([Conv2D(32, (3, 3), activation='relu', padding='same')(conv9), conv9], axis=3) \n conv10 = resnet_block(down10, 32, strides=1) \n pool10 = MaxPooling2D(pool_size=(2, 2))(conv10)\n\n down11 = concatenate([Conv2D(64, (3, 3), activation='relu', padding='same')(pool10), conv8], axis=3)\n conv11 = resnet_block(down11, 64, strides=1)\n pool11 = MaxPooling2D(pool_size=(2, 2))(conv11)\n \n down12 = concatenate([Conv2D(128, (3, 3), activation='relu', padding='same')(pool11), conv7], axis=3)\n conv12 = resnet_block(down12, 128, strides=1)\n pool12 = MaxPooling2D(pool_size=(2, 2))(conv12)\n\n down13 = concatenate([Conv2D(256, (3, 3), activation='relu', padding='same')(pool12), conv6], axis=3)\n conv13 = resnet_block(down13, 256, strides=1)\n pool13 = MaxPooling2D(pool_size=(2, 2))(conv13)\n conv14 = aspp_block(pool13, 512)\n \n up15 = concatenate([Conv2DTranspose(256, (2, 2), strides=(2, 2), padding='same')(conv14), conv13], axis=3)\n conv15 = resnet_block(up15, 256, strides=1) \n \n up16 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv15), conv12], axis=3)\n conv16 = resnet_block(up16, 128, strides=1) \n\n up17 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv16), conv11], axis=3)\n conv17 = resnet_block(up17, 64, strides=1) \n \n up18 = concatenate([Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same')(conv17), conv10], axis=3)\n conv18 = resnet_block(up18, 32, strides=1) \n \n conv18 = aspp_block(conv18, 32)\n \n conv19 = Conv2D(1, (1, 1), activation='sigmoid')(conv18)\n model = Model(inputs=[inputs], outputs=[conv19])\n # model.compile(optimizer=adam_v2(lr=1e-4), loss=[loss], metrics=[dice_coef, iou_coef])\n model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4), loss=[loss], metrics=[dice_coef, iou_coef])\n return model\n\ndef segment(model_path, img):\n model = get_rwnet()\n model.load_weights(model_path)\n img_mask = model.predict(img, verbose=0)[0]\n img_mask = (img_mask[:, :, 0] * 255.).astype(np.uint8)\n return img_mask","repo_name":"lucasca95/uofl-mammography-backend","sub_path":"cronjob/segmentation.py","file_name":"segmentation.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"32980221648","text":"import discord\nimport random\nimport asyncio\nfrom discord import embeds\nfrom discord.ext import commands\n\nclass Help(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n \n @commands.command()\n async def help(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Help List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.casinohelp**\",value=\"Gamble a little bit, its fun\",inline=False)\n page1.add_field(name=\"**.customhelp**\", value=\"If you wanna see custom commands\",inline=False)\n page1.add_field(name=\"**.funhelp**\", value=\"If you wanna see all the random commands I have\",inline=False)\n page1.set_footer(text=\"@Mush if you wanna suggest something\")\n\n await ctx.send(embed=page1)\n\n @commands.command()\n async def funhelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Fun Commands List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n page1.add_field(name=\"**.mushball ''insert question here''** \",value=\"I answer yes or no questions\",inline=False)\n page1.add_field(name=\"**.kith `<@USER>`**\",value=\"Give someone a kith\",inline=False)\n page1.add_field(name=\"**.slap `<@USER>`**\",value=\"Slap someone, they probably deserve it\",inline=False)\n page1.add_field(name=\"**.pat `<@USER>`**\",value=\"Everyone deserves some headpats\",inline=False)\n page1.set_footer(text= \"@Mush if you want your own personal command but no guarantees i'll make it\")\n \n page2 = discord.Embed(title=\"Fun Commands List\", description=\"Page 2\", color=0x01a500)\n page2.set_author(name=\"MushBall\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.glock `<@USER>`**\",value=\"Some people just need to get glocked\",inline=False)\n page2.add_field(name=\"**.yeet `<@USER>`**\",value=\"I yeet a mf\",inline=False)\n page2.add_field(name=\"**.homies `<@USER>`**\", value=\"Always kiss your homies\",inline=False)\n page2.add_field(name=\"**.mushsleep `<@USER>`**\",value=\"I politely tell the person you @ to goto sleep\",inline=False)\n page2.add_field(name=\"**.salty `<@USER>`**\",value=\"For when someones being salty\",inline=False)\n page2.add_field(name=\"**.mushmatch `<@USER>`**\",value=\"Based off a very advanced algorithm and not a random number, I'll tell you the compatibility % of you and another person (I can rig this for a price)\",inline=False)\n page2.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page3 = discord.Embed(title=\"Fun Commands List\", description=\"Page 3\", color=0x01a500)\n page3.set_author(name=\"MushBall\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.afl**\",value=\"Jas fucked up once, and we don't let her forget\",inline=False)\n page3.add_field(name=\"**.milk**\", value=\"I hate milk, but I got a lot of gifs of it\",inline=False)\n page3.add_field(name=\"**.step `<@USER>`**\",value=\"Once again, I think this a degrading thing but I dont judge\",inline=False)\n page3.add_field(name=\"**.spit `<@USER>`**\",value=\"I think this is for the people that like degrading\",inline=False)\n page3.add_field(name=\"**.cry**\",value=\"Demon fighting hours\",inline=False)\n page3.set_footer(text=\"@Mush if you wanna suggest something\")\n\n\n page4 = discord.Embed(title=\"Fun Commands List\", description=\"Last Page\", color=0x01a500)\n page4.set_author(name=\"MushBall\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.mushcrypto**\",value=\"I give a summary of the crypto market today that I wrote and definitely didn't steal\",inline=False)\n page4.add_field(name=\"**.fuck**\", value=\"Just do it and see for yourself\",inline=False)\n page4.add_field(name=\"**.food**\",value=\"I suggest something random to eat/drink\",inline=False)\n page4.add_field(name=\"**.bar**\",value=\"I have a lot of alcoholic drinks to recommend ;)\",inline=False)\n page4.add_field(name=\"**.hi**\",value=\"Say hi to me, I get lonely\",inline=False)\n page4.add_field(name=\"**.bye**\",value=\"Be nice and say bye\",inline=False)\n page4.add_field(name=\"**.shots**\", value=\"SHOTS\",inline=False)\n page4.set_footer(text=\"@Mush if you wanna suggest something\")\n\n self.client.help_pages = [page1, page2, page3,page4]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n \n @commands.command()\n async def customhelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"Custom Commands List\", description=\"Use the buttons below to navigate between help pages.\", color=0x01a500)\n page1.set_author(name=\"MushBall\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n page1.add_field(name=\"**.yumo `<@USER>`**\",value=\"Slap someone\",inline=False)\n page1.add_field(name=\"**.cabby**\", value=\"I send random cabbage gifs\",inline=False)\n page1.add_field(name=\"**.chea**\",value=\"I send a gif of Chea\",inline=False)\n page1.add_field(name=\"**.moggles**\",value=\"Let me share some wisdom from Old Man Moggles\",inline=False)\n page1.add_field(name=\"**.annie**\",value=\"Get some plant facts from Annie\", inline=False)\n page1.add_field(name=\"**.angie**\",value=\"Say something nice to Ang! (If you'd like to add to this list @Mush or DM him)\",inline=False)\n page1.add_field(name=\"**.sleppy**\", value=\"Swag\", inline=False)\n page1.set_footer(text= \"@Mush if you want your own personal command but no guarantees i'll make it\")\n \n page2 = discord.Embed(title=\"Commands List\", description=\"Page 2\", color=0x01a500)\n page2.set_author(name=\"MushBall\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.salty `<@USER>`**\",value=\"If someones being salty\",inline=False)\n page2.add_field(name=\"**.dev**\", value=\"GREEK GOD SUMMER\", inline=False)\n page2.add_field(name=\"**.rio `<@USER>`**\",value=\"Give someone a kith\",inline=False)\n page2.add_field(name=\"**.pat**\", value=\"Pat someone\", inline=False)\n page2.add_field(name=\"**.patrick *playlist***\",value=\"Let me give you a song to listen to. Add *playlist* if you want the full playlist\",inline=False)\n page2.add_field( name=\"**.goose *playlist***\",value=\"Check out Goose's song of the day. Add *playlist* if you want the full playlist\",inline=False)\n page2.add_field(name=\"**.sarah**\", value=\"*NUGGIES*\", inline=False)\n \n page2.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page3 = discord.Embed(title=\"Commands List\", description=\"Page 3\", color=0x01a500)\n page3.set_author(name=\"MushBall\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.zhu `<@USER>`**\",value=\"Drink some joose\",inline=False)\n page3.add_field(name=\"**.bubu**\",value=\"Lemme give you the best pickup lines ever\", inline=False)\n page3.add_field(name=\"**.dahlia**\",value=\"Idk I just do nothing\",inline=False)\n page3.add_field(name=\"**.waylan**\", value=\"Simp time\", inline=False)\n page3.add_field(name=\"**.charie**\", value=\"**PRAISE VODKA**\", inline=False)\n page3.add_field(name=\"**.scribbles `<@USER>`**\", value=\"Glock a mf\", inline=False)\n page3.add_field(name=\"**.burg**\", value=\"I just make no sense\", inline=False)\n page3.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page4 = discord.Embed(title=\"Commands List\", description=\"Page 4\", color=0x01a500)\n page4.set_author(name=\"MushBall\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.jeff**\",value=\"Cute dancing bear\",inline=False)\n page4.add_field(name=\"**.oen**\",value=\"Just Oen being Oen\", inline=False)\n page4.add_field(name=\"**.soda**\",value=\"Soda being weird as always\",inline=False)\n page4.add_field(name=\"**.franny**\", value=\"No concert\", inline=False)\n page4.add_field(name=\"**.kit**\", value=\"Idk why she's so obssessed with milk\", inline=False)\n page4.add_field(name=\"**.jas**\", value=\"Jas crys a lot I guess\", inline=False)\n page4.add_field(name=\"**.ikalgo**\", value=\"He's wholesome (sometimes)\", inline=False)\n page4.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n page5 = discord.Embed(title=\"Commands List\", description=\"Last Page\", color=0x01a500)\n page5.set_author(name=\"MushBall\")\n page5.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page5.add_field(name=\"**.capi**\", value=\"Goose is all hers\", inline=False)\n page5.add_field(name=\"**.nate `<@USER>`**\", value=\"Nate likes spitting on people\", inline=False)\n page5.add_field(name=\"**.anise `<@USER>`**\", value=\"Anise likes stepping on people\", inline=False)\n page5.set_footer(text=\"@Mush if you want your own personal command but no guarantees i'll make it\")\n\n self.client.help_pages = [page1, page2, page3,page4,page5]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n\n @commands.command()\n async def casinohelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"**Page 1 | __Games__**\", color=0x01a500)\n page1.set_author(name=\"Commands List\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.coinflip `` ``**\", value=\"Gamble on a coinflip *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.highlow `` ``**\", value=\"Bet on wheter a randum number is going to be high or low *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.blackjack ``**\", value=\"Lets see if you can beat the dealer *win 2x your bet*\", inline=False)\n page1.add_field(name=\"**.slots ``**\", value=\"Try your luck playing slots *win 10x your bet*\", inline=False)\n page1.add_field(name=\"**.cups `1-4` ``**\", value=\"Guess which cup the ball is under *win 3x your bet*\", inline=False)\n page1.add_field(name=\"**.lottery**\", value=\"For when you're feeling lucky\", inline=False)\n page1.set_footer(text=\"@Mush if you wanna suggest something\")\n \n page2 = discord.Embed(title=\"**Page 2 | __2 Player Games__**\", color=0x01a500)\n page2.set_author(name=\"Commands List\")\n page2.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page2.add_field(name=\"**.rps `<@USER>` ``**\", value=\"Play rock, paper, scissors with someone *win whatever you bet*\", inline=False)\n page2.add_field(name=\"**.ttt `<@USER>` ``**\", value=\"Play tic tac toe with someone *win whatever you bet*\", inline=False)\n page2.add_field(name=\"**.connect4 `` ``**\", value=\"Play connect4 with me or with someone *win whatever you bet*\", inline=False)\n page2.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page3 = discord.Embed(title=\"**Page 3 | __Casino Commands__**\", color=0x01a500)\n page3.set_author(name=\"Commands List\")\n page3.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page3.add_field(name=\"**.balance**\", value=\"Check your current balance\", inline=False)\n page3.add_field(name=\"**.deposit**\", value=\"Deposits your money into your bank\", inline=False)\n page3.add_field(name=\"**.withdraw**\", value=\"Withdraws money into your wallet\", inline=False)\n page3.add_field(name=\"**.daily**\", value=\"Get your daily free money\", inline=False)\n page3.add_field(name=\"**.rob `<@USER>`**\", value=\"Steal someones money\", inline=False)\n page3.add_field(name=\"**.shophelp**\", value=\"Checkout the giftshop\", inline=False)\n page3.add_field(name=\"**.leaderboard**\", value=\"See who's the richest\", inline=False)\n page3.set_footer(text=\"@Mush if you wanna suggest something\")\n\n page4 = discord.Embed(title=\"**Page 4 | _Shop Commands__**\", color=0x01a500)\n page4.set_author(name=\"Commands List\")\n page4.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page4.add_field(name=\"**.shop**\", value=\"See what roles are for sale\", inline=False)\n page4.add_field(name=\"**.buy `<@ROLE>`\\`'ROLE NAME'`**\", value=\"Buy a role from the shop. If role isn't mentionably surround role name with quotes\", inline=False)\n page4.set_footer(text=\"@Mush if you wanna suggest something\")\n\n self.client.help_pages = [page1, page2, page3, page4]\n buttons = [u\"\\u2B05\", u\"\\u27A1\"] # skip to start, left, right, skip to end\n current = 0\n msg = await ctx.send(embed=self.client.help_pages[current])\n \n for button in buttons:\n await msg.add_reaction(button)\n \n while True:\n try:\n reaction, user = await self.client.wait_for(\"reaction_add\", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0)\n\n except asyncio.TimeoutError:\n return \n\n else:\n previous_page = current\n \n if reaction.emoji == u\"\\u2B05\":\n if current > 0:\n current -= 1\n \n elif reaction.emoji == u\"\\u27A1\":\n if current < len(self.client.help_pages)-1:\n current += 1\n\n for button in buttons:\n await msg.remove_reaction(button, ctx.author)\n\n if current != previous_page:\n await msg.edit(embed=self.client.help_pages[current])\n\n @commands.command()\n async def musichelp(self,ctx):\n #Help Pages\n page1 = discord.Embed(title=\"**__Music Help__**\", color=0x01a500)\n page1.set_author(name=\"Commands List\")\n page1.set_thumbnail(url=\"https://cdn.frankerfacez.com/emoticon/388352/4\")\n page1.add_field(name=\"**.play **\", value=\"Play a song from YouTube (If a song is already playing, your song gets added to the queue)\", inline=False)\n page1.add_field(name=\"**.skip**\", value=\"Skips the current song playing\", inline=False)\n page1.add_field(name=\"**.clear**\", value=\"Clears the queue\", inline=False)\n page1.add_field(name=\"**.queue** \", value=\"Shows the song queue (Add page # to go through pages)\", inline=False)\n page1.add_field(name=\"**.delete** \", value=\"Deletes a song in the queue\", inline=False)\n \n await ctx.send(embed=page1)\n \n\n \ndef setup(client):\n client.add_cog(Help(client))","repo_name":"MushhRa/MushBall-Discord-Bot","sub_path":"cogs/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":17691,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"35780059909","text":"#!/usr/bin/env python3\n\n# https://github.com/engineer-man/youtube/blob/master/105/stick_hero.py\n\nfrom ppadb.client import Client as AdbClient\n\nfrom PIL import Image\nimport numpy\nimport time\n\nadb = AdbClient(host='127.0.0.1', port=5037)\ndevices = adb.devices()\n\nif len(devices) == 0:\n print('no device attached')\n quit()\n\ndevice = devices[0]\n\n#while True:\nimage = device.screencap()\nwith open('screen.png', 'wb') as f:\n f.write(image)\nimage = Image.open('screen.png')\nimage = numpy.array(image, dtype=numpy.uint8)","repo_name":"JoSSte/pyFlowfreeSolver","sub_path":"flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"69940792804","text":"\"\"\"\nDataclasses that are relevant in the context of the content_evaluation.\n\"\"\"\nfrom dataclasses import dataclass, replace\nfrom typing import Generic, Optional, TypeVar\n\nfrom maus.edifact import EdifactFormat, EdifactFormatVersion\n\n_BodyT = TypeVar(\"_BodyT\")\n\"\"\"\nthe type of the data on which the evaluations are performed\n\"\"\"\n\n\n@dataclass\nclass EvaluatableData(Generic[_BodyT]):\n \"\"\"\n Data that can be processed/evaluated by an evaluator. They must not change during a content_evaluation run.\n The evaluatable data act as a flexible container to pass information that might be necessary for the\n content_evaluation. As of now (because our content_evaluation capabilities are quite limited) the only information\n provided is the meta seed of the message itself. But in the future the data provided might grow.\n \"\"\"\n\n body: _BodyT #: the body of the message that is being validated in the respective format (e.g. an edifact_seed)\n edifact_format: EdifactFormat #: the format of the evaluatable message (e.g. UTILMD)\n edifact_format_version: EdifactFormatVersion #: the format version of the evaluable data (e.g. FV2210)\n # ideas for what else could go here:\n # - pruefidentifikator to tweak the content_evaluation depending on the situation?\n\n\n# pylint:disable=too-few-public-methods\nclass EvaluatableDataProvider(Generic[_BodyT]):\n \"\"\"\n This is just a dummy class that is used for dependency injection.\n Use it to call binder.bind_to_provider(EvaluatableDataProvider, func_that_returns_evaluatable_data_goes_here)\n during dependency injection.\n See https://github.com/ivankorobkov/python-inject#why-no-scopes\n \"\"\"\n\n\n@dataclass\nclass EvaluationContext:\n \"\"\"\n A content_evaluation context describes the setting in which a condition shall be evaluated. The content_evaluation\n context might have different values for the same condition in one content_evaluation run. E.g. if the purpose of the\n condition is to make sure that every Zähler with zähler type \"EHZ\" has some properties the context of the\n content_evaluation is one zähler entry although there might be multiple zählers present in the message.\n \"\"\"\n\n scope: Optional[\n str\n ] # jsonpath that refers to the scope of the content_eval. If None, then \"$\" = entire message is used as scope.\n\n\ndef copy_evaluation_context(context: EvaluationContext) -> EvaluationContext:\n \"\"\"\n Returns a deep copy of the provided context.\n This allows you to create a copy of a context instead of modifying the original context (as EvaluationContexts are\n \"pass by reference\")\n :param context:\n :return: a deep copy of the context\n \"\"\"\n return replace(context)\n","repo_name":"Hochfrequenz/ahbicht","sub_path":"src/ahbicht/content_evaluation/evaluationdatatypes.py","file_name":"evaluationdatatypes.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"27683143594","text":"#\n# examples for SourceUndulator to be used in ShadowOui\n#\nimport numpy\nfrom syned.storage_ring.electron_beam import ElectronBeam\n\nfrom shadow4.sources.undulator.s4_undulator import S4Undulator\nfrom shadow4.sources.undulator.s4_undulator_light_source import S4UndulatorLightSource\n\nif __name__ == \"__main__\":\n\n\n from srxraylib.plot.gol import plot, set_qt\n set_qt()\n\n do_plots = True\n\n\n ebeam = ElectronBeam(energy_in_GeV=6.04,\n energy_spread = 0.0,\n current = 0.2,\n number_of_bunches = 400,\n moment_xx=(400e-6)**2,\n moment_xxp=0.0,\n moment_xpxp=(10e-6)**2,\n moment_yy=(10e-6)**2,\n moment_yyp=0.0,\n moment_ypyp=(4e-6)**2 )\n\n und = S4Undulator(\n K_vertical=0.25, # syned Undulator parameter\n period_length=0.032, # syned Undulator parameter\n number_of_periods=50, # syned Undulator parameter\n emin=10490.0, # Photon energy scan from energy (in eV)\n emax=10510.0, # Photon energy scan to energy (in eV)\n ng_e=3, # Photon energy scan number of points\n maxangle=0.015, # Maximum radiation semiaperture in RADIANS\n ng_t=100, # Number of points in angle theta\n ng_p=11, # Number of points in angle phi\n ng_j=20, # Number of points in electron trajectory (per period) for internal calculation only\n code_undul_phot=\"internal\", # internal, pysru, srw\n flag_emittance=0, # when sampling rays: Use emittance (0=No, 1=Yes)\n flag_size=2, # when sampling rays: 0=point,1=Gaussian,2=FT(Divergences)\n )\n\n\n print(\"gamma: \", ebeam.gamma())\n print(\"resonance: \", und.resonance_energy(ebeam.gamma()))\n und.set_energy_monochromatic(und.resonance_energy(ebeam.gamma()))\n # sourceundulator._MAXANGLE *= 1.2\n\n # print(und.info())\n\n ls = S4UndulatorLightSource(name=\"\", electron_beam=ebeam, magnetic_structure=und,\n nrays=15000,seed=5655452)\n beam = ls.get_beam()\n\n print(ls.info())\n #\n # plot\n #\n if do_plots:\n from srxraylib.plot.gol import plot_image, plot_scatter\n\n radiation,photon_energy, theta,phi = ls.get_radiation_polar()\n plot_image(radiation[0],1e6*theta,phi,aspect='auto',title=\"intensity\",xtitle=\"theta [urad]\",ytitle=\"phi [rad]\")\n\n radiation_interpolated,photon_energy, vx,vz = ls.get_radiation_interpolated_cartesian()\n plot_image(radiation_interpolated[0],vx,vz,aspect='auto',title=\"intensity interpolated in cartesian grid\",xtitle=\"vx\",ytitle=\"vy\")\n\n polarization = ls.get_result_polarization()\n plot_image(polarization[0],1e6*theta,phi,aspect='auto',title=\"polarization\",xtitle=\"theta [urad]\",ytitle=\"phi [rad]\")\n\n\n\n print(\"Beam intensity: \",beam.get_column(23).sum())\n print(\"Beam intensity s-pol: \",beam.get_column(24).sum())\n print(\"Beam intensity: p-pol\",beam.get_column(25).sum())\n\n #\n # plot\n #\n if do_plots:\n plot_scatter(1e6*beam.rays[:,0],1e6*beam.rays[:,2],title=\"real space\",xtitle=\"X [um]\",ytitle=\"Z [um]\",show=False)\n plot_scatter(1e6*beam.rays[:,3],1e6*beam.rays[:,5],title=\"divergence space\",xtitle=\"X [urad]\",ytitle=\"Z [urad]\",show=True)\n\n plot(ls.get_photon_size_distribution()[0]*1e6,\n ls.get_photon_size_distribution()[1],\n title=\"Photon size distribution\",xtitle=\"R [um]\",ytitle=\"Intensity [a.u.]\")\n\n # check the correct size sampling (values must agree for FLAG_SIZE=1!!!)\n x_photon = beam.rays[:,0]\n z_photon = beam.rays[:,2]\n R = numpy.sqrt(x_photon**2 + z_photon**2)\n print(\">> s_phot, Std R\", ls.get_result_photon_size_sigma(), numpy.sqrt((R ** 2).sum() / (R.size - 1)))\n print(\">> s_phot, Std X\", ls.get_result_photon_size_sigma(), numpy.sqrt((x_photon ** 2).sum() / (x_photon.size - 1)))\n print(\">> s_phot, Std Z\", ls.get_result_photon_size_sigma(), numpy.sqrt((z_photon ** 2).sum() / (z_photon.size - 1)))\n","repo_name":"oasys-kit/shadow4","sub_path":"examples/sources/example_source_undulator.py","file_name":"example_source_undulator.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"26220189954","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nfrom sklearn.linear_model import LogisticRegression\nimport statsmodels.api as sm\nfrom scipy import stats\nfrom statsmodels.stats.proportion import proportions_ztest\nfrom statsmodels.stats.weightstats import ttest_ind\nimport seaborn as sns\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import tree\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.model_selection import KFold, cross_val_score\nfrom sklearn.decomposition import PCA\n\ndf = pd.read_csv('combined_ri_data.csv')\n#limit to one to four family dwellings\ndf = df[df['property_type_name']== 'One-to-four family dwelling (other than manufactured housing)']\n#limit to co_applicant_race == 'No co_applicant' \ndf = df[df['co_applicant_ethnicity_name'] == 'No co-applicant']\ndf['is_denial'] = (df['action_taken_name'] == 'Application denied by financial institution')\n\n#machine learning models\n'''\nclassifier to predict denial vs non denial\n'''\n#x = race, sex, income, loan amount, median hud income, county, census tract, tract_to_msamd_income, population, minority population\n#y = is_denied\n\ncategorical_features = ['applicant_race_name_1', 'applicant_sex_name', 'county_name', 'hud_median_family_income', 'census_tract_number']\ncontinuous_features = ['applicant_income_000s', 'loan_amount_000s']\nlabel = ['is_denial']\nreal_df = df[label + continuous_features]\nfor feature in categorical_features:\n\tsub_df = pd.get_dummies(df[feature])\n\treal_df = pd.merge(real_df, sub_df, left_index=True, right_index=True)\n\t\nreal_df = real_df.fillna(0)\n\nreal_df = real_df.sample(10000)\n\nog_Y = real_df[label].values\nog_Y = np.reshape(og_Y, (len(og_Y),))\nog_X = real_df.drop(columns = ['is_denial'])\n\n\n#PCA with visualization\npca = PCA(n_components = 3)\nscale_x = (og_X - og_X.min(axis=0)) / (og_X.max(axis=0) - og_X.min(axis=0))\nscale_x = scale_x.fillna(0)\npca.fit(scale_x)\nreduced = pca.transform(scale_x)\n\nzero_ind = np.where(og_Y == 0)\none_ind = np.where(og_Y == 1)\n\nfig = plt.figure()\nax = fig.add_subplot(projection='3d')\n\nax.set_title('PCA applied to the HMDA Mortgage Data Sample')\nax.set_xlabel('Principle Component 1')\nax.set_ylabel('Principle Component 2')\nax.set_zlabel('Principle Component 3')\n\nax.scatter(reduced[zero_ind,0], reduced[zero_ind,1], reduced[zero_ind,2], c='orange', label = 'not denied')\nax.scatter(reduced[one_ind,0], reduced[one_ind,1], reduced[one_ind,2], c='blue', label = 'denied')\n\nplt.legend(loc=\"right\")\n\nplt.show()\n\nX, X_Test, Y, Y_Test = train_test_split(og_X, og_Y, test_size = 0.20)\n#Y_Test = Y_Test['is_denial'].values\n#Y = Y['is_denial'].values\nprint(' ')\nprint('dummy accuracy', 1- sum(Y_Test)/len(Y_Test))\n\n\n'''\n#Logistic Regression\nclf = LogisticRegression(random_state=0).fit(X,Y)\nY_Pred = clf.predict(X_Test)\nprint(clf.predict_proba(X_Test))\naccuracy = sum(Y_Pred == Y_Test)/len(Y_Pred)\nprint('log regression', accuracy)\nconfusion = confusion_matrix(Y_Test,Y_Pred)\nprint(confusion)\n\n\n#Decision Tree\nprint(' ')\nprint('Decision Tree')\ndecision_tree = tree.DecisionTreeClassifier().fit(X, Y)\nY_Pred = decision_tree.predict(X_Test)\ndecision_acc = sum((Y_Pred == Y_Test))/len(Y_Pred)\nprint(\"testing accuracy:\", decision_acc)\ndecision_fp = sum(((Y_Pred == 1) == (Y_Test == 0)))/len(Y_Pred)\nprint('FPR:',decision_fp)\nconfusion = confusion_matrix(Y_Test,Y_Pred)\nprint(confusion)\n\n\n#SVM\nprint(' ')\nprint('SVM')\nsvc = SVC(kernel='poly')\nsvc.fit(X, Y)\nY_Pred = svc.predict(X_Test)\nsvm_acc = sum((Y_Pred == Y_Test))/len(Y_Pred)\nprint(\"testing accuracy:\", svm_acc)\n\nsvm_fp = sum(((Y_Pred == 1) == (Y_Test == 0)))/len(Y_Pred)\nprint('FPR:', svm_fp)\n'''\n\n'''KNN'''\nprint(' ')\nprint('KNN')\nks = range(1,50, 5)\naccuracies = []\nfor k in ks:\n\tKNN = KNeighborsClassifier(n_neighbors=k)\n\tkf= KFold(n_splits=5)\n\tscore = cross_val_score(KNN,og_X,og_Y,cv=kf)\n\tprint(' ')\n\tprint('k=', k)\n\tprint(\"Cross Validation Scores are {}\".format(score))\n\tprint(\"Average Cross Validation score :{}\".format(score.mean()))\n\taccuracies.append(score.mean())\n\t'''\n\tKNN.fit(X, Y)\n\t#Y_Pred = KNN.predict(X_Test)\n\tY_Pred = (KNN.predict_proba(X_Test)[:,1] >= 0.5).astype(bool)\n\taccuracy = sum(Y_Pred == Y_Test)/len(Y_Pred)\n\t#accuracies.append(accuracy)\n\tprint('accuracy:', accuracy)\n\tconfusion = confusion_matrix(Y_Test,Y_Pred)\n\tprint('confusion:', confusion)\n\t'''\n\nplt.plot(ks, accuracies)\nplt.title(\"Average Cross Validation Accuracy for K-Nearest-Neighbors vs. K\")\nplt.ylabel(\"Accuracy (%)\")\nplt.xlabel(\"K\")\n#plt.ylim(0,1.1)\nplt.show()\nplt.show()\n\n\n\n\n\n","repo_name":"faleksic9/Loan-Approval-Prediction","sub_path":"final_deliverable/code/classifiers_copy.py","file_name":"classifiers_copy.py","file_ext":"py","file_size_in_byte":4656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10914630562","text":"from bisect import insort, bisect_left, bisect_right, bisect\nfrom collections import deque,Counter\nfrom datetime import datetime\nfrom itertools import islice\nimport numpy as np\nfrom numpy import median\nimport os, copy\nfrom ROOT import TDatime, TFile, TGraph\n\n################################################################################\n# Define comon path to input files (i.e. either EOS or local)\n\nlocal=False\ncommon_path='./root/' if local else '/eos/cms/store/group/phys_bphys/bpark/RootFiles4Run3Parking/'\n\n################################################################################\n\n# BBbar inclusive cross section \n# from http://www.lpthe.jussieu.fr/~cacciari/fonll/fonllform.html\nSigma_B = 4.6940e+11 # fb (femtobarn!!) \n\n# Fragmentation fraction for B+-\nfB = 0.4\n\n# Branching fraction for \"at least one rare B->Kee decay\" per event (simplified to 2 * 4.4E-7)\nBr_kee = 2*4.5e-7\n\n################################################################################\n# Dictionary that maps pT threshold to deltaR requirement at Level-1\ndr_dict = {\n 4.0:0.9,\n 4.5:0.9,\n 5.0:0.9,\n 5.5:0.8,\n 6.0:0.8,\n 6.5:0.8,\n 7.0:0.8,\n 7.5:0.7,\n 8.0:0.7,\n 8.5:0.7,\n 9.0:0.7,\n 9.5:0.6,\n 10.0:0.6,\n 10.5:0.6,\n 11.0:0.6,\n 11.5:0.5,\n 12.0:0.5,\n 12.5:0.5,\n 13.0:0.5,\n 13.5:0.4,\n 14.0:0.4,\n} \n\n################################################################################\n# Maximum HLT bandwidth in 2018 vs Linst, from Sara's presentation:\n# https://indico.cern.ch/event/1032638/contributions/4336416/\nmax_bw_hlt = {\n 2.2:1515,\n 2.0:1515,\n 1.7:1740,\n 1.5:1929,\n 1.3:2163.5,\n 1.1:2463,\n 0.9:2929,\n 0.6:3791, # Default TSG column?\n 0.7:3791,0.47:3791,0.24:3791 # NEED TO UPDATE FOR LOWER LINST???\n}\n\n################################################################################\n# Pairwise (L1,HLT) thresholds to avoid \"vertical regions\" in ROCs\nl1_threshold_list = np.arange(4, 11, 0.5).tolist()\nhlt_threshold_list = [4.0,4.0,4.0,4.0,4.0, # L1: 4.0->6.0\n 4.5,5.0,5.0,5.0,5.5, # L1: 6.5->8.5\n 6.0,6.5,6.5,6.5, # L1: 9.0->10.5\n ]\nhlt_threshold_dict = dict(zip(l1_threshold_list,hlt_threshold_list))\n\n################################################################################\n# List of PU values ...\n# ... that map to Linst values: 2.0, 1.7, 1.5, 1.3, 1.1, 0.9, 0.6E34\nnpu_list = [56, 48, 42, 36, 30, 25, 17]\n\n################################################################################\n# Parse .csv file to extract example \"luminosity profile\" for 2018\n\ndef extractLumiProfiles(original=False,max_duration=12*3600) :\n\n # Golden JSON\n #https://cmsoms.cern.ch/cms/runs/report?cms_run=324980&cms_run_sequence=GLOBAL-RUN\n #\"324980\": [[39, 917], [919, 954], [956, 968], [1005, 1042], [1044, 2340]],\n golden = [[53, 917], [919, 954], [956, 968], [1005, 1042], [1044, 2340]]\n\n # Parse csv file \n times = []\n lumis = []\n for line in open('LumiData/LumiData_2018_20200401.csv', 'r'):\n if line.find('324980:7321')==-1: continue\n\n line = line.rstrip().split(',')\n ls = line[1].split(':')[0]\n\n flag = False\n for lrange in golden:\n if int(ls) >= min(lrange) and int(ls) <= max(lrange): flag = True\n if not flag: continue\n\n time = line[2].split(' ')\n time = TDatime(int(time[0].split('/')[2])+2000, \n int(time[0].split('/')[0]), \n int(time[0].split('/')[1]), \n int(time[1].split(':')[0]), \n int(time[1].split(':')[1]), \n int(time[1].split(':')[2]))\n times.append(time.Convert())\n\n Linst = float(line[5])*0.0001\n lumis.append(Linst)\n \n # Start at zero\n min_time = min(times)\n times = [number - min_time for number in times]\n\n # Check if times are sorted\n if(times != sorted(times)):\n print(\"Times not sorted!\")\n quit()\n\n # Return originals, before smoothing or truncating\n if original: return times,lumis\n\n # Smooth with running median\n window = 11 # has to be odd\n lumis = RunningMedian(lumis,window) # shortens by window-1\n for i in range((window-1)/2): # pad\n lumis.insert(0,lumis[0])\n lumis.insert(-1,lumis[-1])\n\n # Truncate to 12 hours \n times,lumis = zip(*filter(lambda time: \n time[0] max_duration : continue\n graph.SetPoint(idx, time, max(0.,lumi))\n idx += 1\n graph.Write()\n \n # Write to file and close\n file.Write()\n file.Close()\n\n################################################################################\n# Utility methods\n\ndef ensureDir(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef hackRate(rate,which_lumi):\n #linst=[0.6,0.45,0.30,0.15]\n linst=[0.7,0.47,0.24,0.06]\n idx=None\n try: idx = linst.index(which_lumi)\n except ValueError: return rate\n if idx is not None and idx>0: return rate * linst[idx]/linst[0]\n else : return rate\n\ndef scaleGraph(graph,scale) :\n for i in range(graph.GetN()) :\n graph.SetPointY(i,graph.GetPointY(i)*scale)\n return graph\n\ndef RunningMedian(seq, M):\n\n # Running median, used to smooth lumi profiles\n # Taken from https://code.activestate.com/recipes/578480-running-median-mean-and-mode/\n\n seq = iter(seq)\n s = [] \n m = M // 2\n\n # Set up list s (to be sorted) and load deque with first window of seq\n s = [item for item in islice(seq,M)] \n d = deque(s)\n\n # Simple lambda function to handle even/odd window sizes \n median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5\n\n # Sort it in increasing order and extract the median (\"center\" of the sorted window)\n s.sort() \n medians = [median()] \n\n # Now slide the window by one point to the right for each new position (each pass through \n # the loop). Stop when the item in the right end of the deque contains the last item in seq\n for item in seq:\n old = d.popleft() # pop oldest from left\n d.append(item) # push newest in from right\n del s[bisect_left(s, old)] # locate insertion point and then remove old \n insort(s, item) # insert newest such that new sort is not required \n medians.append(median()) \n return medians\n","repo_name":"gitytakahas/Run3BparkingHLTStudies","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":10367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3256918788","text":"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n h = {\n '2': ['a', 'b', 'c'],\n '3': ['d', 'e', 'f'],\n '4': ['g', 'h', 'i'],\n '5': ['j', 'k', 'l'],\n '6': ['m', 'n', 'o'],\n '7': ['p', 'q', 'r', 's'],\n '8': ['t', 'u', 'v'],\n '9': ['w', 'x', 'y', 'z']\n }\n\t\t\n if len(digits) == 0:\n return []\n \t\t\n firstDigit = digits[0]\n firstDigitCharacters = h[firstDigit]\n\t\t\n furtherCombinations = self.letterCombinations(digits[1:])\n result = []\n\t\t\n if len(furtherCombinations) == 0:\n furtherCombinations.append(\"\")\n \n for ele in firstDigitCharacters:\n for char in furtherCombinations:\n result.append(ele + char)\n return result\n","repo_name":"sayankd21/CP2_CIPHERSCHOOLS","sub_path":"17_Letter_Combinations_of_a_Phone_number.py","file_name":"17_Letter_Combinations_of_a_Phone_number.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12134607432","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport time\n\nfrom src import InstaBot\nfrom src.check_status import check_status\nfrom src.feed_scanner import feed_scanner\nfrom src.follow_protocol import follow_protocol\nfrom src.unfollow_protocol import unfollow_protocol\n\nbot = InstaBot(\n login=\"molteo_de\",\n password=\"Uso75V79JpfC\",\n like_per_day=150,\n comments_per_day=0,\n tag_list=['tiefbau','hochbau', 'baugewerbe', 'bauindustrie', 'digitalisierung', 'bauprojekt', 'gartenbau', 'abbund', 'bauunternehmen', 'baustelle', 'hochtief', 'bauverband', 'baurecht', 'rohbau', 'baumesse'],\n tag_blacklist=['livemusic', 'music', 'concert', 'concerti', 'blaelv2'],\n max_like_for_one_tag=15,\n follow_per_day=0,\n unfollow_per_day=0,\n start_at_h=8,\n start_at_m=13,\n end_at_h=17,\n end_at_m=5\n )\n\nwhile True:\n\n print(\"# MODE 0 = ORIGINAL MODE BY LEVPASHA\")\n #print(\"## MODE 1 = MODIFIED MODE BY KEMONG\")\n #print(\"### MODE 2 = ORIGINAL MODE + UNFOLLOW WHO DON'T FOLLOW BACK\")\n #print(\"#### MODE 3 = MODIFIED MODE : UNFOLLOW USERS WHO DON'T FOLLOW YOU BASED ON RECENT FEED\")\n #print(\"##### MODE 4 = MODIFIED MODE : FOLLOW USERS BASED ON RECENT FEED ONLY\")\n #print(\"###### MODE 5 = MODIFIED MODE : JUST UNFOLLOW EVERYBODY, EITHER YOUR FOLLOWER OR NOT\")\n\n ################################\n ## WARNING ###\n ################################\n\n # DON'T USE MODE 5 FOR A LONG PERIOD. YOU RISK YOUR ACCOUNT FROM GETTING BANNED\n ## USE MODE 5 IN BURST MODE, USE IT TO UNFOLLOW PEOPLE AS MANY AS YOU WANT IN SHORT TIME PERIOD\n\n mode = 6\n\n print(\"You choose mode : %i\" %(mode))\n print(\"CTRL + C to cancel this operation or wait 30 seconds to start\")\n #time.sleep(30)\n\n if mode == 0:\n bot.new_auto_mod()\n\n elif mode == 1:\n check_status(bot)\n while bot.self_following - bot.self_follower > 200:\n unfollow_protocol(bot)\n time.sleep(10 * 60)\n check_status(bot)\n while bot.self_following - bot.self_follower < 400:\n while len(bot.user_info_list) < 50:\n feed_scanner(bot)\n time.sleep(5 * 60)\n follow_protocol(bot)\n time.sleep(10 * 60)\n check_status(bot)\n\n elif mode == 2:\n bot.bot_mode = 1\n bot.new_auto_mod()\n\n elif mode == 3:\n unfollow_protocol(bot)\n time.sleep(10 * 60)\n\n elif mode == 4:\n feed_scanner(bot)\n time.sleep(60)\n follow_protocol(bot)\n time.sleep(10 * 60)\n\n elif mode == 5:\n bot.bot_mode = 2\n unfollow_protocol(bot)\n\n elif mode == 6:\n bot.auto_mod()\n else:\n print(\"Wrong mode!\")\n","repo_name":"stammi922/Instabot","sub_path":"real.py","file_name":"real.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"70004584804","text":"import cvzone\nimport os\nimport cv2\nfrom cvzone.SelfiSegmentationModule import SelfiSegmentation\nimport app\n\ndef change_background():\n cap = cv2.VideoCapture(0)\n cap.set(3,640)\n cap.set(4,480)\n segmentor = SelfiSegmentation()\n fps_reader=cvzone.FPS()\n\n bckimg_lis=os.listdir(r'E:\\OpenCVProject_Flask\\static\\background')\n\n lis=[(0,0,0)]\n for i in bckimg_lis:\n img=cv2.imread(r'E:\\OpenCVProject_Flask\\static\\background\\{}'.format(i))\n img=cv2.resize(img,(640,480))\n lis.append(img)\n id=0\n\n while True:\n _,frame = cap.read()\n frame=cv2.flip(frame,1)\n # print(frame.shape)\n imgOut = segmentor.removeBG(frame,lis[id],threshold=0.1)\n stack_img=cvzone.stackImages([frame,imgOut],2,1)\n _,stack_img=fps_reader.update(stack_img)\n cv2.imshow(\"Image\",stack_img)\n\n key=cv2.waitKey(1)\n\n if key == ord(\"d\"): ## d == for change background\n if id Optional[Node]:\n astparser = self.parser\n # given an input file, parse it into an AST object\n lines = None\n fname = infile.name\n with open(infile, \"r\") as f:\n lines = \"\".join([line for line in f])\n try:\n tree = ast.parse(lines)\n return astparser.visit(tree)\n except SyntaxError as e:\n e.filename = fname\n message = \"Syntax Error: {}. Line {:d} Col {:d}\".format(\n str(e), e.lineno, e.offset\n )\n astparser.errors.append(ParseError(message))\n return None\n\n def typecheck(self, ast: Node):\n # given an AST object, typecheck it\n # typechecking mutates the AST, adding types and errors\n self.typechecker.visit(ast)\n return ast\n\n def emitPython(self, ast: Node):\n backend = PythonBackend()\n backend.visit(ast)\n return backend.builder\n\n def emitLLVM(self, ast: Node):\n backend = LLVMBackend()\n ir = backend.visit(ast)\n return ir\n","repo_name":"anihm136/chocollvm","sub_path":"compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"52"}
+{"seq_id":"30548929712","text":"import sys\nimport os\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nfrom flask_api import status\n\nfrom unittest import TestCase\nfrom mock import patch, MagicMock, PropertyMock\n\nsys.modules['pyrebase'] = MagicMock()\nsys.modules['flask_pymongo'] = MagicMock()\nsys.modules['requests'] = MagicMock()\nsys.modules['gridfs'] = MagicMock()\nfrom src.settings.application import app\n\nclass TestSearch(TestCase):\n\n PRODUCTS = [\n {\"_id\": \"5c06f868556f89598152f2ec\",\n \"name\": \"Producto Test1\",\n \"description\": \"Producto de prueba\",\n \"images\": \"\",\n \"price\": 50,\n \"category\": \"Categoría Test\",\n \"ubication\": \"Ubicación Test\",\n \"latitude\": \"-34.583540\",\n \"longitude\": \"-58.406081\",\n \"units\": 1,\n \"user_id\": \"5c06f868556f89598152f2eb\"},\n {\"_id\": \"5c06f868556f89598152f2eb\",\n \"name\": \"Producto Test2\",\n \"description\": \"Producto de prueba\",\n \"images\": \"\",\n \"price\": 50,\n \"category\": \"Categoría Test\",\n \"ubication\": \"Ubicación Test\",\n \"latitude\": \"-34.583540\",\n \"longitude\": \"-58.406081\",\n \"units\": 1,\n \"user_id\": \"5c06f868556f89598152f2eb\"}\n ]\n USER = {'display_name': 'display_name',\n 'email': 'email',\n 'password': 'password',\n 'phone': 'phone',\n 'registration_id': 'registration_id',\n 'rating': 1}\n\n def setUp(self):\n app.testing = True\n self.app = app.test_client()\n self.app.environ_base['HTTP_AUTHORIZATION'] = ' testToken'\n\n def tearDown(self):\n pass\n\n @patch('src.routes.search.Search.get_mongo')\n @patch('src.routes.search.Search.get_firebase')\n def test_get_ok(self, mock_get_firebase, mock_get_mongo):\n mockAux = MagicMock()\n mockAux.refresh.return_value = {'refreshToken': 'testToken', 'userId': 'userId'}\n mock_get_firebase.return_value = mockAux\n mockAux.auth.return_value = mockAux\n\n mockProducts = MagicMock()\n mockProducts.find.return_value = TestSearch.PRODUCTS\n\n mockDB = MagicMock()\n p = PropertyMock(return_value = mockProducts)\n type(mockDB).products = p\n\n mockUsers = MagicMock()\n mockUsers.find_one.return_value = TestSearch.USER\n\n p1 = PropertyMock(return_value = mockUsers)\n type(mockDB).users = p1\n\n mockMongo = MagicMock()\n mock_get_mongo.return_value = mockMongo\n type(mockMongo).db = PropertyMock(return_value = mockDB)\n\n response = self.app.get('http://127.0.0.1:8000/products/search?name=rod&description=prue&latitude=-34.583540&longitude=-58.406081&lowest_price=49&greatest_price=50&category=ate')\n assert status.is_success(response.status_code)","repo_name":"estanislaoledesma/app-server-meli","sub_path":"test/testSearch.py","file_name":"testSearch.py","file_ext":"py","file_size_in_byte":3085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"36594048348","text":"import sys\nimport glob\nimport os\nimport numpy as np\nimport cv2\nfrom cv2 import aruco\n\n\nclass IntrinsicCalibration:\n def __init__(self, dict_aruco=cv2.aruco.DICT_4X4_250, sqWidth=11, sqHeight=8, checkerSquareSize=0.022,\n markerSquareSize=0.016, criteria_eps=1e-9, criteria_count=10000):\n # Initialize ChArUco Board size values: default DINA4\n # Visit: https://calib.io/pages/camera-calibration-pattern-generator\n # To create: calib.io_charuco_279x215_8x11_24_DICT_4X4.pdf\n # Initialize dictionary, see more in OpenCV\n self.dict = dict_aruco\n # Amount of squares in width\n self.sqWidth = sqWidth\n # Amount of squares in heights\n self.sqHeight = sqHeight\n # Size of checker square on printed ChArUco board in meter\n self.checkerSquareSize = checkerSquareSize\n # Size of marker square on printed ChArUco board in meter\n self.markerSquareSize = markerSquareSize\n self.criteria_eps = criteria_eps\n self.criteria_count = criteria_count\n\n @staticmethod\n def readFileList(imgFolder, ImgPattern=\"*.PNG\"):\n # Read all PNG files in folder\n imgFileList = glob.glob(os.path.join(imgFolder, ImgPattern))\n imgFileList.sort()\n return imgFileList\n\n def calibration(self, imgFolder='CalibrationImages/Intrinsic', distImgFolder='CalibrationImages/Distorted'):\n # Retrieve Images\n imgFileList = self.readFileList(imgFolder)\n # All Charuco Corners\n allCorners = []\n # All Charuco Ids\n allIds = []\n decimator = 0\n # Retrieve dictionary\n dictionary = aruco.getPredefinedDictionary(self.dict)\n board = cv2.aruco.CharucoBoard_create(self.sqWidth, self.sqHeight, self.checkerSquareSize,\n self.markerSquareSize, dictionary)\n # Loop through images\n for i in imgFileList:\n print(\"Reading %s\" % i)\n # Load image to grayscale\n img = cv2.imread(i)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Detect markers\n [markerCorners, markerIds, rejectedImgPoints] = cv2.aruco.detectMarkers(gray, dictionary)\n # Draw markers\n if len(markerCorners) > 0:\n [ret, charucoCorners, charucoIds] = cv2.aruco.interpolateCornersCharuco(markerCorners, markerIds, gray,\n board)\n if charucoCorners is not None and charucoIds is not None and len(charucoCorners) > 3:\n allCorners.append(charucoCorners)\n allIds.append(charucoIds)\n\n cv2.aruco.drawDetectedMarkers(img, markerCorners, markerIds, [0, 255, 0])\n cv2.aruco.drawDetectedCornersCharuco(img, charucoCorners, charucoIds, [0, 0, 255])\n\n cv2.namedWindow('Frame', cv2.WINDOW_NORMAL)\n cv2.imshow('Frame', img)\n cv2.waitKey(0) # any key\n decimator += 1\n print(\"NumImg:\", len(allCorners))\n imsize = img.shape\n print(imsize)\n # Try Calibration\n try:\n # , aa, bb, viewErrors\n # Calibrate camera\n [ret, cameraMatrix, disCoeffs, rvecs, tvecs, _, _,\n perViewErrors] = cv2.aruco.calibrateCameraCharucoExtended(\n allCorners, allIds, board, (imsize[0], imsize[1]),\n None, None, flags=cv2.CALIB_RATIONAL_MODEL,\n criteria=(cv2.TERM_CRITERIA_EPS & cv2.TERM_CRITERIA_COUNT, self.criteria_count, self.criteria_eps))\n # Print computed calibration results\n print(\"Rep Error:\", ret)\n print(\"Camera Matrix:\", cameraMatrix)\n print(\"Per View Errors:\", perViewErrors)\n print(\"Distortion Coefficients:\", disCoeffs)\n print(\"R vecs:\", rvecs)\n # Save calibration results in dedicated folder for numpy data of calibration\n np.savez('CalibrationNumpyData/intrinsic_calibration.npz', ret=ret, mtx=cameraMatrix, dist=disCoeffs,\n rvecs=rvecs, tvecs=tvecs)\n # Undistort the images\n imgDistortFolder = distImgFolder\n imgDistortFilelist = self.readFileList(imgDistortFolder)\n img_num = 0\n # Loop through images to undistort\n for j in imgDistortFilelist:\n imgDistort = cv2.imread(j)\n h = imgDistort.shape[0]\n w = imgDistort.shape[1]\n newcameramtx, roi = cv2.getOptimalNewCameraMatrix(cameraMatrix, disCoeffs, (w, h), 1, (w, h))\n print('Image cropped', j)\n # Undistort\n dst = cv2.undistort(imgDistort, cameraMatrix, disCoeffs, None)\n print('Image undistorted', j)\n imgDistortFilename = os.path.join(imgDistortFolder, '/undistort', str(img_num) + '.png')\n cv2.imwrite(imgDistortFilename, dst)\n print('Image saved', j)\n img_num = img_num + 1\n\n except ValueError as e:\n print(e)\n except NameError as e:\n print(e)\n except AttributeError as e:\n print(e)\n except:\n print(\"calibrateCameraCharuco fail:\", sys.exc_info()[0])\n # Close windows\n print(\"Press any key on window to exit\")\n cv2.waitKey(0) # any key\n cv2.destroyAllWindows()\n","repo_name":"merlzbert/SkinScan","sub_path":"Calibrations/.ipynb_checkpoints/IntrinsicCalibration-checkpoint.py","file_name":"IntrinsicCalibration-checkpoint.py","file_ext":"py","file_size_in_byte":5476,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"}
+{"seq_id":"42203521490","text":"import sys\ninput = sys.stdin.buffer.readline\ndef I(): return(list(map(int,input().split())))\ndef sieve(n):\n\ta=[1]*n\n\tfor i in range(2,n):\n\t if a[i]:\n\t for j in range(i*i,n,i):\n\t a[j]=0\n\treturn a\n\nfor __ in range(int(input())):\n\tn=int(input())\n\tarr=I()\n\tarr.sort()\n\tcurrmax=0\n\tans=0\n\tfor i in range(n):\n\t\tcurrmax=max(arr[i],currmax)\n\t\tif currmax<=(i+1):ans=i+1\n\tprint(ans+1)\n\t\n\n\n\n","repo_name":"vishwesh-D-kumar/codeforces_submissions","sub_path":"1358/b/81508017.py","file_name":"81508017.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"105376746","text":"import unittest\nfrom typing import List, Type, Union, NamedTuple, Any\nfrom dataclasses import dataclass\nfrom copy import copy, deepcopy\n\n\nclass Value(object):\n @property\n def value(self):\n return self._value\n\n def __init__(self, value: Union[str, int]):\n if value == 0 or value == '0':\n self._value = 0\n elif value == 1 or value == '1':\n self._value = 1\n elif value == \"D\" or value == \"d\":\n self._value = \"D\"\n elif value == \"D'\" or value == \"d'\":\n self._value = \"D'\"\n elif value == \"U\" or value == \"u\":\n self._value = \"U\"\n else:\n raise ValueError(f\"Cannot be turned into error: {value}\")\n\n def __eq__(self, other):\n if self.value == 1:\n if other == 1 or other == '1':\n return True\n elif self.value == 0:\n if other == 0 or other == '0':\n return True\n elif self.value == 'U':\n if other == 'U' or other == 'u':\n return True\n elif self.value == 'D':\n if other == 'd' or other == 'D':\n return True\n elif self.value == \"D'\":\n if other == \"d'\" or other == \"D'\":\n return True\n return False\n\n def __and__(self, other):\n if self == 1:\n if other == 1:\n return Value('1')\n if other == 'U':\n return Value('U')\n return Value('0')\n\n def __or__(self, other):\n if self == 1 or other == 1:\n return Value(1)\n if self == 'U' or other == 'U':\n return Value('U')\n return Value(0)\n\n def __invert__(self):\n if self == 1:\n return Value(0)\n if self == 0:\n return Value(1)\n if self == 'D':\n return Value(\"D'\")\n if self == \"D'\":\n return Value('D')\n return Value('U')\n\n def __str__(self):\n return str(self.value)\n\n def __repr__(self):\n return repr(self.value)\n\n # def __hash__(self):\n # return hash(self.value)\n\n\nclass Node(object):\n def __init__(self, gate: 'Gate'):\n self.gate: Gate = gate\n self.gate.node: Node = self\n # self.name: str = gate.name\n self.gate_type: str = gate.type\n self.update = gate.update\n self.logic = gate.logic\n self.type: str = 'wire'\n self.input_nodes: List[Node] = []\n self.output_nodes: List[Node] = []\n self.stuck_at: Union[None, Value] = None\n self.get_logic = gate.get_logic\n\n @property\n def name(self):\n return self.gate.name\n\n @property\n def value(self):\n return self.gate.value\n\n @value.setter\n def value(self, val: Value):\n self.gate.value = val\n\n @property\n def value_new(self):\n return self.gate.value_new\n\n @value_new.setter\n def value_new(self, value: Value):\n self.gate.value_new = value\n\n @property\n def input_names(self):\n return [input_node.name for input_node in self.input_nodes]\n\n def __eq__(self, other: Union['Node', Any]):\n if type(other) == Node:\n if self.name == other.name:\n return True\n else:\n return False\n else:\n if self.value == other:\n return True\n else:\n return False\n\n # if self.value == other:\n # return True\n # else:\n # return False\n\n def __repr__(self):\n return self.name\n # return \"repr\"\n\n def __str__(self):\n return f\"{self.type}\\t{self.name} = {self.value}\"\n\n def __hash__(self):\n return hash(self.name)\n\n # def __del__(self):\n # del self.gate\n\n def reset(self):\n self.value = Value('U')\n self.value_new = Value('U')\n self.stuck_at = None\n\n def set(self, value: Value):\n self.value = value\n self.value_new = value\n\n def show_update(self):\n return \", \".join([str(node.value) for node in self.input_nodes]) + \\\n f\"equals {self.value}\"\n\n\nclass DummyNode(Node):\n def __init__(self, node: Node, stuck_at: Value):\n self.genuine = node\n gate_copy = copy(node.gate)\n super(DummyNode, self).__init__(gate=gate_copy)\n self.input_nodes = node.input_nodes\n self.stuck_at = stuck_at\n\n @property\n def name(self):\n return self.genuine.name + \" Dummy\"\n\n # @property\n # def value(self):\n\n\nclass Gate(object):\n def __init__(self, name: str, inputs=[]):\n self.input_names: List[str] = inputs\n self.name: str = name\n self.type: str = ''\n self.node: Union[Node, None] = None\n self._value: Value = Value('U')\n self._value_new: Value = Value('U')\n\n # return hash(self.name)\n\n def __repr__(self):\n return self.name\n\n def propagate(self, value):\n if value == 1 and self.stuck_at == 0:\n return Value(\"D\")\n elif value == 0 and self.stuck_at == 1:\n return Value(\"D'\")\n else:\n return value\n\n @property\n def value(self) -> Value:\n return self.propagate(self._value)\n\n @value.setter\n def value(self, value: Value):\n # self._value = value\n self._value = self.propagate(value)\n\n @property\n def value_new(self) -> Value:\n return self.propagate(self._value_new)\n\n @value_new.setter\n def value_new(self, value: Value):\n # self._value_new = value\n self._value_new = self.propagate(value)\n\n @property\n def input_nodes(self) -> List[Node]:\n return self.node.input_nodes\n\n @property\n def output_nodes(self) -> List[Node]:\n return self.node.output_nodes\n\n @property\n def stuck_at(self) -> Union[None, Value]:\n return self.node.stuck_at\n\n def update(self):\n if self.value_new == 1 and self.stuck_at == 0:\n self.value = Value(\"D\")\n elif self.value_new == 0 and self.stuck_at == 1:\n self.value = Value(\"D'\")\n else:\n self.value = self.value_new\n\n def logic(self):\n # Do not change\n pass\n\n def get_logic(self):\n return self._value\n\n @dataclass\n class Count:\n zero: int = 0\n one: int = 0\n unknown: int = 0\n d: int = 0\n dprime: int = 0\n input: int = 0\n\n @property\n def count(self) -> Count:\n count = self.Count()\n for node in self.input_nodes:\n count.input += 1\n if node == 0:\n count.zero += 1\n elif node == 1:\n count.one += 1\n elif node == \"d'\":\n count.dprime += 1\n elif node == \"d\":\n count.d += 1\n elif node == 'u':\n count.unknown += 1\n else:\n raise ValueError\n return count\n\n\nclass AndGate(Gate):\n def __init__(self, name, inputs=[]):\n super(AndGate, self).__init__(name, inputs)\n self.type = \"AND\"\n\n def logic(self):\n # print(\"And gate logic run\")\n count = self.count\n if count.zero:\n self.value_new = Value(0)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d and count.dprime:\n self.value_new = Value(0)\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(1)\n\n def get_logic(self):\n # print(\"And gate logic run\")\n count = self.count\n if count.zero:\n return Value(0)\n elif count.unknown:\n return Value('U')\n elif count.d and count.dprime:\n return Value(0)\n elif count.d:\n return Value(\"D\")\n elif count.dprime:\n return Value(\"D'\")\n else:\n return Value(1)\n\n\nclass NandGate(AndGate):\n def __init__(self, name, inputs=[]):\n super(AndGate, self).__init__(name, inputs)\n self.type = \"NAND\"\n\n def logic(self):\n super(NandGate, self).logic()\n self.value_new = ~self.value_new\n\n def get_logic(self):\n return ~super(NandGate, self).get_logic()\n\n\nclass OrGate(Gate):\n def __init__(self, name, inputs=[]):\n super(OrGate, self).__init__(name, inputs)\n self.type = \"OR\"\n\n def logic(self):\n count = self.count\n if count.one:\n self.value_new = Value(1)\n elif count.d and count.dprime:\n self.value_new = Value(1)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(0)\n\n def logic(self):\n count = self.count\n if count.one:\n self.value_new = Value(1)\n elif count.d and count.dprime:\n self.value_new = Value(1)\n elif count.unknown:\n self.value_new = Value('U')\n elif count.d:\n self.value_new = Value(\"D\")\n elif count.dprime:\n self.value_new = Value(\"D'\")\n else:\n self.value_new = Value(0)\n\n\nclass NorGate(OrGate):\n def __init__(self, name, inputs=[]):\n super(OrGate, self).__init__(name, inputs)\n self.type = \"NOR\"\n\n def get_logic(self):\n return ~super(NorGate, self).get_logic()\n\n\nclass NotGate(Gate):\n def __init__(self, name, inputs=[]):\n super(NotGate, self).__init__(name, inputs)\n self.type = \"NOT\"\n\n def logic(self):\n self.value_new = ~self.input_nodes[0].value\n\n def get_logic(self):\n return ~self.input_nodes[0].value\n\n\nclass XorGate(Gate):\n def __init__(self, name, inputs=[]):\n super(XorGate, self).__init__(name, inputs)\n self.type = \"XOR\"\n\n def logic(self):\n count = self.count\n if count.one > 1:\n return Value(0)\n elif count.unknown >= 1:\n return Value(\"U\")\n elif count.one == 1:\n return Value(1)\n elif count.d == 1 and count.dprime == 1:\n return Value(1)\n elif count.d == 1:\n return Value(\"D\")\n elif count.dprime == 1:\n return Value(\"D'\")\n else:\n return Value(0)\n\n def logic(self):\n count = self.count\n if count.one > 1:\n return Value(0)\n elif count.unknown >= 1:\n return Value(\"U\")\n elif count.one == 1:\n return Value(1)\n elif count.d == 1 and count.dprime == 1:\n return Value(1)\n elif count.d == 1:\n return Value(\"D\")\n elif count.dprime == 1:\n return Value(\"D'\")\n else:\n return Value(0)\n\n\nclass XnorGate(XorGate):\n def __init__(self, name, inputs=[]):\n super(XorGate, self).__init__(name, inputs)\n self.type = \"XNOR\"\n\n def logic(self):\n super(XnorGate, self).logic()\n self.value_new = ~self.value_new\n\n def get_logic(self):\n return ~super(XnorGate, self).get_logic()\n # super().logic()\n # return ~self.value_new\n\n\nclass BuffGate(Gate):\n def __init__(self, name, inputs=[]):\n super(BuffGate, self).__init__(name, inputs)\n self.type = \"BUFF\"\n\n def logic(self):\n self.value_new = self.input_nodes[0].value\n\n def get_logic(self):\n return self.input_nodes[0].value\n\n\nclass LogicTest(unittest.TestCase):\n def setUp(self):\n super(LogicTest, self).setUp()\n self.zero = Node(Gate('zero'))\n self.zero.value = Value(0)\n self.one = Node(Gate('one'))\n self.one.value = Value(1)\n self.unknown = Node(Gate('unknown'))\n self.unknown.value = Value('U')\n self.sa0 = Node(Gate('sa0'))\n self.sa0.value = Value('D')\n self.sa1 = Node(Gate('sa1'))\n self.sa1.value = Value(\"D'\")\n\n\nclass AndTest(LogicTest):\n def setUp(self):\n super(AndTest, self).setUp()\n self.node = Node(AndGate('and'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 0, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 0, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D\", self.node)\n\n\nclass NandTest(LogicTest):\n def setUp(self):\n super(NandTest, self).setUp()\n self.node = Node(NandGate('nand'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.one]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n\nclass OrTest(LogicTest):\n def setUp(self):\n super(OrTest, self).setUp()\n self.node = Node(OrGate('nand'))\n\n def test_1(self):\n self.node.input_nodes = [self.zero, self.one, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_2(self):\n self.node.input_nodes = [self.sa1, self.sa0]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_3(self):\n self.node.input_nodes = [self.sa1, self.zero]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, \"D'\", self.node)\n\n def test_4(self):\n self.node.input_nodes = [self.sa0, self.sa1]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 1, self.node)\n\n def test_5(self):\n self.node.input_nodes = [self.sa0, self.unknown]\n self.node.logic()\n self.node.update()\n self.assertEqual(self.node, 'U', self.node)\n\n\n# class XorTest(LogicTest):\n# def setUp(self):\n# super(XorTest, self).setUp()\n# self.node = Node(XorGate('xor'))\n#\n# def test_1(self):\n# self.node.input_nodes = [self.zero, self.one, self.sa1]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, \"D\", self.node)\n#\n# def test_2(self):\n# self.node.input_nodes = [self.sa1, self.sa0]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 1, self.node)\n#\n# def test_3(self):\n# self.node.input_nodes = [self.sa1, self.zero]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, \"D'\", self.node)\n\n# def test_4(self):\n# self.node.input_nodes = [self.sa1, self.sa1]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 0, self.node)\n#\n# def test_5(self):\n# self.node.input_nodes = [self.sa0, self.unknown]\n# self.node.logic()\n# self.node.update()\n# self.assertEqual(self.node, 'U', self.node)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"emohammed688/Fault-Sim","sub_path":"nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":15887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5393852100","text":"# -*- coding: utf-8 -*-\n\nimport nmap\n\n\ndef port_scan():\n print (\"---------------单线程端口扫描-----------------\")\n nm = nmap.PortScanner()\n nm.scan(hosts=\"192.168.199.1/24\", ports=\"21-80\")\n for host in nm.all_hosts():\n print (\"Host : %s (%s)\" % (host, nm[host].hostname()))\n print (\"\\tState : %s \" % nm[host].state())\n for protocol in nm[host].all_protocols():\n print (\"\\t\\tProtocols : %s \" % protocol)\n prots = nm[host][protocol].keys()\n prots.sort()\n for prot in prots:\n print (\"\\t\\tProt : %s \\t state : %s \" % (prot, nm[host][protocol][int(prot)]['state']))\n\n\ndef port_state():\n print (\"---------------在线主机扫描-----------------\")\n nm_sp = nmap.PortScanner()\n nm_sp.scan(hosts=\"192.168.199.1/24\", arguments=\"-sP\")\n hosts_list = [(x, nm_sp[x]['status']['state']) for x in nm_sp.all_hosts()]\n for host, statu in hosts_list:\n print (host, \" : \", statu)\n\n\ndef call_back():\n return \"pass\"\n\n\ndef port_scan_async():\n print (\"---------------多线程端口扫描-----------------\")\n nmaps = nmap.PortScannerAsync()\n nmaps.scan(hosts=\"192.168.199.1/24\", ports=\"21-80\", callback=call_back, sudo=False)\n for host_list in nmaps.all_hosts():\n print (\"Host : %s (%s)\" % (host_list, nmaps[host_list].hostname()))\n print (\"State : %s \" % nmaps[host_list].state())\n for protocols in nmaps[host_list].all_protocols():\n print (\"\\tProtocols : %s \" % protocols)\n prots_list = nmaps[host_list][protocols].keys()\n prots_list.sort()\n for prots in prots_list:\n print (\"\\t\\tProt : %s \\t state : %s \" % (prots, nmaps[host_list][protocols][int(prots)]['state']))\n\n\nif __name__ == \"__main__\":\n port_scan()\n port_state()\n","repo_name":"johnsonliu33/myPythonProject","sub_path":"socket_nmap/nmap_demo/nmap_scan.py","file_name":"nmap_scan.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30919980243","text":"from flask import Blueprint\n\nfrom views.todo_item import AddNewTodoItemView, ListAllTodoItems, GetTodoItemsView, DeleteTodoItemsView, \\\n UpdateTodoItemView, ToggleTodoStatusView\nfrom views.todo_list import ListAllTodoIListsView, TodoListGetUpdateDeleteView, AddNewTodoListView, SearchTodoLists\n\ntodo_items_api = Blueprint('todo_items_api', 'todo_items_api')\ntodo_lists_api = Blueprint('todo_lists_api', 'todo_lists_api')\n\n\ntodo_items_api.add_url_rule('/new/', view_func=AddNewTodoItemView.as_view('new-todo-items'))\ntodo_items_api.add_url_rule('/all/', view_func=GetTodoItemsView.as_view('list-all-td-items'))\ntodo_items_api.add_url_rule('delete/', view_func=DeleteTodoItemsView.as_view('delete-todo-item'))\ntodo_items_api.add_url_rule('update/', view_func=UpdateTodoItemView.as_view('update-todo-item'))\ntodo_items_api.add_url_rule('all/', view_func=ListAllTodoItems.as_view('list-all-todo-items'))\ntodo_items_api.add_url_rule('/done', view_func=ToggleTodoStatusView.as_view('toggle-todo-done'))\n\n\ntodo_lists_api.add_url_rule('/all/', view_func=ListAllTodoIListsView.as_view('list-all-todos'))\ntodo_lists_api.add_url_rule('//', view_func=TodoListGetUpdateDeleteView.as_view('g-d-u-todo-list'))\ntodo_lists_api.add_url_rule('/new-list/', view_func=AddNewTodoListView.as_view('add-new-todo-list'))\ntodo_lists_api.add_url_rule('/search/', view_func=SearchTodoLists.as_view('search-todo-lists'))\n","repo_name":"sophialittlejohn/flask-todo-app","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7253978943","text":"#import Environments\nimport numpy as np\n\n\nclass Evaluation:\n \n \"Class for evaluating baselines\"\n \"\"\"\n \n\n Parameters\n ----------\n env : object of gym class environment\n max_skills : int\n max_skills per exercise\n blocks : list\n describes blockstructure\n env_number : int\n describes which kind of envirnoment is used\n mastery_threshold : float, optional\n Describes when a skill with probabilistic learning state counts as mastered\n The default is 0.95.\n\n \"\"\"\n \n def __init__(self,env,max_skills,blocks,env_number,mastery_threshold = 0.95):\n \"Inits an object of class Evaluation\"\n self.env = env\n self.env_number = env_number\n self.max_skills = max_skills\n self.blocks = blocks\n self.mastery_threshold = mastery_threshold\n \n def evaluate(self,action_func,eps,curriculum=False):\n \"\"\"\n Performs the evaluation given an environment, a class and an algorithm\n Parameters\n ----------\n action_func : function\n Defines which policy should be used for evaluation\n eps : int\n Number of episodes that are run through\n curriculum : boolean, optional\n defines if a curriculum should also be shown & saved. The default is False.\n \n Returns\n -------\n med_reward : int\n Average reward the policy achieved\n \n curr: list\n list of skills that were queried in the last episode\n other: list\n consists of further interesting information (evaluation array, learned skills, std)\n \n \n \"\"\"\n eval_arr = []\n skill_arr = []\n for episode in range(eps):\n obs = self.env.reset() \n done = False\n score = 0\n if curriculum and episode == eps-1:\n if isinstance(action_func,str):\n curr = np.full((self.env.learn_length,self.max_skills),None)\n else:\n curr = np.full((self.env.get_attr(\"learn_length\")[0],self.max_skills),None) \n i = 0\n while not done:\n if action_func==\"random\":\n action = self.random(obs) \n elif action_func==\"greedy_single_pol\":\n action = self.greedy_single_pol(obs) \n elif action_func==\"greedy_block_pol\":\n action = self.greedy_block_pol(obs) \n else:\n action,_ = action_func(obs)\n obs, reward, done, info = self.env.step(action)\n if curriculum and episode == eps-1:\n if isinstance(action_func,str):\n skills = np.where(self.env.exercise_types[action,:-1])[0]\n else:\n skills = np.where(self.env.get_attr(\"exercise_types\")[0][action[0],:-1])[0]\n curr[i,:len(skills)]=skills\n i += 1\n score += reward\n eval_arr.append(score)\n skill_arr.append(sum(self.env.state if isinstance(action_func,str) else info[0][\"state\"]))\n med_skill = sum(skill_arr)/len(skill_arr)\n med_reward=sum(eval_arr)/len(eval_arr)\n if curriculum:\n return med_reward, curr,[eval_arr,np.std(eval_arr),med_skill]\n else:\n return med_reward, curr,[eval_arr,np.std(eval_arr),med_skill]\n \n\n def random(self,obs):\n \"\"\"\n Chooses a random possible action.\n \n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n \n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n\n \"\"\"\n return self.env.action_space.sample()\n \n\n\n def greedy_single_pol(self,obs):\n \"\"\"\n Provides as output the endcoded action for giving a student the action \n that includes only his \"lowest\" (namingwise) not learned skill\n (depending if the function gets the probabilistic or true learning states learned\n means over the mastery threshold or =1)\n eg obs = [0,0,0] -> student will get an exercise that includes only skill 0\n if all skills are learned a random action is chosen\n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n\n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n \"\"\"\n if self.env_number in [4,6]:\n obs = self.env.prob_state\n ex_array = self.env.exercise_types\n if not np.all(obs>self.mastery_threshold):\n first_one = np.where(obs \n student will get an exercise that includes two skills from block 0 (the lowest unlearned, rest random)\n so exercise_type [1,1,0,0,0,0]\n if all skills are learned a random action is chosen\n\n\n Parameters\n ----------\n obs: list (n_skills)\n current observation\n\n Returns\n -------\n result : int\n index of the exercisetype that should be performed (=action)\n\n \"\"\"\n \n \n if self.env_number in [4,6]:\n obs = self.env.prob_state\n ex_array = self.env.exercise_types\n if not np.all(obs>self.mastery_threshold):\n first_one = np.where(obs log.txt')\nif sys.argv[1] != \"nomobile\":\n\tprint(\"MobileData\")\n\tlength = len(list(mobilepd.itertuples()))\n\tprint(length)\n\tlast_percent_reported = -1.0\n\tfor index, mb in mobilepd.iterrows():\n\t\t#os.system('echo '+str(index)+'>> log.txt')\n\t\tx.append(getvector(mb['review']))\n\t\ty.append(mb['sentiment'])\n\t\ti+=1\n\t\tpercent = int((float(i)/float(length)) * 100.0)\n\t\tif percent != last_percent_reported:\n\t\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\t\tsys.stdout.flush()\n\t\t\tlast_percent_reported = percent\n\t#os.system('echo saving_data >> log.txt')\n\tpickle.dump(x, open('x_vec.pickle', 'wb'))\n\tpickle.dump(y, open('y_vec.pickle', 'wb'))\n\n\n#os.system('echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\appdata\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt')\nprint(\"AppData\")\nlength = len(list(apppd.itertuples()))\nlast_percent_reported = -1.0\nprint(length)\nj = 0\nfor index, mb in apppd.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx.append(getvector(mb['review']))\n\ty.append(mb['sentiment'])\n\ti+=1\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x, open('x_vec.pickle', 'wb'))\npickle.dump(y, open('y_vec.pickle', 'wb'))\n\n\n\n#os.system('echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\train\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt')\nprint(\"Train\")\nlength = len(list(train.itertuples()))\nprint(length)\nj = 0\nfor index, mb in train.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx.append(getvector(mb['review']))\n\ty.append(mb['sentiment'])\n\ti+=1\n\t\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x, open('x_vec.pickle', 'wb'))\npickle.dump(y, open('y_vec.pickle', 'wb'))\n\n#os.system(\"echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"+str(i)+\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt\")\n\n\n#os.system(\"echo \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\test\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\; >> log.txt\")\nprint(\"Test\")\nlength = len(list(test.itertuples()))\nj = 0\nfor index, mb in test.iterrows():\n\t#os.system('echo '+str(index)+'>> log.txt')\n\tx_test.append(getvector(mb['review']))\n\tpercent = int((float(j)/float(length)) * 100.0)\n\tif percent != last_percent_reported:\n\t\tsys.stdout.write(\"%s%%...\" % percent)\n\t\tsys.stdout.flush()\n\t\tlast_percent_reported = percent\n\tj+=1\n#os.system('echo saving_data >> log.txt')\npickle.dump(x_test, open('x_test_vec.pickle', 'wb'))\nprint(time()-start)\n#os.system('echo saved >> log.txt')\n#os.system(\"echo 'Done, all good.' >> log.txt\")\n#os.system(\"echo '\"+str(time()-start)+\"' >> log.txt\")\n","repo_name":"kalradivyanshu/SentimentAnalyser","sub_path":"tfreadydatavec.py","file_name":"tfreadydatavec.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27765597562","text":"import json\nimport operator\nfrom collections import defaultdict\nfrom tornado.escape import json_encode\nfrom .basehandler import BaseHandler\nimport os, sys\nfrom os import path\nimport networkx as nx\n\nlib_path = os.path.abspath(os.path.join('..', 'biothings_explorer'))\nsys.path.append( path.dirname( path.dirname( path.abspath(lib_path))))\nfrom biothings_explorer import BioThingsExplorer\n\nbt_explorer = BioThingsExplorer()\n\ncolor_dict = {\n 'gene': 'rgba(55, 230, 84, 0.93)',\n 'chemical': 'rgba(230, 55, 218, 0.93)', \n 'protein': 'rgba(55, 227, 230, 0.6)',\n 'variant': 'rgba(230, 174, 55, 0.83)', \n 'anatomy': 'rgba(86, 28, 144, 0.3)',\n 'phenotype': 'rgba(28, 86, 144, 0.3)', \n 'pathway': 'rgba(230, 55, 116, 0.63)',\n 'disease': 'rgba(166, 55, 230, 0.84)', \n 'transcript': 'rgba(100, 88, 77, 0.4)',\n 'organism': 'rgba(10, 133, 177, 0.4)',\n 'structure': 'rgba(8, 233, 7, 0.4)', \n 'ontology': 'rgba(99,123,4,0.4)',\n 'bioassay': \"rgba(100, 100, 100, 0.3)\"}\n\ndef label2color(label):\n uri = bt_explorer.registry.prefix2uri(label)\n if uri:\n return color_dict[bt_explorer.registry.bioentity_info[uri]['semantic type']]\n else:\n return \"rgba(250, 0, 0, 1.0)\"\n\ndef find_edge_label(G, source, target, relation=None):\n \"\"\"\n Given a MultiDiGraph, together with a source, target pair\n Return the edge label info associated with the (source, target) pair\n 1) If only one label exists, return the label\n 2) When multiple label exists, if relation parameter is in the label(s), return the relation parameter\n 3) If relation parameter not in the labels, return None\n\n Parmas\n ======\n G: (multiDiGraph)\n a multiDiGraph containaing nodes, edges and labels\n source: (multiDiGraph node)\n target: (multiDiGraph node)\n relation:\n The label given by user, default is None\n\n Return\n ======\n label info for the source target pair\n \"\"\"\n if (source, target) not in G.edges():\n print('The given pair source-target pair ({}, {}) is not in the graph!'.format(source, target))\n return None\n edge_labels = [v['label'] for k, v in G.get_edge_data(source, target).items()]\n if len(edge_labels) == 1:\n return edge_labels[0]\n elif len(edge_labels) > 1 and not relation:\n return edge_labels\n elif len(edge_labels) > 1 and relation and relation in edge_labels:\n return relation\n else:\n return None\n\n###########################################################################\n# Sample Input: (\n# [('ncbigene', 'http://mygene.info/v1/'),\n# ('ncbigene', 'http://myvariant.info/v1/'),\n# ('http://mygene.info/v1/', 'hgnc.symbol'),\n# ('http://myvariant.info/v1/', 'hgnc.symbol')])\n# The input is the edges returned from networkx\n# We need to take the input and feed it into plotly sankey plot\n# The output which plotly sankey plot accepts looks like this:\n# Sample Output:\n# {\n# \"label\": [\"ncbigene\", \"MyGene.info/v1/query\",\n# \"MyVariant.info/v1/query\", \"hgnc.symbol\"],\n# \"source\": [0, 0, 1, 2], # represent the index in label\n# \"target\": [1, 2, 3, 3],\n# \"value\": [1,1,1,1] # edge weight, this doesn't apply for our use case\n# } \n# Issue: plotly fails to work if there are too many nodes\n###########################################################################\n\n\ndef networkx_to_plotly(edges, duplicates_not_allowed=[]):\n # initialize the output json doc\n output_json = {'labels': [], 'colors': [], 'source': [],\n 'target': [], 'value': [], 'edge_labels': []}\n # loop through each edge, load the first element into source\n # and load the second element into target\n # load all unique elements to the nodes\n idx = 0\n input_idx = {}\n output_idx = {}\n for _edge in edges:\n if _edge[0] in duplicates_not_allowed:\n if _edge[0] not in output_json['labels']:\n input_idx[_edge[0]] = idx\n output_idx[_edge[0]] = idx\n idx += 1\n output_json['labels'].append(_edge[0])\n output_json['colors'].append(label2color(_edge[0]))\n # handle cases where the node is allowed to be duplicate, and\n # the node has not been included in the input before\n elif _edge[0] not in input_idx:\n input_idx[_edge[0]] = idx\n idx += 1\n # create a new entry for this node in the plotly graph\n output_json['labels'].append(_edge[0])\n output_json['colors'].append(label2color(_edge[0]))\n output_json['source'].append(input_idx[_edge[0]])\n if _edge[1] in duplicates_not_allowed:\n if _edge[1] not in output_json['labels']:\n input_idx[_edge[1]] = idx\n output_idx[_edge[1]] = idx\n idx += 1\n output_json['labels'].append(_edge[1])\n output_json['colors'].append(label2color(_edge[1]))\n elif _edge[1] not in output_idx:\n output_idx[_edge[1]] = idx\n idx += 1\n output_json['labels'].append(_edge[1])\n output_json['colors'].append(label2color(_edge[1]))\n output_json['target'].append(output_idx[_edge[1]])\n output_json['edge_labels'].append(_edge[2])\n if type(_edge[2]) == list:\n output_json['value'].append(1 * len(_edge[2]))\n else:\n output_json['value'].append(1)\n return output_json\n\n########################################################################### \n# This function checks whether a node belongs to a specific data type, \n# e.g. api, endpoint, or bio-entity\n# input: node_name\n# output: {id: node_name, type: data_type}\n########################################################################### \ndef construct_cytoscape_node(node, entity_list=[], api_list=[], endpoint_list=[]):\n if node in entity_list:\n return {\"data\": {\"id\": node, \"type\": \"bio-entity\", \"level\": 2}}\n elif node in api_list:\n return {\"data\": {\"id\": node, \"type\": \"api\", \"level\": 0}}\n elif node in endpoint_list:\n return {\"data\": {\"id\": node, \"type\": \"endpoint\", \"level\": 1}}\n else:\n return {\"data\": {\"id\": node, \"type\": \"value\"}}\n\n########################################################################### \n# This function takes a edge in the form of tuple, and convert it to the \n# form accepted by cytoscape.js \n# Sample input: (node1, node2)\n# Sample output: {\"data\": {\"source\": node1, \"target\": node2}}\n########################################################################### \ndef construct_cytoscape_edge(edge, _id=None, level = 0):\n result = {\"data\": {\"source\": edge[0], \"target\": edge[1]}}\n if _id:\n result['data']['label'] = _id\n if level != 0:\n result['group'] = 'edges'\n return result\n\n\ndef construct_cytoscape_node_data(node, type=\"value\", level=0):\n result = {\"data\": {\"id\": node, \"type\": \"value\", \"level\": level}}\n if level == 0:\n return result\n else:\n result['group'] = 'nodes'\n return result\n\n\ndef networkx_to_cytoscape(edges, entity_list=[], api_list=[], endpoint_list=[]):\n elements = []\n unique_nodes = []\n for _edge in edges:\n for _node in _edge:\n if _node not in unique_nodes:\n unique_nodes.append(_node)\n elements.append(construct_cytoscape_node(_node, entity_list=entity_list, api_list=api_list, endpoint_list=endpoint_list))\n elements.append(construct_cytoscape_edge(_edge))\n return elements\n\n\n\nclass ConnectingPathHandler(BaseHandler):\n def get(self):\n start = self.get_argument('start')\n end = self.get_argument('end')\n max_api = self.get_argument('max_api')\n paths = bt_explorer.find_path(start,\n end,\n max_no_api_used=int(max_api),\n dictformat=False,\n display_graph=False)\n edges = []\n for _edge in bt_explorer.temp_G.edges():\n edges.append((_edge[0],\n _edge[1],\n find_edge_label(bt_explorer.temp_G,\n _edge[0],\n _edge[1])))\n no_duplicate = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())] + list(bt_explorer.registry.endpoint_info.keys())\n plotly_results = networkx_to_plotly(edges,\n duplicates_not_allowed=no_duplicate\n )\n if paths:\n self.write(json.dumps({\"plotly\": plotly_results, \"paths\": paths}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, 'error message': \"No path could be found connecting from '\" + start + \"' to '\" + end + \" using \" + max_api + \" api!\\n Please try other input and output or try multi edge!\"}))\n self.finish\n\nclass ConnectingSemanticToIDHandler(BaseHandler):\n def get(self):\n start = self.get_argument('start')\n end = self.get_argument('end')\n max_api = self.get_argument('max_api')\n start_ids = self.get_query_argument('start_ids', [])\n excluded_nodes = self.get_query_argument('excluded_nodes', [])\n if excluded_nodes:\n excluded_nodes = json.loads(excluded_nodes)\n if start_ids:\n start_ids = json.loads(start_ids)\n if not start_ids:\n for _item in bt_explorer.registry.bioentity_info.values():\n if (_item['semantic type'] == start\n and _item['attribute type'] == 'ID'):\n start_ids.append(_item['prefix'])\n edges = []\n full_paths = []\n inputs = []\n predicates = set()\n apis = set()\n nodes = set()\n for _input in start_ids:\n paths = bt_explorer.find_path(_input,\n end,\n max_no_api_used=int(max_api),\n dictformat=False,\n display_graph=False,\n excluded_nodes=excluded_nodes)\n if paths:\n inputs.append(_input)\n full_paths += paths\n for _edge in bt_explorer.temp_G.edges():\n edge_label = find_edge_label(bt_explorer.temp_G,\n _edge[0],\n _edge[1])\n if _edge[0].startswith('http'):\n apis.add(_edge[0])\n else:\n nodes.add(_edge[0])\n if _edge[1].startswith('http'):\n apis.add(_edge[1])\n elif _edge[1] != end:\n nodes.add(_edge[1])\n # handle cases where there are multiple edge labels\n if type(edge_label) == list:\n edge_label = edge_label[0]\n if edge_label.startswith(\"assoc:\"):\n edge_label = edge_label[6:]\n edges.append((_edge[0],\n _edge[1],\n edge_label))\n if edge_label != \"has_input\":\n predicates.add(edge_label)\n no_duplicate = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())] + list(bt_explorer.registry.endpoint_info.keys())\n plotly_results = networkx_to_plotly(edges,\n duplicates_not_allowed=no_duplicate\n )\n if full_paths:\n self.write(json.dumps({\"plotly\": plotly_results,\n \"paths\": full_paths,\n \"inputs\": inputs,\n \"predicates\": list(predicates),\n \"outputs\": [end],\n \"nodes\": list(nodes),\n \"apis\": list(apis)}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, 'error message': \"No path could be found connecting from '\" + start + \"' to '\" + end + \" using \" + max_api + \" api!\\n Please try other input and output or try multi edge!\"}))\n self.finish()\n\nclass ApiMapHandler(BaseHandler):\n def get(self):\n bio_entity_list = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())]\n api_list = bt_explorer.registry.api_info.keys()\n endpoint_list = bt_explorer.registry.endpoint_info.keys()\n cytoscape_results = networkx_to_cytoscape(bt_explorer.api_map.edges(), bio_entity_list, api_list, endpoint_list)\n self.write(json.dumps(cytoscape_results))\n\nclass ApiMapHandlerSankey(BaseHandler):\n def get(self):\n plotly_results = networkx_to_plotly(bt_explorer.api_map.edges(), [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())])\n self.write(json.dumps({\"plotly\": plotly_results}))\n\nclass EndpointHandler(BaseHandler):\n def get(self):\n endpoint_name = self.get_argument('endpoint')\n edges = []\n outputs = bt_explorer.api_map.successors(endpoint_name)\n edges.extend([(endpoint_name, _output, find_edge_label(bt_explorer.api_map, endpoint_name, _output)) for _output in outputs])\n inputs = bt_explorer.api_map.predecessors(endpoint_name)\n inputs = [_input for _input in inputs if bt_explorer.api_map.node[_input]['type'] == 'bioentity']\n edges.extend([(_input, endpoint_name, find_edge_label(bt_explorer.api_map, _input, endpoint_name)) for _input in inputs])\n plotly_results = networkx_to_plotly(edges, duplicates_not_allowed=bt_explorer.registry.endpoint_info.keys())\n self.write(json.dumps({\"plotly\": plotly_results}))\n\nclass MetaDataHandler(BaseHandler):\n def get(self, type):\n if type == 'apis':\n self.write(json.dumps({'api': sorted(list(bt_explorer.registry.api_info.keys()))}))\n elif type == 'endpoints':\n self.write(json.dumps({'endpoint': sorted(list(bt_explorer.registry.endpoint_info.keys()))}))\n elif type == 'bioentities':\n # group all bioentity ids together based on their semantic type\n bioentity_dict = defaultdict(list)\n for _item in bt_explorer.registry.bioentity_info.values():\n bioentity_dict[_item['semantic type']].append(_item['prefix'])\n for k,v in bioentity_dict.items():\n bioentity_dict[k] = sorted(v)\n self.write(json_encode({'bioentity': bioentity_dict}))\n elif type == 'bioentity_input':\n bio_entity_list = [_item['prefix'] for _item in list(bt_explorer.registry.bioentity_info.values())]\n inputs = [_edge[0] for _edge in bt_explorer.api_map.edges()]\n bioentity_inputs = [_entity for _entity in bio_entity_list if _entity in inputs]\n self.write(json.dumps({'input': bioentity_inputs}))\n\n\n###########################################################################\n# Sample Input: {path=[\"hgnc.symbol\", \n# \"http://mygene.info/v1/query\", \n# \"ncbigen\"]\n# input = [\"CDK7\", \"CXCR4\"]}\n# Sample Output: cytoscape.js format\n# [{\"data\": {\"id\": \"hgnc.symbol:CKD7\"}}.\n# {\"data\": {\"id\": \"hgnc.symbol:CXCR4\"}},\n# {\"data\": {\"id\": \"ncbigene:1022\"}},\n# {\"data\": {\"target\": \"ncbigene:1022\", \n# \"source\": \"hgnc.symbol:CDK7\"}}]\n########################################################################### \nclass FindOutputHandler(BaseHandler):\n def get(self):\n path = json.loads(self.get_argument('path'))\n print('path',path)\n input_prefix, _, output_prefix = path\n # the input field by default is a list(even if it only contains one item)\n _input = json.loads(self.get_argument('input'))\n print('input',_input)\n # consider adding a level parameter here\n level = int(self.get_argument('level'))\n print(level)\n transformed_path = bt_explorer.path_conversion(path)\n #start_point = [path[0] + ':' + _item for _item in _input]\n G_output = bt_explorer.find_output(transformed_path, _input, display_graph=False)\n nodes = G_output.nodes()\n outputs = [_node.split(':')[1] for _node in nodes if _node.startswith(output_prefix)]\n cytoscape_results = []\n for _node in nodes:\n if _node.startswith(input_prefix + ':'):\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level))\n elif _node.startswith(output_prefix + ':'):\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level+1))\n else:\n cytoscape_results.append(construct_cytoscape_node_data(_node, level=level+1))\n print('this node could not be related to either input or output:{}')\n for _edge in G_output.edges():\n cytoscape_results.append(construct_cytoscape_edge(_edge, find_edge_label(G_output, _edge[0], _edge[1]), level))\n self.write(json.dumps({'output': outputs, 'cytoscape':cytoscape_results}))\n\n\nclass FindEdgeLabel(BaseHandler):\n \"\"\"\n This function serves as one BioThings Explorer API endpoint\n Given an endpoint and its output, return the relationship info from JSON-LD context\n\n Params\n ======\n endpoint: endpoint name\n output: output of the endpoint\n\n \"\"\"\n def get(self):\n endpoint_name = self.get_argument('endpoint')\n output = self.get_argument('output')\n self.write(json.dumps({'relation': find_edge_label(bt_explorer.api_map, endpoint_name, output)}))\n\n\nclass KnowledgeMap(BaseHandler):\n \"\"\"\n Return subject, object, predicate information\n Users could also query based on subject, object and predicate\n\n Parmas\n ======\n endpoint: specify a specific endpoint name, and return all subject, object\n predicate information specific to this endpoint\n predicate: specify a specific predicate, and return all subject, object\n predicate information which contains the specified predicate\n subject.prefix: specify a specific subject prefix, and return all subject, object\n predicate information which contains the specified subject prefix\n subject.semantic_type: specify a specific subject semantic type, and return all subject, object\n predicate information which contains the specified subject semantic type\n object.prefix: specify a specific object prefix, and return all subject, object\n predicate information which contains the specified object prefix\n object.semantic_type: specify a specific object semantic type, and return all subject, object\n predicate information which contains the specified object semantic type\n \"\"\"\n def get(self):\n # get parameters\n input_endpoint = self.get_query_argument('endpoint', None)\n input_predicate = self.get_query_argument('predicate', None)\n input_subject_prefix = self.get_query_argument('subject.prefix', None)\n input_object_prefix = self.get_query_argument('object.prefix', None)\n input_subject_type = self.get_query_argument('subject.semantic_type', None)\n input_object_type = self.get_query_argument('object.semantic_type', None)\n # load all association information into triples\n bioentity_info = bt_explorer.registry.bioentity_info\n i = 0\n triples = []\n for _endpoint, _endpoint_info in bt_explorer.registry.endpoint_info.items():\n relation = _endpoint_info['relation']\n inputs = _endpoint_info['input']\n for _input in inputs:\n _input_curie = bioentity_info[_input]['prefix']\n _input_type = bt_explorer.registry.bioentity_info[_input]['semantic type']\n for _output, _relation in relation.items():\n _output_curie = bioentity_info[_output]['prefix']\n _output_type = bt_explorer.registry.bioentity_info[_output]['semantic type']\n for _relate in _relation:\n triples.append({'subject': {'prefix': _input_curie, 'semantic_type': _input_type}, \n 'object': {'prefix': _output_curie, 'semantic_type': _output_type}, \n 'predicate': _relate.split(':')[-1], 'endpoint': _endpoint, 'api': _endpoint_info['api']})\n temp_output = triples\n END_OUTPUT = False\n # check if user want to filter for a specific field or combination of fields\n if input_endpoint:\n # check whether user input is valid\n if input_endpoint in bt_explorer.registry.endpoint_info:\n temp_output = [_association for _association in temp_output if _association['endpoint']==input_endpoint]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The endpoint '\" + input_endpoint + \"' you input is not in BioThings Explorer. \\\n Please refer to 'http://biothings.io/explorer/api/v1/metadata/endpoints' for all endpoints currently integrated!\"}))\n self.finish()\n END_OUTPUT = True\n if input_predicate and not END_OUTPUT:\n if input_predicate in [_association['predicate'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['predicate']==input_predicate]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The predicate '\" + input_predicate + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_subject_prefix and not END_OUTPUT:\n if input_subject_prefix in [_association['subject']['prefix'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['subject']['prefix']==input_subject_prefix]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The subject prefix '\" + input_subject_prefix + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_subject_type and not END_OUTPUT:\n if input_subject_type in [_association['subject']['semantic_type'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['subject']['semantic_type']==input_subject_type]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The subject semantic type '\" + input_subject_type + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_object_prefix and not END_OUTPUT:\n if input_object_prefix in [_association['object']['prefix'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['object']['prefix']==input_object_prefix]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The object prefix '\" + input_object_prefix + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n if input_object_type and not END_OUTPUT:\n if input_object_type in [_association['object']['semantic_type'] for _association in triples]:\n temp_output = [_association for _association in temp_output if _association['object']['semantic_type']==input_object_type]\n else:\n temp_output = []\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"The object semantic type '\" + input_object_type + \"' you input is not in BioThings Explorer.\"}))\n self.finish()\n END_OUTPUT = True\n # output\n if not END_OUTPUT:\n if temp_output:\n self.write(json.dumps({\"associations\": temp_output}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"No associations could be found for the input you give!!\"}))\n\nclass KnowledgeMapPath(BaseHandler):\n def get(self):\n start = self.get_query_argument('start')\n end = self.get_query_argument('end')\n max_api = self.get_query_argument('max_api', 3)\n paths = bt_explorer.find_path(start, end, max_no_api_used=int(max_api), dictformat=False, display_graph=False)\n if paths:\n # function to add semantic type, predicate information into the path\n detailed_paths = []\n for _path in paths:\n new_path = []\n for i in range(0, len(_path)-2, 2):\n subject_uri = bt_explorer.registry.prefix2uri(_path[i])\n object_uri = bt_explorer.registry.prefix2uri(_path[i+2])\n subject_type = bt_explorer.registry.bioentity_info[subject_uri]['semantic type']\n object_type = bt_explorer.registry.bioentity_info[object_uri]['semantic type']\n new_path.append({'subject': {'prefix': _path[i], 'semantic_type': subject_type}, \n 'object': {'prefix': _path[i+2], 'semantic_type': object_type}, \n 'predicate': find_edge_label(bt_explorer.api_map, _path[i+1], _path[i+2]).split(':')[-1], 'endpoint': _path[i+1]})\n detailed_paths.append(new_path)\n self.write(json.dumps({\"paths\": detailed_paths}))\n else:\n self.set_status(400)\n self.write(json.dumps({\"status\": 400, \"message\": \"No path could be found between \" + start + \" and \" + end + '!'}))\n","repo_name":"biothings/biothings_explorer_web_old","sub_path":"src/handlers/ConnectingPathHandler.py","file_name":"ConnectingPathHandler.py","file_ext":"py","file_size_in_byte":26698,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"42782853427","text":"import datetime\nimport enum\nimport os\nimport pathlib\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport typing\nimport psutil\nfrom os import access, R_OK, W_OK\nimport dataclasses\n\nMETADATA_DIR_NAME = \".ltarchiver\"\n\nrecordbook_file_name = \"recordbook.txt\"\nif \"DEBUG\" in os.environ:\n DEBUG = True\n recordbook_dir = pathlib.Path(\"test_data\") / METADATA_DIR_NAME\nelse:\n DEBUG = False\n recordbook_dir = pathlib.Path.home() / METADATA_DIR_NAME\nrecordbook_path = recordbook_dir / recordbook_file_name\nrecordbook_checksum_file_path = recordbook_dir / \"checksum.txt\"\nRECORD_PATH = recordbook_dir / \"new_transaction.txt\"\necc_dir_name = \"ecc\"\nchunksize = 1024 # bytes\neccsize = 16 # bytes\n\n\nclass LTAError(Exception):\n pass\n\n\nclass Validation(enum.Enum):\n ECC_DOESNT_EXIST = \"The ecc of the file doesn't exist\"\n ECC_CORRUPTED = \"The ecc of the file was corrupted\"\n DOESNT_EXIST = \"The file doesn't exist\"\n NO_CHECKSUM_FILE = \"The Checksum file doesn't exist\"\n CORRUPTED = \"The file appears to have been corrupted\"\n VALID = \"No errors found\"\n\n def __str__(self):\n return self.value\n\n\n@dataclasses.dataclass\nclass TerminalMenu:\n title: str\n options: typing.Dict[str, typing.Callable]\n with_abort: bool = True\n REDISPLAY_MENU = \"REDISPLAY_MENU\"\n\n @classmethod\n def get_null_option(cls, fun):\n \"\"\"For a callable returns another callable that will not cause the menu to close if chosen as an option.\"\"\"\n\n def f():\n fun()\n return TerminalMenu.REDISPLAY_MENU\n\n return f\n\n def __post_init__(self):\n def abort():\n raise LTAError(\"Aborted by the request of the user\")\n\n if self.with_abort:\n self.options[\"Abort\"] = abort\n\n def show(self):\n callbacks = list(self.options.values())\n while True:\n print(self.title)\n option_count = 1\n for text in self.options.keys():\n print(option_count, \"-\", text)\n option_count += 1\n s = input()\n try:\n user_input = int(s)\n except ValueError:\n print(f\"{s} is not a number\")\n continue\n if 1 > user_input > option_count - 1:\n print(f\"{s} is not a number between 1 and {option_count - 1}\")\n continue\n else:\n if callbacks[user_input - 1]() == TerminalMenu.REDISPLAY_MENU:\n continue\n else:\n break\n\n\n@dataclasses.dataclass(frozen=True)\nclass Record:\n timestamp: datetime.datetime\n source: pathlib.Path\n destination: str\n file_name: str\n checksum: str\n ecc_checksum: str\n chunksize: int = chunksize\n eccsize: int = eccsize\n checksum_algorithm: str = \"md5\"\n deleted: bool = False\n version: int = 1\n\n def write(self, recordbook: pathlib.Path = recordbook_path):\n with recordbook.open(\"at\") as f:\n f.write(\"Item\\n\")\n f.write(f\"Version: {self.version}\\n\")\n f.write(f\"Deleted: {self.deleted}\\n\")\n f.write(f\"File-Name: {self.file_name}\\n\")\n f.write(f\"Source: {self.source.resolve()}\\n\")\n f.write(f\"Destination: {self.destination}\\n\")\n f.write(f\"Bytes-per-chunk: {self.chunksize}\\n\")\n f.write(f\"EC-bytes-per-chunk: {self.eccsize}\\n\")\n f.write(f\"Timestamp: {datetime.datetime.now().isoformat()}\\n\")\n f.write(f\"Checksum-Algorithm: {self.checksum_algorithm}\\n\")\n f.write(f\"Checksum: {self.checksum}\\n\")\n f.write(f\"ECC-Checksum: {self.ecc_checksum}\\n\")\n\n def get_validation(self) -> Validation:\n \"\"\"True if file exists and checksum matches\"\"\"\n root = get_root_from_uuid(self.destination)\n path = self.file_path(root)\n if not path.exists():\n return Validation.DOESNT_EXIST\n checksum = get_file_checksum(path)\n if checksum != self.checksum:\n return Validation.CORRUPTED\n\n ecc_file_path = self.ecc_file_path(root)\n if not ecc_file_path.exists():\n return Validation.ECC_DOESNT_EXIST\n checksum = get_file_checksum(ecc_file_path)\n if checksum != self.ecc_checksum:\n return Validation.ECC_CORRUPTED\n return Validation.VALID\n\n def file_path(self, root: pathlib.Path):\n return root / self.file_name\n\n def ecc_file_path(self, root: pathlib.Path) -> pathlib.Path:\n return root / METADATA_DIR_NAME / ecc_dir_name / self.checksum\n\n def __str__(self):\n return f\"Record of {self.file_name} stored on {self.destination}\"\n\n\ndef error(msg: str):\n print(msg, file=sys.stderr)\n exit(1)\n\n\ndef get_file_checksum(source: pathlib.Path):\n return subprocess.check_output([f\"md5sum\", source], encoding=\"utf-8\").split()[0]\n\n\nclass FileValidation(enum.Enum):\n FILE_DOESNT_EXIST = enum.auto()\n DIRECTORY_DOESNT_EXIST = enum.auto()\n IS_DIRECTORY = enum.auto\n NO_WRITE_PERMISSION_FILE = enum.auto()\n NO_WRITE_PERMISSION_DIRECTORY = enum.auto()\n NO_READ_PERMISSION_FILE = enum.auto()\n NOT_A_FILE = enum.auto()\n\n\ndef file_ok(path: pathlib.Path, source=True) -> None:\n \"\"\"Test for the usefulness of path.\n\n If source is true the path must exist, be a file and readable.\n\n If source is False, will test if it's a directory and writable\n or a path that sits in a directory that's writable.\n\n In case any test fails this function will throw an LTAError with the\n reason.\n \"\"\"\n if source:\n if not path.exists():\n raise LTAError(\n f\"File {path} does not exist\", FileValidation.FILE_DOESNT_EXIST\n )\n if path.is_dir():\n raise LTAError(f\"{path} is a directory\", FileValidation.IS_DIRECTORY)\n if not path.is_file():\n raise LTAError(\n f\"Path {path} does not point to a file\", FileValidation.NOT_A_FILE\n )\n if not access(path, R_OK):\n raise LTAError(\n f\"File {path} is not readable\", FileValidation.NO_READ_PERMISSION_FILE\n )\n else:\n if not path.exists():\n if not path.parent.exists():\n raise LTAError(\n f\"Directory {path.parent} does not exist\",\n FileValidation.DIRECTORY_DOESNT_EXIST,\n )\n else:\n if not access(path.parent, W_OK):\n raise LTAError(\n f\"Cannot write to parent of {path}\",\n FileValidation.NO_WRITE_PERMISSION_DIRECTORY,\n )\n if not access(path, W_OK):\n raise LTAError(\n f\"File {path} is not writable\", FileValidation.NO_WRITE_PERMISSION_FILE\n )\n\n\ndef copy_recordbook_from_to(\n from_file: pathlib.Path,\n from_checksum: pathlib.Path,\n to_file: pathlib.Path,\n to_checksum: pathlib.Path,\n):\n def copy():\n check_recordbook_md5(from_checksum)\n shutil.copy(from_file, to_file)\n shutil.copy(from_checksum, to_checksum)\n\n return copy\n\n\ndef decide_recordbooks(\n destination_recordbook_path: pathlib.Path,\n destination_recordbook_checksum_path: pathlib.Path,\n):\n subprocess.call(\n shlex.split(f\"diff {recordbook_path} {destination_recordbook_path}\")\n )\n menu = TerminalMenu(\n \"What should be done?\",\n {\n f\"Overwrite the contents of {recordbook_path} with {destination_recordbook_path}\": (\n copy_recordbook_from_to(\n destination_recordbook_path,\n destination_recordbook_checksum_path,\n recordbook_path,\n recordbook_checksum_file_path,\n )\n ),\n f\"Overwrite the contents of {destination_recordbook_path} with {recordbook_path}\": (\n copy_recordbook_from_to(\n recordbook_path,\n recordbook_checksum_file_path,\n destination_recordbook_path,\n destination_recordbook_checksum_path,\n )\n ),\n },\n )\n menu.show()\n\n\ndef get_records(recordbook_path: pathlib.Path) -> typing.Iterable[Record]:\n recordbook = recordbook_path.open(\"r\")\n source = None\n destination = None\n file_name = None\n deleted = None\n version = None\n chunksize_ = None\n eccsize_ = None\n timestamp = None\n checksum = None\n checksum_alg = None\n first_item = True\n ecc_checksum = None\n for line in recordbook:\n line = line.strip()\n parts = line.split(\" \")\n if parts[0] == \"Item\":\n if first_item:\n first_item = False\n else:\n yield Record(\n source=pathlib.Path(source),\n destination=destination,\n file_name=file_name,\n deleted=deleted,\n version=version,\n chunksize=chunksize_,\n eccsize=eccsize_,\n timestamp=timestamp,\n checksum=checksum,\n checksum_algorithm=checksum_alg,\n ecc_checksum=ecc_checksum,\n )\n elif parts[0] == \"Deleted:\":\n deleted = parts[1] == \"true\"\n elif parts[0] == \"Source:\":\n source = parts[1]\n elif parts[0] == \"Destination:\":\n destination = parts[1]\n elif parts[0] == \"Checksum:\":\n checksum = parts[1]\n elif parts[0] == \"File-Name:\":\n file_name = parts[1]\n elif parts[0] == \"Bytes-per-chunk:\":\n chunksize_ = int(parts[1])\n elif parts[0] == \"EC-bytes-per-chunk:\":\n eccsize_ = int(parts[1])\n elif parts[0] == \"Timestamp:\":\n timestamp = datetime.datetime.fromisoformat(parts[1])\n elif parts[0] == \"Checksum-Algorithm:\":\n checksum_alg = parts[1]\n elif parts[0] == \"ECC-Checksum:\":\n ecc_checksum = parts[1]\n elif parts[0] == \"Version:\":\n version = int(parts[1])\n recordbook.close()\n if first_item:\n return []\n else:\n yield Record(\n source=pathlib.Path(source),\n destination=destination,\n file_name=file_name,\n deleted=deleted,\n version=version,\n chunksize=chunksize_,\n eccsize=eccsize_,\n timestamp=timestamp,\n checksum=checksum,\n checksum_algorithm=checksum_alg,\n ecc_checksum=ecc_checksum,\n )\n\n\ndef check_recordbook_md5(recordbook_checksum: pathlib.Path):\n if not recordbook_checksum.exists() or recordbook_checksum.stat().st_size == 0:\n raise FileNotFoundError(\n f\"Recordbook checksum file {recordbook_checksum} not found or empty\"\n )\n try:\n subprocess.check_call(shlex.split(f\"md5sum -c {recordbook_checksum}\"))\n except subprocess.CalledProcessError as err:\n raise LTAError(\n f\"The recordbook checksum file {recordbook_checksum} doesn't match what's stored. Please validate it and retry.\"\n ) from err\n\n\ndef mark_record_as_deleted(record_idx: int):\n records = list(get_records(recordbook_path))\n records[record_idx].deleted = True\n os.remove(recordbook_path)\n for record in records:\n record.write()\n\n\ndef get_device_uuid_and_root_from_path(path: pathlib.Path) -> (str, pathlib.Path):\n devices_to_uuids = {}\n for line in subprocess.check_output(\n [\"ls\", \"-l\", \"/dev/disk/by-uuid\"], encoding=\"utf-8\"\n ).split(\"\\n\")[1:]:\n if not line.strip():\n break\n parts = line.split()\n devices_to_uuids[\n (pathlib.Path(\"/dev/disk/by-uuid\") / pathlib.Path(parts[-1])).resolve(\n strict=True\n )\n ] = parts[-3]\n path_to_devices = {}\n for line in subprocess.check_output(\"mount\", encoding=\"utf-8\").split(\"\\n\"):\n if not line.strip():\n break\n if line.startswith(\"/dev/\"):\n parts = line.split()\n path_to_devices[pathlib.Path(parts[2]).resolve(strict=True)] = pathlib.Path(\n parts[0]\n ).resolve(strict=True)\n prev_parent = None\n parent = path.resolve()\n while prev_parent != parent:\n if parent in path_to_devices:\n return devices_to_uuids[path_to_devices[parent]], parent\n else:\n prev_parent = parent\n parent = parent.parent\n raise AttributeError(f\"Could not find the device associated with the path {path}\")\n\n\ndef get_root_from_uuid(uuid: str) -> pathlib.Path:\n uuid_to_device = {}\n for p in pathlib.Path(\"/dev/disk/by-uuid\").iterdir():\n uuid_to_device[p.name] = p.resolve()\n device_to_path = {}\n for partition in psutil.disk_partitions():\n device_to_path[pathlib.Path(partition.device)] = pathlib.Path(\n partition.mountpoint\n )\n try:\n device = uuid_to_device[uuid]\n try:\n return device_to_path[device]\n except KeyError as err:\n raise AttributeError(\n f\"Could not find the root of the device {device}. Is it mounted?\"\n ) from err\n except KeyError as err:\n raise AttributeError(\n f\"Could not find the device associated with the UUID {uuid}.\"\n f\" Is it pluged int?\"\n ) from err\n\n\ndef record_of_file(\n recordbook_path: pathlib.Path,\n backup_file_checksum: str,\n backup_file_path: pathlib.Path,\n):\n for record in get_records(recordbook_path):\n if not record.deleted and (\n record.checksum == backup_file_checksum\n or record.file_name == backup_file_path.name\n ):\n return record\n\n\nclass RecordBook:\n def __init__(self, path: pathlib.Path, checksum_file_path: pathlib.Path):\n self.path = path\n self.records: typing.Set[Record] = set(get_records(path))\n self.checksum_file_path = checksum_file_path\n self.valid = True\n self.invalid_reason: Validation = Validation.VALID\n self.validate()\n\n def merge(self, other_recordbook: \"RecordBook\"):\n self.records = self.records.union(other_recordbook.records)\n self.write()\n\n def write(self):\n remove_file(self.path)\n for record in self.records:\n record.write(self.path)\n subprocess.check_call(\n f\"md5sum {self.path} > {self.checksum_file_path}\", shell=True\n )\n\n def get_records_by_uuid(self, device_uuid: str) -> typing.Iterable[Record]:\n for record in self.records:\n if record.destination == device_uuid:\n yield record\n\n def validate(self):\n if not self.path.exists():\n self.valid = False\n self.invalid_reason = Validation.DOESNT_EXIST\n elif not self.checksum_file_path.exists():\n self.valid = False\n self.invalid_reason = Validation.NO_CHECKSUM_FILE\n elif not self.checksum_file_path.read_text() == get_file_checksum(self.path):\n self.valid = False\n self.invalid_reason = Validation.CORRUPTED\n\n def __str__(self):\n return f\"Recordbook stored on {self.path}, {len(self.records)} entries\"\n\n def update_record(self, record: Record):\n self.records.remove(record)\n self.records.add(dataclasses.replace(record, timestamp=datetime.datetime.now()))\n\n\ndef remove_file(path: pathlib.Path):\n try:\n os.remove(path)\n except IsADirectoryError:\n shutil.rmtree(path, ignore_errors=True)\n except FileNotFoundError:\n pass\n\n\ndef validate_and_recover_recordbooks(\n home_recordbook: RecordBook, device_recordbook: RecordBook, first_time_ok=False\n):\n home_recordbook.validate()\n device_recordbook.validate()\n\n def copy_recordbook_callback(a: RecordBook, b: RecordBook):\n def cp():\n b.records = a.records\n b.write()\n b.validate()\n\n return cp\n\n if home_recordbook.valid and device_recordbook.valid:\n return\n elif not home_recordbook.valid and not device_recordbook.valid:\n\n def overwrite_checksums():\n home_recordbook.write()\n device_recordbook.write()\n\n if (\n home_recordbook.invalid_reason == Validation.DOESNT_EXIST\n and device_recordbook.invalid_reason == Validation.DOESNT_EXIST\n ):\n print(\"No recordbook found.\")\n if not first_time_ok:\n raise LTAError(\"Please store a file first with the store command.\")\n else:\n print(\"Assuming this is the first time you are running ltarchiver.\")\n else:\n # todo recordbooks can have different reasons for being invalid\n TerminalMenu(\n f\"Neither the home recordbook {home_recordbook.path}\"\n f\"\\nnor the device recordbook {device_recordbook}\"\n f\"\\nmatches its checksum. What do you want to do?\",\n {\n \"Show contents of home recordbook\": TerminalMenu.get_null_option(\n lambda: print(home_recordbook.path.read_text())\n ),\n \"Show contents of device recordbook\": TerminalMenu.get_null_option(\n lambda: print(device_recordbook.path.read_text())\n ),\n \"Overwrite checksum files\": overwrite_checksums(),\n },\n )\n elif not home_recordbook.valid:\n if home_recordbook.invalid_reason == Validation.NO_CHECKSUM_FILE:\n TerminalMenu(\n f\"No checksum found for the home recordbook: {home_recordbook.path}.\"\n f\"\\nDo you want to recreate it?\"\n f\"\\nIf you don't have any reason to not do so, you should answer yes.\",\n {\n \"Yes\": (lambda: home_recordbook.write()),\n },\n ).show()\n elif device_recordbook.valid:\n if home_recordbook.invalid_reason == Validation.DOESNT_EXIST:\n copy_recordbook_callback(device_recordbook, home_recordbook)()\n return\n\n elif home_recordbook.invalid_reason == Validation.CORRUPTED:\n TerminalMenu(\n f\"The home recordbook's checksum doesn't correspond to its contents': {home_recordbook.path}.\"\n f\"\\nHowever the device recordbook is valid: {device_recordbook.path}\"\n f\"\\nDo you want to copy the device recordbook content into the home recordbook?\",\n {\n \"Show diff\": TerminalMenu.get_null_option(\n lambda: subprocess.check_call(\n [\"diff\", home_recordbook.path, device_recordbook.path]\n )\n ),\n \"Yes\": copy_recordbook_callback(\n device_recordbook, home_recordbook\n ),\n },\n ).show()\n else:\n # only home_recordbook is valid\n if device_recordbook.invalid_reason == Validation.DOESNT_EXIST:\n copy_recordbook_callback(home_recordbook, device_recordbook)\n elif device_recordbook.invalid_reason == Validation.NO_CHECKSUM_FILE:\n TerminalMenu(\n f\"No checksum found for the device recordbook: {device_recordbook.path}.\"\n f\"\\nDo you want to recreate it?\"\n f\"\\nIf you don't have any reason to not do so, you should answer yes.\",\n {\n \"Yes\": (lambda: device_recordbook.write()),\n },\n ).show()\n elif device_recordbook.invalid_reason == Validation.CORRUPTED:\n TerminalMenu(\n f\"The device recordbook's checksum doesn't correspond to its contents': {device_recordbook.path}.\"\n f\"\\nHowever the home recordbook is valid: {home_recordbook.path}\"\n f\"\\nDo you want to copy the home recordbook content into the device recordbook?\",\n {\n \"Show diff\": TerminalMenu.get_null_option(\n lambda: subprocess.check_call(\n [\"diff\", home_recordbook.path, device_recordbook.path]\n )\n ),\n \"Yes\": copy_recordbook_callback(home_recordbook, device_recordbook),\n },\n ).show()\n","repo_name":"marceloslacerda/ltarchiver","sub_path":"ltarchiver/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":20592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"802796821","text":"\"\"\"Loads frame(s) and applies the effect. \n\n@author: \n@date: 05/11/21\n\"\"\"\nimport constants\nimport cv2\nimport glob\nimport helpers\nimport os\nimport numpy as np\n\n# in case in path is None, default to WebCam.\nclass WebCam():\n def __init__(self): \n self.webcam_descriptor = 0\n\n def run(self, background_effect, write_effect): \n \"\"\"Applies the effect to the frames in the video, and writes it if \n specified. \n \n If the webcam cannot be accessed an assertion error will be thrown.\n\n The webcam will be run for a total of 60 frames. \n Args: \n background_effect (BackgroundEffect Class): an initialized \n BackgroundEffect class.\n write_effect (function): the write_effect function, uses values \n passed to ApplyEffect to determine where and if to write. \n\n Returns: \n (NoneType): None.\n \"\"\"\n video = cv2.VideoCapture(self.webcam_descriptor)\n \n if video is None or not video.isOpened():\n raise AssertionError(\"Was unable to read from webcam.\")\n\n curr_frame = 0\n max_frames = 9\n\n while True:\n check, frame = video.read()\n \n effected_frame = background_effect.apply_effect(frame)\n \n cv2.imshow(\"Webcam view.\", effected_frame)\n cv2.waitKey(1) # Don't wait for a keyboard input\n write_effect(effected_frame)\n\n curr_frame += 1\n print(curr_frame)\n if curr_frame > max_frames: \n break\n\n video.release()\n cv2.destroyAllWindows()\n\n return\n\nclass Images(): \n def __init__(self, in_path):\n self.in_path = in_path\n self.image_paths = self.get_imgs()\n\n def get_imgs(self):\n if os.path.isfile(self.in_path): \n self.image_paths = [self.in_path]\n else: \n # Build path list\n image_paths = []\n\n for ext in constants.IMG_EXTS: \n image_paths += glob.glob(self.in_path + \"*\" + ext)\n\n return\n\n def run(self, background_effect, write_effect):\n \"\"\"Applies the effect to the frames in the video, and writes it if \n specified. \n\n Args: \n background_effect (BackgroundEffect Class): an initialized \n BackgroundEffect class.\n write_effect (function): the write_effect function, uses values \n passed to ApplyEffect to determine where and if to write. \n\n Returns: \n (NoneType): None.\n \"\"\"\n\n for image_path in self.image_paths: \n frame = helpers.load_img(image_path)\n\n effected_frame = background_effect.apply_effect(frame)\n\n write_effect(effected_frame)\n\n return\n\nclass ApplyEffect():\n def __init__(self, in_path, out_path, do_stitch, be): \n self.in_path = in_path\n self.out_path = out_path\n self.do_stitch = do_stitch\n self.background_effect = be\n\n # Pointer for writing. \n self.curr_frame = 0\n\n def write_effect(self, frame): \n \"\"\"Writes a given frame to the specified out_path. \n \n Args: \n frame (ndarray): an effected frame. \n Returns: \n (NoneType): None. \n \"\"\"\n cv2.imwrite(self.out_path + str(self.curr_frame) + \".jpg\", frame)\n\n self.curr_frame += 1\n\n return\n\n def stitch_effected_frames(self, fps=20):\n \"\"\"Stitches the given frames into a video. Saved at the out_path.\n \n Args:\n frames (List[ndarray]): a list of effected frames.\n Returns:\n (NoneType): None. \n \"\"\"\n paths = os.listdir(self.out_path)\n paths.sort()\n print(paths)\n if paths == []: \n return\n\n # get frame shape. \n first_frame = cv2.imread(self.out_path + paths[0])\n\n # TODO\n # Update fps to system setting...\n if self.do_stitch: \n print(\"Attempting to stitch frames together. Will not work on every machine :<\")\n vid_shape = (first_frame[0].shape[1], first_frame[0].shape[0])\n video = cv2.VideoWriter(self.out_path + \"stitched_frames.avi\", \n cv2.VideoWriter_fourcc(*'XVID'), \n fps,\n vid_shape)\n\n for path in paths: \n print(\"Looking at path {}\".format(path))\n video.write(cv2.imread(self.out_path + path).astype(np.uint8))\n\n cv2.destroyAllWindows()\n video.release\n\n def apply_effect(self):\n \"\"\"Applies the specified effect to the specified input mode. \n\n \"\"\"\n feed_src = None\n\n if self.in_path is None: \n feed_src = WebCam()\n else: \n feed_src = Images(self.in_path)\n\n # Bad design but let's just rely on the WebCam and Images class \n # to check for errors and assume they won't give any \n # unexpected behavior.\n feed_src.run(self.background_effect, self.write_effect)\n\n if self.do_stitch:\n self.stitch_effected_frames()\n\n return \n\n","repo_name":"rob-marcus/21344_term_project","sub_path":"src/ApplyEffect.py","file_name":"ApplyEffect.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74943632804","text":"def load_input(filename):\n \"\"\"\n Load input ciphertext\n \"\"\"\n with open(filename) as f:\n return [int(token) for token in f.readlines()[0].strip().split(\",\")]\n\ndef xor_decode(ciphertext, key):\n \"\"\"\n Decode some ciphertext with the given key with XOR algorithm\n ciphertext: the ciphertext to decode (as a string)\n key: the key to use (array of ints representing ASCII codes)\n \"\"\"\n return \"\".join([chr(c ^ key[index % len(key)]) for index, c in enumerate(ciphertext)])\n\ndef main():\n \"\"\"\n Entry point\n \"\"\"\n ciphertext = load_input(\"problem59_input.txt\")\n \n # Try three-letter combos and work out which looks like English\n likely_key = None\n for i in range(ord(\"a\"), ord(\"z\")+1):\n for j in range(ord(\"a\"), ord(\"z\")+1):\n for k in range(ord(\"a\"), ord(\"z\")+1):\n key = [i, j, k]\n decoded_fragment = xor_decode(ciphertext, key)\n key_str = \"\".join([chr(c) for c in key])\n if \"the\" in set(decoded_fragment.split(\" \")):\n likely_key = key\n print(f\"Likely key '{key_str}': {decoded_fragment}\")\n\n decoded = [ord(c) for c in xor_decode(ciphertext, likely_key)]\n print(f\"Sum of decoded ASCII values: {sum(decoded)}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ericgreveson/projecteuler","sub_path":"p_050_059/problem59.py","file_name":"problem59.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70315701286","text":"from typing import List\n\n\n# 方法1-直接回溯算法\nclass Solution1:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n def track_back(n, k, start_index, path):\n if len(path) == k:\n if sum(path) == n:\n res.append(path.copy())\n return\n for i in range(start_index, 10):\n path.append(i)\n track_back(n, k, i + 1, path)\n path.pop()\n\n res = []\n track_back(n, k, 1, [])\n return res\n\n\n# 方法2-剪枝优化\nclass Solution2:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n def track_back(n, k, start_index, path, total):\n if total > n: # 剪枝操作\n return\n if total == n and len(path) == k:\n res.append(path.copy())\n return\n for i in range(start_index, 10 - (k - len(path)) + 1): # 剪枝\n path.append(i)\n total += i\n track_back(n, k, i + 1, path, total)\n path.pop()\n total -= i\n\n res = []\n track_back(n, k, 1, [], 0)\n return res\n\n\nif __name__ == '__main__':\n k1 = 3\n n1 = 7\n k2 = 3\n n2 = 9\n s1 = Solution1()\n s2 = Solution2()\n print(s1.combinationSum3(k1, n1))\n print(s1.combinationSum3(k2, n2))\n print(s2.combinationSum3(k1, n1))\n print(s2.combinationSum3(k2, n2))\n","repo_name":"cxiaolong/Algorithm-Practice","sub_path":"PythonEdition/回溯算法/216_combinationSum3.py","file_name":"216_combinationSum3.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18045535326","text":"from django.shortcuts import render, redirect\n#from .models import Details, Leave_Application, Approved_Leave_Application\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.http import HttpResponse\nfrom django.utils import timezone\nfrom .models import Staff_Details, Leave_Application, Status_Leave_Application\n\n# Create your views here.\ndef homepage(request):\n return render(request, 'staff/homepage.html')\n\ndef user_login(request):\n\n if request.method == \"POST\":\n username = request.POST['username']\n pass1 = request.POST['password']\n user = authenticate(username=username, password=pass1)\n\n if user is not None:\n login(request, user)\n request.session['username'] = username\n if user.groups.filter(name='STAFF').exists():\n return redirect('profile')\n else:\n messages.error(request, \"Invalid Employee ID or Password\")\n return render(request, 'staff/login.html')\n \n \n else:\n messages.error(request, \"Invalid Employee ID or Password\")\n return render(request, 'staff/login.html')\n return render(request, 'staff/login.html')\n\n@login_required\ndef profile(request):\n emp_id = request.session.get('username', \"eNE\")\n details = Staff_Details.objects.filter(employee_id=emp_id)\n if details.exists():\n detail = details[0]\n else:\n detail = None\n print(detail.name)\n\n return render(request, 'staff/profile.html', {'detail': detail})\n\n@login_required\ndef signout(request):\n logout(request)\n return redirect('user_login')\n\n@login_required\ndef new_leave_application(request):\n username = request.session.get('username', \"NONE\")\n do_exist = Leave_Application.objects.filter(employee_id = username)\n\n if do_exist.exists():\n messages.warning(request,\"You have already applied for a leave.\")\n return redirect('profile')\n \n else:\n\n details = Staff_Details.objects.filter(employee_id=username)\n if details.exists():\n detail = details[0] \n else:\n # Handle the case where no matching records are found\n detail = None\n print(detail.name)\n if request.method == \"POST\":\n staff_name = request.POST['staffName']\n department = request.POST['department']\n nature_of_leave = request.POST['natureOfLeave']\n leave_days = request.POST['leaveDays']\n leave_period = request.POST['leavePeriod']\n reason_for_leave = request.POST['reasonForLeave']\n class_semester = request.POST['classSemester']\n hour = request.POST['hour']\n subject = request.POST['subject']\n assigned_teacher = request.POST['assignedTeacher']\n linways_assigned = request.POST['linwaysAssigned']\n\n time_of_request = timezone.now()\n emp_id = Staff_Details.objects.get(employee_id = username)\n\n\n leave_application = Leave_Application(\n employee_id = emp_id,\n name=staff_name,\n department=department,\n nature_of_leave=nature_of_leave,\n no_of_days=leave_days,\n leave_from=leave_period,\n reason=reason_for_leave,\n alt_class_sem=class_semester,\n alt_hour=hour,\n alt_subject=subject,\n alt_assigned_teacher=assigned_teacher,\n alt_linways_assigned=linways_assigned,\n time_of_request = time_of_request\n )\n leave_application.save()\n messages.success(request, \"Your Application submitted successfully\")\n return redirect('profile')\n return render(request, 'staff/new_leave_application.html',{'detail': detail})\n\n@login_required\ndef show_leave_application(request):\n username = request.session.get('username', \"NONE\")\n print(username)\n\n status_of_approved_applications = Status_Leave_Application.objects.filter(employee_id = username).order_by('-leave_from')\n \n pending_applications = Leave_Application.objects.filter(employee_id = username)\n \n return render(request, 'staff/show_leave_applications.html',{'status_of_approved_applications': status_of_approved_applications, 'pending_applications': pending_applications})\n \ndef signup(request):\n if request.method == \"POST\":\n employeeId = request.POST['employeeId']\n ename = request.POST['ename']\n department = request.POST['department']\n designation = request.POST['designation']\n email = request.POST['email']\n password = request.POST['password']\n\n #password1 = request.POST['password1']\n\n\n \n user = User.objects.create_user(employeeId,email,password)\n user.save()\n Staff_Details.objects.create(\n employee_id = employeeId,\n name = ename,\n email = email,\n department = department,\n designation = designation,\n cl1_bal = 6,\n cl2_bal = 6,\n ML_bal = 10,\n VL_bal = 10,\n DL_bal = 10,\n LoP = 0,\n comp_off = 0\n )\n\n return redirect('user_login') \n return render(request, 'staff/signup.html')","repo_name":"shinojeattath/LeaveManagement","sub_path":"staff/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"15156607136","text":"import logging\nimport urllib.request\nimport voluptuous as vol\nimport colorsys\nimport time\nimport threading\nimport pickle\nimport logging\nimport subprocess\nimport os.path\n\nfrom queue import Queue\n\nfrom homeassistant.components.light import ATTR_BRIGHTNESS, ATTR_HS_COLOR, ATTR_COLOR_TEMP, LightEntity, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.util.color as color_util\n\n_LOGGER = logging.getLogger(__name__)\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({})\n\n\nfrom homeassistant.const import CONF_MAC, CONF_CLIENT_ID, CONF_DEVICE_ID, CONF_HOST, CONF_ENTITY_ID\nfrom homeassistant.components.light import PLATFORM_SCHEMA\n\nLIGHT_SCHEMA = vol.All(\n cv.deprecated(CONF_ENTITY_ID),\n vol.Schema(\n {\n vol.Optional(\"name\"): cv.string,\n vol.Optional(\"host\"): cv.string,\n vol.Optional(\"mac\"): cv.string,\n vol.Optional(\"id1\"): cv.port,\n vol.Optional(\"id2\"): cv.port\n }\n ),\n)\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {vol.Required(\"devices\"): cv.schema_with_slug_keys(LIGHT_SCHEMA)}\n)\n\n\nsubprocess.call(['/sbin/apk', 'add', 'bluez-deprecated'])\nimport os\ncwd = os.getcwd()\n_LOGGER.info(cwd)\n\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n devs = []\n for device, device_config in config[\"devices\"].items():\n devs.append(MiLightSm(device_config[\"id1\"], device_config[\"id2\"], device_config[\"mac\"], device_config[\"host\"], device_config[\"name\"]))\n add_devices(devs)\n\nclass GattQueue(threading.Thread):\n def __init__(self, mac, dev, args=(), kwargs=None):\n threading.Thread.__init__(self, args=(), kwargs=None)\n self.queue = Queue()\n self.dev = dev\n self.mac = mac\n self.daemon = True\n\n def run(self):\n# _LOGGER.error(\"Started thread...\")\n while True:\n val = self.queue.get()\n# _LOGGER.error(val)\n ret = subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n# _LOGGER.error(\" \".join(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val]))\n\n if ret is not 0:\n# _LOGGER.error(\"Failed, trying again once.\")\n ret = subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n if ret is not 0:\n# _LOGGER.error(\"Failed, trying again twice.\")\n subprocess.call(['/usr/bin/gatttool', '-i', self.dev, '-b', self.mac, '--char-write-req', '-a', '0x0012', '-n', val])\n\nclass MiLightSm(LightEntity):\n def __init__(self, id1, id2, mac, interface, name):\n self._name = name\n\n self.id1 = id1\n self.id2 = id2\n qu = GattQueue(mac, interface)\n self.q = qu.queue\n qu.start()\n # _LOGGER.error(\"start1\")\n if os.path.isfile(\"./persist/\"+str(self.id1)):\n f = open(\"./persist/\"+str(self.id1), \"rb\")\n self.setParameters(pickle.load(f))\n f.close()\n self.apply()\n else:\n self._state = False\n self._brightness = 100\n self.mode = 1 # 1=temp, 0=color\n self._color = 0\n self._temperature = 100\n self.setStatus(self._state)\n self.apply()\n\n @property\n def name(self):\n return self._name\n\n @property\n def brightness(self):\n return int(self._brightness/100*255)\n\n @property\n def color_temp(self):\n return self._temperature\n\n @property\n def color_hs(self):\n colors = colorsys.hsv_to_rgb(self._color,1,1)\n return color_util.color_RGB_to_hs(int(colors[0]*256), int(colors[1]*256), int(colors[2]*256))\n\n @property\n def hs_color(self):\n colors = colorsys.hsv_to_rgb(self._color,1,1)\n return color_util.color_RGB_to_hs(int(colors[0]*256), int(colors[1]*256), int(colors[2]*256))\n\n @property\n def is_on(self):\n return self._state\n\n @property\n def supported_features(self):\n return SUPPORT_BRIGHTNESS | SUPPORT_COLOR | SUPPORT_COLOR_TEMP\n\n def turn_on(self, **kwargs):\n self._state = True\n if ATTR_COLOR_TEMP in kwargs:\n temp = kwargs[ATTR_COLOR_TEMP]\n self.setParameterInternal(\"temp\", int(temp))\n self.setParameterInternal(\"mode\", 1)\n if ATTR_HS_COLOR in kwargs:\n rgb = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR])\n hsv = colorsys.rgb_to_hsv(rgb[0], rgb[1], rgb[2])\n # if its white, make it white\n #_LOGGER.error(hsv)\n if hsv[2] == 1 or (hsv[2] == 255 and hsv[0] == 0.09959349593495935):\n self.setParameterInternal(\"temp\", self._temperature)\n self.setParameterInternal(\"mode\", 1)\n elif hsv[2] == 250: # cool white\n self.setParameterInternal(\"temp\", 100)\n self.setParameterInternal(\"mode\", 1)\n elif hsv[2] == 230: # gold\n self.setParameterInternal(\"temp\", 255)\n self.setParameterInternal(\"mode\", 1)\n else:\n # otherwise, set colour\n self.setParameterInternal(\"color\", int(hsv[0]*255))\n self.setParameterInternal(\"mode\", 0)\n if ATTR_BRIGHTNESS in kwargs:\n self.setParameterInternal(\"brightness\", int(int(kwargs[ATTR_BRIGHTNESS])/255*100))\n self.setParameterInternal(\"status\", True)\n self.apply()\n\n def turn_off(self, **kwargs):\n self._state = False\n self.setParameterInternal(\"status\", False)\n\n def update(self):\n pass\n\n def setStatus(self, state):\n self._state = state\n if not state:\n self.q.put(self.createPacket([85, 161, self.id1, self.id2, 2, 2, 0, 0, 0, 0, 0]))\n else:\n self.q.put(self.createPacket([32, 161, self.id1, self.id2, 2, 1, 0, 0, 0, 0, 0]))\n\n def setParameterInternal(self, param, value):\n if param == \"status\":\n self.setStatus(int(value))\n elif param == \"mode\":\n self.mode = int(value)\n elif param == \"color\":\n self._color = int(value)\n elif param == \"temp\":\n self._temperature = int(value)\n elif param == \"brightness\":\n self._brightness = int(value)\n\n def apply(self):\n if self.mode == 0:\n self.q.put(self.createPacket([85, 161, self.id1, self.id2 , 2, 4, self._color, 100, 0, 0, 0]))\n self.q.put(self.createPacket([85, 161, self.id1, self.id2, 2, 5, self._color, self._brightness, 0, 0, 0]))\n elif self.mode == 1:\n self.q.put(self.createPacket([20, 161, self.id1, self.id2, 4, 4, self._temperature, 255, 0, 0, 0]))\n self.q.put(self.createPacket([20, 161, self.id1, self.id2 , 4, 5, self._temperature, self._brightness, 0, 0, 0]))\n f = open( \"./persist/\"+str(self.id1), \"wb\" )\n pickle.dump(self.getParameters(), f)\n f.close()\n\n def createPacket(self, data):\n input = data\n\n k = input[0]\n # checksum\n j = 0\n i = 0\n\n while i <= 10:\n j += input[i] & 0xff\n i += 1\n checksum = ((( (k ^ j) & 0xff) + 131) & 0xff)\n\n xored = [(s&0xff)^k for s in input]\n\n offs = [0, 16, 24, 1, 129, 55, 169, 87, 35, 70, 23, 0]\n\n adds = [x+y&0xff for(x,y) in zip(xored, offs)]\n\n adds[0] = k\n adds.append(checksum)\n\n hexs = [hex(x) for x in adds]\n hexs = [x[2:] for x in hexs]\n hexs = [x.zfill(2) for x in hexs]\n\n return ''.join(hexs)\n\n ##### DEPRECATED ############\n def setParameter(self, param, value):\n if param == \"status\":\n self.setStatus(bool(value))\n elif param == \"mode\":\n self.mode = int(value)\n elif param == \"color\":\n self._color = int(value)\n self.mode = 0\n elif param == \"temp\":\n self._temperature = int(value)\n self.mode = 1\n elif param == \"brightness\":\n self._brightness = int(value)\n self.apply()\n time.sleep(0.2)\n\n def setParameters(self, list):\n internal = False\n if list[0][0] == \"status\":\n internal = True\n for a in list:\n if internal == True:\n self.setParameterInternal(a[0], a[1])\n else:\n self.setParameter(a[0], a[1])\n self.apply()\n\n\n def getParameters(self):\n return [ [\"status\", self._state],\n [\"mode\", self.mode],\n [\"color\", self._color],\n [\"temp\", self._temperature],\n [\"brightness\", self._brightness] ]\n\n","repo_name":"souramoo/homeassistant-milight-bluetooth","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":8839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39823237326","text":"from firebase_admin import credentials, initialize_app, storage\n\n\n\ncred = credentials.Certificate(\"parquet-writer-firebase-adminsdk-ibvc3-ccf6d01f9d.json\")\ninitialize_app(cred, {'storageBucket': 'parquet-writer.appspot.com'})\nbucket_name = \"parquet-writer.appspot.com\"\ndef download(path):\n source_blob_name = path\n bucket = storage.bucket()\n blob = bucket.blob(source_blob_name)\n blob.download_to_filename(\"written_csv/file.csv\")\n\ndef downloadToParquet(path):\n source_blob_name = path\n bucket = storage.bucket()\n blob = bucket.blob(source_blob_name)\n blob.download_to_filename(\"parquet/file.parquet\")\n\ndef upload(name, parquet_file):\n storage.child(name+\"/written_parquet/file.parquet\").put(\"/written_parquet/\"+parquet_file)\n url = storage.child(name+\"/written_parquet/file.parquet\").get_url(token=None)\n return url","repo_name":"SultanF1/Parquet_Tools","sub_path":"utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"44894530327","text":"# Excersice HackerRank\n# Artificial IntelligenceStatistics and Machine LearningDay 6: Multiple Linear Regression: Predicting House Prices\n# https://www.hackerrank.com/challenges/computing-the-correlation/problem\n# Compute the correlation\n\nimport math\n\ndef pearson_coef(A,B):\n n = float(len(A))\n meanA = sum(A)/n\n meanB = sum(B)/n\n diff_meanA = map(lambda a : a - meanA, A)\n diff_meanB = map(lambda b : b - meanB, B)\n stdA = math.sqrt((1/(n-1))*sum([c*c for c in diff_meanA]))\n stdB = math.sqrt((1/(n-1))*sum([c*c for c in diff_meanB]))\n p_coef = ( sum(A[i]*B[i] for i in range(int(n))) - n*meanA*meanB )/((n-1)*stdA*stdB) \n return(p_coef)\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n\n\n# Get the parameters:\n# First Line N observatiosn\n# Secon line: records M F C\n\nn= int(input())\nmath_record = []\nphysics_record = []\nchemistry_record = []\nscores = []\nfor i in range(n):\n m, p, c = map(int, input().split())\n math_record.append(m)\n physics_record.append(p)\n chemistry_record.append(c)\n\ncoef_M_P = pearson_coef(math_record,physics_record)\ncoef_P_C = pearson_coef(physics_record,chemistry_record)\ncoef_C_M = pearson_coef(chemistry_record,math_record)\n\nprint(f'{coef_M_P:.2f}')\nprint(f'{coef_P_C:.2f}')\nprint(f'{coef_C_M:.2f}')\n","repo_name":"jjcordova/hackerrank","sub_path":"compute_correlation.py","file_name":"compute_correlation.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23714761440","text":"#Cézarova_šifra\r\nvstup = input('Zadaj text:') #do premennej vstup si uložím zadaný vstup \r\nposun = input('Zadaj posun:') #do premennej posun si uložím posun o koľko posúvam\r\nsifra = '' #premennú sifra nastavím ako string\r\nfor znak in vstup: #for cyklus na šifrovanie\r\n novyznak = znak #do premennej novyznak uložím znak\r\n if 'a' <= znak <= chr(ord('z')-int(posun)): #podmienka ak znak je medzi a a posunom ktorý zadám\r\n novyznak = chr(ord(znak)+int(posun)) ##uložím do premennej novyznak zo zadaným posunom \r\n if znak >= chr(ord('z')-int(posun)): #podmienka ak znak je väčší alebo rovný ako z - zadaný posun\r\n novyznak = chr((ord(znak)-97+int(posun))%26+97) #uložím do premennej novyznak\r\n sifra = sifra+novyznak #do premennej sifra uložím novyznak\r\nprint(sifra) #vypíšem šifru\r\n\r\n","repo_name":"PatrikMraz/Ulohy_z_opakovania_3","sub_path":"Mraz_1.5_28.py","file_name":"Mraz_1.5_28.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"sk","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"36120737648","text":"import os\n\nfrom flask import Blueprint, abort, request\n\nfrom root.auth import is_authorized\n\nfrom .category_controller import categories, categoryController\nfrom .category_query import (\n cache_category_text,\n last_access_register_category_cache,\n search_category,\n)\n\ncategory_router = Blueprint(\"Category\", __name__)\n\n\n@category_router.route(\"/get_category\", methods=[\"POST\"])\ndef get_category():\n AUTH = os.getenv(\"AUTH\")\n authorization_header = request.headers.get(\"Authorization\")\n\n if not is_authorized(\n token_to_validate=AUTH, token_from_request=authorization_header\n ):\n abort(403)\n\n text = request.form.get(\"text\")\n if not text:\n return \"No text\"\n\n search_result = search_category(\n text_to_category=text,\n )\n first_item = search_result[0] if len(search_result) else None\n\n if first_item:\n result = first_item\n last_access_register_category_cache(\n text_to_category=text,\n )\n else:\n result = categoryController.get_category(text)\n cache_category_text(\n text_to_category=text,\n result=result,\n )\n\n return result\n\n\n@category_router.route(\"/get_all_categories\", methods=[\"GET\"])\ndef get_all_categories():\n AUTH = os.getenv(\"AUTH\")\n authorization_header = request.headers.get(\"Authorization\")\n\n if not is_authorized(\n token_to_validate=AUTH, token_from_request=authorization_header\n ):\n abort(403)\n\n return categories\n","repo_name":"openworld-community/ows-events-localisation","sub_path":"root/api/categories/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"6983015416","text":"def solution(N, stages):\n stages_cnt = [[0,0] for _ in range(N+1)]\n failure_rate = {}\n\n for e in stages:\n if e > N: #N보다 클경우 모든 스테이지의 존재하거나 클리어한 사람 +1\n for i in range(1,N+1):\n stages_cnt[i][1] += 1\n else:\n stages_cnt[e][0] += 1 #해당 스테이지에 존재하는 사람\n for i in range(1, e+1):\n stages_cnt[i][1] += 1 #해당 스테이지에 존재하거나 클리어한 사람\n\n for i in range(1, N+1):\n if stages_cnt[i][1] == 0: #처음에 이 예외처리를 안해서 오류남 -> 존재하거나 클리어한 사람이 0명일 경우 0으로 나눌때 오류가 뜸\n rate = 0\n else:\n rate = stages_cnt[i][0] / stages_cnt[i][1]\n failure_rate[i] = rate #dict에 해당 인덱스와 실패율 저장\n\n res = list(dict(sorted(failure_rate.items(), key=lambda x:x[1], reverse=True)).keys()) # 실패율을 기준으로 내림차순한 dict의 keys()를 list화해서 리턴\n\n return res","repo_name":"jeno8522/Coding-Test-Study","sub_path":"2022/9월/2주차/프로그래머스/실패율.py","file_name":"실패율.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"4970037310","text":"'''\nObjective: Static and animation 2D topographic map for brain mapping using power calculated by Welch method\n for Emotiv EPOC 14 channel headset\nInput: csv file (FEIS dataset folder traversing is done)\nOutput: Static 2D topographic map for 21 participants on single phoneme or \n Animation 2D topographic map for 1 participant\n@author: Vinay\nAdapted from: https://github.com/ijmax/EEG-processing-python\n'''\n\nimport os\nfrom pathlib import Path\nimport time\nimport numpy as np\nimport pandas as pd\nfrom scipy import signal\nimport scipy.interpolate\nfrom matplotlib import patches\nimport matplotlib.pyplot as plt\n\ndef get_psds(ch_data, fs = 256, f_range= [0.5, 30]):\n '''\n Calculate signal power using Welch method.\n Input: data- mxn matrix (m: number of channels, n: samples of signals)\n fs- Sampling frequency (default 256Hz)\n f_range- Frequency range (default 0.5Hz to 30Hz)\n Output: Power values and PSD values\n '''\n powers = []\n psds = list()\n for sig in ch_data:\n freq, psd = signal.welch(sig, fs)\n idx = np.logical_and(freq >= f_range[0], freq <= f_range[1])\n powers = np.append(powers, sum(psd[idx]))\n psds.append(psd[idx])\n return powers, psds\n\ndef plot_topomap(data, ax, fig, draw_cbar=False):\n '''\n Plot topographic plot of EEG data. This is specially design for Emotiv 14 electrode data. This can be change for any other arrangement by changing \n ch_pos (channel position array) \n Input: data- 1D array 14 data values\n ax- Matplotlib subplot object to be plotted every thing\n fig- Matplot lib figure object to draw colormap\n draw_cbar- Visualize color bar in the plot\n '''\n N = 300 \n xy_center = [2,2] \n radius = 2 \n \n # AF3, F7, F3, FC5, T7, P7, O1, O2, P8, T8, FC6, F4, F8, AF4\n ch_pos = [[1,4],[0.1,3], [1.5,3.5], \n [0.5,2.5], [-0.1,2], [0.4,0.4], \n [1.5,0], [2.5,0], [3.6,0.4], [4.1,2], \n [3.5,2.5], [2.5,3.5], [3.9,3], [3,4]]\n \n x,y = [],[]\n for i in ch_pos:\n x.append(i[0])\n y.append(i[1])\n \n xi = np.linspace(-2, 6, N)\n yi = np.linspace(-2, 6, N)\n zi = scipy.interpolate.griddata((x, y), data, (xi[None,:], yi[:,None]), method='cubic')\n \n dr = xi[1] - xi[0]\n for i in range(N):\n for j in range(N):\n r = np.sqrt((xi[i] - xy_center[0])**2 + (yi[j] - xy_center[1])**2)\n if (r - dr/2) > radius:\n zi[j,i] = \"nan\"\n \n dist = ax.contourf(xi, yi, zi, 60, cmap = plt.get_cmap('coolwarm'), zorder = 1)\n ax.contour(xi, yi, zi, 15, linewidths = 0.5,colors = \"grey\", zorder = 2)\n \n if draw_cbar:\n cbar = fig.colorbar(dist, ax=ax, format='%.1e')\n cbar.ax.tick_params(labelsize=8)\n \n ax.scatter(x, y, marker = 'o', c = 'k', s = 10, zorder = 3)\n circle = patches.Circle(xy = xy_center, radius = radius, edgecolor = \"k\", facecolor = \"none\", zorder=4)\n ax.add_patch(circle)\n \n for loc, spine in ax.spines.items():\n spine.set_linewidth(0)\n\n ax.set_xticks([])\n ax.set_yticks([])\n \n circle = patches.Ellipse(xy = [0,2], width = 0.4, height = 1.0, angle = 0, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(circle)\n circle = patches.Ellipse(xy = [4,2], width = 0.4, height = 1.0, angle = 0, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(circle)\n \n xy = [[1.6,3.6], [2,4.3],[2.4,3.6]]\n polygon = patches.Polygon(xy = xy, edgecolor = \"k\", facecolor = \"w\", zorder = 0)\n ax.add_patch(polygon) \n\n #ax.set_xlim(-0.2, 4.2)\n ax.set_ylim(-0.2, 4.2)\n return ax\n\n\n# Static visualization for 21 participant\nrootdir = 'C:/Users/vinay/Downloads/FEIS_v1_1/experiments/'\nfig = plt.figure(figsize=(8,10))\nfig.subplots_adjust(hspace=0.5)\nfig.suptitle(\"Topograph for phoneme 'p' in articulator phase\", fontsize=15, y=0.95)\ni = 1\nfor subdir, dirs, files in os.walk(rootdir):\n splitted = Path(subdir).parts\n if splitted[-1] == 'p' and splitted[-2] == 'articulators_eeg':\n for file in files: # reading only 1st file many files\n path = subdir + '/' + file\n data = pd.read_csv(path)\n ch_data = np.transpose(data.to_numpy())\n pwrs, _ = get_psds(ch_data)\n ax = plt.subplot(7, 3, i)\n plot_topomap(pwrs, ax, fig)\n ax.set_title(\"participant \" + str(i))\n i += 1\n break\nplt.show()\nfig.savefig(\"topograph_p_articulator.png\", dpi=300)\n\n'''\n# Animation for only 1 participant\npath = 'C:/Users/vinay/Downloads/FEIS_v1_1/experiments/01/thinking_eeg/f/thinking_f_trial_4.csv'\nplt.ion()\nfig, ax = plt.subplots(figsize=(8,8))\ndata = pd.read_csv(path)\nch_data = np.transpose(data.to_numpy())\nchunk_data = np.array_split(ch_data, 4, axis=1)\nfor chunk in chunk_data: \n pwrs, _ = get_psds(chunk)\n ax.clear() \n plot_topomap(pwrs, ax, fig, draw_cbar=False)\n fig.canvas.draw()\n fig.canvas.flush_events()\n time.sleep(0.01)\n'''","repo_name":"VinayFaria/M.Tech-CSP_PGP","sub_path":"FEIS dataset/codes/topography.py","file_name":"topography.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"8306503312","text":"#!/usr/bin/env python3\nimport copy\nimport logging\nimport os\nimport sys\nimport argparse\nimport json\nimport pandas as pd\nfrom schema.dataschema import Detection, Investigation, dumpJSON, jsonobjproc\nfrom evidenceintegration.DetectionsToVis import DetectionsToVisualization\nfrom evidenceintegration.EvidenceIntegration import EvidenceIntegration, RegionGroup, AlterationGroup\nfrom evidenceintegration.PreprocessInvestigations import PreprocessInvestigations\nfrom evidenceintegration.utils import EvidenceIntegrationUtils\n\nclass DetectionsToCSV:\n\n NOT_APPLICABLE = \"Not applicable\"\n TODO = \"TODO\"\n SAMPLE_ID = \"Sample_ID\"\n NUM_ASSAYS = \"Number_of_Technical_and/or_Biological_Replicates_of_Assay_Performed\"\n CONCENTRATION = \"Concentration_and_Volume_Per_Assay\"\n REF_GEN_USED = \"Reference_Genome_or_Assembly_Used (Y/N)\"\n REF_NAME_ACC = \"Reference_Name_or_Accession\"\n DECISION_CRITERIA = \"Decision_Criteria\"\n DNA_CONCENTRATION = \"Starting_DNA_Concentration\"\n DNA_CONCENTRATION_UNITS = \"Starting_DNA_Concentration_Units\"\n DATE_RUN = \"Date_Run\"\n TESTER = \"Tester_Name\"\n SW_VER = \"Software_Version\"\n HW_ENV = \"Hardware_Environment\"\n COMP_RES = \"Computational_Resources\"\n COMP_TIME = \"Computational_Analysis_Time\"\n ASSAY_TIME = \"Experimental_Assay_Time\"\n SCORE = \"Score_or_Confidence_Measure\"\n ENG_DETECTED = \"Engineering_Detected\"\n ENG_NAME = \"What_was_Detected\"\n NATIVE = \"Native_to_Host\"\n EVIDENCE = \"Evidence_of_Engineering\"\n HOST_SPECIES = \"Host_Species\"\n ENG_DNA_SOURCE = \"Source_of_Engineered_DNA\"\n COORDINATES = \"Base_Pair_Coordinates_or_Gene_Context_in_the_T_&_E_sample\"\n SIZE = \"Size_of_Signature\"\n C_OR_P = \"Chromosome_or_Plasmid\"\n CHROMOSOME = \"Which_Chromosome\"\n PART_CLASS = \"Part_Class\"\n DETECTION_MODULE = \"Detection_Module\"\n NOTES = \"Notes\"\n SIGNATURE_ID = \"Signature_ID\"\n SIGNATURE_GROUP = \"Signature_Group\"\n PARENT_SIGNATURE = \"Parent_Signature\"\n READ_COUNT = \"Read_Count\"\n SEQUENCE = \"Signature_Sequence\" \n\n MIN_CSV_COLUMNS = [\n SAMPLE_ID,\n REF_NAME_ACC,\n SCORE,\n ENG_DETECTED,\n ENG_NAME,\n NATIVE,\n EVIDENCE,\n HOST_SPECIES,\n COORDINATES,\n SIZE,\n PART_CLASS,\n DETECTION_MODULE,\n SIGNATURE_ID,\n SIGNATURE_GROUP,\n READ_COUNT,\n SEQUENCE\n ]\n\n TE_CSV_COLUMNS = [\n SAMPLE_ID,\n NUM_ASSAYS,\n CONCENTRATION,\n REF_GEN_USED,\n REF_NAME_ACC,\n DECISION_CRITERIA,\n DNA_CONCENTRATION,\n DNA_CONCENTRATION_UNITS,\n DATE_RUN,\n TESTER,\n SW_VER,\n HW_ENV,\n COMP_RES,\n COMP_TIME,\n ASSAY_TIME,\n SCORE,\n ENG_DETECTED,\n ENG_NAME,\n NATIVE,\n EVIDENCE,\n HOST_SPECIES,\n ENG_DNA_SOURCE,\n COORDINATES,\n SIZE,\n C_OR_P,\n CHROMOSOME,\n PART_CLASS,\n DETECTION_MODULE,\n NOTES,\n SIGNATURE_ID,\n SIGNATURE_GROUP,\n PARENT_SIGNATURE,\n READ_COUNT,\n SEQUENCE\n ]\n\n\n @staticmethod\n def natural_te_row_for_sample(sample_id):\n row_dict = {}\n row_dict[DetectionsToCSV.SAMPLE_ID] = sample_id\n row_dict[DetectionsToCSV.NUM_ASSAYS] = 1\n row_dict[DetectionsToCSV.CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"no\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DECISION_CRITERIA] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.DNA_CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DNA_CONCENTRATION_UNITS] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DATE_RUN] = \"\"\n row_dict[DetectionsToCSV.TESTER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.SW_VER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.HW_ENV] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_RES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_TIME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ASSAY_TIME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SCORE] = \"0\"\n row_dict[DetectionsToCSV.ENG_DETECTED] = \"no\"\n row_dict[DetectionsToCSV.ENG_NAME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.NATIVE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.EVIDENCE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.HOST_SPECIES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ENG_DNA_SOURCE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.COORDINATES] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SIZE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.C_OR_P] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.CHROMOSOME] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.PART_CLASS] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DETECTION_MODULE] = \"GUARDIAN\"\n row_dict[DetectionsToCSV.NOTES] = \"\"\n\n # -----\n # extra GUARDIAN fields\n # -----\n row_dict[DetectionsToCSV.SIGNATURE_ID] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SIGNATURE_GROUP] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.SEQUENCE] = DetectionsToCSV.NOT_APPLICABLE\n\n\n rows = [row_dict]\n df = pd.DataFrame(rows,\n columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n return df\n\n\n @staticmethod\n def investigation_to_te_df(investigation):\n detections_of_interest = []\n df = pd.DataFrame(\n columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n rows = []\n\n\n\n for detection in investigation.get_detections():\n if detection.get_agent() == EvidenceIntegration.GUARDIAN_FEATURE_GROUP_AGENT_TAG:\n continue\n\n detections_of_interest.append(detection)\n\n all_features = investigation.get_features()\n\n # logging.debug(\"in investigation_to_te_df, all_features: %s\", str([f.get_id() for f in all_features]))\n # logging.debug(\"investigation_to_te_df, investigation provided has %d detections_of_interest\", len(detections_of_interest))\n for detection in detections_of_interest:\n\n # alterations only create one row\n for alteration in detection.get_alterations():\n alteration_rows = DetectionsToCSV.te_rows_for_alteration(alteration, detection, all_features)\n # logging.debug(\"Appending row for alteration: %s\", str(alteration_rows))\n rows = rows + alteration_rows\n # rows.append(row)\n\n # reads can have multiple regions which point at their own features...\n # 1...n rows\n for read in detection.get_reads():\n # logging.debug(\"read: %s\", str(read))\n read_rows = DetectionsToCSV.te_rows_for_read(read, detection, all_features)\n # logging.debug(\"Appending rows for read: %s\", str(read_rows))\n # rows.append(read_rows)\n rows = rows + read_rows\n\n # contigs can have multiple regions which point at their own features...\n # 1...n rows\n for contig in detection.get_contigs():\n contig_rows = DetectionsToCSV.te_rows_for_contig(contig, detection, all_features)\n # logging.debug(\"Appending rows for contig: %s\", str(contig_rows))\n # rows.append(contig_rows)\n rows = rows + contig_rows\n \n\n\n\n df = pd.DataFrame(\n rows, columns=DetectionsToCSV.MIN_CSV_COLUMNS)\n return df\n\n\n @staticmethod\n def te_rows_for_alteration(alteration, detection, features):\n row_dicts = []\n\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n # logging.debug(\"row_dict after te_base_row_for_detection: %s\", str(row_dict))\n\n # row_dict[ENG_NAME] = # must be set by read, contig, or alteration\n # row_dict[EVIDENCE] = # must be set by read, contig, or alteration\n # row_dict[DETECTION_MODULE] = # must be set by read, contig, or alteration\n\n\n # overwrite the type, always found in alteration so no try block necessary ATM\n row_dict[DetectionsToCSV.EVIDENCE] = alteration.get_type()\n\n # try to grab agent\n try:\n if alteration.get_agent() is not None and alteration.get_agent() != \"\":\n row_dict[DetectionsToCSV.DETECTION_MODULE] = alteration.get_agent()\n except AttributeError:\n # no agent in the alteration... we'll have to get it from feature.\n pass\n\n\n # try to grab hostTaxa\n # todo maybe move this into something for all subclasses of Evidence\n try:\n if alteration.get_hostTaxa() is not None and alteration.get_hostTaxa() != \"\":\n row_dict[DetectionsToCSV.HOST_SPECIES] = alteration.get_hostTaxa()\n except AttributeError:\n pass\n\n # 2. The \"Reference_Genome_or_Assembly_Used_(Y/N)\" column should be set to \"yes\"\n # and \"Reference_Name_or_Accession\" should contain an accession number \n # if an Alteration has a \"targetAssembly\" property.\n try:\n if alteration.get_targetAssembly() is not None:\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"yes\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = alteration.get_targetAssembly()\n except AttributeError:\n pass\n\n # get readCount if it exists (only Targeted Search ATM)..\n if alteration.get_readCount() is not None:\n row_dict[DetectionsToCSV.READ_COUNT] = alteration.get_readCount()\n\n\n if alteration.get_derivedFeature() is not None:\n # logging.debug(\"alteration's derivedFeature: %s\", str(alteration.get_derivedFeature()))\n\n for feature in features:\n if feature.get_id() == alteration.get_derivedFeature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n break\n\n if (alteration.get_derivedFeature() is None) and (alteration.get_targetFeature() is not None):\n # logging.debug(\"alteration's targetFeature: %s\", str(alteration.get_targetFeature()))\n for feature in features:\n if feature.get_id() == alteration.get_targetFeature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n break\n\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_contig(contig, detection, features):\n row_dicts = []\n\n # watch this.. but if the contig doesn't have a region.. we will not produce a T&E row for it.\n regions = []\n try:\n regions = contig.get_regions()\n except AttributeError:\n pass\n\n for region in regions:\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_region(region, row_dict, contig.get_source(), features)\n # row_dicts.append(row_dict)\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_read(read, detection, features):\n row_dicts = []\n\n for region in read.get_regions():\n row_dict = DetectionsToCSV.te_base_row_for_detection(detection)\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_region(region, row_dict, read.get_source(), features)\n # row_dicts.append(row_dict)\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_feature(feature, row_dict_arg, features, parent_feature_id = None):\n row_dicts = []\n row_dict = copy.deepcopy(row_dict_arg)\n # logging.debug(\"te_rows_for_feature called, feature: %s\", str(feature))\n\n # only set PART_CLASS to Role if it wasn't set by a parent..\n if row_dict[DetectionsToCSV.PART_CLASS] == \"\":\n try:\n row_dict[DetectionsToCSV.PART_CLASS] = feature.get_role()\n except AttributeError:\n pass\n\n\n # get Agent from Feature if it exists\n if feature.get_agent() is not None and feature.get_agent() != \"\":\n row_dict[DetectionsToCSV.DETECTION_MODULE] = feature.get_agent()\n\n\n # \"Signature_ID\" should be populated with the \"id\" property of a feature.\n if feature.get_id() is not None and feature.get_id() != \"\":\n row_dict[DetectionsToCSV.SIGNATURE_ID] = feature.get_id()\n\n # \"Signature_Sequence\" should be populated the \"sequence\" property of the feature.\n if feature.get_sequence() is not None and feature.get_sequence() != \"\":\n row_dict[DetectionsToCSV.SEQUENCE] = feature.get_sequence()\n row_dict[DetectionsToCSV.SIZE] = len(feature.get_sequence())\n\n # \"Parent_Signature\" should be populated if a row represents a feature identified\n # by the \"subFeatures\" property of another feature (populate using this parent feature's\n # \"id\" property).\n if parent_feature_id is not None:\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = parent_feature_id\n\n identifier = \"\"\n feature_id = feature.get_id()\n feature_name = feature.get_name()\n feature_source = feature.get_source()\n\n\n # If a Feature has both a name and a source, compare them. If either its name\n # or its source is a substring of the other, then identify the feature using its source.\n # Otherwise, identify the feature using the concatenation of “Subsequence of “ and \n # its name, stripping any commas from the result.\n if (feature_name is not None) and (feature_source is not None):\n if (feature_name in feature_source) or (feature_source in feature_name):\n identifier = feature_source\n else:\n identifier = \"Subsequence of \" + feature_name\n identifier = \"\".join(identifier.split(\",\"))\n\n # If a Feature lacks a name but has a source, then identify the Feature using the concatenation\n # of of “Subsequence of “ and its source, stripping any commas from the result.\n elif (feature_name is None) and (feature_source is not None):\n identifier = \"Subsequence of \" + feature_source\n identifier = \"\".join(identifier.split(\",\"))\n\n # If a Feature lacks a source but has a name, then identify the Feature using its name.\n elif (feature_source is None) and (feature_name is not None):\n identifier = feature_name\n\n # If a Feature lacks both a source and a name, then identify it using its id.\n elif (feature_source is None) and (feature_name is None):\n identifier = feature_id\n\n row_dict[DetectionsToCSV.ENG_NAME] = identifier\n row_dicts.append(row_dict)\n\n # If a Feature has subFeatures, then apply the previous steps to them as well. \n # For the overall JSON-to-CSV conversion, this should yield one row for the parent \n # Feature and one row for each child Feature. \n if (feature.get_subFeatures() is not None) and (len(feature.get_subFeatures()) > 0):\n for feature_in_subfeatures in feature.get_subFeatures():\n for f in features:\n if f.get_id() == feature_in_subfeatures:\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(f, row_dict, features, feature.get_id())\n # row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict_arg, features)\n\n\n\n return row_dicts\n\n\n @staticmethod\n def te_rows_for_region(region, row_dict_arg, source_arg, features):\n row_dicts = []\n row_dict = copy.deepcopy(row_dict_arg)\n # logging.debug(\"te_rows_for_region called, region: %s\", str(region))\n\n\n # source, start, and end\n source = source_arg.split(\"/\")[-1]\n start = -1\n end = -1\n try:\n start = region.get_start()\n end = region.get_end()\n except AttributeError:\n pass\n\n try:\n start = region.get_featureStart()\n end = region.get_featureEnd()\n except AttributeError:\n pass\n\n if start != -1 and end != -1:\n coordinates = source + \":\" + str(start) + \"-\" + str(end)\n else:\n coordinates = source\n\n row_dict[DetectionsToCSV.COORDINATES] = coordinates\n\n\n # role into Part_Class\n try:\n row_dict[DetectionsToCSV.PART_CLASS] = region.get_role()\n except AttributeError:\n pass\n\n\n # get info from the region's feature if it has one (it better...)\n if region.get_feature() is not None:\n for feature in features:\n if feature.get_id() == region.get_feature():\n row_dicts = row_dicts + DetectionsToCSV.te_rows_for_feature(feature, row_dict, features)\n\n\n return row_dicts\n\n\n\n @staticmethod\n def te_base_row_for_detection(detection):\n\n row_dict = {}\n row_dict[DetectionsToCSV.SAMPLE_ID] = detection.get_sample()\n row_dict[DetectionsToCSV.NUM_ASSAYS] = 1\n row_dict[DetectionsToCSV.CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.REF_GEN_USED] = \"no\"\n row_dict[DetectionsToCSV.REF_NAME_ACC] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DECISION_CRITERIA] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.DNA_CONCENTRATION] = DetectionsToCSV.NOT_APPLICABLE\n row_dict[DetectionsToCSV.DNA_CONCENTRATION_UNITS] = DetectionsToCSV.NOT_APPLICABLE\n try:\n row_dict[DetectionsToCSV.DATE_RUN] = detection.get_date()\n except AttributeError:\n row_dict[DetectionsToCSV.DATE_RUN] = \"\"\n row_dict[DetectionsToCSV.TESTER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.SW_VER] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.HW_ENV] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_RES] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.COMP_TIME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.ASSAY_TIME] = DetectionsToCSV.NOT_APPLICABLE\n try:\n row_dict[DetectionsToCSV.SCORE] = detection.get_confidence()\n except AttributeError:\n row_dict[DetectionsToCSV.SCORE] = \"\"\n row_dict[DetectionsToCSV.ENG_DETECTED] = \"yes\"\n row_dict[DetectionsToCSV.ENG_NAME] = \"\" # must be set by read, contig, or alteration\n row_dict[DetectionsToCSV.NATIVE] = \"no\"\n row_dict[DetectionsToCSV.EVIDENCE] = \"insertion\"\n row_dict[DetectionsToCSV.HOST_SPECIES] = \"\"\n row_dict[DetectionsToCSV.ENG_DNA_SOURCE] = \"\"\n row_dict[DetectionsToCSV.COORDINATES] = \"\"\n row_dict[DetectionsToCSV.SIZE] = \"\"\n row_dict[DetectionsToCSV.C_OR_P] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.CHROMOSOME] = DetectionsToCSV.TODO\n row_dict[DetectionsToCSV.PART_CLASS] = \"\"\n row_dict[DetectionsToCSV.DETECTION_MODULE] = \"\" # must be set by read, contig, or alteration\n row_dict[DetectionsToCSV.NOTES] = \"\"\n\n # -----\n # extra GUARDIAN fields\n # -----\n row_dict[DetectionsToCSV.SIGNATURE_ID] = \"\"\n row_dict[DetectionsToCSV.SIGNATURE_GROUP] = detection.get_sample() + \":\" + DetectionsToCSV.signature_group_str_for_detection(detection)\n row_dict[DetectionsToCSV.PARENT_SIGNATURE] = \"\"\n row_dict[DetectionsToCSV.READ_COUNT] = \"\"\n row_dict[DetectionsToCSV.SEQUENCE] = \"\"\n\n return row_dict\n\n\n @staticmethod\n def signature_group_str_for_detection(detection):\n # For the \"Signature_Group\" column, we could potentially use any appropriate IDs for\n # the meta-groups that you may form during integration, or we could use the shortest\n # ID of one of the features from a group. For the attached example, I made the feature\n # IDs by prefixing the pre-evidence-integration feature IDs with their detecting agents,\n # but these IDs would actually take whatever form we are currently using to ensure unique\n # feature IDs post-evidence-integration.\n\n # logging.debug(\"Detection, singular=%d, agent=%s\", int(detection.get_singular()), str(detection.get_agent()))\n\n # These are from EvidenceIntegration, so all_regions are in one RegionGroup\n # and all_alterations are in one AlterationGroup\n all_regions = EvidenceIntegration.all_regions_for_detection(detection)\n all_alterations = EvidenceIntegration.all_alterations_for_detection(\n detection)\n\n alteration_str = None\n # it has an AlterationGroup\n if len(all_alterations):\n alteration_group = AlterationGroup(all_alterations[0])\n for alteration in all_alterations[1:]:\n alteration_group.add_alteration(alteration)\n\n try:\n alteration_str = alteration_group.descriptive_name_for_csv()\n except AttributeError as ae:\n logging.warn(\"Using str(AlterationGroup) due to AttributeError: %s\", str(ae))\n alteration_str = str(alteration_group)\n\n region_str = None\n # it has a RegionGroup\n if len(all_regions):\n region_group = RegionGroup(all_regions[0])\n for region in all_regions[1:]:\n region_group.add_region(region)\n\n\n try:\n region_str = region_group.descriptive_name_for_csv()\n except AttributeError as ae:\n logging.warn(\n \"Using str(RegionGroup) due to AttributeError: %s\", str(ae))\n region_str = str(region_group)\n\n\n if alteration_str is not None and region_str is not None:\n signature_group_str = \"Composite detection with an AlterationGroup and RegionGroup. AlterationGroup: \"\n signature_group_str += alteration_str + \". RegionGroup: \"\n signature_group_str += region_str\n elif alteration_str is not None:\n signature_group_str = \"AlterationGroup: \"\n signature_group_str += alteration_str\n else:\n signature_group_str = \"RegionGroup: \"\n signature_group_str += region_str\n\n # logging.debug(\"signature_group_str: %s\", str(signature_group_str))\n # logging.debug(\"alteration_str: %s\", str(alteration_str))\n # logging.debug(\"region_str: %s\", str(region_str))\n return signature_group_str\n\n\ndef main(args=None):\n if args is None:\n args = sys.argv[1:]\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-j', '--json_files', nargs='*', default=[])\n parser.add_argument('-d', '--json_dirs', nargs='*', default=[])\n parser.add_argument('-o', '--out_dir', nargs=1, default=None)\n parser.add_argument('-l', '--integration_log', nargs='?', default='')\n parser.add_argument('-i', '--integrate', action='store_true', default=False)\n\n args = parser.parse_args(args)\n json_files = args.json_files\n json_dirs = args.json_dirs\n out_dir = args.out_dir\n integrate = args.integrate\n\n if len(args.integration_log) > 0:\n for handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\n\n logging.basicConfig(level=logging.INFO, filename=args.integration_log, filemode='w',\n format='%(levelname)s : %(message)s')\n else:\n logging.basicConfig(level=logging.DEBUG,\n format='%(levelname)s : %(message)s')\n\n if ((len(json_files) == 0 or json_files is None) and (len(json_dirs) == 0 or json_dirs is None)):\n logging.error(\n \"Must supply either a directory in json_dirs, or a file in json_files.\")\n exit()\n\n logging.debug(\"json_files in: %s\", str(json_files))\n if len(json_files) == 1:\n parts = json_files[0].split(\",\")\n tmp = []\n for part in parts:\n tmp.append(part.strip())\n json_files = tmp\n\n if (len(json_dirs) == 1):\n parts = json_dirs[0].split(\",\")\n tmp = []\n for part in parts:\n tmp.append(part.strip())\n for json_dir in tmp:\n json_files = json_files + \\\n EvidenceIntegrationUtils.get_json_files_from_dir(\n json_dir)\n\n if (len(out_dir) == 1):\n out_dir = out_dir[0]\n os.makedirs(out_dir, exist_ok=True)\n # if not os.path.exists(out_dir):\n # os.makedirs(out_dir)\n else:\n logging.error(\"supply output dir for json and csv!\")\n exit()\n\n all_investigations = []\n for json_file in json_files:\n logging.debug(\n \"Creating Investigation object for json_file: %s\", str(json_file))\n investigation = Investigation()\n with open(json_file) as json_handle:\n json_dict = json.load(json_handle)\n investigation.read_from_json(json_dict)\n logging.debug(\"investigation: %s\", str(investigation))\n all_investigations.append(investigation)\n\n\n\n if integrate:\n base_detections = DetectionsToVisualization.json_files_to_detections(\n json_files)\n\n frames = []\n processed_investigations = PreprocessInvestigations.process_investigations(\n all_investigations)\n\n sample_to_guardian_investigation = EvidenceIntegration.integrate(\n processed_investigations, json_out_dir=out_dir)\n\n logging.debug(\"all samples: %s\", str(sample_to_guardian_investigation.keys()))\n\n for sample in sample_to_guardian_investigation:\n guardian_investigation = sample_to_guardian_investigation[sample]\n te_df = DetectionsToCSV.investigation_to_te_df(guardian_investigation)\n frames.append(te_df)\n\n non_eng_sample_ids = []\n for detection in base_detections:\n # skip GUARDIAN detections and GUARDIAN_FEATURE_GROUPS\n try:\n if detection.get_singular() == True:\n continue\n except AttributeError:\n # doesn't have singular set, go ahead and let it through\n pass\n # if the detection did not result in a guardian investigation, there is no engineering found\n if detection.get_sample() not in sample_to_guardian_investigation:\n te_df = DetectionsToCSV.natural_te_row_for_sample(detection.get_sample())\n non_eng_sample_ids.append(detection.get_sample())\n frames.append(te_df)\n\n logging.debug(\"samples w/o engineering found: %s\", str(non_eng_sample_ids))\n\n whole_df = pd.concat(frames, ignore_index=True)\n whole_df.to_csv(out_dir + \"/guardian-out.csv\", index=False)\n\n else:\n # just doing 1 for now...\n df = DetectionsToCSV.investigation_to_te_df(all_investigations[0])\n\n logging.debug(\"df: %s\", str(df))\n df.to_csv(out_dir + \"/guardian-out.csv\", index=False)\n\n print('Finished')\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"raytheonbbn/midoe","sub_path":"evidenceintegration/DetectionsToCSV.py","file_name":"DetectionsToCSV.py","file_ext":"py","file_size_in_byte":27358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"920333594","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport time\r\nimport datetime\r\n\r\ndef home(master):\r\n\r\n # Frame 1\r\n frame1 = Frame(master, bg=\"white\",width =900)\r\n frame1.pack(side= TOP, fill = X)\r\n label_heading = Label(frame1)\r\n label_heading.config(text=\"Collyer's Theatre Ticket Booking System\", font=(\"Simplifica 18 bold\"), bg='white', padx=20, pady=25)\r\n label_heading.pack(side=LEFT)\r\n localtime = time.asctime(time.localtime(time.time()))\r\n lblInfo = Label(frame1, font=('arial', 12, 'bold'),\r\n text=localtime, fg=\"Steel Blue\",\r\n bd=10, anchor='w',padx=50)\r\n\r\n lblInfo.pack(side=RIGHT)\r\n # Frame 2\r\n frame2 = Frame(master, bg=\"black\")\r\n frame2.pack(side=TOP, pady=20)\r\n\r\n Intro = \"\"\"Welcome to the Collyer's Theatre Booking System for the 2020 Collyers Performance!.\"\"\"\r\n\r\n Intro_text = Label(frame2)\r\n Intro_text.config(text=Intro, font=\"times 12\", bg=\"light blue\")\r\n Intro_text.grid(row=1, padx=100, pady=10)","repo_name":"HassanMujtaba12/Theatre-Booking-System","sub_path":"Home.py","file_name":"Home.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38709913757","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n# use a variable to control gameplay being active\ngame_active = \"y\"\n\n# use a while loop to control game repeat\nwhile game_active == \"y\":\n import time\n import os\n \n os.system('cls')\n \n # create a dictionary to store each board location and the player whose token holds it. Will be used to track changes during gameplay\n board_locs_dict = {1:\"1\",2:\"2\",3:\"3\",4:\"4\",5:\"5\",6:\"6\",7:\"7\",8:\"8\",9:\"9\"}\n\n # create a function to display the current board throughout the game\n def display_game_board():\n print(f\"{board_locs_dict[1]} | {board_locs_dict[2]} | {board_locs_dict[3]}\")\n print(\"\\n--|---|--\")\n print(f\"{board_locs_dict[4]} | {board_locs_dict[5]} | {board_locs_dict[6]}\")\n print(\"\\n--|---|--\")\n print(f\"{board_locs_dict[7]} | {board_locs_dict[8]} | {board_locs_dict[9]}\")\n\n # begin gameplay here\n print(\"Welcome to Tic-Tac-Toe! Let's begin!\")\n time.sleep(2)\n print(\"\\nIn this game, your moves will be recorded on a game board looking like the one below.\\n\")\n display_game_board()\n time.sleep(4)\n print(\"\"\"\\nThe spots are numbered in the order that you'll eventually use to select them during gameplay. But before we begin,\nwe'll need a little bit more information...\\n\"\"\")\n\n # collect players names and assign player tokens below\n p1_token = None\n p2_token = None\n\n p1_name = str(input(\"Player 1 - what is your name?: \"))\n\n # request token selection from player 1 - force to 'x' or 'o'\n p1_token = str(input(\"Great! And will you be playing as x or o?\")).lower()\n while p1_token not in ['x','o']:\n p1_token = str(input(f\"{p1_name}, please select 'x' or 'o'\")).lower()\n\n print(f\"\\nThanks {p1_name}!\")\n print(\"\\n\")\n time.sleep(2)\n\n p2_name = str(input(\"Player 2 - what is your name?: \"))\n # set player 2 token equal to the opposite of player 1\n if p1_token == 'x':\n p2_token = 'o'\n else:\n p2_token = 'x'\n\n print(f\"\\nThanks {p2_name}!\")\n\n # create a dictionary consisting of player identifiers as keys, name and token as values to use in later references\n player_dict = {\"p1\":[p1_name,p1_token],\"p2\":[p2_name,p2_token]}\n\n time.sleep(2)\n print(\"\\n\\nOkay, so {0[0]} will be player one and use {0[1]}, and {1[0]} will be player two, using {1[1]}. Let's begin!\\n\".format(player_dict[\"p1\"],player_dict[\"p2\"]))\n time.sleep(4)\n #####\n # create a function to identify the potential winning conditions. In this case that should mean that either a full row, a full\n # column, or a diagonal of three all share the same token. We'll refer to locations in the \"board_locs_dict\" to check for a win\n #####\n\n def check_for_win():\n row_cond = None\n col_cond = None\n diag_cond = None\n\n for x in [1,4,7]:\n if board_locs_dict[x] == board_locs_dict[x+1] == board_locs_dict[x+2]:\n row_cond = True\n break\n for x in [1,2,3]:\n if board_locs_dict[x] == board_locs_dict[x+3] == board_locs_dict[x+6]:\n col_cond = True\n break\n for x in [1,3]:\n if x == 1:\n if board_locs_dict[x] == board_locs_dict[x+4] == board_locs_dict[x+8]:\n diag_cond = True\n break\n if x == 3:\n if board_locs_dict[x] == board_locs_dict[x+2] == board_locs_dict[x+4]:\n diag_cond = True\n break\n\n return row_cond or col_cond or diag_cond\n\n # create a list to keep track of eligible selections from the board during gameplay and count of turns\n board_tracking_list = [key for key in board_locs_dict.keys()]\n \n # create a function to request a selection from the player\n def request_p_choice():\n choice = int(input(f\"{cur_player[0]} - please choose an available numbered location from the board: \"))\n while choice not in board_tracking_list:\n choice = int(input(f\"That is not a valid selection. Please try again: \"))\n return choice\n\n #####\n # CREATE AND EXECUTE THE CORE GAMEPLAY LOOP \n #####\n\n # create a variable that will be used to alternate between players. Start at player 1\n cur_player = player_dict[\"p1\"]\n \n os.system('cls')\n \n # begin a while loop referring to the length of the board tracking list. Each turn will remove an element from the list, so\n # the loop will end when all selections have been exhausted\n while len(board_tracking_list) > 0:\n display_game_board()\n print(\"\\n\")\n p_choice = request_p_choice()\n board_locs_dict[p_choice] = cur_player[1]\n board_tracking_list.pop(board_tracking_list.index(p_choice))\n if check_for_win() is True:\n os.system('cls')\n time.sleep(1)\n print(\"\\nWe have a winner!\\n\")\n time.sleep(1)\n display_game_board()\n time.sleep(1)\n print(f\"\\nCongratulations {cur_player[0]}, you have won the game!\")\n break\n else:\n if cur_player == player_dict[\"p1\"]:\n cur_player = player_dict[\"p2\"]\n else:\n cur_player = player_dict[\"p1\"]\n time.sleep(1)\n os.system('cls')\n\n time.sleep(3)\n\n if len(board_tracking_list) == 0:\n print(\"\\nLooks like we did not end up with a winner. Thanks for playing!\")\n else:\n print(\"\\nThanks for playing!\\n\")\n \n time.sleep(2)\n game_replay = str(input(\"Would you like to play again? Y or N: \")).lower()\n while game_replay not in ['y','n']:\n game_replay = str(input(\"Not a valid response - please enter Y or N: \"))\n game_active = game_replay\n print(\"\\n\")\n\ntime.sleep(2)\n\nprint(\"\\nOkay, later on!\")\n\ntime.sleep(4)","repo_name":"vicemayor/my_Python-3-Bootcamp-work","sub_path":"my_Milestone_TicTacToe_game_FINAL.py","file_name":"my_Milestone_TicTacToe_game_FINAL.py","file_ext":"py","file_size_in_byte":5816,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"34993950272","text":"from fastapi.testclient import TestClient\nfrom fastapi import status\nfrom main import app\nfrom routers.conecction_db import select_quantity_cripto\n\nclient = TestClient(app)\n\ndef test_venta():\n response = client.post(\"/venta\",\n json={\n \"cantidad\": 1.0\n }) \n assert response.status_code == status.HTTP_201_CREATED\n\ndef test_cantidad_disponible_para_venta(): \n response = client.post(\"/venta\",\n json={\n \"cantidad\": 10000 # cantidad mayor a lo disponible para probar\n })\n cantidad = select_quantity_cripto()\n assert response.status_code == status.HTTP_406_NOT_ACCEPTABLE\n detail=f\"error : Cantidad disponible: {str(cantidad)} - Cantidad solicitada: 10000.0\"\n assert response.json() == {'detail':detail}\n\ndef test_cantidad_venta_equal_0():\n response = client.post(\"/venta\",\n json={\n \"cantidad\": 0\n }) \n assert response.status_code == status.HTTP_400_BAD_REQUEST\n detail=\"La cantidad vendida debe ser mayor a 0\"\n assert response.json() == {'detail':detail}","repo_name":"eze2286/exchange_crypto","sub_path":"test_endpoints/test_venta.py","file_name":"test_venta.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5975456912","text":"class Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n rows, cols = len(heights), len(heights[0])\n pset = set()\n aset = set()\n \n def dfs(r, c, visit, prevHeight):\n if (r, c) in visit or r not in range(rows) or c not in range(cols) or heights[r][c] < prevHeight:\n return\n visit.add((r, c))\n directions = [(1,0),(0,1),(-1,0),(0,-1)]\n for dr, dc in directions:\n nr, nc = r + dr, c + dc\n dfs(nr, nc, visit, heights[r][c])\n \n for c in range(cols):\n dfs(0, c, pset, heights[0][c])\n dfs(rows - 1, c, aset, heights[rows - 1][c])\n \n for r in range(rows):\n dfs(r, 0, pset, heights[r][0])\n dfs(r, cols - 1, aset, heights[r][cols - 1])\n \n res = []\n for r in range(rows):\n for c in range(cols):\n if (r, c) in pset and (r, c) in aset:\n res.append([r, c])\n \n return res","repo_name":"mchae90/dsa","sub_path":"lp/medium/pacific_atlantic_waterflow.py","file_name":"pacific_atlantic_waterflow.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27770692422","text":"import sys\n\nfrom alembic.config import Config\nfrom alembic import command\nfrom AuthService import settings\n\n\ndef drop_all(alembic_conf=None):\n \"\"\"\n Drops all tables in the database.\n\n @:param alembic_conf: Alembic configuration to be used.\n \"\"\"\n\n if alembic_conf is None:\n alembic_conf = initialize_alembic_conf()\n\n print(\"Dropping all tables in 'auth.models'..\")\n\n from auth import models\n command.downgrade(alembic_conf, \"base\")\n\n print(\"SUCCESS\")\n\n\ndef initialize_alembic_conf():\n \"\"\"\n Initializes alembic configuration.\n \"\"\"\n config = Config(\"alembic.ini\")\n config.set_main_option('script_location', \"alembic\")\n config.set_main_option('sqlalchemy.url', settings.SQLALCHEMY_DB_URL)\n\n return config\n\n\ndef flush_db():\n \"\"\"\n Clears the current database tables by dropping tables and creating new\n empty ones.\n \"\"\"\n\n conf = initialize_alembic_conf()\n\n drop_all(conf)\n\n print(\"Upgrading migrations to head..\")\n command.upgrade(conf, \"head\")\n print(\"SUCCESS\")\n\n\ndef call_command():\n \"\"\"\n Parses the system arguments to call the appropriate command.\n \"\"\"\n commands = {\n \"drop_all\": drop_all,\n \"flush_db\": flush_db\n }\n if len(sys.argv) != 2:\n raise Exception(\n \"Bad script usage. Example: python manage.py [command]\"\n )\n\n command_name = sys.argv[1]\n if command_name not in commands:\n raise Exception(f\"Unrecognized command '{command_name}'\")\n\n commands[command_name]()\n\n\nif __name__ == \"__main__\":\n call_command()\n","repo_name":"biothings/biothings_oauth","sub_path":"auth_service/src/AuthService/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21455113023","text":"# são funções como quaisquer outras\n\n# Basicamente metodos são divididos em dois grupos:\n# metodos de instancia e metodos de classe.\n\n\n# 1 ) METODOS DE INSTANCIA (ACESSADOS SOMENTE PELO OBJETO , APÓS SEREM INSTANCIADOS PELA CLASSE)\n\n# eles precisam de uma instancia da classe (instancia e objetos são a mesma coisa) para ser usado.\n\n# 1.1) metodo construtor (constructor)\n# conhecido tbm como metodo magico( assim como outros que começam e terminam com dunder [__ __])\n# possui esse nome pois controi objetos da classe a que pertence, ou seja, serve para instancia objetos a classe que ele pertence\n# instancia o objeto pato pertencente a classe animais\n\n\n# sintaxe: def __init__(self, parametros):\n # bloco\n\n# SELF - é o proprio objeto, self é uma forma de referenciar esse objeto (foque na palavra ESSE) ---> (self tem o mesmo conceito de THIS no javascript)\n# SELF é o objeto / instancia --> é convencional pode usar qualquer nome\n\n\n # ex\n\nfrom xml.sax.handler import feature_external_ges\n\n\nclass Carro:\n def __init__(self, portas, cor):\n # atributos(caracteristicas do carro)\n self.portas = portas # publico\n self.cor = cor # publico\n self.__arcondicionado = True # privado\n #ou seja, o meu proprio objeto (self) esta recebendo o atributo portas e cor\n# nota a seguinte sintaxe self.__arcondicionado = True, QUANDO PASSAMOS UM ATRIBUTO OU CLASSE COM 2 UNDERLINES QUEREMOS DIZER QUE SÃO ATRIBUTOS OU CLASSES PRIVADOS\n# nossa classe foi criada, agora vamos instanciar um objeto criando o objeto ferrari\n\nferrari = Carro('4 portas','preta')\n\nprint(ferrari) # <__main__.Carro object at 0x7f6d6e364460>\n\n\n# PARA ACESSAR UM ATRIBUTO DE UMA CLASSE ACESSAMOS USANDO O PONTO ( . ), por exemplo para acessar o atributo portas do objeto ferrari --> ferrari.portas\n# A FORMA DE ACESSAR UM OBJETO É IDENTICA A FORMA QUE ACESSAMOS OBJETOS EM JAVASCRIPT\n# ex\n\n\nprint(ferrari.portas) # 4 portas # retorna o valor do atributo portas do objeto ferrari\n\nprint(ferrari.cor) # preta # retorna o valor do atributo cor do objeto ferrari\n\n\n# __arcondicionado é um atributo privado da classe Carro, oque aconteceria se tentassemos acessar ele?\n\n# print(ferrari.__arcondicionado) # AttributeError: 'Carro' object has no attribute '__arcondicionado'\n# como é um atributo privado ele não pode ser acessado por um objeto\n\n\n\n# ATRIBUTO DE CLASSE\n\n# são atributos usados fora do construtor, porem dentro da classe, para acessarmos ele dentro de um metodo (como o constructor por exemplo), devemos chamar a instancia da propria classe\n# sintaxe : classe Cliente:\n #servico = 'contratado'\n #def __init__(self,nome,cpf):\n #Cliente.servico = False # ---> acessamos a instancia da classe Cliente e seu atributo de classe 'servico'\n\n# LEMBRANDO QUE ATRIBUTOS DE CLASSE PODEM SER ACESSADOS DA MESMA FORMA POR UM OBJETO : nome_objeto.nome_atributo, são praticamente atributos (estaticos)\n\n# ex\n\nclass Sapato:\n qtd = 7 # atributo de classe\n def __init__(self, cor, tamanho, preco, qtdCompra): # atributos dentro do metodo\n self.cor = cor\n self.tamanho = tamanho\n self.preco = preco\n self.qtdCompra = qtdCompra\n Sapato.qtd += self.qtdCompra\n# vamos instanciar um objeto agora, usando a classe acima\n\ntamanco = Sapato('preto',40,40.00,2)\n\nprint(tamanco.qtd) # 9 # retorna 9 pois declaramos dentro do construtor que o atributo de classe qtd = 7 agora recebe a soma da quantidade comprada (Sapato.qtd += self.qtdCompra)\n# e como a qtdCompra do objeto tamanco é 2, 2 + 7 = 9.\n\nprint(Sapato.qtd)\n\n\n# agora vamos supor que nunca tivemos o objeto tamanco sendo instanciado pela classe Sapato\n\nprint(Sapato.qtd) # 7 , ainda poderiamos acessar o atributo de classe, usando a propria instancia da classe: instancia_da_classe.nome_atributo_de_classe\n\n\n\n# CRIANDO METODOS --> (que são basicamente atributos que atuam como funções)\n# todos os metodos criados dentro da classe pertencem aos objetos instanciados por ela\n\n# lembrando que os metodos criados, são metodos de instancia ou seja, você não consegue chamar uma classe e usar eles, somente depois que instanciamos um objeto com a classe que podemos acessar eles via objeto\n\nclass Computador:\n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n # criando metodos de ligar e desligar o computador\n def ligar(self): \n self.ligado = True\n return self.ligado\n\n def desligar(self):\n self.ligado = False\n return self.ligado\n\n def memoria(self,ram): \n self.ram = ram\n\n\nacer = Computador('preto',13,20,False)\n\nprint(acer.ligado) # False\n# vamos agora chamar o metodo ligar\n\n\nacer.ligar() # acessando o metodo ligar da classe Computador\n\nprint(acer.ligado) # True\n\n \nacer.desligar() # acessando o metodo desligar da classe Computador\n\n\nprint(acer.ligado) # True\n\n\n# Vamos agora acessar o metodo ram (porem note que o metodo ram tem um parametro ram, logo devemos primeiro acessar esse metodo instanciando esse parametro)\n\nacer.memoria('8gb') # acessando o metodo memoria, e criando uma instancia ram\n\n\nprint(acer.ram) # 8gb # acessando a instancia ram\n\n\n\n\n# OBS -->> SEMPRE EVITE CRIAR METODOS USANDO DUNDER --> pode haver conflito com alguns metodos internos da linguagem.\n# ex: __name__ e __main__\n\n# OBS2 --> nome de metodos possuem APENAS letras minusculas. Em caso de haver mais de uma palavra, separar pelo underline (como a nomenclatura de uma função normal!)\n# ex: def controle_remoto() , def mae_pai_filho_filha()\n\n\n\n# 2) METODOS DE CLASSE\n\n# - Necessario utilizar um decorador: @classmethod\n\n# - Não há a utilização do self, ele utiliza o parametro 'cls' que se refere a propria classe\n# é a mesma ideia do self, porem o self se referencia a propria instancia (ao proprio objeto) , ja o cls se referencia a classe\n\n# sintaxe :\n # @classmethod\n # def nome_metodo(cls):\n\n# o metodo de classe não tem acesso aos atributos dos objetos, pois ele apenas recebe CLS e não SELF\n# ou seja, metodod e classe não faz acesso a atributos de objeto/instancia\n\n# ex (usando a mesma classe criada para metodos de instancia --> Computador)\n\nclass Computador:\n peixes = 98\n\n @classmethod\n def conta_peixes(cls):\n print(f'Nome da class: {cls}')\n print(f'Existe {cls.peixes} peixes dentro da classe {cls}') # cls.peixes é como se estivessemos fazendo isso -->> Computador.peixes\n\n \n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n def memoria(self,ram): \n self.ram = ram\n\n\nComputador.conta_peixes()\n\n# Nome da class: \n# Existe 98 peixes dentro da classe \n\n\n\n\n\n\n\n# ___________ SUBTIPOS ______________\n\n# Construtor - constroi um objeto\n# publicos - metodos/ atributos acessados pelos objetos instanciados pela classe\n# privados - metodos/ atributos que não podem ser acessados pelos objetos instanciados pela classe\n# estaticos\n\n# nós ja vimos atributos publicos, construtores, vamos ver agora os privados e estaticos\n\n\n# 1) PRIVADOS\n\n# ex usando como exemplo da classe Computador\n\n# atributos ou metodos privados tem como sintaxe: def __nome_metodo(self): ou self.__nome_atributo = atributo\n\n# acessamos dessa forma\n# objeto._NomeClasse__atributo/metodo()\n\nclass Computador: \n def __init__(self,cor,peso,polegadas,ligado):\n self.cor = cor\n self.peso = peso\n self.polegadas = polegadas\n self.ligado = ligado\n\n def __caracteristicas(self):\n return f'{self.cor} e {self.peso}'\n\n\nnovoComputador = Computador('preto',20,20,True)\n\n\n# print(Computador.__caracteristicas()) # AttributeError: type object 'Computador' has no attribute '__caracteristicas'\n\n# se tentarmos acessar um atributo privado, vai retornar um erro AttributeError\n\n# PARA ACESSARMOS UM METODO OU ATRIBUTO PRIVADO BASTA ACESSAR O DIR DA CLASSE, que mostra tudo oq podemos fazer com a classe\n\n# ex\n\nprint(dir(Computador))\n\n# ['_Computador__caracteristicas', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']\n\n# note que exite _Computador__caracteristicas --> que é um atributo/metodo privado\n\n# portando para acessar devemos fazer o seguinte\n\nprint( novoComputador._Computador__caracteristicas() ) # preto e 20\n\n# dessa forma conseguimos acessa-lo\n# essa tecnica se chama # name Mangling\n\n\n# usando o exemplo da classe Carro\n\n\nclass Carro:\n def __init__(self, portas, cor):\n self.portas = portas\n self.cor = cor \n self.__arcondicionado = True\n\nferrari = Carro('4 portas','preta')\n \nprint(ferrari._Carro__arcondicionado) #True # acessamos um atributo privado\n\n\n\n# POR TANTO PARA ACESSAR UM ATRIBUTO/METODO PRIVADO DEVEMOS USAR A SINTAXE:\n\n# objeto._NomeClasse__atributo/metodo()\n\n\n# 2) ESTATICOS\n\n# Necessario utilizar um decorador: @staticmethod\n# basicamente é um metodo que não muda\n# a diferença entre metodo de classe e um metodo estatico é que o estatico não recebe parametros (cls, self e etc...)\n\n# - SEM PARAMETROS (METODOS ESTATICOS NÃO RECEBEM PARAMETROS)\n# PODEMOS ACESSAR O METODO ESTATICO TANTO PELA CLASSE QUANTO PELO OBJETO INSTANCIADO POR ELA\n\n# ex\n\nclass Cliente:\n @staticmethod\n def especial():\n print('Você é um cliente especial')\n def __init__(self,nome,idade):\n self.nome = nome\n self.idade = idade\n\n\nmaria = Cliente('Maria',23)\n\nprint(maria.nome) # maria\nprint(maria.idade) # 23 \n\nmaria.especial() # Você é um cliente especial\nCliente.especial() # Você é um cliente especial","repo_name":"castrintt/curso-python","sub_path":"POO/metodos.py","file_name":"metodos.py","file_ext":"py","file_size_in_byte":10045,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"11280895582","text":"# Python script for creating text files with relative paths\n# to train/valid/test files. We use these paths to\n# create datasets. \n#\n# With special thanks to my Bachelor thesis supervisor.\n# Author: Ing. Lukáš Marták\n\nimport shutil\nimport argparse\nimport fnmatch\nimport random\nimport os\n\n\ntest_synthnames = set([\n 'ENSTDkCl',\n 'ENSTDkAm',\n])\n\ntrain_synthnames = set([\n 'StbgTGd2',\n 'SptkBGCl',\n 'SptkBGAm',\n 'AkPnStgb',\n 'AkPnCGdD',\n 'AkPnBsdf',\n 'AkPnBcht'\n])\n\ndef ensure_empty_directory_exists(dirname):\n if os.path.exists(dirname):\n shutil.rmtree(dirname)\n os.makedirs(dirname)\n\n\ndef desugar(c):\n prefix = 'MAPS_MUS-'\n last = c[::-1].find('_')\n pid = c[len(prefix):(-last - 1)]\n return prefix, last, pid\n\n\ndef collect_all_piece_ids(base_dir, synthnames):\n pids = set()\n for synthname in synthnames:\n for base, dirs, files in os.walk(os.path.join(base_dir, synthname)):\n candidates = fnmatch.filter(files, '*MUS*')\n if len(candidates) > 0:\n for c in candidates:\n _, _, pid = desugar(c)\n pids.add(pid)\n\n return pids\n\n\ndef collect_all_filenames(base_dir, synthnames, include):\n filenames = set()\n for synthname in synthnames:\n for base, dirs, files in os.walk(os.path.join(base_dir, synthname)):\n candidates = fnmatch.filter(files, '*MUS*')\n if len(candidates) > 0:\n for c in candidates:\n _, _, pid = desugar(c)\n if pid in include:\n path, ext = os.path.splitext(c)\n filenames.add(os.path.join(base, path))\n return list(filenames)\n\n\ndef write_pairs(filename, lines):\n pairs = []\n for line in lines:\n pairs.append('{}.wav,{}.mid'.format(line, line))\n with open(filename, 'w') as f:\n f.writelines('\\n'.join(pairs) + '\\n')\n\n\ndef main():\n random.seed(155853)\n\n parser = argparse.ArgumentParser(description='create non-overlapping splits')\n parser.add_argument('maps_base_directory', help='path must be relative to the working directory')\n args = parser.parse_args()\n\n train_pids = collect_all_piece_ids(args.maps_base_directory, train_synthnames)\n test_pids = collect_all_piece_ids(args.maps_base_directory, test_synthnames)\n\n print('len(train_pids)', len(train_pids))\n print('len(test_pids)', len(test_pids))\n\n train_filenames = sorted(collect_all_filenames(\n args.maps_base_directory,\n train_synthnames,\n train_pids - test_pids\n ))\n test_filenames = sorted(collect_all_filenames(\n args.maps_base_directory,\n test_synthnames,\n test_pids\n ))\n\n # we're validating on a subset of the trainset!\n # this is going to tell us **how close we are to learning the trainset by heart**...\n # ... and be a **bad estimate of generalization error** ...\n valid_filenames = random.sample(train_filenames, 10)\n\n print('len(train_filenames)', len(train_filenames))\n print('len(valid_filenames)', len(valid_filenames))\n print('len(test_filenames)', len(test_filenames))\n\n dirname = 'non-overlapping'\n ensure_empty_directory_exists(dirname)\n\n write_pairs(os.path.join(dirname, 'train'), train_filenames)\n write_pairs(os.path.join(dirname, 'valid'), valid_filenames)\n write_pairs(os.path.join(dirname, 'test'), test_filenames)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kosmels/amt_nn","sub_path":"create-non-overlapping-splits.py","file_name":"create-non-overlapping-splits.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"20785329921","text":"\ndef max_list_iter(int_list): # must use iteration not recursion\n if type(int_list) != list:\n raise ValueError\n if len(int_list) == 0:\n return None\n max = int_list[0]\n for i in int_list:\n if i > max:\n max = i\n return max\n \n \"\"\"finds the max of a list of numbers and returns the value (not the index)\n If int_list is empty, returns None. If list is None, raises ValueError\"\"\"\n\n\ndef reverse_rec(int_list): # must use recursion\n if type(int_list) != list:\n raise ValueError\n if len(int_list) == 0:\n return []\n if len(int_list) == 1:\n return int_list\n first = int_list[0]\n int_list.remove(first)\n x = reverse_rec(int_list)\n x.append(first)\n return x\n \"\"\"recursively reverses a list of numbers and returns the reversed list\n If list is None, raises ValueError\"\"\"\n\ndef bin_search(target, low, high, int_list): # must use recursion\n if type(int_list) != list:\n raise ValueError\n if high < low:\n return None\n point = (high + low) // 2\n if int_list[point] == target:\n return point\n elif int_list[point] > target:\n return bin_search(target, low, point - 1, int_list)\n return bin_search(target, point + 1, high, int_list)\n \"\"\"searches for target in int_list[low..high] and returns index if found\n If target is not found returns None. If list is None, raises ValueError \"\"\"\n","repo_name":"cpe202spring2019/lab1-jubenjam","sub_path":"lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35579783851","text":"from bottle import request\n\nfrom appapi.paths.base_api import BaseApi\nfrom appcore.helpers import PlatformInstantiationError\nfrom appcore.helpers.singleton import Singleton\nfrom appcore.services.factory import Factory\n\n\n# noinspection PyUnresolvedReferences\n@Singleton\nclass ExecutionApi(BaseApi):\n def _path(self):\n return 'execution'\n\n def run(self):\n \"\"\"\n POST\n \"\"\"\n try:\n account_settings = request.json\n return self._dict_reply(200, {\n 'job_id': Factory().get_execution_service().request_execution(**account_settings)\n })\n\n except PlatformInstantiationError as e:\n print(e.args)\n return self._dict_reply(400, 'Missing parameters in request: ' + ', '.join(e.args))\n except (ModuleNotFoundError, AssertionError):\n return self._dict_reply(400, 'Missing or invalid platform_id')\n except Exception as e:\n print(e.args)\n return self._dict_reply(500, 'Execution threw a ' + str(e.__class__) + 'error')\n\n def get(self):\n \"\"\"\n GET\n \"\"\"\n try:\n job = Factory().get_execution_service().get_job_data(\n job_id=request.GET.get('job_id'),\n is_full='full' in request.GET\n )\n return self._dict_reply(200, job)\n except NameError as e:\n return self._dict_reply(400, e.message)\n except Exception as e:\n return self._dict_reply(500, ', '.join([getattr(e, 'message', ''), ', '.join(e.args)]))\n","repo_name":"QuittyMR/etlas-collector","sub_path":"app/appapi/paths/execution_api.py","file_name":"execution_api.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11536940535","text":"from django.shortcuts import render\nfrom django.views import View\nfrom .models import Project, Person, Skill, Experience, SocialMedia\n\n# Create your views here.\ndef index(request):\n projects_list = Project.objects.order_by('priority')\n person = Person.objects.all()\n skill = Skill.objects.all()\n experience = Experience.objects.all()\n social_media = SocialMedia.objects.all()\n context = {\n 'projects_list': projects_list,\n 'person': person,\n 'skill': skill,\n 'experience': experience,\n 'social_media': social_media,\n }\n return render(request, 'index.html', context)\n\n\ndef project_detail(request, pk):\n project = Project.objects.get(pk=pk)\n context = {\n 'project': project\n }\n return render(request, 'project_detail.html', context)","repo_name":"purhan/personal-website","sub_path":"foliopage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40556504517","text":"import asyncio\nimport base64\nimport random\nimport string\nimport webbrowser\nfrom .constants import *\nimport aiohttp\nimport carb\nimport omni.kit.app\nimport omni.kit.commands\nfrom pxr import Sdf\nfrom aiohttp import web\n\n\n# Constants for Spotify API\nSPOTIFY_API = \"https://api.spotify.com/v1/\"\nSPOTIFY_PLAY_URL = SPOTIFY_API + \"me/player/play\"\nSPOTIFY_TRACK_ANAL_URL = SPOTIFY_API + \"audio-analysis/\"\nDEFAULT_TRACK = \"2BFGRjoK2ZXUa4JlMc3H7J\"\nSCOPE = 'user-read-playback-position user-read-currently-playing user-modify-playback-state'\nAUTH_URL = \"https://accounts.spotify.com/authorize?\"\nAUTH_HEADER_ALT = \"response_type=\" + \"code\" + \"&client_id=\" + CLIENTID + \"&scope=\" + SCOPE + \"&redirect_uri=\" + \"http://localhost:8888/callback\" + \"&state=\" + ''.join(random.choices(string.ascii_lowercase, k=16))\n\ndef startup_spotify_sync(track, auth_token):\n header = {\n \"Authorization\": f\"Bearer {auth_token}\"\n }\n run_loop = asyncio.get_event_loop()\n run_loop.run_until_complete(spotify_loop(track, header))\n\n# Run Spotify connection\nasync def spotify_loop(track, header):\n is_playing = await store_data(track, header)\n if is_playing:\n asyncio.create_task(ov_play())\n\n# Retrieve track analysis from spotify's API to then store it into the USD scene\nasync def store_data(track, headers):\n async with aiohttp.ClientSession() as session:\n data = await get_track_analysis(session, headers)\n if not data[0]:\n return\n else:\n start_times = []\n pitches = [[], [], [], [], [], [], [], [], [], [], [], []]\n segments = data[1]\n index = 0\n \n while index < len(segments):\n time = float(segments[index]['start'])\n start_times.append(time)\n # Store each pitch value at the specific start time value\n for i in range(12):\n val = float(segments[index]['pitches'][i])\n pitches[i].append(val)\n index += 1\n\n await generate_properties(start_times, data[2], pitches)\n\n is_playing = await play_song(session, track, headers)\n return is_playing\n\n# Generate the properties that hold track analysis data\nasync def generate_properties(start_times, duration, pitches):\n # Store Information within the USD as Attributes\n create_attributes(Sdf.Path('/World.beat_start_time'), Sdf.ValueTypeNames.FloatArray)\n create_attributes(Sdf.Path('/World.duration'), Sdf.ValueTypeNames.Float)\n change_properties(Sdf.Path('/World.beat_start_time'), start_times)\n change_properties(Sdf.Path('/World.duration'), duration)\n \n # Create attribute for every pitch\n for i in range(12):\n create_attributes(Sdf.Path('/World.pitch' + str(i)), Sdf.ValueTypeNames.FloatArray)\n change_properties(Sdf.Path('/World.pitch' + str(i)), pitches[i])\n\n# Uses Kit commands to change properties given the path and new value\ndef change_properties(path, new_value):\n omni.kit.commands.execute('ChangeProperty',\n prop_path=path,\n value=new_value,\n prev=None)\n\n# Uses Kit commands to create an attribute given the path and attribute type\ndef create_attributes(path, attr_type):\n omni.kit.commands.execute('CreateUsdAttributeOnPath',\n attr_path=path,\n attr_type=attr_type,\n custom=True,\n variability=Sdf.VariabilityVarying)\n \n# Get Information from the track analysis and grab specific pieces from the json\nasync def get_track_analysis(session, headers):\n async with session.get(SPOTIFY_TRACK_ANAL_URL + DEFAULT_TRACK, headers=headers) as resp:\n if resp.status == 200:\n json = await resp.json()\n segments = json[\"segments\"]\n track = json[\"track\"]\n duration = track[\"duration\"]\n return [True, segments, duration]\n return [False, None, None]\n\n# Plays the song on spotify if we recieve a OK response\nasync def play_song(session, track, headers):\n track_to_play = track\n if track == \"\":\n track_to_play = DEFAULT_TRACK\n async with session.put(SPOTIFY_PLAY_URL, json={\"uris\": [\"spotify:track:\" + track_to_play]},headers=headers) as play_resp:\n if play_resp.status == 204:\n return True\n else:\n return False\n\n# Wait a little bit then run kit command for hitting Play\nasync def ov_play():\n await asyncio.sleep(0.1)\n omni.kit.commands.execute('ToolbarPlayButtonClicked')\n\n# Web Authentication holder\nclass WebData:\n def __init__(self) -> None:\n self._access_code = \"\"\n self._auth_token = \"\"\n \n def get_access_code(self):\n self.run_web_app()\n run_loop = asyncio.get_event_loop()\n return run_loop.run_until_complete(self.boot_server())\n\n def get_access_token(self):\n run_loop = asyncio.get_event_loop()\n return run_loop.run_until_complete(self.auth_token_loop(self._access_code))\n\n def run_web_app(self):\n self.app = web.Application()\n self.app.add_routes([web.get('/callback', self.query_code)])\n\n async def boot_server(self):\n runner = web.AppRunner(self.app)\n await runner.setup()\n site = web.TCPSite(runner, 'localhost', 8888)\n await site.start()\n\n while True:\n self.open_web_browser()\n await asyncio.sleep(5)\n await site.stop()\n break\n\n def open_web_browser(self):\n webbrowser.open(str(AUTH_URL+AUTH_HEADER_ALT))\n\n async def query_code(self, request):\n self._access_code = request.rel_url.query.get('code', '')\n return web.Response(text=f\"You can close this now\")\n\n async def auth_token_loop(self, code):\n authUrl = \"https://accounts.spotify.com/api/token\"\n form = aiohttp.FormData({\n \"code\": str(code),\n \"redirect_uri\": REDIRECT_URI,\n \"grant_type\": 'authorization_code'\n })\n client_string = CLIENTID + ':' + CLIENT_SECRET\n ascii_client = client_string.encode(\"ascii\")\n base64_client = base64.b64encode(ascii_client)\n decode_client = base64_client.decode(\"ascii\")\n headers = {\n 'Authorization': f\"Basic {decode_client}\"\n }\n \n async with aiohttp.ClientSession() as session:\n async with session.request(method='POST', url=authUrl, headers=headers, data=form) as resp:\n if resp.status == 200:\n json = await resp.json()\n self._auth_token = json[\"access_token\"]\n else:\n carb.log_info(f\"Response Status: {resp.status}\")\n \n","repo_name":"JenNVIDIA/musical-lights","sub_path":"exts/jen.music.lights/jen/music/lights/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":6647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"4232153993","text":"import pygame as pg \nfrom pygame.locals import *\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\n\nfrom dataclasses import dataclass\n\nfrom ctypes import sizeof, c_float, Structure, byref, c_void_p\n\nimport numpy as np\nimport random\nimport math\nimport time\nfrom tqdm import trange\n\n#SECTION - Varibles\n\n# width, height\nwidth, height = 720, 480\ndisplaySize = (width, height)\nnumAgents = 30000 # 10*(10**3)\ndimStrength = 1\n\nscaleing = 1\n\nlrw, lrh = int(width*scaleing), int(height*scaleing)\n\nstart_time = time.time()\nprevious_time = start_time\n\n#!SECTION - Varibles\n#SECTION - Dataclasses\n#ANCHOR - Vector 2\n@dataclass\nclass Vec2:\n x: float\n y: float\n\n def __mul__(self, other):\n if isinstance(other, (int, float)):\n return Vec2(self.x * other, self.y * other)\n elif isinstance(other, Vec2):\n return Vec2(self.x * other.x, self.y * other.y)\n else:\n raise TypeError(\"Unsupported opperand type\")\n \n def __add__(self, other):\n if isinstance(other, Vec2):\n return Vec2(self.x + other.x, self.y + other.y)\n elif isinstance(other, (int, float)):\n return Vec2(self.x + other, self.y + other)\n else:\n raise TypeError(\"Unsupported opperand type\")\n \n def __str__(self):\n return f\"({self.x}, {self.y})\"\n \n#ANCHOR - Agent\nclass AgentStruct(Structure):\n _fields_ = [(\"pos\", c_float * 2), (\"angle\", c_float)]\n\n@dataclass\nclass Agent:\n pos: Vec2 = Vec2(0.0, 0.0)\n angle: float = 0.0\n\n def to_struct(self):\n pos_array = (c_float * 2)(self.pos.x, self.pos.y)\n return AgentStruct(pos_array, self.angle)\n \n @classmethod\n def from_struct(cls, agent_struct):\n return cls(agent_struct.pos, agent_struct.angle)\n \nclass Agent2:\n def __init__(self, x, y, angle):\n self.x = x\n self.y = y\n self.angle = angle\n\n \n#!SECTION - Dataclasses\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = \"\\r\"):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\n # Print New Line on Complete\n if iteration == total: \n print()\n#SECTION - Start\n\n# agentsArray = [\n# Agent2(random.uniform(0.2, 0.8), random.uniform(0.2, 0.8), random.uniform(0, 2 * math.pi)) for _ in range(numAgents)\n# ]\nprint(f\"\"\"\n Generating {numAgents} agents.\n This may take some time if theres a lot.\n\"\"\")\n# printProgressBar(0, numAgents, prefix = 'Progress:', suffix = 'Complete', length = 50)\nagentsArray = []\nfor i in trange(numAgents):\n x = random.uniform(0.2, 0.8)\n y = random.uniform(0.2, 0.8)\n angle = random.uniform(0, 2 * math.pi)\n agent = Agent2(x, y, angle)\n agentsArray.append(agent)\n # printProgressBar(i + 1, numAgents, prefix = 'Progress:', suffix = 'Complete', length = 50)\n\nprint(\"converting to numpy array\")\nnpAgentsArray = np.array([(agent.x, agent.y, agent.angle) for agent in agentsArray], dtype=np.float32)\n\npg.init()\npg.display.set_mode(displaySize, OPENGL | DOUBLEBUF)\n\ngl_version = glGetString(GL_VERSION)\nprint(gl_version.decode('utf-8'))\n\nif pg.get_error() != \"\":\n print(\"Pygame error:\", pg.get_error())\n pg.quit()\n quit()\n\n#ANCHOR - Vertex Shader\nprint(\"compiling vertex shader\")\nvertexSource = open(\"./shader.vert\", \"r\")\nvertexShader = glCreateShader(GL_VERTEX_SHADER)\nglShaderSource(vertexShader, vertexSource)\nglCompileShader(vertexShader)\n\n#ANCHOR - Fragment Shader\nprint(\"compiling fragment shader\")\nfragmentSource = open(\"./shader.frag\", \"r\")\nfragmentShader = glCreateShader(GL_FRAGMENT_SHADER)\nglShaderSource(fragmentShader, fragmentSource)\nglCompileShader(fragmentShader)\n\n#ANCHOR - Compute Shader\nprint(\"compiling compute shader\")\ncomputeSource = open(\"./shader.comp\", \"r\")\ncomputeShader = glCreateShader(GL_COMPUTE_SHADER)\nglShaderSource(computeShader, computeSource)\nglCompileShader(computeShader)\n\n#ANCHOR - Check Compile Status\nif glGetShaderiv(vertexShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Vertex shader compilation failed\")\n err = glGetShaderInfoLog(vertexShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\n# Check fragment shader compilation status\nif glGetShaderiv(fragmentShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Fragment shader compilation failed\")\n err = glGetShaderInfoLog(fragmentShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\n# Check compute shader compilation status\nif glGetShaderiv(computeShader, GL_COMPILE_STATUS) != GL_TRUE:\n print(\"Compute shader compilation failed\")\n err = glGetShaderInfoLog(computeShader)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\nshader_program = glCreateProgram()\ncompute_program = glCreateProgram()\n\nglAttachShader(shader_program, vertexShader)\nglAttachShader(shader_program, fragmentShader)\nglAttachShader(compute_program, computeShader)\n\nglLinkProgram(shader_program)\nglLinkProgram(compute_program)\n\n#ANCHOR - Check Link status\nif glGetProgramiv(shader_program, GL_LINK_STATUS) != GL_TRUE:\n print(\"Shader program linking failed\")\n err = glGetShaderInfoLog(shader_program)\n print(err.decode('utf-8'))\n pg.quit()\n quit()\n\nif glGetProgramiv(compute_program, GL_LINK_STATUS) != GL_TRUE:\n print(\"Compute program linking failed\")\n print(glGetProgramInfoLog(compute_program))\n pg.quit()\n quit()\n\n\n#ANCHOR - creating the render texture\ntrailmap = glGenTextures(1)\nglBindTexture(GL_TEXTURE_2D, trailmap)\nglTextureParameteri(trailmap, GL_TEXTURE_MIN_FILTER, GL_NEAREST)\nglTextureParameteri(trailmap, GL_TEXTURE_MAG_FILTER, GL_NEAREST)\nglTextureParameteri(trailmap, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)\nglTextureParameteri(trailmap, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)\n\nglTextureStorage2D(trailmap, 1, GL_RGBA32F, lrw, lrh)\nglBindImageTexture(0, trailmap, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F)\n\ndef random_inside_unit_circle():\n while True:\n x = random.uniform(-1, 1)\n y = random.uniform(-1, 1)\n if x**2 + y**2 <= 1:\n # Normalize the coordinates to [0, 1]\n magnitude = math.sqrt(x**2 + y**2)\n x_normalized = (x + 1) / 2\n y_normalized = (y + 1) / 2\n return Vec2(x_normalized, y_normalized)\n\n#ANCHOR - Create agent array\n# agentsArray = [Agent2(random.uniform(0.2, 0.8), random.uniform(0.2, 0.8), random.uniform(0, 2 * math.pi)) for _ in range(numAgents)]\n# npAgentsArray = np.array([(agent.x, agent.y, agent.angle) for agent in agentsArray], dtype=np.float32)\n\nssbo = glGenBuffers(1)\nglBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\nglBufferData(GL_SHADER_STORAGE_BUFFER, len(npAgentsArray) * sizeof(GLfloat) * 3, npAgentsArray, GL_DYNAMIC_DRAW)\n\nssbo_bindPoint = 1\nglBindBufferBase(GL_SHADER_STORAGE_BUFFER, ssbo_bindPoint, ssbo)\n\n#ANCHOR - Triangles?\nvertices =np.array([\n # Vertex positions (x, y) followed by texture coordinates (u, v)\n -1.0, -1.0, 0.0, 0.0,\n -1.0, 1.0, 0.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, \n -1.0, -1.0, 0.0, 0.0,\n 1.0, 1.0, 1.0, 1.0,\n 1.0, -1.0, 1.0, 0.0\n], dtype=np.float32)\n\nquad_vao = glGenVertexArrays(1)\nglBindVertexArray(quad_vao)\n\nquad_vbo = glGenBuffers(1)\nglBindBuffer(GL_ARRAY_BUFFER, quad_vbo)\nglBufferData(GL_ARRAY_BUFFER, vertices, GL_DYNAMIC_DRAW)\n\nglVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), None)\nglEnableVertexAttribArray(0)\n\nglVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), c_void_p(2 * sizeof(GLfloat)))\nglEnableVertexAttribArray(1)\n\n#!SECTION - Start\n\ndef check_gl_error():\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error: {error_code}\")\n\nprint(npAgentsArray)\n\nif __name__ == \"__main__\":\n clock = pg.time.Clock()\n while True:\n # current_time = time.time()\n # delta_time = current_time - previous_time\n dt = clock.tick()/1000\n # pg.time.Clock.get_time()/1000\n for event in pg.event.get():\n if event.type == pg.QUIT:\n #NOTE - exit stuff\n # glDeleteBuffers(1, [ssbo])\n pg.quit()\n quit()\n elif event.type == pg.KEYDOWN and event.key == K_ESCAPE:\n pg.quit()\n quit()\n\n glUseProgram(compute_program)\n # glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\n glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ssbo_bindPoint, ssbo)\n glUniform1i(glGetUniformLocation(compute_program, \"numAgents\"), numAgents)\n glUniform1i(glGetUniformLocation(compute_program, \"width\"), width)\n glUniform1i(glGetUniformLocation(compute_program, \"height\"), height)\n glUniform1f(glGetUniformLocation(compute_program, \"deltaTime\"), dt)\n glUniform1f(glGetUniformLocation(compute_program, \"dimStrength\"), dimStrength)\n glDispatchCompute(width, height, 1)\n glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT)\n\n glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo)\n # glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, 0, len(npAgentsArray) * sizeof(GLfloat) * 3, npAgentsArray)\n\n glBindFramebuffer(GL_FRAMEBUFFER, 0)\n glViewport(0, 0, lrw, lrh)\n glClear(GL_COLOR_BUFFER_BIT)\n\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error before glUseProgram: {error_code}\")\n\n glUseProgram(shader_program)\n\n error_code = glGetError()\n if error_code != GL_NO_ERROR:\n print(f\"OpenGL error after glUseProgram: {error_code}\")\n\n glBindVertexArray(quad_vao)\n glBindTexture(GL_TEXTURE_2D, trailmap)\n glDrawArrays(GL_TRIANGLES, 0, 6)\n\n # print(delta_time)\n # print(\"Buffer Data:\", np.frombuffer(npAgentsArray, dtype=np.float32))\n\n check_gl_error()\n pg.display.flip()","repo_name":"icantreadmycode/SlimeSim","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10577,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"18939761271","text":"import sys\nimport os\nimport pandas as pd\nfrom pathlib import Path\nresult = []\nroot = \"../ICEtest/\"\n\nfor file in Path(root).glob(\"*.txt\"):\n df = pd.read_csv(file, sep='\\t', header=None)\n df.columns = ['qseqid', 'sseqid', 'pident', 'length', 'mismatch', 'gapopen', 'qstart', 'qend', 'sstart', 'send', 'evalue', 'bitscore']\n # split(char) splits a string into a list using char as a delimiter\n # list[-1] returns the last entry in a list\n stem = str(file).replace('.txt', '').split('/')[-1]\n rslt_df = df.loc[(df['length']>100)]\n dataff = rslt_df.sort_values(by='length',ascending=False)\n dataff.drop_duplicates(subset =\"qstart\", keep = \"first\",inplace = True)\n dataff1 = dataff.sort_values(by='length',ascending=False)\n dataff1.drop_duplicates(subset =\"qend\", keep = \"first\",inplace = True)\n # creat a directiry\n #os. mkdir(stem)\n #store dataff1 to the created directroy\n #subroot = stem\n #subdir = os.path.join(root, subroot)\n #dataff1.to_csv(os.path.join(subdir, stem+\".csv\"), index=False)\n \n final = dataff1.groupby('sseqid')['length'].sum().sort_values(ascending=False).to_frame(name = 'length').reset_index()\n final1 = final[(final.length >5040)]\n \n \n final1['isolate'] = stem\n \n result.append(final1)\n\nall_result = pd.concat(result)\nall_result.to_csv('processed_ICE_lengths.csv', index=False) \nsys.exit(0)\n\n","repo_name":"MathBioInfo/Integrative-transposon-tn916-E-faecium","sub_path":"process_blast.py","file_name":"process_blast.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12508490615","text":"from telemetry.internal.actions import page_action\n\n\nclass ClickElementAction(page_action.PageAction):\n def __init__(self, selector=None, text=None, element_function=None):\n super(ClickElementAction, self).__init__()\n self.selector = selector\n self.text = text\n self.element_function = element_function\n\n def RunAction(self, tab):\n code = '''\n function(element, errorMsg) {\n if (!element) {\n throw Error('Cannot find element: ' + errorMsg);\n }\n element.click();\n }'''\n page_action.EvaluateCallbackWithElement(\n tab, code, selector=self.selector, text=self.text,\n element_function=self.element_function)\n","repo_name":"kiwibrowser/src","sub_path":"third_party/catapult/telemetry/telemetry/internal/actions/javascript_click.py","file_name":"javascript_click.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"}
+{"seq_id":"5129325566","text":"import sys, os\nfrom tqdm import tqdm\n\nsys.path.append(r'E:\\WorkSpaceDucAnh') \nfrom ultils import get_info_txt_with_line_to_list, coppy_file_to_dir\n\n\ndef copy_tif_to_dir_from_txt(fp_txt, dir_contain_image, dir_dest_coppy):\n list_tif_choosen = get_info_txt_with_line_to_list(fp_txt)\n print(list_tif_choosen)\n os.makedirs(dir_dest_coppy, exist_ok=True)\n\n list_fp_tif_choosen = [os.path.join(dir_contain_image, fname) for fname in list_tif_choosen]\n for fp in tqdm(list_fp_tif_choosen, desc='Copping ...'):\n coppy_file_to_dir(fp, dir_dest_coppy)\n print('Done!')\n\n\nif __name__=='__main__':\n fp_txt = 'E:\\WorkSpaceDucAnh\\Tmp\\list_file.txt'\n # dir_contain_image = r'E:\\WorkSpaceSkyMap\\Change_detection_Dubai\\Data_Project\\img2021_2022'\n dir_contain_image = r'Z:\\data_change_detection\\stacked\\stacked'\n dir_dest_coppy = r'E:\\WorkSpaceSkyMap\\Change_detection_Dubai\\DataTraining\\V1\\img'\n copy_tif_to_dir_from_txt(fp_txt, dir_contain_image, dir_dest_coppy)\n\n","repo_name":"anhbn995/GOGOOK","sub_path":"ALL_CODE/WorkSpaceDucAnh/z_Tmp/choosen_image_from_txt.py","file_name":"choosen_image_from_txt.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"6964134215","text":"import pickle\nimport requests\nimport re\nimport os\nimport Importdata as Id\nimport numpy as np\n#import matplotlib.pyplot as plt\nfrom sklearn import datasets, linear_model\nfrom sklearn.metrics import mean_squared_error\n\n'''\nThis file contains some functions you can use to predict scores for players in FPL.\nIt makes use of the Importdata.py file so make sure its in the working directory.\nYou can do a simple fit easily from the terminal or an IDE.\n\nFirst load this file so you can use the functions.\n\n$ import linear_regression as lr\n\nNext, you need to generate or load some examples from the historical data.\ne.g.\n$ filename = \"machine_learning_examples\"\n$ [data, np_examples,np_prediction_set] = lr.import_and_save_examples(filename)\n\nor if you have already saved the data before\n\n$ filename = \"machine_learning_examples\"\n$ [data, np_examples, np_prediction_set] = lr.load_examples(filename)\n\nsee the code for this below.\n'''\ndef import_and_save_examples(filename):\n\t\n\t[data, examples, prediction_set] = Id.generate_examples()\n\tnp_examples = np.array(examples)\n\tnp_prediction_set = np.array(prediction_set)\n\twith open(filename+'.pkl','wb') as f:\n\t\tpickle.dump([data, np_examples,np_prediction_set],f) \n\treturn [data, np_examples,np_prediction_set]\n\ndef load_examples(filename):\n\n\twith open(filename+'.pkl','rb') as f:\n\t\tdata, np_examples, np_prediction_set = pickle.load(f)\n\n\treturn [data, np_examples, np_prediction_set]\n\n'''\nNext we simply perform the linear regression using the sklearn package\nenter\n$ [regr, diff_counts, mean_sq_error] = lr.perform_linear_regression(np_examples)\n'''\n\ndef perform_linear_regression(np_examples):\n\n\t[x_train, y_train, x_test, y_test] = generate_train_test_examples(np_examples)\n\n\tregr = linear_model.LinearRegression()\n\n\tregr.fit(x_train, y_train)\n\n\t[diff_counts, mean_sq_error] = test_model_predictions(regr, x_test, y_test)\n\n\treturn [regr, diff_counts, mean_sq_error]\n\n'''\nNow we are ready to predict next weeks scores.\n\n$ results = lr.predict_next_week(regr, np_prediction_set)\n\nYou can edit the complexity of the model by changing the type of model used\n(see the sklearn website) or adding features to the examples in the 'generate_examples'\nfunction in the Importdata.py file.\n'''\ndef predict_next_week(model,prediction_set):\n\n\ty_pred = model.predict(prediction_set)\n\n\tindex = sorted(range(len(y_pred)), key=lambda k: y_pred[k], reverse=True)\n\tplayer_ids = np.array(index)+1\n\tplayer_scores = np.array(y_pred)\n\tplayer_scores = player_scores[index]\n\n\treturn dictionary(zip(player_ids,player_scores))\n\n'''\nThe scripts below are used by the main scripts to perform the analysis so if you \nfiddle around with them some then stuff above might break!\n'''\n\ndef slice_examples(np_examples, number_examples_required):\n\n\t[row,col] = np_examples.shape\n\n\tnew_order = np.random.permutation(row)\n\n\tshuffled_examples = np_examples[new_order,:]\n\n\treturn shuffled_examples[:number_examples_required,:]\n\ndef generate_train_test_examples(np_examples):\n\n\t[row,col] = np_examples.shape\n\n\tnew_order = np.random.permutation(row)\n\n\tshuffled_examples = np_examples[new_order,:]\n\n\tnumber_for_testing = row//10 + 1\n\n\ty_train = shuffled_examples[:-number_for_testing,0]\n\ty_test = shuffled_examples[-number_for_testing:,0]\n\n\tx_train = shuffled_examples[:-number_for_testing,1:]\n\tx_test = shuffled_examples[-number_for_testing:,1:]\n\n\treturn [x_train, y_train, x_test, y_test]\n\ndef test_model_predictions(model, x_test, y_test):\n\n\ty_pred = model.predict(x_test)\n\n\tdifferences = np.array(y_test-y_pred)\n\n\tabs_diff = np.abs(np.round(differences))\n\n\tmax_diff = int(max(abs_diff))\n\n\tdiffs = list(range(0,max_diff+1))\n\n\tdiff_counts = []\n\n\tfor diff in diffs:\n\t\tdiff_counts.append(len(abs_diff[abs_diff==diff]))\n\n\tmean_sq_error = mean_squared_error(y_test, y_pred)\n\n\treturn [diff_counts, mean_sq_error]\n\ndef test_model(np_examples):\n\n\t[row,col] = np_examples.shape\n\n\ttest_number_step = row//10 + 1\n\n\ttest_numbers = list(range(test_number_step,row,test_number_step))\n\ttest_numbers.append(row)\n\n\tmean_sq_error = []\n\n\tfor number in test_numbers:\n\n\t\ttemp_MSE = []\n\n\t\tfor repeat in range(50):\n\n\t\t\texamples = slice_examples(np_examples,number)\n\n\t\t\t[regr, diff_counts, MSE] = perform_linear_regression(examples)\n\n\t\t\ttemp_MSE.append(MSE)\n\n\t\tmean_sq_error.append(np.mean(temp_MSE))\n\n\t#plt.plot(test_numbers, mean_sq_error)\n\t#plt.show()\n\treturn [test_numbers, mean_sq_error, regr]\n\n\n\n\n\n","repo_name":"H-Cox/FPL","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":4380,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"52"}
+{"seq_id":"13026560408","text":"\n#!python3\n\nfrom importlib import import_module\nimport traceback\n\nfrom common.config import CONNECTOR_MAP\nfrom common.spLogging import logger\nfrom Connectors.azureSQL import AzureSQLConnector\n\ndef main(params: dict) -> dict:\n\n result = {}\n \n try:\n \n azconn = AzureSQLConnector.load_default()\n schema = params['source']\n schema_list = ([schema] if schema else CONNECTOR_MAP.keys())\n action = params['action']\n models = params['model']\n\n if action == 'build':\n result = azconn.create_db(schema_list)\n\n elif action == 'destroy':\n result = azconn.delete_db(schema_list)\n \n elif action =='drop':\n result = azconn.delete_tables(schema,models)\n\n elif action == 'examine':\n for schema in schema_list:\n result[schema] = azconn.plan_changes(schema)\n\n elif action == 'apply':\n for schema in schema_list:\n plan = azconn.plan_changes(schema)\n result[schema] = azconn.apply_changes(plan)\n \n else:\n returnMsg = \"F_db_activity :: Invalid value provided for 'action' parameter: {}\".format(action)\n logger.warning(returnMsg)\n result = returnMsg\n\n except Exception as e:\n returnMsg = 'F_db_activity error :: {}'.format(traceback.print_exc())\n logger.error(returnMsg)\n result = returnMsg\n\n return result\n","repo_name":"kloudkrafts01/kspyder","sub_path":"AzureFunctions/F_db_activity/db_actions.py","file_name":"db_actions.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"32122351059","text":"# Yêu cầu:\n# 1. nhập vào n\n# 2. in ra n kiểu viết ngược lại\n\nn = int(input())\n\ndu_lieu = str(n) # chuyển từ int sang string\n\nketQua = \"\"\n\nfor i in range(len(du_lieu) - 1, -1, -1):\n ketQua = ketQua + du_lieu[i]\n\ndu_lieu2 = int(ketQua)\n\nprint(f\"{du_lieu2}\")","repo_name":"conggaro/Hoc_Python","sub_path":"Nhập môn khoa học máy tính/Tuần 5/Bài thực hành lập trình tuần 5/Lần 3/cau_hoi_1.py","file_name":"cau_hoi_1.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18698237016","text":"from bauth.models.country import Country\nfrom book_rental.libs.uploader.uploader import Uploader\nfrom logger.models.error_log import ErrorLog\nfrom engine.exceptions.br_exception import BRException\n\n\nclass CountryUploader(Uploader):\n def __init__(self, data=[], *args, **kwargs):\n self.data = data\n self.args = args\n self.kwargs = kwargs\n\n def data_as_list(self):\n if not self.data:\n raise BRException(\"No data found\")\n\n data_list = []\n\n for entry in self.data:\n data_list += [[ entry['name'], entry['alpha2Code'], entry['alpha3Code'] ]]\n return data_list\n\n def handle_upload(self):\n\n print(\"Started...\")\n\n self.data = self.data_as_list()\n\n for row in self.data:\n\n if len(row) != 3:\n error_log = ErrorLog()\n error_log.url = ''\n error_log.stacktrace = 'Invalid format in country upload'\n error_log.save()\n continue\n country_objects = Country.objects.filter(name=row[0], short_name2=row[1], short_name3=row[2])\n if country_objects.exists():\n country_object = country_objects.first()\n else:\n country_object = Country()\n country_object.name = row[0]\n country_object.short_name2 = row[1]\n country_object.short_name3 = row[2]\n country_object.save()\n\n print(\"Ended...\")","repo_name":"codenginebd/obr","sub_path":"book_rental/libs/uploader/country_uploader.py","file_name":"country_uploader.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10313671195","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('sfnform', '0008_auto_20151112_0927'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='metadataform',\n name='aprox_years_growing_seasons_int',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n ]\n","repo_name":"aescobarr/sapfluxnet-form","sub_path":"sfnform/migrations/0009_metadataform_aprox_years_growing_seasons_int.py","file_name":"0009_metadataform_aprox_years_growing_seasons_int.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28757064219","text":"from django.conf.urls import url\nfrom artists import views\n\nuuid_match = r'(?P[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})'\n\nurlpatterns = [\n url(r'^genres$', views.genres, name='artists-genres'),\n url(r'^genre/(?P\\d+)$', views.genre, name='artists-genre'),\n url(r'^search$', views.search, name='artists-search'),\n url(r'^artist/%s$' % (uuid_match), views.artist, name='artists-artist'),\n]\n","repo_name":"andrebola/fonil-web","sub_path":"artists/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28535373251","text":"\n# coding: utf-8\n\n\n\nimport sys\nimport requests \nimport pandas as pd\nimport ConfigParser\nimport datetime\nimport csv\nfrom bs4 import BeautifulSoup \nfrom pymongo import MongoClient\nfrom mongoDB import mongoDB\n\n\nclass Crawler:\n \n def __init__(self,collection_name=\"Aggregate-Day\",save_to_all_collection=True):\n self.df = pd.DataFrame()\n self.target_df = pd.DataFrame()\n self.exfeature = pd.DataFrame()\n \n self.config = ConfigParser.ConfigParser()\n self.config.read('config_crawler.ini')\n\n self.now=datetime.datetime.now()\n self.ip_address = self.config.get(\"Server\",\"ip_address\")\n self.from_year = self.config.get(\"Date\",\"from_year\")\n self.from_month = self.config.get(\"Date\",\"from_month\")\n self.from_day = self.config.get(\"Date\",\"from_day\")\n self.to_year=str(self.now.year)\n\n self.collection_name=collection_name\n self.svaetoAll=save_to_all_collection\n \n if(self.now.month<11):\n self.to_month=str(\"0\"+str(self.now.month-1))\n else:\n self.to_month=str(self.now.month-1)\n self.to_day=str(self.now.day-1)\n \n self.mongo = mongoDB(self.ip_address, \"External_factor\")\n \n def date_replace(self,data_list):\n date=str(data_list).replace(\"Jan\",\"01\").replace(\"Feb\",\"02\").replace(\"Mar\",\"03\").replace(\"Apr\",\"04\").replace(\"May\",\"05\").replace(\"Jun\",\"06\") .replace(\"Jul\",\"07\").replace(\"Aug\",\"08\").replace(\"Sep\",\"09\").replace(\"Oct\",\"10\").replace(\"Nov\",\"11\").replace(\"Dec\",\"12\").replace(\",\",\"\")\n return date\n \n def Crawl_rate_exchange(self):\n\n currency_code = self.config.get(\"Exchange_Rate\",\"currency_code\").split(\",\")\n currency = self.config.get(\"Exchange_Rate\",\"currency\").split(\",\")\n index = 0\n for code in currency_code:\n data_list=[]\n doc = {}\n i=0\n count=1\n res = requests.get(\"http://www.exchangerate.com/past_rates.html?letter=&continent=&cid=239-USD¤cy=\"+str(code)+\"&last30=&date_from=\"+str(int(self.from_month)+1)+\"-\"+self.from_day+\"-\"+self.from_year+\"&date_to=\"+str(int(self.to_month)+1)+\"-\"+self.to_day+\"-\"+self.to_year+\"&action=Generate+Chart\")\n soup = BeautifulSoup(res.text.encode(\"utf-8\"), \"html.parser\")\n for texts in soup.findAll(face=\"Arial\",size=\"-1\"):\n data_list.append(texts.text)#data start from index 7 str(data_list[7][5:10])\n i+=1\n if i>=8 :\n if count==1 :\n doc = {\"Month\":int(self.date_replace(str(data_list[i-1][1:4])))}\n doc [\"Day\"]=int(data_list[i-1][5:7])\n doc[\"Year\"]=int(data_list[i-1][8:12])\n count=2\n elif count==2 :\n doc[str(currency[index])+\"/USD\"]=float(str(data_list[i-1]))\n count=3\n elif count==3 :\n doc[\"USD/\"+str(currency[index])]=float(str(data_list[i-1]))\n doc[\"Date\"] = str(doc.get(\"Year\"))+\"-\"+str(doc.get(\"Month\"))+\"-\"+str(doc.get(\"Day\"))\n count=1\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n self.mongo.updateIfExist(\"RateExchange-Day\",{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n else:\n self.mongo.updateIfExist(\"RateExchange-Day\",{\"Year\":doc.get(\"Year\"),\"Month\":doc.get(\"Month\"),\"Day\":doc.get(\"Day\")},{\"$set\":doc})\n #print doc\n doc.clear()\n index +=1\n \n def Crawl_Stock(self):\n company = self.config.get(\"Company_stock\",\"company_code\").split(\",\")\n company_name = self.config.get(\"Company_stock\",\"company_name\").split(\",\")\n \n name=0\n for com in company:\t\n url=\"http://chart.finance.yahoo.com/table.csv?s=\"+com+\"&a=\"+self.from_month+\"&b=\"+self.from_day+\"&c=\"+self.from_year+\"&d=\"+self.to_month+\"&e=\"+self.to_day+\"&f=\"+self.to_year+\"&g=d&ignore=.csv\"\n\n csvFile = requests.get(url)\n output = open('table.csv', 'wb')\n output.write(csvFile.content)\n output.close()\n\n f = open('table.csv', 'r')\n for row in csv.DictReader(f):\n del(row['Open'])\n del(row['High'])\n del(row['Low'])\n del(row['Close'])\n row.setdefault(str(company_name[name])+'-Adj-Close', float(row['Adj Close']))\n del(row['Adj Close'])\n row.setdefault(str(company_name[name])+'-Volume', int(row['Volume']))\n del(row['Volume'])\n d=row[\"Date\"].split(\"-\")\n row[\"Year\"]=int(d[0])\n row[\"Month\"]=int(d[1])\n row[\"Day\"]=int(d[2])\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n self.mongo.updateIfExist(\"Stock-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n else:\n self.mongo.updateIfExist(\"Stock-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n f.close()\n name+=1\n \n def Crawl_Index(self):\n company = self.config.get(\"Company_index\",\"company_code\").split(\",\")\n company_name = self.config.get(\"Company_index\",\"company_name\").split(\",\")\n \n name=0\n for com in company:\t\n url=\"http://chart.finance.yahoo.com/table.csv?s=\"+com+\"&a=\"+self.from_month+\"&b=\"+self.from_day+\"&c=\"+self.from_year+\"&d=\"+self.to_month+\"&e=\"+self.to_day+\"&f=\"+self.to_year+\"&g=d&ignore=.csv\"\n\n csvFile = requests.get(url)\n output = open('table.csv', 'wb')\n output.write(csvFile.content)\n output.close()\n\n f = open('table.csv', 'r')\n for row in csv.DictReader(f):\n del(row['Open'])\n del(row['High'])\n del(row['Low'])\n del(row['Close'])\n row.setdefault(str(company_name[name])+'-Adj-Close', float(row['Adj Close']))\n del(row['Adj Close'])\n row.setdefault(str(company_name[name])+'-Volume', int(row['Volume']))\n del(row['Volume'])\n d=row[\"Date\"].split(\"-\")\n row[\"Year\"]=int(d[0])\n row[\"Month\"]=int(d[1])\n row[\"Day\"]=int(d[2])\n if self.svaetoAll:\n self.mongo.updateIfExist(self.collection_name,{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n self.mongo.updateIfExist(\"Index-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n else:\n self.mongo.updateIfExist(\"Index-Day\",{\"Year\":row.get(\"Year\"),\"Month\":row.get(\"Month\"),\"Day\":row.get(\"Day\")},{\"$set\":row})\n f.close()\n name+=1 \n \n def Set_Time(self):\n self.config.set(\"Date\",\"from_year\",self.to_year)\n self.config.set(\"Date\",\"from_month\",self.to_month)\n self.config.set(\"Date\",\"from_day\",self.to_day)\n self.config.write(open('Config_crawler.ini', 'wb'))\n \n def Crawl_AllExternal(self):\n self.Crawl_rate_exchange()\n self.Crawl_Index()\n self.Crawl_Stock()\n self.Set_Time()\n \nif __name__ == '__main__':\n cr = Crawler()\n cr.Crawl_AllExternal()\n \n \n\n","repo_name":"AnsenHuang14/WebCrawler","sub_path":"StepwiseFeatureSelectionWithExternalFactorCrawler/Crawler.py","file_name":"Crawler.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"73804390244","text":"import collections\n\n\nclass solution:\n ans = 0\n def numTilePossible(self, tiles):\n counter = collections.Counter(tiles)\n for i in range(1, len(tiles) + 1):\n self.words(i, counter, '')\n return self.ans\n\n def words(self, length, counter, word):\n if length == len(word):\n self.ans += 1\n return\n\n for k, v in counter.items():\n if v > 0:\n counter[k] -= 1\n self.words(length, counter, word + k)\n counter[k] += 1\n\nobj = solution()\ntiles = \"AABB\"\nprint(obj.numTilePossible(tiles))\n","repo_name":"tanjingjing123/LeetcodeAlgorithms","sub_path":"letterTilePossibles.py","file_name":"letterTilePossibles.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"31152436676","text":"# coding=utf-8\r\n# author = zhouxin\r\n# date = 2017.7.24\r\n\r\n'''\r\n31. Next Permutation\r\nImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.\r\n\r\nIf such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).\r\n\r\nThe replacement must be in-place, do not allocate extra memory.\r\n\r\nHere are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.\r\n1,2,3 → 1,3,2\r\n3,2,1 → 1,2,3\r\n1,1,5 → 1,5,1\r\n'''\r\n\r\nclass Solution(object):\r\n def nextPermutation(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: void Do not return anything, modify nums in-place instead.\r\n 思路:\r\n 开始的时候没读懂题目,大概意思是说,现在有一个数组,可以看作一个整数 [1,2,3] >> 123 ,\r\n 找到这个数组的下一种排列方式,即形成的整数刚好比原数组大 123 >> 132 这里用了刚好,\r\n 可以理解为, 将 123 随机组合,然后按小到大的顺序排列,找出目前数组下一种排列方式。\r\n 如果该种排列方式形成的数组最大,则输出最小的排列。\r\n\r\n 从后先前遍历数组,如果当前数字索引 i 比下一数字索引 i-1 大,则在 i 之前的数组中寻找 大于 i-1\r\n 但小于 i 的索引 j\r\n 交换 i-1 和 j 的位置\r\n 最后对 i 之后的数从小到大排序\r\n \r\n \"\"\"\r\n if len(nums) < 2 : return\r\n idx = 0\r\n for i in range(len(nums)-1, 0, -1):\r\n if nums[i] > nums[i-1]:\r\n r = self.find_right(nums[i-1], nums[i], i, nums[i+1:])\r\n nums[r], nums[i-1] = nums[i-1], nums[r]\r\n idx = i\r\n break\r\n for i in range(idx,len(nums)):\r\n for j in range(idx, len(nums)-1):\r\n if nums[j+1] < nums[j]:\r\n nums[j+1], nums[j] = nums[j], nums[j+1]\r\n\r\n def find_right(self, left, right, idx, lst):\r\n if not lst:\r\n return idx\r\n suit = right\r\n id = idx\r\n for i in range(len(lst)):\r\n if lst[i] > left and lst[i] < right and lst[i] < suit:\r\n suit = lst[i]\r\n id = idx + i + 1\r\n\r\n return id\r\n\r\nnums = [9,1]\r\ns = Solution()\r\ns.nextPermutation(nums)\r\n","repo_name":"Provinm/leetcode_archive","sub_path":"problems1_100/31_Next_Permutation.py","file_name":"31_Next_Permutation.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"46563352436","text":"from math import pi, sin, cos\nimport sys\nfrom direct.showbase.ShowBase import ShowBase\nfrom direct.task import Task\n \nclass MyApp(ShowBase):\n def __init__(self):\n ShowBase.__init__(self)\n \n \n # Load the environment model.\n self.environ = self.loader.loadModel(\"models/environment\")\n self.environ.reparentTo(self.render)\n self.environ.setScale(0.25, 0.25, 0.25)\n self.environ.setPos(-8, 42, 0)\n\n # Disable default mouse/camera task\n self.disableMouse()\n self.accept(\"w\", self.startMoveForward)\n self.accept(\"w-up\", self.stopMoveForward)\n self.accept(\"a\", self.startMoveLeft)\n self.accept(\"a-up\", self.stopMoveLeft)\n self.accept(\"d\", self.startMoveRight)\n self.accept(\"d-up\", self.stopMoveRight)\n self.accept(\"s\", self.startMoveBack)\n self.accept(\"s-up\", self.stopMoveBack)\n \n self.accept(\"escape\", sys.exit)\n self.taskMgr.add(self.playerControlTask, \"playerControlTask\")\n\n # self.User is a dummy node to attach camera to\n self.Player = render.attachNewNode('Player')\n self.camera.reparentTo(self.Player)\n \n #default movement setting\n self.movingForward = False\n self.movingLeft = False\n self.movingRight = False\n self.movingBack = False\n \n def startMoveForward(self):\n self.movingForward = True\n\n def stopMoveForward(self):\n self.movingForward = False\n\n def startMoveBack(self):\n self.movingBack = True\n\n def stopMoveBack(self):\n self.movingBack = False\n\n def startMoveLeft(self):\n self.movingLeft = True\n \n def stopMoveLeft(self):\n self.movingLeft = False\n\n def startMoveRight(self):\n self.movingRight = True\n \n def stopMoveRight(self):\n self.movingRight = False\n\n\n\n def playerControlTask(self, task):\n \"\"\"\n Handle movement\n constantly move somewhere (or nowhere)\n keydown will trigger movement, keyup will trigger stop\n \n \"\"\" \n if self.movingForward == True:\n self.Player.setPos(self.Player, 0, 0.1, 0)\n if self.movingBack == True:\n self.Player.setPos(self.Player, 0, -0.1, 0)\n if self.movingLeft == True:\n self.Player.setPos(self.Player, -0.1, 0, 0)\n if self.movingRight == True:\n self.Player.setPos(self.Player, 0.1, 0, 0)\n\n return task.cont\n \napp = MyApp()\napp.run()\n","repo_name":"DevDungeon/Cookbook","sub_path":"python/panda3D/camDrivers/camKeyboardDrive.py","file_name":"camKeyboardDrive.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"}
+{"seq_id":"19665585138","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jul 26 18:04:39 2020\r\n\r\n@author: Srinath\r\n\"\"\"\r\n\r\n\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter import ttk\r\nfrom PIL import Image\r\nimport pytesseract\r\nfrom pytesseract import image_to_string\r\npytesseract.pytesseract.tesseract_cmd = \"C:/Program Files (x86)/Tesseract-OCR/tesseract.exe\"\r\n\r\nfrom handwriting_recognition import pytesseractresult\r\n\r\n\r\nclass PyTextractor:\r\n def __init__(self, master):\r\n self.master = master\r\n master.title(\"Text Extraction\")\r\n master.geometry(\"500x500\")\r\n master.resizable(0, 0)\r\n root.configure(bg='blue4')\r\n\r\n self.select_button = Button(master, text=\"Select Method\")\r\n self.select_button.pack()\r\n self.cmb = ttk.Combobox(master,width=\"15\",values=(\"PyTesseract\", \"PyTextractor\"))\r\n self.cmb.pack()\r\n self.textify_button = Button(master, text=\"Open Image\", command=self.textify)\r\n self.textify_button.pack()\r\n def textify(self):\r\n target = filedialog.askopenfilename()\r\n if self.cmb.get()==\"PyTextractor\":\r\n textinimage = image_to_string(Image.open(target))\r\n else:\r\n textinimage = pytesseractresult((target))\r\n T.insert(END, textinimage)\r\n\r\nroot = Tk()\r\n#root.configure(bg='blue4')\r\nS = Scrollbar(root)\r\nT = Text(root, height=4, width=50)\r\nS.pack(side=RIGHT, fill=Y)\r\nT.pack(side=LEFT, fill=Y)\r\nS.config(command=T.yview)\r\nT.config(yscrollcommand=S.set)\r\n\r\ngraphical = PyTextractor(root)\r\ndef quit():\r\n root.destroy()\r\n\r\nbtn1=ttk.Button(root, text=\"Exit\", command=quit)\r\nbtn1.place(relx=\"0.2\",rely=\"0.8\")\r\nroot.mainloop()","repo_name":"srinathmadasu76/TextExtractionNLP","sub_path":"guitextextraction.py","file_name":"guitextextraction.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34299056103","text":"import sys, getopt\nimport json\nimport logging\nfrom datetime import date\n\n\nfuzzer_logger = logging.getLogger(\"Fuzzer\")\n\nurl = \"http://localhost/login-1/\"\ntotal_base_strings = 10\nmax_tries = 7\nodds_file = \"Tools/Database/odds.json\"\ndebug_mode = False\n\nfrom Tools.sql_generator import *\nfrom Tools.tester import payload_check\n\ndef init_args(argv):\n \"\"\"\n This function initialize the args from cmd/Terminal\n \"\"\"\n global url, total_base_strings, max_tries, odds_file, debug_mode\n with open(\"txt/help.txt\") as f:\n help_lines = f.readlines()\n help_lines = \"\".join(help_lines)\n try:\n opts, args = getopt.getopt(argv,\"u:b:t:f:d\")\n except getopt.GetoptError:\n print(\"fuzzer.py -u -b \" \\\n \"-t -f -d\\n\" + help_lines)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print(\"fuzzer.py -u -t \" \\\n \"-c -f -d\\n\" + help_lines)\n sys.exit()\n elif opt in \"-u\":\n url = arg\n elif opt in \"-b\":\n total_base_strings = int(arg)\n elif opt in \"-t\":\n max_tries = int(arg)\n elif opt in \"-f\":\n odds_file = arg\n elif opt in \"-d\":\n debug_mode = True\n init_stats(odds_file)\n\ndef change_info_in_string(s, info):\n \"\"\"\n This function is an addon to the txt_results function.\n It help altering info inside the report format easier.\n \"\"\"\n num_len = len(str(info))\n zero_index = s.find(\"0\")\n\n s = s[:zero_index] + str(info) + s[zero_index + num_len:]\n return s\n\ndef txt_results():\n today = date.today()\n date_today = today.strftime(\"%m_%d_%y\")\n filename = \"{}_report_s{}_e{}.txt\".format(date_today, len(successful_list), len(error_list))\n s = \"\"\n # Adding the fixed report info\n with open(\"txt/sample_report.txt\") as f:\n lines = f.readlines()\n for l in lines[:5]:\n s += l\n # Adding the tries and success info\n total_tries = len(garbage) + len(error_list) + len(successful_list)\n s += change_info_in_string(lines[5], total_tries)\n s += change_info_in_string(lines[6], len(successful_list))\n s += change_info_in_string(lines[7], len(error_list))\n\n for l in lines[8:11]:\n s += l\n\n s += change_info_in_string(lines[11], total_base_strings)\n s += change_info_in_string(lines[12], max_tries)\n\n for l in lines[13:16]:\n s += l\n s += change_info_in_string(lines[16], filename)\n\n for l in lines[17:18]:\n s += l\n\n with open(filename, \"w\") as f:\n f.write(s)\n\n f.write(\"\\nSuccessful Strings\\n------------------\\n\")\n for id, tried_string in successful_list:\n f.write(tried_string + \"\\n\")\n\n f.write(\"\\nError Strings\\n-------------\\n\")\n for id, tried_string in error_list:\n f.write(tried_string + \"\\n\")\n\n f.write(\"\\nNone Effective Strings\\n----------------------\\n\")\n for id, tried_string in garbage:\n f.write(tried_string + \"\\n\")\n\n return s\n\n\ndef fuzzing():\n \"\"\"\n This is the fuzzing function.\n It generates strings and tries them.\n The function prints a summarized report and returns the successful strings\n \"\"\"\n global garbage, error_list, successful_list\n s_list = [] # Stores the base strings\n garbage = [] # Stores the old, non-working strings\n abnormal = [] # Stores the strings with abnormal behaviours\n error_list = []\n successful_list = []\n\n # Making the base strings\n print(\"Making the base strings\")\n for i in range(total_base_strings):\n id, s = create_string()\n fuzzer_logger.info(\" Base string: {}, id: {}\".format(s, id))\n s_list.append((id, s))\n\n print(\"Checking strings...\")\n # Testing every base string\n for id, s in s_list:\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check != \"normal\":\n abnormal.append((id, s))\n # Removing abnormal strings from s_list\n s_list = [(id,s) for id, s in s_list if (id,s) not in abnormal]\n\n\n print(\"First results:\\n Tried strings: {}\\n\"\\\n \" Abnormal Strings: {}\".format(str(len(abnormal) + len(s_list)), len(abnormal)))\n\n print(\"Trying to upgrade the \\\"normal\\\" strings\")\n # Adding commands to the \"normal\" base string to get different result\n if debug_mode:\n fuzzer_logger.info(\" Upgrading \\\"normal\\\" strings\")\n for id, s in s_list:\n tries = 0\n fuzzer_logger.info(\" Upgrading \\\"normal\\\" string: {}\".format(s))\n while tries < max_tries:\n tries += 1\n garbage.append((id,s))\n id, s = upgrade(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check != \"normal\":\n abnormal.append((id,s))\n break\n\n print(\"Adding another command to abnormal strings\")\n # Upgrading abnormal strings to try and make them better\n if debug_mode:\n fuzzer_logger.info(\" Checking abnormal strings\")\n for id, s in abnormal:\n garbage.append((id, s))\n id, s = upgrade(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check == \"normal\":\n # abnormal string has stopped working\n garbage.append((id, s))\n continue\n if check == \"error\":\n # Same result as before, still interesting\n error_list.append((id, s))\n if check == \"success\":\n # This is a perfect string, goes straight to save\n successful_list.append((id, s))\n\n error_list += abnormal\n print(\"Now checking all the strings that made errors\")\n # Trying to make error string be successful\n fuzzer_logger.info(\" Adding finishing touches(comments) to error strings\")\n for id, s in error_list:\n tries = 0\n while tries < max_tries:\n tries += 1\n garbage.append((id, s))\n id, s = finishing_touches(id)\n check = payload_check(url, s)\n fuzzer_logger.info(\" Checked: {}, Result: {}\".format(s, check))\n if check == \"error\":\n continue # nothing has changed, continue to check\n if check == \"normal\":\n garbage.append((id, s)) # error string broke, throw it to garbage\n break\n if check == \"success\":\n successful_list.append((id, s)) # the string is perfect!, Saving it...\n break\n\n print(txt_results())\n return successful_list\n\n\n\nif __name__ == '__main__':\n init_args(sys.argv[1:])\n\n logging.basicConfig(filename=\"\" if debug_mode else \"logs/fuzzer.log\", level=logging.DEBUG)\n fuzzer_logger.debug(\"URL: {}, Max base strings: {},\"\\\n \"Max tries per string: {}, Odds file: {}, \"\\\n \"Debug: {}\".format(url, total_base_strings, max_tries, odds_file, debug_mode))\n\n fuzzing()","repo_name":"AmitayAbudy/SQLi-Fuzzer","sub_path":"fuzzer.py","file_name":"fuzzer.py","file_ext":"py","file_size_in_byte":7085,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"70979516325","text":"#code\nRequest = 1\nSuccess = 3\nResponse = 2\nFailure = 4\n\n#type\nIdentity = 1\nLegacyNak = 3\nMD5Challenge = 4\n\nPEAP = 25\nMSCHAPV2 = 26\n\n#mschap\nChallenge = 1\nResponse = 2\nSuccess = 3\nFailure = 4\nChangePassword =5\n\nimport struct\nimport uuid\nimport logging\n\nlogger = logging.getLogger('eap.message')\ndebug = logger.debug\n\n\n\nclass EAP:\n\n def __init__(self, Identity):\n self.Identity = Identity\n\n def eap_body(self, data):\n r = data()\n t = data[0]\n body = data[1:]\n\n if t == Identity:\n r['Identity'] = body.decode('utf8')\n elif t == LegacyNak:\n r['LegacyNak'] = body[0]\n elif t == MD5Challenge:\n l = body[0]\n r['MD5Challenge'] = body[1:l+1]\n elif t== MSCHAPV2:\n print('TODO')\n\n elif t == PEAP:\n flags = body[0]\n r['TLSFlags'] = flags\n r['TLSMore'] = flags & 0x40\n\n if flags & 0x80:\n l = body[1] << 32 | body[2] << 16 | body[3] << 8 | body[4]\n if l:\n r['TLS'] = body[5:l+5]\n else:\n r['TLS'] = body[5:]\n else:\n r['TLS'] = body[1:]\n\n\n def eap(self, data):\n code,ident,length = data[0],data[1],data[2] << 8 | data[3]\n data = data[4:length]\n\n return code,ident,length, self.eap_body(data)","repo_name":"alex-eri/uradius","sub_path":"radius/eap/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18074786395","text":"def consecutiveNums():\n nums = []\n for i in range(100):\n inputNum = eval(input(\"Enter a number:\\nEnter 0 to quit loop \"))\n if inputNum == 0:\n break\n nums.append(inputNum)\n\n countingList = []\n for k in range(len(nums)):\n counter = 0\n for j in range(len(nums)):\n if nums[k] == nums[j]:\n counter += 1\n if nums[k] not in countingList:\n print(str(nums[k]) + \" is repeated \" + str(counter) + \" times\")\n countingList.append(nums[k])\n\n\nconsecutiveNums()\n","repo_name":"SaadRehmanCS/PythonMiniChallengeProblems","sub_path":"src/ConsecutiveNums.py","file_name":"ConsecutiveNums.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28583543259","text":"data = []\ncount = 0\nwith open('reviews.txt', 'r') as f:\n\tfor line in f:\n\t\tcount += 1 #count = count +1\n\t\tdata.append(line)\n\t\t#if count % 1000 == 0: #餘數等於0\n\t\t\t#print(len(data))\n\nprint('檔案讀取完了, 總共有', len(data), '筆資料')\n\nprint(data[0]) \nprint(len(data[0]))\n \nsum_len = 0\nfor d in data:\n\tsum_len += len(d) #sum_len = sum_len + len(d)\n\nprint('平均長度是', sum_len/len(data))\n\nmata = []\n\nfor s in data:\n\tif len(s) < 100:\n\t\tmata.append(s)\n\nprint('一共有', len(mata), '筆資料長度小於100')\n\ngood = [] #清單快寫法 good[a for a in data if 'good' in d] 第一個a 代表 good.append(a)\n\nfor a in data:\n\tif 'good' in a:\n\t\tgood.append(a)\n\nprint('一共有', len(good),'個留言提到good')\nprint(good[0])\n\nbad = [d for d in data if 'bad' in d]\nprint(bad[0])\n\nbad = [1 for d in data if 'bad' in d]\nprint(bad[0])\n\nbad = ['bad' in d for d in data]\n\nbad = []\nfor d in data:\n\tbad.append('bad' in d)","repo_name":"brad510444/reviews-analytics","sub_path":"read2.py","file_name":"read2.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"32059547630","text":"\"\"\"\nPlugin ytdl para ia.cecil: Devolve vídeo/áudio a partir de link.\n\nia.cecil\n\nCopyleft 2020-2022 Iuri Guilherme \n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\"\"\"\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport io\nimport os\nimport random\nimport uuid\nimport validators\nimport youtube_dl\nimport yt_dlp\nfrom aiogram.utils.markdown import escape_md, pre\nfrom contextlib import redirect_stdout\nfrom tempfile import gettempdir\nfrom iacecil.controllers.aiogram_bot.callbacks import (\n command_callback,\n error_callback,\n message_callback,\n)\n\nasync def baixar(url, extension = 'mp4', **kwargs):\n try:\n video_file_name = os.path.join(gettempdir(), \"ic.{}.{}\".format(\n uuid.uuid4(), extension))\n options = {\n 'outtmpl' : video_file_name,\n #'format': 'worstvideo+worstaudio/worst',\n # ~ 'format': 'mp4',\n # ~ 'max_filesize': 1,\n #'merge_output_format': 'mp4',\n #'postprocessor_args': [\n #'-an',\n #'-c:v libx264',\n #'-crf 26',\n #'-vf scale=640:-1',\n #],\n **kwargs,\n }\n ## FIXME Blocking!\n ## This is always blocking in upstream:\n ## https://github.com/ytdl-org/youtube-dl/issues/30815\n ## https://github.com/yt-dlp/yt-dlp/issues/3298\n ## https://github.com/yt-dlp/yt-dlp/issues/1918\n # ~ youtube_dl.YoutubeDL(options).download([url])\n yt_dlp.YoutubeDL(options).download([url])\n return video_file_name\n except Exception as exception:\n logger.warning(repr(exception))\n raise\n\nasync def ytdl(dispatcher, message):\n url = None\n command = u\"Não deu certo...\"\n ## Será que é link?\n if message.entities is not None:\n for entity in message.entities:\n if entity['type'] == \"url\":\n url = message.text[entity['offset']:entity[\n 'length'] + entity['offset']]\n if not url and message.reply_to_message is not None:\n for entity in message.reply_to_message.entities:\n if entity['type'] == \"url\":\n url = message.reply_to_message.text[entity[\n 'offset']:entity['length'] + entity['offset']]\n if url and validators.url(url):\n pass\n else:\n url = None\n if url:\n video_file = None\n try:\n with redirect_stdout(io.StringIO()) as f:\n await baixar(url, format = 'mp4', max_filesize = 1)\n video_size = f.getvalue().split(\n '[download] File is larger than max-filesize ('\n )[1].split(' bytes > 1 bytes). Aborting.'\n )[0]\n if int(video_size) >= 50000000:\n command = await message.reply(u\"\"\"O vídeo é maior d\\\no que o limite de 50mb do telegram e por consequência disto não posso t\\\ne ajudar hoje. Se no futuro o meu desenvolvedor conseguir dividir o víd\\\neo em pedaços, uma das robôs vai avisar no canal: {}\"\"\".format(\n dispatcher.config.telegram['info']['channel']))\n else:\n video_file = await baixar(url, extension='mp4',\n format='mp4')\n except Exception as exception:\n await error_callback(\n u\"Erro tentando baixar vídeo\",\n message,\n exception,\n ['ytdl'],\n )\n command = await message.reply(\n escape_md(u\"\"\"Não consegui extrair a mídia. Olha o \\\nque o servidor me disse: \"\"\") + pre(\"{}\".format(str(exception))),\n parse_mode = \"MarkdownV2\",\n disable_notification = True,\n )\n video = None\n try:\n if video_file:\n with open(video_file, 'rb') as video:\n command = await message.reply_video(\n video = video,\n caption = url,\n )\n if not command:\n raise\n except Exception as exception:\n await error_callback(\n u\"Erro tentando subir vídeo\",\n message,\n exception,\n ['ytdl', 'exception'],\n )\n command = await message.reply(u\"\"\"Não consegui enviar o\\\n arquivo. Tentei avisar o pessoal do desenvolvimento...\"\"\",\n disable_notification = True,\n )\n finally:\n if video is not None:\n video.close()\n try:\n if video_file is not None and os.path.exists(\n video_file):\n os.remove(video_file)\n except Exception as exception:\n logging.warning(u\"probably path doesn't exist\")\n logging.warning(repr(exception))\n else:\n command = await message.reply(escape_md(u\"\"\"\\nO comando \\\n{comando} serve pra extrair um vídeo ou áudio de algum site com suporte\\\n. Este comando usa o youtube-dl. Digite \"{comando} url\" para usar (dê u\\\nm espaço entre o comando e o link). Por exemplo, para baixar o vídeo do\\\n rick roll:\\n\\n\"\"\".format(comando = message.get_command())) + \\\npre(u\"\"\"{comando} https://youtube.com/watch?v=dQw4w9WgXcQ\"\"\".format(\n comando = message.get_command())) + escape_md(u\"\"\"\\n\\nOu então resp\\\nonda uma mensagem que tem um link com {comando} na resposta.\"\"\".format(\n comando = message.get_command()\n )),\n parse_mode = \"MarkdownV2\",\n )\n await command_callback(command, ['ytdl', message.chat.type])\n\n## Aiogram\nasync def add_handlers(dispatcher):\n try:\n ## Extrai vídeo ou áudio de vários serviços\n @dispatcher.message_handler(commands = ['y', 'yt', 'ytdl',\n 'youtube', 'baixar', 'video', 'download', 'dl'])\n async def ytdl_callback(message):\n await message_callback(message, ['ytdl', message.chat.type])\n await message.reply(u\"ok, vou baixar o vídeo e já te aviso\")\n await ytdl(dispatcher, message)\n except Exception as e:\n logger.exception(e)\n raise\n","repo_name":"iuriguilherme/iacecil","sub_path":"src/plugins/ytdl.py","file_name":"ytdl.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"28672323840","text":"import unittest\nfrom city_functions import formatted_city_country\n\nclass TestFormattedCityCountry(unittest.TestCase):\n\n def test_city_country(self):\n formatted_result = formatted_city_country('santiago', 'chile')\n self.assertEqual(formatted_result, 'Santiago, Chile')\n\n def test_city_country_population(self):\n formatted_result = formatted_city_country('santiago', 'chile', \n 500000)\n self.assertEqual(formatted_result, \n 'Santiago, Chile - population 500000')\n\nunittest.main()","repo_name":"drliebe/python_crash_course","sub_path":"ch11/test_cities.py","file_name":"test_cities.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27810259721","text":"import struct\ntry:\n from collections import OrderedDict\nexcept ImportError: # your python version might be too old already\n from backport import OrderedDict\n\n# constant values for the RPL protocol\n\n# ICMPv6 message type\nICMPv6_RPL = 155\n\n# ICMPv6 message codes for RPL messages\nRPL_DIS = 0x00\nRPL_DIO = 0x01\nRPL_DAO = 0x02\nRPL_DAO_ACK = 0x03\nRPL_SEC_DIS = 0x80\nRPL_SEC_DIO = 0x81\nRPL_SEC_DAO = 0x82\nRPL_SEC_DAO_ACK = 0x83\nRPL_CC = 0x8A # Consistency Check\n\n# RPL control message option type\nRPL_OPT_Pad1 = 0x00\nRPL_OPT_PadN = 0x01\nRPL_OPT_DAG_Metric_Container = 0x02\nRPL_OPT_Routing_Information = 0x03\nRPL_OPT_DODAG_Configuration = 0x04\nRPL_OPT_RPL_Target = 0x05\nRPL_OPT_Transit_Information = 0x06\nRPL_OPT_Solicited_Information = 0x07\nRPL_OPT_Prefix_Information = 0x08\nRPL_OPT_Target_Descriptor = 0x09\n\n\nclass Header(object):\n \"\"\"A Generic Packet Header\"\"\"\n _fields = None\n _compound_fields = None\n\n _format = \"!\"\n _header_size = 0 # in bytes\n _header = None\n _compound = None # compound fields (i.e. fields that contains flag)\n _pure = True # per Packet instances that are directly derived from Packet\n\n def __init__(self):\n super(Header, self).__init__()\n object.__setattr__(self, \"_fields\", [])\n object.__setattr__(self, \"_compound_fields\", [])\n object.__setattr__(self, \"_header\", OrderedDict())\n object.__setattr__(self, \"_compound\", OrderedDict())\n Header.build_compound_fields(self)\n\n def __str__(self):\n self.build_compound_fields()\n return struct.pack(self._format, * self._header.values())\n\n def __repr__(self):\n self.build_compound_fields()\n fields = \"Field: \\n\" + \\\n \"\\n\".join([field + \": \" + repr(self._header[field]) for field in self._fields])\n if self._compound.keys:\n compound_fields = \"\\nCompound fields: \\n\" + \\\n \"\\n\".join([field + \": \" + repr(self._compound[field]) for field in self._compound])\n else:\n compound_fields = \"\"\n return fields + compound_fields\n\n def build_compound_fields(self):\n \"\"\"Build the compound fields from the data that are smaller than a bytes.\n This is the place where the flags are packed into bytes prior sending.\"\"\"\n pass\n\n def unpack_compound_fields(self):\n pass\n\n def parse(self, string):\n \"\"\"parse a binary string into an ICMPv6 header and return the (remaining, unparsed) payload\"\"\"\n if len(string) < self._header_size:\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format, string[:self._header_size])\n if len(unamed_fields) != len(self._fields):\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n return string[self._header_size:]\n\n # provide a dict like interface\n def __getitem__(self, key):\n try:\n return self._header[key]\n except KeyError:\n pass\n try:\n return self._compound[key]\n except KeyError:\n pass\n\n return object.__getattribute__(self, key)\n\n def __setitem__(self, key, value):\n if key in self._fields:\n self._header[key] = value\n elif key in self._compound_fields:\n self._compound[key] = value\n else:\n raise KeyError\n\n # self.unpack_compound_fields()\n\n def __getattr__(self, name):\n return self.__getitem__(name)\n\n def __setattr__(self, name, value):\n if hasattr(self, name):\n if name in self._fields or name in self._compound_fields:\n self.__setitem__(name, value)\n else:\n object.__setattr__(self, name, value)\n else:\n raise AttributeError(\"new attributes can not be added to this class\")\n\n def __div__(self, other):\n \"\"\"Syntaxic sugar for easier Header construction construction.\n Example:\n MyXYZHeader()/MyOtherXYZHeader() would be equivalent to\n \"\".join([str(MyXYZHeader()), str(MyOtherXYZHeader())])\n \"\"\"\n return \"\".join(str(self), str(other))\n\n#\n# Definition of the ICMPv6 header\n#\n\n\nclass ICMPv6(Header):\n \"\"\"A Generic Packet header\"\"\"\n\n def __init__(self, mtype=ICMPv6_RPL, code=RPL_DIO, checksum=0):\n super(ICMPv6, self).__init__()\n\n self._format += \"BBH\"\n self._fields += ['type', 'code', 'checksum']\n self._header_size += 4 # size of an ICMP header\n\n self._header['type'] = mtype\n self._header['code'] = code\n self._header['checksum'] = checksum\n\n ICMPv6.build_compound_fields(self)\n\n def build_compound_fields(self):\n super(ICMPv6, self).build_compound_fields()\n\n def unpack_compound_fields(self):\n super(ICMPv6, self).unpack_compound_fields()\n\n#\n# Definition of the RPL messages\n#\n\n\n# From Section 6.2.1, format of the DIS message:\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Flags | Reserved | Option(s)...\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass DIS(ICMPv6):\n \"\"\"DODAG Information Solicitation\"\"\"\n def __init__(self, flags=0, reserved=0, \\\n pure=False):\n if (not pure):\n super(DIS, self).__init__(code=RPL_DIS)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['flags', 'reserved']\n self._format += \"BB\"\n self._header_size += 2\n\n self._header['flags'] = flags\n self._header['reserved'] = reserved\n\n# From Section 6.3.1 (RFC 6550):\n# DIO Format\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |Version Number | Rank |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# |G|0| MOP | Prf | DTSN | Flags | Reserved |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\n\nclass DIO(ICMPv6):\n \"\"\"DODAG Information Object (DIO) message header\"\"\"\n\n def __init__(self, instanceID=0, version=0, rank=0, G=0, MOP=0,\\\n Prf=0, DTSN=0, flags=0, reserved=0, DODAGID='\\x00' * 16,\\\n pure=False):\n if (not pure):\n super(DIO, self).__init__(code=RPL_DIO)\n self._pure = False\n else:\n Header.__init__(self)\n\n # expend the format\n self._fields += ['instanceID', 'version', 'rank', \\\n 'G_MOP_Prf', 'DTSN', 'flags', 'reserved', \\\n 'DODAGID',\\\n ]\n self._compound_fields += ['G', 'MOP', 'Prf']\n self._format += 'BBHBBBB16s'\n self._header_size += 24\n\n self._header['instanceID'] = instanceID\n self._header['version'] = version\n self._header['rank'] = rank\n self._header['G_MOP_Prf'] = 0 # compound field\n self._header['DTSN'] = DTSN\n self._header['flags'] = flags\n self._header['reserved'] = reserved\n self._header['DODAGID'] = DODAGID\n\n self._compound['G'] = G\n self._compound['MOP'] = MOP\n self._compound['Prf'] = Prf\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DIO, self).build_compound_fields()\n\n # verifies the field content\n if self.G < 0 or self.G > 1:\n raise ValueError(\"G must be 0 or 1\")\n\n if self.MOP < 0 or self.MOP > 4:\n raise ValueError(\"MOP must be within range 0 to 4\")\n\n if self.Prf < 0 or self.Prf > 7:\n raise ValueError(\"Prf (DODAGPreference) must be within range 0 to 7\")\n\n self.G_MOP_Prf = self.G << 7 | self.MOP << 3 | self.Prf\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DIO, self).unpack_compound_fields()\n\n self.G = (self.G_MOP_Prf >> 7) & 0x01\n self.MOP = (self.G_MOP_Prf >> 3) & 0x07\n self.Prf = self.G_MOP_Prf & 0x07\n\n# From Section 6.4.1 (RFC 6550):\n# DAO Format\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |K|D| Flags | Reserved | DAOSequence |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID (optional) +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\nclass DAO(ICMPv6):\n \"\"\"Destination Advertisement Object\"\"\"\n def __init__(self, instanceID=0, K=0, D=0, flags=0, reserved=0, DAOsequence=0, \\\n DODAGID='\\x00' * 16, pure=False):\n if (not pure):\n super(DAO, self).__init__(code=RPL_DAO)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'KDflags', 'reserved', 'DAOsequence', \\\n 'DODAGID']\n self._compound_fields += ['K', 'D', 'flags']\n self._format += \"BBBB16s\"\n self._header_size += 20\n\n self._header['instanceID'] = instanceID\n self._header['KDflags'] = 0 # compound field\n self._header['reserved'] = reserved\n self._header['DAOsequence'] = DAOsequence\n # depends if the D flag is set or not\n self._header['DODAGID'] = DODAGID\n\n self._compound['K'] = K\n self._compound['D'] = D\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DAO, self).build_compound_fields()\n\n # verifies the field content\n if self.K < 0 or self.K > 1:\n raise ValueError(\"K must be 0 or 1\")\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 to 1\")\n\n if self.flags < 0 or self.flags > 2**6 - 1:\n raise ValueError(\"flags must be within range 0 to 63\")\n\n self.KDflags = self.K << 7 | self.D << 6 | self.flags\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DAO, self).unpack_compound_fields()\n\n self.K = (self.KDflags >> 7) & 0x01\n self.D = (self.KDflags >> 6) & 0x01\n self.flags = self.KDflags & 0x3f\n\n def __str__(self):\n # there is a need to override the default string convertion\n # this is because the DODAGID field is optional\n if not self.D: # the DODADID must not be present\n return struct.pack(self._format[:-1], * self._header.values()[:-1])\n else:\n return super(DAO, self).__str__()\n\n def parse(self, string):\n # there is a need to override the default input parsing\n # this is because the DODAGID field is optional\n if len(string) < self._header_size - 16: # that is, if the DODAGID is not present\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format[:-1], string[:self._header_size - 16])\n if len(unamed_fields) != len(self._fields) - 1:\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n\n if not self.D:\n return string[self._header_size - 16:]\n else:\n return super(DAO, self).parse(string)\n\n# From Section 6.5\n# DAO-ACK\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |D| Reserved | DAOSequence | Status |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID* +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\nclass DAO_ACK(ICMPv6):\n \"\"\"Destination Advertisement Object Acknowledgment\"\"\"\n\n def __init__(self, instanceID=0, D=0, reserved=0, DAOSequence=0, Status=0, \\\n DODAGID='\\x00' * 16,\n pure=False):\n if (not pure):\n super(DAO_ACK, self).__init__(code=RPL_DAO_ACK)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'Dreserved', 'DAOSequence', 'Status', \\\n 'DODAGID']\n self._compound_fields += ['D', 'reserved']\n self._format += \"BBBB16s\"\n self._header_size += 20\n\n self._header['instanceID'] = instanceID\n self._header['Dreserved'] = 0 # compound field\n self._header['DAOSequence'] = DAOSequence\n self._header['Status'] = Status\n self._header['DODAGID'] = DODAGID\n\n self._compound['D'] = D\n self._compound['reserved'] = reserved\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(DAO_ACK, self).build_compound_fields()\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 to 1\")\n\n if self.reserved < 0 or self.reserved > 2**7 - 1:\n raise ValueError(\"reserved must be within range 0 to 127\")\n\n self.Dreserved = self.D << 7 | self.reserved\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(DAO_ACK, self).unpack_compound_fields()\n\n self.D = (self.Dreserved >> 7) & 0x01\n self.reserved = self.Dreserved & 0x7f\n\n def __str__(self):\n # there is a need to override the default string convertion\n # this is because the DODAGID field is optional\n if not self.D: # the DODADID must not be present\n return struct.pack(self._format[:-1], * self._header.values()[:-1])\n else:\n return super(DAO_ACK, self).__str__()\n\n def parse(self, string):\n # there is a need to override the default input parsing\n # this is because the DODAGID field is optional\n if len(string) < self._header_size - 16: # that is, if the DODAGID is not present\n raise Exception(\"string argument is to short to be parsed\")\n\n unamed_fields = struct.unpack(self._format[:-1], string[:self._header_size - 16])\n if len(unamed_fields) != len(self._fields) - 1:\n raise Exception(\"unpacked field data does not match, check your header definition\")\n\n for k, field in zip(self._header.keys(), unamed_fields):\n self._header[k] = field\n self.unpack_compound_fields()\n\n if not self.D:\n return string[self._header_size - 16:]\n else:\n return super(DAO_ACK, self).parse(string)\n\n# From Section 6.6.1.\n# Format of the CC Base Object\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | RPLInstanceID |R| Flags | CC Nonce |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Destination Counter |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Option(s)...\n# +-+-+-+-+-+-+-+-+\n\n\nclass CC(ICMPv6):\n \"\"\"Consistency Check message format\"\"\"\n def __init__(self, instanceID=0, R=0, flags=0, Nonce=0, \\\n DODAGID='\\x00' * 16, \\\n DestCounter=0,\\\n pure=False):\n if (not pure):\n super(CC, self).__init__(code=RPL_CC)\n self._pure = False\n else:\n Header.__init__(self)\n\n self._fields += ['instanceID', 'Rflags', 'Nonce', \\\n 'DODAGID', 'DestCounter']\n self._compound_fields += ['R', 'flags']\n self._format += \"BBH16sI\"\n self._header_size += 24\n\n self._header['instanceID'] = instanceID\n self._header['Rflags'] = 0\n self._header['Nonce'] = Nonce\n self._header['DODAGID'] = DODAGID\n self._header['DestCounter'] = DestCounter\n\n self._compound['R'] = R\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n if (not self._pure):\n super(CC, self).build_compound_fields()\n\n # verifies the field content\n if self.R < 0 or self.R > 1:\n raise ValueError(\"R must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 2**7 - 1:\n raise ValueError(\"flags must be within range 0 to 127\")\n\n self.Rflags = self.R << 7 | self.flags\n\n def unpack_compound_fields(self):\n if (not self._pure):\n super(CC, self).unpack_compound_fields()\n\n self.R = (self.Rflags >> 7) & 0x01\n self.flags = self.Rflags & 0x7f\n#\n# Definition of the RPL options\n#\n\n\n# From Section 6.7.1\n# RPL Control message option generic format\n#\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Option Type | Option Length | Option Data\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n\n\nclass RPL_Option(Header):\n \"\"\"A Generic Option header\"\"\"\n\n def __init__(self, mtype=RPL_OPT_Pad1, length=0):\n super(RPL_Option, self).__init__()\n\n self._format += \"BB\"\n self._fields += ['type', 'length']\n self._header_size += 2\n\n self._header['type'] = mtype\n self._header['length'] = length\n\n\n# From Section 6.7.2\n# Pad1 option format\n# 0\n# 0 1 2 3 4 5 6 7\n# +-+-+-+-+-+-+-+-+\n# | Type = 0x00 |\n# +-+-+-+-+-+-+-+-+\n\nclass RPL_Option_Pad1(Header):\n \"\"\"Pad1 option header\"\"\"\n def __init__(self):\n super(RPL_Option_Pad1, self).__init__()\n\n self._format += \"B\"\n self._fields += ['type']\n self._header_size += 1\n\n self._header['type'] = RPL_OPT_Pad1\n\n\n# From Section 6.7.3\n# PadN option format\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Type = 0x01 | Option Length | 0x00 Padding...\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n\n\nclass RPL_Option_PadN(RPL_Option):\n \"\"\"PadN option header\"\"\"\n def __init__(self, ** kwargs):\n super(RPL_Option_PadN, self).__init__(mtype=RPL_OPT_PadN, ** kwargs)\n\n def __str__(self):\n return super(RPL_Option_PadN, self).__str__() + \"\\x00\" * self.length\n\n def parse(self, string):\n payload = super(RPL_Option_PadN, self).parse(string)\n if len(string) < self._header_size + self.length:\n raise Exception(\"string argument is to short to be parsed\")\n\n return payload[self.length:]\n\n\n# From Section 6.7.4\n# DAG Metric Container\n# 0 1 2\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# | Type = 0x02 | Option Length | Metric Data\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - -\n# Figure 22: Format of the DAG Metric Container Option\n\n\nclass RPL_Option_DAG_Metric_Container(RPL_Option):\n \"\"\"DAG Metric container option\"\"\"\n def __init__(self, data=\"\"):\n \"\"\"data is the Metric Data and should contains is expected to be a raw string.\n Formating of the Metric Data is defined in RFC 6551\"\"\"\n super(RPL_Option_DAG_Metric_Container, self).__init__(mtype=RPL_OPT_DAG_Metric_Container)\n\n self._format += \"0s\" # data is considered as an empty string\n self._fields += [\"data\"]\n self._header['data'] = data\n self.length = len(str(self.data))\n\n def __str__(self):\n self.length = len(self.data)\n return super(RPL_Option_DAG_Metric_Container, self).__str__() + str(self.data)\n\n def parse(self, string):\n payload = super(RPL_Option_DAG_Metric_Container, self).parse(string)\n self.data = payload[:self.length]\n return payload[self.length:]\n\n\n# From Section 6.7.5\n# Format of the Route Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x03 | Option Length | Prefix Length |Resvd|Prf|Resvd|\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Route Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# . Prefix (Variable Length) .\n# . .\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nclass RPL_Option_Routing_Information(RPL_Option):\n \"\"\"Routing Information option\"\"\"\n def __init__(self, prefix_len=0, reserved=0, Prf=0, reserved2=0, \\\n route_lifetime=0, \\\n prefix=\"\"):\n super(RPL_Option_Routing_Information, self).__init__(mtype=RPL_OPT_Routing_Information)\n\n self._format += \"BBI0s\"\n self._fields += [\"prefix_len\", \"resvdPrfresvd2\", \\\n \"route_lifetime\", \"prefix\"]\n self._compound_fields += [\"reserved\", \"Prf\", \"reserved2\"]\n self._header_size += 6\n\n self._header['prefix_len'] = prefix_len\n self._header['resvdPrfresvd2'] = 0 # compound field\n self._header['route_lifetime'] = route_lifetime\n self._header['prefix'] = prefix\n\n self._compound['reserved'] = reserved\n self._compound['Prf'] = Prf\n self._compound['reserved2'] = reserved2\n\n # length is inferred by the size of the prefix field\n self.length = len(self.prefix) + 6\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.Prf < 0 or self.Prf > 3:\n raise ValueError(\"Prf must be between 0 or 3\")\n\n if self.reserved < 0 or self.reserved > 7:\n raise ValueError(\"reserved must be between 0 and 7\")\n\n if self.reserved2 < 0 or self.reserved2 > 7:\n raise ValueError(\"reserved2 must be between 0 and 7\")\n\n self.resvdPrfresvd2 = self.reserved << 5 | self.Prf << 3 | self.reserved2\n\n def unpack_compound_fields(self):\n self.reserved = (self.resvdPrfresvd2 >> 5) & 0x05\n self.Prf = (self.resvdPrfresvd2 >> 3) & 0x03\n self.reserved2 = self.resvdPrfresvd2 & 0x05\n\n def __str__(self):\n self.length = len(self.prefix) + 6\n return super(RPL_Option_Routing_Information, self).__str__() + str(self.prefix)\n\n def parse(self, string):\n payload = super(RPL_Option_Routing_Information, self).parse(string)\n if self.length < 6:\n raise ValueError(\"Length field is invalid (< 6)\")\n self.prefix = payload[:self.length - 6]\n return payload[self.length - 6:]\n\n\n# From Sectino 6.7.6\n# Format of the DODAG Configuration Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x04 |Opt Length = 14| Flags |A| PCS | DIOIntDoubl. |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | DIOIntMin. | DIORedun. | MaxRankIncrease |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | MinHopRankIncrease | OCP |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Reserved | Def. Lifetime | Lifetime Unit |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_DODAG_Configuration(RPL_Option):\n \"\"\"DODAG Configuration option\"\"\"\n def __init__(self, flags=0, A=0, PCS=0, DIOIntDoubl=0, \\\n DIOIntMin=0, DIORedun=0, MaxRankIncrease=0, \\\n MinHopRankIncrease=0, OCP=0, \\\n reserved=0, DefLifetime=0, LifetimeUnit=0):\n super(RPL_Option_DODAG_Configuration, self).__init__(mtype=RPL_OPT_DODAG_Configuration, length=14)\n\n self._format += \"BBBBHHHBBH\"\n self._fields += [\"flagsAPCS\", \"DIOIntDoubl\", \"DIOIntMin\", \"DIORedun\", \"MaxRankIncrease\", \\\n \"MinHopRankIncrease\", \"OCP\", \"reserved\", \"DefLifetime\", \"LifetimeUnit\"]\n self._compound_fields += ['flags', 'A', 'PCS']\n self._header_size += 14\n\n self._header['flagsAPCS'] = 0 # compound field\n self._header['DIOIntDoubl'] = DIOIntDoubl\n self._header['DIOIntMin'] = DIOIntMin\n self._header['DIORedun'] = DIORedun\n self._header['MaxRankIncrease'] = MaxRankIncrease\n self._header['MinHopRankIncrease'] = MinHopRankIncrease\n self._header['OCP'] = OCP\n self._header['reserved'] = reserved\n self._header['DefLifetime'] = DefLifetime\n self._header['LifetimeUnit'] = LifetimeUnit\n\n self._compound['flags'] = flags\n self._compound['A'] = A\n self._compound['PCS'] = PCS\n\n def build_compound_fields(self):\n # verifies the field content\n if self.A < 0 or self.A > 1:\n raise ValueError(\"A must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 15:\n raise ValueError(\"flags must be between 0 and 5\")\n\n if self.PCS < 0 or self.PCS > 7:\n raise ValueError(\"PCS must be between 0 and 7\")\n\n self.flagsAPCS = self.flags << 4 | self.A << 3 | self.PCS\n\n def unpack_compound_fields(self):\n self.flags = (self.flagsAPCS >> 4) & 0x0F\n self.A = (self.flagsAPCS >> 3) & 0x01\n self.PCS = self.flagsAPCS & 0x05\n\n\n# From Section 6.7.7\n# Format of the RPL Target Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x05 | Option Length | Flags | Prefix Length |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | Target Prefix (Variable Length) |\n# . .\n# . .\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_RPL_Target(RPL_Option):\n \"\"\"RPL Target option\"\"\"\n def __init__(self, flags=0, prefix_len=0, target_prefix=\"\"):\n super(RPL_Option_RPL_Target, self).__init__(mtype=RPL_OPT_RPL_Target)\n self._format += \"BB0s\"\n self._fields += [\"flags\", \"prefix_len\", \"target_prefix\"]\n self._header_size += 2\n\n self._header['flags'] = flags\n self._header['prefix_len'] = prefix_len\n self._header['target_prefix'] = target_prefix\n\n self.length = len(target_prefix) + 2\n\n def __str__(self):\n self.length = len(self.target_prefix) + 2\n return super(RPL_Option_RPL_Target, self).__str__() + str(self.target_prefix)\n\n def parse(self, string):\n payload = super(RPL_Option_RPL_Target, self).parse(string)\n if self.length < 2:\n raise ValueError(\"Length field is invalid (< 2)\")\n self.target_prefix = payload[:self.length - 2]\n return payload[self.length - 2:]\n\n\n# From Section 6.7.8\n# Format of the Transit Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x06 | Option Length |E| Flags | Path Control |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Path Sequence | Path Lifetime | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +\n# | |\n# + +\n# | |\n# + Parent Address* +\n# | |\n# + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Transit_Information(RPL_Option):\n \"\"\"Transit Information option\"\"\"\n def __init__(self, E=0, flags=0, path_control=0,\\\n path_sequence=0, path_lifetime=0, \\\n parent_address=\"\"):\n super(RPL_Option_Transit_Information, self).__init__(mtype=RPL_OPT_Transit_Information)\n self._format += \"BBBB0s\"\n self._fields += [\"Eflags\", \"path_control\", \"path_sequence\", \"path_lifetime\", \\\n \"parent_address\"]\n self._compound_fields += [\"E\", \"flags\"]\n self._header_size += 4\n\n self._header['Eflags'] = 0 # compound field\n self._header['path_control'] = path_control\n self._header['path_sequence'] = path_sequence\n self._header['path_lifetime'] = path_lifetime\n self._header['parent_address'] = parent_address\n\n self._compound['E'] = E\n self._compound['flags'] = flags\n\n self.length = len(parent_address) + 4\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.E < 0 or self.E > 1:\n raise ValueError(\"E must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 127:\n raise ValueError(\"flags must be between 0 and 127\")\n\n self.Eflags = self.E << 7 | self.flags\n\n def unpack_compound_fields(self):\n self.flags = self.Eflags & 0x7F\n self.E = (self.Eflags >> 7) & 0x01\n\n def __str__(self):\n self.build_compound_fields()\n self.length = len(self.parent_address) + 4\n return super(RPL_Option_Transit_Information, self).__str__() + str(self.parent_address)\n\n def parse(self, string):\n payload = super(RPL_Option_Transit_Information, self).parse(string)\n if self.length < 4:\n raise ValueError(\"Length field is invalid (< 4)\")\n self.parent_address = payload[:self.length - 4]\n return payload[self.length - 4:]\n\n\n# From Section 6.7.9\n# Format of the Solicited Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x07 |Opt Length = 19| RPLInstanceID |V|I|D| Flags |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + DODAGID +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# |Version Number |\n# +-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Solicited_Information(RPL_Option):\n \"\"\"Solicited information option\"\"\"\n def __init__(self, instanceID=0, V=0, I=0, D=0, flags=0, \\\n DODAGID='\\x00' * 16, \\\n version=0):\n super(RPL_Option_Solicited_Information, self).__init__(mtype=RPL_OPT_Solicited_Information, length=19)\n self._format += \"BB16sB\"\n self._fields += [\"instanceID\", \"VIDflags\", 'DODAGID', 'version']\n self._compound_fields += [\"V\", \"I\", \"D\", \"flags\"]\n self._header_size += 19\n\n self._header['instanceID'] = instanceID\n self._header['VIDflags'] = 0 # compound field\n self._header['DODAGID'] = DODAGID\n self._header['version'] = version\n\n self._compound['V'] = V\n self._compound['I'] = I\n self._compound['D'] = D\n self._compound['flags'] = flags\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.V < 0 or self.V > 1:\n raise ValueError(\"V must be 0 or 1\")\n\n if self.I < 0 or self.I > 1:\n raise ValueError(\"I must be 0 or 1\")\n\n if self.D < 0 or self.D > 1:\n raise ValueError(\"D must be 0 or 1\")\n\n if self.flags < 0 or self.flags > 31:\n raise ValueError(\"flags must be between 0 and 31\")\n\n self.VIDflags = self.V << 7 | self.I << 6 | self.D << 5 | self.flags\n\n def unpack_compound_fields(self):\n self.V = self.VIDflags >> 7 & 0x01\n self.I = self.VIDflags >> 6 & 0x01\n self.D = self.VIDflags >> 5 & 0x01\n self.flags = self.VIDflags & 0x1F\n\n\n# From Section 6.7.10\n# Format of the Prefix Information Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x08 |Opt Length = 30| Prefix Length |L|A|R|Reserved1|\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Valid Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Preferred Lifetime |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Reserved2 |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | |\n# + +\n# | |\n# + Prefix +\n# | |\n# + +\n# | |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\nclass RPL_Option_Prefix_Information(RPL_Option):\n \"\"\"Prefix Inforrmation Option\"\"\"\n def __init__(self, prefix_len=0, L=0, A=0, R=0, reserved=0, \\\n valid_lifetime=0, preferred_lifetime=0, \\\n reserved2=0,\n prefix=\"\"):\n super(RPL_Option_Prefix_Information, self).__init__(mtype=RPL_OPT_Prefix_Information, length=30)\n self._format += \"BBIII16s\"\n self._fields += [\"prefix_len\", \"LARreserved\", \"valid_lifetime\", \\\n \"preferred_lifetime\", \"reserved2\", \"prefix\"]\n self._compound_fields += [\"L\", \"A\", \"R\", \"reserved\"]\n self._header_size += 30\n\n self._header['prefix_len'] = prefix_len\n self._header['LARreserved'] = 0 # compound field\n self._header['valid_lifetime'] = valid_lifetime\n self._header['preferred_lifetime'] = preferred_lifetime\n self._header['reserved2'] = reserved2\n self._header['prefix'] = prefix\n\n self._compound['L'] = L\n self._compound['A'] = A\n self._compound['R'] = R\n self._compound['reserved'] = reserved\n\n self.build_compound_fields()\n\n def build_compound_fields(self):\n # verifies the field content\n if self.L < 0 or self.L > 1:\n raise ValueError(\"L must be 0 or 1\")\n\n if self.A < 0 or self.A > 1:\n raise ValueError(\"A must be 0 or 1\")\n\n if self.R < 0 or self.R > 1:\n raise ValueError(\"R must be 0 or 1\")\n\n if self.reserved < 0 or self.reserved > 31:\n raise ValueError(\"reserved must be between 0 and 31\")\n\n self.LARreserved = self.L << 7 | self.A << 6 | self.R << 5 | self.reserved\n\n def unpack_compound_fields(self):\n self.L = self.LARreserved >> 7 & 0x01\n self.A = self.LARreserved >> 6 & 0x01\n self.R = self.LARreserved >> 5 & 0x01\n self.reserved = self.LARreserved & 0x1F\n\n\n# From Section 6.7.11\n# Format of the RPL Target Descriptor Option\n# 0 1 2 3\n# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# | Type = 0x09 |Opt Length = 4 | Descriptor\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n# Descriptor (cont.) |\n# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\nclass RPL_Option_Target_Descriptor(RPL_Option):\n \"\"\"Target Descriptor option\"\"\"\n def __init__(self, descriptor=0):\n super(RPL_Option_Target_Descriptor, self).__init__(mtype=RPL_OPT_Target_Descriptor, length=4)\n self._format += \"I\"\n self._fields += [\"descriptor\"]\n self._header_size += 4\n\n self._header['descriptor'] = descriptor\n\n# map the type/code with the appropriate class\n\nRPL_Header_map = {\n RPL_DIS: DIS,\n RPL_DIO: DIO,\n RPL_DAO: DAO,\n RPL_DAO_ACK: DAO_ACK,\n # not implemented so far\n # RPL_SEC_DIS: None,\n # RPL_SEC_DIO: None,\n # RPL_SEC_DAO: None,\n # RPL_SEC_DAO_ACK: None,\n RPL_CC: CC,\n}\n\nRPL_Option_map = {\n RPL_OPT_Pad1: RPL_Option_Pad1,\n RPL_OPT_PadN: RPL_Option_PadN,\n RPL_OPT_DAG_Metric_Container: RPL_Option_DAG_Metric_Container,\n RPL_OPT_Routing_Information: RPL_Option_Routing_Information,\n RPL_OPT_DODAG_Configuration: RPL_Option_DODAG_Configuration,\n RPL_OPT_RPL_Target: RPL_Option_RPL_Target,\n RPL_OPT_Transit_Information: RPL_Option_Transit_Information,\n RPL_OPT_Solicited_Information: RPL_Option_Solicited_Information,\n RPL_OPT_Prefix_Information: RPL_Option_Prefix_Information,\n RPL_OPT_Target_Descriptor: RPL_Option_Target_Descriptor,\n}\n\n#\n# utility functions\n#\n\ndef findOption(payload, opt_type, position=0):\n \"\"\"Returns an option of type opt_type if it exists, or None.\n\n The position argument is used when the option appears multiple times.\n It indicates the option position (0 being the first time the option is met)\"\"\"\n\n # bottom case\n if payload == \"\":\n return None\n\n # Pad1 need special treatment\n if ord(payload[0]) == RPL_OPT_Pad1:\n if opt_type.__name__ == \"RPL_Option_Pad1\":\n if position == 0:\n return RPL_Option_Pad1()\n else:\n return findOption(payload[:1], opt_type, position - 1)\n else:\n return findOption(payload[:1], opt_type, position)\n\n option = RPL_Option()\n next_header = option.parse(payload)\n try: # parse the current option\n option = RPL_Option_map[option.type]()\n next_header = option.parse(payload)\n if isinstance(option, opt_type):\n if position == 0:\n return option\n else: # we skip this option\n return findOption(next_header, opt_type, position - 1)\n else:\n return findOption(next_header, opt_type, position)\n except KeyError:\n raise AttributeError(\"unable to find option of type %d\" % option.type)\n\ndef getAllOption(payload):\n \"\"\"Decode all option of the payload and returns a list\"\"\"\n if payload == \"\":\n return []\n\n # Pad1 need special treatment\n if ord(payload[0]) == RPL_OPT_Pad1:\n return [ RPL_Option_Pad1() ] + getAllOption(payload[1:])\n\n option = RPL_Option()\n option.parse(payload)\n\n try:\n real_option = RPL_Option_map[option.type]()\n next_option = real_option.parse(payload)\n except KeyError:\n raise AttributeError(\"unable to find option of type %d\" % option.type)\n\n return [real_option] + getAllOption(next_option)\n\n\n","repo_name":"tcheneau/simpleRPL","sub_path":"RPL/icmp.py","file_name":"icmp.py","file_ext":"py","file_size_in_byte":42382,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"52"}
+{"seq_id":"2159996057","text":"\"\"\"\nAuthor: ZR000X\nDated: 2021-08-06\nLicense: MIT\nSource: https://github.com/ZR000X/Nodes\n\"\"\"\n\n\nclass Ordinal():\n \"\"\"\n An ordinal is simply a set of all things it is greater than.\n \"\"\"\n def __init__(self, subordinates=[], superiors=[], inform_on_init = True) -> None:\n if type(subordinates) is Ordinal:\n self.subordinates = [subordinates]\n else:\n self.subordinates = subordinates\n self.superiors = superiors\n if inform_on_init:\n self.inform_subordinates()\n self.inform_superiors()\n\n def __ge__(self, other):\n return other in self.subordinates\n\n def __le__(self, other):\n return self in other.subordinates\n\n def equals(self, other):\n return self >= other and other >= self\n\n def get_rank(self, superiors_asking=[]) -> int:\n \"\"\"\n the rank of an ordinal is precisely one more than the maximum rank of its subordinates\n \"\"\"\n # deal with empty lists\n if len(self.subordinates) == 0:\n return 0 \n # Loop through subordinates\n confused = False\n equals = []\n result = 0\n for sub in self.subordinates:\n # check that subordinate is not contradictory\n # Note: the original asker can never be confused\n if sub in superiors_asking:\n confused = True\n equals += [sub]\n continue\n # if not, get some return from the subordinate when asking rank\n rank = sub.get_rank(superiors_asking=superiors_asking + [self])\n # assess the return we got from asking rank\n if type(rank) is int:\n if rank >= result:\n result = rank + 1\n else:\n if rank[0] >= result:\n result = rank[0]\n equals += rank[1]\n # this subordinate continues the chain of confusion if it answers to superiors\n # if it sees itself in equals, however, it realises not to be confused\n if len(superiors_asking) > 0 and self not in equals:\n confused = True \n # decide what to return based on confusion\n if confused:\n return [result, equals]\n return result\n\n def get_depth(self, subordinates_asking=[]) -> int:\n \"\"\"\n the depth of an ordinal is precisely one more than the maximum depth of its superiors\n \"\"\"\n # deal with empty lists\n if len(self.superiors) == 0:\n return 0 \n # Loop through superiors\n confused = False\n equals = []\n result = 0\n for sup in self.superiors:\n # check that superior is not contradictory\n # Note: the original asker can never be confused\n if sup in subordinates_asking:\n confused = True\n equals += [sup]\n continue\n # if not, get some return from the superior when asking rank\n rank = sup.get_depth(subordinates_asking=subordinates_asking + [self])\n # assess the return we got from asking rank\n if type(rank) is int:\n if rank >= result:\n result = rank + 1\n else:\n if rank[0] >= result:\n result = rank[0]\n equals += rank[1]\n # this superior continues the chain of confusion if it answers to subordinates\n # if it sees itself in equals, however, it realises not to be confused\n if len(subordinates_asking) > 0 and self not in equals:\n confused = True \n # decide what to return based on confusion\n if confused:\n return [result, equals]\n return result\n\n def hire_subordinate(self, sub, inform_sub: bool = True):\n if inform_sub:\n if self not in sub.superiors:\n sub.superiors.append(self)\n self.subordinates.append(sub) \n\n def inform_subordinates(self):\n \"\"\"\n Ensures all subordinates are aware of their subordination\n \"\"\"\n if self.subordinates is not None:\n for sub in self.subordinates:\n if type(sub) is not str and self not in sub.superiors:\n sub.superiors.append(self)\n\n def inform_all_subordinates(self):\n self.inform_subordinates()\n for sub in self.subordinates:\n sub.inform_all_subordinates()\n\n def inform_superiors(self):\n \"\"\"\n Ensures all superiors are aware of their superiority\n \"\"\"\n if self.superiors is not None:\n for sup in self.superiors:\n if self not in sup.superiors:\n sup.subordinates.append(self)\n \n def inform_all_superiors(self):\n self.inform_superiors()\n for sup in self.superiors:\n sup.inform_all_superiors()\n\n def is_root(self):\n return len(self.subordinates) == 0\n\n def is_peak(self):\n return len(self.superiors) == 0\n\n def get_roots(self, roots=[]):\n for sub in self:\n if sub is self or sub in roots:\n return [] \n if sub.is_root():\n roots.append(sub)\n else:\n roots += sub.get_roots(roots)\n return roots\n\n def get_peaks(self, peaks=[]):\n for sup in self.superiors:\n if sup is self or sup in peaks:\n return [] \n if sup.is_peak():\n peaks.append(sup)\n else:\n peaks += sup.get_peaks(peaks)\n return peaks","repo_name":"ZR000X/NetworkDataFlowModel","sub_path":"ordinal.py","file_name":"ordinal.py","file_ext":"py","file_size_in_byte":5708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"31874247160","text":"import random\n\nclass Create():\n def __init__(self,name,*args):\n dic,lic = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890!\"#$%&/()=-_|°?¿',''\n for i in range(8): lic += random.choice(dic)\n name = name.encode('utf-32')\n lic = lic.encode('utf-32')\n f = open('lic.bin','wb')\n f.write(lic); f.close()\n self.Name(name)\n\n def Name(self,name,*args):\n f = open('usr.bin','wb')\n f.write(name); f.close()\n \n \nCreate('H3XEEG')\n","repo_name":"Gashpid/HEXEEG","sub_path":"assets/lib/Others/lic_gen.py","file_name":"lic_gen.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"34247432410","text":"import sys, os, time, string\nfrom fnmatch import fnmatch\nfrom optparse import OptionParser\nimport subprocess\nfrom subprocess import Popen, PIPE\n\n\n\n# Check log files from BEAST runs and summarize HPDs\n################################################################################################################################\n# Parameters\n################################################################################################################################\n\nusage = \"usage: %prog [option]\"\nparser = OptionParser(usage=usage)\n\n\nparser.add_option(\"-i\",\"--inputpath\",\n dest = \"inputpath\",\n default = \"\",\n metavar = \"path\",\n help = \"Path to input file [required]\")\n\nparser.add_option(\"-o\",\"--outputpath\",\n dest = \"outputpath\",\n default = \"\",\n metavar = \"path\",\n help = \"Path to store output files [required]\")\n\nparser.add_option(\"-B\",\"--BEAST\",\n dest = \"beast\",\n default = \"\",\n metavar = \"path\",\n help = \"Beast 2 jar file [required]\")\n\nparser.add_option(\"-e\",\"--ess\",\n dest = \"ess\",\n default = \"\",\n metavar = \"path\",\n help = \"ESS considered sufficient [required]\")\n\nparser.add_option(\"-b\",\"--burnin\",\n dest = \"burnin\",\n default = \"\",\n metavar = \"path\",\n help = \"Percentage of log-files and tree-files to discard as burnin [required]\")\n\nparser.add_option(\"-p\",\"--pattern\",\n dest = \"pattern\",\n default = \"*.xml\",\n metavar = \"\",\n help = \"Pattern to search for (in quotes) [default = %default]\")\n\nparser.add_option(\"-m\",\"--minsamples\",\n dest = \"minsamples\",\n default = \"1000000\",\n metavar = \"\",\n help = \"Minimum number of samples [default = %default]\")\n\n(options,args) = parser.parse_args()\n\ninputpath = os.path.abspath(options.inputpath)+ \"/\"\noutputpath = os.path.abspath(options.outputpath)+ \"/\"\nbeast = os.path.abspath(options.beast)\npattern = options.pattern\ness_sufficient = int(options.ess)\nminsamples = int(options.minsamples)\nb = float(options.burnin)\nif (b > 0 and b < 1):\n\tburnin = int(round(b*100))\nelse:\n\tburnin = int(round(b))\n\nskipstats = [\"*Times*\"]\n\n\n################################################################################################################################ \n\ndef analyseESS(inputfile, skipstats = [], ess_sufficient=200): \n\n\ttol = 1e-10\n\tinsufficient_ess = []\n\n\tstatfile = open(inputfile, \"r\")\n\tstatfile.readline()\n\tfor line in statfile:\n\t\tparts = line.strip().split()\n\t\tstat_name = parts[0]\n\t\tstat_ess = float(parts[8])\n\t\tstat_95upper = float(parts[6])\n\t\tstat_95lower = float(parts[5])\n\n\t\tskip = False\n\t\tfor stat in skipstats:\n\t\t\tif (fnmatch(stat_name, stat)):\n\t\t\t\tskip = True\n\n\t\tif (not skip):\n\t\t\t#sys.stdout.write(\"\\t%s\\t%f\\n\" % (stat_name, stat_ess))\n\t\t\tif (stat_ess < ess_sufficient and stat_95upper - stat_95lower > tol):\n\t\t\t\tinsufficient_ess.append(\"%s\\t%f\" % (stat_name, stat_ess))\n\n\tstatfile.close()\n\treturn(insufficient_ess)\n#\t\n\n\ndef runLogAnalyser(inputpath, filename, outfile, beast, burnin=10):\n\n\tstart = time.time()\n\n\there = os.getcwd()\n\tos.chdir(inputpath)\n\n\tloganalyser = \"java -cp \"+beast+\" beast.util.LogAnalyser\"\n\t\t\n\tloganalyser_cmd = \"%s -b %d %s > %s\" % (loganalyser, burnin, filename, outfile)\n\n\n\tprint(loganalyser_cmd)\n\t#subprocess.check_call(loganalyser_cmd.split(\" \"))\n\n\thandle = Popen(loganalyser_cmd, stdout=None, stderr=PIPE, shell=True)\n\n\terr = handle.stderr.read()\n\tif (err != \"\"):\n\t sys.stderr.write(\"\\tWarning! Errors encountered!\\n\")\n\t #sys.stderr.write(err)\n\n\tos.chdir(here)\n\n\tend = time.time()\n\tsys.stdout.write(\"\\tLog file analysed (\"+str(end-start)+\" seconds)\\n\\n\")\n#\n\n\n\n################################################################################################################################ \nstart = time.time()\n\nif (not os.path.exists(outputpath)):\n os.mkdir(outputpath)\n\nruns = dict()\nstats = []\nfor xmlfile in sorted(os.listdir(inputpath), reverse=True):\n\tif (fnmatch(xmlfile,pattern)):\n\t\tfilename = xmlfile[:xmlfile.rfind('.')]+\"_127.log\"\n\t\tprint(filename)\n\t\tif (os.path.exists(inputpath+filename)):\t\t\t\t\n\t\t\tlogfile = open(inputpath+filename,'r')\n\t\t\tfor line in logfile:\n\t\t\t\tpass\n\t\t\tsamples = line[:line.find('\\t')]\n\n\t\t\trunLogAnalyser(inputpath, filename, outputpath+filename+\".stats\", beast, burnin)\n\n\t\t\tinsufficient_ess = analyseESS(outputpath+filename+\".stats\", skipstats, ess_sufficient)\n\t\t\tif (len(insufficient_ess) > 0):\n\t\t\t\tsys.stdout.write(\"\\tInsufficient ESS values:\\n\")\n\t\t\t\tfor s in insufficient_ess:\n\t\t\t\t\tsys.stdout.write(\"\\t\\t\"+s+\"\\n\")\n\t\t\t\n\t\t\tstats.append((filename[:filename.rfind('.')], int(samples), len(insufficient_ess)))\n\t\telse:\n\t\t\tstats.append((filename[:filename.rfind('.')], -1, -1))\n\n\n#\nstatfile = open(outputpath+\"ESS.stats\",'w')\nstatfile.write(\"Logfile\\tSamples\\tInsufficient ESS\\n\")\n\nconvfile = open(outputpath+\"Converged.stats\",'w')\nstatfile.write(\"Logfile\\tSamples\\n\")\n\nfor s in sorted(stats, key = lambda s : s[1]):\n\tif (s[1] < minsamples or s[2] > 0):\n\t\tstatfile.write(\"\\t\".join(map(str,s))+\"\\n\")\n\t\n\tif (s[2] == 0):\n\t\tconvfile.write(\"\\t\".join(map(str,s[:2]))+\"\\n\")\n\t\t\nstatfile.close()\nconvfile.close()\nend = time.time()\nprint(\"Total time taken: \"+str(end-start)+\" seconds\")","repo_name":"laduplessis/MasterSimulator","sub_path":"scripts/CheckBEAST.py","file_name":"CheckBEAST.py","file_ext":"py","file_size_in_byte":5502,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"20053402621","text":"'''\n@author: Abder-Rahman Ali, PhD\n@email: aali25@mgh.harvard.edu\n@date: 2023\n'''\n\nimport pandas as pd\nimport shutil\nimport os\n\ncsv_files = ['class_1.csv', 'class_2.csv', 'class_3.csv', 'class_4.csv', 'class_5.csv']\n\nimage_path = './data/unlabeled/'\n\nfor file in csv_files:\n df = pd.read_csv(file)\n \n # Get the class number from the file name\n class_num = file.split('_')[1].split('.')[0]\n \n # Create the directories if they don't exist\n os.makedirs(f'class_{class_num}_centroid', exist_ok=True)\n os.makedirs(f'class_{class_num}_outliers', exist_ok=True)\n os.makedirs(f'class_{class_num}', exist_ok=True)\n \n for index, row in df.iterrows():\n image_name = row['image_name']\n \n # Check if the image is a centroid\n if row['is_centroid']:\n shutil.copy(image_path + image_name, f'class_{class_num}_centroid')\n # Check if the image is an outlier\n elif row['is_outlier']:\n shutil.copy(image_path + image_name, f'class_{class_num}_outliers')\n # If the image is not a centroid or an outlier\n else:\n shutil.copy(image_path + image_name, f'class_{class_num}')","repo_name":"abderhasan/radiologist_in_the_loop_ai","sub_path":"csv_to_folders_diversity.py","file_name":"csv_to_folders_diversity.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"26547880292","text":"#!/usr/bin/python\r\n\r\n\"\"\"\r\nCreated on Tue Oct 22 15:11:29\r\n\r\n@Author: Juami\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\nimport matplotlib.pyplot as plt\r\n\r\nT = 277.15\t\t# Temperature in Kelvin\r\n# Curve to fit through the data points\r\ndef sigmoid(x, g, m):\r\n\t\"\"\" Sigmoidal function \"\"\"\r\n\tr = 8.314\t\t# Gas constant in J/(K mol)\r\n\tmt = 0.00006\t# 60 uM fibrils\r\n\treturn (((2*(np.exp((-(g+m*x))/(r*(T)))*(mt)))+1-np.sqrt(4*(np.exp((-(g+m*x))/(r*(T)))*(mt))+1))/(2*np.power((np.exp((-(g+m*x))/(r*(T)))*(mt)),2)))\r\n\r\n# Load data\r\ndf_PB = np.loadtxt('norm_ratio_60uM_PB.txt')\r\ndf_PBS = np.loadtxt('norm_ratio_60uM_PBS.txt')\r\n\r\n### Plotting\r\n# Colors\r\nblues = plt.get_cmap('Blues')\r\nreds = plt.get_cmap('Reds')\r\ncolors = [reds(0.4), reds(0.9), blues(0.4), blues(0.9)]\r\n\r\n# Legend labels\r\nlabels = ['PB room temperature', r'PB 4$^{\\circ}$C', 'PBS room temperature', r'PBS 4$^{\\circ}$C']\r\n\r\n# PB data\r\nx1 = df_PB[:,0]\r\ny11 = df_PB[:,1]\r\ny12 = df_PB[:,5]\r\n\r\n# PB data\r\nx2 = df_PBS[:,0]\r\ny21 = df_PBS[:,1]\r\ny22 = df_PBS[:,5]\r\n\r\nx_plot = np.linspace(0,5,100)\r\n\r\ny_fitted = []\r\ndef plot_sigmoid(x, y, color, label):\r\n\t\"\"\" fit sigmoid through through data points and add to plot \"\"\"\r\n\tpopt, pcov = curve_fit(sigmoid, x, y, bounds=([-50000, 0], [-100, 10000]))\r\n\tplt.plot(x, y, 'o', color=color)\r\n\tplt.plot(x_plot, sigmoid(x_plot, *popt), '-', linewidth=2, color=color, label=label)\r\n\ty_fitted.append(sigmoid(x_plot, *popt))\r\n\r\n# Make plot\r\nfig = plt.figure()\r\n\r\n# 'PB'\r\nT = 303.15\t\t# Temperature in Kelvin 30C\r\nplot_sigmoid(x1, y11, colors[0], labels[0])\r\n\r\n# 'PB'\r\nT = 277.15\t\t# Temperature in Kelvin 4C\r\nplot_sigmoid(x1, y12, colors[1], labels[1])\r\n\r\n# 'PBS'\r\nT = 303.15 \t# Temperature in Kelvin 30C\r\nplot_sigmoid(x2, y21, colors[2], labels[2])\r\n\r\n# 'PBS'\r\nT = 277.15\t\t# Temperature in Kelvin 4C\r\nplot_sigmoid(x2, y22, colors[3], labels[3])\r\n\r\ndiff_PB = y_fitted[1] - y_fitted[0]\r\ndiff_PBS = y_fitted[3] - y_fitted[2]\r\n#plt.plot(x_plot, diff_PB, color='red')\r\n#plt.plot(x_plot, diff_PBS, color='blue')\r\n\r\n#plt.title(r'$\\alpha$-synuclein denaturation at different temperatures')\r\nplt.xlabel('Urea concentration (M)', fontsize=14)\r\nplt.ylabel('Fraction monomeric', fontsize=14)\r\nplt.legend(loc=0)\r\nplt.savefig('salt_urea_denaturation.pdf')\r\nplt.show()\r\n\r\n#print y_fitted","repo_name":"ibivu/amyloid_hydrophobicity","sub_path":"PythonScripts/ionic_strength/ions_urea.py","file_name":"ions_urea.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"32432279586","text":"import json\nimport uuid\n\nfrom GMStrickAuto import *\n\n\ntasks = []\n\nwith open('Files/Tasks.txt', 'r') as file:\n for i in file:\n tasks.append(i.rstrip())\n\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nfor i in tasks:\n\n name = i.split('|')[0]\n tasks_ = i.split('|')[1].split('---')[:-1]\n claimTask = i.split('|')[1].split('---')[-1]\n\n print(tasks_, claimTask)\n\n task = Task(name=name)\n\n BSs = []\n for k in tasks_:\n try:\n data = json.loads(k)\n BS = BountyStep(bounty_step_id = data['0']['json']['bountyStepId'],\n input_data = None if data['0']['json']['inputData'] == None else json.dumps(data['0']['json']['inputData']),\n user_address_id = data['0']['json']['userAddressId'])\n BSs.append(BS)\n except KeyError:\n print(data)\n\n task.bounty_steps = BSs\n\n BC = BountyClaim(TaskID=json.loads(claimTask)['0']['json']['taskId'])\n task.bounty_claims = [BC]\n\n session.add(task)\n session.commit()\n\nsession.close()\n\n","repo_name":"folckol/Layer3","sub_path":"AddTasks.py","file_name":"AddTasks.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35216276084","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 ('tykurllog', '0009_auto_20151122_2145'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='loggedurl',\n name='repeats',\n field=models.PositiveIntegerField(default=0),\n ),\n ]\n","repo_name":"tykling/tykurllog","sub_path":"src/tykurllog/migrations/0010_loggedurl_repeats.py","file_name":"0010_loggedurl_repeats.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"22173361853","text":"import sys\nfrom sys import stderr\nimport os\n\n# Any modules you need to construct objects from should be placed in an\n# imports file\n_PREFIX = os.environ.get(\"CONSTRUCT_PY_DIR\", \".\")\n_INCLUDES_FILE = f\"{_PREFIX}/construct_py_includes.py\"\nif os.path.exists(_INCLUDES_FILE):\n print(f\"Construct.py: using includes file {_INCLUDES_FILE}\", file=stderr)\n exec(open(_INCLUDES_FILE).read())\n\n_IMPORTS_FILE = f\"{_PREFIX}/construct_py_imports.py\"\nif os.path.exists(_IMPORTS_FILE):\n sys.path.append(_IMPORTS_FILE)\n print(f\"Construct.py: using imports file {_IMPORTS_FILE}\",\n file=stderr)\n from construct_py_imports import *\n\n# Import the main module?\n_USE_MAIN = os.environ.get(\"CONSTRUCT_PY_USE_MAIN\", \"\") != \"\"\nif _USE_MAIN:\n # Alternatively, you can import the main module, in which case the\n # program will \"just work\". Two caveats to this approach:\n # 1) This can very easily turn your program into a pretzel\n # 2) In the configuration files, modules need to be prefixed with __main__\n import __main__\n\n\nclass _Custom:\n def __init__(self):\n self._custom_ops = {}\n\n def _register(self, type_: str, f):\n self._custom_ops[type_] = f\n\n def _custom(self, type_: str):\n if type_ not in self._custom_ops:\n return eval(type_)\n return self._custom_ops[type_]\n\n\n_custom = _Custom()\n\n\ndef _construct(type_: str):\n return _custom._custom(type_)\n\n\ndef register(type_: str, f):\n _custom._register(type_, f)\n\n\ndef constant(x):\n return x\n\n\ndef generic(x):\n return _eval(x)\n\n\ndef side_effect(fn, *args, **kwargs):\n if isinstance(fn, str):\n fn = _eval(fn)\n if isinstance(fn, str):\n fn = eval(fn)\n\n fn(*args, **kwargs)\n\n if len(args) == 1 and len(kwargs) == 0:\n return args[0]\n elif len(args) == 0 and len(kwargs) == 1:\n key = list(kwargs.keys())[0]\n return kwargs[key]\n\n return {\"args\": args, \"kwargs\": kwargs}\n\n\ndef arg_at(x, to_index):\n args = to_index[\"args\"]\n return args[x]\n\n\ndef kwarg_at(x, to_index):\n kwargs = to_index[\"kwargs\"]\n return kwargs[x]\n\n\n# Register some custom functions\nregister(\"constant\", constant)\nregister(\"generic\", generic)\nregister(\"side_effect\", side_effect)\nregister(\"arg_at\", arg_at) # TODO: Needs documentation\nregister(\"kwarg_at\", kwarg_at) # TODO: Needs documentation\n\n\ndef parse(config: dict):\n return _parse(config, True)\n\n\ndef _parse(config: dict, top_level: bool = True):\n keys = list(config.keys())\n\n if \"type\" in keys:\n keys.remove(\"type\")\n if \"args\" in keys:\n keys.remove(\"args\")\n if \"kwargs\" in keys:\n keys.remove(\"kwargs\")\n\n if len(keys) == 1 and '0' in keys and top_level:\n # Top-level of configuration dict\n key = keys[0]\n\n if not isinstance(config[key], dict):\n raise ValueError(f\"expected a dict but got {type(config[key])}\")\n return _parse(config[key], False)\n\n # Get positions of positional arguments\n args = []\n keys = sorted(keys)\n int_keys = list(filter(lambda x: x.isdecimal(), keys))\n\n # Construct positional arguments\n for k in int_keys:\n args.append(_parse(config[k], False))\n\n # Ensure only one form of positional argument was given\n if \"args\" in config.keys() and args:\n raise ValueError(\"args can only be specified in one form\")\n elif len(args) == 0 and \"args\" in config.keys():\n args = list(map(lambda x: _eval(x), config[\"args\"]))\n\n # Construct all kwargs\n kwargs = {}\n str_keys = filter(lambda x: not x.isdecimal(), keys)\n for k in str_keys:\n kwargs[k] = _parse(config[k], False)\n\n # Combine both methods of kwargs\n if \"kwargs\" in config.keys():\n for k in config[\"kwargs\"]:\n if k in kwargs:\n raise KeyError(f\"cannot have duplicate key {k})\")\n else:\n kwargs[k] = _eval(config[\"kwargs\"][k])\n\n # Construct the object\n constructor = _construct(config[\"type\"])\n return constructor(*args, **kwargs)\n\n\ndef _eval(expr):\n if isinstance(expr, str) and len(expr) > 2 and expr.startswith(\"<-\"):\n return eval(expr[2:])\n return expr\n\n\ndef set_at(config: dict, value, *positions):\n \"\"\"\n Set the argument in the call tree at position `*positions` to value.\n\n The index for the top level object needs never be specified. That is, if\n any index is specified, it is taken to index the arguments to the top level\n object, not the single top level object itself.\n\n Each consecutive value in `positions` refers to either an argument or\n keyword argument. If the value is an int, then it is taken to refer to a\n positional argument. If it is a string, then the value is taken to refer to\n a keyword argument. For example, if `positions = (0, \"y\", 3)`, then\n calling `set_at` with this `positions` would change the value of the third\n argument to the keyword argument `y` of the first argument of the\n top-level object. `positions` is just a simple indexing mechanism, similar\n to how lists and dicts are indexed.\n\n Parameters\n ----------\n config : dict\n The configuration dictionary to modify before parsing\n value : any\n The value to set\n *positions : int or str\n The position of the argument to set to `value`\n\n Returns\n -------\n dict\n The modified configuration dictionary\n\n Examples\n --------\n ```python\n >>> config = {\n '0': {\n 'type': 'env.mountain_car.MountainCar',\n 'args': [\"SEED\", 0.99],\n 'kwargs': {\n 'continuous_action': False,\n },\n },\n }\n >>> set_at(config, 1, 0)\n >>> set_at(config, True, \"continuous_action\")\n >>> config\n {\n '0': {\n 'type': 'env.mountain_car.MountainCar',\n 'args': [1, 0.99],\n 'kwargs': {\n 'continuous_action': True,\n },\n },\n }\n >>> set_at(config, \"what did I just do?\")\n >>> config\n {'0': \"what did I just do?\"}\n ```\n \"\"\"\n positions = [0] + list(positions)\n return _set_at(config, value, *positions)\n\n\ndef _set_at(config: dict, value, *positions):\n if len(positions) == 0:\n config[0] = value\n\n if isinstance(positions, tuple):\n position = positions[0]\n else:\n position = positions\n\n if len(positions) == 1:\n config[position] = value\n return config\n\n if isinstance(position, int):\n position = str(position)\n\n if isinstance(positions[1], int):\n if \"args\" in config[position]:\n _set_at(config[position][\"args\"], value, *positions[1:])\n else:\n _set_at(config[position], value, *positions[1:])\n else:\n if \"kwargs\" in config[position]:\n _set_at(config[position][\"kwargs\"], value, *positions[1:])\n else:\n _set_at(config[position], value, *positions[1:])\n","repo_name":"samuelfneumann/Construct-Py","sub_path":"construct_py/construct_py.py","file_name":"construct_py.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38773637081","text":"import operator as op\n\nimport magma as m\n\n# I am not making the read latency a generator param\n# as it is not parameter of Chisel provided by Gedeon\nREAD_LATENCY: int = 0\n\n\nclass SRAMBase(m.Generator2):\n # *args, **kwargs for inheritance reasons\n def __init__(\n self,\n addr_width: int,\n data_width: int,\n has_byte_enable: bool = False,\n *args,\n **kwargs,\n ):\n self._init_attrs(\n addr_width, data_width, has_byte_enable, *args, **kwargs\n )\n self._init_io()\n self._instance_subcomponents()\n self._connect()\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool, *args,\n **kwargs\n ):\n\n if addr_width <= 0:\n raise ValueError()\n\n if data_width <= 0:\n raise ValueError()\n\n if has_byte_enable:\n raise NotImplementedError('Byte Enable not currently supported')\n\n self.addr_width = addr_width\n self.data_width = data_width\n self.has_byte_enable = has_byte_enable\n\n def _init_io(self):\n T = m.Bits[self.data_width]\n\n self.io = m.IO(\n CEn=m.In(m.Enable),\n WDATA=m.In(T),\n WEn=m.In(m.Enable),\n RDATA=m.Out(T),\n REn=m.In(m.Enable),\n ) + m.ClockIO()\n\n if self.has_byte_enable:\n self.io += m.IO(WBEn=m.Bits[data_width / 8])\n\n def _instance_subcomponents(self):\n self.memory = m.Memory(\n 1 << self.addr_width,\n m.Bits[self.data_width],\n read_latency=READ_LATENCY,\n has_read_enable=False\n )()\n\n def _connect(self):\n pass\n\n def _read(self, addr):\n self.memory.RADDR @= addr\n return self.memory.RDATA\n\n def _write(self, addr, data):\n self.memory.WE @= self.we\n self.memory.WADDR @= addr\n self.memory.WDATA @= data\n\n @property\n def ce(self):\n return ~self.io.CEn\n\n @property\n def re(self):\n return self.ce & self.io.REn\n\n @property\n def we(self):\n return self.ce & self.io.WEn\n\n\nclass SRAMSingle(SRAMBase):\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(ADDR=m.In(m.Bits[self.addr_width]), )\n\n def _connect(self):\n super()._connect()\n self.io.RDATA @= self._read(self.io.ADDR)\n self._write(self.io.ADDR, self.io.WDATA)\n\n\nclass SRAMDouble(SRAMBase):\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n WADDR=m.In(m.Bits[self.addr_width]),\n RADDR=m.In(m.Bits[self.addr_width]),\n )\n\n def _connect(self):\n super()._connect()\n self.io.RDATA @= self._read(self.io.RADDR)\n self._write(self.io.WADDR, self.io.WDATA)\n\n\ndef _binary_to_unary(data: m.Bits):\n out_size = 1 << data.size\n return m.Bits[out_size](1) << data.zext(out_size - data.size)\n\n\ndef _tree_reduce(f, lst):\n n = len(lst)\n if n == 1:\n return lst[0]\n elif n == 2:\n return f(*lst)\n else:\n assert n >= 3\n return f(_tree_reduce(f, lst[:n // 2]), _tree_reduce(f, lst[n // 2:]))\n\n\ndef _build_mux_tree(lst):\n # Takes a list of (predicate, data)\n # returns a mux tree equivelent to:\n # if predicate[0]:\n # return data[0]\n # elif prdicate[1]:\n # return data[1]\n # ...\n # else:\n # return data[-1]\n n = len(lst)\n if n == 1:\n return lst[0][1]\n else:\n assert n >= 2\n top = lst[:n // 2]\n bot = lst[n // 2:]\n cond = _tree_reduce(op.or_, [pred for pred, _ in top])\n return cond.ite(_build_mux_tree(top), _build_mux_tree(bot))\n\n\nclass SRAMRedundancyMixin:\n def __init__(\n self,\n addr_width: int,\n data_width: int,\n has_byte_enable: bool = False,\n col_width: int = 4,\n num_r_cols: int = 1,\n debug: bool = False,\n *args,\n **kwargs,\n ):\n # All widths are number of bits\n # num_r_cols is number of redundancy columns\n super().__init__(\n addr_width, data_width, has_byte_enable, col_width, num_r_cols,\n debug, *args, **kwargs\n )\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool,\n col_width: int, num_r_cols: int, debug: bool, *args, **kwargs\n ):\n super()._init_attrs(\n addr_width, data_width, has_byte_enable, debug, *args, **kwargs\n )\n\n if col_width <= 0:\n raise ValueError()\n\n if data_width % col_width != 0:\n raise ValueError()\n\n if num_r_cols > data_width // col_width:\n raise ValueError(\"More redundancy than virtual columns\")\n\n self.col_width = col_width\n self.num_r_cols = num_r_cols\n self.debug = debug\n self.redundancy_addr_t = m.Bits[m.bitutils.clog2safe(self.num_v_cols)]\n\n @property\n def num_v_cols(self):\n # Number of virtual columns\n return self.data_width // self.col_width\n\n @property\n def num_p_cols(self):\n # Number of physical columns\n return self.num_v_cols + self.num_r_cols\n\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n RCE=m.In(m.Bits[self.num_r_cols]),\n **{\n f'RCF{i}A':\n m.In(self.redundancy_addr_t)\n for i in range(self.num_r_cols)\n }\n )\n\n def _instance_subcomponents(self):\n self.cols = [\n m.Memory(\n 1 << self.addr_width,\n m.Bits[self.col_width],\n read_latency=READ_LATENCY,\n has_read_enable=False,\n )() for _ in range(self.num_p_cols)\n ]\n\n mask_t = m.Bits[self.num_v_cols]\n zero = mask_t(0)\n RCFs = [\n self.io.RCE[i].ite(\n _binary_to_unary(getattr(self.io, f'RCF{i}A')), zero\n ) for i in range(self.num_r_cols)\n ]\n\n self.mask = _tree_reduce(mask_t.bvor, RCFs)\n\n def _read(self, addr):\n outputs = []\n # wire up all the read addresses and collect the outputs\n for mem in self.cols:\n mem.RADDR @= addr\n outputs.append(mem.RDATA)\n\n # The following function is meant to build this pattern:\n # shifts[k].ite(\n # outputs[i+k+1],\n # shifts[k-1].ite(\n # outputs[i+k],\n # shifts[k-2].ite(\n # ...,\n # shifts[0].ite(\n # outputs[i+1],\n # outputs[i]\n # )\n # )\n # )\n # )\n def build_ite(shifts, outputs, i):\n lst = [(True, outputs[i])]\n for idx, shift in enumerate(shifts):\n lst.append((shift, outputs[i + idx + 1]))\n lst.reverse()\n return _build_mux_tree(lst)\n\n shifts = [m.Bit(0) for _ in range(self.num_r_cols)]\n rdata = None\n\n for i in range(self.num_v_cols):\n prev = m.Bit(1)\n for idx in range(self.num_r_cols):\n shifts[idx] |= prev & self.mask[i]\n prev = shifts[idx]\n\n data = build_ite(shifts, outputs, i)\n\n if rdata is None:\n rdata = data\n else:\n rdata = rdata.concat(data)\n\n assert isinstance(rdata, m.Bits[self.data_width])\n return rdata\n\n def _write(self, addr, data):\n # break the inputs in chuncks\n inputs = [\n data[i * self.col_width:(i + 1) * self.col_width]\n for i in range(self.num_v_cols)\n ]\n\n assert all(isinstance(x, m.Bits[self.col_width]) for x in inputs)\n\n # The following function is meant to build this pattern:\n # if i == 0:\n # retun inputs[i]\n # elif i == 1:\n # return shifts[0].ite(inputs[i-1], inputs[i])\n # elif i < self.num_v_cols:\n # return shifts[1].ite(\n # inputs[i-2],\n # shifts[0].ite(inputs[i-1], inputs[i])\n # )\n # elif i == self.num_v_cols:\n # return shifts[1].ite(inputs[i-2], inputs[i-1])\n # else:\n # return inputs[i-2]\n #\n # Not sure how to generalize it with ... above is for num_r_cols = 2\n # But basically there are 3 cases,\n # i < num_r_cols:\n # we select from the first i chuncks. Use first shift bits.\n # i < num_v_cols:\n # The \"normal\" case where the ith column consumes one preceding\n # num_r_col+1 chunks. Use all the shift bits.\n # i >= num_v_cols:\n # The redundancy columns which must have a shift enabled to be\n # relevant hence we use last shift bits.\n def build_ite(shits, inputs, i):\n max_inputs = len(shifts) + 1\n if i < self.num_r_cols:\n offsets = [k for k in range(i + 1)]\n assert len(offsets) < max_inputs\n shift_offset = 0\n elif i < self.num_v_cols:\n offsets = [k for k in range(self.num_r_cols + 1)]\n assert len(offsets) == max_inputs\n shift_offset = 0\n else:\n offsets = [\n k for k in\n range(i - self.num_v_cols + 1, self.num_r_cols + 1)\n ]\n assert len(offsets) < max_inputs\n shift_offset = max_inputs - len(offsets)\n\n lst = [(True, inputs[i - offsets[0]])]\n for idx, offset in enumerate(offsets[1:]):\n lst.append((shifts[idx + shift_offset], inputs[i - offset]))\n\n lst.reverse()\n return _build_mux_tree(lst)\n\n shifts = [m.Bit(0) for _ in range(self.num_r_cols)]\n for i, mem in enumerate(self.cols):\n # broadcast the addr\n mem.WADDR @= addr\n if i < self.num_v_cols:\n prev = m.Bit(1)\n for idx in range(self.num_r_cols):\n shifts[idx] |= prev & self.mask[i]\n prev = shifts[idx]\n\n # this logic isn't strictly necessary\n if i < self.num_v_cols:\n # only enable normal cols if they aren't masked\n mem.WE @= self.we & ~self.mask[i]\n else:\n # only enable redundancy cols if they are used\n mem.WE @= self.we & shifts[i - self.num_v_cols]\n\n mem.WDATA @= build_ite(shifts, inputs, i)\n\n\nclass SRAMModalMixin:\n class State(m.Enum):\n Normal = 0\n Retention = 1\n TotalRetention = 2\n DeepSleep = 3\n\n def _init_attrs(\n self, addr_width: int, data_width: int, has_byte_enable: bool,\n debug: bool, *args, **kwargs\n ):\n super()._init_attrs(\n addr_width, data_width, has_byte_enable, debug, *args, **kwargs\n )\n\n self.debug = debug\n\n def _init_io(self):\n super()._init_io()\n self.io += m.IO(\n deep_sleep=m.In(m.Bit),\n power_gate=m.In(m.Bit),\n wake_ack=m.Out(m.Bit),\n )\n if self.debug:\n self.io += m.IO(current_state=m.Out(type(self).State))\n\n @property\n def _current_state(self):\n return type(self).State([self.io.deep_sleep, self.io.power_gate])\n\n @property\n def _in_normal(self):\n return self._current_state == type(self).State.Normal\n\n @property\n def ce(self):\n return super().ce & self._in_normal & self.boot_reg.O\n\n def _instance_subcomponents(self):\n super()._instance_subcomponents()\n self.Q_reg = m.Register(\n T=m.Bits[self.data_width],\n has_enable=True,\n )()\n self.boot_reg = m.Register(init=m.Bit(0), )()\n\n def _connect(self):\n super()._connect()\n # Not sure if this correct\n # boot reg blocks enable for a cycle after we enter normal mode\n self.io.wake_ack @= self._in_normal\n self.boot_reg.I @= self._in_normal\n\n if self.debug:\n self.io.current_state @= self._current_state\n\n def _read(self, addr):\n self.Q_reg.I @= super()._read(addr)\n self.Q_reg.CE @= self.re\n return self.Q_reg.O\n\n\nclass SRAMDM(SRAMModalMixin, SRAMDouble):\n pass\n\n\nclass SRAMSM(SRAMModalMixin, SRAMSingle):\n pass\n\n\nclass SRAMDR(SRAMRedundancyMixin, SRAMDouble):\n pass\n\n\nclass SRAMSR(SRAMRedundancyMixin, SRAMSingle):\n pass\n\n\nclass SRAMSMR(SRAMModalMixin, SRAMRedundancyMixin, SRAMSingle):\n pass\n\n\nclass SRAMDMR(SRAMModalMixin, SRAMRedundancyMixin, SRAMDouble):\n pass\n\n\n# Base -> Features -> Class\nSRAM_FEATURE_TABLE = {\n SRAMSingle: {\n frozenset(): SRAMSingle,\n frozenset((SRAMModalMixin, )): SRAMSM,\n frozenset((SRAMRedundancyMixin, )): SRAMSR,\n frozenset((\n SRAMModalMixin,\n SRAMRedundancyMixin,\n )): SRAMSMR,\n },\n SRAMDouble: {\n frozenset(): SRAMDouble,\n frozenset((SRAMModalMixin, )): SRAMDM,\n frozenset((SRAMRedundancyMixin, )): SRAMDR,\n frozenset((\n SRAMModalMixin,\n SRAMRedundancyMixin,\n )): SRAMDMR,\n },\n}\n\n\n","repo_name":"leonardt/smart-components","sub_path":"onyx/onyx_sram_subsystem/mock_mem.py","file_name":"mock_mem.py","file_ext":"py","file_size_in_byte":13329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12566922709","text":"from curses import longname\n\n\ndef lengthOfLongestSubstring(s: str) -> int:\n if s == '': return 0\n c_map = {} # Keep the last index of characters\n p = -1 # pointer to index we start to count from\n max_length = 0\n for i in range(len(s)):\n c = s[i]\n # if c is in the current substring\n if c in c_map and p < c_map[c]:\n # update the pointer\n p = c_map[c]\n else:\n # else, update the max length\n max_length = i - p if max_length < i-p else max_length\n # update the last index of c\n c_map[c] = i\n \n return max_length\n\nprint(lengthOfLongestSubstring('pwwkew'))","repo_name":"eladsadeh/code-challenges","sub_path":"python/longest_substring.py","file_name":"longest_substring.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"4382853172","text":"import time\nimport multiprocessing as mp\nimport queue\n\n# 读队列\ndef read_queue(q):\n while True:\n try:\n rd = q.get(timeout=2)\n print(rd)\n except queue.Empty as e:\n print(\"all done:%s\" % e)\n break\n\n\ndef write_queue(q):\n for i in range(5):\n q.put(time.ctime())\n time.sleep(1)\n\nif __name__ == '__main__':\n # 创建队列\n queue = mp.Queue()\n\n # 创建两个用于读写队列的进程\n p1 = mp.Process(target=write_queue, args=(queue,))\n p2 = mp.Process(target=read_queue, args=(queue,))\n\n p1.start()\n p2.start()\n\n p1.join()\n p2.join()\n","repo_name":"zhangzongyan/python0702","sub_path":"part2_高级编程/day01/code_01/04-进程间通信_消息队列.py","file_name":"04-进程间通信_消息队列.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"}
+{"seq_id":"7914866206","text":"# -*- coding: utf-8 -*-\n\"\"\"Installer for the oli.areadme package.\"\"\"\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nlong_description = (\n open('README.rst').read()\n + '\\n' +\n 'Contributors\\n'\n '============\\n'\n + '\\n' +\n open('CONTRIBUTORS.rst').read()\n + '\\n' +\n open('CHANGES.rst').read()\n + '\\n')\n\n\nsetup(\n name='oli.areadme',\n version='0.1',\n description=\"A simple README add-on\",\n long_description=long_description,\n # Get more from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Environment :: Web Environment\",\n \"Framework :: Plone\",\n \"Framework :: Plone :: 5.0\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.7\",\n \"Operating System :: OS Independent\",\n \"License :: OSI Approved :: GNU General Public License v2 (GPLv2)\",\n ],\n keywords='Python Plone',\n author='Olimpiu Rob',\n author_email='olimpiu.rob@gmail.com',\n url='http://pypi.python.org/pypi/oli.areadme',\n license='GPL version 2',\n packages=find_packages('src', exclude=['ez_setup']),\n namespace_packages=['oli'],\n package_dir={'': 'src'},\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'plone.api',\n 'setuptools',\n 'z3c.jbot',\n 'plone.app.dexterity'\n ],\n extras_require={\n 'test': [\n 'plone.app.testing',\n 'plone.app.contenttypes',\n 'plone.app.robotframework[debug]',\n ],\n },\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n)\n","repo_name":"olimpiurob/oli.areadme","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"17554293085","text":"import random , operator\n\ndef random_operator() :\n operators = {\n \"+\" : operator.add,\n \"-\" : operator.sub,\n \"*\" : operator.mul,\n \"//\" : operator.truediv\n }\n\n first_number = random.randint(1,100)\n second_number = random.randint(1,100)\n operator_chosen = random.choice(list(operators.keys()))\n\n result = operators.get(operator_chosen)(first_number,second_number)\n print(f\"{first_number} {operator_chosen} {second_number}\")\n return result\n\ndef ask_question () :\n result = random_operator()\n answer = float(input(\"please enter your answer : \"))\n return result == answer\n\nscore = 0\nwhile True:\n if ask_question():\n score += 1\n print('True')\n else:\n print('false')\n break\nprint(\"Game Over!!!\")\nprint(f\"your score : {score}\")","repo_name":"MsA081/simple_project","sub_path":"mathGame/mathGame.py","file_name":"mathGame.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"13083028888","text":"max = int(input())\n\nhappy_num = []\n\nfor i in range(1, max+1):\n temp_list = []\n temp = i\n\n while(True):\n if temp == 1: # 계속 계산하다 1이될 경우\n happy_num.append(i)\n break\n\n if temp in temp_list: # 예전에 계산한 수를 발견한 경우\n break;\n\n temp_list.append(temp)\n\n if temp >= 1000: # 4자리 이상의 수\n a = int(temp / 1000)\n b = int((temp % 1000) / 100)\n c = int((temp % 100) / 10)\n d = int(temp % 10)\n temp = a ** 2 + b ** 2 + c ** 2 + d ** 2\n\n elif temp >= 100: # 3자리수\n a = int((temp % 1000) / 100)\n b = int((temp % 100) / 10)\n c = int(temp % 10)\n temp = a ** 2 + b ** 2 + c ** 2\n\n elif temp >= 10: # 2자리수\n a = int((temp % 100) / 10)\n b = int(temp % 10)\n temp = a ** 2 + b ** 2\n\n else:\n temp = temp ** 2\n\nprint(\"1 ~ \" + str(max) + \"범위의 행복 수는 \" + str(len(happy_num)) + \"개이고 총합은 \" + str(sum(happy_num)) + \"입니다.\")","repo_name":"SangCheonP/CodingTest","sub_path":"사이냅 퀴즈/퀴즈 1.py","file_name":"퀴즈 1.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34063148484","text":"print(\"--당첨자 발표--\")\r\nfrom random import *\r\nlst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]\r\nshuffle(lst) \r\nlst_1 = sample(lst, 4)\r\nprint(\"치킨 당첨자 : \", lst_1[0])\r\nprint(\"커피 당첨자 : \", lst_1[1:])\r\nprint(\"--축하합니다---\")\r\n\r\n#from random import *\r\n#users = range(1, 21)\r\n#users = list(users)\r\n#shuffle(users)\r\n#winners = sample(users, 4)\r\n#print(\" -- 당첨자 발표 -- \")\r\n#print(\"치킨 당첨자 : {0}\".format(winners[0]))\r\n#print(\"커피 당첨자 : {0}\".format(winners[1:]))\r\n#print(\" -- 축하합니다 -- \")\r\n\r\nfrom random import *\r\ncustomers = range(1, 51)\r\ncustomers = list(customers)\r\ntime_customers = range(1, 51)\r\ntime_customers = list(time_customers)\r\ni = 0\r\nnum = 0\r\nfor customers[i] in range(1, 51):\r\n time_customers[i] = randint(5, 50)\r\n if 5 <= time_customers[i] <= 15:\r\n print(\"[o] {0}번째 손님 (소요시간 : {1}분)\".format(i + 1, time_customers[i]))\r\n num += 1\r\n else:\r\n print(\"[ ] {0}번째 손님 (소요시간 : {1}분)\".format(i + 1, time_customers[i]))\r\n i += 1\r\nprint(\"\")\r\nprint(\"총 탑승 승객 : {0}분\".format(num))\r\n\r\n#from random import *\r\n#cnt = 0\r\n#for i in range(1, 51):\r\n# time = randrange(5, 51)\r\n# if 5 <= time <= 15:\r\n# print(\"[0] {0}번째 손님 (소요시간 : {1}분)\".format(i, time))\r\n# cnt += 1\r\n# else:\r\n# print(\"[ ] {0}번째 손님 (소요시간 : {1}분)\".format(i, time))\r\n#print(\"총 탑승 승객 : {0} 분\".format(cnt)) \r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"SuYoung888/PythonNewbie","sub_path":"3주차 과제.py","file_name":"3주차 과제.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27811886987","text":"\nfrom hadooplib.mapper import MapperBase\n\nclass WordCountMapper(MapperBase):\n \"\"\"\n count the occurences of each word\n \"\"\"\n\n def map(self, key, value):\n \"\"\"\n for each word in input, output a (word, 1) pair\n\n @param key: None, no use\n @param value: line from input\n \"\"\"\n words = value.split()\n for word in words:\n self.outputcollector.collect(word, 1)\n\nif __name__ == \"__main__\":\n WordCountMapper().call_map()\n","repo_name":"nltk/nltk_contrib","sub_path":"nltk_contrib/hadoop/word_count/wordcount_mapper.py","file_name":"wordcount_mapper.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"52"}
+{"seq_id":"71241466085","text":"import pandas as pd\r\nimport numpy as np\r\n\r\n#! Reindex Dataset Before Normalizing\r\ndef df_reindex(df):\r\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\r\n df.dropna(inplace=True)\r\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\r\n df = df[indices_to_keep]\r\n print(\"DataSet Reindexed...\")\r\n df.info()\r\n return df\r\ndf = df_reindex(df)\r\n\r\n#! Normalize the Data\r\ndef df_normalize(df):\r\n from sklearn.preprocessing import Normalizer\r\n normalizer = Normalizer(norm='l2')\r\n df = pd.DataFrame(normalizer.fit_transform(df),columns=df.columns)\r\n print(\"DataSet Normalized...\")\r\n df.head()\r\n return df\r\ndf = df_normalize(df)\r\n\r\n#! StandardScale the Data\r\ndef df_stdscale(df):\r\n from sklearn.preprocessing import StandardScaler\r\n std_scaler = StandardScaler()\r\n df = pd.DataFrame(std_scaler.fit_transform(df),columns=df.columns)\r\n print(\"DataSet StdScaled...\")\r\n df.head()\r\n return df\r\ndf = df_stdscale(df)\r\n\r\n#! MinMaxScale the Data\r\ndef df_minmaxscale(df):\r\n from sklearn.preprocessing import MinMaxScaler\r\n minmax_scaler = MinMaxScaler()\r\n df = pd.DataFrame(minmax_scaler.fit_transform(df),columns=df.columns)\r\n print(\"DataSet MinMaxScaled...\")\r\n df.head()\r\n return df\r\ndf = df_minmaxscale(df)\r\n\r\n#! RobustScale the Data\r\ndef df_robustscale(df):\r\n from sklearn.preprocessing import RobustScaler\r\n robust_scaler = RobustScaler().fit(df)\r\n df = pd.DataFrame(robust_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet RobustScaled...\")\r\n df.head()\r\n return df\r\ndf = df_robustscale(df)\r\n\r\n#! MaxAbsScale the Data\r\ndef df_maxabsscale(df):\r\n from sklearn.preprocessing import MaxAbsScaler\r\n maxabs_scaler = MaxAbsScaler().fit(df)\r\n df = pd.DataFrame(maxabs_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet MaxAbsScaled...\")\r\n df.head()\r\n return df\r\ndf = df_maxabsscale(df)\r\n\r\n#! QuantileScale the Data\r\ndef df_quantile_scale(df):\r\n from sklearn.preprocessing import QuantileTransformer\r\n quantile_scaler = QuantileTransformer().fit(df)\r\n df = pd.DataFrame(quantile_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet QuantileScaled...\")\r\n df.head()\r\n return df\r\ndf = df_quantile_scale(df)\r\n\r\n#! Power Transform the Data\r\ndef df_power_transformer(df):\r\n from sklearn.preprocessing import PowerTransformer\r\n power_transform_scaler = PowerTransformer().fit(df)\r\n df = pd.DataFrame(power_transform_scaler.transform(df),columns=df.columns)\r\n print(\"DataSet QuantileScaled...\")\r\n df.head()\r\n return df\r\ndf = df_power_transformer(df)\r\n\r\n\r\n","repo_name":"yctasoglu/Scaling","sub_path":"Scaling/Scaling_and_transforming.py","file_name":"Scaling_and_transforming.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"46563260976","text":"###############################################################################\n#\n# $Id: example3.py 718 2012-04-15 23:59:35Z weegreenblobbie $\n#\n# Simulates a drum. Based on the Csound drum by Hans Mikelson.\n#\n# source: http://www.csounds.com/ezine/winter2001/synthesis/\n#\n###############################################################################\n\nfrom nsound import *\n\nsr = 44100.0\nBITS_PER_SAMPLE = 16\n\n###############################################################################\ndef drum(\n duration,\n attack_time,\n high_frequency,\n low_frequency,\n tension,\n resident_frequency):\n \"Simple drum\"\n\n sin = Sine(sr)\n\n frequency_sweep = sin.drawLine(attack_time, high_frequency, low_frequency)\n\n frequency_sweep << sin.drawLine(\n (duration - attack_time), low_frequency, low_frequency)\n\n hz_20 = sin.generate(duration, resident_frequency)\n\n rezzy = hz_20 * frequency_sweep\n\n parabola = sin.drawParabola(duration, 1.0, duration / 2, 0.25, 0.0)\n\n rezzy *= parabola\n\n temp1 = rezzy * tension\n\n frequency_sweep -= temp1\n\n audio = sin.generate(duration, frequency_sweep)\n\n audio *= sin.drawParabola(duration,1.0, 0.5 * duration, 0.3,0.0);\n\n return audio\n\n###############################################################################\n\nsine = Sine(sr)\n\nbd01 = DrumBD01(sr)\ndkb = DrumKickBass(sr, 266, 0.0)\n\nout = AudioStream(sr, 1);\n\nout << bd01.play() \\\n << sine.silence(0.25) \\\n << dkb.play() \\\n << sine.silence(0.25)\n\n# duration, attack, high f, low f, tension, ressonance\nout << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << drum(0.5, 0.012, 160, 51, 0.9, 54) \\\n << sine.silence(0.25)\n\nout *= 0.5\n\nhat = Hat(sr)\n\nout << 0.666 * hat.play() << sine.silence(0.25)\n\nout >> \"example3.wav\"\n\n# ReverberationRoom(sample_rate, room_feedback, wet_percent, dry_percent, low_pass_freq)\nroom = ReverberationRoom(sr, 0.60, 0.5, 1.0, 100.0)\n\nout2 = 0.5 * room.filter(out)\n\nout2 >> \"example3_reverb.wav\"\n\npb = AudioPlayback(sr, 2, 16);\n\nout2 >> pb\n","repo_name":"DevDungeon/Cookbook","sub_path":"python/nsound_examples/drum.py","file_name":"drum.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"52"}
+{"seq_id":"25035704861","text":"from configparser import Error\nfrom klase.metode import dodaj_u_serijsku, sastavi_sekvencijalnu\nfrom .genericka_klasa import GenerickaKlasa\nfrom PySide2.QtCore import QModelIndex\nfrom PySide2 import QtWidgets, QtGui, QtCore\nfrom pydoc import locate\nimport csv\nimport mysql\nimport os\n\nclass PrikazElementa(QtWidgets.QDialog): # izmena, dodaj, pretrazi\n def __init__(self, parent, pretraga=False, element=None):\n super(PrikazElementa,self).__init__(parent)\n meta_podaci = parent.meta_podaci #kada kliknemo saljemo meta podatke u prikaz\n self.lista_atributa = meta_podaci[5].split(\",\")\n self.lista_naziva_atributa = meta_podaci[5].split(\",\")\n self.lista_tipovi_atributa = meta_podaci[6].split(\",\")\n self.lista_duzine_atributa = meta_podaci[7].split(\",\")\n self.lista_obaveznosti_atributa = meta_podaci[8].split(\",\")\n self.lista_kljuceva = meta_podaci[11].split(\",\")\n self.tip_datoteke = meta_podaci[1]\n self.relativna_putanja = meta_podaci[2]\n self.sufiks = meta_podaci[3]\n self.putanja_podaci = meta_podaci[4]\n self.lista = []\n self.primarni_kljucevi=[]\n if self.tip_datoteke == \"sekvencijalna\":\n self.roditelji = meta_podaci[12].split(\",\")\n self.broj_kljuceva = meta_podaci[13].split(\",\")\n self.pozicije_u_formi = meta_podaci[14].split(\",\")\n self.pozicije_u_datoteci = meta_podaci[15].split(\",\")\n \n \n \n self.putanja_kljucevi =\"podaci/podaci/sekvencijalne/\"\n self.pretraga = pretraga\n self.privremena_datoteka = \"podaci/podaci/privremena_ser.csv\"\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n self.setWindowIcon(icon)\n self.layout = QtWidgets.QGridLayout()\n \n \n \n \n self.setWindowFlags(self.windowFlags()\n ^ QtCore.Qt.WindowContextHelpButtonHint)\n self.tip = 0 # tip == 0 -dodavanje / tip == 1 -izmena / tip == 2 -pretraga\n \n if element != None:\n self.dugme = QtWidgets.QPushButton(\"Izmena\")\n self.setWindowTitle(\"Izmena\")\n self.tip = 1\n elif element == None and not pretraga:\n self.dugme = QtWidgets.QPushButton(\"Dodavanje\")\n self.setWindowTitle(\"Dodavanje\")\n self.tip = 0\n else:\n self.dugme = QtWidgets.QPushButton(\"Pretraga\")\n self.setWindowTitle(\"Pretraga\")\n self.tip = 2\n \n self.zatvori = QtWidgets.QPushButton(\"Zatvaranje\")\n self.lista_atr = [] # ovu listu koristim za pretragu, dodaju se samo\n # atributi cija input polja nisu prazna, i onda znam po kojim atributima\n # da vrsim pretragu\n self.lista_kriterijuma = [] # lista kriterijuma, isto kao lista gore sto\n # cuva nazive atributa, ova lista cuva vrednosti tih atributa\n self.lista_vece_manje = []\n m=0\n self.blocked = False\n for i in range(len(self.lista_atributa)):\n naziv = self.lista_atributa[i][0].upper()\n\n for s in range(1, len(self.lista_atributa[i])):\n if self.lista_atributa[i][s] == \"_\":\n naziv += \" \"\n else:\n naziv += self.lista_atributa[i][s]\n \n ime = QtWidgets.QLabel(naziv + \" :\")\n self.layout.addWidget(ime,m,0)\n self.__setattr__(self.lista_atributa[i], QtWidgets.QLineEdit())\n\n if self.tip == 2:\n self.__setattr__(self.lista_atributa[i]+\"_vece_manje\", QtWidgets.QComboBox())\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"jednako\")\n if self.lista_tipovi_atributa[i] != \"str\":\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"manje od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"manje ili jednako od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"vece od\")\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").addItem(\"vece ili jednako od\")\n\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").setCurrentIndex(0)\n self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").setEditable(False)\n\n if element == None and not pretraga:\n self.__getattribute__(self.lista_atributa[i]).setPlaceholderText(\"Do \" + self.lista_duzine_atributa[i] + \" karaktera\")\n self.__getattribute__(self.lista_atributa[i]).setMaxLength(int(self.lista_duzine_atributa[i]))\n if \"datum\" in self.lista_naziva_atributa[i].lower():\n self.__getattribute__(self.lista_atributa[i]).setPlaceholderText(\"YYYY-MM-DD\")\n \n elif element != None:\n self.element = element\n \n self.__getattribute__(self.lista_atributa[i]).setText(element.__getattribute__(self.lista_atributa[i]))\n self.__getattribute__(self.lista_atributa[i]).setMaxLength(int(self.lista_duzine_atributa[i]))\n \n \n veze = self.parent().meta_podaci[9].split(\",\")\n for j in range(len(veze)):\n if hasattr(self.parent(), \"sub_table\"+str(j+1)):\n if len(self.parent().__getattribute__(\"sub_table\"+str(j+1)).model.lista_prikaz) != 0:\n for k in range(len(self.lista_kljuceva)):\n if k <= i:\n if self.__getattribute__(self.lista_kljuceva[k]).isEnabled():\n self.__getattribute__(self.lista_kljuceva[k]).setDisabled(True)\n self.blocked = True\n \n self.__getattribute__(self.lista_atributa[i]).setFixedHeight(27)\n self.layout.addWidget(self.__getattribute__(self.lista_atributa[i]),m,1)\n \n if self.tip == 2:\n self.layout.addWidget(self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\"),m,2)\n m+=1\n self.layout.addWidget(self.dugme,m+1,0,1,3)\n self.layout.addWidget(self.zatvori,m+2,0,3,3)\n self.setLayout(self.layout)\n self.dugme.clicked.connect(self.dugme_kliknuto)\n self.zatvori.clicked.connect(self.zatvori_prikaz)\n \n if self.tip == 1:\n self.original_elem = GenerickaKlasa([],[])\n self.element = element\n for i in range(len(self.lista_atributa)):\n self.original_elem.__setattr__(self.lista_atributa[i], self.element.__getattribute__(self.lista_atributa[i]))\n else:\n self.element = GenerickaKlasa([],[])\n \n self.setMinimumWidth(500)\n self.show()\n \n \n def ucitaj_kljuceve(self,putanja, pozicija_kljuca):\n kljucevi = open(putanja,\"r\",encoding=\"utf-8\")\n next(csv.reader(kljucevi,delimiter=\",\"))\n self.primarni_kljucevi=[i.split(',')[pozicija_kljuca] for i in kljucevi.readlines()]\n return self.primarni_kljucevi\n \n def poredjenje(self, lista, vrijednost):\n brojac = 0\n for i in range(len(lista)):\n \n if lista[i] == vrijednost:\n brojac +=1\n\n if brojac > 0:\n return True\n else:\n return False \n\n def sacuvaj_podatke(self):\n if os.path.exists(self.privremena_datoteka):\n if self.tip_datoteke == \"sekvencijalna\":\n top = QModelIndex()\n top.child(0,0)\n self.parent().table.model().beginRemoveRows(top, 0, 0)\n if sastavi_sekvencijalnu(self):\n if os.path.exists(self.privremena_datoteka):\n os.remove(self.privremena_datoteka)\n else:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Privremena datoteka ne postoji!\")\n poruka.exec_()\n \n self.parent().table.model().endRemoveRows()\n \n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n self.parent().table.model().endInsertRows()\n\n def zatvori_prikaz(self):\n self.close()\n\n def closeEvent(self, event):\n self.sacuvaj_podatke()\n event.accept()\n \n\n def dugme_kliknuto(self):\n try:\n for i in range(len(self.lista_atributa)):\n vrijednost = self.__getattribute__(self.lista_atributa[i]).text()\n \n if self.tip_datoteke == \"sekvencijalna\":\n brojac =0\n if self.broj_kljuceva != ['']:\n for o in range(len(self.broj_kljuceva)):\n if self.broj_kljuceva != ['']:\n \n for k in range(int(self.broj_kljuceva[o])):\n self.ucitaj_kljuceve(self.putanja_kljucevi + self.roditelji[o],int(self.pozicije_u_datoteci[brojac]))\n vrijed = self.__getattribute__(self.lista_atributa[int(self.pozicije_u_formi[brojac])]).text()\n brojac +=1\n \n if self.poredjenje(self.primarni_kljucevi,vrijed) == False: \n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\" Jedno polje sadrzi kljuc koji ne postoji u roditeljskoj klasi! Pokusajte ponovo!\")\n poruka.exec_()\n return\n else:\n continue\n \n \n \n\n if self.tip == 2:\n if len(vrijednost.strip()) == 0:\n continue\n\n if len(vrijednost) <= int(self.lista_duzine_atributa[i]):\n if bool(self.lista_obaveznosti_atributa[i]) == True and self.tip != 2:\n if vrijednost == \"\":\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje ne sme biti prazno! Pokusajte ponovo!\")\n poruka.exec_()\n return\n \n try:\n if isinstance(locate(self.lista_tipovi_atributa[i])(vrijednost), locate(self.lista_tipovi_atributa[i])) == False:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje pogresna vrednost! Pokusajte ponovo!\")\n poruka.exec_()\n return\n except ValueError:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize()+\" polje pogresna vrednost! Pokusajte ponovo!\")\n poruka.exec_()\n return\n\n self.element.__setattr__(self.lista_atributa[i], vrijednost)\n self.lista_atr.append(self.lista_atributa[i])\n self.lista_kriterijuma.append(vrijednost)\n if self.tip == 2:\n self.lista_vece_manje.append(self.__getattribute__(self.lista_atributa[i]+\"_vece_manje\").currentIndex())\n else:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(str(self.lista_atributa[i]).capitalize() + \". Prekoracili ste duzinu karaktera!\")\n poruka.exec_()\n return\n \n if self.tip == 1:\n if not self.parent().is_baza:\n with open(self.putanja_podaci, 'r',newline='') as csvfile:\n spamreader = csv.reader(csvfile, delimiter = \"\\n\")\n counter = 0\n prva_linija = True\n lista = []\n for row in spamreader:\n if prva_linija:\n prva_linija = False\n continue\n if row[0] == \"\":\n break\n \n objekat = GenerickaKlasa(self.lista_atributa, row[0].split(\",\"))\n nadjen = True\n \n self.parent().table.model().lista_prikaz = []\n for i in range(len(self.lista_atributa)):\n if objekat.__getattribute__(self.lista_atributa[i]) != self.original_elem.__getattribute__(self.lista_atributa[i]):\n nadjen = False\n if not nadjen:\n lista.append(objekat)\n else:\n for i in range(len(self.lista_atributa)):\n objekat.__setattr__(self.lista_atributa[i], self.element.__getattribute__(self.lista_atributa[i]))\n\n lista.append(objekat)\n \n counter += 1\n \n self.parent().table.model().lista_prikaz = lista\n\n with open(self.putanja_podaci, 'w', newline='') as f:\n writer = csv.writer(f, delimiter = \",\")\n writer.writerow([self.parent().putanja_meta])\n for i in range(len(self.parent().table.model().lista_prikaz)):\n tekst = \"\"\n for j in range(len(self.lista_atributa)):\n tekst += str(self.parent().table.model().lista_prikaz[i].__getattribute__(self.lista_atributa[j]))\n if j < len(self.lista_atributa)-1:\n tekst += \",\"\n \n novi_red = tekst.split(\",\")\n writer.writerow(novi_red)\n else:\n parent = self.parent().pocetna_strana\n \n query = \"UPDATE \" + self.parent().naziv + \" SET \"\n block = False\n for i in range(len(self.lista_atributa)):\n block = False\n if self.blocked:\n for j in self.lista_kljuceva:\n if self.lista_atributa[i] == j:\n block = True\n break\n if block:\n continue\n query += self.lista_atributa[i] + \"=\"\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n query += self.element.__getattribute__(self.lista_atributa[i])\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n if i < len(self.lista_atributa) - 1:\n query += \" , \"\n \n if len(self.lista_atributa) == len(self.lista_kljuceva) and self.blocked:\n return\n \n query += \" WHERE \"\n for i in range(len(self.lista_kljuceva)):\n query += self.lista_kljuceva[i] + \"=\"\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n query += self.original_elem.__getattribute__(self.lista_kljuceva[i])\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"\n\n if i < len(self.lista_kljuceva) - 1:\n query += \" AND \"\n try:\n parent.csor.execute(query)\n except mysql.connector.errors.IntegrityError as e:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Vec postoji element sa zadatim kljucem!\\n\"+e.msg)\n poruka.exec_()\n\n parent.connection.commit()\n\n query = \"SELECT * FROM \" + self.parent().naziv\n parent.csor.execute(query)\n \n self.parent().table.model().lista_prikaz = []\n for result in parent.csor.fetchall():\n lista_podataka = []\n for i in result:\n lista_podataka.append(str(i))\n \n self.parent().table.model().lista_prikaz.append(GenerickaKlasa(self.lista_atributa, lista_podataka))\n\n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n\n elif self.tip == 0:\n if self.tip_datoteke == \"sql\":\n parent = self.parent().pocetna_strana\n \n query = \"INSERT INTO \" + self.parent().naziv +\" (\" \n brojac =0\n for i in range(len(self.lista_atributa)):\n query += self.lista_atributa[i]\n if brojac < len(self.lista_atributa)-1:\n query += \", \"\n brojac += 1\n query += \") \" + \"VALUES (\"\n brojac2=0\n for i in range(len(self.lista_atributa)):\n if self.lista_tipovi_atributa[i] == \"str\":\n query += \"'\"+self.__getattribute__(self.lista_atributa[i]).text()+\"'\"\n else:\n query += self.__getattribute__(self.lista_atributa[i]).text()\n if brojac2 < len(self.lista_atributa)-1:\n query += \", \"\n brojac2 += 1\n query += \")\"\n \n provjeri = True\n try:\n parent.csor.execute(query)\n except mysql.connector.errors.IntegrityError as e:\n poruka = QtWidgets.QMessageBox()\n provjeri=False\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Vec postoji element sa zadatim kljucem!\\n\"+e.msg)\n poruka.exec_()\n \n except mysql.connector.errors.DataError as e:\n poruka = QtWidgets.QMessageBox()\n provjeri=False\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Uneli ste pogresnu vrednost!\\n\"+e.msg)\n poruka.exec_()\n\n\n parent.connection.commit()\n query = \"SELECT * FROM \" + self.parent().naziv\n parent.csor.execute(query)\n self.parent().table.model().lista_prikaz = []\n for result in parent.csor.fetchall():\n lista_podataka = []\n for i in result:\n lista_podataka.append(str(i))\n \n self.parent().table.model().lista_prikaz.append(GenerickaKlasa(self.lista_atributa, lista_podataka))\n \n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom)\n if provjeri:\n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n model = self.parent().table.model()\n model.lista_prikaz.append(self.element)\n self.parent().table.setModel(model)\n self.parent().table.model().endInsertRows()\n\n \n if self.tip_datoteke == \"serijska\":\n dodaj_u_serijsku(self.element, self.lista_atributa, self.putanja_podaci, self.parent().putanja)\n self.parent().table.model().beginInsertRows(QModelIndex(), 0, 0)\n model = self.parent().table.model()\n model.lista_prikaz.append(self.element)\n self.parent().table.setModel(model)\n self.parent().table.model().endInsertRows()\n\n elif self.tip_datoteke == \"sekvencijalna\":\n dodaj_u_serijsku(self.element, self.lista_atributa, self.privremena_datoteka, self.parent().putanja)\n \n top = QModelIndex()\n top.child(0,0)\n bottom = QModelIndex()\n bottom.child(len(self.parent().table.model().lista_prikaz), self.parent().table.model().broj_kolona)\n self.parent().table.dataChanged(top, bottom) \n \n elif self.tip == 2:\n self.close()\n \n except ValueError:\n poruka = QtWidgets.QMessageBox()\n icon = QtGui.QIcon(\"src/ikonice/logo.jpg\")\n poruka.setWindowIcon(icon)\n poruka.setWindowTitle(\"Upozorenje!\")\n poruka.setText(\"Pogresna vrednost!\")\n poruka.exec_()\n return \n ","repo_name":"mr2853/rukovalac-informacionim-resursima","sub_path":"src/klase/prikaz_elementa.py","file_name":"prikaz_elementa.py","file_ext":"py","file_size_in_byte":24090,"program_lang":"python","lang":"sh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34386989609","text":"import mysql.connector\n\nconectado = False\n\n# Conecta no banco\ndef conecta_banco():\n\n banco = input('Digite o nome do banco: ')\n usuario = input('Digite o nome do usuário do banco: ')\n senha = input('Digite a senha do usuário do banco: ')\n\n db_projeto = mysql.connector.connect(\n host=\"localhost\",\n user=usuario,\n password=senha,\n # database = banco #Se o banco já existir pode ser usado para conectar direto\n)\n global conectado\n conectado = True\n db_cursor = db_projeto.cursor()\n print(f'\\nBanco {banco} conectado.')\n return db_projeto, db_cursor, banco\n\n\n# Cria a conexão e já conecta no banco selecionado\ndef cria_banco():\n\n # Criei uma função só p conectar\n # db_projeto = mysql.connector.connect(\n # host=\"localhost\",\n # user=usuario,\n # password=senha,\n # # database = banco #Se o banco já existir pode ser usado para conectar direto\n # )\n \n db_projeto, db_cursor, banco = conecta_banco()\n db_cursor = db_projeto.cursor()\n db_cursor.execute(f\"CREATE DATABASE {banco}\")\n print(f\"\\nO banco {banco} foi criado com sucesso.\")\n \n # Tenativa de tratamento de erro. Se der tempo volto aqui p acertar\n # db_cursor.execute(\"SHOW DATABASES\")\n # for x in db_cursor:\n # print(x)\n # if banco in x:\n # print(f\"Já existe um banco com o nome {banco}. Por favor selecione outro nome.\")\n # else: \n # # db_cursor.execute(f\"CREATE DATABASE {banco}\")\n # print(f\"O banco {banco} foi criado com sucesso.\")\n\n return db_projeto, db_cursor\n\n\n# Criar as tabelas\ndef cria_tabelas(db_projeto, db_cursor):\n db_cursor.execute(f\"USE {db_projeto}\") # seta o banco\n\n # Cria as tabelas\n db_cursor.execute(\"CREATE TABLE Aluno (CPF VARCHAR(15) NOT NULL, Nome VARCHAR(100) NOT NULL, Endereco VARCHAR(255) NOT NULL, Telefone VARCHAR(30) NOT NULL, Data_Nasc DATE, PRIMARY KEY (CPF))\")\n db_cursor.execute(\"CREATE TABLE Departamento (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(255), PRIMARY KEY (Codigo))\")\n db_cursor.execute(\"CREATE TABLE Curso (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(100) NOT NULL, Descricao VARCHAR(255), Codigo_Depto INT NOT NULL, PRIMARY KEY (Codigo), FOREIGN KEY (Codigo_Depto) REFERENCES Departamento(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Matricula (Codigo_Curso INT NOT NULL, CPF_Aluno VARCHAR(15) NOT NULL, Data_Matricula DATE, PRIMARY KEY (Codigo_Curso, CPF_Aluno), FOREIGN KEY (Codigo_Curso) REFERENCES Curso(Codigo), FOREIGN KEY (CPF_Aluno) REFERENCES Aluno(CPF))\")\n db_cursor.execute(\"CREATE TABLE Professor (Matricula INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(100), Endereco VARCHAR(255), Telefone VARCHAR(30), Data_Nasc DATE, Codigo_Depto INT, Data_Contratacao DATE, PRIMARY KEY (Matricula), FOREIGN KEY (Codigo_Depto) REFERENCES Departamento(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Disciplina (Codigo INT NOT NULL AUTO_INCREMENT, Nome VARCHAR(50) NOT NULL, Qtde_Creditos INT NOT NULL, Matricula_Prof INT, PRIMARY KEY (Codigo), FOREIGN KEY (Matricula_Prof) REFERENCES Professor(Matricula))\")\n db_cursor.execute(\"CREATE TABLE Cursa (CPF_Aluno VARCHAR(15) NOT NULL, Codigo_Disc INT NOT NULL, PRIMARY KEY (CPF_Aluno, Codigo_Disc), FOREIGN KEY (CPF_Aluno) REFERENCES Aluno(CPF), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Compoe (Codigo_Curso INT NOT NULL, Codigo_Disc INT NOT NULL, PRIMARY KEY (Codigo_Curso, Codigo_Disc), FOREIGN KEY (Codigo_Curso) REFERENCES Curso(Codigo), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo))\")\n db_cursor.execute(\"CREATE TABLE Pre_Req (Codigo_Disc INT NOT NULL, Codigo_Disc_Dependencia INT NOT NULL, PRIMARY KEY (Codigo_Disc, Codigo_Disc_Dependencia), FOREIGN KEY (Codigo_Disc) REFERENCES Disciplina(Codigo), FOREIGN KEY (Codigo_Disc_Dependencia) REFERENCES Disciplina(Codigo))\")\n\n # exibe as tabelas\n print(\"As tabelas foram criadas com sucesso.\")\n db_cursor.execute(\"SHOW TABLES\")\n for x in db_cursor:\n print(x)\n\n\n# Exibe os bancos\ndef exibe_bancos(db_projeto, db_cursor):\n\n db_cursor.execute(\"SHOW DATABASES\")\n for x in db_cursor:\n print(x)\n\n# # exibe as tabelas\n# db_cursor.execute(\"SHOW TABLES\")\n# for x in db_cursor:\n# print(x)\n\n\n# Inserir uma linha\n# sql = \"INSERT INTO customers (name, address) VALUES (%s, %s)\"\n# val = (\"John\", \"Highway 21\")\n# mycursor.execute(sql, val)\n# mydb.commit()\n# print(mycursor.rowcount, \"record inserted.\")\n\n# Inserir várias linhas\n# sql = \"INSERT INTO aluno VALUES (%s, %s, %s, %s, %s, %s)\"\n# val = [\n# (0, \"Raphael Prado_1\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# (0, \"Raphael Prado_2\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# (0, \"Raphael Prado_3\", \"Rio de Janeiro\", \"rapha@email.com\", \"2187458954\", 1),\n# ]\n# db_cursor.executemany(sql, val)\n# db_projeto.commit()\n# print(db_cursor.rowcount, \"was inserted.\")\n\n# Select\n# db_cursor.execute(\"SELECT * FROM Aluno\")\n# myresult = db_cursor.fetchall()\n# for x in myresult:\n# print(x)\n\n\ndef solicita_valida_entrada():\n mensagem = '''\n 1. Criar Banco de Dados no MySQL\n 2. Cria as tabelas\n 3. Conectar\n 4. Exibe os bancos do seu ambiente\n 5. Insere os dados nas tabelas\n 0. Sair\n '''\n opcao = input(mensagem)\n \n while not opcao.isdigit() or int(opcao) < 0 or int(opcao) > 5:\n print(\"Opção digitada inválida. Digite novamente.\")\n opcao = input(mensagem)\n opcao = int(opcao)\n\n return opcao\n\ndef menu():\n opcao = solicita_valida_entrada()\n while opcao != 0: # Sair\n if opcao == 1: # Criar Banco de Dados no MySQL\n # banco = input('Digite o nome do banco: ')\n # usuario = input('Digite o nome do usuário do banco: ')\n # senha = input('Digite a senha do usuário do banco: ')\n db_projeto, db_cursor = cria_banco()\n \n elif opcao == 2: # Cria as tabelas\n cria_tabelas(db_projeto, db_cursor)\n\n \n elif opcao == 3: # Conectar\n db_projeto, db_cursor, banco = conecta_banco()\n\n # try: # If\n # len(matriz_gerada) == 0\n # except: # Caso ela não exista ainda\n # print(\"Você deve executar a opcão 1 primeiro.\")\n # else:\n # print(\"\\nEstatísticas da execução:\")\n\n \n elif opcao == 4: # Exibe os bancos\n if conectado == False:\n db_projeto, db_cursor, banco = conecta_banco()\n exibe_bancos(db_projeto, db_cursor)\n else:\n exibe_bancos(db_projeto, db_cursor)\n\n # try:\n # arq = open(caminho_log)\n # except: #FileNotFoundError:\n # print('Erro: Arquivo de log não encontrado.\\nExecute a opção 1 ao menos 1 vez.')\n # else:\n # with open(caminho_log, encoding='UTF-8') as log:\n # print(log.read())\n\n elif opcao == 5: # Conectar\n db_projeto, db_cursor, banco = conecta_banco()\n \n opcao = solicita_valida_entrada()\n\n print(\"Tchau, obrigado.\\n\")\n db_cursor.close()\n db_projeto.close()\n\nmenu()\n","repo_name":"raphacp/Magalu40","sub_path":"840 Desenvolve 40 Python/4 - Banco de Dados/projeto_4_escola.py","file_name":"projeto_4_escola.py","file_ext":"py","file_size_in_byte":7228,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7334813525","text":"import geoip2.database\nfrom apps.app.data import log_file\n\n\ndef get_visitor_ip_address(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[0]\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\n\ndef log_ip_location(ip):\n reader = geoip2.database.Reader('./GeoLite2-City_20190430/GeoLite2-City.mmdb')\n response = reader.city(ip)\n\n print(response.country.name)\n print(response.country.names['zh-CN'])\n print(response.city.name)\n\n reader.close()\n","repo_name":"me-big-tuwien-ac-at/modeling-tool-repo","sub_path":"GenericWebPortal-main/apps/app/ip_info.py","file_name":"ip_info.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10992610878","text":"#!/usr/bin/env python3\nimport shared.shared as share\n\nfrom time import sleep\n\nfrom colors.color import Colors\nfrom gadgets.line_numbers import LineNumbers\nfrom shared.utils import FileSearcher\nfrom tasks.task_list import TaskList\n\n\nclass Banner:\n _banner = None\n\n # MODIFY: Defaults\n _default_color = 'Bold'\n _banner_path = FileSearcher.find_file(\n __file__,\n 'banner',\n )\n\n @staticmethod\n def _load_banner():\n if not Banner._banner:\n with open(Banner._banner_path, 'r') as f:\n Banner._banner = f.read()\n\n return Banner._banner\n\n @staticmethod\n def _print_banner(\n stdscr,\n y,\n x,\n ):\n banner = Banner._load_banner()\n\n for y, line in enumerate(\n banner.splitlines(),\n y,\n ):\n stdscr.addstr(\n y,\n x,\n line,\n Colors.get_color(Banner._default_color)\n )\n\n return y\n\n @staticmethod\n def loop_banner(\n stdscr,\n y,\n x,\n ):\n while True:\n with share.quit_lock:\n if share.is_quit:\n break\n Banner._print_banner(\n stdscr,\n y,\n x,\n )\n sleep(1)\n\n @staticmethod\n def banner_lines():\n banner = Banner._load_banner()\n\n return banner.count('\\n')\n\n\nclass Tasks:\n _task_list = None\n\n # MODIFY: Task filename\n _task_path = FileSearcher.find_file(\n __file__,\n 'tasks.yaml',\n )\n\n @staticmethod\n def _load_task_list():\n if not Tasks._task_list:\n Tasks._task_list = TaskList.from_yaml(Tasks._task_path)\n\n return Tasks._task_list\n\n @staticmethod\n def print_tasks(\n stdscr,\n y,\n max_x,\n ):\n task_list = Tasks._load_task_list()\n\n selected = 0\n start_y = y\n\n for y, task in enumerate(\n task_list,\n y,\n ):\n task_str = str(task)\n\n if task.selected:\n selected = y - start_y\n\n if task_str:\n task_attr = Colors.get_color(\n task.color,\n )\n stdscr.addstr(\n y,\n 4,\n task_str + ' ' * (max_x - len(task_str) - 4),\n task_attr,\n )\n\n LineNumbers.update_line_nums(\n stdscr,\n start_y,\n y,\n selected,\n )\n\n return y, task_list\n","repo_name":"maxwolfe/task-max","sub_path":"src/screen/outputs.py","file_name":"outputs.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16119557202","text":"import turtle\nturtle.goto(0, 0)\nschritteAnzahl = 13\nnMinus2 = 0\nnMinus1 = 1\nwhile schritteAnzahl > 0:\n schritteAnzahl = schritteAnzahl - 1\n n = nMinus2 + nMinus1\n i = 0\n while i < 4:\n turtle.forward(n)\n turtle.right(90)\n i = i + 1\n nMinus2 = nMinus1\n nMinus1 = n","repo_name":"clander/voprogrammieren","sub_path":"VO-Teil-1/GrundkonzepteProgrammierung/TurtleBeispiele/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"29789967731","text":"from flask import Flask, render_template, request, json, redirect\nfrom DinoGame import rundino\nfrom threading import Thread # From 'flask' module import 'Flask' class\n\napp = Flask(__name__) # Construct an instance of Flask class for our webapp\n\n@app.route('/')\ndef entry_point():\n return render_template('index_2.html')\n\n@app.route('/rundino')\ndef go_to_dino():\n Thread(target=rundino).start()\n url='https://chromedino.com/'\n return redirect(url, code=307)\n\nif __name__ == '__main__': # Script executed directly (instead of via import)?\n app.run(debug=True) # Launch built-in web server and run this Flask webapp","repo_name":"nidub/Colour-detection-python-game","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"2628876506","text":"import mfcc\r\nimport tdoa\r\nimport operator\r\nimport modlewrite\r\nimport numpy as np\r\nfrom sklearn.metrics import classification_report\r\nfrom functools import reduce\r\nnum = 95\r\n#结果转化\r\ndef category(y_hat):\r\n group = 0\r\n count = [0] * 7\r\n for j in range(0, len(y_hat)):\r\n for i in range(0, 7):\r\n if int(y_hat[j]) == i:\r\n count[i - 1] = count[i - 1] + 1\r\n for i in range(0, 7): # 待识别笔画的类别数\r\n if count[i] != 0:\r\n group += 1\r\n t = 0\r\n count.append(len(y_hat))\r\n count.append(group)\r\n count = list(map(str, count))\r\n return(count)\r\n\r\ndef arrchange(arr):\r\n arr = reduce(operator.add,arr)\r\n return arr\r\n\r\ndef len0(x):\r\n sum = 0\r\n for i in range(0,len(x)):\r\n if x[i] !='0':\r\n sum = sum +1\r\n return(sum)\r\n\r\ndef contrast(y_hat,x,y,word):\r\n flag =0\r\n num_x =len0(x)\r\n num_y_hat = len0(y_hat)\r\n if num_y_hat != num_x:\r\n return (word)\r\n else:\r\n for i in range(0,num_x):\r\n if x[i]== y_hat[i] :\r\n flag=flag+1\r\n n = num_y_hat - flag\r\n word[n].append(y)\r\n return(word)\r\n\r\n\r\ndef compare(result,x,y):\r\n word =[]\r\n flag = 0 #置信度\r\n if operator.eq(result, x) == True:\r\n word.append(y)\r\n for k in range(0, 7):\r\n if int(x[7]) == len(result) and int(result[k] == x[k]) and int(result[k]) != 0: # 相同的笔画类别\r\n flag = flag + 1\r\n if int(x[7]) == len(result) and (int(result[8]) == int(x[8]) - 1) and flag == int(x[8]) - 2: # 笔画数目相同但有一个笔画类别识别错误\r\n word.append(y)\r\n return(word)\r\n'''\r\ndef main():\r\n reader_mfcc = modlewrite.data_read_csv('pen2mfcc.csv') # 文件中是待识别汉字的特征值\r\n reader_mfcc_tdoa = modlewrite.data_read_csv('pen2_tdoa760.csv')\r\n y_hat_mfcc = []\r\n\r\n X_mfcc= modlewrite.feature_read(reader_mfcc, 210, num * 16 * 3 + 16 * 2) # 读取特征数据\r\n X_tdoa = modlewrite.feature_read(reader_mfcc_tdoa, 210, num)\r\n\r\n X = np.hstack([X_mfcc, X_tdoa]) # 时频域特征组合\r\n\r\n y_hat_mfcc = modlewrite.tree_read(X_mfcc)\r\n y_hat_tdoa = modlewrite.tree_tdoa_read(X_tdoa)\r\n y_hat_mfcc_tdoa =modlewrite.tree_mfcc_tdoa_read(X)\r\n print(\"classification report:\")\r\n target_names = ['1', '2', '3', '4', '5', '6', '7']\r\n y_test = ['1']*30+['2']*30+['3']*30+['4']*30+['5']*30+['6']*30+['7']*30\r\n print('时频域特征组合识别笔画结果:')\r\n print(classification_report(y_test, y_hat_mfcc_tdoa, target_names=target_names))\r\n print('仅频域特征识别笔画结果:')\r\n print(classification_report(y_test, y_hat_mfcc, target_names=target_names))\r\n print('仅时域特征识别笔画结果:')\r\n print(classification_report(y_test, y_hat_tdoa, target_names=target_names))\r\n\r\n\r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n'''\r\ndef main(s):\r\n times_L,time_energyL =mfcc.stft(s)\r\n n,x1,x2 = mfcc.mfcc(times_L,time_energyL,s) #待识别汉字的笔画个数,频域特征提取\r\n print(n)\r\n tdoa.tdoa(s,x1,x2) #时域特征提取\r\n #使用训练好的模型进行笔画识别\r\n reader_mfcc =modlewrite.data_read_csv('mfcc.csv') #文件中是待识别汉字的特征值\r\n reader_mfcc_tdoa = modlewrite.data_read_csv('tdoa.csv')\r\n\r\n X_mfcc = modlewrite.feature_read(reader_mfcc,n,num*16*3+16*2) #读取特征数据\r\n X_tdoa = modlewrite.feature_read(reader_mfcc_tdoa,n,num)\r\n\r\n X = np.hstack([X_tdoa,X_mfcc]) #时频域特征组合\r\n y_hat_mfcc= modlewrite.tree_read(X_mfcc)\r\n y_hat_mfcc_tdoa = modlewrite.tree_mfcc_tdoa_read(X)\r\n\r\n print('仅频域特征识别笔画结果:',y_hat_mfcc)\r\n print('时频域特征组合识别笔画结果:',y_hat_mfcc_tdoa)\r\n\r\n #笔画识别结果转化为字典集相同形式\r\n# result_mfcc = category(y_hat_mfcc)\r\n# result_tdoa = category(y_hat_mfcc_tdoa)\r\n\r\n# print (\"仅频域特征识别结果:\",result_mfcc)\r\n# print (\"时频域特征组合识别结果:\",result_tdoa)\r\n\r\n reader_data =modlewrite.data_read_csv('data1.csv') #数据库文件\r\n word_mfcc =[[] for i in range (12)]\r\n word_mfcc_tdoa =[[] for i in range (12)]\r\n\r\n#对比数据库结果\r\n for x in reader_data:\r\n y = x[0]\r\n x.remove(x[0])\r\n word_mfcc = contrast(y_hat_mfcc,x,y,word_mfcc)\r\n word_mfcc_tdoa= contrast(y_hat_mfcc_tdoa,x,y,word_mfcc_tdoa)\r\n\r\n word_mfcc = arrchange(word_mfcc)\r\n word_mfcc_tdoa = arrchange(word_mfcc_tdoa)\r\n\r\n\r\n if len(word_mfcc)==0:\r\n print(\"mfcc分类失败!\")\r\n if len(word_mfcc_tdoa)==0 and len(word_mfcc) == 0:\r\n print(\"mfcc_tdoa分类失败!\")\r\n return\r\n else:\r\n if 0 = 5:\r\n print(word_mfcc[0],word_mfcc[1],word_mfcc[2],word_mfcc[3],word_mfcc[4])\r\n\r\n if len(word_mfcc_tdoa) <5:\r\n print(\"时频域特征组合识别汉字:\")\r\n print(word_mfcc_tdoa)\r\n if len(word_mfcc_tdoa) >=5:\r\n print(word_mfcc_tdoa[0], word_mfcc_tdoa[1], word_mfcc_tdoa[2], word_mfcc_tdoa[3], word_mfcc_tdoa[4])\r\n#print(0)\r\nif __name__=='__main__':\r\n s = 'pen2word/9.wav'\r\n main(s)\r\n","repo_name":"dqmyzhang/acoustic-perception","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"13335681761","text":"import random\n\n# Define the list of regions\nregions = [\"IRE\", \"FRA\", \"ROM\", \"SPA\"]\n\n# Read the list of ids from a file and store them in a list\nwith open(\"ids.txt\") as f:\n ids = f.readlines()\nids = [x.strip() for x in ids]\n\n# Define the list of orders\norders = [\"Water\", \"HotChocolate\", \"Tea\", \"Latte\", \"Cappuccino\", \"Americano\", \"Croissant\"]\n\n# Define the list of functions\nfunctions = [\n \"purchase_add.py\",\n \"purchase_deduct.py\",\n \"read_points.py\",\n \"read_transaction_history.py\",\n \"read_user_details.py\",\n \"update_user_details.py\",\n]\n\ndetail_change = [\"email\",\"name\",\"both\"]\n\nshops = [\"1\",\"2\",\"3\",\"4\",\"5\"]\n\nnew_detail_count = 0\n\n# Define the number of iterations\nnum_iterations = 100\n\n# Loop through the iterations and print the strings\nfor i in range(num_iterations):\n # Generate a random shop number between 1 and 20\n shop_number = random.randint(1, 20)\n # Choose a random region from the list\n region = random.choice(regions)\n # Choose a random id from the list\n id = random.choice(ids)\n # Choose a random order from the list\n order = random.choice(orders)\n # Choose a random function from the list\n function = random.choice(functions)\n # Choose random shop\n shop = random.choice(shops)\n # Print the string\n if function == \"purchase_add.py\":\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --shop {shop} --region {region} --id {id} --order {order}'\")\n elif function == \"purchase_deduct.py\":\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id} --order {order}'\")\n elif function == \"update_user_details.py\":\n change = random.choice(detail_change)\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id} --name new_name{new_detail_count} --email new_email{new_detail_count}@example.com --change {change}'\")\n new_detail_count+=1\n else:\n print(f\"tmux send-keys -t Shops:s{shop_number} 'python {function} --region {region} --id {id}'\")\n \n # Every random number of iterations, sleep for a random amount of time\n if random.randint(1, 3) == 1:\n sleep_time = random.randint(2, 18)\n print(f\"tmux send-keys -t Shops:s{shop_number} 'Sleep {sleep_time}'\")\n","repo_name":"sureshvarshini/Distributed_systems","sub_path":"network_emulation/create_scenario.py","file_name":"create_scenario.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30240311390","text":"import argparse\nimport time\nimport numpy as np\nfrom collections import defaultdict\nfrom scipy import stats\nimport cv2\n\n\ndef makecartoon(image):\n \"\"\"\n convert image into cartoon-like image\n \"\"\"\n\n output = np.array(image)\n x, y, c = output.shape\n\n for i in xrange(c):\n output[:, :, i] = cv2.bilateralFilter(output[:, :, i], 5, 50, 50)\n edge = cv2.Canny(output, 100, 200)\n\n output = cv2.cvtColor(output, cv2.COLOR_RGB2HSV)\n\n hists = []\n\n hist, _ = np.histogram(output[:, :, 0], bins=np.arange(180+1))\n hists.append(hist)\n\n hist, _ = np.histogram(output[:, :, 1], bins=np.arange(256+1))\n hists.append(hist)\n\n hist, _ = np.histogram(output[:, :, 2], bins=np.arange(256+1))\n hists.append(hist)\n\n C = []\n for h in hists:\n C.append(k_histogram(h))\n print(\"centroids: {0}\".format(C))\n\n output = output.reshape((-1, c))\n for i in xrange(c):\n channel = output[:, i]\n index = np.argmin(np.abs(channel[:, np.newaxis] - C[i]), axis=1)\n output[:, i] = C[i][index]\n output = output.reshape((x, y, c))\n output = cv2.cvtColor(output, cv2.COLOR_HSV2RGB)\n\n contours, _ = cv2.findContours(edge,\n cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_NONE)\n\n cv2.drawContours(output, contours, -1, 0, thickness=1)\n return output\n\n\ndef update_C(C, hist):\n \"\"\"\n update centroids until they don't change\n \"\"\"\n while True:\n groups = defaultdict(list)\n for i in range(len(hist)):\n if hist[i] == 0:\n continue\n d = np.abs(C-i)\n index = np.argmin(d)\n groups[index].append(i)\n\n new_C = np.array(C)\n for i, indice in groups.items():\n if np.sum(hist[indice]) == 0:\n continue\n new_C[i] = int(np.sum(indice*hist[indice])/np.sum(hist[indice]))\n if np.sum(new_C-C) == 0:\n break\n C = new_C\n return C, groups\n\n\ndef k_histogram(hist):\n \"\"\"\n choose the best K for k-means and get the centroids\n \"\"\"\n alpha = 0.001\n N = 80\n C = np.array([128])\n\n while True:\n C, groups = update_C(C, hist)\n\n new_C = set()\n for i, indice in groups.items():\n if len(indice) < N:\n new_C.add(C[i])\n continue\n z, pval = stats.normaltest(hist[indice])\n if pval < alpha:\n left = 0 if i == 0 else C[i-1]\n right = len(hist)-1 if i == len(C)-1 else C[i+1]\n delta = right-left\n if delta >= 3:\n c1 = (C[i]+left)/2\n c2 = (C[i]+right)/2\n new_C.add(c1)\n new_C.add(c2)\n else:\n new_C.add(C[i])\n else:\n new_C.add(C[i])\n if len(new_C) == len(C):\n break\n else:\n C = np.array(sorted(new_C))\n return C\n\t\n\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--image\", required = True, help = \"Path to the image\")\nargs = vars(ap.parse_args())\n\nimage = cv2.imread(args[\"image\"])\nprint('==============')\nstart_time = time.time()\noutput = makecartoon(image)\nend_time = time.time()\nprint(\"time: {0}s\".format(end_time-start_time))\ncv2.imwrite(\"output.jpg\", output)","repo_name":"chasehamrick/Turn-Picture-into-Art","sub_path":"makecartoon.py","file_name":"makecartoon.py","file_ext":"py","file_size_in_byte":3343,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"}
+{"seq_id":"31327585355","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .utils import batch_matrix_mul, element_wise_mul, zero_gating_softmax_normalize\nimport pandas as pd\nimport numpy as np\nimport csv\nimport pickle\nfrom sklearn.preprocessing import normalize\n\ntorch.set_default_dtype(torch.float64)\n\n#\n\n\nclass WordAttNet(nn.Module):\n def __init__(self, feature_path, dict_path, max_vocab, use_cuda, dataset):\n super(WordAttNet, self).__init__()\n\n mapping = pickle.load(open(feature_path, 'rb'))\n\n dict_len = len(dataset.index_dict)\n word_feature_size = len(mapping[dataset.index_dict[2002]])\n\n feature = np.zeros((dict_len, word_feature_size))\n for key, value in mapping.items():\n if key in dataset.vocab_dict:\n feature[dataset.vocab_dict[key]] = value\n\n feature[:, 3] = -feature[:, 3]\n feature = normalize(feature, axis=0, norm='max')\n unknown_word = np.zeros((1, word_feature_size))\n feature = torch.from_numpy(np.concatenate([unknown_word, feature], axis=0).astype(np.float))\n\n self.lookup = nn.Embedding(num_embeddings=dict_len,\n embedding_dim=word_feature_size).from_pretrained(feature)\n self.lookup.weight.requires_grad = False\n\n dict_len += 1\n\n self.word_weight = nn.Parameter(torch.Tensor(word_feature_size, word_feature_size))\n self.word_bias = nn.Parameter(torch.Tensor(1, word_feature_size))\n self.context_weight = nn.Parameter(torch.Tensor(word_feature_size, 1))\n self.context_bias = nn.Parameter(torch.Tensor(1))\n self.dict_len = dict_len\n self._create_weights(mean=0.0, std=0.05)\n\n self.context_weight_history = []\n\n def _create_weights(self, mean=0.0, std=0.005):\n\n self.word_weight.data.normal_(mean, std)\n self.word_bias.data.normal_(mean, std)\n\n self.context_weight.data.normal_(1, std)\n\n self.context_bias.data.zero_()\n self.context_bias.requires_grad = False\n\n def forward(self, input):\n # [word ind, batch]\n self.context_weight_history.append(\n self.context_weight.data.cpu().numpy().reshape(-1).copy())\n\n input = input.permute(1, 0)\n f_output = self.lookup(input)\n output = batch_matrix_mul(f_output, self.context_weight, self.context_bias).permute(1, 0)\n attn_score = zero_gating_softmax_normalize(output)\n\n output = element_wise_mul(f_output, attn_score.permute(1, 0))\n\n return output, attn_score\n","repo_name":"kleeeeea/Hiercon","sub_path":"similarity_aggregation/src/word_att_model.py","file_name":"word_att_model.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"75251449444","text":"from django.urls import path,include\nfrom . import views\nfrom .views import UserPostListView, PostListView, PostDeleteView, PostDetailView, PostCreateView, PostUpdateView\n\nurlpatterns = [\n # path('admin/', admin.site.urls),\n path('',PostListView.as_view(),name='blog-home'),\n path('user/',UserPostListView.as_view(),name='user-posts'),\n path('post/',PostDetailView.as_view(),name='post-detail'),\n path('about/',views.about, name='blog-about'),\n path('post/new/',PostCreateView.as_view(), name='post-create'),\n path('post//update',PostUpdateView.as_view(),name='post-update'),\n path('post//delete',PostDeleteView.as_view(template_name='blog/post_confirm_delete.html'),name='post-delete'),\n\n\n]\n","repo_name":"hruday-tej/Blogify","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74824446885","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 13:49:48 2017\n\nFunctions for tokenizing texts.\n\nAll tokenizers are defined as classes that must feature a fit and transform\nmethod.\n\n@author: Álvaro Barbero Jiménez\n\"\"\"\n\nimport re\nimport collections\nfrom itertools import chain\n\nfrom neurowriter.linkedlist import LinkedList\n\n\nclass CharTokenizer:\n \"\"\"Tokenizer that splits a text into its basic characters\"\"\"\n\n @staticmethod\n def fit(corpus):\n # No training necessary\n pass\n\n @staticmethod\n def transform(text):\n return list(text)\n\n def __eq__(self, other):\n return isinstance(other, CharTokenizer)\n\n\nclass WordTokenizer:\n \"\"\"Tokenizer that splits text in words\n \n Punctuation and whitespace symbols are kept as individual\n tokens, so the input text can be rebuild by just concatenating\n all tokens.\n \n Words that have a low number of occurrences in the text are broken\n down to individual characters, to reduce the overall number of tokens.\n \"\"\"\n \n def __init__(self, numsymbols=4096, minfreq=2):\n self.numsymbols = numsymbols\n self.minfreq = minfreq\n self.symbols = None\n # Precompile parsing expression\n self.parser = re.compile('(\\W)')\n \n def fit(self, corpus):\n # First add all basic characters to the dictionary\n self.symbols = set(chain(*[doc for doc in corpus]))\n # Split input in words, get unique tokens and counts\n tokens = collections.Counter(\n chain(*[self.parser.split(doc) for doc in corpus])\n )\n # Filter out unfrequent symbols\n freqsymbols = [(symbol, freq) for symbol, freq in tokens.items() \n if freq >= self.minfreq]\n # Sort remaining symbols by frequency\n srt = sorted(freqsymbols, key=lambda x: x[1], reverse=True)\n # Remove already included characters\n remain = [symbol for symbol, freq in srt if symbol not in self.symbols]\n # Fill the dictionary with symbols until max allowed\n freespace = self.numsymbols - len(self.symbols)\n self.symbols.update(remain[0:freespace])\n \n def transform(self, text):\n # Break input in words\n tokens = self.parser.split(text)\n # For every word not in the recognized symbols list, break into chars\n # If a character has never been seen before, it is ignored\n result = []\n for token in tokens:\n if token in self.symbols:\n result.append(token)\n else:\n for char in token:\n if char in self.symbols:\n result.append(char)\n return result\n\n def __eq__(self, other):\n if not isinstance(other, WordTokenizer):\n return False\n return self.symbols == other.symbols\n\n\nclass SubwordTokenizer:\n \"\"\"Tokenizer that splits text in descriptive subword parts\n\n Subword parts are trained for each corpus, building from single\n characters and using a Byte Pair Encoding (BPE) method.\n\n References:\n - https://en.wikipedia.org/wiki/Byte_pair_encoding\n - https://github.com/rsennrich/subword-nmt\n - https://arxiv.org/abs/1508.07909\n \"\"\"\n\n def __init__(self, numsymbols=4096, minfreq=10, crosswords=False):\n \"\"\"Creates a Byte Pair Encoding Subword Tokenizer\n\n Arguments:\n numsymbols: maximum number of symbols to generate\n minfreq: minimum frequency for a string of characters to be made into a symbol\n crosswords: whether to allow generated symbols to cross word boundaries\n \"\"\"\n self.numsymbols = numsymbols\n self.minfreq = minfreq\n self.crosswords = crosswords\n self.symbols = None\n self.detector = None\n\n def validpair(self, s1, s2):\n \"\"\"Checks that a pair a symbols is valid for joining\n\n Essentially amounts to checking that neither symbol is crossing a word boundary, if such option is\n active.\n \"\"\"\n # If crosswords option is active, we can join anything\n if self.crosswords:\n return True\n # Else, if both are already a composite symbol, it's ok to join\n elif len(s1) > 1 and len(s2) > 1:\n return True\n # If any of them are characters, check that both are valid word symbols\n else:\n return (len(s1) > 1 or re.match(\"\\w\", s1)) and (len(s2) > 1 or re.match(\"\\w\", s2))\n\n def pairfreqs(self, corpus):\n \"\"\"Computes symbol pair statistics over a corpus\n\n The input must be a list of docs, each a LinkedList of symbols.\n Statistics over words won't be accounted for if the crosswords options is disabled.\n \"\"\"\n stats = collections.defaultdict(int)\n for doc in corpus:\n for node in doc.iternodes():\n # Only account for non-word symbols of crosswords option is active\n if node.nxt is not None and self.validpair(node.value, node.nxt.value):\n stats[node.value, node.nxt.value] += 1\n return stats\n\n def mergesymbols(self, corpus, symbols, freqs, leftsymbol, rightsymbol):\n \"\"\"Merges two symbols in the encoding\n\n Arguments:\n - corpus: current list of docs, each a LinkedList of symbols\n - symbols: current set of symbols\n - freqs: current symbol pairs statistics\n - leftsymbol, rightsymbol: symbols to merge\n\n Returns:\n - new corpus with merged symbols\n - new list of symbols\n - updated symbol pair statistics\n \"\"\"\n # Add new symbol to set\n newsymbol = leftsymbol + rightsymbol\n self.symbols.add(newsymbol)\n\n # Go over each doc in corpus, find occurrences of the given pair and merge\n for doc in corpus:\n for node in doc.iternodes():\n if node.value == leftsymbol and node.nxt is not None and node.nxt.value == rightsymbol:\n node.mergewithnext()\n # Update frequencies with previous symbol\n if node.prev is not None and self.validpair(node.prev.value, newsymbol):\n prevsymbol = node.prev.value\n freqs[prevsymbol, newsymbol] += 1\n freqs[prevsymbol, leftsymbol] -= 1\n # Update frequencies with next symbol\n if node.nxt is not None and self.validpair(node.nxt.value, newsymbol):\n nextsymbol = node.nxt.value\n freqs[newsymbol, nextsymbol] += 1\n freqs[rightsymbol, nextsymbol] -= 1\n\n # Delete statistics of merged symbols\n del freqs[(leftsymbol, rightsymbol)]\n\n return corpus, freqs, symbols\n\n def compile(self):\n \"\"\"Compiles the parsing expression for more efficiency\"\"\"\n # Sort symbols by length, so larger symbols have precedence\n srt = sorted(self.symbols, key=lambda x: len(x), reverse=True)\n # Escape special symbols\n srt = [re.escape(token) for token in srt]\n # Detect any symbol, with precedence for larger ones\n self.detector = re.compile('|'.join(srt))\n\n def bestmatch(self, string):\n \"\"\"Find the best matching symbol at the beggining of a string\"\"\"\n if self.detector is None:\n raise ValueError(\"Tokenizer has not been fitted\")\n match = self.detector.match(string)\n if match is not None:\n return match.group()\n else:\n return None\n\n def prunesymbols(self, corpus):\n \"\"\"Removes from the list of symbols those that appear unfrequently in the corpus\n\n This is useful after performing all the merge operations, where some symbols might\n have dissapeared from the corpus aftar being merged with others.\n\n The provided corpus must be an iterable of documents, each a Linked List of symbols\n after all merge operations.\n\n Symbols made of 1 character are never removed.\n \"\"\"\n # Compute frequencies of the provided corpus\n freqs = collections.defaultdict(int)\n for doc in corpus:\n for symbol in doc:\n freqs[symbol] += 1\n # Go over the symbols in the tokenizer, remove those with low frequency and more than 1 char\n self.symbols = {symbol for symbol in self.symbols if len(symbol) == 1 or freqs[symbol] >= self.minfreq}\n\n def mergingrun(self, corpus, freqs):\n \"\"\"Performs symbol merge operations till a max number of symbols is reached, or too infrequent symbols appear\"\"\"\n while len(self.symbols) < self.numsymbols:\n # Find most frequent pair\n leftsymbol, rightsymbol = max(freqs, key=freqs.get)\n # If most frequent is too infrequent, stop procedure\n if freqs[(leftsymbol, rightsymbol)] < self.minfreq:\n return corpus, freqs\n # Merge symbols\n corpus, freqs, self.symbols = self.mergesymbols(\n corpus,\n self.symbols,\n freqs,\n leftsymbol,\n rightsymbol\n )\n return corpus, freqs\n\n def fit(self, corpus):\n # Cast corpus to list of linked-lists of symbols\n corpus = [LinkedList(doc) for doc in corpus]\n # Initialize symbols with chars\n self.symbols = set(chain(*[doc for doc in corpus]))\n # Compute char pairs frequencies\n freqs = self.pairfreqs(corpus)\n # Merge steps until maximum number of symbols reached\n finished = False\n while not finished:\n # Merge symbols as much as possible\n corpus, freqs = self.mergingrun(corpus, freqs)\n # Now prune the set to remove small symbols that might have been embedded in others\n beforeprune = len(self.symbols)\n self.prunesymbols(corpus)\n afterprune = len(self.symbols)\n # If the prune was effective, try another merge run. Else finish the algorithm\n if beforeprune == afterprune:\n finished = True\n # Compile tokenizer for found symbols\n self.compile()\n\n def transform(self, text):\n transformed = []\n i = 0\n while i < len(text):\n symbol = self.bestmatch(text[i:])\n transformed.append(symbol)\n i += len(symbol)\n return transformed\n\n def __eq__(self, other):\n if not isinstance(other, SubwordTokenizer):\n return False\n return self.symbols == other.symbols\n\n\n\"\"\"Dictionary of tokenizers indexed by a string\"\"\"\nTOKENIZERSBYNAME = {\n \"char\": CharTokenizer,\n \"word\": WordTokenizer,\n \"subword\": SubwordTokenizer,\n}\n\n\ndef tokenizerbyname(tokenizername):\n \"\"\"Returns a tokenizer class by name\"\"\"\n if tokenizername not in TOKENIZERSBYNAME:\n raise ValueError(\"Unknown tokenizer %s\" % tokenizername)\n return TOKENIZERSBYNAME[tokenizername]\n","repo_name":"albarji/neurowriter","sub_path":"neurowriter/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":11030,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"52"}
+{"seq_id":"5284140451","text":"def factorial(num):\n \"\"\"calculates factorial of a number using recursion\"\"\"\n if num == 0 or num == 1: # base cases\n return 1\n return num * factorial(num-1) # recursion with num-1\n \ndef sums(num):\n \"\"\"calculates the sum of numbers from 0 to 'num' using recursion\"\"\"\n if num == 0: # base case\n return 0\n if num == 1: # base case\n return 1\n return num + sums(num-1) # recursion with num-1\n\n# open file 'recursion.txt' and iterate over each line\nwith open('recursion.txt') as file:\n for line in file:\n n = int(line.strip()) # strip whitespace from line and convert it to integer\n if n < 0: # check if n is negative\n print(\"number is negative\")\n continue # skip to next iteration\n factorial_n = factorial(n)\n sum_n = sums(n)\n print(f\"factorial sum: {factorial_n} {sum_n}\")","repo_name":"luminaa/CSCI-135","sub_path":"Lab Works/Recursion_Lab/recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11152741375","text":"from road_vehicle import BoxHauler, ElectricRoadVehicle\n\nconsist = BoxHauler(id='rakeway_box',\n base_numeric_id=870,\n name='Rakeway',\n tram_type='ELRL',\n vehicle_life=40,\n intro_date=1900)\n\nconsist.add_unit(type=ElectricRoadVehicle,\n capacity=30,\n vehicle_length=8,\n effects=['EFFECT_SPRITE_ELECTRIC, 0, 0, 10'],\n repeat=2)\n","repo_name":"andythenorth/road-hog","sub_path":"src/vehicles/rakeway_box.py","file_name":"rakeway_box.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"27382888483","text":"import networkx as nx\nimport os\nimport pandas as pd\n\nfrom pyomo.environ import Set, Var, Constraint, Reals, Param\n\nfrom gridpath.auxiliary.auxiliary import (\n subset_init_by_param_value,\n subset_init_by_set_membership,\n)\n\n\ndef add_model_components(m, d, scenario_directory, subproblem, stage):\n \"\"\"\n The following Pyomo model components are defined in this module:\n\n +-------------------------------------------------------------------------+\n | Sets |\n +=========================================================================+\n | | :code:`TX_DCOPF` |\n | |\n | The set of transmission lines of the :code:`tx_dcopf` operational type. |\n +-------------------------------------------------------------------------+\n | | :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Two-dimensional set with transmission lines of the :code:`tx_dcopf` |\n | operational type and their operational timepoints. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Derived Sets |\n +=========================================================================+\n | | :code:`PRDS_CYCLES_ZONES` |\n | |\n | Three-dimensional set describing the combination of periods, cycles, |\n | and zones/nodes. A cycle is a \"basic cycle\" in the network as defined |\n | in graph theory. This is the key set on which most other sets are |\n | derived. |\n +-------------------------------------------------------------------------+\n | | :code:`PRDS_CYCLES` |\n | |\n | Two-dimensional set with the period and cycle_id of the independent |\n | cycles of the network graph (the network can change between periods). |\n +-------------------------------------------------------------------------+\n | | :code:`CYCLES_OPR_TMPS` |\n | |\n | Two-dimensional set with of cycle IDs and operational timepoints. |\n | KVL constraint is indexed by this set. |\n +-------------------------------------------------------------------------+\n | | :code:`ZONES_IN_PRD_CYCLE` |\n | | *Defined over*: :code:`PRDS_CYCLES` |\n | |\n | Indexed set of ordered zones/nodes by period-cycle. Helper set, not |\n | directly used in constraints/param indices. |\n +-------------------------------------------------------------------------+\n | | :code:`PRDS_CYCLES_TX_DCOPF` |\n | |\n | Three-dimensional set of periods, cycle_ids, and transmission lines in |\n | that period-cycle. This set is used to determine the set |\n | :code:`TX_DCOPF_IN_PRD_CYCLE`. |\n +-------------------------------------------------------------------------+\n | | :code:`TX_DCOPF_IN_PRD_CYCLE` |\n | | *Defined over*: :code:`PRDS_CYCLES` |\n | |\n | Indexed set of transmission lines in each period-cycle. This set is |\n | used in the KVL constraint when summing up the values. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Required Params |\n +=========================================================================+\n | | :code:`tx_dcopf_reactance_ohms` |\n | | *Defined over*: :code:`TX_DCOPF` |\n | |\n | The series reactance in Ohms for each :code:`tx_dcopf` transmission |\n | line. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Derived Params |\n +=========================================================================+\n | | :code:`tx_dcopf_cycle_direction` |\n | | *Defined over*: :code:`PRDS_CYCLES_TX_DCOPF` |\n | |\n | The value of the cycle incidence matrix for each period-cycle-tx_line. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Variables |\n +=========================================================================+\n | | :code:`TxDcopf_Transmit_Power_MW` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | | *Within*: :code:`Reals` |\n | |\n | The transmission line's power flow in each timepoint in which the line |\n | is operational. Negative power means the power flow goes in the |\n | opposite direction of the line's defined direction. |\n +-------------------------------------------------------------------------+\n\n |\n\n +-------------------------------------------------------------------------+\n | Constraints |\n +=========================================================================+\n | | :code:`TxDcopf_Min_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Transmitted power should exceed the transmission line's minimum power |\n | flow for in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxDcopf_Max_Transmit_Constraint` |\n | | *Defined over*: :code:`TX_DCOPF_OPR_TMPS` |\n | |\n | Transmitted power cannot exceed the transmission line's maximum power |\n | flow in every operational timepoint. |\n +-------------------------------------------------------------------------+\n | | :code:`TxDcopf_Kirchhoff_Voltage_Law_Constraint` |\n | | *Defined over*: :code:`CYCLES_OPR_TMPS` |\n | |\n | The sum of all potential difference across branches around all cycles |\n | in the network must be zero. Using DC OPF assumptions, this can be |\n | expressed in terms of the cycle incidence matrix and line reactance. |\n +-------------------------------------------------------------------------+\n\n \"\"\"\n\n # Sets\n ###########################################################################\n\n m.TX_DCOPF = Set(\n within=m.TX_LINES,\n initialize=lambda mod: subset_init_by_param_value(\n mod=mod,\n set_name=\"TX_LINES\",\n param_name=\"tx_operational_type\",\n param_value=\"tx_dcopf\",\n ),\n )\n\n m.TX_DCOPF_OPR_TMPS = Set(\n dimen=2,\n within=m.TX_OPR_TMPS,\n initialize=lambda mod: subset_init_by_set_membership(\n mod=mod, superset=\"TX_OPR_TMPS\", index=0, membership_set=mod.TX_DCOPF\n ),\n )\n\n # Derived Sets\n ###########################################################################\n\n m.PRDS_CYCLES_ZONES = Set(\n dimen=3, initialize=periods_cycles_zones_init, ordered=True\n )\n\n m.PRDS_CYCLES = Set(dimen=2, initialize=period_cycles_init)\n\n # Note: This assumes timepoints are unique across periods\n m.CYCLES_OPR_TMPS = Set(\n dimen=2,\n initialize=lambda mod: list(\n set((c, tmp) for (p, c) in mod.PRDS_CYCLES for tmp in mod.TMPS_IN_PRD[p])\n ),\n )\n\n m.ZONES_IN_PRD_CYCLE = Set(\n m.PRDS_CYCLES, initialize=zones_by_period_cycle_init, ordered=True\n )\n\n m.PRDS_CYCLES_TX_DCOPF = Set(\n dimen=3,\n within=m.PRDS_CYCLES * m.TX_LINES,\n initialize=periods_cycles_transmission_lines_init,\n )\n\n m.TX_DCOPF_IN_PRD_CYCLE = Set(\n m.PRDS_CYCLES, initialize=tx_lines_by_period_cycle_init\n )\n\n # Required Params\n ###########################################################################\n\n m.tx_dcopf_reactance_ohms = Param(m.TX_DCOPF)\n\n # Derived Params\n ###########################################################################\n\n m.tx_dcopf_cycle_direction = Param(\n m.PRDS_CYCLES_TX_DCOPF, initialize=tx_dcopf_cycle_direction_init\n )\n\n # Variables\n ###########################################################################\n\n m.TxDcopf_Transmit_Power_MW = Var(m.TX_DCOPF_OPR_TMPS, within=Reals)\n\n # Constraints\n ###########################################################################\n\n m.TxDcopf_Min_Transmit_Constraint = Constraint(\n m.TX_DCOPF_OPR_TMPS, rule=min_transmit_rule\n )\n\n m.TxDcopf_Max_Transmit_Constraint = Constraint(\n m.TX_DCOPF_OPR_TMPS, rule=max_transmit_rule\n )\n\n m.TxDcopf_Kirchhoff_Voltage_Law_Constraint = Constraint(\n m.CYCLES_OPR_TMPS, rule=kirchhoff_voltage_law_rule\n )\n\n\n# Set Rules\n###############################################################################\n\n\ndef periods_cycles_zones_init(mod):\n \"\"\"\n Use the networkx module to determine the elementary (basic) cycles in the\n network graph, where a cycle is defined by the list of unordered zones\n (nodes) that belong to it. We do this for each period since the network\n can change between periods as we add/remove transmission lines (edges).\n\n The result is returned as a 3-dimensional set of period-cycle-zone\n combinations, e.g. (2030, 1, zone1) means that zone1 belongs to cycle 1\n in period 2030. This is the key set on which all other derived sets are\n based such that we onlyl have to perform the networkx calculations once.\n \"\"\"\n result = list()\n for period in mod.PERIODS:\n # Get the relevant tx_lines (= currently operational & DC OPF)\n tx_lines = list(mod.TX_DCOPF & mod.TX_LINES_OPR_IN_PRD[period])\n\n # Get the edges from the relevant tx_lines\n edges = [(mod.load_zone_to[tx], mod.load_zone_from[tx]) for tx in tx_lines]\n # TODO: make sure there are no parallel edges (or pre-process those)\n\n # Create a network graph from the list of lines (edges) and find\n # the elementary cycles (if any)\n graph = nx.Graph()\n graph.add_edges_from(edges)\n cycles = nx.cycle_basis(graph) # list w list of zones for each cycle\n for cycle_id, cycle in enumerate(cycles):\n for zone in cycle:\n result.append((period, cycle_id, zone))\n return result\n\n\ndef period_cycles_init(mod):\n \"\"\"\n Determine the period-cycle combinations from the larger PRDS_CYCLES_ZONES\n set. Note: set() will remove duplicates.\n \"\"\"\n return list(set([(p, c) for (p, c, z) in mod.PRDS_CYCLES_ZONES]))\n\n\ndef zones_by_period_cycle_init(mod, period, cycle):\n \"\"\"\n Re-arrange the 3-dimensional PRDS_CYCLES_ZONES set into a 1-dimensional\n set of ZONES, indexed by PRD_CYCLES\n \"\"\"\n zones = [z for (p, c, z) in mod.PRDS_CYCLES_ZONES if p == period and c == cycle]\n return zones\n\n\ndef periods_cycles_transmission_lines_init(mod):\n \"\"\"\n Based on which zones are in which cycle in each period (as defined in\n ZONES_IN_PRD_CYCLE), create a 3-dimensional set describing which\n transmission lines are in which cycle during each period.\n\n Note: Alternatively, we could simply define this set by the bigger set\n m.PRDS_CYCLES * m.TX_DCOPF and set the tx_dcopf_cycle_direction to zero\n whenever the line is not part of the cycle. This would get rid of the\n repetitive code in the init function below at the cost of iterating over\n more tx_lines than necessary in the summation of the KVL constraint.\n \"\"\"\n result = list()\n for p, c in mod.PRDS_CYCLES:\n # Ordered list of zones in the current cycle\n zones = list(mod.ZONES_IN_PRD_CYCLE[(p, c)])\n\n # Relevant tx_lines\n tx_lines = list(mod.TX_DCOPF & mod.TX_LINES_OPR_IN_PRD[p])\n\n # Get the edges from the relevant tx_lines\n edges = [(mod.load_zone_to[tx], mod.load_zone_from[tx]) for tx in tx_lines]\n\n # Get the tx lines in this cycle\n for tx_from, tx_to in zip(zones[-1:] + zones[:-1], zones):\n try:\n index = edges.index((tx_from, tx_to))\n except:\n try:\n # Revert direction\n index = edges.index((tx_to, tx_from))\n except:\n raise ValueError(\n \"The branch connecting {} and {} is not in the \"\n \"transmission line inputs\".format(tx_from, tx_to)\n )\n tx_line = tx_lines[index]\n result.append((p, c, tx_line))\n return result\n\n\ndef tx_lines_by_period_cycle_init(mod, period, cycle):\n \"\"\"\n Re-arrange the 3-dimensional PRDS_CYCLES_TX_DCOPF set into a 1-dimensional\n set of TX_DCOPF, indexed by PRD_CYCLES.\n \"\"\"\n txs = list(\n tx for (p, c, tx) in mod.PRDS_CYCLES_TX_DCOPF if c == cycle and p == period\n )\n return txs\n\n\n# Param Rules\n###############################################################################\n\n\ndef tx_dcopf_cycle_direction_init(mod, period, cycle, tx_line):\n \"\"\"\n **Param Name**: tx_dcopf_cycle_direction\n **Defined Over**: PRDS_CYCLES_TX_DCOPF\n\n This parameter describes the non-zero values of the cycle incidence\n matrix in each period. The parameter's value is 1 if the given tx_line\n is an element of the given cycle in the given period and -1 if it is the\n case for the reversed transmission line. The index of this param already\n excludes combinations of transmission lines that aren't part of a cycle,\n so the value is never zero.\n\n Note: The cycle direction is randomly determined by the networkx\n algorithm which means the param values can all be multiplied by (-1)\n in some model runs compared ot others.\n\n See \"Horsch et al. (2018). Linear Optimal Power Flow Using Cycle Flows\"\n for more background.\n \"\"\"\n zones = list(mod.ZONES_IN_PRD_CYCLE[(period, cycle)])\n from_to = (mod.load_zone_from[tx_line], mod.load_zone_to[tx_line])\n if from_to in zip(zones[-1:] + zones[:-1], zones):\n direction = 1\n elif from_to in zip(zones, zones[-1:] + zones[:-1]):\n direction = -1\n else:\n raise ValueError(\n \"The branch connecting {} and {} is not in the \"\n \"transmission line inputs\".format(\n mod.load_zone_from[tx_line], mod.load_zone_to[tx_line]\n )\n )\n return direction\n\n\n# Constraint Formulations\n###############################################################################\n\n\ndef min_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Min_Transmit_Constraint\n **Enforced Over**: TX_DCOPF_OPR_TMPS\n\n Transmitted power should exceed the minimum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return (\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n >= mod.Tx_Min_Capacity_MW[l, mod.period[tmp]]\n * mod.Tx_Availability_Derate[l, tmp]\n )\n\n\ndef max_transmit_rule(mod, l, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Max_Transmit_Constraint\n **Enforced Over**: TX_DCOPF_OPR_TMPS\n\n Transmitted power cannot exceed the maximum transmission flow capacity in\n each operational timepoint.\n \"\"\"\n return (\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n <= mod.Tx_Max_Capacity_MW[l, mod.period[tmp]]\n * mod.Tx_Availability_Derate[l, tmp]\n )\n\n\ndef kirchhoff_voltage_law_rule(mod, c, tmp):\n \"\"\"\n **Constraint Name**: TxDcopf_Kirchhoff_Voltage_Law_Constraint\n **Enforced Over**: CYCLES_OPR_TMPS\n\n The sum of all potential difference across branches around all cycles\n in the network must be zero in each operational timepoint. In DC power\n flow we assume all voltage magnitudes are kept at nominal value and the\n voltage angle differences across branches is small enough that we can\n approximate the sinus of the angle with the angle itself, i.e. sin(\n theta) ~ theta. We can therefore write KVL in terms of voltage angles as\n follows:\n\n ..math:: \\\\sum_{l} C_{l,c} * \\theta_{l} = 0 \\\\forall c = 1,...,L-N+1\n\n Using the linearized relationship between voltage angle\n differences across branches and the line flow, :math:`\\theta_{l} = x_{l}\n * f_{l}`, we can factor out the voltage angles and write KVL purely in\n terms of line flows and line reactances:\n\n .. math:: C_{l,c} * x_{l} * f_{l} = 0 \\\\forall c = 1,...,L-N+1\n\n The latter equation is enforced in this constraint.\n\n Note: While most power flow formulations normalize all inputs to per\n unit (p.u.) we can safely avoid that here since the normalization\n factors out in the equation, and it is really just about the relative\n magnitude of the reactance of the lines.\n\n Source: Horsch et al. (2018). Linear Optimal Power Flow Using Cycle Flows\n \"\"\"\n\n return (\n sum(\n mod.TxDcopf_Transmit_Power_MW[l, tmp]\n * mod.tx_dcopf_cycle_direction[mod.period[tmp], c, l]\n * mod.tx_dcopf_reactance_ohms[l]\n for l in mod.TX_DCOPF_IN_PRD_CYCLE[mod.period[tmp], c]\n )\n == 0\n )\n\n\n# Operational Type Methods\n###############################################################################\n\n\ndef transmit_power_rule(mod, l, tmp):\n \"\"\" \"\"\"\n return mod.TxDcopf_Transmit_Power_MW[l, tmp]\n\n\ndef transmit_power_losses_lz_from_rule(mod, line, tmp):\n \"\"\"\n No losses in DC OPF module for now.\n \"\"\"\n return 0\n\n\ndef transmit_power_losses_lz_to_rule(mod, line, tmp):\n \"\"\"\n No losses in DC OPF module for now.\n \"\"\"\n return 0\n\n\n# Input-Output\n###############################################################################\n\n\ndef load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param data_portal:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n\n # Get the DC OPF lines\n df = pd.read_csv(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"transmission_lines.tab\",\n ),\n sep=\"\\t\",\n usecols=[\n \"transmission_line\",\n \"load_zone_from\",\n \"load_zone_to\",\n \"tx_operational_type\",\n \"reactance_ohms\",\n ],\n )\n df = df[df[\"tx_operational_type\"] == \"tx_dcopf\"]\n\n # Dict of reactance by tx_dcopf line\n reactance_ohms = dict(\n zip(df[\"transmission_line\"], pd.to_numeric(df[\"reactance_ohms\"]))\n )\n\n # Load data\n data_portal.data()[\"tx_dcopf_reactance_ohms\"] = reactance_ohms\n","repo_name":"blue-marble/gridpath","sub_path":"gridpath/transmission/operations/operational_types/tx_dcopf.py","file_name":"tx_dcopf.py","file_ext":"py","file_size_in_byte":20714,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"52"}
+{"seq_id":"71656302885","text":"import threading\nimport time\n\nimport websocket\nfrom slackclient.server import SlackConnectionError\n\nimport handlers.handler_factory as handler_factory\n\nfrom bottypes.invalid_console_command import *\nfrom util.slack_wrapper import *\nfrom util.loghandler import log\nfrom services.enabled_services import enabled_services\n\n# This pointless line is quite important. This registers all the handlers so no delete plox until a rewrite\nfrom handlers import *\n\n\nclass BotServer(threading.Thread):\n\n # Global lock for locking global data in bot server\n thread_lock = threading.Lock()\n user_list = {}\n\n def __init__(self):\n log.debug(\"Parse config file and initialize threading...\")\n threading.Thread.__init__(self)\n self.running = False\n self.config = {}\n self.bot_name = \"\"\n self.bot_id = \"\"\n self.bot_at = \"\"\n self.slack_wrapper = None\n self.service_stack = []\n\n @staticmethod\n def lock():\n \"\"\"Acquire global lock for working with global (not thread-safe) data.\"\"\"\n BotServer.thread_lock.acquire()\n\n @staticmethod\n def release():\n \"\"\"Release global lock after accessing global (not thread-safe) data.\"\"\"\n BotServer.thread_lock.release()\n\n def quit(self):\n \"\"\"Inform the application that it is quitting.\"\"\"\n log.info(\"Shutting down\")\n self.running = False\n\n def load_config(self):\n \"\"\"Load configuration file.\"\"\"\n self.lock()\n with open(\"./config.json\") as f:\n self.config = json.load(f)\n self.release()\n\n def get_config_option(self, option):\n \"\"\"Get configuration option.\"\"\"\n self.lock()\n result = self.config.get(option)\n self.release()\n\n return result\n\n def set_config_option(self, option, value):\n \"\"\"Set configuration option.\"\"\"\n self.lock()\n\n try:\n if option in self.config:\n self.config[option] = value\n log.info(\"Updated configuration: {} => {}\".format(option, value))\n\n with open(\"./config.json\", \"w\") as f:\n json.dump(self.config, f)\n else:\n raise InvalidConsoleCommand(\"The specified configuration option doesn't exist: {}\".format(option))\n finally:\n self.release()\n\n def parse_slack_message(self, message_list):\n \"\"\"\n The Slack Real Time Messaging API is an events firehose.\n Return (message, channel, user) if the message is directed at the bot,\n otherwise return (None, None, None).\n \"\"\"\n for msg in message_list:\n if msg.get(\"type\") == \"message\" and \"subtype\" not in msg:\n if self.bot_at in msg.get(\"text\", \"\"):\n # Return text after the @ mention, whitespace removed\n return msg['text'].split(self.bot_at)[1].strip(), msg['channel'], msg['user']\n elif msg.get(\"text\", \"\").startswith(\"!\"):\n # Return text after the !\n return msg['text'][1:].strip(), msg['channel'], msg['user']\n\n return None, None, None\n\n def parse_slack_reaction(self, message_list):\n for msg in message_list:\n msgtype = msg.get(\"type\")\n\n if msgtype == \"reaction_removed\" or msgtype == \"reaction_added\":\n # Ignore reactions from the bot itself\n if msg[\"user\"] == self.bot_id:\n continue\n\n if msg[\"item\"]:\n return msg[\"reaction\"], msg[\"item\"][\"channel\"], msg[\"item\"][\"ts\"], msg[\"user\"]\n\n return None, None, None, None\n\n def load_bot_data(self):\n \"\"\"\n Fetches the bot user information such as\n bot_name, bot_id and bot_at.\n \"\"\"\n log.debug(\"Resolving bot user in slack\")\n self.bot_name = self.slack_wrapper.username\n self.bot_id = self.slack_wrapper.user_id\n self.bot_at = \"<@{}>\".format(self.bot_id)\n log.debug(\"Found bot user {} ({})\".format(self.bot_name, self.bot_id))\n self.running = True\n\n def start_services(self):\n for service in enabled_services:\n log.info(\"[Services] Enabling {}\".format(service.__name__))\n s = service(self, self.slack_wrapper)\n self.service_stack.append(s)\n s.start()\n\n def stop_services(self):\n for service in self.service_stack:\n service.cancel()\n\n def run(self):\n log.info(\"Starting server thread...\")\n\n self.running = True\n self.load_config()\n self.slack_wrapper = SlackWrapper(self.get_config_option(\"api_key\"))\n self.start_services()\n\n while self.running:\n try:\n if self.slack_wrapper.connected:\n log.info(\"Connection successful...\")\n self.load_bot_data()\n read_websocket_delay = 1 # 1 second delay between reading from firehose\n\n # Might even pass the bot server for handlers?\n log.info(\"Initializing handlers...\")\n handler_factory.initialize(self.slack_wrapper, self)\n\n # Main loop\n log.info(\"Bot is running...\")\n while self.running:\n message = self.slack_wrapper.read()\n if message:\n reaction, channel, ts, reaction_user = self.parse_slack_reaction(message)\n\n if reaction:\n log.debug(\"Received reaction : {} ({})\".format(reaction, channel))\n handler_factory.process_reaction(\n self.slack_wrapper, reaction, ts, channel, reaction_user)\n\n command, channel, user = self.parse_slack_message(message)\n\n if command:\n log.debug(\"Received bot command : {} ({})\".format(command, channel))\n handler_factory.process(self.slack_wrapper, command, channel, user)\n\n time.sleep(read_websocket_delay)\n else:\n log.error(\"Connection failed. Invalid slack token or bot id?\")\n self.running = False\n except websocket._exceptions.WebSocketConnectionClosedException:\n log.exception(\"Web socket error. Executing reconnect...\")\n except SlackConnectionError:\n # Try to reconnect if slackclient auto_reconnect didn't work out. Keep an eye on the logfiles,\n # and remove the superfluous exception handling if auto_reconnect works.\n log.exception(\"Slack connection error. Trying manual reconnect in 5 seconds...\")\n time.sleep(5)\n self.stop_services()\n log.info(\"Shutdown complete...\")\n","repo_name":"cr0wnctf/old-slack-bot","sub_path":"server/botserver.py","file_name":"botserver.py","file_ext":"py","file_size_in_byte":6910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39933672677","text":"import numpy as np\r\nimport itertools\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\nimport matplotlib.animation as animation\r\nimport pandas as pd\r\n\"\"\"\"\"Class to solve the TSP for our little example with the 10 biggest cities in CH \"\"\"\r\nclass bftsp(object):\r\n def __init__(self,mat):\r\n self.matkm = mat\r\n self.n = len(mat)\r\n\r\n def bf(self,a= True) :\r\n if a == True :\r\n mat = self.matkm\r\n else :\r\n mat = self.mat \r\n minLength = np.inf\r\n for tour in itertools.permutations(list(range(1,self.n))):\r\n fr = 0\r\n length = 0\r\n count = 0\r\n while count < self.n-1:\r\n to = tour[count]\r\n length += mat[fr][to]\r\n fr = to\r\n count += 1\r\n length += mat[fr][0]\r\n if length < minLength:\r\n minLength = length\r\n minTour = tour\r\n minTour = (0,) + minTour + (0,)\r\n if a == True :\r\n self.minLengthkm = minLength\r\n self.minTourkm = minTour\r\n else :\r\n self.minLength = minLength\r\n self.minTour = minTour \r\n \r\n def matdist(self,coords):\r\n self.coord = coords\r\n self.mat = np.zeros((self.n,self.n))\r\n for i in range(self.n):\r\n for j in range(i+1,self.n):\r\n lon = (self.coord[i][0]-self.coord[j][0])**2\r\n la = (self.coord[i][1]-self.coord[j][1])**2\r\n self.mat[i,j] = (la + lon)**0.5\r\n self.mat[j,i] = self.mat[i,j]\r\n return self.mat\r\n \r\n def __str__(self):\r\n return \"Minpath is :\" + str(self.minTour) + \" and has a length of : \" + str(self.minLength)\r\n\r\n\r\n","repo_name":"Endkas/TSP","sub_path":"BFex.py","file_name":"BFex.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"22293844439","text":"import prettytable\nimport argparse\nimport argparse_parent_base\nimport time\nfrom printer import Printer\nfrom multiprocessing import Pool, Queue\nfrom misc import read_host_from_file, valid_port\n\nfrom scapy.all import *\nICMP_TYPE_DESTINATION_UNREACHABLE = 3\nICMP_CODE_HOST_UNREACHABLE = 1\nICMP_CODE_PROTOCAL_UNREACHABLE = 2\nICMP_CODE_PORT_UNREACHABLE = 3\nICMP_CODE_ADMINISTRATIVELY_PROHIBITED = 13\nICMP_CODE = [ICMP_CODE_PORT_UNREACHABLE,\n ICMP_CODE_HOST_UNREACHABLE,\n ICMP_CODE_PROTOCAL_UNREACHABLE,\n ICMP_CODE_ADMINISTRATIVELY_PROHIBITED]\n\n\nclass Scanner():\n\n def __init__(self):\n self.ips = []\n self.timeout = 1\n self.status_ports = []\n self.ports = range(1, 1025)\n self.number_of_process = 10\n\n def scan(self, args):\n dst_ip, dst_port = args\n src_port = RandShort()\n answered, unanswered = sr(IP(dst=dst_ip) / TCP(sport=src_port,\n dport=dst_port, flags=\"S\"),\n timeout=self.timeout, verbose=False)\n for packet in unanswered:\n return packet.dst, packet.dport, \"Filtered\"\n\n for (send, recv) in answered:\n if(recv.haslayer(TCP)):\n flags = recv.getlayer(TCP).sprintf(\"%flags%\")\n if(flags == \"SA\"):\n # set RST to server in case of ddos attack\n send_rst = sr(IP(dst=dst_ip) / TCP(sport=src_port,\n dport=dst_port, flags=\"R\"),\n timeout=self.timeout, verbose=True)\n return dst_ip, dst_port, \"Open\"\n elif (flags == \"RA\" or flags == \"R\"):\n return dst_ip, dst_port, \"Closed\"\n elif(recv.haslayer(ICMP)):\n icmp_type = recv.getlayer(ICMP).type\n icmp_code = recv.getlayer(ICMP).code\n if(icmp_type == ICMP_TYPE_DESTINATION_UNREACHABLE and icmp_code in ICMP_CODE):\n return dst_ip, dst_port, \"Filtered\"\n else:\n return dst_ip, dst_port, \"CHECK\"\n\n def start(self):\n pool = Pool(processes=self.number_of_process)\n for ip in self.ips:\n for host, port, status in pool.imap_unordered(self.scan, [(ip, port) for port in self.ports]):\n self.status_ports.append(\n \"ip:{0}->port:{1} is {2}\".format(host, port, status))\n\n\ndef banner():\n banner_txt = \"\"\"\n _ __ ___ _ __| |_ ___ ___ __ _ _ __ _ __ ___ _ __ \n | '_ \\ / _ \\| '__| __/ __|/ __/ _` | '_ \\| '_ \\ / _ \\ '__|\n | |_) | (_) | | | |_\\__ \\ (_| (_| | | | | | | | __/ | \n | .__/ \\___/|_| \\__|___/\\___\\__,_|_| |_|_| |_|\\___|_| \n |_| \n\n\"A simple port scanner use syn scan\",Check status of given port\nAuthor:Samray \nMore Info:python3 syn_scan.py -h\n\"\"\"\n print(banner_txt)\n\n\ndef main():\n parser = argparse.ArgumentParser(parents=[argparse_parent_base.parser],\n description=banner(),\n add_help=True)\n args = parser.parse_args()\n scanner = Scanner()\n printer = Printer()\n if args.timeout:\n scanner.timeout = args.timeout\n if args.number_of_process:\n scanner.number_of_process = args.number_of_process\n if args.ports:\n ports = map(int, args.ports)\n scanner.ports = filter(valid_port, ports)\n if args.host_file:\n scanner.ips = read_host_from_file(args.host_file)\n scanner.ips += args.host\n scanner.start()\n if args.output_file:\n printer.filepath = args.output_file\n printer.list_to_file(scanner.status_ports)\n else:\n printer.list_to_console(scanner.status_ports)\nif __name__ == \"__main__\":\n start_time = time.time()\n main()\n print(\"---%s seconds ---\" % (time.time() - start_time))\n","repo_name":"ramsayleung/PortScanner","sub_path":"syn_scan.py","file_name":"syn_scan.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"23799154808","text":"import wandb\nimport numpy as np\nimport tensorflow as tf\n\nfrom typing import Deque, Dict, List, Tuple\n\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.optimizers import Adam\nfrom keras import backend as K\n\nfrom mlagents_envs.environment import UnityEnvironment\nfrom mlagents_envs.side_channel.engine_configuration_channel import (\n EngineConfigurationChannel,\n)\nfrom mlagents_envs.exception import (\n UnityEnvironmentException,\n UnityCommunicationException,\n UnityCommunicatorStoppedException,\n)\nfrom mlagents_envs.environment import ActionTuple\n\nENV_NAME = \"./DQN/build\"\nRUN_ID = \"train-1\"\nRESUME = True\nSUMMARY_FREQ = 10\n\nNUM_LAYERS = 2\nHIDDEN_UNITS = 512\nLEARNING_RATE = 3.0e-4\n\nBATCH_SIZE = 128\nBUFFER_SIZE = 128\nMAX_STEPS = 50\nNUM_EPOCH = 3\n\nLAMBDA = 0.95\nGAMMA = 0.99\nEPSILON = 0.2\nCRITIC_DISCOUNT = 0.5\nBETA = 0.001\n\n\nclass Actor_Critic:\n @staticmethod\n def ppo_loss(oldpolicy_probs, advantage, reward, value):\n def loss(y_true, y_pred):\n newpolicy_probs = y_true * y_pred\n old_prob = y_true * oldpolicy_probs\n\n ratio = newpolicy_probs / (old_prob + 1e-10)\n clip_ratio = K.clip(ratio, min_value=1 - EPSILON, max_value=1 + EPSILON)\n surrogate1 = ratio * advantage\n surrogate2 = clip_ratio * advantage\n\n actor_loss = -K.mean(K.minimum(surrogate1, surrogate2))\n critic_loss = K.mean(K.square(reward - value))\n entropy_loss = K.mean(\n -(newpolicy_probs * K.log(K.abs(newpolicy_probs) + 1e-10))\n )\n\n total_loss = (\n tf.constant(CRITIC_DISCOUNT) * critic_loss\n + actor_loss\n - tf.constant(BETA) * entropy_loss\n )\n return total_loss\n\n return loss\n\n @staticmethod\n def actor_model(input_dims, output_dims):\n observation = Input(shape=(input_dims,), name=\"observation_input\")\n oldpolicy_probs = Input(shape=(output_dims,), name=\"old_prediction_input\")\n advantage = Input(shape=(1,), name=\"advantage_input\")\n reward = Input(shape=(1,), name=\"reward_input\")\n value = Input(shape=(1,), name=\"value_input\")\n\n x = Dense(HIDDEN_UNITS, activation=\"tanh\", name=\"fc1\")(observation)\n for _ in range(NUM_LAYERS - 1):\n x = Dense(HIDDEN_UNITS, activation=\"tanh\")(x)\n policy = Dense(output_dims, activation=\"tanh\", name=\"policy\")(x)\n\n actor_network = Model(\n inputs=[observation, oldpolicy_probs, advantage, reward, value],\n outputs=[policy])\n\n actor_network.compile(\n optimizer=Adam(lr=LEARNING_RATE),\n loss=Actor_Critic.ppo_loss(\n oldpolicy_probs=oldpolicy_probs,\n advantage=advantage,\n reward=reward,\n value=value,\n ),\n run_eagerly=True,\n )\n actor_network.summary()\n return actor_network\n\n @staticmethod\n def critic_model(input_dims):\n observation = Input(shape=(input_dims,), name=\"observation_input\")\n\n x = Dense(HIDDEN_UNITS, activation=\"tanh\", name=\"fc1\")(observation)\n for _ in range(NUM_LAYERS - 1):\n x = Dense(HIDDEN_UNITS, activation=\"tanh\")(x)\n V = Dense(1, name=\"values\")(x) # activation='tanh'\n\n critic_network = Model(inputs=[observation], outputs=[V])\n critic_network.compile(optimizer=Adam(lr=LEARNING_RATE), loss=\"mse\")\n critic_network.summary()\n return critic_network\n\n\nclass AutopilotAgent:\n def __init__(self, env: UnityEnvironment):\n self.base_model_dir = \"model/\" + RUN_ID\n self.env = env\n self.env.reset()\n self.behavior_name = list(self.env.behavior_specs)[0]\n self.behavior_spec = self.env.behavior_specs[self.behavior_name]\n self.state_dims = sum([observation.shape[0] for observation in self.behavior_spec.observation_specs])\n self.n_actions = len(self.behavior_spec.action_spec.discrete_branches)\n\n self.dummy_n = np.zeros((1, self.n_actions))\n self.dummy_1 = np.zeros((1, 1))\n\n self.actor = Actor_Critic.actor_model(\n input_dims=self.state_dims, output_dims=self.n_actions\n )\n self.critic = Actor_Critic.critic_model(input_dims=self.state_dims)\n\n def save_model_weights(self, steps: int) -> None:\n actor_path = self.base_model_dir + \"/checkpoints/actor_weights_{}.ckpt\"\n critic_path = self.base_model_dir + \"/checkpoints/critic_weights_{}.ckpt\"\n\n self.actor.save_weights(actor_path.format(steps))\n self.critic.save_weights(critic_path.format(steps))\n\n def load_model_weights(self):\n _dir = self.base_model_dir + \"/checkpoints/\"\n latest = tf.train.latest_checkpoint(_dir)\n\n if latest == None:\n print(\"Model not found!\")\n return 0\n else:\n print(\"Loading model..\")\n\n self.actor.load_weights(latest.replace(\"critic\", \"actor\"))\n self.critic.load_weights(latest)\n\n # return last training step number.\n return int(latest.split(\"_\")[-1].split(\".\")[0])\n\n def save_model(self, steps):\n actor_path = self.base_model_dir + \"/actor_{}.hdf5\"\n critic_path = self.base_model_dir + \"/critic_{}.hdf5\"\n\n self.actor.save(actor_path.format(steps))\n self.critic.save(critic_path.format(steps))\n\n def get_advantages(self, values, masks, rewards):\n dis_returns = []\n gae = 0\n for i in reversed(range(len(rewards))):\n delta = rewards[i] + GAMMA * values[i + 1] * masks[i] - values[i]\n gae = delta + GAMMA * LAMBDA * masks[i] * gae\n dis_returns.insert(0, gae + values[i])\n\n adv = np.array(dis_returns) - values[:-1]\n return dis_returns, (adv - np.mean(adv)) / (np.std(adv) + 1e-10)\n\n def check_if_done(self, step_result) -> bool:\n if len(step_result[1].obs[0]) != 0:\n return True\n else:\n return False\n\n def step(self, action: np.ndarray) -> Tuple[np.ndarray, np.float64, bool]:\n self.env.set_actions(self.behavior_name, ActionTuple().add_discrete(np.array(action).reshape(1,3)))\n self.env.step()\n step_result = self.env.get_steps(self.behavior_name)\n done = self.check_if_done(step_result)\n next_obs = np.array([])\n\n if not done:\n next_obs = np.concatenate(step_result[0].obs, axis=1)\n reward = step_result[0].reward[0]\n else:\n next_obs = np.concatenate(step_result[1].obs, axis=1)\n reward = step_result[1].reward[0]\n return next_obs, reward, done\n\n def get_action(self, action_probs: np.ndarray, train: bool):\n no_of_agents = 1\n if train is True:\n action_matrix = action_probs[0] + np.random.normal(\n loc=0, scale=1.0, size=action_probs[0].shape\n )\n else:\n action_matrix = action_probs[0]\n\n action = np.clip(action_matrix, -1, 1)\n return np.reshape(action, (no_of_agents, self.n_actions)), action_matrix\n\n def get_buffer(self):\n observations = []\n actions = []\n old_predictions = []\n rewards = []\n values = []\n masks = []\n episode_lens = []\n counter = 0\n observation = np.array([])\n\n self.env.reset()\n step_result = self.env.get_steps(self.behavior_name)\n\n while len(observations) < BUFFER_SIZE:\n observation = np.concatenate(step_result[0].obs, axis=1)\n observation = observation[0].reshape(1,93)\n\n action_probs = self.actor.predict(\n [observation, self.dummy_n, self.dummy_1, self.dummy_1, self.dummy_1],\n steps=1,\n )\n q_value = self.critic.predict([observation], steps=1)\n\n action, action_matrix = self.get_action(action_probs, True)\n next_obs, reward, done = self.step(action)\n mask = not done\n \n observations.append(observation)\n actions.append(action_matrix)\n old_predictions.append(action_probs)\n rewards.append(reward)\n values.append(q_value)\n masks.append(mask)\n\n observation = next_obs\n counter += 1\n if done:\n episode_lens.append(counter)\n counter = 0\n self.env.reset()\n\n if len(episode_lens) == 0:\n episode_lens.append(0)\n\n observation = observation[0].reshape(1,93)\n q_value = self.critic.predict(observation, steps=1)\n values.append(q_value)\n discounted_returns, advantages = self.get_advantages(values, masks, rewards)\n\n observations = np.reshape(observations, (BUFFER_SIZE, self.state_dims))\n actions = np.reshape(actions, (BUFFER_SIZE, self.n_actions))\n old_predictions = np.reshape(old_predictions, (BUFFER_SIZE, self.n_actions))\n\n rewards = np.reshape(rewards, (BUFFER_SIZE, 1))\n values = np.reshape(values, (len(values), 1))\n advantages = np.reshape(advantages, (BUFFER_SIZE, 1))\n discounted_returns = np.reshape(discounted_returns, (BUFFER_SIZE, 1))\n\n return {\n \"observations\": observations,\n \"actions\": actions,\n \"old_predictions\": old_predictions,\n \"rewards\": rewards,\n \"values\": values[:-1],\n \"advantages\": advantages,\n \"discounted_returns\": discounted_returns,\n \"episode_lens\": episode_lens,\n }\n\n def train(self) -> None:\n if RESUME == True:\n start_pt = self.load_model_weights()\n step = 1 if (start_pt == 0) else start_pt + 1\n\n try:\n while step <= MAX_STEPS:\n buffer = self.get_buffer()\n\n observations = buffer[\"observations\"]\n actions = buffer[\"actions\"]\n old_predictions = buffer[\"old_predictions\"]\n rewards = buffer[\"rewards\"]\n values = buffer[\"values\"]\n advantages = buffer[\"advantages\"]\n discounted_returns = buffer[\"discounted_returns\"]\n episode_lens = buffer[\"episode_lens\"]\n\n actor_loss = self.actor.fit(\n [observations, old_predictions, advantages, rewards, values],\n [actions],\n batch_size=BATCH_SIZE,\n shuffle=False,\n epochs=NUM_EPOCH,\n verbose=1,\n )\n critic_loss = self.critic.fit(\n [observations],\n [discounted_returns],\n batch_size=BATCH_SIZE,\n shuffle=False,\n epochs=NUM_EPOCH,\n verbose=1,\n )\n\n print(actor_loss.history[\"loss\"], critic_loss.history[\"loss\"])\n wandb.log({'actor loss': np.mean(actor_loss.history[\"loss\"]), \n 'critic loss': np.mean(critic_loss.history[\"loss\"]),\n 'eps':np.max(episode_lens) , 'avg_reward':np.mean(rewards), \n 'advantages': np.mean(advantages)}, step=step)\n\n if step % SUMMARY_FREQ == 0:\n self.save_model_weights(step)\n step += 1\n except (\n KeyboardInterrupt,\n UnityCommunicationException,\n UnityEnvironmentException,\n UnityCommunicatorStoppedException,\n ) as ex:\n print(\"Some problem occurred, saving model\")\n self.save_model_weights(step)\n finally:\n self.save_model(step)\n self.env.close()\n\nif __name__ == \"__main__\":\n engine_config_channel = EngineConfigurationChannel()\n engine_config_channel.set_configuration_parameters(\n width=1800, height=900, time_scale=1.0\n )\n\n env = UnityEnvironment(\n file_name=ENV_NAME, seed=0, side_channels=[engine_config_channel]\n )\n wandb.init(project=\"dqn-ppo-autopilot-new\", name=\"dqn-ppo-autopilot-new\")\n\n agent = AutopilotAgent(env)\n agent.train()","repo_name":"rsuhaib678/Playing-games-with-reinforcement-learning","sub_path":"ppo_unity.py","file_name":"ppo_unity.py","file_ext":"py","file_size_in_byte":12266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41734245783","text":"class RoleModel:\n def __init__(self, role_id, role_name=\"\", can_role=False, can_user=False, can_production=False, can_packing=False,\n can_inspection=False, can_inoculation=False, can_production_in_charge=False,\n can_production_reviewer=False,can_packing_in_charge=False,\n can_packing_reviewer=False,can_inspection_in_charge=False,\n can_inspection_reviewer=False):\n self.role_id = role_id\n self.role_name = role_name\n self.can_role = can_role\n self.can_user = can_user\n self.can_production = can_production\n self.can_packing = can_packing\n self.can_inspection = can_inspection\n self.can_inoculation = can_inoculation\n self.can_production_in_charge = can_production_in_charge\n self.can_production_reviewer = can_production_reviewer\n self.can_packing_in_charge = can_packing_in_charge\n self.can_packing_reviewer = can_packing_reviewer\n self.can_inspection_in_charge = can_inspection_in_charge\n self.can_inspection_reviewer = can_inspection_reviewer\n","repo_name":"nishanthsankar7/py-vaccine-supply-chain","sub_path":"RoleModel.py","file_name":"RoleModel.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"26871565389","text":"from src.exceptions import MessageException\nfrom src import roles, utils, schemas\nfrom src.database.access import get_db\nfrom fastapi import APIRouter, status, Query\nfrom fastapi import Depends\nfrom sqlalchemy.orm import Session\nfrom src.database import models\n\nfrom src.schemas.pagination import CustomPage\n\nrouter = APIRouter(tags=[\"favorites\"])\n\n\n@router.get(\n \"/users/{uid}/favorites/songs/\", response_model=CustomPage[schemas.SongBase]\n)\ndef get_favorite_songs(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n return user.get_favorite_songs(role=role, offset=offset, limit=limit)\n\n\n@router.post(\"/users/{uid}/favorites/songs/\", response_model=schemas.SongBase)\ndef add_song_to_favorites(\n song: models.SongModel = Depends(utils.song.get_song),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if song in user.favorite_songs:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Song already in favorites\"\n )\n user.add_favorite_song(pdb, song=song)\n return song\n\n\n@router.delete(\"/users/{uid}/favorites/songs/\")\ndef remove_song_from_favorites(\n song: models.SongModel = Depends(utils.song.get_song),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if song not in user.favorite_songs:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Song not in favorites\"\n )\n user.remove_favorite_song(pdb, song=song)\n\n\n@router.get(\"/users/{uid}/favorites/albums/\", response_model=CustomPage[schemas.Album])\ndef get_favorite_albums(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n favorite_albums = user.get_favorite_albums(role=role, offset=offset, limit=limit)\n\n return favorite_albums\n\n\n@router.post(\"/users/{uid}/favorites/albums/\", response_model=schemas.AlbumBase)\ndef add_album_to_favorites(\n album: models.AlbumModel = Depends(utils.album.get_album),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if album in user.favorite_albums:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Album already in favorites\"\n )\n user.add_favorite_album(pdb, album=album)\n return album\n\n\n@router.delete(\"/users/{uid}/favorites/albums/\")\ndef remove_album_from_favorites(\n album: models.AlbumModel = Depends(utils.album.get_album),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if album not in user.favorite_albums:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Album not in favorites\"\n )\n return user.remove_favorite_album(pdb, album=album)\n\n\n@router.get(\n \"/users/{uid}/favorites/playlists/\", response_model=CustomPage[schemas.PlaylistBase]\n)\ndef get_favorite_playlists(\n user: models.UserModel = Depends(utils.user.retrieve_user),\n role: roles.Role = Depends(roles.get_role),\n offset: int = Query(0, ge=0),\n limit: int = Query(50, ge=1, le=100),\n):\n return user.get_favorite_playlists(role=role, offset=offset, limit=limit)\n\n\n@router.post(\"/users/{uid}/favorites/playlists/\", response_model=schemas.PlaylistBase)\ndef add_playlist_to_favorites(\n playlist: models.PlaylistModel = Depends(utils.playlist.get_playlist),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if playlist in user.favorite_playlists:\n raise MessageException(\n status_code=status.HTTP_409_CONFLICT, detail=\"Playlist already in favorites\"\n )\n user.add_favorite_playlist(pdb, playlist=playlist)\n return playlist\n\n\n@router.delete(\"/users/{uid}/favorites/playlists/\")\ndef remove_playlist_from_favorites(\n playlist: models.PlaylistModel = Depends(utils.playlist.get_playlist),\n user: models.UserModel = Depends(utils.user.retrieve_user),\n pdb: Session = Depends(get_db),\n):\n if playlist not in user.favorite_playlists:\n raise MessageException(\n status_code=status.HTTP_404_NOT_FOUND, detail=\"Playlist not in favorites\"\n )\n return user.remove_favorite_playlist(pdb, playlist=playlist)\n","repo_name":"taller2-grupo5-rostov-1c2022/songs-server","sub_path":"src/app/favorites.py","file_name":"favorites.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"3936641528","text":"\n\"\"\"\nhttps://leetcode.com/problems/validate-binary-tree-nodes/\nYou have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], \nreturn true if and only if all the given nodes form exactly one valid binary tree.\n\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\n\nNote that the nodes have no values and that we only use the node numbers in this problem.\n\n\nExample 1:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\n\nExample 2:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\n\nExample 3:\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n\nExample 4:\nInput: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]\nOutput: false\n\n思路:判断每个孩子节点是否有合理的唯一的父亲节点\n\"\"\"\n\n\nclass Solution:\n def validateBinaryTreeNodes(self, n, leftChild, rightChild):\n D = {}\n for i, (left, right) in enumerate(zip(leftChild, rightChild)):\n if left != -1:\n if left in D or i > left:\n return False\n else:\n D[left] = i\n if right != -1:\n if right in D or i > right:\n return False\n else:\n D[right] = i\n if len(D) < n - 1:\n return False\n return True\n\n\nS = Solution()\nn = 4\nleftChild = [1, -1, 3, -1]\nrightChild = [2, 3, -1, -1]\nres = S.validateBinaryTreeNodes(n, leftChild, rightChild)\nprint(res)\n","repo_name":"wenjiaaa/Leetcode","sub_path":"P1001_P1500/1361-validate-binary-tree-nodes.py","file_name":"1361-validate-binary-tree-nodes.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"10292807561","text":"\"\"\"\n문자열 압축 - 3회차\n\"\"\"\n\n# 풀이 제한 시간 : 30분\n# 2021/01/14 12:25 ~ 13:05\n# 실패 - 시간 초과 (알고리즘은 정답)\n\ndef solution(s):\n n = len(s)\n answer = \"\"\n count = 1\n min_value = 1001\n \n for i in range(1, n+1):\n j = 0\n\n while j < n:\n if s[j:j+i] == s[j+i:j+2*i]:\n count += 1\n else:\n if count != 1:\n answer += str(count) + s[j:j+i]\n count = 1\n else:\n answer += s[j:j+i]\n\n j += i\n\n min_value = min(min_value, len(answer))\n answer = \"\"\n\n return min_value\n\nprint(solution(\"abcabcdede\"))","repo_name":"LeeSeok-Jun/Algorithms","sub_path":"algorithms_questions/ch12_implementaion/q9_2.py","file_name":"q9_2.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"15963168667","text":"class ConnectFourView:\n\n def draw_board(self, board):\n render_list = [ [None] * 7 for x in range(7) ]\n for x in range(7):\n for y in range(len(board[x])):\n render_list[x][y] = board[x][y]\n\n formated_list = [ self.color_code(y) for x in render_list for y in x]\n formatted_string = ''\n for y in range(6, -1, -1):\n for x in range(7):\n formatted_string += formated_list[(7 * x) + y] + ' '\n formatted_string += '\\n'\n print(formatted_string)\n\n def color_code(self, token):\n if token == 0:\n return \"\\033[1;31;40m X\"\n if token == 1:\n return \"\\033[1;33;40m X\"\n else:\n return \"\\033[1;37;40m *\"\n\nif __name__ == '__main__':\n array = [\n [],\n [],\n [0,0,1],\n [0],\n [1,1],\n [1],\n []\n ]\n\n renderer = ConnectFourView()\n renderer.draw_board(array)\n","repo_name":"mikelhomeless/Monte-Carlo-Tree-Search-Connect-4","sub_path":"view_controller.py","file_name":"view_controller.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41260743737","text":"def MaximumSubarrayBrute(input_array):\n max_sum = input_array[0];\n start_index = 0;\n end_index = 0;\n\n i = 0\n for idx in input_array:\n running_sum = idx;\n if running_sum > max_sum:\n max_sum = running_sum\n start_index = i\n end_index = i\n j = i + 1\n for jdx in input_array[input_array.index(idx) + 1:]:\n running_sum += jdx\n if running_sum > max_sum:\n max_sum = running_sum\n start_index = i\n end_index = j\n j += 1\n i += 1\n\n return input_array[start_index:end_index + 1]\n\ndef MaximumSubarrayDivideandConquer(input_array, ldx, hdx):\n if ldx == hdx: # base case when there is only one element left\n return ldx, hdx, input_array[ldx]\n\n else: # for arrays with two or more elements, calculate midpoint mdx\n mdx = (ldx + hdx)//2 # divide the array into Left[ldx:mdx] and Right[mdx+1: hdx]\n Left_ldx, Left_hdx, Left_sum = MaximumSubarrayDivideandConquer(input_array, ldx, mdx)\n Cross_ldx, Cross_hdx, Cross_sum = MaxCrossingSubArray(input_array, ldx, mdx, hdx) # you will enter here if there are two elements left. ldx = mdx; mdx+1 = hdx\n Right_ldx, Right_hdx, Right_sum = MaximumSubarrayDivideandConquer(input_array, mdx+1, hdx)\n\n if Left_sum >= Right_sum and Left_sum >= Cross_sum:\n return Left_ldx, Left_hdx, Left_sum\n elif Right_sum >= Left_sum and Right_sum >= Cross_sum:\n return Right_ldx, Right_hdx, Right_sum\n else:\n return Cross_ldx, Cross_hdx, Cross_sum\n\ndef MaxCrossingSubArray(input_array, ldx, mdx, hdx):\n Left_sum = float('-inf')\n sum = 0\n\n # for idx in input_array[mdx:ldx:-1]:\n for idx in range(mdx,ldx-1,-1):\n sum += input_array[idx]\n if sum > Left_sum:\n Left_sum = sum\n max_left = idx\n\n Right_sum = float('-inf')\n sum = 0\n\n for idx in range(mdx+1,hdx+1):\n sum += input_array[idx]\n if sum > Right_sum:\n Right_sum = sum\n max_right = idx\n\n return max_left, max_right, Left_sum + Right_sum\n\n\n","repo_name":"magpayang/python_maximum_subarray","sub_path":"MaximumSubArray.py","file_name":"MaximumSubArray.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35621519203","text":"import os\nimport time\nimport socket\nimport paho.mqtt.client as mqtt\nimport psutil\nimport re\nimport subprocess\nimport shlex \nfrom subprocess import Popen, PIPE, STDOUT\nimport random\nfrom datetime import datetime\n\nREPETITIONS = 30\nMOSQUITO_CLIENT_NAME = socket.gethostname() +'_cpu_temperature_mqtt_' + str(random.randint(0, 100000))\n\n\ndef on_disconnect(client, userdata, rc):\n connect_to_broker()\n \n \ndef connect_to_broker():\n not_connected = True\n while not_connected:\n try:\n client.connect('myhomeipdk.hopto.org', port=1883)\n not_connected = False\n print(datetime.now())\n print('Im connected')\n time.sleep(10)\n except:\n print(datetime.now())\n print('Failed connection')\n time.sleep(3)\n \n \nclient = mqtt.Client(MOSQUITO_CLIENT_NAME)\nconnect_to_broker()\nclient.on_disconnect = on_disconnect\nclient.loop_start()\n\n\ndef read_wifi_strenght_from_cmd():\n p = subprocess.Popen(\"iwconfig\", stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out = p.stdout.read().decode()\n m = re.findall('(wlan[0-9]+).*?Signal level=(-[0-9]+) dBm', out, re.DOTALL) # ex. [('wlan0', '-21')]\n p.communicate()\n return m[0][1]\n \ndef get_simple_cmd_output(cmd, stderr=STDOUT):\n \"\"\"\n Execute a simple external command and get its output.\n \"\"\"\n args = shlex.split(cmd)\n return (Popen(args, stdout=PIPE, stderr=stderr).communicate()[0]).decode(\"utf-8\") \n\ndef get_ping_time(host):\n print('getting ping')\n host = host.split(':')[0]\n cmd = \"fping {host} -C 10 -q\".format(host=host)\n try:\n res_arr = get_simple_cmd_output(cmd).strip().split(':')[-1]\n res = 0\n for val in res_arr.strip().split(' '):\n res += float(val)\n res /= 10\n except Exception as e:\n print(e)\n res = 1000\n return res\n\n\n\nwhile True:\n try:\n cpu_temp = 0\n cpu_usage = 0\n wifi_rssi = 0\n ping_time = get_ping_time('192.168.8.1')\n \n for i in range (REPETITIONS):\n cpu_temp += float( os.popen(\"cat /sys/class/thermal/thermal_zone0/temp\").read() ) / 1000\n cpu_usage += int(psutil.cpu_percent())\n wifi_rssi += int(read_wifi_strenght_from_cmd())\n time.sleep(2)\n \n cpu_temp /= REPETITIONS\n cpu_usage /= REPETITIONS\n wifi_rssi /= REPETITIONS\n \n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/cpuTemp\", \"{:.1f}\". format(cpu_temp))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/cpuUsage\", \"{:.1f}\". format(cpu_usage))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/wifi_rssi\", \"{:.1f}\". format(wifi_rssi))\n client.publish(\"homeAssistant/systemStatus/garage_cpu_temperature_mqtt/ping_time\", \"{:.1f}\". format(ping_time))\n except Exception as e:\n print(e)\n time.sleep(30)\n","repo_name":"AndreaCavagna/mqtt_gate_control_raspberry_pi","sub_path":"cpu_temperature_mqtt.py","file_name":"cpu_temperature_mqtt.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30805927106","text":"# -*- coding: utf-8 -*-\n\nfrom .handlers import base\nfrom .handlers import api\nimport tornado.web\nfrom .appconfig import AppConfig\nconfig = AppConfig()\nfrom settings import settings\n\nurl_patterns = [\n (r'/', base.MainHandler),\n (r'/recent/json', api.JsonHandler),\n (r'/info', api.InfoHandler),\n (r'/info(.json)', api.InfoHandler),\n (r'/info(.html)', api.InfoHandler),\n (r'/info/system2log.json', api.System2LogHandler),\n (r'/job/data.html', api.JobInfoHandler),\n (r'/job/data.json', api.JobHandler),\n (r'/joblist(.html)', api.JobListHandler),\n (r'/joblist(.json)', api.JobListHandler),\n (r'/tasklist.html', api.TaskHandler),\n (r'/test/(.*)/(.*)', api.TestHandler),\n (r'/build-notebook', api.NotebookHandler),\n (r'/static/(.*)', tornado.web.StaticFileHandler),\n (r'/tmp/(.*)', tornado.web.StaticFileHandler, {\"path\": config[\"DEFAULT\"][\"bigfile_tmp_path\"]}),\n (r'/data/(.*)', tornado.web.StaticFileHandler, {\"path\": config[\"DEFAULT\"][\"bigfile_path\"]}),\n (r'/favicon.ico', tornado.web.StaticFileHandler, {\"path\": './static/assets/img/favicon.ico'})\n\n\n]\n","repo_name":"MMTObservatory/database_dumper","sub_path":"db_dumper/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28459862440","text":"import random\n\ndef adivinhe(x):\n numero_aleatorio = random.randint(1,x)\n palpite = 0\n\n while palpite != numero_aleatorio:\n\n palpite = int(input(f'Dê seu palpite entre 1 e {x}: '))\n if palpite < numero_aleatorio:\n print('Tente um número maior!')\n\n elif palpite > numero_aleatorio:\n print('Tente um número menor!')\n\n print(f'Parabéns, você acertou, o número era {numero_aleatorio}!')\n\n# x = int(input(f'Deseja gerar um número de 1 até: '))\n\ndef computador_advinhara(x):\n menor = 1\n maior = x\n resposta = ''\n\n while resposta != \"c\":\n palpite = random.randint(menor, maior)\n resposta = input(f'O palpite {palpite} está muito alto (A), muito baixo (B) ou está correto (C)? R: ').lower()\n\n if resposta == 'a':\n maior = palpite - 1\n\n elif resposta == 'b':\n menor = palpite + 1\n\n print(f'O computador deu o palpite correto que é {palpite}')\n\ncomputador_advinhara(1001)\n","repo_name":"ADT1710/adivinhe-numeros","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"25526780407","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nimport model_utils.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='ClinicLead',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('created', model_utils.fields.AutoCreatedField(verbose_name='created', editable=False, default=django.utils.timezone.now)),\n ('modified', model_utils.fields.AutoLastModifiedField(verbose_name='modified', editable=False, default=django.utils.timezone.now)),\n ('clinic_name', models.CharField(max_length=100)),\n ('zipcode', models.CharField(max_length=5)),\n ('state', models.CharField(max_length=30)),\n ('practice_type', models.CharField(max_length=50, choices=[('small_animal_exclusive', 'Small Animal Exclusive'), ('small_animal_predominant', 'Small Animal Predominant'), ('large animal predominant', 'Large Animal Predominant'), ('large_animal_exclusive', 'Large Animal Exclusive'), ('equine_exclusive', 'Equine Exclusive'), ('equine_predominant', 'Equine Predominant'), ('other', 'Other')])),\n ('number_of_licensed_veterinarians', models.IntegerField(max_length=3)),\n ('total_employees', models.IntegerField(max_length=3)),\n ('clinic_website', models.CharField(null=True, max_length=30, blank=True)),\n ('your_name', models.CharField(max_length=100)),\n ('your_position', models.CharField(null=True, max_length=100, blank=True)),\n ('your_email', models.CharField(max_length=200)),\n ('phone_number', models.CharField(null=True, max_length=25, blank=True)),\n ('placing_orders', models.BooleanField(default=False)),\n ('authorized', models.BooleanField(default=False)),\n ('feature_sales', models.BooleanField(default=False)),\n ('feature_support', models.BooleanField(default=False)),\n ('feature_analytics', models.BooleanField(default=False)),\n ('feature_invoicing', models.BooleanField(default=False)),\n ('feature_webpresence', models.BooleanField(default=False)),\n ('beta_user', models.BooleanField(default=False)),\n ('howdidyouhear', models.CharField(max_length=20, choices=[('conference', 'Conference'), ('personal referral', 'Personal Referral'), ('website', 'Website'), ('email', 'Email'), ('other', 'Other')])),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SupplierLead',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('created', model_utils.fields.AutoCreatedField(verbose_name='created', editable=False, default=django.utils.timezone.now)),\n ('modified', model_utils.fields.AutoLastModifiedField(verbose_name='modified', editable=False, default=django.utils.timezone.now)),\n ('company', models.CharField(max_length=100)),\n ('company_type', models.CharField(max_length=25, choices=[('manufacturer', 'Manufacturer'), ('distributor', 'Distributor'), ('compounding pharmacy', 'Compounding Pharmacy'), ('reseller', 'Reseller')])),\n ('company_size', models.CharField(max_length=100, choices=[('< 5', '< 5 employees'), ('5-10', '5-9 employees'), ('10-20', '10-20 employees'), ('21-50', '21-50 employees'), ('51-100', '51-100 employees'), ('101-500', '101-500 employees'), ('500+', '500+ employees')])),\n ('feature_sales', models.BooleanField(default=False)),\n ('feature_support', models.BooleanField(default=False)),\n ('feature_analytics', models.BooleanField(default=False)),\n ('feature_invoicing', models.BooleanField(default=False)),\n ('feature_webpresence', models.BooleanField(default=False)),\n ('name', models.CharField(max_length=100)),\n ('position', models.CharField(max_length=100)),\n ('email', models.CharField(max_length=100)),\n ('phonenumber', models.CharField(null=True, max_length=100, blank=True)),\n ('sell_method', models.CharField(max_length=30, choices=[('exclusive_distribution', 'Exclusively through distribution'), ('predominant_distribution', 'Predominantly through distribution'), ('mixed', 'Mixed between distribution and direct to vets'), ('predominant_direct', 'Predominantly direct to vets'), ('exclusive_direct', 'Exclusively direct to vets')])),\n ('selldirect', models.BooleanField(default=False)),\n ('managing_presence', models.BooleanField(default=None)),\n ('authorized', models.BooleanField(default=None)),\n ('next_steps', models.CharField(max_length=100, choices=[('betauser', \"Beta User: We'd like first access to Vetcove as a beta user\"), ('confirmed', 'Confirmed: We Plan to begin using Vetcove once the site is live'), ('undecided', 'Undecided: Speak with us to learn more between now and launch day')])),\n ('howdidyouhear', models.CharField(null=True, choices=[('conference', 'Conference'), ('personal_referral', 'Personal Referral'), ('google', 'Google'), ('emailmarketing', 'Email Marketing')], max_length=200, blank=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","repo_name":"mkates/vetcove-legacy","sub_path":"vetcove/general/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38780606783","text":"from sklearn.externals import joblib\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split, cross_val_score, cross_validate, KFold\nfrom sklearn.preprocessing import MinMaxScaler, LabelEncoder, StandardScaler, OrdinalEncoder\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction import DictVectorizer\n\nimport jsonparser\nimport player_info\nimport logging\nimport os\nimport downloader\nimport data_visualization\n\nimport pickle\nfrom math import sqrt, pi, cos, sin, atan2\nfrom random import random, randint\nimport pandas as pd\nimport numpy as np\nimport constants\nimport random\n\n\ndef in_zone(x, y, zone_x, zone_y, zone_r):\n \"\"\" Given (x, y) of a position, return True if it is within the zone boundaries\n and False if it is not\n \"\"\"\n dist_to_center = sqrt((x - zone_x)**2 + (y - zone_y)**2)\n return dist_to_center < zone_r\n\n\ndef gen_new_safezone(curr_x, curr_y, curr_r, rad_decrease):\n \"\"\"\n Given the current safe zone properties and the proportion to decrease the next one by, generate the next safe zone\n\n :param curr_x: current x coordinate of the safe zone center\n :param curr_y: current y coordinate of the safe zone center\n :param curr_r: current radius of the safe zone\n :param rad_decrease: the ratio to decrease the circle radius by. Typically 0.5\n :return: x, y and radius of the new safe zone\n \"\"\"\n new_r = curr_r * rad_decrease\n\n # Get random radius to new point within new_r\n r_ = new_r * sqrt(random())\n # Get random angle\n theta = random() * 2 * pi\n\n new_x = curr_x + r_ * cos(theta)\n new_y = curr_y + r_ * sin(theta)\n\n return new_x, new_y, new_r\n\n\ndef get_closest_to_safezone(x, y, safe_x, safe_y, safe_r):\n \"\"\"\n Get the point in the safe zone that is closest to the player location\n (Assumed that the player location is OUTSIDE the safe zone)\n\n :param x: player x coordinate\n :param y: player y coordinate\n :param safe_x: x coordinate of safe zone center\n :param safe_y: y coordinate of safe zone center\n :param safe_r: safe zone radius\n :return: the point (rounded like the player locations) closest to the safe zone\n \"\"\"\n distance = sqrt((x - safe_x)**2 + (y - safe_y)**2)\n to_move = distance - safe_r\n angle = atan2(safe_y - y, safe_x - x)\n x_ = player_info.round_raw(x + to_move * cos(angle))\n y_ = player_info.round_raw(y + to_move * sin(angle))\n return x_, y_\n\n\ndef gen_candidate_locations(curr_x, curr_y, next_safe_x, next_safe_y, next_safe_r):\n \"\"\"\n Given a player location and where the next safe zone is, calculate the neighboring locations to use\n as candidates for path generation. Only neighboring locations in the safe zone are considered.\n --> (return may be empty list)\n\n :param curr_x: player x coordinate\n :param curr_y: player y coordinate\n :param next_safe_x: safe zone x coordinate\n :param next_safe_y: safe zone y coordinate\n :param next_safe_r: safe zone radius\n :return: a list of [(x1, y1), (x2, y2), ...] of each neighboring location\n \"\"\"\n candidates = []\n for x in range(curr_x - 10000, curr_x + 20000, 10000):\n for y in range(curr_y - 10000, curr_y + 20000, 10000):\n if in_zone(x, y, next_safe_x, next_safe_y, next_safe_r):\n candidates.append((x, y))\n return candidates\n\n\ndef get_next_loc(game_state, x, y, safe_x, safe_y, safe_r, model):\n \"\"\"\n Given the current game_state, player location, safe zone location, and model, get the next location to add to path\n\n :param game_state: current game state\n :param x: player x coordinate\n :param y: player y coordinate\n :param safe_x: x coordinate of safe zone center\n :param safe_y: y coordinate of safe zone center\n :param safe_r: safe zone radius\n :param model: model used to predict whether locations will result in win or not\n :return:\n \"\"\"\n candidates = gen_candidate_locations(x, y, safe_x, safe_y, safe_r)\n if len(candidates) == 0: # No usual candidates were in the zone\n return get_closest_to_safezone(x, y, safe_x, safe_y, safe_r)\n\n winning_locs = []\n ranks = {0: [], 1: [], 2: [], 3: [], 4: []}\n for cand_x, cand_y in candidates:\n rank = predict_rank(game_state, cand_x, cand_y, safe_x, safe_y, safe_r, model)\n ranks[rank].append((cand_x, cand_y))\n\n if len(ranks[0]) > 0:\n print(\"NEXT LOC RANK 0\")\n return ranks[0][randint(0, len(ranks[0]) - 1)]\n elif len(ranks[1]) > 0:\n print(\"NEXT LOC RANK 1\")\n return ranks[1][randint(0, len(ranks[1]) - 1)]\n elif len(ranks[2]) > 0:\n print(\"NEXT LOC RANK 2\")\n return ranks[2][randint(0, len(ranks[2]) - 1)]\n elif len(ranks[3]) > 0:\n print(\"NEXT LOC RANK 3\")\n return ranks[3][randint(0, len(ranks[3]) - 1)]\n elif len(ranks[4]) > 0:\n print(\"NEX LOC RANK 4\")\n return ranks[4][randint(0, len(ranks[4]) - 1)]\n else:\n return -1, -1\n\n\ndef predict_rank(game_state, x, y, safe_x, safe_y, safe_r, model):\n \"\"\"\n Given information about a location, time, and where the safe zone is, predict whether\n the location is likely to result in a win or loss\n\n :param game_state: float representing the time of game: 0.5, 1.0... etc\n :param x: x coordinate of location to predict\n :param y: y coordinate of location to predict\n :param safe_x: x coordinate of the center of the safe zone\n :param safe_y: y coordinate of the center of the safe zone\n :param safe_r: radius of the safe zone\n :param model: the model to predict with\n :return: 1 if the location is predicted to be a winning location, 0 if it is not\n \"\"\"\n predicted = model.predict(np.array([game_state, x, y, safe_x, safe_y, safe_r]).reshape(1, -1))\n return int(predicted[0].item())\n\n\ndef gen_path(drop_x, drop_y, possible_safe_zones, end_state, model):\n \"\"\"\n Given a drop location, potential locations for the first safe zone, and a model, generate a path\n starting at the drop location.\n\n Path is generated by looking at all neighboring locations that are predicted to result in a win and selecting a\n random one as the next location. If there are no neighboring locations predicted to result in a win, the location\n does not change and the path ends. Otherwise path generation continues until the end_state (a game_state) is reached.\n For each game_state (0.5, 1, 1.5,...) there are two locations generated, and on each even game_state the safe zone\n is updated. This results in 4 locations for each safe zone, except for the first zone which only has 2 generated\n (+ the original drop location)\n\n :param drop_x: x coordinate of the drop location to start from\n :param drop_y: y coordinate of the drop location to start from\n :param possible_safe_zones: a DataFrame where the columns are:\n [x, y, radius]\n and each row represents a possible first safe zone\n :param end_state: the game_state to generate paths up to. Typical values from observed games are in the range of\n 6.5 to 9.5\n :param model: the model to use for predicting whether a location will result in a win\n :return: a DataFrame with columns:\n [x, y, game_state, safe_x, safe_y, safe_r]\n where the first row is the drop location and each subsequent row is the next location in the path\n \"\"\"\n safe_zone = possible_safe_zones.sample(n=1)\n safe_x = safe_zone[\"x\"].values[0].item()\n safe_y = safe_zone[\"y\"].values[0].item()\n safe_r = safe_zone[\"radius\"].values[0].item()\n\n curr_x = drop_x\n curr_y = drop_y\n path = list()\n\n game_state = 0.5\n path.append({\"x\": curr_x, \"y\": curr_y,\n \"game_state\": game_state,\n \"safe_x\": safe_x,\n \"safe_y\": safe_y,\n \"safe_r\": safe_r})\n\n print(\"SAFE ZONE STARTING AT {}, {} : {}\".format(safe_x, safe_y, safe_r))\n\n # While the end_state has not been reached\n while game_state < end_state:\n\n # Get the next position to move\n curr_x, curr_y = get_next_loc(game_state, curr_x, curr_y, safe_x, safe_y, safe_r, model)\n\n if curr_x == -1 and curr_y == -1: # No candidate locations were predicted to be winning locations, path ends\n game_state = end_state\n print(\"NO WINNING MOVES - YOU DIED\")\n else:\n # Add to path\n path.append({\"x\": curr_x, \"y\": curr_y,\n \"game_state\": game_state,\n \"safe_x\": safe_x,\n \"safe_y\": safe_y,\n \"safe_r\": safe_r})\n\n game_state += 0.25\n\n # Update safe zone if the game_state is a whole number\n if int(game_state) == game_state:\n safe_x, safe_y, safe_r = gen_new_safezone(safe_x, safe_y, safe_r, 0.5)\n print(\"NEW SAFE ZONE AT {}, {} : {}\".format(safe_x, safe_y, safe_r))\n return pd.DataFrame(path)\n\n\n# note that I am assuming the target is in the last position of the dataframe\n# additionally, I am assuming that the list has already been filtered(ie. we are only training on the top players)\n# additionally, my current assumption is the data has already been transformed into non-categorical data\ndef train_model(df, max_k):\n x = df[['x_drop_loc_raw', 'y_drop_loc_raw']]\n y = df['success_category']\n # x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2)\n best_score = 0.0\n best_model = None\n for k in range(1, max_k):\n scaler = StandardScaler()\n model = KNeighborsClassifier(n_neighbors=k)\n pipeline = Pipeline([('scaler', scaler),\n ('fit', model)])\n score = cross_val_score(pipeline, x, y, cv=5, scoring='accuracy').mean()\n\n\n\n if score > best_score or best_model is None:\n best_score = score\n best_model = pipeline\n print(\"Best Accuracy Score: \" + str(best_score))\n best_model.fit(x, y)\n # return best_model\n return best_model\n\n# preprocess the dataframe\ndef preprocess_data(drop_data):\n drop_data = drop_data.dropna()\n drop_data = drop_data.drop(columns=['player']) # probably don't need to include the player in the model\n drop_data = drop_data.drop(columns=['drop_loc_raw']) # probably don't need to include the player in the model\n drop_data = drop_data.dropna()\n drop_data = drop_data[drop_data['rank'] <= 5]\n labelencoder_x = LabelEncoder()\n x = drop_data.iloc[:, :].values\n drop_data['flight_path'] = labelencoder_x.fit_transform(x[:, 1])\n drop_data['map'] = labelencoder_x.fit_transform(x[:, 2])\n drop_data = drop_data.drop(columns=['rank'])\n drop_data = drop_data[['flight_path', 'map', 'drop_loc_cat']]\n scaler = MinMaxScaler()\n drop_data.loc[:, :-1] = scaler.fit_transform(drop_data[drop_data.columns[:-1]])\n return drop_data\n\n\ndef tune_player_path_model(position_df, max_k):\n \"\"\" Get the optimal k value for predicting rank based on player position and the locations of the two zones\n\n :param position_df: Output of player_info.join_player_and_zone(...)\n :param max_k: max K value to test\n :return: the model that resulted in the highest accuracy when predicting rank\n \"\"\"\n # Zone and player data\n x = position_df.drop(['name', 'ranking'], axis=1)\n\n # Player rank\n y = position_df['ranking']\n\n best_score = 0\n best_model = None\n\n # Hyperparameter Tuning\n for k in range(1, max_k):\n scaler = StandardScaler()\n model = KNeighborsClassifier(n_neighbors=k)\n pipeline = Pipeline([('scaler', scaler),\n ('fit', model)])\n\n score = cross_val_score(pipeline,\n x,\n y,\n cv=5, scoring='accuracy').mean()\n\n #print(\"\\tacc: \", score)\n if score > best_score or best_model is None:\n best_score = score\n best_model = pipeline\n\n print(\"Best Accuracy Score: \" + str(best_score))\n return best_model\n\ndef get_drop_data_by_map(drop_data):\n for i in range(len(drop_data)):\n df = drop_data[i]\n df['x_drop_loc_raw'] = df['drop_loc_raw'].apply(lambda x: x[0])\n df['y_drop_loc_raw'] = df['drop_loc_raw'].apply(lambda x: x[1])\n drop_data[i] = df\n\n for i in range(len(drop_data)):\n df = drop_data[i]\n df = df.drop(columns=['drop_loc_raw'])\n\n for i in range(len(drop_data)):\n df = drop_data[i]\n rank_range = df[\"rank\"].max() - df[\"rank\"].min()\n df[\"success_category\"] = df[\"rank\"].apply(ranking_to_bin, args=(rank_range,))\n drop_data[i] = df\n for i in range(len(drop_data)):\n df = drop_data[i]\n df = df.drop(columns=[\"drop_loc_cat\", \"drop_loc_raw\", \"player\", \"rank\"])\n drop_data[i] = df\ndef ranking_to_bin(ranking, rank_range):\n rank_bin = (ranking - 1) // (rank_range // 5)\n if rank_bin == 5: # Range doesn't divide into 5 evenly, so there will be a 6th bin, need to add to 5th instead\n rank_bin = 4\n return rank_bin\n\n\ndef get_map_data(telemetry_files):\n \"\"\"\n Given a list of telemetry file names, extract the player location and safe zone info to aggregate by map and flight\n path\n\n :param telemetry_files: list of telemetry file names\n :return: dict: {(map_name, flight_path): DataFrame of locations with safe zone, ...}\n \"\"\"\n map_data = dict()\n for i, telemetry_file in enumerate(telemetry_files):\n print(\"\\tMatch {} of {}\".format(i, len(telemetry_files)))\n telemetry = jsonparser.load_pickle(data_dir + telemetry_file)\n flight_cat = jsonparser.get_flight_cat_from_telemetry(telemetry)\n map_name = jsonparser.get_map(telemetry)\n\n if flight_cat is not None:\n print(map_name, \" : \", flight_cat)\n player_loc_info = player_info.get_player_paths(telemetry)\n zone_info = jsonparser.getZoneStates(telemetry)\n combined = player_info.join_player_and_zone(player_loc_info, zone_info).dropna()\n rank_range = combined[\"ranking\"].max() - combined[\"ranking\"].min()\n combined[\"ranking\"] = combined[\"ranking\"].apply(ranking_to_bin, args=(rank_range,))\n print(combined[\"ranking\"].value_counts())\n print(\"MAX STATE: \", combined['gameState'].max())\n\n if (map_name, flight_cat) not in map_data.keys( ):\n map_data[(map_name, flight_cat)] = []\n map_data[(map_name, flight_cat)].append(combined.dropna())\n\n for key, data in map_data.items():\n map_data[key] = pd.concat(data)\n\n return map_data\n\n\ndef train_models(map_data):\n \"\"\" Given the data for each map, train models for that data, fit them to the data, and pickle them\n\n :param map_data: dict: {(map_name, flight_path): DataFrame of player location, ...}\n :return: dict: {(map_name, flight_path): DataFrame of models, ...}\n \"\"\"\n models = dict()\n for key, data in map_data.items():\n print(key, \" : \", len(data))\n optimal = tune_player_path_model(data, 15)\n\n data_x = data.drop(['name', 'ranking'], axis=1)\n data_y = data['ranking']\n optimal.fit(data_x, data_y)\n\n models[key] = optimal\n\n with open(\"./models/{}_{}-model.pickle\".format(key[0], key[1]), \"wb\") as model_f:\n pickle.dump(optimal, model_f)\n model_f.close()\n\n return models\n\n# get_drop_data_by_map should be called before this\ndef train_models_drop_locations(drop_data, max_k):\n '''\n writes trains and writes drop data dataframe to a file\n :param drop_data: array[dataframe] for all map, flight path drop data\n :return: void\n '''\n for i in range(len(drop_data)):\n df = drop_data[i]\n mapName = df.iloc[0]['map']\n flight_direction = df.iloc[0]['flight_path']\n if mapName == 'Savage_Main':\n filepath = \"./drop_models/model_\" + mapName + \".pkl\"\n else:\n filepath = \"./drop_models/model_\" + mapName + \"_\" + flight_direction + \".pkl\"\n model = train_model(df, max_k)\n logging.debug(\"SAVING MODEL TO PATH \" + filepath)\n joblib.dump(model, filepath)\n\n\ndef get_map_constraints(mapName):\n '''\n\n :param mapName: String\n :return: tuple(:min_x: int, :max_x: int, :min_y: int, :max_y: int)\n '''\n if mapName == 'Desert_Main':\n return (constants.DESERT_MIN_X, constants.DESERT_MAX_X, constants.DESERT_MIN_Y, constants.DESERT_MAX_Y)\n elif mapName == 'Erangel_Main':\n return (constants.ERANGEL_MIN_X, constants.ERANGEL_MAX_X, constants.ERANGEL_MIN_Y, constants.ERANGEL_MAX_Y)\n elif mapName == 'DihorOtok_Main':\n return (constants.DIHOROTOK_MIN_X, constants.DIHOROTOK_MAX_X, constants.ERANGEL_MIN_Y, constants.ERANGEL_MAX_Y)\n else:\n assert(mapName == 'Savage_Main')\n return (constants.SAVAGE_MIN_X, constants.SAVAGE_MAX_X, constants.SAVAGE_MIN_Y, constants.SAVAGE_MAX_Y)\n\ndef get_drop_predictions(mapName, flight_path, model):\n '''\n\n :param mapName: String\n :param flight_path: String\n :param model: sklearn Pipeline\n :return: void\n\n writes to a csv file for the best predicted drop locations\n '''\n\n min_x, max_x, min_y, max_y = get_map_constraints(mapName)\n locations = {'x_location': [], 'y_location': []}\n # find the best drop locations\n for x in range(min_x, max_x + 1, constants.DROP_MAP_INCREMENT):\n for y in range(min_y, max_y + 1, constants.DROP_MAP_INCREMENT):\n locations['x_location'].append(x)\n locations['y_location'].append(y)\n\n locations = pd.DataFrame(locations)\n predicted_ranks = model.predict(locations)\n locations['predicted_rank'] = predicted_ranks\n best_predicted_rank = min(predicted_ranks)\n\n locations = locations[locations['predicted_rank'] == best_predicted_rank]\n\n # create a dataframe of the best drop locations and then write to a csv\n if mapName != \"Savage_Main\":\n csv_file_path = \"./drop_locations/drop_\" + mapName + \"_\" + flight_path + \".csv\"\n else:\n csv_file_path = \"./drop_locations/drop_\" + mapName + \".csv\"\n locations.to_csv(csv_file_path)\n print(\"predictions for flight_path \" + flight_path + \" for map \" + mapName + \" written to \" + csv_file_path)\n\n\ndef get_best_drop_location(mapName, flight_path):\n '''\n\n :param mapName: string\n :param flight_path: string\n :return: tuple(:x: int, :y: int)\n\n given a map name and flight direction returns an optimal drop location\n '''\n\n file_path = './drop_locations'\n\n if mapName == 'Savage_Main':\n file_path = file_path + '/' + 'drop_' + mapName + '.csv'\n else:\n file_path = file_path + '/' + 'drop_' + mapName + '_' + flight_path + '.csv'\n\n df = pd.read_csv(file_path)\n index = random.randint(0, len(df) - 1)\n\n optimal_location = df.iloc[index]\n x = optimal_location['x_location']\n y = optimal_location['y_location']\n\n\n return (x, y)\n\n\n\n\nif __name__ == \"__main__\":\n data_dir = \"./data/\"\n match_files = []\n telemetry_files = []\n\n downloader.setup_logging(show_debug=False)\n logging.info(\"Scanning for match and telemetry files in %s to parse\", data_dir)\n for file in os.listdir(data_dir):\n if \"_match\" in file:\n logging.debug(\"Match file %s found, adding as match\", file)\n match_files.append(file)\n elif \"_telemetry\" in file:\n logging.debug(\"Telemetry file %s found, adding as match\", file)\n telemetry_files.append(file)\n\n\n\n\n # this trains the models for predictiing drop locations\n drop_data = jsonparser.get_drop_data(data_dir)\n get_drop_data_by_map(drop_data)\n train_models_drop_locations(drop_data, 20)\n\n\n # Just a test telemetry object\n # t = jsonparser.load_pickle(data_dir + telemetry_files[0])\n # zone_info = jsonparser.getZoneStates(t)\n # blue_zones = zone_info[[\"safetyZonePosition_x\", \"safetyZonePosition_y\", \"safetyZoneRadius\"]]\n # blue_zones.columns = blue_zones.columns.map({\"safetyZonePosition_x\": \"x\",\n # \"safetyZonePosition_y\": \"y\",\n # \"safetyZoneRadius\": \"radius\"})\n #\n # #data = get_map_data(telemetry_files[:5])\n # #models = train_models(data)\n # #\n # # Get map name, flight path, and location info from telemetry\n # map_n = jsonparser.get_map(t)\n # fp = jsonparser.get_flight_cat_from_telemetry(t)\n # drop = player_info.get_player_paths(t)\n # total = player_info.join_player_and_zone(drop, zone_info)\n #\n # # Load the model (NOTE, must have pickled models that are fit to the data already)\n # model = jsonparser.load_pickle(\"./models/Savage_Main_nn-model.pickle\")\n #\n # # Get a random location to use as the drop location\n # total.dropna(inplace=True)\n # rand_pos = total.sample(n=1)\n # x_ = rand_pos['x'].values[0].item()\n # y_ = rand_pos['y'].values[0].item()\n # print(x_, y_)\n # #\n # # Generate a path (DataFrame)\n # path = gen_path(int(x_), int(y_), blue_zones, 8.5, model)\n # print(path)\n #\n # # Display the path\n # data_visualization.display_player_path(pd.DataFrame(path), None, map_n)\n\n # \"\"\"\n","repo_name":"ssachnof/pubg-recommendation-system","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":21335,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"74508896163","text":"import sys\ninput = sys.stdin.readline\nN = int(input())\nM = int(input())\nerr = list(map(int,input().split())) #고장난 리모컨 번호\nremote =[] #멀쩡한 리모콘 번호\ncnt = abs(100-N)\nif N == 100:\n print(0)\n exit(0)\nfor t in range(10):\n if t in err:\n continue\n remote.append(t)\nfor i in range(1000001):\n tmp = str(i)\n a=False\n for j in tmp:\n if int(j) in err:\n a=True\n break\n if a:\n continue\n else:\n cnt = min(cnt , abs(N-i) + len(str(i)))\nprint(cnt)\n\n\n\n\n\n\n#check_remote ='' #체킹용 리모콘번호 #545\n#for j in N :\n# if int(j) in remote:\n# check_remote = check_remote +str(j)\n#cha = len(N)-len(check_remote)\n#\n#for i in range(int(cha)):\n# for j in remote:\n# res.append(check_remote+str(j))\n#\n#for t in res:\n# answer.append(abs(int(N) - int(t)))\n#\n#print(check_remote)\n#print(len(N)+min(answer))","repo_name":"young0264/hellopycharm","sub_path":"백준/1107_리모컨.py","file_name":"1107_리모컨.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16134389952","text":"import os\r\nimport torch\r\nfrom basicsr.utils.download_util import load_file_from_url\r\nfrom basicsr.archs.rrdbnet_arch import RRDBNet\r\nfrom basicsr.archs.srvgg_arch import SRVGGNetCompact\r\nfrom gfpgan.utils import GFPGANer\r\nfrom realesrgan.utils import RealESRGANer\r\n\r\nfrom config import *\r\nfrom srcnn import SRCNN\r\n\r\n\r\ndef get_upsampler(model_name, device=None):\r\n if model_name == \"RealESRGAN_x4plus\": # x4 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=4,\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth\"\r\n ]\r\n elif model_name == \"RealESRNet_x4plus\": # x4 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=4,\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth\"\r\n ]\r\n elif model_name == \"RealESRGAN_x4plus_anime_6B\": # x4 RRDBNet model with 6 blocks\r\n model = RRDBNet(\r\n num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth\"\r\n ]\r\n elif model_name == \"RealESRGAN_x2plus\": # x2 RRDBNet model\r\n model = RRDBNet(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_block=23,\r\n num_grow_ch=32,\r\n scale=2,\r\n )\r\n netscale = 2\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.1/RealESRGAN_x2plus.pth\"\r\n ]\r\n elif model_name == \"realesr-animevideov3\": # x4 VGG-style model (XS size)\r\n model = SRVGGNetCompact(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_conv=16,\r\n upscale=4,\r\n act_type=\"prelu\",\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-animevideov3.pth\"\r\n ]\r\n elif model_name == \"realesr-general-x4v3\": # x4 VGG-style model (S size)\r\n model = SRVGGNetCompact(\r\n num_in_ch=3,\r\n num_out_ch=3,\r\n num_feat=64,\r\n num_conv=32,\r\n upscale=4,\r\n act_type=\"prelu\",\r\n )\r\n netscale = 4\r\n file_url = [\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-wdn-x4v3.pth\",\r\n \"https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth\",\r\n ]\r\n elif model_name == \"srcnn\":\r\n model = SRCNN(device=device)\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n model.load_state_dict(torch.load(model_path, map_location=torch.device(\"cpu\")))\r\n if device:\r\n model.to(device)\r\n return model\r\n else:\r\n raise ValueError(f\"Wrong model version {model_name}.\")\r\n\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n if not os.path.exists(model_path):\r\n print(f\"Downloading weights for model {model_name}\")\r\n\r\n for url in file_url:\r\n # model_path will be updated\r\n model_path = load_file_from_url(\r\n url=url,\r\n model_dir=os.path.join(ROOT_DIR, WEIGHT_DIR),\r\n progress=True,\r\n file_name=None,\r\n )\r\n\r\n if model_name != \"realesr-general-x4v3\":\r\n dni_weight = None\r\n else:\r\n dni_weight = [0.5, 0.5]\r\n wdn_model_path = model_path.replace(\r\n \"realesr-general-x4v3\", \"realesr-general-wdn-x4v3\"\r\n )\r\n model_path = [model_path, wdn_model_path]\r\n\r\n half = \"cuda\" in str(device)\r\n\r\n return RealESRGANer(\r\n scale=netscale,\r\n model_path=model_path,\r\n dni_weight=dni_weight,\r\n model=model,\r\n half=half,\r\n device=device,\r\n )\r\n\r\n\r\ndef get_face_enhancer(model_name, upscale=2, bg_upsampler=None, device=None):\r\n if model_name == \"GFPGANv1.3\":\r\n arch = \"clean\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth\"\r\n elif model_name == \"GFPGANv1.4\":\r\n arch = \"clean\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth\"\r\n elif model_name == \"RestoreFormer\":\r\n arch = \"RestoreFormer\"\r\n channel_multiplier = 2\r\n file_url = \"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth\"\r\n else:\r\n raise ValueError(f\"Wrong model version {model_name}.\")\r\n\r\n model_path = os.path.join(ROOT_DIR, WEIGHT_DIR, model_name + \".pth\")\r\n if not os.path.exists(model_path):\r\n print(f\"Downloading weights for model {model_name}\")\r\n model_path = load_file_from_url(\r\n url=file_url,\r\n model_dir=os.path.join(ROOT_DIR, WEIGHT_DIR),\r\n progress=True,\r\n file_name=None,\r\n )\r\n\r\n return GFPGANer(\r\n model_path=model_path,\r\n upscale=upscale,\r\n arch=arch,\r\n channel_multiplier=channel_multiplier,\r\n bg_upsampler=bg_upsampler,\r\n device=device,\r\n )\r\n","repo_name":"binh234/isr","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"3072511311","text":"DEBUG = False\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2 as cv\nimport matplotlib.pyplot as plt\n\ndef find_circles(img_cv):\n img_cv = cv.cvtColor(img_cv, cv.COLOR_GRAY2BGR)\n img_cv = cv.applyColorMap(img_cv, cv.COLORMAP_JET)\n\n if circles is not None:\n circles = np.uint16(np.around(circles))\n print(circles.shape)\n for i in circles[0,:]:\n # draw the outer circle\n cv.circle(img_cv,(i[0],i[1]),i[2],(0,255,0),2)\n # draw the center of the circle\n cv.circle(img_cv,(i[0],i[1]),2,(0,0,255),3)\n #cv.imwrite('test.png',img_cv)\n cv.imwrite('test.png',img_cv)\n circles = cv.HoughCircles(img_cv, cv.HOUGH_GRADIENT, 3, 10, param1=50, param2=30, minRadius=1, maxRadius= 5)\n\ndef plot_preprocessed_img(img_cv_in):\n img_cv = cv.cvtColor(img_cv_in, cv.COLOR_BGR2GRAY)\n #img_cv = cv.GaussianBlur(img_cv,(3,3), 0)\n #ret, thresh = cv.threshold(img_cv, 10, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n ret, thresh = cv.threshold(img_cv, 115, 256,cv.THRESH_BINARY)\n edge = cv.Canny(thresh, 120, 190, 3)\n cv.imwrite(f\"plots/edge/edge_img_lo_120_hi_190_grad_3.png\",edge)\n '''\n for i in range(10, 300,5):\n ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n cv.imwrite(f\"plots/thresh/thresh_{i}.png\",thresh)\n for j in range(100, 200, 20): \n for k in range(60, 100,10):\n for l in range(2, 8, 1):\n #edge = cv.Canny(img_cv, j, j+k, l)\n edge = cv.Canny(thresh, j, j+k, l)\n cv.imwrite(f\"plots/edge/edge_img_lo_{j}_hi_{j+k}_grad_{l}.png\",edge)\n edge = cv.GaussianBlur(edge,(3,3), 0)\n cv.imwrite(f\"plots/edge/edge_blurred_img_lo_{j}_hi_{j+k}_grad_{l}.png\",edge)\n\n '''\n\ndef crop_rect(img, rect):\n # get the parameter of the small rectangle\n center, size, angle = rect[0], rect[1], rect[2]\n center, size = tuple(map(int, center)), tuple(map(int, size))\n\n # get row and col num in img\n height, width = img.shape[0], img.shape[1]\n\n # calculate the rotation matrix\n M = cv.getRotationMatrix2D(center, angle, 1)\n # rotate the original image\n img_rot = cv.warpAffine(img, M, (width, height))\n\n # now rotated rectangle becomes vertical, and we crop it\n img_crop = cv.getRectSubPix(img_rot, size, center)\n\n return img_crop, img_rot\ndef prepare_img(img_cv, img_cv2):\n #img_cv = img_cv[:,:,0]\n print(\"here\")\n m1 = np.mean(img_cv)\n m2 = np.mean(img_cv2)\n #im_array = im_array * (m1/m2)\n img_cv2 = cv.convertScaleAbs(img_cv2,.9,5) \n img_cv2 = cv.resize(img_cv2, (img_cv.shape[0], img_cv.shape[1]), interpolation = cv.INTER_AREA)\n print(img_cv.shape)\n cv.imwrite(f\"plots/compare_R.png\",img_cv)\n cv.imwrite(f\"plots/compare_IR.png\",img_cv2)\n img_cv2 = np.asarray(img_cv2)\n img_arr2 = img_cv2.flatten()\n img_arr2 = img_arr2[img_arr2 < 255] \n fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)\n bins_x = np.linspace(img_arr2.min(), img_arr2.max(), 20)\n #bins_y = range(7500, 9500, 20)\n axs[0].hist(img_arr2, bins=bins_x)\n axs[1].hist(img_arr2, bins=bins_x)\n plt.savefig(f\"plots/hist/hist_IR.png\")\n\ndef preprocess_image(img_cv,ks=5, d=3, sigColor=100, sigSpace=100,gc=1.):\n if DEBUG:\n cv.imwrite(f\"plots/pre_preprocessed.png\",img_cv)\n # ks must be odd 3,5,7\n kernel = np.ones((ks,ks), np.float32)/(ks*ks)\n img_conv = cv.filter2D(src=img_cv, ddepth=-1, kernel=kernel)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed_conv.png\",img_conv)\n img_bi = cv.bilateralFilter(src=img_conv, d=d, sigmaColor=sigColor, sigmaSpace=sigSpace)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed_bilateral.png\",img_bi)\n img_gamma = gammaCorrection(img_bi, gc)\n if DEBUG:\n cv.imwrite(f\"plots/preprocessed.png\",img_gamma)\n\n return img_gamma\n \ndef gammaCorrection(img_cv, gamma):\n invGamma = 1/ gamma\n table = [((i/255)**invGamma) * 255 for i in range(256)]\n table = np.array(table, np.uint8)\n\n return cv.LUT(img_cv, table)\n\n\n\ndef find_rectangles(img_cv_in,img_cv_in2):\n #i = 95\n img_cv_out = img_cv_in\n img_cv_out = cv.cvtColor(img_cv_out, cv.COLOR_BGR2GRAY)\n for i in range(2, 8):\n img_cv = cv.cvtColor(img_cv_in, cv.COLOR_BGR2GRAY)\n #img_cv = img_cv_in\n cv.imwrite(\"bin_img.png\",img_cv)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY_INV+cv.THRESH_OTSU)\n\n #img_cv = cv.GaussianBlur(img_cv,(5,5), 0)\n img_cv = preprocess_image(img_cv,ks=5, d=3, sigColor=100, sigSpace=100,gc=1.)\n\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #thresh = cv.adaptiveThreshold(img_cv,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,13,i)\n thresh = cv.adaptiveThreshold(img_cv,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,13,i)\n #ret, thresh = cv.threshold(img_cv,i,255,cv.THRESH_BINARY+cv.THRESH_OTSU)\n #ret, thresh = cv.threshold(img_cv, i, 256,cv.THRESH_BINARY)\n #thresh = cv.GaussianBlur(thresh,(5,5), 0)\n #edge = cv.Canny(thresh, 120, 190, 3)\n #edge = cv.Canny(img_cv, 100, 150, 2)\n cv.imwrite(f\"plots/thresh/thresh_img_{i}.png\",thresh)\n #cv.imwrite(f\"plots/edge/edge_img_{i}.png\",edge)\n \n contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n #contours, hierarchy = cv.findContours(edge, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)\n\n print(\"Number of contours detected: \", len(contours))\n\n #img_cv2 = cv.imread('Lato_SUD_TIR.tif', cv.IMREAD_UNCHANGED)\n #img_cv2 = cv.imread('1mw_TIR_index_grayscale.tif', cv.IMREAD_UNCHANGED)\n\n img_cv2 = cv.resize(img_cv_in2, (img_cv.shape[1], img_cv.shape[0]), interpolation = cv.INTER_AREA)\n img_cv2 = cv.cvtColor(np.uint8(img_cv2), cv.COLOR_GRAY2BGR)\n img_cv2 = cv.applyColorMap(img_cv2, cv.COLORMAP_TURBO)\n #img_cv2 = cv.applyColorMap(img_cv2, cv.COLORMAP_JET)\n\n w_arr = []\n h_arr = []\n for k,cnt in enumerate(contours):\n x1, y1 = cnt[0][0]\n approx = cv.approxPolyDP(cnt, 0.01*cv.arcLength(cnt, True), True)\n if len(approx) == 4:\n #x, y, w, h = cv.boundingRect(cnt)\n rect = cv.minAreaRect(cnt)\n #print(rect)\n box = cv.boxPoints(rect)\n box = np.int0(box)\n x1 = box[0]\n x2 = box[1]\n x3 = box[2]\n w = np.sum(np.power(x2-x1,2))\n h = np.sum(np.power(x3-x1,2))\n #print(h)\n #print(f\"box: {box}\")\n if( w >50**2 and h > 50**2 and w < 120**2 and h<120**2):\n #img_crop, img_rot = crop_rect(img_cv2,rect)\n #cv.imwrite(f\"plots/crops/cropped_rect_{k}_param_{i}.png\",img_crop)\n print(f\"width: {w}, height: {h}\")\n w_arr.append(w)\n h_arr.append(h)\n #img_cv = cv.drawContours(img_cv_in, [cnt], -1, (0, 255,255),6)\n img_cv = cv.drawContours(img_cv, [cnt], -1, (255,0,0),6)\n #img_cv2 = cv.drawContours(img_cv2, [cnt], -1, (255, 255,0),8)\n img_cv_out = cv.drawContours(img_cv_out, [box], -1, (255, 0,0),6)\n #cv.putText(img_cv, f\"{k}\", (x1[0], x1[1]), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255,0), 2)\n #cv.putText(img_cv2, f\"{k}\", (x1[0], x1[1]), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255,0), 2)\n\n fig, axs = plt.subplots(1, 2, sharey=True, tight_layout=True)\n bins_x = range(5500, 7500, 20)\n bins_y = range(7500, 9500, 20)\n axs[0].hist(w_arr, bins=bins_x)\n axs[1].hist(h_arr, bins=bins_y)\n plt.savefig(f\"plots/hist/hist_rec_{i}.png\")\n cv.imwrite(f\"plots/contours/contour_rec_{i}.png\",img_cv)\n cv.imwrite(f\"plots/contours/coutour_IR_rec_{i}.png\",img_cv2)\n #cv.imshow(\"Shapes\", img_cv)\n #cv.waitKey(0)\n cv.imwrite(f\"plots/contours/contour_all.png\",img_cv_out)\n cv.destroyAllWindows()\n\ndef main():\n Image.MAX_IMAGE_PIXELS = 254162108\n #im = Image.open('Lato_SUD_LERS.tif')\n #im = Image.open('Lato_SUD.tif')\n im1 = Image.open('Ortho1mw_Lres.tif')\n im_array1 = np.array(im1)\n img_cv1 = im_array1.astype(np.uint8)\n\n im2 = Image.open('1mw_TIR_index_grayscale.tif')\n im_array2 = np.array(im2)\n img_cv2 = im_array2.astype(np.uint8)\n\n #prepare_img(img_cv1, img_cv2)\n find_rectangles(img_cv1, img_cv2)\n #plot_preprocessed_img(img_cv)\n #find_circle(img_cv)\n\n if DEBUG:\n #im_array = im_array * (im_array > 30)\n print('mean')\n print(im_array.mean())\n print('max')\n print(im_array.max())\n print('min')\n print(im_array.mean())\n print(im.getbands())\n print(im.tell())\n print(im_array.shape)\n print(im_array.size)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"gabriel-rmrz/hotspot_finder","sub_path":"hotspot_finder.py","file_name":"hotspot_finder.py","file_ext":"py","file_size_in_byte":8506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41543271749","text":"import os\nimport csv\nfrom xlrd import open_workbook\n\nfiles = '/home/openerp/Documentos/Herrera/CSV Files/'\n\nnames = os.listdir(files)\nfield_help = open_workbook('/home/openerp/Documentos/Herrera/descripcion campos txt.xls')\nsheet = field_help.sheet_by_index(0)\nos.popen('mkdir /home/openerp/auto/herrera_madi_data')\nopenerp = open('/home/openerp/auto/herrera_madi_data/__openerp__.py','w')\nos.popen('echo import model >> /home/openerp/auto/herrera_madi_data/__init__.py')\nos.popen('mkdir /home/openerp/auto/herrera_madi_data/model /home/openerp/auto/herrera_madi_data/view /home/openerp/auto/herrera_madi_data/wizard')\ninit = open('/home/openerp/auto/herrera_madi_data/model/__init__.py','w')\nmenu = False\nopenerp.write('''#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n###########################################################################\n# Module Writen to OpenERP, Open Source Management Solution\n# Copyright (C) Vauxoo ().\n# All Rights Reserved\n###############Credits######################################################\n# Coded by: Vauxoo C.A. \n# Planified by: Nhomar Hernandez\n# Audited by: Vauxoo C.A.\n#############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n################################################################################''')\nopenerp.write('\\n{\\n')\nopenerp.write('\"name\" : \"Herrera madi Data Imported\",\\n')\nopenerp.write('\"version\" : \"0.1\",\\n')\nopenerp.write('\"depends\" : [\"base\"],\\n')\nopenerp.write('\"author\" : \"Vauxoo\",\\n')\nopenerp.write('\"description\" : \"Create modules by file used to import data from cobol \" ,\\n')\nopenerp.write('\"website\" : \"http://vauxoo.com\",\\n')\nopenerp.write('\"category\" : \"Generic Modules\",\\n')\nopenerp.write('\"init_xml\" : [],\\n')\nopenerp.write('\"demo_xml\" : [],\\n')\nopenerp.write('\"test\" : [],\\n')\nopenerp.write('\"update_xml\" : [\\n')\n\n\nfor name_file in names:\n name_file and name_file[:-4].find('~') <0 and init.write('import %s\\n'%name_file[:-4])\n fields = csv.DictReader(open('%s/%s'%(files,name_file)))\n clase = open('/home/openerp/auto/herrera_madi_data/model/%s.py'%name_file[:-4],'w')\n view = open('/home/openerp/auto/herrera_madi_data/view/%s_view.xml'%name_file[:-4],'w')\n\n\n view.write('\\n \\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" %s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" form\\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" %s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" tree\\n\")\n view.write(\" \\n\")\n view.write(\" \\n\"%str(name_file[:-4]))\n for tree in tree_name:\n view.write(\" \\n\"%tree)\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n view.write(\" \\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" maestro.%s\\n\"%str(name_file[:-4]).lower())\n view.write(\" form\\n\")\n view.write(\" form\\n\")\n view.write(\" tree,form\\n\")\n view.write(\" \\n\")\n view.write('\\n\\n\\n')\n if not menu:\n view.write(\" \\n\")\n view.write(\" \\n\")\n \n view.write(\"\\n\"%(str(name_file[:-4]),str(name_file[:-4]).lower(),str(name_file[:-4]).lower()))\n menu = True\n view.write(\" \\n\")\n view.write(\"\\n\")\n openerp.write(\"'view/%s_view.xml',\\n\"%name_file[:-4])\n break\n\n\n clase.write(\"\\n }\")\n clase.write('\\n%s()'%name_file[:-4])\nopenerp.write('],\\n')\nopenerp.write('\"active\": False,\\n')\nopenerp.write('\"installable\": True,\\n')\nopenerp.write('}')\n\n\n\n","repo_name":"josemoralesp/odoo-scripts","sub_path":"odoo-scripts/create_class.py","file_name":"create_class.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"37979874656","text":"import pandas as pd\nfrom sklearn import metrics\nimport joblib\n\n\nfrom sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier\n\n## full dataset ##\ntrain = pd.read_csv(\"train.csv\").drop([\"Unnamed: 0\",\"Unnamed: 0.1\"], axis = 1)\ntest = pd.read_csv(\"test.csv\").drop([\"Unnamed: 0\",\"Unnamed: 0.1\"], axis = 1)\nX_train,y_train = train.loc[:, train.columns != 'Primary Type'], train['Primary Type']\nX_test,y_test = test.loc[:, test.columns != 'Primary Type'], test['Primary Type']\n\nclf = RandomForestClassifier(n_estimators=120)\nX_train_no_beat = X_train.loc[:,~X_train.columns.str.contains(\"^Beat\")]\nX_test_no_beat = X_test.loc[:,~X_test.columns.str.contains(\"^Beat\")]\n\nclf.fit(X_train, y_train)\ny_pred=clf.predict(X_test)\njoblib.dump(clf, 'randomForestModel.pkl')\nprint(\"Accuracy randomForest no beats:\",metrics.accuracy_score(y_test, y_pred))\nfeature_names = [f'feature {c}' for c in X_train.columns]\nfeature_imp = pd.Series(clf.feature_importances_,index=feature_names).sort_values(ascending=False)\nfeature_imp.to_csv(\"feature_importance.csv\")\nclf = AdaBoostClassifier(n_estimators=120)\nclf.fit(X_train_no_beat, y_train)\ny_pred = clf.predict(X_test_no_beat)\njoblib.dump(clf, 'adaBoostModel.pkl')\nprint(\"Accuracy Adaboost no beats full dataset: \", metrics.accuracy_score(y_test, y_pred))\n\nclf = GradientBoostingClassifier(n_estimators=120)\nclf.fit(X_train_no_beat, y_train)\ny_pred = clf.predict(X_test_no_beat)\njoblib.dump(clf, 'gradientBoostingModel.pkl')\nprint(\"Accuracy GradientBoosting full no beats dataset: \", metrics.accuracy_score(y_test, y_pred))\n\n\n","repo_name":"yaelkirk/Hackaton","sub_path":"random_forest.py","file_name":"random_forest.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40463852757","text":"import binascii\nimport tempfile\nimport xlrd\nfrom odoo import fields, models, _\nfrom odoo.exceptions import ValidationError\n\n\nclass UserImport(models.TransientModel):\n \"\"\"Import User with access right\"\"\"\n _name = 'user.import'\n _description = 'User Import'\n\n file = fields.Binary(string=\"Upload File\", help='Upload the file here')\n\n def import_file(self):\n \"\"\" function to import user from xlsx file \"\"\"\n if self:\n try:\n file_string = tempfile.NamedTemporaryFile(suffix=\".xlsx\")\n file_string.write(binascii.a2b_base64(self.file))\n book = xlrd.open_workbook(file_string.name)\n sheet = book.sheet_by_index(0)\n except:\n raise ValidationError(_(\"Please choose the correct file\"))\n\n startline = True\n for i in range(sheet.nrows):\n if startline:\n startline = False\n else:\n line = list(sheet.row_values(i))\n res_lang = self.env['res.lang']\n res_groups = self.env['res.groups']\n res_company = self.env['res.company']\n user_type = [line[4]]\n invalid_language = [lang for lang in [line[2]] if\n not res_lang.search(\n [('code', '=', lang), ('active', '=', True)])]\n if invalid_language:\n raise ValidationError(_(\"Language %s is not active\") % (\n \" \".join(invalid_language)))\n invalid_company = [res for res in [line[3]] if\n not res_company.search(\n [('name', '=', res)])]\n if invalid_company:\n raise ValidationError(_(\"Company %s not exists\") % (\n \" \".join(invalid_company)))\n invalid_user = [rec for rec in user_type if\n not res_groups.search(\n [('full_name', '=', rec)])]\n if invalid_user:\n raise ValidationError(_(\"Invalid User Type %s\") % (\n \" \".join(invalid_user)))\n if line[5]:\n groups = line[5].split(\",\")\n invalid_groups = [rec for rec in groups if\n not res_groups.search(\n [('full_name', '=', rec)])]\n if invalid_groups:\n raise ValidationError(_(\"Invalid groups %s\") % (\n \" \".join(invalid_groups)))\n else:\n groups = []\n access_right = res_groups.search(\n [('full_name', 'in', groups)]).ids\n tech_settings = line[6].split(',')\n tech_settings += user_type\n total_rights = res_groups.search(\n [('name', '=', tech_settings)]).ids\n group_ids = access_right + total_rights\n if line[0]:\n self.env['res.users'].create({\n 'name': line[0],\n 'login': line[1],\n 'lang': line[2],\n 'company_id': self.env['res.company'].search(\n [('name', '=', line[3])]).id if line[3] else '',\n 'groups_id': group_ids,\n })\n else:\n raise ValidationError(_('Please Enter the User Name.'))\n","repo_name":"CybroOdoo/CybroAddons","sub_path":"import_user_excel/wizard/user_import.py","file_name":"user_import.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","stars":204,"dataset":"github-code","pt":"52"}
+{"seq_id":"13891239384","text":"import csv\nimport BaseStats\nfrom math import floor\n\n\nclass EquipmentBase(object):\n def __init__(self, key, name=\"None\"):\n self.name = name\n self.key = key\n self.type = str\n self.slot = str\n self.stat_bonuses = {\n \"Strength\": 0,\n \"Dexterity\": 0,\n \"Endurance\": 0,\n \"Technic\": 0,\n \"Speed\": 0,\n \"HitChance\": 0,\n \"Crit\": 0,\n \"DodgeChance\": 0,\n \"DebuffEfficiency\": 0,\n \"ResPhys\": 0,\n \"ResChem\": 0,\n \"ResThermo\": 0,\n \"Heal\": 0,\n \"Power\": 0\n }\n\n\nclass EquipmentCommon(EquipmentBase):\n def __init__(self, key, rarity, name=\"None\", mod_list=[]):\n EquipmentBase.__init__(self, key, name)\n self.rarity = EquipmentRarity(rarity)\n self.mod_list = mod_list\n self.rand_amount = 0\n self.rand_stat_distr = {}\n\n self.get_nonunique_item_stats()\n\n def get_nonunique_item_stats(self):\n\n self.get_common_equip_base_stats()\n self.get_mod_bonus_stats()\n\n def get_mod_bonus_stats(self):\n rand_amount = 0\n for m in self.mod_list:\n for key, value in m.bonus_dict.items():\n if key != \"Random\":\n self.stat_bonuses[key] += int(value)\n else:\n rand_amount += int(value)\n self.rand_amount = rand_amount\n\n def get_common_equip_base_stats(self):\n stat_source = csv.DictReader(open(BaseStats.ITEM_COMMON_BASES_CSV))\n for row in stat_source:\n if row[\"Key\"] == self.key:\n # Ключ предмета, должен совпадать с одним из ключей в таблице EquipmentCommon\n # Мы смотрим, что по табличным значениям предмет действительно дает бонус к статам сам по себе\n # И если да, то увеличиваем этот бонус учитывая рарность\n if row[\"BonusType1\"] != \"None\" and int(row[\"BonusAmount1\"]) != 0:\n self.stat_bonuses[row[\"BonusType1\"]] += floor(int(row[\"BonusAmount1\"]) * self.rarity.multi_stats)\n if row[\"BonusType2\"] != \"None\" and int(row[\"BonusAmount2\"]) != 0:\n self.stat_bonuses[row[\"BonusType2\"]] += floor(int(row[\"BonusAmount2\"]) * self.rarity.multi_stats)\n # Так как power задается в отдельном столбце и со своим модификатором, его мы добавляем отдельно.\n if int(row[\"Power\"]) != 0:\n self.stat_bonuses[\"Power\"] = int(row[\"Power\"]) * self.rarity.multi_power\n self.type = row[\"Type\"]\n self.slot = row[\"Slot\"]\n\n\nclass EquipmentRarity(object):\n def __init__(self, key):\n self.key = key\n source = csv.DictReader(open(BaseStats.ITEM_RARITY_COEF_CSV))\n for row in source:\n if len(row[\"Rarity\"]) == 0:\n continue\n elif self.key == row[\"Rarity\"]:\n self.multi_power = float(row[\"MultiPower\"])\n self.multi_stats = float(row[\"MultiStats\"])\n self.multi_salvage = float(row[\"MultiSalvage\"])\n\n\nclass EquipmentUnique(EquipmentBase):\n\n def __init__(self, key, name=\"None\"):\n self.key = key\n EquipmentBase.__init__(self, key, name)\n meta_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_KEYS))\n for row in meta_source:\n if row[\"Key\"] == self.key and row[\"Rarity\"] in BaseStats.RARITY_LIST:\n self.rarity = row[\"Rarity\"]\n else:\n raise Exception(\"Unique item {} dosen't have apropriate rarity \".format(self.key))\n self.get_unique_equip_stats()\n\n def get_unique_equip_stats(self):\n stat_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_STATS_CSV))\n for row in stat_source:\n if row[\"Key\"] == self.key:\n self.stat_bonuses[row[\"BonusType\"]] += int(row[\"BonusAmount\"])\n\n meta_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_KEYS))\n for row in meta_source:\n if row[\"Key\"] == self.key:\n self.type = row[\"Type\"]\n self.slot = row[\"Slot\"]\n\n\nclass EquipmentUtility:\n @staticmethod\n def check_weapon_type(merc, weapon):\n check = False\n if weapon.type == merc.mercenary_class.merc_weapon_type:\n check = True\n return check\n\n\n","repo_name":"Tapkevich/Posscam-CC","sub_path":"Equipment.py","file_name":"Equipment.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1534234634","text":"class Ciudad:\n \"\"\"\"Clase para representar una ciudad.\n \n Atributos de clase:\n nombre -- El nombre de la ciudad.\n \n latitud -- Latitud de las coordenadas que determinan la ubicación \n de la ciudad.\n \n longitud -- Longitud de las coordenadas que determinan la ubicación \n de la ciudad.\n \"\"\"\n\n def __init__(self, datos):\n \"\"\"Constructor de una ciudad que inicializa sus atributos con los \n datos recibe.\n \n Parámetros:\n \n datos (dict) -- Información de una ciudad. Contiene las llaves\n \"name\" y \"coord\", cuyos valores son el nombre y las coordebadas\n de la ciudad respectivamente. Las coordenadas estarán dadas \n como un diccionario, en el cual sus claves serán \"lat\" y \n \"lon\" y sus respectivos valores la latitud y longitud de la \n ciudad. \n \"\"\"\n self.nombre = datos[\"name\"]\n self.latitud = datos[\"coord\"][\"lat\"]\n self.longitud = datos[\"coord\"][\"lon\"]\n\n def to_string(self):\n \"\"\"Representa en cadena a una ciudad, un atributo por linea.\n \n Regresa:\n \n cadena (Str) -- La representación de la ciudad.\n \"\"\"\n cadena = (\"Ciudad: {0}\\n\" +\n \"Coordenas:\\n\" + \n \" -Latitud: {1}°\\n\" +\n \" -Longitud: {2}°\\n\").format(\n self.nombre, self.latitud,self.longitud)\n return cadena \n ","repo_name":"alexiscoca/Web-Service","sub_path":"src/clima/Ciudad.py","file_name":"Ciudad.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"19792714626","text":"#!/usr/bin/env python3\nimport logging\nimport time\n\nimport boto3\nimport retrying\n\nfrom test_util.helpers import Host, retry_boto_rate_limits, SshInfo\n\nLOGGING_FORMAT = '[%(asctime)s|%(name)s|%(levelname)s]: %(message)s'\nlogging.basicConfig(format=LOGGING_FORMAT, level=logging.DEBUG)\n# AWS verbosity in debug mode overwhelms meaningful logging\nlogging.getLogger('botocore').setLevel(logging.INFO)\nlog = logging.getLogger(__name__)\n\nVPC_TEMPLATE_URL = 'https://s3.amazonaws.com/vpc-cluster-template/vpc-cluster-template.json'\nVPC_EBS_ONLY_TEMPLATE_URL = 'https://s3.amazonaws.com/vpc-cluster-template/vpc-ebs-only-cluster-template.json'\n\n\ndef template_by_instance_type(instance_type):\n if instance_type.split('.')[0] in ('c4', 't2', 'm4'):\n return VPC_EBS_ONLY_TEMPLATE_URL\n else:\n return VPC_TEMPLATE_URL\n\n\n@retry_boto_rate_limits\ndef instances_to_hosts(instances):\n return [Host(i.private_ip_address, i.public_ip_address) for i in instances]\n\n\nclass BotoWrapper():\n def __init__(self, region, aws_access_key_id, aws_secret_access_key):\n self.region = region\n self.session = boto3.session.Session(\n aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)\n\n def client(self, name):\n return self.session.client(service_name=name, region_name=self.region)\n\n def resource(self, name):\n return self.session.resource(service_name=name, region_name=self.region)\n\n def create_key_pair(self, key_name):\n \"\"\"Retruns private key of newly generated pair\n \"\"\"\n key = self.resource('ec2').KeyPair(key_name)\n return key.key_material\n\n def delete_key_pair(self, key_name):\n self.resource('ec2').KeyPair(key_name).delete()\n\n def create_stack(self, name, template_url, user_parameters, deploy_timeout=60):\n \"\"\"Returns boto stack object\n \"\"\"\n log.info('Requesting AWS CloudFormation...')\n cf_parameters = []\n for k, v in user_parameters.items():\n cf_parameters.append({'ParameterKey': k, 'ParameterValue': v})\n self.resource('cloudformation').create_stack(\n StackName=name,\n TemplateURL=template_url,\n DisableRollback=True,\n TimeoutInMinutes=deploy_timeout,\n Capabilities=['CAPABILITY_IAM'],\n Parameters=cf_parameters)\n return CfStack(name, self)\n\n\nclass CfStack():\n def __init__(self, stack_name, boto_wrapper):\n self.boto_wrapper = boto_wrapper\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(stack_name)\n self._host_cache = {}\n\n def wait_for_status_change(self, state_1, state_2, wait_before_poll_min, timeout=60 * 60):\n \"\"\"\n Note: Do not use unwrapped boto waiter class, it has very poor error handling\n\n Stacks can have one of the following statuses. See:\n http://boto3.readthedocs.io/en/latest/reference/\n services/cloudformation.html#CloudFormation.Client.describe_stacks\n\n CREATE_IN_PROGRESS, CREATE_FAILED, CREATE_COMPLETE\n ROLLBACK_IN_PROGRESS, ROLLBACK_FAILED, ROLLBACK_COMPLETE\n DELETE_IN_PROGRESS, DELETE_FAILED, DELETE_COMPLETE\n UPDATE_IN_PROGRESS, UPDATE_COMPLETE_CLEANUP_IN_PROGRESS\n UPDATE_COMPLETE, UPDATE_ROLLBACK_IN_PROGRESS\n UPDATE_ROLLBACK_FAILED, UPDATE_ROLLBACK_COMPLETE\n UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS\n \"\"\"\n log.info('Waiting for status to change from {} to {}'.format(state_1, state_2))\n log.info('Sleeping for {} minutes before polling'.format(wait_before_poll_min))\n time.sleep(60 * wait_before_poll_min)\n\n @retrying.retry(wait_fixed=10 * 1000,\n stop_max_delay=timeout * 1000,\n retry_on_result=lambda res: res is False,\n retry_on_exception=lambda ex: False)\n def wait_loop():\n stack_details = self.get_stack_details()\n stack_status = stack_details['StackStatus']\n if stack_status == state_2:\n return True\n if stack_status != state_1:\n log.error('Stack Details: {}'.format(stack_details))\n for event in self.get_stack_events():\n log.error('Stack Events: {}'.format(event))\n raise Exception('StackStatus changed unexpectedly to: {}'.format(stack_status))\n return False\n wait_loop()\n\n @retry_boto_rate_limits\n def get_stack_details(self):\n log.debug('Requesting stack details')\n return self.boto_wrapper.client('cloudformation').describe_stacks(\n StackName=self.stack.stack_id)['Stacks'][0]\n\n @retry_boto_rate_limits\n def get_stack_events(self):\n log.debug('Requesting stack events')\n return self.boto_wrapper.client('cloudformation').describe_stack_events(\n StackName=self.stack.stack_id)['StackEvents']\n\n def wait_for_stack_creation(self, wait_before_poll_min=3):\n self.wait_for_status_change('CREATE_IN_PROGRESS', 'CREATE_COMPLETE', wait_before_poll_min)\n\n def wait_for_stack_deletion(self, wait_before_poll_min=3):\n self.wait_for_status_change('DELETE_IN_PROGRESS', 'DELETE_COMPLETE', wait_before_poll_min)\n\n def get_parameter(self, param):\n \"\"\"Returns param if in stack parameters, else returns None\n \"\"\"\n for p in self.stack.parameters:\n if p['ParameterKey'] == param:\n return p['ParameterValue']\n raise KeyError('Key not found in template parameters: {}. Parameters: {}'.\n format(param, self.stack.parameters))\n\n @retry_boto_rate_limits\n def get_auto_scaling_instances(self, logical_id):\n \"\"\" Get instances in ASG with logical_id. If logical_id is None, all ASGs will be used\n Will return instance objects as describd here:\n http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#instance\n\n Note: there is no ASG resource hence the need for this method\n \"\"\"\n ec2 = self.boto_wrapper.resource('ec2')\n return [ec2.Instance(i['InstanceId']) for asg in self.boto_wrapper.client('autoscaling').\n describe_auto_scaling_groups(\n AutoScalingGroupNames=[self.stack.Resource(logical_id).physical_resource_id])\n ['AutoScalingGroups'] for i in asg['Instances']]\n\n def get_hosts_cached(self, group_name, refresh=False):\n if refresh or group_name not in self._host_cache:\n host_list = instances_to_hosts(self.get_auto_scaling_instances(group_name))\n self._host_cache[group_name] = host_list\n return host_list\n return self._host_cache[group_name]\n\n\nclass DcosCfSimple(CfStack):\n @classmethod\n def create(cls, stack_name, template_url, public_agents, private_agents,\n admin_location, key_pair_name, boto_wrapper):\n parameters = {\n 'KeyName': key_pair_name,\n 'AdminLocation': admin_location,\n 'PublicSlaveInstanceCount': str(public_agents),\n 'SlaveInstanceCount': str(private_agents)}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n # Use stack_name as the binding identifier. At time of implementation,\n # stack.stack_name returns stack_id if Stack was created with ID\n return cls(stack.stack.stack_name, boto_wrapper), SSH_INFO['coreos']\n\n def delete(self):\n log.info('Starting deletion of CF stack')\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n self.stack.delete()\n self.empty_and_delete_s3_bucket_from_stack()\n\n def empty_and_delete_s3_bucket_from_stack(self):\n bucket_id = self.stack.Resource('ExhibitorS3Bucket').physical_resource_id\n s3 = self.boto_wrapper.resource('s3')\n bucket = s3.Bucket(bucket_id)\n log.info('Starting bucket {} deletion'.format(bucket))\n all_objects = bucket.objects.all()\n obj_count = len(list(all_objects))\n if obj_count > 0:\n assert obj_count == 1, 'Expected one object in Exhibitor S3 bucket but found: ' + str(obj_count)\n exhibitor_object = list(all_objects)[0]\n log.info('Trying to delete object from bucket: {}'.format(repr(exhibitor_object)))\n exhibitor_object.delete()\n log.info('Trying deleting bucket {} itself'.format(bucket))\n bucket.delete()\n log.info('Delete successfully triggered for {}'.format(self.stack.stack_name))\n\n def get_master_ips(self, refresh=False):\n return self.get_hosts_cached('MasterServerGroup', refresh=refresh)\n\n def get_public_agent_ips(self, refresh=False):\n return self.get_hosts_cached('PublicSlaveServerGroup', refresh=refresh)\n\n def get_private_agent_ips(self, refresh=False):\n return self.get_hosts_cached('SlaveServerGroup', refresh=refresh)\n\n\nclass DcosCfAdvanced(CfStack):\n @classmethod\n def create(cls, stack_name, boto_wrapper, template_url,\n public_agents, private_agents, key_pair_name,\n private_agent_type, public_agent_type, master_type,\n vpc_cidr='10.0.0.0/16', public_subnet_cidr='10.0.128.0/20',\n private_subnet_cidr='10.0.0.0/17',\n gateway=None, vpc=None, private_subnet=None, public_subnet=None):\n ec2 = boto_wrapper.client('ec2')\n if not vpc:\n log.info('Creating new VPC...')\n vpc = ec2.create_vpc(CidrBlock=vpc_cidr, InstanceTenancy='default')['Vpc']['VpcId']\n ec2.get_waiter('vpc_available').wait(VpcIds=[vpc])\n ec2.create_tags(Resources=[vpc], Tags=[{'Key': 'Name', 'Value': stack_name}])\n log.info('Using VPC with ID: ' + vpc)\n\n if not gateway:\n log.info('Creating new InternetGateway...')\n gateway = ec2.create_internet_gateway()['InternetGateway']['InternetGatewayId']\n ec2.attach_internet_gateway(InternetGatewayId=gateway, VpcId=vpc)\n ec2.create_tags(Resources=[gateway], Tags=[{'Key': 'Name', 'Value': stack_name}])\n log.info('Using InternetGateway with ID: ' + gateway)\n\n if not private_subnet:\n log.info('Creating new PrivateSubnet...')\n private_subnet = ec2.create_subnet(VpcId=vpc, CidrBlock=private_subnet_cidr)['Subnet']['SubnetId']\n ec2.create_tags(Resources=[private_subnet], Tags=[{'Key': 'Name', 'Value': stack_name + '-private'}])\n ec2.get_waiter('subnet_available').wait(SubnetIds=[private_subnet])\n log.info('Using PrivateSubnet with ID: ' + private_subnet)\n\n if not public_subnet:\n log.info('Creating new PublicSubnet...')\n public_subnet = ec2.create_subnet(VpcId=vpc, CidrBlock=public_subnet_cidr)['Subnet']['SubnetId']\n ec2.create_tags(Resources=[public_subnet], Tags=[{'Key': 'Name', 'Value': stack_name + '-public'}])\n ec2.get_waiter('subnet_available').wait(SubnetIds=[public_subnet])\n log.info('Using PublicSubnet with ID: ' + public_subnet)\n\n parameters = {\n 'KeyName': key_pair_name,\n 'Vpc': vpc,\n 'InternetGateway': gateway,\n 'MasterInstanceType': master_type,\n 'PublicAgentInstanceCount': str(public_agents),\n 'PublicAgentInstanceType': public_agent_type,\n 'PublicSubnet': public_subnet,\n 'PrivateAgentInstanceCount': str(private_agents),\n 'PrivateAgentInstanceType': private_agent_type,\n 'PrivateSubnet': private_subnet}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n try:\n os_string = template_url.split('/')[-1].split('.')[-2].split('-')[0]\n ssh_info = CF_OS_SSH_INFO[os_string]\n except (KeyError, IndexError):\n log.exception('Unexpected template URL: {}'.format(template_url))\n if os_string:\n log.exception('No SSH info for OS string: {}'.format(os_string))\n raise\n return cls(stack.stack.stack_name, boto_wrapper), ssh_info\n\n def delete(self, delete_vpc=False):\n log.info('Starting deletion of CF Advanced stack')\n vpc_id = self.get_parameter('Vpc')\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n log.info('Deleting Infrastructure Stack')\n infrastack = DcosCfSimple(self.get_resource_stack('Infrastructure').stack.stack_id, self.boto_wrapper)\n infrastack.delete()\n log.info('Deleting Master Stack')\n self.get_resource_stack('MasterStack').stack.delete()\n log.info('Deleting Private Agent Stack')\n self.get_resource_stack('PrivateAgentStack').stack.delete()\n log.info('Deleting Public Agent Stack')\n self.get_resource_stack('PublicAgentStack').stack.delete()\n self.stack.delete()\n if delete_vpc:\n self.wait_for_stack_deletion()\n self.boto_wrapper.resource('ec2').Vpc(vpc_id).delete()\n\n def get_master_ips(self, refresh=False):\n return self.get_resource_stack('MasterStack').get_hosts_cached('MasterServerGroup', refresh=refresh)\n\n def get_private_agent_ips(self, refresh=False):\n return self.get_resource_stack('PrivateAgentStack').get_hosts_cached('PrivateAgentServerGroup', refresh=refresh)\n\n def get_public_agent_ips(self, refresh=False):\n return self.get_resource_stack('PublicAgentStack').get_hosts_cached('PublicAgentServerGroup', refresh=refresh)\n\n def get_resource_stack(self, resource_name):\n \"\"\"Returns a CfStack for a given resource\n \"\"\"\n return CfStack(self.stack.Resource(resource_name).physical_resource_id, self.boto_wrapper)\n\n\nclass VpcCfStack(CfStack):\n @classmethod\n def create(cls, stack_name, instance_type, instance_os, instance_count,\n admin_location, key_pair_name, boto_wrapper):\n ami_code = OS_AMIS[instance_os][boto_wrapper.region]\n template_url = template_by_instance_type(instance_type)\n parameters = {\n 'KeyPair': key_pair_name,\n 'AllowAccessFrom': admin_location,\n 'ClusterSize': str(instance_count),\n 'InstanceType': str(instance_type),\n 'AmiCode': ami_code}\n stack = boto_wrapper.create_stack(stack_name, template_url, parameters)\n return cls(stack.stack.stack_name, boto_wrapper), OS_SSH_INFO[instance_os]\n\n def delete(self):\n # boto stacks become unusable after deletion (e.g. status/info checks) if name-based\n self.stack = self.boto_wrapper.resource('cloudformation').Stack(self.stack.stack_id)\n self.stack.delete()\n\n def get_vpc_host_ips(self):\n # the vpc templates use the misleading name CentOSServerAutoScale for all deployments\n # https://mesosphere.atlassian.net/browse/DCOS-11534\n return self.get_hosts_cached('CentOSServerAutoScale')\n\n\nSSH_INFO = {\n 'centos': SshInfo(\n user='centos',\n home_dir='/home/centos',\n ),\n 'coreos': SshInfo(\n user='core',\n home_dir='/home/core',\n ),\n 'debian': SshInfo(\n user='admin',\n home_dir='/home/admin',\n ),\n 'rhel': SshInfo(\n user='ec2-user',\n home_dir='/home/ec2-user',\n ),\n 'ubuntu': SshInfo(\n user='ubuntu',\n home_dir='/home/ubuntu',\n ),\n}\n\n\nOS_SSH_INFO = {\n 'cent-os-7': SSH_INFO['centos'],\n 'cent-os-7-dcos-prereqs': SSH_INFO['centos'],\n 'coreos': SSH_INFO['coreos'],\n 'debian-8': SSH_INFO['debian'],\n 'rhel-7': SSH_INFO['rhel'],\n 'ubuntu-16-04': SSH_INFO['ubuntu'],\n}\n\nCF_OS_SSH_INFO = {\n 'el7': SSH_INFO['centos'],\n 'coreos': SSH_INFO['coreos']\n}\n\n\nOS_AMIS = {\n 'cent-os-7': {'ap-northeast-1': 'ami-965345f8',\n 'ap-southeast-1': 'ami-332de750',\n 'ap-southeast-2': 'ami-c80320ab',\n 'eu-central-1': 'ami-1548ae7a',\n 'eu-west-1': 'ami-2ea92f5d',\n 'sa-east-1': 'ami-2921ad45',\n 'us-east-1': 'ami-fa9b9390',\n 'us-west-1': 'ami-12b3ce72',\n 'us-west-2': 'ami-edf11b8d'},\n 'cent-os-7-dcos-prereqs': {'ap-northeast-1': 'ami-965345f8',\n 'ap-southeast-1': 'ami-332de750',\n 'ap-southeast-2': 'ami-c80320ab',\n 'eu-central-1': 'ami-1548ae7a',\n 'eu-west-1': 'ami-2ea92f5d',\n 'sa-east-1': 'ami-2921ad45',\n 'us-east-1': 'ami-fa9b9390',\n 'us-west-1': 'ami-12b3ce72',\n 'us-west-2': 'ami-edf11b8d'},\n 'coreos': {'ap-northeast-1': 'ami-84e0c7ea',\n 'ap-southeast-1': 'ami-84e0c7ea',\n 'ap-southeast-2': 'ami-f35b0590',\n 'eu-central-1': 'ami-fdd4c791',\n 'eu-west-1': 'ami-55d20b26',\n 'sa-east-1': 'ami-f35b0590',\n 'us-east-1': 'ami-37bdc15d',\n 'us-west-1': 'ami-27553a47',\n 'us-west-2': 'ami-00ebfc61'},\n 'debian-8': {'ap-northeast-1': 'ami-fe54f3fe',\n 'ap-southeast-1': 'ami-60989c32',\n 'ap-southeast-2': 'ami-07e3993d',\n 'eu-central-1': 'ami-b092aaad',\n 'eu-west-1': 'ami-0ed89d79',\n 'sa-east-1': 'ami-a5bd3fb8',\n 'us-east-1': 'ami-8b9a63e0',\n 'us-west-1': 'ami-a5d621e1',\n 'us-west-2': 'ami-3d56520d'},\n 'rhel-7': {'ap-northeast-1': 'ami-35556534',\n 'ap-southeast-1': 'ami-941031c6',\n 'ap-southeast-2': 'ami-83e08db9',\n 'eu-central-1': 'ami-e25e6cff',\n 'eu-west-1': 'ami-8cff51fb',\n 'sa-east-1': 'ami-595ce844',\n 'us-east-1': 'ami-a8d369c0',\n 'us-west-1': 'ami-33cdd876',\n 'us-west-2': 'ami-99bef1a9'},\n 'ubuntu-16-04': {'ap-northeast-1': 'ami-0919cd68',\n 'ap-southeast-1': 'ami-42934921',\n 'ap-southeast-2': 'ami-623c0d01',\n 'eu-central-1': 'ami-a9a557c6',\n 'eu-west-1': 'ami-643d4217',\n 'sa-east-1': 'ami-60bd2d0c',\n 'us-east-1': 'ami-2ef48339',\n 'us-west-1': 'ami-a9a8e4c9',\n 'us-west-2': 'ami-746aba14'}\n}\n","repo_name":"samchiang/DC-OS","sub_path":"test_util/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":18673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23683920594","text":"# repeat loops and lists\n'''\n# write a message on the screen 4 times \nfor palavra in range(1,4):\n print('carregando')\n \n'''\n\n'''\n# range(1,20) vai de 1 a 19\nfor item in range(1,20):\n print('billy')\n'''\n\n'''\n# range (2,12,2) vai de 2 a 10 de dois em dois, 2-4-6-8-10\nfor item in range(2,12,2):\n print(item)\n '''\n\n\n'''\n #write a program that write the users name and age the same amount of times as the age of the user. (random ideas)\n \nnome_pessoa = input('Your name:')\nidade = input('Your age?')\nfor item in range(1,int(idade)):\n print(idade)\nfor item in range(1,int(idade)):\n print(nome_pessoa)\n'''\n\n'''\n#write a names list\nnames = ['Joao','Jose','Maria','Conceicao']\nfor names in names:\n print(names)\n# escreva um programa que recebe uma lista de nomes e printa eles na tela\nnames = input('Escreva os nomes seguido de espaco')\nfor item in names:\n print(names)\n'''\n\n# Print values from 1 to N (n being the variable input by the user)\nuser_value = int(input('Insert a number: '))\nstart_value = 1\nuser_value = user_value + 1\nfor start_value in range(start_value,user_value):\n print(start_value)","repo_name":"gustavosrios/Studies.beginner","sub_path":"printobjects.py","file_name":"printobjects.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"20690268096","text":"#!/usr/bin/env python \n\nimport sys\n\nimport numpy\nimport pylab\n#import matplotlib\n#YLIM = 2\nYLIM = None\n\ntry:\n if sys.argv[2] != None:\n only_slips = True\nexcept:\n only_slips = False\n\nfilename = sys.argv[1]\n\ndata = open(filename).readlines()\nheaders = data[0][1:].split('\\t')\ndata = numpy.loadtxt(filename)\n\nnum_rows, num_columns = data.shape\nseconds = data[:,0]\n#print num_columns\n\npylab.figure()\nfor i in range(1,num_columns):\n if only_slips:\n if i != 5:\n continue\n column = data[:,i]\n #color = matplotlib.cm.jet((num_columns-float(i)) / (num_columns-1))\n pylab.plot(seconds, column,\n '.-',\n #color=color,\n label=headers[i])\n\nif YLIM is not None:\n pylab.ylim([-YLIM,YLIM])\npylab.legend(loc=2)\npylab.title(filename)\npylab.show()\n\n\n\n","repo_name":"gperciva/artifastring","sub_path":"research/visualize_string_debug.py","file_name":"visualize_string_debug.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"52"}
+{"seq_id":"5136588655","text":"from decorators import api_company_req, api_sensor_req, token_required\nimport os, jwt, bcrypt, datetime, logging, json\nfrom flask import Flask, Blueprint, request, jsonify, g, session, make_response\nfrom functools import wraps\nfrom app import app\nfrom Connect import connection\nfrom flask_cors import CORS, cross_origin\nfrom uuid import uuid4\n# make route to insert in company table with protected route in token_required\nCORS(app)\n\n@app.route(\"/create_company\", methods=[\"POST\"])\n@token_required\ndef insert_company(current_user):\n company_name = request.json['company_name']\n # insert data in the company table\n # token = request.headers.get('x-access-tokens')\n # hay que usar el token del usuario para api_key\n company_api_key = str(uuid4())\n \n conn = connection()\n \n # requerir company_name\n if not company_name:\n return jsonify({\"message\": \"company_name is required\"}), 400\n \n if conn.execute(\"SELECT * FROM Company WHERE company_name = ?\", (company_name,)).fetchone() is not None:\n return jsonify({\"message\": \"Company already exists\"}), 400\n \n if conn.execute(\"SELECT * FROM Company WHERE company_api_key = ?\", (company_api_key,)).fetchone() is not None:\n return jsonify({\"message\": \"Company already exists\"}), 400\n \n sql = \"INSERT INTO Company (company_name, company_api_key) VALUES (?, ?)\"\n conn.execute(sql, (company_name, company_api_key))\n conn.commit()\n conn.close()\n return jsonify({\n \"company_name\": company_name,\n \"company_api_key\": company_api_key\n })\n\n\n@app.route(\"/get_company\", methods=[\"GET\"])\ndef get_company():\n # get all data from company table\n sql = \"SELECT * FROM Company\"\n conn = connection()\n rv = conn.execute(sql)\n rows = rv.fetchall()\n conn.close()\n Companies = []\n for i in rows:\n get_Admin = {}\n get_Admin[\"ID\"] = i[\"ID\"]\n get_Admin[\"company_name\"] = i[\"company_name\"]\n get_Admin[\"company_api_key\"] = i[\"company_api_key\"]\n Companies.append(get_Admin)\n return jsonify(Companies)\n\n\n@app.route(\"/login_company\", methods=[\"POST\"])\ndef login_company():\n # auth from the body of the request\n auth = request.authorization\n if not auth or not auth.username or not auth.password:\n return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: \"login required\"'})\n \n sql = \"SELECT * FROM Admin\"\n conn = connection()\n rv = conn.execute(sql)\n rows = rv.fetchall()\n conn.close()\n for i in rows:\n user = i \n if user[\"Password\"] == auth.password: \n token = jwt.encode({'user': user[\"Username\"]}, \"un_secreto\", algorithm='HS256') \n return jsonify({'token' : token}) \n \n return make_response('could not verify', 401, {'WWW.Authentication': 'Basic realm: \"login required\"'})\n\n\n@app.route(\"/protected2\", methods=[\"GET\"])\n@token_required\ndef protected2(current_user):\n return jsonify({\"message\":f\"Hello {current_user['username']}\"})\n","repo_name":"Joacker/T3-Arquitecturas-Emergentes","sub_path":"app/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70896795684","text":"# -*- coding: UTF-8 -*-\n# Objective-C 语法定义\n\nimport random\nimport math\n\n# 超类UIButton\nSUPERS = ('NSObject', 'UIViewController', 'UINavigationController',\n 'UIView', 'UIImageView', 'UIScrollView', 'UIWindow',\n 'UITextField', 'UIButton', 'UILabel', 'UIImage',\n 'UIPanGestureRecognizer', 'UITapGestureRecognizer', 'UIColor',\n 'CAAnimationGroup', 'CAShapeLayer')\n# 换行符号\nSN = '\\r\\n'\n# 缩进符号\ndef ST(indent=0):\n if (indent == 0):\n return ''\n t = ''\n for i in range(indent):\n t += '\\t'\n return t\n\n# OC语句树\nclass JOcLineTree:\n def __init__(self, mMethod):\n self.mMethod = mMethod #所属函数\n self.statements = [] #语句块\n\n # 字符串化\n def toString(self, indent = 0):\n s = ''\n for b in self.statements:\n if (isinstance(b, JOcLineTree)):\n s += b.toString(indent + 1)\n else:\n s += ST(indent) + b + SN\n return s\n\n\n# OC函数\nclass JOcMethod:\n def __init__(self, mClass):\n self.mClass = mClass # 属类\n self.scope = None # 类函数或对象函数 ('+', '-')\n self.ret = None # 返回数据类型 (NSString*, NSInteger, int, short, long)\n self.messages = [] # 指令元组\n self.argTypes = None # 参数类型数组\n self.argNames = None # 参数名称数组\n self.lineTree = None # 语句树 (JOcLineTree)\n self.variables = None # 局部变量列表\n\n # 函数定义复制\n def copyDef(self, tClass=None):\n meth = JOcMethod(tClass)\n meth.scope = self.scope\n meth.ret = self.ret\n meth.messages = self.messages[:]\n if (self.argTypes is not None):\n meth.argTypes = self.argTypes[:]\n if (self.argNames is not None):\n meth.argNames = self.argNames[:]\n return meth\n\n # 声明字符串化\n def toStringInterface(self, indent=0):\n # header\n s = self.scope + ' (' + self.ret + ') '\n # selector\n l = self.messages.__len__()\n for i in range(l):\n s += self.messages[i]\n if (self.argTypes is not None):\n s += ':(' + self.argTypes[i] + ')' + self.argNames[i]\n s += ' '\n return s\n\n # 实现字符串化\n def toStringImplement(self, indent=0):\n s = self.toStringInterface(indent)\n # logic\n s += '{' + SN\n # varialbe\n var_map = self.variables\n if (var_map is not None) and (len(var_map) > 0):\n for n in var_map:\n v = var_map[n]\n s += ST(indent + 1) + v[0] + ' ' + n\n if (v[1] is None):\n s += ';' + SN\n else:\n s += ' = ' + str(v[1]) + ';' + SN\n if (self.lineTree is not None):\n s += self.lineTree.toString(indent + 1)\n s += '}' + SN\n return s\n\n# OC类\nclass JOcClass:\n def __init__(self, className, baseClass=None, protocol=None):\n self.baseClass = baseClass # 父类\n self.protocol = protocol # 接口\n self.className = className # 类名\n self.imports = None # 导入头文件\n self.variables = None # 变量元组\n self.methods = None # 函数数组\n self.fileSuffix = '.m' # 文件后缀(.m, .mm),默认是:.m\n\n # # 设置接口\n # def __setProtocol(self, protocol):\n # if (self.methods is None):\n # self.methods = []\n # functions = protocol.requireds\n # if (functions is not None):\n # for meth in functions:\n # self.methods.append( meth.copyDef(self.mClass) )\n # functions = protocol.optionals\n # if (functions is not None):\n # for meth in functions:\n # self.methods.append( meth.copyDef(self.mClass) )\n\n # 头文件串化\n def toStringInterface(self, indent=0):\n s = ''\n # header\n s += ST(indent) + '@interface' + ' ' + self.className + ' : '\n # super class\n if (self.baseClass is not None):\n s += self.baseClass\n else:\n s += SUPERS[int(math.pow(random.random(), 3) * len(SUPERS))]\n # protocol\n if (self.protocol is not None):\n s += ' ' + '<' + self.protocol + '>' + SN\n else:\n s += SN\n # method\n s += SN\n if (self.methods is not None):\n for m in self.methods:\n s += ST(indent) + m.toStringInterface(indent) + ';' + SN + SN\n s += ST(indent) + '@end'\n return s\n\n # 实现文件串化\n def toStringImplement(self, indent=0):\n s = ''\n # import\n s += ST(indent) + '#import \"' + self.className + '.h\"' + SN\n if (self.imports is not None):\n for head in self.imports:\n if head.startswith('<') and head.endswith('>'):\n s += ST(indent) + '#import ' + head + SN\n else:\n s += ST(indent) + '#import \"' + head + '\"' + SN\n s += SN\n # header\n s += ST(indent) + '@implementation' + ' ' + self.className\n # varialbe\n var_map = self.variables\n if (var_map is not None) and (len(var_map) > 0):\n s += ' ' + '{' + SN\n for n in var_map:\n t = var_map[n]\n s += ST(indent + 1) + t[0] + ' ' + n + ';' + SN\n # if (t[1] is None):\n # s += ';' + SN\n # else:\n # s += ' = ' + str(t[1]) + ';' + SN\n s += ST(indent) + '}' + SN\n else:\n s += SN\n # method\n s += SN\n if (self.methods is not None):\n for m in self.methods:\n s += ST(indent) + m.toStringImplement(indent) + SN + SN\n s += ST(indent) + '@end'\n return s\n\n\n# OC接口\n# class JOcProtocol:\n# def __init__(self):\n# self.protocolName = None # 接口名称\n# self.imports = None # 导入头文件\n# self.requireds = None # 必须的函数数组\n# self.optionals = None # 可选的函数数组\n#\n# # 字符串化\n# def toString(self, indent = 0):\n# s = ''\n# # import\n# if (self.imports is not None):\n# for head in self.imports:\n# s += ST(indent) + head + SN\n# # class name\n# s += SN\n# s += ST(indent) + '@protocol' + ' ' + self.protocolName + SN\n# # interface\n# if (self.requireds is not None):\n# s += ST(indent) + '@required' + SN\n# for meth in self.requireds:\n# s += ST(indent) + meth.toStringInterface() + ';' + SN + SN\n# if (self.optionals is not None):\n# s += ST(indent) + '@optional' + SN\n# for meth in self.optionals:\n# s += ST(indent) + meth.toStringInterface() + ';' + SN + SN\n# s += ST(indent) + '@end'\n# return s","repo_name":"JoliChen/py-tool","sub_path":"easy1/XcHelper/garbages/source/oc/OCGrammar.py","file_name":"OCGrammar.py","file_ext":"py","file_size_in_byte":7015,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"15948691086","text":"from bs4 import BeautifulSoup\nfrom urllib import request\nimport time\nfrom Poem import Poem\n\nclass PoemsCrawler():\n\n def __init__(self, url):\n self.url = url\n self.poem_urls = []\n self.poems_list = []\n\n def generateUrls(self):\n while (True):\n with request.urlopen(self.url) as response:\n pageSoup = BeautifulSoup(response.read(), 'html.parser')\n table_of_poems = pageSoup.find('table', attrs={'class': 'List'}) # Now I found the aimed table\n for tr in table_of_poems.find_all('tr'): # Now I should extract all urls pointed to peoms\n for td in tr.findAll('td'):\n self.poem_urls.append('http://www.chinapoesy.com/' + td.find('a').get('href')) # save all urls\n break\n print(\"Connection error came again, maybe you need to wait for 15s \")\n time.sleep(15) # if error merges, sleep, and access again\n\n def collectPoems(self):\n self.poem_urls.reverse()\n while(len(self.poem_urls) > 0):\n url = self.poem_urls.pop()\n with request.urlopen(url) as response:\n pageSoup = BeautifulSoup(response.read(), 'html.parser')\n\n # Extract poem's title\n head = pageSoup.find('title')\n head = head.text.strip().split('_')\n title = re.sub(r\"\\r\\n\", \"\", head[0]) # newline char may embed in title\n author = head[1][:-2] # exclude last two words\n # Extract poem's body\n script_tags = pageSoup.findAll('script', {'type': 'text/javascript'})\n body = script_tags[9].find_next('p')\n if len(body.text) < 20:\n body = script_tags[9].find_next('div')\n body = body.text # you shuld remove title and author\n self.poems_list.append(Poem(title, author, body))\n print(title, author)\n continue\n print(\"Connection error came again, maybe you need to wait for 15s \")\n time.sleep(15)\n self.poem_urls.append(url)\n'''\ndef test():\n pc = PoemsCrawler('http://www.chinapoesy.com/XianDaiList_1.html');\n pc.generateUrls()\n pc.collectPoems()\n for poem in pc.poems_list:\n print(poem.author)\n\ntest()\n'''","repo_name":"chibinjiang/PoetryRecommender","sub_path":"app/DataCollector/PoemsCrawler.py","file_name":"PoemsCrawler.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70064287846","text":"import pandas as pd\nimport numpy as np\nimport xgboost as xgb\nfrom flask import Flask, jsonify, request\nimport pickle\n\n# model\nmodel = pickle.load(open('model.pkl','rb'))\n\napp = Flask(__name__)\n\n@app.route('/', methods=['POST'])\n\ndef make_predict():\n #get data\n data = request.get_json(force=True)\n\n predict_request = [data['neighborhood'],\n data['room_type'],\n data['accommodates'],\n data['bedrooms'],\n data['number_of_reviews'],\n data['wifi'],\n data['cable_tv'],\n data['washer'],\n data['kitchen']]\n\n data.update((x, [y]) for x, y in data.items())\n data_df = pd.DataFrame.from_dict(data)\n\n # preds\n y_hat = model.predict(data_df) # this works for xgb\n\n # send back to browser\n output = {'y_hat': int(y_hat[0])}\n\n # return data\n return jsonify(results=output)\n\nif __name__ == '__main__':\n app.run(port = 9000, debug=True)\n\n","repo_name":"elizabethts/airbnb-optimize","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18836126421","text":"n=int(input())\na=list(map(int,input().split()))\nlow=0\nhigh=n-1\nwhile(low<=high):\n if(a[low]<0):\n low=low+1\n else:\n a[low],a[high]=a[high],a[low]\n high=high-1\nprint(a)","repo_name":"Tejas1510/Love-Babbar-Sheet","sub_path":"Array/moveAllNegativeLeft.py","file_name":"moveAllNegativeLeft.py","file_ext":"py","file_size_in_byte":193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"73796804645","text":"# 클래스 변수 ( static ? ) - Class 내 반드시 선언이 필요하다 ( ClassName.VarName )\n\n\nclass UserInfo:\n \"\"\"\n UserInfo Class\n Author : 홍길동\n Date : 2022-05-26\n Description : 클래스 작성법\n \"\"\"\n\n user_cnt = 0\n def __init__(self, author, date, description):\n self.author = author\n self.date = date\n self.description = description\n # Class 변수 ( Static ) : CLass 내 변수가 없는경우 에러 발생 ( AttributeError: type object 'UserInfo' has no attribute 'user_cnt' )\n UserInfo.user_cnt += 1\n\n def __str__(self):\n return \"Author : {}, Date : {}, Description : {}\".format(\n self.author, self.date, self.description\n )\n\n def __del__(self): # 객체 삭제 시 호출되는 메소드\n UserInfo.user_cnt -= 1\n\n\nuser1 = UserInfo(\"홍길동\", \"2022-05-26\", \"클래스 작성법\")\nprint(user1)\nuser2 = UserInfo(\"성춘향\", \"2022-03-23\", \"클래스 사용법\")\nprint(user2)\n\nprint(\"현재 생성된 User {} 명\".format(UserInfo.user_cnt))\n\ndel user1 # __del__ 호출 \n# print(user1) # NameError: name 'user1' is not defined. Did you mean: 'user2'?\nprint(user2)\nprint(\"현재 생성된 User {} 명\".format(UserInfo.user_cnt))\n","repo_name":"ycr5007/SolDesk","sub_path":"PythonSource/class/class3.py","file_name":"class3.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16858755841","text":"import time\nimport json\nimport numpy as np\n\n\nclass ASGF:\n \"\"\"Adaptive Stochastic Gradient-Free algorithm\"\"\"\n\n def __init__(self, s0=None, s_rate=.9, s_min=1e-03, s_max=1e+03,\\\n m_min=5, m_max=25, qtol=.1, quad_rule='gh',\\\n L_lmb=.9, lr_min=1e-03, lr_max=1e+03,\\\n A_grad=.1, A_dec=.95, A_inc=1.02,\\\n B_grad=.9, B_dec=.98, B_inc=1.01,\\\n restart=False, num_res=2, res_mlt=10, res_div=10, fun_req=-np.inf,\\\n xtol=1e-06, maxiter=1000):\n '''initialize class variables'''\n self.s0 = s0\n self.s_rate = s_rate\n self._s_min, self._s_max = s_min, s_max\n self.m_min, self.m_max = m_min, m_max\n self.qtol, self.quad_rule = qtol, quad_rule\n self.L_avg, self.L_lmb = 0, L_lmb\n self.lr_min, self.lr_max = lr_min, lr_max\n self.A_grad, self.B_grad = A_grad, B_grad\n self.A_dec, self.A_inc = A_dec, A_inc\n self.B_dec, self.B_inc = B_dec, B_inc\n self.restart = restart\n self.num_res = num_res\n self.res_mlt, self.res_div = res_mlt, res_div\n self.fun_req = fun_req\n self.update_rule = update_rule\n self.xtol = xtol\n self.maxiter = maxiter\n self.record_parameters()\n if self.quad_rule == 'gh':\n self.quad = self.gh_quad\n\n def optimization_init(self, fun, x0, subname):\n '''initialize optimization variables'''\n self.fun = fun\n self.x = np.array(x0)\n self.dim = self.x.size\n self.dx = np.zeros(self.dim)\n self.df = np.zeros(self.dim)\n self.lr = 0\n self.f = self.fun(self.x)\n self.itr, self.feval = 0, 1\n self.x_min, self.f_min = self.x, self.f\n self.reset_params()\n self.s_min = self.s / 1000 if self._s_min is None else self._s_min\n self.s_max = self.s * 1000 if self._s_max is None else self._s_max\n self.s_res = self.s\n self.converged = False\n self.subname = '' if subname is None else '_' + str(subname)\n self.record_iteration(log_mode='w')\n\n def generate_directions(self, vec=None):\n '''generate search directions'''\n if vec is None:\n self.u = np.random.randn(self.dim, self.dim)\n else:\n self.u = np.concatenate((vec.reshape((-1,1)),\\\n np.random.randn(self.dim, self.dim-1)), axis=1)\n self.u /= np.linalg.norm(self.u, axis=0)\n self.u = np.linalg.qr(self.u)[0].T\n\n def reset_params(self):\n '''set parameters to their initial values'''\n self.generate_directions()\n self.s = np.sqrt(self.dim) if self.s0 is None else self.s0\n self.s_status = '*'\n self.L, self.A, self.B = 0, self.A_grad, self.B_grad\n\n def minimize(self, fun, x0, subname=None):\n '''iteratively update minimizer'''\n self.optimization_init(fun, x0, subname)\n while (self.itr < self.maxiter) and not self.converged:\n # compute gradient and update minimizer\n self.compute_df()\n self.update_x()\n self.save_state()\n # update variables\n self.itr += 1\n self.update_parameters()\n self.record_iteration()\n\n def gh_quad(self, g, s, g0, mode='adaptive'):\n '''compute derivative via adaptive Gauss-Hermite quadrature'''\n dg_quad = np.array([np.inf])\n g_vals, p_vals, feval_gh = np.array([]), np.array([]), 0\n num_pts = range(max(3, self.m_min-2), self.m_max+1, 2)\\\n if mode == 'adaptive' else [self.m_min]\n # iteratively estimate smoothed derivative\n for m in num_pts:\n p, w = np.polynomial.hermite.hermgauss(m)\n g_val = np.array([g(p_i * s) for p_i in p[p != 0]])\n feval_gh += m - 1\n g_val = np.insert(g_val, *np.where(p == 0), g0)\n g_vals = np.append(g_vals, g_val)\n p_vals = np.append(p_vals, p)\n dg_quad = np.append(dg_quad, np.sum(w * p * g_val) / (s * np.sqrt(np.pi) / 2))\n # compute relative difference for gradient estimate\n qdelta = np.abs(dg_quad[:-1] - dg_quad[-1]) / (np.abs(dg_quad[-1]) + 1e-06)\n if np.amin(qdelta) < self.qtol:\n break\n p, p_ind = np.unique(p_vals, return_index=True)\n g_val = g_vals[p_ind]\n # estimate local Lipschitz constant\n L = np.amax(np.abs(g_val[1:] - g_val[:-1]) / (p[1:] - p[:-1]) / s)\n return dg_quad[-1], feval_gh, L\n\n def compute_df(self):\n '''estimate gradient from directional derivatives'''\n mode = ['adaptive' if i==0 else None for i in range(self.dim)]\n if self.parallel:\n self.dg, feval, self.L = zip(*ray.get([self.quad_parallel.remote(\\\n lambda t : self.fun(self.x + t * self.u[d]), self.s, self.f, mode[d])\\\n for d in range(self.dim)]))\n else:\n self.dg, self.L = np.zeros(self.dim), np.zeros(self.dim)\n feval = np.zeros(self.dim, dtype=int)\n for d in range(self.dim):\n self.dg[d], feval[d], self.L[d] = self.quad(\\\n lambda t : self.fun(self.x + t * self.u[d]), self.s, self.f, mode[d])\n self.feval += np.sum(feval)\n self.df = np.matmul(self.dg, self.u)\n\n def update_x(self):\n '''update minimizer'''\n # select learning rate\n self.L_avg = self.L[0] if self.L_avg==0\\\n else (1 - self.L_lmb) * self.L[0] + self.L_lmb * self.L_avg\n self.lr = np.clip(self.s / self.L_avg, self.lr_min, self.lr_max)\n if self.update_rule == 'adam':\n # adam update\n self.mt = self.adam_beta[0] * self.mt + (1 - self.adam_beta[0]) * self.df\n self.vt = self.adam_beta[1] * self.vt + (1 - self.adam_beta[1]) * self.df**2\n mh = self.mt / (1 - self.adam_beta[0]**(self.itr + 1))\n vh = self.vt / (1 - self.adam_beta[1]**(self.itr + 1))\n self.dx = self.lr * mh / (np.sqrt(vh) + self.adam_eps)\n else:\n # gradient descent\n self.dx = self.lr * self.df\n # update minimizer\n self.x -= self.dx\n self.f = self.fun(self.x)\n self.feval += 1\n\n def save_state(self):\n '''save the best state'''\n if self.f < self.f_min:\n self.x_min = self.x.copy()\n self.f_min = self.f\n self.s_res = self.s\n\n def restart_state(self):\n '''restart from the best state'''\n self.x = self.x_min.copy()\n self.f = self.f_min\n self.s = self.s_res\n\n def update_parameters(self):\n '''update hyperparameters'''\n self.converged = np.amax(np.abs(self.dx)) < self.xtol\n flag_conv = self.s < self.s_min * self.res_mlt\n flag_div = self.s > self.s_max / self.res_div\n if self.restart and ((flag_conv and self.num_reset > 0) or flag_div):\n # reset parameters / restart state\n self.reset_params()\n self.num_res -= 1\n if self.num_res == -1 or flag_div:\n self.restart_state()\n if self.verbose > 1:\n print('iteration {:d}: resetting the parameters'.format(self.itr+1))\n else:\n # update directions and adjust smoothing parameter\n self.generate_directions(self.df)\n s_norm = np.amax(np.abs(self.dg) / self.L)\n if s_norm < self.A:\n self.s *= self.s_rate\n self.A *= self.A_dec\n self.s_status = '-'\n elif s_norm > self.B:\n self.s /= self.s_rate\n self.B *= self.B_inc\n self.s_status = '+'\n else:\n self.A *= self.A_inc\n self.B *= self.B_dec\n self.s_status = '='\n self.s = np.clip(self.s, self.s_min, self.s_max)\n\n def record_parameters(self):\n '''record hyperparameters'''\n os.makedirs('./logs/', exist_ok=True)\n json.dump(self.__dict__, open('./logs/' + self.log_name + '.json', 'w'))\n\n def record_iteration(self, log_mode='a'):\n '''record current variables'''\n with open('./logs/' + self.log_name + self.subname + '.csv', log_mode) as logfile:\n if log_mode == 'w':\n log_func = lambda x: x.replace('self.', '')\n logfile.write(','.join(map(log_func, self.log_vars)) + '\\n')\n log_func = lambda x: self.log_vars[x].format(eval(x))\n logfile.write(','.join(map(log_func, self.log_vars)) + '\\n')\n self.display_variables()\n\n def display_variables(self):\n '''display current variables'''\n if self.verbose > 0:\n print('iteration {:d}: f = {:.2e}, lr = {:.2e}, s = {:.2e} ({:s})'.\\\n format(self.itr, self.f, self.lr, self.s, self.s_status))\n if self.verbose > 1:\n print(' df_2 = {:.2e}, dx_2 = {:.2e}, dx_inf = {:.2e}'.\\\n format(np.linalg.norm(self.df), np.linalg.norm(self.dx), np.amax(np.abs(self.dx))))\n if self.verbose > 2:\n print(' x =', self.x[:10])\n print(' df =', self.df[:10])\n\n\nif __name__ == '__main__':\n\n # problem setup\n fun_name = 'ackley'\n fun_dim = 10\n fun, x_min, x_dom = target_function(fun_name, fun_dim)\n x0 = initial_guess(x_dom)\n\n # run asgf optimization\n asgf = ASGF(log_name=log_name, verbose=1, parallel=False)\n asgf.minimize(fun, x0, subname='test')\n x_opt = asgf.x_min\n itr_opt = asgf.itr\n feval_opt = asgf.feval\n\n # report results\n f_delta = np.abs((fun(x_opt) - fun(x_min)) / (fun(x0) - fun(x_min)))\n print('\\nasgf-optimization terminated after {:d} iterations and {:d} evaluations: '\\\n 'f_min = {:.2e} / {:.2e}'.format(itr_opt, feval_opt, fun(x_opt), f_delta))\n\n\n","repo_name":"sukiboo/smoothing_based_optimization","sub_path":"extra_scripts/asgf.py","file_name":"asgf.py","file_ext":"py","file_size_in_byte":9810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"15449195834","text":"from spack.package import *\n\n\nclass Mppp(CMakePackage):\n \"\"\"mp++ is a C++11/14/17/20 library for multiprecision arithmetic\"\"\"\n\n # URL for package's homepage.\n homepage = \"https://bluescarni.github.io/mppp/index.html\"\n url = \"https://github.com/bluescarni/mppp/archive/refs/tags/v1.0.1.tar.gz\"\n\n # List of GitHub accounts to notify when the package is updated.\n maintainers(\"bluescarni\", \"agseaton\")\n\n # SPDX identifier of the project's license.\n license(\"MPL-2.0\")\n\n version(\"1.0.1\", sha256=\"90e8758bad2d9ebec04305d9cc394168de7bd563acc290e273dd68467e07de07\")\n version(\"1.0.0\", sha256=\"e58b1a5fb8bdf095261eeb0861c3f46f96c71c4b043d19700e73ce3e4e639268\")\n version(\"0.27\", sha256=\"a1e04f6605b3242d4361742159cf5ab273162fd7c105c2743a9bebcf44c846c3\")\n version(\"0.26\", sha256=\"4dbfa68802d9a1365eda884f085418afc147d01b7a928e8333e4dcc1c3b3ce9e\")\n version(\"0.25\", sha256=\"3e6142acd5c6d71405537311b0c800b6fa27a009a46af538ad07b7e6a115f95d\")\n version(\"0.24\", sha256=\"c84cbe38545b7f3f20688791e0a7ce4020830ed84ab6a109ab13a208745be9dc\")\n version(\"0.23\", sha256=\"76f4ee484afae4dbe00f4b0bf91063e4d5dc3eb2bbf5d34ecf174821965d5910\")\n version(\"0.22\", sha256=\"92e34a393c7b6e61daec6a26827a2b73b9b61d961ab37bcabbf051cc7ff19ad2\")\n version(\"0.21\", sha256=\"49a05fc6874a800cb42a3ac16eb46a50583f0b59d3b54008c58af766186a8c69\")\n version(\"0.20\", sha256=\"c736daeaac30e38e1c09a19d249209ad49f8ec92ab1315a8fb9a47cc1f54e607\")\n\n variant(\n \"mpfr\",\n default=True,\n description=(\n \"Enable features relying on GNU MPFR library. Used in the\"\n \" implementation of the real class and for providing \"\n \"support for the long double type in integer and \"\n \"rational\"\n ),\n )\n variant(\n \"mpc\",\n default=True,\n when=\"+mpfr\",\n description=(\n \"Enable features relying on the GNU MPC library. Used in \"\n \"the implementation of the complex class.\"\n ),\n )\n variant(\n \"quadmath\",\n default=False,\n description=(\n \"Enable features relying on the GNU quadmath library. \"\n \"Used in the implementation of the real128 and complex128\"\n \" classes.\"\n ),\n )\n variant(\n \"serialization\",\n default=False,\n when=\"@0.22:\",\n description=\"Enable support for serialization via the Boost.serialization library\",\n )\n variant(\n \"fmt\",\n default=True,\n when=\"@0.27:\",\n description=\"Enable support for formatting via the fmt library\",\n )\n variant(\"tests\", default=False, description=\"Build the test suite\")\n variant(\n \"benchmarks\",\n default=False,\n when=\"+serialization +fmt\",\n description=\"Build the benchmarking suite\",\n )\n variant(\n \"static\",\n default=False,\n description=\"build mp++ as a static library, instead of a dynamic library\",\n )\n\n # Dependencies\n depends_on(\"cmake@3.8:\", type=\"build\")\n\n # Required dependencies\n depends_on(\"gmp@5:\")\n\n # Optional dependencies\n depends_on(\"mpfr@3:\", when=\"+mpfr\")\n depends_on(\"mpc\", when=\"+mpc\")\n depends_on(\"gcc\", when=\"+quadmath\")\n depends_on(\"boost@1.69: +serialization\", when=\"+serialization\")\n depends_on(\"fmt@6.2:\", when=\"+fmt\")\n\n def cmake_args(self):\n args = [\n self.define_from_variant(\"MPPP_WITH_MPFR\", \"mpfr\"),\n self.define_from_variant(\"MPPP_WITH_MPC\", \"mpc\"),\n self.define_from_variant(\"MPPP_WITH_QUADMATH\", \"quadmath\"),\n self.define_from_variant(\"MPPP_WITH_BOOST_S11N\", \"serialization\"),\n self.define_from_variant(\"MPPP_WITH_FMT\", \"fmt\"),\n self.define_from_variant(\"MPPP_BUILD_TESTS\", \"tests\"),\n self.define_from_variant(\"MPPP_BUILD_BENCHMARKS\", \"benchmarks\"),\n self.define_from_variant(\"MPPP_BUILD_STATIC_LIBRARY\", \"static\"),\n self.define_from_variant(\"MPPP_ENABLE_IPO\", \"ipo\"),\n ]\n return args\n","repo_name":"tmadlener/spack","sub_path":"var/spack/repos/builtin/packages/mppp/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"39588701614","text":"import sys\r\ndef kadane(arr, start, finish, n):\r\n Sum = 0\r\n maxSum = -sys.maxsize-1\r\n i = None\r\n finish[0] = -1\r\n local_start = 0\r\n for i in range(n):\r\n Sum += arr[i]\r\n if(Sum<0):\r\n Sum = 0\r\n local_start = i + 1\r\n elif(Sum > maxSum):\r\n maxSum = Sum\r\n start[0] = local_start\r\n finish[0] = i \r\n if (finish[0] != -1):\r\n return maxSum\r\n maxSum = arr[0] \r\n start[0] = finish[0] = 0\r\n for i in range(1, n):\r\n if (arr[i] > maxSum):\r\n maxSum = arr[i]\r\n start[0] = finish[0] = i \r\n return maxSum \r\n\r\ndef findMaxSum(M):\r\n global ROW, COL \r\n maxSum, finalLeft = -sys.maxsize-1, None\r\n finalRight, finalTop, finalBottom = None, None, None\r\n left, right, i = None, None, None\r\n maxsum2=0\r\n temp = [None] * ROW \r\n Sum = 0\r\n start = [0] \r\n finish = [0] \r\n for left in range(COL):\r\n temp = [0] * ROW \r\n for right in range(left, COL):\r\n for i in range(ROW):\r\n temp[i] += M[i][right]\r\n Sum = kadane(temp, start, finish, ROW)\r\n if(Sum > maxSum):\r\n maxSum = Sum\r\n finalLeft = left \r\n finalRight = right \r\n finalTop = start[0] \r\n finalBottom = finish[0] \r\n \r\n for i in range(finalTop,finalBottom+1):\r\n for j in range(finalLeft,finalRight+1):\r\n #print(M[i][j])\r\n if(M[i][j]<0):\r\n pass\r\n else:\r\n maxsum2=maxsum2+abs(M[i][j]) \r\n print(maxSum)\r\n print(maxsum2)\r\n \r\nROW,COL=map(int,input().split())\r\nm=[]\r\nfor i in range(0,ROW):\r\n l=list(map(int,input().split()))\r\n m.append(l)\r\nfindMaxSum(m) \r\n\r\n","repo_name":"Manthanc007/APS-2o2o","sub_path":"arrangmental max.py","file_name":"arrangmental max.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10128660888","text":"# This file is used to configure the behavior of pytest when using the Astropy\n# test infrastructure.\ntry:\n from pytest_astropy_header.display import (PYTEST_HEADER_MODULES,\n TESTED_VERSIONS)\nexcept ImportError:\n PYTEST_HEADER_MODULES = {}\n TESTED_VERSIONS = {}\n\n# Uncomment and customize the following lines to add/remove entries from\n# the list of packages for which version numbers are displayed when running\n# the tests. Making it pass for KeyError is essential in some cases when\n# the package uses other astropy affiliated packages.\nPYTEST_HEADER_MODULES['Astropy'] = 'astropy'\nPYTEST_HEADER_MODULES['Ginga'] = 'ginga'\nPYTEST_HEADER_MODULES.pop('h5py', None)\nPYTEST_HEADER_MODULES.pop('Pandas', None)\n\n# Uncomment the following lines to display the version number of the\n# package rather than the version number of Astropy in the top line when\n# running the tests.\ntry:\n from astrowidgets import __version__ as version\nexcept ImportError:\n version = 'unknown'\nTESTED_VERSIONS['astrowidgets'] = version\n","repo_name":"astropy/astrowidgets","sub_path":"astrowidgets/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"52"}
+{"seq_id":"8698522481","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 23 22:39:14 2020\n\n@author: OCAC\n\"\"\"\nus_mpg=235.215\nFuelEff_US=float(input(\"Enter Fuel Efficiency Value :\"))\nFuelEff_Can=FuelEff_US*us_mpg\n\nprint(\"The Equivalent Fuel Efficiency in Canadian Unit :\",FuelEff_Can)","repo_name":"AnkitM18-tech/Python-Introductory-Problems","sub_path":"1.Introductory/FuelEfficiency.py","file_name":"FuelEfficiency.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"71151365605","text":"import random\r\nimport string\r\nfrom Domain.CardCustomer import Card\r\nfrom Domain.ValidateCard import CustomerCardValidator\r\nfrom Repository.GenericRepository import GenericFileRepository\r\n\r\n\r\nclass CardService:\r\n def __init__(self,\r\n card_repository: GenericFileRepository,\r\n card_validator: CustomerCardValidator,\r\n transaction_repository: GenericFileRepository):\r\n self.__card_repository = card_repository\r\n self.__card_validator = card_validator\r\n self.__transaction_repository = transaction_repository\r\n\r\n def add_customer_card(self,\r\n customer_card_id,\r\n customer_name,\r\n customer_first_name,\r\n customer_cnp,\r\n birth_date,\r\n registration_date,\r\n isRemoved):\r\n \"\"\"\r\n Function creates a card\r\n :param customer_card_id: int\r\n :param customer_name: string\r\n :param customer_first_name: string\r\n :param customer_cnp: int\r\n :param birth_date: string\r\n :param registration_date: string\r\n :param isRemoved: bool\r\n \"\"\"\r\n customer_card = Card(customer_card_id,\r\n customer_name,\r\n customer_first_name,\r\n customer_cnp,\r\n birth_date,\r\n registration_date,\r\n isRemoved)\r\n self.__card_validator.validate_date(birth_date)\r\n self.__card_validator.validate_date(registration_date)\r\n self.__card_repository.ensure_unique_cnp(customer_card)\r\n self.__card_validator.validate_customer_card(customer_card)\r\n self.__card_repository.create(customer_card)\r\n\r\n # READ\r\n\r\n def get_all(self):\r\n \"\"\"\r\n The functionality for getting all the object from file\r\n :return: all the object from file\r\n \"\"\"\r\n return self.__card_repository.read()\r\n\r\n # UPDATE\r\n\r\n def update_card(self, ID, name, surname, cnp, date_birth, date_registration, is_removed):\r\n \"\"\"\r\n\r\n :param ID:\r\n :param name:\r\n :param surname:\r\n :param cnp:\r\n :param date_birth:\r\n :param date_registration:\r\n :param is_removed:\r\n :return:\r\n \"\"\"\r\n new_card = Card(ID, name, surname, cnp, date_birth, date_registration, is_removed)\r\n self.__card_validator.validate_customer_card(new_card)\r\n self.__card_repository.update(new_card)\r\n\r\n # DELETE\r\n\r\n def delete_card(self, id_card):\r\n \"\"\"\r\n\r\n :param id_card:\r\n :return:\r\n \"\"\"\r\n self.__card_repository.delete(id_card)\r\n\r\n def get_list_of_customer_cards_that_match(self, string_card):\r\n \"\"\"\r\n Function finds all the cards that have the given string in them\r\n :param string_card: string\r\n :return: a list of CustomerCards objects that contain the string\r\n \"\"\"\r\n found_customer_cards = []\r\n for customer_card in self.__card_repository.read():\r\n if string_card in customer_card.get_text_format():\r\n found_customer_cards.append(customer_card)\r\n return found_customer_cards\r\n\r\n def get_all_cards(self):\r\n \"\"\"\r\n Gets all cards from repository\r\n :return: a list of CustomerCard objects\r\n \"\"\"\r\n found_cards = []\r\n for card in self.__card_repository.read():\r\n found_cards.append(card)\r\n return found_cards\r\n\r\n def search_text(self, string_cards):\r\n \"\"\"\r\n\r\n :param string_cards:\r\n :return:\r\n \"\"\"\r\n list_cards = []\r\n for cards in self.__card_repository.read():\r\n if string_cards in cards.get_text_format():\r\n list_cards.append(cards)\r\n\r\n return list_cards\r\n\r\n def populate(self):\r\n \"\"\"\r\n\r\n :return:\r\n \"\"\"\r\n letters = string.ascii_lowercase\r\n id_card = random.randint(1, 101)\r\n surname = ''.join(random.choice(letters) for i in range(10))\r\n name = ''.join(random.choice(letters) for i in range(10))\r\n cnp = random.randint(1000000000000, 7000000000000)\r\n day1 = random.randint(0, 31)\r\n month1 = random.randint(0, 12)\r\n year1 = random.randint(1950, 2000)\r\n date_birth = \"{}.{}.{}\".format(day1, month1, year1)\r\n day2 = random.randint(0, 31)\r\n month2 = random.randint(0, 12)\r\n year2 = random.randint(1950, 2000)\r\n date_registered = \"{}.{}.{}\".format(day2, month2, year2)\r\n self.add_customer_card(id_card, name, surname, cnp, date_birth, date_registered, False)\r\n\r\n def clear(self):\r\n self.__card_repository.clear()\r\n\r\n def show_card_client_desc_ord(self):\r\n list_of_customer_cards = self.__card_repository.read()\r\n max_per_id = {}\r\n for transaction in self.__transaction_repository.read():\r\n card_id_in_transaction = transaction.get_id_card()\r\n discount_for_card = transaction.get_discount()\r\n if card_id_in_transaction not in max_per_id:\r\n max_per_id[card_id_in_transaction] = 0\r\n max_per_id[card_id_in_transaction] += discount_for_card\r\n list_of_filtered_cards = []\r\n for card_d in list_of_customer_cards:\r\n if card_d.id_entity() in max_per_id:\r\n list_of_filtered_cards.append(card_d)\r\n return sorted(list_of_filtered_cards, key=lambda card: max_per_id[card.id_entity()], reverse=True)\r\n","repo_name":"Gabi240400/car-service","sub_path":"Service/ServiceCard.py","file_name":"ServiceCard.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"42435563666","text":"from itertools import accumulate\n\n\ndef prefix_sum(nums):\n N = len(nums)\n psum = [0]*(N+1)\n for i, n in enumerate(nums):\n psum[i+1] = psum[i]+n\n return psum\n\n\ndef prefix_sum_with_append(nums):\n psum = [0]\n for n in nums:\n psum.append(psum[-1]+n)\n return psum\n\n\ndef prefix_sum_with_accumulate(nums):\n return [0]+list(accumulate(nums))\n\n\npsum = prefix_sum([1, 2, 3, 4, 6, 7, 10])\nprint(psum)\nleft, right = 3, 5 # nums[3]連加至nums[5]\nprint(psum[right+1]-psum[left]) # 17\nleft, right = 0, 2 # nums[0]連加至nums[2]\nprint(psum[right+1]-psum[left]) # 6\nleft, right = 1, 1 # nums[1]\nprint(psum[right+1]-psum[left]) # 2\n","repo_name":"mocowcow/my-library","sub_path":"pattern/prefix_sum.py","file_name":"prefix_sum.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"43479350916","text":"# I'm going to use ordered tuples to represent the operations (po1, operation, po2)\n# after this I will try to implement everything in dictionaries as an actual graph.\n\n# Note since these are binary operators these 'meta graphs' are binary trees.\n# For generating any SPn you just need to go through all binary trees of size n - 1\n# And the generate the 2n permutations operation of those (Doesn't hold for non-cummutative\n# and can create duplicates.)\n\n# This is called generating topologies. We can implement it such that leaves represent\n# the nodes of a hasse and the nodes the operators.\n# This would literaly just be generating the binary trees.\n\n# The number of partial orders of size n is\n\nfrom functools import reduce\n\nCOMMUTATIVE = 'commutative'\nSERIES = 's'\nPARALLEL = 'p'\nNODE = 'n'\nOPERATORS = [[SERIES], [PARALLEL, COMMUTATIVE]]\n\n# Dynamic programming memo\nMEMO = {}\n\n#pylint: disable = w0622, c0103\nclass frozenset(frozenset):\n '''Check normal frozenset. This just makes it look like any old set.\n Nothing to see here. Move along.'''\n def __repr__(self):\n return '{{{}}}'.format(', '.join(map(repr, self)))\n\ndef combine(SPn1_Collection, SPn2_Collection):\n operations = frozenset()\n for operator in OPERATORS:\n #Duplicate code her for time / memory reasons\n if COMMUTATIVE in operator:\n operations = operations.union(frozenset(frozenset([SPn1, operator[0], SPn2])\n for SPn1 in SPn1_Collection\n for SPn2 in SPn2_Collection))\n else:\n operations = operations.union(frozenset((SPn1, operator[0], SPn2)\n for SPn1 in SPn1_Collection\n for SPn2 in SPn2_Collection))\n return operations\n\ndef SPn(size):\n if size == 1:\n return set(NODE)\n elif not size in MEMO:\n combinations = map(lambda i: combine(SPn(i), SPn(size - i)), range(1, size))\n MEMO[size] = reduce(lambda x, y: x.union(y), combinations)\n return MEMO[size]\n\n# Since I'm using the same base node value and the sets are not unique\n# some look smaller because the second occurence of n in SPn(2) is not there.\n# Think of {n, s} as {n, s, n}\nprint(*list(SPn(4)), sep='\\n')","repo_name":"JorikSchellekens/POSets","sub_path":"SP.py","file_name":"SP.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72580108645","text":"#!/usr/bin/env python\n\"\"\"This is users.py.py\"\"\"\n# -----------------------------------------------------------------------\n# requests.py\n# Piers Ozuah\n# -----------------------------------------------------------------------\n\nfrom datetime import date\nimport sys\nfrom os import name\nfrom sys import argv, stderr\nfrom socket import socket, SOL_SOCKET, SO_REUSEADDR\n\nfrom pickle import dump\nfrom pickle import load\n\nfrom contextlib import closing\n# from sqlite3 import DataError, DatabaseError\n# from sqlite3 import connect\nfrom psycopg2 import connect, DatabaseError\nimport psycopg2\nimport restaurant\nimport argparse\nfrom add_restaurant import add_restaurant\n# loading\n\n\nfrom restaurant import restaurant\n\n\n# -----------------------------------------------------------------------\n# Old Database -> for the original reg\n#DATABASE_URL = 'file:reg.sqlite?mode=ro'\n\n# New database for restaurants\nDATABASE_URL = 'file:trentoneats.sql?mode=ro'\n# -----------------------------------------------------------------------\n\n\ndef delete_request(request_id):\n \"\"\"delete a restaurant from the requests table\"\"\"\n try:\n # with connect(host='localhost', port=5432, user='rmd', password='xxx',\n # database=\"trentoneats\") as connection:\n with connect(host='ec2-3-229-161-70.compute-1.amazonaws.com', port=5432, user='jazlvqafdamomp', password='6bc2f9e25e0ab4a2e167d5aed92096137eaacd1667e2863a6659e019dbb7e81a',\n database=\"dequ5ope4nuoit\") as connection:\n\n with closing(connection.cursor()) as cursor:\n # This needs to be adjusted\n stmt_str = \"DELETE FROM requests \"\n stmt_str += \"WHERE request_id =\" + request_id + \";\"\n\n print(stmt_str)\n cursor.execute(stmt_str, [request_id])\n\n except DatabaseError as error:\n print(sys.argv[0] + \": \" + str(error), file=stderr)\n return (\"stdservererr\")\n\n\ndef delete_request_add_res(request_id):\n \"\"\"find all information on one restaurant\"\"\"\n try:\n # with connect(host='localhost', port=5432, user='rmd', password='xxx',\n # database=\"trentoneats\") as connection:\n with connect(host='ec2-3-229-161-70.compute-1.amazonaws.com', port=5432, user='jazlvqafdamomp', password='6bc2f9e25e0ab4a2e167d5aed92096137eaacd1667e2863a6659e019dbb7e81a',\n database=\"dequ5ope4nuoit\") as connection:\n\n with closing(connection.cursor()) as cursor:\n # This needs to be adjusted\n\n stmt_str = \"SELECT name, address, hours, open_closed, menu, \"\n stmt_str += \"media, tags, review_count, stars, image, \"\n stmt_str += \"price, cuisine, type FROM requests \"\n stmt_str += \"WHERE request_id = '\" + request_id + \"'; \"\n\n cursor.execute(stmt_str)\n print(stmt_str)\n row = cursor.fetchone()\n\n # hashmap to hold object info\n info_obj = {}\n\n # This will parse through the row and occupy the hashmap\n if row is not None:\n info_obj['name'] = str(row[0])\n info_obj['address'] = str(row[1])\n info_obj['hours'] = str(row[2])\n info_obj['open_closed'] = str(row[3])\n info_obj['menu'] = str(row[4])\n info_obj['media'] = str(row[5])\n info_obj['tags'] = str(row[6])\n info_obj['review_count'] = str(row[7])\n info_obj['stars'] = str(row[8])\n info_obj['image'] = str(row[9])\n info_obj['price'] = str(row[10])\n info_obj['cuisine'] = str(row[11])\n info_obj['type'] = str(row[12])\n\n print(info_obj['name'])\n print(info_obj['address'])\n print(info_obj['hours'])\n print(info_obj['open_closed'])\n print(info_obj['menu'])\n print(info_obj['media'])\n print(info_obj['tags'])\n print(info_obj['review_count'])\n print(info_obj['stars'])\n print(info_obj['image'])\n print(info_obj['price'])\n print(info_obj['cuisine'])\n print(info_obj['type'])\n\n name = info_obj['name']\n address = info_obj['address']\n hours = info_obj['hours']\n open_closed = info_obj['open_closed']\n menu = info_obj['menu']\n media = info_obj['media']\n tags = info_obj['tags']\n review_count = info_obj['review_count']\n stars = info_obj['stars']\n image = info_obj['image']\n cuisine = info_obj['cuisine']\n type = info_obj['type']\n price = info_obj['price']\n\n add_restaurant(name, address, hours, menu, media,\n tags, cuisine, type, price, image)\n\n # stmt_str2 = \"\"\"\n # INSERT INTO restaurants (name, address, hours,\n # open_closed, menu, media, tags, review_count, stars, image, cuisine, type, price)\n # VALUES ( '\"\"\"\n # stmt_str2 += info_obj['name'] + \\\n # \"','\" + info_obj['address'] + \"','\"\n # stmt_str2 += info_obj['hours'] + \\\n # \"', 'TRUE', '\" + info_obj['menu'] + \"', '\"\n # stmt_str2 += info_obj['media'] + \"', '\" + \\\n # info_obj['tags'] + \"', '0', '0', '\"\n # stmt_str2 += info_obj['image'] + \"', \"\n # stmt_str2 += \"'\" + str(info_obj['cuisine'])\n # stmt_str2 += \"', '\" + info_obj['type']\n # stmt_str2 += \"', '\" + info_obj['price'] + \"');\"\n\n # print(stmt_str2)\n # cursor.execute(stmt_str2)\n\n stmt_str3 = \"DELETE FROM requests \"\n stmt_str3 += \"WHERE request_id =\" + request_id + \";\"\n\n print(stmt_str3)\n cursor.execute(stmt_str3)\n\n # Normally exit status 0.\n # If database-related error, terminate with exit status 1.\n # If erroneous command-line arguments terminate with exit status 2\n\n except DatabaseError as error:\n print(sys.argv[0] + \": \" + str(error), file=stderr)\n return (\"stdservererr\")\n","repo_name":"stephendongg/trentoneats","sub_path":"requestshelper.py","file_name":"requestshelper.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"5731121699","text":"import sys\ninput = sys.stdin.readline\n\ndef reverse_row(rows, cols):\n for row in range(rows//2):\n for col in range(cols):\n array[rows-(row+1)][col], array[row][col] = array[row][col], array[rows-(row+1)][col]\n\ndef reverse_col(rows, cols):\n for row in range(rows):\n for col in range(cols//2):\n array[row][cols-(col+1)], array[row][col] = array[row][col], array[row][cols-(col+1)]\n\ndef rotate_array(rows, cols):\n max_depth = min(rows//2, cols//2)\n rotated_array = [[0 for _ in range(rows)] for _ in range(cols)]\n\n if rows == cols:\n rotated_array[rows//2][cols//2] = array[rows//2][cols//2]\n\n for depth in range(max_depth):\n # top -> right\n for col in range(depth, cols-depth):\n rotated_array[col][rows-(depth+1)] = array[depth][col]\n\n # right -> bottom\n for row in range(depth, rows-depth):\n rotated_array[cols-(depth+1)][row] = array[rows-(row+1)][cols-(depth+1)]\n\n # bottom -> left\n for col in range(depth, cols-depth):\n rotated_array[cols-(col+1)][depth] = array[rows-(depth+1)][cols-(col+1)]\n\n # left -> top\n for row in range(depth, rows-depth):\n rotated_array[depth][rows-(row+1)] = array[row][depth]\n\n return rotated_array\n\ndef move_array(rows, cols):\n last = [[0 for _ in range(cols//2)] for _ in range(rows//2)]\n\n # 4번 그룹 저장\n for row in range(rows//2, rows):\n for col in range(cols//2):\n last[row-rows//2][col] = array[row][col]\n \n # 3 -> 4\n for row in range(rows//2, rows):\n for col in range(cols//2):\n array[row][col] = array[row][col+cols//2]\n\n # 2 -> 3\n for row in range(rows//2, rows):\n for col in range(cols//2, cols):\n array[row][col] = array[row-rows//2][col]\n\n # 1 -> 2\n for row in range(rows//2):\n for col in range(cols//2, cols):\n array[row][col] = array[row][col-cols//2]\n\n # 4 -> 1\n for row in range(rows//2):\n for col in range(cols//2):\n array[row][col] = last[row][col]\n\nrows, cols, op_count = map(int, input().split())\narray = [list(map(int, input().split())) for _ in range(rows)]\nops = list(map(int, input().split()))\n\nfor op in ops:\n if op == 1:\n # 상하 반전\n reverse_row(rows, cols)\n elif op == 2:\n # 좌우 반전\n reverse_col(rows, cols)\n elif op == 3:\n # → 90도 회전\n array = rotate_array(rows, cols)\n rows, cols = cols, rows\n elif op == 4:\n # 4: ← 90도 회전\n for _ in range(3):\n array = rotate_array(rows, cols)\n rows, cols = cols, rows\n elif op == 5:\n move_array(rows, cols)\n else: \n for _ in range(3):\n move_array(rows, cols)\n\nfor row in range(rows):\n for col in range(cols):\n print(array[row][col], end=' ')\n print()","repo_name":"BangDori/python-algorithm","sub_path":"baekjoon/16935.py","file_name":"16935.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30344245097","text":"#!/usr/bin/python3\n\nimport rclpy\nfrom rclpy.service import Service\nfrom rclpy.action import ActionClient\nfrom rclpy.node import Node\n\n#from ament_index_python.packages import get_package_share_directory\n\nfrom std_msgs.msg import String\nfrom chatbot_speech_recognizer_interface.srv import Speechrec\nfrom tts_messages.srv import StringToWav\nfrom chatterbot import ChatBot\nimport logging\n#from chatterbot.trainers import ChatterBotCorpusTrainer\n\n#from preprocessors import preprocess_text\n#from preprocessors import clean_whitespace\n#from spacyadapter import SpacyBestMatch\nfrom chatbot.language_detector import detect_language\nfrom chatbot.translate_text import translate_to_english\nfrom chatbot.translate_text import translate_to_finnish\nfrom chatbot.best_match_adapter import BestMatchAdapter\n\n#from trainers import ChatterBotTXTTrainer\n#from trainers import SQuADJSONTrainer\n#from trainers import MSMARCOJSONTrainer\n#from trainers import ChatterBotJSONTrainer\n#from trainers import ChatterBotCorpusTrainer\n\nlogging.basicConfig(level=logging.INFO)\n\n\nclass ChatBotClientNode(Node):\n\n def __init__(self):\n super().__init__('chatbot_node')\n self.publisher_ = self.create_publisher(String, 'chatbot_response', 10)\n self.subscription = self.create_subscription(String, 'recognized_speech', self.tts_callback, 10)\n self.chatbot = ChatBot(\"Helper\", read_only=True, storage_adapter='chatterbot.storage.SQLStorageAdapter',\n logic_adapters=[\n {\n #'import_path': '__main__.BestMatchAdapter',\n 'import_path': 'chatbot.best_match_adapter.BestMatchAdapter',\n 'default_response': 'I am sorry, but I do not understand.',\n 'maximum_similarity_threshold': 0.90,\n 'statement_comparison_function': 'chatterbot.comparisons.LevenshteinDistance',\n #'response_selection_method': 'chatterbot.response_selection.get_most_frequent_response'\n },\n {\n 'import_path': 'chatterbot.logic.MathematicalEvaluation',\n }\n ]\n )\n\n def tts_callback(self, msg):\n data = self.chatbot_worker_callback(msg.data)\n if (data != \"I am sorry, but I do not understand.\"):\n tts_msg = String()\n tts_msg.data = data\n self.publisher_.publish(tts_msg)\n\n\n\n def chatbot_worker_callback(self, recognized_speech):\n # Get response for the original input\n original_response = self.chatbot.get_response(recognized_speech)\n original_confidence = original_response.confidence\n\n # Translate input to English\n translated_input = translate_to_english.translate(recognized_speech)\n #preprocessed_translated_input = preprocess_text(translated_input)\n # Get response for the translated input\n translated_response = self.chatbot.get_response(translated_input)\n translated_confidence = translated_response.confidence\n\n # Compare confidence levels and choose the higher one\n # Balance the translater confidence by lowering it\n balance_variable = 0.1\n if (translated_confidence - balance_variable) > original_confidence:\n # Translate the English response back to the input language\n final_response_text = translate_to_finnish.translate(translated_response.text)\n else:\n final_response_text = original_response.text\n\n print(\"Bot: \", final_response_text)\n return(final_response_text)\n\n def chatbot_train(self):\n pass\n # train with self-written data\n # trainer = ChatterBotCorpusTrainer(chatbot)\n #\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/trainingdata\"\n # )\n #\n #\n # # train with ambignq data\n # trainer = ChatterBotJSONTrainer(chatbot)\n #\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/ambignq/train.json\", input_language=\"en\"\n # )\n #\n #\n # # train with qa dataset\n # trainer = ChatterBotTXTTrainer(chatbot)\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S08/question_answer_pairs.txt\", input_language=\"en\"\n # )\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S09/question_answer_pairs.txt\", input_language=\"en\"\n # )\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/Question_Answer_Dataset_v1.2/S10/question_answer_pairs.txt\", input_language=\"en\"\n # )\n #\n # # train with stanford training data\n # trainer = SQuADJSONTrainer(chatbot)\n # trainer.train(\n # \"/workspace/src/chatbot/chatbot/train_stanford/train-v2.0.json\", input_language=\"en\"\n # )\n\n \ndef main(args=None):\n rclpy.init(args=args)\n client = ChatBotClientNode()\n rclpy.spin(client)\n rclpy.shutdown()\n\n #response = client.send_request()\n #if (response.success):\n # client.get_logger().info(response.recognized_speech)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ouspg/SOP-Robot","sub_path":"src/chatbot/chatbot/chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"27301365342","text":"import requests\nfrom assertpy import assert_that\n\n\n\nclass Client(object):\n \"\"\"Client(url, method, datatype=None)\"\"\"\n\n def __init__(self, url, method, datatype=None):\n self.__url = url\n self.__method = method\n self.__datatype = datatype\n self.__headers = {}\n self.__data = {}\n self.__res = None\n\n def add_header(self, key, value):\n \"\"\"添加头信息\"\"\"\n self.__headers[key] = value\n\n def set_data(self, data):\n \"\"\"添加接口参数\"\"\"\n self.__data = data\n\n def send(self):\n \"\"\"根据发送数据方式,发送数据\"\"\"\n\n # 发送GET请求\n if self.__method == \"GET\":\n self.__res = requests.get(url=self.__url, params=self.__data)\n # 发送POST请求\n elif self.__method == \"POST\":\n # 发送普通form-data\n if self.__datatype == 0:\n self.__res = requests.post(url=self.__url, data=self.__data)\n # 发送x-www-url-form-url-encoded数据\n elif self.__datatype == 1:\n self.add_header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n self.__res = requests.post(url=self.__url, data=self.__data, headers=self.__headers)\n # 发送json数据\n elif self.__datatype == 2:\n self.add_header(\"Content-Type\", \"application/json\")\n self.__res = requests.post(url=self.__url, json=self.__data, headers=self.__headers)\n # 发送xml格式数据\n elif self.__datatype == 3:\n xml = self.__data[\"xml\"]\n if xml:\n self.add_header(\"Content-Type\", \"text/xml\")\n requests.post(url=self.__url, data=self.__data, headers=self.__headers)\n else:\n raise Exception('xml数据传输错误,请按照{\"xml\":\"xxxx\"}方式进行传输')\n else:\n raise Exception(\"请求类型不合法\")\n else:\n raise Exception(\"不支持的请求方法类型\")\n\n @property\n def res_text(self):\n \"\"\"返回响应正文字符串\"\"\"\n if self.__res:\n return self.__res.text\n else:\n return None\n\n @property\n def res_status_code(self):\n \"\"\"返回响应状态码\"\"\"\n if self.__res:\n return self.__res.status_code\n else:\n return None\n\n @property\n def res_json(self):\n \"\"\"返回响应json对象\"\"\"\n if self.__res:\n try:\n return self.__res.json()\n except Exception:\n print(\"json数据转换失败\")\n return None\n else:\n return None\n\n @property\n def res_time(self):\n \"\"\"返回响应时间毫秒值\"\"\"\n if self.__res:\n return int(round(self.__res.elapsed.total_seconds()))\n else:\n return None\n\n @property\n def res_headers(self):\n if self.__res:\n return self.__res.headers\n else:\n return None\n\n def check_status_code(self, expect):\n \"\"\"check_status_code(expect),校验响应状态码\"\"\"\n try:\n assert_that(self.res_status_code).is_equal_to(expect)\n print(\"状态码校验成功\")\n except AssertionError:\n print(\"状态码校验失败:实际状态码[{actual}],预期状态码[{expect}]\".format(actual=self.res_status_code, expect=expect))\n\n def check_res_time_less(self, expect_time):\n \"\"\"check_res_time_less(self, expect_time),校验响应时间\"\"\"\n try:\n assert_that(self.res_time).is_less_than(expect_time)\n print(\"响应时间校验成功\")\n except AssertionError:\n print(\"响应时间校验失败:实际响应时间[{actual}],预期响应时间[{expect}]\".format(actual=self.res_time), expect=expect_time)\n\n def check_data_equal(self, actual, expect):\n \"\"\"check_data_equal(self,actual,expect),校验响应内容\"\"\"\n try:\n assert_that(actual).is_equal_to(expect)\n print(\"响应内容校验成功\")\n except AssertionError:\n print(\"响应内容校验失败:实际响应内容[{actual}],预期响应内容[{expect}]\".format(actual=actual, expect=expect))\n\n def check_contains(self, expect):\n \"\"\"check_contains(self, expect),校验响应正文是否包含内容\"\"\"\n try:\n assert_that(self.res_text).contains(expect)\n print(\"响应内容包含校验成功\")\n except AssertionError:\n print(\"响应内容包含校验失败:实际响应内容[{actual}],预期包含内容[{expect}]\".format(actual=self.res_text), expect=expect)\n\n\nclass Method(object):\n GET = \"GET\"\n POST = \"POST\"\n\n\nclass Type(object):\n FORM = 0\n URL_ENCODED = 1\n JSON = 2\n XML = 3\n FILE = 4\n","repo_name":"ivyfangqian/requests_demo","sub_path":"hit_asserpy.py","file_name":"hit_asserpy.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"70933517605","text":"import os\nimport unittest\nimport tempdir\nimport numpy\nfrom paste.deploy import appconfig\nfrom wand.image import Image\nfrom static_map_generator.renderer import Renderer, WmsRenderer, LogoRenderer, WktRenderer, TextRenderer, \\\n GeojsonRenderer, ScaleRenderer, LegendRenderer, DefaultRenderer\n\nTEST_DIR = os.path.dirname(__file__)\nsettings = appconfig(\n 'config:' + os.path.join(TEST_DIR, 'test.ini'),\n name='static_map_generator'\n)\n\nclass UtilsTests(unittest.TestCase):\n\n def setUp(self):\n self.tempdir = tempdir.TempDir()\n self.here = os.path.abspath(os.path.dirname(__file__))\n self.file_path = os.path.join(self.tempdir.name, 'file.png')\n\n def tearDown(self):\n pass\n\n def test_wms_renderer(self):\n renderer = Renderer.factory(\"wms\")\n self.assertIsInstance(renderer, WmsRenderer)\n self.assertEquals(renderer.type(), \"wms\")\n\n def test_wms_renderer_errors(self):\n renderer = Renderer.factory(\"wms\")\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'http://non_existant/geoserver/wms?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Request could not be executed'))\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'https://geo.onroerenderfgoed.be/geoserver/wee_em_es?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Service not found (status_code 404)'))\n\n with self.assertRaises(Exception) as context:\n renderer.render(\n **{\n 'type': 'wms',\n 'url': 'https://geo.onroerenderfgoed.be/geoserver/wms?',\n 'layers': 'vioe_geoportaal:onbestaande_laag',\n 'filename': 'filename',\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000]\n }\n )\n self.assertTrue(context.exception.args[0].startswith('Exception occured'))\n\n def test_text_renderer(self):\n renderer = Renderer.factory(\"text\")\n self.assertIsInstance(renderer, TextRenderer)\n self.assertEquals(renderer.type(), \"text\")\n\n def test_wkt_renderer(self):\n renderer = Renderer.factory(\"wkt\")\n self.assertIsInstance(renderer, WktRenderer)\n self.assertEquals(renderer.type(), \"wkt\")\n\n def test_logo_renderer(self):\n renderer = Renderer.factory(\"logo\")\n self.assertIsInstance(renderer, LogoRenderer)\n self.assertEquals(renderer.type(), \"logo\")\n\n def test_logo_renderer_render(self):\n renderer = Renderer.factory(\"logo\")\n renderer.render(\n **{\n 'type': 'logo',\n 'url': 'https://www.onroerenderfgoed.be/assets/img/logo-og.png',\n 'opacity': 0.5,\n 'imagewidth': 100,\n 'imageheight': 100,\n 'gravity': 'south_west',\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'bbox': [145000, 195000, 165000, 215000],\n 'offset': '0,0'\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer(self):\n renderer = Renderer.factory(\"geojson\")\n self.assertIsInstance(renderer, GeojsonRenderer)\n self.assertEquals(renderer.type(), \"geojson\")\n\n def test_multipoint_renderer_render(self):\n renderer = Renderer.factory(\"wkt\")\n renderer.render(\n **{\n 'type': 'wkt',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': '#0000ff',\n 'wkt': 'MULTIPOINT ((103500 192390.11), (103912.03 192390.11))',\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_multipoint2_renderer_render(self):\n renderer = Renderer.factory(\"wkt\")\n renderer.render(\n **{\n 'type': 'wkt',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': '#0000ff',\n 'wkt': 'MULTIPOINT (103500 192390.11, 103912.03 192390.11)',\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer_render(self):\n renderer = Renderer.factory(\"geojson\")\n renderer.render(\n **{\n 'type': 'geojson',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': 'steelblue',\n 'geojson':{\n \"type\":\"MultiPolygon\",\n \"coordinates\":[[[[103827.44321801752,192484.5100535322],[103826.65621839411,192565.57026445214],[103839.2000972359,192622.4958831761],[103877.27257229008,192673.1911981115],[103981.90807816133,192592.71585010737],[104050.62835409257,192535.07265175506],[104119.78606355426,192526.95860514138],[104157.5529127745,192543.1371434061],[104163.33481632298,192516.068607972],[104043.86794770884,192451.07658289373],[103839.39232099024,192304.2814310426],[103825.49962980268,192434.99411542248],[103827.44321801752,192484.5100535322]]]],\n \"crs\":{\n \"type\":\"name\",\n \"properties\":{\n \"name\":\"urn:ogc:def:crs:EPSG::31370\"}}},\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_geojson_renderer_render2(self):\n renderer = Renderer.factory(\"geojson\")\n renderer.render(\n **{\n 'type': 'geojson',\n 'opacity': 0.5,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 500,\n 'height': 500,\n 'color': 'steelblue',\n 'geojson':{'crs': {'type': 'name', 'properties': {'name': 'EPSG:31370'}}, 'type': 'MultiPoint', 'coordinates': [[103912.03, 192390.11],[103500, 192390.11]]},\n 'bbox': [100000, 100000, 200000, 200000]\n }\n )\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_scale_renderer(self):\n renderer = Renderer.factory(\"scale\")\n renderer.render(\n **{\n 'type': 'scale',\n 'gravity': 'south_west',\n 'offset':'10,20',\n 'opacity': 1,\n 'filename': self.file_path,\n 'epsg': 31370,\n 'filetype': 'png',\n 'width': 750,\n 'height': 750,\n 'bbox': [100000, 100000, 200000, 200000],\n 'font_size': 11,\n 'imagewidth': 200,\n 'imageheight': 50\n })\n self.assertIsInstance(renderer, ScaleRenderer)\n self.assertEquals(renderer.type(), \"scale\")\n self.assertTrue(os.path.isfile(self.file_path))\n image = Image(filename=self.file_path)\n self.assertIsInstance(image, Image)\n\n def test_legend_renderer(self):\n renderer = Renderer.factory(\"legend\")\n self.assertIsInstance(renderer, LegendRenderer)\n self.assertEquals(renderer.type(), \"legend\")\n self.assertRaises(NotImplementedError, renderer.render)\n\n\n def test_default_renderer(self):\n renderer = Renderer.factory(\"\")\n self.assertIsInstance(renderer, DefaultRenderer)\n self.assertEquals(renderer.type(), \"default\")\n self.assertRaises(NotImplementedError, renderer.render)","repo_name":"cedrikv/static_map_generator","sub_path":"tests/test_renderer.py","file_name":"test_renderer.py","file_ext":"py","file_size_in_byte":9108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"13081387899","text":"from socket import *\r\nfrom datetime import datetime\r\n\r\n# sends the message\r\n# - wait up to one second for a reply\r\n# - - resend if timeout\r\n# - resend on error\r\n# print what happens on each attempt to std_out\r\ndef send_message(socket, message, server):\r\n time_start = datetime.now()\r\n try:\r\n # this blocks until success, throws timeout on error\r\n socket.sendto(message.encode(), server)\r\n # get the response\r\n response, server_address = socket.recvfrom(2048)\r\n response = response.decode()\r\n if response == 'Incorrect sum':\r\n print('Server Error, ' + \\\r\n 'RTT = ' + str(datetime.now() - time_start))\r\n send_message(socket, message, server) # try again\r\n else:\r\n print('Result = ' + str(response) + ' '\\\r\n 'RTT = ' + str(datetime.now() - time_start))\r\n return(response)\r\n except timeout:\r\n print('Request timed out')\r\n send_message(socket, message, server) # try again\r\n\r\n\r\n# init UDP object to send\r\nclient_socket = socket(AF_INET, SOCK_DGRAM)\r\n\r\n# init servername, port, numbers from user\r\nserver_name = input('Input server name: ')\r\nserver_port = input('Input server port: ')\r\nnum_a = input('Input first number to multiply: ')\r\nnum_b = input('Input second number to multiply: ')\r\n\r\nmessage = 'Multiply ' \\\r\n + str(num_a) + ' ' + str(num_b) + ' ' + str(num_a+num_b) + ' ' \\\r\n + str(datetime.now())\r\n\r\nclient_socket.settimeout(1.0)\r\n\r\nsend_message(client_socket, message, (server_name, int(server_port)))\r\n\r\n\r\nclient_socket.close()\r\n","repo_name":"will-jac/CS5473-PDN","sub_path":"HW1/UDP_Multiplier_Client.py","file_name":"UDP_Multiplier_Client.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"31612362115","text":"# -*- coding: utf-8 -*-\n\ndef operacion_record_to_dict(record):\n operacion = dict()\n operacion['id'] = record['id_operacion']\n operacion['precio'] = record['precio']\n operacion['vendedor'] = record['publicada_por']\n operacion['comprador'] = record['id_comprador']\n operacion['comision'] = record['comision']\n operacion['valoracion_comprador'] = {\n 'id_valoracion' : record['valoracion_comprador_id_valoracion'],\n 'puntaje' : record['valoracion_comprador_puntaje'],\n 'comentario' : record['valoracion_comprador_comentario'],\n 'respuesta' : record['valoracion_comprador_respuesta'],\n }\n operacion['valoracion_vendedor'] = {\n 'id_valoracion' : record['valoracion_vendedor_id_valoracion'],\n 'puntaje' : record['valoracion_vendedor_puntaje'],\n 'comentario' : record['valoracion_vendedor_comentario'],\n 'respuesta' : record['valoracion_vendedor_respuesta'],\n }\n operacion['publicacion'] = {\n 'id_publicacion': record['id_publicacion'],\n 'titulo': record['titulo'],\n 'descripcion': record['descripcion'],\n 'fecha': record['fecha'],\n 'id_tipo_publicacion': record['id_tipo_publicacion'],\n 'publicada_por': record['publicada_por'],\n 'tipo': record['tipo'],\n 'tipo_publicacion': record['tipo_publicacion'],\n }\n return operacion\n\ndef factura_record_to_dict(record):\n factura = dict()\n factura['usuario'] = record['id_usuario']\n factura['mes'] = record['mes']\n factura['monto_suscripciones'] = record['suscripciones']\n factura['monto_comisiones'] = record['comisiones']\n return factura\n","repo_name":"lbarrios/uba-dc-bd_2016-1c_tp2","sub_path":"converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5202547280","text":"\"\"\"\r\nExercício\r\nCrie uma função que encontra o primeiro duplicado considerando o segundo\r\nnúmero como a duplicação. Retorne a duplicação considerada.\r\nRequisitos:\r\n A ordem do número duplicado é considerada a partir da segunda\r\n ocorrência do número, ou seja, o número duplicado em si.\r\n Exemplo:\r\n [1, 2, 3, ->3<-, 2, 1] -> 1, 2 e 3 são duplicados (retorne 3)\r\n [1, 2, 3, 4, 5, 6] -> Retorne -1 (não tem duplicados)\r\n [1, 4, 9, 8, ->9<-, 4, 8] (retorne 9)\r\n Se não encontrar duplicados na lista, retorne -1\r\n\"\"\"\r\n\r\nlista_de_listas_de_inteiros = [\r\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\r\n [9, 1, 8, 9, 9, 7, 2, 1, 6, 8],\r\n [1, 3, 2, 2, 8, 6, 5, 9, 6, 7],\r\n [3, 8, 2, 8, 6, 7, 7, 3, 1, 9],\r\n [4, 8, 8, 8, 5, 1, 10, 3, 1, 7],\r\n [1, 3, 7, 2, 2, 1, 5, 1, 9, 9],\r\n [10, 2, 2, 1, 3, 5, 10, 5, 10, 1],\r\n [1, 6, 1, 5, 1, 1, 1, 4, 7, 3],\r\n [1, 3, 7, 1, 10, 5, 9, 2, 5, 7],\r\n [4, 7, 6, 5, 2, 9, 2, 1, 2, 1],\r\n [5, 3, 1, 8, 5, 7, 1, 8, 8, 7],\r\n [10, 9, 8, 7, 6, 5, 4, 3, 2, 1],\r\n]\r\n\r\nn = 0\r\nnumbers = []\r\nfor indices in lista_de_listas_de_inteiros:\r\n lista = lista_de_listas_de_inteiros[n]\r\n n = n + 1\r\n print(lista)\r\n for i in lista:\r\n numbers.append(i)\r\n last = numbers[-1]\r\n if len(numbers) > 1:\r\n if last in repetidos:\r\n duplicado = numbers.pop()\r\n print(f'o primeiro número duplicado é', duplicado)\r\n repetidos.clear()\r\n numbers.clear()\r\n break\r\n if len(numbers) == 10:\r\n print(-1)\r\n repetidos.clear()\r\n numbers.clear()\r\n repetidos = set(numbers)\r\n\r\n# FAZENDO USANDO FUNÇÃO:\r\n\r\ndef encontra_primeiro_duplicado(lista_de_inteiros):\r\n n_checados = set()\r\n primeiro_duplicado = -1\r\n\r\n for numero in lista_de_inteiros:\r\n if numero in n_checados:\r\n primeiro_duplicado = numero\r\n break\r\n n_checados.add(numero)\r\n\r\n return primeiro_duplicado\r\n\r\nfor lista in lista_de_listas_de_inteiros:\r\n print(lista, encontra_primeiro_duplicado(lista)) #recebeu lista como argumento)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"rafalimma/learningpython","sub_path":"aula85-exercicio.py","file_name":"aula85-exercicio.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"4156785570","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 13 00:08:23 2018\r\n\r\n@author: Kaushal\r\n\"\"\"\r\n\r\n#Scope Rules\r\n#Python searches for the object, layer by layer, moving from inner layers towards\r\n#outer layers, and it uses the first update function or the first x variable that it\r\n#finds.\r\n\r\n#Scope Rule\r\n#LEGB\r\n#Local\r\n#Enclosing function\r\n#Global\r\n#Built-in\r\n\r\n#In other words, local is the current function you are in.\r\n#Enclosing function is the function that called the current function, if any.\r\n#Global refers to the module in which the function was defined.\r\n#And Built-in refers to Python's buit-in namespace\r\n\r\n#We can manipulate global variables, variables defined in the global scope, from within\r\n#functions.\r\n\r\n\r\n\r\n#Mutability, Immutability and Scope Rules\r\ndef update(n,x):\r\n n = 2\r\n y = x\r\n y.append(2)\r\n print('update:', n, y)\r\n \r\ndef main():\r\n n = 1\r\n x = [0,1,2,3]\r\n print('main:', n, x)\r\n update(n,x)\r\n print('main:', n, x)\r\n \r\n \r\nmain()\r\n\r\n#An arguement is an object that is passed to a function as its input when the\r\n#function is called.\r\n#A parameter, in cotrast, is a variable that is used in the function defination\r\n#to refer to that arguement.\r\n\r\nsome_guy = 'Fred'\r\n\r\nfirst_names = []\r\nfirst_names.append(some_guy)\r\n\r\nprint(some_guy is first_names[0])\r\n\r\nanother_list_of_names = first_names\r\nanother_list_of_names.append('George')\r\nsome_guy = 'Bill'\r\n\r\n\r\nfirst_names = ['Fred', 'George', 'Bill']\r\nlast_names = ['Smith', 'Jones', 'Williams']\r\nname_tuple = (first_names, last_names)\r\n\r\nfirst_names.append('Igor')\r\n\r\nprint (some_guy, first_names, another_list_of_names)","repo_name":"KaushalTak/Python-for-Research","sub_path":"Scope Rules.py","file_name":"Scope Rules.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74192280165","text":"from flask import jsonify\nfrom app import db, app\nfrom app.auth import basic_auth, token_auth\n\n\n@app.route('/api/tokens', methods=['POST'])\n@basic_auth.login_required\ndef get_token():\n data = basic_auth.current_user().get_token()\n db.session.commit()\n return jsonify(data)\n\n\n@app.route('/api/tokens', methods=['DELETE'])\n@token_auth.login_required\ndef revoke_token():\n token_auth.current_user().revoke_token()\n db.session.commit()\n return '', 204\n\n#curl -X GET -H \"Authorization: Bearer 18yra2aIeQVqmzKcDk0cD8bfmJILpm4n\" http://localhost:5000/api/users/30\n","repo_name":"kollie/wolomapp-backend","sub_path":"app/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"37723520347","text":"#!/usr/bin/env python\n\nimport sys\nimport random\n\ntemplate = ''' {\n \"name\": \"powermule\",\n \"addr\": \"10.99.176.%d:7946\",\n \"port\": 7946,\n \"tags\": {\n \"role\": \"%s\"\n },\n \"status\": \"alive\",\n \"protocol\": {\n \"max\": 4,\n \"min\": 2,\n \"version\": 4\n }\n }%s\n'''\n\nprint('''{\n \"members\": [''')\nnlines = int(sys.argv[1])\nroles = ['ui', 'database', 'loadbalancer']\nfor i in range(nlines):\n\tprint(template % (i, random.choice(roles), '' if i == nlines - 1 else ','))\nprint(''']\n}''')\n","repo_name":"pinireznik/antitude","sub_path":"antitudeUI/make_members.py","file_name":"make_members.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30316790866","text":"r\"\"\".. _ref_vm18:\n\nOut-of-Plane Bending of a Curved Bar\n------------------------------------\nProblem description:\n - A portion of a horizontal circular ring, built-in at A, is loaded by a vertical (Z)\n load F applied at the end B. The ring has a solid circular cross-section of diameter d.\n Determine the deflection :math:`\\delta` at end B, the maximum bending\n stress :math:`\\sigma_{Bend}` , and the maximum torsional shear stress τ.\n\nReference:\n - S. Timoshenko, Strength of Materials, Part I, Elementary Theory and\n Problems, 3rd Edition, D. Van Nostrand Co., Inc., New York, NY, 1955,\n pg. 412, eq. 241.\n\nAnalysis type(s):\n - Static Analysis ``ANTYPE=0``\n\nElement type(s):\n - Elastic Curved Pipe Element (PIPE18)\n - 3-D 3 Node Pipe Element (PIPE289)\n\n.. figure:: ../_static/vm18_setup1.png\n :align: center\n :width: 400\n :alt: VM18 Curved Bar Problem Sketch\n\n.. figure:: ../_static/vm18_setup2.png\n :align: center\n :width: 400\n :alt: VM18 Curved Bar Finite Element Model\n\nMaterial properties:\n - :math:`E = 30 \\cdot 10^6 psi`\n - :math:`\\mu = 0.3`\n\nGeometric properties:\n - :math:`r = 100 in`\n - :math:`d = 2 in`\n - :math:`\\theta = 90°`\n\nLoading:\n - :math:`F = 50 lb`\n\nAnalysis Assumptions and Modeling Notes:\n - Node 10 is arbitrarily located on the radius of curvature side of the element to define the\n plane of the elbow when PIPE18 elements are used. The wall thickness is set to half the diameter\n for a solid bar. Since the section has no hole in the middle, ovalization cannot occur and\n PIPE289 elements can be used to determine the deflection and stresses.\n\n\"\"\"\n# sphinx_gallery_thumbnail_path = '_static/vm18_setup1.png'\n\n# Importing the `launch_mapdl` function from the `ansys.mapdl.core` module\nfrom ansys.mapdl.core import launch_mapdl\nimport numpy as np\nimport pandas as pd\n\n# Launch MAPDL with specified settings\nmapdl = launch_mapdl(loglevel=\"WARNING\", print_com=True, remove_temp_dir_on_exit=True)\n\n# Clear the existing database\nmapdl.clear()\n\n# Run the FINISH command to exists normally from a processor\nmapdl.finish()\n\n# Set the ANSYS version\nmapdl.com(\"ANSYS MEDIA REL. 2022R2 (05/13/2022) REF. VERIF. MANUAL: REL. 2022R2\")\n\n# Run the /VERIFY command\nmapdl.run(\"/VERIFY,VM18\")\n\n# Set the title of the analysis\nmapdl.title(\"VM18 OUT-OF-PLANE BENDING OF A CURVED BAR\")\n\n# Enter the model creation /Prep7 preprocessor\nmapdl.prep7()\n\n###############################################################################\n# Define element type and real properties\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Use Elastic Curved Pipe element (PIPE18) and set KEYOPT(6)=2 for printing member forces.\nmapdl.et(1, \"PIPE18\", \"\", \"\", \"\", \"\", \"\", 2)\n\n# Define geometry parameters (OD, wall thickness, radius) using \"r\" command (real constant)\nmapdl.r(1, 2, 1, 100)\n\n##################################################################################\n# Define material\n# ~~~~~~~~~~~~~~~\n# Set up the material and its type (a single material), Young's modulus of 30e6\n# and Poisson's ratio NUXY of 0.3 is specified.\nmapdl.mp(\"EX\", 1, 30e6)\nmapdl.mp(\"NUXY\", 1, 0.3)\n\n###############################################################################\n# Define geometry\n# ~~~~~~~~~~~~~~~\n# Set up the nodes and elements. This creates a mesh just like in the\n# problem setup.\n\n# Define nodes\nmapdl.n(1, 100)\nmapdl.n(2, \"\", 100)\nmapdl.n(10)\n\n# Define element\nmapdl.e(1, 2, 10)\n\n###############################################################################\n# Define boundary conditions and load\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Fix all dofs at node 1. Specify nodal force F = -50 lb along Z direction at node 2.\n# Then exit prep7 processor.\n\nmapdl.d(1, \"ALL\") # Define boundary conditions\nmapdl.f(2, \"FZ\", -50) # Define load\n\n# Selects all entities\nmapdl.allsel()\n# Element plot\nmapdl.eplot(vtk=False)\n\n# Finish preprocessing processor\nmapdl.finish()\n\n###############################################################################\n# Solve\n# ~~~~~\n# Enter solution mode and solve the system.\nmapdl.slashsolu()\n\n# Set the analysis type to STATIC\nmapdl.antype(\"STATIC\")\n\n# Set output options\nmapdl.outpr(\"BASIC\", 1)\n\n# Perform the solution\nmapdl.solve()\n# exists solution processor\nmapdl.finish()\n\n###############################################################################\n# Post-processing\n# ~~~~~~~~~~~~~~~\n# Enter post-processing. Compute deflection and stress quantities.\nmapdl.post1()\n\n# Set the current results set to the last set to be read from result file\nmapdl.set(\"LAST\")\n\n# Get displacement results at node 2 in the Z direction\ndef_z = mapdl.get(\"DEF\", \"NODE\", 2, \"U\", \"Z\")\n\n# Create an element table for bending stresses using ETABLE command\nstrs_ben = mapdl.etable(\"STRS_BEN\", \"NMISC\", 91)\n\n# Create an element table for shear stresses using ETABLE command\nstrs_shr = mapdl.etable(\"STRS_SHR\", \"LS\", 4)\n\n# Get bending stresses (ETAB: STRS_BEN) for element 1\nstrss_b = mapdl.get(\"STRSS_B\", \"ELEM\", 1, \"ETAB\", \"STRS_BEN\")\n\n# Get shear stresses (ETAB: STRS_SHR) for element 1\nstrss_t = mapdl.get(\"STRSS_T\", \"ELEM\", 1, \"ETAB\", \"STRS_SHR\")\n\n###############################################################################\n# Verify the results.\n# ~~~~~~~~~~~~~~~~~~~\n\n# Set target values\ntarget_val = [-2.648, 6366, -3183]\n\n# Fill result values\nsim_res = [def_z, strss_b, strss_t]\n\ncol_headers = [\"TARGET\", \"Mechanical APDL\", \"RATIO\"]\nrow_headers = [\"Deflection (in)\", \"Stress_Bend (psi)\", \"Shear Stress (psi)\"]\n\ndata = [target_val, sim_res, np.abs(target_val) / np.abs(sim_res)]\n\ntitle = f\"\"\"\n\n------------------- VM18 RESULTS COMPARISON ---------------------\n\nPIPE18:\n-------\n\"\"\"\n\nprint(title)\nprint(pd.DataFrame(np.transpose(data), row_headers, col_headers))\n\n###############################################################################\n# Finish the post-processing processor.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.finish()\n\n###############################################################################\n# Clears the database without restarting.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.run(\"/CLEAR,NOSTART\")\n\n###############################################################################\n# Set a new title for the analysis\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.title(\"VM18 OUT-OF-PLANE BENDING OF A CURVED BAR Using PIPE289 ELEMENT MODEL\")\n\n###############################################################################\n# Switches to the preprocessor (PREP7)\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.prep7()\n\n###############################################################################\n# Define element type and section properties\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Use 3-D 3-Node Pipe element (PIPE289) and set KEYOPT(4)= 2 Thick pipe theory.\nmapdl.et(1, \"PIPE289\", \"\", \"\", \"\", 2)\nmapdl.sectype(1, \"PIPE\") # Set section type PIPE\nmapdl.secdata(2, 1, 16) # Set section data (OD, wall thickness)\n\n##################################################################################\n# Define material\n# ~~~~~~~~~~~~~~~\n# Set up the material and its type (a single material), Young's modulus of 30e6\n# and Poisson's ratio NUXY of 0.3 is specified.\nmapdl.mp(\"EX\", 1, 30e6)\nmapdl.mp(\"NUXY\", 1, 0.3)\n\n###############################################################################\n# Define geometry\n# ~~~~~~~~~~~~~~~\n# Set up the nodes and elements. This creates a mesh just like in the\n# problem setup.\n\nmapdl.csys(1) # Set coordinate system to 1\n\nmapdl.n(1, 100) # Define nodes\n\n# Generate additional nodes\nmapdl.ngen(19, 1, 1, \"\", \"\", \"\", 5)\n\n# Define element\nmapdl.e(1, 3, 2)\n\n# Generate additional elements from an existing pattern\nmapdl.egen(9, 2, -1)\n\n# Reset coordinate system to global\nmapdl.csys(0)\n\n###############################################################################\n# Define boundary conditions and load\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Fix all dofs at node 1. Specify nodal force F = -50 lb along Z direction at node 19.\n# Then exit prep7 processor.\nmapdl.d(1, \"ALL\")\nmapdl.f(19, \"FZ\", -50)\n\n# Selects all entities\nmapdl.allsel()\n# Element plot\nmapdl.eplot(vtk=False)\n\n# exists pre-processing processor\nmapdl.finish()\n\n###############################################################################\n# Solve\n# ~~~~~\n# Enter solution mode and solve the system.\nmapdl.slashsolu()\n\n# Set the analysis type to STATIC\nmapdl.antype(\"STATIC\")\n\n# Set output options\nmapdl.outpr(\"BASIC\", 1)\n\n# Perform the solution\nmapdl.solve()\n# exists solution processor\nmapdl.finish()\n\n###############################################################################\n# Post-processing\n# ~~~~~~~~~~~~~~~\n# Enter post-processing. Compute deflection and stress quantities.\nmapdl.post1()\n\n# Set the current results set to the last set\nmapdl.set(\"LAST\")\nmapdl.graphics(\"POWER\") # Set graphics mode to POWER\nmapdl.eshape(1) # Set element shape\nmapdl.view(1, 1, 1, 1) # Set view\n\n# Get displacement results at node 19 in the Z direction\ndef_z = mapdl.get(\"DEF\", \"NODE\", 19, \"U\", \"Z\")\n\n# Create an element table for bending stresses using ETABLE command\nstrs_ben = mapdl.etable(\"STRS_BEN\", \"SMISC\", 35)\n\n# Get bending stresses (ETAB: STRS_BEN) for element 1 using ETABLE command\nstrss_b = mapdl.get(\"STRSS_B\", \"ELEM\", 1, \"ETAB\", \"STRS_BEN\")\n\n# for graphics displays\nmapdl.show(option=\"REV\")\n# Plot elemtal solution values for SXY component\nmapdl.plesol(\"S\", \"XY\")\n# Get minimum shear stress\nshear_sxy = mapdl.get(\"SHEAR\", \"PLNSOL\", 0, \"MIN\")\nmapdl.show(\"close\")\n\n###############################################################################\n# Verify the results.\n# ~~~~~~~~~~~~~~~~~~~\n\n# Set target values\ntarget_val = [-2.648, 6366, -3183]\n\n# Fill result values\nsim_res = [def_z, strss_b, shear_sxy]\n\ncol_headers = [\"TARGET\", \"Mechanical APDL\", \"RATIO\"]\nrow_headers = [\"Deflection (in)\", \"Stress_Bend (psi)\", \"Shear Stress (psi)\"]\n\ndata = [target_val, sim_res, np.abs(target_val) / np.abs(sim_res)]\n\ntitle = f\"\"\"\n\nPIPE289:\n--------\n\"\"\"\n\nprint(title)\nprint(pd.DataFrame(np.transpose(data), row_headers, col_headers))\n\n###############################################################################\n# Finish the post-processing processor.\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmapdl.finish()\n\n###############################################################################\n# Stop MAPDL.\n# ~~~~~~~~~~~\nmapdl.exit()\n","repo_name":"ansys/pymapdl-examples","sub_path":"examples/verif-manual/vm-018.py","file_name":"vm-018.py","file_ext":"py","file_size_in_byte":10311,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"1551765363","text":"#-*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport struct\r\nimport matplotlib.pyplot as plt\r\n#训练集的文件\r\ntrain_images_idx3_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/train-images.idx3-ubyte'\r\n#训练集标签文件\r\ntrain_labels_idx1_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/train-labels.idx1-ubyte'\r\n## 测试集文件\r\ntest_images_idx3_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/t10k-images.idx3-ubyte'\r\n# 测试集标签文件\r\ntest_labels_idx1_ubyte_file = 'F:/python/marchine_learning_note/MINST_data/t10k-labels.idx1-ubyte'\r\n\r\n#读取并解析idx3的通用函数\r\ndef decode_idx3_ubyte(idx3_ubyte_file):\r\n #读取二进制数据\r\n bin_data = open(idx3_ubyte_file,'rb').read()\r\n #解析文件头信息\r\n offset = 0 #从文件的第几个字节开始读取\r\n fmt_header = '>iiii' #>代表大端,内存从左到右存储的字节越来越大 i代表无符号整型\r\n magic_number,num_images,num_rows,num_cols=struct.unpack_from(fmt_header,bin_data,offset)\r\n print(\"magic_number: %d\\nthe number of images: %d\\nthe size of images: %d,%d\\n\" % (magic_number,num_images,num_rows,num_cols))\r\n\r\n #解析数据集\r\n image_size = num_rows * num_cols\r\n offset += struct.calcsize(fmt_header) #获得数据在缓存中的指针位置 calcsize函数可以计算参数给定的数据格式占用的内存字节大小\r\n print(offset)\r\n fmt_image = '>' + str(image_size) + 'B' #读取image_size(28*28)个B格式数据 B对应unsignedchar\r\n print(\"读取的数据 开始的内存指针位置 读取数据的大小\")\r\n print(fmt_image,offset,struct.calcsize(fmt_image))\r\n images = np.empty((num_images,num_rows,num_cols))\r\n\r\n for i in range(num_images):\r\n if(i + 1) % 10000 ==0:\r\n print(\"%d pieces of images have been parsed\" % (i + 1))\r\n print(offset)\r\n\r\n images[i] = np.array(struct.unpack_from(fmt_image,bin_data,offset)).reshape((num_rows,num_cols))\r\n #print(images[i])\r\n offset += struct.calcsize(fmt_image) #指针移动fmt_image个大小的位置\r\n plt.imshow(images[i],'gray')#用matplotlib的imshow可以通过传入数组和图谱参数来显示图像\r\n plt.pause(0.00001)\r\n plt.show()\r\n exit()\r\n return images\r\n\r\ndef decode_idx1_ubyte(idx1_ubyte_file):\r\n #读取二进制数据\r\n bin_data = open(idx1_ubyte_file,'rb').read()\r\n\r\n #解析文件头信息 分别是magic_number 和 num_images\r\n offset = 0\r\n fmt_header = '>ii'\r\n magic_number,num_images = struct.unpack_from(fmt_header,bin_data,offset)\r\n print(\"the magic number : %d\" %magic_number)\r\n print(\"the label number : %d\" %num_images)\r\n\r\n #解析数据集\r\n offset += struct.calcsize(fmt_header)\r\n fmt_image = '>B'\r\n labels = np.empty(num_images)\r\n for i in range(num_images):\r\n if(i + 1) % 10000 == 0:\r\n print('%d pieces of labels have been parsed' % (i + 1))\r\n labels[i] = struct.unpack_from(fmt_image,bin_data,offset)[0] #只读取从offset位置开始的fmt_image数据的第一个\r\n offset += struct.calcsize(fmt_image) #把指针更新到offset的位置\r\n #print(labels[i])\r\n #print(type(labels[i]))\r\n #exit()\r\n #print(labels[5000])\r\n return labels\r\n\r\n\r\n\r\n\r\n\r\n#decode_idx1_ubyte(train_labels_idx1_ubyte_file)\r\n#decode_idx3_ubyte(train_images_idx3_ubyte_file)\r\n\r\n\r\n","repo_name":"Crystal-Dragon-Liu/ML_practise","sub_path":"marchine_learning_note/MINST_data/MINST_DATA.py","file_name":"MINST_DATA.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"37019498751","text":"#Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\eve\\client\\script\\ui\\shared\\languageWindow.py\r\nfrom carbonui.primitives.containerAutoSize import ContainerAutoSize\r\nfrom carbonui.primitives.layoutGrid import LayoutGrid\r\nfrom carbonui.primitives.line import Line\r\nfrom eve.client.script.ui.control.buttonGroup import ButtonGroup\r\nfrom eve.client.script.ui.control.checkbox import Checkbox\r\nfrom eve.client.script.ui.control.eveCombo import Combo\r\nfrom eve.client.script.ui.control.eveLabel import WndCaptionLabel, EveLabelMedium\r\nfrom eve.client.script.ui.control.eveWindow import Window\r\nfrom localization import GetByLabel\r\nimport carbonui.const as uiconst\r\nimport localization\r\nfrom localization.const import IMPORTANT_EN_OVERRIDE\r\nfrom localization.util import ConvertLanguageIDToMLS\r\nmlsToDisplayNamePaths = {'JA': 'UI/SystemMenu/Language/LanguageJapanese',\r\n 'DE': 'UI/SystemMenu/Language/LanguageGerman',\r\n 'EN': 'UI/SystemMenu/Language/LanguageEnglish',\r\n 'FR': 'UI/SystemMenu/Language/LanguageFrench',\r\n 'RU': 'UI/SystemMenu/Language/LanguageRussian',\r\n 'ZH': 'UI/SystemMenu/Language/LanguageChinese'}\r\n\r\nclass LanguageWindow(Window):\r\n __guid__ = 'LanguageWindow'\r\n default_windowID = 'bilingualWindow'\r\n default_captionLabelPath = 'UI/LanguageWindow/BilingualFunctionalityHeader'\r\n default_iconNum = 'res:/ui/Texture/WindowIcons/Settings.png'\r\n\r\n def ApplyAttributes(self, attributes):\r\n Window.ApplyAttributes(self, attributes)\r\n self.SetWndIcon('res:/ui/Texture/WindowIcons/Settings.png', mainTop=-6)\r\n self.SetMainIconSize(64)\r\n self.width = 350\r\n self.height = 400\r\n self.MakeUnResizeable()\r\n self.currentComboValue = localization.settings.bilingualSettings.GetValue('localizationImportantNames')\r\n WndCaptionLabel(text=GetByLabel('UI/LanguageWindow/BilingualFunctionalityHeader'), parent=self.sr.topParent, align=uiconst.RELATIVE)\r\n self.autoSizeMain = ContainerAutoSize(parent=self.sr.main, name='autoSizeMain', align=uiconst.TOTOP, callback=self.OnAutoSizeMainResize, padLeft=2, padRight=2)\r\n text = GetByLabel('UI/LanguageWindow/BodyText')\r\n EveLabelMedium(text=text, parent=self.autoSizeMain, align=uiconst.TOTOP, padding=(10, 4, 10, 0))\r\n self.btnGroup = ButtonGroup(parent=self.sr.main, idx=0)\r\n self.btnGroup.AddButton(GetByLabel('UI/Commands/Apply'), self.Save)\r\n self.btnGroup.AddButton(GetByLabel('UI/Common/Close'), self.Cancel)\r\n grid = LayoutGrid(parent=self.autoSizeMain, align=uiconst.TOTOP, columns=2, name='grid', padTop=10, padLeft=20, cellSpacing=4)\r\n languageID = ConvertLanguageIDToMLS(session.languageID)\r\n self.currentLanguageString = GetByLabel(mlsToDisplayNamePaths[languageID])\r\n text = GetByLabel('UI/SystemMenu/Language/Display')\r\n comboLabel = EveLabelMedium(text=text, parent=grid, align=uiconst.TOPLEFT, state=uiconst.UI_NORMAL)\r\n comboLabel.hint = GetByLabel('UI/SystemMenu/Language/ImportantNamesExplanation')\r\n options = [(self.currentLanguageString, 0), (GetByLabel('UI/SystemMenu/Language/EnglishReplacement'), IMPORTANT_EN_OVERRIDE)]\r\n self.displayCombo = Combo(label='', parent=grid, options=options, name='displayCombo', select=self.currentComboValue, width=115, pos=(10, 0, 0, 0), align=uiconst.TOPLEFT, callback=self.OnComboChanged, hint=GetByLabel('UI/SystemMenu/Language/ImportantNamesExplanation'))\r\n tooltipText = self.GetTooltipCheckboxText()\r\n checked = localization.settings.bilingualSettings.GetValue('languageTooltip')\r\n self.tooltipCB = Checkbox(text=tooltipText, parent=None, configName='tooltipsCB', checked=checked, align=uiconst.TOPLEFT, width=300)\r\n grid.AddCell(cellObject=self.tooltipCB, colSpan=grid.columns)\r\n hiliteImportantText = GetByLabel('UI/SystemMenu/Language/HighlightImportantNames')\r\n checked = localization.settings.bilingualSettings.GetValue('localizationHighlightImportant')\r\n self.importantCB = Checkbox(text=hiliteImportantText, parent=None, configName='importantNamesCB', checked=checked, align=uiconst.TOPLEFT, width=300)\r\n grid.AddCell(cellObject=self.importantCB, colSpan=grid.columns)\r\n text = localization.GetByLabel('UI/LanguageWindow/ChangeSettingsInEsc')\r\n EveLabelMedium(text=text, parent=self.autoSizeMain, align=uiconst.TOTOP, padding=(10, 10, 10, 0))\r\n Line(parent=self.autoSizeMain, align=uiconst.TOTOP, color=(1, 1, 1, 0.1), padTop=4, padBottom=2)\r\n text = GetByLabel('UI/Messages/TxtSuppress2Body')\r\n self.suppressCb = Checkbox(text=text, parent=self.autoSizeMain, configName='importantNamesCB', retval=0, checked=0, align=uiconst.TOTOP, padLeft=6)\r\n\r\n def OnAutoSizeMainResize(self):\r\n headerHeight = self.GetCollapsedHeight()\r\n captionHeight = self.topParentHeight\r\n if getattr(self, 'btnGroup', None):\r\n buttonHeight = self.btnGroup.height\r\n else:\r\n buttonHeight = 0\r\n autoContainerSize = self.autoSizeMain.height + self.autoSizeMain.padTop + self.autoSizeMain.padBottom + buttonHeight\r\n newheight = headerHeight + captionHeight + autoContainerSize\r\n if newheight != self.height:\r\n self.height = newheight\r\n self.SetFixedHeight(self.height)\r\n\r\n def GetTooltipCheckboxText(self):\r\n if self.currentComboValue == localization.const.IMPORTANT_EN_OVERRIDE:\r\n tooltipText = GetByLabel('UI/SystemMenu/Language/ShowTooltipInLanguage', language=self.currentLanguageString)\r\n else:\r\n english = GetByLabel(mlsToDisplayNamePaths['EN'])\r\n tooltipText = GetByLabel('UI/SystemMenu/Language/ShowTooltipInLanguage', language=english)\r\n return tooltipText\r\n\r\n def OnComboChanged(self, combo, key, value, *args):\r\n self.currentComboValue = value\r\n tooltipText = self.GetTooltipCheckboxText()\r\n self.tooltipCB.SetLabel(tooltipText)\r\n\r\n def Save(self, *args):\r\n changeMade = False\r\n importantNamesLocalized = self.displayCombo.GetValue()\r\n if self.GetLanguageSetting('localizationImportantNames') != importantNamesLocalized:\r\n changeMade = True\r\n self.SetLanguageSetting('localizationImportantNames', importantNamesLocalized)\r\n tooltipChecked = self.tooltipCB.checked\r\n if self.GetLanguageSetting('languageTooltip') != tooltipChecked:\r\n changeMade = True\r\n self.SetLanguageSetting('languageTooltip', tooltipChecked)\r\n importantNameChecked = self.importantCB.checked\r\n if self.GetLanguageSetting('localizationHighlightImportant') != importantNameChecked:\r\n changeMade = True\r\n self.SetLanguageSetting('localizationHighlightImportant', importantNameChecked)\r\n localization.ClearImportantNameSetting()\r\n self.StoreSuppressSettingAndCloseWindow()\r\n if changeMade:\r\n localization.settings.bilingualSettings.UpdateAndSaveSettings()\r\n sm.ChainEvent('ProcessUIRefresh')\r\n sm.ScatterEvent('OnUIRefresh')\r\n\r\n def Cancel(self, *args):\r\n self.StoreSuppressSettingAndCloseWindow()\r\n\r\n def StoreSuppressSettingAndCloseWindow(self):\r\n suppressedChecked = self.suppressCb.checked\r\n if suppressedChecked:\r\n settings.user.suppress.Set('suppress.Bilingual_suppressMessage', True)\r\n self.CloseByUser()\r\n\r\n def GetLanguageSetting(self, configName):\r\n return localization.settings.bilingualSettings.GetValue(configName)\r\n\r\n def SetLanguageSetting(self, configName, value):\r\n return localization.settings.bilingualSettings.SetValue(configName, value)\r\n","repo_name":"connoryang/dec-eve-serenity","sub_path":"client/eve/client/script/ui/shared/languageWindow.py","file_name":"languageWindow.py","file_ext":"py","file_size_in_byte":7730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"18984291622","text":"import requests\n\n# Ruta de la API para analizar un archivo comprimido en formato bz2 y realizar el análisis de números de coincidencias.\n# Recibe una solicitud POST con un archivo comprimido en formato bz2.\n# Realiza el análisis de números de coincidencias en el archivo.\n# Devuelve los resultados del análisis en formato JSON.\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n\n#Ruta principal que renderiza la página index.html.\n\n return render_template('index.html')\n\n@app.route('/analisis', methods=['POST'])\ndef analizar_archivo():\n \n try:\n archivo = request.files['archivo']\n except KeyError:\n return jsonify({'error': 'No se proporcionó ningún archivo en la solicitud POST.'}), 400\n\n datos = []\n with bz2.open(archivo, 'rt') as f:\n df = pd.read_csv(f, sep=',', header=None, names=[\"Time\", \"Duration\", \"SrcDevice\", \"DstDevice\", \"Protocol\", \"SrcProt\", \"DstPort\", \"SrcPackets\", \"DstPackets\", \"SrcBytes\", \"DstBytes\"])\n datos = df.to_dict(orient='records')\n\n return jsonify(datos)\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"ericitstep/ProyectoFinal","sub_path":"analisis.py","file_name":"analisis.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"19561578982","text":"from __future__ import annotations\n\nimport logging\n\nimport requests\n\nfrom comictaggerlib import ctversion\n\nlogger = logging.getLogger(__name__)\n\n\nclass VersionChecker:\n def get_request_url(self, uuid: str) -> tuple[str, dict[str, str]]:\n base_url = \"https://api.github.com/repos/comictagger/comictagger/releases/latest\"\n params: dict[str, str] = {}\n\n return base_url, params\n\n def get_latest_version(self, uuid: str) -> tuple[str, str]:\n try:\n url, params = self.get_request_url(uuid)\n release = requests.get(\n url,\n params=params,\n headers={\"user-agent\": \"comictagger/\" + ctversion.version},\n ).json()\n except Exception:\n return \"\", \"\"\n\n new_version = release[\"tag_name\"]\n if new_version is None or new_version == \"\":\n return \"\", \"\"\n return new_version.strip(), release[\"name\"]\n","repo_name":"comictagger/comictagger","sub_path":"comictaggerlib/versionchecker.py","file_name":"versionchecker.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":444,"dataset":"github-code","pt":"52"}
+{"seq_id":"32592616951","text":"def max_returns(prices):\n \"\"\"\n Calculate maxiumum possible return\n \n Args:\n prices(array): array of prices\n Returns:\n int: The maximum profit possible\n \"\"\"\n current_min_index = 0\n min_price_index = 0\n max_price_index = 0\n for index in range(len(prices)):\n if prices[index] < prices[current_min_index]:\n current_min_index = index\n \n if prices[index] - prices[current_min_index] > prices[max_price_index] - prices[min_price_index]:\n max_price_index = index\n min_price_index = current_min_index\n \n return prices[max_price_index] - prices[min_price_index]\n\nprices = [2, 2, 7, 9, 9, 12, 18, 23, 34, 37, 45, 54, 78]\nsolution = 76\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [54, 18, 37, 9, 11, 48, 23, 1, 7, 34, 2, 45, 67]\nsolution = 66\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [40, 100, 1, 50]\nsolution = 60\ntest_case = [prices, solution]\ntest_function(test_case)\n\nprices = [78, 54, 45, 37, 34, 23, 18, 12, 9, 9, 7, 2, 2]\nsolution = 0\ntest_case = [prices, solution]\ntest_function(test_case)","repo_name":"sh-tatsuno/python-algorithm","sub_path":"advanced/dynamic_programming/stock_prices.py","file_name":"stock_prices.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41609900443","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport numpy as np\nimport tensorflow as tf\nimport math\nimport reader\nimport util\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-model', type=str, default='small',\n choices=['small', 'medium', 'large', 'test'])\nparser.add_argument('-data_path', type=str, default='./data/simple-examples/data')\nparser.add_argument('-save_path', type=str, default='./model/saved_new')\nparser.add_argument('-prior_pi', type=float, default=0.25)\nparser.add_argument('-log_sigma1', type=float, default=-1.0)\nparser.add_argument('-log_sigma2', type=float, default=-7.0)\nparser.add_argument('-inference_mode', type=str, default='sample')\nparser.add_argument('-b_stochastic', type=int, default=1)\nparser.add_argument('-random_seed', type=int, default=12)\nFLAGS = parser.parse_args()\nFLAGS.b_stochastic = bool(FLAGS.b_stochastic)\n\n\ndef data_type():\n\treturn tf.float32\n\n\n# Helpers\ndef logsum_mog(x, pi, mu1, mu2, sigma1, sigma2):\n\treturn log_sum_exp(tf.log(pi) + log_normal(x, mu1, sigma1),\n\t tf.log(1. - pi) + log_normal(x, mu2, sigma2))\n\n\ndef log_sum_exp(u, v):\n\tm = tf.maximum(u, v)\n\treturn m + tf.log(tf.exp(u - m) + tf.exp(v - m))\n\n\ndef log_normal(x, mu, sigma):\n\treturn -0.5 * tf.log(2.0 * math.pi) - tf.log(tf.abs(sigma)) - tf.square((x - mu)) / (\n\t\t2 * tf.square(sigma))\n\n\ndef compute_KL(shape, mu, sigma, prior, sample):\n\tposterior = tf.contrib.distributions.Normal(mu, sigma)\n\tKL = tf.reduce_sum(posterior.log_prob(tf.reshape(sample, [-1])))\n\tN1 = tf.contrib.distributions.Normal(0.0, prior.sigma1)\n\tN2 = tf.contrib.distributions.Normal(0.0, prior.sigma2)\n\tmix1 = tf.reduce_sum(N1.log_prob(sample), 1) + tf.log(prior.pi_mixture)\n\tmix2 = tf.reduce_sum(N2.log_prob(sample), 1) + tf.log(1.0 - prior.pi_mixture)\n\tprior_mix = tf.stack([mix1, mix2])\n\tKL += -tf.reduce_sum(tf.reduce_logsumexp(prior_mix, [0]))\n\treturn KL\n\n\ndef get_config():\n\t\"\"\"Get model config.\"\"\"\n\tconfig = None\n\tif FLAGS.model == \"small\":\n\t\tconfig = SmallConfig()\n\telif FLAGS.model == \"medium\":\n\t\tconfig = MediumConfig()\n\telif FLAGS.model == \"large\":\n\t\tconfig = LargeConfig()\n\telif FLAGS.model == \"test\":\n\t\tconfig = TestConfig()\n\telse:\n\t\traise ValueError(\"Invalid model: %s\", FLAGS.model)\n\n\t# Set BBB params\n\tconfig.prior_pi = FLAGS.prior_pi\n\tconfig.log_sigma1 = FLAGS.log_sigma1\n\tconfig.log_sigma2 = FLAGS.log_sigma2\n\tconfig.b_stochastic = FLAGS.b_stochastic\n\n\treturn config\n\n\ndef get_bbb_variable(shape, name, prior, is_training):\n\t\"\"\"gets a bbb_variable.\n\n\tIt assumes Gaussian posterior and it creates two variables: name +'_mean',\n\twhich corresponds to the mean of the gaussian; and name+ '_rho' which\n\tcorresponds to the std of the gaussian (sigma = tf.nn.softplus(rho) + 1e-5).\n\n\tArgs:\n\t shape: shape of variable\n\t name: string with variable name\n\t prior: belongs to class Prior\n\t kl: if True will compute(approx) kl between prior and current variable and\n\t\t add it to a collection called \"KL_layers\"\n\t reuse: either to reuse variable or not\n\n\tReturns:\n\t output: sample from posterior Normal(mean, sigma)\n\t\"\"\"\n\n\t# No initializer specified -> will use the U(-scale, scale) init from main()\n\twith tf.variable_scope('BBB', reuse=not is_training):\n\t\tmu = tf.get_variable(name + '_mean', shape, dtype=data_type())\n\n\trho_max_init = math.log(math.exp(prior.sigma_mix / 1.0) - 1.0)\n\trho_min_init = math.log(math.exp(prior.sigma_mix / 2.0) - 1.0)\n\tinit = tf.random_uniform_initializer(rho_min_init, rho_max_init)\n\n\twith tf.variable_scope('BBB', reuse=not is_training):\n\t\trho = tf.get_variable(\n\t\t\tname + '_rho', shape, dtype=data_type(), initializer=init)\n\n\tif is_training or FLAGS.inference_mode == 'sample':\n\t\tepsilon = tf.contrib.distributions.Normal(0.0, 1.0).sample(shape)\n\t\tsigma = tf.nn.softplus(rho) + 1e-5\n\t\toutput = mu + sigma * epsilon\n\telse:\n\t\toutput = mu\n\n\tif not is_training:\n\t\treturn output\n\n\ttf.summary.histogram(name + '_rho_hist', rho)\n\ttf.summary.histogram(name + '_mu_hist', mu)\n\ttf.summary.histogram(name + '_sigma_hist', sigma)\n\n\tsample = output\n\t# kl = compute_kl(mu, sigma, prior, sample, name)\n\tkl = compute_KL(shape, tf.reshape(mu, [-1]), tf.reshape(sigma, [-1]), prior, sample)\n\ttf.add_to_collection('KL_layers', kl)\n\treturn output\n\n\nclass Prior(object):\n\tdef __init__(self, pi, log_sigma1, log_sigma2):\n\t\tself.pi_mixture = pi\n\t\tself.log_sigma1 = log_sigma1\n\t\tself.log_sigma2 = log_sigma2\n\t\tself.sigma1 = tf.exp(log_sigma1)\n\t\tself.sigma2 = tf.exp(log_sigma2)\n\n\t\tsigma_one, sigma_two = math.exp(log_sigma1), math.exp(log_sigma2)\n\t\tself.sigma_mix = np.sqrt(pi * np.square(sigma_one) + (1.0 - pi) * np.square(sigma_two))\n\n\tdef get_logp(self, sample):\n\t\tsigma1, sigma2 = tf.exp(self.log_sigma1), tf.exp(self.log_sigma2)\n\t\treturn logsum_mog(sample, self.pi_mixture, 0., 0., sigma1, sigma2)\n\n\ndef compute_kl(mu, sigma, prior, sample, name):\n\tlogp = prior.get_logp(sample)\n\tlogq = log_normal(sample, mu, sigma)\n\tkl = tf.reduce_sum(logq - logp)\n\n\ttf.summary.histogram(name + '_log_p', logp)\n\ttf.summary.histogram(name + '_log_q', logq)\n\treturn kl\n\n\nclass BayesianLSTM(tf.contrib.rnn.BasicLSTMCell):\n\t\"\"\"\n\tPass weights in init.\n\t\"\"\"\n\n\tdef __init__(self, num_units, theta, b, forget_bias=1.0, state_is_tuple=True,\n\t activation=tf.tanh,\n\t reuse=None, name=None):\n\t\tsuper(BayesianLSTM, self).__init__(num_units, forget_bias, state_is_tuple, activation,\n\t\t reuse=reuse)\n\n\t\tself.theta = theta\n\t\tself.b = b\n\t\tself.name = name\n\n\tdef _output(self, inputs, h):\n\t\t\"\"\"\n\t\tForward pass in the LSTM.\n\t\t\"\"\"\n\t\txh = tf.concat([inputs, h], 1)\n\t\tout = tf.matmul(xh, self.theta) + tf.squeeze(self.b)\n\t\treturn out\n\n\tdef call(self, inputs, state):\n\t\tif self._state_is_tuple:\n\t\t\tc, h = state\n\t\telse:\n\t\t\tc, h = tf.split(value=state, num_or_size_splits=2, axis=1)\n\n\t\tconcat = self._output(inputs, h)\n\t\ti, j, f, o = tf.split(value=concat, num_or_size_splits=4, axis=1)\n\n\t\tnew_c = (\n\t\t\tc * tf.sigmoid(f + self._forget_bias) + tf.sigmoid(i) * self._activation(j))\n\t\tnew_h = self._activation(new_c) * tf.sigmoid(o)\n\n\t\tif self._state_is_tuple:\n\t\t\tnew_state = tf.contrib.rnn.LSTMStateTuple(c=new_c, h=new_h)\n\t\telse:\n\t\t\tnew_state = tf.concat(values=[new_c, new_h], axis=1)\n\n\t\treturn new_h, new_state\n\n\nclass PTBInput(object):\n\t\"\"\"The input data.\"\"\"\n\n\tdef __init__(self, config, data, name=None):\n\t\tself.batch_size = batch_size = config.batch_size\n\t\tself.num_steps = num_steps = config.num_steps\n\t\tself.epoch_size = ((len(data) // batch_size) - 1) // num_steps\n\t\tself.input_data, self.targets = reader.ptb_producer(\n\t\t\tdata, batch_size, num_steps, name=name)\n\n\nclass PTBModel(object):\n\tdef __init__(self, is_training, config, input_):\n\t\tself._is_training = is_training\n\t\tself._input = input_\n\t\tself._rnn_params = None\n\t\tself._cell = None\n\t\tself.batch_size = input_.batch_size\n\t\tself.num_steps = input_.num_steps\n\t\tsize = config.hidden_size\n\t\tvocab_size = config.vocab_size\n\n\t\t# Construct prior\n\t\tprior = Prior(config.prior_pi, config.log_sigma1, config.log_sigma2)\n\n\t\twith tf.device(\"/cpu:0\"):\n\t\t\tembedding = get_bbb_variable([vocab_size, size], 'embedding', prior, is_training)\n\t\t\tinputs = tf.nn.embedding_lookup(embedding, input_.input_data)\n\n\t\t# Build the BBB LSTM cells\n\t\tcells = []\n\t\ttheta_shape = (size + config.hidden_size, 4 * config.hidden_size)\n\t\tb_shape = (4 * config.hidden_size, 1)\n\t\tfor i in range(config.num_layers):\n\t\t\ttheta = get_bbb_variable(theta_shape, 'theta_{}'.format(i), prior, is_training)\n\t\t\tif config.b_stochastic:\n\t\t\t\tb = get_bbb_variable(b_shape, 'b_{}'.format(i), prior, is_training)\n\t\t\telse:\n\t\t\t\t# Note: Reuse is passed down from variable scope in main()\n\t\t\t\tb = tf.get_variable('b_{}'.format(i), b_shape, data_type(),\n\t\t\t\t tf.constant_initializer(0.))\n\t\t\tcells.append(BayesianLSTM(config.hidden_size, theta, b, forget_bias=0.0,\n\t\t\t name='bbb_lstm_{}'.format(i)))\n\n\t\tcell = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)\n\t\tself._initial_state = cell.zero_state(config.batch_size, data_type())\n\t\tstate = self._initial_state\n\n\t\t# Forward pass for the truncated mini-batch\n\t\twith tf.variable_scope(\"RNN\"):\n\t\t\tinputs = tf.unstack(inputs, num=config.num_steps, axis=1)\n\t\t\toutputs, state = tf.contrib.rnn.static_rnn(cell, inputs,\n\t\t\t initial_state=state)\n\n\t\t\toutput = tf.reshape(tf.concat(outputs, 1), [-1, config.hidden_size])\n\n\t\t# Softmax BBB output projection layer\n\t\tsoftmax_w_shape = (size, vocab_size)\n\t\tsoftmax_b_shape = (vocab_size, 1)\n\t\tsoftmax_w = get_bbb_variable(softmax_w_shape, 'softmax_w', prior, is_training)\n\n\t\tif config.b_stochastic:\n\t\t\tsoftmax_b = get_bbb_variable(softmax_b_shape, 'softmax_b', prior, is_training)\n\t\telse:\n\t\t\tsoftmax_b = tf.get_variable('softmax_b', softmax_b_shape, data_type(),\n\t\t\t tf.constant_initializer(0.))\n\n\t\tlogits = tf.nn.xw_plus_b(output, softmax_w, tf.squeeze(softmax_b))\n\n\t\t# Reshape logits to be a 3-D tensor for sequence loss\n\t\tlogits = tf.reshape(logits, [self.batch_size, self.num_steps, vocab_size])\n\n\t\t# Use the contrib sequence loss and average over the batches\n\t\tloss = tf.contrib.seq2seq.sequence_loss(\n\t\t\tlogits,\n\t\t\tinput_.targets,\n\t\t\ttf.ones([self.batch_size, self.num_steps], dtype=data_type()),\n\t\t\taverage_across_timesteps=False,\n\t\t\taverage_across_batch=False)\n\n\t\t# Update the cost\n\t\tself._cost = tf.reduce_sum(loss) / self.batch_size\n\t\tself._kl_div = 0.\n\t\tself._final_state = state\n\n\t\tif not is_training:\n\t\t\treturn\n\n\t\t# Compute KL divergence for each cell, projection layer and embedding layer.\n\t\t# KL is scaled by 1./(B*C) as in the paper\n\t\tkl_const = self._input.epoch_size\n\t\tkl_div = tf.add_n(tf.get_collection('KL_layers'), 'kl_divergence')\n\n\t\t# ELBO\n\t\tself._kl_div = (1. / self.batch_size) * kl_div * (1. / kl_const)\n\t\tself._total_loss = self._cost + self._kl_div\n\n\t\t# Learning rate & optimization\n\t\tself._lr = tf.Variable(0.0, trainable=False)\n\t\ttvars = tf.trainable_variables()\n\t\tgrads, _ = tf.clip_by_global_norm(tf.gradients(self._total_loss, tvars),\n\t\t config.max_grad_norm)\n\t\toptimizer = tf.train.GradientDescentOptimizer(self._lr)\n\t\tself._train_op = optimizer.apply_gradients(\n\t\t\tzip(grads, tvars),\n\t\t\tglobal_step=tf.contrib.framework.get_or_create_global_step())\n\n\t\tself._new_lr = tf.placeholder(\n\t\t\tdata_type(), shape=[], name=\"new_learning_rate\")\n\t\tself._lr_update = tf.assign(self._lr, self._new_lr)\n\n\tdef assign_lr(self, session, lr_value):\n\t\tsession.run(self._lr_update, feed_dict={self._new_lr: lr_value})\n\n\tdef export_ops(self, name):\n\t\t\"\"\"Exports ops to collections.\"\"\"\n\t\tself._name = name\n\t\tops = {util.with_prefix(self._name, \"cost\"): self._cost,\n\t\t util.with_prefix(self._name, \"kl_div\"): self._kl_div}\n\t\tif self._is_training:\n\t\t\tops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)\n\t\t\tif self._rnn_params:\n\t\t\t\tops.update(rnn_params=self._rnn_params)\n\t\tfor name, op in ops.items():\n\t\t\ttf.add_to_collection(name, op)\n\t\tself._initial_state_name = util.with_prefix(self._name, \"initial\")\n\t\tself._final_state_name = util.with_prefix(self._name, \"final\")\n\t\tutil.export_state_tuples(self._initial_state, self._initial_state_name)\n\t\tutil.export_state_tuples(self._final_state, self._final_state_name)\n\n\tdef import_ops(self):\n\t\t\"\"\"Imports ops from collections.\"\"\"\n\t\tif self._is_training:\n\t\t\tself._train_op = tf.get_collection_ref(\"train_op\")[0]\n\t\t\tself._lr = tf.get_collection_ref(\"lr\")[0]\n\t\t\tself._new_lr = tf.get_collection_ref(\"new_lr\")[0]\n\t\t\tself._lr_update = tf.get_collection_ref(\"lr_update\")[0]\n\t\t\trnn_params = tf.get_collection_ref(\"rnn_params\")\n\t\t\tif self._cell and rnn_params:\n\t\t\t\tparams_saveable = tf.contrib.cudnn_rnn.RNNParamsSaveable(\n\t\t\t\t\tself._cell,\n\t\t\t\t\tself._cell.params_to_canonical,\n\t\t\t\t\tself._cell.canonical_to_params,\n\t\t\t\t\trnn_params,\n\t\t\t\t\tbase_variable_scope=\"Model/RNN\")\n\t\t\t\ttf.add_to_collection(tf.GraphKeys.SAVEABLE_OBJECTS, params_saveable)\n\t\tself._cost = tf.get_collection_ref(util.with_prefix(self._name, \"cost\"))[0]\n\t\tself._kl_div = tf.get_collection_ref(util.with_prefix(self._name, \"kl_div\"))[0]\n\t\tnum_replicas = 1\n\t\tself._initial_state = util.import_state_tuples(\n\t\t\tself._initial_state, self._initial_state_name, num_replicas)\n\t\tself._final_state = util.import_state_tuples(\n\t\t\tself._final_state, self._final_state_name, num_replicas)\n\n\t@property\n\tdef input(self):\n\t\treturn self._input\n\n\t@property\n\tdef initial_state(self):\n\t\treturn self._initial_state\n\n\t@property\n\tdef cost(self):\n\t\treturn self._cost\n\n\t@property\n\tdef final_state(self):\n\t\treturn self._final_state\n\n\t@property\n\tdef lr(self):\n\t\treturn self._lr\n\n\t@property\n\tdef train_op(self):\n\t\treturn self._train_op\n\n\t@property\n\tdef initial_state_name(self):\n\t\treturn self._initial_state_name\n\n\t@property\n\tdef final_state_name(self):\n\t\treturn self._final_state_name\n\n\t@property\n\tdef kl_div(self):\n\t\treturn self._kl_div if self._is_training else tf.constant(0.)\n\n\nclass SmallConfig(object):\n\t\"\"\"Small config.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 20\n\thidden_size = 200\n\tmax_epoch = 4\n\tmax_max_epoch = 13\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass MediumConfig(object):\n\t\"\"\"\n\tMedium config.\n\tSlightly modified according to email.\n\t\"\"\"\n\tinit_scale = 0.05\n\tlearning_rate = 1.0\n\tmax_grad_norm = 5\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 650\n\tmax_epoch = 20\n\tmax_max_epoch = 60\n\tkeep_prob = 1.0\n\tlr_decay = 0.9\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass LargeConfig(object):\n\t\"\"\"Large config.\"\"\"\n\tinit_scale = 0.04\n\tlearning_rate = 1.0\n\tmax_grad_norm = 10\n\tnum_layers = 2\n\tnum_steps = 35\n\thidden_size = 1500\n\tmax_epoch = 14\n\tmax_max_epoch = 55\n\tkeep_prob = 0.35\n\tlr_decay = 1 / 1.15\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\nclass TestConfig(object):\n\t\"\"\"Tiny config, for testing.\"\"\"\n\tinit_scale = 0.1\n\tlearning_rate = 1.0\n\tmax_grad_norm = 1\n\tnum_layers = 1\n\tnum_steps = 2\n\thidden_size = 2\n\tmax_epoch = 1\n\tmax_max_epoch = 1\n\tkeep_prob = 1.0\n\tlr_decay = 0.5\n\tbatch_size = 20\n\tvocab_size = 10000\n\n\ndef run_epoch(session, model, eval_op=None, verbose=False):\n\t\"\"\"Runs the model on the given data.\"\"\"\n\tstart_time = time.time()\n\tcosts = 0.0\n\titers = 0\n\tstate = session.run(model.initial_state)\n\n\tfetches = {\n\t\t\"cost\": model.cost,\n\t\t\"final_state\": model.final_state,\n\t}\n\tif eval_op is not None:\n\t\tfetches[\"eval_op\"] = eval_op\n\t\tfetches[\"kl_divergence\"] = model.kl_div\n\n\tfor step in range(model.input.epoch_size):\n\t\tfeed_dict = {}\n\t\tfor i, (c, h) in enumerate(model.initial_state):\n\t\t\tfeed_dict[c] = state[i].c\n\t\t\tfeed_dict[h] = state[i].h\n\n\t\tvals = session.run(fetches, feed_dict)\n\t\tcost = vals[\"cost\"]\n\t\tstate = vals[\"final_state\"]\n\n\t\tcosts += cost\n\t\titers += model.input.num_steps\n\n\t\tif verbose and (step % (model.input.epoch_size // 10) == 10 or step == 0):\n\t\t\tprint(\"%.3f perplexity: %.3f speed: %.0f wps\" %\n\t\t\t (step * 1.0 / model.input.epoch_size, np.exp(costs / iters),\n\t\t\t iters * model.input.batch_size / (time.time() - start_time)))\n\n\t\t\tif model._is_training:\n\t\t\t\tprint(\"KL is {}\".format(vals[\"kl_divergence\"]))\n\n\treturn np.exp(costs / iters)\n\n\ndef change_random_seed(seed):\n\tglobal prng\n\tprng = np.random.RandomState(seed)\n\ttf.set_random_seed(seed)\n\n\ndef run():\n\tif not FLAGS.data_path:\n\t\traise ValueError(\"Must set --data_path to PTB data directory\")\n\n\tchange_random_seed(FLAGS.random_seed)\n\n\traw_data = reader.ptb_raw_data(FLAGS.data_path)\n\ttrain_data, valid_data, test_data, _ = raw_data\n\n\tconfig = get_config()\n\teval_config = get_config()\n\teval_config.batch_size = 1\n\teval_config.num_steps = 1\n\n\twith tf.Graph().as_default():\n\t\tinitializer = tf.random_uniform_initializer(-config.init_scale,\n\t\t config.init_scale)\n\n\t\twith tf.name_scope(\"Train\"):\n\t\t\ttrain_input = PTBInput(config=config, data=train_data, name=\"TrainInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=None, initializer=initializer):\n\t\t\t\tm = PTBModel(is_training=True, config=config, input_=train_input)\n\t\t\ttf.summary.scalar(\"Training Loss\", m.cost)\n\t\t\ttf.summary.scalar(\"Learning Rate\", m.lr)\n\n\t\twith tf.name_scope(\"Valid\"):\n\t\t\tvalid_input = PTBInput(config=config, data=valid_data, name=\"ValidInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmvalid = PTBModel(is_training=False, config=config, input_=valid_input)\n\t\t\ttf.summary.scalar(\"Validation Loss\", mvalid.cost)\n\n\t\twith tf.name_scope(\"Test\"):\n\t\t\ttest_input = PTBInput(\n\t\t\t\tconfig=eval_config, data=test_data, name=\"TestInput\")\n\t\t\twith tf.variable_scope(\"Model\", reuse=True, initializer=initializer):\n\t\t\t\tmtest = PTBModel(is_training=False, config=eval_config,\n\t\t\t\t input_=test_input)\n\n\t\tmodels = {\"Train\": m, \"Valid\": mvalid, \"Test\": mtest}\n\t\tfor name, model in models.items():\n\t\t\tmodel.export_ops(name)\n\t\tmetagraph = tf.train.export_meta_graph()\n\t\tsoft_placement = False\n\n\twith tf.Graph().as_default():\n\t\ttf.train.import_meta_graph(metagraph)\n\t\tfor model in models.values():\n\t\t\tmodel.import_ops()\n\t\tsv = tf.train.Supervisor(logdir=FLAGS.save_path)\n\t\tconfig_proto = tf.ConfigProto(allow_soft_placement=soft_placement)\n\t\twith sv.managed_session(config=config_proto) as session:\n\t\t\tfor i in range(config.max_max_epoch):\n\t\t\t\tlr_decay = config.lr_decay ** max(i + 1 - config.max_epoch, 0.0)\n\t\t\t\tm.assign_lr(session, config.learning_rate * lr_decay)\n\n\t\t\t\tprint(\"Epoch: %d Learning rate: %.3f\" % (i + 1, session.run(m.lr)))\n\t\t\t\ttrain_perplexity = run_epoch(session, m, eval_op=m.train_op,\n\t\t\t\t verbose=True)\n\t\t\t\tprint(\"Epoch: %d Train Perplexity: %.3f\" % (i + 1, train_perplexity))\n\t\t\t\tvalid_perplexity = run_epoch(session, mvalid)\n\t\t\t\tprint(\"Epoch: %d Valid Perplexity: %.3f\" % (i + 1, valid_perplexity))\n\n\t\t\ttest_perplexity = run_epoch(session, mtest)\n\t\t\tprint(\"Test Perplexity: %.3f\" % test_perplexity)\n\n\t\t\tif FLAGS.save_path:\n\t\t\t\tprint(\"Saving model to %s.\" % FLAGS.save_path)\n\t\t\t\tsv.saver.save(session, FLAGS.save_path, global_step=sv.global_step)\n\n\nif __name__ == '__main__':\n\trun()\n","repo_name":"alexkrk/brnn","sub_path":"ptb_word_lm3.py","file_name":"ptb_word_lm3.py","file_ext":"py","file_size_in_byte":17979,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"}
+{"seq_id":"70765095524","text":"__all__ = ['minkunion', 'mtocollection', 'kambiguate']\n\nfrom itertools import izip, imap\n\nargmax = lambda funct, items: max(izip(imap(funct, items), items))\nargmin = lambda funct, items: min(izip(imap(funct, items), items))\n\ndef minkunion(collection, k):\n '''try to find the minimum k-union of the input collection'''\n if len(collection) < k:\n return []\n sol = []\n cover = set()\n avail = set(range(len(collection)))\n for idx in xrange(k):\n best = argmin(lambda i : len(cover | collection[i]), avail)[1]\n sol.append(best)\n cover |= collection[best]\n avail.remove(best)\n return cover\n\ndef mtocollection(m, target):\n '''construct discernibility matrix (collection) relative to target'''\n v = m[target]\n collection = []\n for i,row in enumerate(m):\n if i == target:\n continue\n collection.append(set([j for j in xrange(len(v)) if v[j] != row[j]]))\n return collection\n\ndef kambiguate(m,k):\n '''k-ambiguate input matrix by cell suppression'''\n newm = []\n for i,r in enumerate(m):\n newr = [x for x in r]\n for j in minkunion(mtocollection(m,i), k):\n newr[j] = '?'\n newm.append(newr)\n return newm\n\n\nif __name__ == \"__main__\":\n try:\n import psyco\n psyco.full()\n pass\n except ImportError:\n pass\n\n from urllib import urlopen\n from optparse import OptionParser\n from logging import debug, warning, error, info\n import logging\n import re\n import sys\n import os\n \n progname = os.path.basename(sys.argv[0])\n url = progname\n Version = \"0.01\"\n parser = OptionParser(usage = \"\".join(\n [\"%prog [options] URL\\n\",\n \"\\n Version: \", Version, \" SAV (C) 2009\\n\",\n \" K-ambiguate by cell suppression.\\n\\n\",\n \" URL points to a rectangular data table where the first line\\n\",\n \" contains attribute names. Table entries are separated by /\\s,:/.\\n\",\n \" URL can also be a simple filename or '-' for stdin.\\n\"]),\n version = ''.join([\"%prog \",Version,\" (C) SAV 2009\"]))\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\", action=\"count\",\n default = 0,\n help=\"print more stuff than strictly needed. Given\"\n \" twice results in debug info.\")\n parser.add_option(\"-k\", dest=\"k\", type='int',\n default=5, metavar='INTEGER',\n help=\"Ambiguation: how many original data \"\n \"points must match the suppressed row.\"\n \"(default: '%default')\")\n parser.add_option(\"-e\", \"--explain\", dest=\"explain\",\n default=False, action=\"store_true\",\n help=\"print description of what this program does.\")\n\n (opt, args) = parser.parse_args()\n\n verbose = opt.verbose > 0\n logging.basicConfig(level=max(logging.DEBUG,\n logging.WARNING - 10*opt.verbose),\n format='%(levelname)-5s %(message)s')\n\n if opt.explain:\n print(__doc__ % {'prog': progname,\n 'version' : Version,\n 'url': url})\n sys.exit(0)\n\n\n if len(args) < 1:\n error(\"Missing input file. Try -h for help.\")\n sys.exit(1)\n\n info('fetching data...')\n f = (args[0] == '-' and sys.stdin or urlopen(args[0]))\n rex = re.compile('[\\s,:]') # separators are whitespace, ',' and ':'\n m = [rex.split(line.strip()) for line in f]\n # remove empty and comment lines (start with '#')\n m = filter(lambda r: (not all(map(lambda x: x == '', r))\n and (r[0] == '' or r[0][0] != '#')), m)\n info('fetched ' + str(len(m) - 1) + ' rows.') \n\n info(str(opt.k) + '-ambiguating...')\n tra = kambiguate(m[1:],opt.k) # note that we are assuming that the first\n # line contains column (attribute) names\n\n info('printing output...')\n print(' '.join(m[0])) # print column names\n for row in tra:\n print(' '.join(row))\n info('done.\\n') \n\n \n","repo_name":"Beerkay/laats.github.io","sub_path":"sw/msj/minkunion.py","file_name":"minkunion.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3728669379","text":"#return an array that indicates appearing twice in array nums\n#input nums = [4,3,2,7,8,2,3,1], return [2,3]\nfrom typing import List\n\ndef findDuplicates(nums: List[int]) -> List[int]:\n # *O(n)search* dicを作り、keyにnumsの数字、valueに出てきた回数を記録\n dic = {}\n for i in range(len(nums)):\n if nums[i] not in dic:\n dic[nums[i]] = 1\n else:\n dic[nums[i]] += 1\n\n return [twice for twice in dic if dic[twice] == 2]\n\nnums = [4,3,2,7,8,2,3,1]\nprint(findDuplicates(nums))\n","repo_name":"kumo2kumo/CodingProblems","sub_path":"LeetCode/Find All Duplicates in an Array.py","file_name":"Find All Duplicates in an Array.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"25170231849","text":"#深度强化学习——原理、算法与PyTorch实战,代码名称:代41-TD3算法的实验过程.py\r\nimport numpy as np\r\nimport torch\r\nimport gym\r\nimport os\r\nimport copy\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\nclass ReplayBuffer(object):\r\n def __init__(self, state_dim, action_dim, max_size=int(1e6)):\r\n self.max_size = max_size # 最大容量\r\n self.ptr = 0 # 添加索引\r\n self.size = 0 # 容量\r\n\r\n self.state = np.zeros((max_size, state_dim)) # 一行一个状态\r\n self.action = np.zeros((max_size, action_dim))\r\n self.next_state = np.zeros((max_size, state_dim))\r\n self.reward = np.zeros((max_size, 1))\r\n self.not_done = np.zeros((max_size, 1))\r\n\r\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n def add(self, state, action, next_state, reward, done):\r\n self.state[self.ptr] = state\r\n self.action[self.ptr] = action\r\n self.next_state[self.ptr] = next_state\r\n self.reward[self.ptr] = reward\r\n self.not_done[self.ptr] = 1. - done\r\n\r\n self.ptr = (self.ptr + 1) % self.max_size # 每添加一次索引加一直到max时归零\r\n self.size = min(self.size + 1, self.max_size) # 不超过max_size\r\n\r\n def sample(self, batch_size):\r\n ind = np.random.randint(0, self.size, size=batch_size) # 采样索引\r\n\r\n return (\r\n torch.FloatTensor(self.state[ind]).to(self.device),\r\n torch.FloatTensor(self.action[ind]).to(self.device),\r\n torch.FloatTensor(self.next_state[ind]).to(self.device),\r\n torch.FloatTensor(self.reward[ind]).to(self.device),\r\n torch.FloatTensor(self.not_done[ind]).to(self.device)\r\n )\r\n # 全连接层需要我们把输入拉直成一个列向量 不同于卷积神经网络[,,,]\r\n # 输入是图像需要进行标准化(x-u)/std 神经网络学习的本质就是为了学习的数据分布,\r\n # 一旦训练数据与测试数据分布不同,那么网络的泛化性能会大大降低 \r\n # 标准化的作用仅仅是将数据拉回到同一个量级,使网络更容易学习\r\nclass Actor(nn.Module):\r\n def __init__(self, state_dim, action_dim, max_action):\r\n super(Actor, self).__init__()\r\n\r\n self.l1 = nn.Linear(state_dim, 256)\r\n self.l2 = nn.Linear(256, 256)\r\n self.l3 = nn.Linear(256, action_dim)\r\n\r\n self.max_action = max_action # 改为倒立摆后 state[,,] \r\n\r\n def forward(self, state):\r\n a = F.relu(self.l1(state))\r\n a = F.relu(self.l2(a))\r\n return self.max_action * torch.tanh(self.l3(a)) # 输出为连续动作值[-2,2]\r\n \r\n \r\n\r\nclass Critic(nn.Module):\r\n def __init__(self, state_dim, action_dim):\r\n super(Critic, self).__init__()\r\n # 为解决过高估,用较小的Q值去构造Critic学习的Target Value\r\n # Q1 architecture\r\n self.l1 = nn.Linear(state_dim + action_dim, 256)\r\n self.l2 = nn.Linear(256, 256)\r\n self.l3 = nn.Linear(256, 1)\r\n\r\n # Q2 architecture\r\n self.l4 = nn.Linear(state_dim + action_dim, 256)\r\n self.l5 = nn.Linear(256, 256)\r\n self.l6 = nn.Linear(256, 1)\r\n\r\n def forward(self, state, action):\r\n # 前向传播时求Q(s,a) 需要拼接再输入 行向量?\r\n sa = torch.cat([state, action], 1)\r\n\r\n q1 = F.relu(self.l1(sa))\r\n q1 = F.relu(self.l2(q1))\r\n q1 = self.l3(q1)\r\n\r\n q2 = F.relu(self.l4(sa))\r\n q2 = F.relu(self.l5(q2))\r\n q2 = self.l6(q2)\r\n return q1, q2\r\n # actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\r\n def Q1(self, state, action):\r\n sa = torch.cat([state, action], 1)\r\n\r\n q1 = F.relu(self.l1(sa))\r\n q1 = F.relu(self.l2(q1))\r\n q1 = self.l3(q1)\r\n return q1\r\n\r\n# actor1=Actor(17,6,1.0)\r\nactor1=Actor(3,1,2.0)\r\n# self.children()只包括网络模块的第一代儿子模块,而self.modules()包含网络模块的自己本身和所有后代模块。\r\nfor ch in actor1.children():\r\n print(ch)\r\nprint(\"*********************\")\r\ncritic1=Critic(3,1)\r\nfor ch in critic1.children():\r\n print(ch)\r\n\r\nclass TD3(object):\r\n def __init__(\r\n self,\r\n state_dim,\r\n action_dim,\r\n max_action,\r\n discount=0.99,\r\n tau=0.005,\r\n policy_noise=0.2,\r\n noise_clip=0.5,\r\n policy_freq=2\r\n ):\r\n\r\n self.actor = Actor(state_dim, action_dim, max_action).to(device)\r\n self.actor_target = copy.deepcopy(self.actor) # 创建目标策略网络\r\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=3e-4)\r\n\r\n self.critic = Critic(state_dim, action_dim).to(device)\r\n self.critic_target = copy.deepcopy(self.critic) # 创建目标价值网络\r\n self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=3e-4)\r\n\r\n self.max_action = max_action\r\n self.discount = discount\r\n self.tau = tau\r\n self.policy_noise = policy_noise\r\n self.noise_clip = noise_clip\r\n self.policy_freq = policy_freq\r\n\r\n self.total_it = 0\r\n\r\n\r\n def select_action(self, state):\r\n # 化为向量形式方面linear网络输入\r\n state = torch.FloatTensor(state.reshape(1, -1)).to(device)\r\n return self.actor(state).cpu().data.numpy().flatten()\r\n\r\n\r\n def train(self, replay_buffer, batch_size=100):\r\n self.total_it += 1 # 用于策略网络和价值网络的不同步\r\n\r\n # Sample replay buffer 都应该加s(多数)\r\n state, action, next_state, reward, not_done = replay_buffer.sample(batch_size)\r\n\r\n \"\"\" 在交互的时候,a加上了了noise。这个时候的noise是为了更充分地开发整个游戏空间。\r\n 计算target_Q的时候,a'加上noise,是为了预估更准确,网络更有健壮性。\r\n 更新actor网络的时候,我们不需要加上noise,这里是希望actor能够寻着最大值。加上noise并没有任何意义\r\n \"\"\"\r\n # pytorch对于tensor的计算操作,默认是要进行计算图的构建的,在这种情况下,\r\n # 可以使用 with torch.no_grad():,强制之后的内容不进行计算图构建,反向传播\r\n # 因为后面要取最小值和软更新 不是立即改变网络参数\r\n with torch.no_grad():\r\n # Select action according to policy(探索) noise and add clipped noise\r\n # randn_like返回一个和输入大小相同的张量,其由均值为0、方差为1的标准正态分布填充\r\n noise = (\r\n torch.randn_like(action) * self.policy_noise\r\n ).clamp(-self.noise_clip, self.noise_clip)\r\n # clip(a' + noise)-> (-2.0,2.0) clip防止action超出范围\r\n next_action = (\r\n self.actor_target(next_state) + noise\r\n ).clamp(-self.max_action, self.max_action)\r\n\r\n # Compute the target Q value\r\n target_Q1, target_Q2 = self.critic_target(next_state, next_action)\r\n target_Q = torch.min(target_Q1, target_Q2) # 用target网络的Double Q',一共6个网络\r\n target_Q = reward + not_done * self.discount * target_Q # y\r\n\r\n # Get current Q estimates\r\n current_Q1, current_Q2 = self.critic(state, action)\r\n\r\n # Compute critic loss (Double Q的loss和)\r\n # torch.mean()有必要加上 梯度累积时,记得要除以累积次数 ,不然梯度会太大导致训练异常(actor和critic) 这里加不加效果一样\r\n critic_loss = torch.mean(F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q))\r\n\r\n # Optimize the critic\r\n self.critic_optimizer.zero_grad()\r\n critic_loss.backward()\r\n self.critic_optimizer.step()\r\n\r\n # Delayed policy updates\r\n if self.total_it % self.policy_freq == 0:\r\n\r\n # Compute actor losse 评论家更新d次后行动家再更新 mean():batch_size 负号:最大化J\r\n # 更新行动家网络时的a不需要加noise,因为这只是 Loss = -Q(s,a) 即最大化Q(J)\r\n actor_loss = -self.critic.Q1(state, self.actor(state)).mean()\r\n\r\n # Optimize the actor\r\n self.actor_optimizer.zero_grad()\r\n actor_loss.backward()\r\n self.actor_optimizer.step()\r\n\r\n # Update the frozen target models 软更新\r\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n\r\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\r\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\r\n\r\n\r\n def save(self, filename):\r\n # pytorch 中的 state_dict 是一个简单的python的字典对象,将每一层与它的对应参数建立映射关系\r\n # torch.save(model.state_dict(), PATH) \r\n # 常用的保存state_dict的格式是\".pt\"或'.pth'的文件,即下面命令的 PATH=\"./***.pt\"\r\n torch.save(self.critic.state_dict(), filename + \"_critic\")\r\n torch.save(self.critic_optimizer.state_dict(), filename + \"_critic_optimizer\")\r\n\r\n torch.save(self.actor.state_dict(), filename + \"_actor\")\r\n torch.save(self.actor_optimizer.state_dict(), filename + \"_actor_optimizer\")\r\n\r\n\r\n def load(self, filename):\r\n self.critic.load_state_dict(torch.load(filename + \"_critic\"))\r\n self.critic_optimizer.load_state_dict(torch.load(filename + \"_critic_optimizer\"))\r\n self.critic_target = copy.deepcopy(self.critic)\r\n\r\n self.actor.load_state_dict(torch.load(filename + \"_actor\"))\r\n self.actor_optimizer.load_state_dict(torch.load(filename + \"_actor_optimizer\"))\r\n self.actor_target = copy.deepcopy(self.actor)\r\n\r\n# Runs policy for X episodes and returns average reward\r\n# A fixed seed is used for the eval environment 评估策略\r\ndef eval_policy(policy, env_name, seed, eval_episodes=10):\r\n eval_env = gym.make(env_name)\r\n eval_env.seed(seed + 100) #固定随机种子生成的随机值保证每次训练相同\r\n\r\n avg_reward = 0.\r\n for _ in range(eval_episodes):\r\n state, done = eval_env.reset(), False # done = False\r\n while not done:\r\n # env.render()\r\n action = policy.select_action(np.array(state))\r\n state, reward, done, _ = eval_env.step(action)\r\n avg_reward += reward\r\n \r\n\r\n avg_reward /= eval_episodes # 平均每个episode的奖励\r\n\r\n print(\"---------------------------------------\")\r\n print(f\"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}\")\r\n print(\"---------------------------------------\")\r\n return avg_reward\r\n\r\n\r\npolicy = \"TD3\"\r\nenv_name = \"Pendulum-v0\" # OpenAI gym environment name\r\nseed = 0 # Sets Gym, PyTorch and Numpy seeds\r\nstart_timesteps = 25e3 # 如果小于25e3步,就随机,如果大于就用get-action :e-greedy策略\r\neval_freq = 5e3 # How often (time steps) we evaluate 5e3\r\nmax_timesteps = 1e6 # Max time steps to run environment 10e6\r\nexpl_noise = 0.1 # Std of Gaussian exploration noise\r\nbatch_size = 256 # Batch size for both actor and critic\r\ndiscount = 0.99 # Discount factor\r\ntau = 0.005 # Target network update rate\r\npolicy_noise = 0.2 # Noise added to target policy during critic update\r\nnoise_clip = 0.5 # Range to clip target policy noise\r\npolicy_freq = 2 # Frequency of delayed policy updates\r\nsave_model = \"store_true\" # Save model and optimizer parameters\r\nload_model = \"\" # Model load file name, \"\" doesn't load, \"default\" uses file_name\r\n\r\n# Python3.6新加特性,前缀f用来格式化字符串。可以看出f前缀可以更方便的格式化字符串,比format()方法可读性高且使用方便\r\nfile_name = f\"{policy}_{env_name}_{seed}\"\r\nprint(\"---------------------------------------\")\r\nprint(f\"Policy: {policy}, Env: {env_name}, Seed: {seed}\")\r\nprint(\"---------------------------------------\")\r\n\r\nif not os.path.exists(\"./results\"):\r\n os.makedirs(\"./results\")\r\n\r\nif save_model and not os.path.exists(\"./models\"):\r\n os.makedirs(\"./models\")\r\n\r\nenv = gym.make(env_name)\r\n\r\n# Set seeds :env pytorch numpy\r\nenv.seed(seed)\r\ntorch.manual_seed(seed)\r\nnp.random.seed(seed)\r\n\r\nstate_dim = env.observation_space.shape[0]\r\naction_dim = env.action_space.shape[0]\r\nmax_action = float(env.action_space.high[0])\r\n\r\nkwargs = {\r\n \"state_dim\": state_dim,\r\n \"action_dim\": action_dim,\r\n \"max_action\": max_action,\r\n \"discount\": discount,\r\n \"tau\": tau,\r\n \"policy_noise\": policy_noise * max_action,\r\n \"noise_clip\": noise_clip * max_action,\r\n \"policy_freq\": policy_freq\r\n}\r\n# **表示有键值对的可变形参\r\npolicy = TD3(**kwargs)\r\n\r\nif load_model != \"\":\r\n policy_file = file_name if load_model == \"default\" else load_model\r\n policy.load(f\"./models/{policy_file}\")\r\n\r\nreplay_buffer = ReplayBuffer(state_dim, action_dim)\r\n\r\n# 初始化网络 此处需要额外调用以使内部函数能够使用 model.forward\r\nevaluations = [eval_policy(policy, env_name, seed)]\r\n\r\nstate, done = env.reset(), False\r\nepisode_reward = 0\r\nepisode_timesteps = 0\r\nepisode_num = 0\r\n# take_action- > step-> collect -> Train -> evaluate -> save model and result\r\nfor t in range(int(max_timesteps)):\r\n\r\n episode_timesteps += 1\r\n \r\n\r\n \r\n # 如果小于25000步就只交互进行存储,大于后开始训练,训练动作用 a+noise代替e-greedy(这是DQN)(同ddpg)\r\n if t < start_timesteps: \r\n action = env.action_space.sample()\r\n else:\r\n action = (\r\n policy.select_action(np.array(state))\r\n + np.random.normal(0, max_action * expl_noise, size=action_dim)\r\n ).clip(-max_action, max_action)\r\n\r\n # Perform action\r\n next_state, reward, done, _ = env.step(action)\r\n done_bool = float(done) if episode_timesteps < env._max_episode_steps else 0\r\n # env._max_episode_steps = 200 是强制改变最大step防止done\r\n \r\n \r\n\r\n # Store data in replay buffer\r\n replay_buffer.add(state, action, next_state, reward, done_bool)\r\n\r\n state = next_state\r\n episode_reward += reward\r\n\r\n # Train agent after collecting sufficient data\r\n if t >= start_timesteps:\r\n policy.train(replay_buffer, batch_size)\r\n\r\n if done:\r\n # +1 to account for 0 indexing. +0 on ep_timesteps since it will increment +1 even if done=True \r\n print(\r\n f\"Total T: {t + 1} Episode Num: {episode_num + 1} Episode T: {episode_timesteps} Reward: {episode_reward:.3f}\")\r\n # Reset environment\r\n state, done = env.reset(), False\r\n episode_reward = 0 # 一个episode的G\r\n episode_timesteps = 0 # 一个episode所经过的step\r\n episode_num += 1 # episode数\r\n\r\n # Evaluate episode 这里的动作不加noise\r\n if (t + 1) % eval_freq == 0:\r\n evaluations.append(eval_policy(policy, env_name, seed))\r\n np.save(f\"./results/{file_name}\", evaluations)\r\n\r\n if save_model:\r\n policy.save(f\"./models/{file_name}\")\r\n\r\nstate_dim","repo_name":"bao666liang/drl_pytorch","sub_path":"动手学强化学习书籍代码/TD3.py","file_name":"TD3.py","file_ext":"py","file_size_in_byte":15492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"25627485936","text":"import textwrap\nimport logging\nfrom benchmarkstt.cli import create_parser, args_help, args_common, args_complete\nfrom benchmarkstt.cli import CustomHelpFormatter, before_parseargs\nfrom benchmarkstt.modules import Modules\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef argparser():\n name = 'benchmarkstt-tools'\n desc = 'Some additional helpful tools'\n parser = create_parser(prog=name, description=desc)\n\n subparsers = parser.add_subparsers(dest='subcommand')\n\n for module, cli in Modules('cli'):\n kwargs = dict()\n if hasattr(cli, 'Formatter'):\n kwargs['formatter_class'] = cli.Formatter\n else:\n kwargs['formatter_class'] = CustomHelpFormatter\n\n if cli.__doc__ is not None:\n docs = cli.__doc__\n else:\n docs = '?'\n logger.warning('Missing __doc__ for benchmarkstt.%s._cli', module)\n\n kwargs['description'] = textwrap.dedent(docs)\n subparser = subparsers.add_parser(module, add_help=False, allow_abbrev=False, **kwargs)\n\n cli.argparser(subparser)\n args_common(subparser)\n args_help(subparser)\n\n args_help(parser)\n return parser\n\n\ndef run():\n before_parseargs()\n\n parser = argparser()\n args_complete(parser)\n\n args = parser.parse_args()\n\n if not args.subcommand:\n parser.error(\"expects at least 1 argument\")\n\n Modules('cli')[args.subcommand].run(parser, args)\n exit(0)\n\n\nif __name__ == '__main__': # pragma: nocover\n run()\n","repo_name":"ebu/benchmarkstt","sub_path":"src/benchmarkstt/cli/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"52"}
+{"seq_id":"39792883547","text":"import bb\nimport bb.event\nimport itertools\nimport logging\nimport multiprocessing\nimport os\nimport signal\nimport sys\nimport time\nfrom Queue import Empty\nfrom multiprocessing import Event, Process, util, Queue, Pipe, queues\n\nfrom . import BitBakeBaseServer, BitBakeBaseServerConnection, BaseImplServer\n\nlogger = logging.getLogger('BitBake')\n\nclass ServerCommunicator():\n def __init__(self, connection):\n self.connection = connection\n\n def runCommand(self, command):\n # @todo try/except\n self.connection.send(command)\n\n while True:\n # don't let the user ctrl-c while we're waiting for a response\n try:\n if self.connection.poll(20):\n return self.connection.recv()\n else:\n bb.fatal(\"Timeout while attempting to communicate with bitbake server\")\n except KeyboardInterrupt:\n pass\n\n\nclass EventAdapter():\n \"\"\"\n Adapter to wrap our event queue since the caller (bb.event) expects to\n call a send() method, but our actual queue only has put()\n \"\"\"\n def __init__(self, queue):\n self.queue = queue\n\n def send(self, event):\n try:\n self.queue.put(event)\n except Exception as err:\n print(\"EventAdapter puked: %s\" % str(err))\n\n\nclass ProcessServer(Process, BaseImplServer):\n profile_filename = \"profile.log\"\n profile_processed_filename = \"profile.log.processed\"\n\n def __init__(self, command_channel, event_queue):\n BaseImplServer.__init__(self)\n Process.__init__(self)\n self.command_channel = command_channel\n self.event_queue = event_queue\n self.event = EventAdapter(event_queue)\n self.quit = False\n\n self.keep_running = Event()\n self.keep_running.set()\n\n def run(self):\n for event in bb.event.ui_queue:\n self.event_queue.put(event)\n self.event_handle = bb.event.register_UIHhandler(self)\n bb.cooker.server_main(self.cooker, self.main)\n\n def main(self):\n # Ignore SIGINT within the server, as all SIGINT handling is done by\n # the UI and communicated to us\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n while self.keep_running.is_set():\n try:\n if self.command_channel.poll():\n command = self.command_channel.recv()\n self.runCommand(command)\n\n self.idle_commands(.1)\n except Exception:\n logger.exception('Running command %s', command)\n\n self.event_queue.cancel_join_thread()\n bb.event.unregister_UIHhandler(self.event_handle)\n self.command_channel.close()\n self.cooker.stop()\n self.idle_commands(.1)\n\n def idle_commands(self, delay):\n nextsleep = delay\n\n for function, data in self._idlefuns.items():\n try:\n retval = function(self, data, False)\n if retval is False:\n del self._idlefuns[function]\n elif retval is True:\n nextsleep = None\n elif nextsleep is None:\n continue\n elif retval < nextsleep:\n nextsleep = retval\n except SystemExit:\n raise\n except Exception:\n logger.exception('Running idle function')\n\n if nextsleep is not None:\n time.sleep(nextsleep)\n\n def runCommand(self, command):\n \"\"\"\n Run a cooker command on the server\n \"\"\"\n self.command_channel.send(self.cooker.command.runCommand(command))\n\n def stop(self):\n self.keep_running.clear()\n\nclass BitBakeProcessServerConnection(BitBakeBaseServerConnection):\n def __init__(self, serverImpl, ui_channel, event_queue):\n self.procserver = serverImpl\n self.ui_channel = ui_channel\n self.event_queue = event_queue\n self.connection = ServerCommunicator(self.ui_channel)\n self.events = self.event_queue\n\n def terminate(self, force = False):\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n self.procserver.stop()\n if force:\n self.procserver.join(0.5)\n if self.procserver.is_alive():\n self.procserver.terminate()\n self.procserver.join()\n else:\n self.procserver.join()\n while True:\n try:\n event = self.event_queue.get(block=False)\n except (Empty, IOError):\n break\n if isinstance(event, logging.LogRecord):\n logger.handle(event)\n self.ui_channel.close()\n self.event_queue.close()\n if force:\n sys.exit(1)\n\n# Wrap Queue to provide API which isn't server implementation specific\nclass ProcessEventQueue(multiprocessing.queues.Queue):\n def waitEvent(self, timeout):\n try:\n return self.get(True, timeout)\n except Empty:\n return None\n\n def getEvent(self):\n try:\n return self.get(False)\n except Empty:\n return None\n\n\nclass BitBakeServer(BitBakeBaseServer):\n def initServer(self):\n # establish communication channels. We use bidirectional pipes for\n # ui <--> server command/response pairs\n # and a queue for server -> ui event notifications\n #\n self.ui_channel, self.server_channel = Pipe()\n self.event_queue = ProcessEventQueue(0)\n self.serverImpl = ProcessServer(self.server_channel, self.event_queue)\n\n def detach(self):\n self.serverImpl.start()\n return\n\n def establishConnection(self):\n self.connection = BitBakeProcessServerConnection(self.serverImpl, self.ui_channel, self.event_queue)\n signal.signal(signal.SIGTERM, lambda i, s: self.connection.terminate(force=True))\n return self.connection\n","repo_name":"openagriculture/poky","sub_path":"bitbake/lib/bb/server/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10294542604","text":"import os\nimport warnings\n\nfrom weblate.settings_example import * # noqa: F403\n\nCI_DATABASE = os.environ.get(\"CI_DATABASE\", \"\")\n\ndefault_user = \"weblate\"\ndefault_name = \"weblate\"\nif CI_DATABASE in (\"mysql\", \"mariadb\"):\n DATABASES[\"default\"][\"ENGINE\"] = \"django.db.backends.mysql\"\n default_user = \"root\"\n DATABASES[\"default\"][\"OPTIONS\"] = {\n \"init_command\": (\n \"SET NAMES utf8mb4, \"\n \"wait_timeout=28800, \"\n \"default_storage_engine=INNODB, \"\n 'sql_mode=\"STRICT_TRANS_TABLES\"'\n ),\n \"charset\": \"utf8\",\n \"isolation_level\": \"read committed\",\n }\nelif CI_DATABASE == \"postgresql\":\n DATABASES[\"default\"][\"ENGINE\"] = \"django.db.backends.postgresql\"\n default_user = \"postgres\"\nelse:\n if not CI_DATABASE:\n raise ValueError(\"Missing CI_DATABASE configuration in the environment\")\n raise ValueError(f\"Not supported database: {CI_DATABASE}\")\n\nDATABASES[\"default\"][\"HOST\"] = os.environ.get(\"CI_DB_HOST\", \"\")\nDATABASES[\"default\"][\"NAME\"] = os.environ.get(\"CI_DB_NAME\", default_name)\nDATABASES[\"default\"][\"USER\"] = os.environ.get(\"CI_DB_USER\", default_user)\nDATABASES[\"default\"][\"PASSWORD\"] = os.environ.get(\"CI_DB_PASSWORD\", \"\")\nDATABASES[\"default\"][\"PORT\"] = os.environ.get(\"CI_DB_PORT\", \"\")\n\n# Configure admins\nADMINS = ((\"Weblate test\", \"noreply@weblate.org\"),)\n\n# The secret key is needed for tests\nSECRET_KEY = \"secret key used for tests only\" # noqa: S105\n\nSITE_DOMAIN = \"example.com\"\n\n# Different root for test repos\nif \"CI_BASE_DIR\" in os.environ:\n BASE_DIR = os.environ[\"CI_BASE_DIR\"]\nelse:\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nDATA_DIR = os.path.join(BASE_DIR, \"data-test\")\nCACHE_DIR = os.path.join(DATA_DIR, \"cache\")\nMEDIA_ROOT = os.path.join(DATA_DIR, \"media\")\nSTATIC_ROOT = os.path.join(DATA_DIR, \"static\")\nCELERY_TASK_ALWAYS_EAGER = True\nCELERY_BROKER_URL = \"memory://\"\nCELERY_TASK_EAGER_PROPAGATES = True\nCELERY_RESULT_BACKEND = None\n\n# Enable lazy stats for testing\nSTATS_LAZY = True\n\nVCS_API_DELAY = 0\n\n# Localize CDN addon\nLOCALIZE_CDN_URL = \"https://cdn.example.com/\"\nLOCALIZE_CDN_PATH = os.path.join(DATA_DIR, \"l10n-cdn\")\n\n# Needed for makemessages, otherwise it does not discover all available locales\n# and the -a parameter does not work\nLOCALE_PATHS = [os.path.join(os.path.dirname(__file__), \"locale\")]\n\n# Silent logging setup\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"filters\": {\"require_debug_false\": {\"()\": \"django.utils.log.RequireDebugFalse\"}},\n \"formatters\": {\"simple\": {\"format\": \"%(levelname)s %(message)s\"}},\n \"handlers\": {\n \"mail_admins\": {\n \"level\": \"ERROR\",\n \"filters\": [\"require_debug_false\"],\n \"class\": \"django.utils.log.AdminEmailHandler\",\n },\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"simple\",\n },\n },\n \"loggers\": {\n \"django.request\": {\n \"handlers\": [\"mail_admins\"],\n \"level\": \"ERROR\",\n \"propagate\": True,\n },\n \"weblate\": {\"handlers\": [], \"level\": \"ERROR\"},\n \"social\": {\"handlers\": [], \"level\": \"ERROR\"},\n },\n}\n\n# Reset caches\nCACHES = {\"default\": {\"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\"}}\n\nif \"CI_REDIS_HOST\" in os.environ:\n CACHES[\"avatar\"] = {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"redis://{}:{}/0\".format(\n os.environ[\"CI_REDIS_HOST\"], os.environ.get(\"CI_REDIS_PORT\", \"6379\")\n ),\n }\n\n# Selenium can not clear HttpOnly cookies in MSIE\nSESSION_COOKIE_HTTPONLY = False\n\n# Use database backed sessions for transaction consistency in tests\nSESSION_ENGINE = \"django.contrib.sessions.backends.db\"\n\n# Test optional apps as well\nINSTALLED_APPS += (\"weblate.billing\", \"weblate.legal\")\n\n# Test GitHub auth\nAUTHENTICATION_BACKENDS = (\n \"social_core.backends.email.EmailAuth\",\n \"social_core.backends.github.GithubOAuth2\",\n \"weblate.accounts.auth.WeblateUserBackend\",\n)\n\n# Disable random admin checks trigger\nBACKGROUND_ADMIN_CHECKS = False\n\n# Use weak password hasher for testing\nPASSWORD_HASHERS = [\n \"django.contrib.auth.hashers.MD5PasswordHasher\",\n]\n\n# Let the testsuite fail on timezone issues\nwarnings.filterwarnings(\n \"error\",\n r\"DateTimeField .* received a naive datetime\",\n RuntimeWarning,\n r\"django\\.db\\.models\\.fields\",\n)\n","repo_name":"WeblateOrg/weblate","sub_path":"weblate/settings_test.py","file_name":"settings_test.py","file_ext":"py","file_size_in_byte":4439,"program_lang":"python","lang":"en","doc_type":"code","stars":3905,"dataset":"github-code","pt":"52"}
+{"seq_id":"13016322175","text":"import BaseHandler\n\nimport os\n\nfrom google.appengine.api import mail\n\nclass SignupHandler(BaseHandler.BaseHandler):\n def get(self):\n self._serve_page()\n\n def post(self):\n email = self.request.get('email_address').lower()\n name = self.request.get('name')\n password = self.request.get('password')\n last_name = self.request.get('lastname')\n major = self.request.get_all('major')\n resendEmail = self.request.get('resendEmail')\n resendVerification = self.request.get('resendVerification')\n\n if not resendEmail:\n unique_properties = None\n user_data = self.user_model.create_user(email,\n unique_properties,\n email_address=email, name=name, password_raw=password,\n last_name=last_name, major=major[0], verified=False)\n\n if not user_data[0]: #user_data is a tuple\n self._serve_page(duplicate=True, duplicateKeys=user_data[1])\n return\n\n user = user_data[1]\n user_id = user.get_id()\n\n token = self.user_model.create_signup_token(user_id)\n\n verification_url = self.uri_for('verification', type='v', user_id=user_id,\n signup_token=token, _full=True)\n\n if resendVerification:\n verification_url = resendVerification\n\n receiverString = name + \" \" + last_name + \"<\" + email + \">\";\n email_body = \"\"\"Hello\"\"\" + name + \"\"\",\\n\\nPlease verify your account by going to this link: \"\"\" + verification_url;\n\n message = mail.EmailMessage(sender=\"\",\n subject=\"Account Verification\")\n message.to = receiverString\n message.body = email_body\n message.send()\n\n self._serve_page(email_sent=True, verification_url=verification_url, resendEmail=resendEmail)\n\n def _serve_page(self, email_sent=False, verification_url='', duplicate=False, duplicateKeys='', resendEmail=''):\n email_address = self.request.get('email_address')\n params = {\n 'development_mode': os.environ['SERVER_SOFTWARE'].startswith('Development'),\n 'email_address': email_address,\n 'email_sent': email_sent,\n 'verification_url': verification_url,\n 'duplicate': duplicate,\n 'duplicateKeys': duplicateKeys,\n 'resendEmail': resendEmail\n }\n self.render_template('signup.html', params)","repo_name":"nmcmahon1215/CS4241-FinalProject","sub_path":"WPIMajorTracking/SignupHandler.py","file_name":"SignupHandler.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"17119691305","text":"from utils.header import *\n\n\ndef unzip_all_block_files(block_shapes_dir=\"data/census_block_shapefiles_2020/\"):\n\n import zipfile\n\n all_files_and_folders = os.listdir(block_shapes_dir)\n all_zip_files_to_extract = [\n f\n for f in all_files_and_folders\n if f.endswith(\".zip\") and not f.split(\".zip\")[0] in all_files_and_folders\n ]\n for f in all_zip_files_to_extract:\n print(f)\n with zipfile.ZipFile(block_shapes_dir + f, \"r\") as zip_ref:\n dest_dir = f.split(\".zip\")[0]\n zip_ref.extractall(block_shapes_dir + dest_dir)\n\n\ndef output_block_racial_demos_by_state(\n states_codes_file=\"data/state_codes.csv\",\n block_demos_file=\"data/census_block_covariates/2020_census_race_hisp_over_18_by_block/filtered_demos.csv\",\n output_dir=\"data/census_block_covariates/2020_census_race_hisp_over_18_by_block/by_state/\",\n output_file_name=\"racial_demos_by_block.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n # states_already_computed = [f for f in os.listdir(output_dir)]\n # df_states = df_states[\n # ~df_states[\"abbrev\"].isin(states_already_computed)\n # ].reset_index()\n\n print(\"Loading filtered demos data ...\")\n df_demos = pd.read_csv(block_demos_file, encoding=\"ISO-8859-1\", dtype=\"str\")\n print(\"Iterating over states ...\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n state_code = str(df_states[\"fips_code\"][i])\n if len(state_code) < 2:\n state_code = \"0\" + state_code\n curr_demos = df_demos[df_demos[\"STATEA\"].isin([state_code])].reset_index(\n drop=True\n )\n print(state_abbrev, state_code, len(curr_demos))\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n curr_demos.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\ndef output_school_covars_by_state(\n states_codes_file=\"data/state_codes.csv\",\n school_race_covars_file=\"data/school_covariates/ccd_race_1920.csv\",\n school_frl_covars_file=\"data/school_covariates/ccd_frl_1920.csv\",\n school_ell_covars_file=\"data/school_covariates/crdc_1718/files/Data/SCH/CRDC/CSV/Enrollment.csv\",\n output_dir=\"data/school_covariates/ccd_1920_school_covars_by_state/\",\n output_file_name=\"ccd_1920_crdc_1718_school_covars.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n # states_already_computed = [f for f in os.listdir(output_dir)]\n # df_states = df_states[\n # ~df_states[\"abbrev\"].isin(states_already_computed)\n # ].reset_index()\n\n print(\"Loading school race covars data ...\")\n df_race_covars = pd.read_csv(\n school_race_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n print(\"Loading school frl covars data ...\")\n df_frl_covars = pd.read_csv(\n school_frl_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n print(\"Loading school ell covars data ...\")\n df_ell_covars = pd.read_csv(\n school_ell_covars_file, encoding=\"ISO-8859-1\", dtype=\"str\"\n )\n\n df_race_covars[\"STUDENT_COUNT\"] = df_race_covars[\"STUDENT_COUNT\"].astype(float)\n df_frl_covars[\"STUDENT_COUNT\"] = df_frl_covars[\"STUDENT_COUNT\"].astype(float)\n df_ell_covars[\"SCH_ENR_LEP_M\"] = df_ell_covars[\"SCH_ENR_LEP_M\"].astype(float)\n df_ell_covars[\"SCH_ENR_LEP_F\"] = df_ell_covars[\"SCH_ENR_LEP_F\"].astype(float)\n\n race_keys = {\n \"White\": \"num_white\",\n \"Black or African American\": \"num_black\",\n \"Hispanic/Latino\": \"num_hispanic\",\n \"American Indian or Alaska Native\": \"num_native\",\n \"Asian\": \"num_asian\",\n }\n\n print(\"Iterating over states ...\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n # if not state_abbrev == \"VA\":\n # continue\n\n # RACE AND ETHNICITY\n curr_race_covars = df_race_covars[\n df_race_covars[\"ST\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_race_covars = curr_race_covars[\n [\"NCESSCH\", \"RACE_ETHNICITY\", \"STUDENT_COUNT\", \"TOTAL_INDICATOR\"]\n ]\n print(state_abbrev, len(curr_race_covars))\n\n df_s = (\n curr_race_covars[\n curr_race_covars[\"TOTAL_INDICATOR\"].isin(\n [\"Derived - Education Unit Total minus Adult Education Count\"]\n )\n ][[\"NCESSCH\", \"STUDENT_COUNT\"]]\n .rename(columns={\"STUDENT_COUNT\": \"total_students\"})\n .reset_index(drop=True)\n )\n\n for r in race_keys:\n filtered_df = curr_race_covars[\n curr_race_covars[\"RACE_ETHNICITY\"].isin([r])\n & curr_race_covars[\"TOTAL_INDICATOR\"].isin(\n [\n \"Derived - Subtotal by Race/Ethnicity and Sex minus Adult Education Count\"\n ]\n )\n ]\n df_curr = (\n filtered_df.groupby([\"NCESSCH\"])\n .agg(\n {\n \"STUDENT_COUNT\": \"sum\",\n }\n )\n .rename(columns={\"STUDENT_COUNT\": race_keys[r]})\n )\n df_s = pd.merge(df_s, df_curr, on=\"NCESSCH\", how=\"left\")\n\n # FRL\n curr_frl_covars = df_frl_covars[\n df_frl_covars[\"ST\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_frl_covars = curr_frl_covars[\n [\"NCESSCH\", \"LUNCH_PROGRAM\", \"STUDENT_COUNT\"]\n ]\n filtered_df = curr_frl_covars[\n curr_frl_covars[\"LUNCH_PROGRAM\"].isin(\n [\"Free lunch qualified\", \"Reduced-price lunch qualified\"]\n )\n ]\n df_frl = (\n filtered_df.groupby([\"NCESSCH\"])\n .agg({\"STUDENT_COUNT\": \"sum\"})\n .rename(columns={\"STUDENT_COUNT\": \"num_frl\"})\n )\n df_s = pd.merge(df_s, df_frl, on=\"NCESSCH\", how=\"left\")\n\n # ELL\n curr_ell_covars = df_ell_covars[\n df_ell_covars[\"LEA_STATE\"].isin([state_abbrev])\n ].reset_index(drop=True)\n curr_ell_covars = curr_ell_covars[\n [\"COMBOKEY\", \"SCH_ENR_LEP_M\", \"SCH_ENR_LEP_F\"]\n ]\n curr_ell_covars[\"num_ell\"] = (\n curr_ell_covars[\"SCH_ENR_LEP_M\"] + curr_ell_covars[\"SCH_ENR_LEP_F\"]\n )\n\n # all_nces = set(df_s[\"NCESSCH\"].tolist())\n # ell_nces = set(curr_ell_covars[\"COMBOKEY\"].tolist())\n # print(len(all_nces.intersection(ell_nces)) / len(all_nces.union(ell_nces)))\n # exit()\n df_s = pd.merge(\n df_s,\n curr_ell_covars,\n left_on=\"NCESSCH\",\n right_on=\"COMBOKEY\",\n how=\"left\",\n ).drop(columns=[\"SCH_ENR_LEP_M\", \"SCH_ENR_LEP_F\", \"COMBOKEY\"])\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n df_s.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\ndef output_block_group_demos_by_state(\n states_codes_file=\"data/state_codes.csv\",\n bgrp_file=\"data/census_block_covariates/2015_2019_ACS_block_group_poverty_ratios/nhgis0014_ds244_20195_blck_grp.csv\",\n output_dir=\"data/census_block_covariates/2015_2019_ACS_block_group_poverty_ratios/by_state/\",\n output_file_name=\"frl_demos_by_block_group.csv\",\n):\n\n df_states = pd.read_csv(states_codes_file, dtype=\"str\")\n # Only process those states we haven't processed yet\n states_already_computed = [f for f in os.listdir(output_dir)]\n df_states = df_states[\n ~df_states[\"abbrev\"].isin(states_already_computed)\n ].reset_index()\n\n print(\"Loading demos data ...\")\n df_demos = pd.read_csv(bgrp_file, encoding=\"ISO-8859-1\", dtype=\"str\")\n for i in range(0, len(df_states)):\n try:\n state_abbrev = df_states[\"abbrev\"][i]\n state_code = str(df_states[\"fips_code\"][i])\n if len(state_code) < 2:\n state_code = \"0\" + state_code\n curr_demos = df_demos[df_demos[\"STATEA\"].isin([state_code])].reset_index(\n drop=True\n )\n print(state_abbrev, state_code, len(curr_demos))\n\n curr_output_dir = output_dir + state_abbrev + \"/\"\n if not os.path.exists(curr_output_dir):\n os.mkdir(curr_output_dir)\n curr_demos.to_csv(curr_output_dir + output_file_name, index=False)\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n # unzip_all_block_files()\n # output_block_racial_demos_by_state()\n # output_block_group_demos_by_state()\n output_school_covars_by_state()\n","repo_name":"Plural-Connections/attendance-boundaries","sub_path":"utils/data_org.py","file_name":"data_org.py","file_ext":"py","file_size_in_byte":9310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23821425406","text":"import hashlib\nimport importlib\nimport os\nimport sys\nimport uuid\nimport zipfile\nimport appdirs\nimport shutil\n\nimport pyflink\n\n# import ast\n# from pathlib import Path\n# from typing import Callable, AnyStr\n# notFuncName: list = [\"__call__\", \"eval\"]\n# udfNameList: list = []\n# is_udf: Callable[[AnyStr], bool] = lambda func: isinstance(getattr(importlib.import_module(path.stem), func),\n# pyflink.table.udf.UserDefinedFunctionWrapper)\n#\n# # filePath: str = sys.argv[1]\n# # if str is None:\n# # raise Exception(\"请输入文件路径\")\n# # path = Path(filePath)\n# # if path.parent.name != \"\":\n# # sys.path.append(path.parent.__str__())\n# with open(filePath, 'r', encoding='utf8') as f:\n# tree = ast.parse(f.read())\n#\n# for node in ast.walk(tree):\n# if isinstance(node, ast.FunctionDef):\n# try:\n# if node.args.args[0].arg == \"self\":\n# continue\n# except Exception as e:\n# pass\n# if notFuncName.__contains__(node.name):\n# continue\n#\n# if not is_udf(node.name):\n# continue\n# udfNameList.append(node.name)\n#\n# try:\n# if isinstance(node.targets[0], ast.Name) and is_udf(node.targets[0].id):\n# udfNameList.append(node.targets[0].id)\n# except Exception as e:\n# pass\n\nif len(sys.argv) < 2:\n raise Exception(\"Please enter the file path\")\n\nproject_path: str = sys.argv[1]\n\nudf_name_list = set()\n\n\ndef get_file_md5(path):\n \"\"\"\n 获取文件内容的MD5值\n :param path: 文件所在路径\n :return:\n \"\"\"\n with open(path, 'rb') as file:\n data = file.read()\n\n diff_check = hashlib.md5()\n diff_check.update(data)\n md5_code = diff_check.hexdigest()\n return md5_code\n\n\ndef list_modules(root_dir):\n \"\"\"返回给定目录下所有模块和子模块的名称\"\"\"\n modules = []\n if os.path.isdir(root_dir):\n sys.path.append(project_path)\n for dirpath, _, filenames in os.walk(root_dir):\n for filename in filenames:\n parse_file(dirpath, filename, modules, root_dir)\n else:\n file_dir = os.path.dirname(root_dir)\n sys.path.append(file_dir)\n parse_file(file_dir, root_dir, modules, file_dir)\n if project_path.endswith(\".py\"):\n sys.path.append(file_dir)\n elif project_path.endswith(\".zip\"):\n tmp_dir = appdirs.user_cache_dir()\n file = zipfile.ZipFile(project_path)\n unzip_file_path = os.path.normpath(tmp_dir + \"/dinky/udf_parse/\" + get_file_md5(project_path))\n if os.path.exists(unzip_file_path):\n shutil.rmtree(unzip_file_path)\n file.extractall(unzip_file_path)\n sys.path.append(unzip_file_path)\n for dirpath, _, filenames in os.walk(unzip_file_path):\n for filename in filenames:\n parse_file(dirpath, filename, modules, unzip_file_path)\n file.close()\n return modules\n\n\ndef parse_file(dirpath, filename, modules, root_dir):\n root_dir = os.path.normpath(root_dir)\n if filename.endswith(\".py\"):\n p_ = root_dir.replace(os.sep, \".\")\n module_name = os.path.splitext(os.path.join(dirpath, filename))[0].replace(os.sep, \".\").replace(\n p_ + \".\", \"\")\n modules.append(module_name.replace(root_dir, \"\"))\n\n\nif __name__ == '__main__':\n modules = list_modules(project_path)\n\n for module_name in modules:\n try:\n module = importlib.import_module(module_name)\n for m in dir(module):\n if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):\n udf_name_list.add(module.__name__ + \".\" + m)\n\n except Exception as e:\n pass\n\n print(str.join(\",\", udf_name_list))\n\n# import pkgutil\n# for _, module_name, _ in pkgutil.walk_packages([\"\"]):\n# if module_name == os.path.splitext(os.path.basename(__file__))[0]:\n# continue\n# try:\n# print(module_name)\n# module = importlib.import_module(module_name)\n# for m in dir(module):\n# if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):\n# udfNameList.add(module.__name__ + \".\" + m)\n#\n# except Exception as e:\n# pass\n#\n# print(str.join(\",\", udfNameList))\n","repo_name":"leeoo/dinky","sub_path":"dinky-function/src/main/resources/getPyFuncList.py","file_name":"getPyFuncList.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"}
+{"seq_id":"4231839263","text":"\"\"\"\n 1. Install python 2.X\n 1.1 Mechenize requires python 2.X\n \n 2. Install mechanize\n 2.1 Linux:\n run the command:\n $ sudo pip install mechanize\n 2.2 Windows: download mechanize from http://wwwsearch.sourceforge.net/mechanize/src/mechanize-0.2.5.zip\n unpack\n access the folder from command prompt\n run the command:\n python setup.py install\n \n 3. Not tested with captcha.\n\"\"\"\n\nimport sys\nimport mechanize\n\nreload(sys)\nsys.setdefaultencoding('utf8')\n\ntimes = int(input('How many times do you want to submit form? '))\naddress = 'https://address.site/contact_page/here/'\nbrowser = mechanize.Browser()\nbrowser.open(address)\n\nfor time in range(0, times):\n browser.select_form(nr = 2)\n browser.form['name'] = 'Name ' + str(time)\n browser.form['email'] = 'em@il' + str(time) + '.com'\n browser.form['fone'] = '+5585999999999'\n browser.form['subject'] = 'Subject ' + str(time)\n browser.form['message'] = 'Message ' + str(time)\n browser.submit()\n print(time)\n","repo_name":"ifreire/using_mechanize","sub_path":"submit_form.py","file_name":"submit_form.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"28187717646","text":"import torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\nfrom mmcv.runner import BaseModule, ModuleList, auto_fp16\nfrom mmcv.cnn import ConvModule\n\nfrom mmdet3d.ops import PointFPModule, build_sa_module\nfrom mmdet.models import BACKBONES\n\n\nclass SA_Layer(nn.Module):\n\n def __init__(self, channels):\n super(SA_Layer, self).__init__()\n self.q_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.k_conv = nn.Conv1d(channels, channels // 4, 1, bias=False)\n self.q_conv.weight = self.k_conv.weight\n self.q_conv.bias = self.k_conv.bias\n\n self.v_conv = nn.Conv1d(channels, channels, 1)\n self.trans_conv = nn.Conv1d(channels, channels, 1)\n self.after_norm = nn.BatchNorm1d(channels)\n self.act = nn.ReLU()\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n # b, n, c\n x_q = self.q_conv(x).permute(0, 2, 1)\n # b, c, n\n x_k = self.k_conv(x)\n x_v = self.v_conv(x)\n # b, n, n\n energy = torch.bmm(x_q, x_k)\n\n attention = self.softmax(energy)\n attention = attention / (1e-9 + attention.sum(dim=1, keepdim=True))\n # b, c, n\n x_r = torch.bmm(x_v, attention)\n x_r = self.act(self.after_norm(self.trans_conv(x - x_r)))\n x = x + x_r\n return x\n\n\n@BACKBONES.register_module()\nclass Point_Transformer(BaseModule):\n \"\"\"Point_Transformer single scale.\n\n Args:\n\n \"\"\"\n\n def __init__(self,\n in_channels,\n out_channels=1024,\n channels=128,\n num_stages=4,\n conv_cfg=dict(type='Conv1d'),\n norm_cfg=dict(type='BN1d'),\n act_cfg=dict(type='ReLU'),\n init_cfg=None):\n super(Point_Transformer, self).__init__(init_cfg=init_cfg)\n\n self.num_stages = num_stages\n\n self.point_embedding = ConvModule(\n in_channels,\n channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg)\n self.conv = ConvModule(\n channels,\n channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=act_cfg)\n\n self.sa = ModuleList()\n for _ in range(self.num_stages):\n self.sa.append(SA_Layer(channels))\n\n self.conv_fuse = ConvModule(\n channels * num_stages,\n out_channels,\n 1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n act_cfg=dict(type='LeakyReLU', negative_slope=0.2))\n\n @auto_fp16()\n def forward(self, points):\n # b, n, c --> b, c, n\n x = points.permute(0, 2, 1)\n x = self.point_embedding(x)\n x = self.conv(x)\n\n features = []\n for i in range(self.num_stages):\n x = self.sa[i](x)\n features.append(x)\n x = torch.cat(features, dim=1)\n out = self.conv_fuse(x)\n return out\n","repo_name":"Whu-gaozhao/my_mmdetection3d","sub_path":"mmdet3d/models/backbones/pct.py","file_name":"pct.py","file_ext":"py","file_size_in_byte":3020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"43341924194","text":"from math import inf\n\nfrom matplotlib.pyplot import plot\nfrom .priority_queue import PriorityQueue\nfrom .plot_trees import TreeNode, construct_tree_nodes, plot_tree\n\nclass Node:\n def __init__(self, k):\n self.k = k\n self.children = []\n \n @property\n def degree(self):\n return len(self.children)\n \n def add(self, other):\n if self.degree != other.degree:\n raise ValueError(\"Cannot merge binomial trees of different size\")\n self.children.insert(0, other)\n \n \nclass MergableHeap(PriorityQueue):\n def __init__(self, arr=[], ascending=False):\n self.trees = dict()\n self.bit = -1\n self.ascending = ascending\n if ascending:\n self.compare = lambda x, y: x < y\n else:\n self.compare = lambda x, y: x > y\n for x in arr:\n self.insert(x)\n \n def from_trees(self, trees):\n for tree in trees:\n self.trees[tree.degree] = tree\n if tree.degree > self.bit:\n self.bit = tree.degree\n\n def __peek_node(self):\n m, trees_k = inf, -1\n for i, node in self.trees.items():\n if self.compare(node.k, m):\n m = node.k\n trees_k = i\n return self.trees[trees_k]\n \n def peek(self):\n return self.__peek_node().k\n \n def union(self, other):\n if self.ascending != other.ascending:\n raise ValueError(\"Two Mergable Heaps have different order\")\n if other.bit == -1:\n return\n if self.bit == -1:\n self.trees = other.trees\n self.bit = other.bit\n return\n bit, max_bit = 0, max(self.bit, other.bit)\n new_trees = dict()\n reg = []\n while bit <= max_bit:\n if self.trees.get(bit):\n reg.append(self.trees[bit])\n if other.trees.get(bit):\n reg.append(other.trees[bit])\n if len(reg) == 1:\n new_trees[bit] = reg.pop()\n elif len(reg) == 2:\n t1 = reg.pop()\n t2 = reg.pop()\n if self.compare(t1.k, t2.k):\n t1.add(t2)\n reg.append(t1)\n else:\n t2.add(t1)\n reg.append(t2)\n elif len(reg) == 3:\n new_trees[bit] = reg.pop()\n t1 = reg.pop()\n t2 = reg.pop()\n if self.compare(t1.k, t2.k):\n t1.add(t2)\n reg.append(t1)\n else:\n t2.add(t1)\n reg.append(t2)\n bit += 1\n if len(reg) == 1:\n new_trees[bit] = reg.pop()\n else:\n bit -= 1\n self.trees = new_trees\n self.bit = bit\n \n def insert(self, k):\n if len(self.trees) == 0:\n self.trees[0] = Node(k)\n self.bit = 0\n else:\n new_mh = MergableHeap([k], ascending=self.ascending)\n self.union(new_mh)\n \n \n def pull(self):\n m = self.__peek_node()\n del self.trees[m.degree]\n other = MergableHeap(ascending=self.ascending)\n other.from_trees(m.children)\n self.union(other)\n return m.k\n \n def plot(self, path):\n forest_root = TreeNode(\"\")\n for tree in self.trees.values():\n forest_root.children.append(construct_tree_nodes(tree, label_fn=lambda x: x.k, children_attr =\"children\"))\n return plot_tree(forest_root, path)\n \n","repo_name":"haoda-li/notebook","sub_path":"notebook/csc265/assets/mergeable_heap.py","file_name":"mergeable_heap.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"52"}
+{"seq_id":"3067432500","text":"import torch\nimport torch.nn as nn\nfrom tqdm import tqdm\n\n\nclass Engine():\n def __init__(self, train_config, train_loader, val_loader, device):\n self.train_config = train_config\n self.train_loader = train_loader\n self.val_loader = val_loader\n self.device = device \n \n def loss_fn(self, true_mel, \n true_stop_token, \n pred_mel_post, \n pred_mel, \n pred_stop_token):\n \n mel_loss = nn.L1Loss()(pred_mel, true_mel) + nn.L1Loss()(pred_mel_post, true_mel)\n bce_loss = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(self.train_config.bce_weight))(pred_stop_token.squeeze(), true_stop_token)\n \n \n return mel_loss, bce_loss\n\n def train_step(self, model, optimizer, scheduler):\n running_loss = 0\n mel_losses = 0\n bce_losses = 0\n model.train()\n optimizer.zero_grad()\n for data in tqdm(self.train_loader):\n character = data['text'].to(self.device)\n mel = data['mel'].to(self.device)\n mel_input = data['mel_input'].to(self.device)\n pos_text = data['pos_text'].to(self.device)\n pos_mel = data['pos_mel'].to(self.device)\n stop_token = data['stop_tokens'].to(self.device)\n \n mel_out, postnet_out, stop_pred, enc_attn_list, mask_attn_list, enc_dec_attn_list = model(\n character, mel_input, pos_text, pos_mel)\n mel_loss, bce_loss = self.loss_fn(mel, stop_token, postnet_out, mel_out, stop_pred)\n \n mel_losses += mel_loss\n bce_losses += bce_loss\n loss = mel_loss + bce_loss\n running_loss += loss\n loss.backward()\n nn.utils.clip_grad_norm_(model.parameters(), 1.)\n optimizer.step()\n scheduler.step()\n \n epoch_loss = running_loss/len(self.train_loader)\n mel_losses = mel_losses/len(self.train_loader)\n bce_losses = bce_losses/len(self.train_loader)\n return epoch_loss, mel_losses, bce_losses, enc_attn_list, mask_attn_list, enc_dec_attn_list\n \n \n def val_step(self, model):\n model.eval()\n running_loss = 0\n mel_losses = 0\n bce_losses = 0\n with torch.no_grad():\n for data in tqdm(self.val_loader):\n character = data['text'].to(self.device)\n mel = data['mel'].to(self.device)\n mel_input = data['mel_input'].to(self.device)\n pos_text = data['pos_text'].to(self.device)\n pos_mel = data['pos_mel'].to(self.device)\n stop_token = data['stop_tokens'].to(self.device)\n\n mel_out, postnet_out, stop_pred, enc_attn_list, mask_attn_list, enc_dec_attn_list = model(\n character, mel_input, pos_text, pos_mel)\n mel_loss, bce_loss = self.loss_fn(\n mel, stop_token, postnet_out, mel_out, stop_pred)\n\n mel_losses += mel_loss\n bce_losses += bce_loss\n loss = mel_loss + bce_loss\n running_loss += loss\n \n epoch_loss = running_loss/len(self.val_loader)\n mel_losses = mel_losses/len(self.val_loader)\n bce_losses = bce_losses/len(self.val_loader)\n return epoch_loss, mel_losses, bce_losses, enc_attn_list, mask_attn_list, enc_dec_attn_list\n","repo_name":"yw0nam/TransformerTTS","sub_path":"regacy/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9482318539","text":"import copy\nfrom .gotypes import Player\n\n\nclass Move():\n def __init__(self, point=None, is_pass=False, is_regin=False):\n assert (point is not None) ^ is_pass ^ is_regin\n self.point = point\n self.is_play = (point is not None) # 落子\n self.is_pass = is_pass # 跳过\n self.is_regin = is_regin # 认输\n\n @classmethod # classmethod 修饰符对应的函数不需要实例化\n def play(cls, point):\n return Move(point=point) # 在棋盘上落下一颗棋子\n\n @classmethod\n def pass_turn(cls):\n return Move(is_pass=True)\n\n @classmethod\n def regin(cls):\n return Move(is_regin=True)\n\n\nclass GoString():\n def __init__(self, color, stones, liberties):\n self.color = color\n self.stones = set(stones)\n self.liberties = set(liberties)\n\n def remove_liberty(self, point):\n self.liberties.remove(point)\n # def remove_liberty(self, point):\n # self.liberties.remove(point)\n\n def add_liberty(self, point):\n self.liberties.add(point)\n\n def merged_with(self, go_string): # 合并棋链的函数\n assert go_string.color == self.color\n combined_stones = self.stones | go_string.stones\n return GoString(\n self.color,\n combined_stones,\n (self.liberties | go_string.liberties) - combined_stones) # 气指的是棋链还剩的气眼\n\n @property\n def num_liberties(self):\n return len(self.liberties)\n\n def __eq__(self, other):\n return isinstance(other, GoString) and \\\n self.color == other.color and \\\n self.stones == other.stones and \\\n self.liberties == other.liberties\n # 比较两个值是否相等\n\n\nclass Board(): # 定义棋盘类\n def __init__(self, num_rows, num_cols):\n self.num_rows = num_rows\n self.num_cols = num_cols\n self._grid = {}\n\n def is_on_grid(self, point):\n return 1 <= point.row <= self.num_rows and \\\n 1 <= point.col <= self.num_cols\n\n def get(self, point): # 返回棋盘交叉点的颜色\n string = self._grid.get(point)\n if string is None:\n return None\n return string.color\n\n def get_go_string(self, point): # 返回一个交叉点上的整条棋链\n string = self._grid.get(point)\n if string is None:\n return None\n return string\n\n # def place_stone(self, player, point):\n # assert self.is_on_grid(point)\n # assert self._grid.get(point) is None\n # adjacent_same_color = []\n # adjacent_opposiet_color = []\n # liberties = []\n # for neighbor in point.neighbors():\n # if not self.is_on_grid(neighbor):\n # continue\n # # pdb.set_trace()\n # neighbor_string = self._grid.get(neighbor)\n\n # if neighbor_string is None:\n # liberties.append(neighbor) # 如果没被占据说明还有气那么我们增加\n # elif neighbor_string.color == player:\n # if neighbor_string not in adjacent_same_color:\n\n # adjacent_same_color.append(neighbor_string)\n # else:\n # if neighbor_string not in adjacent_opposiet_color:\n # adjacent_opposiet_color.append(neighbor_string)\n # new_string = GoString(player, [point], liberties)\n # for same_color_string in adjacent_same_color:\n # new_string = new_string.merged_with(same_color_string)\n # for new_string_point in new_string.stones:\n # self._grid[new_string_point] = new_string\n # for other_color_string in adjacent_opposiet_color:\n # other_color_string.remove_liberty(point) # 减少对面棋子的气\n # for other_color_string in adjacent_opposiet_color:\n # if other_color_string.num_liberties == 0:\n # self._remove_string(other_color_string)\n # # 如果气全部提走,那么我们将该链全部取消\n def place_stone(self, player, point):\n assert self.is_on_grid(point)\n assert self._grid.get(point) is None\n adjacent_same_color = []\n adjacent_opposite_color = []\n liberties = []\n for neighbor in point.neighbors(): # <1>\n if not self.is_on_grid(neighbor):\n continue\n neighbor_string = self._grid.get(neighbor)\n if neighbor_string is None:\n liberties.append(neighbor)\n elif neighbor_string.color == player:\n if neighbor_string not in adjacent_same_color:\n adjacent_same_color.append(neighbor_string)\n else:\n if neighbor_string not in adjacent_opposite_color:\n adjacent_opposite_color.append(neighbor_string)\n new_string = GoString(player, [point], liberties)\n# <1> First, we examine direct neighbors of this point.\n# end::board_place_0[]\n# tag::board_place_1[]\n for same_color_string in adjacent_same_color: # <1>\n new_string = new_string.merged_with(same_color_string)\n for new_string_point in new_string.stones:\n self._grid[new_string_point] = new_string\n for other_color_string in adjacent_opposite_color: # <2>\n other_color_string.remove_liberty(point)\n for other_color_string in adjacent_opposite_color: # <3>\n if other_color_string.num_liberties == 0:\n self._remove_string(other_color_string)\n def _remove_string(self, string):\n for point in string.stones:\n for neighbor in point.neighbors():\n neighbor_string = self._grid.get(neighbor)\n if neighbor_string is None:\n continue\n if neighbor_string is not string:\n neighbor_string.add_liberty(point) # 如果一个棋链被提走则气会增加\n self._grid[point] = None\n# 游戏状态类包括棋子中的下一回合执子方,上一回合的游戏状态以及上一步动作\n\n\nclass GameState():\n def __init__(self, board, next_player, previous, move):\n self.board = board\n self.next_player = next_player\n self.previous_state = previous\n self.last_move = move\n\n def apply_move(self, move):\n if move.is_play:\n next_board = copy.deepcopy(self.board) # 深度拷贝,被复制的对象作为一个新的对象存在\n next_board.place_stone(self.next_player, move.point)\n else:\n next_board = self.board\n return GameState(next_board, self.next_player.other, self, move)\n\n @classmethod\n def new_game(cls, board_size):\n if isinstance(board_size, int):\n board_size = (board_size, board_size)\n board = Board(*board_size)\n return GameState(board, Player.black, None, None)\n\n def is_over(self):\n if self.last_move is None:\n return False\n if self.last_move.is_regin:\n return True\n second_last_move = self.previous_state.last_move\n if second_last_move is None:\n return False\n return self.last_move.is_pass and second_last_move.is_pass # 如果两方都选择不下那么本局结束\n\n def is_move_self_capture(self, player, move):\n if not move.is_play:\n return False\n next_board = copy.deepcopy(self.board)\n next_board.place_stone(player, move.point)\n new_string = next_board.get_go_string(move.point)\n return new_string.num_liberties == 0 # 判断是否到自吃的地步\n\n @property\n def situation(self):\n return (self.next_player, self.board)\n\n def does_move_violate_ko(self, player, move):\n if not move.is_play:\n return False\n next_board = copy.deepcopy(self.board)\n next_board.place_stone(player, move.point)\n next_situation = (player.other, next_board) # 这个状态代表即将下子的人和当前棋局的样子\n past_state = self.previous_state\n while past_state is not None:\n if past_state.situation == next_situation:\n return True\n past_state = past_state.previous_state # 个人感觉这个速度挺慢的\n return False\n\n def is_valid_move(self, move):\n if self.is_over():\n return False\n if move.is_pass or move.is_regin:\n return True\n return (\n self.board.get(move.point) is None and\n not self.is_move_self_capture(self.next_player, move) and\n not self.does_move_violate_ko(self.next_player, move)\n\n )\n","repo_name":"liujiawen-jpg/code1","sub_path":"dlgo/goboard_slow.py","file_name":"goboard_slow.py","file_ext":"py","file_size_in_byte":8688,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"17818695880","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport logging\nfrom setuptools import setup\nimport kolibri_oidc_client_plugin\n\n\ndist_name = 'kolibri_oidc_client_plugin'\n\n\n# Default description of the distributed package\ndescription = (\n \"\"\"Kolibri plugin to authenticate using an OpenID Connect provider\"\"\"\n)\n\n\ndef enable_log_to_stdout(logname):\n \"\"\"Given a log name, outputs > INFO to stdout.\"\"\"\n log = logging.getLogger(logname)\n log.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n # add formatter to ch\n ch.setFormatter(formatter)\n # add ch to logger\n log.addHandler(ch)\n\n\nlong_description = \"\"\"\n`Kolibri `_ is the offline learning platform\nfrom `Learning Equality `_.\n\nOpenID Connect (OIDC) is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.).\n\nThis package provides Kolibri users with the ability to authenticate against an OpenID provider. This is usually a need when integrating it with another applications sharing a Single Sign On (SSO) authentication.\n\"\"\"\n\nsetup(\n name=dist_name,\n version=kolibri_oidc_client_plugin.__version__,\n description=description,\n long_description=long_description,\n author='Learning Equality',\n author_email='info@learningequality.org',\n url='https://github.com/learningequality/kolibri-oidc-client-plugin',\n packages=[\n str('kolibri_oidc_client_plugin'), # https://github.com/pypa/setuptools/pull/597\n ],\n entry_points={\n \"kolibri.plugins\": \"kolibri_oidc_client_plugin = kolibri_oidc_client_plugin\",\n },\n package_dir={'kolibri_oidc_client_plugin': 'kolibri_oidc_client_plugin'},\n include_package_data=True,\n license='MIT',\n install_requires=['mozilla-django-oidc==1.2.4', 'kolibri>=0.15'],\n extras_require={\n 'dev': [\n 'setuptools',\n 'wheel>=0.34.1',\n 'twine',\n ]\n },\n zip_safe=False,\n keywords='kolibri',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Education :: Computer Aided Instruction (CAI)',\n 'Topic :: System :: Systems Administration :: Authentication/Directory'\n ],\n)\n","repo_name":"learningequality/kolibri-oidc-client-plugin","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"38903392004","text":"\"\"\"\r\nWrite a function done_or_not/DoneOrNot passing a board (list[list_lines]) as parameter.\r\nIf the board is valid return 'Finished!', otherwise return 'Try again!'\r\n\"\"\"\r\n\r\n\r\ndef done_or_not(board): # board[i][j]\r\n if len(board) != 9:\r\n return 'Try again!'\r\n else:\r\n for line in board:\r\n if (len(line) != 9) or (len(line) > len(set(line))) or (sum(line) != 45):\r\n return 'Try again!'\r\n else:\r\n for i in range(0, 9):\r\n vert_list = [board[0][i], board[1][i], board[2][i],\r\n board[3][i], board[4][i], board[5][i],\r\n board[6][i], board[7][i], board[8][i]]\r\n if sum(vert_list) != 45 or (len(vert_list) > len(set(vert_list))):\r\n return 'Try again!'\r\n else:\r\n for i in range(0, 7, 3):\r\n region = [board[i][i], board[i][i + 1], board[i][i + 2],\r\n board[i + 1][i], board[i + 1][i + 1], board[i + 1][i + 2],\r\n board[i + 2][i], board[i + 2][i + 1], board[i + 2][i + 2]]\r\n if sum(region) != 45 or (len(region) > len(set(region))):\r\n return 'Try again!'\r\n else:\r\n return 'Finished!'\r\n","repo_name":"sulcjusz/DP-Portfolio","sub_path":"CodewarsSolutions/check_sudoku.py","file_name":"check_sudoku.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"31223716384","text":"# -*- encoding=utf8 -*-\n__author__ = \"zheng.cong\"\n\nfrom airtest.core.api import *\nimport time\nimport pytest\nimport os, sys\nfrom airtest.core.api import *\n\nimport logging\nimport airtest.utils.logger as logger\nlogger.get_logger(\"airtest\").setLevel(logging.ERROR)\n\nclass Get_config(object):\n\tdef __init__(self):\n\t\tself.path = 'Z:\\\\publish\\\\android\\\\China\\\\6.9.1\\\\pilot_run'\n\n\tdef get_apks_name(self):\n\t\treturn ([os.path.join(root, filename) for root, dirs, files, in os.walk(self.path) for filename in files if filename.endswith('apk')])\n\n\tdef get_devices():\n\t\tos.system('adb kill-server')\n\t\tos.system('adb start-server')\n\t\tconnect_device(\"Android://127.0.0.1:5037/172.16.2.144:7777\")\n\t\tprint('设备已连接:', device())\n\n\tdef get_channel_name(apkName):\n\t\twhole_channelName = os.path.basename(apkName)\n\t\tif whole_channelName.split('_')[2].isdigit():\n\t\t\tchannelName = whole_channelName.split('_')[1]\n\t\telse:\n\t\t\tchannelName = whole_channelName.split('_')[1] + '_' + whole_channelName.split('_')[2]\n\t\treturn channelName\n\nclass channelLogin():\n\tdef __init__(self, channelName):\n\t\tself.channelName = channelName\n\tdef channelLogin(self):\n\t\tif self.channelName == 'vivo':\n\t\t\tif exists(Template(r\"tpl1570873650954.png\", record_pos=(-0.261, 0.714), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570873650954.png\", record_pos=(-0.261, 0.714), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'oppo':\n\t\t\tif exists(Template(r\"tpl1570873720097.png\", record_pos=(0.355, -0.363), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570873720097.png\", record_pos=(0.355, -0.363), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\t\telif exists(Template(r\"tpl1570874787685.png\", record_pos=(-0.27, 0.716), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570874787685.png\", record_pos=(-0.27, 0.716), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'huawei' or self.channelName == 'qq_huawei':\n\t\t\tprint(self.channelName)\n\t\t\tif exists(Template(r\"tpl1570873588104.png\", record_pos=(-0.207, 0.696), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570873588104.png\", record_pos=(-0.207, 0.696), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\t\telif exists(Template(r\"tpl1571387538084.png\", record_pos=(0.445, -0.54), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1571387538084.png\", record_pos=(0.445, -0.54), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\n\t\telif self.channelName == 'tencent' or self.channelName == 'qq_browser' or self.channelName == 'qq_guanjia':\n\t\t\tif exists(Template(r\"tpl1570873686930.png\", record_pos=(0.001, 0.682), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570873686930.png\", record_pos=(0.001, 0.682), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\nclass Test_updateCheck(object):\n\n\tdef teardown_class(self):\n\t\tfor apkName in device().list_app():\n\t\t\tif 'jelly' in apkName:\n\t\t\t\tuninstall(apkName)\n\n\t@pytest.fixture\n\tdef log(self):\n\t\tlog_for_test = logging.getLogger('test_check')\n\t\tlog_for_test.setLevel(logging.INFO)\n\t\treturn log_for_test\n\n\t@pytest.fixture\n\tdef channelName(self, apkName):\n\t\twhole_channelName = os.path.basename(apkName)\n\t\tif whole_channelName.split('_')[2].isdigit():\n\t\t\tchannelName = whole_channelName.split('_')[1]\n\t\telse:\n\t\t\tchannelName = whole_channelName.split('_')[1] + '_' + whole_channelName.split('_')[2]\n\t\treturn channelName\n\t# @pytest.mark.usefixtures('device_connect')\n\t# 使用usefixtures的方法会报错——无法识别出fixture的返回(识别成了function)\n\t# fixture配置成auto且下方不将device_connect配置为参数也会报错,信息同上\n\t# @pytest.mark.parametrize(\"apkName\", Get_config().get_apks_name())\n\tdef test_install_apks(self, apkName, channelName, log):\n\t\tprint('start install %s'%(channelName))\n\t\tis_installed = False\n\t\tdevice().install_app(apkName, replace=True)\n\t\tsleep(10)\n\t\tfor apkName in device().list_app():\n\t\t\tif 'jelly' in apkName:\n\t\t\t\tis_installed = True\n\t\t\t\tbreak\n\t\tassert is_installed, '低版本安装失败'\n\t\tlog.info('低版本%s安装成功'%(channelName))\n\n\t@pytest.mark.incremental\n\tdef test_start_apk(self, log):\n\t\tstart_game = False\n\t\tfor i in device().list_app():\n\t\t\tif 'jelly' in i:\n\t\t\t\tstart_app(i)\n\t\t\t\tsleep(10)\n\t\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\t\tstart_game = True\n\t\t\t\t\tbreak\n\t\t# 这里应该判断一下当前运行的app, 但由于有权限弹窗干扰了判断\n\t\t# air_adb = r'C:\\Users\\zheng.cong\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\\airtest\\core\\android\\static\\adb\\windows\\adb'\n\t\t# cur_app = os.popen(air_adb + ' shell dumpsys window | findstr mCurrentFocus').readlines()\n\t\t# for i in cur_app:\n\t\t# \tif 'jelly' in cur_app:\n\t\t# \t\tstart_game = True\n\t\tassert start_game, '启动失败'\n\t\tlog.info('启动游戏')\n\n\tdef is_in_game(self):\n\t\tif exists(Template(r\"tpl1570782212384.png\", record_pos=(0.427, -0.824), resolution=(1080, 1920))):\n\t\t\ttouch(Template(r\"tpl1570782212384.png\", record_pos=(0.427, -0.824), resolution=(1080, 1920)))\n\t\t\tif exists(Template(r\"tpl1571210117925.png\", record_pos=(0.101, -0.027), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1571210148111.png\", record_pos=(0.431, -0.647), resolution=(1080, 1920)))\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef phone_authorized(self):\n\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\tsleep(1)\n\n\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\tsleep(1)\n\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\tsleep(1)\n\n\t\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\tif exists(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920))):\n\t\t\t\t\tsleep(1)\n\n\t\t\t\t\ttouch(Template(r\"tpl1570782102183.png\", record_pos=(0.244, 0.806), resolution=(1080, 1920)))\n\t\t\t\t\tsleep(1)\n\n\t@pytest.mark.incremental\n\tdef test_get_in_game(self, channelName, log):\n\t\ttryNum = 1\n\t\twhile not self.is_in_game():\n\t\t\tis_in_game = False\n\t\t\tself.phone_authorized()\n\t\t\tsleep(10)\n\t\t\ttry_login = channelLogin(channelName).channelLogin()\n\t\t\tsleep(5)\n\t\t\tif exists(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920)))\n\t\t\tif tryNum == 4:\n\t\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_登录失败.png')\n\t\t\t\tbreak\n\t\t\ttryNum += 1\n\t\telse:\n\t\t\tis_in_game = True\n\t\t\t# print('执行点击')\n\t\t\tif exists(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570862752616.png\", record_pos=(-0.062, -0.042), resolution=(1080, 1920)))\n\t\tassert is_in_game, '进入游戏失败,需要处理前置渠道登录等'\n\t\tlog.info('进入游戏主界面')\n\n\t@pytest.mark.incremental\n\tdef test_update_opened(self, log):\n\t\ttry:\n\t\t\tif exists(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570779065225.png\", record_pos=(0.009, 0.315), resolution=(1080.0, 1920.0)))\n\t\t\t\tsleep(1)\n\t\t\t\tis_update_opened = True\n\t\t\telse:\n\t\t\t\tis_update_opened = False\n\t\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_无更新提醒主界面截图.png')\n\t\texcept:\n\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_无更新提醒主界面截图.png')\n\t\t\tis_update_opened = False\n\t\tassert is_update_opened, '此渠道更新提醒未开启'\n\t\tlog.info('开启了更新提醒')\n\n\t@pytest.mark.incremental\n\tdef test_is_downloading(self, log):\n\t\ttry:\n\t\t\t# 有时候点击开始下载出现进度条后会立即失败,多试几次\n\t\t\tsleep(3)\n\t\t\ttryNum = 1\n\t\t\twhile not exists(Template(r\"tpl1570793068491.png\", record_pos=(-0.151, 0.225), resolution=(1080, 1920))):\n\t\t\t\ttouch(Template(r\"tpl1570779032974.png\", record_pos=(-0.426, -0.654), resolution=(1080, 1920)))\n\t\t\t\tsleep(1)\n\t\t\t\ttouch(Template(r\"tpl1570779065225.png\", record_pos=(0.009, 0.315), resolution=(1080.0, 1920.0)))\n\t\t\t\tsleep(1)\n\t\t\t\t# start_update_download(channelName, log)\n\t\t\t\ttryNum += 1\n\t\t\t\tif tryNum == 3:\n\t\t\t\t\tis_downloading = False\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tis_downloading = True\n\t\texcept:\n\t\t\tis_downloading = False\n\t\tassert is_downloading, '未能正常开始下载'\n\t\tlog.info('更新提醒开始下载')\n\n\n\t@pytest.mark.incremental\n\tdef test_is_downloaded_finished(self, log):\n\t\ttry:\n\t\t\tif wait(Template(r\"tpl1570780317693.png\", record_pos=(0.246, 0.8), resolution=(1080, 1920)), timeout=300, interval=10):\n\t\t\t\tis_downloaded_finished = True\n\t\texcept:\n\t\t\tsnapshot('G:\\\\Airtest\\\\test_upadte.air\\\\' + channelName + '_下载失败.png')\n\t\t\tis_downloaded_finished = False\n\t\tassert is_downloaded_finished, '下载失败或超时'\n\t\tlog.info('新版本下载成功')\n\n\nif __name__ == '__main__':\n\tGet_config.get_devices()\n\tmy_cmd = '--apkName'\n\tfor apkName in Get_config().get_apks_name():\n\t\tcmd_content = apkName\n\t\tchannelName = Get_config.get_channel_name(apkName)\n\t\tcmd_report = '--html=./report/' + channelName + '_report.html'\n\t\tpytest.main(['-p', 'no:warnings', '-s', '-v', my_cmd, cmd_content, 'test_updateCheck_pytest.py', cmd_report])\n\n\n\n","repo_name":"congzheng-git/myProject","sub_path":"Test_UpdateCheck_byPytest/test_updateCheck_inGame_pytest.py","file_name":"test_updateCheck_inGame_pytest.py","file_ext":"py","file_size_in_byte":9332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"37173514785","text":"from unittest import TestCase\nimport pandas as pd\n\nfrom elmo_on_md.data_loaders.sentiment_loader import SentimentLoader\n\nclass TestSentimentLoader(TestCase):\n def test_load_data(self):\n data = SentimentLoader().load_data()\n self.assertGreater(len(data['train']['sentences']), 0)\n self.assertEqual(len(data['train']['labels']), len(data['train']['sentences']))\n\n def test__read_sentence(self):\n sentence ='שלום עולם!\\t1'\n loader = SentimentLoader()\n (tokens,label)=loader._read_sentence(sentence)\n self.assertEqual(len(tokens),2)\n self.assertEqual(label,1)\n\n","repo_name":"idanbrus/ELMoOnMD","sub_path":"elmo_on_md/data_loaders/tests/test_SentimentLoader.py","file_name":"test_SentimentLoader.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"19994265655","text":"from builtins import map\nfrom builtins import str\nfrom hashlib import sha1\nimport re\nimport json\nimport yaml\nimport subprocess\nimport os\nimport logging\nimport time\nfrom stallion import util\nfrom stallion.components.base import BaseComponent\nfrom stallion.auth import Authorizer\nfrom stallion.deploy.base import \\\n BaseVersionedArtifactDeployer, \\\n ServiceVersion\nfrom .autoscaling import AutoscalingManager\n\n\nclass GCEServiceVersion(ServiceVersion):\n def __init__(self, instance):\n base_instance_name = instance['baseInstanceName']\n\n (version, timestamp) = (None, None) if 'instanceTemplate' not in instance \\\n else self.version_from_template_name(\n os.path.basename(instance['instanceTemplate']),\n base_instance_name)\n\n super(GCEServiceVersion, self).__init__(\n service_name=base_instance_name,\n version=version if version else None)\n\n self.instance = instance\n\n\n is_active = True\n\n @staticmethod\n def version_from_template_name(template_name, base_instance_name):\n \"\"\" Determine the deployed code version from the instance template\n name. Requires the instance template name to be of the format\n $BASE_INSTANCE_NAME-$CODE_SEMVER-$TIMESTAMP, although the SEMVER\n is assembled with '-' between fields rather than '.'.\n\n Returns tuples of the form ($SEMVER, $TIMESTAMP).\n\n :param template_name: name of the instance template\n :type template_name: string\n :param base_instance_name: base instance name, returned by GCE API\n :type base_instance_name: string\n \"\"\"\n name_pattern = base_instance_name + '-(([0-9]+-){3})([a-zA-Z0-9-]+-)?([0-9]+)'\n if not template_name.startswith(base_instance_name):\n logging.debug('Instance template name %s does not start with '\n 'base instance name %s; cannot determine instance'\n ' template version',\n base_instance_name,\n template_name)\n return (None, None)\n\n match = re.match(name_pattern, template_name)\n if not match:\n logging.debug(\n 'Unrecognized template version %s for instance '\n 'template %s: not of the format $SEMVER-$TIMESTAMP',\n template_name[1+len(base_instance_name):],\n template_name)\n return (None, None)\n\n major_minor_patch = match.group(1).rstrip('-').replace('-', '.')\n prerelease = match.group(3)\n semver = '-'.join([_f for _f in [major_minor_patch, prerelease] if _f]).rstrip('-')\n\n timestamp = int(match.group(4))\n\n logging.info(\n 'Parsed template name %s to service version %s, timestamp %d',\n template_name,\n semver,\n timestamp)\n\n return (semver, timestamp)\n\n\nclass ComputeEngineDeployer(BaseVersionedArtifactDeployer):\n type = 'gce'\n\n deploy_files = [ 'cloud-init.yaml' ]\n\n # Experimental feature. That URI will have to be defined elsewhere.\n def get_deployment_uri(self, component, versioned=False):\n host_prefix = '{app_name}-dot-{project_id}'.format(\n app_name = component.name,\n project_id = self.project_id)\n\n if versioned:\n encoded_version = util.encode_version(component.code_version)\n host_prefix = encoded_version + '-dot-' + host_prefix\n\n return 'https://' + host_prefix + '-dot-us-central1.etsycloud.com'\n\n def get_deployed_versions(self, relevant_components):\n \"\"\" Find all deployed managed instance groups and the versions of\n their associated instance templates\n \"\"\"\n gcloud_args = [\n 'gcloud',\n 'compute',\n 'instance-groups',\n 'managed',\n 'list',\n '--format=json',\n '--project', self.project_id ]\n\n result = json.loads(subprocess.check_output(gcloud_args).decode('utf-8'))\n\n return self.get_GCEServiceVersions_from_groups(result)\n\n @staticmethod\n def get_GCEServiceVersions_from_groups(result):\n return [ item for item in map(GCEServiceVersion, result) if item.version ]\n\n @classmethod\n def build_cloud_init_path(cls, component):\n return os.path.join(component.config_dir, 'cloud-init.yaml')\n\n @classmethod\n def build_service_version_name(cls, component):\n template_version = util.encode_version(component.code_version)\n timestamp = int(time.time()*1000)\n # The full instance group name may only be up to 61 characters long\n # The timestamp and the hyphen before it are 14 characters, so the\n # service name and version can be no longer than 47 characters\n name_and_version = \"{}-{}\".format(component.name, template_version)\n if len(name_and_version) > 47:\n name_and_version_hash = sha1(name_and_version.encode(\"utf-8\")).hexdigest()[:6]\n name_and_version = name_and_version[:40] + \"-\" + name_and_version_hash\n return \"{}-{}\".format(name_and_version, timestamp).lower()\n\n @staticmethod\n def instance_group_uri(project_id, component):\n zone_or_region_path = (\n 'regions/' + component.descriptor['gce']['region']\n ) if component.descriptor['gce'].get('zones') else (\n 'zones/' + component.descriptor['gce']['zone']\n )\n\n return 'https://www.googleapis.com/compute/v1/projects/{project}/{zone_or_region}/instanceGroupManagers/{name}'.format(\n project = project_id,\n zone_or_region = zone_or_region_path,\n name = component.name\n )\n\n def _get_instance_group(self, component, session):\n response = session.get(\n self.instance_group_uri(self.project_id, component),\n timeout=10)\n\n if response.status_code < 300:\n return response.json()\n elif response.status_code == 404:\n logging.info('Instance group %s does not exist', component.name)\n return None\n\n response.raise_for_status()\n\n @staticmethod\n def instance_template_uri(project, name):\n return 'https://www.googleapis.com/compute/v1/projects/{project}/global/instanceTemplates/{name}'.format(**locals())\n\n def _check_if_instance_template_exists(self, service_name, session):\n response = session.get(\n self.instance_template_uri(self.project_id, service_name),\n timeout=10)\n\n if response.status_code < 300:\n return True\n elif response.status_code == 404:\n return False\n\n response.raise_for_status()\n\n def _delete_instance_template(self, component, template_version, service_name):\n\n cmd = \"echo y | gcloud compute instance-templates delete {instance_template_name} --project {project}\".format(\n instance_template_name=service_name,\n project=self.project_id)\n\n return cmd\n\n def _build_network_config(self, config):\n def port_legacy_network():\n return [] if not config.get('default_network_uri') else [{\n 'network': config['default_network_uri'],\n 'subnet': config['default_subnetwork_uri'],\n 'no_address': True,\n }]\n\n def build_network_directive(network):\n return '--network-interface=network={network},subnet={subnet},no-address'.format(**network)\n\n networks = port_legacy_network() + config.get('network_interfaces', [])\n\n return ' '.join(map(build_network_directive, networks))\n\n def _create_instance_template(self, component: BaseComponent,\n cloud_init_path: str, template_version: str, service_name: str) -> str:\n\n config = component.descriptor['gce']\n\n pd_settings = ''\n pd = config.get('persistent_disk')\n if pd:\n pd_settings += '--disk=auto-delete=no,boot=no'\n pd_settings += ',device-name={}'.format(pd['device_name'])\n pd_settings += ',mode={}'.format(pd['mode'])\n pd_settings += ',name={}'.format(pd['name'])\n\n # If a reservation name is supplied, force the instance-template to use it.\n reservation_affinity_setting = ''\n reservation_name_setting = ''\n res_name = config.get('reservation_name')\n if res_name:\n reservation_affinity_setting += '--reservation-affinity=specific'\n reservation_name_setting += '--reservation={}'.format(res_name)\n\n cmd = \"gcloud beta compute instance-templates create \\\n {instance_template_name} \\\n --project={project} \\\n --region={region} \\\n --machine-type={machine_type} \\\n --boot-disk-size={boot_disk_size} \\\n --boot-disk-type=pd-standard \\\n --image-project=cos-cloud \\\n --image-family=cos-stable \\\n --tags={tags} \\\n --labels=code_version={version} \\\n --service-account={service_account} \\\n --scopes=https://www.googleapis.com/auth/cloud-platform \\\n {network_config} {persistent_disk} {reservation_affinity} {reservation_name} \\\n --metadata-from-file=user-data={cloud_init_path}\".format(\n instance_template_name = service_name,\n project = self.project_id,\n region = config['region'],\n machine_type = config['machine_type'],\n boot_disk_size = config['disk_size_gb'],\n network_config = self._build_network_config(config),\n persistent_disk = pd_settings,\n reservation_affinity = reservation_affinity_setting,\n reservation_name = reservation_name_setting,\n service_account = config['service_account'],\n version = template_version,\n tags = \",\".join(config['default_network_tags']),\n cloud_init_path = cloud_init_path)\n\n return cmd\n\n def _update_instance_group_if_needed(self, component, instance_group):\n \"\"\" Perform any necessary updates on the instance group. Right now,\n the only thing we support is changes to the instance group size\n \"\"\"\n config = component.descriptor['gce']\n\n if component.descriptor['gce'].get('autoscaling'):\n logging.info(\n 'Instance group %s: autoscaling is enabled; skipping group size check.',\n component.name)\n return ''\n\n # GCE refers to the 'targetSize' as opposed to the _actual_ size\n # of the instance group, in order to account for things like\n # autoscaling that can cause these things to be different.\n # For our manually-scaled instance groups, we'll refer to a\n # \"requested target size\", indicating that this is what we want GCE\n # to want the group size to be, if that makes sense...\n # We compare against GCE's actual target size and apply changes if\n # they do not match.\n requested_target_size = config['instance_group_size']\n actual_target_size = instance_group['targetSize']\n if actual_target_size == requested_target_size:\n return ''\n\n logging.info(\n 'Updating size of instance group %s from %d to %d',\n component.name,\n actual_target_size,\n requested_target_size)\n\n cmd = \"\"\"\n gcloud beta compute instance-groups managed resize \\\n {instance_group_name} \\\n --size {target_size} \\\n {zone_or_region} \\\n --project {project}\n \"\"\".format(\n instance_group_name=component.name,\n target_size=requested_target_size,\n zone_or_region=self._zone_or_region_arg(component),\n project=self.project_id)\n\n return cmd\n\n\n def _rolling_update_instance_template(self, component, instance_template_name, instance_group):\n \"\"\" Perform a rolling update of the existing instance group with the new template.\n See: https://cloud.google.com/compute/docs/instance-groups/updating-managed-instance-groups#starting_a_basic_rolling_update\n \"\"\"\n config = component.descriptor['gce']\n\n recreate_on_replace = config.get('recreate_on_replace', False)\n replace_method_arg = '--replacement-method=recreate' if recreate_on_replace else ''\n\n # Choose the max-surge parameter. Ideally we would set this as a fraction\n # of the instance group, and google does technically allow this, but only\n # for groups with > 10 instances. If this group is large enough, we'll\n # do that, otherwise, we'll set to the maximium of:\n # - the number of zones enabled (this is a hard minimum)\n # - the specified instance group size\n # - the actual instance group size\n # We don't generally expect to use very large instance groups, to deploy\n # very often, or for deploys to take much time, so we're not overly\n # concerned about the groups growing too big during the update.\n #\n # If we use the recreate replacement method, max_surge must be 0.\n # https://cloud.google.com/compute/docs/instance-groups/rolling-out-updates-to-managed-instance-groups#replacement_method\n\n max_surge = None\n if recreate_on_replace:\n max_surge = 0\n elif instance_group.get('targetSize', 0) > 10:\n max_surge = '80%'\n else:\n max_surge = max(\n 1,\n len(config.get('zones', [])),\n config.get('instance_group_size', 1),\n instance_group.get('targetSize', 1)\n )\n\n # If using recreate_on_replace set max_unavailable to 1, basically stopping an\n # instance, bringing a new one up, and then moving on to the next in the group.\n #\n # Otherwise, set the maxUnavailable parameter to 0, which will prevent GCE from\n # allowing a state in which no instances are available for querying\n # (we believe that we have entered such a state in the past when we\n # have rolled updates to instance groups containing only 1 instance,\n # or only 1 instance per zone). Note that the only apparent downside\n # to setting this to 0 is that this maximizes the size of the\n # instance group during the rolling update. But generally our instance\n # groups are all quite small, so this seems like it should not create\n # any real problems?\n # Make this a variable so that we can easily add more logic to it at\n # some future time.\n # see: https://cloud.google.com/compute/docs/instance-groups/rolling-out-updates-to-managed-instance-groups#max_unavailable\n max_unavailable = 1 if recreate_on_replace else 0\n\n cmd = \"\"\"\n gcloud beta compute instance-groups managed \\\n rolling-action start-update {instance_group_name} \\\n --version template={instance_template_name} \\\n --max-surge {max_surge} \\\n --max-unavailable {max_unavailable} \\\n {zone_or_region} \\\n {replacement} \\\n --project {project}\n \"\"\".format(instance_group_name=component.name,\n instance_template_name=instance_template_name,\n replacement=replace_method_arg,\n max_surge=max_surge,\n max_unavailable=max_unavailable,\n zone_or_region = self._zone_or_region_arg(component),\n project=self.project_id)\n\n return cmd\n\n @staticmethod\n def _zone_or_region_arg(component):\n config = component.descriptor['gce']\n\n if config.get('zone'):\n return '--zone ' + config['zone']\n else:\n return '--region ' + config['region']\n\n def _create_instance_group(self, component, service_name):\n # if creating a regional group, we must pass --zones as a separate\n # comma-separated parameter. So construct it as an optional parameter\n # (that is empty if not used) and include it in the template.\n optional_zones = ''\n if component.descriptor['gce'].get('zones'):\n optional_zones = '--zones ' + ','.join(\n component.descriptor['gce'].get('zones', [])\n )\n\n autohealing_settings = []\n autohealing = component.descriptor['gce'].get('autohealing')\n if autohealing:\n autohealing_settings += [\n '--health-check', autohealing['health_check_name']\n ]\n\n initial_delay = autohealing.get('initial_delay_sec')\n if initial_delay is not None:\n autohealing_settings += [\n '--initial-delay', str(initial_delay)\n ]\n\n cmd = \"\"\"\n gcloud compute instance-groups managed create \\\n {instance_group_name}\\\n --project={project} \\\n --template={instance_template_name}\\\n --size {instance_group_size} \\\n {zone_or_region} {optional_zones} \\\n {optional_autohealing_config}\"\"\".format(\n project=self.project_id,\n instance_group_name=component.name,\n instance_template_name=service_name,\n instance_group_size=component.descriptor['gce']['instance_group_size'],\n zone_or_region=self._zone_or_region_arg(component),\n optional_zones=optional_zones,\n optional_autohealing_config=' '.join(autohealing_settings))\n\n return cmd\n\n def _attach_load_balancer_to_instance_group(self, component):\n instance_group_region_or_zone = None\n if component.descriptor['gce'].get('zones'):\n instance_group_region_or_zone = (\n '--instance-group-region ' + component.descriptor['gce']['region']\n )\n else:\n instance_group_region_or_zone = (\n '--instance-group-zone ' + component.descriptor['gce']['zone']\n )\n\n cmd = \"\"\"\n gcloud compute backend-services add-backend {backend_name} \\\n --project {project} \\\n --instance-group {instance_group_name} \\\n {instance_group_region_or_zone} \\\n --region us-central1 \\\n --balancing-mode CONNECTION\n \"\"\".format(project=self.project_id,\n backend_name=component.name,\n instance_group_name=component.name,\n instance_group_region_or_zone=instance_group_region_or_zone)\n\n return cmd\n\n def build_gcloud_deploy_args(self, component, tmp_cloud_init_path, session, delete_template = False):\n template_version = util.encode_version(component.code_version)\n service_name = self.build_service_version_name(component)\n\n gcloud_args = []\n\n if delete_template and self._check_if_instance_template_exists(service_name, session):\n gcloud_args.append(self._delete_instance_template(\n component,\n template_version,\n service_name ))\n\n gcloud_args.append(self._create_instance_template(\n component,\n tmp_cloud_init_path,\n template_version,\n service_name ))\n\n instance_group = self._get_instance_group(component, session)\n if instance_group:\n gcloud_args.append(self._update_instance_group_if_needed(component, instance_group))\n gcloud_args.append(self._rolling_update_instance_template(component, service_name, instance_group))\n else:\n gcloud_args.append(self._create_instance_group(component, service_name))\n gcloud_args.append(self._attach_load_balancer_to_instance_group(component))\n\n return [self.prettify_output(arg) for arg in gcloud_args]\n\n def _needs_stable_wait(self, component):\n return component.descriptor['gce'].get('recreate_on_replace', False)\n\n def _create_stable_wait_command(self, component):\n zone_or_region_arg = None\n if component.descriptor['gce'].get('zones'):\n zone_or_region_arg = (\n '--region=' + component.descriptor['gce']['region']\n )\n else:\n zone_or_region_arg = (\n '--zone=' + component.descriptor['gce']['zone']\n )\n\n cmd = \"\"\"\n gcloud --project {project} \\\n compute instance-groups managed wait-until --stable \\\n --timeout=420 \\\n {instance_group_name} \\\n {zone_or_region_arg}\n \"\"\".format(project=self.project_id,\n instance_group_name=component.name,\n zone_or_region_arg=zone_or_region_arg)\n\n return cmd\n\n def _run_gcloud_deploy_args(self, gcloud_args, workdir):\n for arg in gcloud_args:\n subprocess.check_call(arg, cwd=workdir, shell=True)\n\n def _deploy_with_rendered_cloud_init_yaml(\n self,\n component,\n rendered_cloud_init_yaml,\n dry_run,\n workdir,\n session):\n\n logging.info(\n 'Deploying gce service %s: %s',\n component.name,\n component.code_version)\n\n tmp_cloud_init_path = os.path.join(workdir, 'cloud-init.yaml')\n with open(tmp_cloud_init_path, 'w') as _out:\n _out.write(rendered_cloud_init_yaml)\n\n gcloud_args = self.build_gcloud_deploy_args(\n component,\n tmp_cloud_init_path,\n session)\n\n if dry_run:\n logging.info(' dry run: Skipping execution of gcloud command `%s`', gcloud_args)\n return\n\n try:\n logging.info('Running these gcloud commands `%s`', gcloud_args)\n self._run_gcloud_deploy_args(gcloud_args, workdir)\n\n except Exception as e:\n logging.warning(\"Building gcloud deploy args failed with error {}. Deleting {} template and trying again\".format(\n e, component.name))\n\n gcloud_args = self.build_gcloud_deploy_args(\n component,\n tmp_cloud_init_path,\n session,\n delete_template = True)\n\n self._run_gcloud_deploy_args(gcloud_args, workdir)\n\n if self._needs_stable_wait(component):\n logging.info('Waiting for instance group to become stable')\n wait_cmd = self._create_stable_wait_command(component)\n logging.info('Executing wait command `%s`', self.prettify_output(wait_cmd))\n self._run_gcloud_deploy_args([wait_cmd], workdir)\n\n def _validate_cloud_init_yaml(self, component, rendered_cloud_init_yaml):\n \"\"\" For now, just do some simple validation: make sure that the\n rendered cloud_init.yaml file is a valid yaml file. It is\n conceivable that we could add more rigorous checks in the\n future, especially if we apply more standardized structure to the\n cloud-init.yaml files.\n \"\"\"\n loaded = yaml.safe_load(rendered_cloud_init_yaml)\n\n def _do_deploy(self, component, existing_versions, workdir, dry_run):\n rendered_cloud_init_yaml = self._render_config_template(\n component=component,\n template_path=self.build_cloud_init_path(component))\n\n self._validate_cloud_init_yaml(component, rendered_cloud_init_yaml)\n\n # We are gradually moving all of this away from making subprocess\n # calls to gcloud, in favor of direct API calls. So, create an\n # authorized requests session.\n session = (\n Authorizer.read_only() if dry_run else Authorizer.read_write()\n ).get_access_session()\n\n self._deploy_with_rendered_cloud_init_yaml(\n component = component,\n rendered_cloud_init_yaml = rendered_cloud_init_yaml,\n dry_run = dry_run,\n workdir = workdir,\n session = session)\n\n # If we've made it here, then the instance group was created\n # and/or updated successfully, and now we have to apply the autoscaler\n # settings, in case they have changed.\n\n AutoscalingManager(self.project_id, session).update_autoscaler(component, dry_run)\n","repo_name":"chumomega/recursive-fun","sub_path":"venv/lib/python3.8/site-packages/stallion/deploy/gce/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":25175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"4848683164","text":"# -*- coding: utf-8 -*-\n\nimport megabox\n\ndata = megabox.getBookingMovieListIDByDate(\"20200219\")\n\nusers_tag = [\n\t{\n\t'user' : 'Alex',\n\t'tags' : [\n\t\t'러브라이브 선샤인',\n\t\t'First LOVELIVE',\n\t]},\n\t{\n\t'user' : 'Kim',\n\t'tags' : [\n\t\t'First LOVELIVE',\n\t\t'러브라이브 선샤인',\n\t]},\n]\n\n#print(megabox.addMovieDate(data, users_tag))\n#print(megabox.getCinemas(\"20200223\",\"20004000\"))\nprint(megabox.getSeatCount(\"20200223\",\"20004000\",\"1003\"))\n\n'''\n\nparam\n\nuser_tag = {\n\t'user' : 'xxxx',\n\t'tags' : [\n\t\t'yyyyx',\n\t\t'yyyyy',\n\t\t...\n\t]\n}\n\nreturn_value\n\nuser_value = [\n\t{\n\t\t'user' : 'xxxxxx',\n\t\t'search_result' : [\n\t\t\t{'movieNo': '20004000', 'movieNm': 'yyyyy'}\n\t\t]\n\t},\n\t{\n\t\t'user' : 'xxxxxy',\n\t\t'search_result' : [\n\t\t\t{'movieNo': '20004000', 'movieNm': 'yyyyy'}\n\t\t]\n\t},\n\t...\n]\n\n'''","repo_name":"tlqaksqhr/MegaboxNotifier","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38155168504","text":"from django.contrib import admin\nfrom django.urls import path\nfrom tasks.views import (view_add_task, view_all_completed_task, view_all_task,\n view_completed_task, view_delete_task, view_task)\n\nurlpatterns = [\n path(\"admin/\", admin.site.urls),\n path(\"complete_task//\", view_completed_task),\n path(\"completed_tasks/\", view_all_completed_task),\n path(\"all_tasks/\", view_all_task),\n path(\"tasks/\",view_task),\n path(\"add-task/\",view_add_task),\n path(\"delete-task//\",view_delete_task),\n]\n","repo_name":"kunatastic/yeah-django","sub_path":"level5/task_manager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"14583228351","text":"# Q2 \n# imports\nimport json\nimport math\n\nclass Graph:\n '''\n Graphs Object Class\n @param self.graph_dict: dict\n @param self.directed: bool\n '''\n def __init__(self, graph_dict=None, directed=True):\n self.graph_dict = graph_dict or {}\n self.directed = directed\n if not directed:\n self.make_undirected()\n\n def make_undirected(self):\n '''\n Create an undirected graph\n @param self: Graph\n '''\n for a in list(self.graph_dict.keys()):\n for (b, dist) in self.graph_dict[a].items():\n self.graph_dict.setdefault(b, {})[a] = dist\n \n def connect(self, A, B, distance=1):\n '''\n Given the distance, connect the nodes A and B\n If undirected, add the inverse link between A and B\n @param self: Graph\n '''\n self.graph_dict.setdefault(A, {})[B] = distance\n if not self.directed:\n self.graph_dict.setdefault(B, {})[A] = distance\n \n def get(self, a, b=None):\n '''\n Gets neighbours of the node\n @param self: Graph\n '''\n links = self.graph_dict.setdefault(a, {})\n if b is None:\n return links\n else:\n return links.get(b)\n\n def nodes(self):\n '''\n Return a list of nodes in the graph\n @param self: Graph\n '''\n s1 = set([k for k in self.graph_dict.keys()])\n s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])\n nodes = s1.union(s2)\n return list(nodes)\n \n\nclass Node:\n '''\n A node class for the station\n @param self.name: str\n @param self.parent: str\n ''' \n \n def __init__(self, name:str, parent:str):\n self.name = name\n self.parent = parent\n self.g = 0 # Distance to the start node (point)\n self.h = 0 # Distance to the end node (point)\n self.f = 0 # Total cost\n \n def __eq__(self, other):\n '''\n Compare nodes\n @param self: Node\n '''\n return self.name == other.name\n\n def __lt__(self, other):\n '''\n Sort nodes\n @param self: Node\n '''\n return self.f < other.f\n\n def __repr__(self):\n '''\n Print nodes\n @param self: Node\n '''\n return ('({0},{1})'.format(self.name, self.f))\n\ndef read_file(filename):\n '''\n Reads .json file and returns contents\n @param myParam1: str\n @return: dict\n '''\n with open(filename, \"r\") as myfile:\n content = json.load(myfile)\n return content \n \ndef makegraph(filename):\n '''\n Creates graph structure and defines nodes from .json file\n @param myParam1: str\n @return: Graph\n '''\n content = read_file(filename)\n graph = Graph()\n node_dict = {}\n [val_list] = content.values()\n for i in range(0, len(val_list)):\n node_dict[val_list[i][\"Name\"]] = val_list[i][\"Neighbours\"]\n\n for each_node in node_dict:\n for each_neighbour in node_dict[each_node]:\n graph.connect(each_node, each_neighbour[\"Name\"], each_neighbour[\"Distance\"])\n \n graph.make_undirected()\n \n return graph\n\n# A* search\ndef astar_search(graph, heuristics, start, end):\n '''\n Returns the shortest path and its distance from the startpoint to the endpoint\n '''\n open = [] # open nodes list\n closed = [] # closed nodes list\n\n start_node = Node(start, None) # start node (startpoint)\n goal_node = Node(end, None) # end node (endpoint)\n\n open.append(start_node) # append the start node\n \n # Loop until there are no other nodes in the open list\n while len(open) > 0:\n\n open.sort() # sort to determine the closest node\n \n current_node = open.pop(0) # node with the shortest distance\n \n closed.append(current_node) # append to the closed list\n \n # if reached the end node, return the path\n if current_node == goal_node:\n path = []\n while current_node != start_node:\n path.append(current_node.name + ': ' + str(current_node.g))\n current_node = current_node.parent\n path.append(start_node.name + ': ' + str(start_node.g))\n\n return path[::-1] # reversed path\n \n # Get neighbours\n neighbors = graph.get(current_node.name)\n\n # Looping neighbors\n for key, value in neighbors.items():\n \n neighbor = Node(key, current_node) # Create a neighbor node\n \n # if the neighbor is in the closed list, just continue\n if(neighbor in closed): \n continue\n\n # Calculate the full distance\n neighbor.g = current_node.g + graph.get(current_node.name, neighbor.name)\n neighbor.h = heuristics.get(neighbor.name)\n neighbor.f = neighbor.g + neighbor.h\n \n # Check if neighbor is in the open list and has a lower total cost\n if(add_to_open(open, neighbor) == True):\n open.append(neighbor)\n \n return None # no path found\n\n# Check if a neighbor should be added to the open list\ndef add_to_open(open, neighbor):\n for node in open:\n if (neighbor == node and neighbor.f > node.f):\n return False\n return True\n\ndef cartesian_distance(x_1,y_1,x_2,y_2):\n return math.sqrt((x_2 - x_1)**2 + (y_2 - y_1)**2)\n\ndef calc_heuristic(filename, startpoint, endpoint):\n \n coordinates = {}\n data = read_file(filename)[\"Nodes\"]\n for i in data:\n coordinates.update({i[\"Name\"]:i[\"Coordinates\"]})\n \n heuristics = {}\n for key, value in coordinates.items():\n approx = cartesian_distance(value[0],value[1],coordinates[endpoint][0],coordinates[endpoint][1])\n heuristics.update({key:approx})\n \n return heuristics\n\ndef conditions(filename1, filename2):\n graph = makegraph(filename2) #making the graph\n ofile = open(\"2.out\",\"w\") #output file\n\n myfile = open(filename1, \"r\")\n lines = myfile.readlines()\n lst = [line.rstrip(\"\\n\") for line in lines]\n output = [element.split(',') for element in lst]\n for i in output:\n estimate = calc_heuristic(filename2, i[0], i[1])\n path = astar_search(graph, estimate, i[0], i[1]) #gives in form ['location:distance', etc...]\n stops = [location.split(': ') for location in path]\n #splits into [['location','distance'],etc...]\n for j in stops:\n ofile.write(j[0]+\", \") #writes all the locations\n ofile.write(stops[-1][1]+\"\\n\") #writes the total distance\n\n \n# Driver Code\nif __name__ == \"__main__\":\n conditions(\"2.in\", \"2.json\")\n","repo_name":"donmin062501/UTEK2021","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":6601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"29368022401","text":"\"\"\"\nNew.secondary utils\nData_Analysis.Visualisation is added.\n\"\"\"\n\nimport random\nimport argparse\nimport numpy as np\nimport glob\nimport utils.utils1 as utils\nimport os\nimport pandas as pd\nimport utils.data_utils2 as datatools\nfrom colorama import Fore, Back, Style\nimport argparse\nfrom utils.data_utils2 import use_root_dir\n\n\n# import open3d as o3d\n\n\ndef load_single_point_cloud(healthy_status, stage_spec, phase_spec, ventricle_spec, case_id=12345,\n reduce_size=3, is_random=False):\n \"\"\"\n This function returns a loaded 3D point cloud based on the case id provided.\n Or it randomly chooses a point cloud.\n :return:\n \"\"\"\n dir_wanted = utils.get_ventricle_dir(healthy_status, stage_spec, phase_spec, ventricle_spec)\n file_list = glob.glob(dir_wanted + '/*.npy')\n n = random.randint(0, len(file_list))\n if is_random:\n for i, file_name in enumerate(file_list):\n if i == n:\n id_here = read_id(file_name)\n print('Case id: ', id_here)\n return utils.reduce_pc_size(np.load(file_name), reduce_size)\n for file_name in file_list:\n id_here = read_id(file_name)\n if id_here == case_id:\n return utils.reduce_pc_size(np.load(file_name), reduce_size)\n\n\ndef readXYZ(filename, delimiter=','):\n xs = []\n ys = []\n zs = []\n f = open(filename, 'r')\n line = f.readline()\n N = 0\n while line:\n x, y, z = line.split(delimiter)[0:3]\n x, y, z = float(x), float(y), float(z)\n xs.append(x)\n ys.append(y)\n zs.append(z)\n line = f.readline()\n N += 1\n f.close()\n xs = np.array(xs).reshape(N, 1)\n ys = np.array(ys).reshape(N, 1)\n zs = np.array(zs).reshape(N, 1)\n points = np.concatenate((xs, ys, zs), axis=1)\n return points\n\n\n# def visualize_PC(point_cloud):\n# \"\"\"\n# This function visualize the input point cloud.\n# :param point_cloud: shape in the form of tensors.\n# :return:\n# \"\"\"\n# sample_heart = point_cloud.permute(1, 0)\n# sample_heart = utils.to_numpy(sample_heart)\n# pcd = o3d.geometry.PointCloud()\n# pcd.points = o3d.utility.Vector3dVector(sample_heart)\n# o3d.visualization.draw_geometries([pcd])\n\n\n# def visualize_ds(ds):\n# sample = ds[0]\n# sample_PC = sample[0]\n# visualize_PC(sample_PC)\n\n\ndef get_people_with_disease(n_disease, disease_metadata, include=True):\n \"\"\"\n This function returns cases with a certain number of diseases.\n n_disease: number of diseases\n disease_metadata: pandas dataframe of disease metadata file\n \"\"\"\n out_list = [] # List with all the cases\n index_list = [] # List with all indices of the cases\n for i, row in disease_metadata.iterrows():\n case_id = row[0]\n list_for_count = pd.isna(row)\n disease_count = -1\n for is_na in list_for_count:\n if not is_na:\n disease_count += 1\n else:\n break\n if include:\n if disease_count <= n_disease:\n out_list.append(str(int(case_id)))\n index_list.append(i)\n else:\n if disease_count == n_disease:\n out_list.append(str(int(case_id)))\n index_list.append(i)\n\n return out_list\n\n\ndef count_0_and_1(labels):\n count0 = 0\n count1 = 0\n for label in labels:\n if int(label) == 1:\n count1 += 1\n elif int(label) == 0:\n count0 += 1\n else:\n print('Error: label not equal to 0 or 1')\n return count0, count1\n\n\ndef count_0_and_1_print(labels):\n count0 = 0\n count1 = 0\n for label in labels:\n if int(label) == 1:\n count1 += 1\n elif int(label) == 0:\n count0 += 1\n else:\n print('Error: label not equal to 0 or 1')\n print('Number in class 0: ', count0)\n print('Number in class 1: ', count1)\n return count0, count1\n\n\ndef pick_one_gender(matrix, labels, ids, args):\n df_disease = datatools.read_metadata_disease2(args.disease_csv, 'eid', gender=args.gender_spec)\n df_healthy = datatools.read_metadata_disease2(args.data_csv, 'case-id', gender=args.gender_spec)\n wanted_list = []\n for i, label in enumerate(labels):\n if label == 0:\n df = df_healthy\n else:\n df = df_disease\n gender_id_list = df['case-id'].values\n if ids[i] in gender_id_list:\n wanted_list.append(i)\n return matrix[wanted_list], labels[wanted_list], ids[wanted_list]\n\n\ndef pick_one_gender_balance(matrix, labels, ids, args):\n \"\"\"\n This function takes in the data matrix and labels. It picks out cases of one specified gender from both the healthy\n and diseased cases. It forced class balance between healthy and diseased cases by picking the smaller number.\n For example, if we have 80 healthy male cases and 70 diseased male cases, the function returns 70 male healthy and\n diseased cases respectively.\n \"\"\"\n\n # Pick out cases with a single specified gender\n df_disease = datatools.read_metadata_disease2(args.disease_csv, 'eid', gender=args.gender_spec)\n df_healthy = datatools.read_metadata_disease2(args.data_csv, 'case-id', gender=args.gender_spec)\n wanted_list = []\n for i, label in enumerate(labels):\n # Pick the right metadata for healthy or diseased cases\n if label == 0:\n df = df_healthy\n else:\n df = df_disease\n gender_id_list = df['case-id'].values\n if ids[i] in gender_id_list:\n wanted_list.append(i)\n count0, count1 = count_0_and_1(labels[wanted_list])\n if count0 > count1:\n del wanted_list[count1:count0]\n elif count1 > count0:\n del wanted_list[2 * count0:(count1 + count0)]\n return matrix[wanted_list], labels[wanted_list], ids[wanted_list]\n\n\ndef read_condition(df, case_id):\n \"\"\"\n This function reads the conditionals from the metadata df based on the case id provided.\n :param df:\n :param case_id:\n :return:\n \"\"\"\n gender_list = df['sex'].values\n temp = df.index[df['case-id'] == case_id].tolist()\n index = temp[0]\n gender = gender_list[index]\n return gender\n\n\ndef concatenate_condition(x, condition):\n \"\"\"\n This function add one more dimension to the point cloud x to make it contain the conditional information.\n For example, if x is 1000x3, new x will be 1000x4 with all elements in the 4th dimension being the condition.\n This function by default assume x has a shape of 3 x number of points and condition is assumed to be an integer.\n :param x:\n :param condition:\n :return:\n \"\"\"\n dim = x.shape\n new_x = np.zeros((4, dim[1]))\n new_x[0:3, :] = x\n new_x[3, :] = condition\n return new_x\n\n\ndef get_data_and_labels(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels1(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels2(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels3(args):\n matrix0, matrix1, id_list0, id_list1 = get_vectors3(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels4(args):\n \"\"\"\n This function reads the data from healthy and diseased directories directly.\n No reading from metadata file is required.\n Positive and negative cases are of different quantity.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels401(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It forces class balance by removing the excessive healthy data.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n matrix0 = np.array(remove_excessive(matrix1, matrix0))\n id_list0 = np.array(remove_excessive(id_list1, id_list0))\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels41(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It uses concatenated data.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels42(args):\n \"\"\"\n Extension of get_data_and_labels4.\n It uses concatenated data.\n It removes excessive cases from the major class to ensure class balance.\n Class 1 is assumed to be the minor class.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n matrix0 = np.array(remove_excessive(matrix1, matrix0))\n id_list0 = np.array(remove_excessive(id_list1, id_list0))\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n return total_data, total_label, total_id\n\n\ndef get_data_and_labels411(args):\n \"\"\"\n Extension of get_data_and_labels41.\n It moves the extra class 0 data to the end of the overall data matrix.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same21(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n n_extra = int(matrix0.shape[0] - matrix1.shape[0])\n return move_to_the_end(total_data, n_extra), move_to_the_end(total_label, n_extra), move_to_the_end(total_id,\n n_extra)\n\n\ndef get_data_and_labels412(args):\n \"\"\"\n Extension of get_data_and_labels411. It does not use concatenated data.\n It moves the extra class 0 data to the end of the overall data matrix.\n \"\"\"\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n n_extra = int(matrix0.shape[0] - matrix1.shape[0])\n return move_to_the_end(total_data, n_extra), move_to_the_end(total_label, n_extra), move_to_the_end(total_id,\n n_extra)\n\n\ndef move_to_the_end(data_matrix, n_extra):\n \"\"\"\n This function moves the extra class 0 data to the end of the entire data matrix.\n So that the training set could be made balanced.\n :param data_matrix:\n :param n_extra:\n :return:\n \"\"\"\n n_total = data_matrix.shape[0]\n n0 = int((n_total + n_extra) / 2)\n n1 = int((n_total - n_extra) / 2)\n matrix0 = data_matrix[:n1]\n matrix1 = data_matrix[n0:]\n matrix_extra = data_matrix[n1:n0]\n return np.concatenate((matrix0, matrix1, matrix_extra))\n\n\ndef remove_excessive(data_small, data_large):\n \"\"\"\n This function removes the excessive data from 'data_large' so that it contains the same number\n of data as 'data_small'\n :param data_small: first dimension has to be the number of data\n :param data_large: the larger dataset to be removed\n :return:\n \"\"\"\n data_large_new = index_list_list(data_large, list(range(data_small.shape[0])))\n return data_large_new\n\n\ndef duplicate_minor_class(matrix0, matrix1, id_list0, id_list1):\n \"\"\"\n This forces matrix0 and matrix1 to have the same number of cases.\n The id lists are modified accordingly.\n :param matrix0:\n :param matrix1:\n :param id_list0:\n :param id_list1:\n :return:\n \"\"\"\n num0 = matrix0.shape[0]\n num1 = matrix1.shape[0]\n num_extra = np.abs(num0 - num1)\n if num0 > num1:\n matrix1, id_list1 = make_large_small_equal(matrix1, id_list1, num_extra)\n elif num0 < num1:\n matrix0, id_list0 = make_large_small_equal(matrix0, id_list0, num_extra)\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef make_large_small_equal(matrix_s, id_list_s, num_extra):\n num_s = matrix_s.shape[0]\n if num_extra <= num_s:\n list_extra = generate_list(0, num_s, num_extra, repeat=False)\n else:\n list_extra = generate_list(0, num_s, num_extra, repeat=True)\n matrix_extra = index_list_list(matrix_s, list_extra)\n id_extra = index_list_list(id_list_s, list_extra)\n matrix_s = np.concatenate((matrix_s, matrix_extra), axis=0)\n id_list_s = np.concatenate((id_list_s, id_extra), axis=0)\n return matrix_s, id_list_s\n\n\ndef generate_list(start, end, num, repeat=True):\n temp_list = range(start, end)\n if repeat:\n return random.choices(temp_list, k=num)\n else:\n return random.sample(temp_list, num)\n\n\ndef get_data_and_labels5(args):\n \"\"\"\n This function is an extended version of get_data_and_labels4().\n But it removes cases whose information is not available in the metadata file.\n \"\"\"\n df = datatools.read_metadata_disease(args.csv_file, 'eid')\n matrix0, matrix1, id_list0, id_list1 = get_vectors_not_same2(args)\n total_id = np.concatenate((id_list0, id_list1), axis=0)\n total_id, final_list = check_missing_meta(df, total_id)\n label0, label1 = label_data(matrix0, matrix1)\n total_data = np.concatenate((matrix0, matrix1), axis=0)\n total_label = np.concatenate((label0, label1), axis=0)\n total_data = index_list_list(total_data, final_list)\n total_label = index_list_list(total_label, final_list)\n return total_data, total_label, total_id\n\n\ndef index_list_list(list_in, index_list):\n \"\"\"\n This function allows one to index a list using a list.\n For example, if we want to pick the 1st, 3rd, 4th element of a list a.\n We use a as list_in and [1, 3, 4] as the index_list.\n :param list_in: List to be indexed\n :param index_list: List of indices\n :return: List made of elements of interests\n \"\"\"\n list_out = [list_in[i] for i in index_list]\n return list_out\n\n\ndef check_missing_meta(df, id_list):\n \"\"\"\n This function reads the metadata file and returns a list of ids whose information is available in the metadata.\n :param df: data frame of the metadata\n :param id_list: list of all ids of the point clouds available.\n :return: an id list that only contain cases appeared in the metadata file.\n \"\"\"\n wanted_list = []\n for i, case_id in enumerate(id_list):\n try:\n temp = read_condition(df, int(id_list[i]))\n wanted_list.append(i)\n except IndexError:\n pass\n id_out = [id_list[i] for i in wanted_list]\n return id_out, wanted_list\n\n\ndef get_vectors(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC2(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n dim1 = matrix1.shape\n n_positive = dim1[0]\n n_negative = n_positive * 1 # Tune ratio between positive and negative cases\n matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same(args):\n \"\"\"\n This function reads and stores the point clouds of diseased and healthy cases in the given directories.\n 0 stands for healthy and 1 stands for diseased.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix0, id_list0 = readPC2(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size)\n\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same2(args):\n \"\"\"\n This function reads and stores the point clouds of diseased and healthy cases in the given directories.\n 0 stands for healthy and 1 stands for diseased.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix0, id_list0 = readPC(data_dir, reduce_size)\n matrix1, id_list1 = readPC(disease_dir, reduce_size + 1)\n print(Fore.GREEN + 'Single phase data(ES/ED) are read correctly' + Style.RESET_ALL)\n # i_list = shuffle_matrix(matrix0)\n # matrix0 = matrix0[i_list]\n # id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors_not_same21(args):\n \"\"\"\n Extension of get_vectors_not_same2.\n It reads the point clouds of ED and ES respectively and concatenates them to make the overall point clouds.\n \"\"\"\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n reduce_size = args.reduce_size\n disease_es_dir, disease_ed_dir = get_es_ed_path(args.disease_dir)\n healthy_es_dir, healthy_ed_dir = get_es_ed_path(args.data_dir)\n\n # This step chooses cases with 0 disease on record and avoid mismatch between the data in the directory and the\n # metadata.\n matrix00, id_list0 = readPC(healthy_es_dir, reduce_size)\n matrix01, id_list0 = readPC(healthy_ed_dir, reduce_size)\n matrix10, id_list1 = readPC(disease_es_dir, reduce_size + 1)\n matrix11, id_list1 = readPC(disease_ed_dir, reduce_size + 1)\n matrix0 = np.concatenate((matrix00, matrix01), axis=2)\n matrix1 = np.concatenate((matrix10, matrix11), axis=2)\n print_concatenation_info(matrix00, matrix0)\n print(Fore.GREEN + 'ES and ED point clouds have been successfully concatenated' + Style.RESET_ALL)\n # Below shuffles the healthy data.\n # i_list = shuffle_matrix(matrix0)\n # matrix0 = matrix0[i_list]\n # id_list0 = id_list0[i_list]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef print_concatenation_info(m_before, m_after):\n shape_b = m_before.shape\n shape_a = m_after.shape\n print(Fore.GREEN + 'Number of points before concatenation: {}'.format(shape_b[2]) + Style.RESET_ALL)\n print(Fore.GREEN + 'Number of points after concatenation: {}'.format(shape_a[2]) + Style.RESET_ALL)\n\n\ndef get_vectors2(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC22(data_dir, reduce_size)\n matrix1, id_list1 = readPC12(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n # dim1 = matrix1.shape\n # n_positive = dim1[0]\n # n_negative = n_positive*1 # Tune ratio between positive and negative cases\n # matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n # id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef get_vectors3(args):\n # If names of the npy files change, indexing of id needs to be changed.\n # Currently the function only works with a format like: latent_space_1002549.npy\n data_dir = args.data_dir\n disease_dir = args.disease_dir\n reduce_size = args.reduce_size\n\n matrix0, id_list0 = readPC22(data_dir, reduce_size)\n matrix1, id_list1 = readPC12(disease_dir, reduce_size)\n\n # Shuffle the data of healthy cases and then take the same number as the diseased cases\n i_list = shuffle_matrix(matrix0)\n matrix0 = matrix0[i_list]\n id_list0 = id_list0[i_list]\n dim1 = matrix1.shape\n n_positive = dim1[0]\n n_negative = n_positive * 1 # Tune ratio between positive and negative cases\n matrix0 = matrix0[0:n_negative] # To make diseased cases and healthy cases balance\n id_list0 = id_list0[0:n_negative]\n return matrix0, matrix1, id_list0, id_list1\n\n\ndef label_data(matrix0, matrix1):\n shape0 = matrix0.shape\n shape1 = matrix1.shape\n label0 = np.zeros((shape0[0], 1))\n label1 = np.ones((shape1[0], 1))\n return label0, label1\n\n\ndef readPC(file_dir, reduce_size):\n \"\"\"This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds\"\"\"\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(filelist)\n Case_id = np.zeros((nfiles, 1))\n print('Reading point clouds from directories...')\n for fname in filelist:\n case_id = read_id(fname)\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data[:, 0:3]\n data_in = utils.reduce_pc_size(data_in, reduce_size)\n data_in = np.transpose(data_in)\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n\n return matrix_out, Case_id\n\n\ndef read_id(file_name):\n \"\"\"\n This function extracts the case id in a file name.\n :param file_name: name of the file in string\n :return: case id of the file in string\n \"\"\"\n case_id = ''\n temp = os.path.normpath(file_name)\n last = os.path.basename(temp)\n for elem in last:\n if elem.isdigit():\n case_id += elem\n return int(case_id)\n\n\ndef readPC12(file_dir, reduce_size):\n \"\"\"This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds\"\"\"\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(filelist)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = int(fname[-11:-4])\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n\n return matrix_out, Case_id\n\n\ndef readPC2(file_dir, reduce_size):\n \"\"\"\n This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds.\n It only reads cases with no disease at all, based on the metadata 'No_MF.csv'\n \"\"\"\n csv_dir = PathString('data/csv/No_MF.csv')\n df_no_MF = pd.read_csv(csv_dir.ab)\n # case_list1 = get_people_with_disease(1, df_no_MF, include=False)\n # case_list2 = get_people_with_disease(2, df_no_MF, include=False)\n # case_list = case_list1 + case_list2\n case_list = get_people_with_disease(0, df_no_MF)\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(case_list)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = fname[-11:-4]\n if case_id in case_list:\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data[:, 0:3]\n data_in = utils.reduce_pc_size(data_in, reduce_size)\n data_in = np.transpose(data_in)\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n return matrix_out, Case_id\n\n\ndef readPC22(file_dir, reduce_size):\n \"\"\"\n This function takes in a file list and reads off all files in the list. It returns\n a matrix containing all the point clouds.\n It only reads cases with no disease at all, based on the metadata 'No_MF.csv'\n \"\"\"\n csv_dir = PathString('data/csv/No_MF.csv')\n df_no_MF = pd.read_csv(csv_dir.ab)\n case_list = get_people_with_disease(0, df_no_MF)\n filelist = glob.glob(file_dir + '/*.npy')\n file_count = 0\n nfiles = len(case_list)\n Case_id = np.zeros((nfiles, 1))\n for fname in filelist:\n case_id = fname[-11:-4]\n if case_id in case_list:\n Case_id[file_count] = int(case_id)\n lat_data = np.load(fname)\n data_in = lat_data\n if file_count == 0:\n PC_dim = data_in.shape\n n_points = PC_dim[1]\n matrix_out = np.zeros((nfiles, 3, n_points))\n matrix_out[file_count] = data_in\n file_count += 1\n\n if file_count < nfiles:\n # This step is to get rid of the effect of cases that appear in metadata but not in the point cloud directory.\n matrix_out = matrix_out[:file_count]\n Case_id = Case_id[:file_count]\n return matrix_out, Case_id\n\n\ndef count_nfiles(file_dir):\n initial_count = 0\n for path in os.listdir(file_dir):\n if os.path.isfile(os.path.join(file_dir, path)):\n initial_count += 1\n return initial_count\n\n\ndef shuffle_matrix(data_in):\n \"\"\"\n This function shuffles any arrays along its first dimension. It returns the shuffled index list so that\n any other arrays could be shuffled exactly the same.\n :param data_in:\n :return:\n \"\"\"\n dim = data_in.shape\n i_list = list(range(dim[0]))\n random.shuffle(i_list)\n return i_list\n\n\ndef shuffle_list(data_in):\n \"\"\"\n This function shuffles any arrays along its first dimension. It returns the shuffled index list so that\n any other arrays could be shuffled exactly the same.\n :param data_in:\n :return:\n \"\"\"\n dim = len(data_in)\n i_list = list(range(dim))\n random.shuffle(i_list)\n return i_list\n\n\ndef add_list(a, b):\n \"\"\"\n Add two lists a and b element-wise\n a and b should have the same number of elements\n :param a:\n :param b:\n :return:\n \"\"\"\n c = [x + y for x, y in zip(a, b)]\n\n if len(a) == 0:\n c = b\n elif len(b) == 0:\n c = a\n return c\n\n\ndef divide_list(A, a):\n \"\"\"\n Divide each element in A by a\n :param A:\n :param a:\n :return:\n \"\"\"\n c = [x / a for x in A]\n return c\n\n\nclass PathString(str):\n def __init__(self, path):\n self.value = path\n self.ab = use_root_dir(path)\n\n\ndef get_es_ed_path(data_dir):\n ES_path = data_dir + '/ES'\n ED_path = data_dir + '/ED'\n return ES_path, ED_path\n\n\nif __name__ == '__main__':\n a = np.array([0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1])\n print(move_to_the_end(a, 3))\n # print(a[:3])\n","repo_name":"RiceKooker/3D_heart_model_MI_prediction","sub_path":"utils/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":29792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72056056485","text":"import json\nimport sys\nfrom traceback import format_exc\nfrom typing import Final, Optional\n\nimport openai\nfrom openai import ChatCompletion\nfrom openai.error import InvalidRequestError\n\nfrom function import CreateBooleanFeatureInput, create_evidently_boolean_feature\n\nCHAT_MODEL_GPT35T_0613: Final[str] = \"gpt-3.5-turbo-0613\"\n\n\ndef run_chat(client: ChatCompletion, query: str) -> Optional[str]:\n \"\"\"Run chat with GPT-3-turbo-0613 model to create Evidently Feature.\n\n Args:\n client (ChatCompletion): OpenAI ChatCompletion client.\n query (str): User query.\n\n Returns:\n Optional[str]: Response of create Evidently Feature.\n \"\"\"\n\n try:\n response = client.create(\n model=CHAT_MODEL_GPT35T_0613,\n messages=[{\"role\": \"user\", \"content\": query}],\n functions=[\n {\n \"name\": \"create_evidently_boolean_feature\",\n \"description\": \"Create a new boolean feature in evidently\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"project_name\": {\n \"type\": \"string\",\n \"description\": \"Project name of CloudWatch Evidently.\",\n },\n \"feature_name\": {\n \"type\": \"string\",\n \"description\": \"Feature name of CloudWatch Evidently.\",\n },\n \"default_value\": {\n \"type\": \"boolean\",\n \"description\": \"Default value of CloudWatch Evidently.\",\n \"default\": False,\n },\n \"override_rules\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n },\n },\n \"description\": \"\"\"Override rules of CloudWatch Evidently.\n This value is list of tuple that has two elements.\n First element is the name of entity,\n second element is the variation 'True' or 'False'.\"\"\",\n \"default\": [],\n },\n },\n \"required\": [\n \"project_name\",\n \"feature_name\",\n \"default_value\",\n \"override_rules\",\n ],\n },\n }\n ],\n function_call=\"auto\",\n )\n except InvalidRequestError as ire:\n print(ire.__repr__())\n return None\n except: # pylint: disable=W0702\n print(format_exc())\n return None\n\n params: CreateBooleanFeatureInput = __generate_calling_function_input(\n response.choices[0][\"message\"]\n )\n if params is None:\n print(\"Failed to create parameters for calling function.\")\n return None\n\n __debug(\"params\", params)\n\n create_res = create_evidently_boolean_feature(params)\n if not create_res:\n print(\"Failed to create a feature.\")\n return None\n\n return f\"\"\"created a feature info\n\n Project: {params.project_name}\n Feature: {params.feature_name}\n\n Check the feature on CloudWatch Evidently using following command:\n\n aws evidently get-feature --project '{params.project_name}' --feature '{params.feature_name}'\n \"\"\"\n\n\ndef __generate_calling_function_input(\n openai_message: dict,\n) -> Optional[CreateBooleanFeatureInput]:\n __debug(\"openai_message\", openai_message)\n\n if openai_message.get(\"function_call\") is None:\n print(\"No function call.\")\n return None\n\n print(f\"function_call: {openai_message['function_call']['name']}\")\n\n args_for_function = json.loads(openai_message[\"function_call\"][\"arguments\"])\n\n override_rules = None\n if args_for_function.get(\"override_rules\"):\n override_rules = [\n tuple(rule) for rule in args_for_function.get(\"override_rules\")\n ]\n\n params = CreateBooleanFeatureInput(\n project_name=str(args_for_function.get(\"project_name\")),\n feature_name=str(args_for_function.get(\"feature_name\")),\n default_value=str(bool(args_for_function.get(\"default_value\"))),\n override_rules=override_rules,\n )\n\n return params\n\n\ndef __debug(name: str, value: any):\n print(f\"-------{name}-------\")\n print(value)\n print(\"--------------------\")\n\n\nif __name__ == \"__main__\":\n message: str = \"\"\n while len(message) == 0:\n message = input(\"What do you want to create a feature? > \")\n\n if len(message) == 0:\n continue\n\n response_message = run_chat(\n client=openai.ChatCompletion,\n query=message,\n )\n\n if response_message is None:\n print(\"Failed to create a feature.\")\n sys.exit(1)\n\n print(\"\\n-------Response-------\")\n print(response_message)\n sys.exit(0)\n","repo_name":"michimani/misc","sub_path":"llm/openai/get-started-to-use-function-calling/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9638575174","text":"\r\n\r\n# please be kind.......\r\n\r\n\r\nimport numpy as np\r\n\r\nfrom OpenGL.GL import *\r\n\r\nfrom OpenGL_2D_class import gl2DCircle\r\n\r\nfrom copy import deepcopy\r\n\r\nfrom math import *\r\n\r\nfrom scipy.optimize import fsolve\r\n\r\n\r\nclass style:\r\n def __init__(self):\r\n self.name = None\r\n self.rgb = None\r\n self.width = None\r\n\r\n\r\nclass Fourbar:\r\n def __init__(self, ):\r\n self.linestyle = []\r\n self.connections = []\r\n self.payload = []\r\n self.payloadx = []\r\n self.payloady = []\r\n self.positions = []\r\n self.boundary = []\r\n self.window = [] # an empty list of nodes\r\n\r\n self.p0 = None\r\n self.p1 = None\r\n self.p2 = None\r\n\r\n self.a0 = None\r\n self.b0 = None\r\n\r\n self.ha = None\r\n self.ka = None\r\n\r\n self.a0x = None\r\n self.a0y = None\r\n self.b0x = None\r\n self.b0y = None\r\n\r\n self.a1x = None\r\n self.a1y = None\r\n self.b1x = None\r\n self.b1y = None\r\n\r\n self.a2x = None\r\n self.a2y = None\r\n self.b2x = None\r\n self.b2y = None\r\n\r\n self.newx = None\r\n self.newy = None\r\n\r\n self.thetaInitial1 = None\r\n self.thetaEnding1 = None\r\n\r\n self.thetaInitial2 = None\r\n self.thetaEnding2 = None\r\n\r\n self.theta1 = None\r\n self.theta2 = None\r\n self.theta3 = None\r\n self.theta4 = None\r\n\r\n self.l1 = None\r\n self.l2 = None\r\n self.l3 = None\r\n self.l4 = None\r\n\r\n self.dtheta1 = None\r\n self.dtheta2 = None\r\n\r\n self.apath = []\r\n self.bpath = []\r\n\r\n # # data for animation\r\n # self.nframes = 121\r\n # # self.dronepath = np.zeros([self.nframes, 2])\r\n # self.b0 = np.zeros([self.nframes, 2])\r\n # self.a0 = np.zeros([self.nframes, 2])\r\n # # self.theta2 +=self.dtheta1\r\n # # self.CalculateFlightPaths()\r\n\r\n\r\n # Don't change anything in ReadTrussData\r\n def ReadFourBarData(self, data): # reads data from text file\r\n # data is an array of strings, read from a Truss data file\r\n for line in data: # loop over all the lines\r\n cells = line.strip().split(',')\r\n keyword = cells[0].lower()\r\n\r\n if keyword == 'title': self.title = cells[1].replace(\"'\", \"\")\r\n if keyword == 'connections':\r\n for con in cells[1:]:\r\n ans = float(con.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.connections.append(ans)\r\n\r\n if keyword == 'linestyle':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n ncells = len(cells)\r\n for cell in cells[2:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.linestyle.append(this_name)\r\n\r\n if keyword == 'payload':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n this_name.append(cells[2].replace(\" \", \"\"))\r\n ncells = len(cells)\r\n for cell in cells[3:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.payload.append(this_name)\r\n\r\n if keyword == 'positions':\r\n for pos in cells[1:]:\r\n ans = float(pos.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.positions.append(ans)\r\n\r\n if keyword == 'boundary':\r\n this_name = [cells[1].replace(\"'\", \"\").replace(\" \", \"\")]\r\n this_name.append(cells[2].replace(\" \", \"\"))\r\n ncells = len(cells)\r\n for cell in cells[3:]:\r\n value = float(cell.replace(\"(\", \"\").replace(\")\", \"\"))\r\n this_name.append(value)\r\n self.boundary.append(this_name)\r\n\r\n if keyword == 'window':\r\n for win in cells[1:]:\r\n ans = float(win.replace(\"(\", \"\").replace(\")\", \"\"))\r\n self.window.append(ans)\r\n\r\n self.a0x = self.connections[0]\r\n self.a0y = self.connections[1]\r\n self.b0x = self.connections[2]\r\n self.b0y = self.connections[3]\r\n self.a0 = np.array([self.a0x, self.a0y])\r\n self.b0 = np.array([self.b0x, self.b0y])\r\n\r\n def Translation(self):\r\n p0x = self.positions[0]\r\n p0y = self.positions[1]\r\n p1x = self.positions[2]\r\n p1y = self.positions[3]\r\n theta1 = np.radians(self.positions[4])\r\n p2x = self.positions[5]\r\n p2y = self.positions[6]\r\n theta2 = np.radians(self.positions[7])\r\n p0 = np.array([p0x, p0y])\r\n p1 = np.array([p1x, p1y])\r\n p2 = np.array([p2x, p2y])\r\n\r\n self.a0 = np.array([self.a0x, self.a0y])\r\n self.b0 = np.array([self.b0x, self.b0y])\r\n\r\n # test = np.zeros((3,3))\r\n alldata = []\r\n for j in range(len(\r\n self.payload)): # theres multiple sections of payloades so some how this line is supposed to sort through them\r\n vals = []\r\n for i in range(2, len(self.payload[j]) - 1,\r\n 2): # this i is supposed to sort through the data once a payload row is selected\r\n # if i > 1 and i % 2 == 0: #and i < self.payload-2: # based on order, if its odd it should be an x... even should be y...\r\n x = self.payload[j][i]\r\n y = self.payload[j][i + 1]\r\n # vals.append((np.array([x,y])))\r\n vals.append([x, y])\r\n\r\n vals_numpy = np.array(vals)\r\n alldata.append(vals_numpy)\r\n\r\n self.p0 = deepcopy(alldata)\r\n self.p1 = deepcopy(alldata)\r\n self.p2 = deepcopy(alldata)\r\n\r\n self.a0 = deepcopy(self.a0)\r\n self.a1 = deepcopy(self.a0)\r\n self.a2 = deepcopy(self.a0)\r\n\r\n self.b0 = deepcopy(self.b0)\r\n self.b1 = deepcopy(self.b0)\r\n self.b2 = deepcopy(self.b0)\r\n\r\n # Translate to origin\r\n for i in range(len(self.p1)):\r\n for j in range(len(self.p1[i])):\r\n self.p1[i][j][0] -= p0x\r\n self.p1[i][j][1] -= p0y\r\n self.p2[i][j][0] -= p0x\r\n self.p2[i][j][1] -= p0y\r\n\r\n self.a1[0] -= p0x\r\n self.a1[1] -= p0y\r\n self.b1[0] -= p0x\r\n self.b1[1] -= p0y\r\n\r\n self.a2[0] -= p0x\r\n self.a2[1] -= p0y\r\n self.b2[0] -= p0x\r\n self.b2[1] -= p0y\r\n\r\n # Rotate\r\n rotate1 = [[np.cos(theta1), np.sin(theta1)], [-np.sin(theta1), np.cos(theta1)]]\r\n rotate2 = [[np.cos(theta2), np.sin(theta2)], [-np.sin(theta2), np.cos(theta2)]]\r\n\r\n for i in range(len(self.p1)):\r\n self.p1[i] = np.matmul(self.p1[i], rotate1)\r\n self.p2[i] = np.matmul(self.p2[i], rotate2)\r\n\r\n self.a1 = np.matmul(self.a1, rotate1)\r\n self.b1 = np.matmul(self.b1, rotate1)\r\n self.a2 = np.matmul(self.a2, rotate2)\r\n self.b2 = np.matmul(self.b2, rotate2)\r\n\r\n # Currently both at origin and rotated\r\n\r\n for i in range(len(self.p1)):\r\n for j in range(len(self.p1[i])):\r\n self.p1[i][j][0] += p1x\r\n self.p1[i][j][1] += p1y\r\n self.p2[i][j][0] += p2x\r\n self.p2[i][j][1] += p2y\r\n\r\n self.a1[0] += p1x\r\n self.a1[1] += p1y\r\n self.b1[0] += p1x\r\n self.b1[1] += p1y\r\n\r\n self.a2[0] += p2x\r\n self.a2[1] += p2y\r\n self.b2[0] += p2x\r\n self.b2[1] += p2y\r\n\r\n self.a1x = self.a1[0]\r\n self.a1y = self.a1[1]\r\n self.b1x = self.b1[0]\r\n self.b1y = self.b1[1]\r\n\r\n self.a2x = self.a2[0]\r\n self.a2y = self.a2[1]\r\n self.b2x = self.b2[0]\r\n self.b2y = self.b2[1]\r\n\r\n # math studd to calculate positions\r\n\r\n # newpayload.append(newpayloadxy)\r\n\r\n def ThreeBarCircle(self):\r\n # initial guesses\r\n self.ha = 1\r\n self.ka = 1\r\n self.ra = 1\r\n\r\n self.hb = 2\r\n self.kb = 1\r\n self.rb = 0\r\n\r\n def solve(vars, args):\r\n [h, k, r] = vars\r\n [x0, y0, x1, y1, x2, y2] = args\r\n\r\n a = sqrt(((x0 - h) ** 2) + ((y0 - k) ** 2)) - r\r\n b = sqrt(((x1 - h) ** 2) + ((y1 - k) ** 2)) - r\r\n c = sqrt(((x2 - h) ** 2) + ((y2 - k) ** 2)) - r\r\n\r\n return a, b, c\r\n\r\n vars = [self.ha, self.ka, self.ra]\r\n args = [self.a0[0], self.a0[1], self.a1[0], self.a1[1], self.a2[0], self.a2[1]]\r\n self.ha, self.ka, self.ra = fsolve(solve, vars, args=args) # ha = x, ka = y, r = radius of circle\r\n\r\n vars = [self.hb, self.kb, self.rb]\r\n args = [self.b0[0], self.b0[1], self.b1[0], self.b1[1], self.b2[0], self.b2[1]]\r\n self.hb, self.kb, self.rb = fsolve(solve, vars, args=args)\r\n\r\n self.l1 = sqrt((self.ha + self.hb) ** 2 + (self.ka + self.kb) ** 2)\r\n self.l2 = self.ra\r\n self.l3 = sqrt((self.b0x + self.a0x) ** 2 + (self.b0y + self.a0y) ** 2)\r\n self.l4 = self.rb\r\n\r\n self.thetaInitial1 = atan2((self.a0y - self.ka), (self.a0x - self.ha)) * 180 / np.pi\r\n self.thetaEnding1 = atan2((self.a2y - self.ka), (self.a2x - self.ha)) * 180 / np.pi\r\n\r\n # self.thetaInitial2 = atan2((self.b0y - self.kb), (self.b0x - self.hb)) * 180 / np.pi\r\n # self.thetaEnding2 = atan2((self.b2y - self.kb), (self.b2x - self.hb)) * 180 / np.pi\r\n\r\n # self.dtheta1 = (self.thetaEnding1 - self.thetaInitial1) / self.nframes\r\n # self.dtheta2 = (self.thetaEnding2 - self.thetaInitial2) / self.nframes\r\n\r\n def calculate(self):\r\n self.theta1 = atan2((self.ka - self.kb), (self.ha - self.hb))*(180/np.pi)\r\n\r\n self.theta2 = atan2((self.a0y - self.ka), (self.a0x - self.ha))*(180/np.pi)\r\n\r\n self.theta3 = atan2((self.b0y - self.a0y), (self.b0x - self.a0y))*(180/np.pi)\r\n self.theta4 = atan2((self.kb - self.b0y), (self.hb - self.b0x))*(180/np.pi)\r\n\r\n def ThetaSolver(vars, args):\r\n [theta3, theta4] = vars\r\n [l1, l2, l3, l4, theta1, theta2] = args\r\n\r\n d = l1 * np.sin(theta1) + l2 * np.sin(theta2) + l3 * np.sin(theta3) + l4 * np.sin(theta4)\r\n e = l1 * np.cos(theta1) + l2 * np.cos(theta2) + l3 * np.cos(theta3) + l4 * np.cos(theta4)\r\n return d, e\r\n\r\n vars = [self.theta3, self.theta4]\r\n args = [self.l1, self.l2, self.l3, self.l4, self.theta1, self.theta2]\r\n self.theta3, self.theta4 = fsolve(ThetaSolver, vars, args=args) # ha = x, ka = y, r = radius of circle\r\n\r\n\r\n def CreateDraggingList(self):\r\n draglist = [[self.a0x, self.a0y],\r\n [self.b0x, self.b0y]]\r\n return draglist\r\n\r\n def DraggingListItemChanged(self, x, y, draglist, index):\r\n if index == 0: # A Connection\r\n self.a0x, self.a0y = [x, y]\r\n draglist[0] = [x, y]\r\n\r\n if index == 1: # B Connection\r\n self.b0x, self.b0y = [x, y]\r\n draglist[1] = [x, y]\r\n\r\n self.Translation()\r\n self.ThreeBarCircle()\r\n\r\n # def draggingCallback(self, start):\r\n # if start is True:\r\n # draglist = self.fourbar.CreateDraggingList()\r\n # near = 15\r\n # self.glwindow1.g1StartDragging(self.draggingCallback, draglist, near, handlesize=.1, handlewidth=1,\r\n # handlecolor=[1, 0, 1])\r\n # self.ui.dragging.setChecked(False)\r\n # elif start is False:\r\n # self.glwindow1.glStopDragging()\r\n # self.ui.dragging.setChecked(False)\r\n\r\n # def ShowConstruction(self, show)\r\n # if show is True...\r\n\r\n # Animation Stuff\r\n\r\n # def CalculateFlightPaths(self):\r\n # # This to draw the picture and during animation!\r\n # for frame in range(self.nframes):\r\n # # time = self.tmax * frame / self.nframes\r\n # #newdriverpoints[] fill these with new x and y points depending on each frame\r\n # #for each nframe add .01 in loop to each point so that new driverpoints are being created\r\n # #rotate about center point eventually\r\n #\r\n # # draglist points that are being animated\r\n #\r\n # # self.dthetab = (self.thetaEnding - self.thetaInitial) / self.nframes\r\n # self.theta1 = atan2((self.ka - self.kb), (self.ha - self.hb)) * (180 / np.pi)\r\n #\r\n # self.theta2 = atan2((self.a0y - self.ka), (self.a0x - self.ha)) * (180 / np.pi)\r\n #\r\n # self.theta3 = atan2((self.b0y - self.a0y), (self.b0x - self.a0y)) * (180 / np.pi)\r\n # self.theta4 = atan2((self.kb - self.b0y), (self.hb - self.b0x)) * (180 / np.pi)\r\n #\r\n # NewDriverPoints = []\r\n # for i in range(self.nframes):\r\n # self.theta2 += self.dtheta1\r\n # self.theta4 += self.dtheta2\r\n #\r\n # self.a0x = self.ra*np.cos(self.theta2)\r\n # self.a0y = self.ra*np.sin(self.theta2)\r\n #\r\n # self.b0x = self.rb*np.cos(self.theta4)\r\n # self.b0y = self.rb*np.cos(self.theta4)\r\n #\r\n # self.a0 = np.array([self.a0x, self.a0y])\r\n # self.b0 = np.array([self.b0x, self.b0y])\r\n #\r\n # # self.Translation()\r\n # # self.ThreeBarCircle()\r\n # # self.calculate()\r\n # # self.DrawTrussPicture()\r\n # NewDriverPoints.append([self.theta2, self.a0x,self.a0y])\r\n # points = np.array(NewDriverPoints)\r\n #\r\n # for i in range(0, len(self.connections) - 1, 2):\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(self.points[frame][i][0], self.points[frame][i][1], .015 * (abs(self.window[0]) + abs(self.window[1])),fill=True)\r\n\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(self.bpath[i][0], self.bpath[i][1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n # end def\r\n\r\n # finds frames for the payload to move through\r\n\r\n # def ConfigureAnimationFrame(self, frame, nframes):\r\n # # self.drone_x = self.dronepath[frame, 0] # driverlink\r\n # # self.ball_x = self.ballpath[frame, 0]\r\n # # self.ball_y = self.ballpath[frame, 1]\r\n # self.a0x = self.apath[frame, 0]\r\n # self.a0y = self.apath[frame, 1]\r\n # self.b0x = self.bpath[frame, 0]\r\n # self.b0y = self.bpath[frame, 1]\r\n\r\n def DrawTrussPicture(self):\r\n # this is what actually draws the picture\r\n # using data to control what is drawn\r\n\r\n # begin drawing connected lines\r\n # use GL_LINE for drawing a series of disconnected lines\r\n # draws boundaries using self.boundary and self.linestyle with correct color and thickness\r\n for i in range(len(self.boundary)):\r\n for k in range(len(self.linestyle)):\r\n if self.boundary[i][1] == self.linestyle[k][0]:\r\n red = self.linestyle[k][1]\r\n green = self.linestyle[k][2]\r\n blue = self.linestyle[k][3]\r\n width = self.linestyle[k][4]\r\n glColor3f(red, green, blue)\r\n glLineWidth(width)\r\n for j in range(2, len(self.boundary[i]) - 3, 2):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.boundary[i][j], self.boundary[i][j + 1])\r\n glVertex2f(self.boundary[i][j + 2], self.boundary[i][j + 3])\r\n glEnd()\r\n\r\n # glColor3f(1, .5, .3) #\r\n # glLineWidth(1.5)\r\n # for i in range(0, len(self.connections) - 1, 2):\r\n # gl2DCircle(self.connections[i], self.connections[i + 1], .015 * (abs(self.window[0]) + abs(self.window[1])),fill=True)\r\n\r\n # Draws the A and B points according p0, p1, p2 of payload\r\n glColor3f(1, .5, .3) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a0[0], self.a0[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, .5, .3) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b0[0], self.b0[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 1, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a1[0], self.a1[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 1, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b1[0], self.b1[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.a2[0], self.a2[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(1, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.b2[0], self.b2[1], .015 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n # Draws the positions that the payload will go through\r\n glColor3f(.5, .5, .5) #\r\n glLineWidth(1.5)\r\n for i in range(len(self.p0)):\r\n for j in range(0, len(self.p0[i]) - 1, 1):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p0[i][j][0], self.p0[i][j][1])\r\n glVertex2f(self.p0[i][j + 1][0], self.p0[i][j + 1][1])\r\n glEnd()\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p1[i][j][0], self.p1[i][j][1])\r\n glVertex2f(self.p1[i][j + 1][0], self.p1[i][j + 1][1])\r\n glEnd()\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.p2[i][j][0], self.p2[i][j][1])\r\n glVertex2f(self.p2[i][j + 1][0], self.p2[i][j + 1][1])\r\n glEnd()\r\n\r\n # Draws the actual payload with colored lines and the wheel\r\n for i in range(len(self.payload)):\r\n for k in range(len(self.linestyle)):\r\n if self.payload[i][1] == self.linestyle[k][0]:\r\n red = self.linestyle[k][1]\r\n green = self.linestyle[k][2]\r\n blue = self.linestyle[k][3]\r\n width = self.linestyle[k][4]\r\n glColor3f(red, green, blue)\r\n glLineWidth(width)\r\n for j in range(2, len(self.payload[i]) - 3, 2):\r\n glBegin(GL_LINE_STRIP)\r\n glVertex2f(self.payload[i][j], self.payload[i][j + 1])\r\n glVertex2f(self.payload[i][j + 2], self.payload[i][j + 3])\r\n glEnd()\r\n\r\n # draws the links between the A and B connections and the arc that fsolve calculated\r\n glColor3f(0, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.ha, self.ka, .02 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glColor3f(0, 0, 0) #\r\n glLineWidth(1.5)\r\n gl2DCircle(self.hb, self.kb, .02 * (abs(self.window[0]) + abs(self.window[1])), fill=True)\r\n\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(0, 0, 0)\r\n glVertex2f(self.ha, self.ka)\r\n glVertex2f(self.a0[0], self.a0[1])\r\n glEnd()\r\n\r\n glBegin(GL_LINE_STRIP)\r\n glColor3f(1, 1, 0)\r\n glVertex2f(self.hb, self.kb)\r\n glVertex2f(self.b0[0], self.b0[1])\r\n glEnd()\r\n\r\n # test for sports wing\r\n\r\n # glColor3f(.2, .8, 1) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(4,1,.018,fill=True)\r\n #\r\n # glColor3f(.2, .8, 1) #\r\n # glLineWidth(1.5)\r\n # gl2DCircle(4.3,1.7,.018,fill=True)\r\n","repo_name":"TDCrotty124/4-Bar-Project","sub_path":"FourBar_Class.py","file_name":"FourBar_Class.py","file_ext":"py","file_size_in_byte":19737,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"3201311018","text":"from django.shortcuts import render, redirect\nfrom . models import BugUser, Ticket\nfrom . forms import NewUserForm, NewTicketForm, LoginForm, EditTicketForm\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\n\n\ndef landing(request):\n return render(request, 'landing.html')\n\n\ndef index(request):\n tickets = Ticket.objects.all()\n\n new = [t for t in tickets if t.status == 'New']\n in_progress = [t for t in tickets if t.status == \"In progress\"]\n completed = [t for t in tickets if t.status == \"Completed\"]\n invalid = [t for t in tickets if t.status == \"Invalid\"]\n sorted_tickets = new + in_progress + completed + invalid\n context = {\"tickets\": sorted_tickets}\n\n return render(request, 'index.html', context)\n\n\ndef new_ticket(request):\n # need to import the form and instantiate and all that good stuff\n if request.method == 'POST':\n form = NewTicketForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n Ticket.objects.create(\n title=form_data['title'],\n time_created=timezone.now(),\n description=form_data['description'],\n submitters_name=request.user.buguser,\n status='New',\n assigned_dev=None,\n completed_dev=None\n )\n\n return redirect('/bugs-tracker/ticket/all')\n else:\n form = NewTicketForm()\n context = {'form': form}\n\n return render(request, 'ticket/new_ticket.html', context)\n\n\ndef edit_ticket(request, ticket_id):\n ticket = Ticket.objects.filter(id=ticket_id).first()\n if request.method == 'POST':\n form = EditTicketForm(request.POST)\n\n if form.is_valid():\n form = form.cleaned_data\n\n if form['Invalidate_ticket'] == 'True':\n ticket.status = 'Invalid'\n ticket.completed_dev = ticket.assigned_dev\n ticket.assigned_dev = None\n ticket.save()\n\n elif form['Mark_complete'] == 'True':\n ticket.status = 'Completed'\n ticket.completed_dev = ticket.assigned_dev\n ticket.assigned_dev = None\n ticket.save()\n\n elif form['assigned_dev'] is not None and ticket.assigned_dev == None:\n ticket.assigned_dev = form['assigned_dev']\n ticket.status = \"In progress\"\n ticket.save()\n\n return redirect('/bugs-tracker/ticket/{}'.format(ticket.id))\n \n else:\n form = EditTicketForm(instance=ticket)\n context = {'form': form}\n\n return render(request, 'ticket/edit_ticket.html', context)\n\n\ndef ticket_detail(request, ticket_id):\n ticket = Ticket.objects.filter(id=ticket_id).first()\n context = {'ticket': ticket}\n\n return render(request, 'ticket/ticket_detail.html', context)\n\n\ndef tickets_by_user(request, user_id):\n user = BugUser.objects.filter(id=user_id).first()\n\n current_tickets = Ticket.objects.filter(submitters_name=user)\n filed = Ticket.objects.filter(submitters_name=user)\n completed = Ticket.objects.filter(completed_dev=user)\n merged_queries = current_tickets | filed | completed\n\n context = {'tickets': merged_queries}\n\n return render(request, 'ticket/tickets_by_user.html', context)\n\n\ndef login_user(request):\n if request.method == \"POST\":\n form = LoginForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n user = authenticate(\n username=form_data['username'],\n password=form_data['password']\n )\n\n if user is not None:\n login(request, user)\n return redirect('/bugs-tracker/ticket/all')\n else:\n form = LoginForm()\n context = {\n 'error': \"incorrect username or password \", \n 'form': form\n }\n return render(request, 'auth/login.html', context)\n else:\n form = LoginForm()\n context = {'form': form}\n\n return render(request, 'auth/login.html', context)\n\n\ndef new_user(request):\n if request.method == 'POST':\n form = NewUserForm(request.POST)\n\n if form.is_valid():\n form_data = form.cleaned_data\n\n user = User.objects.create_user(\n username=form_data['username'],\n password=form_data['password']\n )\n\n BugUser.objects.create(\n name=form_data['username'],\n user=user\n )\n \n return render(request, 'index.html')\n else:\n form = NewUserForm()\n context = {'form': form}\n\n return render(request, 'auth/new_user.html', context)\n\n\ndef all_users(request):\n users = BugUser.objects.all()\n context = {\"users\": users}\n return render(request, 'all_users.html', context)","repo_name":"ethan375/sup-doc","sub_path":"sup_doc/bugs_tracker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38363121474","text":"# coding=utf-8\nimport pandas as pd\nimport numpy as np\n\n\nclass Spider():\n n = 0\n filename1 = './data1/test' + str(n) + '.csv'\n data = pd.read_csv(filename1)\n # print file1\n data_all = pd.DataFrame(columns=[0])\n # list_all_file = open('./data2/all.csv','w')\n user_name = [\"\"] * 2\n # print data.iloc[22,0]\n # ss = data.iloc[22,0]\n # if ss == '-':\n # print ###########\n # if ss == '-':\n # print ###########\n for i in range(len(data)):\n row = data.iloc[i,0]\n if i==0:\n row1 = data.iloc[i,0]\n name1 = row.split('(view source)')\n name2 = name1[1].split('(')\n user_name[0] = name2[0]\n row1 = data.iloc[i, 1]\n name1_2 = row.split('(view source)')\n name2_2 = name1[1].split('(')\n user_name[1] = name2[0]\n else:\n if pd.isnull(row):\n if data.iloc[i,1] == '+':\n if not pd.isnull(data.iloc[i,2]):\n aa = 'banben:2banben:user:'+str(user_name[1])+'user:'+str(data.iloc[i,2])\n insertrow = pd.DataFrame([aa])\n\n data_all=data_all.append(insertrow,ignore_index=True)\n # list_all_file.write('banben:2banben:user:'+str(user_name[1])+'user:'+str(data.iloc[i,2])+'\\n')\n else:\n print('sssss')\n # list_all_file.write('nothing' + '\\n')\n else:\n if pd.isnull(data.iloc[i,1]):\n print('sssss')\n\n # list_all_file.write('nothing' + '\\n')\n else:\n if data.iloc[i,1] == data.iloc[i,3]:\n aa = 'banben:1banben:user:' + str(user_name[0]) + 'user:' + str(data.iloc[i, 1])\n insertrow = pd.DataFrame([aa])\n data_all = data_all.append(insertrow, ignore_index=True)\n # list_all_file.write('banben:1banben:user:' + str(user_name[0]) + 'user:' + str(data.iloc[i, 1]) + '\\n')\n else:\n print ('data.iloc[i,1] == data.iloc[i,3]bu deng')\n else:\n if row == \"−\":\n aa = 'banben:2banben:user:' + str(user_name[1]) + 'user:' + str(data.iloc[i, 3])\n insertrow = pd.DataFrame([aa])\n\n data_all = data_all.append(insertrow, ignore_index=True)\n # list_all_file.write('banben:2banben:user:' + str(user_name[1]) + 'user:' + str(data.iloc[i, 3]) + '\\n')\n\n # if pd.isnull(data.iloc[i,2])&pd.isnull(data.iloc[i,3]):\n # print str(data.iloc[i,0])+'&&'+str(data.iloc[i,1])\n else:\n print (str(data.iloc[i, 0]) + '&&' + str(data.iloc[i, 1]))\n # print 'pd.isnull(data.iloc[i,2])&&pd.isnull(data.iloc[i,3])bu wei kong'\n data_all.to_csv('./data2/all0.csv',encoding='utf-8',index=False,header=False)\n\n\n\n\n\n # for j in range(4):\n # row = data.iloc[i, j]\n #\n # if i == 0:\n # if not pd.isnull(row):\n # row = data.iloc[i, j]\n # name1 = row.split('(edit)')\n # name2 = name1[1].split('(')\n # user_name = name2[0]\n # user_time1 = name1[0].split('of')\n # user_time = user_time1[1]\n # list_all_file.write(str(user_name) + ',' + str(user_time) + '\\n')\n # else:\n # break\n # elif not pd.isnull(row):\n # line = row.split(' ')\n # if line[0] == 'Line':\n # line1 = line.split(':')\n # line_count = line1[0]\n #\n # list_all_file.write(row + '\\n')\n # else:\n # print 22\n # # aa = np.isnan(row)pd.np.nan\n # print 22\n\n\n# print row\nspider1 = Spider()\n","repo_name":"zouchangjie/wiki_spiker_bigdata","sub_path":"conn_wiki/datawork_fist_ver.py","file_name":"datawork_fist_ver.py","file_ext":"py","file_size_in_byte":4082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21824086962","text":"# solving Riddler Classic @ https://fivethirtyeight.com/features/can-you-zoom-around-the-race-track/\n\nimport functools\nimport numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple\nfrom math import atan2, pi\n\n\nP = namedtuple('P', 'x y') # 2-D Point\n\n# to label moves\nACCELERATIONS = {i: P(x, y) for i, (x, y) in enumerate([(x, y) for x in range(-1, 2) for y in range(-1, 2)], 1)}\n\n\ndef calc_angle(x, y):\n \"\"\"get angle of polar coordinates from Cartesian coordinates\"\"\"\n return (atan2(y, x) + (2 * pi if y < 0 else 0.)) / (2 * pi)\n\n\ndef point_sum(p0, p1):\n \"\"\"vector sum of two Points\"\"\"\n return P(p0.x + p1.x, p0.y + p1.y)\n\n\ndef point_dist(p0, p1):\n \"\"\"Euclidean distance between two Points\"\"\"\n return ((p0.x - p1.x) ** 2 + (p0.y - p1.y) ** 2) ** 0.5\n\n\ndef point_rotate(p):\n \"\"\"rotate Point by 90% clockwise\"\"\"\n return P(p.y, -p.x)\n\n\nclass S:\n \"\"\"race State = <2-D position: Point, 2-D velocity: Point>\"\"\"\n def __init__(self, p, v):\n self.p = p\n self.v = v\n\n def __key(self):\n return (self.p.x, self.p.y, self.v.x, self.v.y)\n\n def __eq__(self, other):\n return self.__key() == other.__key()\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n def __hash__(self):\n return hash(self.__key())\n\n def __repr__(self):\n return f'S(p={self.p}, v={self.v})'\n\n def get_potential_moves(self):\n \"\"\"get all potential next states in a boundless track\"\"\"\n potential_moves = {}\n for move, acc in ACCELERATIONS.items():\n v1 = point_sum(self.v, acc)\n p1 = point_sum(self.p, v1)\n potential_moves[move] = S(p1, v1)\n return potential_moves\n\n\nA = namedtuple('A', 'moves prevs time') # attributes of a state: prev( State)s, moves leading to it in given time\n\n\nclass RaceTrack:\n \"\"\"representing a race track and the graph of possible race states to optimize upon\"\"\"\n def __init__(self, half_side=7, r=3, start_x=None, accept=None):\n \"\"\"init the track and the graph of possible race states\"\"\"\n self.half_side = half_side\n self.r = r\n self.r2 = r ** 2\n self.accept = accept if accept else self.angle_doesnt_worsen\n self.points_to_angles = {\n P(x, y): calc_angle(x, y)\n for x in range(-half_side, half_side + 1)\n for y in range(-half_side, half_side + 1)\n if x**2 + y**2 >= self.r2\n }\n self.start_point = P(x=start_x if start_x else (half_side + r) // 2, y=0)\n self.start_node = S(self.start_point, P(0, 0))\n self.nodes = {self.start_node: A(moves=[''], prevs=[], time=0.)}\n self.starts = set([self.start_node])\n self.ends = set()\n\n @functools.lru_cache(maxsize=None)\n def segment_crosses_circle(self, p0, p1):\n \"\"\"True iff the segment between the two given Points crosses the circle in two crossing points\"\"\"\n if p0.x == p1.x:\n delta = self.r2 - p0.x ** 2\n if delta <= 0.:\n return False\n else:\n (y_min, y_max) = (p0.y, p1.y) if p0.y < p1.y else (p1.y, p0.y)\n y_plus = delta ** 0.5\n y_minus = - y_plus\n return y_min <= y_minus <= y_max and y_min <= y_plus <= y_max\n elif p0.y == p1.y:\n delta = self.r2 - p0.y ** 2\n if delta <= 0.:\n return False\n else:\n (x_min, x_max) = (p0.x, p1.x) if p0.x < p1.x else (p1.x, p0.x)\n x_plus = delta ** 0.5\n x_minus = -x_plus\n return x_min <= x_minus <= x_max and x_min <= x_plus <= x_max\n else:\n m = (p1.y - p0.y) / (p1.x - p0.x)\n k = p0.y - m * p0.x\n km = k * m\n m2_1 = m ** 2 + 1\n delta = km ** 2 - m2_1 * (k ** 2 - self.r2)\n if delta <= 0.:\n return False\n else:\n (x_min, x_max) = (p0.x, p1.x) if p0.x < p1.x else (p1.x, p0.x)\n delta_sqrt = delta ** 0.5\n x_plus = (-km + delta_sqrt) / m2_1\n x_minus = (-km - delta_sqrt) / m2_1\n return x_min <= x_minus <= x_max and x_min <= x_plus <= x_max\n\n @functools.lru_cache(maxsize=None)\n def arrow_crosses_finish(self, p0, p1):\n \"\"\"True iff Point p1 is on or beyond the finish line, but p0 is not\"\"\"\n if p1.y < 0:\n return False\n elif p0.y >= 0:\n return False\n elif p0.x == p1.x:\n return self.r <= p0.x <= self.half_side\n else:\n x_cross = p0.x - p0.y * (p1.x - p0.x) / (p1.y - p0.y)\n return self.r <= x_cross <= self.half_side\n\n def get_admissible_moves(self, s0, accept=None):\n \"\"\"\n If no potential move crosses the finish line, then return:\n (list of all potential next states within the track boundaries, False)\n otherwise return:\n (list of all potential next states within the track boundaries and across the finish line, True)\n \"\"\"\n if not accept:\n accept = self.accept\n admissible_moves = {}\n finish_possible = False\n for move, s1 in s0.get_potential_moves().items():\n if not s1.p in self.points_to_angles or self.segment_crosses_circle(s0.p, s1.p):\n continue\n finishing = self.arrow_crosses_finish(s0.p, s1.p)\n if not finish_possible and finishing:\n admissible_moves = {}\n finish_possible = True\n if finish_possible and finishing or not finish_possible and accept(s0, s1):\n admissible_moves[move] = s1\n return admissible_moves, finish_possible\n\n def angle_compares_ok(self, s0, s1, comparison_function):\n \"\"\"True iff the angle improves between the two given states, as measured by the given comparison_function\"\"\"\n phi0, phi1 = self.points_to_angles[s0.p], self.points_to_angles[s1.p]\n return comparison_function(phi0, phi1) and phi1 - phi0 < 0.5\n\n def angle_improves(self, s0, s1):\n \"\"\"True iff the angle improves between the two given states\"\"\"\n return self.angle_compares_ok(s0, s1, lambda phi0, phi1: phi1 > phi0)\n\n def angle_doesnt_worsen(self, s0, s1):\n \"\"\"True iff the angle does not worsen between the two given states\"\"\"\n return self.angle_compares_ok(s0, s1, lambda phi0, phi1: phi1 >= phi0)\n\n def move_forward(self):\n \"\"\"enrich the graph of race states by one move forward from every last reached state\"\"\"\n new_starts = set()\n finish_reached = False\n for s0 in self.starts:\n a0 = self.nodes[s0]\n admissible_moves, finishing = self.get_admissible_moves(s0)\n finish_reached = finish_reached or finishing\n for move1, s1 in admissible_moves.items():\n new_time = a0.time + 1.\n if s1 not in self.nodes:\n a1 = A(moves=[move1], prevs=[s0], time=new_time)\n self.nodes[s1] = a1\n new_starts.add(s1)\n elif self.nodes[s1].time == new_time:\n a1 = self.nodes[s1]\n a1.moves.append(move1)\n a1.prevs.append(s0)\n if finishing:\n self.ends.add(s1)\n if finish_reached:\n self.starts = set()\n else:\n self.starts = new_starts\n return finish_reached\n\n def retrace_paths_back_to_start(self, s1):\n \"\"\"get all bakward sequences of points from state s1 to the start point\"\"\"\n if s1 == self.start_node:\n return [[('', s1.p)]]\n paths = []\n a1 = self.nodes[s1]\n for move01, s0 in zip(a1.moves, a1.prevs):\n path_end = [(move01, s1.p)]\n prev_paths = self.retrace_paths_back_to_start(s0)\n for prev_path in prev_paths:\n paths.append(path_end + prev_path)\n return paths\n\n def score_path(self, points):\n \"\"\"\n compute the time and the length of a path, given as a sequence of points;\n for the move crossing the finish line, only the fraction of time and length before crossing is considered\n \"\"\"\n time, length = 0., 0.\n for p0, p1 in zip(points[:-1], points[1:]):\n fraction_before_finish = -p0.y / (p1.y - p0.y) if self.arrow_crosses_finish(p0, p1) else 1.\n time += fraction_before_finish\n length += fraction_before_finish * point_dist(p0, p1)\n return time, length\n\n def optimize_route(self, do_print=True, do_plot=True):\n \"\"\"\n identify and return the best routes [(time, length, , )]\n :param consider_length: True iff the min. length should be a secondary optimization criterion, after min. time\n :param do_print: True iff the best routes should be printed\n :param do_plot: True iff the best routes should be plotted\n :return: the best routes [(time, length, , )], sorted\n \"\"\"\n def route2str(time, length, moves, points):\n return f'time = {time:.3f}, length = {length:.3f}, moves = {moves}, points = {[(p.x, p.y) for p in points]}'\n\n if do_print:\n print(f'\\nFINDING THE FASTEST ROUTES...')\n n_moves = 0\n while self.starts:\n n_moves += 1\n self.move_forward()\n n_open_paths = len(self.starts)\n if n_open_paths:\n if do_print:\n print(f'After {n_moves} moves, {len(self.starts)} states/nodes have been reached...')\n backward_paths = []\n for s_end in self.ends:\n backward_paths.extend(self.retrace_paths_back_to_start(s_end))\n fastest_routes = []\n for backward_path in backward_paths:\n moves, points = zip(*reversed(backward_path))\n moves = ''.join([str(move) for move in moves])\n time, length = self.score_path(points)\n fastest_routes.append((time, length, moves, [point_rotate(point) for point in points]))\n fastest_routes = sorted(fastest_routes)\n best_time = fastest_routes[0][0]\n n_fastest = 0\n for route in fastest_routes:\n if route[0] > best_time:\n break\n else:\n n_fastest += 1\n fastest_routes = fastest_routes[:n_fastest]\n best_time_length = fastest_routes[0][:2]\n n_shortest_fastest = 0\n for route in fastest_routes:\n if route[:2] > best_time_length:\n break\n else:\n n_shortest_fastest += 1\n shortest_fastest_routes = fastest_routes[:n_shortest_fastest]\n if do_print:\n print(f'After {n_moves} moves, the finish line has been reached or crossed.')\n print()\n print(f'{\"These are\" if n_fastest > 1 else \"This is\"} '\n f'the {n_fastest} fastest path{\"s\" if n_fastest > 1 else \"\"}:')\n for (time, length, moves, points) in fastest_routes:\n print(route2str(time, length, moves, points))\n print()\n print(f'{\"These are\" if n_shortest_fastest > 1 else \"This is\"} '\n f'the {n_shortest_fastest} shortest fastest path{\"s\" if n_shortest_fastest > 1 else \"\"}:')\n for (time, length, moves, points) in shortest_fastest_routes:\n print(route2str(time, length, moves, points))\n if do_plot:\n min_time, min_length = shortest_fastest_routes[0][:2]\n self.plot_routes(\n fastest_routes,\n f'The {n_fastest} fastest route{\"s\" if n_fastest > 1 else \"\"}: time = {min_time:.3f}'\n )\n self.plot_routes(\n shortest_fastest_routes,\n f'The {n_shortest_fastest} shortest fastest route{\"s\" if n_shortest_fastest > 1 else \"\"}: '\n f'time = {min_time:.3f}, length = {min_length:.3f}'\n )\n return fastest_routes\n\n def plot_routes(self, routes, title, do_annotate=False):\n \"\"\"\n plot the given routes\n :param routes: sequence of routes [(time, length, , )]\n :param title: figure title\n :param do_annotate: True iff moves should be labelled in the plot\n :return: nothing\n \"\"\"\n foreground = 10\n background = 0\n hs = self.half_side\n margin = 1\n plt_hs = hs + margin\n fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(plt_hs, plt_hs))\n fig.suptitle(title, fontsize=16)\n plt.xlim(-plt_hs, +plt_hs)\n plt.ylim(-plt_hs, +plt_hs)\n major_ticks = np.linspace(-plt_hs, plt_hs, 2 * plt_hs + 1)\n ax.set_xticks(major_ticks)\n ax.set_yticks(major_ticks)\n wall_col = 'gray'\n ax.grid(color=wall_col, zorder=background)\n ax.plot([-hs, +hs], [-hs, -hs], color=wall_col, zorder=background)\n ax.plot([-hs, +hs], [+hs, +hs], color=wall_col, zorder=background)\n ax.plot([-hs, -hs], [-hs, +hs], color=wall_col, zorder=background)\n ax.plot([+hs, +hs], [-hs, +hs], color=wall_col, zorder=background)\n ax.add_patch(plt.Circle((0, 0), self.r, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, -plt_hs), margin, 2 * plt_hs, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((hs, -plt_hs), margin, 2 * plt_hs, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, -plt_hs), 2 * plt_hs, margin, color=wall_col, zorder=background))\n ax.add_patch(plt.Rectangle((-plt_hs, hs), 2 * plt_hs, margin, color=wall_col, zorder=background))\n ax.plot([0, 0], [-self.r, -hs], linewidth=3, color=wall_col, zorder=background)\n legends = []\n for route_count, (time, length, moves, points) in enumerate(routes, 1):\n colors = reversed(cm.rainbow(np.linspace(0, 1, len(points) - 1)))\n for arrow_count, (p0, p1, move, arrow_color) in enumerate(zip(points[:-1], points[1:], moves, colors), 1):\n arrow_zorder = foreground + arrow_count\n ax.plot([p0.x], [p0.y], marker='o', markersize=5, color=arrow_color, zorder=arrow_zorder - 2)\n arrow = ax.arrow(p0.x, p0.y, p1.x - p0.x, p1.y - p0.y, color=arrow_color, linewidth=2,\n zorder=arrow_zorder, head_width=0.2, head_length=0.4, length_includes_head=True)\n if route_count == 1:\n legends.append((arrow, 'move ' + str(arrow_count)))\n if do_annotate:\n ax.annotate(move, ((p0.x + p1.x) / 2, (p0.y + p1.y) / 2), zorder=arrow_zorder + 10)\n arrows, labels = zip(*legends)\n ax.legend(arrows, labels)\n plt.show()\n\n\nif __name__ == '__main__':\n RaceTrack().optimize_route()\n","repo_name":"stefperf/racetrack","sub_path":"racetrack.py","file_name":"racetrack.py","file_ext":"py","file_size_in_byte":14992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"22611931560","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n # Split the string\n s = s.split()\n # Convert string into a list\n words = list(s)\n left, right = 0, len(words) - 1\n while left < right:\n # Swap words\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n # Convert list back to string\n return \" \".join(s)\n ","repo_name":"abdifatahmohamad/Coding-Interview-Solutions","sub_path":"0151-reverse-words-in-a-string/0151-reverse-words-in-a-string.py","file_name":"0151-reverse-words-in-a-string.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27997693447","text":"# -*- coding: utf-8 -*-\nimport cv2\nimport openface\nfrom joblib import load\nfrom PIL import Image\n\nfrom estimate.core.cert import cert\n\n\ndef warn(*args, **kwargs):\n pass\n\n\nimport warnings\nimport random\nimport traceback\nimport urllib.parse\n\nwarnings.warn = warn\n\n# dlibFacePredictor = 'shape_predictor_68_face_landmarks.dat'\ndlibFacePredictor = '/home/ubuntu/project/kafis/backend/process/shape_predictor_68_face_landmarks.dat'\nnetworkModel = '/home/ubuntu/project/kafis/backend/process/nn4.small2.v1.t7'\nalign = openface.AlignDlib(dlibFacePredictor)\nnet = openface.TorchNeuralNet(networkModel, 96)\nmodels_path = '/home/ubuntu/project/kafis/backend/kafis/estimate/core/model.joblib'\n\n\ndef preprocess(imgPath, gender='F', name=None):\n if name is None:\n name = str(random.randint(1, 999999))\n bgrImg = cv2.imread(urllib.parse.unquote(imgPath))\n\n rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)\n\n bb = align.getAllFaceBoundingBoxes(rgbImg)\n\n class_names = ('красивый', 'обычный', 'некрасивый')\n\n if len(bb) > 1:\n raise Exception('Найдено больше одного лица!')\n elif len(bb) == 0:\n raise Exception('Не найдено ни одного лица!')\n else:\n bb = align.getAllFaceBoundingBoxes(rgbImg)[0]\n try:\n alignedFace = align.align(96, rgbImg, bb,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n #rep = net.forward(alignedFace).reshape(1, -1)\n\n left = max(int(bb.left() - bb.width() * 0.5), 0)\n right = min(int(bb.right() + bb.width() * 0.5), int(rgbImg.shape[1]))\n top = max(int(bb.top() - bb.height() * 0.5), 0)\n bottom = min(int(bb.bottom() + bb.height() * 0.5), int(rgbImg.shape[0]))\n\n models = load(models_path)[0]\n\n cls_name = 'красивый'#class_names[models[gender].predict(rep)[0]]\n print(cls_name)\n face = Image.fromarray(rgbImg[top:bottom, left:right])\n img_path = cert(face, name, cls_name)\n return img_path, cls_name\n except Exception as e:\n traceback.print_exc()\n raise Exception('Не удаётся извлечь признаки, выберите другую фотографию!' + '\\n' + str(e)) \n \n\n# img1 = '/home/ivan/faces/Kristina_Фомина_75814093_M_4.jpg'\n# img2 = '/home/ivan/faces/img/yandex2.jpg'\n# img3 = '/home/ivan/faces/img/grim.jpg'\n# img4 = '/home/ivan/faces/img/kravez.jpg'\n# # try:\n# # preprocess(img1, gender='F')\n# # except Exception as e:\n# # print(str(e))\n#\n# preprocess(img1, gender='F', name='Кристина Фомина')\n","repo_name":"khaliullin/kafis","sub_path":"backend/kafis/estimate/core/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11909411303","text":"from machine import Pin, PWM, ADC\nimport utime\n\n#Initialize the potentiometer pin\nrp = ADC(28)\n\n#PWM output initialization, motor pin\npwm1 = PWM(Pin(13))\npwm1.freq(1000) #Set frequency\n\n#Numerical conversion parameters\nconver_100 = 101 / (65536)\n\n#Numerical remapping\ndef my_map(x, in_min, in_max, out_min, out_max):\n return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)\n\n\n#Set speed of fan, speed=[0, 100]\ndef pwm_motor(speed):\n if speed > 100 or speed < 0:\n print('Please enter a limited speed value of 0-100')\n return\n pulse = my_map(speed, 0, 100, 0, 65535)\n print(pulse)\n pwm1.duty_u16(pulse)\n\nwhile True:\n # Convert the read potentiometer value into [0, 100]\n val_rp = int(rp.read_u16() * conver_100)\n utime.sleep(.1)\n # print(val_rp)\n pwm_motor(val_rp)\n","repo_name":"YahboomTechnology/Pico-sensor-kit","sub_path":"4.Advanced course/6.Adjustable speed fan/Adjustable_speed_fan.py","file_name":"Adjustable_speed_fan.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9158547357","text":"\"\"\"Fundamental routines for computing the Mandelbrot set\n\n Ole Nielsen, SUT 2003\n\"\"\"\n\n\ndef balance(N, P, p):\n \"\"\"Compute p'th interval when N is distributed over P bins.\n \"\"\"\n\n from math import floor\n\n L = int(floor(float(N) / P))\n K = N - P * L\n if p < K:\n Nlo = p * L + p\n Nhi = Nlo + L + 1\n else:\n Nlo = p * L + K\n Nhi = Nlo + L\n\n return Nlo, Nhi\n\n\ndef calculate_point(c, kmax):\n \"\"\"Python version for calculating on point of the set\n This is slow and for reference purposes only.\n Use version from mandel_ext instead.\n \"\"\"\n\n z = complex(0, 0)\n\n count = 0\n while count < kmax and abs(z) <= 2:\n z = z * z + c\n count += 1\n\n return count\n\n\ndef calculate_region(real_min, real_max, imag_min, imag_max, kmax, M, N,\n Mlo=0, Mhi=None, Nlo=0, Nhi=None):\n \"\"\"Calculate the mandelbrot set in the given region with resolution M by N\n If Mlo, Mhi or Nlo, Nhi are specified computed only given subinterval.\n \"\"\"\n\n from numpy import zeros\n from mandel_ext import calculate_point # Fast C implementation\n\n if Mhi is None:\n Mhi = M\n if Nhi is None:\n Nhi = N\n\n real_step = (real_max - real_min) / M\n imag_step = (imag_max - imag_min) / N\n\n A = zeros((M, N), dtype='i') # Create M x N matrix\n\n for i in range(Mlo, Mhi):\n for j in range(Nlo, Nhi):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n\n return A\n\n\ndef calculate_region_cyclic(real_min, real_max, imag_min, imag_max, kmax,\n M, N, p=0, P=1, row=1):\n \"\"\"Calculate rows p+nP, n in N of the mandelbrot set in the given region\n with resolution M by N\n\n This is the most efficient way of partitioning the work.\n \"\"\"\n\n from numpy import zeros\n from mandel_ext import calculate_point # Fast C implementation\n\n real_step = (real_max - real_min) / M\n imag_step = (imag_max - imag_min) / N\n\n A = zeros((M, N), dtype='i') # Create M x N matrix\n\n if row:\n for i in range(M):\n if i % P == p:\n for j in range(N):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n else:\n for j in range(N):\n if j % P == p:\n for i in range(M):\n c = complex(real_min + i * real_step,\n imag_min + j * imag_step)\n A[i, j] = calculate_point(c, kmax)\n return A\n","repo_name":"daleroberts/pypar","sub_path":"examples/mandelbrot_example/mandelbrot.py","file_name":"mandelbrot.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"52"}
+{"seq_id":"20775140287","text":"import logging\n\nimport torch\nfrom coremltools.models.model import MLModel\n\nfrom helpers.constants import BATCH_SIZE, IMAGE_NAME, IOU_NAME, CONF_NAME, CONFIDENCE_NAME, COORDINATES_NAME, \\\n MASKS_NAME, NUMBER_NAME\nfrom pytorch_utils.pytorch_nms import pt_xywh2yxyx_yolo\n\n\nclass CoreMLModel:\n \"\"\" Class to load a CoreML model and run inference\n\n Attributes\n ----------\n model_path: str\n The path to the CoremL model\n \"\"\"\n def __init__(self, model_path):\n logging.info(\"- Initializing CoreML model...\")\n self.model = MLModel(model_path)\n\n spec = self.model.get_spec()\n pipeline = spec.pipeline\n self.labels = [label.rstrip() for label in pipeline.models[-1].nonMaximumSuppression.stringClassLabels.vector]\n if len(self.labels) == 0:\n self.labels = spec.description.output[-1].shortDescription.split(',')\n logging.info(f\"- There are {len(self.labels)} labels.\")\n\n input_details = spec.description.input\n output_details = spec.description.output\n\n input_names = ', '.join([input.name for input in input_details])\n output_name = ', '.join([output.name for output in output_details])\n\n self.img_size = (int(input_details[0].type.imageType.height), int(input_details[0].type.imageType.width))\n logging.info(\n f\"- The model takes {len(input_details)} input{'s' if len(input_details) > 1 else ''}: {input_names}.\")\n logging.info(f\"- The image is of size {self.img_size}.\")\n logging.info(f\"- It has {len(output_details)} output{'s' if len(output_details) > 1 else ''}: {output_name}\")\n\n def get_input_info(self):\n \"\"\"\n Returns the information about the input\n\n Returns\n ----------\n normalized, img size, batch size, PIL image, channel first\n Information about the input\n \"\"\"\n return False, self.img_size, BATCH_SIZE, True, False\n\n def predict(self, img, iou_threshold, conf_threshold):\n \"\"\"\n Runs the inference\n\n Parameters\n ----------\n img: PIL.Image\n The input image\n\n iou_threshold: float\n The IoU threshold\n\n conf_threshold: float\n The confidence threshold\n\n Returns\n ----------\n yxyx, classes, scores, masks, nb_detected\n The detections made by the model\n \"\"\"\n try:\n predictions = self.model.predict(\n {IMAGE_NAME: img, IOU_NAME: iou_threshold, CONF_NAME: conf_threshold})\n except:\n predictions = self.model.predict(\n {IMAGE_NAME: img, IOU_NAME: [iou_threshold], CONF_NAME: [conf_threshold]})\n\n yxyx = torch.from_numpy(predictions[COORDINATES_NAME]).view(-1, 4)\n confidence = torch.from_numpy(predictions[CONFIDENCE_NAME]).view(-1, len(self.labels))\n\n yxyx = pt_xywh2yxyx_yolo(yxyx) # coordinates are xywh\n classes = torch.argmax(confidence, dim=1)\n scores = torch.max(confidence, dim=1).values\n nb_detected = confidence.shape[0]\n\n if MASKS_NAME in predictions.keys():\n masks = torch.from_numpy(predictions[MASKS_NAME]).view(-1, self.img_size[0], self.img_size[1])\n nb_detected = predictions[NUMBER_NAME][0]\n else:\n masks = None\n\n return yxyx.unsqueeze(0), classes.unsqueeze(0), scores.unsqueeze(0), masks, torch.Tensor([nb_detected])\n","repo_name":"SchweizerischeBundesbahnen/sbb-ml-models","sub_path":"converter/inference-python/python_model/coreml_model.py","file_name":"coreml_model.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"52"}
+{"seq_id":"17124035476","text":"from nornir_pyez.plugins.tasks import pyez_config, pyez_diff, pyez_commit\nfrom nornir import InitNornir\nfrom nornir_utils.plugins.functions import print_result\nfrom nornir.core.filter import F\nimport os\n\nscript_dir = os.path.dirname(os.path.realpath(__file__))\n\nnr = InitNornir(config_file=f\"{script_dir}/config.yml\")\n\njunos_devices = nr.filter(F(topo_type=\"PE\") | F(topo_type=\"P\"))\n\n\ndef rsvp_config(task):\n data = task.host.data\n net_response = task.run(task=pyez_config, template_path='/mnt/c/NornirJunos/mpls_proto.j2',\n template_vars=data, data_format='xml', name='Config RSVP')\n if net_response:\n diff = task.run(task=pyez_diff, name='RSVP diff')\n if diff:\n task.run(task=pyez_commit, name='RSVP commit')\n\n\nsend_result = junos_devices.run(\n task=rsvp_config)\nprint_result(send_result)\n","repo_name":"DataKnox/NornirJunos","sub_path":"deploy_mpls.py","file_name":"deploy_mpls.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"38270932654","text":"class Solution:\n def minCostConnectPoints(self, points: [[int]]) -> int:\n\n # Calcular peso de arestas\n def manhattan_distance(p1, p2):\n return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])\n\n # Estrutura union-find\n def find(parent, i):\n if parent[i] == i:\n return i\n return find(parent, parent[i])\n\n def union(parent, rank, i, j):\n iroot = find(parent, i)\n jroot = find(parent, j)\n if rank[iroot] < rank[jroot]:\n parent[iroot] = jroot\n elif rank[iroot] > rank[jroot]:\n parent[jroot] = iroot\n else:\n parent[iroot] = jroot\n rank[jroot] += 1\n\n n = len(points)\n edges = []\n\n # Indicar o peso relativo a cada aresta\n for i in range(n):\n for j in range(i + 1, n):\n distance = manhattan_distance(points[i], points[j])\n edges.append((distance, i, j))\n\n # Ordena as arestas com base no peso\n edges.sort()\n\n parent = list(range(n))\n rank = [0] * n\n total_cost = 0\n num_edges_added = 0\n\n # Kruskal\n for edge in edges:\n distance, u, v = edge\n if find(parent, u) != find(parent, v):\n union(parent, rank, u, v)\n total_cost += distance\n num_edges_added += 1\n if num_edges_added == n - 1:\n break\n\n return total_cost\n\ndef tests(points: [[int]]):\n solution = Solution()\n return solution.minCostConnectPoints(points)\n\nresult = tests([[0,0],[2,2],[3,10],[5,2],[7,0]])\nprint(result)","repo_name":"projeto-de-algoritmos/Grafos2_Exercicios_Resolvidos","sub_path":"exercicio3/min_cost_to_connect_all_points.py","file_name":"min_cost_to_connect_all_points.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"16291477966","text":"#!/usr/bin/env python3\n\nimport re\nfrom enum import Enum, auto\n\n# INPUT_FILE = 'input20.txt'\nINPUT_FILE = 'example20.txt'\n\ndef main():\n # unittest.main()\n text = get_text(INPUT_FILE)\n tiles = parse_text(text)\n # for tile_id, grid in tiles.items():\n # print(f'Tile {tile_id}:')\n # for row in grid:\n # print(''.join(row))\n # print()\n\n tile_id = next(iter(tiles))\n print(f'Tile {tile_id}')\n tile = tiles[tile_id]\n for row in tile:\n print(''.join(row))\n print()\n for direction in Direction:\n print(f'\\tDirection: {direction:15} => {\"\".join(get_edge(tile, direction))}')\n print()\n\n for tile_id in tiles:\n matching = find_matching_directions(tile_id, tiles)\n for direction, other_direction, other_tile_id in matching:\n print(f'{direction:15} side of {tile_id} matches {other_direction:15} side of {other_tile_id}')\n print()\n grid = assemble_image(tiles)\n for row in grid:\n print(' '.join(str(tile_id for tile_id in row)))\n\ndef get_text(filename):\n with open(filename) as f:\n return f.read().strip()\n\ndef parse_text(text):\n tiles_texts = text.split('\\n\\n')\n return dict(parse_tile(t) for t in tiles_texts)\n\nHEADER_RE = re.compile('Tile (\\d+):')\ndef parse_tile(text):\n lines = text.split('\\n')\n header = lines[0]\n tile_id = int(HEADER_RE.match(header).group(1))\n lines = lines[1:]\n grid = [list(row) for row in lines]\n return tile_id, grid\n \ndef assemble_image(tiles):\n matching_directions = {tile_id: find_matching_directions(tile_id, tiles) for tile_id in tiles}\n # for tile_id, rotations in matching_rotations.items():\n # print(f'Tile {tile_id}:')\n # for rotation, directions in rotations.items():\n # print(f'\\tRotation: {rotation}')\n # for direction, tile_ids in directions.items():\n # print(f'\\t\\tDirection: {direction}')\n # for tile_id in tile_ids:\n # print(f'\\t\\t\\tTile {tile_id}')\n # break\n remaining = set(tiles.keys())\n grid = [[]]\n num_tiles = len(tiles)\n for num_rows in divisors(num_tiles):\n num_columns = num_tiles // num_rows\n result = assemble_image_helper(tiles, matching_directions, remaining, grid, num_rows,\n num_columns, 0, 0)\n if result:\n return result\n raise Exception('No image found')\n\ndef assemble_image_helper(tiles, matching_directions, remaining, grid, num_rows, num_columns,\n row_index, column_index):\n if not remaining:\n return grid\n offset = row_index * num_columns + column_index\n print(f'{\" \" * offset}remaining: {remaining}')\n print(f'{\" \" * offset}grid: {grid}')\n next_column_index = (column_index + 1) % num_columns\n next_row_index = row_index + 1 if next_column_index == 0 else row_index\n if next_column_index == 0:\n grid.append([])\n for tile_id in remaining:\n tile = tiles[tile_id]\n next_remaining = set(remaining)\n next_remaining.remove(tile_id)\n next_grid = [r[:] for r in grid]\n row = next_grid[row_index]\n for rotation in range(len(Direction)):\n for flip_horizontal in [False, True]:\n for flip_vertical in [False, True]:\n if row_index > 0:\n above_tile_id, above_rotation, above_flip_h, above_flip_v = grid[row_index - 1][column_index]\n above_tile = tiles[above_tile_id]\n if not tiles_match(above_tile, above_rotation, above_flip_h, above_flip_v,\n tile, rotation, flip_horizontal, flip_vertical, Direction.DOWN):\n offset = row_index * num_columns + column_index\n print(f'{\" \" * offset}Tile #{tile_id} does not match tile above, #{above_tile_id}')\n continue\n if column_index > 0:\n left_tile_id, left_rotation, left_flip_h, left_flip_v = grid[row_index][column_index - 1]\n left_tile = tiles[left_tile_id]\n if not tiles_match(left_tile, left_rotation, left_flip_h, left_flip_v, tile,\n rotation, flip_horizontal, flip_vertical, Direction.DOWN):\n print(f'{\" \" * offset}Tile #{tile_id} does not match tile left, #{left_tile_id}')\n continue\n print(f'{\" \" * offset}Adding tile #{tile_id} with rotation {rotation} at row ' + \\\n f'{row_index} and column {column_index}')\n row.append((tile_id, rotation, flip_horizontal, flip_vertical))\n result = assemble_image_helper(tiles, matching_directions, next_remaining, next_grid,\n num_rows, num_columns, next_row_index, next_column_index)\n if result:\n return result\n del row[-1]\n\ndef tiles_match(tile1, rotation1, flip1_h, flip1_v, tile2, rotation2, flip2_h, flip2_v, direction):\n edge1 = get_rotated_edge(tile1, rotation1, flip1_h, flip1_v, direction)\n edge2 = get_rotated_edge(tile2, rotation2, flip2_h, flip1_v, direction.opposite())\n return edges_match(edge1, edge2)\n \ndef find_matching_directions(tile_id, tiles):\n tile = tiles[tile_id]\n matching = []\n for direction in Direction:\n edge = get_edge(tile, direction)\n for other_tile_id, other_tile in tiles.items():\n if other_tile_id == tile_id:\n continue\n for other_direction in Direction:\n other_edge = get_edge(other_tile, other_direction)\n if edges_match(edge, other_edge):\n matching.append((direction, other_direction, other_tile_id))\n return matching\n\ndef edges_match(edge1, edge2):\n return all(x == y for x, y in zip(edge1, reversed(edge2)))\n\ndef get_edge(tile, direction):\n return get_rotated_edge(tile, 0, False, False, direction)\n\ndef get_rotated_edge(tile, rotation, flip_h, flip_v, direction):\n reverse = False\n if direction == Direction.RIGHT or direction == Direction.LEFT:\n reverse = flip_h\n elif direction == Direction.UP or direction == Direction.DOWN:\n reverse = flip_v\n else:\n raise Exception(f'Non-exhaustive case for {direction}')\n direction = add_wrapping_to_enum(direction, rotation)\n if direction == Direction.RIGHT and not flip_h or direction == Direction.LEFT and flip_h:\n return [row[-1] for row in tile]\n elif direction == Direction.UP and not flip_v or direction == Direction.DOWN and flip_v:\n return tile[0]\n elif direction == Direction.LEFT and not flip_h or direction == Direction.RIGHT and flip_h:\n return [row[0] for row in reversed(tile)]\n elif direction == Direction.DOWN and not flip_v or direction == Direction.UP and flip_v:\n return list(reversed(tile[-1]))\n else:\n raise Exception(f'Non-exhaustive case for {direction}')\n\nclass Direction(Enum):\n RIGHT = auto()\n DOWN = auto()\n LEFT = auto()\n UP = auto()\n \n def rotation(self):\n return self.value - 1\n\n def opposite(self):\n return add_wrapping_to_enum(self, 2)\n\ndef divisors(num):\n return [x for x in range(1, num + 1) if num % x == 0]\n\ndef add_wrapping_to_enum(variant, add):\n cls = type(variant)\n zero_based_value = variant.value - 1\n zero_based_next_value = (zero_based_value + add) % len(cls)\n next_value = zero_based_next_value + 1\n return cls(next_value)\n\nif __name__ == '__main__':\n main()\n","repo_name":"HarrisonMc555/adventofcode","sub_path":"2020/day20a.py","file_name":"day20a.py","file_ext":"py","file_size_in_byte":7743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"71543596005","text":"from os import remove\n\nfrom firebase_admin import firestore\n\n\nfrom src.model.feedback_model import FeedbackModel\n\n\"\"\"service to manage feedback collection\"\"\"\n\n\nclass FeedbackService:\n def __init__(self):\n self.db = firestore.client()\n self.feedbacks_ref = self.db.collection(\"feedbacks\")\n\n \"\"\"add a new feedback\"\"\"\n\n def add(self, feedback: FeedbackModel):\n return self.feedbacks_ref.document().set(feedback.to_json())\n\n \"\"\"get list of feedback\"\"\"\n\n def get(self, search, rating):\n if rating == 0:\n query = self.feedbacks_ref.where(\"rating\", \"!=\", rating)\n else:\n query = self.feedbacks_ref.where(\"rating\", \"==\", rating)\n if search.replace(\" \", \"\") != \"\":\n query = query.where(\"prompt.message\", \">=\", search).where(\n \"prompt.message\", \"<=\", search + \"~\"\n )\n docs = query.stream()\n result = []\n for item in docs:\n item_data = item.to_dict()\n result.append({\"id\": item.id, \"data\": item_data})\n print(result)\n return result\n","repo_name":"SnowRobert/RisingBrain","sub_path":"src/service/feedback_service.py","file_name":"feedback_service.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"33997146560","text":"__author__ = [\"chrisholder\"]\n\nfrom typing import Tuple\n\nimport numpy as np\n\nfrom sktime.utils.numba.njit import njit\n\n\n@njit(fastmath=True)\ndef _dba_update(\n center: np.ndarray, X: np.ndarray, path_callable\n) -> Tuple[np.ndarray, float]:\n \"\"\"Perform an update iteration for dba.\n\n Parameters\n ----------\n center: np.ndarray (2d array of shape (m, p) where m is the number of dimensions\n and p is the number of time point)\n Time series that is the current center (or average).\n X : np.ndarray (3d array of shape (n, m, p) where n is number of instances, m\n is the dimensions and p is the timepoints))\n Time series instances compute average from.\n path_callable: Callable[Union[np.ndarray, np.ndarray], tuple[list[tuple], float]]\n Callable that returns the distance path.\n\n Returns\n -------\n np.ndarray (2d array of shape (m, p) where m is the number of dimensions and p is\n the number of time points.)\n The time series that is the computed average series.\n \"\"\"\n X_size, X_dims, X_timepoints = X.shape\n sum = np.zeros(X_timepoints)\n\n alignment = np.zeros((X_dims, X_timepoints))\n cost = 0.0\n for i in range(X_size):\n curr_ts = X[i]\n curr_alignment, _ = path_callable(curr_ts, center)\n for j, k in curr_alignment:\n alignment[:, k] += curr_ts[:, j]\n sum[k] += 1\n cost += np.linalg.norm(curr_ts[:, j] - center[:, k]) ** 2\n\n return alignment / sum, cost / X_timepoints\n","repo_name":"sktime/sktime","sub_path":"sktime/clustering/metrics/averaging/_dba_numba.py","file_name":"_dba_numba.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":7028,"dataset":"github-code","pt":"52"}
+{"seq_id":"10568785238","text":"def check(x):\r\n for i in range(2, x):\r\n if x % i == 0:\r\n return False\r\n return True\r\n\r\n\r\ndef check2(x):\r\n x = str(x)\r\n\r\n if x == x[::-1]:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nn = int(input())\r\n\r\n\r\nwhile 1:\r\n if check2(n) == True and check(n) == True and n != 1:\r\n break\r\n\r\n else:\r\n n += 1\r\n\r\n\r\nprint(n)","repo_name":"MinHyukSeok/Algorithm_Solved","sub_path":"백준/Silver/1747. 소수&팰린드롬/소수&팰린드롬.py","file_name":"소수&팰린드롬.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21529461928","text":"import numpy as np\nimport matplotlib.pyplot as plt\npraise_the_sun = np.linspace(0, 1, 100000)\ndef jeg_er_trott(tuppelupp1,tuppelupp2,t = praise_the_sun):\n \n swaggy_boy_jesus = t * tuppelupp1[0] + (1 - t) * tuppelupp2[0]\n swaggy_boy_judas = t * tuppelupp1[1] + (1 - t) * tuppelupp2[1]\n return (swaggy_boy_jesus, swaggy_boy_judas)\n\n\nplt.plot(jeg_er_trott((1,1),(1,2))[0],jeg_er_trott((1,1),(1,2))[1], label = \"VERTIKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL\")\nplt.plot(jeg_er_trott((1,1),(2,1))[0],jeg_er_trott((1,1),(2,1))[1], label = \"HORISONTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL\")\nplt.legend()\nplt.xlabel(\"OH LAWD HE COMIN (x-posisjon)\")\nplt.ylabel(\"HERE COME DAT BOI. OH SHIT WADDUP! (y-posisjon)\")\nplt.show()\n\n\"\"\"\nrunning example:\nI get that gucci graph\n\"\"\"\n\"\"\"\nI'm brutally tired and can't really get my head to do the b assignment.\nTo do it I would make a loop that would traverse a list of tuples of points and plot them.\n\"\"\"","repo_name":"MrMelk/IN1900","sub_path":"Oblig6/graph1.py","file_name":"graph1.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7253072413","text":"import bs4\n\nfrom lxml import html\nfrom django.conf import settings\nfrom scrapy.spiders import Spider\nfrom scrapy.http.request import Request\nfrom scrapy.http.response import Response\n\nfrom resources.models import Company\nfrom utils.web.scrapy import parse_symbols_or_indexes_argument\nfrom .extras.shareholders_item import TseTmcShareholdersItem, TseTmcShareholdersLoader\n\n\nclass TseTmcShareholdersSpider(Spider):\n \"\"\"\n Uses one urls, which needs isin (tsetmc_instrument_id).\n - Uses one request per url.\n Output: list[dict]\n Dictionary Keys: tsetmc_index, shareholder_id, shareholder_name, number_of_shares, shares_percentage, change\n \"\"\"\n\n name = 'tsetmc_shareholders_spider'\n allowed_domains = ['tsetmc.com', 'tsetmc.ir']\n\n custom_settings = {\n 'ITEM_PIPELINES':\n {'scrapy_scrapers.spiders.tsetmc.extras.shareholders_pipeline.TseTmcShareholdersPipeline': 300}\n }\n\n URL = settings.TSE_STOCK_SHAREHOLDERS_DATA_URL\n\n def __init__(self, *a, indexes: list = None, **kw):\n super().__init__(*a, **kw)\n self.indexes = parse_symbols_or_indexes_argument(indexes)\n\n @classmethod\n def format_url(cls, ci_sin: str):\n return cls.URL.format(ci_sin=ci_sin)\n\n def start_requests(self):\n ci_sins = Company.objects.all() if self.indexes == 'all' else Company.objects. \\\n filter(tsetmc_index__in=self.indexes)\n ci_sins = ci_sins.exclude(isin__exact=str()).values_list('tsetmc_index', 'ci_sin')\n for index, isin in ci_sins:\n url = self.format_url(isin)\n yield Request(url=url, callback=self.parse, cb_kwargs={'index': index})\n\n def parse(self, response: Response, **kwargs):\n index = response.cb_kwargs['index']\n soup = bs4.BeautifulSoup(response.body, 'html.parser')\n doc: html.HtmlElement = html.document_fromstring(str(soup))\n items: list[TseTmcShareholdersItem] = list()\n rows = doc.xpath('//body//table/tbody/tr')\n for row in rows:\n loader = TseTmcShareholdersLoader()\n loader.add_value('tsetmc_index', index)\n\n if 'onclick' not in row.attrib:\n continue\n sh_id = row.attrib['onclick']\n sh_id = sh_id[sh_id.find(\"'\") + 1: sh_id.find(\",\")]\n loader.add_value('shareholder_id', sh_id)\n\n tds = row.xpath('./td')\n shareholder_name = tds[0].text_content().strip()\n loader.add_value('shareholder_name', shareholder_name)\n shares_percentage = tds[2].text_content().strip()\n loader.add_value('shares_percentage', shares_percentage)\n\n number_of_shares = tds[1].xpath('./div')\n if not len(number_of_shares) or 'title' not in number_of_shares[0].attrib:\n continue\n number_of_shares = number_of_shares[0].attrib['title']\n loader.add_value('number_of_shares', number_of_shares)\n\n change = tds[3].xpath('./div')\n if len(change) and 'title' in number_of_shares[0].attrib:\n change = change.attrib['title']\n loader.add_value('change', change)\n\n item = loader.load_item()\n items.append(item)\n\n for item in items:\n yield item\n","repo_name":"mrafee113/Stocker","sub_path":"scrapy_scrapers/scrapy_scrapers/spiders/tsetmc/shareholders_spider.py","file_name":"shareholders_spider.py","file_ext":"py","file_size_in_byte":3261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74783685605","text":"from cubicweb import _\n\nfrom logilab.mtconverter import xml_escape\nfrom logilab.common.registry import yes\nfrom logilab.common.deprecation import class_renamed\n\nfrom cubicweb.predicates import (match_context, configuration_values,\n anonymous_user, authenticated_user)\nfrom cubicweb.utils import wrap_on_write\nfrom cubicweb.uilib import toggle_action\nfrom cubicweb.web import component\nfrom cubicweb.web.htmlwidgets import MenuWidget, PopupBoxMenu\n\nVISIBLE_PROP_DEF = {\n _('visible'): dict(type='Boolean', default=True,\n help=_('display the component or not')),\n }\n\nclass RQLInputForm(component.Component):\n \"\"\"build the rql input form, usually displayed in the header\"\"\"\n __regid__ = 'rqlinput'\n cw_property_defs = VISIBLE_PROP_DEF\n visible = False\n\n def call(self, view=None):\n req = self._cw\n if hasattr(view, 'filter_box_context_info'):\n rset = view.filter_box_context_info()[0]\n else:\n rset = self.cw_rset\n # display multilines query as one line\n rql = rset is not None and rset.printable_rql() or req.form.get('rql', '')\n rql = rql.replace(u\"\\n\", u\" \")\n rql_suggestion_comp = self._cw.vreg['components'].select_or_none('rql.suggestions', self._cw)\n if rql_suggestion_comp is not None:\n # enable autocomplete feature only if the rql\n # suggestions builder is available\n self._cw.add_css('jquery.ui.css')\n self._cw.add_js(('cubicweb.ajax.js', 'jquery.ui.js'))\n self._cw.add_onload('$(\"#rql\").autocomplete({source: \"%s\"});'\n % (req.build_url('json', fname='rql_suggest')))\n self.w(u'''')\n\n\n\nclass HeaderComponent(component.CtxComponent): # XXX rename properly along with related context\n \"\"\"if the user is the anonymous user, build a link to login else display a menu\n with user'action (preference, logout, etc...)\n \"\"\"\n __abstract__ = True\n cw_property_defs = component.override_ctx(\n component.CtxComponent,\n vocabulary=['header-center', 'header-left', 'header-right', ])\n # don't want user to hide this component using an cwproperty\n site_wide = True\n context = _('header-center')\n\n\nclass ApplLogo(HeaderComponent):\n \"\"\"build the instance logo, usually displayed in the header\"\"\"\n __regid__ = 'logo'\n __select__ = yes() # no need for a cnx\n order = -1\n context = _('header-left')\n\n def render(self, w):\n w(u'' % self._cw.base_url())\n\n\nclass ApplicationName(HeaderComponent):\n \"\"\"display the instance name\"\"\"\n __regid__ = 'appliname'\n\n # XXX support kwargs for compat with other components which gets the view as\n # argument\n def render(self, w, **kwargs):\n title = self._cw.property_value('ui.site-title')\n if title:\n w(u'%s' % (\n self._cw.base_url(), xml_escape(title)))\n\n\nclass CookieLoginComponent(HeaderComponent):\n __regid__ = 'anonuserlink'\n __select__ = (HeaderComponent.__select__ & anonymous_user()\n & configuration_values('auth-mode', 'cookie'))\n context = 'header-right'\n loginboxid = 'popupLoginBox'\n _html = u\"\"\"%s\"\"\"\n\n def render(self, w):\n # XXX bw compat, though should warn about subclasses redefining call\n self.w = w\n self.call()\n\n def call(self):\n self._cw.add_css('cubicweb.pictograms.css')\n self.w(self._html % (self._cw._('login / password'),\n self.loginboxid, self._cw._('i18n_login_popup')))\n self._cw.view('logform', rset=self.cw_rset, id=self.loginboxid,\n klass='%s hidden' % self.loginboxid, title=False,\n showmessage=False, w=self.w)\n\n\nclass HTTPLoginComponent(CookieLoginComponent):\n __select__ = (HeaderComponent.__select__ & anonymous_user()\n & configuration_values('auth-mode', 'http'))\n\n def render(self, w):\n # this redirects to the 'login' controller which in turn\n # will raise a 401/Unauthorized\n req = self._cw\n w(u'[%s]'\n % (req._('login / password'), req.build_url('login'), req._('login')))\n\n\n_UserLink = class_renamed('_UserLink', HeaderComponent)\nAnonUserLink = class_renamed('AnonUserLink', CookieLoginComponent)\nAnonUserLink.__abstract__ = True\nAnonUserLink.__select__ &= yes(1)\n\n\nclass AnonUserStatusLink(HeaderComponent):\n __regid__ = 'userstatus'\n __select__ = anonymous_user()\n context = _('header-right')\n order = HeaderComponent.order - 10\n\n def render(self, w):\n pass\n\nclass AuthenticatedUserStatus(AnonUserStatusLink):\n __select__ = authenticated_user()\n\n def render(self, w):\n # display useractions and siteactions\n self._cw.add_css('cubicweb.pictograms.css')\n actions = self._cw.vreg['actions'].possible_actions(self._cw, rset=self.cw_rset,\n view=self.cw_extra_kwargs['view'])\n box = MenuWidget('', 'userActionsBox', _class='', islist=False)\n menu = PopupBoxMenu(self._cw.user.login, isitem=False, link_class='icon-user')\n box.append(menu)\n for action in actions.get('useractions', ()):\n menu.append(self.action_link(action))\n if actions.get('useractions') and actions.get('siteactions'):\n menu.append(self.separator())\n for action in actions.get('siteactions', ()):\n menu.append(self.action_link(action))\n box.render(w=w)\n\n\nclass ApplicationMessage(component.Component):\n \"\"\"display messages given using the __message/_cwmsgid parameter into a\n special div section\n \"\"\"\n __select__ = yes()\n __regid__ = 'applmessages'\n # don't want user to hide this component using a cwproperty\n cw_property_defs = {}\n\n def call(self, msg=None):\n if msg is None:\n msg = self._cw.message # XXX don't call self._cw.message twice\n self.w(u'\\n' %\n (toggle_action('appMsg'), (msg and ' ' or 'hidden')))\n self.w(u'
%s
' % (self.domid, msg))\n self.w(u'
')\n\n\n# contextual components ########################################################\n\n\nclass MetaDataComponent(component.EntityCtxComponent):\n __regid__ = 'metadata'\n context = 'navbottom'\n order = 1\n\n def render_body(self, w):\n self.entity.view('metadata', w=w)\n\n\nclass SectionLayout(component.Layout):\n __select__ = match_context('navtop', 'navbottom',\n 'navcontenttop', 'navcontentbottom')\n cssclass = 'section'\n\n def render(self, w):\n if self.init_rendering():\n view = self.cw_extra_kwargs['view']\n w(u'' % (self.cssclass, view.cssclass,\n view.domid))\n with wrap_on_write(w, '
') as wow:\n view.render_title(wow)\n view.render_body(w)\n w(u'
\\n')\n","repo_name":"gurneyalex/cubicweb","sub_path":"cubicweb/web/views/basecomponents.py","file_name":"basecomponents.py","file_ext":"py","file_size_in_byte":7809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"72231918246","text":"\"\"\"testerServer URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/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\"\"\"\n\nfrom django.urls import path\n\nfrom modules.funcition.case.views import CaseList, CaseUpdate, UploadFile, AssignCase, CaseOperation, DeleteCase, \\\n UpdateCaseOperation, TaskDetails, QuestionList, UpdateProblemCase, deleteQuestion, AssignDelete, AssignCaseOperation\n\nurlpatterns = [\n path('list', CaseList.as_view()),\n path('update', CaseUpdate.as_view()),\n path('upload', UploadFile.as_view()),\n path('assign', AssignCase.as_view()),\n path('operation', CaseOperation.as_view()),\n path('assignCase', AssignCaseOperation.as_view()),\n path('updateCase', UpdateCaseOperation.as_view()),\n path('deleteCase', DeleteCase.as_view()),\n path('taskDetails', TaskDetails.as_view()),\n path('updateProblemCase', UpdateProblemCase.as_view()),\n path('problemCase', QuestionList.as_view()),\n path('problemCase/', deleteQuestion.as_view()),\n path('assignDelete', AssignDelete.as_view()),\n]\n","repo_name":"liubox98/platform-server","sub_path":"modules/funcition/case/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"17138940766","text":"import tkinter as tk\nimport numpy as np\nfrom tkvideo import tkvideo\nfrom tkinter import ttk\nimport os\nimport sys\nsys.path.append('./src/tests')\nsys.path.append('./src/v1')\nfrom model1 import Model1\nfrom test_v1 import Tests\nimport copy\n\nclass View(object):\n\n sceneTemp = {\n \"title\": \"N-Body Gravitational Simulation - David René\",\n \"data\": [],\n \"size\": (600, 200)\n }\n\n def __init__(self):\n self.root = tk.Tk()\n self.history = []\n self.width = 600\n self.height = 200\n self.sceneLst = []\n self.root.geometry(f\"{self.width}x{self.height}\")\n\n btn_back = ttk.Button(self.root, text=\"Back\", width=20, command=lambda: self.back())\n\n lbl_select = ttk.Label(self.root, text=\"Please select a case study:\")\n btn_lagrange = ttk.Button(self.root, text=\"Lagrange points\", width=20, command=lambda: self.Lagrange())\n btn_galaxy = ttk.Button(self.root, text=\"Galaxy collision\", width=20, command=self.Galaxy)\n btn_test = ttk.Button(self.root, text=\"Run tests\", width=20, command=self.Tests)\n menu_scene = copy.deepcopy(self.sceneTemp)\n menu_scene['data'] = [lbl_select, btn_lagrange, btn_galaxy, btn_test]\n self.sceneLst.append(menu_scene)\n\n frame_lagrange = tk.Frame(self.root)\n lbl_lagrange = ttk.Label(self.root, text=\"Which Lagrange point would you like to observe?\")\n ttk.Button(frame_lagrange, text=\"L2\", width=20, command=self.L2).grid(row=0, column=0)\n ttk.Button(frame_lagrange, text=\"L4\", width=20, command=self.L4).grid(row=0, column=1)\n lagrange_scene1 = copy.deepcopy(self.sceneTemp)\n lagrange_scene1['data'] = [lbl_lagrange, frame_lagrange, btn_back]\n lagrange_scene1['title'] = \"Lagrange points - David René\"\n self.sceneLst.append(lagrange_scene1)\n\n frame_L2 = tk.Frame(self.root)\n tk.Canvas(frame_L2, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n L2_scene = copy.deepcopy(self.sceneTemp)\n L2_scene['data'] = [frame_L2, btn_back]\n L2_scene['title'] = \"L2 Observation - David René\"\n L2_scene['size'] = (600, 500)\n self.sceneLst.append(L2_scene)\n\n frame_L4 = tk.Frame(self.root)\n tk.Canvas(frame_L4, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n L4_scene = copy.deepcopy(self.sceneTemp)\n L4_scene['data'] = [frame_L4, btn_back]\n L4_scene['title'] = \"L4 Observation - David René\"\n L4_scene['size'] = (600, 500)\n self.sceneLst.append(L4_scene)\n\n frame_galaxy = tk.Frame(self.root)\n tk.Canvas(frame_galaxy, width=600, height=400).pack(anchor=tk.CENTER, expand=True)\n galaxy_scene = copy.deepcopy(self.sceneTemp)\n galaxy_scene['data'] = [frame_galaxy, btn_back]\n galaxy_scene['title'] = \"Galaxy Collision - David René\"\n galaxy_scene['size'] = (600, 500)\n self.sceneLst.append(galaxy_scene)\n\n self.build(menu_scene)\n self.root.mainloop()\n\n def Lagrange(self):\n self.build(self.sceneLst[1])\n\n def L2(self):\n self.build(self.sceneLst[2])\n\n def L4(self):\n self.build(self.sceneLst[3])\n \n def Galaxy(self):\n self.build(self.sceneLst[4])\n \n def Tests(self):\n os.system('python3 -m unittest ./src/tests/test_v1.py')\n\n def setGeo(self, size):\n self.width = size[0]\n self.height = size[1]\n self.root.geometry(f\"{self.width}x{self.height}\")\n\n def build(self, endScene, back=False):\n if len(self.history) == 0:\n startScene = None\n else:\n startScene = self.history[-1]\n if not back:\n self.history.append(endScene)\n if startScene is not None:\n for widget in startScene['data']:\n widget.pack_forget()\n self.setGeo(endScene['size'])\n self.root.title(endScene['title'])\n for widget in endScene['data']:\n widget.pack(anchor=tk.CENTER, expand=True)\n \n return endScene\n\n def back(self):\n prev_scene = self.history[-2]\n self.build(prev_scene, back=True)\n self.history.pop(-1)\n\n \nif __name__ == \"__main__\":\n view = View()\n\n\n\n\n\n","repo_name":"davidreneuw/PHYS349-nbody","sub_path":"src/view/view_v1.py","file_name":"view_v1.py","file_ext":"py","file_size_in_byte":4223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"21432740288","text":"\"\"\"\nbattle.py\nMade by lapyo and Sikanaama\n\"\"\"\nimport random\nimport re\nimport sopel.module\n\nNORRIS = re.compile(r'chuck norris', re.I)\n\n@sopel.module.commands('battle')\ndef battle(bot, trigger):\n group = trigger.group(2)\n if not group:\n bot.say('Tarttis parametrejä')\n return\n \n query = re.split(r',\\W*', group.strip())\n if len(query) < 2:\n bot.say('Tarttis enemmän parametrejä')\n return\n\n weights = []\n weight = 0\n for x in range(len(query)):\n word = query[x]\n if NORRIS.match(word):\n answer = ', '.join(['%s: %d%%' % (query[i], 100 if i is x else 0) for i in range(len(query))])\n bot.say(answer)\n return\n rand = random.random()\n weights.append(rand)\n weight += rand\n \n values = []\n total = 0\n for w in weights:\n value = round(w / weight * 100)\n values.append(value)\n total += value\n \n # Rounding percentages might cause total to be 101, let's\n # snatch it from the greatest value (these are random after all) :P\n if total > 100:\n max = 0\n i = 0\n for x in range(len(values)):\n v = values[x]\n if v > max:\n max = v\n i = x\n values[i] -= total - 100\n \n answer = '%s ' % trigger.nick\n answer += ', '.join(['%s: %d%%' % (query[x], values[x]) for x in range(len(query))])\n bot.say(answer)\n","repo_name":"pulinairc/kummitus","sub_path":"modules/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"4396580419","text":"import os\nimport numpy as np\nfrom data_settings import DataSettings\n\nclass ModelSettings(DataSettings):\n\n def __init__(self):\n super(ModelSettings, self).__init__()\n\n self.MEAN = [0.485, 0.456, 0.406]\n self.STD = [0.229, 0.224, 0.225]\n self.IMAGE_SIZE_HEIGHT = 256\n self.IMAGE_SIZE_WIDTH = 256\n self.ANNOTATION_SIZE_HEIGHT = 256\n self.ANNOTATION_SIZE_WIDTH = 256\n\n self.HORIZONTAL_FLIPPING = True\n self.RANDOM_CROPPING = False # CROP_SCALE and CROP_AR is used iff self.RANDOM_CROPPING is True\n self.CROP_SCALE = (0.8, 1.0) # Choose it carefully - have a look at lib/preprocess.py -> RandomResizedCrop\n self.CROP_AR = (3. / 4., 4. / 3.) # Choose it carefully - have a look at lib/preprocess.py -> RandomResizedCrop\n","repo_name":"Wizaron/reseg-pytorch","sub_path":"code/pytorch/settings/model_settings.py","file_name":"model_settings.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"52"}
+{"seq_id":"28137662221","text":"from google.appengine.api import memcache\nfrom google.appengine.ext import ndb\nimport logging\nfrom apiMethods import examOpened\n\n\nlogging.basicConfig(level=logging.DEBUG)\nLOG = logging.getLogger(__name__)\nLOG.info(str(examOpened))\n\nfor urlsafeId in examOpened:\n examId = ndb.Key(urlsafe=urlsafeId)\n exam = examId.get()\n views = memcache.get('views' + urlsafeId)\n if views is not None:\n exam.examViews = views\n exam.put()\n else:\n memcache.add('views' + urlsafeId, exam.examViews)\nexamOpened.clear()\n","repo_name":"yp-palF/NotesCC","sub_path":"cronTasks/updateExam.py","file_name":"updateExam.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"24192322697","text":"from lib.globals import *\nfrom lib.exceptions import *\nfrom functools import wraps\nfrom copy import deepcopy\nimport requests\n\n# NOTE: Usage notes below.\n'''\n# Creating API Calls\n\n## The call Decorator\n\nThis decorator handles repetitive code.\n\nArguments:\n\n - path: The GitLab URL path that will be requested.\n - paginate: A boolean that determines if respones should be\n paginated, causing the method will behave as a generator.\n - rest_params: A dictionary that specifies the valid types\n for a given rest parameter.\n\n# Making Calls\n\n## Passing Standard Params and Data to API Calls\n\nREST parameters aside, all data and parameters are passed directly\nto the requests library for handling.\n\n## Passing Arguments to REST Parameters\n\nWhen making calls to Session objects, it will likely be necessary\nto pass arguments to REST parameters within the URI. This is\nachieved by passing a \"rest_params\" keyword argument to the method.\n\nExample:\n\nsession.revokeProjectAccessToken(\n rest_params={\n 'project_id': 7,\n 'token_id': 33})\n'''\n\nAPI_BASE = GITLAB_API_URL\n\nclass RTypes:\n\n project_id = user_id = token_id = key_id = int\n\n @classmethod\n def getTypes(cls, *handles):\n \n invalid_handles, types = [], {}\n for handle in handles:\n\n if not type(handle) == str:\n invalid_handles.append('{}: handle must be a string, got {}',\n str(handle), type(handle))\n elif not hasattr(cls, handle):\n invalid_handles.append('{}: Unknown handle.', handle)\n else:\n types[handle] = getattr(cls, handle)\n\n if invalid_handles:\n\n raise ValueError(\n 'Invalid type handles supplied: '\n f'{\" -- \".join(invalid_handles)}')\n\ndef checkResponse(resp):\n\n if resp.status_code == 403:\n\n # =======================\n # INSUFFICIENT PRIVILEGES\n # =======================\n\n raise InsufficientPrivileges(\n 'Insufficient privileges for token: '\n f'{resp.json()}')\n\n elif resp.status_code == 204:\n\n # ===================\n # NO CONTENT RETURNED\n # ===================\n\n setattr(resp, 'json', lambda: {})\n\n elif resp.status_code > 400:\n\n raise RequestError(\n f'Response status code {resp.status_code} indicates an error: '\n 'https://docs.gitlab.com/ee/api/#status-codes')\n\n return resp\n\ndef getNextURL(resp):\n return resp.links.get('next', {}) \\\n .get('url', None)\n\ndef prepareParams(rest_params, rest_args, kwargs) -> (dict, dict,):\n '''Initialize and return the parameters.\n '''\n\n # Ensure that a dictionary is always supplied to\n # rest_params\n rest_params = rest_params if rest_params else {}\n rest_args = rest_args if rest_args else {}\n\n # ================================\n # PERFORM CHECKS ON REST ARGUMENTS\n # ================================\n\n value_errors = {}\n\n for name, types in rest_params.items():\n\n # =======================================\n # ENSURE THAT REST ARGUMENTS ARE SUPPLIED\n # =======================================\n\n if not name in rest_args:\n\n value_errors[name] = (\n f'{name}: Requires a value of the following types > '\n f'{types}')\n\n else:\n\n # =====================\n # ENFORCE TYPE CHECKING\n # =====================\n\n if not isinstance(rest_args[name], types):\n\n value_errors[name] = (\n f'{name}: Requires a value of the following '\n f'types > {types}. Got {type(rest_args[\"name\"])}')\n\n if value_errors:\n\n # ==================\n # RAISE AN EXCEPTION\n # ==================\n\n msg = ''\n\n for name, error in value_errors.items():\n if not msg:\n msg = error\n else:\n msg += ' ' + error\n\n raise ValueError(msg)\n\n # Ensure a dictionary is always supplied to the\n # params value within kwargs.\n if not kwargs.get('params', None):\n kwargs['params']={}\n\n return rest_args, kwargs\n\ndef call(path, paginate=False, rest_params=None):\n '''Wrap a Session method such that it will receive a URI value\n with updated REST parameters, followed by making the request\n and returning/yielding the response from the Session object.\n\n Args:\n path: String path for the API call.\n paginate: Determines if this decorator should behave as\n a generator.\n '''\n\n # Ensure path is prefixed with a slash\n if not path[0] == '/':\n path = '/'+path\n\n _rest_params = rest_params if rest_params else {}\n\n def outer(method):\n\n if paginate:\n\n # ============\n # YIELDS PAGES\n # ============\n\n @wraps(method)\n def wrapper(obj, rest_params=None, *args, **kwargs):\n \n rest_params, kwargs = prepareParams(_rest_params,\n rest_params, kwargs)\n\n # Get the initial response\n uri = API_BASE+path.format(**rest_params) \n resp = checkResponse(method(obj, uri, *args, **kwargs))\n\n # yield the initial response\n if obj.json_output:\n yield resp.json()\n else:\n yield resp\n \n # get the next url from the links within the response\n # object\n next_url = getNextURL(resp)\n \n # yield each subsequent request\n while next_url is not None:\n\n resp = obj.get(next_url)\n\n if obj.json_output:\n yield resp.json()\n else:\n yield resp\n\n next_url = getNextURL(resp)\n\n else:\n\n # ============================\n # RETURNS INDIVIDUAL RESPONSES\n # ============================\n\n @wraps(method)\n def wrapper(obj, rest_params=None,\n *args, **kwargs):\n \n rest_params, kwargs = prepareParams(_rest_params,\n rest_params,\n kwargs)\n \n # Call the method and return the response\n resp = checkResponse(method(obj,\n API_BASE+path.format(**rest_params),\n *args, **kwargs))\n\n if obj.json_output:\n return resp.json()\n else:\n return resp\n \n return wrapper\n\n return outer\n\nclass Session(requests.Session):\n\n def __init__(self, token, json_output=False, *args, **kwargs):\n '''Initialize a Session object by accepting a token and\n binding it as an instance variable.\n\n Args:\n token: Authorization token used to authenticate to the\n GitLab API.\n json_output: Determines if all output from API calls should\n be returned as JSON objects instead of a response object.\n\n Notes:\n - The last_resp attribute will always hold the most recent\n response object.\n '''\n\n super().__init__(*args, **kwargs)\n self.token = token\n self.json_output = json_output\n self.last_resp = None\n self.headers.update({'PRIVATE-TOKEN': self.token})\n\n def request(self, url, *args, **kwargs):\n '''Override the request method such that the proper authorization\n header is always sent to the API.\n '''\n\n # Make the request\n self.last_resp = super().request(url, *args, **kwargs)\n return self.last_resp\n\n def search(self, uri, *args, **kwargs):\n '''Query GitLab's search endpoint.\n\n Notes:\n - https://docs.gitlab.com/ee/api/search.html\n '''\n\n return self.get(uri, *args, **kwarg)\n\n def findProject(self, repo_name, repo_https_url) -> dict:\n '''Find a project based on repository name while verifying\n that the proper project has been identified by comparing\n the \"http_url_to_repo\" member to repo_https_url.\n\n Args:\n repo_name: Repo name to search for.\n repo_https_url: Full URL to the repository, for validation.\n\n Returns:\n Dictionary object representing the project, as returned\n by the GitLab API.\n\n Notes:\n - Unlike other API calls, this call will always return\n a dict object.\n '''\n\n if not repo_https_url.endswith('.git'):\n repo_https_url += '.git'\n\n json_output = self.json_output\n self.json_output = True\n output = {}\n\n for page in self.iterProjects(params={'search':repo_name}):\n\n for proj in page:\n if proj['http_url_to_repo'] == repo_https_url:\n output = proj\n break\n\n self.json_output = json_output\n\n return output\n\n @call(path='/projects/{project_id}/access_tokens/{token_id}',\n rest_params=RTypes.getTypes('project_id', 'token_id'))\n def revokeProjectAccessToken(self, uri, *args, **kwargs):\n '''Revoke a project access token.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#revoke-a-project-access-token\n '''\n\n return self.delete(uri, *args, **kwargs)\n\n @call(path='/users', paginate=True)\n def iterAllUsers(self, uri, *args, **kwargs):\n '''Generator that iterates over all GitLab users.\n\n Notes:\n - https://docs.gitlab.com/ee/api/users.html#list-users\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/access_tokens',\n paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterProjectAccessTokens(self, uri, *args, **kwargs):\n '''Generator that iterates over all Project Access Tokens for\n a given GitLab project.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#list-project-access-tokens\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/deploy_keys', paginate=True)\n def iterDeployKeys(self, uri, *args, **kwargs):\n '''Paginate over all deploy keys configured in GitLab.\n\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#list-all-deploy-keys\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys',\n paginate=True, rest_params=RTypes.getTypes('project_id'))\n def iterProjectDeployKeys(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#list-project-deploy-keys\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys/{key_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def updateProjectDeployKey(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#update-deploy-key\n '''\n\n return self.put(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/deploy_keys/{key_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def deleteProjectDeployKey(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/deploy_keys.html#update-deploy-key\n '''\n\n return self.delete(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}',\n rest_params=RTypes.getTypes('project_id', 'key_id'))\n def getProject(self, uri, *args, **kwargs):\n '''Get an individual project from the GitLab API.\n\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#get-single-project\n '''\n \n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/repository/tree',\n rest_params=RTypes.getTypes('project_id'), paginate=True)\n def iterProjectRepoTree(self, uri, *args, **kwargs):\n '''Get a list of files from the repository.\n\n Notes:\n - https://docs.gitlab.com/ee/api/repositories.html#list-repository-tree\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/groups', paginate=True)\n def iterGroups(self, uri, *args, **kwargs):\n '''Generator that iterates over all GitLab groups.\n Notes:\n - https://docs.gitlab.com/ee/api/groups.html#list-groups\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/share',\n rest_params=RTypes.getTypes('project_id'))\n def shareProjectWithGroup(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#share-project-with-group\n '''\n\n return self.post(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members',\n rest_params=RTypes.getTypes('project_id'))\n def addMemberToProject(self, uri, *args, **kwargs):\n '''\n Note:\n - https://docs.gitlab.com/ee/api/members.html#add-a-member-to-a-group-or-project\n '''\n\n return self.post(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/access_tokens',\n rest_params=RTypes.getTypes('project_id'))\n def getProjectAccesstokens(self, uri, *args, **kwargs):\n '''Get all access tokens configured for a project.\n\n Notes:\n - https://docs.gitlab.com/ee/api/resource_access_tokens.html#list-project-access-tokens\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects', paginate=True)\n def iterProjects(self, uri, *args, **kwargs):\n '''Return a generator that iterates through each project in\n the GitLab instance.\n\n Notes:\n - https://docs.gitlab.com/ee/api/projects.html#list-all-projects\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members', paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterProjectMembers(self, uri, *args, **kwargs):\n '''Return a generateor that iterates over each member of the\n project identified by the project_id REST parameter.\n\n Notes:\n - This does not return inhertied group members.\n - https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members/all', paginate=True,\n rest_params=RTypes.getTypes('project_id'))\n def iterAllProjectMembers(self, uri, *args, **kwargs):\n '''Return a generateor that iterates over each member of the\n project identified by the project_id REST parameter.\n\n Notes:\n - This differs from iterProjectMembers by including inherited\n group members as well.\n - https://docs.gitlab.com/ee/api/members.html#list-all-members-of-a-group-or-project\n '''\n\n return self.get(uri, *args, **kwargs)\n\n @call(path='/projects/{project_id}/members/{user_id}',\n rest_params=RTypes.getTypes('project_id', 'user_id'))\n def updateProjectMember(self, uri, *args, **kwargs):\n '''\n Notes:\n - https://docs.gitlab.com/ee/api/members.html#edit-a-member-of-a-group-or-project\n '''\n\n return self.put(uri, *args, **kwargs)\n","repo_name":"ImpostorKeanu/sec-vault-gen","sub_path":"lib/gitlab.py","file_name":"gitlab.py","file_ext":"py","file_size_in_byte":15643,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"52"}
+{"seq_id":"45121291857","text":"import cv2\nimport mediapipe as mp\nimport numpy as np\nimport pickle\nimport json\nfrom flask import Flask, render_template, request, Response\nimport nltk\nimport time\n\n# For Filtring wrords\nnltk.download('wordnet')\nnltk.download('punkt')\nnltk.download('stopwords')\nwnl = nltk.stem.WordNetLemmatizer()\n\n# From Sign To Text\n# Load the saved SVM model\nwith open('model.pkl', 'rb') as f:\n svm = pickle.load(f)\n\n# Initialize the Flask app\napp = Flask(__name__)\n\n# Define the server's route\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n@app.route('/home')\ndef home():\n return render_template('home.html')\n\n# Initialize an empty list to store the prediction results\npredictions = []\n\n# Define the function to process the hand image and make predictions\ndef image_processed(hand_img):\n # Convert BGR to RGB\n img_rgb = cv2.cvtColor(hand_img, cv2.COLOR_BGR2RGB)\n\n # Flip the image in Y-axis\n img_flip = cv2.flip(img_rgb, 1)\n\n # Accessing MediaPipe solutions\n mp_hands = mp.solutions.hands\n\n # Initialize Hands\n hands = mp_hands.Hands(static_image_mode=True, max_num_hands=2, min_detection_confidence=0.7)\n\n # Process the image\n output = hands.process(img_flip)\n\n # Close the Hands object\n hands.close()\n\n try:\n # Extract the hand landmarks from the output\n data = output.multi_hand_landmarks[0]\n data = str(data)\n data = data.strip().split('\\n')\n\n # Remove the unnecessary information from the landmark data\n garbage = ['landmark {', ' visibility: 0.0', ' presence: 0.0', '}']\n without_garbage = []\n for i in data:\n if i not in garbage:\n without_garbage.append(i)\n\n clean = []\n for i in without_garbage:\n i = i.strip()\n clean.append(i[2:])\n\n for i in range(0, len(clean)):\n clean[i] = float(clean[i])\n\n # Return the cleaned hand landmark data\n return(clean)\n except:\n # If no hand landmarks are detected, return an array of zeros\n return(np.zeros([1,63], dtype=int)[0])\n\n# Define the video capture function\ndef generate_frames():\n # Initialize the video capture\n cap = cv2.VideoCapture(0)\n\n # Loop over the frames from the video stream\n while True:\n # Read a frame from the video stream\n success, frame = cap.read()\n\n if not success:\n break\n frame = cv2.flip(frame,1)\n # Process the frame to get the hand landmarks\n hand_landmarks = image_processed(frame)\n\n # Use the SVM to make a prediction based on the landmarks\n prediction = svm.predict([hand_landmarks])[0]\n\n # Append the prediction to the predictions list\n predictions.append(prediction)\n\n # Draw the prediction on the frame\n cv2.putText(frame, prediction, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n\n # Encode the frame as a jpeg image\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n\n # Yield the encoded frame\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n # Release the video capture\n cap.release()\n\n# Define the route for the video stream\n@app.route('/video')\ndef video():\n return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n# Define the route for getting the prediction result\n@app.route('/results.json')\ndef results():\n # If the predictions list is not empty, return the last prediction as a JSON object\n if predictions:\n return json.dumps({'prediction': predictions[-1]})\n else:\n # If the predictions list is empty, return an empty JSON object\n return json.dumps({})\n \n# From Text/Voice to Sign\n# Define the route for processing the form submission\n@app.route('/submit', methods=['POST'])\ndef submit():\n text = request.form['text']\n stop = nltk.corpus.stopwords.words('english')\n stop_words=['@','#',\"http\",\":\",\"is\",\"the\",\"are\",\"am\",\"a\",\"it\",\"was\",\"were\",\"an\",\",\",\".\",\"?\",\"!\",\";\",\"/\"]\n for i in stop_words:\n stop.append(i)\n\n #processing the text using bag of wor\n tokenized_text = nltk.tokenize.word_tokenize(text)\n lemmed = [wnl.lemmatize(word) for word in tokenized_text]\n processed=[]\n for i in lemmed :\n if i == \"i\" or i == \"I\":\n processed.append(\"me\")\n elif i not in stop:\n i=i.lower()\n processed.append((i))\n print(\"Keywords:\",processed)\n\n #Showing animation of the keywords.\n assets_list=['0.mp4', '1.mp4', '2.mp4', '3.mp4', '4.mp4', '5.mp4','6.mp4', '7.mp4', '8.mp4', '9.mp4', 'a.mp4', 'after.mp4',\n 'again.mp4', 'against.mp4', 'age.mp4', 'all.mp4', 'alone.mp4','also.mp4', 'and.mp4', 'ask.mp4', 'at.mp4', 'b.mp4', 'be.mp4',\n 'beautiful.mp4', 'before.mp4', 'best.mp4', 'better.mp4', 'busy.mp4', 'but.mp4', 'bye.mp4', 'c.mp4', 'can.mp4', 'cannot.mp4',\n 'change.mp4', 'college.mp4', 'come.mp4', 'computer.mp4', 'd.mp4', 'day.mp4', 'distance.mp4', 'do not.mp4', 'do.mp4', 'does not.mp4',\n 'e.mp4', 'eat.mp4', 'engineer.mp4', 'f.mp4', 'fight.mp4', 'finish.mp4', 'from.mp4', 'g.mp4', 'glitter.mp4', 'go.mp4', 'god.mp4',\n 'gold.mp4', 'good.mp4', 'great.mp4', 'h.mp4', 'hand.mp4', 'hands.mp4', 'happy.mp4', 'hello.mp4', 'help.mp4', 'her.mp4', 'here.mp4',\n 'his.mp4', 'home.mp4', 'homepage.mp4', 'how.mp4', 'i.mp4', 'invent.mp4', 'it.mp4', 'j.mp4', 'k.mp4', 'keep.mp4', 'l.mp4', 'language.mp4', 'laugh.mp4',\n 'learn.mp4', 'm.mp4', 'me.mp4', 'mic3.png', 'more.mp4', 'my.mp4', 'n.mp4', 'name.mp4', 'next.mp4', 'not.mp4', 'now.mp4', 'o.mp4', 'of.mp4', 'on.mp4',\n 'our.mp4', 'out.mp4', 'p.mp4', 'pretty.mp4', 'q.mp4', 'r.mp4', 'right.mp4', 's.mp4', 'sad.mp4', 'safe.mp4', 'see.mp4', 'self.mp4', 'sign.mp4', 'sing.mp4', \n 'so.mp4', 'sound.mp4', 'stay.mp4', 'study.mp4', 't.mp4', 'talk.mp4', 'television.mp4', 'thank you.mp4', 'thank.mp4', 'that.mp4', 'they.mp4', 'this.mp4', 'those.mp4', \n 'time.mp4', 'to.mp4', 'type.mp4', 'u.mp4', 'us.mp4', 'v.mp4', 'w.mp4', 'walk.mp4', 'wash.mp4', 'way.mp4', 'we.mp4', 'welcome.mp4', 'what.mp4', 'when.mp4', 'where.mp4', \n 'which.mp4', 'who.mp4', 'whole.mp4', 'whose.mp4', 'why.mp4', 'will.mp4', 'with.mp4', 'without.mp4', 'words.mp4', 'work.mp4', 'world.mp4', 'wrong.mp4', 'x.mp4', 'y.mp4',\n 'you.mp4', 'your.mp4', 'yourself.mp4', 'z.mp4']\n tokens_sign_lan=[]\n\n for word in processed:\n string = str(word+\".mp4\")\n if string in assets_list:\n tokens_sign_lan.append(str(\"assets/\"+string))\n else:\n for j in word:\n tokens_sign_lan.append(str(\"assets/\"+j+\".mp4\"))\n\n def generate_frames(video_file):\n cap = cv2.VideoCapture(video_file)\n if not cap.isOpened():\n raise ValueError(\"Error File Not Found\")\n while True:\n label = video_file.replace(\"assets/\",\"\").replace(\".mp4\",\"\")\n fps= int(cap.get(cv2.CAP_PROP_FPS))\n ret, frame = cap.read()\n if not ret:\n break\n time.sleep(1/fps)\n frame = cv2.putText(frame, label, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 1, cv2.LINE_AA)\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n cap.release()\n\n # Concatenate the video frames from all the video files\n def generate_all_frames():\n for video_file in tokens_sign_lan:\n label = video_file.replace(\"assets/\",\"\").replace(\".mp4\",\"\")\n yield from generate_frames(video_file)\n\n return Response(generate_all_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n# Run the Server\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"TArOoO2/Sign-Language-Recognizer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12999127790","text":"\nfrom unittest import TestCase\n\nimport omdb\n\n\nclass TestApi(TestCase):\n\n def test_search(self):\n s = 'True Grit'\n data = omdb.search(s)\n\n self.assertEqual(data[0].title, s)\n\n def test_imdbid(self):\n i = 'tt0065126'\n data = omdb.imdbid(i)\n\n self.assertEqual(data.imdb_id, i)\n\n def test_title(self):\n t = 'True Grit'\n data = omdb.title(t)\n\n self.assertEqual(data.title, t)\n\n def test_set_default(self):\n t = 'True Grit'\n\n self.assertEqual(omdb.title(t).year, '2010')\n\n omdb.set_default('year', '1969')\n\n self.assertEqual(omdb.title(t).year, '1969')\n\n def test_get(self):\n self.assertEqual(omdb.get(title='True Grit').title, 'True Grit')\n self.assertEqual(omdb.get(imdbid='tt0065126').imdb_id, 'tt0065126')\n self.assertEqual(omdb.get(search='True Grit')[0].title, 'True Grit')\n\n def test_empty_data(self):\n invalid = 'asdfghjkl'\n\n self.assertEqual(omdb.search(invalid), [])\n self.assertEqual(omdb.title(invalid), {})\n self.assertEqual(omdb.imdbid(invalid), {})\n\n def test_search_model_fields(self):\n expected_fields = [\n 'title',\n 'year',\n 'type',\n 'imdb_id'\n ]\n\n for item in omdb.search('True Grit'):\n self.assertEqual(set(item.keys()), set(expected_fields))\n\n def test_get_model_fields(self):\n expected_fields = [\n 'actors',\n 'director',\n 'genre',\n 'plot',\n 'poster',\n 'rated',\n 'released',\n 'runtime',\n 'title',\n 'type',\n 'writer',\n 'year',\n 'imdb_id',\n 'imdb_rating',\n 'imdb_votes'\n ]\n\n self.assertEqual(set(omdb.title('True Grit').keys()), set(expected_fields))\n self.assertEqual(set(omdb.imdbid('tt0065126').keys()), set(expected_fields))\n\n def test_get_model_fields_tomatoes(self):\n expected_fields = [\n 'actors',\n 'director',\n 'genre',\n 'plot',\n 'poster',\n 'rated',\n 'released',\n 'runtime',\n 'title',\n 'type',\n 'writer',\n 'year',\n 'imdb_id',\n 'imdb_rating',\n 'imdb_votes',\n\n 'box_office',\n 'dvd',\n 'production',\n 'website',\n 'tomato_consensus',\n 'tomato_fresh',\n 'tomato_image',\n 'tomato_meter',\n 'tomato_rating',\n 'tomato_reviews',\n 'tomato_rotten',\n 'tomato_user_meter',\n 'tomato_user_rating',\n 'tomato_user_reviews'\n ]\n\n self.assertEqual(set(omdb.title('True Grit', tomatoes=True).keys()), set(expected_fields))\n self.assertEqual(set(omdb.imdbid('tt0065126', tomatoes=True).keys()), set(expected_fields))\n","repo_name":"rishirajsinghjhelumi/Entity-Mining","sub_path":"assets/omdb.py-master/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38418694184","text":"from typing import IO, List\n\nfrom cfinterface.components.section import Section\nfrom cfinterface.data.sectiondata import SectionData\nfrom cfinterface.writing.sectionwriting import SectionWriting\n\nfrom tests.mocks.mock_open import mock_open\nfrom io import StringIO\nfrom unittest.mock import MagicMock, patch\n\n\nclass DummySection(Section):\n def __eq__(self, o: object) -> bool:\n if not isinstance(o, self.__class__):\n return False\n else:\n return o.data == self.data\n\n def read(self, file: IO) -> bool:\n self.data: List[str] = []\n line: str = file.readline()\n self.data.append(line)\n return True\n\n def write(self, file: IO) -> bool:\n file.write(self.data)\n return True\n\n\ndef test_sectionwriting_withdata():\n filedata = \"Hello, World!\"\n bd = SectionData(DummySection(data=filedata))\n bw = SectionWriting(bd)\n m: MagicMock = mock_open(read_data=filedata)\n with patch(\"builtins.open\", m):\n bw.write(\"\", \"utf-8\")\n m().write.assert_called_once_with(filedata)\n\n\ndef test_sectionwriting_withdata_tobuffer():\n filedata = \"Hello, World!\"\n bd = SectionData(DummySection(data=filedata))\n bw = SectionWriting(bd)\n m = StringIO(\"\")\n bw.write(m, \"utf-8\")\n assert m.getvalue() == filedata\n","repo_name":"rjmalves/cfi","sub_path":"tests/writing/test_sectionwriting.py","file_name":"test_sectionwriting.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"1550275102","text":"class UnitFind:\n\n def __init__(self, grids):\n row = len(grids)\n col = len(grids[0])\n self.roots = [i * row + j for i in range(row) for j in range(col)]\n self.rank = [0] * (row * col)\n self.count = 0\n for i in range(row):\n for j in range(col):\n if grids[i][j] == '1':\n self.roots[i * col + j] = i * col + j\n self.count += 1\n\n def findRoot(self, i):\n root = i\n while self.roots[root] != root:\n root = self.roots[root]\n # 重新排列这个i的父序列,重拍,减小直接到root的层级\n while self.roots[i] != i:\n temp = self.roots[i]\n self.roots[i] = root\n i = temp\n return root\n\n def union(self, p, q):\n rootP = self.findRoot(p)\n rootQ = self.findRoot(q)\n if rootP != rootQ:\n if self.rank[rootP] < self.rank[rootQ]:\n self.roots[rootP] = rootQ\n elif self.rank[rootP] > self.rank[rootQ]:\n self.roots[rootQ] = rootP\n else:\n self.roots[rootQ] = rootP\n self.rank[rootP] += 1\n self.count -= 1\n\n\nclass Solution(object):\n dirs = ((-1, 0), (1, 0), (0, -1), (0, 1))\n\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if not grid:\n return 0\n quickU = UnitFind(grid)\n row = len(grid)\n col = len(grid[0])\n for i in range(row):\n for j in range(col):\n if grid[i][j] == '0':\n continue\n for dir in self.dirs:\n nr, nc = i + dir[0], j + dir[1]\n if 0 <= nr < row and 0 <= nc < col and grid[nr][nc] == '1':\n quickU.union(i * col + j, nr * col + nc)\n return quickU.count","repo_name":"PykeChen/pythonBasicGramer","sub_path":"quickUnionFind.py","file_name":"quickUnionFind.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10292963581","text":"\"\"\"\n가사 검색 - 2회차\n\"\"\"\n\n# 풀이 제한 시간 : 1시간 30분\n# 2020/12/10 11:16 ~ 11:26\n\nfrom bisect import bisect_left, bisect_right\n\narray = [[] for _ in range(10001)]\nreversed_array = [[] for _ in range(10001)]\n\ndef countByRange(array, start, end):\n min_value = bisect_left(array, start)\n max_value = bisect_right(array, end)\n\n return max_value - min_value\n\ndef solution(words, queries):\n answer = []\n\n for word in words:\n array[len(word)].append(word)\n reversed_array[len(word)].append(word[::-1])\n\n for i in range(10001):\n array[i].sort()\n reversed_array[i].sort()\n\n for q in queries:\n if q[0] != '?':\n # array[len(q)] 빼먹음\n result = countByRange(array[len(q)], q.replace('?', 'a'), q.replace('?', 'z'))\n answer.append(result)\n else:\n result = countByRange(reversed_array[len(q)], q[::-1].replace('?', 'a'), q[::-1].replace('?', 'z'))\n answer.append(result)\n\n return answer","repo_name":"LeeSeok-Jun/Algorithms","sub_path":"algorithms_questions/ch15_search/q30_1.py","file_name":"q30_1.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"37937647041","text":"\r\n\r\n# you can write to stdout for debugging purposes, e.g.\r\n# print(\"this is a debug message\")\r\n\r\ndef solution(A):\r\n if A:\r\n z= sorted(A)\r\n dom = z[len(A)//2]\r\n x = A.count(dom)\r\n if x > len(A)//2:\r\n return A.index(dom)\r\n else:\r\n return -1\r\n else:\r\n return -1\r\n\r\n\r\n\r\n\r\nprint(solution( [1, 2, 1]))","repo_name":"PillarofMorning/Codility","sub_path":"codility dominator.py","file_name":"codility dominator.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9921606208","text":"import torch\r\nimport torch.nn.functional as F\r\nfrom torch.cuda import amp\r\nfrom spikingjelly.activation_based import functional, neuron\r\nfrom torch.utils.data import DataLoader\r\nimport time\r\nimport argparse\r\nimport datetime\r\nimport model\r\nimport data\r\nimport numpy as np\r\n\r\n\r\ntorch.backends.cudnn.benchmark = True\r\n_seed_ = 202208\r\ntorch.manual_seed(_seed_) \r\ntorch.backends.cudnn.deterministic = True\r\ntorch.backends.cudnn.benchmark = False\r\nnp.random.seed(_seed_)\r\n\r\n\r\ndef load_data(args):\r\n if args.dataset == \"SHD\":\r\n train_ds = data.SHD(train=True, dt=args.dt, T=args.T)\r\n test_ds = data.SHD(train=False, dt=args.dt, T=args.T)\r\n train_dl = DataLoader(train_ds, shuffle=True, batch_size=args.batch_size, pin_memory=True)\r\n test_dl = DataLoader(test_ds, shuffle=False, batch_size=args.batch_size, pin_memory=True)\r\n return train_dl, test_dl\r\n\r\n\r\ndef main():\r\n # python ./classify_shd.py -dataset SHD -T 15 -dt 60 -device cuda:0 -batch_size 256 -epochs 1000 -opt adam -lr 0.0001 -loss MSE\r\n\r\n parser = argparse.ArgumentParser(description='Classify SHD')\r\n parser.add_argument(\"-dataset\",type=str,default=\"SHD\")\r\n parser.add_argument(\"-batch_size\",type=int,default=256) \r\n parser.add_argument(\"-T\",type=int,default=15,help='simulating time-steps') \r\n parser.add_argument(\"-dt\",type=int,default=60,help='frame time-span') \r\n parser.add_argument('-device', default='cuda:0', help='device')\r\n parser.add_argument('-epochs', default=200, type=int, metavar='N',\r\n help='number of total epochs to run')\r\n parser.add_argument('-amp', default=True, type=bool, help='automatic mixed precision training')\r\n parser.add_argument('-cupy', default=True, type=bool, help='use cupy backend')\r\n parser.add_argument('-opt', default=\"adam\", type=str, help='use which optimizer. SDG or Adam')\r\n parser.add_argument('-momentum', default=0.9, type=float, help='momentum for SGD')\r\n parser.add_argument('-lr', default=0.0001, type=float, help='learning rate')\r\n parser.add_argument('-loss', default=\"MSE\", type=str, help='loss function')\r\n\r\n args = parser.parse_args()\r\n print(args)\r\n\r\n net = model.SHD_STSC()\r\n\r\n functional.set_step_mode(net, 'm')\r\n if args.cupy:\r\n functional.set_backend(net, 'cupy', instance=neuron.LIFNode)\r\n\r\n\r\n print(net)\r\n net.to(args.device)\r\n\r\n train_data_loader, test_data_loader = load_data(args) \r\n\r\n\r\n scaler = None\r\n if args.amp:\r\n scaler = amp.GradScaler()\r\n\r\n start_epoch = 0\r\n max_test_acc = -1\r\n\r\n optimizer = None\r\n if args.opt == 'sgd':\r\n optimizer = torch.optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum)\r\n elif args.opt == 'adam':\r\n optimizer = torch.optim.Adam(net.parameters(), lr=args.lr)\r\n else:\r\n raise NotImplementedError(args.opt)\r\n\r\n lr_scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 1000)\r\n\r\n for epoch in range(start_epoch, args.epochs):\r\n start_time = time.time()\r\n net.train()\r\n train_loss = 0\r\n train_acc = 0\r\n train_samples = 0\r\n for frame, label in train_data_loader:\r\n optimizer.zero_grad()\r\n frame = frame.to(args.device)\r\n frame = frame.transpose(0, 1) # [B, T, N] -> [T, B, N]\r\n label = label.to(args.device)\r\n label_onehot = F.one_hot(label.to(torch.int64), 20).float()\r\n\r\n if scaler is not None:\r\n with amp.autocast():\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n scaler.scale(loss).backward()\r\n scaler.step(optimizer)\r\n scaler.update()\r\n else:\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n train_samples += label.numel()\r\n train_loss += loss.item() * label.numel()\r\n train_acc += (out_fr.argmax(1) == label).float().sum().item()\r\n\r\n functional.reset_net(net)\r\n\r\n train_time = time.time()\r\n train_speed = train_samples / (train_time - start_time)\r\n train_loss /= train_samples\r\n train_acc /= train_samples\r\n\r\n lr_scheduler.step()\r\n\r\n net.eval()\r\n test_loss = 0\r\n test_acc = 0\r\n test_samples = 0\r\n with torch.no_grad():\r\n for frame, label in test_data_loader:\r\n frame = frame.to(args.device)\r\n frame = frame.transpose(0, 1) # [B, T, N] -> [T, B, N]\r\n label = label.to(args.device)\r\n label_onehot = F.one_hot(label.to(torch.int64), 20).float()\r\n out_fr = None\r\n if args.loss == \"MSE\":\r\n out_fr = net(frame).mean(0)\r\n loss = F.mse_loss(out_fr, label_onehot)\r\n test_samples += label.numel()\r\n test_loss += loss.item() * label.numel()\r\n test_acc += (out_fr.argmax(1) == label).float().sum().item()\r\n functional.reset_net(net)\r\n test_time = time.time()\r\n test_speed = test_samples / (test_time - train_time)\r\n test_loss /= test_samples\r\n test_acc /= test_samples\r\n\r\n if test_acc > max_test_acc:\r\n max_test_acc = test_acc\r\n\r\n print(args)\r\n print(f'epoch = {epoch}, train_loss ={train_loss: .4f}, train_acc ={train_acc: .4f}, test_loss ={test_loss: .4f}, test_acc ={test_acc: .4f}, max_test_acc ={max_test_acc: .4f}')\r\n print(f'train speed ={train_speed: .4f} images/s, test speed ={test_speed: .4f} images/s')\r\n print(f'escape time = {(datetime.datetime.now() + datetime.timedelta(seconds=(time.time() - start_time) * (args.epochs - epoch))).strftime(\"%Y-%m-%d %H:%M:%S\")}\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Tab-ct/STSC-SNN","sub_path":"classify_shd.py","file_name":"classify_shd.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"52"}
+{"seq_id":"12612413211","text":"from bson import ObjectId\n\nfrom models.enrollment import Enrollment\nfrom repositories.interface_repository import InterfaceRepository\n\n\nclass ReportsRepository(InterfaceRepository[Enrollment]):\n\n def get_grades_stats(self):\n query_aggregation = {\n \"$group\": {\n \"_id\": \"$student\",\n \"count\": {\"$sum\": 1}\n }\n }\n query_sort = {\n \"$sort\": {\n \"count\": 1\n }\n }\n query_limit = {\n \"$limit\": 15\n }\n pipeline = [query_aggregation, query_sort, query_limit]\n return self.query_aggregation(pipeline)\n\n def get_students_enrollments(self, id_: str = \"-1\", limit: int = None) -> list:\n \"\"\"\n\n :param limit:\n :param id_:\n :return:\n \"\"\"\n # Equivalent to WHERE student_fk = ObjectId(id_)\n query_match = {\"$match\": {}}\n if id_ != \"-1\":\n query_match = {\n \"$match\": {\n \"student.$id\": ObjectId(id_)\n }\n }\n # Equivalent to make a INNER JOIN\n query_lookup = {\n \"$lookup\": {\n \"from\": \"student\",\n \"localField\": \"student.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"students_info\"\n },\n \"$unwind\": \"$students_info\"\n }\n # Equivalent to GROUP BY\n query_group = {\n \"$group\": {\n \"_id\": \"$students_info\",\n \"enrollments\": {\"$sum\": 1}\n }\n }\n # Clean the response, using equivalent to ALIAS and ORDER BY\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"lastname\": \"$_id.lastname\",\n \"personal_id\": \"$_id.personal_id\",\n \"_id\": \"$_id._id\"\n },\n \"$sort\": {\n \"enrollments\": 1\n }\n }\n query_limit = {}\n if limit:\n query_limit = {\n \"$limit\": limit\n }\n pipeline = [query_match, query_lookup, query_group, query_add_fields, query_limit]\n return self.query_aggregation(pipeline)\n\n def get_course_enrollments(self, id_: str) -> list:\n \"\"\"\n\n :param id_:\n :return:\n \"\"\"\n # Equivalent to WHERE course_fk = ObjectId(id_)\n query_match = {\"$match\": {}}\n if id_ != \"-1\":\n query_match = {\n \"$match\": {\n \"course.$id\": ObjectId(id_)\n }\n }\n # Equivalent to make a INNER JOIN\n query_lookup = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n }\n }\n query_unwind = {\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to GROUP BY\n query_group = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"enrollments\": {\"$sum\": 1}\n }\n }\n # Clean the response, using equivalent to ALIAS and ORDER BY DESC\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"credits\": \"$_id.credits\",\n \"_id\": \"$_id._id\"\n }\n }\n query_sort = {\n \"$sort\": {\n \"enrollments\": -1\n }\n }\n pipeline = [query_match,\n query_lookup,\n query_unwind,\n query_group,\n query_add_fields,\n query_sort]\n return self.query_aggregation(pipeline)\n\n def get_department_enrollments(self) -> list:\n \"\"\"\n\n :return:\n \"\"\"\n # Equivalent to make an INNER JOIN courses\n query_preprocess_courses = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n },\n }\n query_unwind_courses = {\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to make a GROUP BY courses\n query_group_courses = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"count\": {\"$sum\": 1}\n }\n }\n query_add_fields_department = {\n \"$addFields\": {\n \"department\": \"$_id.department\"\n }\n }\n # Equivalent to make an INNER JOIN departments\n query_process_departments = {\n \"$lookup\": {\n \"from\": \"department\",\n \"localField\": \"department.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"department_info\"\n }\n }\n query_unwind_department = {\n \"$unwind\": \"$department_info\"\n }\n # Equivalent to make GROUP BY and ORDER BY departments\n query_group_departments = {\n \"$group\": {\n \"_id\": \"$department_info\",\n \"enrollments\": {\"$sum\": \"$count\"}\n },\n }\n query_add_fields = {\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"_id\": \"$_id._id\"\n }\n }\n pipeline = [query_preprocess_courses,\n query_unwind_courses,\n query_group_courses,\n query_add_fields_department,\n query_process_departments,\n query_unwind_department,\n query_group_departments,\n query_add_fields]\n return self.query_aggregation(pipeline)\n\n def get_departments_distribution(self) -> list:\n \"\"\"\n\n :return:\n \"\"\"\n winners = 15\n # Equivalent to make an INNER JOIN courses\n query_preprocess_courses = {\n \"$lookup\": {\n \"from\": \"course\",\n \"localField\": \"course.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"course_info\"\n },\n \"$unwind\": \"$course_info\"\n }\n # Equivalent to make a GROUP BY courses\n query_group_courses = {\n \"$group\": {\n \"_id\": \"$course_info\",\n \"count\": {\"$sum\": 1}\n },\n \"$sort\": {\n \"enrollments\": -1\n },\n \"$limit\": winners,\n \"$addFields\": {\n \"department\": \"$_id.department\"\n }\n }\n # Equivalent to make an INNER JOIN departments\n query_process_departments = {\n \"$lookup\": {\n \"from\": \"department\",\n \"localField\": \"department.$id\",\n \"foreignField\": \"_id\",\n \"as\": \"department_info\"\n },\n \"$unwind\": \"$department_info\"\n }\n # Equivalent to make GROUP BY and ORDER BY departments\n query_group_departments = {\n \"$group\": {\n \"_id\": \"$department_info\",\n \"enrollments\": {\"$sum\": \"$count\"}\n },\n \"$addFields\": {\n \"name\": \"$_id.name\",\n \"_id\": \"$_id._id\"\n }\n }\n pipeline = [query_preprocess_courses, query_group_courses, query_process_departments, query_group_departments]\n return self.query_aggregation(pipeline)\n","repo_name":"MisionTIC-2022-Ciclo-4a-UNAL/academic_backend","sub_path":"repositories/reports_repository.py","file_name":"reports_repository.py","file_ext":"py","file_size_in_byte":7454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40556149346","text":"filename = input(\"Please input file name with extension (e.g. filename.txt): \")\r\n\r\nf = open(filename,\"r\")\r\nf2 = open('SPOWNER_Check.txt','w')\r\n\r\n# 2. Read the text file row by row\r\ncontent_list = f.readlines()\r\n\r\n# 3. Define convert string to list function\r\ndef convert(string):\r\n list1=[]\r\n list1[:0]=string\r\n return list1\r\n\r\n# 4. User to input Position Date\r\nfile_date = input(\"Please input the Position date in YYYYMMDD format (e.g. 20211217): \")\r\n\r\n# 5. User to input Creation Date\r\ncreation_date = input(\"Please input the Creation date in YYYYMMDD format (e.g. 20211217): \")\r\n\r\n\r\n# 6. Check HDR\r\n# 6a. HDR, Date checks\r\nfirst_row = convert(content_list[0])\r\nhdrcheck = first_row[0:3] == [\"H\", \"D\", \"R\"]\r\ncreationdatecheck = first_row[11:19] == convert(creation_date)\r\nfiledatecheck = creationdatecheck #Cut off date leave as blanks\r\n\r\n\r\nif hdrcheck == True:\r\n f2.write(\"Format and position of HDR is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of HDR is WRONG.\\n\")\r\n\r\nif filedatecheck == True:\r\n f2.write(\"Format and position of File Date is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of File Date is WRONG.\\n\")\r\n\r\nif creationdatecheck == True:\r\n f2.write(\"Format and position of Creation Date is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of Creation Date is WRONG.\\n\")\r\n\r\n#6b. Check timestamp is in correct format and position, will not be able to check whether exact time is correct\r\n\r\ntimehour = int(first_row[19]) < 3\r\ntimeminute = int(first_row[21]) < 6\r\ntimesecond = int(first_row[23]) < 6\r\n\r\nif timehour == True and timeminute == True and timesecond == True:\r\n f2.write(\"Format and position of Report Creation Time is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of Report Creation Time is WRONG.\\n\")\r\n\r\n#6c. Check file name \"CIF20211102001\"\r\n\r\nprefix = first_row[25:32] == convert(\"SPOWNER\")\r\nfilenamedatecheck = first_row[32:40] == convert(file_date)\r\nsuffix = first_row[40:43] == convert(\"001\")\r\n\r\nif prefix == True and filenamedatecheck == True and suffix == True:\r\n f2.write(\"Format and position of File name is CORRECT.\\n\")\r\nelif prefix == False:\r\n f2.write(\"File name prefix is WRONG.\\n\")\r\nelif filenamedatecheck == False:\r\n f2.write(\"Date of File name is WRONG.\\n\")\r\nelif suffix == False:\r\n f2.write(\"Suffix of file name is WRONG.\\n\")\r\n\r\n#6f. Check file description\r\nfiledesccheck = first_row[45:75] == convert('Sole Prop Owner Info File ')\r\nif filedesccheck == True:\r\n f2.write(\"File description is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"File description is WRONG.\\n\")\r\n\r\n# 6g. Check Scheme member ID\r\nschemeID = first_row[75:85] == convert('MARIBK ')\r\nif schemeID == True:\r\n f2.write(\"Scheme member ID is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Scheme member ID is WRONG.\\n\")\r\n\r\n# 6h. Check Filler\r\nfillercheck = first_row[85:160] == convert(' '*75)\r\nif fillercheck == True:\r\n f2.write(\"Filler is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Filler is WRONG.\\n\")\r\n\r\n\r\nlast_row = convert(content_list[-1])\r\ntlrcheck = last_row[0:3] == [\"T\", \"L\", \"R\"]\r\n\r\nif tlrcheck == True:\r\n f2.write(\"Format and position of TLR is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of TLR is WRONG.\\n\")\r\n\r\nrowsnumbercheck = last_row[3:18] == convert(\"0\"*15)\r\n\r\nif rowsnumbercheck == True:\r\n f2.write(\"Format and positioning of number of records is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and positioning of number of records is WRONG.\\n\")\r\n\r\ntlrfiller = last_row[18:160] == convert(\" \"*142)\r\nif tlrfiller == True:\r\n f2.write(\"Format and position of TLR filler is CORRECT.\\n\")\r\nelse:\r\n f2.write(\"Format and position of TLR filler is Wrong.\\n\")\r\n","repo_name":"yuchenyang-96/SDIC","sub_path":"SPOwner Unmasked file check.py","file_name":"SPOwner Unmasked file check.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"18691598096","text":"import pytest\nimport pandas as pd\nimport statsmodels.formula.api as sm\nfrom wildboottest.wildboottest import wildboottest\nimport numpy as np\n\n@pytest.fixture\ndef data():\n np.random.seed(12312)\n N = 1000\n k = 3\n G = 20\n # small sample size -> full enumeration\n X = np.random.normal(0, 1, N * k).reshape((N,k))\n X[:,0] = 1\n beta = np.random.normal(0,1,k)\n beta[1] = 0.005\n u = np.random.normal(0,1,N)\n Y = X @ beta + u\n cluster = np.random.choice(list(range(0,G)), N)\n X_df = pd.DataFrame(X)\n Y_df = pd.DataFrame(Y)\n cluster_df = pd.DataFrame(cluster)\n df = pd.concat([X_df, Y_df, cluster_df], axis = 1) \n df.columns = ['intercept','X1','X2','Y', 'cluster']\n\n return df\n\ndef test_results_from_same_seed(data):\n \n model = sm.ols(formula='Y ~ X1 + X2', data=data) \n\n cluster_list = [data.cluster, None]\n for x in cluster_list: \n\n # same seed used in function -> same results\n a = wildboottest(model, param = \"X1\", cluster = x, B= 999, seed=876587)\n b = wildboottest(model, param = \"X1\", cluster = x, B= 999, seed=876587)\n pd.testing.assert_frame_equal(a,b)\n \n # random seed outside of function 2x -> same results\n np.random.seed(123)\n a2 = wildboottest(model, param = \"X1\", cluster = x, B= 999)\n np.random.seed(123)\n b2 = wildboottest(model, param = \"X1\", cluster = x, B= 999)\n pd.testing.assert_frame_equal(a2,b2)\n","repo_name":"s3alfisc/wildboottest","sub_path":"tests/test_seeds.py","file_name":"test_seeds.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"43864620879","text":"import sys \ninput = sys.stdin.readline\n\nN = int(input())\ncount = 0\n\nfor hour in range(N + 1):\n if '3' in str(hour):\n count += 60 * 60\n else:\n for minute in range(60):\n if '3' in str(minute):\n count += 60\n else:\n for sec in range(60):\n if '3' in str(sec):\n count += 1\n \nprint(count)\n","repo_name":"jhu97/coding-test","sub_path":"implementation_2.py","file_name":"implementation_2.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"71241445285","text":"from __future__ import division\nimport os.path as osp\nimport sys\nimport argparse\nfrom tqdm import tqdm\n\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\nimport torch.backends.cudnn as cudnn\nfrom torch.nn.parallel import DistributedDataParallel\n\nfrom config import config\nfrom dataloader import get_train_loader\nfrom network import FCN\nfrom datasets import VOC\nfrom utils.init_func import init_weight, group_weight\nfrom engine.lr_policy import PolyLR\nfrom engine.engine import Engine\nfrom seg_opr.sync_bn import DataParallelModel, Reduce, BatchNorm2d\n\ntry:\n from apex.parallel import SyncBatchNorm\nexcept ImportError:\n raise ImportError(\n \"Please install apex from https://www.github.com/nvidia/apex .\")\n\ntorch.manual_seed(config.seed)\nif torch.cuda.is_available():\n torch.cuda.manual_seed(config.seed)\n\nparser = argparse.ArgumentParser()\n\nwith Engine(custom_parser=parser) as engine:\n args = parser.parse_args()\n\n cudnn.benchmark = True\n if engine.distributed:\n torch.cuda.set_device(engine.local_rank)\n\n # data loader\n train_loader, train_sampler = get_train_loader(engine, VOC)\n\n # config network and criterion\n criterion = nn.CrossEntropyLoss(reduction='mean',\n ignore_index=255)\n\n if engine.distributed:\n BatchNorm2d = SyncBatchNorm\n else:\n BatchNorm2d = BatchNorm2d\n model = FCN(config.num_classes, criterion=criterion,\n pretrained_model=config.pretrained_model,\n norm_layer=BatchNorm2d)\n init_weight(model.business_layer, nn.init.kaiming_normal_,\n BatchNorm2d, config.bn_eps, config.bn_momentum,\n mode='fan_out', nonlinearity='relu')\n\n # group weight and config optimizer\n base_lr = config.lr\n if engine.distributed:\n base_lr = config.lr * engine.world_size\n\n params_list = []\n params_list = group_weight(params_list, model,\n BatchNorm2d, base_lr)\n\n optimizer = torch.optim.SGD(params_list,\n lr=base_lr,\n momentum=config.momentum,\n weight_decay=config.weight_decay)\n\n # config lr policy\n total_iteration = config.nepochs * config.niters_per_epoch\n lr_policy = PolyLR(base_lr, config.lr_power, total_iteration)\n\n if engine.distributed:\n if torch.cuda.is_available():\n model.cuda()\n model = DistributedDataParallel(model,\n device_ids=[engine.local_rank],\n output_device=engine.local_rank)\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model = DataParallelModel(model, engine.devices)\n model.to(device)\n\n engine.register_state(dataloader=train_loader, model=model,\n optimizer=optimizer)\n if engine.continue_state_object:\n engine.restore_checkpoint()\n\n optimizer.zero_grad()\n model.train()\n\n for epoch in range(engine.state.epoch, config.nepochs):\n if engine.distributed:\n train_sampler.set_epoch(epoch)\n bar_format = '{desc}[{elapsed}<{remaining},{rate_fmt}]'\n pbar = tqdm(range(config.niters_per_epoch), file=sys.stdout,\n bar_format=bar_format)\n dataloader = iter(train_loader)\n for idx in pbar:\n engine.update_iteration(epoch, idx)\n\n minibatch = dataloader.next()\n imgs = minibatch['data']\n gts = minibatch['label']\n\n imgs = imgs.cuda(non_blocking=True)\n gts = gts.cuda(non_blocking=True)\n\n loss = model(imgs, gts)\n\n # reduce the whole loss over multi-gpu\n if engine.distributed:\n dist.all_reduce(loss, dist.ReduceOp.SUM)\n loss = loss / engine.world_size\n else:\n loss = Reduce.apply(*loss) / len(loss)\n\n optimizer.zero_grad()\n current_idx = epoch * config.niters_per_epoch + idx\n lr = lr_policy.get_lr(current_idx)\n\n for i in range(0, len(optimizer.param_groups)):\n optimizer.param_groups[i]['lr'] = lr\n\n loss.backward()\n optimizer.step()\n print_str = 'Epoch{}/{}'.format(epoch, config.nepochs) \\\n + ' Iter{}/{}:'.format(idx + 1, config.niters_per_epoch) \\\n + ' lr=%.2e' % lr \\\n + ' loss=%.2f' % loss.item()\n\n pbar.set_description(print_str, refresh=False)\n\n if epoch % config.snapshot_iter == 0:\n if engine.distributed and (engine.local_rank == 0):\n engine.save_and_link_checkpoint(config.snapshot_dir,\n config.log_dir,\n config.log_dir_link)\n elif not engine.distributed:\n engine.save_and_link_checkpoint(config.snapshot_dir,\n config.log_dir,\n config.log_dir_link)\n","repo_name":"ycszen/TorchSeg","sub_path":"model/fcn/voc.fcn32s.R101_v1c/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","stars":1396,"dataset":"github-code","pt":"52"}
+{"seq_id":"23769885010","text":"import socket\nimport sys\nimport random\n\n# Packet codes\nSERVER_FULL = 'F'\nGAME_INFO = ' '\nGAME_END = 'V'\nREGISTER = 'R'\n\n# Packet constants\nBUFLEN = 512\n\n# Board constants\nNULL_CHAR = ' '\nBOARD_ROWS = 3\nBOARD_COLS = 3\nMAX_PLAYERS = 2\n\n\nif len(sys.argv) < 2:\n print(\"usage: \")\n sys.exit()\n\n# Constants\nTURN_ERROR = \"It isn't your turn right now.\"\nINPUT_ERROR = (\"Invalid Move\\n\"\n\"Move should be M with no spaces\\n\"\n\"Example: MA1 or MB3\\n\")\nWAIT_MSG = \"You are player X. Waiting on player O to connect \\n\"\n\nROLE_PROMPT = \"You are playing as: %s\\n\"\nMOVE_PROMPT = \"Your Turn \\n\"\nVALID_ROWS = {\n 'A': 0,\n 'B': 1,\n 'C': 2\n}\nVALID_COLS = {\n '1': 0,\n '2': 1,\n '3': 2\n}\nSYMBOLS = [\n 'X',\n 'O'\n]\n\nclass Board(object):\n def __init__(self):\n self.ROLE = {}\n self.PLAYERS = []\n self.PLAY_PTR = 0\n self.NUM_PLAYERS = 0\n self.GAME_BOARD = [\n [ NULL_CHAR] * BOARD_COLS\n for _ in range( BOARD_ROWS)\n ]\n self.LINES = self.generate_lines()\n self.MOVES_LEFT = self.move_set()\n\n def move_set(self):\n moves = set()\n for row in VALID_ROWS.keys():\n for col in VALID_COLS.keys():\n moves.add(\"M\"+row + col)\n return moves\n\n def generate_lines(self):\n lines = []\n\n # rows and cols\n for row in range( BOARD_ROWS):\n temp_rows = []\n temp_cols = []\n for col in range( BOARD_COLS):\n temp_rows.append((row, col))\n temp_cols.append((col, row))\n lines.append(temp_rows)\n lines.append(temp_cols)\n\n # diagonals\n diag_a = []\n diag_b = []\n for row in range( BOARD_ROWS):\n diag_a.append((row, row))\n diag_b.append(( BOARD_ROWS - row - 1, row))\n lines.append(diag_a)\n lines.append(diag_b)\n\n return lines\n\n def add_player(self, player_id):\n self.ROLE[player_id] = SYMBOLS[self.NUM_PLAYERS]\n self.PLAYERS.append(player_id)\n self.NUM_PLAYERS += 1\n\nBOARD = Board()\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\nserver_address = ('localhost', int(sys.argv[1]))\n\nprint('Network Server Starting')\n\nsock.bind(server_address)\n\ndef send_to_address(message, address):\n '''send msg btween server and clients '''\n if address != \"AI\":\n sock.sendto(message, address)\n # print(BOARD.ROLE[address]+\">\")\n\n\ndef broadcast(message):\n '''to broadcast msg to all users connected with server'''\n for address in BOARD.PLAYERS:\n send_to_address(message, address)\n\ndef is_valid_move(move):\n #return the rest of valid moves \n return(len(move) <= 3 and\n move in BOARD.MOVES_LEFT and\n move[0]=='M' and\n move[1] in VALID_ROWS and\n move[2] in VALID_COLS)\n\ndef reset():\n '''reset the all game'''\n global BOARD\n BOARD = Board()\n\ndef increment_play_order():\n '''keep tracking of clients order'''\n BOARD.PLAY_PTR += 1\n if BOARD.PLAY_PTR >= len(BOARD.PLAYERS):\n\n BOARD.PLAY_PTR = 0\n\ndef await_players():\n print(\"Waiting on Clients..\")\n #waiting clients to connect \n while BOARD.NUM_PLAYERS < MAX_PLAYERS:\n data, address = sock.recvfrom( BUFLEN)\n if address not in BOARD.ROLE:\n BOARD.add_player(address)\n\n else:\n #server full check and user inputs warinings\n send_to_address(INPUT_ERROR, address)\n print(INPUT_ERROR , address)\n # send_to_address(WAIT_MSG, address)\n print(BOARD.ROLE[address]+\"< Connected\") \n broadcast_state(address)\n\n\ndef broadcast_state(address):\n '''transmiting the game states between clients'''\n if BOARD.NUM_PLAYERS < MAX_PLAYERS:\n message = WAIT_MSG\n broadcast(message )\n print(BOARD.ROLE[address]+\">\"+WAIT_MSG)\n\n\ndef drawmapS(game_info1):\n '''draw the board in the server side'''\n print(\"board\")\n print(\" 1|2|3\")\n print(\"+\"*9)\n print(\"A|\" + game_info1[1] + \"|\" + game_info1[2] + \"|\" + game_info1[3] + \"|\")\n print(\"+\"*9)\n print(\"B|\" + game_info1[4] + \"|\" + game_info1[5] + \"|\" + game_info1[6] + \"|\") \n print(\"+\"*9)\n print(\"C|\" + game_info1[7] + \"|\" + game_info1[8] + \"|\" + game_info1[9] + \"|\")\n print(\"+\"*9)\n\n# is user try to resign ?!\ndef checkresign(move,address):\n if move ==\"R\":\n if BOARD.ROLE[address]==\"X\":\n # send_to_address( \"you lose\", address)\n broadcast(\"player O win\")\n print(\"player O win\")\n else:\n broadcast(\"player X win\")\n print(\"player X win\")\n m=\"%s is resigned\"\n broadcast(m% BOARD.ROLE[address])\n broadcast( GAME_END)\n print(\"Game Ended\")\n sys.exit()\n else:\n return False\n\ndef broadcast_game():\n game_state = [ GAME_INFO]\n for row in range(len(BOARD.GAME_BOARD)):\n for col in range(len(BOARD.GAME_BOARD)):\n game_state.append(BOARD.GAME_BOARD[row][col])\n broadcast(''.join(game_state))\n drawmapS(game_state)\n\n\ndef is_winning_set(char_set):\n '''combination od=f moves which led to win the game'''\n return ( NULL_CHAR not in char_set and\n len(char_set) == 1)\n\ndef get_winner():\n '''winner announcing fuction ''' \n for line in BOARD.LINES:\n temp = set()\n for row, col in line:\n temp.add(BOARD.GAME_BOARD[row][col])\n if is_winning_set(temp):\n return \"%s won!\" %temp.pop()\n \n #game is tie no body won \n if not BOARD.MOVES_LEFT:\n return \"Tie Game\\n\"\n\n return None\n\ndef launch_game():\n '''this func starts the game between 2 clients'''\n # broadcast(\"\\nGame on!\\n\")\n for address in BOARD.PLAYERS:\n message = ROLE_PROMPT % BOARD.ROLE[address]\n send_to_address(message, address)\n if BOARD.ROLE[address]==\"O\":\n print(BOARD.ROLE[address]+\">\"+message)\n\n # print(BOARD.PLAYERS)\n manage_board()\n\ndef prompt_player(address):\n message = (MOVE_PROMPT) \n send_to_address(message, address)\n print(BOARD.ROLE[address]+\">\"+message)\n\n#set of all moves in the game \ndef set_board_at(move, value):\n row = VALID_ROWS[move[1]]\n col = VALID_COLS[move[2]]\n BOARD.GAME_BOARD[row][col] = value\n BOARD.MOVES_LEFT.remove(move)\n\ndef point_to_move(point):\n '''points to move as x and y '''\n row, col = point[0], point[1]\n move = \"\"\n\n for key, value in VALID_ROWS.items():\n if value == row:\n move += key\n break\n\n for key, value in VALID_COLS.items():\n if value == col:\n move += key\n break\n\n return move\n\ndef moves_and_symbols_from(line):\n '''this func replace the taken place with x an O symbols'''\n line_symbols = {}\n moves = set()\n for point in line:\n symbol = BOARD.GAME_BOARD[point[0]][point[1]]\n if symbol == NULL_CHAR:\n moves.add(point_to_move(point))\n elif symbol in line_symbols:\n line_symbols[symbol] += 1\n else:\n line_symbols[symbol] = 1\n\n return moves, line_symbols\n\n# def enemy_is_winning(symbol_dict):\n# if len(symbol_dict.keys()) > 1:\n# return False\n# for key, value in symbol_dict.items():\n# if value > 1 and key != BOARD.ROLE[ AI]:\n# return True\n# return False\n\n\ndef get_move_from(player):\n '''this func check moves validations and constrictions'''\n taken=[]\n\n valid_move = None\n\n prompt_player(player)\n\n while not valid_move:\n move, address = sock.recvfrom( BUFLEN)\n print(BOARD.ROLE[address]+\"<\"+move)\n if address not in BOARD.ROLE:\n send_to_address( SERVER_FULL, address)\n print(BOARD.ROLE[address]+\">\"+SERVER_FULL)\n\n continue\n move = move.upper()\n\n if address != player:\n checkresign(move,address)\n send_to_address(TURN_ERROR, address)\n print(BOARD.ROLE[address]+\">\"+TURN_ERROR)\n\n elif move not in BOARD.MOVES_LEFT and move[0]=='M' and move[1] in VALID_ROWS and move[2] in VALID_COLS:\n send_to_address(\"spot is already taken\",address)\n print(BOARD.ROLE[address]+\">\"+\"spot is already taken\")\n\n # print(\"spot is already taken\")\n elif is_valid_move(move):\n valid_move = move\n \n elif checkresign(move,address):\n pass\n\n \n else:\n send_to_address(INPUT_ERROR, address)\n print(BOARD.ROLE[address]+\">\"+INPUT_ERROR)\n\n \n\n return valid_move\n\ndef manage_board():\n while True:\n # for each player do following steps \n active_player = BOARD.PLAYERS[BOARD.PLAY_PTR]\n print(BOARD.ROLE[active_player]+\">\")\n broadcast_game()\n\n move = get_move_from(active_player)\n set_board_at(move, BOARD.ROLE[active_player])\n increment_play_order()\n winner = get_winner()\n if winner:\n broadcast_game()\n message = \"%s\" % winner\n broadcast(message)\n print(\">\"+message)\n broadcast( GAME_END)\n print(\"Game Ended\")\n # break\n sys.exit()\n\n# main loop \nwhile True:\n reset()\n await_players()\n launch_game()\n","repo_name":"hima888/tic-tac-toe-Sokets","sub_path":"minor5server.py","file_name":"minor5server.py","file_ext":"py","file_size_in_byte":9290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"33953318564","text":"\"\"\"\nTrend following\nbuying on the bull-trend and selling on the bear-trend.\nBuy: When the stock price approaches the top band and the indicator is strong-trended.\nSell: When the stock price approaches the lower band and the indicator is weak-trended.\n%b: Buy = when MFI is higher than 0.8\n Sell = when MFI is lower than 0.2\n\nMFI: Money flow index = 100 - (100 / (1+positive money flow/negative money flow))\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport Analyzer.Marketdata\nimport sys\nimport io\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\nmkt = Analyzer.Marketdata.Marketdata()\nprint(\"Please enter company_name, year-month-date to check band\")\nname, date = map(str, input().split())\ndf = mkt.get_daily_price(''.join(name), '%s'%date)\n\ndf['MA20'] = df['close'].rolling(window=20).mean() # 20개 종가 표본으로 평균 구하기\ndf['stddev'] = df['close'].rolling(window=20).std() # stddev 칼럼으로 데이터프레임에 추가\ndf['upper'] = df['MA20'] + (df['stddev'] * 2) # 중간 볼린저밴드 + (2 * 표준편차)를 계산(상단)\ndf['lower'] = df['MA20'] - (df['stddev'] * 2) # 중간 볼린저밴드 + (2 * 표준편차)를 계산(하단)\ndf['PB'] = (df['close'] - df['lower']) / (df['upper'] - df['lower']) # (종가 - 하단밴드) / (상단밴드 - 하단밴드를 구해 %b 생성)\ndf['TP'] = (df['high'] + df['low'] + df['close']) / 3\ndf['PMF'] = 0\ndf['NMF'] = 0\n\nfor i in range(len(df.close) - 1):\n if df.TP.values[i] < df.TP.values[i+1]:\n df.PMF.values[i+1] = df.TP.values[i+1] * df.volume.values[i+1]\n df.NMF.values[i+1] = 0\n else:\n df.NMF.values[i+1] = df.TP.values[i+1] * df.volume.values[i+1]\n df.PMF.values[i+1] = 0\n\ndf['MFR'] = (df.PMF.rolling(window=10).sum() / df.NMF.rolling(window=10).sum())\ndf['MFI10'] = 100 - 100 / (1 + df['MFR'])\ndf = df[19:]\n\nplt.figure(figsize=(10, 8))\nplt.subplot(2, 1, 1)\nplt.title('%s Trend following with based bollinger band(20days, 2std)' %name)\nplt.plot(df.index, df['close'], color='#0000ff', label='Close') # x좌표 index의 종가를 y좌표로 설정해 실선 표시\nplt.plot(df.index, df['upper'], 'r--', label='Upper band') # 상단 볼린저밴드를 y좌표로 설정해 검은 실선표시\nplt.plot(df.index, df['MA20'], 'k--', label='Moving average 20')\nplt.plot(df.index, df['lower'], 'c--', label='Lower band')\n\n\nfor i in range(len(df.close)):\n if df.PB.values[i] > 0.8 and df.MFI10.values[i] > 80:\n plt.plot(df.index.values[i], df.close.values[i], 'r^')\n elif df.PB.values[i] < 0.2 and df.MFI10.values[i] < 20:\n plt.plot(df.index.values[i], df.close.values[i], 'bv')\nplt.legend(loc='best')\n\nplt.subplot(2, 1, 2)\nplt.plot(df.index, df['PB'] * 100, 'b', label = \"%B * 100\")\nplt.plot(df.index, df['MFI10'], 'g--', label = 'MFI(10 days)')\nplt.yticks([-20, 0, 20, 40, 60, 80, 100, 120])\n\nfor i in range(len(df.close)):\n if df.PB.values[i] > 0.8 and df.MFI10.values[i] > 80:\n plt.plot(df.index.values[i], 0, 'r^')\n elif df.PB.values[i] < 0.2 and df.MFI10.values[i] < 20:\n plt.plot(df.index.values[i], 0, 'bv')\n\nplt.grid(True)\nplt.legend(loc='best')\nplt.show()","repo_name":"MebukiYamashi/Quantitative_Trading","sub_path":"Plot/Trendfollowing.py","file_name":"Trendfollowing.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35359550945","text":"from torch.autograd import Variable\nfrom torchvision import transforms\nfrom .preprocessing import faceAlignment\nfrom PIL import Image\nfrom .apps import *\n# from moviepy.editor import *\n# import librosa\nimport numpy as np\nimport mediapipe as mp\nimport pandas as pd\nimport csv\n\n# device 설정. CUDA 사용가능하면 CUDA 모드로, 못 쓰면 CPU 모드로 동작\n# 단 cpu로 연산 할 경우 인식 함수 내 코드 수정 필요.\n# device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n# device = \"cuda\"\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0,1\"\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n# 얼굴 정보를 담을 class\nclass Face:\n def __init__(self):\n # class init\n self.rt = [-1, -1, -1, -1]\n self.sID = \"\"\n self.fvScore = -1.\n self.ptLE = [-1, -1]\n self.ptRE = [-1, -1]\n self.ptLM = [-1, -1]\n self.ptRM = [-1, -1]\n\n self.ptLED = [-1, -1]\n self.ptRED = [-1, -1]\n\n self.fYaw = -1.\n self.fPitch = -1.\n self.fRoll = -1.\n\n self.nEmotion = -1\n self.fEmotionScore = [-1, -1, -1, -1, -1, -1, -1]\n\n\n\ndef get_state_dict(origin_dict):\n old_keys = origin_dict.keys()\n new_dict = {}\n\n for ii in old_keys:\n temp_key = str(ii)\n if temp_key[0:7] == \"module.\":\n new_key = temp_key[7:]\n else:\n new_key = temp_key\n\n new_dict[new_key] = origin_dict[temp_key]\n return new_dict\n\n\n\n# 초기화\ndef Initialization():\n # face detector. OpenCV SSD\n # FD_Net = cv2.dnn.readNetFromCaffe(\"C:/Users/withmind/Desktop/models/opencv_ssd.prototxt\", \"C:/Users/withmind/Desktop/models/opencv_ssd.caffemodel\")\n FD_Net = ImConfig.FD_Net\n\n # Landmark 모델\n # Landmark_Net = LandmarkNet(3, 3)\n # # Landmark_Net = torch.nn.DataParallel(Landmark_Net).to(device)\n # Landmark_Net = Landmark_Net.to(device)\n # Landmark_Net.load_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_LANDMARK_68pt.pth.tar\", map_location=device)['state_dict'])\n # Landmark_Net.load_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_LANDMARK_68pt.pth.tar\", map_location=device)['state_dict'])\n ImConfig.Landmark_Net\n\n\n # Headpose 모델\n # Headpose_Net = HeadposeNet(torchvision.models.resnet.Bottleneck, [3, 4, 6, 3], 66)\n # Headpose_Net = Headpose_Net.to(device)\n # Headpose_Net.load_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_HEAD_POSE.pth.tar\"))\n # Headpose_Net.load_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_HEAD_POSE.pth.tar\"))\n ImConfig.Headpose_Net\n\n # Emotion classifier\n # Emotion_Net = EmotionNet(num_classes=7).to(device)\n # new_dict = get_state_dict(torch.load(\"C:/Users/withmind/Desktop/models/ETRI_Emotion.pth.tar\")['state_dict'])\n # # new_dict = get_state_dict(torch.load(\"/home/ubuntu/projects/withmind_video/im_video/file/ETRI_EMOTION.pth.tar\")['state_dict'])\n # Emotion_Net.load_state_dict(new_dict)\n ImConfig.Emotion_Net\n\n\n # 각 모델 evaluation 모드로 설정\n ImConfig.Landmark_Net.eval()\n ImConfig.Headpose_Net.eval()\n ImConfig.Emotion_Net.eval()\n\n return FD_Net, ImConfig.Landmark_Net, ImConfig.Headpose_Net, ImConfig.Emotion_Net\n\n\n# 얼굴검출\n# OpenCV 기본 예제 적용\ndef Face_Detection(FD_Net, cvImg, list_Face):\n del list_Face[:]\n img = cvImg.copy()\n (h, w) = img.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))\n\n FD_Net.setInput(blob)\n detections = FD_Net.forward()\n\n for i in range(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated with the\n # prediction\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by ensuring the `confidence` is\n # greater than the minimum confidence\n if confidence > 0.91:\n # compute the (x, y)-coordinates of the bounding box for the\n # object\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # ETRIFace 클래스에 입력하여 리스트에 저장.\n # 정방 사이즈로 조절하여 저장 함.\n ef = Face()\n difX = endX - startX\n difY = endY - startY\n if difX > difY:\n offset = int((difX - difY) / 2)\n new_startY = max(startY - offset, 0)\n new_endY = min(endY + offset, h - 1)\n new_startX = max(startX, 0)\n new_endX = min(endX, w - 1)\n ef.rt = [new_startX, new_startY, new_endX, new_endY]\n else:\n offset = int((difY - difX) / 2)\n new_startX = max(startX - offset, 0)\n new_endX = min(endX + offset, w - 1)\n new_startY = max(startY, 0)\n new_endY = min(endY, h - 1)\n ef.rt = [new_startX, new_startY, new_endX, new_endY]\n\n list_Face.append(ef)\n\n # torch.cuda.empty_cache()\n\n return len(list_Face)\n\n# landmark 검출\ndef Landmark_Detection(Landmark_Net, cvImg, list_Face, nIndex):\n h, w, _ = cvImg.shape\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n yLeftBottom_in = list_Face[nIndex].rt[1]\n yRightTop_in = list_Face[nIndex].rt[3]\n xLeftBottom_in = list_Face[nIndex].rt[0]\n xRightTop_in = list_Face[nIndex].rt[2]\n\n n15 = (yRightTop_in - yLeftBottom_in) * 0.2\n xLeftBottom_in = max(xLeftBottom_in - n15, 0)\n xRightTop_in = min(xRightTop_in + n15, w - 1)\n yLeftBottom_in = max(yLeftBottom_in - n15, 0)\n yRightTop_in = min(yRightTop_in + n15, h - 1)\n\n INPUT = cvImg[(int(yLeftBottom_in)):(int(yRightTop_in)), (int(xLeftBottom_in)): (int(xRightTop_in))]\n # print(\"INPUI>>>>>>>>>>>>>>>\", INPUT)\n # 인식 좌표 정보에 얼굴 위치 보정하기 위한 값\n # offsetX = list_ETRIFace[nIndex].rt[0]\n # offsetY = list_ETRIFace[nIndex].rt[1]\n offsetX = xLeftBottom_in\n offsetY = yLeftBottom_in\n\n # if len(INPUT) != 0:\n\n # preprocessing\n w = xRightTop_in - xLeftBottom_in\n INPUT = cv2.resize(INPUT, (256, 256))\n INPUT = INPUT / 255\n ratio = w / 256\n INPUT = np.transpose(INPUT, axes=[2, 0, 1])\n INPUT = np.array(INPUT, dtype=np.float32)\n INPUT = torch.from_numpy(INPUT)\n INPUT = torch.unsqueeze(INPUT, 0)\n INPUT = INPUT.to(device)\n OUTPUT = Landmark_Net(INPUT)\n OUTPUT = torch.squeeze(OUTPUT)\n output_np = OUTPUT.cpu().detach().numpy()\n output_np = output_np * 1.1 * 256\n output_np = output_np * ratio\n\n # 좌표 보정\n for ii in range(68):\n output_np[ii * 2 + 0] = output_np[ii * 2 + 0] + offsetX\n output_np[ii * 2 + 1] = output_np[ii * 2 + 1] + offsetY\n\n leX = leY = reX = reY = lmX = lmY = rmX = rmY = nX = nY = 0\n for ii in range(36, 42, 1):\n leX = leX + output_np[ii * 2 + 0]\n leY = leY + output_np[ii * 2 + 1]\n\n for ii in range(42, 48, 1):\n reX = reX + output_np[ii * 2 + 0]\n reY = reY + output_np[ii * 2 + 1]\n\n # 눈, 입 양 끝점 저장\n list_Face[nIndex].ptLE = [int(leX / 6), int(leY / 6)]\n list_Face[nIndex].ptRE = [int(reX / 6), int(reY / 6)]\n list_Face[nIndex].ptLM = [int(output_np[48 * 2 + 0]), int(output_np[48 * 2 + 1])]\n list_Face[nIndex].ptRM = [int(output_np[54 * 2 + 0]), int(output_np[54 * 2 + 1])]\n list_Face[nIndex].ptN = [int(output_np[30 * 2 + 0]), int(output_np[30 * 2 + 1])]\n\n torch.cuda.empty_cache()\n\n return output_np\n\n # else:\n # return []\n\n\ntransformations_emotionnet = transforms.Compose(\n [transforms.Grayscale(),\n transforms.CenterCrop(128),\n transforms.ToTensor()]\n)\n\ntransformations_headposenet = transforms.Compose(\n [transforms.Resize(224),\n transforms.CenterCrop(224), transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]\n)\n\n\ndef HeadPose_Estimation(HeadPose_Net, cvImg, list_Face, nIndex):\n # device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n oImg = cvImg[list_Face[nIndex].rt[1]:list_Face[nIndex].rt[3], \\\n list_Face[nIndex].rt[0]:list_Face[nIndex].rt[2]].copy()\n\n # cv2.imshow(\"ZZ\", oImg)\n # cv2.waitKey(0)\n\n idx_tensor = [idx for idx in range(66)]\n idx_tensor = torch.FloatTensor(idx_tensor).to(device)\n\n PILImg = Image.fromarray(oImg)\n\n img = transformations_headposenet(PILImg)\n img_shape = img.size()\n img = img.view(1, img_shape[0], img_shape[1], img_shape[2])\n img = Variable(img).to(device)\n\n yaw, pitch, roll = HeadPose_Net(img)\n\n yaw_predicted = F.softmax(yaw)\n pitch_predicted = F.softmax(pitch)\n roll_predicted = F.softmax(roll)\n\n yaw_predicted = torch.sum(yaw_predicted.data[0] * idx_tensor) * 3 - 99\n pitch_predicted = torch.sum(pitch_predicted.data[0] * idx_tensor) * 3 - 99\n roll_predicted = torch.sum(roll_predicted.data[0] * idx_tensor) * 3 - 99\n\n list_Face[nIndex].fYaw = yaw_predicted\n list_Face[nIndex].fPitch = pitch_predicted\n list_Face[nIndex].fRoll = roll_predicted\n\n torch.cuda.empty_cache()\n\n return (yaw_predicted, pitch_predicted, roll_predicted)\n\n\n\ndef list2SoftList(srcList):\n tmpList = srcList.copy()\n\n fSum = 0.\n\n for ii in range(len(srcList)):\n fExp = np.exp(srcList[ii])\n fSum = fSum + fExp\n tmpList[ii] = fExp\n for ii in range(len(srcList)):\n srcList[ii] = tmpList[ii] / fSum;\n\n return srcList\n\ndef Emotion_Classification(Emotion_Net, cvImg, list_Face, nIndex):\n if list_Face[nIndex].ptLE == [-1, -1]:\n return -1\n\n # 정규화 얼굴영역 이미지 생성\n img = cvImg.copy()\n ROIImg = faceAlignment(img, list_Face[nIndex].ptLE, list_Face[nIndex].ptRE\n , list_Face[nIndex].ptLM, list_Face[nIndex].ptLM)\n\n # image preprocessing\n PILROI = Image.fromarray(ROIImg)\n transformedImg = transformations_emotionnet(PILROI)\n transformedImg = torch.unsqueeze(transformedImg, 0)\n transformedImg = transformedImg.to(device)\n\n # emotion-net feedforward processing\n output_glasses = Emotion_Net(transformedImg)\n\n # 출력 결과 확률로 변환\n output_cpu = output_glasses.cpu().detach().numpy().squeeze()\n output = list2SoftList(output_cpu).tolist()\n\n # emotion label\n # surprise, fear, disgust, happy, sadness, angry, neutral\n list_Face[nIndex].nEmotion = output.index(max(output))\n for ii in range(7):\n list_Face[nIndex].fEmotionScore[ii] = output[ii]\n\n # torch.cuda.empty_cache()\n\ndef Gaze_Regression(list_Face, nIndex):\n if list_Face[nIndex].ptLE == [-1, -1] or list_Face[nIndex].fYaw == -1:\n return -1\n\n d2r = 3.141592 / 180.0\n #fDist = math.sqrt(pow(list_Face[nIndex].ptRE[0] - list_Face[nIndex].ptLE[0], 2) + pow(list_Face[nIndex].ptRE[1] - list_Face[nIndex].ptLE[1], 2))\n fDist = 20 * ((list_Face[nIndex].fPitch + list_Face[nIndex].fYaw)/2)\n\n normX = -1 * math.sin(d2r * list_Face[nIndex].fYaw) * fDist\n normY = -1 * math.sin(d2r * list_Face[nIndex].fPitch) * math.cos(d2r * list_Face[nIndex].fYaw) * fDist\n\n list_Face[nIndex].ptLED = [list_Face[nIndex].ptLE[0] + normX, list_Face[nIndex].ptLE[1] + normY]\n list_Face[nIndex].ptRED = [list_Face[nIndex].ptRE[0] + normX, list_Face[nIndex].ptRE[1] + normY]\n\n torch.cuda.empty_cache()\n\n return list_Face[nIndex].ptLED, list_Face[nIndex].ptRED\n\nclass pose_Detector():\n\n def __init__(self, mode=False, upBody=False, smooth=True, detectionCon=0.7, trackCon=0.5):\n\n self.mode = mode\n self.upBody = upBody\n self.smooth = smooth\n self.detectionCon = detectionCon\n self.trackCon = trackCon\n\n self.mpPose = mp.solutions.pose\n self.mpDraw = mp.solutions.drawing_utils\n self.pose = self.mpPose.Pose(self.mode, self.upBody, self.smooth, self.detectionCon, self.trackCon)\n\n def findPose(self, img, draw=True):\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n self.results = self.pose.process(imgRGB)\n\n # print(results.pose_landmarks)\n\n if self.results.pose_landmarks:\n if draw:\n self.mpDraw.draw_landmarks(img, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS)\n\n return img\n\n def gaze_Detector(self, gaze, img_show):\n if gaze != None:\n # print(\"gaze\", gaze)\n center_gaze_x = (gaze[0][0] + gaze[1][0]) / 2\n center_gaze_y = (gaze[0][1] + gaze[1][1]) / 2\n cv2.circle(img_show, (int(center_gaze_x), int(center_gaze_y)), 8, (0, 0, 255), -1)\n center_gaze = (int(center_gaze_x), int(center_gaze_y))\n return center_gaze\n\n\n def findPosition(self, img, draw=True):\n lmList = []\n if self.results.pose_landmarks:\n for id, lm in enumerate(self.results.pose_landmarks.landmark):\n h, w, c = img.shape\n cx, cy = int(lm.x * w), int(lm.y * h)\n lmList.append([id, cx, cy])\n cv2.circle(img, (cx, cy), 5, (255, 0, 0), cv2.FILLED)\n return lmList\n\n\n# def soundcheck(self):\n#\n# sound = AudioFileClip(self) # self = .mp4\n#\n# shortsound = sound.subclip(\"00:00:01\", \"00:00:10\") # audio from 1 to 10 seconds\n# # fileroute = 'C:/Users/withmind/Desktop/'\n# fileroute = '/home/ubuntu/project/'\n# filename = self + '.wav'\n# shortsound.write_audiofile(fileroute + filename, 44100, 2, 2000, \"pcm_s32le\")\n#\n# y, sr = librosa.load(fileroute + filename)\n# sound_result = 0\n# for i in y:\n# if y[-0] == 0.00:\n# print('음성확인 > ', False)\n# sound_result = 1\n# break\n# else:\n# if i == 0.00:\n# continue\n# else:\n# print('음성확인 > ', True)\n# sound_result = 0\n# break\n#\n# os.remove(fileroute + filename)\n#\n# return sound_result\n\nclass shoulder_movement:\n def shoulder_vertically(shoulder, Landmark_list):\n landmark_no7_y = Landmark_list[13]\n shoulder_move_list = []\n shoulder_move_count = 0\n\n if shoulder[1] >= landmark_no7_y:\n shoulder_move_list.append(1)\n else:\n if len(shoulder_move_list) > 1:\n shoulder_move_count = 1\n shoulder_move_list = []\n\n return shoulder_move_count\n\n def shoulder_horizontally(shoulder, Landmark_list):\n landmark_no5_x = Landmark_list[8]\n # print(landmark_no5_x)\n landmark_no13_x = Landmark_list[24]\n # print(landmark_no13_x)\n shoulder_left_move_list = []\n shoulder_left_move_count = 0\n shoulder_right_move_list = []\n shoulder_right_move_count = 0\n\n if shoulder[0] <= landmark_no5_x:\n shoulder_left_move_list.append(1)\n\n elif shoulder[0] >= landmark_no13_x:\n shoulder_right_move_list.append(1)\n\n else:\n if len(shoulder_left_move_list) > 1:\n shoulder_left_move_count = 1\n if len(shoulder_right_move_list) > 1:\n shoulder_right_move_count = 1\n\n return (shoulder_left_move_count, shoulder_right_move_count)\n\n def shoulder_vertical_low_high(shoulder_list):\n shoulder_low_y = max(t[1] for t in shoulder_list)\n shoulder_high_y = min(t[1] for t in shoulder_list)\n for x, y in enumerate(shoulder_list):\n if shoulder_low_y in y:\n shoulder_low_point = y\n if shoulder_high_y in y:\n shoulder_high_point = y\n\n return (shoulder_low_point , shoulder_high_point)\n\n def shoulder_horizon_left_right(shoulder_list):\n shoulder_left_x = min(t[0] for t in shoulder_list)\n shoulder_right_x = max(t[0] for t in shoulder_list)\n\n for x, y in enumerate(shoulder_list):\n if shoulder_left_x in y:\n shoulder_extreme_left_point = y\n if shoulder_right_x in y:\n shoulder_extreme_right_point = y\n\n return (shoulder_extreme_left_point, shoulder_extreme_right_point)\n\n\nclass Average:\n # Gaze 표준편차 / Gaze_Avg = [x_std, y_std] 리스트안 튜플\n def Gaze_Avg(self):\n df = pd.DataFrame(self, columns=['x', 'y'])\n x_std = round(np.std(df['x']))\n y_std = round(np.std(df['y']))\n\n GazeAvg_x = x_std\n GazeAvg_y = y_std\n\n return GazeAvg_x, GazeAvg_y\n\n # 어깨 상하 최고 길이 도출\n def vertically_Avg(Left_shoulder_high, Left_shoulder_low, Right_shoulder_high, Right_shoulder_low):\n Left_shoulder = Left_shoulder_high[1] - Left_shoulder_low[1]\n Right_shoulder = Right_shoulder_high[1] - Right_shoulder_low[1]\n\n if Left_shoulder > Right_shoulder:\n return Left_shoulder\n else:\n return Right_shoulder\n\n # 어깨 좌우 최고 길이 도출\n def horizontally_Avg(Center_shoulder_extreme_right, Center_shoulder_extreme_left):\n\n if Center_shoulder_extreme_right[0] >= Center_shoulder_extreme_left[0]:\n horizontally = Center_shoulder_extreme_right[0] - Center_shoulder_extreme_left[0]\n else:\n horizontally = Center_shoulder_extreme_left[0] - Center_shoulder_extreme_right[0]\n\n return horizontally\n\n def shoulder_left_count(self):\n count = 0\n for i in self:\n if i != 0:\n count += 1\n else:\n count += 0\n return count\n\n def shoulder_right_count(self):\n count = 0\n for i in self:\n if i != None:\n count += 0\n else:\n count += 1\n return count\n\n # 제스처 왼.오 큰값 도출\n def GestureTIME(Left_Hand_time, Right_Hand_time):\n Left_Hand = Left_Hand_time\n Right_Hand = Right_Hand_time\n\n if Left_Hand > Right_Hand:\n return Left_Hand\n else:\n return Right_Hand\n\n\n # def Average_csv(Gaze_value, Roll_value, Shoulder_value,vertically_value, horizontally_value, GestureTIME_value):\n # # ftp = FTP()\n # #\n # # ftp.connect('withmind.cache.smilecdn.com', 21)\n # # ftp.login('withmind', 'dnlemakdlsem1!')\n # # ftp.cwd('./analy_result')\n # filename = '/Average.csv'\n # # fileroute = 'C:/Users/withmind/Desktop'\n # fileroute = '/home/ubuntu/project'\n #\n # # CSV 누적\n # headersCSV = ['Gaze', 'Roll', 'Shoulder', 'vertically', 'horizontally', 'GestureTIME']\n # dict = {'Gaze': Gaze_value,\n # 'Roll': Roll_value,\n # 'Shoulder': Shoulder_value,\n # 'vertically': vertically_value,\n # 'horizontally': horizontally_value,\n # 'GestureTIME': GestureTIME_value\n # }\n #\n # with open(fileroute + filename, mode='a', encoding='utf-8', newline='') as csvfile:\n # wr = csv.DictWriter(csvfile, fieldnames=headersCSV)\n # wr.writerow(dict)\n #\n # os.remove(fileroute + filename)\n\n\n\nclass scoring:\n\n '''\n 구간별 점수 : 100점, 80점, 60점, 40점, 20점\n <시선 x> <얼굴 각도 >\n 1구간 1~5% = ~3 1구간 1~5% = ~1\n 2구간 6~25% = 4~5 2구간 6~25% = 2~7\n 3구간 26~75% = 6~18 3구간 26~75% = 8~28\n 4구간 76~95% = 19~33 4구간 76~95% = 29~46\n 5구간 95~100% = 34~ 5구간 95~100% = 47~\n\n <시선 y> <어깨 각도>\n 1구간 1~5% = ~2 1구간 1~5% = ~0\n 2구간 6~25% = 3~5 2구간 6~25% = 1~1\n 3구간 26~75% = 6~17 3구간 26~75% = 2~4\n 4구간 76~95% = 18~30 4구간 76~95% = 5~6\n 5구간 95~100% = 31~ 5구간 95~100% = 7~\n\n <어깨 상하> <어깨 좌우>\n 1구간 1~5% = ~13 1구간 1~5% = ~10\n 2구간 6~25% = 14~26 2구간 6~25% = 11~20\n 3구간 26~75% = 27~94 3구간 36~75% = 21~69\n 4구간 76~95% = 95~175 4구간 76~95% = 70~143\n 5구간 95~100% = 176~ 5구간 95~100% = 144~\n '''\n\n def GAZE_X_scoring(self):\n if self >= 34:\n return 20\n elif self >= 19:\n return 40\n elif self >= 6:\n return 60\n elif self >= 4:\n return 80\n else:\n return 100\n\n def GAZE_Y_scoring(self):\n if self >= 31:\n return 20\n elif self >= 18:\n return 40\n elif self >= 6:\n return 60\n elif self >= 3:\n return 80\n else:\n return 100\n\n def SHOULDER_VERTICAL_scoring(self):\n if self >= 176:\n return 20\n elif self >= 95:\n return 40\n elif self >= 27:\n return 60\n elif self >= 14:\n return 80\n else:\n return 100\n\n def SHOULDER_HORIZON_scoring(self):\n if self >= 144:\n return 20\n elif self >= 70:\n return 40\n elif self >= 21:\n return 60\n elif self >= 11:\n return 80\n else:\n return 100\n\n def FACE_ANGLE_scoring(self):\n if self >= 47:\n return 20\n elif self >= 29:\n return 40\n elif self >= 8:\n return 60\n elif self >= 2:\n return 80\n else:\n return 100\n #\n # def GESTURE_scoring(self):\n # if self >= 2:\n # return 60\n # elif self >= 1:\n # return 80\n # else:\n # return 100\n\n def SHOULDER_ANGLE_scoring(self):\n if self >= 7:\n return 20\n elif self >= 5:\n return 40\n elif self >= 2:\n return 60\n elif self >= 1:\n return 80\n else:\n return 100","repo_name":"EndewSeoho/video_async","sub_path":"analy/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":22101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"22489062943","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n import queue\n output = []\n q = queue.Queue()\n q.put(root)\n while not q.empty():\n level = queue.Queue()\n level_output = []\n while not q.empty():\n tmp = q.get()\n if tmp == None:\n continue\n level_output.append(tmp.val)\n level.put(tmp.left)\n level.put(tmp.right)\n if level_output != []:\n output.append(level_output)\n q = level\n return output\n\n\nsol = Solution()\nroot = TreeNode(1)\nroot.left = TreeNode(4)\nroot.right = TreeNode(2)\nroot.right.right = TreeNode(8)\nprint(sol.levelOrder(root))","repo_name":"Fernadoo/LeetCode","sub_path":"top_400/tree/102_binaary_tree_level_order_traversal.py","file_name":"102_binaary_tree_level_order_traversal.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"34051430762","text":"from random import randint as RI\nfrom time import time, sleep\nimport pyxel as px\n\n\nfrom pyxel_code.message_classes import CombatText\nfrom pyxel_code.utils import items as itm, Interactable # Application Imports \nfrom .dicts import * # Application Imports\nfrom .item_screen import EquippedItems, Backpack # Application Imports\nfrom pyxel_code.image_classes import Sprite, DisplayText # Application Imports\n\n# from ..pyxel_code.image_classes import Sprite # Test Import Path\n\n\ndex = [-1, 2]\nstrength = [-3, 4]\nintelligence = [-1, 1]\n\n\nrirs = randint(0,1) # randint small (0,1)\nrirm = randint(-1,1) # randint medium (-1,1)\nnrn = randint(0,2)\n\n\n\nclass Character():\n def __init__ (self, name, strength, dexterity, intelligence, constitution, armor=0, resistance=0):\n self.name = name\n # Items\n self.lifetime_currency = 0\n self.currency = 0\n self.bag = Backpack(self)\n self.items_worn = self.bag.equipped\n\n # Stats and whatnot\n self.armor = armor # 0 if self.items_worn.placement['slot']['body'] == {'nothing':'nothing'} else itm[self.items_worn.placement['slot']['body']['armor_value']]\n self.resistance = resistance\n self.strength = strength\n self.dexterity = dexterity\n self.intelligence = intelligence\n self.constitution = constitution\n self.hp = self.constitution * 2\n self.max_mp = self.intelligence * 2\n self.weapon = {} if self.items_worn.slot['hand'] == {'nothing':'nothing'} else itm[self.items_worn.slot['hand']]\n self.weapon_damage = self.weapon['damage'] if 'damage' in self.weapon else 0\n self.damage = strength // 2 + self.weapon_damage if strength > 2 else 1 + self.weapon_damage\n self.attribute_list = []\n # self.level = 1\n\n # Ability list\n self.abilities = []\n self.abilities.append(self.attack)\n self.abilities.append(self.dodge)\n self.abilities.append(self.defend)\n self.abilities.append(self.flee)\n \n # // Persistent changed stats //\n self.current_hp = self.hp\n self.current_mp = self.max_mp \n\n \n\n # // Temp Stat changes //\n self.armor_val = armor\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage_val = self.damage\n self.dodge_val = dexterity // 2 if dexterity > 2 else 1\n self.resist_val = self.resistance\n\n \n\n \n # // STATUSES //\n # Status flags\n self.defended = False #incrementer\n self.dodging = False # Incrementor\n self.fleeing = False # Incrementor\n self.stone_armored = False # Incrementor\n self.slowed = False # Incrementor\n self.vulnerable = False # Incrementor\n self.double_armed = False # Incrementor\n self.burning_blades = False # Incrementor = damage = magic\n self.stone_fists = False # Incrementor = Bonus damage\n\n # No incrementors/counters\n self.poisoned = False \n self.burning = False\n self.wind_hit_by = False \n self.stunned = False \n\n # Status Incrementors\n self.dodging_rounds = 0\n self.defended_rounds = 0\n self.flee_count = 0\n self.slowed_rounds = 0\n self.stone_armored_rounds = 0\n self.vulnerable_rounds = 0\n self.double_armed_rounds = 0\n self.burning_blades_rounds = 0\n self.burning_rounds = 0\n self.poisoned_rounds = 0\n self.set_attribute_list()\n # self.set_currency()\n\n self.game = None\n self.combat_state = None\n\n\n\n def attack(self, target):\n damage_num = 0\n stat_mod = 0\n\n # Setting which attack modifier to use based on high stat\n if self.dexterity > self.strength and self.dexterity > self.intelligence:\n stat_mod = dex\n\n elif self.strength > self.dexterity and self.strength > self.intelligence:\n stat_mod = strength\n\n elif self.intelligence > self.dexterity and self.intelligence > self.strength:\n stat_mod = intelligence\n\n # checking for hitting and critting, then assigning damage and calling damage function\n attack_mod = RI(*stat_mod)\n if attack_mod == max(stat_mod):\n damage_num = (self.damage + 2)\n self.in_combat_text(f'''{self.name.title()} attacks!\n \n**Critical hit!**''')\n self.attack_damage(target, damage_num)\n\n elif self.att_val + RI(*stat_mod) <= target.dodge_val:\n self.in_combat_text(f'{self.name.title()} attacks!')\n self.in_combat_text(f\"{self.name.title()} missed!\")\n \n elif self.att_val + RI(*stat_mod) > target.dodge_val:\n self.in_combat_text(f'{self.name.title()} attacks!')\n damage_num = (self.damage + RI(*stat_mod)) - target.armor_val\n self.attack_damage(target, damage_num)\n\n return attack_mod, damage_num\n\n\n\n def attack_damage(self, target, damage_num):\n if damage_num > 0:\n self.in_combat_text(f'''{target.name.title()} was hit! \n{str(damage_num)} damage!''',)\n target.current_hp -= damage_num\n if target.current_hp <= 0:\n target.current_hp = 0\n # self.in_combat_text(f\"\\n{target.name.title()} has been defeated.\")\n # # del target\n elif damage_num <= 0 and target.name[-1] != \"s\":\n self.in_combat_text(f\"\"\"{target.name.title()} blocks \n{self.name.title()}' strike.\"\"\")\n elif damage_num <= 0 and target.name[-1] == \"s\":\n self.in_combat_text(f\"\"\"{target.name.title()} blocks\n{self.name.title()}'s strike.\"\"\")\n \n\n def wear_armor(self):\n self.armor = 0 if self.items_worn.placement['slot']['body'] == 'nothing' else itm[self.items_worn.placement['slot']['body']['armor_value']]\n self.armor_val = self.armor\n\n def defend(self):\n if self.defended:\n self.defended_rounds = 0\n self.in_combat_text(f\"\"\"{self.name}\nis defending\"\"\")\n else:\n self.armor_val += 2\n self.defended = True\n if self.class_name == 'player':\n print(f'You are defended: Armor val = {self.armor_val} ')\n self.in_combat_text(f\"\"\"You defend. \nArmor: {self.armor_val}\"\"\")\n else:\n self.in_combat_text(f'''{ self.combat_state.enemy} \nhunkers down to defend.''')\n # rnd_count = 2\n\n def undefend(self):\n self.armor_val -= 2\n self.defended = False\n self.defended_rounds = 0\n if self.class_name != 'player':\n self.in_combat_text(f'''{ self.combat_state.enemy} \nrelaxes their guard.''')\n\n def dodge(self):\n if self.dodging == True:\n self.dodging_rounds = 0\n self.in_combat_text(f\"{self.name} is dodging\")\n else:\n self.dodging = True\n self.dodge_val += 2\n if self.class_name == 'player':\n self.in_combat_text(f\"\"\"You focus on dodging.\"\"\")\n else:\n self.in_combat_text(f'''{ self.combat_state.enemy} \ndances about nimbly.''')\n # rnd_count = 2\n\n def undodge(self):\n self.dodging = False\n self.dodging_rounds = 0\n self.dodge_val -= 2\n\n def flee(self, enemy):\n if self.dexterity > enemy.dexterity or self.flee_count > 0: \n self.fleeing = True\n else:\n self.flee_count += 1\n self.in_combat_text(f'You try to run')\n return False\n\n def __repr__(self):\n return self.name.title()\n\n def stone_armor(self):\n if self.stone_armored == True:\n self.in_combat_text(F'''{self.name}\nis already protected''')\n else:\n self.armor_val += 2\n self.stone_armored = True\n print(f\"You cast a spell to boost your armor. Armor: {self.armor_val}\")\n\n def slow(self):\n if self.slowed:\n self.slowed_rounds = 0\n print(f\"{self.name} is already slowed\")\n else:\n self.dodge_val -= 2\n self.slowed = True\n print(f\"{self.name} is slowed\")\n \n def unslow(self):\n self.dodge_val += 2\n self.slowed_rounds = 0\n self.slowed = False\n\n def vulnerability(self):\n if self.vulnerable:\n print(f\"{self.name} is already vulnerable.\")\n else:\n self.resist_val -= 2\n self.vulnerable = True\n print(f\"{self.name} is now vulnerable to magic.\")\n\n def stone_armor_2(self):\n self.armor_val = self.armor + 4\n self.double_armed = True\n print(f\"You cast a spell to boost your armor. Armor: {self.armor_val}\")\n\n def damage_to_magic(self):\n # alter the attack action to add default parameters that can be over written\n pass\n\n def stony_fists(self):\n self.stone_fists = True\n self.damage_val = self.damage + 4\n print(f\"You cast a spell to boost your damage. Damage: {self.damage_val}\")\n\n def poison(self):\n if self.poisoned:\n print(f\"{self.name} is already poisoned!\")\n else:\n self.poisoned = True\n self.in_combat_text(f\"\"\"{self.name} \nis poisoned\"\"\")\n\n def unpoison(self):\n self.poisoned = False\n self.poisoned_rounds = 0\n self.in_combat_text(\"\"\"You recover\nfrom poison\"\"\")\n\n def burn_baby_burn(self):\n if self.burning:\n print(f\"{self.name} is already on fire!\")\n else:\n self.burning = True\n print(f\"{self.name} caught on fire!\")\n\n def in_the_wind(self):\n self.wind_hit_by = True\n\n def stun(self):\n if self.stunned == True:\n self.stunned_rounds = 0\n else:\n self.stunned = True\n\n def unstun(self):\n self.stunned = False\n self.stunned_rounds = 0\n \n def level_attribute(self, stat_choice:str, new_stat:int = 1):\n if stat_choice == 'STR':\n self.strength = new_stat\n elif stat_choice == 'DEX':\n self.dexterity = new_stat\n elif stat_choice == 'INT':\n self.intelligence = new_stat\n elif stat_choice == 'CON':\n self.constitution = new_stat\n self.set_hp()\n \n self.set_attribute_list()\n self.set_dependant_atts()\n \n def set_hp(self):\n self.hp = self.constitution * 2\n \n\n def set_attribute_list(self):\n self.attribute_list= [\n {'name': \"STR\", \"att\":self.strength}, {'name': \"DEX\", \"att\": self.dexterity}, \n {'name': \"CON\", \"att\": self.constitution}, {'name': \"INT\", \"att\": self.intelligence}\n ]\n\n def set_dependant_atts(self):\n self.current_hp = self.hp\n self.armor_val = self.armor if self.armor >= 0 else 0\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.damage_val = self.damage\n self.dodge_val = self.dexterity // 2 if self.dexterity > 2 else 1\n self.resist_val = self.resistance\n\n self.current_mp = self.max_mp\n\n def change_outfit(self, outfit:tuple):\n self.u = outfit[0]\n self.v = outfit[1]\n\n def reset_flags(self):\n # print('reseting flags')\n self.defended = False #incrementer\n self.dodging = False # Incrementor\n self.fleeing = False # Incrementor\n self.stone_armored = False # Incrementor\n self.slowed = False # Incrementor\n self.vulnerable = False # Incrementor\n self.double_armed = False # Incrementor\n self.burning_blades = False # Incrementor = damage = magic\n self.stone_fists = False # Incrementor = Bonus damage\n self.stunned = False\n self.dodging_rounds = 0\n self.defended_rounds = 0\n self.flee_count = 0\n self.slowed_rounds = 0\n self.stone_armored_rounds = 0\n self.vulnerable_rounds = 0\n self.double_armed_rounds = 0\n self.burning_blades_rounds = 0\n self.burning_rounds = 0\n self.poisoned_rounds = 0\n\n\n def in_combat_text(self, combat_text, display_time:float = 1.5):\n self.add_text(self.combat_state, combat_text, {'display_time':display_time})\n\n\n def add_text(self, combat_state:object, text:str, kwarg_dict:dict):\n # print(f'Game text length = {len(self.game.text)}')\n if len(self.game.text) < 1:\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n elif len(self.game.text) >= 1:\n if self.game.text[-1] == Interactable.unfreeze:\n print('pop and switch')\n popped = self.game.text.pop()\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n self.game.text.append(popped)\n else:\n self.game.text.append({'combat_state': combat_state, 'combat_text': text, **kwarg_dict})\n\n\n \n def equip(self):\n self.armor = 0 if self.items_worn.slot['body'] == {'nothing':'nothing'} else self.items_worn.slot['body'].item_stat\n self.weapon = {} if self.items_worn.slot['hand'] == {'nothing':'nothing'} else self.items_worn.slot['hand']\n self.weapon_damage = self.weapon.item_stat if self.weapon else 0\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.armor_val = self.armor\n\n\nclass Player(Character, Sprite):\n def __init__(self, name, strength, dexterity, intelligence, constitution, v, job, x=164, y=64, game:object = None, armor=0, resistance=0):\n super().__init__(name, strength, dexterity, intelligence, constitution, armor, resistance)\n self.class_name = 'player'\n self.job = job\n self.u=8\n self.v=v\n self.x = x\n self.y= y\n self.w=8\n self.h=8\n self.bank = 2\n self.colkey = 7\n # self.draw_sidebar()\n self.running = False\n\n\n def combat_draw(self):\n self.draw()\n px.text(168, 34, f\"HP:{self.current_hp}/{self.hp}\", 7)\n\n def draw_sidebar(self):\n stat_list = []\n\n px.text(12, 24, f'NAME: {self.name}', 7)\n px.text(12, 32, f\"HP: {self.current_hp}/{self.hp}\", 7)\n px.text(12, 42, f\"STR: {self.strength}\", 7)\n px.text(12, 50, f\"DEX: {self.dexterity}\", 7)\n px.text(12, 58, f\"CON: {self.constitution}\", 7)\n px.text(12, 66, f\"INT: {self.intelligence}\", 7)\n px.text(12, 76, f\"Attack: {self.att_val}\", 7)\n px.text(12, 84, f\"Damage: {self.damage}\", 7)\n px.text(12, 92, f\"Defense: {self.armor_val}\", 7)\n px.text(12, 100, f\"Resistance: {self.resistance}\", 7)\n px.text(12, 108, f\"Dodge: {self.dodge_val}\", 7)\n px.text(12, 118, f\"Trophies: {self.currency}\", 7)\n\n # placeholder\n # px.text(32, 118, \"Quit\", 0)\n\n def intersects(self, mouse_location:tuple):\n is_intersected = False\n if (\n px.mouse_x > self.x and px.mouse_x < self.x + self.w\n and px.mouse_y > self.y and px.mouse_y < self.y + self.h + 2\n ):\n is_intersected = True\n return is_intersected\n\n def intersection(self):\n self.character_choice_text()\n \n def character_choice_text(self):\n px.text(116, 84, self.name, 7)\n px.text(84, 92, f\"Job: {self.job} \", 7)\n px.text(86, 102, f'{background_stats[self.name][\"description\"]}', 7)\n\n def set_combat_atts(self):\n self.armor_val = self.armor if self.armor >= 0 else 0\n self.att_val = self.dexterity // 2 if self.dexterity > self.strength else self.strength // 2\n self.damage = self.strength // 2 + self.weapon_damage if self.strength > 2 else 1 + self.weapon_damage\n self.damage_val = self.damage\n self.dodge_val = self.dexterity // 2 if self.dexterity > 2 else 1\n self.resist_val = self.resistance","repo_name":"Nephilus-notes/The-Dragon-s-Tail","sub_path":"old_code/character_builder.py","file_name":"character_builder.py","file_ext":"py","file_size_in_byte":16213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"2527086728","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 24 11:08:44 2022\r\n\r\n@author: Simon (Python 3.8)\r\nGiven a full 2\\theta integration scan from XRDSol, \r\nplot the contour plot (x, y, z(x,y)) -> (time, q, intensity)\r\nand save individual arrays/matrices as .csv files in a separate folder called\r\n'output'.\r\n\r\nIdeas for improvements:\r\n - label orientations or give separate table with q values and reflexes\r\n - eliminate user input necessities\r\n - Make get data more efficient by pre-defining q array with random values\r\n and then replace consecutively\r\n - Check if csv file already exists and only convert if it doesn't\r\n \r\n \r\nKnown bugs:\r\n - Depending on the host computer settings, XRDSol saves the scan images with \r\ndifferent time formats, for example 1:23 PM instead of 13:23. Pandas \r\ninterprets the AM/PM part as additional column. To eliminate this bug, append/\r\ndelete last column name in the array -names- and placeholder variable in\r\nline.split(',') (for-loop in get_data).\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport os\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom tqdm import tqdm\r\nfrom pathlib import Path\r\nimport ntpath\r\nfrom matplotlib import cm\r\nfrom matplotlib.ticker import LinearLocator\r\n\r\n\r\n### USER INPUTS:\r\n \r\n# The output scan seperators are irregular tab spaces. \r\n# The following saves the output scan as a csv file:\r\nfile_path = r\"C:\\Users\\User\\Desktop\\LBL\\BT_December\\ZnO_SAM\\GIWAXS\\ZnO_SAM.dat\" # absolute location of \r\n # scan, must be .dat file!\r\ntime_per_frame = 1.844 # in sec\r\nnum_frames = 675 # input the number of frames in the scan\r\n# plt.style.use('seaborn-white') # uncomment, restart kernel for other style\r\n\r\n### OTHER:\r\n \r\nfile_name = ntpath.basename(file_path)\r\nsample_name = file_name.rstrip('.dat') # under which name data is saved later\r\nPath(os.path.join(file_path.rstrip(file_name), 'output_' + sample_name)).mkdir(parents=True, exist_ok=True)\r\nsave_path = os.path.join(file_path.rstrip(file_name), 'output_' + sample_name)\r\n# print('Converting to csv...')\r\nfile = pd.read_csv(file_path, sep='\\s+', header=0, names=np.array(['image_num', 'twotheta', 'twotheta_cuka', 'dspacing', 'qvalue', 'intensity', 'frame_number', 'izero', 'date', 'time', 'am']))\r\ncsv_path = os.path.join(save_path, sample_name + '.csv')\r\nfile.to_csv(csv_path, index=0)\r\nlength = len(file)\r\n\r\n\r\n### CODE:\r\n\r\n# =================Part 1: Loading Data======================\r\n\r\ndef get_data(csv_path, frames, sample_name, save_path, time_per_frame):\r\n '''\r\n Parameters\r\n ----------\r\n csv_path : path object, \r\n points towards the saved csv file.\r\n frames : int,\r\n imports the total number of frames taken for the scan\r\n sample_name : str,\r\n name of the sample. Default is the name under which scan is saved.\r\n save_path : path object\r\n where the output is saved.\r\n\r\n Returns\r\n -------\r\n three arrays, q, frame_num and full_intensity which are one, one and two \r\n dimensional, respectively. These are saved as csv files.\r\n\r\n '''\r\n with open(csv_path, 'r') as data_file:\r\n counter = 1\r\n q = np.array([])\r\n q_size = int(length/frames)\r\n full_intensity = np.zeros(shape=(frames, q_size))\r\n frame_intensity = np.array([])\r\n data_file.readline()\r\n for line in tqdm(data_file, desc = 'Gathering data'):\r\n imagenum, twotheta, twotheta_cuka, dspacing, qvalue, intensity, frame_number, izero, date, time, am = line.split(',')\r\n if int(frame_number) == counter:\r\n intensity = np.array([float(intensity)])\r\n q = np.append(q, float(qvalue)) \r\n frame_intensity = np.append(frame_intensity, intensity)\r\n else:\r\n full_intensity[int(counter) - 1] = frame_intensity\r\n counter += 1\r\n # clearing the arrays that save the data of each frame\r\n q = np.array([]) \r\n frame_intensity = np.array([])\r\n # save data of current line\r\n q = np.append(q, float(qvalue))\r\n frame_intensity = np.append(frame_intensity, intensity)\r\n # save last frame values\r\n full_intensity[frames - 1] = frame_intensity\r\n data_file.close()\r\n frame_num = np.linspace(0, int(frames)-1, int(frames))\r\n \r\n # saving the data in separate csv files\r\n df_q = pd.DataFrame(q)\r\n df_t = pd.DataFrame(frame_num * time_per_frame + time_per_frame/2)\r\n df_i = pd.DataFrame(full_intensity.T)\r\n \r\n df_q.to_csv(os.path.join(save_path, 'reciprocal_' + sample_name + '.csv'), header = ['Q r$(1/\\AA\\)$'], index = None)\r\n df_t.to_csv(os.path.join(save_path, 'time_' + sample_name + '.csv'), header = ['Time (s)'], index = None)\r\n df_i.to_csv(os.path.join(save_path, 'intensity_' + sample_name + '.csv'), header = frame_num, index = None)\r\n # Note: intensity matrix saved with frames for columns and qs for rows\r\n print('\\n Saved data in: ' + save_path)\r\n \r\n return (q, frame_num, full_intensity.T)\r\n\r\n# =================Part 2: Contour plot======================\r\n\r\ndef plot_contour(csv_path, frames, sample_name, save_path, time_per_frame):\r\n '''\r\n Parameters\r\n ----------\r\n csv_path : path object, \r\n points towards the saved csv file.\r\n frames : int,\r\n imports the total number of frames taken for the scan\r\n sample_name : str,\r\n name of the sample. Default is the name under which scan is saved.\r\n save_path : path object\r\n where the output is saved.\r\n time_per_frame: float.\r\n\r\n Returns\r\n -------\r\n Contour plot\r\n\r\n '''\r\n # call/define variables for contour plot\r\n q, frame_num, intensity = get_data(csv_path, frames, sample_name, save_path, time_per_frame)\r\n \r\n # create an empty figure with the following dimensions\r\n fig = plt.figure(figsize=(6,5))\r\n left, bottom, width, height = 0.1, 0.1, 0.8, 0.8\r\n ax = fig.add_axes([left, bottom, width, height]) \r\n \r\n # add the contour plot and a colorbar\r\n cp = plt.contourf(frame_num*time_per_frame, q, intensity, np.linspace(0, np.amax(intensity), 100))\r\n plt.colorbar(cp, location='left', ticks = np.arange(0, np.amax(intensity), 1000))\r\n \r\n # define axis names, ticks, etc.\r\n q_min, q_max = (q[0], q[-1])\r\n q_min, q_max = (0.5, 3.5)\r\n y_ticks = np.linspace(q_min, q_max, 20) # number of tickmarks \r\n ax.set_xlabel('Time (s)')\r\n ax.set_ylabel(r'Q $(\\AA^{-1})$')\r\n ax.set_yticks(y_ticks)\r\n ax.yaxis.tick_right()\r\n ax.yaxis.set_label_position(\"right\")\r\n ax.set_ylim(q_min, q_max)\r\n ax.set_title(sample_name)\r\n plt.savefig(os.path.join(save_path, 'Contour_plot_' + str(sample_name)), dpi = 300, bbox_inches = \"tight\")\r\n plt.show()\r\n\r\n# =================Part 3: Surface plot (WORK IN PROGRESS)======================\r\n\r\ndef plot_surface(csv_path, frames, sample_name, save_path, time_per_frame, q_range, frame_range):\r\n q, frame_num, intensity = get_data(csv_path, frames, sample_name, save_path, time_per_frame)\r\n \r\n fig = plt.figure(figsize=(6,5))\r\n left, bottom, width, height = 0.1, 0.1, 0.8, 0.8\r\n ax = fig.add_axes([left, bottom, width, height]) \r\n \r\n surf = ax.plot_surface(frame_num*time_per_frame + time_per_frame/2, q, intensity, cmap=cm.coolwarm,\r\n linewidth=0, antialiased=False)\r\n\r\n\r\n\r\nplot_contour(csv_path, num_frames, sample_name, save_path, time_per_frame)\r\n# plot_surface(csv_path, num_frames, sample_name, save_path, time_per_frame, (0.5, 2.0), (25, 45))\r\n","repo_name":"simonwb98/XRDSol-supplementary","sub_path":"contour_plot.py","file_name":"contour_plot.py","file_ext":"py","file_size_in_byte":7605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"14859528924","text":"from typing import Dict, List\n\nimport numpy as np\nfrom tensorflow import keras\nfrom the_game.game_env import GameEnv, Heap, Player\n\n\nclass InvalidActionError(Exception):\n \"\"\"\n Raise on invalid action from LearningPlayer.\n Useful for learning.\n \"\"\"\n\n\nclass LearningPlayer(Player):\n CARD_ACTIONS = [\n f\"card_{x}::{action}\"\n for x in range(8)\n for action in [\n \"heap_up_1\",\n \"heap_up_2\",\n \"heap_down_1\",\n \"heap_down_2\",\n ]\n ]\n\n PASS_ACTION = \"pass\"\n ACTIONS = [\n *CARD_ACTIONS,\n PASS_ACTION,\n ]\n\n OBSERVATION = [\n \"heap_up_1\",\n \"heap_up_2\",\n \"heap_down_1\",\n \"heap_down_2\",\n *[f\"card_{x}\" for x in range(8)],\n ]\n\n def __init__(self, game_env: GameEnv):\n super().__init__(game_env)\n self.turn_played_cards = 0\n self.model: keras.Model = None\n\n @property\n def heaps(self) -> Dict[str, Heap]:\n return {\n \"heap_up_1\": self.game_env.heaps[Heap.HEAP_UP][0],\n \"heap_up_2\": self.game_env.heaps[Heap.HEAP_UP][1],\n \"heap_down_1\": self.game_env.heaps[Heap.HEAP_DOWN][0],\n \"heap_down_2\": self.game_env.heaps[Heap.HEAP_DOWN][1],\n }\n\n @property\n def observation(self) -> List[int]:\n \"\"\"\n Return observation for neural network.\n :return: [\n heap_up_1,\n heap_up_2,\n heap_down_1,\n heap_down_2,\n hand_cards...\n ]\n :rtype: List[int]\n \"\"\"\n\n observation = []\n\n for heap in (\n self.game_env.heaps[Heap.HEAP_UP] + self.game_env.heaps[Heap.HEAP_DOWN]\n ):\n observation.append(heap.heap[0])\n\n observation.extend(sorted(self.hand))\n observation.extend([0] * (8 - len(self.hand)))\n\n return observation\n\n def play_action(self, action) -> int:\n \"\"\"\n Play action according to its index.\n Return the gain on heap.\n :param action:\n :type action:\n :return:\n :rtype:\n \"\"\"\n if self.ACTIONS[action] == self.PASS_ACTION:\n if (self.game_env.remaining_cards > 0 and self.turn_played_cards < 2) or (\n self.game_env.remaining_cards == self.turn_played_cards == 0\n ):\n raise InvalidActionError\n\n self.turn_played_cards = 0\n return 50\n\n sorted_hand = sorted(self.hand)\n card_label, heap_label = self.ACTIONS[action].split(\"::\")\n card_index = int(card_label.split(\"_\")[1])\n\n # invalid selection from neural network\n if card_index >= len(sorted_hand):\n raise InvalidActionError\n\n played_heap = self.heaps[heap_label]\n played_card = sorted_hand[card_index]\n\n # compute gain\n if played_heap.direction == Heap.HEAP_UP:\n gain = played_heap.heap[0] - played_card\n else:\n gain = played_card - played_heap.heap[0]\n\n if self.play_card(played_card, played_heap) is True:\n self.turn_played_cards += 1\n return gain + 100\n else:\n raise InvalidActionError\n\n def can_play(self) -> bool:\n \"\"\"\n Check if player can play with his current hand.\n :return:\n :rtype:\n \"\"\"\n for card in self.hand:\n for heap in self.game_env.heap_list:\n if heap.validate_card(card) is True:\n return True\n return False\n\n def play(self):\n assert self.model is not None, \"Please setup model.\"\n\n while self.can_play():\n\n observation = np.array(self.observation)\n predictions = self.model.predict(np.expand_dims(observation, axis=0))[0]\n\n for _ in range(len(predictions)):\n selected_action: int = np.argmax(predictions)\n\n try:\n result = self.play_action(selected_action)\n except InvalidActionError:\n predictions[selected_action] = 0.0\n continue\n\n print(\"Observation:\", observation)\n print(\"Played:\", LearningPlayer.ACTIONS[selected_action])\n\n if result == 50:\n print(\"Draw.\")\n return\n break\n","repo_name":"Swelio/TheGameSolver","sub_path":"project_package/learning_player.py","file_name":"learning_player.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"26823107638","text":"import json\nimport re\nfrom lxml import etree\nfrom html import unescape\n\n\ndef load_jsonl_file(fn):\n data = []\n with open(fn, mode='r', encoding='utf8') as f:\n for line in f:\n data.append(json.loads(line))\n f.close()\n return data\n\n\ndef dump_jsonl_file(data: list, fn):\n with open(fn, mode='w', encoding='utf8') as f:\n for item in data:\n f.write(json.dumps(item, ensure_ascii=False))\n f.write('\\n')\n f.close()\n\n\ndef html2text(html, escape=False):\n if escape:\n html = unescape(html)\n\n tree = etree.HTML(html)\n if tree is None: return \"\"\n texts = tree.xpath('//text()')\n # texts = [re.sub(r'(\\xa0|\\uf0b7)', ' ', text) for text in texts]\n text = re.sub(r'\\s+', ' ', ' '.join(texts))\n return text\n","repo_name":"vudat1710/fashion_engine","sub_path":"backend/process_data/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"34670873288","text":"import os\nimport numpy as np\nfrom glob import iglob\nfrom scipy.io import loadmat, savemat\nfrom os.path import join, basename, splitext\n#from random import shuffle\n#from math import floor\n\n\nTYPE = ['clean', '-2.5db', '0db', '2.5db', '5db', '7.5db']\nPERSON = ['100','101','102','103','104','105','106','107','108','109','111','112','113','114','115','116','117','118','119','121','122','123','124','200','201','202','203','205','207','208','209','210','212','213','214','215','217','219','220','221','222','223','228','230','231','232','233','234']\n\ndef main(dirname):\n #os.mkdir('dataset')\n for m in TYPE:\n if not os.path.exists('dataset/'+m):\n os.mkdir('dataset/'+m)\n node = 1024\n train = np.zeros((1, node))\n train_lab = []\n for p in PERSON:\n label = []\n path = join(dirname, m, p )\n data = np.zeros((1, node))\n for f in iglob(path + '/*mat'):\n filename = join(path, f)\n #print(filename)\n mat = loadmat(filename)\n name = splitext(basename(f))[0]\n #print(name)\n label.append(name)\n sig = mat['temp']\n #sig = np.reshape(sig, (5, node))\n data = np.concatenate([data, sig], axis=0)\n train = np.concatenate([train, data[1:]], axis=0)\n train_lab.append(np.asarray(label[:]))\n #print(test_lab)\n #np.save('dataset/' + '/train_{}'.format(), train[1:])\n #np.save('dataset/' + '/train_name_{}', train_lab)\n np.save('dataset/' + m + '/train', train[1:]) \n np.save('dataset/' + m + '/train_name', train_lab)\n print(train.shape)\n #print(train_lab)\n\n\nif __name__ == '__main__':\n main('/mnt/intern/user_sophie/short_ecg_0_1/train')\n\n","repo_name":"sophie091524/Noise-Reduction-in-ECG-Signals","sub_path":"buid_data/build_train.py","file_name":"build_train.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"52"}
+{"seq_id":"42063547423","text":"from django.shortcuts import redirect, render\nfrom .forms import ClientForm\nfrom django.contrib import messages\n# Create your views here.\ndef index(request):\n if request.method == \"POST\":\n clientform = ClientForm(request.POST)\n if clientform.is_valid():\n clientform.save()\n messages.success(request,\"Thank You For Your Response We Will Contact You Soon\")\n return redirect('html/index.html')\n else:\n messages.error(request,\"Something Is Wrong Sorry For Inconvinience\")\n else:\n clientform =ClientForm() \n return render(request,'html/index.html',{'clientform':clientform})\n","repo_name":"Prateeklodhi/Official","sub_path":"perftechsolapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"32880462998","text":"from ..items import *\nfrom ..str_filter import *\n\nclass Collection87(scrapy.Spider):\n name = \"Collection87\"\n allowed_domains = ['ahbbmuseum.com']\n start_urls = ['https://www.ahbbmuseum.com/?list_4/',\n 'https://www.ahbbmuseum.com/?list_4_2/',\n 'https://www.ahbbmuseum.com/?list_4_3/',\n 'https://www.ahbbmuseum.com/?list_4_15/',\n 'https://www.ahbbmuseum.com/?list_4_21/',\n 'https://www.ahbbmuseum.com/?list_4_35/',\n 'https://www.ahbbmuseum.com/?list_4_45/',\n 'https://www.ahbbmuseum.com/?list_4_60/']\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'mySpider.pipelines.CollectionPipeLine': 301,\n },\n 'DOWNLOADER_MIDDLEWARES': {\n 'mySpider.middlewares.DefaultMiddleware': 0,\n },\n }\n\n def parse(self, response, **kwargs):\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]\n li_list = response.xpath(\"/html/body/div[2]/div[2]/div/div/div[2]/ul/li\")\n for li in li_list:\n item = CollectionItem()\n item[\"museumID\"] = 87\n item[\"museumName\"] = \"蚌埠市博物馆\"\n\n\n # 注意是否为全路径,一般后缀为@src有的是@oldsrc\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]/a/div[1]/img\n #https://www.ahbbmuseum.com/static/upload/image/20210205/1612490736211016.jpg\n item['collectionImageLink'] = \"https://www.ahbbmuseum.com/\" + li.xpath(\"./a/div[1]/img/@src\").extract_first()\n\n\n #注意是否是全路径\n #怎么判断是否是全路径\n #https://www.ahbbmuseum.com/?list_19/1180.html\n #/html/body/div[2]/div[2]/div/div/div[2]/ul/li[1]/a\n url = \"https://www.ahbbmuseum.com/\" + str(li.xpath(\"./a/@href\").extract_first())\n\n yield scrapy.Request(\n url,\n callback=self.parseAnotherPage,\n meta={\"item\": item}\n )\n # 翻页\n def parseAnotherPage(self, response):\n r = re.compile(u\"\\\\n|\\\\r|\\\\[.*?]|\\\\t\")\n item = response.meta[\"item\"]\n\n # 名字的xpath都一样\n # /html/body/div[6]/div/ul/li[1]/div/span[1]\n r = re.compile(u\"\\\\n|\\\\r|\\\\[.*?]|\\\\t\")\n item['collectionName'] = response.xpath(\"/html/body/div[2]/div[2]/div/div/h1/text()\").extract_first()\n item[\"collectionName\"] = \"\".join(item[\"collectionName\"].split())\n item[\"collectionName\"] = re.sub(r, '', item[\"collectionName\"])\n\n item[\"collectionIntroduction\"] = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[4])').extract_first()\n item[\"collectionIntroduction\"] = StrFilter.filter_2(item[\"collectionIntroduction\"])\n\n str2 = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[6])').extract_first()\n str2 = StrFilter.filter_2(str2)\n\n str3 = response.xpath(\n 'normalize-space(/html/body/div[2]/div[2]/div/div/div[2]/div[2]/p[8])').extract_first()\n str3 = StrFilter.filter_2(str3)\n item[\"collectionIntroduction\"] = item[\"collectionIntroduction\"] + str2 + str3\n print(item)\n yield item\n","repo_name":"CS1803-SE/The-First-Subsystem","sub_path":"mySpider/spiders/Collection87.py","file_name":"Collection87.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"25603012321","text":"from socket import *\nimport sys\n\n\ndef webServer(port=13331):\n serverSocket = socket(AF_INET, SOCK_STREAM)\n serverSocket.bind((\"\", port))\n serverSocket.listen(1)\n\n while True:\n # Establish the connection\n # print('Ready to serve...')\n connectionSocket, addr = serverSocket.accept()\n try:\n\n try:\n message = connectionSocket.recv(1024)\n filename = message.split()[1]\n f = open(filename[1:])\n outputdata = f.read()\n response = 'HTTP/1.1 200 OK\\r\\n'\n response += 'Content-Type: text/html\\n'\n response += '\\n'\n connectionSocket.send(response.encode())\n # Send one HTTP header line into socket.\n connectionSocket.send(\"HTTP/2 200 OK\".encode())\n\n # Send the content of the requested file to the client\n for i in range(0, len(outputdata)):\n connectionSocket.send(outputdata[i].encode())\n\n connectionSocket.send(\"\\r\\n\".encode())\n connectionSocket.close()\n except IOError:\n connectionSocket.send(\"HTTP/2 404 NOT FOUND\".encode())\n connectionSocket.close()\n\n except (ConnectionResetError, BrokenPipeError):\n pass\n\n serverSocket.close()\n sys.exit() # Terminate the program after sending the corresponding data\n\n\nif __name__ == \"__main__\":\n webServer(13331)\n","repo_name":"ronniemyers/comp-networking","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74531686243","text":"# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1423375004.043891\n_enable_loop = True\n_template_filename = 'C:\\\\Users\\\\Steven\\\\test_dmp\\\\homepage\\\\templates/notAuthorized.html'\n_template_uri = 'notAuthorized.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = []\n\n\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\t\\r\\n\\r\\n\\r\\n\\t\\r\\n\\t
You are not authorized to perform this action!
\\r\\n\\t
Please ask a manager or administrator to receive authorization. Until then please return back to the home screen by clicking below
\\r\\n\\t
Home
\\r\\n\\t
\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"source_encoding\": \"ascii\", \"uri\": \"notAuthorized.html\", \"filename\": \"C:\\\\Users\\\\Steven\\\\test_dmp\\\\homepage\\\\templates/notAuthorized.html\", \"line_map\": {\"16\": 0, \"27\": 21, \"21\": 1}}\n__M_END_METADATA\n\"\"\"\n","repo_name":"StevenDewey/colonial-project","sub_path":"homepage/cached_templates/templates/notauthorized.html.py","file_name":"notauthorized.html.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3064602614","text":"import pandas as pd\nimport numpy as np\nimport base64\nimport csv\n\ndef trans_base64(num):\n # 转为二进制格式\n with open(\"./tupian/{}.png\".format(num), \"rb\") as f:\n base64_data = base64.b64encode(f.read())\n return base64_data\n\n\nif __name__ == '__main__':\n\n data = pd.read_csv('pp_pic_des33_header.csv')\n count = 0\n\n for index, row in data.iterrows():\n\n p_id = row[0]\n name = row[1]\n list_r = [p_id,name]\n\n if not pd.isna(row[2]):\n cur_base64_data = trans_base64(p_id)\n else:\n cur_base64_data = ''\n\n list_r.append(cur_base64_data)\n list_r.append(row[2])\n\n f1 = open('./pp_pic_des_t64.csv', 'a+', encoding='utf-8', newline='')\n writer1 = csv.writer(f1)\n writer1.writerow(list_r)\n f1.close()\n\n count += 1\n if count >= 5000 and count%5000==0:\n print('===finish===', count)","repo_name":"realmiya/ScentSearcher","sub_path":"DATA_PROCESS/translate_base64.py","file_name":"translate_base64.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"33674486439","text":"from infGrammarNgram2 import nGramModel\nfrom nltk.corpus import brown\nfrom nltk.probability import ELEProbDist\nfrom nltk.probability import SimpleGoodTuringProbDist\nfrom math import log\nimport nltk\nimport random\n#import ngramTrials2\nimport sys\n\nsmoothing_string = \"SimpleGoodTuringProbDist\"\n\ndef main():\n \"\"\"\n Provide an entry point into program.\n :return: None\n \"\"\"\n print(\"Building models...\")\n order = 4\n smoothing = SimpleGoodTuringProbDist\n sents_ = brown.tagged_sents()\n sents = list(sents_) #needs to be mutable to insert start/end tokens if working with tags\n sents = remove_punctuation(sents)\n sentences_of_tags = []\n #Pull out the tags and make sentences of just tags!\n for sentence in sents:\n sentence_tags = [tag for (word, tag) in sentence if word.isalnum()]\n sentences_of_tags.append(sentence_tags)\n\n print(\"Building grammar model\")\n testModelGrammar = generateModelFromSentences(sentences_of_tags, smoothing, order,False,\"START\",\"END\") #Create trigram of only grammar\n ##NGRAM MODEL FOR TAGS AND WORDS\n #print(sents[0], \" order: \", order)\n print(\"Building word model\")\n testModelwordtags = generateModelFromSentences(sents, smoothing, order, True)\n\n\n print(\"Generating text...\")\n ## GENERATE TEXT\n # infGrammarGenerate(testModelGrammar, testModelwordtags, 10)\n\n ## HERE BE DEBUGGING\n #TODO: Implement function to split corpus sentences into training and test set.\n #brown_sents_ = brown.tagged_sents()\n #brown_sents = list(brown_sents_)\n ##word_model = ngramTrials2.nGramModel(brown_sents, smoothing, order)\n infGrammarGenerate(testModelGrammar, testModelwordtags, None, 50)\n\n\n #Testing out other model\n # ngramTrials2.nGramModel(sents_,smoothing,order)\n\n #\n # print(perplexity(word_model, test_sent))\n\n ## TESTS\n assert(testModelGrammar.tagged == False)\n assert(testModelwordtags.tagged == True)\n #assert('START' in testModelwordtags.model)\n\ndef remove_punctuation(sentences):\n sents = []\n #Pull out the tags and make sentences of just tags!\n for sentence in sentences:\n nopunc_sentence = [(word, tag) for (word, tag) in sentence if word.isalnum()]\n sents.append(nopunc_sentence)\n return sents\n\ndef generateModelFromSentences(sents, smoothingF, n, isTagged=False, startChar=\"\", endChar=\"\"):\n if isTagged:\n addPseudo(sents, n, True)\n return nGramModel(sents, smoothingF, n, True)\n else:\n sents = [[w.lower() for w in s] for s in sents]\n addPseudo(sents,n,False, startChar, endChar)\n return nGramModel(sents, smoothingF, n)\n\ndef entropy(model, test):\n \"\"\"Calculate entropy given an ngram model and a list of test sentences.\"\"\"\n\n p = 0\n n = 0\n order = model.getOrder()\n if order == 2:\n for sent in test:\n n += len(sent)\n wPrev = sent.pop(0)\n for w in sent:\n p += -log(model.prob(w,wPrev),2)\n return p/n\n elif order == 3:\n for sent in test:\n n += len(sent)\n w1 = sent.pop(0)\n w2 = sent.pop(0)\n for w in sent:\n p += -log(model.prob_tri(w1, w2, w))\n return p/n\n\n\n\ndef perplexity(model, test):\n e = entropy(model, test)\n return 2**e\n\n#mutator\ndef addPseudo(sents, n, tag=False, start=\"\", end=\"\"):\n \"\"\"Modify sents by inserting start and end tokens to beginning and end of each sentence\"\"\"\n if tag:\n start_symbol = ('', 'START')\n end_symbol = ('', 'END')\n for s in sents:\n for _ in range(n-1):\n s.insert(0, start_symbol)\n s.append(end_symbol)\n else:\n for s in sents:\n for _ in range(n-1):\n s.insert(0,start)\n s.append(end)\n\ndef infGrammarGenerate(grammar_model, word_tag_model, word_model, nrSents):\n \"\"\"Generate a given number of sentences using a model for grammar and a (word,tag) model of equal N\"\"\"\n assert(grammar_model.getOrder() == word_tag_model.getOrder())\n #Create an empty list to hold our conditional tokens\n gram_prevTk = list()\n word_prevTk = list()\n counter = 0\n tagged_sentence = list()\n best_sentence = (\"\", 999999)\n order = grammar_model.getOrder()\n for _ in range(nrSents): #Generate a sentence, nrSents times\n text = \"\" #Initialize empty string\n for _ in range(order-1): #Generate sentences on a given word/symbol (here it is the start symbol)\n word_prevTk.append(\"\")\n gram_prevTk.append(\"START\")\n gram_tk = \"\" #Initialize empty token string\n word_tk = \"\"\n wordgram = \"\"\n while(wordgram != \"END\"): #Loop until we find an END token\n #print(\"GRAMTOKEN: \",gram_tk)\n text += word_tk + \" \"\n #print(\"text so far: \",text)\n tagged_sentence.append((word_tk, gram_tk))\n #print(\"gram prevtkn: \",list(gram_prevTk))\n gram_tk = grammar_model.generate(list(gram_prevTk))\n #print(\"gramtoken: \",gram_tk)\n wordgram = gram_tk.upper()\n #print(\"wordgram: \",wordgram)\n word_tk = word_tag_model.generate(list(word_prevTk), wordgram)\n #print(\"wdtoken\", word_tk)\n while(word_tk == None): # No word found for w1,w2,tag\n gram_tk = grammar_model.generate(list(gram_prevTk)) # GET UPPERCASE\n wordgram = gram_tk.upper()\n #print(\"new gram_tk: \",gram_tk)\n word_tk = word_tag_model.generate(list(word_prevTk), wordgram)\n #sys.exit()\n #while(word_tk == \"\"):\n # word_tk = word_tag_model.generate(list(word_prevTk))\n gram_prevTk.pop(0)\n word_prevTk.pop(0)\n gram_prevTk.append(gram_tk)\n word_prevTk.append(word_tk)\n gram_prevTk = list()\n word_prevTk = list()\n counter += 1\n print(counter)\n if not validate_sentence(text, order):\n continue\n '''perplexity = word_model.perplexity(tagged_sentence)\n if perplexity < best_sentence[1]:\n best_sentence = (text.strip(), perplexity)\n write_to_file(best_sentence, smoothing_string)\n print(text.strip())\n # print(text.strip())'''\n write_to_file((text.strip(),0), smoothing_string)\n gram_prevTk = list()\n word_prevTk = list()\n\n\n\ndef split(sentences, fraction):\n \"\"\"\n Split a fraction of a list of sentences into a training and test set.\n :param sentences: Initial training as a list of sentences data to be split\n :param fraction: represents the fraction of sentences to place in a training data set, the remainder goes into test set\n :return: list of training sentences, list of test sentences\n \"\"\"\n split_sentences = list(sentences)\n random.shuffle(split_sentences)\n break_point = int(len(split_sentences) * fraction)\n return split_sentences[:break_point], split_sentences[break_point:]\n\n\ndef write_to_file(text, smoothingTechnique):\n model_name = \"InferredGrammar\"\n sentence = text[0]\n perplexity = float(text[1])\n print(\"text[1] = \" + str(text[1]))\n filename = smoothingTechnique + \".txt\"\n with open(filename, \"a\") as file:\n file.write(\"%s\\t%s\\t%s\\t%.02f\\n\" % (model_name, smoothingTechnique, sentence, perplexity))\n file.close()\n\ndef validate_sentence(sentence, order):\n \"\"\"\n Check if a sentence meets various constraints such as length.\n :param sentence:\n :return:\n \"\"\"\n sent_length = len(sentence.split())\n maximum_phrase_length = 20\n minimum_phrase_length = 4\n\n #if\n if (sent_length >= maximum_phrase_length) or (order >= sent_length) or (sent_length <= minimum_phrase_length):\n print(\"Rejected sentence: \")\n return False\n else:\n return True\n\n\ndef generateText(model, sents):\n \"\"\"\n Generate sentences of text based on a single model.\n :param model: NgramModel of words\n :param sents: Integer, number of sentences to generate\n :return: none\n \"\"\"\n prevTk = list()\n lN = model.getOrder()\n for _ in range(sents):\n text = \"\"\n for _ in range(lN-1):\n prevTk.append(\"\")\n tk = \"\"\n while(tk != \"\"):\n text += tk + \" \"\n tk = model.generate(list(prevTk))\n prevTk.pop(0)\n prevTk.append(tk)\n\n print(text.strip())\n prevTk = list()\n\nif __name__ == '__main__':\n main()\n","repo_name":"jandersson/NLG-2-Models","sub_path":"infGrammarMain.py","file_name":"infGrammarMain.py","file_ext":"py","file_size_in_byte":8533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"3468769652","text":"import io\nimport re\nfrom cli.utils import *\nfrom PIL import Image\nimport click\nimport requests\n\nfrom cli.app import App\n\n\nfq_title = None\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.group()\ndef books():\n pass\n\n\n@books.command()\ndef add():\n click.clear()\n\n # Setup resource providers\n w(\"Setting up application...\")\n app = App()\n categories = app.the_base_client.categories.get()\n\n # Input: isbn,book_id\n w(\"Enter books to add, one line per book, follow this format: ISBN,Book_Id\")\n books_raw = click.edit()\n if books_raw is None:\n w(\"Input is empty, exit.\")\n exit(0)\n\n unprocessed_list = []\n successful_list = []\n for book_raw in books_raw.splitlines():\n split = [s.strip() for s in book_raw.split(\",\")]\n isbn = split[0]\n book_id = split[1]\n unprocessed_list.append(book_id)\n book_cat = re.sub(r'\\d+', '', book_id)\n book_cat_id = categories[book_cat]\n try:\n isbn, book_id, title, description, authors, has_img = _add_one(app, isbn, book_id, book_cat_id)\n unprocessed_list.remove(book_id)\n successful_list.append(f\"{isbn},{book_id},{title},{description},{authors},{has_img}\")\n except Exception as e:\n w(f\"Error processing book {book_id}: {e}\")\n\n if len(unprocessed_list) > 0:\n click.echo(\"Here are unprocessed books:\", err=True)\n for unprocessed_book in unprocessed_list:\n click.echo(unprocessed_book, err=True)\n\n click.edit(\"\\n\".join(successful_list))\n\n\ndef _add_one(app, isbn, book_id, cat_id):\n w(f\"Finding book [{book_id}] - ISBN:{isbn}...\")\n simple_info = app.google_books.search_by_isbn(isbn)\n\n if simple_info is None:\n w(f\"Book {isbn} not found. Do you want to submit manually? (y)es/(n)o\")\n while True:\n c = click.getchar()\n if c == 'y':\n t = prompt(\"Enter book title:\")\n a = prompt(\"Enter book authors (if many, separated by commas (,):\")\n simple_info = {\n \"title\": t,\n \"authors\": a\n }\n simple_info[\"authors\"] = simple_info[\"authors\"].split(\",\")\n break\n elif c == 'n':\n raise Exception(f\"Book {isbn} will be put into unprocessed list.\")\n\n title = simple_info[\"title\"]\n authors = simple_info[\"authors\"]\n\n global fq_title\n fq_title = f\"[{book_id}] {title}\"\n\n w(fq_title, \"Add or modify the description as you see fit, SAVE the text file before close it\")\n description = click.edit(simple_info.get(\"description\"))\n\n img_link = simple_info.get(\"image\")\n if img_link is None:\n img_link = _search_for_book_cover(app, title, authors)\n\n w(fq_title, \"Creating item...\")\n resp = app.the_base_client.items.add({\n \"title\": f\"[{book_id}] {title}\",\n \"detail\": description\n })\n item_id = resp[\"item\"][\"item_id\"]\n\n w(fq_title, \"Adding category to item...\")\n app.the_base_client.item_categories.add(item_id, cat_id)\n\n if img_link is not None:\n w(\"Adding image to item...\")\n app.the_base_client.items.add_image(item_id, img_link)\n\n w(fq_title, \"終了しました!\")\n return isbn, book_id, title, description.replace(\"\\n\", \" \"), \" & \".join(authors), \"x\" if img_link else \"\"\n\n\ndef _search_for_book_cover(app, title, authors):\n w(fq_title, \"Finding book covers with Google image search...\")\n links = app.cse_image.search_for_links(f\"{title} {authors[0]} books\")\n if links is None:\n return _manual_image_link(\"No image found! \")\n\n img_link = links[0]\n _show_img(img_link)\n\n w(fq_title, \"Is this cover OK? (y)es/(n)o\")\n while True:\n c = click.getchar()\n if c == 'y':\n return img_link\n elif c == 'n':\n return _manual_image_link()\n\n\ndef _manual_image_link(pre_msg=\"\"):\n w(fq_title, f\"{pre_msg}You can: (1) paste an image link or (2) continue without an image\")\n while True:\n c = click.getchar()\n if c == '1':\n return prompt(\"Image link:\")\n elif c == '2':\n w(fq_title, \"Continuing without book cover\")\n return\n\n\ndef _show_img(img_link):\n response = requests.get(img_link)\n image_bytes = io.BytesIO(response.content)\n img = Image.open(image_bytes)\n img.show()\n","repo_name":"Ventilateur/vysacharity","sub_path":"cli/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1293571174","text":"import pandas as pd\nimport csv\nimport numpy as np\nimport re\nimport pickle\n\n\ndef load_rel(rel, queryids, docids, file):\n for line in np.array(file):\n [q, _, d, r] = line\n q = int(q)\n d = int(d)\n r = int(r)\n queryids.add(q)\n docids.add(d)\n if q not in rel:\n rel[q] = {}\n rel[q][d] = r\n\n\ndef load_queries(queryids, queries, reader):\n i = 0\n for [id, text] in reader:\n i += 1\n print(i, end='\\r')\n id = int(id)\n if id in queryids:\n queries[id] = text\n\n\ndef calculate_data():\n docids = set()\n queryids = set()\n\n rel = {}\n\n file_in = open('data/L2R_2/feature_dev_train.txt', 'r')\n\n for line in file_in.readlines():\n line_parts = line.split(' ')\n r = int(line_parts[0])\n qid = int(line_parts[1][4:])\n did = int(line_parts[6])\n if qid not in rel:\n rel[qid] = {}\n rel[qid][did] = r\n docids.add(did)\n queryids.add(qid)\n \n file_in.close()\n\n docs = {}\n doc_reader = csv.reader(open('./data/docs.tsv', 'r'), delimiter='\\t')\n print('Collecting document text')\n i = 0\n for [id, text] in doc_reader:\n i += 1\n print('\\r[{:10}] {:4.1f}%'.format(int(i // 884182.3) * '#', i / 88418.23), end='')\n id = int(id)\n if id in docids:\n docs[id] = text\n print('Done')\n\n queries = {}\n load_queries(queryids, queries, csv.reader(open('./data/queries.train.tsv', 'r'), delimiter='\\t'))\n load_queries(queryids, queries, csv.reader(open('./data/queries.dev.tsv', 'r'), delimiter='\\t'))\n load_queries(queryids, queries, csv.reader(open('./data/queries.eval.tsv', 'r'), delimiter='\\t'))\n\n with open('./data/L2R_2/processed/relevance.pickle', 'wb') as file:\n pickle.dump(rel, file)\n with open('./data/L2R_2/processed/docs.pickle', 'wb') as file:\n pickle.dump(docs, file)\n with open('./data/L2R_2/processed/queries.pickle', 'wb') as file:\n pickle.dump(queries, file)\n\n\ndef load_data():\n [relevance, documents, queries, stop_words] = [None] * 4\n\n with open('./data/L2R_2/processed/relevance.pickle', 'rb') as file:\n relevance = pickle.load(file)\n with open('./data/L2R_2/processed/docs.pickle', 'rb') as file:\n documents = pickle.load(file)\n with open('./data/L2R_2/processed/queries.pickle', 'rb') as file:\n queries = pickle.load(file)\n with open('data/stop_words.pickle', 'rb') as file:\n stop_words = pickle.load(file)\n\n return [relevance, documents, queries, stop_words]\n\n\ndef index_terms(documents, stop_words):\n terms = {}\n i = 0\n count = len(documents)\n for doc_id in documents:\n i += 1\n print('\\r{:5.2f}%'.format(i / count * 100), end='')\n terms[doc_id] = {}\n for term in re.findall(r\"[\\w']+\", documents[doc_id].lower()):\n if term in stop_words:\n continue\n if term not in terms[doc_id]:\n terms[doc_id][term] = 0\n terms[doc_id][term] += 1\n return terms\n\n\ndef calculate_index(data):\n [relevance, documents, queries, stop_words] = data\n indexed_ques = index_terms(queries, stop_words)\n print('done')\n with open('data/L2R_2/processed/indexed_ques.pickle', 'wb') as file:\n pickle.dump(indexed_ques, file)\n\n indexed_docs = index_terms(documents, stop_words)\n print('done')\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'wb') as file:\n pickle.dump(indexed_docs, file)\n\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'rb') as file:\n indexed_docs = pickle.load(file)\n\n inverted_index = {}\n i = 0\n for did in indexed_docs:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(indexed_docs) * 100), end='')\n for term in indexed_docs[did]:\n if term not in inverted_index:\n inverted_index[term] = set()\n inverted_index[term].add(did)\n with open('./data/L2R_2/processed/inverted_index.pickle', 'wb') as file:\n pickle.dump(inverted_index, file)\n\n\ndef load_index():\n [indexed_ques, indexed_docs, inverted_index] = [None] * 3\n\n with open('data/L2R_2/processed/indexed_ques.pickle', 'rb') as file:\n indexed_ques = pickle.load(file)\n\n with open('./data/L2R_2/processed/indexed_docs.pickle', 'rb') as file:\n indexed_docs = pickle.load(file)\n\n with open('./data/L2R_2/processed/inverted_index.pickle', 'rb') as file:\n inverted_index = pickle.load(file)\n\n return [indexed_ques, indexed_docs, inverted_index]\n\n\ndef calc_tf(index, qid, did):\n [indexed_ques, indexed_docs, inverted_index] = index\n\n count = 0\n summ = 0\n for term in indexed_ques[qid]:\n count += indexed_ques[qid][term]\n if term in indexed_docs[did]:\n summ += indexed_ques[qid][term] * indexed_docs[did][term] / np.sum(\n [indexed_docs[did][tid] for tid in indexed_docs[did]])\n\n if count == 0:\n return 0\n return summ / count\n\n\ndef calc_idf(index, did, idf_cache):\n [indexed_ques, indexed_docs, inverted_index] = index\n\n count = 0\n summ = 0\n for term in indexed_docs[did]:\n if term not in idf_cache:\n idf_cache[term] = np.log2(len(indexed_docs) / len(inverted_index[term]))\n count += indexed_docs[did][term]\n summ += indexed_docs[did][term] * idf_cache[term]\n\n if count == 0:\n return 0\n return summ / count\n\n\n# def calc_bm25(n, tf, doc_len, avg_len, qf, N):\ndef calc_bm25(data, index, f_vals, qid, did, avg_len):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n r = 0\n R = 0\n\n # constants\n k1 = 1.2\n k2 = 100\n b = 0.75\n\n doc_len = np.sum([indexed_docs[did][t] for t in indexed_docs[did]])\n\n K = k1 * ((1 - b) + b * (doc_len / avg_len))\n\n score = 0\n for term in indexed_ques[qid]:\n if term not in indexed_docs[did]:\n continue\n\n tf = indexed_docs[did][term]\n qf = indexed_ques[qid][term]\n n = len(inverted_index[term])\n\n sub1 = R - r + 0.5\n upper = (r + 0.5) / sub1 * (k1 + 1) * tf * (k2 + 1) * qf\n sub2 = len(documents) - n - R + r + 0.5\n lower = (n - r + 0.5) / sub2 * (K + tf) * (k2 + qf)\n score += max(-1, np.log10(upper / lower))\n\n return score\n\n\ndef process_tf(data, index):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n\n print('tf_values:')\n tf_vals = {}\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n tf_vals[query] = {}\n for document in relevance[query]:\n tf_vals[query][document] = calc_tf(index, query, document)\n print('done')\n\n with open('./data/L2R_2/processed/tf_values.pickle', 'wb') as file:\n pickle.dump(tf_vals, file)\n\n\ndef load_tf():\n with open('./data/L2R_2/processed/tf_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef process_idf(data, index):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n\n print('idf_values:')\n idf_vals = {}\n idf_cache = {}\n i = 0\n for document in documents:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(documents) * 100), end='')\n idf_vals[document] = calc_idf(index, document, idf_cache)\n print('done')\n\n with open('./data/L2R_2/processed/idf_values.pickle', 'wb') as file:\n pickle.dump(idf_vals, file)\n\n\ndef load_idf():\n with open('./data/L2R_2/processed/idf_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef process_bm25(data, index, f_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n avg_len = np.average([np.sum([indexed_docs[d][t] for t in indexed_docs[d]]) for d in indexed_docs])\n\n print('bm25_values:')\n bm25_vals = {}\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n bm25_vals[query] = {}\n for document in relevance[query]:\n bm25_vals[query][document] = calc_bm25(data, index, f_vals, query, document, avg_len)\n print('done')\n\n with open('./data/L2R_2/processed/bm25_values.pickle', 'wb') as file:\n pickle.dump(bm25_vals, file)\n\n\ndef load_bm25():\n with open('./data/L2R_2/processed/bm25_values.pickle', 'rb') as file:\n return pickle.load(file)\n\n\ndef append_features(data, index, f_vals, bm25_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n\n file_in = open('data/L2R_2/feature_dev_train.txt', 'r')\n file_out = open('data/L2R_2/feature_dev_train_plus.txt', 'w')\n\n i = 0\n for line in file_in.readlines():\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n line_parts = line.split(' ')\n qid = int(line_parts[1][4:])\n did = int(line_parts[6])\n line_parts.insert(4, '3:{:}'.format(tf_vals[qid][did]))\n line_parts.insert(5, '4:{:}'.format(idf_vals[did]))\n line_parts.insert(6, '5:{:}'.format(bm25_vals[qid][did]))\n file_out.write(' '.join(line_parts))\n\n file_in.close()\n file_out.close()\n\n\ndef export_features(data, index, f_vals, bm25_vals):\n [relevance, documents, queries, stop_words] = data\n [indexed_ques, indexed_docs, inverted_index] = index\n [tf_vals, idf_vals] = f_vals\n\n file_out = open('data/L2R_2/feature_dev_train_plus.txt', 'w')\n\n i = 0\n for query in relevance:\n i += 1\n print('\\r{:5.2f}%'.format(i / len(relevance) * 100), end='')\n for document in relevance[query]:\n line = '{:} qid:{:} 1:{:} 2:{:} 3:{:} 4:{:} 5:{:} #docid = {:}\\n'.format(\n relevance[query][document],\n query,\n len(indexed_docs[document]),\n np.sum([indexed_docs[document][term] for term in indexed_docs[document]]),\n tf_vals[query][document],\n idf_vals[document],\n bm25_vals[query][document],\n document)\n file_out.write(line)\n\n file_out.close()\n\nif __name__ == '__main__':\n # calculate_data()\n data = load_data()\n # calculate_index(data)\n index = load_index()\n # process_tf(data, index)\n # process_idf(data, index)\n f_vals = [load_tf(), load_idf()]\n # process_bm25(data, index, f_vals)\n bm25_vals = load_bm25()\n append_features(data, index, f_vals, bm25_vals)","repo_name":"lzhanggithub/IR-Group-42","sub_path":"py-scripts/L2R_script_2.py","file_name":"L2R_script_2.py","file_ext":"py","file_size_in_byte":10751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30463145786","text":"import jwt, random, json\r\n\r\nimport os\r\nimport hmac\r\nimport time\r\nimport base64\r\nimport datetime\r\nimport hashlib\r\nimport requests\r\nfrom .serializers import *\r\n\r\n\r\nfrom .models import User, AuthSMS\r\nfrom . import models as m\r\nfrom django.conf import settings\r\n\r\nfrom django.contrib.auth import authenticate\r\nfrom django.http import JsonResponse\r\nfrom django.shortcuts import render, get_object_or_404\r\nfrom nuseum.settings import SECRET_KEY\r\n\r\nfrom rest_framework import status\r\nfrom rest_framework.response import Response\r\nfrom rest_framework.views import APIView\r\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer\r\n\r\n### 소셜 로그인 사용 위한 url 변수 설정 ###\r\nBASE_URL = '/'\r\nKAKAO_CALLBACK_URI = BASE_URL + 'kakao/callback/'\r\nNAVER_CALLBACK_URI = BASE_URL + 'naver/callback/'\r\n\r\ndef test_view(request):\r\n return render(request, 'account/test.html')\r\n\r\nclass AuthAPIView(APIView):\r\n # 유저 정보 확인\r\n def get(self, request):\r\n try:\r\n # access token을 decode 해서 유저 id 추출 => 유저 식별\r\n access = request.COOKIES['access']\r\n payload = jwt.decode(access, SECRET_KEY, algorithms=['HS256'])\r\n pk = payload.get('user_id')\r\n user = get_object_or_404(User, pk=pk)\r\n serializer = UserSerializer(instance=user)\r\n return Response(serializer.data, status=status.HTTP_200_OK)\r\n\r\n except(jwt.exceptions.ExpiredSignatureError):\r\n # 토큰 만료 시 토큰 갱신\r\n data = {'refresh': request.COOKIES.get('refresh', None)}\r\n serializer = TokenRefreshSerializer(data=data)\r\n if serializer.is_valid(raise_exception=True):\r\n access = serializer.data.get('access', None)\r\n refresh = serializer.data.get('refresh', None)\r\n payload = jwt.decode(access, SECRET_KEY, algorithms=['HS256'])\r\n pk = payload.get('user_id')\r\n user = get_object_or_404(User, pk=pk)\r\n serializer = UserSerializer(instance=user)\r\n res = Response(serializer.data, status=status.HTTP_200_OK)\r\n res.set_cookie('access', access)\r\n res.set_cookie('refresh', refresh)\r\n return res\r\n raise jwt.exceptions.InvalidTokenError\r\n\r\n except(jwt.exceptions.InvalidTokenError):\r\n # 사용 불가능한 토큰일 때\r\n return Response(status=status.HTTP_400_BAD_REQUEST)\r\n\r\n # 로그인\r\n def post(self, request):\r\n \t# 유저 인증 self.request, username=user_id, password=password\r\n user = authenticate(username=request.data.get(\"user_id\"), password=request.data.get(\"password\"))\r\n # 이미 회원가입 된 유저일 때\r\n if user is not None:\r\n serializer = UserSerializer(user)\r\n # jwt 토큰 접근\r\n token = TokenObtainPairSerializer.get_token(user)\r\n refresh_token = str(token)\r\n access_token = str(token.access_token)\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"Login success\",\r\n \"user\": serializer.data,\r\n \"token\": {\r\n \"access\": access_token,\r\n \"refresh\": refresh_token,\r\n },\r\n },\r\n status=status.HTTP_200_OK,\r\n )\r\n # jwt 토큰 => 쿠키에 저장\r\n res.set_cookie(\"access\", access_token, httponly=True)\r\n res.set_cookie(\"refresh\", refresh_token, httponly=True)\r\n return res\r\n else:\r\n return Response(\r\n {\r\n \"message\" : \"Login Fail\",\r\n \"code\" : \"1000\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n\r\n # 로그아웃\r\n def delete(self, request):\r\n # 쿠키에 저장된 토큰 삭제 => 로그아웃 처리\r\n response = Response({\r\n \"code\" : \"0000\",\r\n \"message\": \"Logout success\"\r\n }, status=status.HTTP_202_ACCEPTED)\r\n response.delete_cookie(\"access\")\r\n response.delete_cookie(\"refresh\")\r\n return response\r\n\r\nclass RegisterAPIView(APIView):\r\n # 회원가입\r\n def post(self, request):\r\n serializer = RegisterSerializer(data=request.data)\r\n if serializer.is_valid():\r\n user = serializer.save()\r\n\r\n # jwt 토큰 접근\r\n token = TokenObtainPairSerializer.get_token(user)\r\n refresh_token = str(token)\r\n access_token = str(token.access_token)\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"register successs\",\r\n \"user\": serializer.data, \r\n \"token\": {\r\n \"access\": access_token,\r\n \"refresh\": refresh_token,\r\n },\r\n },\r\n status=status.HTTP_200_OK,\r\n )\r\n \r\n return res\r\n else:\r\n return Response(\r\n {\r\n \"message\" : \"Registration Fail\",\r\n \"code\" : \"1001\",\r\n \"detail\" : serializer.errors,\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n ) \r\n\r\nclass IdValidation(APIView):\r\n '''\r\n 중복 아이디가 있는지 검증하는 API\r\n jquery blur로 AJAX통해 제출.\r\n '''\r\n def post(self, request):\r\n try:\r\n user_id = request.data['user_id']\r\n try:\r\n user = User.objects.get(user_id=user_id)\r\n except Exception as e:\r\n user = None\r\n \r\n if user is None:\r\n res = Response(\r\n {\r\n \"code\" : \"0001\",\r\n \"message\": \"id not exist\",\r\n } \r\n )\r\n else:\r\n res = Response(\r\n {\r\n \"code\" : \"0002\",\r\n \"message\": \"id exist\",\r\n }\r\n )\r\n\r\n# context = {\r\n# 'data' : \"not exist\" \r\n# if user is None \r\n# else \"exist\"\r\n# }\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1002\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n \r\n else:\r\n# return JsonResponse(context)\r\n return res\r\n \r\nclass HPValidation(APIView):\r\n '''\r\n 중복 휴대폰 번호가 있는지 검증하는 API\r\n jquery blur로 AJAX통해 제출.\r\n '''\r\n def post(self, request):\r\n try:\r\n hp = request.data['hp']\r\n try:\r\n user = User.objects.get(hp=hp)\r\n except Exception as e:\r\n user = None\r\n \r\n if user is None:\r\n res = Response(\r\n {\r\n \"code\" : \"0003\",\r\n \"message\": \"hp not exist\",\r\n } \r\n )\r\n else:\r\n res = Response(\r\n {\r\n \"code\" : \"0004\",\r\n \"message\": \"hp exist\",\r\n }\r\n )\r\n\r\n# context = {\r\n# 'data' : \"not exist\" if user is None else \"exist\"\r\n# }\r\n\r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1003\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n \r\n else:\r\n# return JsonResponse(context)\r\n return res\r\n\r\nclass AuthView(APIView):\r\n '''\r\n 받은 request data로 휴대폰번호를 통해 AuthSMS에 update_or_create\r\n 인증번호 난수 생성및 저장은 모델 안에 존재.\r\n '''\r\n def post(self, request):\r\n try:\r\n p_num = request.data['hp']\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1004\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n AuthSMS.objects.update_or_create(hp=p_num)\r\n #return Response({'message': 'OK', 'phone#':request.data['hp'], \"auth_code\":auth_code})\r\n return Response(\r\n {\r\n 'message': 'OK', \r\n \"code\" : \"0000\",\r\n 'phone#':request.data['hp']\r\n }\r\n )\r\n\r\n #휴대폰번호를 쿼리로 인증번호가 매치되는지 찾는 함수\r\n #hp, auth 매개변수\r\n def get(self, request):\r\n try: \r\n p_number = request.data['hp']\r\n a_number = request.data['auth']\r\n \r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1005\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n result = AuthSMS.objects.check_auth_number(p_number, a_number)\r\n return Response({\"message\":\"ok\", \"result\":result})\r\n \r\n\r\nclass Check_auth(APIView):\r\n\r\n #휴대폰번호를 쿼리로 인증번호가 매치되는지 찾는 함수\r\n #hp, auth 매개변수\r\n\r\n def post(self, request):\r\n try:\r\n user_hp = request.data['hp']\r\n user_auth = request.data['auth']\r\n\r\n auth = AuthSMS.objects.get(hp=user_hp).auth\r\n c_auth = str(auth)\r\n\r\n if c_auth == user_auth:\r\n res = Response(\r\n {\r\n \"code\" : \"0000\",\r\n \"message\": \"hp Auth success\",\r\n \"user_auth\" : user_auth ,\r\n \"auth\" : auth\r\n } \r\n ) \r\n elif c_auth != user_auth:\r\n res = Response(\r\n {\r\n \"code\" : \"1005\",\r\n \"message\": \"hp Auth fail\",\r\n \"user_auth\" : user_auth ,\r\n \"auth\" : auth\r\n } \r\n )\r\n except KeyError:\r\n return Response(\r\n {\r\n \"message\" : \"Bad Request\",\r\n \"code\" : \"1005\",\r\n },\r\n status=status.HTTP_400_BAD_REQUEST,\r\n )\r\n else:\r\n return res\r\n\r\n return res\r\n\r\ndef send_sms(request): \r\n phone_number = request \r\n\r\n BASE_DIR = getattr(settings, 'BASE_DIR', None)\r\n file_path = \"naver_cloud_sens.json\" # 네이버 sens api key 파일\r\n\r\n with open(os.path.join(BASE_DIR,file_path), encoding='utf-8') as f:\r\n nc_sens_key = json.load(f)\r\n\r\n # Generate and store an authentication code (for later verification)\r\n # You can use libraries like random or secrets to generate a code\r\n authentication_code = random.randint(100000, 1000000) # 난수로 6자리 문자 인증 번호 생성\r\n\r\n ##### 네이버 sens 서비스 이용 위한 json request 형식 #####\r\n timestamp = str(int(time.time() * 1000))\r\n\r\n url = \"https://sens.apigw.ntruss.com\"\r\n uri = \"/sms/v2/services/ncp:sms:kr:306737371424:quickself/messages\"\r\n apiUrl = url + uri\r\n\r\n access_key = nc_sens_key['NAVER_SENS_ACCESS_KEY']\r\n secret_key = bytes(nc_sens_key['NAVER_SENS_SECRET_KEY'], 'UTF-8')\r\n message = bytes(\"POST\" + \" \" + uri + \"\\n\" + timestamp + \"\\n\" + access_key, 'UTF-8')\r\n signingKey = base64.b64encode(hmac.new(secret_key, message, digestmod=hashlib.sha256).digest())\r\n \r\n body = {\r\n \"type\" : \"SMS\",\r\n \"contentType\" : \"COMM\",\r\n \"from\" : \"01052802707\",\r\n \"subject\" : \"subject\",\r\n \"content\" : \"[뉴지엄] 인증 번호 [{}]를 입력해주세요.\".format(authentication_code),\r\n \"messages\" : [{\"to\" : phone_number}]\r\n }\r\n \r\n body2 = json.dumps(body)\r\n headers = {\r\n \"Content-Type\": \"application/json; charset=utf-8\",\r\n \"x-ncp-apigw-timestamp\": timestamp,\r\n \"x-ncp-iam-access-key\": access_key,\r\n \"x-ncp-apigw-signature-v2\": signingKey\r\n }\r\n\r\n response = requests.post(apiUrl, headers=headers, data=body2)\r\n\r\n if response.status_code == 202:\r\n return authentication_code\r\n else:\r\n return response.status_code\r\n \r\ndef verify_code(request):\r\n if request.method == 'POST':\r\n user_input_code = request.POST.get('code')\r\n stored_code = request.session.get('authentication_code')\r\n phone_number = request.session.get('phone_number')\r\n \r\n if user_input_code == stored_code:\r\n # Code matches, do something like marking the phone number as verified\r\n return JsonResponse({\"message\": \"Verification successful\"})\r\n else:\r\n return JsonResponse({\"message\": \"Verification failed\"}, status=400)\r\n","repo_name":"pample-pay/Nuseum-V3-BE","sub_path":"nuseum/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"26757382954","text":"from base64 import encode\nimport io\nfrom publisher import publish_forever\nfrom xml_json_yaml_convert.converter import Converter\nMLs = [\"pyDict\", \"xml\", \"json\", \"yaml\"]\nfrom fastapi import APIRouter, FastAPI, UploadFile\nimport shutil\n\nrouter = APIRouter(\n prefix=\"/files\"\n)\n\n\ndef converter(data = \"\", input_ml:str = \"pyDict\", output_ml:str = \"pyDict\"):\n\n if input_ml == output_ml:\n return data\n else:\n translator = Converter(data)\n if input_ml == \"xml\":\n data = translator.from_xml()\n if input_ml == \"json\":\n data = translator.from_json()\n if input_ml == \"yaml\":\n data = translator.from_yaml()\n inverce_translator = Converter(data)\n if output_ml == \"pyDict\":\n return data\n if output_ml == \"xml\":\n return inverce_translator.to_xml()\n if output_ml == \"json\":\n return inverce_translator.to_json()\n if output_ml == \"yaml\":\n return inverce_translator.to_yaml()\n\ndef sendFileToConverter(file):\n return converter(file, input_ml=\"xml\")\n\ndef sendJSONToRabbit(file):\n parameter = sendFileToConverter(file)\n print(parameter)\n publish_forever(file)\n \n\n\n@router.post('/')\nasync def upload_file(\n file: UploadFile\n):\n with open(f'{file.filename}', \"wb\") as buffer:\n shutil.copyfileobj(file.file, buffer)\n shutil.move(file.filename, \"uploads/\" + \"file.xml\")\n data = open(\"./uploads/file.xml\", 'r', encoding='utf-8')\n sendJSONToRabbit(data.read())\n \n\napp = FastAPI()\n\napp.include_router(router)","repo_name":"elkopass/AGORAHACK","sub_path":"gateway/rest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"40449797601","text":"import scrapy\nfrom scrapy.crawler import CrawlerProcess\n\nfrom bd.spiders.sc import SCSpider\n\ncrawler_process = CrawlerProcess({\n 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'\n})\n\ncrawler = crawler_process.create_crawler()\nspider = crawler.spiders.create('sc')\ncrawler.crawl(spider)\ncrawler_process.start()","repo_name":"AgentG2015/Scrapy","sub_path":"bd2/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"25439503361","text":"def xor_uncipher(string:str, key: str)->str:\r\n \"\"\"Kodeeritud text dekodeeritakse\r\n \"\"\"\r\n result=''\r\n temp=[]\r\n for i in range(len(string)):\r\n temp.append(string[i])\r\n for j in reversed(range(len(key))):\r\n temp[i]=chr(ord(key[j])^ord(temp[i]))\r\n result +=temp[i]\r\n return result\r\n\r\n\r\n","repo_name":"Robot372/Rjazanov12.11","sub_path":"module1.py","file_name":"module1.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1083379875","text":"from sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine, Integer, String, Text, Binary, Column, Float\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\n# DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nDB_URI = 'sqlite:///stuff2.db'\n\nSession = sessionmaker(autocommit=False,\n autoflush=False,\n bind=create_engine(DB_URI))\nsession = scoped_session(Session)\nBase = declarative_base()\n\n\nclass Bid(Base):\n\n __tablename__ = 'bid'\n\n id \t = Column(Integer, primary_key=True)\n code \t\t = Column(String(50))\n created_at = Column(String(50))\n created_by = Column(String(50))\n quantity = Column(Float(precision=4, asdecimal=True))\n price \t\t = Column(Float(precision=4, asdecimal=True))\n\n def __init__(self, code, created_at ,created_by, quantity, price):\n\n self.code = code\n self.created_at = created_at\n self.created_by = created_by\n self.quantity = quantity\n self.price = price\n\n @classmethod\n def from_json(cls, data):\n return cls(**data)\n\n def to_json(self):\n to_serialize = ['id', 'code', 'created_at', 'created_by', 'quantity', 'price']\n d = {}\n for attr_name in to_serialize:\n d[attr_name] = getattr(self, attr_name)\n return d\n\n\n# creates database\nif __name__ == \"__main__\":\n print('in main', DB_URI)\n engine = create_engine(DB_URI)\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(engine)","repo_name":"lmarent/Auction_Engine","sub_path":"auction/auctionapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9278758260","text":"import BioSimSpace as BSS\r\n\r\nfrom os.path import basename\r\n\r\nimport itertools\r\nimport sys\r\n\r\ndef test_mapping(file0, file1, count, output, verbose=False):\r\n\r\n if verbose:\r\n print(\"Loading the molecules...\")\r\n\r\n print(\"%05d : %s --> %s\" % (count, basename(file0), basename(file1)))\r\n\r\n # Load each file and grab the first (only) molecule.\r\n mol0 = BSS.IO.readMolecules(file0).getMolecules()[0]\r\n mol1 = BSS.IO.readMolecules(file1).getMolecules()[0]\r\n\r\n if verbose:\r\n print(\"Performing the mapping...\")\r\n\r\n # Find the best MCS mapping.\r\n mapping = BSS.Align.matchAtoms(mol0, mol1, verbose=verbose)\r\n\r\n # Write the mapping to file.\r\n with open(output + \".mapping\", \"w\") as file:\r\n for idx0, idx1 in mapping.items():\r\n atom0 = mol0._getSireMolecule().atom(idx0)\r\n atom1 = mol1._getSireMolecule().atom(idx1)\r\n\r\n file.write(\"%s --> %s\\n\" % (atom0, atom1))\r\n\r\n # Align mol0 to mol1.\r\n mol0 = BSS.Align.rmsdAlign(mol0, mol1, mapping)\r\n\r\n # Create a combined system from the aligned molecules.\r\n system = mol0 + mol1\r\n\r\n # Write the system to file.\r\n BSS.IO.saveMolecules(output, system, \"PDB\")\r\n\r\nif __name__ == \"__main__\":\r\n\r\n if len(sys.argv) == 2:\r\n ligand_dir = sys.argv[1]\r\n else:\r\n ligand_dir = \".\"\r\n\r\n ligand_list = BSS.IO.glob(\"%s/*.mol2\" % ligand_dir)\r\n\r\n count = 0\r\n\r\n # Loop over all pairs of ligands.\r\n for pair in itertools.combinations(ligand_list, 2):\r\n file0 = pair[0]\r\n file1 = pair[1]\r\n name_0 = basename(file0).split(\".\")[0]\r\n name_1 = basename(file1).split(\".\")[0]\r\n output = \"%05d\" % count + \"_\" + name_0 + \"_\" + name_1\r\n\r\n try:\r\n test_mapping(file0, file1, count, output, False)\r\n except:\r\n print (\"ERROR: mapping problem: %s, %s\" % (file0, file1))\r\n\r\n count = count +1\r\n","repo_name":"michellab/BioSimSpace_examples","sub_path":"mappings/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"20455466159","text":"import sys, os\nimport logging\nimport yaml\n\nlog = logging.getLogger(__name__)\n\n# figure correct function to import, though used elsewhere\ntry:\n from ushlex import split as shplit\nexcept ImportError:\n from shlex import split as shplit\n if sys.version < '3.0':\n log.warning('Warning: shlex module cannot handle unicode. '\n 'install ushlex.')\nshplit # make pyflakes happy\n\n\nclass MultiMap(dict):\n ''' Holds an ordered list of pairs while masquerading as a dictionary.\n Keeps order like the OrderedDict, but also duplicate keys,\n which is useful to represent HMTL nodes.\n '''\n def __init__(self, value):\n self.value = value\n\n def __repr__(self):\n return repr(self.value)\n\n def iteritems(self):\n for pair in self.value:\n yield pair\n\n\nclass SafeOrdLoader(yaml.BaseLoader):\n ''' An ordered and simplified/safe yaml loader.\n\n Disables the use of \"%\" chars as directive characters,\n and {}, [] as inline flow characters so we can use templating\n languages and don't have to quote so much. Also @ & etc.\n '''\n #~ def check_directive(self):\n #~ return False\n\n def check_plain(self):\n ch = self.peek()\n return ch not in u'\\0 \\t\\r\\n\\x85\\u2028\\u2029-?:!|>\\'\\\"`' \\\n or (self.peek(1) not in u'\\0 \\t\\r\\n\\x85\\u2028\\u2029'\n and (ch == u'-' or (not self.flow_level and ch in u'?:')))\n return True\n\n def fetch_more_tokens(self):\n 'Override this to skip several chars like %, {, and }.'\n from yaml.scanner import ScannerError\n\n # Eat whitespaces and comments until we reach the next token.\n self.scan_to_next_token()\n\n # Remove obsolete possible simple keys.\n self.stale_possible_simple_keys()\n\n # Compare the current indentation and column. It may add some tokens\n # and decrease the current indentation level.\n self.unwind_indent(self.column)\n\n # Peek the next character.\n ch = self.peek()\n\n # Is it the end of stream?\n if ch == u'\\0':\n return self.fetch_stream_end()\n\n # Is it a directive?\n #~ if ch == u'%' and self.check_directive():\n #~ return self.fetch_directive()\n\n # Is it the document start?\n if ch == u'-' and self.check_document_start():\n return self.fetch_document_start()\n\n # Is it the document end?\n if ch == u'.' and self.check_document_end():\n return self.fetch_document_end()\n\n # TODO: support for BOM within a stream.\n #if ch == u'\\uFEFF':\n # return self.fetch_bom() <-- issue BOMToken\n\n # Note: the order of the following checks is NOT significant.\n\n #~ # Is it the flow sequence start indicator?\n #~ if ch == u'[':\n #~ return self.fetch_flow_sequence_start()\n\n #~ # Is it the flow mapping start indicator?\n #~ if ch == u'{':\n #~ return self.fetch_flow_mapping_start()\n\n #~ # Is it the flow sequence end indicator?\n #~ if ch == u']':\n #~ return self.fetch_flow_sequence_end()\n\n #~ # Is it the flow mapping end indicator?\n #~ if ch == u'}':\n #~ return self.fetch_flow_mapping_end()\n\n #~ # Is it the flow entry indicator?\n #~ if ch == u',':\n #~ return self.fetch_flow_entry()\n\n # Is it the block entry indicator?\n if ch == u'-' and self.check_block_entry():\n return self.fetch_block_entry()\n\n # Is it the key indicator?\n if ch == u'?' and self.check_key():\n return self.fetch_key()\n\n # Is it the value indicator?\n if ch == u':' and self.check_value():\n return self.fetch_value()\n\n # Is it an alias?\n #~ if ch == u'*':\n #~ return self.fetch_alias()\n\n # Is it an anchor?\n #~ if ch == u'&':\n #~ return self.fetch_anchor()\n\n # Is it a tag?\n if ch == u'!':\n return self.fetch_tag()\n\n # Is it a literal scalar?\n if ch == u'|' and not self.flow_level:\n return self.fetch_literal()\n\n # Is it a folded scalar?\n if ch == u'>' and not self.flow_level:\n return self.fetch_folded()\n\n # Is it a single quoted scalar?\n if ch == u'\\'':\n return self.fetch_single()\n\n # Is it a double quoted scalar?\n if ch == u'\\\"':\n return self.fetch_double()\n\n # It must be a plain scalar then.\n if self.check_plain():\n return self.fetch_plain()\n\n # No? It's an error. Let's produce a nice error message.\n raise ScannerError('while scanning for the next token', None,\n 'found character %r that cannot start any token'\n % ch.encode('utf-8'), self.get_mark())\n\n def _construct_mapping(loader, node):\n ''' Keep duplicates and order in mappings,\n uses a list of (name, val) tuple pairs instead.\n '''\n return MultiMap(loader.construct_pairs(node))\n\n# register it\nSafeOrdLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n SafeOrdLoader._construct_mapping)\n\n\ndef get_output_filename(infile, ext='.html'):\n ''' Change extension of given filename. '''\n basename, _ = os.path.splitext(infile.name)\n return basename + ext\n\n\ndef tree_indent(elem, level=0, width=4):\n ''' Poor-man's pretty html printer\n http://effbot.org/zone/element-lib.htm#prettyprint\n '''\n spaces = width * ' '\n indent = '\\n' + (level * spaces)\n if len(elem):\n if elem.text:\n elem.text = elem.text.rstrip() + indent + spaces\n if not elem.text or not elem.text.strip():\n elem.text = indent + spaces # one level extra\n\n if elem.tail:\n elem.tail = elem.tail.rstrip() + indent\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent\n\n for elem in elem:\n tree_indent(elem, level+1)\n\n if not elem.tail or not elem.tail.strip():\n elem.tail = indent\n else:\n if elem.tail:\n elem.tail = elem.tail.rstrip() + indent\n if level and (not elem.tail or not elem.tail.strip()):\n elem.tail = indent\n","repo_name":"mixmastamyk/yamlweb","sub_path":"yamlweb/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"8385355276","text":"#예제 1번\r\nimport threading\r\n\r\ndef execute(number):\r\n \"\"\"\r\n 쓰레드에 실행할 함수\r\n \"\"\"\r\n print(threading.current_thread().getName(),number)\r\n\r\nif __name__=='__main__':\r\n for i in range(1,8): # 1~7 실행\r\n my_thread = threading.Thread(target=execute, args=(i,))\r\n my_thread.start()\r\n","repo_name":"hacks0921/2020year","sub_path":"Thread(쓰레드).py","file_name":"Thread(쓰레드).py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"35663781873","text":"import os\r\nimport pickle\r\nimport numpy as np\r\nimport pandas as pd\r\nimport argparse\r\nimport random\r\n\r\n\r\ndef window_data(start_frame, ann_df, video_name, ws, label_frequency):\r\n window_size = ws\r\n end_frame = start_frame + window_size\r\n\r\n label_one_win = list()\r\n box_one_win = list()\r\n window_one_win = [int(start_frame), video_name]\r\n # '0' for neg samples\r\n class_label = [0, 1, 2]\r\n # all samples without neg samples \r\n # class_label = [0, 1]\r\n\r\n for i in range(len(ann_df)):\r\n\r\n act_start = ann_df.startFrame.values[i]//label_frequency\r\n act_end = ann_df.endFrame.values[i]//label_frequency\r\n assert act_end > act_start\r\n overlap = min(end_frame, act_end) - max(start_frame, act_start)\r\n overlap_ration = overlap * 1.0 / (act_end - act_start)\r\n\r\n overlap_ratio_threshold = 0.9\r\n if overlap_ration > overlap_ratio_threshold:\r\n gt_start = max(start_frame, act_start) - start_frame\r\n gt_end = min(end_frame, act_end) - start_frame\r\n label_one_win.append(class_label.index(ann_df.type_idx.values[i]))\r\n box_one_win.append([gt_start, gt_end])\r\n\r\n box_one_win = np.array(box_one_win).astype('float32')\r\n label_one_win = np.array(label_one_win)\r\n return label_one_win, box_one_win, window_one_win\r\n\r\n\r\ndef sliding_window(ann_df, video_name, ws, label_frequency, train_sample, is_train, neg):\r\n window_size = ws\r\n video_ann_df = ann_df[ann_df.video == video_name]\r\n frame_count = video_ann_df.frame_num.values[0]//label_frequency\r\n if is_train:\r\n stride = int(window_size / (train_sample))\r\n else:\r\n stride = int(window_size / (2*train_sample))\r\n \r\n num_window = int(1.0*(frame_count + stride - window_size) / stride)\r\n windows_start = [i * stride for i in range(num_window)]\r\n if is_train and num_window == 0:\r\n windows_start = [0]\r\n if frame_count > window_size:\r\n windows_start.append(frame_count - window_size)\r\n\r\n label_one_video = list()\r\n box_one_video = list()\r\n window_one_video = list()\r\n for start in windows_start:\r\n if is_train:\r\n label_tmp, box_tmp, window_tmp = window_data(start, video_ann_df, video_name, ws, label_frequency)\r\n if len(label_tmp) > 0:\r\n label_one_video.append(label_tmp)\r\n box_one_video.append(box_tmp)\r\n window_one_video.append(window_tmp)\r\n else:\r\n window_one_video.append([int(start), video_name])\r\n \r\n # generate more neg samples\r\n if is_train and neg:\r\n num_pos = len(label_one_video)\r\n start_pos = [int(i[0]) for i in window_one_video]\r\n remain_windows_start = [i for i in windows_start[:-1] if i not in start_pos]\r\n number_neg = min(len(remain_windows_start), 3*num_pos)\r\n if remain_windows_start:\r\n # method 2\r\n # for i in range(num_pos):\r\n # num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n # window_one_video.append([int(remain_windows_start[num_tmp]),video_name])\r\n # method 4-1 & 4-2\r\n # for i in range(len(remain_windows_start)):\r\n # num_tmp = i \r\n # window_one_video.append([int(remain_windows_start[num_tmp]), video_name])\r\n repeat_list = list()\r\n for i in range(number_neg):\r\n if number_neg==len(remain_windows_start):\r\n num_tmp = i \r\n window_one_video.append([int(remain_windows_start[num_tmp]), video_name])\r\n else:\r\n num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n while num_tmp in repeat_list:\r\n num_tmp = random.randint(0, len(remain_windows_start)-1)\r\n window_one_video.append([int(remain_windows_start[num_tmp]),video_name])\r\n repeat_list.append(num_tmp)\r\n rnd_tmp = random.randint(0, 100)\r\n\r\n tmp_sss = os.path.basename(os.path.dirname(video_name)) [:4]\r\n try:\r\n tmp_sss = int(tmp_sss)\r\n if window_size==128:\r\n if 0 < rnd_tmp <= 55:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+15*ws//128, min(ws, fake_start+50*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 56 < rnd_tmp <= 82:\r\n fake_start = random.randint(0, ws-54*ws//128)\r\n fake_end= random.randint(fake_start+50*ws//128, min(ws, fake_start+75*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-93*ws//128)\r\n fake_end= random.randint(fake_start+75*ws//128, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n if 0 < rnd_tmp <= 52:\r\n fake_start = random.randint(0, ws-18*ws//window_size)\r\n fake_end= random.randint(fake_start+15*ws//window_size, min(ws, fake_start+50*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 53 < rnd_tmp <= 78:\r\n fake_start = random.randint(0, ws-54*ws//window_size)\r\n fake_end= random.randint(fake_start+50*ws//window_size, min(ws, fake_start+75*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 79 < rnd_tmp <= 91:\r\n fake_start = random.randint(0, ws-93*ws//window_size)\r\n fake_end= random.randint(fake_start+75*ws//window_size, min(ws, fake_start+116*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 92 < rnd_tmp <= 97:\r\n fake_start = random.randint(0, ws-155*ws//window_size)\r\n fake_end= random.randint(fake_start+116*ws//window_size, min(ws, fake_start+160*ws//window_size))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-212*ws//window_size)\r\n fake_end= random.randint(fake_start+160*ws//window_size, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n except:\r\n if tmp_sss != 'samm':\r\n if 0 < rnd_tmp <= 75:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+12*ws//128, min(ws, fake_start+36*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 75 < rnd_tmp <= 94:\r\n fake_start = random.randint(0, ws-54*ws//128)\r\n fake_end= random.randint(fake_start+36*ws//128, min(ws, fake_start+62*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-93*ws//128)\r\n fake_end= random.randint(fake_start+62*ws//128, min(ws, fake_start + ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n if 0 < rnd_tmp <= 92:\r\n fake_start = random.randint(0, ws-18*ws//128)\r\n fake_end= random.randint(fake_start+13*ws//128, min(ws, fake_start+23*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n elif 92 < rnd_tmp <= 97:\r\n fake_start = random.randint(0, ws-35*ws//128)\r\n fake_end= random.randint(fake_start+ 23*ws//128, min(ws, fake_start+64*ws//128))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n else:\r\n fake_start = random.randint(0, ws-96*ws//128)\r\n fake_end= random.randint(fake_start+ 64*ws//128, min(ws, fake_start+ws))\r\n box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n label_one_win = np.array([0])\r\n box_one_video.append(box_one_win)\r\n label_one_video.append(label_one_win)\r\n \r\n # for k in range(num_pos): \r\n # method 1\r\n # if ws > 128:\r\n # box_one_win = list()\r\n # label_one_win = list()\r\n # fake_start = random.randint(0, ws-18)\r\n # fake_end= random.randint(fake_start+8, ws)\r\n # # while (3 <= int(fake_end-fake_start) <= 117) == False:\r\n # # fake_start = random.randint(0, ws-18*ws/128)\r\n # # fake_end= random.randint(fake_start+8*ws/128, ws)\r\n # rest = fake_end\r\n # box_one_win.append([fake_start, fake_end])\r\n # label_one_win.append(0)\r\n # while rest + 8 > ws-18:\r\n # fake_start = random.randint(rest, ws-18)\r\n # fake_end= random.randint(fake_start+8, ws)\r\n # rest = fake_end\r\n # box_one_win.append([fake_start, fake_end])\r\n # label_one_win.append(0)\r\n # box_one_win = np.array(box_one_win).astype('float32')\r\n # label_one_win = np.array(label_one_win)\r\n # else:\r\n \r\n # method 2: this method is better than others\r\n # generate the fake length of clips\r\n # fake_start = random.randint(0, ws-18*ws//128)\r\n # fake_end= random.randint(fake_start+12*ws//128, min(ws, fake_start+32*ws//128))\r\n # box_one_win = np.array([[fake_start, fake_end]]).astype('float32')\r\n # label_one_win = np.array([0])\r\n # box_one_video.append(box_one_win)\r\n # label_one_video.append(label_one_win)\r\n\r\n # method 3: this method is worst\r\n # box_tmp_fake = list()\r\n # label_tmp_fake = list()\r\n # num_neg = random_num_times(1, 0.8, 1, 5)\r\n # start_tmp = list()\r\n # end_tmp = list()\r\n # proposal_clips = list()\r\n # for _ in range(num_neg):\r\n # if start_tmp:\r\n # for i in range(len(start_tmp)+1):\r\n # if i == 0 and start_tmp[i]>=15:\r\n # proposal_clips.append([1,start_tmp[i]])\r\n # elif i == len(start_tmp) and end_tmp[i-1]<=128-15:\r\n # proposal_clips.append([end_tmp[i-1],128])\r\n # elif 0=15 :\r\n # proposal_clips.append([end_tmp[i-1],start_tmp[i]])\r\n # if not proposal_clips:\r\n # break\r\n # else:\r\n # random_loc = random.randint(1,len(proposal_clips))\r\n # random_clip = proposal_clips[random_loc-1] \r\n # left_tmp = random_clip[0]\r\n # left_len = random_clip[1]-9*ws//128\r\n # right_len = random_clip[1]\r\n # else:\r\n # left_tmp = 1\r\n # left_len = ws-9*ws//128\r\n # right_len = ws\r\n # fake_start = random.randint(left_tmp, left_len)\r\n # fake_length = random_num_frame(16, 8, 40, 30, 8, 120)\r\n # fake_end = min(right_len, fake_start+fake_length *ws//128)\r\n # box_tmp_fake.append([fake_start, fake_end]) \r\n # label_tmp_fake.append(0) \r\n # start_tmp.append(fake_start)\r\n # end_tmp.append(fake_end)\r\n # start_tmp.sort()\r\n # end_tmp.sort() \r\n # box_fake = np.array(box_tmp_fake).astype('float32')\r\n # label_fake = np.array(label_tmp_fake)\r\n # box_one_video.append(box_fake)\r\n # label_one_video.append(label_fake)\r\n\r\n # method 4: it created in 5 November 2021\r\n # according to the distribution of all pos samples, generating negative samples in turn\r\n # all generated neg samples are remained sliding windows in method 4\r\n # the number of method 2 is based on number of pos samples\r\n\r\n return label_one_video, box_one_video, window_one_video\r\n\r\n\r\ndef random_num_frame(avg1, stdd1, avg2, stdd2, left, right):\r\n a = random.sample([random.gauss(avg1, stdd1), random.gauss(avg2, stdd2)],1)[0]\r\n while (left <= a <= right) == False:\r\n a = random.sample([random.gauss(avg1, stdd1), random.gauss(avg2, stdd2)],1)[0]\r\n return int(a)\r\n\r\ndef random_num_times(avg, stdd, left, right):\r\n a = random.gauss(avg, stdd)\r\n while (left <= a <= right) == False:\r\n a = a = random.gauss(avg, stdd)\r\n return int(a)\r\n\r\n\r\ndef video_process(ann_df, ws, label_frequency, train_sample=4, is_train=True, neg=True):\r\n # List(set()) operation to delete the repeated\r\n # Make sure the generated file in the same order\r\n video_name_list = list(set(ann_df.video.values[:].tolist()))\r\n video_name_list.sort()\r\n\r\n label = list()\r\n boxes = list()\r\n window = list()\r\n\r\n for video_name in video_name_list:\r\n label_tmp, box_tmp, window_tmp = sliding_window(ann_df, video_name, ws, label_frequency, train_sample, is_train, neg)\r\n if is_train and (len(label_tmp) > 0):\r\n label.extend(label_tmp)\r\n boxes.extend(box_tmp)\r\n window.extend(window_tmp)\r\n return label, boxes, window\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-ann_path', type=str, default='./casme2_annotation.csv')\r\n parser.add_argument('-info_dir', type=str, default='./')\r\n parser.add_argument('-is_train', type=bool, default=True)\r\n parser.add_argument('-window_sliding', type=int, default=128)\r\n parser.add_argument('-frequency', type=int, default=1)\r\n args = parser.parse_args()\r\n\r\n ann_df = pd.read_csv(args.ann_path)\r\n gt_label, gt_box, gt_windows = video_process(ann_df, args.window_sliding, args.frequency, is_train=args.is_train)\r\n if args.is_train:\r\n with open(os.path.join(args.info_dir, 'gt_label.pkl'), 'wb') as f:\r\n pickle.dump(gt_label, f)\r\n with open(os.path.join(args.info_dir, 'gt_box.pkl'), 'wb') as f:\r\n pickle.dump(gt_box, f)\r\n with open(os.path.join(args.info_dir, 'window_info.log'), 'w') as f:\r\n f.writelines(\"%d, %s\\n\" % (gt_window[0], gt_window[1]) for gt_window in gt_windows)\r\n\r\n\r\n\r\n","repo_name":"williamlee91/LGSNet","sub_path":"get_sliding_windows.py","file_name":"get_sliding_windows.py","file_ext":"py","file_size_in_byte":15800,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"}
+{"seq_id":"27478152229","text":"from multiprocessing import Process, Queue\nfrom multiprocessing.pool import Pool\nimport os\nimport time\nimport random\n\n\ndef run_proc(name):\n print('Run task %s (%s)' % (name, os.getpid()))\n start = time.time()\n time.sleep(random.random() * 3)\n end = time.time()\n print('task %s complete in %.2f s (%s)' % (name, end - start, os.getpid()))\n\n\ndef write(q):\n for c in ['A', 'B', 'C']:\n print('write %s pid=%s' % (c, os.getpid()))\n q.put(c)\n time.sleep(random.random() * 3)\n\n\ndef read(q):\n while True:\n c = q.get(True)\n print('read %s pid=%s' % (c, os.getpid()))\n\n\nif __name__ == '__main__':\n print('\\ntest multi process pool\\n')\n pool = Pool(4)\n for i in range(4):\n pool.apply_async(run_proc, ('child' + str(i),))\n pool.close()\n pool.join()\n print('all done!')\n\n print('\\ntest multi process communication\\n')\n q = Queue()\n pw = Process(target=write, args=(q,))\n pr = Process(target=read, args=(q,))\n pw.start()\n pr.start()\n pw.join()\n pr.terminate()\n print('end')\n","repo_name":"sky0014/python_study","sub_path":"multi_process.py","file_name":"multi_process.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"47949678998","text":"import cv2\r\nfrom cv2 import IMREAD_COLOR\r\nfrom cv2 import IMREAD_GRAYSCALE\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nim = cv2.imread('img_gray.png',IMREAD_GRAYSCALE)\r\n\r\n\r\n'''\r\n transformation type\r\n s => T{f[i,j]} => hs\r\n linear transformation g[i,j] = alpha*f[i,j] + beta\r\n if alpha = -1 and beta = 255\r\n the image will become negative\r\n alpha: corresponds to the contrast\r\n beta: corresponds to brightness\r\n'''\r\n\r\nim_contra = 4*im\r\n\r\nim_bright = im+50 \r\n\r\nim_neg = -1*im + 255\r\n\r\nplt.figure(figsize=(50,50))\r\n\r\nplt.subplot(4,1,1)\r\nplt.title('Contrast++')\r\nplt.imshow(im_contra,cmap='gray')\r\n\r\nplt.subplot(4,1,2)\r\nplt.title('Negative')\r\nplt.imshow(im_neg,cmap='gray')\r\n\r\nplt.subplot(4,1,3)\r\nplt.title('Original')\r\nplt.imshow(im,cmap='gray')\r\n\r\nplt.subplot(4,1,4)\r\nplt.title('Bright')\r\nplt.imshow(im,cmap='gray')\r\n\r\nplt.show()","repo_name":"zee-1/ComputerVision","sub_path":"linearTransf.py","file_name":"linearTransf.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16188396992","text":"# coding=utf-8\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Button\nimport matplotlib.animation as animation\nfrom Emotion.FaceLocations.inspector import Inspector\n\n\nclass MultipleAnimation(Inspector):\n def __init__(self, emotion):\n Inspector.__init__(self, emotion, reset=False)\n self.scatters = []\n self.objects = []\n self.plot_sizes = None\n self.rgba_colors = None\n self.next_it = 0\n\n def set_navigate_buttons(self):\n \"\"\"\n Sets a button to add the next object to display it.\n \"\"\"\n Inspector.set_navigate_buttons(self)\n ax_add = plt.axes([0.1, 0.05, 0.1, 0.075])\n b_add = Button(ax_add, \"Add\")\n b_add.on_clicked(self.add_next)\n\n def add_next(self, event):\n self.next_it = (self.next_it + 1) % len(self.database)\n next_obj = self.database[self.next_it]\n if next_obj not in self.objects:\n self.objects.append(next_obj)\n rand_shift = np.random.random(3)\n rgba_colors = self.rgba_colors.copy()\n for interested_id in self.hot_ids:\n rgba_colors[interested_id, :-1] = rand_shift\n\n scat = plt.scatter(next_obj.norm_data[:, 0, 0],\n next_obj.norm_data[:, 0, 1],\n color=rgba_colors,\n s=self.plot_sizes)\n self.scatters.append(scat)\n title = self.ax.get_title()\n title += \", %s\" % next_obj.fname\n self.ax.set_title(title)\n print(\"Added %s.\" % next_obj.fname)\n\n def next_frame(self, frame):\n \"\"\"\n :param frame: frame ID to be displayed\n \"\"\"\n for obj_id in range(len(self.objects)):\n obj = self.objects[obj_id]\n obj_frame = frame % obj.frames\n self.scatters[obj_id].set_offsets(obj.norm_data[:, obj_frame, :])\n return []\n\n def define_plot_style(self):\n self.hot_ids = self.current_obj.get_ids(*self.labels[self.active_area])\n markers = self.current_obj.data.shape[0]\n sizes = np.ones(markers) * 30\n rgba_colors = np.zeros(shape=(markers, 4))\n for rgb in range(3):\n rgba_colors[:, rgb] = 0.5\n rgba_colors[:, 3] = 0.5\n for interested_id in self.hot_ids:\n sizes[interested_id] *= 2\n rgba_colors[interested_id, 1] = 0\n rgba_colors[interested_id, 2] = 1\n rgba_colors[interested_id, 3] = 1\n self.rgba_colors = rgba_colors\n self.plot_sizes = sizes\n\n def animate(self):\n \"\"\"\n Animates current emotion file.\n \"\"\"\n if self.scat is not None:\n self.scat.remove()\n self.ax.clear()\n self.ax.grid()\n\n self.define_plot_style()\n\n title = \"%s: %s\" % (self.current_obj.emotion, self.current_obj.fname)\n scat = plt.scatter(self.current_obj.norm_data[:, 0, 0],\n self.current_obj.norm_data[:, 0, 1],\n color=self.rgba_colors,\n s=self.plot_sizes)\n self.objects = [self.current_obj]\n self.scatters = [scat]\n self.ax.set_title(title)\n self.next_it = self.iterator\n\n anim = animation.FuncAnimation(self.fig,\n func=self.next_frame,\n frames=self.current_obj.frames,\n interval=1,\n blit=True)\n try:\n plt.draw()\n except AttributeError:\n pass\n\n\nif __name__ == \"__main__\":\n MultipleAnimation(u\"улыбка\").show()","repo_name":"dizcza/GesturesSpeech","sub_path":"Emotion/FaceLocations/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41879382048","text":"# https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2502\nN=int(input())\ndp=[0] * (394)\nSLP=[list(map(int, input().split())) for _ in range(N)]\nfor s,l,p in SLP:\n for j in range(394):\n for k in range(s,l+1):\n if 0<=j+k<=393:\n dp[j+k] = max(dp[j+k], dp[j]+p)\nM=int(input())\nans = []\nfor _ in range(M):\n w=int(input())\n if dp[w] == 0:\n print(-1)\n exit()\n else:\n ans.append(dp[w])\nprint(*ans, sep=\"\\n\")","repo_name":"tokumaru-y/competitive_program_python","sub_path":"antBook/re_solve/200/161.py","file_name":"161.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"29048617178","text":"from click import command\nfrom flask import Flask, request, jsonify, send_from_directory, Response, send_file\nfrom config import config\nfrom utils import *\nfrom Exceptions import *\nfrom flask_wtf.csrf import CSRFProtect\nfrom flask_cors import CORS, cross_origin\nimport uuid\nimport coloredlogs\nimport logging\nimport json\nimport ERROR_CODES\n\n# TODO: Implementar API KEY https://geekflare.com/es/securing-flask-api-with-jwt/\n\n\ndef create_app(enviroment):\n app = Flask(__name__)\n CORS(app)\n app.config.from_object(enviroment)\n return app\n\n\n# Logger\nlogger = logging.getLogger(__name__)\ncoloredlogs.install(level='DEBUG')\n\n# Configuración\nenviroment = config['DEVELOPMENT_CONFIG']\napp = create_app(enviroment)\n# TODO: No funciona session cookie\n# TODO: Comprobar CSRF\n# app.secret_key = \"secret_key\"\n# csrf = CSRFProtect(app)\n\n# Directorio de subida de archivos\n# if not os.path.exists(config['DIRECTORY_UPLOADED_FILE']):\n# os.makedirs(config['DIRECTORY_UPLOADED_FILE'])\n# TODO: Y si no existe el directorio?\nos.makedirs(getAbsolutePath(config['DIRECTORY_UPLOADED_FILE']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_FILES_PROCESSED']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_FILES_BAKED_TEXTURES']), exist_ok=True)\nos.makedirs(getAbsolutePath(\n config['DIRECTORY_MOSAICS_GENERATED']), exist_ok=True)\n\n\nif(config[\"REMOVE_DIRECTORIES\"]):\n for f in os.listdir(config['DIRECTORY_UPLOADED_FILE']):\n os.remove(getAbsolutePath(config['DIRECTORY_UPLOADED_FILE'], f))\n for f in os.listdir(config['DIRECTORY_FILES_PROCESSED']):\n os.remove(getAbsolutePath(config['DIRECTORY_FILES_PROCESSED'], f))\n for f in os.listdir(config['DIRECTORY_FILES_BAKED_TEXTURES']):\n os.remove(getAbsolutePath(config['DIRECTORY_FILES_BAKED_TEXTURES'], f))\n for f in os.listdir(config['DIRECTORY_MOSAICS_GENERATED']):\n os.remove(getAbsolutePath(config['DIRECTORY_MOSAICS_GENERATED'], f))\n\n# Manejo de errores\n# TODO: Cambiar codigo de vuelta\n\n\ndef invalid_api_usage(e):\n response = jsonify(e.to_dict())\n response.headers.add('Access-Control-Allow-Origin', '*')\n return response, 300\n\n\n# Registro de manejadores\napp.register_error_handler(InvalidAPIParameterException, invalid_api_usage)\n# app.register_error_handler(InvalidResolutionRangeException, invalid_api_usage)\n# app.register_error_handler(InvalidResolutionTypeException, invalid_api_usage)\n# app.register_error_handler(NotAllowedFileExtensionException, invalid_api_usage)\n# app.register_error_handler(MissingArgumentsException, invalid_api_usage)\n\n# Método de apoyo para enviar respuesta\n# def sendResponse(exc):\n# response = jsonify({'message': \"OK\" })\n# response.headers.add('Access-Control-Allow-Origin', '*')\n# return response, exc.code\n\n\n@ app.route('/api/uploadFile', methods=['POST'])\ndef receive_file():\n # PARÁMETROS DE ENTRADA\n # ==============================================================\n # Resolucion para la voxelización\n try:\n resolution = request.form[config['API_PARAM_RESOLUTION']]\n except KeyError as e:\n resolution = None\n # Usar eliminar elementos inconexos\n try:\n removeDisconnectedElements = request.form[config['API_PARAM_USE_REMOVE_DISCONNECTED']]\n except KeyError as e:\n removeDisconnectedElements = None\n\n missingArguments = []\n if(not resolution):\n missingArguments.append(config['API_PARAM_RESOLUTION'])\n if(not removeDisconnectedElements):\n missingArguments.append(config['API_PARAM_USE_REMOVE_DISCONNECTED'])\n if(not request.files or not config['API_PARAM_MAIN_FILE'] in request.files):\n missingArguments.append(config['API_PARAM_MAIN_FILE'])\n\n if(len(missingArguments) > 0):\n raise InvalidAPIParameterException(\n ERROR_CODES.MISSING_PARAMETERS_ERROR_013, missingArguments)\n\n try:\n resolution = int(resolution)\n except ValueError:\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_RESOLUTION_TYPE_ERROR_011)\n\n if(resolution not in config['RESOLUTION_RANGE_ALLOWED']):\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_RESOLUTION_RANGE_ERROR_010)\n\n if(removeDisconnectedElements not in config['USE_REMOVE_DISCONNECTED_ELEMENTS_ALLOWED']):\n raise InvalidAPIParameterException(\n ERROR_CODES.INVALID_REMOVE_DISCONNECTED_ELEMENTS_TYPE_ERROR_014)\n\n # Analizar el fichero de entrada\n file = checkFileUploaded(request.files)\n # ==============================================================\n # Guardar archivo y voxelizar figura\n returned_file_name = None\n if file:\n # Nombre y extension del archivo\n ext = file.filename.split('.')[1]\n UUID = str(uuid.uuid1())\n file_name = UUID + '.' + ext\n\n # Guardar en archivos subidos\n path_save = getAbsolutePath(\n config[\"DIRECTORY_UPLOADED_FILE\"], file_name)\n file.save(path_save)\n\n # Voxelization with textures Algorithm and Mosaic generation\n uvs_info = Voxelization(UUID, file_name, resolution,\n removeDisconnectedElements)\n\n returned_file_name = UUID + \".\" + \\\n config[\"RETURNED_ALLOW_FILE_EXTENSION\"]\n\n textureBlocks = Mosaic(uvs_info, UUID)\n\n applyTexture(returned_file_name, UUID)\n\n comando = createMinecraftCommand(textureBlocks)\n # print(commando.replace(\"'\", '\"'))\n\n # TODO: Send OK, archivo, comando...\n filePath = getAbsolutePath(\n config['DIRECTORY_FILES_PROCESSED'], returned_file_name)\n f = open(filePath, \"r\")\n s_f = f.read()\n f.close()\n return {\"command\": comando, \"file\": s_f}\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"davidominguezapata/VoxelizationAPP","sub_path":"App/Backend/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"40700685830","text":"from tkinter import *\r\n\r\naplikasi = Tk()\r\naplikasi.title(\"bangunann\")\r\n\r\nL = Label(aplikasi, text=\"Bangun Geometri\", font=('Arial Black', 20))\r\nL.grid(row=0, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\nL22 = Label(aplikasi, text=\"Piramid adalah piramida dengan alas persegi yang membutuhkan 2 parameter yaitu alas dan tinggi segitiga\")\r\nL22.grid(row=1, column=0, sticky=\"W\", columnspan=10)\r\n\r\n\r\nL2 = Label(aplikasi, text=\"Alas Segitiga : \")\r\nL2.grid(row=2, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\n\r\nalas = StringVar()\r\nL5 = Entry(aplikasi, textvariable=alas)\r\nL5.grid(row=2, column=1, sticky=\"W\")\r\n\r\n######----------------------------------------\r\n\r\nL3 = Label(aplikasi, text=\"Tinggi Segitiga : \")\r\nL3.grid(row=3, column=0, sticky=\"W\", columnspan=3)\r\n\r\n\r\n\r\ntinggi = StringVar()\r\nL6 = Entry(aplikasi, textvariable=tinggi)\r\nL6.grid(row=3, column=1, sticky=\"W\")\r\n\r\n####--------------------------------------------\r\n\r\ndef hitung():\r\n segitiga = (float(alas.get()) * float(tinggi.get())) * 4\r\n alasnya = float(alas.get()) * float(alas.get())\r\n hasil = segitiga + alasnya\r\n Lhasil.config(text=hasil)\r\n###----------tombol-----------\r\nb1 = Button(aplikasi, text=\"Hitung Luas\", command=hitung)\r\nb1.grid(row=4, column=0)\r\n\r\n\r\nLJhasil = Label(aplikasi, text=\"Hasil : \")\r\nLJhasil.grid(row=4, column=1, sticky=\"W\", columnspan=3)\r\n\r\n\r\nLhasil = Label(aplikasi, text=\"\")\r\nLhasil.grid(row=4, column=2, sticky=\"W\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\naplikasi.mainloop()\r\n\r\n","repo_name":"L200190185/Praktikum-Algopro","sub_path":"Praktikum 11/keg 3.py","file_name":"keg 3.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"19592339215","text":"import random\nimport sys\nfrom visualization import SongVisual\n#from empty import SongVisual\n#keeping a copy ther\nimport random\nimport string\n\nLETTERSANDPUNCTUATIONS=(string.ascii_uppercase) + (string.ascii_uppercase).lower() + str(\"\\'\")\nNUMLINES=random.randint(4,20)\n\ndef process_line(line):\n '''\n Process a line of text to extract (state, new_word) pairs.\n\n We add the BEGIN and END keywords so that we can initialize the\n sentence and know when the line ends.\n '''\n\n line_list=(line.lower().strip().split())\n line_list.insert(0,'BEGIN')\n line_list.append('END')\n\n\n line=[]\n\n if (line == '') or line == False:\n #cound also use x.isspace()\n return 'empty line'\n\n for i in range(len(line_list)-2):\n if line_list[i]=='END':\n break\n #list_after=line_list[i+1:] list of all the words after this word\n key=str(line_list[i])\n one_after=line_list[i+1]\n two_after=line_list[i+1] +' ' +line_list[i+2]\n if line_list[i+2]=='END':\n two_after=one_after\n #easier to give the tuple a value but it's a repeat so it will be parsed out anyway\n tuple1=(key,one_after,two_after)\n line.append(tuple(tuple1)) #tuples\n\n return line #list of tuples of the word, the words after it\n\ndef process_textfile(filename):\n '''\n Creates a dictionary with transition pairs\n based on a file provided\n\n For the first part of the assignment, we use a\n placeholder text that you will have to replace\n at some point.\n\n Based on the placeholder text, the dictionary\n should contain the following key-value pairs:\n\n 'blue,': ['END']\n 'by': ['yellow', 'day.', 'day?']\n 'still': ['hopping', 'going']\n '''\n d = {}\n\n for lines in open(filename, 'r'):\n if ',' in lines:\n # IS THERE A WAY TO HAVE AFTER A COMMA COUNT AS A NEW SENTENCE?\n split_line=lines.split(',')\n for line in split_line:\n line_clean=no_punct(line)\n line=process_line(line_clean)\n put_into_dictionary(d,line)\n else:\n line_clean=no_punct(lines)\n line=process_line(line_clean)\n put_into_dictionary(d,line)\n\n #realized that anything after 'and' would usually make a good new sentence starter\n beginners=d.get('BEGIN')\n beginners.extend(d.get('and'))\n d['BEGIN']=beginners\n\n return d\n\ndef no_punct(line):\n clean_str=''\n for i in range(len(line)):\n if line[i] not in LETTERSANDPUNCTUATIONS:\n clean_str += ' '\n continue\n else:\n clean_str += line[i]\n return clean_str\n\ndef put_into_dictionary(d, line):\n if line == 'empty line':\n return d\n for elem in line:\n if elem[0] in d.keys():\n oldlist=d.get(elem[0])\n if elem[1] not in oldlist:\n oldlist.append(elem[1])\n #cann take out last line if you dont want the word after, just 2 words\n oldlist.append(elem[2])\n d[elem[0]]=oldlist\n else:\n new_list=[]\n new_list.append(elem[1])\n #cann take out last line if you dont want the word after, just 2 words\n new_list.append(elem[2])\n d[elem[0]]=new_list\n #need to account for repeat words\n return d\n\ndef generate_line(d):\n \"\"\"\n Generates a random sentence based on the dictionary\n with transition pairs\n \"\"\"\n sentence=''\n #random.choice to pick a random element from a list\n next=random.choice(d.get('BEGIN'))\n #first is BEGIN but we don't want to use it\n\n while next != 'stop':\n sentence += (str(next)+' ')\n if ' ' in next:\n last_word=(next.split())[1]\n else:\n last_word=next\n next=next_word(last_word)\n return sentence\n\ndef next_word(last_word):\n if not d.get(last_word):\n return 'stop'\n word = random.choice(d.get(last_word))\n if word == 'END':\n return 'stop'\n else:\n return word\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print ('ERROR: Run as python markov.py ')\n exit()\n\n d = process_textfile(sys.argv[1])\n #it creates a dictionary from the texts that I put in the file I call as first argument\n\n print(d)\n\n #news_song=\n # #import new song class stufff - making a visual of these song lines\n newsong= []\n for i in range(NUMLINES):\n line = str(generate_line(d))\n newsong.append(no_punct(line))\n\n visualize_song=SongVisual(newsong)\n\n #put line onto canvas for the class\n","repo_name":"rockness26/koldemama","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7636335632","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\nimport sys, time, os, shlex\nimport numpy, cv2\nfrom subprocess import *\nfrom TouchStyle import *\nfrom threading import Timer\nfrom TouchAuxiliary import *\n\ntry:\n if TouchStyle_version<1.2:\n print(\"aux: TouchStyle >= v1.2 not found!\") \nexcept:\n print(\"aux: TouchStyle_version not found!\")\n TouchStyle_version=0\n\nlocal = os.path.dirname(os.path.realpath(__file__)) + \"/icons/\"\n\nclass myColorRequest(TouchDialog):\n \"\"\" \n Opens up a window containing a list of items and returns the item selected by the user\n \n ******** function call **********\n m = TouchAuxColorRequest(title:str, initcolor:QColor(), parent:class)\n (int:QColor)=m.exec_()\n ******** parameters *************\n \n title:str Title of the input window\n parent:class Parent class\n \n ******** Return values **********\n success:bool True for user confirmed selection, False for user aborted selection\n result:str selected item in case of success==True or None in case of success=False\n \"\"\"\n \n def __init__(self,title:str, initcolor, parent=None):\n TouchDialog.__init__(self,title,parent) \n \n self.result=None\n self.initcolor=initcolor\n self.title=title\n self.confbutclicked=False\n \n def on_button(self):\n self.result=self.sender().text()\n self.close()\n \n def exec_(self):\n self.layout=QVBoxLayout()\n \n # the message\n self.l_color=QLabel()\n self.l_color.setObjectName(\"smalllabel\")\n self.l_color.setAlignment(Qt.AlignCenter)\n self.layout.addWidget(self.l_color)\n \n self.layout.addStretch()\n \n self.s_red=QSlider()\n self.s_red.setOrientation(Qt.Horizontal)\n self.s_red.setRange(0,255)\n self.s_red.setSingleStep(1)\n self.s_red.setPageStep(1)\n self.s_red.setValue(self.initcolor.red())\n self.s_red.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_red)\n\n self.layout.addStretch()\n \n self.s_green=QSlider()\n self.s_green.setOrientation(Qt.Horizontal)\n self.s_green.setRange(0,255)\n self.s_green.setSingleStep(1)\n self.s_green.setPageStep(1)\n self.s_green.setValue(self.initcolor.green())\n self.s_green.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_green)\n \n self.layout.addStretch()\n \n self.s_blue=QSlider()\n self.s_blue.setOrientation(Qt.Horizontal)\n self.s_blue.setRange(0,255)\n self.s_blue.setSingleStep(1)\n self.s_blue.setPageStep(1)\n self.s_blue.setValue(self.initcolor.blue())\n self.s_blue.valueChanged.connect(self.on_color_update)\n self.layout.addWidget(self.s_blue)\n \n self.layout.addStretch()\n \n self.cbox=QLabel()\n self.cbox.setPixmap(QPixmap(240,40))\n self.layout.addWidget(self.cbox)\n \n self.layout.addStretch()\n if TouchStyle_version >=1.3:\n self.setCancelButton()\n confirmbutton=self.addConfirm()\n confirmbutton.clicked.connect(self.on_button)\n else:\n self.layout.addStretch()\n okb=QPushButton(\"Okay\")\n okb.clicked.connect(self.on_button)\n self.layout.addWidget(okb)\n \n self.on_color_update()\n self.centralWidget.setLayout(self.layout) \n \n TouchDialog.exec_(self)\n \n if self.confbutclicked or self.result!=None: return True,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value())\n return False,None\n \n def on_color_update(self):\n self.l_color.setText(\n \"R \"+(\"00\"+str(self.s_red.value()))[-3:]+\" :\"+\n \"G \"+(\"00\"+str(self.s_green.value()))[-3:]+\": \"+\n \"B \"+(\"00\"+str(self.s_blue.value()))[-3:])\n p=QPainter()\n p.begin(self.cbox.pixmap())\n p.fillRect(0,0,240,40,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value()))\n self.cbox.update()\n self.update()\n\nclass colorset(TouchDialog):\n \"\"\" \n Opens up a window containing a list of items and returns the item selected by the user\n \n ******** function call **********\n m = colorset(title:str, colors[]:QColor, parent:class)\n (success, colors)=m.exec_()\n ******** parameters *************\n \n title:str Title of the input window\n parent:class Parent class\n \n ******** Return values **********\n success:bool True for user confirmed selection, False for user aborted selection\n result:QColor[] array of colors or None in case of success=False\n \"\"\"\n \n def __init__(self,title:str, colors, parent=None):\n TouchDialog.__init__(self,title,parent) \n \n self.result=None\n self.colors=colors\n \n self.title=title\n self.confbutclicked=False\n \n def on_button(self):\n self.result=self.sender().text()\n self.close()\n \n def colorgrid(self):\n colcnt = len(self.colors)\n cpr=8\n \n k=QVBoxLayout()\n c=QHBoxLayout()\n \n for i in range(32):\n s = i % cpr\n z = i // cpr\n if s==0:\n if i>0:\n c.addStretch()\n k.addLayout(c)\n c=QHBoxLayout()\n \n self.b=TouchAuxPicButton(QPixmap(28,28))\n p=QPainter()\n p.begin(self.b.pixmap)\n if icnc:\n for i in range(cnc,r): self.addcolor()\n if r=1.3:\n self.setCancelButton()\n confirmbutton=self.addConfirm()\n confirmbutton.clicked.connect(self.on_button)\n else:\n self.layout.addStretch()\n okb=QPushButton(\"Okay\")\n okb.clicked.connect(self.on_button)\n self.layout.addWidget(okb)\n \n self.on_color_update()\n \n def exec_(self):\n self.mode=\"\"\n self.set_layout()\n\n self.centralWidget.setLayout(self.layout) \n \n TouchDialog.exec_(self)\n \n if self.confbutclicked or self.result!=None: return True,self.colors\n return False,None\n \n def on_color_update(self):\n return\n self.l_color.setText(\n \"R \"+(\"00\"+str(self.s_red.value()))[-3:]+\" :\"+\n \"G \"+(\"00\"+str(self.s_green.value()))[-3:]+\": \"+\n \"B \"+(\"00\"+str(self.s_blue.value()))[-3:])\n p=QPainter()\n p.begin(self.cbox.pixmap())\n p.fillRect(0,0,240,40,QColor(self.s_red.value(),self.s_green.value(), self.s_blue.value()))\n self.cbox.update()\n self.update()\n","repo_name":"ftCommunity/ftcommunity-apps","sub_path":"packages/BenoiTXT/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":13258,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"}
+{"seq_id":"41299772953","text":"\ndef date_to_days(y, m, d):\n \"\"\"A Gergely-naptár szerinti időszámítás nulladik napjától a paraméterben megadott dátumig visszaadja a napok számát.\n Returns the number of days from the zero day of the Gregorian calendar to the date specified in the parameter.\"\"\"\n m = (m + 9) % 12\n y = y - m // 10\n return 365 * y + y // 4 - y // 100 + y // 400 + (m * 306 + 5) // 10 + d - 1\n\ndef days_of_month(y, m):\n \"\"\"A hónapokhoz tartozó napok számát adja vissza. Februárban figyelembe veszi a szökőéveket is.\n Returns the number of days in the month. In February, the leap years are also taken into account.\"\"\"\n dom = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n feb = 28\n if y % 4 == 0:\n feb = 29\n if y % 100 == 0:\n feb = 28\n if y % 400 == 0:\n feb = 29\n dom[1] = feb\n return dom[m % 12]\n\n\nclass Month:\n\n # header_week = 'hétf kedd szer csüt pént szom vasn'\n # header_week = 'hét ked sze csü pén szo vas'\n header_week = 'hé ke sz cs pé sz va'\n fam_day = '1848-03-15, 2' # A 19. századi magyar forradalom, mint minden menő projekt, a hét közepén, szerdán kedődött. The 19th century Hungarian revolution, like all cool projects, began on Wednesday in the middle of the week.\n months = [\n 'január', 'február', 'március',\n 'április', 'május', 'június',\n 'július', 'augusztus', 'szeptember',\n 'október', 'november', 'december']\n\n def __init__(self, year, month):\n self.year = year\n self.month = month\n\n def __str__(self):\n return self.month_view()\n\n def month_view(self):\n h = self.lhw()\n days_list = [self.strd(d) for d in self.days_numb()]\n days_str = (h // 7 + 1) * self.firs_day_ident( )* ' '\n days_str += (h // 7 - 2) * ' '\n days_str += ((h // 7 - 1) * ' ').join(days_list)\n days_str += (h * 6 - len(days_str) + 5) * ' '\n month_str = (str(self.year) + '. ' + self.months[(self.month - 1) % 12]).center(h) + '\\n'\n month_str +=(self.header_week) + '\\n'\n for i in range(len(days_str) // h + 2):\n month_str += days_str[(h + 1) * i:(h + 1) * (i + 1) - 1] + '\\n'\n return month_str\n\n def strd(self, d):\n \"\"\"Az egyjegyű napsorszámokat jobbra igazítja.\n Aligns single-digit day numbers to the right.\"\"\"\n return str(d) if d > 9 else ' ' + str(d)\n\n def firs_day_ident(self):\n \"\"\"Megadja a napsorszámokat tartalmazó karakterlánc első sorának behúzását.\n Specifies to indent the first line of the string containing the date numbers.\"\"\"\n return (date_to_days(self.year, self.month, 1) - self.days_of_fam_day())%7\n\n def days_numb(self):\n \"\"\"Az aktuális hónap napsorszámokat tartalmazó listáját adja vissza.\n Returns with the list of date numbers of the current month.\"\"\"\n return [d for d in range(1, days_of_month(self.year, (self.month - 1) % 12) + 1)]\n\n @classmethod\n def lhw(cls):\n return len(cls.header_week)\n\n @classmethod\n def days_of_fam_day(cls):\n datum, weekday = [el for el in cls.fam_day.strip().split(',')]\n y, m, d = [int(el) for el in datum.split('-')]\n return date_to_days(y, m, d) - int(weekday)\n\n\nclass Calendar:\n\n def __init__(self, year, month=None):\n self.year = year\n self.month = month\n self.col = 4\n self.row = 3\n self.col_gap = 6\n self.months = [Month(year, m) for m in range(self.col * self.row + 1)]\n\n def __str__(self):\n return self.calendar_view()\n\n def calendar_view(self):\n if self.month is not None:\n m = Month(self.year, self.month)\n result = str(m)\n else:\n pm = [self.months[i] for i in range(1, self.col * self.row + 1)]\n result = ''\n for r in range(self.row):\n calstr = ['' for _ in range(10)]\n for c in range(self.col):\n for i in range(10):\n calstr[i] += str(pm[r * self.col + c]).splitlines()[i] + ' ' * self.col_gap\n for l in calstr:\n result += l + '\\n'\n return '\\n\\n' + result\n\n\nif __name__ == '__main__':\n a = Calendar(2020,2)\n print(a)\n","repo_name":"Janick7/print-calendar","sub_path":"calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"9215255428","text":"\"\"\"\nDesign pattern: since each model has it's own data, we wrap each model in an agent class that can take care of the\nspecifics of the data manipulation form a batch. e.g. if they are tensors, or symbolic objects or NL etc.\n\nNote:\n - the forward functions are used in training so calling .item() on the values it returns will create issues for\n training.\n\"\"\"\nfrom argparse import Namespace\n\nimport numpy as np\nimport torch\nfrom torch import nn, Tensor\n\nfrom uutils.torch_uu.agents.common import Agent\nfrom uutils.torch_uu.distributed import process_batch_ddp\nfrom uutils.torch_uu.metrics.confidence_intervals import mean_confidence_interval\nfrom uutils.torch_uu.metrics.metrics import accuracy\n\nfrom pdb import set_trace as st\n\n\nclass ClassificationSLAgent(Agent):\n\n def __init__(self,\n args: Namespace,\n model: nn.Module,\n ):\n super().__init__()\n self.args = args\n self.model = model\n if hasattr(args, 'loss'):\n self.loss = nn.CrossEntropyLoss() if args.loss is not None else args.loss\n self.criterion = args.loss\n\n def forward(self, batch: Tensor, training: bool = True) -> tuple[Tensor, Tensor]:\n \"\"\"\n Note:\n - does not need get_lists_accs_losses (in contrast to meta-learning) because in meta-learning with episodic\n meta-learning we always compute the list of losses/accs for both forward & eval pass. But in SL we only\n need the list info when explicitly needed and in eval (so we can compute CIs). Basically, the train forward\n in eval just returns the single float/tensor element for loss/acc -- doesn't explicitly use the iter representations.\n \"\"\"\n self.model.train() if training else self.model.eval()\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n logits: Tensor = self.model(batch_x)\n loss: Tensor = self.loss(logits, batch_y)\n acc, = accuracy(logits, batch_y)\n assert loss.size() == torch.Size([])\n assert acc.size() == torch.Size([])\n return loss, acc\n\n def eval_forward(self, batch: Tensor, training: bool = False) -> tuple[Tensor, Tensor, Tensor, Tensor]:\n \"\"\"\n Note:\n - reason this is different than forward is because we have a torch.no_grad() and because in eval we are\n also returning the CI's, so we need to get the flat tensor/list/iterable to compute those, so we can't just\n get the loss as it's usually done in forward passes in pytorch that only return the loss/acc. We use the\n accs & losses info basically.\n \"\"\"\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n B: int = batch_x.size(0)\n with torch.no_grad(): # note, this might not be needed in meta-eval due to MAML using grads at eval\n # - to make sure we get the [B] tensor to compute confidence intervals/error bars\n loss, acc = self.get_lists_accs_losses(batch, training)\n assert loss.size() == torch.Size([B])\n assert acc.size() == torch.Size([B])\n\n # - stats, compute this in context manager to avoid memory issues (perhaps not needed but safer)\n eval_loss_mean, eval_loss_ci = mean_confidence_interval(loss)\n eval_acc_mean, eval_acc_ci = mean_confidence_interval(acc)\n return eval_loss_mean, eval_loss_ci, eval_acc_mean, eval_acc_ci\n\n def get_lists_accs_losses(self, batch: Tensor,\n training: bool,\n as_list_floats: bool = False,\n as_numpy_data: bool = False, # careful, if NOT set you might get GPU memory issues\n ) -> tuple[iter, iter]:\n \"\"\"\n Note:\n - train doesn't need this but eval does. Also, it could be useful to get lists to do other analysis with them if needed.\n \"\"\"\n # -- get data\n batch_x, batch_y = process_batch_ddp(self.args, batch)\n B: int = batch_x.size(0)\n\n # -- get ready to collect losses and accs\n original_reduction: str = self.loss.reduction\n self.loss.reduction = 'none'\n self.model.train() if training else self.model.eval()\n\n # -- \"forward\"\n logits: Tensor = self.model(batch_x)\n loss: Tensor = self.loss(logits, batch_y)\n acc, = accuracy(logits, batch_y, reduction='none')\n assert loss.size() == torch.Size([B])\n assert acc.size() == torch.Size([B])\n\n # -- convert losses & accs to list of floats\n if as_list_floats:\n loss: list[float] = loss.detach().cpu().numpy().tolist()\n acc: list[float] = acc.detach().cpu().numpy().tolist()\n\n if as_numpy_data:\n loss: np.ndarray = loss.detach().cpu().numpy()\n acc: np.ndarray = acc.detach().cpu().numpy()\n\n # - return loss to normal\n self.loss.reduction = original_reduction\n self.model.train()\n return loss, acc\n\n\nclass RegressionSLAgent(Agent):\n \"\"\"\n todo - main difference is to use R2 score (perhaps squeezed, for accuracy instead of loss), and\n to make sure it has the options for reduction.\n \"\"\"\n\n def __init__(self, model: nn.Module, loss: nn.Module):\n super().__init__()\n self.model = model\n self.loss = loss\n","repo_name":"brando90/ultimate-utils","sub_path":"ultimate-utils-proj-src/uutils/torch_uu/agents/supervised_learning.py","file_name":"supervised_learning.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"52"}
+{"seq_id":"31327574595","text":"import pandas as pd\nfrom torch.utils.data.dataset import Dataset\nimport csv\nfrom nltk.tokenize import sent_tokenize, word_tokenize\nimport numpy as np\nimport pickle\n\n\ndef get_label(label):\n try:\n return eval(label.strip())[0]\n except Exception as e:\n pass\n\n return label\n\n# add visualize\n\n\nclass MyDataset(Dataset):\n def __init__(self, data_path, label_path, label_namesFile, ImportanceFeatureMatsFile, model_gensim, max_vocab, training_inds, childLabel2ParentLabelFile=None, test_this_label=None, dataset=None, descriptor_HANsFile=None, VvFile=None, max_length_sentences_given=None, max_length_word_given=None):\n if VvFile:\n self.Vv = pickle.load(open(VvFile, 'rb'))\n self.dataset = dataset\n super(MyDataset, self).__init__()\n\n texts, labels = [], []\n max_length_sentences = 0\n max_length_word = 0\n count = 0\n docind_withMaxLength = 0\n text_lines = open(data_path).readlines()\n labels_lines = [l.strip() for l in open(label_path).readlines()]\n training_labels = [labels_lines[i] for i in training_inds]\n\n if descriptor_HANsFile:\n descriptor_HANsFile = open(descriptor_HANsFile).readlines()\n self.model_gensim = model_gensim\n self.additional_info = []\n\n ImportanceFeatureMatsOriginal = pickle.load(open(ImportanceFeatureMatsFile, 'rb'))\n ImportanceFeatureMats = []\n\n class_ids = pickle.load(open(label_namesFile, 'rb'))\n if childLabel2ParentLabelFile:\n self.childLabel2ParentLabel = pickle.load(open(childLabel2ParentLabelFile, 'rb'))\n class_id2ind = {id: ind for ind, id in enumerate(class_ids)}\n\n for i, (line, label) in enumerate(zip(text_lines, labels_lines)):\n label = get_label(label.strip())\n\n if label not in class_id2ind:\n break\n\n if training_inds and i not in training_inds:\n continue\n if test_this_label and test_this_label != label:\n continue\n\n label_id = class_id2ind.get(label)\n labels.append(label_id)\n ImportanceFeatureMats.append(ImportanceFeatureMatsOriginal[i])\n self.additional_info.append('index_in_input {}'.format(i))\n\n if descriptor_HANsFile:\n self.additional_info[-1] += ' original: {}'.format(descriptor_HANsFile[i])\n\n super_con = []\n super_concepts = line.strip().split('. ')\n if(len(super_concepts) > max_length_sentences):\n max_length_sentences = len(super_concepts)\n docind_withMaxLength = count\n for super_concept in super_concepts:\n concept = super_concept.split(' ')\n if(len(concept) > max_length_word):\n max_length_word = len(concept)\n super_con.append(concept)\n texts.append(super_con)\n count += 1\n\n self.text_lines = text_lines\n self.texts = texts\n self.labels = labels\n self.ImportanceFeatureMats = ImportanceFeatureMats\n self.labels_list = class_ids\n self.class_id2ind = class_id2ind\n self.index_dict = self.model_gensim.wv.index2word[:max_vocab]\n self.vocab_dict = {}\n for index, value in enumerate(self.index_dict[:max_vocab]):\n self.vocab_dict[value] = index\n\n self.sent_feature_len = self.ImportanceFeatureMats[0].shape[1]\n self.max_length_sentences = max_length_sentences\n if max_length_sentences_given:\n self.max_length_sentences = max(self.max_length_sentences, max_length_sentences_given)\n self.max_length_word = max_length_word\n if max_length_word_given:\n self.max_length_word = max(self.max_length_word, max_length_word_given)\n\n self.num_classes = len(self.class_id2ind)\n print('self.labels_list', self.labels_list)\n print('max_length_sentences', max_length_sentences)\n print('max_length_word', max_length_word)\n print('num_classes: ', self.num_classes)\n print('num_docs: ', len(self.texts))\n\n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, index):\n label = self.labels[index]\n text = self.texts[index]\n additional_info = self.additional_info[index]\n\n ImportanceFeatureMat = self.ImportanceFeatureMats[index]\n try:\n ImportanceFeatureMat_padded = np.zeros(\n (self.max_length_sentences, ImportanceFeatureMat.shape[1]))\n except Exception as e:\n import ipdb\n ipdb.set_trace()\n raise e\n ImportanceFeatureMat_padded[:ImportanceFeatureMat.shape[0]] = ImportanceFeatureMat\n\n document_encode = [\n [self.vocab_dict[word] if word in self.vocab_dict else -1 for word in sentences] for sentences\n in text]\n\n for sentences in document_encode:\n if len(sentences) < self.max_length_word:\n extended_words = [-1 for _ in range(self.max_length_word - len(sentences))]\n sentences.extend(extended_words)\n\n if len(document_encode) < self.max_length_sentences:\n extended_sentences = [[-1 for _ in range(self.max_length_word)] for _ in\n range(self.max_length_sentences - len(document_encode))]\n document_encode.extend(extended_sentences)\n\n document_encode = [sentences[:self.max_length_word] for sentences in document_encode][\n :self.max_length_sentences]\n\n document_encode = np.stack(arrays=document_encode, axis=0)\n document_encode += 1\n\n return document_encode.astype(np.int64), ImportanceFeatureMat_padded, label, index, additional_info\n\n def doc_tensor2doc(self, t):\n texts = [self.index_dict[i - 1] if i > 0 else '' for i in t.data.cpu().numpy().reshape(-1)]\n return texts\n\n\nif __name__ == '__main__':\n test = MyDataset(data_path=\"/disk/home/klee/data/cs_merged_tokenized_superspan_HANs.txt\",\n label_path='/disk/home/klee/data/cs_merged_label', dict_path=\"/disk/home/klee/data/cs_merged_tokenized_dictionary.bin\")\n print(test[0])\n print(test.__getitem__(index=1)[0].shape)\n","repo_name":"kleeeeea/Hiercon","sub_path":"similarity_aggregation/src/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"}
+{"seq_id":"14764545111","text":"from constraint import *\n\n\ndef checkSum(t_l, t_m1, t_m2, t_m3, t_m4, t_m5):\n team_lider_weight = t_l\n team_member1 = t_m1\n team_member2 = t_m2\n team_member3 = t_m3\n team_member4 = t_m4\n team_member5 = t_m5\n total_score = team_lider_weight + team_member1 + team_member2 + team_member3 + team_member4 + team_member5\n if 0 < total_score <= 100.0:\n return True\n # togas ovaa kombinacija e validna moze da se racuna kako rezultat\n else:\n return None\n # togas ovaa kombinacija na vrednosti ne gi zadovoluva uslovite\n\n\nif __name__ == '__main__':\n problem = Problem()\n\n total_score = 0.0\n number_members = int(input())\n\n i = 0\n t_m_names = []\n t_m_weights = []\n\n while i < number_members:\n line = input().split(\" \")\n number = float(line[0])\n t_m_weights.append(number)\n name = str(line[1])\n t_m_names.append(name)\n i += 1\n\n number_leaders = int(input())\n\n j = 0\n t_l_names = []\n t_l_weights = []\n\n while j < number_leaders:\n line = input().split(\" \")\n number = float(line[0])\n t_l_weights.append(number)\n name = str(line[1])\n t_l_names.append(name)\n j += 1\n\n t_m_names.reverse()\n t_m_weights.reverse()\n\n t_l_names.reverse()\n t_l_weights.reverse()\n\n problem.addVariable('1', t_l_weights)\n problem.addVariable('2', t_m_weights)\n problem.addVariable('3', t_m_weights)\n problem.addVariable('4', t_m_weights)\n problem.addVariable('5', t_m_weights)\n problem.addVariable('6', t_m_weights)\n problem.addConstraint(AllDifferentConstraint(), ['1'])\n\n for i in range(2, 7):\n for j in range(2, 7):\n if i < j:\n problem.addConstraint(lambda a, b: a != b, (f'{i}', f'{j}'))\n problem.addConstraint(checkSum, ['1', '2', '3', '4', '5', '6'])\n\n solutions = problem.getSolutions()\n\n optimal_team = dict()\n max_score = 0\n total_score = 0\n number_of_optimal_team = 0\n\n for index in range(0, len(solutions)):\n for k in solutions[index].keys():\n total_score += solutions[index][k]\n if total_score == 100.0:\n max_score = total_score\n number_of_optimal_team = index\n else:\n total_score = 0\n\n optimal_team = solutions[number_of_optimal_team]\n\n t_l_index = t_l_weights.index(optimal_team[\"1\"])\n t_m1_index = t_m_weights.index(optimal_team[\"2\"])\n t_m2_index = t_m_weights.index(optimal_team[\"3\"])\n t_m3_index = t_m_weights.index(optimal_team[\"4\"])\n t_m4_index = t_m_weights.index(optimal_team[\"5\"])\n t_m5_index = t_m_weights.index(optimal_team[\"6\"])\n\n print(f'Total score: {max_score}')\n print(f'Team leader: {t_l_names[t_l_index]}')\n print(f'Participant 1: {t_m_names[t_m1_index]}')\n print(f'Participant 2: {t_m_names[t_m2_index]}')\n print(f'Participant 3: {t_m_names[t_m3_index]}')\n print(f'Participant 4: {t_m_names[t_m4_index]}')\n print(f'Participant 5: {t_m_names[t_m5_index]}')","repo_name":"StefBelcev/PythonCourse","sub_path":"exercises/lab02/optimal_team4.py","file_name":"optimal_team4.py","file_ext":"py","file_size_in_byte":3017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"71392812326","text":"import sys\nsys.path.append('.')\nimport day2\nfrom day2 import checksum\nfrom day2 import findboxes\nimport unittest\n\nclass TestDay2(unittest.TestCase):\n def test_checksum(self):\n ids = [\n \"abcdef\",\n \"bababc\",\n \"abbcde\",\n \"abcccd\",\n \"aabcdd\",\n \"abcdee\",\n \"ababab\"\n ]\n self.assertEqual(12, day2.checksum(ids))\n\n def test_findboxes(self):\n ids2 = [\n \"abcde\",\n \"fghij\",\n \"klmno\",\n \"pqrst\",\n \"fguij\",\n \"axcye\",\n \"wvxyz\"\n ]\n self.assertEqual('fgij', day2.findboxes(ids2))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"avecci/AoC2018","sub_path":"test/test_day2.py","file_name":"test_day2.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5088585427","text":"import names\n\nPLAYER_ACTIONS = [\"FOLD\", \"CHECK\", \"CALL\", \"ALL_IN\", \"RAISE_50\", \"RAISE_75\", \"RAISE_100\"]\n\nclass Player:\n # general\n chips = 0\n INITIAL_CHIPS = 0\n name = \"\"\n \n # game\n hand = None # Card Tuple\n \n # round\n bet = 0\n action_completed = False\n is_all_in = False\n is_folded = False\n \n def __init__(self, chips):\n self.chips = chips\n self.INITIAL_CHIPS = chips\n self.name = names.get_first_name()\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return self.name\n\n def buy_in(self, value):\n self.chips += value\n\n def give_hand(self, card1, card2): # hand = (Card, Card)\n self.hand = (card1, card2)\n\n def soft_reset(self):\n self.bet = 0\n self.action_completed = False\n\n def hard_reset(self):\n if self.chips == 0:\n self.chips += self.INITIAL_CHIPS\n self.bet = 0\n self.action_completed = False\n self.is_all_in = False\n self.is_folded = False\n\n # cool methods:\n\n def ask_for_action(self, entire_pot, highest_bet):\n check_is_possible = highest_bet == self.bet\n call_is_possible = (highest_bet - self.bet) < self.chips and not check_is_possible\n raise_50_is_possible = (entire_pot + (highest_bet - self.bet)) * 1.5 < self.chips\n raise_75_is_possible = (entire_pot + (highest_bet - self.bet)) * 1.75 < self.chips\n raise_100_is_possible = (entire_pot + (highest_bet - self.bet)) * 2 < self.chips\n\n possible_actions = ['FOLD', 'ALL_IN']\n if check_is_possible:\n possible_actions.append('CHECK')\n if call_is_possible:\n possible_actions.append('CALL')\n if raise_50_is_possible:\n possible_actions.append('RAISE_50')\n if raise_75_is_possible:\n possible_actions.append('RAISE_75')\n if raise_100_is_possible:\n possible_actions.append('RAISE_100')\n\n \"\"\"\n self.action_completed = True\n if check_is_possible:\n return \"CHECK\"\n elif call_is_possible:\n return \"CALL\"\n else:\n return \"FOLD\"\n \"\"\"\n\n action = None\n if True:\n print(f\"Hi {self.name}!\")\n print(f\"You have {str(self.hand[0])} and {str(self.hand[1])}\")\n print(f\"Your current bet is {self.bet}\")\n print(f\"You have {self.chips} chips\")\n print(f\"The current pot is {entire_pot}\")\n print(f\"The highest bet is {highest_bet}\")\n if call_is_possible:\n print(f\"You need {highest_bet - self.bet} to call\")\n while not action in possible_actions:\n action = input(f\"What do you want to do? ({', '.join(possible_actions)}) \").upper()\n \n self.action_completed = True\n return action\n\n def set_bet(self, value):\n chips_to_pay = value - self.bet\n self.chips -= chips_to_pay\n self.bet = value\n\n def raise_bet(self, entire_pot, highest_bet, percentage):\n goal = (entire_pot + (highest_bet - self.bet)) * percentage\n\n rounded_goal = round(goal * 2) / 2\n\n self.set_bet(rounded_goal)\n\n\n","repo_name":"TokeyChan/poker","sub_path":"game/classes/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1538151272","text":"import sys\n\n\ndef matric_chain(p, n):\n m = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n):\n m[i][i] = 0\n j, q = 0, 0\n for l in range(2, n):\n for i in range(1, n-l+1):\n j = i+l-1\n m[i][j] = sys.maxsize\n for k in range(i, j):\n q = m[i][k] + m[k+1][j] + (p[i-1] * p[k] * p[j])\n if q < m[i][j]:\n m[i][j] = q\n\n return m[1][n-1]\n\n\narr = list(map(int, input(\"Enter Dimentions of the Matrices :- \").rstrip().split()))\nprint(\"Minimum Number of Multiplication is :- \", matric_chain(arr, len(arr)))\n","repo_name":"Pyk017/Important-Algorithms","sub_path":"Matric_Chain_Multiplication/Matric_Chain_Multiplication.py","file_name":"Matric_Chain_Multiplication.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"41011321648","text":"from django.shortcuts import render\nfrom django.core.checks import messages\nfrom django.contrib import messages\nfrom django.shortcuts import render, HttpResponse\nfrom django.views.generic import View\nfrom .forms import *\nfrom .models import *\nfrom myapp1 import views\nfrom django.shortcuts import redirect\n\n# Create your views here.\n\nclass MyIndexView(View):\n def get(self,request):\n return render(request, 'index.html')\n\nclass MyResView(View):\n def get(self,request):\n return render(request, 'res.html' )\n\nclass MyMornView(View):\n def get(self,request):\n return render(request, 'morning.html')\n def post(self, request): \n form = BookForm(request.POST) \n\n if form.is_valid():\n # try:\n res_number = request.POST.get(\"res_number\")\n Name = request.POST.get(\"Name\")\n Address = request.POST.get(\"Address\")\n tel_Number = request.POST.get(\"tel_Number\")\n room_number = request.POST.get(\"room_number\")\n date = request.POST.get(\"date\")\n time = request.POST.get(\"time\")\n\n form = ResBook(res_number = res_number, Name = Name, Address = Address, tel_Number = tel_Number, room_number = room_number, date = date, time= time)\n form.save()\n\n \n return redirect('/res')\n \n else:\n print(form.errors)\n return HttpResponse('not valid')\n\n\nclass CreateRoomView(View):\n def get(self,request):\n return render(request, 'createRoom.html')\n \n def post(self,request):\n form = RoomForm(request.POST)\n\n if form.is_valid():\n room_number = request.POST.get(\"room_number\")\n room_type = request.POST.get(\"room_type\")\n no_guest = request.POST.get(\"no_guest\")\n form = Room(room_number = room_number,room_type = room_type, no_guest = no_guest)\n form.save()\n return redirect('/Rooms')\n else:\n print(form.errors) \n return HttpResponse('Please Fill Out All The Information') \n\nclass RoomView(View):\n def get(self, request):\n room = Room.objects.all()\n context = {\n 'roomRow' : room\n }\n return render(request, 'Rooms.html', context)\n\n def post(self, request):\n if(request.method) == 'POST':\n if 'btnUpdate' in request.POST:\n print('update profile')\n room_number = request.POST.get(\"room_number\")\n room_type = request.POST.get(\"room_type\")\n no_guest = request.POST.get(\"no_guest\")\n update = Room.objects.filter(room_number = room_number).update(room_type = room_type, no_guest = no_guest)\n print(update)\n print('Room updated')\n return redirect('/Rooms')\n elif 'btnDelete' in request.POST:\n print('delete button clicked')\n iddn = request.POST.get(\"room_number\")\n iddn = Room.objects.filter(room_number = iddn).delete()\n print('record deleted')\n return redirect('/Rooms')\n\nclass RoomDisplayView(View):\n def get(self, request):\n room = Room.objects.all()\n context = {\n 'roomRow' : room\n }\n return render(request, 'RoomsDisplay.html', context)\n\n\n\n\n\n\n \n \n \n \n \n \n \n\n\n \n \n\n\n","repo_name":"franzcasia/DJFReservationSystem","sub_path":"myapp1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"32060039896","text":"from typing import List\n\nfrom fastapi import Depends\nfrom fastapi import APIRouter\nfrom fastapi.encoders import jsonable_encoder\n\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom core.database import get_current_db\nfrom users.models import User\nfrom users.service import get_current_user\n\nimport conditions.schemas as cond_schemas\nimport conditions.models as cond_models\n\n\nrouter = APIRouter(\n prefix=\"/conditions\",\n tags=[\"conditions\"]\n)\n\n# region ConditionCRUD\n\n\n@router.get(\"/\", response_model=List[cond_schemas.Condition])\nasync def get_all_condition(\n *,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> List[cond_schemas.Condition]:\n\n conditions = await cond_models.Condition.get_all(db_session=db_session)\n\n return conditions\n\n\n@router.post(\"/\", response_model=cond_schemas.Condition)\nasync def create_condition(\n *,\n visit_in: cond_schemas.Condition,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.create(db_session=db_session, cls_in=visit_in)\n return condition\n\n\n@router.get(\"/{cond_id}/\", response_model=cond_schemas.Condition)\nasync def get_condition_by_id(\n *,\n cond_id: int,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.get_by_id(db_session=db_session, id=cond_id)\n return condition\n\n\n@router.put(\"/{cond_id}/\", response_model=cond_schemas.Condition)\nasync def update_condition(\n *,\n cond_id: int,\n cond_in: cond_schemas.Condition,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> cond_schemas.Condition:\n\n condition = await cond_models.Condition.update(\n db_session=db_session,\n id=cond_id,\n cls_in=cond_in\n )\n return condition\n\n\n@router.delete(\"/{cond_id}/\")\nasync def delete_condition(\n *,\n cond_id: int,\n db_session: AsyncSession = Depends(get_current_db),\n current_user: User = Depends(get_current_user)\n) -> None:\n\n await cond_models.Condition.delete(db_session=db_session, id=cond_id)\n\n# endregion\n","repo_name":"ustimova-a/med_records","sub_path":"src/conditions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"32401575746","text":"import json\nfrom typing import Optional, List\nfrom fastapi import FastAPI, Body, status\nfrom fastapi.responses import JSONResponse\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom pydantic import BaseModel\n\n\napp = FastAPI(title=\"Persons FastApi\")\n\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n )\n\n# ========== Model =============\nclass PersonInput(BaseModel):\n first_name: str\n last_name: str\n gender: str\n age: int\n email: str\n phone: str\n city: str\n address: str\n\nclass PersonOutput(PersonInput):\n id: int\n\n# ======== Helpers =========\n\ndef load_db():\n with open(\"/home/keys4/app/dummy_db.json\") as f:\n return [PersonOutput.parse_obj(el) for el in json.load(f)]\n\ndef save_db(persons: List[PersonInput]):\n with open(\"/home/keys4/app/dummy_db.json\", \"w\") as f:\n json.dump([person.dict() for person in persons], f)\n\n\npersons = load_db()\n\n\n# ========= Routes =========\n\n@app.get(\"/\")\nasync def main():\n return \"Root page: use /api/persons
\"\n\n\n@app.get(\"/api/persons\")\ndef get_persons(gender: Optional[str] = None, age: Optional[int] = None):\n res = persons\n if gender:\n res = [person for person in persons if person.gender == gender]\n if age:\n res = [person for person in persons if person.age >= age]\n return res\n\n\n@app.get(\"/api/persons/{person_id}\")\ndef get_person(person_id: int):\n res = [person for person in persons if person.id == person_id]\n if not len(res):\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n return res[0]\n\n\n@app.post(\"/api/persons\", response_model=PersonOutput)\ndef create_person(data = Body()):\n new_person = PersonOutput(\n id=len(persons)+1,\n first_name=data[\"first_name\"],\n last_name=data[\"last_name\"],\n gender=data[\"gender\"],\n age=data[\"age\"],\n email=data[\"email\"],\n phone=data[\"phone\"],\n city=data[\"city\"],\n address=data[\"address\"]\n )\n persons.append(new_person)\n save_db(persons)\n return new_person\n\n\n@app.put(\"/api/persons/{person_id}\", response_model=PersonOutput)\ndef edit_person(person_id: int, data = Body()):\n matches = [person for person in persons if person.id == person_id]\n if matches:\n person = matches[0]\n person.first_name = data[\"first_name\"]\n person.last_name = data[\"last_name\"]\n person.gender = data[\"gender\"]\n person.age = data[\"age\"]\n person.email = data[\"email\"]\n person.phone = data[\"phone\"]\n person.city = data[\"city\"]\n person.address = data[\"address\"]\n save_db(persons)\n return person\n else:\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n\n\n@app.delete(\"/api/persons/{person_id}\", status_code=204)\ndef delete_person(person_id: int):\n matches = [person for person in persons if person.id == person_id]\n if matches:\n person = matches[0]\n persons.remove(person)\n save_db(persons)\n else:\n return JSONResponse(\n status_code=status.HTTP_404_NOT_FOUND,\n content={\"message\": \"Person not found\"}\n )\n","repo_name":"keys4words/fastApi","sub_path":"code/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"7908313462","text":"inFp, outFp = None, None\ninStr = \"\"\n\ninFp=open(\"c:/Windows/notepad.exe\", \"rb\")\noutFp=open(\"c:/temp/notepad.exe\", \"wb\") #temp폴더 만들어서 이 바이너리파일 복사\n\nwhile True :\n inStr = inFp.read()\n if not inStr :\n break\n outFp.write(inStr)\n\ninFp.close()\noutFp.close()\nprint(\"바이너리 파일 복사 완료!\")\n","repo_name":"dbelleK/study_python","sub_path":"Python_Pro2/base55.py","file_name":"base55.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"16464493208","text":"from fpdf import FPDF\nfrom datetime import datetime\n\nclass PDF(FPDF):\n def __init__(self, *args, data, **kwargs):\n self.WIDTH = 210\n self.HEIGHT = 297\n self.data = data\n super().__init__(*args, **kwargs)\n \n def header(self):\n self.set_font('Arial', 'I', 11)\n self.cell(self.WIDTH/2-10, 10, f\"Battery {self.data['sn']}\", 0, 0, 'L')\n self.cell(self.WIDTH/2-10, 10, f\"{datetime.today().replace(microsecond=0)}\", 0, 0, 'R')\n self.ln(10)\n \n def footer(self):\n self.set_y(-15)\n self.set_font('Arial', 'I', 8)\n self.set_text_color(128)\n self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C')\n self.image('ui/assets/trexo-logo.png', 10, self.HEIGHT - 20, 20)\n\n def add_summary_table(self):\n self.add_page()\n self._add_page_title('Battery Capacity Test Report')\n \n # Serial number and capacity text\n self.set_font('Arial', '', 12)\n self.ln()\n self.cell(self.WIDTH - 20, 10, f\"Battery Serial Number: {self.data['sn']}\", 0, align='C')\n self.ln()\n self.cell(self.WIDTH - 20, 10, f\"Battery Capacity: {self.data['cap']} mAh\", 0, align='C')\n self.ln(20)\n\n # Text\n self._set_font(False)\n self.cell(self.WIDTH - 20, 10, f\"Table 1 presents an overview of the charging and discharging process executed during the capacity test.\", 0, align='LR')\n self.ln(10)\n\n # Table caption\n self.set_font('Arial', 'I', 9)\n self.cell(self.WIDTH - 20, 10, f\"Table 1: Battery {self.data['sn']} charge/discharge process\", 0, align='C')\n self.ln()\n\n # Table Header\n self._set_font(True)\n headers = [\"\", \"Start Time\", \"End Time\", \"Duration\", \"Charge (mAh)\"]\n widths = [34, 44, 44, 34, 34]\n for i in range(len(headers)):\n if i == 0:\n self.cell(widths[i], 7, headers[i], 0, 0, 'C')\n else:\n self.cell(widths[i], 7, headers[i], 1, 0, 'C')\n self.ln()\n\n # Timedeltas\n cf_st = self.data['cf_st'].replace(microsecond=0)\n cf_et = self.data['cf_et'].replace(microsecond=0)\n df_st = self.data['df_st'].replace(microsecond=0)\n df_cp_t = self.data['df-cp_t'].replace(microsecond=0)\n cp_et = self.data['cp_et'].replace(microsecond=0)\n\n cf_duration = cf_et - cf_st\n df_duration = df_cp_t -df_st\n cp_duration = cp_et - df_cp_t\n total_duration = cp_et - cf_st\n\n total_charge = self.data['cf_c'] + self.data['df_c'] + self.data['cp_c']\n\n # Full Charge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Full Charge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(cf_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(cf_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(cf_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['cf_c']), 1, 0, 'C')\n self.ln() \n\n # Full Discharge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Full Discharge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(df_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(df_cp_t), 1, 0, 'C')\n self.cell(widths[3], 6, str(df_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['df_c']), 1, 0, 'C')\n self.ln() \n\n # Partial Charge Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Partial Charge\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(df_cp_t), 1, 0, 'C')\n self.cell(widths[2], 6, str(cp_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(cp_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(self.data['cp_c']), 1, 0, 'C')\n self.ln() \n\n # Total Row\n self._set_font(True)\n self.cell(widths[0], 6, \"Total\", 1, 0, 'C')\n self._set_font(False)\n self.cell(widths[1], 6, str(cf_st), 1, 0, 'C')\n self.cell(widths[2], 6, str(cp_et), 1, 0, 'C')\n self.cell(widths[3], 6, str(total_duration), 1, 0, 'C')\n self.cell(widths[4], 6, str(total_charge), 1, 0, 'C')\n self.ln() \n\n def _set_font(self, bold):\n self.set_font('Arial', 'B' if bold else '', 10)\n\n def add_plots(self, plots):\n self.add_page()\n self._add_page_title('Plots')\n self.image(plots[0], x=25, y=31, h=self.HEIGHT/2 - 15)\n self.image(plots[1], x=25, y=self.HEIGHT / 2 + 11, h=self.HEIGHT/2 - 15)\n\n def _add_page_title(self, txt):\n self.set_font('Arial', 'B', 12)\n self.cell(self.WIDTH - 20, 10, txt, 1, align='C')\n self.ln(10)","repo_name":"Zia-F/battery-recertification-station","sub_path":"ui/report_pdf.py","file_name":"report_pdf.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"42024897503","text":"import matplotlib.pyplot as plt\nimport math\n\n\ndef plot_images(images):\n fig = plt.figure(figsize=(15, 10))\n ncols = 5 if len(images) >= 5 else len(images)\n nrows = math.ceil(len(images) / ncols)\n for i in range(len(images)):\n fig.add_subplot(nrows, ncols, i+1)\n img = images[i]\n plt.imshow(img, cmap='gray')\n\n plt.show()\n\n\ndef moving_avg(curr_avg, val, samples_count):\n res = curr_avg\n res -= res / samples_count\n res += val / samples_count\n return res\n","repo_name":"r0busta/CarND-Advanced-Lane-Lines","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"1799084141","text":"import numpy as np\nfrom numpy.core.numeric import identity\n\ndef sigmoid(x): #시그모이드 함수\n return 1 / (1 + np.exp(-x))\n\ndef identity_function(x): #항등 함수\n return x\n\ndef init_network(): #신경망 가중치 및 편향값 구현\n network = {}\n network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])\n network['b1'] = np.array([0.1, 0.2, 0.3])\n network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])\n network['b2'] = np.array([0.1, 0.2])\n network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]])\n network['b3'] = np.array([0.1, 0.2])\n\n return network\n\ndef forward(network, x): #각 층의 신호전달 구현(순방향으로 전달됨 즉, 순전파)\n W1, W2, W3 = network['W1'], network['W2'], network['W3']\n b1, b2, b3 = network['b1'], network['b2'], network['b3']\n\n a1 = np.dot(x, W1) + b1\n z1 = sigmoid(a1)\n a2 = np.dot(z1, W2) + b2\n z2 = sigmoid(a2)\n a3 = np.dot(z2, W3) + b3\n y = identity_function(a3)\n\n return y\n\nnetwork = init_network()\nx = np.array([1.0, 0.5])\ny = forward(network, x)\nprint(y)","repo_name":"NewPlus/deepLearning_from_scratch_1_practice","sub_path":"밑바닥부터 시작하는 딥러닝 예제/cp02/cp2_5(각 층의 신호전달 구현 함수화).py","file_name":"cp2_5(각 층의 신호전달 구현 함수화).py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39871829487","text":"import collections\nimport string\nimport os\nimport math\nimport matplotlib.pylab as plt\n\ncase_sensitive = False\nwith open('sample.txt', 'r') as f:\n\toriginal_text = f.read()\nif case_sensitive:\n\talphabet = string.ascii_letters\n\ttext = original_text\nelse:\n\talphabet = string.ascii_lowercase\n\ttext = original_text.lower()\nalphabet_set = set(alphabet)\ncounts = dict(collections.Counter(c for c in text if c in alphabet_set))\n# for letter in alphabet:\n# \tprint(letter, counts[letter])\n\n#print(\"total:\", sum(counts.values()))\nmy_dict = {}\nfor key, value in sorted(counts.items(), key=lambda item: item[1], reverse=True):\n my_dict.update({key:value})\n\n#print(my_dict)\n\n# n = math.floor(len(my_dict.items())*0.2)\n# for i in range(1,n):\n# \tdel list(my_dict)[i]\n# print('hello')\n\n\n\nlists = sorted(my_dict.items()) # sorted by key, return a list of tuples\n\nx, y = zip(*lists) # unpack a list of pairs into two tuples\n\nplt.bar(x, y)\nplt.show()\n\n\n\n# infile=open('sample.txt', 'r')\n# lines=0\n# words=0\n# characters=0\n# for line in infile:\n# line = line.strip(os.linesep)\n# wordslist=line.split()\n# lines=lines+1\n# words=words+len(wordslist)\n# characters=characters+ len(line)\n# print(lines)\n# print(words)\n# print(characters)\n\n\n\n\n","repo_name":"syedsaadahmed/playing-with-pandas-numpy-matplotlib","sub_path":"Task_1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"26170822992","text":"# std\nimport time\nimport unicodedata\n\n# local\nfrom src.cron_jobs.utils.file import has_valid_file, read_json, write_json\nfrom src.cron_jobs.utils.fetch import (\n fetch_entity,\n fetch_json,\n load_entity,\n load_entity_from_db,\n)\nfrom src.db.connection import engine, Session, Base\nfrom src.db.models.country import Country\nfrom src.db.models.city import City\nfrom src.db.models.party_style import PartyStyle\nfrom src.db.models.party import Party\nfrom src.db.models.politician import Politician\nfrom src.db.models.parliament import Parliament\nfrom src.db.models.parliament_period import ParliamentPeriod\nfrom src.db.models.topic import Topic\nfrom src.db.models.committee import Committee\nfrom src.db.models.committee_has_topic import CommitteeHasTopic\nfrom src.db.models.fraction import Fraction\nfrom src.db.models.constituency import Constituency\nfrom src.db.models.electoral_list import ElectoralList\nfrom src.db.models.election_program import ElectionProgram\nfrom src.db.models.fraction_membership import FractionMembership\nfrom src.db.models.electoral_data import ElectoralData\nfrom src.db.models.candidacy_mandate import CandidacyMandate\nfrom src.db.models.committee_membership import CommitteeMembership\nfrom src.db.models.poll import Poll\nfrom src.db.models.poll_has_topic import PollHasTopic\nfrom src.db.models.field_related_link import FieldRelatedLink\nfrom src.db.models.vote import Vote\nfrom src.db.models.sidejob_organization import SidejobOrganization\nfrom src.db.models.sidejob_organization_has_topic import SidejobOrganizationHasTopic\nfrom src.db.models.sidejob import Sidejob\nfrom src.db.models.sidejob_has_mandate import SidejobHasMandate\nfrom src.db.models.sidejob_has_topic import SidejobHasTopic\nfrom src.db.models.position_statement import PositionStatement\nfrom src.db.models.cv import CV\nfrom src.db.models.career_path import CareerPath\nfrom src.db.models.position import Position\nfrom src.db.models.politician_weblink import PoliticianWeblink\nfrom src.db.models.poll_result_per_party import PollResultPerFraction\nfrom src.db.models.party_donation import PartyDonation\nfrom src.db.models.party_donation_organization import PartyDonationOrganization\nfrom src.cron_jobs.utils.partydonations import clean_donations\n\nimport src.db.models as models\nfrom src.cron_jobs.utils.vote_result import (\n generate_vote_results,\n get_total_votes_of_type,\n)\nfrom src.cron_jobs.utils.insert_and_update import insert_and_update\nfrom src.cron_jobs.utils.parser import (\n gen_statements,\n gen_positions,\n gen_party_styles_map,\n PERIOD_POSITION_TABLE,\n)\nfrom src.cron_jobs.utils.truncate_table import truncate_table\n\n# third-party\nfrom sqlalchemy.dialects.postgresql import insert\nfrom sqlalchemy import func\n\nsession = Session()\n\n\ndef populate_countries() -> None:\n api_countries = load_entity(\"countries\")\n countries = [\n {\n \"id\": api_country[\"id\"],\n \"entity_type\": api_country[\"entity_type\"],\n \"label\": api_country[\"label\"],\n \"api_url\": api_country[\"api_url\"],\n }\n for api_country in api_countries\n ]\n insert_and_update(Country, countries)\n\n\ndef populate_cities() -> None:\n api_cities = load_entity(\"cities\")\n cities = [\n {\n \"id\": api_city[\"id\"],\n \"entity_type\": api_city[\"entity_type\"],\n \"label\": api_city[\"label\"],\n \"api_url\": api_city[\"api_url\"],\n }\n for api_city in api_cities\n ]\n insert_and_update(City, cities)\n\n\ndef populate_party_styles() -> None:\n api_parties = load_entity(\"parties\")\n party_styles_map = gen_party_styles_map(api_parties)\n party_styles = []\n for api_party in api_parties:\n party_id: int = api_party[\"id\"]\n if party_id in party_styles_map:\n party_styles.append(party_styles_map[party_id])\n else:\n party_style = {\n \"id\": party_id,\n \"display_name\": api_party[\"label\"],\n \"foreground_color\": \"#FFFFFF\",\n \"background_color\": \"#333333\",\n \"border_color\": None,\n }\n party_styles.append(party_style)\n insert_and_update(PartyStyle, party_styles)\n\n\ndef populate_parties() -> None:\n api_parties = load_entity(\"parties\")\n parties = [\n {\n \"id\": api_party[\"id\"],\n \"entity_type\": api_party[\"entity_type\"],\n \"label\": api_party[\"label\"],\n \"api_url\": api_party[\"api_url\"],\n \"full_name\": api_party[\"full_name\"],\n \"short_name\": api_party[\"short_name\"],\n \"party_style_id\": api_party[\"id\"],\n }\n for api_party in api_parties\n ]\n insert_and_update(Party, parties)\n\n\ndef populate_politicians() -> None:\n api_politicians = load_entity(\"politicians\")\n begin_time = time.time()\n politicians = [\n {\n \"id\": api_politician[\"id\"],\n \"entity_type\": api_politician[\"entity_type\"],\n \"label\": api_politician[\"label\"],\n \"api_url\": api_politician[\"api_url\"],\n \"abgeordnetenwatch_url\": api_politician[\"abgeordnetenwatch_url\"],\n \"first_name\": api_politician[\"first_name\"],\n \"last_name\": api_politician[\"last_name\"],\n \"birth_name\": api_politician[\"birth_name\"],\n \"sex\": api_politician[\"sex\"],\n \"year_of_birth\": api_politician[\"year_of_birth\"],\n \"party_id\": api_politician[\"party\"][\"id\"]\n if api_politician[\"party\"]\n else None,\n \"party_past\": api_politician[\"party_past\"],\n \"deceased\": api_politician[\"deceased\"],\n \"deceased_date\": api_politician[\"deceased_date\"],\n \"education\": api_politician[\"education\"],\n \"residence\": api_politician[\"residence\"],\n \"occupation\": api_politician[\"occupation\"],\n \"statistic_questions\": api_politician[\"statistic_questions\"],\n \"statistic_questions_answered\": api_politician[\n \"statistic_questions_answered\"\n ],\n \"qid_wikidata\": api_politician[\"qid_wikidata\"],\n \"field_title\": api_politician[\"field_title\"],\n }\n for api_politician in api_politicians\n ]\n insert_and_update(Politician, politicians)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(api_politicians)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_parliaments() -> None:\n api_parliaments = load_entity(\"parliaments\")\n parliaments = [\n {\n \"id\": api_parliament[\"id\"],\n \"entity_type\": api_parliament[\"entity_type\"],\n \"label\": api_parliament[\"label\"],\n \"api_url\": api_parliament[\"api_url\"],\n \"abgeordnetenwatch_url\": api_parliament[\"abgeordnetenwatch_url\"],\n \"label_external_long\": api_parliament[\"label_external_long\"],\n }\n for api_parliament in api_parliaments\n ]\n insert_and_update(Parliament, parliaments)\n\n\ndef update_parliament_current_project_ids() -> None:\n api_parliaments = load_entity(\"parliaments\")\n parliaments = [\n {\n \"id\": parliament[\"id\"],\n \"current_project_id\": parliament[\"current_project\"][\"id\"]\n if parliament[\"current_project\"]\n else None,\n }\n for parliament in api_parliaments\n ]\n\n for parliament in parliaments:\n if parliament[\"current_project_id\"]:\n engine.execute(\n \"UPDATE {table} SET current_project_id = {current_project_id} WHERE id = {id}\".format(\n table=Parliament.__tablename__,\n current_project_id=parliament[\"current_project_id\"],\n id=parliament[\"id\"],\n )\n )\n\n\ndef populate_parliament_periods() -> None:\n api_parliament_periods = load_entity(\"parliament-periods\")\n parliament_periods = [\n {\n \"id\": api_parliament_period[\"id\"],\n \"entity_type\": api_parliament_period[\"entity_type\"],\n \"label\": api_parliament_period[\"label\"],\n \"api_url\": api_parliament_period[\"api_url\"],\n \"abgeordnetenwatch_url\": api_parliament_period[\"abgeordnetenwatch_url\"],\n \"type\": api_parliament_period[\"type\"],\n \"election_date\": api_parliament_period[\"election_date\"],\n \"start_date_period\": api_parliament_period[\"start_date_period\"],\n \"end_date_period\": api_parliament_period[\"end_date_period\"],\n \"parliament_id\": api_parliament_period[\"parliament\"][\"id\"]\n if api_parliament_period[\"parliament\"]\n else None,\n \"previous_period_id\": api_parliament_period[\"previous_period\"][\"id\"]\n if api_parliament_period[\"previous_period\"]\n else None,\n }\n for api_parliament_period in api_parliament_periods\n ]\n parliament_periods = sorted(parliament_periods, key=lambda p: p[\"id\"])\n insert_and_update(ParliamentPeriod, parliament_periods)\n update_parliament_current_project_ids()\n\n\ndef populate_topics() -> None:\n api_topics = load_entity(\"topics\")\n topics = [\n {\n \"id\": api_topic[\"id\"],\n \"entity_type\": api_topic[\"entity_type\"],\n \"label\": api_topic[\"label\"],\n \"api_url\": api_topic[\"api_url\"],\n \"abgeordnetenwatch_url\": api_topic[\"abgeordnetenwatch_url\"],\n \"description\": api_topic[\"description\"],\n \"parent_id\": api_topic[\"parent\"][0][\"id\"] if api_topic[\"parent\"] else None,\n }\n for api_topic in api_topics\n ]\n topics = sorted(topics, key=lambda t: t[\"id\"])\n insert_and_update(Topic, topics)\n\n\ndef populate_committees() -> None:\n api_committees = load_entity(\"committees\")\n committees = [\n {\n \"id\": api_committee[\"id\"],\n \"entity_type\": api_committee[\"entity_type\"],\n \"label\": api_committee[\"label\"],\n \"api_url\": api_committee[\"api_url\"],\n \"field_legislature_id\": api_committee[\"field_legislature\"][\"id\"],\n }\n for api_committee in api_committees\n ]\n insert_and_update(Committee, committees)\n\n\ndef populate_committee_has_topic() -> None:\n api_committees = load_entity(\"committees\")\n committee_topics = []\n for api_committee in api_committees:\n field_topics = api_committee[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n committee_topic = {\n \"committee_id\": api_committee[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n committee_topics.append(committee_topic)\n stmt = insert(CommitteeHasTopic).values(committee_topics)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_fractions() -> None:\n api_fractions = load_entity(\"fractions\")\n fractions = [\n {\n \"id\": api_fraction[\"id\"],\n \"entity_type\": api_fraction[\"entity_type\"],\n \"label\": api_fraction[\"label\"],\n \"api_url\": api_fraction[\"api_url\"],\n \"full_name\": api_fraction[\"full_name\"],\n \"short_name\": api_fraction[\"short_name\"],\n \"legislature_id\": api_fraction[\"legislature\"][\"id\"]\n if api_fraction[\"legislature\"]\n else None,\n }\n for api_fraction in api_fractions\n ]\n insert_and_update(Fraction, fractions)\n\n\ndef populate_constituencies() -> None:\n api_constituencies = load_entity(\"constituencies\")\n constituencies = [\n {\n \"id\": api_constituency[\"id\"],\n \"entity_type\": api_constituency[\"entity_type\"],\n \"label\": api_constituency[\"label\"],\n \"api_url\": api_constituency[\"api_url\"],\n \"name\": api_constituency[\"name\"],\n \"number\": api_constituency[\"number\"],\n }\n for api_constituency in api_constituencies\n ]\n insert_and_update(Constituency, constituencies)\n\n\ndef update_constituencies_with_parliament_period_id() -> None:\n begin_time = time.time()\n constituencies = []\n constituency_dict = {}\n\n api_constituencies = load_entity(\"constituencies\")\n for item in api_constituencies:\n constituency_dict[item[\"id\"]] = item\n\n json_data = read_json(\n \"src/data_scraper/json_data/constituency_id_parliament_period_id.json\"\n )\n\n for item in json_data:\n constituency_id = item[\"constituency_id\"]\n has_api_constituency = constituency_dict.get(constituency_id)\n\n if has_api_constituency:\n api_constituency = constituency_dict[constituency_id]\n constituency = {\n \"id\": api_constituency[\"id\"],\n \"entity_type\": api_constituency[\"entity_type\"],\n \"label\": api_constituency[\"label\"],\n \"api_url\": api_constituency[\"api_url\"],\n \"name\": api_constituency[\"name\"],\n \"number\": api_constituency[\"number\"],\n # Add parliament_period_id from json\n \"parliament_period_id\": item[\"parliament_period_id\"],\n }\n\n constituencies.append(constituency)\n insert_and_update(Constituency, constituencies)\n end_time = time.time()\n print(f\"Total runtime to store {len(json_data)} data is {end_time - begin_time}\")\n\n\ndef populate_electoral_lists() -> None:\n api_electoral_lists = load_entity(\"electoral-lists\")\n electoral_lists = [\n {\n \"id\": api_electoral_list[\"id\"],\n \"entity_type\": api_electoral_list[\"entity_type\"],\n \"label\": api_electoral_list[\"label\"],\n \"api_url\": api_electoral_list[\"api_url\"],\n \"name\": api_electoral_list[\"name\"],\n \"parliament_period_id\": api_electoral_list[\"parliament_period\"][\"id\"]\n if api_electoral_list[\"parliament_period\"]\n else None,\n }\n for api_electoral_list in api_electoral_lists\n ]\n insert_and_update(ElectoralList, electoral_lists)\n\n\ndef populate_election_programs() -> None:\n api_election_programs = load_entity(\"election-program\")\n election_programs = [\n {\n \"id\": api_election_program[\"id\"],\n \"entity_type\": api_election_program[\"entity_type\"],\n \"label\": api_election_program[\"label\"],\n \"api_url\": api_election_program[\"api_url\"],\n \"parliament_period_id\": api_election_program[\"parliament_period\"][\"id\"]\n if api_election_program[\"parliament_period\"]\n else None,\n \"party_id\": api_election_program[\"party\"][\"id\"]\n if api_election_program[\"party\"]\n else None,\n \"link_uri\": api_election_program[\"link\"][0][\"uri\"],\n \"link_title\": api_election_program[\"link\"][0][\"title\"],\n \"link_option\": api_election_program[\"link\"][0][\"option\"]\n if api_election_program[\"link\"][0].get(\"option\")\n else None,\n \"file\": api_election_program[\"file\"],\n }\n for api_election_program in api_election_programs\n ]\n insert_and_update(ElectionProgram, election_programs)\n\n\ndef populate_fraction_memberships() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n fraction_memberships = []\n for api_candidacies_mandate in api_candidacies_mandates:\n fraction_membership = api_candidacies_mandate.get(\"fraction_membership\")\n if fraction_membership:\n membership = fraction_membership[0]\n new_fraction_membership = {\n \"id\": membership[\"id\"],\n \"entity_type\": membership[\"entity_type\"],\n \"label\": membership[\"label\"],\n \"fraction_id\": membership[\"fraction\"][\"id\"],\n \"valid_from\": membership[\"valid_from\"],\n \"valid_until\": membership[\"valid_until\"],\n }\n fraction_memberships.append(new_fraction_membership)\n insert_and_update(FractionMembership, fraction_memberships)\n\n\ndef populate_electoral_data() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n electoral_data_list = []\n for api_candidacies_mandate in api_candidacies_mandates:\n electoral_data = api_candidacies_mandate[\"electoral_data\"]\n if electoral_data:\n new_electoral_data = {\n \"id\": electoral_data[\"id\"],\n \"entity_type\": electoral_data[\"entity_type\"],\n \"label\": electoral_data[\"label\"],\n \"electoral_list_id\": electoral_data[\"electoral_list\"][\"id\"]\n if electoral_data[\"electoral_list\"]\n else None,\n \"list_position\": electoral_data[\"list_position\"],\n \"constituency_id\": electoral_data[\"constituency\"][\"id\"]\n if electoral_data[\"constituency\"]\n else None,\n \"constituency_result\": electoral_data[\"constituency_result\"],\n \"constituency_result_count\": electoral_data[\n \"constituency_result_count\"\n ],\n \"mandate_won\": electoral_data[\"mandate_won\"],\n }\n electoral_data_list.append(new_electoral_data)\n insert_and_update(ElectoralData, electoral_data_list)\n\n\ndef populate_candidacies_mandates() -> None:\n api_candidacies_mandates = load_entity(\"candidacies-mandates\")\n begin_time = time.time()\n candidacies_mandates = [\n {\n \"id\": api_candidacies_mandate[\"id\"],\n \"entity_type\": api_candidacies_mandate[\"entity_type\"],\n \"label\": api_candidacies_mandate[\"label\"],\n \"api_url\": api_candidacies_mandate[\"api_url\"],\n \"id_external_administration\": api_candidacies_mandate[\n \"id_external_administration\"\n ],\n \"id_external_administration_description\": api_candidacies_mandate[\n \"id_external_administration_description\"\n ],\n \"type\": api_candidacies_mandate[\"type\"],\n \"parliament_period_id\": api_candidacies_mandate[\"parliament_period\"][\"id\"]\n if api_candidacies_mandate[\"parliament_period\"]\n else None,\n \"politician_id\": api_candidacies_mandate[\"politician\"][\"id\"]\n if api_candidacies_mandate[\"politician\"]\n else None,\n # Some dict don't include party itsself\n \"party_id\": api_candidacies_mandate[\"party\"][\"id\"]\n if api_candidacies_mandate.get(\"party\")\n else None,\n \"start_date\": api_candidacies_mandate[\"start_date\"],\n \"end_date\": api_candidacies_mandate[\"end_date\"],\n \"info\": api_candidacies_mandate[\"info\"],\n \"electoral_data_id\": api_candidacies_mandate[\"electoral_data\"][\"id\"]\n if api_candidacies_mandate[\"electoral_data\"]\n else None,\n # Some dict don't include fraction_membership itsself\n \"fraction_membership_id\": api_candidacies_mandate[\"fraction_membership\"][0][\n \"id\"\n ]\n if api_candidacies_mandate.get(\"fraction_membership\")\n else None,\n }\n for api_candidacies_mandate in api_candidacies_mandates\n ]\n insert_and_update(CandidacyMandate, candidacies_mandates)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(candidacies_mandates)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_committee_memberships() -> None:\n api_committees = load_entity(\"committees\")\n committee_ids = set([api_committee[\"id\"] for api_committee in api_committees])\n api_committee_memberships = load_entity(\"committee-memberships\")\n begin_time = time.time()\n committee_memberships = []\n for api_committee_membership in api_committee_memberships:\n committee_id = (\n api_committee_membership[\"committee\"][\"id\"]\n if api_committee_membership[\"committee\"]\n else None\n )\n if committee_id in committee_ids:\n new_membership = {\n \"id\": api_committee_membership[\"id\"],\n \"entity_type\": api_committee_membership[\"entity_type\"],\n \"label\": api_committee_membership[\"label\"],\n \"api_url\": api_committee_membership[\"api_url\"],\n \"committee_id\": api_committee_membership[\"committee\"][\"id\"]\n if api_committee_membership[\"committee\"]\n else None,\n \"candidacy_mandate_id\": api_committee_membership[\"candidacy_mandate\"][\n \"id\"\n ]\n if api_committee_membership[\"candidacy_mandate\"]\n else None,\n \"committee_role\": api_committee_membership[\"committee_role\"],\n }\n committee_memberships.append(new_membership)\n insert_and_update(CommitteeMembership, committee_memberships)\n end_time = time.time()\n print(\n f\"Total runtime to store {len(committee_memberships)} data is {end_time - begin_time}\"\n )\n\n\ndef populate_polls() -> None:\n api_polls = load_entity(\"polls\")\n polls = [\n {\n \"id\": api_polls[\"id\"],\n \"entity_type\": api_polls[\"entity_type\"],\n \"label\": api_polls[\"label\"],\n \"api_url\": api_polls[\"api_url\"],\n \"field_committees_id\": api_polls[\"field_committees\"][0][\"id\"]\n if api_polls[\"field_committees\"]\n else None,\n \"field_intro\": api_polls[\"field_intro\"]\n if api_polls[\"field_intro\"]\n else None,\n \"field_legislature_id\": api_polls[\"field_legislature\"][\"id\"]\n if api_polls[\"field_legislature\"]\n else None,\n \"field_poll_date\": api_polls[\"field_poll_date\"],\n }\n for api_polls in api_polls\n ]\n insert_and_update(Poll, polls)\n\n\ndef populate_poll_has_topic() -> None:\n api_polls = load_entity(\"polls\")\n polls_topics = []\n for api_poll in api_polls:\n field_topics = api_poll[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n poll_topic = {\n \"poll_id\": api_poll[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n polls_topics.append(poll_topic)\n session = Session()\n stmt = insert(PollHasTopic).values(polls_topics)\n stmt = stmt.on_conflict_do_nothing()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_field_related_link() -> None:\n api_polls = load_entity(\"polls\")\n poll_related_links = []\n for api_poll in api_polls:\n poll_id = api_poll[\"id\"]\n field_related_links = api_poll[\"field_related_links\"]\n if field_related_links:\n for field_related_link in field_related_links:\n poll_related_link = {\n \"poll_id\": poll_id,\n \"uri\": field_related_link[\"uri\"],\n \"title\": field_related_link[\"title\"],\n }\n poll_related_links.append(poll_related_link)\n insert_and_update(FieldRelatedLink, poll_related_links)\n\n\ndef populate_votes() -> None:\n api_polls = load_entity(\"polls\")\n poll_ids = set([api_poll[\"id\"] for api_poll in api_polls])\n api_votes = load_entity(\"votes\")\n begin_time = time.time()\n votes = []\n for api_vote in api_votes:\n poll_id = api_vote[\"poll\"][\"id\"] if api_vote[\"poll\"] else None\n if poll_id in poll_ids:\n vote = {\n \"id\": api_vote[\"id\"],\n \"entity_type\": api_vote[\"entity_type\"],\n \"label\": api_vote[\"label\"],\n \"api_url\": api_vote[\"api_url\"],\n \"mandate_id\": api_vote[\"mandate\"][\"id\"]\n if api_vote[\"mandate\"]\n else None,\n \"fraction_id\": api_vote[\"fraction\"][\"id\"]\n if api_vote[\"fraction\"]\n else None,\n \"poll_id\": poll_id,\n \"vote\": api_vote[\"vote\"],\n \"reason_no_show\": api_vote[\"reason_no_show\"],\n \"reason_no_show_other\": api_vote[\"reason_no_show_other\"],\n }\n votes.append(vote)\n insert_and_update(Vote, votes)\n end_time = time.time()\n print(f\"Total runtime to store {len(api_votes)} data is {end_time - begin_time}\")\n\n\n# id=1 to id=281 are missing\ndef complement_missing_votes():\n api_polls = load_entity(\"polls\")\n poll_ids = set([api_poll[\"id\"] for api_poll in api_polls])\n api_votes = list(\n (\n fetch_json(\n \"https://www.abgeordnetenwatch.de/api/v2/votes?id[lt]=282&range_end=1000\"\n )[\"data\"]\n )\n )\n votes = []\n for api_vote in api_votes:\n poll_id = api_vote[\"poll\"][\"id\"] if api_vote[\"poll\"] else None\n if poll_id in poll_ids:\n vote = {\n \"id\": api_vote[\"id\"],\n \"entity_type\": api_vote[\"entity_type\"],\n \"label\": api_vote[\"label\"],\n \"api_url\": api_vote[\"api_url\"],\n \"mandate_id\": api_vote[\"mandate\"][\"id\"]\n if api_vote[\"mandate\"]\n else None,\n \"fraction_id\": api_vote[\"fraction\"][\"id\"]\n if api_vote[\"fraction\"]\n else None,\n \"poll_id\": poll_id,\n \"vote\": api_vote[\"vote\"],\n \"reason_no_show\": api_vote[\"reason_no_show\"],\n \"reason_no_show_other\": api_vote[\"reason_no_show_other\"],\n }\n votes.append(vote)\n insert_and_update(Vote, votes)\n\n\ndef populate_sidejob_organizations() -> None:\n api_sidejob_organizations = load_entity(\"sidejob-organizations\")\n sidejob_organizations = [\n {\n \"id\": api_sidejob_organization[\"id\"],\n \"entity_type\": api_sidejob_organization[\"entity_type\"],\n \"label\": api_sidejob_organization[\"label\"],\n \"api_url\": api_sidejob_organization[\"api_url\"],\n \"field_city_id\": api_sidejob_organization[\"field_city\"][\"id\"]\n if api_sidejob_organization[\"field_city\"]\n else None,\n \"field_country_id\": api_sidejob_organization[\"field_country\"][\"id\"]\n if api_sidejob_organization[\"field_country\"]\n else None,\n }\n for api_sidejob_organization in api_sidejob_organizations\n ]\n insert_and_update(SidejobOrganization, sidejob_organizations)\n\n\ndef populate_sidejob_organization_has_topic() -> None:\n api_sidejob_organizations = load_entity(\"sidejob-organizations\")\n organization_topics = []\n for api_sidejob_organization in api_sidejob_organizations:\n field_topics = api_sidejob_organization[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n organization_topic = {\n \"sidejob_organization_id\": api_sidejob_organization[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n organization_topics.append(organization_topic)\n session = Session()\n stmt = insert(SidejobOrganizationHasTopic).values(organization_topics)\n stmt = stmt.on_conflict_do_nothing()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_sidejobs() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejobs = [\n {\n \"id\": api_sidejob[\"id\"],\n \"entity_type\": api_sidejob[\"entity_type\"],\n \"label\": api_sidejob[\"label\"],\n \"api_url\": api_sidejob[\"api_url\"],\n \"job_title_extra\": api_sidejob[\"job_title_extra\"],\n \"additional_information\": api_sidejob[\"additional_information\"],\n \"category\": api_sidejob[\"category\"],\n \"income_level\": api_sidejob[\"income_level\"],\n \"interval\": api_sidejob[\"interval\"],\n \"data_change_date\": api_sidejob[\"data_change_date\"],\n \"created\": api_sidejob[\"created\"],\n \"sidejob_organization_id\": api_sidejob[\"sidejob_organization\"][\"id\"]\n if api_sidejob[\"sidejob_organization\"]\n else None,\n \"field_city_id\": api_sidejob[\"field_city\"][\"id\"]\n if api_sidejob[\"field_city\"]\n else None,\n \"field_country_id\": api_sidejob[\"field_country\"][\"id\"]\n if api_sidejob[\"field_country\"]\n else None,\n }\n for api_sidejob in api_sidejobs\n ]\n insert_and_update(Sidejob, sidejobs)\n\n\ndef populate_sidejob_has_mandate() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejob_mandates = []\n for api_sidejob in api_sidejobs:\n mandates = api_sidejob[\"mandates\"]\n if mandates:\n for mandate in mandates:\n sidejob_mandate = {\n \"sidejob_id\": api_sidejob[\"id\"],\n \"candidacy_mandate_id\": mandate[\"id\"],\n }\n sidejob_mandates.append(sidejob_mandate)\n stmt = insert(SidejobHasMandate).values(sidejob_mandates)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_sidejob_has_topic() -> None:\n api_sidejobs = load_entity(\"sidejobs\")\n sidejob_topics = []\n for api_sidejob in api_sidejobs:\n field_topics = api_sidejob[\"field_topics\"]\n if field_topics:\n for topic in field_topics:\n sidejob_topic = {\n \"sidejob_id\": api_sidejob[\"id\"],\n \"topic_id\": topic[\"id\"],\n }\n sidejob_topics.append(sidejob_topic)\n stmt = insert(SidejobHasTopic).values(sidejob_topics)\n stmt = stmt.on_conflict_do_nothing()\n session = Session()\n session.execute(stmt)\n session.commit()\n session.close()\n\n\ndef populate_position_statements() -> None:\n position_statements = []\n for period_id in PERIOD_POSITION_TABLE:\n statements = gen_statements(period_id)\n position_statements += statements\n insert_and_update(PositionStatement, position_statements)\n\n\ndef populate_positions() -> None:\n positions_list = []\n for period_id in PERIOD_POSITION_TABLE:\n positions = gen_positions(period_id)\n positions_list += positions\n insert_and_update(Position, positions_list)\n\n\ndef populate_cvs_and_career_paths() -> None:\n cv_connection = read_json(\"src/cron_jobs/data/220516_connections.json\")\n cv_table = load_entity_from_db(models.CV)\n cv_table_ids = [cv.politician_id for cv in cv_table]\n last_cv_id = 755\n cvs = []\n for politician in cv_connection:\n politician_id = politician[\"ID\"]\n cv_data = read_json(f\"src/cron_jobs/data/data_politicians/{id}.json\")\n if id in cv_table_ids:\n for cv in cv_table:\n if cv.politician_id == politician_id:\n cv = {\n \"id\": cv.id,\n \"politician_id\": politician_id,\n \"raw_text\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"Raw\"]\n ),\n \"short_description\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"ShortDescription\"]\n ),\n }\n cvs.append(cv)\n else:\n cv = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"raw_text\": unicodedata.normalize(\"NFKD\", cv_data[\"Biography\"][\"Raw\"]),\n \"short_description\": unicodedata.normalize(\n \"NFKD\", cv_data[\"Biography\"][\"ShortDescription\"]\n ),\n }\n cvs.append(cv)\n last_cv_id += 1\n write_json(\"src/cron_jobs/data/cvs_new.json\", cvs)\n # insert_and_update(CV, cvs)\n\n\ndef insert_weblinks() -> None:\n cv_connection = read_json(\"src/cron_jobs/data/220516_connections.json\")\n weblink_table = load_entity_from_db(models.PoliticianWeblink)\n cv_table_ids = [cv.politician_id for cv in weblink_table]\n last_cv_id = 1\n weblinks = []\n for politician in cv_connection:\n politician_id = politician[\"ID\"]\n cv_data = read_json(f\"src/cron_jobs/data/data_politicians/{id}.json\")\n if id not in cv_table_ids:\n bundestag_link = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"link\": cv_data[\"Href\"],\n }\n weblinks.append(bundestag_link)\n last_cv_id += 1\n if \"Links\" in cv_data:\n for link in cv_data[\"Links\"]:\n new_link = {\n \"id\": last_cv_id,\n \"politician_id\": politician_id,\n \"link\": link,\n }\n weblinks.append(new_link)\n last_cv_id += 1\n else:\n print(\"No links\")\n insert_and_update(PoliticianWeblink, weblinks)\n\n\ndef populate_weblinks() -> None:\n truncate_table(\"politician_weblink\")\n weblink_data = read_json(\"src/data_scraper/json_data/weblinks.json\")\n weblinks = []\n for item in weblink_data:\n links = item[\"weblink\"]\n for link in links:\n weblink = {\n \"politician_id\": item[\"politician_id\"],\n \"link\": link,\n }\n weblinks.append(weblink)\n insert_and_update(PoliticianWeblink, weblinks)\n\n\ndef populate_vote_result() -> None:\n vote_results = generate_vote_results(session)\n insert_and_update(models.VoteResult, vote_results)\n\n\ndef populate_poll_results_per_fraction():\n print(\"Starting Process to populate poll_result_per_fraction table\")\n begin_time = time.time()\n\n polls = session.query(Poll.id).all()\n poll_results = session.query(PollResultPerFraction.poll_id).all()\n poll_results_ids = [poll_results_id[0] for poll_results_id in poll_results]\n poll_ids = [poll_id[0] for poll_id in polls]\n\n poll_results_per_fraction = []\n for poll_id in poll_ids:\n if poll_id not in poll_results_ids:\n print(f\" Poll_id {poll_id} is NOT in here\")\n print(f\" Creating items when poll_id is {poll_id}\")\n fractions = (\n session.query(Vote.fraction_id)\n .filter(Vote.poll_id == poll_id)\n .distinct()\n .all()\n )\n fraction_ids = [fraction_id[0] for fraction_id in fractions]\n for fraction_id in fraction_ids:\n total_yes = get_total_votes_of_type(\n \"yes\", poll_id, fraction_id, session\n )\n total_no = get_total_votes_of_type(\"no\", poll_id, fraction_id, session)\n total_abstain = get_total_votes_of_type(\n \"abstain\", poll_id, fraction_id, session\n )\n total_no_show = get_total_votes_of_type(\n \"no_show\", poll_id, fraction_id, session\n )\n poll_result_id = int(str(poll_id) + str(fraction_id))\n poll_result = {\n \"id\": poll_result_id,\n \"entity_type\": \"poll_result\",\n \"poll_id\": poll_id,\n \"fraction_id\": fraction_id,\n \"total_yes\": total_yes,\n \"total_no\": total_no,\n \"total_abstain\": total_abstain,\n \"total_no_show\": total_no_show,\n }\n print(f\" -> Item of fraction_id {fraction_id} created\")\n poll_results_per_fraction.append(poll_result)\n\n print(\n f\"Inserting {len(poll_results_per_fraction)} items into poll_results_per_fraction table\"\n )\n insert_and_update(models.PollResultPerFraction, poll_results_per_fraction)\n\n end_time = time.time()\n print(\n f\"Total runtime to store {len(poll_results_per_fraction)} data is {end_time - begin_time}\"\n )\n\n\ndef update_politicians_occupation() -> None:\n begin_time = time.time()\n session = Session()\n file_path = \"src/cron_jobs/data/politicians.json\"\n \"\"\"has_file = has_valid_file(file_path)\n if not has_file:\n politicians_data = fetch_entity(\"politicians\")\n write_json(file_path, politicians_data) \"\"\"\n politicians = read_json(file_path)\n for politician in politicians:\n id = politician[\"id\"]\n occupation = politician[\"occupation\"]\n if occupation:\n session.query(Politician).filter(Politician.id == id).update(\n {Politician.occupation: occupation}\n )\n session.commit()\n end_time = time.time()\n print(f\"Total runtime to update data is {end_time - begin_time}\")\n\n\ndef populate_party_donations() -> None:\n # TODO: confirm default file name and location from scrapy branch\n party_donations = load_entity(\"party_donations\")\n\n # TODO: hook this function up to db, currently it requires additional local data\n clean_donations(party_donations)\n\n # TODO: move this into the clean donations function, the goal was to keep one JSON\n # with all of the data together to make it easier to work with manually, but that\n # means it has extra keys we don't need for insertion meaning we need to loop through\n # an extra time to remove it\n donations_to_append = []\n\n for donation in party_donations:\n donation_to_append = {\n \"id\": donation[\"id\"],\n \"party_id\": donation[\"party_id\"],\n \"amount\": donation[\"amount\"],\n \"date\": donation[\"date\"],\n \"party_donation_organization_id\": donation[\n \"party_donation_organization_id\"\n ],\n }\n\n donations_to_append.append(donation_to_append)\n\n insert_and_update(PartyDonation, donations_to_append)\n\n\ndef populate_party_donation_organizations() -> None:\n clean_api_party_donation_organizations = load_entity(\"clean_donors\")\n # clean_api_party_donation_organizations = clean_donor(\n # api_party_donation_organizations\n # )\n id = 1\n party_donation_organizations = []\n for api_party_donation_organization in clean_api_party_donation_organizations:\n fail = True\n for item in party_donation_organizations:\n print(item)\n if (\n item[\"donor_name\"] == api_party_donation_organization[\"donor_name\"]\n and api_party_donation_organization[\"donor_address\"]\n == item[\"donor_address\"]\n ):\n fail = False\n if fail:\n party_donation_organization = {\n \"id\": id,\n \"donor_name\": api_party_donation_organization[\"donor_name\"],\n \"donor_address\": api_party_donation_organization[\"donor_address\"],\n \"donor_zip\": api_party_donation_organization[\"donor_zip\"],\n \"donor_city\": api_party_donation_organization[\"donor_city\"],\n \"donor_foreign\": api_party_donation_organization[\"donor_foreign\"],\n }\n party_donation_organizations.append(party_donation_organization)\n id = id + 1\n insert_and_update(PartyDonationOrganization, party_donation_organizations)\n\n\nif __name__ == \"__main__\":\n Base.metadata.create_all(engine)\n # add specific populate function to run from command line here\n","repo_name":"FaceTheFacts/backend","sub_path":"src/cron_jobs/crud_db.py","file_name":"crud_db.py","file_ext":"py","file_size_in_byte":39315,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"30308363186","text":"from pydantic import BaseSettings\nimport os\nfrom pathlib import Path\n\npath_to_dotenv = Path(os.path.dirname(__file__)) / \"..\" / \".env\"\n\n\nclass Settings(BaseSettings):\n \"\"\"\n Set the Environment Variables Automatically using Pydantic\n \"\"\"\n PYTHON_RUNNING_IN_CONTAINER: bool = False\n USE_REMOTE_WEBDRIVER: bool = False\n MAX_ITEMS_PER_SCRAPE: int = 20\n BATCH_SIZE: int = 5\n DEBUG_MODE: bool = False\n\n class Config:\n env_file = path_to_dotenv\n env_file_encoding = 'utf-8'\n\n\nSETTINGS = Settings()\n","repo_name":"dStern98/Redbubble_Scraper","sub_path":"redbubble_scrape/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"19194507052","text":"import requests\nimport time\nimport random\nfrom faker import Faker\nimport time\nfrom time import strftime, localtime\n\n\n\n# Base URL for the Card API\nurl = \"http://localhost:8080\"\n\n# Endpoint paths\nendpoints_normal = [ \n [\"/cards/\", \"GET\"], \n [\"/cards/{id}\", \"GET\"], \n [\"/cards/\", \"POST\"],\n [\"/cards/{id}\", \"PUT\"], \n [\"/cards/{id}\", \"DELETE\"]\n ]\n\nendpoints_anomaly = [ \n [\"/cards/error?count={count}&type=random\", \"GET\"], \n]\n \n\nWINDOW_TIME = 600 # n seconds \n\nfake = Faker()\n\ndef get_dummy_card():\n # generate random expiration date\n exp_month = random.randint(1, 12)\n exp_year = random.randint(2023, 2030)\n exp_date = f\"{exp_month}/{exp_year}\"\n\n id = random.randint(1, 100)\n data = {\n \"id\": id,\n \"cardNumber\" : fake.credit_card_number(),\n \"expirationDate\" : exp_date,\n \"cardHolderName\" : fake.name(),\n \"userId\": id\n }\n return data\n\ndef call_card_service(endpoint):\n\n # Make the HTTP request and print the response\n method = endpoint[1]\n path = endpoint[0]\n\n response = None\n\n if endpoint in endpoints_anomaly:\n if \"{count}\" in path:\n full_url = url + path.replace(\"{count}\", str(random.randint(1, 5)))\n else:\n full_url = url + path\n else:\n data = get_dummy_card()\n\n if \"{id}\" in path:\n full_url = url + path.replace(\"{id}\", str(random.randint(1, 100)))\n else:\n full_url = url + path\n\n\n if method == \"GET\":\n response = requests.get(full_url, timeout=20)\n elif method == \"PUT\":\n response = requests.put(full_url, json=data, timeout=20)\n elif method == \"POST\":\n response = requests.post(full_url, json=data, timeout=20)\n elif method == \"DELETE\":\n response = requests.delete(full_url, timeout=20)\n\n print(f\"Request: {method} {full_url} - Response status code: {response.status_code}\")\n\n# Generate normal window logs for 10 mins\ndef generate_normal_window_logs():\n # print(\"=======================Generating normal logs ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n\n print(f\"Normal window: {strftime('%l:%M%p %Z on %b %d, %Y', localtime(start_time))} {strftime('%l:%M%p %Z on %b %d, %Y', localtime(end_time))}\")\n\n while time.time() < end_time:\n # Call normal endpoint 90% of the time and anomlous 10% of the time \n if random.random() < 0.9:\n endpoint = random.choice(endpoints_normal)\n else:\n endpoint = random.choice(endpoints_anomaly)\n time.sleep(2) # extra 2 secs of sleep for anomalous as they generate a lot of data\n \n call_card_service(endpoint) \n time.sleep(1)\n\n print(\"Finished executing normal window for 10 minutes.\")\n\n# Generate anomalous window logs for 10 mins\ndef generate_anomalous_window_logs():\n print(\"=======================Generating anomalous logs ==================================\") \n if random.random() < 0.5:\n generate_more_errors()\n else:\n generate_lots_of_messages()\n\n\ndef generate_more_errors():\n print(\"=======================Generating logs with 90% error and 10% info ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n\n while time.time() < end_time:\n\n # Call anomalous endpoint 90% of the time and normal 10% of the time\n if random.random() < 0.9:\n endpoint = random.choice(endpoints_anomaly)\n time.sleep(2) # extra 2 secs of sleep for anomalous as they generate a lot of data\n else:\n endpoint = random.choice(endpoints_normal)\n \n call_card_service(endpoint) \n time.sleep(1)\n\n print(\"Finished executing anomalous window for 10 minutes - 90% ERROR\") \n\ndef generate_lots_of_messages():\n # print(\"=======================Generating lots of INFO logs ==================================\")\n\n start_time = time.time()\n end_time = start_time + WINDOW_TIME # 600 seconds = 10 minutes\n \n print(f\"Normal window: {strftime('%l:%M%p %Z on %b %d, %Y', localtime(start_time))} {strftime('%l:%M%p %Z on %b %d, %Y', localtime(end_time))}\")\n\n while time.time() < end_time:\n # Call normal endpoint all the time \n endpoint = random.choice(endpoints_normal)\n call_card_service(endpoint) \n\n print(\"Finished executing anomalous window for 10 minutes - 100% INFO\")\n\n# Define the start time\nstart_time = time.time()\n\n# Run the program for HOURS_TO_RUN hours\nHOURS_TO_RUN = 2\nwhile (time.time() - start_time) < (HOURS_TO_RUN * 60 * 60):\n if random.random() < 0.9:\n generate_normal_window_logs()\n else:\n generate_anomalous_window_logs()\n time.sleep(3)\n\nprint(\"Program has finished running for 2 hours\", time.time())\n","repo_name":"AnjaliJain-17/Anomaly-Detection","sub_path":"log-generator/log_generation_smart.py","file_name":"log_generation_smart.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"75093034083","text":"from bs4 import BeautifulSoup\nimport requests\n\nresponse = requests.get(\"https://news.ycombinator.com/\")\n\ncontent = response.text\nsoup = BeautifulSoup(content, \"html.parser\")\n#print(soup.title)\n\ntopic = soup.find_all(class_=\"titlelink\")\n#print(topic.get_text())\ntopic_name = []\ntopic_link = []\nfor t in topic:\n name = t.get_text()\n topic_name.append(name)\n link = t.get(\"href\")\n topic_link.append(link)\n\n#\n\ntopic_scores = [int(score.get_text().split(\" \")[0]) for score in soup.find_all(class_=\"score\")]\n#print(topic_scores)\n\nmax_score_index = topic_scores.index(max(topic_scores))\nprint(topic_name[max_score_index])\nprint((topic_link[max_score_index]))\nprint(topic_scores[max_score_index])\n","repo_name":"mehtavandit/100-days-of-code","sub_path":"day 045/Web Scrapping of Hacker News/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"6983814346","text":"import sys, bisect\n\ninput = sys.stdin.readline\n\ndef binary_search(idx):\n if not dp:\n dp.append(arr[idx])\n else:\n if arr[idx] > dp[-1]:\n dp.append(arr[idx])\n index[idx] = len(dp)-1\n else:\n insert = bisect.bisect_left(dp,arr[idx])\n dp[insert] = arr[idx]\n index[idx] = insert\n\n\nif __name__ == '__main__':\n n = int(input())\n arr = list(map(int, input().split()))\n dp = []\n index = [0] * n\n index[0] = 0\n for i in range(n):\n binary_search(i)\n max_len = len(dp)\n print(max_len)\n # print(index)\n result = []\n max_len-=1\n for i in range(n-1, -1, -1):\n if index[i] == max_len:\n max_len -= 1\n result.append(arr[i])\n print(*result[::-1])\n\n","repo_name":"jeno8522/Coding-Test-Study","sub_path":"2023(싸피 코테스터디)/6월/4주차/BOJ_G4_14002_가장긴증가하는부분수열4.py","file_name":"BOJ_G4_14002_가장긴증가하는부분수열4.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30699225392","text":"#!/usr/bin/python\nimport sys\nimport re\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import MultipleLocator\nimport numpy as np\nimport math\n\nfile = open('data', 'r')\nnano = []\npage = []\nstr_re = re.compile('\\d+\\.\\d+')\nLines = file.readlines()\nfor line in Lines:\n for s in line.split():\n match = re.search(str_re, s)\n if match:\n nano.append(s)\n if s.isdigit(): \n page.append(s)\n\na = np.arange(len(page))\nx = 2**a\nnano = [float(s) for s in nano]\n\npage = np.array(page)\n\nplt.plot(a, nano, marker='o', color='blue')\nx = [math.log2(int(e)) for e in page]\nprint(page)\nprint(nano)\ny_major_locator=MultipleLocator(2.0)\nax=plt.gca()\nax.yaxis.set_major_locator(y_major_locator)\nplt.ylim(0,25)\nplt.plot(page, nano, marker='o', color='blue')\nplt.xlabel('Number of pages')\nplt.ylabel('Time per Access(ns)')\nplt.xticks(x, page)\nplt.title(\"TLB size measurement (macOS X)\")\nplt.savefig('tlb.png', dpi=227)\nplt.show()\n","repo_name":"MarekZhang/OSTEP-Homework","sub_path":"C19-TLBs/figure.py","file_name":"figure.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"52"}
+{"seq_id":"31576617309","text":"from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401\nfrom oci.decorators import init_model_state_from_kwargs\n\n\n@init_model_state_from_kwargs\nclass DynamicSelectionKey(object):\n \"\"\"\n Base policy for defining how to match the context variable in an incoming request with selection keys when dynamically routing and dynamically authenticating requests.\n \"\"\"\n\n #: A constant which can be used with the type property of a DynamicSelectionKey.\n #: This constant has a value of \"ANY_OF\"\n TYPE_ANY_OF = \"ANY_OF\"\n\n #: A constant which can be used with the type property of a DynamicSelectionKey.\n #: This constant has a value of \"WILDCARD\"\n TYPE_WILDCARD = \"WILDCARD\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initializes a new DynamicSelectionKey object with values from keyword arguments. This class has the following subclasses and if you are using this class as input\n to a service operations then you should favor using a subclass over the base class:\n\n * :class:`~oci.apigateway.models.WildcardSelectionKey`\n * :class:`~oci.apigateway.models.AnyOfSelectionKey`\n\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param type:\n The value to assign to the type property of this DynamicSelectionKey.\n Allowed values for this property are: \"ANY_OF\", \"WILDCARD\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n :type type: str\n\n :param is_default:\n The value to assign to the is_default property of this DynamicSelectionKey.\n :type is_default: bool\n\n :param name:\n The value to assign to the name property of this DynamicSelectionKey.\n :type name: str\n\n \"\"\"\n self.swagger_types = {\n 'type': 'str',\n 'is_default': 'bool',\n 'name': 'str'\n }\n\n self.attribute_map = {\n 'type': 'type',\n 'is_default': 'isDefault',\n 'name': 'name'\n }\n\n self._type = None\n self._is_default = None\n self._name = None\n\n @staticmethod\n def get_subtype(object_dictionary):\n \"\"\"\n Given the hash representation of a subtype of this class,\n use the info in the hash to return the class of the subtype.\n \"\"\"\n type = object_dictionary['type']\n\n if type == 'WILDCARD':\n return 'WildcardSelectionKey'\n\n if type == 'ANY_OF':\n return 'AnyOfSelectionKey'\n else:\n return 'DynamicSelectionKey'\n\n @property\n def type(self):\n \"\"\"\n Gets the type of this DynamicSelectionKey.\n Type of the selection key.\n\n Allowed values for this property are: \"ANY_OF\", \"WILDCARD\", 'UNKNOWN_ENUM_VALUE'.\n Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.\n\n\n :return: The type of this DynamicSelectionKey.\n :rtype: str\n \"\"\"\n return self._type\n\n @type.setter\n def type(self, type):\n \"\"\"\n Sets the type of this DynamicSelectionKey.\n Type of the selection key.\n\n\n :param type: The type of this DynamicSelectionKey.\n :type: str\n \"\"\"\n allowed_values = [\"ANY_OF\", \"WILDCARD\"]\n if not value_allowed_none_or_none_sentinel(type, allowed_values):\n type = 'UNKNOWN_ENUM_VALUE'\n self._type = type\n\n @property\n def is_default(self):\n \"\"\"\n Gets the is_default of this DynamicSelectionKey.\n Specifies whether to use the route or authentication server associated with this selection key as the default. The default is used if the value of a context variable in an incoming request does not match any of the other selection key values when dynamically routing and dynamically authenticating requests.\n\n\n :return: The is_default of this DynamicSelectionKey.\n :rtype: bool\n \"\"\"\n return self._is_default\n\n @is_default.setter\n def is_default(self, is_default):\n \"\"\"\n Sets the is_default of this DynamicSelectionKey.\n Specifies whether to use the route or authentication server associated with this selection key as the default. The default is used if the value of a context variable in an incoming request does not match any of the other selection key values when dynamically routing and dynamically authenticating requests.\n\n\n :param is_default: The is_default of this DynamicSelectionKey.\n :type: bool\n \"\"\"\n self._is_default = is_default\n\n @property\n def name(self):\n \"\"\"\n **[Required]** Gets the name of this DynamicSelectionKey.\n Name assigned to the branch.\n\n\n :return: The name of this DynamicSelectionKey.\n :rtype: str\n \"\"\"\n return self._name\n\n @name.setter\n def name(self, name):\n \"\"\"\n Sets the name of this DynamicSelectionKey.\n Name assigned to the branch.\n\n\n :param name: The name of this DynamicSelectionKey.\n :type: str\n \"\"\"\n self._name = name\n\n def __repr__(self):\n return formatted_flat_dict(self)\n\n def __eq__(self, other):\n if other is None:\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n return not self == other\n","repo_name":"oracle/oci-python-sdk","sub_path":"src/oci/apigateway/models/dynamic_selection_key.py","file_name":"dynamic_selection_key.py","file_ext":"py","file_size_in_byte":5480,"program_lang":"python","lang":"en","doc_type":"code","stars":345,"dataset":"github-code","pt":"52"}
+{"seq_id":"30887256392","text":"# -*- coding: UTF-8 -*-\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plot\n\nxArr = [1,3,6,10,15,21]\nyArr = [7,11,17,25,35,47]\n\nplot.plot(xArr,yArr)\nplot.show()\n\n\nprint(\"样本协方差矩阵,显示的四个元素, cov(x,x),cov(x,y),cov(y,x),cov(y,y)。 \"+ str(np.cov(xArr,yArr)))\nprint(\"xArr的协方差:%.2f\"%np.cov(xArr))\nprint(\"xArr的方差:%.2f\"%np.var(xArr))\nprint(\"yArr的方差:%.2f\"%np.var(yArr))\n\nEx = np.mean(xArr)\nprint(\"xArr的期望:%.2f\"%Ex)\nEy = np.mean(yArr)\nprint(\"yArr的期望:%.2f\"%Ey)\nSumExx = 0\nfor x in (xArr-Ex):\n SumExx+=x*x\nVarx =SumExx/len(xArr)\nprint(\"xArr的方差:%.2f\"%Varx)\n\nprint(\"xArr的sigma标准差:%.2f\"%np.std(xArr))\nprint(\"yArr的sigma标准差:%.2f\"%np.std(yArr))\n\nsumEx_Ey =0\nfor i in range(len(xArr)):\n sumEx_Ey+=(xArr[i]-Ex)*(yArr[i]-Ey)\n#以下两个函数都是协方差\ncov_xy_sample =sumEx_Ey*1/ (len(xArr)-1) #样本协方差\ncov_xy=sumEx_Ey*1/ len(xArr) #当n很大时,协方差=样本的协方差\nprint(\"cov(x,y)协方差:%.2f\"%cov_xy)\nprint(\"cov(x,y)样本的协方差:%.2f 该值应该和np.cov算出来的值一样 %s\"%(cov_xy_sample, abs(cov_xy_sample-np.cov(xArr,yArr)[0,1])<=0.0001))\n\nrho = np.cov(xArr,yArr)[0,1] / (np.std(xArr)*np.std(yArr))\nprint(\"x和y相关系数corr(x,y):%f\"%(rho))\n#一般用下面这个来计算相关性,rho绝对值时小于等于1的,等于1表示存在y=ax+b的关系。\n#皮尔逊相关系数,表示的线性关系,如果为0不代表没有非线性关系。所以独立一定不相关,但是不相关不一定独立。\nrho= cov_xy / (np.std(xArr)*np.std(yArr))\nprint(\"x和y的皮尔逊相关系数,corr(x,y):%f\"%(rho))\n","repo_name":"ggwhsd/PythonPractice","sub_path":"mathStudy/statistic.py","file_name":"statistic.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"37713225544","text":"# apt-get install python3-tk\n# used for windowing\nimport tkinter as tk\n#from tkinter import ttk # also import the themed tkinter for good looking widgets (not obligatory)\nimport sys\n\nfrom tkinter.font import Font\n#from tkinter.scrolledtext import ScrolledText\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename, askdirectory\n\n# pip3 install imgurpython (NO! out-of-date, roken code)\n# git clone https://github.com/ueg1990/imgurpython.git\n# used for imgur access\nimport imgurpython\n\n# does not need any installation \n# necessary to expand path for config file\nimport os.path\n\n# does not need any installation \nimport configparser\n\n# does not need any installation \n# used to get authorization from imgur web site\nimport webbrowser\n \n# does not need any installation \n# used to get current date and time\nimport datetime \n# does not need any installation \n# used to get authorization from imgur web site\nimport webbrowser\n\nclass ImgurClientEnhanced(imgurpython.ImgurClient):\n \n allowed_album_fields = {\n 'ids', 'title', 'description', 'privacy', 'layout', 'cover', 'order'\n }\n \n def __init__(self, client_id, client_secret, access_token=None, refresh_token=None, mashape_key=None):\n super(ImgurClientEnhanced, self).__init__(client_id, client_secret, access_token, refresh_token, mashape_key)\n \n def update_image(self, image_id, fields):\n '''\n Note: Can only update title or description of image\n '''\n post_data = {field: fields[field] for field in set({'title', 'description'}).intersection(fields.keys())}\n return self.make_request('POST', 'image/%s' % image_id, data=post_data)\n \nclass MainWindow:\n\n def __init__(self, parent):\n \n font_default = Font(family = \"default\", size = \"10\")\n font_status = Font(family = \"default\", size = \"10\", slant = 'italic')\n font_contents = font_default\n \n parent.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\n\n self.images = {}\n self.albums = {}\n\n self.parent = parent\n self.parent.title(os.path.basename(__file__))\n \n self.string_status = tk.StringVar()\n \n if self.read_config():\n if self.create_client():\n self.authorize()\n \n self.parent.geometry(self.config.get('gui', 'geometry', fallback = '526x300+275+191'))\n\n self.frame_id = tk.Frame(parent)\n self.frame_id.pack(anchor = tk.W)\n\n #self.frame_buttons = tk.Frame(parent)\n #self.frame_buttons.pack(anchor = tk.W)\n\n #self.button_readconfig = tk.Button(self.frame_buttons, text = \"Do work\", command = self.do_work)\n #self.button_readconfig.pack(side = tk.LEFT, padx = 5, pady = 2)\n\n # this should come before the contents, so that it does not shrink first when resizing windows\n # put this into the pack manager before the contents so it does not resize until the contents have\n self.label_status = tk.Label(parent, textvariable = self.string_status, font = font_status, bd = 1, relief = tk.SUNKEN, justify = tk.LEFT, anchor = tk.W)\n self.label_status.pack(side = tk.BOTTOM, fill = tk.BOTH) \n\n # contents\n columnnames = ['id', 'type']\n displaycolumnnames = []\n\n self.treeview = ttk.Treeview(parent, selectmode = 'browse', columns = columnnames, displaycolumns = displaycolumnnames) # , height = 10, show = 'headings'\n #self.treeview.bind('', self.treeview_doubleclick)\n self.treeview.bind('', self.treeview_rightclick)\n #self.treeview.bind('', self.treeview_click)\n self.treeview.bind('<>', self.populate_album)\n for columnname in columnnames:\n self.treeview.heading(columnname, text = columnname)\n self.treeview.column(columnname, stretch = True)\n self.treeview.pack(anchor = tk.W, fill = tk.BOTH, expand = True)\n \n # immediately populate tree\n self.populate_albums()\n\n # create an album context menu\n self.menu_album_context = tk.Menu(parent, tearoff = 0)\n self.menu_album_context.add_command(label=\"Get Info\", command = self.get_album_info)\n self.menu_album_context.add_command(label=\"View\", command = self.view_album)\n self.menu_album_context.add_command(label=\"Edit\", command = self.edit_album)\n self.menu_album_context.add_command(label=\"Delete\", command = self.delete_album)\n self.menu_album_context.add_command(label=\"Upload Image\", command = self.upload_image)\n self.menu_album_context.add_separator()\n self.menu_album_context.add_command(label=\"Upload Album\", command = self.upload_album)\n self.menu_album_context.bind(\"\", lambda event: self.menu_album_context.unpost()) # keyboard focus\n self.menu_album_context.bind(\"\", lambda event: self.menu_album_context.unpost()) # mouse focus\n\n # create an image context menu\n self.menu_image_context = tk.Menu(parent, tearoff = 0)\n self.menu_image_context.add_command(label=\"Get Info\", command = self.get_image_info)\n self.menu_image_context.add_command(label=\"View\", command = self.view_image)\n self.menu_image_context.add_command(label=\"Edit\", command = self.edit_image)\n self.menu_image_context.add_command(label=\"Delete\", command = self.delete_image)\n self.menu_image_context.bind(\"\", lambda event: self.menu_image_context.unpost()) # keyboard focus\n self.menu_image_context.bind(\"\", lambda event: self.menu_image_context.unpost()) # mouse focus\n\n def on_closing(self):\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['geometry'] = self.parent.geometry()\n self.write_config()\n self.parent.destroy()\n\n def treeview_click(self, event):\n #print(\"geometry!\")\n #print(self.parent.geometry())\n bob = 'you uncle'\n\n def treeview_doubleclick(self, event):\n item = self.treeview.selection()[0]\n #print(\"you double-clicked \", self.treeview.item(item, \"values\"))\n iid = self.treeview.identify_row(event.y)\n if iid:\n # mouse pointer over item\n self.treeview.selection_set(iid)\n item = self.treeview.selection()[0]\n print(\"{0} {1} you double-clicked {2}\".format(event.x, event.y, self.treeview.item(item, \"values\")))\n else:\n # clear selection\n #self.treeview.selection_clear()\n if len(self.treeview.selection()) > 0:\n self.treeview.selection_remove(self.treeview.selection()[0])\n \n def treeview_rightclick(self, event):\n # select row under mouse\n iid = self.treeview.identify_row(event.y)\n if iid:\n # mouse pointer over item\n self.treeview.selection_set(iid)\n type = self.treeview_item()['type']\n if type == 'album':\n self.menu_album_context.post(event.x_root - 5, event.y_root - 5)\n if type == 'image':\n self.menu_image_context.post(event.x_root - 5, event.y_root - 5)\n else:\n # clear selection\n #self.treeview.selection_clear()\n if len(self.treeview.selection()) > 0:\n self.treeview.selection_remove(self.treeview.selection()[0])\n self.menu_other_context.post(event.x_root - 5, event.y_root - 5)\n\n def get_album_info(self):\n tk.messagebox.showinfo(\"album info\", vars(self.albums[self.treeview_item()['id']]))\n\n def get_image_info(self):\n tk.messagebox.showinfo(\"image info\", vars(self.images[self.treeview_item()['id']]))\n\n def treeview_node(self):\n return self.treeview.selection()[0] # iid\n\n def treeview_item(self):\n iid = self.treeview.selection()[0]\n return self.treeview.set(iid)\n\n def treeview_delete(self):\n iid = self.treeview.selection()[0]\n self.treeview.delete(iid)\n\n def view_album(self):\n self.open_url(self.client.get_album(self.treeview_item()['id']).link)\n\n def view_image(self):\n self.open_url(self.client.get_image(self.treeview_item()['id']).link)\n\n def edit_album(self):\n AlbumEditor(self.parent, self.albums[self.treeview_item()['id']], self.client, self.config)\n\n def edit_image(self):\n ImageEditor(self.parent, self.images[self.treeview_item()['id']], self.client)\n\n def upload_album(self):\n defaultdirectory = self.config.get('gui', 'lastopendir', fallback = '.')\n directory = askdirectory(initialdir = defaultdirectory)\n if directory:\n prefixdirectory, basedirectory = os.path.split(directory)\n\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['lastopendir'] = directory\n \n # give warning if album may already exist\n \n newalbum = self.create_album(directory)\n \n filenames = os.listdir(directory)\n for filename in filenames:\n baseprefix, baseext = os.path.splitext(filename)\n if baseext in ('.jpg', '.png'):\n self.set_status('Uploading ' + filename)\n newimage = self.upload_image_to_album(newalbum.id, directory + '/' + filename) \n self.set_status('Done uploading ' + filename)\n\n def upload_image(self):\n id = self.treeview_item()['id']\n directory = self.config.get('gui', 'lastopendir', fallback = '.')\n filename = askopenfilename(initialdir = directory) # show an \"Open\" dialog box and return the path to the selected file\n if filename:\n directory, basename = os.path.split(filename)\n baseprefix, baseext = os.path.splitext(basename)\n\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['lastopendir'] = directory\n\n newimage = self.upload_image_to_album(id, filename)\n \n # add to internal collection\n self.images[newimage.id] = newimage\n # add to treeview\n image_name = newimage.name if newimage.name else 'Unnamed'\n self.treeview.insert(self.treeview_node(), tk.END, text = image_name, values = [newimage.id, 'image'])\n return True\n\n def upload_image_to_album(self, album_id, filepath):\n\n directory, basename = os.path.split(filepath)\n baseprefix, baseext = os.path.splitext(basename)\n\n imageconfig = { \"album\": album_id, \"name\": basename, \"title\": baseprefix, \"description\": baseprefix }\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n newimage = imgurpython.imgur.models.image.Image(self.client.upload_from_path(path = filepath, config = imageconfig, anon = False))\n except ImgurClientError as e:\n self.set_status('Failed to upload image.')\n print(sys.exc_info(), file = sys.stderr)\n raise\n finally:\n self.parent.config(cursor = '')\n\n return newimage\n\n def create_album(self, directory):\n\n prefixdirectory, basedirectory = os.path.split(directory)\n\n albumfields = { \"title\": basedirectory, \"description\": basedirectory }\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n newalbum = imgurpython.imgur.models.album.Album(self.client.create_album(fields = albumfields))\n except ImgurClientError as e:\n self.set_status('Failed to upload image.')\n print(sys.exc_info(), file = sys.stderr)\n raise\n finally:\n self.parent.config(cursor = '')\n\n return newalbum\n\n def delete_image(self):\n id = self.treeview_item()['id']\n if messagebox.askyesno('Deleting image ' + id, 'Are you sure?'):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.delete_image(id)\n except imgurpython.ImgurClientError as e:\n self.set_status('Failed to delete image.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n # remove from internal collection\n self.images.pop(id, None)\n # remove from treeview\n self.treeview_delete()\n return True\n\n def delete_album(self):\n id = self.treeview_item()['id']\n if messagebox.askyesno('Deleting album ' + id, 'Are you sure?'):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.album_delete(id)\n except imgurpython.ImgurClientError as e:\n self.set_status('Failed to delete album.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n # remove from internal collection\n self.albums.pop(id, None)\n # remove from treeview\n self.treeview_delete()\n return True\n\n def open_url(self, url):\n webbrowser.open(url, new = 0, autoraise = True)\n\n def set_status(self, message):\n print(message)\n self.string_status.set(message)\n \n def lock_minimum_size(self):\n self.parent.update() # make sure all the info from previous widget placements has been recalculated\n self.parent.minsize(self.parent.winfo_width(), self.parent.winfo_height())\n\n def create_client(self):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client = ImgurClientEnhanced(self.config['client']['id'], self.config['client']['secret'])\n return True\n except ImgurClientError as e:\n print(e)\n self.set_status('ImgurClientError.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n except:\n self.set_status('Failed to create client using saved credentials. Run register program.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n\n def authorize(self):\n try:\n self.parent.config(cursor = 'watch')\n self.parent.update()\n self.client.set_user_auth(self.config['credentials']['access_token'], self.config['credentials']['refresh_token'])\n return True\n except:\n self.set_status('Failed to authorize using saved credentials. Run authorize program.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n finally:\n self.parent.config(cursor = '')\n\n def write_config(self):\n try:\n # write the configuration back to the file it came from\n with open(self.configfilename, 'w') as configfile: # save\n self.config.write(configfile)\n self.set_status('Successfully wrote config file.')\n return True\n\n except:\n self.set_status('Failed to write config file.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n\n def populate_albums(self):\n tempalbums = sorted(self.client.get_account_albums('me'), key = lambda album: album.order)\n for album in tempalbums:\n self.albums[album.id] = album\n album_title = album.title if album.title else 'Untitled'\n rowid = self.treeview.insert('', tk.END, text = album_title, values = [album.id, 'album'])\n self.treeview.insert(rowid, tk.END, text = 'dummy', values = ['', 'dummy']) # makes the item \"openable\"\n \n def populate_album(self, event):\n try:\n \n self.parent.config(cursor = 'watch')\n self.parent.update()\n\n selectednode = self.treeview.focus()\n if self.treeview.set(selectednode, 'type') == 'album':\n for child in self.treeview.get_children(selectednode):\n if self.treeview.set(child, 'type') == 'dummy':\n self.treeview.delete(*self.treeview.get_children(selectednode))\n for image in self.client.get_album_images(self.treeview.set(selectednode, 'id')):\n self.images[image.id] = image\n image_name = image.name if image.name else 'Unnamed'\n self.treeview.insert(selectednode, tk.END, text = image_name, values = [image.id, 'image'])\n finally:\n self.parent.config(cursor = '')\n\n def read_config(self):\n try:\n self.config = configparser.ConfigParser() # don't know what to do if this fails.\n configfiles = self.config.read(['.imgursyncconfig', os.path.expanduser('~/.imgursyncconfig')])\n # Save the name of the first file that was successfully read\n if len(configfiles) > 0:\n self.configfilename = configfiles[0]\n else:\n self.configfilename = '.imgursyncconfig'\n self.set_status('Successfully read config file. File is ' + self.configfilename)\n return True\n\n except:\n self.set_status('Failed to read config file.')\n print(sys.exc_info(), file = sys.stderr)\n return False\n \nclass AlbumEditor:\n def __init__(self, parent, album, client, config):\n\n self.album = album\n self.client = client\n self.config = config\n\n self.parent = tk.Toplevel(parent)\n self.parent.title(\"album \" + album.id)\n \n self.parent.geometry(self.config.get('gui', 'geometry.album', fallback = '526x150+604+529'))\n\n # configure the \"data\" column to be the one that stretches.\n self.parent.columnconfigure(1, weight = 1)\n \n # 'layout' is deprecated and can be changed, but has no effec on the site, so we don;t bother to change it.\n self.editfields = ['title', 'description', 'privacy', 'cover', 'order']\n self.editvalues = {}\n for editfield in self.editfields:\n editvalue = tk.StringVar() \n editvalue.set(str(getattr(album, editfield))) \n self.editvalues[editfield] = editvalue\n \n row = 0\n for editfield in self.editfields:\n row = row + 1\n label = tk.Label(self.parent, text = editfield)\n label.grid(sticky = tk.W, row = row, column = 0)\n entry = tk.Entry(self.parent, textvariable = self.editvalues[editfield])\n entry.grid(sticky = (tk.W + tk.E), row = row, column = 1) \n\n row = row + 1\n\n self.frame_buttons = tk.Frame(self.parent, bd = 2)\n self.button_apply = tk.Button(self.frame_buttons, text = 'Apply', command = self.apply)\n self.button_apply.pack(side = tk.LEFT)\n self.button_done = tk.Button(self.frame_buttons, text = 'Done', command = self.done)\n self.button_done.pack(side = tk.LEFT)\n\n self.frame_buttons.grid(sticky = tk.W, row = row, column = 0, columnspan = 2)\n \n def done(self):\n if not 'gui' in self.config.sections():\n self.config.add_section('gui')\n self.config['gui']['geometry.album'] = self.parent.geometry()\n\n self.parent.destroy()\n\n def apply(self):\n # write the changed fields back to the album object, and write to imgur, too\n fieldstoupdate = { 'ids': None }\n for editfield in self.editfields:\n newvalue = self.editvalues[editfield].get()\n fieldstoupdate[editfield] = newvalue\n setattr(self.album, editfield, newvalue)\n\n # Bug in update_album function requires that ids be set. If not a list, then it is not considered.\n self.client.update_album(album_id = self.album.id, fields = fieldstoupdate)\n \n # try re-reading now, debug code\n temp = self.client.get_album(self.album.id)\n print(temp)\n print(vars(temp))\n\nclass ImageEditor:\n def __init__(self, parent, image, client):\n\n self.image = image\n self.client = client\n self.parent = tk.Toplevel(parent)\n self.parent.title(\"image \" + image.id)\n \n # configure the \"data\" column to be the one that stretches.\n self.parent.columnconfigure(1, weight = 1)\n \n self.editfields = ['title', 'description']\n self.editvalues = {}\n for editfield in self.editfields:\n editvalue = tk.StringVar() \n editvalue.set(str(getattr(image, editfield))) \n self.editvalues[editfield] = editvalue\n \n row = 0\n for editfield in self.editfields:\n row = row + 1\n label = tk.Label(self.parent, text = editfield)\n label.grid(sticky = tk.W, row = row, column = 0)\n entry = tk.Entry(self.parent, textvariable = self.editvalues[editfield])\n entry.grid(sticky = (tk.W + tk.E), row = row, column = 1) \n \n row = row + 1\n\n self.frame_buttons = tk.Frame(self.parent, bd = 2)\n self.button_apply = tk.Button(self.frame_buttons, text = 'Apply', command = self.apply)\n self.button_apply.pack(side = tk.LEFT)\n self.button_done = tk.Button(self.frame_buttons, text = 'Done', command = self.done)\n self.button_done.pack(side = tk.LEFT)\n\n self.frame_buttons.grid(sticky = tk.W, row = row, column = 0, columnspan = 2)\n\n def done(self):\n self.parent.destroy()\n \n def apply(self):\n # write the changed fields back to the image object, and write to imgur, too\n fieldstoupdate = {}\n for editfield in self.editfields:\n newvalue = self.editvalues[editfield].get()\n fieldstoupdate[editfield] = newvalue\n setattr(self.image, editfield, newvalue)\n\n self.client.update_image(image_id = self.image.id, fields = fieldstoupdate )\n\nif __name__ == '__main__':\n root = tk.Tk()\n my_gui = MainWindow(root)\n root.mainloop()\n","repo_name":"ccady/imgursync","sub_path":"imgursync_test.py","file_name":"imgursync_test.py","file_ext":"py","file_size_in_byte":22415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"74699947045","text":"import yfinance as yf\nimport pandas as pd\nimport numpy as np\nfrom stocks_sample import stock_symbols_sample\n\ndef categorize_stocks_by_volatility(stock_symbols):\n # Define the time range\n start_date = \"2020-01-01\"\n end_date = \"2021-12-31\"\n\n risk_levels = [\"Low\", \"Medium\", \"High\"]\n risk_thresholds = [0.4, 0.5] # Adjust these thresholds as per your preference\n\n categorized_stocks = {}\n\n for symbol in stock_symbols:\n # Retrieve the historical stock data\n stock_data = yf.download(symbol, start=start_date, end=end_date, progress=False)\n\n # Calculate the stock's volatility\n stock_data['Log Returns'] = np.log(stock_data['Close'] / stock_data['Close'].shift(1))\n stock_volatility = stock_data['Log Returns'].std() * np.sqrt(252) # Assuming 252 trading days in a year\n\n # Categorize the stock based on volatility\n if stock_volatility <= risk_thresholds[0]:\n risk_level = risk_levels[0]\n elif stock_volatility <= risk_thresholds[1]:\n risk_level = risk_levels[1]\n else:\n risk_level = risk_levels[2]\n\n categorized_stocks[symbol] = risk_level\n\n # Save categorized stocks to a CSV file\n df = pd.DataFrame.from_dict(categorized_stocks, orient='index', columns=['risk_level'])\n df.index.name = 'Symbol'\n df.to_csv('categorized_stocks.csv')\n\n return categorized_stocks\n","repo_name":"sebastianmarmolejo/wealthai","sub_path":"risk_categorizer.py","file_name":"risk_categorizer.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10236083528","text":"import gym\nfrom gym import spaces\nimport numpy as np\n\nclass DRLRadiationEnv(gym.Env):\n def __init__(self):\n # load state from dicom file, radiation dose file, and angles tested vector\n self.dicom_file = \"path/to/dicom/file\"\n self.radiation_file = \"path/to/radiation/file.mat\"\n self.tested_angles = np.loadtxt(\"path/to/tested_angles.txt\")\n\n # define action and observation spaces\n self.action_space = spaces.Discrete(2) # 0: do not change angle, 1: add 2 degrees to previous angle\n self.observation_space = spaces.Box(low=0, high=255, shape=(image_height, image_width, num_channels), dtype=np.float32)\n\n # define other parameters\n self.current_angle = None # angle corresponding to current observation\n self.current_observation = None # current state of the environment\n self.episode_reward = 0.0 # cumulative reward for current episode\n\n def step(self, action):\n # apply the selected action to the current state\n if action == 1:\n self.current_angle += 2\n\n # update observation and reward based on new angle\n self.current_observation = self._get_observation()\n reward = self._get_reward()\n\n # check if episode is done (e.g. if max reward has been achieved)\n done = False\n if reward == MAX_REWARD:\n done = True\n\n # return new observation, reward, and done flag\n return self.current_observation, reward, done, {}\n\n def reset(self):\n # reset the environment to its initial state\n self.current_angle = self.tested_angles[-1] # start from last tested angle\n self.current_observation = self._get_observation()\n self.episode_reward = 0.0\n return self.current_observation\n\n def render(self, mode='human'):\n # display the current observation (e.g. as an image)\n pass\n\n def _get_observation(self):\n \n # extract relevant features from dicom data and dose file\n feature_1 = self.dicom_data.PixelSpacing[0]\n feature_2 = self.dicom_data.PixelSpacing[1]\n feature_3 = self.dose_data['dose'][0][0]\n \n # one-hot encode the tested angles vector\n tested_angles_onehot = np.zeros(num_angles)\n for angle in self.tested_angles:\n tested_angles_onehot[angle] = 1\n \n # combine all features into a single observation vector\n observation = np.concatenate((feature_1, feature_2, feature_3, tested_angles_onehot))\n \n return observation\n\n def _get_reward(self):\n # compute reward based on the radiation dose for the current angle\n # return reward as a float\n pass\n","repo_name":"giulia97-w/Tesi-DRL","sub_path":"DRL.py","file_name":"DRL.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10252140023","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse, JsonResponse\nfrom django.conf import settings\nfrom pathlib import Path\nimport cv2\nimport os\nimport shutil\nimport pandas as pd\nimport numpy as np\n\nprint(\"loading DeepFace ...\")\nfrom deepface import DeepFace\nfrom deepface.commons import functions\nprint(\"DeepFace is loaded\")\n\nfrom . import forms, models\n\n\ndef clear_cached_files(request):\n \"\"\"\n This function clears the cached images and the model entries.\n \"\"\"\n\n # delete media directory\n media_dir_path = settings.MEDIA_ROOT\n if media_dir_path.is_dir():\n shutil.rmtree(path=media_dir_path)\n\n # delete all entries in the model\n img_entries = models.UploadedImages.objects.all()\n print(f\"deleting {len(img_entries)} entries\")\n for img_entry in img_entries:\n img_entry.delete()\n\n return render(request, \"home/cleared_cached_files.html\")\n\n\nclass DeepFaceWrapper:\n \"\"\"\n This wrapper handles the DeepFace module for django.\n \"\"\"\n\n # choose another model or detector if you want to experiment:\n\n # 'VGG-Face', 'OpenFace', 'Facenet', 'Facenet512', 'DeepFace', 'DeepID', 'Dlib', 'ArcFace'\n # ('Emotion', 'Age', 'Gender', 'Race') not implemented\n model_name = 'Facenet'\n recog_model = DeepFace.build_model(model_name)\n # 'opencv', 'ssd', 'dlib', 'mtcnn', 'retinaface'\n detector = 'mtcnn'\n representations = DeepFace.load_representations(\n db_path=settings.BASE_DIR / \"database\",\n model_name=model_name,\n model=recog_model,\n detector_backend=detector,\n verbose=True\n )\n\n @classmethod\n def analyze_uploaded_img(cls):\n \"\"\"\n This method analyses the last uploaded image using DeepFace, and saves\n the analyzed image in MEDIA_ROOT/analyzed_images\n \"\"\"\n\n # get the last uploaded image from the model UploadedImages\n image_db = models.UploadedImages.objects.latest('id')\n\n # get the path of the last analyzed image\n img_path = Path(image_db.uploaded_img.path)\n\n # put the name of the image in the model\n img_name = img_path.name\n image_db.img_name = img_name\n\n # analyze the image using the DeepFace module\n df_result = DeepFace.find_faces(\n img_path=img_path,\n db_path=settings.BASE_DIR / \"database\",\n model_name=cls.model_name,\n model=cls.recog_model,\n detector_backend=cls.detector,\n representations=cls.representations,\n verbose=True\n )\n\n # drop distance and best_match_path\n df_result = df_result.drop(columns=[\"distance\", \"best_match_path\"])\n\n # add empty columns to match ClientDB\n df_result[\"date_of_birth\"] = np.nan\n df_result[\"VIP\"] = np.nan\n df_result[\"is_allowed_in\"] = np.nan\n df_result[\"comments\"] = np.nan\n df_result[\"total_entry_tickets_bought\"] = np.nan\n df_result[\"creation_date\"] = np.nan\n\n # complete df_result with data from ClientDB\n for client in models.ClientDB.objects.all():\n for index in df_result.index:\n if df_result.loc[index, \"name\"] == client.client_name:\n df_result.loc[index, \"date_of_birth\"] = client.date_of_birth\n df_result.loc[index, \"VIP\"] = client.VIP\n df_result.loc[index, \"is_allowed_in\"] = client.is_allowed_in\n df_result.loc[index, \"comments\"] = client.comments\n df_result.loc[index, \"total_entry_tickets_bought\"] = client.total_entry_tickets_bought\n df_result.loc[index, \"creation_date\"] = client.creation_date\n\n # load original image\n analyzed_img = cv2.imread(str(img_path))\n\n # resize it to standard size\n analyzed_img, ratio = functions.resize_img_to_target_size(analyzed_img)\n\n # draw boxes on the image\n for face_index in df_result.index:\n box = df_result.loc[face_index, \"box\"]\n name = df_result.loc[face_index, \"name\"]\n is_allowed_in = df_result.loc[face_index, \"is_allowed_in\"]\n if pd.isnull(name):\n # draw an orange box with the name \"Unknown\"\n analyzed_img = functions.draw_box(analyzed_img, box, ratio=ratio)\n else:\n if is_allowed_in:\n # draw a green box\n color = (0,255,0)\n else:\n # draw a red box\n color = (0,0,255)\n analyzed_img = functions.draw_box(analyzed_img, box, color=color, name=name.replace(\"_\", \" \"), ratio=ratio)\n\n # save the analyzed image in MEDIA_ROOT/analyzed_images\n # (create the directory if it doesn't exist)\n analyzed_images_dir_path = Path(settings.MEDIA_ROOT / \"analyzed_images\")\n analyzed_img_path = analyzed_images_dir_path / img_name\n if not analyzed_images_dir_path.is_dir():\n print(\"no analyzed_images directory yet in media, creating\")\n os.mkdir(path=analyzed_images_dir_path)\n cv2.imwrite(str(analyzed_img_path), analyzed_img)\n\n # drop \"box\" column and rows with null values\n df_result = df_result.drop(columns=\"box\").dropna()\n\n # save df_result as a csv file in MEDIA_ROOT/analyzed_images\n csv_name = img_path.stem + \".csv\"\n csv_path = analyzed_images_dir_path / csv_name\n df_result.to_csv(path_or_buf=str(csv_path), index=False)\n\n # save the model\n image_db.save()\n\n\ndef index(request):\n \"\"\"\n Home page. Allows the user to upload an image for analysis.\"\n \"\"\"\n\n if request.method == 'GET':\n form = forms.ImageForm()\n return render(request, 'home/index.html', {'form': form})\n\n elif request.method == 'POST':\n\n form = forms.ImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n DeepFaceWrapper.analyze_uploaded_img()\n return redirect('/last_analyzed_image/')\n else:\n raise ValueError(\"form not valid ?\")\n\n\ndef last_analyzed_image(request):\n \"\"\"\n Shows the last analysed image.\n \"\"\"\n\n try:\n # get the last entry in UploadedImages\n last_image_db = models.UploadedImages.objects.latest('id')\n\n # get the name of the last analyzed image and its corresponding csv\n img_name = last_image_db.img_name\n csv_name = Path(img_name).stem + \".csv\"\n\n # load the csv with pandas\n csv_path = settings.MEDIA_ROOT / \"analyzed_images\" / csv_name\n df_result = pd.read_csv(filepath_or_buffer=str(csv_path))\n\n # format the DataFrame\n df_result[\"total_entry_tickets_bought\"] = df_result[\"total_entry_tickets_bought\"].astype('int32')\n df_result[\"date_of_birth\"] = pd.to_datetime(df_result[\"date_of_birth\"]).dt.strftime('%d %b %Y')\n df_result[\"creation_date\"] = pd.to_datetime(df_result[\"creation_date\"]).dt.strftime('%d %b %Y')\n\n last_analyzed_img_url = settings.MEDIA_URL + \"analyzed_images/\" + img_name\n context = {\n \"db_is_empty\": False,\n \"analyzed_img_url\": last_analyzed_img_url,\n \"df_result\": df_result.to_html(index=False).replace(\"_\", \" \")\n }\n\n except models.UploadedImages.DoesNotExist:\n context = {\"db_is_empty\": True}\n\n return render(request, \"home/show_last_analyzed_image.html\", context)\n","repo_name":"Gwizdo51/face_recognition_project_simplon","sub_path":"face_analyzer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"10816380967","text":"\"\"\"This module will contain the KeyPad-object\"\"\"\nfrom time import sleep\nimport RPi.GPIO as GPIO\n\n\ndef setup():\n \"\"\"This method will set the proper mode via GPIO.setmode(GPIO.BCM).\n It will also set the row-pins as output and the column-pins as input.\"\"\"\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(18, GPIO.OUT)\n print(\"now we have set pin 18 to OUT\")\n GPIO.setup(23, GPIO.OUT)\n GPIO.setup(24, GPIO.OUT)\n GPIO.setup(25, GPIO.OUT)\n GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(27, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(22, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n\nclass KeyPad:\n \"\"\"This class is representing the keypad, but I am currently\n not sure what happens here\"\"\"\n\n def __init__(self):\n \"\"\"This class initializes the KeyPad-object,\n so the setup-method must be called\"\"\"\n setup()\n # A dict that uses a tupple with (row, col) as key\n self.signs = {(18, 17): '1', (18, 27): '2', (18, 22): '3',\n (23, 17): '4', (23, 27): '5', (23, 22): '6',\n (24, 17): '7', (24, 27): '8', (24, 22): '9',\n (25, 17): '*', (25, 27): '0', (25, 22): '#'}\n\n def do_polling(self):\n \"\"\"Will use nested loops to determine which key is currently being pressed.\n We will check if a key is pressed 10 times with 10ms sleep-time.\"\"\"\n row_pins = [18, 23, 24, 25]\n col_pins = [17, 27, 22]\n\n for row in row_pins:\n # Set the current row_pin HIGH\n GPIO.output(row, GPIO.HIGH)\n for col in col_pins:\n # If both col and row is high (10 times), save the values in a\n # tupple that will also be stored in a dict\n i = 0\n for j in range(0, 10):\n if GPIO.input(col) == GPIO.HIGH:\n i += 1\n sleep(0.01)\n if i == 10:\n tupple_answer = (row, col)\n GPIO.output(row, GPIO.LOW)\n return self.signs[tupple_answer]\n GPIO.output(row, GPIO.LOW)\n return None\n\n def get_next_signal(self):\n \"\"\"The interface between the agent and the keypad.\n Calls do_polling until a key press is detected.\"\"\"\n next_signal = None\n while next_signal is None:\n next_signal = self.do_polling()\n sleep(2)\n return next_signal\n","repo_name":"ingraso/Keypad","sub_path":"keypad.py","file_name":"keypad.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"48094234228","text":"import sys\n\ndef find(a):\n\n if a != parent[a]:\n parent[a] = find(parent[a])\n return parent[a]\n\ndef union(a, b):\n\n parent[find(b)] = find(a)\n print(parent)\n\ndef is_union(a, b):\n\n if find(a) == find(b):\n print('YES')\n else:\n print('NO')\n\n\nn, m = map(int, input().split())\nparent = [i for i in range(n+1)]\nfor _ in range(m):\n f, a, b = map(int, sys.stdin.readline().split())\n\n if f == 0:\n union(a, b)\n else:\n is_union(a, b)","repo_name":"yevini118/baekjoon","sub_path":"union_find/집합의_표현.py","file_name":"집합의_표현.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"36226640180","text":"import numpy as np\nimport params as P\nimport sys, os\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\nfrom controller import Controller\n\n\nclass MassSpringDamperDynamics(object):\n\t\n\tdef __init__(self, controller):\n\t\tself.state = np.matrix([\n\t\t\t[float(P.z0)],\n\t\t\t[float(P.zdot0)]\n\t\t])\n\n\t\tself.ctrl = controller\n\n\n\tdef propogateDynamics(self, ref_input):\n\t\t'''ref_input is the reference position'''\n\n\t\tu = self.ctrl.getForces(ref_input[0], self.state.item(0)) + P.input_disturbance\n\t\t# RK4 integration\n\t\tk1 = self.Derivatives(self.state, u)\n\t\tk2 = self.Derivatives(self.state + P.Ts/2.0*k1, u)\n\t\tk3 = self.Derivatives(self.state + P.Ts/2.0*k2, u)\n\t\tk4 = self.Derivatives(self.state + P.Ts*k3, u)\n\t\tder = P.Ts/6.0 * (k1 + 2*k2 + 2*k3 + k4)\n\t\tself.state += der\n\n\n\tdef Derivatives(self, state, u):\n\t\t'''Return the derivatives of the state'''\n\n\t\tz = state.item(0)\n\t\tzdot = state.item(1)\n\t\tF = u\n\n\t\t# m*zddot + b*zdot + k*z = F\n\t\t# zddot = (F - b*zdot - k*z) / m\n\t\tzddot = (F - P.b*zdot - P.k*z) / P.m\n\t\treturn np.matrix([[zdot], [zddot]])\n\n\n\tdef Outputs(self):\n\t\treturn self.state.item(0)\n\n\n\tdef States(self):\n\t\treturn self.state.T.tolist()[0]\n","repo_name":"catalys1/FeedbackControlSystemsEE483","sub_path":"massSpringDamper/msd_dynamics.py","file_name":"msd_dynamics.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"22417686461","text":"import pyrebase\nclass Firebase:\n __firebaseConfig = {\n \"apiKey\": \"AIzaSyD5-FOcfZTu_FeyMaZioPEz7MLpjSTYSfk\",\n \"authDomain\": \"atujobportal-33aba.firebaseapp.com\",\n \"databaseURL\": \"https://atujobportal-33aba-default-rtdb.firebaseio.com\",\n \"projectId\": \"atujobportal-33aba\",\n \"storageBucket\": \"atujobportal-33aba.appspot.com\",\n \"messagingSenderId\": \"501965329940\",\n \"appId\": \"1:501965329940:web:3f8bd58f8e0427a2c9b901\",\n \"measurementId\": \"G-J9BRLQTB9R\",\n \"serviceAccount\": \"static/firebase/atujobportal-33aba-firebase-adminsdk-wcge9-31d51b269e.json\",\n }\n\n __firebase = pyrebase.initialize_app(__firebaseConfig)\n authe = __firebase.auth()\n db = __firebase.database()\n storage = __firebase.storage()\n","repo_name":"tmsoft96/ATUJobPortal","sub_path":"ATUJobPortal/config/firebase.py","file_name":"firebase.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"25601809954","text":"\"\"\"\n.. module:: django_core_utils.tests.test_models\n :synopsis: django_core_utils models unit test module.\n\n*django_core_utils* models unit test module. The unit tests for\n abstract models are implemented in a separate project due\n to Django not handling of dynamic model db table creation.\n\"\"\"\nfrom __future__ import absolute_import, print_function\n\nfrom django.test import TestCase\n\nfrom ..models import (NamedModel, VersionedModel, db_table,\n db_table_for_app_and_class, db_table_for_class,\n pluralize, verbose_class_name)\n\n_app_label = 'test_inflection'\n\n\nclass MyModel(VersionedModel):\n \"\"\"Sample model class.\"\"\"\n class Meta(VersionedModel.Meta):\n \"\"\"Meta model class.\"\"\"\n app_label = _app_label\n\n\nclass InflectionTestCase(TestCase):\n \"\"\"Inflection usage unitest class.\n \"\"\"\n expected_table_name = \"sl_test_inflection_my_model\"\n\n def test_verbose_class_name(self):\n verbose_name = verbose_class_name(MyModel.__name__)\n self.assertEqual(verbose_name, \"my model\",\n \"verbose class name error %s\" % verbose_name)\n\n def test_pluralize(self):\n pluralized = pluralize(MyModel.__name__)\n self.assertEqual(pluralized, \"MyModels\",\n \"pluralized error %s\" % pluralized)\n\n def test_db_table_for_class(self):\n name = db_table_for_class(MyModel.__name__)\n self.assertEqual(name, \"my_model\",\n \"db_table_for_class error %s\" % name)\n\n def test_db_table_for_app_and_class(self):\n name = db_table_for_app_and_class(\n _app_label,\n db_table_for_class(MyModel.__name__),\n site_label=None)\n self.assertEqual(name, self.expected_table_name,\n \"db_table_name error %s\" % name)\n\n def test_db_table(self):\n name = db_table(\n _app_label,\n db_table_for_class(MyModel.__name__),\n site_label=None)\n self.assertEqual(name, self.expected_table_name,\n \"db_table_name error %s\" % name)\n\n\nclass VersionedModelTestCase(TestCase):\n \"\"\"Versioned model unitest class.\n \"\"\"\n def test_str(self):\n expected = 'MyModel object None'\n instance = MyModel()\n self.assertTrue(str(instance).startswith(expected))\n\n\nclass MyNamedModel(NamedModel):\n \"\"\"Sample named model class.\"\"\"\n class Meta(NamedModel.Meta):\n \"\"\"Meta model class.\"\"\"\n app_label = _app_label\n\n\nclass NamedModelTestCase(TestCase):\n \"\"\"Named model unitest class.\n \"\"\"\n def test_str(self):\n myname = 'myname'\n instance = MyNamedModel(name=myname)\n self.assertEqual(str(instance), myname, \"invalid str result\")\n","repo_name":"ajaniv/django-core-utils","sub_path":"django_core_utils/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"40616184865","text":"#!/usr/bin/env python\nimport sys, os\n\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../..\"))\nfrom pika_demo._base import mq_connection\n\n\ndef main():\n connection = mq_connection.get_mq_connection()\n channel = connection.channel()\n\n # 配置exchange 支持通过routing_key来配置绑定关系\n channel.exchange_declare(exchange='direct_logs', exchange_type='direct')\n\n routing_key = sys.argv[1] if len(sys.argv) > 1 else 'info'\n message = ' '.join(sys.argv[2:]) or 'Hello World!'\n # 找到对应的exchange,并让其使用routing_key来找到绑定的queue并推送消息\n channel.basic_publish(exchange='direct_logs', routing_key=routing_key, body=message)\n print(\" [x] Sent %r\" % message)\n\n # 关闭连接\n connection.close()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Constellat/rabbitmq-python-demo","sub_path":"pika_demo/04_routing/emit_log_direct.py","file_name":"emit_log_direct.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"10645310344","text":"\"\"\"本脚本是用来从声音(.wav)中提取mfcc特征并将数据((299*13*count),count是wav文件数),并存入二进制文件中,说明:数字是double类型不是float;\"\"\"\r\n\r\nimport scipy.io.wavfile as wav\r\nimport matplotlib.pylab as plt\r\nfrom python_speech_features import mfcc\r\nimport operator\r\nfrom functools import reduce\r\nimport os\r\nimport struct\r\n\r\nWav_input_dir = ['MADE_DATASETS/Data_wav_trainsets_Normal/', 'MADE_DATASETS/Data_wav_trainsets_Abnormal/',\r\n 'MADE_DATASETS/Data_wav_testsets_Normal/', 'MADE_DATASETS/Data_wav_testsets_Abnormal/']\r\nlist_root_dir = Wav_input_dir\r\nBinary_output_dir = \"MADE_DATASETS/Data_Binary\"\r\nclass Wav_to_Binary:\r\n def __init__(self):\r\n self.Binary_output_dir = Binary_output_dir\r\n self.list_root_dir = list_root_dir\r\n self.Wav_input_dir = Wav_input_dir\r\n self.Binary_output_dir = Binary_output_dir\r\n @staticmethod\r\n def Binary(Wav_input_dir,Binary_name,Binary_output_dir):\r\n # 检查/创建 将要生成的二进制文件上级目录(在哪个文件夹下)\r\n pathdir_bigdata = Binary_output_dir #脚本目录下 \"异常_训练集“ 文件夹\r\n b = os.path.exists(pathdir_bigdata)\r\n if b:\r\n print(\"File Exist!\")\r\n else:\r\n os.mkdir(pathdir_bigdata)\r\n filename = Binary_name #二进制文件名\r\n path = Wav_input_dir #获取当前路径(声音文件.wav 输入)\r\n count = 0 #为计算该目录下有多少个wav文件计数\r\n for root,dirs,files in os.walk(path): #遍历统计wav文件数\r\n for each in files:\r\n count += 1 #统计文件夹下文件个数\r\n #print(count)\r\n m = count\r\n list_all = [] #每个299*13=3887 将所有的mfcc数据存储在list_all里\r\n #循环每个声音文件,提取mfcc数据\r\n for i in range(m):\r\n fs, audio = wav.read(path + str(i+1) + \".wav\")\r\n feature_mfcc = mfcc(audio, samplerate=fs)\r\n mfcc_features = feature_mfcc.T\r\n mfcc_features = mfcc_features.tolist()\r\n y = mfcc_features\r\n y_ = reduce(operator.add, y)\r\n #plot梅尔倒谱系数图\r\n # plt.matshow(mfcc_features)\r\n # # plt.title('MFCC')\r\n # # plt.show()\r\n list_all.append(y_)#[:3887]\r\n #由于是[[1,2,3],[4,5,6]...[7,8,9]]类似的格式,需转换成[1,2,3....7,8,9]格式,用reduce函数转换\r\n y_all = reduce(operator.add, list_all)\r\n ##print(y_all[:6])\r\n LONG = len(y_all)\r\n print(LONG)\r\n #循环list里的每一个元素写入\r\n fid = open(pathdir_bigdata + \"/\" + filename, 'wb') #创建写入文件(二进制文件)\r\n for n in range(LONG):\r\n data_bin_images = struct.pack('>d', y_all[n])\r\n fid.write(data_bin_images)\r\n fid.close()\r\n return m\r\n\r\n @staticmethod\r\n def pramaters(dir,wav_nameber_pramater):\r\n file_handle = open(dir, mode='w')\r\n file_handle.write(str(wav_nameber_pramater))\r\n file_handle.close()\r\n\r\n def Main(self):\r\n for lis in list_root_dir:\r\n #print(list_root_dir[:])\r\n if (list_root_dir.index(lis) + 1) == 1:\r\n filename = \"Binary_train_normal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir+'/'+filename+'.txt',self.Binary(lis,filename,Binary_output_dir))\r\n\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 2:\r\n filename = \"Binary_train_abnormal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 3:\r\n filename = \"Binary_test_normal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n if (list_root_dir.index(lis) + 1) == 4:\r\n filename = \"Binary_test_abnormal\"\r\n #self.Binary(lis,filename,Binary_output_dir)\r\n self.pramaters(Binary_output_dir + '/' + filename + '.txt',\r\n self.Binary(lis, filename, Binary_output_dir))\r\n else:\r\n pass\r\n\r\n\r\n","repo_name":"Diting-li/DITI_github.io","sub_path":"CNN_AUDIO/MADE_DATASETS/wav_to_Biary.py","file_name":"wav_to_Biary.py","file_ext":"py","file_size_in_byte":4670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"6504633769","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"hypertuner\",\n version=\"0.0.1\",\n author=\"Klemen Kotar, Dian Niu\",\n author_email=\"klemen@cs.washington.edu, dian.niu.11@gmail.com\",\n description=\"A library for passing arguments and graphing with HyperTuner\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/hypertuner/hypertuner-pythonlib\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=[\n 'torch>=1.0.0',\n ]\n)\n","repo_name":"hypertuner/hypertuner-pythonlib","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"9359264495","text":"# -*- coding: utf-8 -*-\r\nimport pygame\r\nimport sys\r\nfrom pygame.locals import QUIT,KEYDOWN,K_LEFT,K_a,K_UP,K_w,K_RIGHT,K_d,K_DOWN,K_s,K_ESCAPE,K_r\r\nfrom os.path import abspath,join\r\nfrom random import choice,randint as random\r\nfrom time import sleep\r\nimport pickle\r\nfrom itertools import count\r\nimport numpy as np\r\n\r\nLINE_LENGTH=4\r\n\r\nIMAGE_NUMBER=13\r\n\r\nclass LastStepException(Exception):\r\n pass\r\nclass QuitException(Exception):\r\n pass\r\nclass GetBackException(Exception):\r\n pass\r\n\r\n\r\nclass _loadsave(object):\r\n @classmethod\r\n def load(cls):\r\n try:\r\n with open(cls.filename,'rb') as file:\r\n return pickle.load(file)\r\n except:\r\n return cls.new()\r\n \r\n def save(self):\r\n with open(self.filename,'wb') as file:\r\n pickle.dump(self,file)\r\n\r\n##### - - - - - score - - - - - #####\r\n\r\nclass point(_loadsave):\r\n filename='point.sxm'\r\n class _subtype():\r\n def __init__(self):\r\n self.actual=0\r\n self.highest=0\r\n def __getstate__(self):\r\n return self.actual,self.highest\r\n def __setstate__(self,state):\r\n self.actual=state[0]\r\n self.highest=state[1]\r\n @classmethod\r\n def new(cls):\r\n print('new')\r\n self=object.__new__(cls)\r\n self._data={LINE_LENGTH:cls._subtype()}\r\n return self\r\n \r\n def __init__(self):\r\n self._data={LINE_LENGTH:self._subtype()}\r\n\r\n def __getstate__(self):\r\n return self._data\r\n def __setstate__(self,state):\r\n self._data=state\r\n \r\n def get_actual(self):\r\n try:\r\n return self._data[LINE_LENGTH].actual\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n return 0\r\n def set_actual(self,value):\r\n try:\r\n obj=self._data[LINE_LENGTH]\r\n except KeyError:\r\n obj=self._subtype()\r\n self._data[LINE_LENGTH]=obj\r\n obj.actual=value\r\n if value>obj.highest:\r\n obj.highest=value\r\n self.save()\r\n def del_actual(self):\r\n try:\r\n self._data[LINE_LENGTH].actual=0\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n self.save()\r\n def get_highest(self):\r\n try:\r\n return self._data[LINE_LENGTH].highest\r\n except KeyError:\r\n self._data={LINE_LENGTH:self._subtype()}\r\n return 0\r\n \r\n actual=property(get_actual,set_actual,del_actual)\r\n highest=property(get_highest,None,None)\r\n del get_actual,set_actual,del_actual,get_highest\r\n \r\n##### - - - - - pygame - - - - - #####\r\n \r\npygame.init()\r\n\r\nFONT_GENERAL=pygame.font.Font(None,24)\r\nFONT_BIG=pygame.font.SysFont(\"comicsansms\",60)\r\nFONT_COLOR=(0,0,0)\r\n\r\nclass score(pygame.sprite.Sprite):\r\n def __init__(self,x,y):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.update()\r\n self.rect=self.image.get_rect().move(x,y)\r\n \r\nclass score_actual(score):\r\n def update(self):\r\n self.image=FONT_GENERAL.render('Points: '+str(POINT.actual),0,FONT_COLOR)\r\n\r\n \r\nclass score_highest(score):\r\n def update(self):\r\n self.image=FONT_GENERAL.render('Highest: '+str(POINT.highest),0,FONT_COLOR)\r\n\r\nclass large_text(pygame.sprite.Sprite):\r\n def __init__(self,x,y,text):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image=FONT_BIG.render(text,0,FONT_COLOR)\r\n size=self.image.get_size()\r\n self.rect=self.image.get_rect().move(x-size[0]//2,y-size[1]//2)\r\n\r\nclass button(pygame.sprite.Sprite):\r\n _passive_color=(0,200,0)\r\n _active_color=(0,255,0)\r\n def __init__(self,coords,command):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.x1=coords[0]\r\n self.y1=coords[1]\r\n self.x2=coords[2]\r\n self.y2=coords[3]\r\n self.state=False\r\n self.command=command\r\n self.image=pygame.Surface([coords[2]-coords[0],coords[3]-coords[1]])\r\n self.rect=self.image.get_rect().move(coords[0],coords[1])\r\n self.update()\r\n def update(self):\r\n mouse=pygame.mouse.get_pos()\r\n click=pygame.mouse.get_pressed()\r\n if self.x10:\r\n while indexend:\r\n buffer[index]=buffer[index+step]\r\n index+=step\r\n buffer[index]=0\r\n self._line_length-=1\r\n def __repr__(self):\r\n return it_con(self)\r\n __str__=__repr__\r\n def __iter__(self):\r\n return _data_line_iterator(self)\r\n def __reversed__(self):\r\n return _data_line_reversed_iterator(self)\r\n def copy(self):\r\n return np.fromiter(self,np.uint32)\r\n def __eq__(self,other):\r\n ln_self=self._line_length\r\n ln_other=len(other)\r\n index=0\r\n if ln_selfln_other:\r\n for index in range(ln_other):\r\n if self[index]!=other[index]:\r\n return False\r\n for index in range(index+1,ln_self):\r\n if self[index]:\r\n return False\r\n else:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return False\r\n return True\r\n def __ne__(self,other):\r\n ln_self=self._line_length\r\n ln_other=len(other)\r\n index=0\r\n if ln_selfln_other:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return True\r\n for index in range(index+1,ln_self):\r\n if self[index]:\r\n return True\r\n else:\r\n for index in range(ln_self):\r\n if self[index]!=other[index]:\r\n return True\r\n return False\r\n \r\ndef _data_line_iterator(parent):\r\n buffer=parent._buffer\r\n for index in range(parent._start,parent._start+parent._step*parent._line_length,parent._step):\r\n yield buffer[index]\r\n \r\ndef _data_line_reversed_iterator(parent):\r\n buffer=parent._buffer\r\n for index in range(parent._start+parent._step*(parent._line_length-1),parent._start-parent._step,-parent._step):\r\n yield buffer[index]\r\n \r\ndef _data_iterator(parent):\r\n line_length=parent._line_length\r\n buffer=parent._buffer\r\n if parent._aim<2:\r\n if parent._aim==0:\r\n for index in range(0,parent._size,line_length):\r\n yield _data_line_acces(buffer,index,1,line_length)\r\n else:\r\n for index in range(0,line_length,1):\r\n yield _data_line_acces(buffer,index,line_length,line_length)\r\n else:\r\n if parent._aim==2:\r\n for index in range(line_length-1,parent._size,line_length):\r\n yield _data_line_acces(buffer,index,-1,line_length)\r\n else:\r\n for index in range(parent._size-line_length,parent._size,1):\r\n yield _data_line_acces(buffer,index,-line_length,line_length)\r\n\r\ndef _data_reversed_iterator(parent):\r\n line_length=parent._line_length\r\n buffer=parent._buffer\r\n if parent._aim<2:\r\n if parent._aim==0:\r\n for index in range(parent._size-line_length,-line_length,-line_length):\r\n yield _data_line_acces(buffer,index,1,line_length)\r\n else:\r\n for index in range(line_length-1,-1,-1):\r\n yield _data_line_acces(buffer,index,line_length,line_length)\r\n else:\r\n if parent._aim==2:\r\n for index in range(parent._size-1,-1,-line_length):\r\n yield _data_line_acces(buffer,index,-1,line_length)\r\n else:\r\n for index in range(parent._size-1,parent._size-line_length-1,-1):\r\n yield _data_line_acces(buffer,index,-line_length,line_length) \r\n\r\n##### - - - - - core - - - - - #####\r\n \r\nclass core(data_object,_loadsave):\r\n filename='save.sxm'\r\n @classmethod\r\n def new(cls):\r\n POINT.actual=0\r\n self=cls(LINE_LENGTH)\r\n self.create_random()\r\n self.create_random()\r\n self.save()\r\n return self\r\n \r\n def create_random(self):\r\n buffer=self._buffer\r\n counter=-1\r\n for element in buffer:\r\n if not element:\r\n counter+=1\r\n if counter<0:\r\n return\r\n counter=random(0,counter)\r\n for index in count():\r\n if not buffer[index]:\r\n if counter:\r\n counter-=1\r\n else:\r\n buffer[index]=random(4,8)>>2\r\n break\r\n \r\n def push_lines(self):\r\n counter=self._line_length\r\n for line in self:\r\n linecopy=line.copy()\r\n for index,value in zip(reversed(range(self._line_length)),reversed(line)):\r\n if not value:\r\n del line[index]\r\n try:\r\n for index in count():\r\n if line[index]==line[index+1]:\r\n POINT.actual+=1<> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n self.spi.write(bytes([0x03] + toWrite))\n data = self.spi.read(size)\n self.cs.value(1)\n return data\n\n # Written for the 0x02 command (PP) (writing)\n def page_program(self, addr, data):\n # enable writing\n self.cs.value(0)\n self.spi.write(bytes([0x06]))\n self.cs.value(1)\n\n # check read status register\n self.cs.value(0)\n self.spi.write(bytes([0x05]))\n read = self.spi.read(1)[0]\n self.cs.value(1)\n\n # check WEL (bit of status register)\n mask = 0b00000010\n read = int(read) & mask\n read = read >> 1\n\n # writing data\n if read == 1:\n lst = []\n toWrite = [addr >> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n for i in range(len(data)):\n lst.append(ord(data[i]))\n self.cs.value(0)\n self.spi.write(bytes([0x02] + toWrite + lst))\n self.cs.value(1)\n return 1\n else:\n self.cs.value(1)\n return 0\n\n # Written for the 0x20 (SE) (erase)\n def sector_erase(self, addr):\n # enable writing\n self.cs.value(0)\n self.spi.write(bytes([0x06]))\n self.cs.value(1)\n\n # check read status register\n self.cs.value(0)\n self.spi.write(bytes([0x05]))\n read = self.spi.read(1)[0]\n self.cs.value(1)\n\n # check WEL (bit of status register)\n mask = 0b00000010\n read = int(read) & mask\n read = read >> 1\n\n # erases data\n if read == 1:\n toWrite = [addr >> 16 & 0xFF, addr >> 8 & 0xFF, addr & 0xFF]\n self.cs.value(0)\n self.spi.write(bytes([0x20] + toWrite))\n self.cs.value(1)\n return 1\n else:\n self.cs.value(1)\n return 0\n\n","repo_name":"Marcano-Pannuto-ERSP/flash-testing","sub_path":"flash.py","file_name":"flash.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"36117601026","text":"#!/usr/bin/python3\n\nfrom .cache_utils import rebuild_paste_cache, rebuild_paste_string_cache\nfrom .binaryedge_utils import update_host_ports, update_honeypot_activity, update_torrent_status, update_domain_leaks, update_email_leaks, find_c2_hosts\nfrom .feed_utils import check_feeds\nfrom .log_utils import get_module_logger\nfrom .shodan_utils import get_shodan_scan_data\nfrom .twitter_utils import check_twitter\nfrom .urlscan_utils import check_urlscan, find_bad_refs\nfrom .virustotal_utils import update_vt_ip_activity, update_vt_domain_activity, enrich_country_hosts\nfrom django.contrib.auth.models import Group, Permission\nfrom django.utils import timezone\nfrom web.models import Host, Domain, Email, Organisation, OpenPort, Setting\n\nimport time\n\nlogger = get_module_logger(__name__)\n\ndef process_host(host, is_weekly):\n logger.info('Processing host: {0}'.format(host.address))\n\n Host.objects.filter(pk=host.pk).update(lastscanned=timezone.now())\n\n get_shodan_scan_data(host)\n update_vt_ip_activity(host)\n\n if is_weekly:\n logger.info('Clearing historic port data...')\n Host.objects.filter(pk=host.pk).update(lastscanned=timezone.now(),torrentdetected=False)\n OpenPort.objects.filter(host=host).delete()\n logger.info('Done.')\n\n update_host_ports(host)\n update_honeypot_activity(host)\n update_torrent_status(host)\n\n logger.info('Host complete.')\n\n\ndef process_domain(domain, is_weekly):\n logger.info('Processing domain: {0}'.format(domain.domain))\n\n Domain.objects.filter(pk=domain.pk).update(lastscanned=timezone.now())\n\n find_bad_refs(domain)\n update_vt_domain_activity(domain)\n\n if is_weekly:\n update_domain_leaks(domain)\n\n logger.info('Domain complete.')\n\n\ndef process_email(email):\n logger.info('Processing email: {0}'.format(email.email))\n\n Email.objects.filter(pk=email.pk).update(lastscanned=timezone.now())\n\n update_email_leaks(email)\n\n logger.info('Email complete.')\n\ndef apply_group_permissions(group):\n permission_list = ['Can view compromise', 'Can view country hit', 'Can view domain', 'Can view email', 'Can view host', 'Can view open port', 'Can view organisation', 'Can view paste', 'Can view port cve', 'Can view sensor hit']\n\n for permission_name in permission_list:\n logger.info('Providing {0} permission: {1}'.format(group.name, permission_name))\n\n permission = Permission.objects.get(name=permission_name)\n group.permissions.add(permission)\n\n\ndef check_orgs():\n group_list = list(Group.objects.all().values_list('name', flat=True))\n\n for org in Organisation.objects.all():\n if not org.name in group_list:\n logger.info('Loading new organisation: {0}'.format(org.name))\n\n new_group, created = Group.objects.get_or_create(name=org.name)\n\n if created:\n apply_group_permissions(new_group)\n\n logger.info('Organisation group created. Loading initial data...')\n\n weekly_operations(org)\n\n\ndef refresh_entities(organisation):\n logger.info('Refreshing entity data...')\n\n for address in organisation.addresses:\n if not Host.objects.filter(address=address).exists():\n logger.info('Adding new host: {0}'.format(address))\n new_host = Host(added=timezone.now(), address=address, organisation=organisation)\n new_host.save()\n\n for address in Host.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(addresses__contains=[address.address]):\n logger.info('Removing old host: {0}'.format(address.address))\n address.delete()\n\n for domain in organisation.domains:\n if not Domain.objects.filter(domain=domain).exists():\n logger.info('Adding new domain: {0}'.format(domain))\n new_domain = Domain(added=timezone.now(), domain=domain, organisation=organisation)\n new_domain.save()\n\n for domain in Domain.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(domains__contains=[domain.domain]):\n logger.info('Removing old domain: {0}'.format(domain.domain))\n domain.delete()\n\n for email in organisation.emails:\n if not Email.objects.filter(email=email).exists():\n logger.info('Adding new email: {0}'.format(email))\n new_email = Email(added=timezone.now(), email=email, organisation=organisation)\n new_email.save()\n\n for email in Email.objects.filter(organisation=organisation):\n if not Organisation.objects.filter(emails__contains=[email.email]):\n logger.info('Removing old email: {0}'.format(email.email))\n email.delete()\n\n logger.info('Refresh complete.')\n\n\ndef do_country_operations():\n logger.info('Running country operations...')\n\n for organisation in Organisation.objects.all():\n refresh_entities(organisation)\n\n check_feeds()\n check_twitter()\n check_urlscan()\n enrich_country_hosts()\n find_c2_hosts()\n\n logger.info('Country operations complete.')\n\n\ndef organisation_operations(organisation, is_weekly):\n refresh_entities(organisation)\n\n for host in Host.objects.filter(organisation=organisation):\n process_host(host, is_weekly)\n\n for domain in Domain.objects.filter(organisation=organisation):\n process_domain(domain, is_weekly)\n\n if is_weekly:\n for email in Email.objects.filter(organisation=organisation):\n process_email(email)\n\n\ndef do_organisation_operations(is_weekly):\n logger.info('Running organisation operations...')\n\n for organisation in Organisation.objects.all():\n logger.info('Beginning organisation: {0}'.format(organisation.name))\n\n organisation_operations(organisation, is_weekly)\n\n logger.info('Organisation operations complete.')\n\n\ndef start_core():\n logger.info('Starting core worker...')\n\n run_times = Setting.objects.get(name='Core Run Times').value1.split(',')\n weekly_days = Setting.objects.get(name='Core Weekly Tasks Days').value1.split(',')\n\n logger.info('Daily tasks will run at: {0}'.format(str(run_times)))\n logger.info('Weekly tasks will run on {0} at: {1}'.format(str(weekly_days), str(run_times[0])))\n\n while True:\n if time.strftime('%H:%M') in run_times:\n do_country_operations()\n\n if time.strftime('%H:%M') == run_times[0] and time.strftime('%A').lower() in (day.lower() for day in weekly_days):\n do_organisation_operations(True)\n\n else:\n do_organisation_operations(False)\n\n time.sleep(60)\n\n logger.info('Core worker finished.')\n\n\ndef start_helper():\n logger.info('Starting helper...')\n\n rebuild_paste_cache()\n rebuild_paste_string_cache()\n\n while True:\n check_orgs()\n\n if time.strftime('%M') == '00':\n rebuild_paste_string_cache()\n\n time.sleep(60)\n\n logger.info('Helper finished.')\n","repo_name":"phage-nz/observer","sub_path":"core/core_utils.py","file_name":"core_utils.py","file_ext":"py","file_size_in_byte":6965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"40191893860","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"myprocess\")\nprocess.TFileService=cms.Service(\"TFileService\", fileName=cms.string('JERplots.root'))\n\n##-------------------- Communicate with the DB -----------------------\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc')\n\n##-------------------- Define the source ----------------------------\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(10)\n)\n\nfrom PhysicsTools.PatAlgos.patInputFiles_cff import filesRelValTTbarPileUpMINIAODSIM\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = filesRelValTTbarPileUpMINIAODSIM\n)\n\n##-------------------- User analyzer --------------------------------\nprocess.demo = cms.EDAnalyzer('JetResolutionDemo',\n jets = cms.InputTag('slimmedJets'),\n rho = cms.InputTag('fixedGridRhoAll'),\n\n payload = cms.string('AK4PFchs'),\n\n resolutionsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer15_V0_MC_JER_AK4PFchs.txt'),\n scaleFactorsFile = cms.FileInPath('CondFormats/JetMETObjects/data/Summer12_V1_MC_JER_SF_AK5PFchs.txt'),\n\n debug = cms.untracked.bool(False),\n useCondDB = cms.untracked.bool(False)\n)\n\nprocess.p = cms.Path(process.demo)\n\n","repo_name":"cms-sw/cmssw","sub_path":"JetMETCorrections/Modules/test/JetResolutionDemo_cfg.py","file_name":"JetResolutionDemo_cfg.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"}
+{"seq_id":"36945835853","text":"import turtle\nimport time\nscreen = turtle.Screen()\nscreen.bgcolor(\"blue\")\npen = turtle.Pen()\npen.color(\"black\")\npen.speed(20)\ni = 0\nwhile(i<200):\n pen.forward(2*i)\n pen.left(i)\n i = i+1\ntime.sleep(2)\n","repo_name":"Dileepadari/Turtle_projects","sub_path":"corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"20432245879","text":"import sys\nimport os\nimport datetime\n\n\n# 工程化.\nfrom pathlib import Path\nFILE = Path(__file__).resolve() # 绝对路径.\nROOT = FILE.parents[0] # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n sys.path.append(str(ROOT)) # add ROOT to PATH\nos.chdir(ROOT) # runtime path in current path. \n\nprint(\"run on:\", ROOT)\n\n\n# 允许的文件类型.\nIMAGE_FILE = ['jpg','jpeg','png']\nVIDEO_FILE = ['mp4','avi']\n\n# 0: stop, 1: open detective \nSTOP = 0\n\nSAVE_PATH = \"./file\"\nLOG_PATH = \"./logs\"\n\n\n\n","repo_name":"WakingHours-GitHub/ObjectDetection-Platform","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"}
+{"seq_id":"25780205289","text":"from django.http import HttpResponse\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import status\nfrom .models import Movie, Actor\nfrom .serializers import MovieSerializer, ActorSerializer\n# Create your views here.\n\n\ndef Home(request):\n context = {}\n return HttpResponse('Hello')\n\n\nclass MovieList(APIView):\n \"\"\"\n List all movies \n \"\"\"\n\n def get(self, request):\n movies = Movie.objects.all()\n serializer = MovieSerializer(movies, many=True)\n return Response(serializer.data)\n\n def get_movie(self, pk):\n try:\n return Movie.objects.get(pk=pk)\n\n except Movie.DoesNotExist:\n raise Http404\n\n def put(self, request):\n movie = self.get_movie(request.data['id'])\n serializer = MovieSerializer(movie, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass ActorList(APIView):\n \"\"\"\n List all the actors \n \"\"\"\n\n def get(self, request):\n actors = Actor.objects.all()\n serializer = ActorSerializer(actors, many=True)\n return Response(serializer.data)\n","repo_name":"Ajay-creator/Movie-Maintanance-App","sub_path":"movie_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"3373489907","text":"#import datapre\n\nfrom csv_utils import CSV\nfrom keras.models import load_model\nimport numpy as np\nimport pandas as pd\n\n\"\"\" df = CSV(\"creditcard.csv\")\nscaled = df.normalized()\nprint(scaled[:5]) \"\"\"\n\n\ndf = CSV(\"sensor_data.csv\")\nprint(df.df.shape)\n\n#df.normalaize()\n\n\n\nmodel = load_model(\"weights/autoencoder.best.hdf5\")\nx,y = df.to_train_test()\npredictions = model.predict(x)\n\nmse = np.mean(np.power(x - predictions, 2), axis=1)\ndf_error = pd.DataFrame({'reconstruction_error': mse}) \nprint(df_error.describe())\noutliers = df_error.index[df_error.reconstruction_error > 0.5].tolist()\nprint(outliers[:10])\n\n","repo_name":"motkeg/Deep-learning","sub_path":"Autoencoder/simple/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"29255916711","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\nfrom lab.environments import LocalEnvironment, MaiaEnvironment\n\nfrom common_setup import IssueConfig, IssueExperiment, is_test_run\n\n\nBENCHMARKS_DIR = os.environ[\"DOWNWARD_BENCHMARKS\"]\nREVISIONS = [\"issue591-base\", \"issue591-v1\"]\nCONFIGS = [\n IssueConfig(\n \"lazy_greedy_{}\".format(heuristic),\n [\"--heuristic\", \"h={}()\".format(heuristic),\n \"--search\", \"lazy_greedy(h, preferred=h)\"])\n for heuristic in [\"add\", \"cea\", \"cg\", \"ff\"]\n]\nSUITE = [\n 'barman-sat14-strips', 'cavediving-14-adl', 'childsnack-sat14-strips',\n 'citycar-sat14-adl', 'floortile-sat14-strips', 'ged-sat14-strips',\n 'hiking-sat14-strips', 'maintenance-sat14-adl',\n 'openstacks-sat14-strips', 'parking-sat14-strips',\n 'tetris-sat14-strips', 'thoughtful-sat14-strips',\n 'transport-sat14-strips', 'visitall-sat14-strips']\nENVIRONMENT = MaiaEnvironment(\n priority=0, email=\"jendrik.seipp@unibas.ch\")\n\nif is_test_run():\n SUITE = IssueExperiment.DEFAULT_TEST_SUITE\n ENVIRONMENT = LocalEnvironment(processes=1)\n\nexp = IssueExperiment(\n revisions=REVISIONS,\n configs=CONFIGS,\n environment=ENVIRONMENT,\n)\nexp.add_suite(BENCHMARKS_DIR, SUITE)\n\nexp.add_absolute_report_step()\nexp.add_comparison_table_step()\nexp.add_scatter_plot_step(attributes=[\"total_time\"])\n\nexp()\n","repo_name":"aig-upf/automated-programming-framework","sub_path":"PLANNERS/fast-downward/experiments/issue591/v1-sat.py","file_name":"v1-sat.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"50"}
+{"seq_id":"15262122448","text":"from flask import Blueprint, request, abort, jsonify, make_response\nimport configparser\nfrom http import HTTPStatus\nimport logging\n\nfrom spatialapi.manager.spatial_manager import SpatialManager\nfrom spatialapi.utils import json_error\n\nlogger = logging.getLogger(__name__)\n\nspatial_search_hubmap_id_blueprint = Blueprint('spatial_search_hubmap_id_blueprint', __name__)\n\n\n@spatial_search_hubmap_id_blueprint.route('/spatial-search/hubmap-id', methods=['POST'])\ndef spatial_search_hubmap_id():\n request_dict: dict = request.get_json()\n logger.info(f'spatial_search_hubmap_id: POST /spatial-search/hubmap-id {request_dict}')\n request_validation(request_dict)\n\n config = configparser.ConfigParser()\n app_properties: str = 'resources/app.properties'\n logger.info(f'spatial_search: Reading properties file: {app_properties}')\n config.read(app_properties)\n spatial_manager = SpatialManager(config)\n\n cell_type_name: str = None\n if 'cell_type' in request_dict:\n cell_type_name = request_dict['cell_type']\n\n results = spatial_manager.find_relative_to_spatial_entry_iri_within_radius_from_hubmap_id(\n request_dict['target'],\n request_dict['radius'],\n request_dict['hubmap_id'],\n cell_type_name\n )\n\n response = make_response(jsonify(hubmap_ids=results), HTTPStatus.OK)\n response.headers[\"Content-Type\"] = \"application/json\"\n return response\n\n\ndef request_validation(request_dict: dict) -> None:\n int_instances_keys: tuple = (\"radius\", )\n required_request_keys: tuple = int_instances_keys + (\"target\", \"hubmap_id\")\n optional_request_keys: tuple = (\"cell_type\", )\n all_request_keys: tuple = required_request_keys + optional_request_keys\n for k in request_dict.keys():\n if k not in all_request_keys:\n abort(json_error(f\"Request Body: can only have the following attributes {all_request_keys}\",\n HTTPStatus.BAD_REQUEST))\n if not all(key in request_dict for key in required_request_keys):\n abort(json_error(f\"Request Body: must have the following required attributes {required_request_keys}\", HTTPStatus.BAD_REQUEST))\n if not all(isinstance(value, (int, float)) for value in [request_dict[k] for k in int_instances_keys]):\n abort(json_error(f\"Request Body: the following attributes {int_instances_keys} must have numeric values\", HTTPStatus.BAD_REQUEST))\n target_values: list = ['VHMale', 'VHFemale']\n if not request_dict['target'] in target_values:\n abort(json_error(f\"Request Body: the attribute 'target' must be one of: {', '.join(target_values)}\", HTTPStatus.BAD_REQUEST))\n","repo_name":"hubmapconsortium/spatial-api","sub_path":"server/spatialapi/routes/spatial_search_hubmap_id/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"35165497005","text":"'''\n[BOJ] 1916 최소비용 구하기\n나의 idea : 특정 도시로 가는 최단경로(버스) 구하기 >> 다익스트라 알고리즘\n'''\nimport sys\nimport heapq\ninput = sys.stdin.readline\nINF = int(1e9)\n\nn = int(input()) #도시의 갯수 - 노드\nm = int(input()) #버스의 개수 - 간선\n\ngraph = [[] for i in range(n+1)]\ndistance = [INF]*(n+1)\nfor _ in range(m):\n a,b,c = map(int, input().split())\n graph[a].append((b,c))\nstart, end = map(int, input().split())\ndef dijkstra(start):\n q = [] #(거리, 노드)\n distance[start] = 0\n heapq.heappush(q,(0,start))\n while q:\n dist, now = heapq.heappop(q)\n #이미 처리된 노드\n if distance[now] < dist:\n continue\n for elem in graph[now]:\n cost = dist + elem[1]\n if cost < distance[elem[0]]:\n distance[elem[0]] = cost\n heapq.heappush(q, (cost, elem[0]))\ndijkstra(start)\nprint(distance[end])","repo_name":"LikeLionBE-Algorithm/Algorithm","sub_path":"김희정/7. 최단경로/3_1916.py","file_name":"3_1916.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"14456604642","text":"#!/usr/bin/env python2\nfor T in range(1, int(raw_input()) + 1):\n N, M = list(map(int, raw_input().split()))\n # print(N, M)\n semut = [i for i in range(1, N+1)]\n # print(semut)\n depth = list(map(int, raw_input().split()))\n # print(depth)\n for i in depth:\n # semut = semut[:i] + semut[i+1:]\n semut = semut[i:] + semut[:i][::-1]\n #print(semut)\n print('Kasus #{}: {}'.format(T, ' '.join(map(str, semut))))","repo_name":"IEP/submissions","sub_path":"JOINTS 2018/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"41726630283","text":"import re\nimport unittest\n\nfrom blinkpy.presubmit import audit_non_blink_usage\n\n\nclass TestAuditNonBlinkUsageTest(unittest.TestCase):\n # This is not great but it allows us to check that something is a regexp.\n _REGEXP_CLASS = re.compile(r\"foo\").__class__\n\n def test_valid_compiled_config(self):\n # We need to test this protected data.\n # pylint: disable=W0212\n for entry in audit_non_blink_usage._COMPILED_CONFIG:\n for path in entry['paths']:\n self.assertIsInstance(path, str)\n if 'allowed' in entry:\n self.assertIsInstance(entry['allowed'], self._REGEXP_CLASS)\n if 'disallowed' in entry:\n self.assertIsInstance(entry['disallowed'], self._REGEXP_CLASS)\n for match, advice, warning in entry.get('advice', []):\n self.assertIsInstance(match, self._REGEXP_CLASS)\n self.assertIsInstance(advice, str)\n\n def test_for_special_cases(self):\n for entry in audit_non_blink_usage._COMPILED_CONFIG:\n if entry['paths'] == ['third_party/blink/renderer/']:\n check_list = [\n {'type': 'url::mojom::Origin', 'allowed': False},\n {'type': '::media::mojom::InterfaceFactory', 'allowed': False},\n {'type': 'Hogenetwork::mojom::URLLoaderFactory', 'allowed': False},\n {'type': 'url::mojom::blink::Origin', 'allowed': True},\n {'type': '::media::mojom::blink::InterfaceFactory', 'allowed': True},\n {'type': 'network::mojom::URLLoaderFactory', 'allowed': True},\n {'type': '::network::mojom::URLLoaderFactory', 'allowed': True},\n ]\n for item in check_list:\n if item['allowed']:\n self.assertIsNone(re.match(entry['disallowed'], item['type']))\n elif not item['allowed']:\n self.assertIsNotNone(re.match(entry['disallowed'], item['type']))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"RSATom/Qt","sub_path":"qtwebengine/src/3rdparty/chromium/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage_test.py","file_name":"audit_non_blink_usage_test.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":50,"dataset":"github-code","pt":"50"}
+{"seq_id":"7128003612","text":"from django.contrib.auth import get_user_model\nfrom django_tenants.utils import get_public_schema_name, schema_context\nfrom rest_framework import status, viewsets\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.authtoken.views import ObtainAuthToken\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\n\nfrom users.serializers import TenantUserSerializer\n\n\nclass CustomAuthToken(ObtainAuthToken):\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(\n data=request.data, context={\"request\": request}\n )\n serializer.is_valid(raise_exception=True)\n user = serializer.validated_data[\"user\"]\n token, _ = Token.objects.get_or_create(user=user)\n tenants = [\n {\"uuid\": v[\"uuid\"], \"name\": v[\"name\"]} for v in user.tenants.values()\n ]\n userdata = {\n \"name\": user.name,\n \"email\": user.email,\n \"tenants\": tenants,\n }\n return Response({\"token\": token.key, \"user\": userdata})\n\n\nclass TenantUserViewSet(viewsets.ViewSet):\n permission_classes = [AllowAny]\n serializer_class = TenantUserSerializer\n\n def create(self, request):\n tenantuser = request.data or {}\n\n with schema_context(get_public_schema_name()):\n user = (\n get_user_model()\n .objects.filter(email__exact=tenantuser[\"email\"])\n .first()\n )\n\n if not user:\n serializer = self.serializer_class(data=tenantuser)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n user = get_user_model().objects.get(email__exact=tenantuser[\"email\"])\n \n # Just for example\n user.is_active = True\n user.is_verified = True\n user.save()\n \n return Response(\"OK\", status=status.HTTP_201_CREATED)\n\n return Response(\"ERROR\", status=status.HTTP_400_BAD_REQUEST)\n\n def update(self, request, pk):\n serializer = self.serializer_class(\n request.user, data=request.data, partial=True\n )\n serializer.is_valid(raise_exception=True)\n serializer.save()\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def retrieve(self, request, pk):\n return Response(status=status.HTTP_200_OK)\n\n def list(self, request):\n users = get_user_model().objects.all()\n serializer = self.serializer_class(users, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk):\n pass\n","repo_name":"ivcmartello/tenant_api","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"8519675108","text":"from django.urls import path\nfrom . import views\n\napp_name = 'core'\n\nurlpatterns = [\n path('movies', views.MovieList.as_view(), name='movie_list'),\n path('top/ten/movies', views.TopMovies.as_view(), name='top_ten_movie'),\n path('movie/', views.MovieDetail.as_view(), name='movie_detail'),\n path('movie/vote//create', views.CreateVote.as_view(), name='create_vote'),\n path('movie/vote//update/', views.UpdateVote.as_view(), name='update_vote'),\n path('movie//upload/image', views.MovieImageUpload.as_view(), name='movie_image_upload')\n]\n\n","repo_name":"henrymbuguak/imdb-movies-django-2-clone","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"74253148316","text":"from django.contrib.auth.models import User\nfrom rest_framework import viewsets, status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom myapp.models import Meal, Rating\nfrom myapp.serializers import MealSerializer, RatingSerializer\n\n\nclass MealViewSet(viewsets.ModelViewSet):\n queryset = Meal.objects.all()\n serializer_class = MealSerializer\n\n @action(methods=['POST'], detail=True)\n def rate_meal(self, request, pk=None):\n if 'stars' in request.data:\n '''\n create or update\n '''\n username = request.data['username']\n user = User.objects.get(username=username)\n meal = Meal.objects.get(id=pk)\n stars = request.data['stars']\n try:\n # update\n rating = Rating.objects.get(user=user.id, meal=meal.id) # meal.id or pk\n rating.stars = stars\n rating.save()\n serializer = RatingSerializer(rating, many=False)\n jason = {\n 'message': 'Meal rate updated',\n 'result': serializer.data\n }\n return Response(jason, status=status.HTTP_200_OK)\n except:\n # create\n rating = Rating.objects.create(stars=stars, meal=meal, user=user)\n serializer = RatingSerializer(rating, many=False)\n jason = {\n 'message': 'Meal rate created',\n 'result': serializer.data\n }\n return Response(jason, status=status.HTTP_200_OK)\n else:\n '''\n send message \n '''\n json = {\n 'message': 'stars not provided'\n }\n return Response(json, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RatingViewSet(viewsets.ModelViewSet):\n queryset = Rating.objects.all()\n serializer_class = RatingSerializer\n","repo_name":"GhaythAli1710/Gh-Rater","sub_path":"myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"27235409215","text":"import sys\ninput = sys.stdin.readline\n\ndef findGW(word):\n wordList = list(word)\n curWord = ''\n wordSet = set()\n for w in wordList:\n if w in wordSet:\n if curWord == w :\n continue\n else:\n return False\n else :\n wordSet.add(w)\n curWord = w\n\n return True\n\ndef main():\n # 입력받을 단어의 개수 입력\n # 입력받은 개수만큼 단어 입력\n qtyWords = int(input().rstrip())\n words = [input().rstrip() for _ in range(qtyWords)]\n qtyGroupWords = 0\n\n # 한 단어씩 검사\n for word in words:\n # if findGroupWord(word) == True:\n if findGW(word) == True:\n qtyGroupWords += 1\n \n print(qtyGroupWords)\n\nmain()\n","repo_name":"goomseo/myBaekjoon","sub_path":"백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py","file_name":"그룹 단어 체커.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"10642746774","text":"from models.users import Feedback\nimport typing\nimport asyncio\nimport aiohttp\nimport math\nimport asyncpg\nimport simplejson as json\nimport aiogram.utils.markdown as md\nimport random\nimport itertools\n\nfrom operator import and_\n\nfrom exceptions import PairAlreadyExists\nfrom models import db, User, Kata, SolvedKata, Chat, MenteeToMentor\nfrom aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton\nfrom datetime import date, datetime\nfrom config import *\nfrom tabulate import tabulate\n\n\nclass UserService:\n\n async def get_or_create(**kwargs):\n user = await User.query.where(User.tg_id == kwargs.get('tg_id')).gino.first()\n if user is None:\n user = await User.create(**kwargs)\n return user, user != None\n\n @classmethod\n async def get_daily_message(cls):\n data = await cls.get_users_stats()\n content = [\"Here is a list of all of our warriors!\",\n \"-----------------------------------\"]\n for num, item in enumerate(data, start=1):\n content.append(md.text(num, '--', item.get('cw_username'),\n '--', item.get('count')))\n return md.text(*content, sep='\\n')\n\n @classmethod\n async def get_users_stats(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n records = await conn.fetch(\"\"\"\n SELECT users.cw_username, COUNT('solved.id')\n FROM solved_katas AS solved\n INNER JOIN users\n ON users.tg_id = solved.user_id\n WHERE solved.kata_id IN (SELECT id FROM katas)\n GROUP BY users.cw_username\n ORDER BY COUNT('solved.id') DESC;\n \"\"\")\n values = [dict(record) for record in records]\n solved = json.loads(json.dumps(values).replace(\"\", \"<\\\\/\"))\n await conn.close()\n return solved\n\n @classmethod\n async def get_missing_katas(cls, user, offset=0):\n conn = await asyncpg.connect(POSTGRES_URI)\n records = await conn.fetch(\"\"\"\n SELECT name, slug\n FROM katas\n WHERE id in (\n SELECT id\n FROM katas\n\n EXCEPT\n\n SELECT kata_id\n FROM solved_katas\n WHERE user_id = $1\n )\n LIMIT 10 OFFSET $2;\n \"\"\", user.id, offset)\n count = await conn.fetchrow(\"\"\"\n SELECT COUNT(*)\n FROM katas\n WHERE id in (\n SELECT id\n FROM katas\n\n EXCEPT\n\n SELECT kata_id\n FROM solved_katas\n WHERE user_id = $1\n );\n \"\"\", user.id)\n await conn.close()\n markup = InlineKeyboardMarkup()\n for r in records:\n btn = InlineKeyboardButton(text=r.get('name'),\n url=f\"{CODEWARS_BASE_KATA_URL}/{r.get('slug')}/\")\n markup.add(btn)\n buttons = []\n if not count.get('count') - offset <= 10:\n buttons.append(InlineKeyboardButton(\n text='Далее', callback_data=f'next_{offset + 10}'))\n if offset > 0:\n buttons.append(InlineKeyboardButton(\n text='Назад', callback_data=f'next_{offset - 10}'))\n if buttons:\n markup.add(*buttons)\n return markup, count.get('count')\n\n async def get_total_pages(user):\n async with aiohttp.ClientSession() as session:\n async with session.get(f'{CODEWARS_BASE_URL}/{user.cw_username}/code-challenges/completed?page=0') as resp:\n resp = await resp.json()\n return resp.get('totalPages')\n\n @classmethod\n async def get_user_solved_katas(cls, user):\n # pages = math.ceil(await cls.get_total_items(user) / 200)\n user = await User.query.where(User.tg_id == user.id).gino.first()\n count = await cls.extract_solved_katas(user)\n return count\n\n async def get_katas(url):\n async with aiohttp.ClientSession() as session:\n async with session.get(url) as resp:\n resp = await resp.json()\n return resp.get('data')\n\n @classmethod\n async def extract_solved_katas(cls, user):\n pages = await cls.get_total_pages(user)\n count = 0\n for page in range(pages):\n url = f\"{CODEWARS_BASE_URL}/{user.cw_username}/code-challenges/completed?page={page}\"\n katas = await cls.get_katas(url)\n for kata in katas:\n instance = await Kata.query.where(Kata.id == kata.get('id')).gino.first()\n exists = await SolvedKata.query.where(and_(SolvedKata.user_id == user.tg_id, SolvedKata.kata_id == kata.get('id'))).gino.first()\n if exists is None and instance is not None:\n await SolvedKata.create(kata_id=instance.id, user_id=user.tg_id)\n count += 1\n return count\n\n @classmethod\n async def extract_solved_katas_in_bulk(cls):\n users = await User.query.gino.all()\n for user in users:\n await cls.extract_solved_katas(user)\n\n\nclass ChatService:\n\n async def get_chat():\n return await Chat.query.limit(1).gino.first()\n\n async def set_chat(chat):\n chat = await Chat.create(id=chat.id, chat_type=chat.type)\n return chat\n\n\nclass MentorService:\n\n model = User\n\n async def make_me_mentor(user):\n instance = await User.query.where(User.tg_id == user.id).gino.first()\n if instance is None:\n await User.create(tg_id=user.id, tg_username=user.username, is_mentor=True)\n else:\n await instance.update(is_mentor=True).apply()\n\n async def get_mentors():\n return await User.query.where(User.is_mentor == True).gino.all()\n\n async def list_mentees():\n return await User.query.where(User.is_mentor == False).gino.all()\n\n async def get_number_of_mentees(mentor: User):\n query = db.text(\n \"\"\"\n SELECT mentor.tg_username AS mentor, COUNT(mentee.tg_id)\n FROM pairs\n INNER JOIN users AS mentor\n ON pairs.mentor_id = mentor.tg_id\n INNER JOIN users AS mentee\n ON pairs.mentee_id = mentee.tg_id\n WHERE mentor.tg_id = :mentor_id AND pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n )\n GROUP BY mentor.tg_username;\n \"\"\"\n )\n data = await db.first(query, mentor_id=mentor.tg_id)\n return data.count if data is not None else 0\n\n @classmethod\n async def get_random_mentor(cls):\n mentors = await cls.get_mentors()\n query = db.text(\"\"\"\n SELECT COUNT(*)\n FROM users\n WHERE is_mentor = false;\n \"\"\")\n total = await db.first(query)\n weights = [\n abs(total.count - await cls.get_number_of_mentees(mentor)) for mentor in mentors]\n return random.choices(mentors, weights).pop()\n\n @classmethod\n async def get_random_mentee(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n query = await conn.fetch(\"\"\"\n SELECT tg_id\n FROM users\n WHERE users.tg_id not in (SELECT mentee_id FROM pairs WHERE created_at::date = (SELECT MAX(created_at::date) FROM pairs)) AND is_mentor = false;\n \"\"\")\n await conn.close()\n mentees = [record.get('tg_id') for record in query]\n return await User.query.where(User.tg_id == random.choice(mentees)).gino.first()\n\n @classmethod\n async def find_pair(cls, mentor: User, mentee: User):\n return await MenteeToMentor.query.where(MenteeToMentor.mentor_id == mentor.tg_id and MenteeToMentor.mentee_id == mentee.tg_id).gino.first()\n\n @classmethod\n async def delete_previous_pairs(cls):\n max_date = await db.func.max(MenteeToMentor.created_at).gino.scalar()\n await MenteeToMentor.delete.where(db.cast(MenteeToMentor.created_at, db.Date) == max_date).gino.status()\n\n @classmethod\n async def is_mentor_available(cls, mentor: User):\n today = datetime.now().date()\n return await MenteeToMentor.query.where(db.cast(MenteeToMentor.created_at, db.Date) == today and MenteeToMentor.mentor_id == mentor.tg_id).gino.first() is None\n\n @staticmethod\n async def number_of_available_mentors():\n query = db.text(\"\"\"\n SELECT COUNT(*)\n FROM users\n WHERE is_mentor = true AND tg_id in (SELECT mentor_id FROM pairs WHERE created_at::date = CURRENT_DATE);\n \"\"\")\n total = await db.first(query)\n return total.count\n\n @classmethod\n async def distribute_users(cls):\n # TODO\n # 1) add limit on amount of mentees\n # 2) add probability system\n mentees = await cls.list_mentees()\n mentors = await cls.get_mentors()\n\n random.shuffle(mentors)\n\n for mentee in mentees:\n _mentor = None\n for mentor in mentors:\n pair = await cls.find_pair(mentor, mentee)\n if pair is not None:\n continue\n elif cls.is_mentor_available(mentor):\n _mentor = mentor\n break\n else:\n _mentor = await cls.get_random_mentor()\n await MenteeToMentor.create(mentor_id=_mentor.tg_id, mentee_id=mentee.tg_id)\n\n @classmethod\n async def get_latest_list(cls):\n conn = await asyncpg.connect(POSTGRES_URI)\n query = await conn.fetch(\"\"\"\n SELECT mentor.tg_username AS mentor, mentee.tg_username AS mentee\n FROM pairs\n INNER JOIN users AS mentor\n ON pairs.mentor_id = mentor.tg_id\n INNER JOIN users AS mentee\n ON pairs.mentee_id = mentee.tg_id\n WHERE pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n );\n \"\"\")\n await conn.close()\n return [(num, record.get('mentor'), record.get('mentee'))\n for num, record in enumerate(query, start=1)]\n\n @classmethod\n async def generate_table(cls):\n headers = [\"#\", \"Mentor\", \"Mentee\"]\n table = await cls.get_latest_list()\n pairs = tabulate(table, headers, tablefmt=\"pretty\")\n return f'{pairs}'\n\n @staticmethod\n async def generate_rate_markup():\n markup = InlineKeyboardMarkup()\n\n markup.row(*[InlineKeyboardButton(text=num, callback_data=f\"rate_{num}\")\n for num in range(MIN_RATE, MAX_RATE + 1)])\n return markup\n\n @staticmethod\n async def get_current_mentor(mentee: User) -> User:\n query = db.text(\"\"\"\n SELECT mentor.tg_id, mentor.tg_username\n FROM pairs\n INNER JOIN users AS mentor\n ON mentor.tg_id = pairs.mentor_id\n WHERE pairs.mentee_id = :mentee_id AND pairs.created_at::date = (\n SELECT MAX(created_at::date)\n FROM pairs\n );\n \"\"\")\n mentor = await db.first(query, mentee_id=mentee.tg_id)\n return mentor\n\n @classmethod\n async def get_reminder_message(cls, mentee: User) -> str:\n mentor = await cls.get_current_mentor(mentee)\n base = f\"Please, rate @{mentor.tg_username}'s work\"\n return md.text(base, \"Don't worry.\\nIt's all confidential
\", sep='\\n\\n')\n\n @staticmethod\n async def rate_mentor(mentee_id: int, mentor_id: int, rate: int):\n await Feedback.create(\n mentee_id=mentee_id,\n mentor_id=mentor_id,\n rate=rate)\n\n @staticmethod\n async def get_mentee(mentee_id: int):\n return await User.query.where(User.tg_id == mentee_id).gino.first()\n","repo_name":"Dinmukhamet/teamlead_assistant","sub_path":"services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"21412812756","text":"import os\nimport sys\nimport LIST2JSON\nimport DrawTextBox\nfrom ocr import OCR\nfrom types import SimpleNamespace\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", category=UserWarning, module=\"torch.nn.functional\")\n\n\ndef OCREngine(image):\n # 이하 opt을 변경하여 기학습된 모델을 교체할 수 있음\n # Parameters가 변경되었을 경우 OCR-Attn/text_recognize/recognition.py을 참조할 것.\n\n path_abs = os.path.dirname(os.path.abspath(__file__))\n opt = SimpleNamespace()\n opt.detect_trained_model = f\"{path_abs}/models/craft_mlt_25k.pth\"\n opt.detect_result_folder = f\"{path_abs}/images/box/\"\n opt.recognize_image_folder = f\"{path_abs}/images/box/\"\n opt.recognize_saved_model = f\"{path_abs}/models/TPS-VGG-BiLSTM-Attn.pth\"\n opt.recognize_Transformation = \"TPS\"\n opt.recognize_FeatureExtraction = \"VGG\"\n opt.recognize_SequenceModeling = \"BiLSTM\"\n opt.recognize_Prediction = \"Attn\"\n\n start = OCR(opt)\n result = start.run(image)\n\n print(\"#Model :\", opt.detect_trained_model,\n \"\\n Network Model :\", opt.recognize_Transformation, opt.recognize_FeatureExtraction,\n opt.recognize_SequenceModeling, opt.recognize_Prediction,\n \"\\n Results :\\n\", result)\n\n json_path = os.path.dirname(image) + \"/\" + os.path.basename(image) + \".json\"\n LIST2JSON.tojsonsingle(result, json_path)\n DrawTextBox.Draw(image, result)\n\n\nif __name__ == '__main__':\n image_path = sys.argv[1] # 명령행 인자\n OCREngine(image_path)\n # OCREngine('C:/Users/Fair/PycharmProjects/Module/OCR-Attn/test/demo.png')\n","repo_name":"c4fiber/AllDayLong","sub_path":"backend/ocr-modules/OCR-Attn/RunOCREngine.py","file_name":"RunOCREngine.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"42479066354","text":"import douban \nimport logging\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%a, %d %b %Y %H:%M:%S',\n filename='spider.log',\n filemode='a')\n\n\n#\nSAVE_PATH = \"F://doubandata2\"\nNUM = 15000\nCONFIGURE_PATH = \"info.txt\"\ntry:\n\tdoubanSp = douban.DouBanMovieSpider()\n\tdoubanSp.configure(\"info.txt\")\n\tprint(\"OK\")\n\tprint(\"url: \",doubanSp._url)\n\tdoubanSp.spider(SAVE_PATH,num=NUM)\nexcept Exception as err:\n\tlogging.error(\"Fuck! %s\"%(str(err)))\n\t#raise err\nelse:\n\tlogging.info(\"Finish!\")\n","repo_name":"MashiMaroLjc/ML-and-DM-in-action","sub_path":"DouBanMovie/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":324,"dataset":"github-code","pt":"50"}
+{"seq_id":"12297513718","text":"import datetime\nimport decimal\nimport enum\nimport re\n\nfrom . import IsolationLevel, FKAction, FKMatch, ConstraintDeferrable\n\n# These are the default SQL strings that correspond to enumerations in the package\n\nISOLATION_LEVEL_SQL = {IsolationLevel.MANUAL_TRANSACTIONS : 'ERROR',\n IsolationLevel.READ_UNCOMMITTED : 'READ UNCOMMITTED',\n IsolationLevel.READ_COMMITTED : 'READ COMMITTED',\n IsolationLevel.REPEATABLE_READ : 'REPEATABLE READ',\n IsolationLevel.SERIALIZABLE : 'SERIALIZABLE'}\n\nFOREIGN_KEY_MATCH_SQL = {FKMatch.SIMPLE : 'MATCH SIMPLE',\n FKMatch.PARTIAL : 'MATCH PARTIAL',\n FKMatch.FULL : 'MATCH FULL'}\n\nFOREIGN_KEY_ACTION_SQL = {FKAction.NO_ACTION : 'NO ACTION',\n FKAction.RESTRICT : 'RESTRICT',\n FKAction.CASCADE : 'CASCADE',\n FKAction.SET_NULL : 'SET NULL',\n FKAction.SET_DEFAULT : 'SET DEFAULT'}\n\nCONSTRAINT_DEFERRABLE_SQL = {ConstraintDeferrable.NOT_DEFERRABLE : 'NOT DEFERRABLE',\n ConstraintDeferrable.DEFERRABLE_INITIALLY_DEFERRED :\n 'DEFERRABLE INITIALLY DEFERRED',\n ConstraintDeferrable.DEFERRABLE_INITIALLY_IMMEDIATE :\n 'DEFERRABLE INITIALLY IMMEDIATE'}\n\nSCHEMA_SEPARATOR_REGEXP = re.compile(r'\\{([^\\}\\.]+)\\.([^\\}\\.]+)\\}', re.UNICODE)\n\ndef convert_schema_sep(sql_text, separator='.'):\n '''Find any instances of '{schema.obj}' in the sql_text parameter and\n return a string using the given separator character 'schema.obj'. This is\n used to emulate SQL schema on databases that don't really support them.'''\n\n match = SCHEMA_SEPARATOR_REGEXP.search(sql_text)\n result = ''\n current_pos = 0\n\n if match:\n while match:\n result += sql_text[current_pos:match.start()] + match[1] + separator + match[2]\n current_pos = match.end()\n match = SCHEMA_SEPARATOR_REGEXP.search(sql_text, match.end())\n result += sql_text[current_pos:]\n return result\n\nclass TransactionContext:\n '''This is a small helper context manager class that allows the dialect.transaction method to\n be used in a 'with' statement. A transaction will have been begun, and at the end of the 'with'\n block or when an exception occurs the transaction will be committed or rolled-back as\n appropriate.\n\n This can also be used as an async context manager. This will assume that the cursor provided\n has coroutines for its cursor.execute method rather than regular methods.'''\n\n def __init__(self, cursor,\n on_entry='BEGIN TRANSACTION;',\n on_success='COMMIT;',\n on_exception='ROLLBACK;'):\n\n self.cursor = cursor\n self.on_entry = on_entry\n self.on_success = on_success\n self.on_exception = on_exception\n\n def __enter__(self):\n if self.on_entry:\n self.cursor.execute(self.on_entry)\n return self\n\n async def __aenter__(self):\n if self.on_entry:\n await self.cursor.execute(self.on_entry)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n if self.on_success:\n self.cursor.execute(self.on_success)\n else:\n if self.on_exception:\n self.cursor.execute(self.on_exception)\n return False\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n if exc_type is None:\n if self.on_success:\n await self.cursor.execute(self.on_success)\n else:\n if self.on_exception:\n await self.cursor.execute(self.on_exception)\n return False\n\nclass SQLDialect:\n '''This is an abstract base class from which concrete dialect classes should be derived.'''\n\n @classmethod\n def parameter(cls, number=1, start=1):\n '''Return a string that represents a parameter placeholder in the query strings in the\n format required by the database adaptor.'''\n\n return '?, '*(number-1) + '?'\n\n @classmethod\n def parameter_values(cls, names, start=1, concat=','):\n '''Return a string of the pattern 'name1=$1, name2=$2' etc. for the names contained in the\n list 'names', starting with parameter number 'start' (where appropriate). The 'concat'\n parameter is used to separate the pairs.'''\n\n result = ''\n for name in names[:-1]:\n result += name + '=? ' + concat + ' '\n return result + names[-1]+'=?'\n\n schema_support = True\n\n store_decimal_as_text = False\n store_date_time_datetime_as_text = False\n enum_support = False\n\n foreign_key_match_sql = FOREIGN_KEY_MATCH_SQL\n foreign_key_action_sql = FOREIGN_KEY_ACTION_SQL\n constraint_deferrable_sql = CONSTRAINT_DEFERRABLE_SQL\n\n truncate_table_sql = '''TRUNCATE TABLE {table_name};'''\n truncate_table_cascade_sql = '''TRUNCATE TABLE {table_name} CASCADE;'''\n\n create_sequence_sql = ('',)\n nextval_sequence_sql = ('',)\n reset_sequence_sql = ('',)\n\n create_view_sql = '''CREATE VIEW IF NOT EXISTS'''\n\n index_specifies_schema = True\n\n @classmethod\n def sql_repr(cls, value):\n '''This method returns the value in the form expected by the particular\n database and database adaptor specified by the dialect parameter. It\n exists to handle cases where the database adaptor cannot accept the\n Python type being used - for example while SQL NUMERIC types map quite\n well to Python decimal.Decimal types, the sqlite3 database adaptor does\n not recognise them, so string values must be stored.'''\n\n return value\n\n @classmethod\n def begin_transaction(cls, cursor, isolation_level=None):\n '''This method starts a new transaction using the database cursor and the (optional)\n isolation level specified, which should be one of the IsolationLevel enum values. It\n returns a context manager so must be used in a 'with' statement.'''\n\n raise NotImplementedError\n\n @classmethod\n def commit_transaction(cls, cursor, isolation_level=None):\n '''This method commits a transaction using the database cursor. The isolation level can be\n specified in order to cover cases where MANUAL_TRANSACTIONS (i.e. no automatic management)\n is desired.'''\n\n raise NotImplementedError\n\n @classmethod\n def rollback_transaction(cls, cursor, isolation_level=None):\n '''This method rolls back a transaction using the database cursor. The isolation level can\n be specified in order to cover cases where MANUAL_TRANSACTIONS (i.e. no automatic\n management) is desired.'''\n\n raise NotImplementedError\n\n @staticmethod\n def create_enum_type(cursor, py_type, sql_name, sql_schema=None):\n '''Create an enum type in the database for the given py_type under the name sql_name\n in the sql_schema (if given).'''\n\n raise NotImplementedError\n\nclass sqliteDialect(SQLDialect):\n '''This class contains information used internally to generate suitable SQL\n for use with the standard library interface to SQLite3, the embedded\n database engine that usually comes supplied with Python.'''\n\n schema_support = False\n\n store_decimal_as_text = False\n store_date_time_datetime_as_text = True\n enum_support = False\n\n foreign_key_match_sql = FOREIGN_KEY_MATCH_SQL\n foreign_key_action_sql = FOREIGN_KEY_ACTION_SQL\n constraint_deferrable_sql = CONSTRAINT_DEFERRABLE_SQL\n\n truncate_table_sql = '''DELETE FROM {table_name};'''\n truncate_table_cascade_sql = truncate_table_sql\n\n create_sequence_sql = ('''\n CREATE TABLE IF NOT EXISTS {qualified_name} (start {index_type},\n interval {index_type},\n lastval {index_type},\n nextval {index_type});''',\n '''INSERT INTO {qualified_name} VALUES '''\n '''({start},{interval},{start},{start});''')\n nextval_sequence_sql = ('''UPDATE {qualified_name} SET lastval=nextval, '''\n '''nextval=nextval+interval;''',\n '''SELECT lastval FROM {qualified_name};''')\n reset_sequence_sql = ('''UPDATE {qualified_name} SET lastval=start, nextval=start;''',)\n\n create_view_sql = '''CREATE VIEW IF NOT EXISTS'''\n\n index_specifies_schema = True\n\n @classmethod\n def sql_repr(cls, value):\n if isinstance(value, bool):\n return 1 if value else 0\n if isinstance(value, (int, float, str, bytes)) or value is None:\n return value\n if isinstance(value, decimal.Decimal):\n return str(value)\n if isinstance(value, datetime.datetime):\n if value.tzinfo:\n return value.strftime('%Y-%m-%dT%H:%M:%S.%f%z')\n return value.strftime('%Y-%m-%dT%H:%M:%S.%f')\n if isinstance(value, datetime.date):\n return value.strftime('%Y-%m-%d')\n if isinstance(value, datetime.time):\n return value.strftime('%H:%M:%S.%f')\n if isinstance(value, enum.Enum):\n return value.value\n\n raise TypeError('sqlite3 Python module cannot handle type {}'.format(str(type(value))))\n\n @classmethod\n def begin_transaction(cls, cursor, isolation_level=None):\n\n if isolation_level == IsolationLevel.MANUAL_TRANSACTIONS:\n return TransactionContext(cursor, None, None, None)\n\n # Note that while SQLite does support READ_UNCOMMITTED, it is a per-session pragma and not\n # per-transaction, which makes it harder to use reliably. We always leave the setting on\n # the default, which is the maximalist SERIALIZABLE isolation level.\n return TransactionContext(cursor, 'BEGIN TRANSACTION;', 'COMMIT;', 'ROLLBACK;')\n\n @classmethod\n def commit_transaction(cls, cursor, isolation_level=None):\n if isolation_level != IsolationLevel.MANUAL_TRANSACTIONS:\n cursor.execute('COMMIT;')\n\n @classmethod\n def rollback_transaction(cls, cursor, isolation_level=None):\n if isolation_level != IsolationLevel.MANUAL_TRANSACTIONS:\n cursor.execute('ROLLBACK;')\n\n @staticmethod\n def create_enum_type(cursor, py_type, sql_name, sql_schema=None):\n '''Enum are not supported natively in SQLite, so nothing is necessary to create them.'''\n\n# This will be used by routines when no dialect is specified. It is not a\n# constant as it is intended that it may be over-ridden by package users\n\nDefaultDialect = sqliteDialect\n","repo_name":"jhumphry/pyxact","sub_path":"pyxact/dialects.py","file_name":"dialects.py","file_ext":"py","file_size_in_byte":10841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"3170249650","text":"key_long = 26\n\ndef getkey():\n key = 0\n print(\"Ingresa la llave: \")\n key = int(input())\n if (key > 1 and key <= key_long):\n return key\n\ndef getMsg():\n entrada = input(\"Introduzca el mensaje a encriptar: \")\n return entrada\n\ndef traduct(mensaje, llave):\n traduction = \"\"\n for caracter in mensaje:\n if caracter.isalpha():\n num = ord(caracter)\n num += llave\n if caracter.isupper():\n if num > ord('Z'):\n num -= 26\n elif num < ord('A'):\n num += 26\n elif caracter.islower():\n if num > ord('z'):\n num -= 26\n elif num < ord('a'):\n num += 26\n \n traduction += chr(num)\n else:\n traduction += caracter\n return traduction\n\nllave = getkey()\nmensaje = getMsg()\n\nprint(\"El mensaje encriptado es: \")\nprint(traduct(mensaje, llave))\n","repo_name":"Edrasen/Teoria_Computacional","sub_path":"T_Computacional/p20.py","file_name":"p20.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"28106939737","text":"#######################################################\n##\n## 백준 24444번 - 알고리즘 수업 - 너비 우선 탐색 1\n## acmicpc.net/problem/24444\n##\n#######################################################\n\nimport sys\nfrom collections import deque\n\ninput = sys.stdin.readline\n\ndef bfs():\n global order\n\n queue = deque()\n queue.append(R)\n\n while queue:\n tmp = queue.popleft()\n if visited[tmp] == 0:\n visited[tmp] = order\n order += 1\n for v in edges[tmp]:\n queue.append(v)\n\nN, M, R = map(int, input().split())\nedges = [[] for _ in range(N+1)]\nvisited = [0 for _ in range(N+1)]\norder = 1\n\nfor i in range(M):\n a, b = map(int, input().split())\n edges[a].append(b)\n edges[b].append(a)\n\nfor i in range(1,N+1):\n edges[i].sort()\n\nbfs()\n\nfor i in range(1, N+1):\n print(visited[i])\n","repo_name":"xuio-0528/Algorithm-Study","sub_path":"Inseok/Week 1 (0516~0522)/24444.py","file_name":"24444.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"9964549355","text":"import json\nimport time\nimport hashlib\nfrom src.database.base.client import Client\nfrom src.helpers import SubParserLogger, ServiceCommand\nfrom src.service.message.service_message import ServiceMessage\nfrom src.service.manager_producer_service import ProducerProcessorManager\nfrom src.sandboxes.cape_sandbox import CapeSandBox\nfrom src.config.configuration import Configuration\n\nclass CAPEEnricher(ServiceCommand):\n \"\"\"\n Cape Sandbox Enricher Command - Collects data from the cape sandbox.\n\n Methods\n -------\n - information(self): dict\n returns a dictionary that has information about the enricher\n \n - service_initialized(self, message: ServiceMessage) -> bool:\n returns a boolean if the callback from the service was able to submit the sample to the CAPE V2 Instance\n\n - service_processing(self, message: ServiceMessage) -> bool:\n returns a boolean if the callback from the service was able to submit the processing message\n\n - service_reporting(self, message: ServiceMessage, elastic: Elastic) -> bool:\n returns a boolean if the callback from the service was able to submit the reporting message\n and update the elastic instance(s) database\n \n - service_error(self, message: ServiceMessage, elastic: Elastic) -> bool:\n returns nothing at the moment, have not gotten to the error messages from CAPE V2, \n since as of yet, no sample has been submitted has generated an error on that end\n\n - _submit_message(self, type: str, org_submitted_time: int):\n makes the call to Kafka submitting the message to the messaging service\n\n - execute(self) -> dict:\n returns a dictionary that has the inital data to be placed into Elastic noting that it is processing.\n This also make a call to Kafka to start the messaging process(es) that will be used during the \n processing of the sample with CAPE.\n \n \"\"\"\n\n def __init__(self, md5: str, path: str):\n \"\"\"\n Constructor for cape enricher\n\n Parameters\n ----------\n - md5: str\n MD5 hash of the sample\n \n - logger: SubParserLogger\n SubParserLogger Object for output to console and file\n\n - path: str\n Full path to the location of the sample\n\n \n \"\"\"\n ServiceCommand.__init__(self)\n self.full_path = path\n self.logger = SubParserLogger(\"CAPE-ENRICHER\")\n self._config = Configuration()\n self.module_type = str(self.__module__) + \".\" + str(self.__class__.__name__)\n self.message_producer = ProducerProcessorManager()\n self.cape_sandbox = CapeSandBox(self._config, self.logger)\n self.tasks = None\n \n if self.full_path != None:\n self.md5 = str(hashlib.md5(open(self.full_path,'rb').read()).hexdigest())\n else:\n self.md5 = None\n\n def information(self) -> dict:\n \"\"\"\n Compatiblity information for enricher\n\n Returns\n -------\n Dictionary\n \"\"\"\n return {\"name\": \"CAPEEnricher\"}\n\n def service_initialize(self, message: ServiceMessage) -> bool:\n \"\"\"\n The first message to be used when submitting a sample to CAPE V2\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to submit the sample to the CAPE V2 instance. \n \"\"\"\n try:\n try:\n if self.cape_sandbox.sandbox_status() == True:\n # check to see if the sample has been submitted \n self.tasks = self.service_getTasks()\n _md5 = hashlib.md5(open(message.sample,'rb').read()).hexdigest()\n _exits = False\n\n if self.tasks != None:\n for _t in self.tasks['data']:\n self.logger.info(\"In tasks: \" + str(_t['sample']['md5']))\n if _t['sample']['md5'] == _md5:\n _exits = True\n break\n if _exits:\n self.logger.info(\"Sample Exists\")\n _submitted = True\n else:\n self.logger.info(\"Sample Not there\")\n _submitted = self.cape_sandbox.submit_job(message)\n \n if _submitted: \n self._submit_message(\"processing\", message.first_seen)\n else:\n self._submit_message(\"error\", message.first_seen)\n\n else:\n raise Exception(\"[CAPE-Enricher] (Init Message) CAPE SYSTEM CAN NOT BE REACHED :: STATUS :: \" + str(self.cape_sandbox.sandbox_status()))\n\n \n except Exception as e:\n self.logger.error(str(e))\n return False\n except Exception as e:\n self.logger.error(str(e))\n return False\n\n def service_processing(self, message: ServiceMessage) -> bool:\n \"\"\"\n The second message to be used, this checks on the progress of the sample and if it has been completed or not\n if it has been, a reporting message is emited, else it replays the processing message.\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to check on the sample in the CAPE V2 instance.\n \"\"\"\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Sample is processinig...\")\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Sample status needs to be checked...\")\n if(message.job_id == None):\n try:\n _sample = self.cape_sandbox.sample_exists(message.md5)\n message.job_id = _sample.data[0]['id'] \n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job ID: \" + str(message.job_id))\n _status = self.cape_sandbox.job_status(message.job_id)\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job Status\")\n self.logger.info(_status)\n\n _json = json.loads(_status)\n\n if _json['data'] == \"running\":\n self._submit_message(\"processing\", message.first_seen)\n elif _json['data'] == \"pending\":\n self._submit_message(\"processing\", message.first_seen)\n elif _json['data'] == \"reported\":\n self._submit_message(\"reporting\", message.first_seen)\n else:\n self.logger.info(\"[CAPE-Enricher] (Processing Message) Job Status :: \" + str(_status))\n\n except Exception as e:\n self.logger.error(\"[CAPE-Enricher] (Processing Message) Error getting job status: \" + str(e))\n\n return True\n \n def service_reporting(self, message: ServiceMessage, client: Client) -> bool:\n \"\"\"\n The last message to be used, this will collect the report from CAPE V2 and add the data to the corresponding \n samples data in the Elastic instance.\n\n Parameters\n ----------\n - message: ServiceMessage\n This message contains the information needed to check on the sample in the CAPE V2 instance.\n\n - elastic: Elastic\n Allows access to the Elastic Instance that contains the rest of the sample(s) data.\n \"\"\"\n self.logger.info(\"[CAPE-Enricher] (Reporting Message) Reporting From Kafka\")\n if self.cape_sandbox.sandbox_status() == True:\n _exits = False\n _task_data = None\n self.tasks = self.service_getTasks()\n if self.tasks != None:\n for _t in self.tasks['data']:\n self.logger.info(\"In tasks: \" + str(_t['sample']['md5']))\n if _t['sample']['md5'] == message.md5:\n _exits = True\n _task_data = _t\n break\n if _exits:\n self.logger.info(\"Sample Exists\")\n self.logger.info(\"Job Report: \" + str(_task_data['id']))\n try:\n _job_report = self.cape_sandbox.get_job_report(_task_data['id']) \n self.logger.info(\"Report Type: \" + str(type(_job_report)))\n if _job_report != None:\n try:\n _report_data = {\n 'payloads' : None,\n 'info' : None\n }\n self.logger.info(\"Report data type: \" + str(type(_job_report)))\n\n try:\n _payloads = _job_report['CAPE']['payloads']\n for _payload in _payloads:\n del _payload['strings']\n\n _report_data['payloads'] = _payloads\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['target'] = _job_report['target']\n del _report_data['target']['file']['strings']\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['info'] = _job_report['info']\n except Exception as e:\n self.logger.exception(str(e))\n\n try:\n _report_data['dropped'] = _job_report['dropped']\n except Exception as e:\n self.logger.exception(str(e))\n \n client.update_sandbox_data(_report_data, message)\n except Exception as e:\n self.logger.error(\"Error with submitting to client: \" + str(e))\n return False\n except Exception as e:\n self.logger.exception(\"ERROR GETTING REPORT :: \" + str(e))\n else:\n self.logger.info(\"Sample Not there\")\n self.logger.info(\"[CAPE-Enricher] (Reporting Message) Trying to submit job to cape :: REPORT NOT THERE\")\n\n return True\n \n def service_error(self, message: ServiceMessage, client: Client) -> bool:\n \"\"\"\n Currently not being used, as of yet, the samples that have been used have not caused CAPE V2 to emit a \n error status\n \"\"\"\n pass\n\n # could be moved to the parent object?\n def _submit_message(self, type: str = None, org_submitted_time: int = None, msg: ServiceMessage = None):\n \"\"\"\n Wrapper for submitting a new ServiceMessage to the background services that work with Kafka.\n \"\"\"\n if msg == None:\n msg = ServiceMessage(\n first_seen=org_submitted_time, last_seen=int(time.time()),\n topic=self._config.cape_topic, md5=self.md5, sample=self.full_path, type=type,\n module= self.module_type, module_name=self.__class__.__name__\n )\n self.message_producer.commands.submit_message(msg)\n self.logger.info(\"[CAPE-Enricher] (Submitting Message) :: \" + str(msg))\n \n\n def service_getTasks(self):\n return self.cape_sandbox.get_task()\n \n\n def execute(self) -> dict:\n \"\"\"\n Execute the CapeEnricher from subparse, to then pass the rest of the processing off to the \n background services and the CAPE V2 Sandbox.\n \"\"\"\n # Since this is now a service command the execute section is for submitting\n # a message to the producer service ONLY!\n _message = ServiceMessage(\n first_seen=int(time.time()), last_seen=int(time.time()),\n topic=self._config.cape_topic, md5=self.md5, sample=self.full_path, type=\"initialized\",\n module= self.module_type, module_name=self.__class__.__name__\n )\n \n self._submit_message(msg=_message)\n \n return {\"enricher\": \"CAPEEnricher\", \"data\": {\"status\" : \"processing\"}}","repo_name":"jstrosch/subparse","sub_path":"parser/src/enrichers/capeenricher.py","file_name":"capeenricher.py","file_ext":"py","file_size_in_byte":12670,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"50"}
+{"seq_id":"40229099250","text":"import FWCore.ParameterSet.Config as cms\n\ninOutSeedsFromTrackerMuons = cms.EDProducer(\"MuonReSeeder\",\n ## Input collection of muons, and selection. track.isNonnull is implicit.\n src = cms.InputTag(\"muons\"),\n cut = cms.string(\"pt > 2\"),\n ## Keep at most these layers from the tracker track of the muon\n layersToKeep = cms.int32(5),\n ## Use the inner part of the tracker track to make a seed\n insideOut = cms.bool(True),\n #### Turn on verbose debugging (to be removed at the end)\n debug = cms.untracked.bool(False),\n ## Configuration for the refitter\n DoPredictionsOnly = cms.bool(False),\n Fitter = cms.string('KFFitterForRefitInsideOut'),\n TrackerRecHitBuilder = cms.string('WithAngleAndTemplate'),\n Smoother = cms.string('KFSmootherForRefitInsideOut'),\n MuonRecHitBuilder = cms.string('MuonRecHitBuilder'),\n MTDRecHitBuilder = cms.string('MTDRecHitBuilder'),\n RefitDirection = cms.string('alongMomentum'),\n RefitRPCHits = cms.bool(True),\n Propagator = cms.string('SmartPropagatorAnyRKOpposite'),\n)\n","repo_name":"cms-sw/cmssw","sub_path":"RecoTracker/SpecialSeedGenerators/python/inOutSeedsFromTrackerMuons_cfi.py","file_name":"inOutSeedsFromTrackerMuons_cfi.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"}
+{"seq_id":"5164750147","text":"# Programa que ajude um jogador na mega sena. o programa vai perguntar quantos jogos serao gerados e vai sortear 6 numeros entre 1 a 60\n# para cada jogo, cadastrando tudo em uma lista composta\n\nfrom random import randint\nfrom time import sleep\n\nprint('-='*20)\nprint(f'{\"MEGA SENA\":^40}')\nprint('-='*20)\n\nlista = []\nnum = 0\n\njogos = int(input('Quantos jogos serao gerados? '))\n\nfor n in range(0, jogos):\n while len(lista) < 6:\n num = randint(1, 60)\n if num not in lista:\n lista.append(num)\n\n print(f'jogo {n+1}: {sorted(lista)}')\n sleep(1)\n lista.clear()\n\n\n","repo_name":"GabrielBrotas/Python","sub_path":"modulo 3/exercicios/Ex088 - Mega sena.py","file_name":"Ex088 - Mega sena.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"40989621424","text":"__VERSION__ = \"0.3.0\"\n\n# -*- coding: utf-8 -*-\nr\"\"\"Exports mermaid diagrams in Markdown documents as images.\n\nExample:\n ::\n\n $ pip install -e .\n\n.. _Google Python Style Guide:\n http://google.github.io/styleguide/pyguide.html\n\n\"\"\"\n\nimport io\nimport logging\nimport os\nimport subprocess\nimport sys\nimport uuid\nfrom pathlib import Path\nfrom shutil import which\n\nimport click\nimport panflute\nimport pypandoc\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\n@click.command()\n@click.option(\n \"--file\",\n \"-m\",\n type=click.Path(exists=True),\n help=\"Path to markdown file, where the mermaid code blocks will be converted to images.\",\n)\n@click.option(\n \"--folder\",\n \"-f\",\n type=click.Path(exists=True),\n help=\"Path to folder where we will convert all markdown mermaid code blocks to images.\",\n)\n@click.option(\n \"--ignore\",\n \"-i\",\n type=click.Path(exists=True),\n multiple=True,\n help=\"Path to folder to ignore, markdown files in this folder will not be converted.\",\n)\n@click.option(\n \"--output\",\n \"-o\",\n type=click.Path(exists=True),\n required=True,\n help=\"Path to folder where to save the new markdown files.\",\n)\n@click.option(\n \"--log-level\", \"-l\", default=\"INFO\", type=click.Choice([\"DEBUG\", \"INFO\", \"ERROR\"]), help=\"Log level for the script.\"\n)\ndef cli(file, folder, ignore, output, log_level):\n \"\"\"Exports mermaid diagrams in Markdown documents as images..\"\"\"\n logger.setLevel(log_level)\n markdown_files = get_markdown_file_paths(file, folder, ignore)\n install_mermaid_cli()\n convert_markdown(markdown_files, output)\n\n\ndef get_markdown_file_paths(file, folder, ignore_paths):\n \"\"\"Gets all the paths to the local markdown article. Either file or folder must be set. If the file is in the\n ignore path it will not convert markdown to .\n\n Args:\n file (str): Path to file.\n folder (str): Path to folder.\n ignore_paths (tuple): A list of paths to ignore markdown files in.\n\n Returns:\n dict: key is the title of the article and value is details.\n\n \"\"\"\n logger.info(\"Getting markdown files.\")\n article_paths = []\n if not file and not folder:\n logger.error(\"File and folder cannot be both be empty.\")\n sys.exit(1)\n elif folder:\n for path in Path(folder).rglob(\"*.md\"):\n ignore = should_file_be_ignored(ignore_paths, path)\n\n if not ignore:\n article_paths.append(path)\n else:\n article_paths = [file]\n return article_paths\n\n\ndef should_file_be_ignored(ignore_paths, path):\n \"\"\"Checks if file should be ignored or not, based on what list of files/folders\n the user has passed as input.\n\n Args:\n ignore_paths (tuple): A list of paths to ignore markdown files in.\n path (str): Path to markdown file.\n\n Returns:\n bool: True if we should ignore the file and it will not be uploaded.\n\n \"\"\"\n ignore = False\n for path_to_ignore in ignore_paths:\n normalised_ignore_path = os.path.normpath(path_to_ignore)\n if os.path.commonpath([path_to_ignore, path]) == normalised_ignore_path:\n ignore = True\n break\n\n return ignore\n\n\ndef install_mermaid_cli():\n \"\"\"Checks if mermaid-cli (mmdc) is installed locally, if not tries to install it. Using \"npm install\".\n If it fails we will throw an error and quit.\n\n \"\"\"\n exists = which(\"mmdc\") is not None\n if not exists:\n logger.info(\"Installing mermaid-cli.\")\n default_mmdc_installation_location = os.path.expanduser(\"~\")\n try:\n subprocess.check_output(\n [f\"npm install --prefix {default_mmdc_installation_location} @mermaid-js/mermaid-cli@8.9.1\"],\n shell=True,\n timeout=600,\n )\n except subprocess.CalledProcessError as e:\n logger.error(f\"Failed to install mermaid-cli, using 'npm install'. Check 'node and npm' are installed. {e}\")\n sys.exit(1)\n\n\ndef convert_markdown(markdown_files, output):\n \"\"\"Converts markdown file's mermaid code blocks to image blocks. It does this by:\n\n * Convert the markdown file to JSON, which include various details such as styling\n * Then find all mermaid code blocks\n * Save the code block to `input.mmd`\n * Use mermaid-cli to export `input.mmd` to a png file\n * Finally replace all code blocks with the image blocks referencing the new image\n * Convert JSON to markdown\n * Save new markdown file\n\n Where a mermaid code block looks something like:\n ..\n\n ```mermaid\n graph LR\n A --> B\n ```\n\n Args:\n markdown_files (:obj:`list` of :obj:`str`): List of paths of the markdown files, we will parse/convert.\n output (str): Path to the output folder where the new markdown files will be saved.\n\n \"\"\"\n for markdown_file in markdown_files:\n logger.info(f\"Exporting {markdown_file} mermaid code blocks to images.\")\n doc = convert_markdown_to_json(markdown_file)\n try:\n doc = panflute.run_filter(export_mermaid_blocks, doc=doc, output=output)\n except subprocess.CalledProcessError as e:\n logger.error(f\"Failed to convert mermaid code block to image. Skiping file. {e}\")\n sys.exit(1)\n except OSError as e:\n logger.error(f\"Failed to open/create `input.mmd`, check file permissions. Skipping file. {e}\")\n sys.exit(1)\n\n file_name = os.path.basename(markdown_file)\n new_file_name = os.path.join(output, file_name)\n replace_mermaid_blocks_with_images(doc)\n save_new_file(doc, new_file_name)\n\n\ndef convert_markdown_to_json(markdown_file):\n \"\"\"Converts our markdown file into JSON, which becomes a list of elements.\n We also create an empty dict, where we will store all the code blocks\n we will need to replace with images.\n\n Where the JSON data looks like:\n\n ..\n data\n '{\"blocks\":[{\"t\":\"Para\",\"c\":[{\"t\":\"Str\",\"c\":\"title:\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"Provisioning\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"API\"},{\"t\":\"Space\"},{\"t\":\"Str\",\"c\":\"LLD\"}]},{\"t\":\"Header\",\"c\":[1,[\"low-level-design\",[],[]],[{\"t\":\"Str\",\"c\":\"Low\"},{\"t\":\"Space\"}}}'\n\n ..\n doc.content.list\n 00: Para(Str(title:) Space Str(Provisioning) Space Str(API) Space Str(LLD))\n 01: Header(Str(Low) Space Str(Level) Space Str(Design); level=1, identifier='low-level-design')\n ...\n 12: CodeBlock(graph LR;\\n A--> B; classes=['mermaid'])\n\n Args:\n markdown_file (str): List of paths of the markdown files, we will parse/convert.\n\n Return:\n panflute.Doc: Pandoc document container.\n\n \"\"\"\n try:\n data = pypandoc.convert_file(str(markdown_file), \"json\")\n except OSError as e:\n logger.error(f\"Pandoc is not installed on the host machine. {e}\")\n sys.exit(1)\n\n doc = panflute.load(io.StringIO(data))\n doc.mermaid = {}\n return doc\n\n\ndef export_mermaid_blocks(elem, doc, output):\n \"\"\"This function is called for every element in the content list. For every element we check if it's a mermaid\n code block. If it is a mermaid code block:\n\n * Save the mermaid code to a `input.mmd`\n * Export `input.mmd` to an randomly named image `npm run export_image -- -i input.mmd -o random_name.png`\n * Store where the index of the mermaid block in the content list so we can later replace it with an image.\n\n The reason we don't replace the code block with an image here is because panflute expects a \"Block\" object\n to be returned. Hence we store where the code block is, so we can replace it later.\n\n Args:\n element (panflute.elements.x): An element in the markdown file, i.e. `panflute.elements.CodeBlock`.\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where we store code block \\\n index and image path.\n output (str): Path to the output folder where the new markdown files will be saved.\n\n \"\"\"\n if isinstance(elem, panflute.CodeBlock) and \"mermaid\" in elem.classes:\n output_text = elem.text\n image_name = uuid.uuid4().hex\n first_line = elem.text.split(\"\\n\")[0]\n if first_line.startswith(\"\"\"%% Image: \"\"\"):\n output_text = elem.text.replace(first_line, \"\")\n image_name = first_line.replace(\"\"\"%% Image: \"\"\", \"\").strip()\n\n with open(\"input.mmd\", \"w+\") as tmp:\n tmp.write(output_text)\n\n output_name = f\"{image_name}.png\"\n output_path = os.path.join(output, output_name)\n\n puppeteer = \"\"\n if os.path.isfile(\"/usr/bin/chromium-browser\"):\n puppeteer = \"-p /data/puppeteer.json\"\n\n mmdc_default_installation = f\"{os.path.expanduser('~')}/node_modules/.bin/mmdc\"\n mmdc = \"mmdc\" if which(\"mmdc\") else mmdc_default_installation\n command = [f\"{mmdc} -i input.mmd -o {output_path} {puppeteer}\"]\n mermaid_output = subprocess.check_output(command, shell=True, timeout=180)\n logger.info(mermaid_output)\n os.remove(\"input.mmd\")\n doc.mermaid[elem.index] = output_name\n\n\ndef replace_mermaid_blocks_with_images(doc):\n \"\"\"Replaces all mermaid code blocks with image blocks. Then saves the markdown content as a new file.\n\n Args:\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where the code block \\\n index and image path are stored.\n\n \"\"\"\n logger.info(\"Replacing mermaid code blocks with image blocks.\")\n for mermaid_block_index, image_path in doc.mermaid.items():\n logger.debug(f\"Replacing mermaid block {doc.content.list[mermaid_block_index]}.\")\n image_element = panflute.Para(panflute.Image(panflute.Str(\"Image\"), url=image_path))\n doc.content.list[mermaid_block_index] = image_element\n\n\ndef save_new_file(doc, new_file_name):\n \"\"\"Saves the new markdown content to a file.\n\n Args:\n doc (panflute.Doc): Pandoc document container, has a mermaid attribute, where the code block \\\n index and image path are stored.\n new_file_name (str): Path where to save the new markdown file.\n\n \"\"\"\n logger.info(f\"Saving new file to {new_file_name}.\")\n with io.StringIO() as temp_file:\n panflute.dump(doc, temp_file)\n contents = temp_file.getvalue()\n\n try:\n pypandoc.convert_text(contents, \"markdown_github\", \"json\", outputfile=new_file_name)\n except OSError as e:\n logger.error(f\"Failed to save file, check permissions. {e}.\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n cli(sys.argv[1:])\n","repo_name":"hmajid2301/markdown-mermaid-to-images","sub_path":"src/markdown_mermaid_to_images/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":10651,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"}
+{"seq_id":"1573737379","text":"n = list(map(int, input().split()))\r\na, b = list([n[0], n[1]]), list([n[2], n[3]])\r\na.sort(), b.sort()\r\na1, a2 = set(), set()\r\n\r\nfor i in range(a[0], a[1] + 1):\r\n a1.add(i)\r\nfor j in range(b[0], b[1] + 1):\r\n a2.add(j)\r\nprint(len(a1 & a2))\r\n","repo_name":"oOoSanyokoOo/Course-Python-Programming-Basics","sub_path":"Пересадки.py","file_name":"Пересадки.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"40187264370","text":"import FWCore.ParameterSet.Config as cms\n\nfrom DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer\nveryHighEtDQM = DQMEDAnalyzer('EmDQM',\n genEtaAcc = cms.double(2.5),\n genEtAcc = cms.double(2.0),\n reqNum = cms.uint32(1),\n filters = cms.VPSet(cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1sRelaxedSingleEgamma\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(82)\n ), \n cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1NonIsoSingleEMVeryHighEtL1MatchFilterRegional\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(100)\n ), \n cms.PSet(\n PlotBounds = cms.vdouble(0.0, 0.0),\n HLTCollectionLabels = cms.InputTag(\"hltL1NonIsoSinglePhotonEMVeryHighEtEtFilter\",\"\",\"HLT\"),\n IsoCollections = cms.VInputTag(cms.InputTag(\"none\")),\n theHLTOutputTypes = cms.uint32(100)\n )),\n PtMax = cms.untracked.double(4000.0),\n pdgGen = cms.int32(11)\n)\n\n\n\n","repo_name":"cms-sw/cmssw","sub_path":"HLTriggerOffline/Egamma/python/veryHighEtDQM_cfi.py","file_name":"veryHighEtDQM_cfi.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":985,"dataset":"github-code","pt":"50"}
+{"seq_id":"73821531354","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nfrom collections import Counter\nfrom Utils.MyDataset import MyDataset\nimport pickle\nfrom tqdm import tqdm\nimport pandas as pd\n\nX_DIR = '/data/Xy/2018_04_10_ERA_interim_storm/X_pl_crop25_z_u_v/'\nX_DIR2 = '/data/Xy/2018_04_10_ERA_interim_storm/X_pl_crop25_z_u_v_historic6h/'\nY_DIR_D = '/data/Xy/2018_04_10_ERA_interim_storm/y_disp2/'\nData_stormids_csv = \"/data/Xy/2018_04_10_ERA_interim_storm/1D_data_matrix_IBTRACS.csv\"\n\n\n\ndef load_datasets(sample=0.1, list_params=None, load_t = (0, -6), valid_split=0.2, test_split=0.2, randomseed=47):\n \"\"\"\n load X1, Y, storm ids from raw pkl files\n :param list_params:\n :param sample: the proportion of sampling, Set sample=1.0 to get the whole data\n :param category: type of label to load, if True, load category as label, if False, load deplacement\n :param localtest: If True, load data from local directory, if False, load from cluster\n :return: X1,Y,storm_ids\n \"\"\"\n\n if list_params is None:\n list_params = ['r', 'd', 'o3', 'v', 'ciwc', 'q', 'pv', 'z', 'clwc', 't', 'w', 'vo', 'u', 'cc']\n X1 = []\n X2 = []\n Y = []\n storm_ids = []\n print('loading from pkls ...')\n # load which y\n x_dir = X_DIR\n x_dir2 = X_DIR2\n y_dir = Y_DIR_D\n\n data = pd.read_csv(Data_stormids_csv)\n stormids = np.unique(data['stormid'].values)\n for filename in tqdm(stormids):\n non_empty_storm = False # check if the storm is empty\n if np.random.random() > sample:\n continue\n else:\n if 0 in load_t:\n with open(x_dir+filename+'.pkl', 'rb') as f:\n storm_data = pickle.load(f)\n if len(storm_data['grids']) != 0:\n non_empty_storm = True\n storm_i = []\n for storm_t in storm_data['grids'][:]:\n grid_allchannels = []\n for key in list_params:\n grid = storm_t[key]\n grid_allchannels.append(grid)\n storm_i.append(grid_allchannels)\n X1.append(storm_i)\n storm_ids.append(filename)\n del storm_data\n if -6 in load_t:\n with open(x_dir2+filename+'.pkl', 'rb') as f:\n storm_data = pickle.load(f)\n if len(storm_data['grids']) != 0:\n non_empty_storm = True\n storm2_i = []\n for storm_t in storm_data['grids'][:]:\n grid_allchannels = []\n for key in list_params:\n grid = storm_t[key]\n grid_allchannels.append(grid)\n storm2_i.append(grid_allchannels)\n X2.append(storm2_i)\n del storm_data\n for item in load_t:\n if item not in (0,-6,-12):\n raise ValueError('only support for t, t-6, t-12')\n\n with open(y_dir+filename+'.pkl', 'rb') as f:\n y_data = pickle.load(f)\n if non_empty_storm is True:\n y_labels = []\n n_storms = len(y_data['next_disp'])\n for i in range(n_storms):\n y_label_i = [y_data['curr_longlat'][i], y_data['curr_longlat'][i+1], y_data['next_disp'][i]]\n y_labels.append(y_label_i)\n Y.append(y_labels)\n\n # set indices for train, valid, test\n num_storm = len(X1)\n indices = list(range(num_storm))\n num_test = int(np.floor(test_split * num_storm))\n num_valid = int(np.floor(valid_split * num_storm))\n np.random.seed(randomseed)\n np.random.shuffle(indices)\n train_idx, valid_idx, test_idx =\\\n indices[:-num_valid-num_test], indices[-num_valid-num_test:-num_test], indices[-num_test:]\n\n trainset = load_foldset(train_idx, storm_ids, Y, X1, X2)\n validset = load_foldset(valid_idx, storm_ids, Y, X1, X2)\n testset = load_foldset(test_idx, storm_ids, Y, X1, X2)\n\n return trainset, validset, testset\n\n\n\ndef load_foldset(fold_idx, storm_ids, Y, X1, X2=None):\n \"\"\"\n :return: foldset (train, test ou valid)\n \"\"\"\n first_non_empty_X=True\n for X in (X1, X2):\n if X != [] and X is not None:\n if first_non_empty_X is True:\n # !!called train in the future, but it actually depend on the fold.\n\n fold_X = list(X[i] for i in fold_idx)\n fold_Y = list(Y[i] for i in fold_idx)\n fold_ids = list(storm_ids[i] for i in fold_idx)\n\n # put datapoints from different storm to a big list\n for idx, storm in enumerate(fold_X):\n fold_ids[idx] = np.repeat(fold_ids[idx],len(storm))\n fold_ids = reduce_dim(fold_ids)\n fold_X = reduce_dim_float32(fold_X)\n fold_Y = reduce_dim_float32(fold_Y)\n\n #set Y to be double float\n fold_Y = np.double(fold_Y)\n\n # convert nan to 0\n np.nan_to_num(fold_X, copy=False)\n np.nan_to_num(fold_Y, copy=False)\n\n # get list of timesteps\n fold_timestep = []\n fold_indexes = np.unique(fold_ids, return_index=True)[1]\n fold_ids_list = [fold_ids[index] for index in sorted(fold_indexes)]\n fold_ids_count = Counter(fold_ids)\n for id in fold_ids_list:\n fold_timestep.extend(list(range(fold_ids_count[id])))\n\n # set flag 'first_non_empty_X' to be False\n first_non_empty_X = False\n\n else:\n fold_X2 = list(X[i] for i in fold_idx)\n fold_X2 = reduce_dim_float32(fold_X2)\n fold_X = np.concatenate((fold_X, fold_X2), axis=1)\n\n # foldset can be either train, test ou valid.\n foldset = MyDataset(fold_X, fold_Y, fold_ids, fold_timestep)\n\n return foldset\n\n\ndef reduce_dim(X):\n X_reduced = []\n for x in tqdm(X):\n X_reduced.extend(x)\n X_reduced_array = np.array(X_reduced)\n return X_reduced_array\n\n\ndef reduce_dim_float32(X):\n X_reduced = []\n for x in tqdm(X):\n X_reduced.extend(x)\n X_reduced_array = np.array(X_reduced, dtype=np.float32)\n return X_reduced_array\n\n\n","repo_name":"sophiegif/FusionCNN_hurricanes","sub_path":"Utils/model_inputs_3D.py","file_name":"model_inputs_3D.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"50"}
+{"seq_id":"6592699024","text":"#####################################\n# --- Day 8: Space Image Format --- #\n#####################################\n\nimport AOCUtils\n\n#####################################\n\nw, h = 25, 6\nimage = [int(i) for i in str(AOCUtils.loadInput(8))]\n\nlayerAmt = len(image) // (w*h)\n\nlayers = []\nlayerCounts = []\nfor l in range(layerAmt):\n layer = []\n for x in range(h):\n s, e = l*w*h + x*w, l*w*h + (x+1)*w\n layer.append(image[s:e])\n\n layers.append(layer)\n\n lc0 = sum(l.count(0) for l in layer)\n lc1 = sum(l.count(1) for l in layer)\n lc2 = sum(l.count(2) for l in layer)\n layerCounts.append((lc0, lc1, lc2))\n\nlayerCounts.sort()\nchecksum = layerCounts[0][1] * layerCounts[0][2]\n\nprint(\"Part 1: {}\".format(checksum))\n\nimage = [[None for _ in range(w)] for _ in range(h)]\nfor i in range(h):\n for j in range(w):\n for layer in layers:\n if image[i][j] is None and layer[i][j] != 2:\n image[i][j] = layer[i][j]\n\nprint(\"Part 2:\")\nfor i in range(h):\n for j in range(w):\n if image[i][j] == 1:\n print(\"##\", end=\"\")\n else:\n print(\" \", end=\"\")\n print()\n\nAOCUtils.printTimeTaken()","repo_name":"KanegaeGabriel/advent-of-code-2019","sub_path":"08_space_image_format.py","file_name":"08_space_image_format.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"24884246990","text":"# Author: Tiago M. de Barros\n# Date: 2022-08-26\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\n\n# File names to use\nFILE_INPUT = \"data_sample.xlsx\"\nFILE_TRAIN = \"data_train.csv\"\nFILE_TEST = \"data_test.csv\"\n\n# Pandas display option\npd.set_option(\"display.max_columns\", None)\n\n# Set seaborn theme\nsns.set_theme()\n\n\ndef main():\n \"Main function\"\n\n data = pd.read_excel(FILE_INPUT, header=0, engine=\"openpyxl\")\n\n # Check data shape\n print(f\"Input data shape: {data.shape}\")\n\n # Check for missing data\n print(f\"Null entries: {data.isnull().sum().sum()}\\n\")\n\n # Check data summary information\n data.info()\n\n # Check data descriptive statistics\n print(\"\\n\", data.describe())\n\n # Print negative values of time\n negative = data[\"Dump spot time/s\"][data[\"Dump spot time/s\"] < 0]\n print(f\"\\nNegative time:\\n{negative}\")\n\n # Drop these entries\n data = data.drop(negative.index)\n\n # Drop entries containing outliers\n data = remove_outliers(data, \"Production/bcm\", 140000)\n data = remove_outliers(data, \"Cycle distance empty/m\", 10000)\n data = remove_outliers(data, \"Cycle distance full/m\", 10000)\n data = remove_outliers(data, \"Spot total duration/s\", 120)\n data = remove_outliers(data, \"Load time/s\", 240)\n data = remove_outliers(data, \"Dump spot time/s\", 40)\n data = remove_outliers(data, \"Dump spot time/s\", 5, True)\n data = remove_outliers(data, \"Off circuit travel time/s\", 4000)\n data = remove_outliers(data, \"Truck production hours\", 400, True)\n data = remove_outliers(data, \"Loader production hours\", 100, True)\n\n # Check correlation between features\n sns.heatmap(data.corr(), cmap=plt.cm.Reds, annot=True, fmt=\".1g\")\n plt.show()\n\n # Drop features presenting multicollinearity\n data = data.drop(columns=[\"Travel empty speed/kmh\",\n \"Cycle distance empty/m\",\n \"Cycle distance full/m\",\n \"Rise distance empty/m\",\n \"Travel empty duration/s\",\n \"Total cycle time/s\",\n \"Number of loading units\",\n \"Truck available hours\",\n \"Loader available hours\"])\n\n # Plot new correlation between features\n sns.heatmap(data.corr(), cmap=plt.cm.Reds, annot=True)\n plt.show()\n\n # Check multi-variate relationship (it may take some time to plot)\n sns.pairplot(data, diag_kind=\"kde\")\n plt.show()\n\n print(f\"\\nNew data shape: {data.shape}\")\n\n # Split data into training and test sets\n X_train, X_test = train_test_split(data,\n test_size=0.1,\n shuffle=True,\n random_state=42)\n\n # Save the sets as CSV files\n X_train.to_csv(FILE_TRAIN, header=True, index=True)\n X_test.to_csv(FILE_TEST, header=True, index=True)\n\n print(f\"\\nSaved training ({FILE_TRAIN}) and test ({FILE_TEST}) sets.\")\n\n\ndef remove_outliers(data: pd.DataFrame,\n field: str,\n threshold: int,\n lessthan: bool = False) -> pd.DataFrame:\n \"Removes outliers from data\"\n\n sns.boxplot(x=data[field])\n plt.show()\n if lessthan:\n outliers = data[field][data[field] < threshold]\n else:\n outliers = data[field][data[field] > threshold]\n\n return data.drop(outliers.index)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"slackhideo/shifts-data-analysis","sub_path":"0_clean_split.py","file_name":"0_clean_split.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"28014594615","text":"import datetime\n\nfrom django.contrib.gis.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User)\n bio = models.TextField(blank=True, null=True)\n\n def __unicode__(self):\n return self.user.username\n\n class Meta:\n db_table = 'profiles'\n app_label = 'ethnoua'\n verbose_name = 'profile'\n verbose_name_plural = 'profiles'\n","repo_name":"ethnoua/ethnoua","sub_path":"src/ethnoua/models/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"5683067459","text":"from pygubu.i18n import _\nfrom pygubu.api.v1 import register_widget, register_custom_property\nfrom pygubu.plugins.tk.tkstdwidgets import TKCanvas\nfrom ttkwidgets.color import AlphaBar, ColorSquare, GradientBar\nfrom ttkwidgets.color.functions import rgb_to_hsv\nfrom PIL.ImageColor import getrgb\nfrom ..ttkwidgets import _designer_tab_label, _plugin_uid\n\n\nclass AlphaBarBO(TKCanvas):\n class_ = AlphaBar\n container = False\n OPTIONS_CUSTOM = (\"alpha\", \"color\", \"variable\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"alpha\", \"height\", \"width\"):\n final_value = int(value)\n elif pname == \"color\":\n final_value = getrgb(value)\n else:\n final_value = super(AlphaBarBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def _code_process_property_value(self, targetid, pname, value):\n if pname == \"color\":\n return f'getrgb(\"{value}\")'\n return super()._code_process_property_value(targetid, pname, value)\n\n def code_imports(self):\n return ((\"PIL.ImageColor\", \"getrgb\"), (\"ttkwidgets.color\", \"AlphaBar\"))\n\n\n_builder_uid = f\"{_plugin_uid}.AlphaBar\"\n\nregister_widget(\n _builder_uid, AlphaBarBO, \"AlphaBar\", (\"ttk\", _designer_tab_label), group=5\n)\n\nregister_custom_property(\n _builder_uid,\n \"alpha\",\n \"integernumber\",\n help=_(\"initially selected alpha value (between 0 and 255)\"),\n)\nregister_custom_property(\n _builder_uid, \"color\", \"colorentry\", help=_(\"gradient color\")\n)\nregister_custom_property(\n _builder_uid,\n \"variable\",\n \"tkvarentry\",\n help=_(\"variable linked to the alpha value\"),\n)\n\n\nclass ColorSquareBO(TKCanvas):\n class_ = ColorSquare\n container = False\n OPTIONS_CUSTOM = (\"hue\", \"color\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def realize(self, parent, extra_init_args: dict = None):\n args = self._get_init_args(extra_init_args)\n master = parent.get_child_master()\n hue_value = args.pop(\"hue\", 0)\n self.widget = self.class_(master, hue_value, **args)\n return self.widget\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"hue\", \"height\", \"width\"):\n final_value = int(value)\n elif pname == \"color\":\n rgb = getrgb(value)\n final_value = rgb_to_hsv(*rgb)\n else:\n final_value = super(ColorSquareBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def _code_process_property_value(self, targetid, pname, value):\n if pname == \"color\":\n return f'rgb_to_hsv(*getrgb(\"{value}\"))'\n return super()._code_process_property_value(targetid, pname, value)\n\n def code_imports(self):\n return (\n (\"PIL.ImageColor\", \"getrgb\"),\n (\"ttkwidgets.color\", \"ColorSquare\"),\n (\"ttkwidgets.color.functions\", \"rgb_to_hsv\"),\n )\n\n\n_builder_uid = f\"{_plugin_uid}.ColorSquare\"\n\nregister_widget(\n _builder_uid,\n ColorSquareBO,\n \"ColorSquare\",\n (\"ttk\", _designer_tab_label),\n group=5,\n)\n\n# Custom properties\nregister_custom_property(\n _builder_uid,\n \"hue\",\n \"integernumber\",\n default_value=0,\n help=_(\"hue (between 0 and 360) of the color square gradient\"),\n)\nregister_custom_property(\n _builder_uid, \"color\", \"colorentry\", help=_(\"initially selected color\")\n)\n\n\nclass GradientBarBO(TKCanvas):\n class_ = GradientBar\n container = False\n OPTIONS_CUSTOM = (\"hue\", \"variable\")\n properties = (\n TKCanvas.OPTIONS_STANDARD + TKCanvas.OPTIONS_SPECIFIC + OPTIONS_CUSTOM\n )\n ro_properties = OPTIONS_CUSTOM + (\"height\", \"width\")\n virtual_events = (\"<>\",)\n\n def _process_property_value(self, pname, value):\n final_value = None\n if pname in (\"hue\", \"height\", \"width\"):\n final_value = int(value)\n else:\n final_value = super(GradientBarBO, self)._process_property_value(\n pname, value\n )\n return final_value\n\n def code_imports(self):\n return ((\"ttkwidgets.color\", \"GradientBar\"),)\n\n\n_builder_uid = f\"{_plugin_uid}.GradientBar\"\n\nregister_widget(\n _builder_uid,\n GradientBarBO,\n \"GradientBar\",\n (\"ttk\", _designer_tab_label),\n group=5,\n)\n\nregister_custom_property(\n _builder_uid,\n \"hue\",\n \"integernumber\",\n help=_(\"initially selected hue value (between 0 and 360)\"),\n)\nregister_custom_property(\n _builder_uid,\n \"variable\",\n \"tkvarentry\",\n help=_(\"variable linked to the hue value\"),\n)\n","repo_name":"alejandroautalan/pygubu","sub_path":"src/pygubu/plugins/ttkwidgets/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":1900,"dataset":"github-code","pt":"50"}
+{"seq_id":"9853288336","text":"import os\nfrom typing import List, Optional\n\nimport hydra\nfrom omegaconf import DictConfig\nfrom pytorch_lightning import (\n Callback,\n LightningDataModule,\n LightningModule,\n Trainer,\n seed_everything,\n)\nfrom pytorch_lightning.loggers import LightningLoggerBase\n\nfrom src.utils import utils\nfrom pytorch_lightning import plugins\nlog = utils.get_logger(__name__)\n\n\ndef get_pl_logger(cfg: DictConfig) -> List[LightningLoggerBase]:\n loggers: List[LightningLoggerBase] = []\n if \"logger\" in cfg:\n for _, lg_conf in cfg[\"logger\"].items():\n if \"_target_\" in lg_conf:\n log.info(f\"Instantiating logger <{lg_conf._target_}>\")\n logger = hydra.utils.instantiate(lg_conf)\n loggers.append(logger)\n while True:\n try:\n # sometimes fail for unknown reason\n print(logger.experiment)\n break\n except BaseException:\n pass\n\n if \"wandb\" in lg_conf[\"_target_\"]:\n id = \"offline\"\n # if not cfg.debug:\n # will upload this run to cloud\n log.info(f\"wandb url in {logger.experiment.url}\")\n # get id from x-y-id\n id = logger.experiment.name.rsplit('-', 1)[1]\n cfg.callbacks.model_checkpoint.dirpath = os.path.join(\n cfg.callbacks.model_checkpoint.dirpath, id\n )\n # if debug, not saving checkpoint at all\n # since del in `touch`\n return loggers\n\n\ndef train(config: DictConfig) -> Optional[float]:\n \"\"\"Contains training pipeline.\n Instantiates all PyTorch Lightning objects from config.\n\n Args:\n config (DictConfig): Configuration composed by Hydra.\n\n Returns:\n Optional[float]: Metric score for hyperparameter optimization.\n \"\"\"\n\n # Set seed for random number generators in pytorch, numpy and python.random\n if config.get(\"seed\"):\n seed_everything(config.seed, workers=True)\n\n # Init lightning datamodule\n log.info(f\"Instantiating datamodule <{config.datamodule._target_}>\")\n datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)\n\n # Init lightning module\n log.info(f\"Instantiating model <{config.module._target_}>\")\n model: LightningModule = hydra.utils.instantiate(\n config.module, optcfg=config.module.optim,\n schcfg=getattr(config.module, \"scheduler\", None),\n _recursive_=False\n )\n\n # Init lightning loggers\n logger: List[LightningLoggerBase] = get_pl_logger(config)\n\n\n # Init lightning callbacks\n callbacks: List[Callback] = []\n if \"callbacks\" in config:\n for _, cb_conf in config.callbacks.items():\n if \"_target_\" in cb_conf:\n log.info(f\"Instantiating callback <{cb_conf._target_}>\")\n callbacks.append(hydra.utils.instantiate(cb_conf))\n\n # Init lightning trainer\n log.info(f\"Instantiating trainer <{config.trainer._target_}>\")\n trainer: Trainer = hydra.utils.instantiate(\n config.trainer, callbacks=callbacks, logger=logger, _convert_=\"partial\"\n )\n\n # Send some parameters from config to all lightning loggers\n log.info(\"Logging hyperparameters!\")\n utils.log_hyperparameters(\n config=config,\n model=model,\n datamodule=datamodule,\n trainer=trainer,\n callbacks=callbacks,\n logger=logger,\n )\n\n # Train the module\n log.info(\"Starting training!\")\n trainer.fit(model=model, datamodule=datamodule)\n\n # Evaluate module on test set, using the best module achieved during training\n if config.get(\"test_after_training\") and not config.trainer.get(\"fast_dev_run\"):\n log.info(\"Starting testing!\")\n trainer.test()\n\n # Make sure everything closed properly\n log.info(\"Finalizing!\")\n utils.finish(\n config=config,\n model=model,\n datamodule=datamodule,\n trainer=trainer,\n callbacks=callbacks,\n logger=logger,\n )\n\n # Print path to best checkpoint\n if not config.trainer.get(\"fast_dev_run\"):\n log.info(f\"Best model ckpt: {trainer.checkpoint_callback.best_model_path}\")\n\n # save LM ckpt\n model = type(model).load_from_checkpoint(trainer.checkpoint_callback.best_model_path)\n LM = model.transformer\n LM.save_pretrained(f\"{config.callbacks.model_checkpoint.dirpath}/LM\")\n\n # Return metric score for hyperparameter optimization\n optimized_metric = config.get(\"optimized_metric\")\n if optimized_metric:\n return trainer.callback_metrics[optimized_metric]","repo_name":"cnut1648/uncanny_valley","sub_path":"motif/lightning/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"36853509589","text":"# -*- coding: utf-8 -*-\n\n###################### copy/paste from appadmin.py ###############\n\n# ##########################################################\n# ## make sure administrator is on localhost\n# ###########################################################\n\nimport os\nimport socket\nimport datetime\nimport copy\nimport gluon.contenttype\nimport gluon.fileutils\n\ntry:\n import pygraphviz as pgv\nexcept ImportError:\n pgv = None\n\nis_gae = request.env.web2py_runtime_gae or False\n\n# ## critical --- make a copy of the environment\n\nglobal_env = copy.copy(globals())\nglobal_env['datetime'] = datetime\n\nhttp_host = request.env.http_host.split(':')[0]\nremote_addr = request.env.remote_addr\ntry:\n hosts = (http_host, socket.gethostname(),\n socket.gethostbyname(http_host),\n '::1', '127.0.0.1', '::ffff:127.0.0.1')\nexcept:\n hosts = (http_host, )\n\nif request.is_https:\n session.secure()\nelif (remote_addr not in hosts) and (remote_addr != \"127.0.0.1\"):\n # and (request.function != 'manage'):\n raise HTTP(200, T('appadmin is disabled because insecure channel'))\n\n################## some auxilary functions \n\ndef get_databases(request):\n dbs = {}\n for (key, value) in global_env.items():\n cond = False\n try:\n cond = isinstance(value, GQLDB)\n except:\n cond = isinstance(value, SQLDB)\n if cond:\n dbs[key] = value\n return dbs\n\ndatabases = get_databases(None)\n\n############# DIFF's start here ####################\n\nTABLE_ADMIN_HREF_TPL = URL(\"appadmin\", \"select\")+\"/db?query=db.%s\" # CAN CONFIG to point to phpmyadmin, adminer or so...\n# example: \"http://127.0.0.1:8000/app/appadmin/select/db?query=db.address_country\"\n\ndef index(): redirect( URL( 'graph_model' ))\n\ndef table_template(table):\n from gluon.html import TR, TD, TABLE, TAG\n\n def FONT(*args, **kwargs):\n return TAG.font(*args, **kwargs)\n\n def types(field):\n f_type = field.type\n if not isinstance(f_type,str):\n return ' '\n elif f_type == 'string':\n return field.length\n elif f_type == 'id':\n return B('pk')\n elif f_type.startswith('reference') or \\\n f_type.startswith('list:reference'):\n return B('fk')\n else:\n return ' '\n\n def type_repr(field):\n result = field.type\n if 'reference' in field.type:\n result = field.type.replace('reference ', '--> ')\n if field.name.endswith('_id') and field.name[:-3]==result[len('--> '):] :\n result = '--> '\n return result\n \n # This is horribe HTML but the only one graphiz understands\n rows = []\n cellpadding = 4\n color = \"#000000\"\n bgcolor = \"#FFFFFF\"\n face = \"Helvetica\"\n face_bold = \"Helvetica Bold\"\n border = 0\n\n rows.append(TR(TD(FONT(table, _face=face_bold, _color='blue'), # _size=\"20\" doesn't work..\n _colspan=3, _cellpadding=cellpadding,\n _align=\"center\", _bgcolor=bgcolor)))\n for row in db[table]:\n if is_interesting_field( row.name +\" \"+ row.type +\" \"+ str(types(row)) ):\n rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold),\n _align=\"left\", _cellpadding=cellpadding,\n _border=border),\n TD(FONT(type_repr(row), _color=color, _face=face),\n _align=\"left\", _cellpadding=cellpadding,\n _border=border),\n TD(FONT(types(row), _color=color, _face=face),\n _align=\"center\", _cellpadding=cellpadding,\n _border=border)))\n return \"< %s >\" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1,\n _cellborder=0, _cellspacing=0)\n ).xml()\n\n\ndef is_interesting_field( fieldname ):\n # defaults could be 'pk fk'\n show_fields=(request.get_vars.show_fields or '').replace('%20', ' ').split()\n if not show_fields: return True\n for word in show_fields: \n if word in fieldname: \n return True # include\n if word.startswith('-') and word[1:] in fieldname:\n return False # or exclude \n\ndef is_important_force_exceptions_first(tablename): # DEPRECATED\n # in views/appadmin.html forward vars=request.vars: =IMG(_src=URL('appadmin', 'bg_graph_model', vars=request.vars)\n # graph_model?table_filters=...&field_filters=...&show_fields=fk%20pk\n table_filters=(request.vars.table_filters or 'invoice sales_order -blind -good -batch -discount -shipment').replace('%20', ' ').split()\n \n field_filters=(request.vars.field_filters or 'user').replace('%20', ' ').split()\n # if request.vars.filters:\n # filters=request.vars.filters.split()\n\n # match by table name\n excluding_filters = [word[1:] for word in table_filters if word.startswith('-')]\n for word in excluding_filters: \n if word in tablename: \n return False # force exclude first\n \n for word in table_filters: \n if word in tablename: \n return True # include\n\n # match by field name\n for field in db[tablename]:\n for word in field_filters: # or one of it's fields' names\n if word in field.name:\n return True\n\ndef is_shown(tablename):\n if session.graph_shown_tables:\n return tablename in session.graph_shown_tables\n \ndef matches_filter(tablename):\n \"\"\"\n Takes arguments and returns True on first match, \n minus sign (\"-\") means, we don't want this match...\n \"\"\"\n # in views/appadmin.html forward vars=request.vars: =IMG(_src=URL('appadmin', 'bg_graph_model', vars=request.vars)\n # graph_model?table_filters=...&field_filters=...\n table_filters=(request.get_vars.table_filters or \"\").replace('%20', ' ').split()\n \n field_filters=(request.get_vars.field_filters or request.get_vars.table_filters or \"\").replace('%20', ' ').split()\n \n if table_filters==[] and field_filters==[]: # if no filters set -- show everything\n return True \n \n # if request.vars.filters:\n # filters=request.vars.filters.split()\n\n for word in table_filters: \n if word in tablename: \n return True # include\n if word.startswith('-') and word[1:] in tablename:\n return False # or exclude\n\n # match by field name\n for field in db[tablename]:\n for word in field_filters: # or one of it's fields' names\n if word in field.name:\n return True # include\n if word.startswith('-') and word[1:] in field.name:\n return False # or exclude\n\ndef bg_graph_model():\n\n if request.vars.action == 'match':\n session.graph_shown_tables = [table for table in db.tables if matches_filter(table)]\n\n if request.vars.action == 'findpath':\n if (session.findpath['start'] == request.vars.start\n and session.findpath['finish'] == request.vars.finish):\n pass # no need to re-generate stuff\n else:\n session.graph_shown_tables = findpath_between_tables()\n \n if request.vars.action == 'list':\n session.graph_shown_tables = request.vars.tables.replace(\"%20\", \" \").replace(\"->\", \"\").replace(\"<-\", \"\").split()\n\n graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR')\n\n subgraphs = dict()\n for tablename in db.tables:\n if hasattr(db[tablename],'_meta_graphmodel'):\n meta_graphmodel = db[tablename]._meta_graphmodel\n else:\n meta_graphmodel = dict(group=request.application, color='#ECECEC')\n\n group = meta_graphmodel['group'].replace(' ', '')\n if not subgraphs.has_key(group):\n subgraphs[group] = dict(meta=meta_graphmodel, tables=[])\n subgraphs[group]['tables'].append(tablename)\n else:\n subgraphs[group]['tables'].append(tablename)\n\n graph.add_node(tablename, name=tablename, shape='plaintext',\n href=TABLE_ADMIN_HREF_TPL % tablename,\n label=table_template(tablename) \n if is_shown(tablename) else tablename\n )\n \n\n\n for n, key in enumerate(subgraphs.iterkeys()):\n graph.subgraph(nbunch=subgraphs[key]['tables'],\n name='cluster%d' % n,\n style='filled',\n color=subgraphs[key]['meta']['color'],\n label=subgraphs[key]['meta']['group'])\n\n shown_tables = set([])\n for tablename in db.tables:\n for field in db[tablename]:\n f_type = field.type\n if isinstance(f_type,str) and (\n f_type.startswith('reference') or\n f_type.startswith('list:reference')):\n referenced_table = f_type.split()[1].split('.')[0]\n n1 = graph.get_node(tablename)\n n2 = graph.get_node(referenced_table)\n \n if request.vars.neighbours=='0': # show only filtered, &neighbours=0\n if is_shown(tablename) : shown_tables.add( tablename )\n if is_shown(referenced_table) : shown_tables.add( referenced_table )\n if is_shown(tablename) and is_shown(referenced_table):\n graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n else: # default: show neighbours\n if is_shown(tablename) or is_shown(referenced_table):\n shown_tables.add( tablename )\n shown_tables.add( referenced_table )\n graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n \n\n # import rpdb2; rpdb2.start_embedded_debugger(\"a\")\n # from gluon.debug import dbg; dbg.set_trace() # stop here\n for tablename in db.tables:\n if not tablename in shown_tables:\n graph.delete_node( tablename )\n\n graph.layout()\n if not request.args:\n # response.headers['Content-Type'] = 'image/png'\n # return graph.draw(format='png', prog='dot')\n response.headers['Content-Type'] = 'image/svg+xml'\n return graph.draw(format='svg', prog='dot')\n else:\n response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)\n if request.args(0) == 'dot':\n return graph.string()\n else:\n return graph.draw(format=request.args(0), prog='dot')\n\ndef build_graph():\n dgraph = { tablename: {'to':[], 'fk':{}, 'from':[]} for tablename in db.tables }\n \n for tablename in db.tables:\n for field in db[tablename]:\n f_type = field.type\n if isinstance(f_type,str) and (\n f_type.startswith('reference') or\n f_type.startswith('list:reference')):\n referenced_table = f_type.split()[1].split('.')[0]\n dgraph[tablename]['to'].append( referenced_table )\n dgraph[tablename]['fk'][ referenced_table ] = field.name\n dgraph[referenced_table]['from'].append( tablename )\n # n1 = graph.get_node(tablename)\n # n2 = graph.get_node(referenced_table)\n # graph.add_edge(n1, n2, color=\"#4C4C4C\", label='')\n return dgraph \n \n# http://localhost:8000/app/appadmin/smart_join\n# BUG? \n# http://localhost:8000/app/appadmin/graph_model?start=sales_order&finish=address_country&max_joins=6&show_fields=-&neighbours=0&action=findpath#\n# neranda visų kelių (tame tarpe teisingo - subject_address)\n# http://localhost:8000/app/appadmin/graph_model?tables=sales_order+-%3E+branch+%3C-+subject_settings+-%3E+address_country++subject_address+sales_order+-%3E+branch+%3C-+subject_settings+-%3E+address_country++address_address&show_fields=-&neighbours=0&action=list#\ndef findpath_between_tables(start=request.vars.start, finish=request.vars.finish, max_joins=request.vars.max_joins):\n dgraph = build_graph()\n \n # use breadth-first search\n queue = [start]\n paths = [ [start] ] # list of names\n # paths_refs = [ [\"\"] ]\n # result = []\n result_paths = []\n # visited = [ start ]\n\n \n while queue:\n table = queue.pop(0)\n path = paths.pop(0)\n # refs = paths_refs.pop(0)\n \n \n if table == finish: # reach finish\n result_paths.append( path )\n continue\n\n if len(path) > int(max_joins): # if path would become too long\n continue\n \n # from gluon.debug import dbg\n # dbg.set_trace() # stop here! \n \n node = dgraph[ table ]\n for x in node['to']+node['from']: # look for join in any direction\n if (not x in path) or x==finish: # exception for x==finish will let find many paths (probably not needed after deprecating visited)\n queue.append( x )\n paths.append( path+[x] )\n # visited.append( x )\n \n # joins from path (using foreign key names)\n \n def repr_joins( path, style='w2p' or 'str' ):\n \n def add_join(A, B):\n def make_join_w2p(added_table, pk_table, fk_table, fk): \n # return db[added_table].on( db[pk_table].id == db[fk_table][fk] )\n join_txt = \"db[added_table].on( db[pk_table].id == db[fk_table][fk] )\"\n # hack to generate nicer txt\n for var in \"added_table, pk_table, fk_table, fk\".split(\", \"):\n join_txt = join_txt.replace(\"[%s]\"%var, \".\"+locals()[var])\n return join_txt\n \n if style=='w2p':\n if B in dgraph[A]['to']:\n joins.append( make_join_w2p(B, B, A, dgraph[A]['fk'][B]) )\n else:\n joins.append( make_join_w2p(B, A, B, dgraph[B]['fk'][A]) )\n\n if style=='str':\n if B in dgraph[A]['to']:\n joins.append( \" -> \"+B )\n else:\n joins.append( \" <- \"+B )\n\n joins = [] \n for i in range(len(path)-1):\n A = path[i]\n B = path[i+1]\n add_join( A, B )\n \n return joins\n from pprint import pformat\n session.findpath = {'start':start, 'finish':finish}\n # session.findpath['joins'] = {str(path): generate_join_chain(path) for path in result_paths}\n def path_hash(path): return path[0]+''.join(repr_joins(path, 'str')) if path else None\n # constructs sth like: invoice -> auth_user <- sales_settings -> good_category\n session.findpath['joins'] = { path_hash(path) : [PRE(', \\n'.join(repr_joins(path, 'w2p'))), \n A('(url)', _href= URL(vars={'action':'list', 'tables':path_hash(path) }))\n ] \n for path in result_paths}\n \n \n # return list(set(sum(result_paths))) # return set of names from paths\n \n return list(set(reduce(lambda a, b: a+b, result_paths))) if result_paths else [] # return set of names from paths\n\ndef smart_join(): \n return dict(path=findpath_between_tables()) #alias\n\n# src= https://gist.github.com/dz0/ef4bea4e6f4aaf21f084c06190efecf6\ndef graph_model():\n\n session.graph_model_vars = session.graph_model_vars or {} #init stuff for request vars\n if request.vars: session.graph_model_vars.update( request.post_vars or request.get_vars) ;\n previous = session.graph_model_vars # prepare to fill form fields with earlier info\n \n\n match_form = SQLFORM.factory(\n Field('table_filters', default=previous.get('table_filters', '') ), \n Field('field_filters', default=previous.get('fields_filters', '') ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"match\"), \n _method=\"GET\",\n )\n \n findpath_form = SQLFORM.factory(\n Field('start', default=previous.get('start', ''), requires=IS_IN_SET( list(db.tables)) ), \n # Field('bla', default=127, widget = SQLFORM.widgets.autocomplete(request, db.good.sku, id_field=db.good.id) )\n Field('finish', default=previous.get('finish', '') , requires=IS_IN_SET( list(db.tables))), \n Field('max_joins', \"integer\", default=previous.get('max_joins', 3) ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"findpath\"), \n _method=\"GET\",\n )\n \n if request.vars.action == 'findpath':\n try:\n session.graph_shown_tables = findpath_between_tables()\n except Exception as e:\n response.flash += \"Error: Can't 'findpath_between_tables':\\n\"+str(e)\n\n \n list_form = SQLFORM.factory(\n Field('tables', default=previous.get('tables', ''), ), \n Field('show_fields', default=previous.get('show_fields', 'fk') ), \n Field('neighbours', \"integer\", default=previous.get('neighbours', 0 )), \n Field('action', default=\"list\"), \n _method=\"GET\",\n )\n \n # highlight currently submitted form\n for form in [match_form, findpath_form, list_form]:\n input_action_type = form.element('input', _name='action')\n input_action_type.parent.parent['_style'] = \"display: none\"\n form_action = input_action_type['_value']\n if form_action :\n if form_action == request.vars.action:\n # response.flash+= form_action+ \" \\n \"\n form['_style']=\"margin: 5px; padding:5px; border:1px gray solid; background-color: #E5E5E5;\"\n # form.element('table')['_style']=\"background-color: #E5E5E5\"\n \n docs = {\n 'FindPath': \"Selects tables that connect \\\"Start\\\" with \\\"Finish\\\"\", \n 'List': \"Selects tables that are listed (wrong names are ignored) \", \n 'Match': \"\"\"Selects tables with names or fieldnames, that match given fragments. \n
Some \"features\":\n Fragments should be separated by spaces \n If you want to exclude sth, you can put \"-fragment\" before (it would not affect if mentiont afterwards). \n Empty \"Table filters\" will select all the tables \n If \"Field filters\" is empty, it defaults to \"Table filters\" \n \"\"\", \n 'common': \"\"\"
\n \"Show Fields\" - filter by fragments which fields to display in tables structure.
\n \"Neighbours\" - how many levels of adjacent neighbour-tables to show (just table names). \n \"\"\"\n }\n forms=[ \n findpath_form, \n list_form, \n match_form\n ]\n \n names = locals()\n get_form = lambda form_name: names[form_name.lower()+\"_form\"]\n \n forms = [ CAT(\n H3(form_name , \n CAT( \" (\", A(\"?\", _href=\"#\", _onclick=\"toggle('docs_\"+form_name+\"');\" ), \")\") ), \n DIV(XML(docs[form_name]+docs['common']), _id=\"docs_\"+form_name, _style=\"display:none\"), \n get_form(form_name)\n ) for form_name in \"FindPath List Match\".split() ]\n \n return dict(databases=databases, pgv=pgv, forms=forms)\n","repo_name":"dz0/web2py_grand_helpers","sub_path":"plugins/controllers/plugin_dbgraph.py","file_name":"plugin_dbgraph.py","file_ext":"py","file_size_in_byte":19611,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"50"}
+{"seq_id":"24577683946","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom time import gmtime, strftime\nfrom string import ascii_uppercase, digits\nimport random\n\nfrom flask import Flask\nfrom flask import request, url_for, session, redirect, flash, jsonify\nfrom flask import current_app, make_response, abort, send_file, render_template\nfrom flask_cors import CORS\nfrom flask_oauthlib.client import OAuth\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\n\nfrom .utils import read4json, save2json, create_menssage\n\n\n# Create the flask app\napp = Flask(__name__,\n template_folder=\"../templates/_site\",\n static_folder=\"../static\",\n instance_relative_config=True)\n\n# Cofiguration of flask\nsys.path.insert(0, os.getcwd())\napp.config.from_object('server.config.DevelopmentConfig')\n\n# Allow post from other domains with cookies\ncors = CORS(app, supports_credentials=True)\n\n# Twitter configuration to login via OAuth\noauth = OAuth()\ntwitter = oauth.remote_app(\n 'twitter',\n base_url='https://api.twitter.com/1.1/',\n request_token_url='https://api.twitter.com/oauth/request_token',\n access_token_url='https://api.twitter.com/oauth/access_token',\n authorize_url='https://api.twitter.com/oauth/authorize',\n consumer_key=app.config['TWITTER_CONSUMER_KEY'],\n consumer_secret=app.config['TWITTER_CONSUMER_SECRET']\n)\n\n\ndef generate_random_id(size=20, chars=ascii_uppercase + digits):\n \"\"\"\n Generate a random string used on the cookies to\n autetication of the user.\n\n Thanks to Ignacio Vazquez-Abrams for this solution\n https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python#2257449\n\n Parameters\n ----------\n size: int\n Leng of the random string\n chars: string\n String used to choice the random values\n \"\"\"\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef allowed_file(filename):\n \"\"\"\n Check if the upload image is in a valid format\n\n Parameters\n ----------\n filename: string\n Filename\n \"\"\"\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() \\\n in app.config['ALLOWED_EXTENSIONS']\n\n\n\"\"\"\nLogin in the aplication\n-----------------------\n\"\"\"\n\n\n@app.route('/login')\ndef login():\n \"\"\"\n Login via twitter\n\n Parameters\n ----------\n return_to: str\n Url to return after login\n\n TODO:\n ----\n * Login via facebook\n \"\"\"\n next_url = request.args.get('next')\n\n allowed_routes = ['accionDirecta', 'mapeoCiudadano',\n 'historico']\n if next_url not in allowed_routes:\n next_url = ''\n\n callback_url = url_for('oauthorized', next=next_url)\n return twitter.authorize(callback=callback_url or\n request.referrer or None)\n\n\n@app.route('/logout')\ndef logout():\n \"\"\"\n Logout and remove all the cookies\n\n TODO:\n ----\n * Guardar la url de la que viene para volver a la misma\n \"\"\"\n next_url = request.args.get('next')\n\n allowed_routes = ['accionDirecta', 'mapeoCiudadano',\n 'historico']\n if next_url not in allowed_routes:\n next_url = '/'\n\n response = current_app.make_response(redirect(next_url))\n\n # Remove all the cookies\n response.set_cookie('status', '', expires=0)\n response.set_cookie('session', '', expires=0)\n\n return response\n\n\n@app.route('/oauthorized')\ndef oauthorized():\n \"\"\"\n Check if the login user have the correct permission to add points.\n\n TODO:\n * check if the facebook user have the coorect permission\n * retornar a la ultima pagina que visito el usuario antes del login\n \"\"\"\n next_url = request.args.get('next') or '/'\n\n resp = twitter.authorized_response()\n\n if resp is None:\n flash('You denied the request to sign in.')\n return redirect('/')\n elif resp['screen_name'] not in app.config['TWITTER_ALLOWED']:\n flash('You dont have premission')\n return redirect('/')\n\n access_token = resp['oauth_token']\n session['access_token'] = access_token\n session['screen_name'] = resp['screen_name']\n\n session['twitter_token'] = (\n resp['oauth_token'],\n resp['oauth_token_secret']\n )\n\n flash('You were successfully logged in')\n\n response = current_app.make_response(redirect(next_url))\n response.set_cookie('status', value=generate_random_id())\n return response\n\n\n\"\"\"\nBasic routes\n------------\n\"\"\"\n\n\n@app.route('/')\ndef home():\n return render_template(\"index.html\",\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/accionDirecta')\ndef accion_directa():\n return render_template(\"accionDirecta.html\",\n layersNames=app.config['DA_LAYERS_NAMES'],\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/mapeoCiudadano')\ndef mapeo_ciudadano():\n return render_template(\"mapeoCiudadano.html\",\n layersNames=app.config['CM_LAYERS_NAMES'],\n serverUrl=app.config['SERVER_URL'])\n\n\n@app.route('/historico')\ndef historio():\n return render_template(\"index.html\",\n serverUrl=app.config['SERVER_URL'])\n\n\n\"\"\"\nDirect action routes\n--------------------\n\"\"\"\n\n\n@app.route('/direct_action/layer/', methods=['GET'])\ndef da_data(layer_name):\n \"\"\"\n Get a geoJson data layer for direct action map.\n If the 'layer_name' dont exist, return an empty json\n\n Parameters\n ----------\n layer_name: str\n Name of the layer\n \"\"\"\n data_path = app.config['DA_FOLDER'] + layer_name + '.geojson'\n\n # Invalid layer name\n if layer_name not in app.config['DA_LAYERS_NAMES']:\n return jsonify({})\n\n data = read4json(data_path)\n return jsonify(data)\n\n\n@app.route('/direct_action/point', methods=['POST'])\ndef da_new_point():\n \"\"\"\n Add a new point to direct action map.\n Only allowed user can do this.\n\n Parameters\n ----------\n\n Errors\n ------\n 401: The user dont have permission\n 400: The image is empty\n 400: Invalid type of image\n \"\"\"\n # The user don't have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Data of the point: title, day, etc\n data = request.files['data'].read()\n data = eval(data)\n\n # Photo\n file = FileStorage(request.files['photo'])\n filename = secure_filename(request.files['photo'].filename)\n\n # Diferents check of the data and image\n\n # Invalid coordinates\n if data['latitud'] == 0:\n print(\"Error: latitud invalida\")\n abort(400, \"Invalid latitude\")\n if data['longitud'] == 0:\n print(\"Error: longitud invalida\")\n abort(400, \"Invalid longitude\")\n\n # Empty file\n if filename == '':\n print('Error: no archivo')\n abort(400, \"The image is empty\")\n\n # Invalid image extention\n if not allowed_file(filename):\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n elif not file:\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n\n # Invalid data layer\n if data['tipo'] not in app.config['DA_LAYERS_NAMES']:\n print(\"Error: Nombre de capa invalido\")\n abort(400, \"Invalid layer name\")\n\n # Open the geojson dataframe\n data_path = app.config['DA_FOLDER'] + data['tipo'] + '.geojson'\n df = read4json(data_path)\n\n # get the unic point id\n if len(df['features']) == 0:\n point_id = 0\n else:\n last_id = df['features'][-1]['properties']['id']\n point_id = last_id + 1\n\n # The image is correct and can save\n filename = data['tipo'] + '_' + str(point_id) + '.jpeg'\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(path)\n\n # Save the now point to geojson file\n point = {\n \"type\": \"Feature\",\n \"properties\": {\n \"fecha_creacion\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()),\n \"foto\": filename,\n \"nombre\": data['titulo'],\n \"descripcion\": data['resumen'],\n \"barrio\": data['barrio'],\n \"tipo\": data['tipo'].replace(\"_\", \" \"),\n \"twit\": \"\",\n \"face\": \"\",\n \"valido\": True,\n \"id\": point_id\n },\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n float(data['latitud']),\n float(data['longitud'])\n ]\n }\n }\n\n df['features'].append(point)\n save2json(data_path, df)\n\n # Update the message\n create_menssage(\"direct_action\", data['tipo'])\n\n return jsonify('201')\n\n\n@app.route('/direct_action/point_d', methods=['DELETE'])\ndef da_delet_point():\n \"\"\"\n Delet an existen point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['DA_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['DA_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n elements = []\n for element in data['features']:\n if element['properties']['id'] != req_data['id']:\n elements.append(element)\n\n new_data = {'features': elements,\n 'type': 'FeatureCollection'}\n\n save2json(data_path, new_data)\n\n # Get the uniques point id\n return jsonify({'201': 'Point delete'})\n\n\n\"\"\"\nCitizen map routes\n------------------\n\"\"\"\n\n\n@app.route('/citizen_map/layer/', methods=['GET'])\ndef citizen_map(layer_name):\n \"\"\"\n Get a geoJson data layer for citizen map.\n If the 'layer_name' dont exist, return an empty json\n\n Parameters\n ----------\n layer_name: str\n Name of the layer\n \"\"\"\n data_path = app.config['CM_FOLDER'] + layer_name + '.geojson'\n\n # Invalid layer name\n if layer_name not in app.config['CM_LAYERS_NAMES']:\n return jsonify({})\n\n data = read4json(data_path)\n\n # If the user is login, return all the data\n if 'twitter_token' in session:\n return jsonify(data)\n\n # The user is not login. Only return valid points\n valid_elements = []\n for element in data['features']:\n if element['properties']['valido']:\n valid_elements.append(element)\n\n data = {'type': 'FeatureCollection',\n 'features': valid_elements}\n return jsonify(data)\n\n\n@app.route('/citizen_map/point', methods=['POST'])\ndef citizen_new_point():\n \"\"\"\n Add a new point to direct action map\n\n Parameters\n ----------\n\n Errors\n ------\n 401: user dont have permission to make post\n 400: the image is empty\n 400: Invalid type of image\n \"\"\"\n # Data of the point: title, day, etc\n data = request.files['data'].read()\n data = eval(data)\n\n # Photo\n file = FileStorage(request.files['photo'])\n filename = secure_filename(request.files['photo'].filename)\n\n # Diferents check of the data and image\n\n # Invalid coordinates\n if data['latitud'] == 0:\n print(\"Error: latitud invalida\")\n abort(400, \"Invalid latitude\")\n if data['longitud'] == 0:\n print(\"Error: longitud invalida\")\n abort(400, \"Invalid longitude\")\n\n # Empty file\n if filename == '':\n print('Error: no archivo')\n abort(400, \"The image is empty\")\n\n # Invalid image extention\n if not allowed_file(filename):\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n elif not file:\n print(\"Error: Tipo de imagen invalida\")\n abort(400, \"Invalid type of image\")\n\n # Invalid data layer\n if data['tipo'] not in app.config['CM_LAYERS_NAMES']:\n print(\"Error: Nombre de capa invalido\")\n abort(400, \"Invalid layer name\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + data['tipo'] + '.geojson'\n df = read4json(data_path)\n\n # The image is correct and can save\n amount_type = len(df['features']) + 1\n filename = data['tipo'] + '_' + str(amount_type) + '.jpeg'\n path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n file.save(path)\n\n # If the user is login, the point is validate\n if 'twitter_token' in session:\n validate = True\n else:\n validate = False\n\n # get the unic point id\n if len(df['features']) == 0:\n point_id = 0\n else:\n last_id = df['features'][-1]['properties']['id']\n point_id = last_id + 1\n\n # Save the now point to geojson file\n point = {\n \"type\": \"Feature\",\n \"properties\": {\n \"fecha_creacion\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()),\n \"foto\": filename,\n \"nombre\": data['titulo'],\n \"descripcion\": data['resumen'],\n \"barrio\": data['barrio'],\n \"tipo\": data['tipo'].replace(\"_\", \" \"),\n \"twit\": \"\",\n \"face\": \"\",\n \"valido\": validate,\n \"id\": point_id\n },\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [\n float(data['latitud']),\n float(data['longitud'])\n ]\n }\n }\n\n df['features'].append(point)\n save2json(data_path, df)\n\n # Update the message\n # create_menssage(\"citizen_map\", data['tipo'])\n\n return jsonify('201')\n\n\n@app.route('/citizen_map/point', methods=['DELETE'])\ndef cm_delet_point():\n \"\"\"\n Delet an existen point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['CM_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n elements = []\n for element in data['features']:\n if element['properties']['id'] != req_data['id']:\n elements.append(element)\n\n new_data = {'features': elements,\n 'type': 'FeatureCollection'}\n\n save2json(data_path, new_data)\n return jsonify({'201': 'Point delete'})\n\n\n@app.route('/citizen_map/point', methods=['PUT'])\ndef cm_validate_point():\n \"\"\"\n Validate a point\n\n Parameters\n ----------\n name: str\n Layer name\n id: int\n Unique id of the point to delet\n\n Errors\n ------\n 401: The user don't have permission\n 400: The json is empy\n 400: The layer name don't exist\n 400: The point id don't exist\n \"\"\"\n req_data = request.json\n\n # First, check the data\n # Check if the user have permission\n if 'twitter_token' not in session:\n print(\"Error: no tiene permiso\")\n abort(401, \"You don't have permission\")\n\n # Check if the json is complete\n if 'id' not in req_data:\n abort(400, \"The request json don't have a point id\")\n if 'name' not in req_data:\n abort(400, \"The request json don't have a layer name\")\n\n # Check if the layer name is valid\n if req_data['name'] not in app.config['CM_LAYERS_NAMES']:\n abort(400, \"The layer name don't exist\")\n\n # Open the geojson dataframe\n data_path = app.config['CM_FOLDER'] + req_data['name'] + '.geojson'\n data = read4json(data_path)\n\n # Get the uniques ids\n uniques_ids = []\n for element in data['features']:\n uniques_ids.append(element['properties']['id'])\n\n # Check if the point id is valid\n if req_data['id'] not in uniques_ids:\n abort(400, \"The point id don't exist\")\n\n for element in data['features']:\n if element['properties']['id'] == req_data['id']:\n element['properties']['valido'] = True\n\n save2json(data_path, data)\n return jsonify({'201': 'Point validate'})\n\n\n\"\"\"\nGet image\n-----------\n\"\"\"\n\n\n@app.route('/image/', methods=['GET'])\ndef get_image(image_name):\n \"\"\"\n\n \"\"\"\n elemets = os.listdir(app.config['UPLOAD_FOLDER'])\n\n if image_name not in elemets:\n print(\"Error: nombre de imagen incorrecto\")\n abort(400, \"Invalid image name\")\n\n image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_name)\n\n return send_file(image_path, mimetype='image/gif')\n\n\n\"\"\"\nHttp Errors\n-----------\n\"\"\"\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n \"\"\"\n Error 400 for Bad Request.\n The body request is empy or with a bad key\n For example `new_name` in side of `name`.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Not found'\n return make_response(jsonify({'error': message}), 400)\n\n\n@app.errorhandler(401)\ndef unauthorized(error):\n \"\"\"\n Error 401 for Unauthorized.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Unauthorized'\n\n return make_response(jsonify({'error': message}), 401)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n \"\"\"\n Error 404 for Resource Not Found.\n The id in the URI don't exist.\n \"\"\"\n if error.description:\n message = error.description\n else:\n message = 'Not found'\n\n return make_response(jsonify({'error': message}), 404)\n","repo_name":"pewen/mapeoColectivo","sub_path":"server/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":19074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"72049104476","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom database.datamodel import DataModel\n\nclass DMCategory(DataModel):\n def __init__(self, cls):\n super().__init__(cls)\n\n def select(self, business_id):\n self.query_sql = u'SELECT category FROM category WHERE ' \\\n + 'business_id = \"%s\"' % (business_id)\n ret = super().select()\n result = dict()\n for index, entry in enumerate(ret):\n result[index] = entry[0]\n return result\n\n def delete(self, business_id, category):\n if len(category) == 0:\n self.query_sql = u'DELETE FROM `category` WHERE business_id=\"%s\"' \\\n % (business_id)\n super().execute()\n for key, val in category.items():\n self.query_sql = \\\n u'DELETE FROM `category` WHERE business_id=\"%s\" AND category=\"%s\"' \\\n % (business_id, val)\n super().execute()\n\n def insert(self, business_id, category):\n from datamodel.business import business\n if len(business.select(business_id)) < 1:\n business.insert(business_id, {})\n for key, val in category.items():\n self.query_sql = \\\n u'INSERT INTO `category`(`business_id`, `category`) ' \\\n + 'VALUES(\"%s\", \"%s\")' \\\n % (business_id, val)\n super().execute()\n\n def update(self, business_id, category, old_category):\n for key, val in category.items():\n self.query_sql = \\\n u'UPDATE `category` SET category=%s WHERE ' \\\n % (self.quote_sql(val)) + 'business_id=\"%s\" AND category=%s' \\\n % (business_id, self.quote_sql(val))\n super().execute()\n","repo_name":"Cedric-Chen/ShopMe","sub_path":"database/dmcategory.py","file_name":"dmcategory.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"3555914948","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nfrom edo_client.api import SessionStore\n\n\nclass SessionStoreTestCase(unittest.TestCase):\n\n def setUp(self):\n self.workspace = tempfile.mkdtemp()\n self.store = SessionStore(self.workspace)\n\n def tearDown(self):\n shutil.rmtree(self.workspace)\n\n def test_session_store_init(self):\n temp_dir = os.path.join(self.workspace, 'does_no_exist')\n self.assertFalse(os.path.isdir(temp_dir), 'root does not exist yet')\n self.store = SessionStore(temp_dir)\n self.assertTrue(\n os.path.isdir(temp_dir),\n 'SessionStore should create its `root` if not exist'\n )\n\n def test_session_store_save_load_remove(self):\n test_key = 'test_key might be a file path or other text'\n test_data = {\n 'key_1': 'some random string',\n 'key_2': 'well, not that random',\n 'some other type': 911,\n }\n self.store.save(test_key, **test_data)\n self.assertEqual(\n 1, len(os.listdir(self.workspace)),\n 'Data should be saved to a file on disk'\n )\n self.assertEqual(\n self.store.load(test_key),\n test_data,\n 'Should be able to load data back the same as we saved them'\n )\n self.store.remove(test_key)\n self.assertEqual(\n 0, len(os.listdir(self.workspace)),\n 'File should be removed from disk once we remove this session'\n )\n self.assertIsNone(\n self.store.load(test_key),\n 'Should return default value if no session found'\n )\n","repo_name":"easydo-cn/edo_client","sub_path":"tests/test_session_store.py","file_name":"test_session_store.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"12238099692","text":"def fib_range(x):\n print(\"First fibonacci numbers in range 1-1000 are\") \n a=0\n b=1\n c=0\n while c= self.K:\n heapq.heappop(init_heap)\n\n # return list of pairs (score, qid)\n return init_heap\n\n def param_estimation(self):\n \"\"\"estimates all the parameters of the weighted sum of the components\"\"\"\n\n # expected output = alpha, beta, gamma, delta\n # return a array with 4 tuple values\n\n # best params and score from all restarts\n best_params = [0 for _ in range(5)]\n best_score = 0\n\n # heaps for each duplicate question which contain top K questions as predicted by algorithm\n q_heaps = {\n _id: heapq.heapify([]) for _id in self.dup_score_details.keys()\n }\n\n for _ in tqdm(range(self.iterations)):\n\n # random restart type approach, for each iteration choose a new set of starting params\n init_params = [random() for _ in range(5)]\n\n for dup_q_id in self.dup_score_details.keys():\n q_heaps[dup_q_id] = self.cal_param_scores_for_a_question(init_params,\n self.dup_score_details[dup_q_id][\n \"scores\"])\n # score for initial set of params\n init_score = self.evaluation_criteria(q_heaps)\n\n # trial params are copy of initial set of params\n params = init_params.copy()\n\n # update and try values for each parameter iteratively\n for i in tqdm(range(5)):\n j = 0\n while j < 1.01:\n # try each value from 0 to 1\n params[i] = j\n\n # iterate through each duplicate question\n for dup_q_id in self.dup_score_details.keys():\n # calculate scores using current set of trial params\n q_heaps[dup_q_id] = self.cal_param_scores_for_a_question(params,\n self.dup_score_details[dup_q_id][\n \"scores\"])\n score = self.evaluation_criteria(q_heaps)\n\n # if score for these sets of parameters is better than best score for this iteration, then update\n # best params of this iteration \n if score > init_score:\n init_params[i] = j\n init_score = score\n j += 0.05\n\n # update trial params to best params of current restart before fine-tuning next parameter\n params[i] = init_params[i]\n\n # take best params of each iteration in random restart\n if init_score > best_score:\n best_params = init_params.copy()\n best_score = init_score\n\n # return best params from all restarts\n return best_params, best_score\n\n def evaluation_criteria(self, q_heaps):\n\n # I curently have a heap with qid as key and list of pairs of (score, best candid)\n # exp found in dup_score_details[qid][expected_questions]\n\n wanted_q_ids = list(q_heaps.keys())\n success_num = 0\n success_denom = len(wanted_q_ids)\n for curr_q_id, curr_heap in q_heaps.items():\n predicted_best = set([x[1] for x in curr_heap])\n actual_best = self.dup_score_details[curr_q_id]['expected_questions']\n matched = predicted_best.intersection(actual_best)\n if len(matched):\n success_num += 1\n params_score = success_num / success_denom\n return params_score\n\n\nif __name__ == \"__main__\":\n begin = datetime.datetime.now()\n\n composer = Composer(duplicate_details_path=sys.argv[1])\n composer.load_file()\n best_params, best_score = composer.param_estimation()\n print(f'final best score: {best_score} with {best_params} params')\n\n print(datetime.datetime.now() - begin)\n","repo_name":"anmolagarwal999/Multi-Factor-Duplicate-Question-Detection-in-Stack-Overflow","sub_path":"jac_training.py","file_name":"jac_training.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"13453213154","text":"import inspect\n\nimport decompil.ir\n\n\nclass Position:\n def __init__(self, basic_block, index):\n self.basic_bloc = basic_block\n self.index = index\n\n\nclass Builder:\n\n def __init__(self):\n _create_build_methods()\n self.basic_block = None\n self.index = None\n self.current_origin = None\n\n @property\n def position(self):\n if self.basic_block is not None:\n return Position(self.basic_block, self.index)\n else:\n return None\n\n @property\n def current_basic_block(self):\n return self.basic_block\n\n def create_basic_block(self):\n return self.basic_block.function.create_basic_block()\n\n def set_position(self, position):\n self.basic_block = position.basic_block\n self.index = position.index\n\n def position_at_entry(self, function):\n self.basic_block = function.entry\n self.index = 0\n\n def position_at_start(self, basic_block):\n self.basic_block = basic_block\n self.index = 0\n\n def position_at_end(self, basic_block):\n self.basic_block = basic_block\n self.index = len(basic_block.instructions)\n\n def insert_instruction(self, insn):\n assert self.position\n self.basic_block.insert(self.index, insn)\n self.index += 1\n\n def set_origin(self, origin):\n self.current_origin = origin\n\n\n_build_method_created = False\ndef _create_build_methods():\n global _build_method_created\n\n if _build_method_created:\n return\n else:\n _build_method_created = True\n\n kind_to_cls = {}\n for names in dir(decompil.ir):\n obj = getattr(decompil.ir, names)\n if (\n inspect.isclass(obj)\n and issubclass(obj, decompil.ir.BaseInstruction)\n and obj != decompil.ir.BaseInstruction\n ):\n for kind in obj.KINDS:\n kind_to_cls[kind] = obj\n\n for kind, name in decompil.ir.NAMES.items():\n cls = kind_to_cls[kind]\n\n def create_build_method(cls, name, kind):\n\n def build(self, *operands, **kwargs):\n if 'origin' not in kwargs:\n kwargs['origin'] = self.current_origin\n func = self.basic_block.function\n args = [func]\n if len(cls.KINDS) > 1:\n args.append(kind)\n args.extend(operands)\n insn = cls(*args, **kwargs)\n self.insert_instruction(insn)\n if insn.type != func.context.void_type:\n return insn.as_value\n\n return 'build_{}'.format(name), build\n\n method_name, method = create_build_method(\n kind_to_cls[kind], name, kind\n )\n setattr(Builder, method_name, method)\n","repo_name":"pmderodat/decompil","sub_path":"decompil/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"16542430673","text":"'''Recognize image file formats and size based on their first few bytes.\r\n\r\nThis module is a port of Image::Size Perl Module\r\nsee more http://search.cpan.org/author/RJRAY/Image-Size-3.01/lib/Image/Size.pm\r\n\r\nported by jigloo(phus@live.com)\r\nadd rgbsize rassize pcxsize function\r\n\r\nNew BSD license\r\n'''\r\n# see https://github.com/phuslu/imgsz\r\n\r\n__version__ = '2.1'\r\n__all__ = ['what', 'size', 'frombytes']\r\n\r\nimport io\r\nimport re\r\nfrom struct import unpack\r\n\r\nfrom PIL import Image\r\n\r\n\r\ndef _jpegsize(stream):\r\n '''gets the width and height (in pixels) of a JPEG file'''\r\n x, y = 0, 0\r\n # Dummy read to skip header ID\r\n stream.read(2)\r\n while 1:\r\n # Extract the segment header.\r\n (marker, code, length) = unpack('!BBH', stream.read(4))\r\n # Verify that it's a valid segment.\r\n if marker != 0xFF:\r\n # Was it there?\r\n raise ValueError('JPEG marker not found')\r\n elif code >= 0xC0 and code <= 0xC3:\r\n # Segments that contain size info\r\n (y, x) = unpack('!xHH', stream.read(5))\r\n break\r\n else:\r\n # Dummy read to skip over data\r\n stream.read(length - 2)\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine JPEG size')\r\n return 'JPEG', x, y\r\n\r\n\r\ndef _bmpsize(stream):\r\n '''size a Windows-ish BitMap image'''\r\n x, y = 0, 0\r\n # Dummy read to skip header data\r\n stream.read(18)\r\n (x, y) = unpack(' num_dirent:\r\n break\r\n tag = unpack(be + 'H', ifd[:2])[0] # ...and decode its tag\r\n type = unpack(be + 'H', ifd[2:2 + 2])[0] # ...and the data type\r\n # Check the type for sanity.\r\n if type > len(packspec) or packspec[type] is None:\r\n continue\r\n if tag == 0x0100: # ImageWidth (x)\r\n # Decode the value\r\n x = unpack(packspec[type], ifd[8:4 + 8])[0]\r\n elif tag == 0x0101: # ImageLength (y)\r\n # Decode the value\r\n y = unpack(packspec[type], ifd[8:4 + 8])[0]\r\n\r\n # Decide if we were successful or not\r\n\r\n if x == 0 or y == 0:\r\n error = '%s%s%s ' % ('ImageWidth ' if x == 0 else '',\r\n ' and ' if x + y > 0 else '',\r\n 'ImageHeigth ' if y == 0 else '')\r\n error += 'tag(s) could not be found'\r\n raise ValueError(error)\r\n\r\n return 'TIFF', x, y\r\n\r\n\r\ndef _psdsize(stream):\r\n '''determine the size of a PhotoShop save-file (*.PSD)'''\r\n x, y = 0, 0\r\n stream.read(14)\r\n (y, x) = unpack('!LL', stream.read(8))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine PSD size')\r\n return 'PSD', x, y\r\n\r\n\r\n# pcdsize :\r\n# Kodak photo-CDs are weird. Don't ask me why, you really don't want details.\r\nPCD_MAP = {'base/16': (192, 128),\r\n 'base/4': (384, 256),\r\n 'base': (768, 512),\r\n 'base4': (1536, 1024),\r\n 'base16': (3072, 2048),\r\n 'base64': (6144, 4096)}\r\n# Default scale for PCD images\r\nPCD_SCALE = 'base'\r\n\r\n\r\ndef _pcdsize(stream):\r\n '''determine the size of a file in Kodak photo-CDs'''\r\n x, y = 0, 0\r\n buff = stream.read(0xf00)\r\n if buff[0x800:3 + 0x800] != 'PCD':\r\n raise ValueError('Invalid/Corrupted PCD (bad header)')\r\n orient = ord(buff[0x0e02:1 + 0x0e02]) & 1 # Clear down to one bit\r\n if orient:\r\n (x, y) = PCD_MAP[PCD_SCALE]\r\n else:\r\n (y, x) = PCD_MAP[PCD_SCALE]\r\n return 'PCD', x, y\r\n\r\n\r\ndef _bin(n, count=32):\r\n '''returns the binary of integer n, using count number of digits'''\r\n return ''.join([str((n >> i) & 1) for i in range(count - 1, -1, -1)])\r\n\r\n\r\ndef _swfsize(stream):\r\n '''determine size of ShockWave/Flash files.'''\r\n x, y = 0, 0\r\n header = stream.read(33)\r\n bs = ''.join([_bin(c, 8) for c in unpack('B' * 17, header[8:17 + 8])])\r\n bits = int(bs[:5], 2)\r\n x = int(bs[(5 + bits):bits + (5 + bits)], 2) / 20\r\n y = int(bs[(5 + bits * 3):bits + (5 + bits * 3)], 2) / 20\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine SWF size')\r\n return 'SWF', x, y\r\n\r\n\r\ndef _swfmxsize(stream):\r\n '''determine size of Compressed ShockWave/Flash files.'''\r\n import zlib\r\n x, y = 0, 0\r\n stream.read(8)\r\n z = zlib.decompressobj()\r\n header = z.decompress(stream.read(1024))\r\n del z\r\n bs = ''.join([_bin(c, 8) for c in unpack('B' * 9, header[:9])])\r\n bits = int(bs[:5], 2)\r\n x = int(bs[(5 + bits):bits + (5 + bits)], 2) / 20\r\n y = int(bs[(5 + bits * 3):bits + (5 + bits * 3)], 2) / 20\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine CWS size')\r\n return 'CWS', x, y\r\n\r\n\r\ndef _mngsize(stream):\r\n '''gets the width and height (in pixels) of an MNG file.\r\n Basically a copy of pngsize.'''\r\n x, y = 0, 0\r\n stream.read(12)\r\n if stream.read(4) == b'MHDR':\r\n # MHDR = Image Header\r\n x, y = unpack('!LL', stream.read(8))\r\n else:\r\n raise ValueError('Invalid/Corrupted MNG (bad header)')\r\n return 'MNG', x, y\r\n\r\n\r\ndef _rgbsize(stream):\r\n '''gets the width and height (in pixels) of a SGI file.'''\r\n x, y = 0, 0\r\n stream.read(6)\r\n x, y = unpack('!HH', stream.read(4))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine SGI size')\r\n return 'RGB', x, y\r\n\r\n\r\ndef _rassize(stream):\r\n '''gets the width and height (in pixels) of a Sun raster file.'''\r\n x, y = 0, 0\r\n stream.read(4)\r\n x, y = unpack('!LL', stream.read(8))\r\n if x == 0 or y == 0:\r\n raise ValueError('could not determine Sun raster size')\r\n return 'RAS', x, y\r\n\r\n\r\ndef _pcxsize(stream):\r\n '''gets the width and height (in pixels) of a ZSoft PCX File.'''\r\n x, y = 0, 0\r\n stream.read(4)\r\n (xmin, ymin, xmax, ymax) = unpack(' str:\n duration = run_info[\"duration\"]\n dt = run_info[\"dt\"]\n x_0 = sympy.Matrix(run_info[\"x_0\"])\n run_name = run_info[\"name\"]\n caption = run_info[\"caption\"] if \"caption\" in run_info else \"\"\n A = sympy.Matrix([\n [-2, 1],\n [0, -1]\n ])\n B = sympy.Matrix([\n [0],\n [1]\n ])\n C = sympy.eye(2)\n D = sympy.Matrix([[0],[0]])\n k = sympy.Matrix(run_info[\"k\"])\n time_steps = [\n t for t in np.arange(start=0, stop=duration, step=dt)\n ]\n inputs = [\n sympy.Matrix([[0]]) for t in time_steps\n ]\n outputs = ModelSystem(\n update=non_linear_update,\n output=linear_output,\n x_0=x_0,\n inputs=inputs,\n k=k,\n dt=dt,\n C=C,\n D=D\n )\n graph_location = f\"resources/{run_name}.png\"\n QuestionFour.plotter(\n time_steps,\n outputs,\n graph_location,\n run_name,\n )\n inst = TemplateCore.instance()\n return inst.filter(\n \"image\",\n [f\"../{graph_location}\", caption, f\"fig:{run_name}\"]\n ) \n\n @staticmethod\n def plotter(time_steps: Iterable[float],\n outputs: Iterable[sympy.Matrix],\n save_file: str,\n title_name: str,\n output_names: Iterable[str] = None):\n \"\"\"\n takes the system outputs and plots them, returns the file path\n \"\"\"\n fig = plt.figure()\n axis = fig.add_axes([0.15, 0.15, 0.75, 0.75])\n outputs = np.concatenate(outputs, axis=1)\n if output_names is None:\n output_names = []\n for i in range(len(outputs)):\n output_names.append(f\"output {i}\")\n\n for output, name in zip(outputs, output_names):\n axis.plot(time_steps, output.T, label=name)\n axis.set_title(title_name)\n axis.set_xlabel('Time(s)')\n axis.set_ylabel('System outputs')\n axis.legend()\n fig.savefig(save_file)\n \n","repo_name":"NathanRoseCE/ControlsClass","sub_path":"HomeworkFive/Filters/QuestionFour.py","file_name":"QuestionFour.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"13645115028","text":"\nimport torch\nimport torch.nn as nn \nimport pandas as pd\nimport numpy as np\nimport sys\nsys.path.append('/home/petaon/python_packages/site-packages')\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pandas as pd\nimport pytorch_lightning as pl\nfrom models import loss_func, concordance_index\n\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass LightningnDeep(pl.LightningModule):\n\n def __init__(self, \n input_size = 12, \n layer_hidden_sizes = [3,3,5],\n num_layers = 3,\n bias = True,\n dropout = 0.0,\n bidirectional = False,\n batch_first = True,\n label_size = 1,\n E=1):\n super().__init__()\n self.E = E\n self.num_layers = num_layers\n self.rnn_models = nn.ModuleList([])\n if bidirectional:\n layer_input_sizes = [input_size] + [2 * chs for chs in layer_hidden_sizes]\n else:\n\n layer_input_sizes = [input_size] + layer_hidden_sizes\n for i in range(num_layers):\n self.rnn_models.append(nn.LSTM(input_size = layer_input_sizes[i],\n hidden_size = layer_hidden_sizes[i],\n num_layers = num_layers,\n bias = bias,\n dropout = dropout,\n bidirectional = bidirectional,\n batch_first = batch_first))\n self.label_size = label_size\n self.output_size = layer_input_sizes[-1]\n self.output_func = nn.Linear(self.output_size, self.label_size) \n\n def forward(self, input_data):\n X = input_data['X'].float()\n M = input_data['M'].float()\n cur_M = input_data['cur_M'].float()\n _data = X\n for temp_rnn_model in self.rnn_models:\n _data, _ = temp_rnn_model(_data)\n outputs = _data\n all_output = outputs * M.unsqueeze(-1)\n n_batchsize, n_timestep, n_featdim = all_output.shape\n all_output = self.output_func(outputs.reshape(n_batchsize*n_timestep, n_featdim)).reshape(n_batchsize, n_timestep, self.label_size)\n cur_output = (all_output * cur_M.unsqueeze(-1)).sum(dim=1)\n return all_output, cur_output\n\n def surv_loss(self, pred, lifetime, event, device = 'cpu'):\n return loss_func(pred, lifetime, event, device = device)\n\n def training_step(self, train_batch, batch_idx):\n E = self.E\n _, yhat = self.forward(train_batch) \n loss = self.surv_loss(pred = yhat, \n lifetime=torch.tensor(np.sum(train_batch['T'].detach().cpu().numpy(), axis = 1)),\n event=torch.tensor(train_batch['Y'][:, E-1]),\n device='cpu')\n self.log('train_loss', loss)\n \n return {'loss': loss, 'pred': yhat, 'T': train_batch['T'], 'event': train_batch['Y'][:, E-1]}\n\n\n def validation_step(self, val_batch, batch_idx):\n E = self.E\n\n _, yhat = self.forward(val_batch)\n loss = self.surv_loss(pred = yhat, \n lifetime=torch.tensor(np.sum(val_batch['T'].detach().cpu().numpy(), axis = 1)),\n event=torch.tensor(val_batch['Y'][:, E-1]),\n device='cpu')\n\n self.log('val_loss', loss)\n \n def test_step(self, test_batch, batch_idx):\n E = self.E\n _, yhat = self.forward(test_batch)\n acc = concordance_index(np.sum(test_batch['T'].detach().cpu().numpy(), axis = 1), \n np.exp(yhat), \n test_batch['Y'][:, E-1])\n self.log('c-index', acc)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n return optimizer\n\nclass LightningMTLnDeep(pl.LightningModule):\n\n def __init__(self, \n in_features,\n shared_layers = [3],\n num_tasks = None, \n lstm_layers = [3, 3, 5], \n bias = True,\n dropout = 0.0, \n batch_first = True,\n bidirectional = False,\n label_size = 1):\n super().__init__()\n self.save_hyperparameters()\n self.sharedlayer = nn.Sequential(\n nn.Linear(in_features, shared_layers[0]* in_features), \n nn.BatchNorm1d(shared_layers[0]* in_features),\n nn.ReLU(), \n )\n\n if bidirectional:\n layer_input_sizes = [(shared_layers[-1]+1)*in_features] + [2 * chs for chs in lstm_layers]\n else:\n\n layer_input_sizes = [(shared_layers[-1]+1)*in_features] + lstm_layers \n\n self.rnn_models = nn.ModuleList([])\n\n for i in range(len(lstm_layers)):\n self.rnn_models.append(nn.LSTM(input_size = layer_input_sizes[i],\n hidden_size = lstm_layers[i],\n num_layers = len(lstm_layers),\n bias = bias,\n dropout = dropout,\n bidirectional = bidirectional,\n batch_first = batch_first))\n self.in_features = in_features\n self.shared_layers = shared_layers\n self.lstm_layers = lstm_layers\n self.label_size = label_size\n self.output_size = layer_input_sizes[-1]\n self.num_tasks = num_tasks\n self.task = nn.ModuleList()\n for task in range(num_tasks):\n self.task.append(nn.Sequential(\n self.rnn_models,\n nn.Linear(self.output_size, self.label_size)))\n\n self.output_func = nn.Linear(self.output_size, self.label_size)\n \n def forward(self, input_data):\n x_wide = torch.stack([x[0] for x in input_data['X']])\n residual = x_wide.float()\n shared = self.sharedlayer(x_wide.float()) \n shared = torch.cat((shared, residual), dim=1)\n time = np.sum(input_data['T'].detach().cpu().numpy(), axis = 1) \n X = []\n for i in range(len(shared)):\n if time[i]< 2:\n X.append(shared[i])\n else:\n X.append(shared[i].repeat(time[i].astype(int), 1))\n \n # Replicate x_series similar to DatasetReader\n x_series = torch.zeros(len(X),\n len(input_data['M'][0]), \n (self.shared_layers[0]+1) * self.in_features) \n \n for i in range(len(X)): \n x_series[i][:len(X[i]), :] = X[i] \n X = x_series\n M = input_data['M'].float()\n cur_M = input_data['cur_M'].float()\n output = []\n for task in self.task:\n _data = X \n for temp_rnn_model in self.rnn_models: \n _data, _ = temp_rnn_model(_data)\n outputs = _data\n all_output = outputs * M.unsqueeze(-1)\n n_batchsize, n_timestep, n_featdim = all_output.shape\n all_output = self.output_func(outputs.reshape(n_batchsize*n_timestep, n_featdim)).reshape(n_batchsize, n_timestep, self.label_size)\n cur_output = (all_output * cur_M.unsqueeze(-1)).sum(dim=1)\n output.append(cur_output) \n return output \n\n def surv_loss(self, pred, lifetime, event):\n return loss_func(pred, lifetime, event, device='cpu') \n\n def training_step(self, train_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(train_batch) \n train_loss = []\n for i in range(task_nums):\n loss = self.surv_loss(pred = yhat[i], \n lifetime=torch.tensor(np.sum(train_batch['T'].detach().cpu().numpy(), axis = 1)), #to device?\n event=torch.tensor(train_batch['Y'][:, i]),\n ) \n train_loss.append(loss)\n train_loss = sum(train_loss)/len(train_loss)\n self.log('train_loss', train_loss) \n \n return {'loss': train_loss, 'pred': yhat, 'T': train_batch['T'], 'event': train_batch['Y'][:, i]}\n\n\n def validation_step(self, val_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(val_batch) \n val_loss = []\n for i in range(task_nums):\n \n loss = self.surv_loss(pred = yhat[i], \n lifetime=torch.tensor(np.sum(val_batch['T'].detach().cpu().numpy(), axis = 1)), #to device?\n event=torch.tensor(val_batch['Y'][:, i]),\n ) \n val_loss.append(loss)\n val_loss = sum(val_loss)/len(val_loss)\n self.log('val_loss', val_loss)\n \n def test_step(self, test_batch, batch_idx): \n task_nums = self.num_tasks \n yhat = self.forward(test_batch)\n accs = {}\n for i in range(task_nums):\n acc = concordance_index(np.sum(test_batch['T'].detach().cpu().numpy(), axis = 1), \n np.exp(yhat[i]),\n test_batch['Y'][:, i])\n accs['event_' + str(i+1)] = acc\n \n self.log('c-index', accs)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)\n return optimizer\n\n\ndef pl_ndeep(train, train_f, test, valid, input_size, task_name , n_epochs=1):\n model = LightningnDeep(input_size = input_size, \n layer_hidden_sizes = [3,3,5])\n trainer = pl.Trainer(max_epochs=n_epochs)\n trainer.fit(model, train, valid)\n \n test_result = trainer.test(model, dataloaders=test, verbose=False)\n train_result = trainer.test(model, dataloaders=train_f, verbose=False)\n return train_result, test_result\n\ndef pl_mtl_ndeep(train, train_f, test, valid, input_size, num_tasks, n_epochs=1):\n model = LightningMTLnDeep(in_features=input_size, num_tasks=num_tasks)\n trainer = pl.Trainer(max_epochs=n_epochs) \n trainer.fit(model, train, valid) \n train_result = trainer.test(model, dataloaders=train_f, verbose=False)\n test_result = trainer.test(model, dataloaders=test, verbose=False)\n return train_result, test_result","repo_name":"ngocdung03/nDeep","sub_path":"ndeep/lib/pylightning.py","file_name":"pylightning.py","file_ext":"py","file_size_in_byte":10372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"3487712690","text":"import configparser\n\n\nclass ReadIni:\n def __init__(self):\n self.data = self.load_ini()\n\n def load_ini(self):\n cf = configparser.ConfigParser()\n cf.read(r'/Users/zhangjiangtao/PycharmProjects/selenium_chrome/config/LocalElement.ini')\n return cf\n\n # def __init__(self):\n # self.cf = configparser.ConfigParser()\n # self.cf.read(r'/Users/zhangjiangtao/PycharmProjects/selenium_chrome/config/LocalElement.ini')\n\n def get_value(self, list_name, key):\n print(list_name, key)\n return self.data.get(list_name, key)\n\n\nif __name__ == '__main__':\n aa = ReadIni()\n print(aa.get_value('element', 'username'))\n\nread_ini = ReadIni()","repo_name":"zyzcyd/selenium_chrome","sub_path":"read_init.py","file_name":"read_init.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"37236081504","text":"import types\nfrom logging import Logger\nfrom injecta.container.ContainerInterface import ContainerInterface\nfrom injecta.dtype.AbstractType import AbstractType\nfrom injecta.module import attribute_loader\nfrom injecta.parameter.all_placeholders_replacer import replace_all_placeholders, find_all_placeholders\nfrom injecta.service.class_.InspectedArgument import InspectedArgument\nfrom daipecore.decorator.StringableParameterInterface import StringableParameterInterface\n\n\nclass ArgumentResolver:\n def __init__(\n self,\n logger: Logger,\n container: ContainerInterface,\n ):\n self.__logger = logger\n self.__container = container\n\n def resolve(self, function_argument: InspectedArgument, decorator_argument):\n if decorator_argument is not None:\n return self.__resolve_explicit_value(function_argument, decorator_argument)\n\n argument_type = function_argument.dtype\n\n if function_argument.has_default_value():\n return self.__check_type(function_argument.default_value, argument_type, function_argument.name)\n\n if not argument_type.is_defined():\n raise Exception(f'Argument \"{function_argument.name}\" must either have explicit value, default value or typehint defined')\n\n if str(argument_type) == \"logging.Logger\":\n return self.__logger\n\n class_ = attribute_loader.load(argument_type.module_name, argument_type.class_name)\n\n return self.__container.get(class_)\n\n def __resolve_explicit_value(self, function_argument: InspectedArgument, decorator_argument):\n argument_type = function_argument.dtype\n\n if isinstance(decorator_argument, str):\n output = self.__resolve_string_argument(decorator_argument)\n return self.__check_type(output, argument_type, function_argument.name)\n if isinstance(decorator_argument, StringableParameterInterface):\n output = self.__resolve_string_argument(decorator_argument.to_string())\n return self.__check_type(output, argument_type, function_argument.name)\n if isinstance(decorator_argument, types.FunctionType):\n return decorator_argument()(self.__container)\n # isinstance(decorator_argument, InputDecorator) does not work probably due to some cyclic import\n if hasattr(decorator_argument, \"_is_decorator\") and decorator_argument._is_decorator is True: # pylint: disable=protected-access\n return decorator_argument.result\n\n return self.__check_type(decorator_argument, argument_type, function_argument.name)\n\n def __resolve_string_argument(self, decorator_argument):\n if decorator_argument[0:1] == \"@\":\n return self.__container.get(decorator_argument[1:])\n\n matches = find_all_placeholders(decorator_argument)\n\n if not matches:\n return decorator_argument\n\n parameters = self.__container.get_parameters()\n\n return replace_all_placeholders(decorator_argument, matches, parameters, decorator_argument)\n\n def __check_type(self, value, expected_type: AbstractType, argument_name: str):\n value_type_str = value.__class__.__module__ + \".\" + value.__class__.__name__\n expected_type_str = str(expected_type)\n\n if expected_type.is_defined() and value_type_str != expected_type_str:\n expected_type_str = expected_type_str.replace(\"builtins.\", \"\")\n value_type_str = value_type_str.replace(\"builtins.\", \"\")\n raise Exception(f'Argument \"{argument_name}\" is defined as {expected_type_str}, {value_type_str} given instead')\n\n return value\n","repo_name":"daipe-ai/daipe-core","sub_path":"src/daipecore/function/ArgumentResolver.py","file_name":"ArgumentResolver.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"54659293","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\n\r\nfrom ..algorithms.dqn import get_trainee\r\nfrom .trainer_base import _TrainerBase\r\n\r\n\r\nclass TrainerDQN(_TrainerBase):\r\n \"\"\"Trainer for DQN\"\"\"\r\n\r\n def __init__(self, model_name, device,\r\n pos_rm_path, neg_rm_path,\r\n encoder_params, learning_params, model_params,\r\n ep_rm_path=None, seed=None):\r\n super().__init__(\r\n model_name,\r\n device,\r\n pos_rm_path,\r\n neg_rm_path,\r\n encoder_params,\r\n learning_params,\r\n model_params,\r\n ep_rm_path,\r\n seed\r\n )\r\n\r\n def set_trainee(self):\r\n \"\"\"Prepare trainee\"\"\"\r\n # Get model architecture and online-target map\r\n nets, target_map = get_trainee(\r\n self.config_model,\r\n self.device\r\n )\r\n self.dqn, self.target_dqn = nets\r\n self.target_map = target_map\r\n\r\n # Print number of trainable parameters\r\n self._print_num_params(self.dqn.parameters(), name=\"DQN\")\r\n\r\n # Prepare optimizer and scheduler\r\n self.optimizer = optim.AdamW(\r\n self.dqn.parameters(),\r\n lr=self.config_learning[\"learning_rate\"],\r\n amsgrad=True\r\n )\r\n self.optimizers = [self.optimizer]\r\n self.schedulers = self._prepare_schedulers()\r\n self.criterion = nn.SmoothL1Loss()\r\n\r\n # Get DQN type and set correct training step method\r\n double_learning = self.config_model[\"double_learning\"]\r\n if double_learning:\r\n self._training_step = self._training_step_double\r\n elif self.config_model[\"type\"] == \"dueling\":\r\n self._training_step = self._training_step_duel\r\n else:\r\n self._training_step = self._training_step\r\n\r\n def _training_step(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single training step\"\"\"\r\n # Load batch\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n # Compute current q-value\r\n q_value = self.dqn(state, item)\r\n q_value = q_value.squeeze(-1)\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates\r\n next_q_value = self.target_dqn(next_state_rep, candidates)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find max q-value and compute target\r\n max_next_q_value = torch.max(next_q_value, dim=1).values\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _training_step_duel(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single dueling DQN training step\"\"\"\r\n # Load batch\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates\r\n next_vals, next_adv = self.target_dqn(next_state_rep, candidates)\r\n next_q_value = (next_adv - next_adv.nanmean(dim=1).unsqueeze(1)) + \\\r\n next_vals.nanmean(dim=1).unsqueeze(1)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find max q-value and compute target\r\n max_next_q_value = torch.max(next_q_value, dim=1).values\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Compute current q-value\r\n value, adv = self.dqn(state, item)\r\n q_value = value + \\\r\n (adv - next_adv.nanmean(dim=1).nan_to_num(nan=0))\r\n q_value = q_value.squeeze(-1)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _training_step_double(self, batch, step_i, gamma, print_q):\r\n \"\"\"Single double DQN training step\"\"\"\r\n state, item, reward, next_state, candidates, not_done = batch\r\n n_candidates = candidates.shape[1]\r\n\r\n # Compute current q-value\r\n q_value = self.dqn(state, item)\r\n q_value = q_value.squeeze(-1)\r\n\r\n with torch.no_grad():\r\n # Copy next state for each candidate\r\n rep_shape = self._get_rep_shape(state.shape, n_candidates)\r\n next_state_rep = next_state.unsqueeze(1).repeat(*rep_shape)\r\n\r\n # Compute q-values for all candidates with online network\r\n next_q_value = self.dqn(next_state_rep, candidates)\r\n next_q_value = next_q_value.squeeze(-1)\r\n\r\n # Set q-values produced by padded-candidates to large negative number\r\n next_q_value = torch.nan_to_num(next_q_value, nan=-10000)\r\n # Find best candidate\r\n argmax_next_q_value = torch.argmax(next_q_value, dim=1)\r\n best_candidates = candidates[\r\n torch.arange(candidates.shape[0]),\r\n argmax_next_q_value\r\n ]\r\n # Compute q-values for best candidate with target network\r\n max_next_q_value = self.target_dqn(next_state, best_candidates)\r\n max_next_q_value = max_next_q_value.squeeze(-1)\r\n max_next_q_value[(not_done == 0)] = 0.0\r\n q_target = reward + (gamma * max_next_q_value * not_done)\r\n\r\n # Update DQN\r\n if print_q:\r\n print(\"[INFO] example Q values: \")\r\n print(q_value)\r\n loss = self.criterion(q_value, q_target)\r\n self.optimizer.zero_grad()\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n def _get_rep_shape(self, state_shape, n_candidates):\r\n \"\"\"Get correct shape for repeating state\"\"\"\r\n rep_shape = [1, n_candidates, 1]\r\n if len(state_shape) == 3:\r\n rep_shape.append(1)\r\n return rep_shape\r\n","repo_name":"d-vesely/drlnrs","sub_path":"src/rl/trainers/trainer_dqn.py","file_name":"trainer_dqn.py","file_ext":"py","file_size_in_byte":6879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"1185551431","text":"# -*- coding: utf-8 -*-\n\"\"\"\nauthentication test_services module.\n\"\"\"\n\nimport pytest\n\nimport pyrin.security.authentication.services as authentication_services\nimport pyrin.security.session.services as session_services\n\nfrom pyrin.security.exceptions import AuthenticationFailedError\nfrom pyrin.security.authentication.handlers.exceptions import AccessTokenRequiredError, \\\n InvalidAccessTokenError\n\n\ndef test_authenticate_with_fresh_access_token(client_request_fresh_access_token):\n \"\"\"\n authenticates given request with fresh access token and\n pushes the authenticated data into request context.\n \"\"\"\n\n authentication_services.authenticate(client_request_fresh_access_token,\n authenticator='test')\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is not None\n assert client_request.user == 100\n\n\ndef test_authenticate_with_access_token(client_request_access_token):\n \"\"\"\n authenticates given request with access token and\n pushes the authenticated data into request context.\n \"\"\"\n\n authentication_services.authenticate(client_request_access_token,\n authenticator='test')\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is not None\n assert client_request.user == 200\n\n\ndef test_authenticate_with_refresh_token(client_request_refresh_token):\n \"\"\"\n authenticates given request with access token.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(InvalidAccessTokenError):\n authentication_services.authenticate(client_request_refresh_token,\n authenticator='test')\n\n\ndef test_authenticate_without_token(client_request_without_token):\n \"\"\"\n authenticates given request that has no token.\n it should not push anything into request object.\n \"\"\"\n\n with pytest.raises(AccessTokenRequiredError):\n authentication_services.authenticate(client_request_without_token,\n authenticator='test')\n\n client_request = session_services.get_current_request()\n assert client_request is not None\n assert client_request.user is None\n\n\ndef test_authenticate_with_no_identity_token(client_request_no_identity_token):\n \"\"\"\n authenticates given request with an access token\n which has no user identity in it's payload.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(AuthenticationFailedError):\n authentication_services.authenticate(client_request_no_identity_token,\n authenticator='test')\n\n\ndef test_authenticate_with_invalid_token(client_request_invalid_token):\n \"\"\"\n authenticates given request with an invalid token.\n it should raise an error.\n \"\"\"\n\n with pytest.raises(AuthenticationFailedError):\n authentication_services.authenticate(client_request_invalid_token,\n authenticator='test')\n","repo_name":"mononobi/pyrin","sub_path":"src/tests/unit/security/authentication/test_services.py","file_name":"test_services.py","file_ext":"py","file_size_in_byte":3125,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"50"}
+{"seq_id":"75067065756","text":"from investpy.etfs import get_etf_historical_data\nfrom numpy.testing._private.utils import measure\nimport random\nimport pandas as pd\nimport yfinance as yf\nfrom stockService import stocks, update\nimport investpy as ipy\nfrom datetime import datetime\nimport datetime as dt\nimport json\n\n\ndef getSuggestions(input):\n strats = input[\"strats\"].split(\",\")\n products = input[\"products\"].split(\",\")\n result = {}\n for product in products:\n for strat in strats:\n handler = handlerMap[product][strat]\n if handler != None:\n temp = handler(input)\n if len(result) == 0:\n result = temp\n elif list(temp.keys())[0] not in result:\n result.update(temp)\n else:\n curProduct = list(temp.keys())[0]\n curTickers = result[curProduct][\"names\"]\n toAddTickers = temp[curProduct][\"names\"]\n \n curFullNames = result[curProduct][\"full_names\"] if curProduct == \"stock\" else None\n toAddFullNames = temp[curProduct][\"full_names\"] if curProduct == \"stock\" else None\n\n curMeasures = result[curProduct][\"measures\"]\n toAddMeasures = temp[curProduct][\"measures\"]\n\n curHistory = result[curProduct][\"history\"]\n toAddHistory = temp[curProduct][\"history\"]\n for i in range(len(toAddTickers)):\n ticker = toAddTickers[i]\n if ticker in curTickers:\n index = curTickers.index(ticker)\n curMeasures[index] = curMeasures[index] + toAddMeasures[i]\n else:\n curTickers.append(ticker)\n if curProduct == \"stock\":\n curFullNames.append(toAddFullNames[i])\n curMeasures.append(toAddMeasures[i])\n curHistory[ticker] = toAddHistory[ticker]\n\n allsum = 0\n for key in result:\n productRateAve = 0\n productRateSum = sum(result[key][\"measures\"])\n productRateAve = 0 if len(result[key][\"measures\"]) == 0 else productRateSum / len(result[key][\"measures\"])\n result[key][\"rate_ave\"] = productRateAve\n result[key][\"rate_sum\"] = productRateSum\n result[key][\"ratio\"] = [(0 if productRateSum == 0 else tickerRate/productRateSum) for tickerRate in result[key][\"measures\"]]\n allsum += productRateAve\n for key in result:\n result[key][\"spend\"] = 0 if allsum == 0 else round((int)(input[\"amount\"]) * (result[key][\"rate_ave\"] / allsum) , 2)\n if key == \"stock\":\n result[key][\"current\"] = []\n for name in result[key][\"names\"]:\n ticker = yf.Ticker(name)\n history = ticker.history(period=\"1d\", interval=\"1m\")\n lastMin = history.iloc[-1]['Close']\n result[key][\"current\"].append(lastMin)\n return result\n\n\ndef get_etf_names_by_symbols(symbolList):\n allETFs = ipy.get_etfs_dict(columns=[\"name\",\"symbol\"])\n result = [None]*len(symbolList)\n for obj in allETFs:\n if obj['symbol'] in symbolList:\n index = symbolList.index(obj['symbol'])\n result[index] = obj['name']\n return result\n \n \ndef get_growth_etfs(input):\n result={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n \n etf = [ {\"TQQQ\": \"267.71%\"}, {\"SOXL\": \"245.03%\"}, {\"TECL\": \"242.95%\"}, \n {\"ROM\": \"218.33%\"}, {\"ARKG\": \"203.18%\"}, {\"QLD\": \"200.51%\"}]\n \n etf_symbol = [list(pair.keys())[0] for pair in etf]\n names = get_etf_names_by_symbols(etf_symbol)\n \n for i in range(len(etf_symbol)):\n if names[i] != None:\n result[\"ETF\"][\"names\"].append(names[i])\n percent = (float)(etf[i][list(etf[i].keys())[0]].split(\"%\")[0])\n percent = percent / 100\n percent = pow(percent, 1/3)\n result[\"ETF\"][\"measures\"].append(percent)\n result[\"ETF\"][\"history\"][names[i]] = get_eft_history(names[i])\n return result\n\ndef get_growth_stocks(input):\n result={\n \"stock\": {\n \"names\" : [],\n \"full_names\" : [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n for ticker in [key for key in stocks.keys() if key != \"date\"]:\n if \"earnings\" in stocks[ticker]:\n earnings = stocks[ticker][\"earnings\"]\n years = 3\n if len(earnings) >= years+1:\n qualified = True\n rateSum = 0.0\n for i in range(years):\n prevYear = (int)(earnings.iloc[-(i+1)]['Earnings'])\n prevPrev = (int)(earnings.iloc[-(i+2)]['Earnings'])\n if (prevYear - prevPrev) / prevPrev < 0.15:\n qualified = False\n break\n else:\n rateSum += ((prevYear - prevPrev) / prevPrev)\n if qualified:\n result[\"stock\"][\"names\"].append(ticker)\n result[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[ticker][\"info\"] else stocks[ticker][\"info\"][\"shortName\"])\n result[\"stock\"][\"measures\"].append(rateSum/years)\n result[\"stock\"][\"history\"][ticker] = get_history(ticker)\n\n if len(result[\"stock\"][\"names\"]) == 10:\n break\n return result\n\"\"\"\n Only for stocks for now\n\"\"\"\ndef get_history(name):\n history = []\n series = stocks[name]['history']\n if series is not None:\n for i in range(min(len(series), 7)):\n x = series.iloc[[-(i+1)]]\n date = x.index.date[0].strftime(\"%m-%d-%Y\")\n price = x.values[0]\n history.append([date, price])\n return history[::-1]\n\"\"\"\n Pass in etf name\n returns array formatted for chart.js\n\"\"\"\ndef get_eft_history(name):\n history = []\n date = datetime.now().date()\n curr_date = \"{}/{}/{}\".format(\"{0:0=2d}\".format(date.day), \"{0:0=2d}\".format(date.month), \"{0:0=2d}\".format(date.year))\n weekAgo = datetime.now() - dt.timedelta(days=7)\n week_ago = \"{}/{}/{}\".format(\"{0:0=2d}\".format(weekAgo.day), \"{0:0=2d}\".format(weekAgo.month), \"{0:0=2d}\".format(weekAgo.year))\n\n jsonStr = ipy.etfs.get_etf_historical_data(etf=name,\n country='United States',\n from_date=week_ago,\n to_date=curr_date, as_json=True)\n if jsonStr:\n jsonObj = json.loads(jsonStr)\n for obj in jsonObj[\"historical\"]:\n dateStr = obj[\"date\"]\n dateArr = dateStr.split(\"/\")\n mon = dateArr[1]\n day = dateArr[0]\n yr = dateArr[2]\n date = mon + \"-\" + day + \"-\" + yr\n pr = obj[\"high\"]\n history.append([date, pr])\n return history\n\ndef get_value_stocks(input):\n # from the list of stocks, return top three and amount to each stocks\n # select from large cap stocks and choose one that suffered drop recently or traded sideways for a while\n val_stock = []\n measures = [0, 0, 0]\n pegRatio = []\n visited = []\n ret={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n #print(stocks)\n ticker = random.choice(list(stocks.keys()))\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n \n while len(val_stock) < 3:\n visited.append(ticker)\n s = stocks[ticker]\n\n value_tick = 0\n if 'info' in s:\n info = s['info']\n if \"marketCap\" not in info:\n ticker = random.choice(list(stocks.keys()))\n continue\n if info['marketCap'] > 2000000000:\n if 'profitMargins' in info and info['profitMargins'] is not None and info['profitMargins'] >= 0.2:\n value_tick += 1\n if 'priceToBook' in info and info['priceToBook'] is not None and info['priceToBook'] <= 3:\n value_tick += 1\n if 'dividendRate' in info and info['dividendRate'] is not None:\n value_tick += 1\n\n # peg ratio to determine if stock is fairly valued\n if 'pegRatio' in info and info['pegRatio'] is not None and 1 >= info['pegRatio'] >= 0:\n value_tick += 1\n \n if value_tick >= 2:\n val_stock.append(ticker)\n ret['stock']['history'][ticker] = get_history(ticker)\n if 'pegRatio' in info and info['pegRatio'] is not None:\n pegRatio.append(info['pegRatio'])\n else:\n pegRatio.append(99999999999)\n\n # measures.append(value_tick)\n while ticker in visited:\n ticker = random.choice(list(stocks.keys()))\n \"\"\"\n determin allocation of stocks\n stocks with smallest peg is given most allocation\n other are equally allocated\n \"\"\"\n smallestPeg = min(pegRatio)\n indexSmallestPeg = pegRatio.index(smallestPeg)\n \n if (useStock and useETF) :\n if smallestPeg == 99999999999:\n measures = [0.25, 0.25, 0.25]\n else:\n for i in range(len(measures)):\n if i == indexSmallestPeg:\n measures[i] = 0.35\n else:\n measures[i] = 0.2\n ret['stock']['names'] = val_stock\n ret[\"stock\"][\"full_names\"] = [ (\"\" if \"shortName\" not in stocks[n][\"info\"] else stocks[n][\"info\"][\"shortName\"]) for n in val_stock]\n ret['stock']['measures'] = measures[:]\n elif (useStock):\n if smallestPeg == 99999999999:\n measures = [0.25, 0.25, 0.25]\n else:\n for i in range(len(measures)):\n if i == indexSmallestPeg:\n measures[i] = 0.7\n else:\n measures[i] = 0.15\n ret['stock']['names'] = val_stock\n ret[\"stock\"][\"full_names\"] = [ (\"\" if \"shortName\" not in stocks[n][\"info\"] else stocks[n][\"info\"][\"shortName\"]) for n in val_stock]\n ret['stock']['measures'] = measures[:]\n # print(ret)\n return ret\n\ndef get_value_eft(input):\n ret={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n \"\"\"\n VYM has high divdend yields which makes it good value\n VTV tracks the value stocks\n SPY tracks SP500 which is always good value\n \"\"\"\n etf = ['VYM', 'VTV', 'SPY']\n full_etf = get_etf_names_by_symbols(etf)\n vtv = get_etf_names_by_symbols(['VTV'])\n\n measures = [0.25, 0.5, 0.25]\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n if (useStock and useETF) :\n ret['ETF']['names'] = ['VTV'][:]\n ret['ETF']['measures'] = [0.25]\n final_hist = {}\n for i in vtv:\n tmp_hist = get_eft_history(i)\n final_hist['VTV'] = tmp_hist\n # print(final_hist)\n ret['ETF']['history'] = final_hist\n elif (useETF):\n ret['ETF']['names'] = etf[:]\n ret['ETF']['measures'] = measures[:]\n final_hist = {}\n for index, i in enumerate(full_etf):\n tmp_hist = get_eft_history(i)\n final_hist[etf[index]] = tmp_hist\n # print(final_hist)\n ret['ETF']['history'] = final_hist\n return ret\n\n\n\ndef get_ethical_stocks(input):\n '''\n Choose 3 stocks from the top 10 companies that have made great efforts for the environment\n https://www.forbes.com/sites/justcapital/2019/04/22/the-top-33-companies-for-the-environment-by-industry/?sh=7bee72ce6461\n '''\n result={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {},\n },\n }\n \n ethical_stock_tickers_top10 = ['MSFT', 'INTC', 'GOOGL', 'IBM', 'ACN', 'T', 'GM', 'GIS', 'AAPL', 'RMD']\n\n # recommendation score = 10 * past year percentage change + 5 * past 6-month percentage change + 3 * past 3-month percentage change\n recommendation_score_list = {}\n for ticker in ethical_stock_tickers_top10:\n if ticker not in stocks:\n continue\n tk = stocks[ticker]\n history = tk[\"history\"]\n today_data = history.iloc[-1:]\n current_price = round(today_data.values[0], 2)\n total_rows = len(history)\n prev_year_price = round(history.iloc[0], 2)\n prev_6month_price = round(history.iloc[round(total_rows * 0.5)], 2)\n prev_3month_price = round(history.iloc[round(total_rows * 0.75)], 2) \n past_year_percetage_change = (current_price - prev_year_price) / prev_year_price\n past_6month_percentage_change = (current_price - prev_6month_price) / prev_6month_price \n past_3month_percentage_change = (current_price - prev_3month_price) / prev_3month_price \n recommendation_score = 10 * past_year_percetage_change + 5 * past_6month_percentage_change + 3 * past_3month_percentage_change \n recommendation_score_list[ticker] = recommendation_score\n \n # sort recommendation score in descending order\n sorted_recommendation_score_list= sorted(recommendation_score_list.items(), key=lambda x: x[1], reverse=True)\n \n\n # output top 3 stock recommendations\n count = 0\n for stock_ticker, recommendation_score in sorted_recommendation_score_list:\n if count < 3:\n result[\"stock\"][\"names\"].append(stock_ticker)\n result[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[stock_ticker][\"info\"] else stocks[stock_ticker][\"info\"][\"shortName\"])\n result[\"stock\"][\"measures\"].append(recommendation_score)\n result[\"stock\"][\"history\"][stock_ticker] = get_history(stock_ticker)\n count = count + 1 \n else: \n break\n return result\n\n\n\ndef get_ethical_etfs(input):\n '''\n Choose 3 stocks from the top 10 ETFs that are environmentally responsible\n https://etfdb.com/esg-investing/environmental-issues/\n '''\n\n ret={\n \"ETF\": {\n \"names\" : [],\n \"measures\": [],\n \"history\": {},\n },\n }\n\n \n ethical_etf_tickers_top10 = ['KGRN', 'ACES', 'ICLN', 'TAN', 'SMOG', 'CTEC', 'QCLN', 'RNRG', 'FAN', 'SDG']\n\n # recommendation score = 10 * past year percentage change + 5 * past 6-month percentage change + 3 * past 3-month percentage change\n recommendation_score_list = {}\n for ticker in ethical_etf_tickers_top10:\n if ticker not in stocks:\n continue\n tk = stocks[ticker]\n history = tk[\"history\"]\n today_data = history.iloc[-1:]\n current_price = round(today_data.values[0], 2)\n total_rows = len(history)\n prev_year_price = round(history.iloc[0], 2)\n prev_6month_price = round(history.iloc[round(total_rows * 0.5)], 2)\n prev_3month_price = round(history.iloc[round(total_rows * 0.75)], 2) \n past_year_percetage_change = (current_price - prev_year_price) / prev_year_price\n past_6month_percentage_change = (current_price - prev_6month_price) / prev_6month_price \n past_3month_percentage_change = (current_price - prev_3month_price) / prev_3month_price \n recommendation_score = 10 * past_year_percetage_change + 5 * past_6month_percentage_change + 3 * past_3month_percentage_change \n recommendation_score_list[ticker] = recommendation_score\n \n # sort recommendation score in descending order\n sorted_recommendation_score_list= sorted(recommendation_score_list.items(), key=lambda x: x[1], reverse=True)\n \n\n # output top 3 ETF recommendations\n count = 0\n for etf_ticker, recommendation_score in sorted_recommendation_score_list:\n if count < 3:\n ret[\"ETF\"][\"names\"].append(etf_ticker)\n ret[\"ETF\"][\"measures\"].append(recommendation_score)\n ret[\"ETF\"][\"history\"][etf_ticker] = get_history(etf_ticker)\n count = count + 1 \n return ret\n\n\ndef get_index_stocks(input):\n res = {\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\": {}\n },\n }\n '''\n For index strategy, we are using annualReportExpenseRatio as metric. The lower the expenseRatio, the better the stock.\n\n source: \n https://www.forbes.com/advisor/retirement/best-total-stock-market-index-funds/\n https://www.bankrate.com/investing/best-index-funds/\n The following index fund are good index stocks because they have low expense ratio and considerable 5 year return\n FNILX\n SWPPX\n SWTSX\n VTSAX\n FZROX\n FSKAX\n VRTTX\n WFIVX\n '''\n tickers = ['FNILX', 'SWPPX', 'SWTSX', 'VTSAX', 'FZROX', 'FSKAX', 'VRTTX', 'WFIVX']\n #tickers = list(stocks.keys())\n\n products = input['products'].split(',')\n useStock = 'stock' in products\n useETF = 'etf' in products\n\n selected_tickers = []\n measures = []\n stock_dic = {}\n for ticker in tickers:\n stock = yf.Ticker(ticker)\n info = stock.info\n if 'annualReportExpenseRatio' in info and info['annualReportExpenseRatio'] is not None:\n if info['annualReportExpenseRatio'] <= 0.01:\n stock_dic[ticker] = info['annualReportExpenseRatio']\n \n sort_stocks = sorted(stock_dic.items(), key=lambda x: x[1])\n for s in sort_stocks:\n if len(selected_tickers) <=2:\n selected_tickers.append(s[0])\n if (s[1] == 0):\n measures.append(0.00001) \n measures.append(s[1]) \n if (useStock and useETF) :\n selected_tickers.pop()\n measures.pop()\n res[\"stock\"][\"names\"] = selected_tickers\n res[\"stock\"][\"measures\"] = measures\n elif (useStock):\n res[\"stock\"][\"names\"] = selected_tickers\n res[\"stock\"][\"measures\"] = measures\n return res\n\ndef get_index_etfs(input):\n res={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n '''\n source: https://www.bankrate.com/investing/best-index-funds/\n VOO: expense ratio = 0.03%\n SPY: expense ratio = 0.09%\n IVV: expense ratio = 0.03%\n '''\n etf = ['VOO', 'SPY', 'IVV']\n names = get_etf_names_by_symbols(etf)\n measures = [0.4, 0.2, 0.4]\n\n for i in range(len(etf)):\n if names[i] != None:\n res[\"ETF\"][\"names\"].append(etf[i])\n res[\"ETF\"][\"measures\"].append(measures[i])\n res[\"ETF\"][\"history\"][etf[i]] = get_eft_history(names[i])\n return res \n\ndef get_quality_stocks(input):\n res={\n \"stock\": {\n \"names\" : [],\n \"full_names\": [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n\n #https://www.risk.net/definition/quality-factor#:~:text=The%20quality%20factor%20refers%20to,over%20a%20long%20time%20horizon.&text=Quality%2Dbased%20strategies%20try%20to,stocks%20versus%20low%2Dquality%20stocks.\n # use payoutRatio as metric, the higher the better\n selected_stocks = {}\n for ticker in [key for key in stocks.keys() if key != \"date\"]:\n\n stock = stocks[ticker]\n if 'info' in stock:\n info = stock['info']\n if 'payoutRatio' in info:\n payoutRatio = info['payoutRatio']\n if payoutRatio is not None and payoutRatio >= 0.35:\n selected_stocks[ticker] = payoutRatio\n if len(selected_stocks) > 2:\n break\n sort_stocks = sorted(selected_stocks.items(), key=lambda x: x[1], reverse=True)\n for s in sort_stocks:\n res[\"stock\"][\"names\"].append(s[0])\n res[\"stock\"][\"full_names\"].append(\"\" if \"shortName\" not in stocks[s[0]][\"info\"] else stocks[s[0]][\"info\"][\"shortName\"])\n res[\"stock\"][\"measures\"].append(s[1])\n res[\"stock\"][\"history\"][s[0]] = get_history(s[0])\n return res\n\ndef get_quality_etfs(input):\n res={\n \"ETF\": {\n \"names\" : [],\n \"measures\" : [],\n \"history\" : {},\n },\n }\n #https://www.etf.com/sections/features-and-news/dissecting-3-big-quality-etfs\n #https://www.nasdaq.com/articles/5-solid-quality-etfs-to-buy-now-2021-03-26\n selected_etfs = []\n etf = {\"QUAL\": 0.1658, \"SPHQ\": 0.1565, \"DGRW\": 0.1659, \"QDF\": 0.1291, \"IQLT\": 0.1197, \"IQDF\": 0.088599995, \"BFOR\":0.1524, \"QDF\":0.1291, \"QUS\": 0.16420001}\n sort_etfs = sorted(etf.items(), key=lambda x: x[1], reverse=True)\n measures = [0.5, 0.3, 0.2]\n for e in sort_etfs:\n if len(selected_etfs) <=2:\n selected_etfs.append(e[0])\n measures.append(measures[len(selected_etfs) - 1]) \n\n names = get_etf_names_by_symbols(selected_etfs)\n\n for i in range(len(selected_etfs)):\n if names[i] != None:\n res[\"ETF\"][\"names\"].append(selected_etfs[i])\n res[\"ETF\"][\"measures\"].append(measures[i])\n res[\"ETF\"][\"history\"][selected_etfs[i]] = get_eft_history(names[i])\n return res\n\nhandlerMap = {\n \"stock\":{\n \"ethical\": get_ethical_stocks,\n \"growth\": get_growth_stocks,\n \"quality\": get_quality_stocks,\n \"index\": get_index_etfs,\n \"value\": get_value_stocks,\n },\n \"etf\": {\n \"ethical\": get_ethical_etfs,\n \"growth\": get_growth_etfs,\n \"quality\": get_quality_etfs,\n \"index\": get_index_etfs,\n \"value\": get_value_eft,\n },\n}\n\n","repo_name":"lhy2016/Investment-Strategy","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":21846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"74148656476","text":"# -*- coding: utf-8 -*-\n\nfrom algo.common.setting import local_config\nfrom algo.kernal.images_download import ImageDownload\nfrom algo.kernal.reviewresult_upload import ReviewResultUpload\nfrom algo.kernal.image_processing import ImageProcessing\nfrom algo.kernal.recognition_engine import RecognitionEngine\nfrom algo.kernal.dataset import MyDataset\nfrom algo.kernal.classification_engine import ClassificationEngine\nfrom algo.common.logger import log\nimport os\nfrom torch.utils.data import DataLoader\n\n\nclass Main(object):\n \"\"\"图片审核算法主程序\"\"\"\n def __init__(self, key):\n \"\"\"初始化参数\"\"\"\n log.info(\"图片审核算法开始运行......\")\n log.info(\"初始化图片路径、分类模型路径及敏感词汇库路径......\")\n self.key = key\n current_path = os.path.dirname(__file__)\n self.imgs_path = os.path.join(current_path, local_config[\"images_path\"])\n self.model_path = os.path.join(current_path, local_config[\"model_path\"])\n self.vocabulary_path = os.path.join(current_path, local_config[\"vocalbulary_path\"])\n log.info(\"初始化完毕!\")\n self.image_download()\n self.imgs_name = os.listdir(self.imgs_path)\n\n def image_download(self):\n \"\"\"下载图片\"\"\"\n log.info(\"从数据库中下载待审核图片......\")\n download_engine = ImageDownload(self.key)\n download_engine.download()\n log.info(\"下载完毕!\")\n\n def result_upload(self, review_result):\n \"\"\"将审核结果上传至数据库\"\"\"\n log.info(\"将审核结果上传至数据库中......\")\n upload_engine = ReviewResultUpload(review_result)\n upload_engine.upload()\n log.info(\"上传完毕!\")\n\n def images_delete(self):\n \"\"\"审核结束后删除images\"\"\"\n log.info(\"删除已审核图片......\")\n for img_name in self.imgs_name:\n os.remove(os.path.join(self.imgs_path, img_name))\n log.info(\"删除完毕!\")\n\n def review(self):\n \"\"\"审核器\"\"\"\n log.info(\"审核开始......\")\n datasets = MyDataset(self.imgs_path)\n dataloader = DataLoader(datasets, batch_size=1)\n classification_engine = ClassificationEngine(self.imgs_name, self.model_path)\n classified_result = classification_engine.classifier(dataloader)\n review_result = {}\n for img_name, result in classified_result.items():\n imageid = img_name.split(\".\")[0]\n if result == 0:\n review_result[imageid] = result\n else:\n img_path = os.path.join(self.imgs_path, img_name)\n processing_engine = ImageProcessing(img_name, img_path)\n sub_imgs = processing_engine.get_tailored_img()\n recognition_engine = RecognitionEngine(img_name, sub_imgs, self.vocabulary_path)\n review_result[imageid] = recognition_engine.recognizer()\n log.info(\"审核结束!\")\n self.result_upload(review_result)\n self.images_delete()\n log.info(\"图片审核算法执行完毕!\")\n\n\nif __name__ == '__main__':\n review_engine = Main(key=\"algo_mysql\")\n review_engine.review()\n\n\n\n\n\n\n","repo_name":"DeerZhifan/Images_Review_Project","sub_path":"engine_main.py","file_name":"engine_main.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"32651156737","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 17 23:52:56 2015\n\n@author: gibon\n\nfrom http://codereview.stackexchange.com/questions/39642/helper-function-to-solve-project-euler-question-26\n\"\"\"\n\ndef cycle_length(d):\n \n if not isinstance(d, int) or d <= 0:\n raise ValueError(\"cycle_length(d): d must be a positive integer\")\n \n rlist = [] # list of remainder\n qlist_len = 0\n remainder = 1\n \n while remainder:\n remainder = remainder % d\n if remainder in rlist:\n return qlist_len - rlist.index(remainder)\n rlist.append(remainder)\n remainder *= 10\n qlist_len += 1\n \n return 0\n\nc_max = [0,0]\n\nif __name__ == '__main__':\n for d in range(1,1000): #d = raw_input('d: ')\n try:\n c = cycle_length(int(d))\n print('1/%s =' % (d), c)\n if c > c_max[1]:\n c_max[1] = c\n c_max[0] = int(d)\n except ValueError:\n print('invalid input')\n \n print('Solution to problem 26 is %i (cycle %i).'%(tuple(c_max)))","repo_name":"thomasgibon/project-euler","sub_path":"026.py","file_name":"026.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"33313544915","text":"def data_type(arg):\n # checking the argument type and returning the appropriate result\n if type(arg) == str:\n return len(arg)\n elif type(arg) == bool:\n return arg\n elif type(arg) == int:\n if arg < 100:\n return 'less than 100'\n elif arg > 100:\n return 'more than 100'\n else:\n return 'equal to 100'\n elif type(arg) == list:\n if len(arg) >= 3:\n return arg[2]\n else:\n return None\n else:\n return 'no value'","repo_name":"joemug23/bootcamp_execrises","sub_path":"andelabs/data_structure_lab.py","file_name":"data_structure_lab.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"50"}
+{"seq_id":"41302132135","text":"import socketserver\nimport json\nimport configparser\nimport os, sys\n\nPath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(Path)\nfrom conf import settings\nimport os\n\ns_code = {\n 250: \"invalid cmd format, e.g: {'action':'get','filename':'text.py','size':344}\",\n 251: \"invalid cmd\",\n 252: \"invalid auth data\",\n 253: \"wrong username or password\",\n 254: \"passed authentication\",\n 255: \"filename doesn't provided\",\n 256: \"file doesn't exist on server\",\n 257: \"ready to send file\",\n 258: \"md5 verification\",\n\n 800: \"the file exist but not enough, is countinue\",\n 801: \"the flie exist!\",\n 802: \"ready to receive datas\",\n\n 900: \"md5 valdate success\"\n\n}\n\n\nclass MySever(socketserver.BaseRequestHandler):\n def handle(self):\n # print(\"conn is\", self.request)\n # print(\"addr is:\", self.client_address)\n while True:\n try:\n\n data = self.request.recv(1024).strip()\n print(\"data-----\", data)\n if len(data) == 0: break\n\n data = json.loads(data.decode(\"utf-8\"))\n print(\"data:\", type(data))\n\n if data.get(\"action\"):\n print(str(data.get(\"action\")))\n if hasattr(self, \"%s\" % data.get(\"action\")):\n func = getattr(self, data.get(\"action\"))\n func(**data)\n else:\n print(\"Invalid cmd\")\n self.send_answer(251)\n else:\n print(\"Invalid cmd\")\n self.send_answer(250)\n\n # self.request.sendall(a.encode(\"utf-8\"))\n except Exception as e:\n print(e)\n break\n\n def send_answer(self, s_code):\n answer = {\"s_code\": s_code}\n self.request.sendall(json.dumps(answer).encode(\"utf-8\"))\n\n def auth(self, **data):\n username = data[\"username\"]\n password = data[\"password\"]\n urse = self.jude(username, password)\n if urse:\n self.send_answer(254)\n else:\n self.send_answer(253)\n\n def jude(self, urse, pwd):\n cfg = configparser.ConfigParser()\n cfg.read(settings.ACCOUNT_PATH)\n if urse in cfg.sections():\n\n if cfg[urse][\"password\"] == pwd:\n self.ures = urse\n self.mainpath = os.path.join(settings.BASE_DIR, \"home\", self.ures)\n print(\"weclcome\")\n return urse\n\n def put(self, **data):\n print(\"data\", type(data))\n file_name = data.get(\"file_name\")\n file_size = data.get(\"file_size\")\n targerpath = data.get(\"targerpath\")\n\n abs_path = os.path.join(self.mainpath, targerpath, file_name)\n\n big = 0\n\n if os.path.exists(abs_path):\n has_size = os.stat(abs_path).st_size\n if has_size < file_size:\n self.request.sendall(\"800\".encode(\"utf-8\"))\n choise = self.request.recv(1024).decode(\"utf-8\")\n if choise == \"Y\":\n self.request.sendall(str(has_size).encode(\"utf-8\"))\n big += has_size\n f = open(abs_path, \"ab\")\n\n else:\n f = open(abs_path, \"wb\")\n else:\n self.request.sendall(\"801\".encode(\"utf-8\"))\n return\n else:\n self.request.sendall(\"802\".encode(\"utf-8\"))\n f = open(abs_path, \"wb\")\n\n while big < file_size:\n try:\n data = self.request.recv(1024)\n\n except Exception as e:\n break\n f.write(data)\n big += len(data)\n f.close()\n\n def Is(self, **data):\n g_file = os.listdir(self.mainpath)\n file_str = \"\\n\".join(g_file)\n if not len(g_file):\n file_str = \"\"\n self.request.sendall(file_str.encode(\"utf-8\"))\n return\n\n def cd(self, **data):\n\n dirname = data.get(\"dirname\")\n if dirname == \"..\":\n self.mainpath = os.path.dirname(self.mainpath)\n else:\n self.mainpath = os.path.join(self.mainpath, dirname)\n self.request.sendall(self.mainpath.encode(\"utf-8\"))\n\n def download(self, **data):\n dirname = data.get(\"dirname\")\n download_file = os.path.join(self.mainpath, dirname)\n file_size = os.stat(download_file).st_size\n self.request.sendall(str(file_size).encode(\"utf-8\"))\n is_exist = self.request.recv(1024).decode(\"utf-8\")\n\n has_sent = 0\n\n if is_exist == \"800\":\n self.request.sendall(\"the file exist,but not enough,is countinue?[Y/N]\".encode(\"utf-8\"))\n answer = self.request.recv(1024).decode(\"utf-8\")\n if answer == \"Y\":\n print(\"ssssss\")\n v = self.request.recv(1024).decode(\"utf-8\")\n print(v)\n has_sent += int(v)\n print(has_sent)\n else:\n self.request.sendall(\"N\".encode(\"utf-8\"))\n elif is_exist == \"801\":\n return\n a = open(download_file, \"rb\")\n while has_sent < file_size:\n data = a.read(1024)\n self.request.sendall(data)\n has_sent += len(data)\n a.close()\n\n def mkdir(self, **data):\n dirname = data.get(\"dirname\")\n path = os.path.join(self.mainpath, dirname)\n if not os.path.exists(path):\n if \"/\" in dirname:\n os.makedirs(path)\n else:\n os.mkdir(path)\n\n self.request.sendall(\"dirname exist\".encode(\"utf-8\"))\n else:\n self.request.sendall(\"dirname exist\".encode(\"utf-8\"))\n\n def register(self, **data):\n username = data.get(\"username\")\n password = data.get(\"password\")\n cfg = configparser.ConfigParser()\n cfg.read(settings.ACCOUNT_PATH)\n print(username, password, type(username), type(password))\n cfg[username] = {}\n cfg[username][\"password\"] = password\n cfg[username][\"quotation\"] = \"100\"\n\n with open(settings.ACCOUNT_PATH, \"w\") as f:\n cfg.write(f)\n path = os.path.join(settings.BASE_DIR, \"home\", username)\n os.mkdir(path)\n\n self.request.sendall(\"Account setup successful please continue other operations\".encode(\"utf-8\"))\n\n\nif __name__ == \"__main__\":\n s = socketserver.ThreadingTCPServer((\"127.0.0.1\", 8000), MySever)\n s.serve_forever()\n","repo_name":"tanghaoen/FTP_poject","sub_path":"FTP_1/FTP_sever/core/mysever.py","file_name":"mysever.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"20166508850","text":"from math import pi\nfrom typing import Type\n\ndef circle_area(radius):\n if type(radius) not in [int, float]:\n raise TypeError(\"The radius must be a non-negative real number\")\n \n if radius < 0:\n raise ValueError(\"The radius cannot be negative\")\n\n return pi*(radius**2)\n\n# print(circle_area(7))","repo_name":"codewithlennylen/Software-Testing","sub_path":"Unit-testing/Socratica/circles.py","file_name":"circles.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"3636587974","text":"#元组拆包\r\n\"\"\"\r\nx,y = (1,2)\r\nprint(\"%d、%d\" % (x,y)) #1、2\r\nx,y = y,x #交换两个元素\r\nprint(\"%d、%d\" % (x,y)) #2、1\r\n\"\"\"\r\n\"\"\"\r\npoints = [(\"x\",1),(\"y\",2)]\r\nfor point in points:\r\n print(\"%s:%d\" % point) #x:1 y:2 列表会报错\r\n\"\"\"\r\n\"\"\"\r\n#*可把元组拆开作为函数参数\r\nprint(divmod(20,8))\r\nt = (20,8)\r\nprint(divmod(*t))\r\n#*处理剩下元素\r\na,b,*rest,c = range(5) #a=0,b=1,rest=[2,3],c=4\r\na,b,*rest,c,d,e = range(5) #rest=[]\r\n\"\"\"\r\n\"\"\"\r\nfrom collections import namedtuple\r\npoint = namedtuple(\"point\",'x y z')\r\npoint1 = point(1,2,3) #point(x=1, y=2, z=3)\r\nprint(point1.y) #2\r\nprint(point1._fields) #('x', 'y', 'z')\r\npoint2 = point1._make(range(4,7)) #point(x=4, y=5, z=6)\r\n#_make() 跟 *类似相当于以下代码\r\na = range(4,7)\r\npoint2 = point(*a) #point(x=4, y=5, z=6)\r\n#point2 = point(*range(4,7)) #point(x=4, y=5, z=6)\r\nprint(point2._asdict()) #{'x': 4, 'y': 5, 'z': 6}\r\n\"\"\"\r\n\"\"\"\r\n#元组没有__reversed__方法,但可以使用reversed(tuple)\r\npoints = range(5)\r\nfor point in reversed(points):\r\n print(point) #4 3 2 1 0\r\n\"\"\"\r\n#元组方法:\r\n#s.__contains__(e) 即 in\r\n#s.count(e) e出现的次数\r\n#s.__getitem__(p) 即s[p]\r\n#s.__getnewargs__() 列表没有,元组有\r\n#s.index(e) e第一次出现的位置\r\n#s.__iter__() 迭代器\r\n#s.__len__() len(s)\r\n#s.__mul__(n) s * n n个s重复拼接\r\n#s.__rmul__(n) n * s 反向拼接\r\n\r\n#切片操作 slice(a,b,c)\r\n#s = 'bicycle'\r\n#s[a:b:c] 在a和b直接以c为间隔取值,c可以为负数\r\n#print(s[slice(3,None)]) #ycle\r\n#print(s[3:]) #从下标为3的地方分割,ycle\r\n#print(s[::3]) #对s每隔3个取一次值,bye\r\n#print(s[::-1]) #elcycib\r\n#print(s[:3:-1]) #elc\r\n#print(s[3::-2]) #yi\r\n#赋值\r\n#s[:3] = ['a'] #TypeError: 'str' object does not support item assignment\r\n#l = list(range(10)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n#l[:3] #[0, 1, 2]\r\n#l[:3] = [-1] #[-1, 3, 4, 5, 6, 7, 8, 9]\r\n#l[:3] = list(range(10,15)) #[10, 11, 12, 13, 14, 3, 4, 5, 6, 7, 8, 9]\r\n#del l[:3] #[3, 4, 5, 6, 7, 8, 9]\r\n#print(l*2) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n#print(l+list(range(10,15))) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\r\n\"\"\"\r\n#l1 = [['_']*3] * 3 #[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']] \r\n#l得到的其实是3个['_', '_', '_']的引用 而不是3个['_', '_', '_']里面的值\r\n#l1[1][1] = 'X' #[['_', '_', 'X'], ['_', '_', 'X'], ['_', '_', 'X']]\r\n#等同于以下操作:\r\nl = ['_']*3\r\nl1 = []\r\nfor i in range(3):\r\n l1.append(l) #每一次都将l加入\r\n #l1.append(l[:]) #每一次都将l所有值加入\r\nl1[1][1] = 'X'\r\nprint(l1)\r\n\"\"\"\r\n\"\"\"\r\nl2 = [['_']*3 for i in range(3)]\r\nl2[1][1] = 'X' #[['_', '_', '_'], ['_', 'X', '_'], ['_', '_', '_']]\r\nprint(l2)\r\n#等同于以下操作:\r\nl2 = []\r\nfor i in range(3):\r\n l = ['_']*3 #每一次都新建一个列表加入\r\n l2.append(l) \r\nl2[1][1] = 'X'\r\nprint(l2)\r\n\"\"\"\r\n'''\r\n#对元组进行+=运算\r\n#元组元素是不能修改的,但下面t确实修改了\r\nt = (1,2,[3,4])\r\n\"\"\"\r\ntry:\r\n t[2]+=[5,6] #TypeError: 'tuple' object does not support item assignment\r\nexcept TypeError:\r\n print(t) #(1, 2, [3, 4, 5, 6])\r\n实际上:\r\n1、将t[2]的值存入了TOS(TOP Of Stack,栈的顶端)\r\n2、计算 TOS += [5,6],即[3,4] += [5,6] 这一步是可以完成的,TOS一个可变对象\r\n3、对t[2] = TOS 赋值。失败,因为t是不可变的元组\r\n\"\"\"\r\nTOS = t[2] #[3, 4] TOS即是t[2]的引用\r\n#TOS = t[2][:] #[3, 4] TOS即是t[2]的值\r\nTOS += [5,6] #[3, 4, 5, 6] 即t[2]已经是[3, 4, 5, 6]\r\nprint(t) #(1, 2, [3, 4, 5, 6])\r\ntry:\r\n t[2] = TOS\r\nexcept TypeError:\r\n print(t)\r\n#t[2].extend([5,6]) #(1, 2, [3, 4, 5, 6]) 没有异常可以实现\r\n#print(t)\r\n'''\r\n\r\n#排序\r\n#list.sort 就地排序,即不会;把原列表拷贝一份进行排序\r\n#内置函数 sorted 会新建一个列表作为返回值,故可以接受任何形式的参数(可变、不可变、...),最终都会返回一个列表\r\n#sorted 可选关键字参数:\r\n#reverse:如果设定为True,则降序排列(由大到小),默认是False\r\n#key:排序算法依赖对比的关键字,如key=str.lower忽略大小写排序,key=len以长度进行排序\r\n#l = list(range(5,0,-1)) #[5, 4, 3, 2, 1]\r\n#print(l.sort()) #返回#None会被忽略\r\n#print(l) #[1, 2, 3, 4, 5]\r\n#None:如果一个函数或者方法对对象进行的是就地改动,返回None,让调用者只读传入的参数发生了变化并未产生新的对象\r\n\r\n#fruits = ['grape', 'raspberry', 'apple', 'banana']\r\n#print(sorted(fruits)) #['apple', 'banana', 'grape', 'raspberry']\r\n#原fruits排序没有变化\r\n#print(fruits) #['grape', 'raspberry', 'apple', 'banana']\r\n#print(sorted(fruits,reverse=True)) #['raspberry', 'grape', 'banana', 'apple']\r\n#print(sorted(fruits,key=len)) #['grape', 'apple', 'banana', 'raspberry']\r\n#fruits.sort() #原排序发生了变化\r\n#print(fruits) #['apple', 'banana', 'grape', 'raspberry']\r\n\"\"\"\r\nl = [28,14,'28',1,'12',5,0,6,19,23,'27']\r\nprint(sorted(l,key=int)) #[0, 1, 5, 6, '12', 14, 19, 23, '27', 28, '28']\r\nprint(sorted(l,key=str)) #[0, 1, '12', 14, 19, 23, '27', 28, '28', 5, 6]\r\n\"\"\"\r\n#有序序列插入元素\r\n#bisect(haystack, needle) \r\n#在haystack中查找needle的位置\r\n#导入bisect\r\n'''\r\nimport bisect\r\n#l = list(range(1,10,2)) #[1, 3, 5, 7, 9]\r\n#index = bisect.bisect(l,6) #3\r\n#l.insert(index,6) #[1, 3, 5, 6, 7, 9]\r\n#使用bisect.insort()插入新元素\r\n#bisect.insort(l,6) #[1, 3, 5, 6, 7, 9]\r\n#print(l)\r\n\"\"\"分数跟成绩对应函数\"\"\"\r\ndef grade(score,points=[60,70,80,90,100],grade='FDCBAS'):\r\n i = bisect.bisect(points,score)\r\n return grade[i]\r\nprint([grade(score) for score in [33,99,77,70,89,90,100]]) #['F', 'A', 'C', 'C', 'B', 'A', 'S']\r\n\r\n\r\n'''\r\n#数组 array\r\n#数组对数字类型文件的读写操作\r\n#array.tofile 写方法\r\n#array.fromfile 读方法\r\n#from array import array\r\n#from random import random\r\n#创建一个double(d)型的数组\r\n#floats = array('d',(random() for i in range(10**7)))\r\n\"\"\"\r\nwith open('floats.bin','wb') as fp:\r\n floats.tofile(fp)\r\nfloats2 = array('d')\r\nwith open('floats.bin','rb') as fp:\r\n floats2.fromfile(fp,10**7)\r\n\"\"\"\r\n#对数组进行复制操作copy.copy、copy.deepcopy\r\n#导入copy包里的copy\r\n#from copy import copy\r\n#from copy import deepcopy\r\n#floats2 = copy(floats)\r\n#print(floats2[-1] == floats[-1]) #True\r\n'''\r\n\"\"\"copy.copy和copy.deepcopy的区别\"\"\"\r\n\"\"\"经过copy操作得到的两个拥有不同的地址,但列表里面如果还有列表,则里面的列表拥有相同的地址,即如果修改里面的列表,原列表也会被修改\r\n经过deepcopy操作得到的两个拥有不同的地址,且列表里面如果还有列表,则里面的列表也拥有不同的地址,即对新列表操作不影响原列表\"\"\"\r\nlist1 = list(range(3))+[[11,22]] #[0, 1, 2, [11, 22]]\r\nn_list2 = copy(list1)\r\nd_list2 = deepcopy(list1)\r\n#对使用deepcopy的列表进行操作\r\nd_list2[-1]+=[12]\r\n#原列表的值没有被修改\r\nprint(list1) #[0, 1, 2, [11, 22]]\r\nprint(d_list2) #[0, 1, 2, [11, 22, 12]]\r\n#对使用copy的列表进行操作\r\nn_list2[-1]+=[12]\r\n#原列表的值被修改\r\nprint(list1) #[0, 1, 2, [11, 22, 12]]\r\nprint(n_list2) #[0, 1, 2, [11, 22, 12]]\r\n'''\r\n'''\r\narray1 = array('b',(1,2,3)) #一个存储byte类型的数组array('b', [1, 2, 3])\r\n#使用extend()添加可迭代列表,如果有TypeError异常,之前添加的元素还存在\r\n#使用fromlist()添加可迭代列表,如果有TypeError异常,则取消所有添加\r\n\"\"\"\r\ntry:\r\n array1.extend((4,5,'6')) #array('b', [1, 2, 3, 4, 5])\r\nexcept TypeError:\r\n print(array1) \r\n\"\"\"\r\n\"\"\"\r\ntry:\r\n array1.fromlist((4,5,'6')) #array('b', [1, 2, 3])\r\nexcept TypeError:\r\n print(array1) \r\n\"\"\"\r\n'''\r\n#s.itemsize 返回数组中元素长度的字节数'b':1、'i':4、'f':4、'l':4、'd':8\r\n#s.typecode 返回数组的存储类型:b、i、...\r\n#s.tolist() 转换为列表,元素是数字对象\r\n#数组排序 python 3.4后数组类型不再支持list.sort()这种就地排序方法。要排序只能新建一个数组\r\n#array1 = array('b',(2,1,6))\r\n#array1 = array(array1.typecode,sorted(array1)) #array('b', [1, 2, 6])\r\n#print(array1)\r\n#对已是有序序列的数组可以使用bisect.insort进行插入\r\n#import bisect\r\n#bisect.insort(array1,5) #array('b', [1, 2, 5, 6])\r\n\r\n#memoryview\r\n#Numpy\r\n#SciPy\r\n\r\n#双向队列 collections.deque\r\n#from collections import deque\r\n#dq = deque(range(7), maxlen=7) #deque([0, 1, 2, 3, 4, 5, 6], maxlen=7), maxlen=5) \r\n#maxlen 可选参数,表示队列最大容纳元素的数量,一旦设定无法改变\r\n#.rotate(n),当n>0,表示把最右n个元素移到队列左边,当n<0时,将最左移到右边\r\n#dq.rotate(3) #deque([4, 5, 6, 0, 1, 2, 3], maxlen=7)\r\n#dq.rotate(-3) #deque([3, 4, 5, 6, 0, 1, 2], maxlen=7)\r\n#appendleft在队列头部添加元素,append在队列尾部添加元素\r\n#extendleft按迭代器里面的元素逐个添加,故会逆序出现在队列\r\n#当len()>maxlen时会挤掉另一端元素\r\n#dq.appendleft(-1) #deque([-1, 0, 1, 2, 3, 4, 5], maxlen=7)\r\n#dq.append(-1) #deque([1, 2, 3, 4, 5, 6, -1], maxlen=7)\r\n#dq.extend([11,12,13]) #deque([3, 4, 5, 6, 11, 12, 13], maxlen=7)\r\n#dq.extendleft([11,12,13]) #deque([13, 12, 11, 0, 1, 2, 3], maxlen=7)\r\n#pop()、popleft()\r\n#print(dq)\r\n\r\n\r\n#字典(dict)\r\n\"\"\"\r\n#创建一个{'one': 1, 'two': 2, 'three': 3}的字典\r\na = dict(one=1,two=2,three=3)\r\nb = {'one':1,'two':2,'three':3}\r\nc = dict(zip(['one','two','three'],[1,2,3]))\r\nd = dict([('two',2),('one',1),('three',3)])\r\ne = dict({'three':3,'one':1,'two':2})\r\nprint(a==b==c==d==e) #True\r\n\"\"\"\r\n#字典推导:\r\n#l = [(1, 'one'), (2, 'two'), (3, 'three')]\r\n#dict1 = {s_num:num for num,s_num in l} #{'one': 1, 'two': 2, 'three': 3}\r\n#d.keys() 所有的键\r\n#d.values() 所有的值\r\n#d.get(k,[default]) 返回键k对应的值,如果不存在则返回None或[default]\r\n#d.setdefult(k,[default]) 返回键k对应的值,如果不存在则添加d[k] = [default],然后返回[default]\r\n#print(dict1.get('one')) #1\r\n#print(dict1.get('o')) #None\r\n#print(dict1.get('o','not found')) #not found\r\n#print(dict1.setdefault('one')) #1\r\n#print(dict1.setdefault('four',4)) #4 dict1 = {'one': 1, 'two': 2, 'three': 3, 'four': 4}\r\n#d.items() 返回所有的键值对\r\n#for key,value in dict1.items():\r\n# print(key+\":\"+str(value)) #one:1 two:2 three:3\r\n#d.pop(k,[default]) #返回k所对应的键,并移除,如果不存在则返回None或[default]\r\n#d.popitem() #返回最后一个键值对并移除它吧!!!有些资料上写着作用是随机返回(翻译有误吧)一个键值对并移除它,但测试了一下是返回最后一个\r\n#print(\"key:%s,value:%d\"%dict1.popitem()) #key:three,value:3\r\n#for i in range(10):\r\n# dict1 = dict(zip('a b c d e f g h i j k l n m o p q r s t u v w x y z'.split(),list(range(1,27))))\r\n# print(\"key:%s,value:%d\"%dict1.popitem()) #输出结果全是key:z,value:26\r\n#d.update(m, [**kargs]) 如果key已存在,则会更新对应的value\r\n#如果m存在keys方法,则对dict1更新m和[**kargs]\r\n#如果不存在则会当作包含键值对(key,value)元素的迭代器\r\n#dict1.update(dict1,four=4,five=5) #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}\r\n#dict2 = {'four':4,'five':5,'one':11}\r\n#d = zip(['eight','nine'],[8,9])\r\n#dict1.update(dict2,six=6,nana=7) #{'one': 11, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'nana': 7}\r\n#dict1.update(d,one=1) #{'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'nana': 7, 'eight': 8, 'nine': 9}\r\n#print(dict1)\r\n\"\"\"\r\n#__missing__\r\n#基类dict没有定义这个方法,但dict是知道有这么一个方法。\r\n#如果一个类继承了dict且提供了一个__missing__方法,那么在__getitem__找不到键时(d[k]),会调用它\r\n\r\nclass StrKeyDict(dict):\r\n def __missing__(self,key):\r\n if isinstance(key,str):\r\n raise KeyError(key)\r\n return self[str(key)]\r\n def get(self,key,default=None):\r\n try:\r\n return self[key]\r\n except KeyError:\r\n return default\r\n def __contains__(self,key):\r\n return key in self.keys() or str(key) in self.keys()\r\n \r\nstr_dict = StrKeyDict({'1':'one','2':'two','3':'three'})\r\nprint(str_dict[1]) #one\r\n#str_dict[1]先调用__getitem__方法,没有找到,调用__missing__\r\n#__missing__方法先是判断1是不是字符串,如果是直接引发异常,如果不是将其返回用字符串再查一遍\r\n\"\"\"\r\n#其他字典\r\n\"\"\"\r\n#collections.Counter 用于计算各个字母出现的次数\r\n#most_common([n]) 返回计数中最常见的n个键和它的计数\r\nfrom collections import Counter\r\nct = Counter('sadhjkashcjaksga') #Counter({'a': 4, 's': 3, 'h': 2, 'j': 2, 'k': 2, 'd': 1, 'c': 1, 'g': 1})\r\n#ct = Counter(a=5,b=1,c=7)\r\nct.update('asddasd') #Counter({'a': 6, 's': 5, 'd': 4, 'h': 2, 'j': 2, 'k': 2, 'c': 1, 'g': 1})\r\nct2 = Counter('vo da vi vi'.split()) #Counter({'vi': 2, 'vo': 1, 'da': 1})\r\nct2.update('vo da vi vi'.split()) #Counter({'vi': 4, 'vo': 2, 'da': 2})\r\nprint(ct.most_common(3)) #[('a', 6), ('s', 5), ('d', 4)]\r\n\"\"\"\r\n#不可变映射类型\r\n#types.MappingProxyType\r\nfrom types import MappingProxyType\r\nd = {1:'A'}\r\nd_proxy = MappingProxyType(d) #{1: 'A'}\r\n#d_proxy[2] = 'B' #TypeError: 'mappingproxy' object does not support item assignment\r\n#d[2] = 'B' #d_proxy = {1: 'A', 2: 'B'}\r\n#print(d_proxy) \r\n\r\n#集合\r\n#set、frozenset\r\n#a|b,a与b的合集 a&b,a与b的交集 a-b,a与b的差集\r\ns = {1} #type: {1}\r\nprint(s.pop()) #1 s:set()\r\n#空集\r\n#s = {} #type:\r\n#s = set() #type:\r\n#print(type(s)) ","repo_name":"yRxf/python","sub_path":"tuple-list_test.py","file_name":"tuple-list_test.py","file_ext":"py","file_size_in_byte":14830,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"29108609620","text":"'''Module for the parsing on input data from .tia file.'''\n\n# Provides:\n# readIn\n# dicOf\n\nimport numpy as np\nfrom ..helpers import settings\nfrom ..helpers.units import *\nfrom ..helpers.tools import InputError\n\n# these defs are for evaluation from input file\npi = np.pi\ncos = np.cos\nsin = np.sin\ntan = np.tan\narcsin = np.arcsin\narccos = np.arccos\narctan = np.arctan\nsqrt = np.sqrt\nexp = np.exp\n\ndef readIn(name):\n '''Finds the input data in a file.\n\n Returns a list of tuples where tuple[0] identifies the object of which data\n has been found and tuple[1] the data itself. tuple[1] may be a simple value\n or a dictionary for constructors, etc.\n\n Example return value: [ ('bd', {'X': 0., 'Y': 0., 'Z': 1.}), #constructor\n ('LName', 'foo')] #string data.\n\n name: file to read. [string]\n\n May raise an InputError.\n\n Returns a list of tuples.\n\n '''\n\n #error messages\n malformed = \"Malformed input in %s, line %s. Could not %s '%s'\"\n\n #possible tags in beginning of lines\n tags = ['bm', 'mr', 'bs', 'sp', 'bo', 'th', 'tk', 'bd', 'gh']\n ans = list()\n\n with open(name, 'r') as inF:\n for (j, line) in enumerate(inF):\n line = line.translate(None, '\\t \\n') #no spaces or tabs or newline\n if '#' in line:\n line = line[0:line.find('#')] #no comments\n if len(line) < 2:\n continue\n elif line[0:5] == 'order':\n word = line[6:]\n try:\n ans.append(('order', int(eval(word))))\n except (SyntaxError, NameError):\n raise InputError((malformed + '.') \\\n %(fileName, str(j + 1), 'parse', word))\n except TypeError:\n raise InputError((malformed + 'to int') \\\n %(fileName, str(j + 1), 'cast', word))\n\n elif line[0:9] == 'threshold':\n word = line[10:]\n try:\n ans.append(('threshold', float(eval(word))))\n except (SyntaxError, NameError):\n raise InputError(malformed + \".\"\\\n %(fileName, str(j + 1), 'parse', word))\n except TypeError:\n raise InputError((malformed + \"to float.\") \\\n %(fileName, str(j + 1), 'cast', word))\n\n elif line[0:2] in tags:\n ans.append((line[0:2], dicOf(line[0:2], line[2:], name, j + 1)))\n else:\n ans.append(('LName', line[0:]))\n\n return ans\n\ndef dicOf(st, line, fileName, lineNumber):\n '''Extract the initializer dictionary from a line.\n\n st: object tag, 'bm', 'th', ... [string]\n line: line of data in .tia format (supposed no spaces nor tabs nor comments)\n and without the object tag. [string]\n fileName: name of file (used to write errors). [string]\n lineNumber: number for this line in the file (used to write errors). [int]\n\n\tMay raise an InputError\n\tReturns a dictionary ready for construction.\n\n '''\n #error message\n malformed = \"Malformed input in %s, line %s, entry %s\"\n ans = dict()\n\n #allow empty constructor\n if line == '':\n return ans\n\n words = line.split(',')\n explicit = False\n\n if len(words) > len(settings.inOrder[st]):\n raise InputError(\n \"Malformed input in %s, line %s. To many arguments given.\"\\\n % (fileName, str(lineNumber)))\n\n for (i, word) in enumerate(words):\n if '=' in word:\n explicit = True\n if explicit and not '=' in word:\n raise InputError(\n (malformed + \". Found non explicit entry '%s' among explicit entries.\")\\\n % (fileName, lineNumber, str(i + 1), word))\n\n if explicit:\n var, val = word[:word.find('=')], word[word.find('=') + 1:]\n if var not in settings.inOrder[st]:\n raise InputError(\n (malformed + \". Unknown constructor parameter '%s'.\")\\\n % (fileName, lineNumber, str(i + 1), var))\n else:\n var, val = settings.inOrder[st][i], word\n\n try:\n ans[var] = settings.types[var](eval(val))\n except SyntaxError:\n raise InputError((malformed + \". Could not parse '%s'.\")\\\n %(fileName, lineNumber, str(i + 1), val))\n except NameError:\n raise InputError(\n (malformed + \". Did not recognize reference in '%s'.\")\\\n % (fileName, lineNumber, str(i + 1), val))\n except ValueError:\n raise InputError(\n (malformed + \". Expected %s for parameter %s, \"\\\n + \"but got '%s' which evaluates to %s.\")\\\n % (fileName, lineNumber, str(i + 1),\n settings.typeStrings[settings.types[var]], var, val,\n settings.typeStrings[type(eval(val))]))\n return ans\n","repo_name":"bandang0/theia","sub_path":"theia/running/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5032,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"50"}
+{"seq_id":"24922533877","text":"import logging\nimport re\nimport requests\nimport time\n\nfrom bs4 import BeautifulSoup\n\nfrom rprec.db import db_connection, query_database_slugs, write_article_to_database\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=\"INFO\")\n\n\ndef tutorial_categories_from_rp_sitemap(sitemap_url, wrong_endpoints):\n \"\"\"Scrapes a list of tutorial categories from the Real Python sitemap.\n \n :param sitemap_url: The url string for the Real Python sitemap xml.\n :type sitemap_url: str\n :param wrong_endpoints: endpoints that don't have content.\n :type wrong_endpoints: list\n :return: A list Real Python tutorial categories\n :rtype: list\n \"\"\"\n soup = BeautifulSoup(requests.get(sitemap_url).text, \"lxml\")\n\n slugs_to_read = []\n for loc in soup.select(\"url > loc\"):\n if any([f\"https://realpython.com/{endpoint}\" in loc.text for endpoint in wrong_endpoints]):\n continue\n else:\n slugs_to_read.append(loc.text)\n\n return slugs_to_read\n\n\ndef scrape_article(slug):\n \"\"\"Scrapes the article text body from a Real Python tutorial page.\n \n :param slug: Name of the article slug to parse\n :type slug: str\n :return: (slug, author, article_text)\n :rtype: tuple\n \"\"\"\n page_url = f\"https://realpython.com/{slug}\"\n response = requests.get(page_url)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n try:\n find_author = soup.find(\"a\", href=\"#author\")\n author = find_author.text\n except AttributeError:\n author = \"Real Python\"\n\n find_article_body = soup.find_all(\"div\", {\"class\": \"article-body\"})\n\n article_text = \"\"\n for element in find_article_body:\n article_text += \"\\n\" + \"\".join(element.findAll(text=True))\n\n return slug, author, article_text\n\n\ndef run_scraper(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n):\n \"\"\"Scrapes Real Python articles and writes new articles to a database.\n \n :param database_name: Name of the db\n :type database_name: str\n :param database_user: database username\n :type database_user: str\n :param database_password: password for the db\n :type database_password: str\n :param database_server: where the database is hosted\n :type database_server: str\n :param database_port: port for the db\n :type database_port: int\n :param database_url: the environment variable for the database url in heroku\n :type database_url: str\n \"\"\"\n rp_sitemap_url = \"http://realpython.com/sitemap.xml\"\n\n wrong_endpoints = [\n 'all',\n 'quizzes',\n 'questions',\n 'resources',\n 'security',\n 'sponsorships',\n 'start-here',\n 'support',\n 'team',\n 'testimonials',\n 'tutorials',\n 'write-for-us',\n 'learning-paths',\n 'lessons', \n ]\n urls_to_read = tutorial_categories_from_rp_sitemap(rp_sitemap_url, wrong_endpoints)\n\n # first check the database for slugs so we can skip those\n connection = db_connection(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n )\n database_slugs = query_database_slugs(connection)\n # slugs = scrape_category_pages_for_slugs(categories, database_slugs)\n\n\n # iterate the new RP articles and write them to db\n for url in urls_to_read:\n m = re.search(r'^.*\\/([^/]*)/.*$', url)\n slug = m.group(1)\n if slug in database_slugs:\n continue\n article_object = scrape_article(slug)\n # I close the connection object after each write\n connection = db_connection(\n database_name,\n database_user,\n database_password,\n database_server,\n database_port,\n database_url,\n )\n write_article_to_database(article_object, connection)\n # be nice to RP\n time.sleep(1)\n","repo_name":"arvkevi/rprec","sub_path":"rprec/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"50"}
+{"seq_id":"14891104124","text":"from tkinter import *\nimport console\nfrom tkinter import messagebox\nfrom random import randint\n\n\ndef x_check(x, number, x_entries):\n for j in range(number):\n if x == x_entries[j].get():\n return False\n return True\n\n\nclass Application(Frame):\n def __init__(self, master):\n super().__init__(master)\n self.grid()\n self.create_widget()\n\n def create_widget(self):\n self.x_entries = []\n self.y_entries = []\n self.x_labels = []\n self.y_labels = []\n\n for i in range(8):\n lx = Label(self, text='x'+str(i))\n lx.grid(row=i, column=0)\n self.x_labels.append(lx)\n\n ex = Entry(self)\n ex.grid(row=i, column=1)\n self.x_entries.append(ex)\n\n ly = Label(self, text='y' + str(i))\n ly.grid(row=i, column=2)\n self.y_labels.append(ly)\n\n ey = Entry(self)\n ey.grid(row=i, column=3)\n self.y_entries.append(ey)\n\n self.x_entries[0].insert(0, '0')\n self.y_entries[0].insert(0, '0')\n self.x_entries[1].insert(0, '1')\n self.y_entries[1].insert(0, '1')\n self.x_entries[2].insert(0, '2')\n self.y_entries[2].insert(0, '-1')\n self.x_entries[3].insert(0, '3')\n self.y_entries[3].insert(0, '0')\n\n self.random_button = Button(self, text='Random', command=self.randomize)\n self.random_button.grid(row=8, column=1)\n\n self.spline_button = Button(self, text='Get spline', command=self.solve)\n self.spline_button.grid(row=8, column=3)\n\n self.number_label = Label(self, text='Number of dots')\n self.number_label.grid(row=9, column=1)\n\n self.number_entry = Entry(self)\n self.number_entry.grid(row=9, column=3)\n self.number_entry.insert(0, '4')\n\n def randomize(self):\n try:\n size = int(self.number_entry.get())\n except ValueError:\n messagebox.showinfo('Error', 'Number of dots must be a number from range (4, 5, 6, 7, 8)')\n\n if size not in (4, 5, 6, 7, 8):\n messagebox.showinfo('Error', 'Number of dots must be a number from range (4, 5, 6, 7, 8)')\n raise ValueError\n\n for i in range(size, 8):\n self.x_entries[i].delete(0, END)\n self.y_entries[i].delete(0, END)\n\n numbers = []\n for i in range(size):\n self.x_entries[i].delete(0, END)\n self.y_entries[i].delete(0, END)\n x_rand = str(randint(-20, 20))\n y_rand = str(randint(-20, 20))\n self.x_entries[i].insert(0, x_rand)\n self.y_entries[i].insert(0, y_rand)\n numbers.append(x_rand)\n\n for i in range(size):\n if not x_check(self.x_entries[i].get(), i, self.x_entries):\n while self.x_entries[i].get() in numbers:\n self.x_entries[i].delete(0, END)\n self.x_entries[i].insert(0, str(randint(-20, 20)))\n\n def solve(self):\n try:\n file = open('dots.txt', 'w', encoding='utf-8')\n except FileNotFoundError:\n print(\"Dots file is nor founded\")\n exit(2)\n\n for i in range(8):\n x = self.x_entries[i].get()\n y = self.y_entries[i].get()\n if x != '' and y != '':\n if x_check(x, i, self.x_entries):\n file.write(x + ' ' + y + '\\n')\n else:\n messagebox.showinfo('Error', 'All points must have different x')\n raise ValueError\n\n file.close()\n\n console.main()\n\n\nroot = Tk()\nroot.title(\"Cubic Spline\")\nroot.geometry(\"300x300\")\napp = Application(root)\nroot.mainloop()\n","repo_name":"owerbat/Cubic_Spline","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"16368532897","text":"from __future__ import absolute_import\nfrom __future__ import print_function\n\nimport argparse\nimport glob\nimport os\nimport sys\nimport subprocess\nimport textwrap\n\n\nVERSION = '0.2'\n\n\ndef execute_command(cmd, verbose=False):\n \"\"\"\n Executes command @cmd\n Shows output when @quiet is False\n\n Returns: False if command failed\n \"\"\"\n stderr = ''\n try:\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n result = process.returncode\n except OSError as exception:\n result = -1\n print_error('could not execute {0}'.format(cmd))\n print_error(format(exception.strerror))\n if (result != 0) and verbose:\n print_error(stderr)\n print_status(stdout, verbose)\n return result == 0\n\n\ndef print_line(text, error=False):\n \"\"\"\n Prints @text to stdout, or to stderr if @error is True.\n Flushes stdout and stdin.\n \"\"\"\n if not error:\n print(text)\n else:\n print(text, file=sys.stderr)\n sys.stdout.flush()\n sys.stderr.flush()\n\n\ndef print_error(text, result=False):\n \"\"\"\n Prints error message @text and exits with result code @result if not 0.\n \"\"\"\n if len(text):\n print_line('[-] ' + text, True)\n if result:\n sys.exit(result)\n\n\ndef print_status(text, verbose=False):\n \"\"\"\n Prints status message @text if @verbose\n \"\"\"\n if verbose and text:\n print_line('[*] ' + text)\n\n\ndef loop_repositories(options):\n \"\"\"\n Finds all git repositories in @options['root'] and updates them.\n \"\"\"\n for config in glob.glob(options['root'] + '*/.git/config'):\n repo = os.path.abspath(os.path.join(config, \"../..\"))\n print_status('Working on ' + repo)\n os.chdir(repo)\n if execute_command(['git', 'status'], options['verbose']):\n execute_command(['git', 'pull'], options['verbose'])\n\n\ndef parse_arguments(banner):\n \"\"\"\n Parses command line arguments.\n Uses @banner when showing description.\n\n Returns: an array of options.\n \"\"\"\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent(banner + '''\\\n - Bulk updates git repositories\n\nCopyright (C) 2016 Peter Mosmans [Go Forward]\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.'''))\n parser.add_argument('root', type=str, help=\"\"\"root directory\"\"\")\n parser.add_argument('-v', '--verbose', action='store_true', default=False,\n help='Be more verbose')\n options = vars(parser.parse_args())\n return options\n\n\ndef preflight_checks(options):\n \"\"\"\n Check whether valid @options are given.\n \"\"\"\n try:\n if not os.path.isdir(options['root']):\n print_error('Root directory {0} does not exist'.\n format(options['root']), -1)\n except TypeError:\n print_error('Error verifying paths', -1)\n\n\ndef main():\n \"\"\"\n Main program loop.\n \"\"\"\n banner = 'git-updater version ' + VERSION\n options = parse_arguments(banner)\n preflight_checks(options)\n loop_repositories(options)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"PeterMosmans/git-utilities","sub_path":"updaterepos.py","file_name":"updaterepos.py","file_ext":"py","file_size_in_byte":3416,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"50"}
+{"seq_id":"73869218395","text":"\"\"\"\nSimulate the target with verilator\n\"\"\"\nfrom migen import *\nfrom litex.soc.integration.builder import Builder, builder_args, builder_argdict\nfrom litex.boards.targets.cmod_a7 import BaseSoC\nfrom litex.build.sim import SimPlatform\nfrom litex.build.generic_platform import Pins, Subsignal\nfrom migen.genlib.io import CRG\nfrom cmod_a7_design_example import MySoc\nfrom litex.build.sim.config import SimConfig\nfrom litex.soc.cores import uart\nfrom liteeth.phy.model import LiteEthPHYModel\nfrom liteeth.core.mac import LiteEthMAC\nfrom litex.soc.integration.soc_core import mem_decoder, get_mem_data\nimport argparse\n\n\nclass SimPins(Pins):\n def __init__(self, n=1):\n Pins.__init__(self, \"s \" * n)\n\n\n_io = [\n (\"sys_clk\", 0, SimPins(1)),\n (\"sys_rst\", 0, SimPins(1)),\n (\"user_led\", 0, SimPins(1)),\n (\"serial\", 0,\n Subsignal(\"source_valid\", SimPins()),\n Subsignal(\"source_ready\", SimPins()),\n Subsignal(\"source_data\", SimPins(8)),\n\n Subsignal(\"sink_valid\", SimPins()),\n Subsignal(\"sink_ready\", SimPins()),\n Subsignal(\"sink_data\", SimPins(8)),\n ),\n (\"eth_clocks\", 0,\n Subsignal(\"none\", SimPins()),\n ),\n (\"eth\", 0,\n Subsignal(\"source_valid\", SimPins()),\n Subsignal(\"source_ready\", SimPins()),\n Subsignal(\"source_data\", SimPins(8)),\n\n Subsignal(\"sink_valid\", SimPins()),\n Subsignal(\"sink_ready\", SimPins()),\n Subsignal(\"sink_data\", SimPins(8)),\n )\n]\n\n\nclass Platform(SimPlatform):\n default_clk_name = \"sys_clk\"\n default_clk_period = 1000 # ~ 1MHz\n\n def __init__(self):\n SimPlatform.__init__(self, \"SIM\", _io)\n\n def do_finalize(self, fragment):\n \"\"\" ignore adding a clock constraint \"\"\"\n pass\n\n\ndef main():\n parser = argparse.ArgumentParser(description=__doc__)\n builder_args(parser)\n MySoc.basesoc_args(parser)\n parser.add_argument(\"--trace\", action=\"store_true\",\n help=\"enable VCD tracing\")\n parser.add_argument(\"--rom-init\", default=None,\n help=\"rom_init file\")\n parser.set_defaults(\n integrated_rom_size=0x8000,\n integrated_main_ram_size=0x8000,\n # integrated_sram_size=0, # Litex will complain if 0!\n cpu_type=\"vexriscv\",\n platform=\"cmod_a7_sim\",\n clk_freq=int(1e6),\n with_uart=False # We will add our own mock uart\n )\n args = parser.parse_args()\n soc_kwargs = vars(args)\n if args.rom_init:\n soc_kwargs[\"integrated_rom_init\"] = get_mem_data(args.rom_init)\n soc = MySoc(crg=CRG, **soc_kwargs)\n\n # Push in a fake uart\n soc.submodules.uart_phy = uart.RS232PHYModel(soc.platform.request(\"serial\"))\n soc.submodules.uart = uart.UART(soc.uart_phy)\n\n sim_config = SimConfig(default_clk=\"sys_clk\")\n # sim_config.add_module(\"ethernet\", \"eth\", args={\"interface\": \"tap0\", \"ip\": \"192.168.1.100\"})\n sim_config.add_module(\"serial2console\", \"serial\")\n # sim_config.add_module(\"serial2tcp\", \"serial\", args={\"port\": 55555})\n # now you can do these 2 things to get a terminal\n # telnet localhost 55555\n # litex_term socket://localhost:55555\n # soc.add_constant(\"TFTP_SERVER_PORT\", int(tftp_port))\n\n builder = Builder(soc, **builder_argdict(args))\n builder.build(run=False, sim_config=sim_config, trace=args.trace)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yetifrisstlama/litex_test_project","sub_path":"cmod_a7_2/cmod_a7_sim.py","file_name":"cmod_a7_sim.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"50"}
+{"seq_id":"12519906858","text":"# -*- coding: utf-8 -*-\n## ---- Tut04-VariableAleatoriaDiscreta\n\"\"\"\nwww.postdata-statistics.com\nPOSTDATA. Introducción a la Estadística\nTutorial 04. \nFichero de comandos Python para el estudio de \nuna variable aleatoria discreta.\n\"\"\"\n## Importacion de Modulos\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport math as m \n\n\n# Definicion de X a partir de valores y probabilidades.\n\nvaloresX = [2, 4, 7, 8, 11]\nprobabilidadesX = [1/5, 1/10, 1/10, 2/5, 1/5]\nX = [[valoresX[_], probabilidadesX[_]] for _ in range(0, len(valoresX))]\n\n# Alternativamente, definicion de la variable X como lista de pares [valor, probabilidad].\n# Descomentar la siguiente linea para usarla.\n\n# X = [[2, 1/5], [4, 1/10], [7, 1/10], [8, 2/5], [11, 1/5]]\n\n# En cualquier caso:\n\nvaloresX = [x[0] for x in X]\nprobabilidadesX = [x[1] for x in X]\n\n# Calculo de la media.\n\nmedia = sum([x[0] * x[1] for x in X])\nprint(\"Media de X = {0:0.4f}\".format(media))\n\n# Calculo de la varianza y desviacion tipica.\n\nvarianza = sum([(x[0] - media)**2 * x[1] for x in X])\nprint(\"varianza = {0:0.4f}\".format(varianza))\n\nsigma = m.sqrt(varianza)\nprint(\"desviacion tipica = {0:0.4f}\".format(sigma))\n\n# Función de distribucion.\n\nFdistX = np.cumsum(probabilidadesX).tolist()\n\n# y su tabla:\n\nk = len(valoresX)\nprint(\"\\nTabla de densidad de la variable aleatoria X:\\n\")\nlinea = \"_\" * 49\nprint(linea)\nprint(\"| Valor x | Probabilidad p | Fun. de dist. F(x) |\")\nprint(linea)\nfor i in range(0, k):\n print(\"| {0: 7d} | {1: 14.2f} | {2: 18.2f} |\".format(valoresX[i],\\\n probabilidadesX[i], FdistX[i]))\nprint(linea)\n\n# Gráfico de barras de la función de densidad.\n\nplt.suptitle(\"Gráfico de barras de la función de densidad:\")\nplt.xticks(valoresX)\nplt.axis([min(valoresX) - 1,max(valoresX) + 1, 0, 1])\nplt.bar(valoresX, probabilidadesX, color='tan', align='center')\n\n# Reset gráfico.\n\nplt.figure()\n\n# Gráfico de escalera de la función de distribucion.\n\nplt.suptitle(\"Gráfico de escalera de la función de distribucion:\")\nplt.xticks(valoresX)\nplt.step([min(valoresX) - 2] + valoresX + [max(valoresX) + 1],\n [0] + FdistX + [1.00001], where='post', linewidth=4.0, color='red')\n","repo_name":"fernandosansegundo/PostDataStatistics","sub_path":"TutorialesPython/code/Tut04-VariableAleatoriaDiscreta.py","file_name":"Tut04-VariableAleatoriaDiscreta.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"25945616197","text":"import numpy as np\nimport numba\n\n\n@numba.jit(nopython=True)\ndef find_particle_in_grid(particle_pos, h):\n \"\"\"Find position (index and offset from lower left node) of particle in grid\"\"\"\n j, x = divmod(particle_pos[0], h)\n k, y = divmod(particle_pos[1], h)\n return int(j), int(k), x, y\n\n\n@numba.jit(nopython=True)\ndef cic_charge_weighting(particle_pos, particle_charge, active_particles, rho, h):\n \"\"\"Cloud-in-cell charge weighting of particles to rho grid\"\"\"\n S_h = h**2 # cell surface\n n = rho.shape[0]\n for i in range(active_particles):\n j, k, x, y = find_particle_in_grid(particle_pos[i], h)\n rho[j,k] += particle_charge * (h-x)*(h-y)/S_h\n jj, kk = j+1, k+1\n if jj < n:\n rho[jj,k] += particle_charge * x*(h-y)/S_h\n if kk < n:\n rho[jj,kk] += particle_charge * x*y/S_h\n if kk < n:\n rho[j,kk] += particle_charge * (h-x)*y/S_h\n\n\n@numba.jit(nopython=True)\ndef cic_field_weighting(particle_pos, particle_field, active_particles, field, h):\n \"\"\"Cloud-in-cell field weighting of field grid to particles\"\"\"\n S_h = h**2 # cell surface\n n = field.shape[0]\n for i in range(active_particles):\n j, k, x, y = find_particle_in_grid(particle_pos[i], h)\n particle_field[i] = 0.0\n particle_field[i] += field[j,k] * (h-x)*(h-y)/S_h\n jj, kk = j+1, k+1\n if jj < n:\n particle_field[i] += field[jj,k] * x*(h-y)/S_h\n if kk < n:\n particle_field[i] += field[jj,kk] * x*y/S_h\n if kk < n:\n particle_field[i] += field[j,kk] * (h-x)*y/S_h\n\n","repo_name":"smartass101/pmpl_pic","sub_path":"pic/weighting.py","file_name":"weighting.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"32096529809","text":"from statistics import mean\r\ndata =[]\r\ndef inputData():\r\n while True:\r\n name = input('이름:')\r\n kor = int( input('국어:') )\r\n eng = int( input('영어:') )\r\n math = int( input('수학:') )\r\n data.append( (name, kor, eng,math) )\r\n yn= input('계속 입력하시겠습니까(y/n)?')\r\n if yn=='n':\r\n break\r\n# print(data)\r\ndef title():\r\n print(\"=\"*50)\r\n print('이름','국어','영어','수학',sep='\\t')\r\n print(\"=\"*50)\r\ndef outputData():\r\n print(\"=\"*50)\r\n print('이름','국어','영어','수학','총점','평균',sep='\\t')\r\n print(\"=\"*50)\r\n for n,k,e,m in data:\r\n tot = k+e+m\r\n print( n,k,e,m,tot,tot/3,sep='\\t\\t' )\r\n ktot = sum( [n[1] for n in data ] )\r\n etot = sum( [n[2] for n in data ] )\r\n mtot = sum( [n[3] for n in data ] )\r\n kmean = mean( [n[1] for n in data ] )\r\n emean = mean( [n[2] for n in data ] )\r\n mmean = mean( [n[3] for n in data ] )\r\n kmax = max( data, key=lambda v:v[0])[1]\r\n emax = max( data, key=lambda v:v[1])[2]\r\n mmax = max( data, key=lambda v:v[2])[3]\r\n print('총점:','국어',ktot,'영어',etot,'수학',mtot)\r\n print('평균:','국어',kmean,'영어',emean,'수학',mmean)\r\n print('최고점수:','국어',kmax,'영어',emax,'수학',mmax)\r\n\r\ndef searchData():\r\n sname = input('검색할 이름을 입력하세요:')\r\n fName =filter( lambda v:v[0]==sname,data)\r\n title()\r\n for n,k,e,m in fName:\r\n print( n,k,e,m,sep='\\t\\t' )\r\n\r\ndef showMenu():\r\n menu = {1:inputData, 2:outputData, 3:searchData,4:exit}\r\n while True:\r\n print( '1.입력','2.출력','3.검색','4.종료',sep='\\n')\r\n nSel = int( input('번호를 입력하세요:'))\r\n menu[nSel]()\r\n\r\nshowMenu()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"andy-kr/PythonWorkSpace","sub_path":"secondSolA.py","file_name":"secondSolA.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"17189709234","text":"from llvmlite import binding, ir\nfrom nachlang import utils\nfrom functools import partial\n\n# LLVM Initialization\n# https://llvmlite.readthedocs.io/en/latest/user-guide/binding/initialization-finalization.html?highlight=initialize#initialization-and-finalization\n\nsymbol_table = {}\n\nbinding.initialize()\nbinding.initialize_native_target()\nbinding.initialize_native_asmprinter()\n\n# TODO: Review this ###\nmodule = ir.Module(name=__file__)\nmodule.triple = binding.get_default_triple()\nfunc_type = ir.FunctionType(ir.IntType(32), [], False)\nbase_func = ir.Function(module, func_type, name=\"main\")\nblock = base_func.append_basic_block(name=\"entry\")\nbuilder = ir.IRBuilder(block)\n####\n\n\n# Types\n\nINT32 = ir.IntType(32)\nINT1 = ir.IntType(1)\n\n\n#\n# Common resolvers\n#\n\n\ndef get_first_key(data: dict, max_length: int = 1):\n if len(data) > max_length:\n raise Exception(f\"Unexpected length for {data}\")\n\n return next(iter(data.keys()))\n\n\n# TODO: rename?\ndef resolve_ast_object(o: dict):\n \"\"\"\n Expects an AST object.\n\n The Object is represented by a dictionary which should only contain one key\n \"\"\"\n return nodes[o[\"name\"]](o[\"value\"])\n\n\n#\n# Resolvers\n#\n\n\ndef resolve_with_no_returns(values):\n for e in values:\n resolve_ast_object(e)\n\n\ndef resolve_expression(expression):\n exp = utils._filter_parens(expression)[0]\n\n if type(exp) == dict:\n return resolve_ast_object(exp)\n else:\n expression_type = exp.name\n return nodes[expression_type](exp)\n\n\ndef resolve_binary_operation(bin_op):\n lhs = resolve_expression(bin_op[0][\"value\"])\n binary_operand = resolve_operand(bin_op[1])\n rhs = resolve_expression(bin_op[2][\"value\"])\n return binary_operand(lhs, rhs)\n\n\ndef resolve_define_var(definition):\n var_name = definition[1]\n\n expression = definition[2]\n expression_value = nodes[\"expression\"](expression[\"value\"])\n\n var_pointer = builder.alloca(INT32)\n symbol_table[var_name.value] = var_pointer\n builder.store(expression_value, var_pointer)\n\n\ndef resolve_if_statement(if_statement):\n \"\"\"\n Allows both if/else type statements or just if statements\n\n * if it's an if/else statement the length of the if_statement arg will be equal to 10\n * if it's an if statement the length of the if_statement arg will be equal to 7\n \"\"\"\n with builder.if_else(\n builder.trunc(resolve_ast_object(if_statement[2]), INT1)) as (then, otherwise):\n with then:\n resolve_ast_object(if_statement[4])\n with otherwise:\n if len(if_statement) == 10:\n resolve_ast_object(if_statement[7])\n\n\n#\n# Terminals\n#\n\n\ndef resolve_number(num):\n return ir.Constant(INT32, num.value)\n\n\ndef resolve_operand(operand):\n if operand.name == \"PLUS_SIGN\":\n return builder.add\n if operand.name == \"MINUS_SIGN\":\n return builder.sub\n if operand.name == \"MULTIPLICATION_SIGN\":\n return builder.mul\n if operand.name == \"DIVISION_SIGN\":\n return builder.sdiv\n if operand.name in [\"EQ\", \"NEQ\", \"LT\", \"GT\", \"GTE\", \"LTE\"]:\n return partial(builder.icmp_signed, operand.value)\n if operand.name == \"AND\":\n return builder.and_\n if operand.name == \"OR\":\n return builder.or_\n\n raise Exception(f\"Couldn't resolve operand {operand}\")\n\n\ndef resolve_var(var):\n pointer = symbol_table.get(var.value)\n if pointer == None:\n raise Exception(f\"Variable not defined {var.name} at {var.source_pos}\")\n return builder.load(pointer)\n\n\ndef ignore(item):\n return \n\n\n#\n# Function pointers\n#\n\nnodes = {\n \"define_var\": resolve_define_var,\n \"binary_operation\": resolve_binary_operation,\n \"expression\": resolve_expression,\n \"NUMBER\": resolve_number,\n \"OPEN_PAREN\": ignore,\n \"CLOSE_PAREN\": ignore,\n \"VAR\": resolve_var,\n \"statement_list\": resolve_with_no_returns,\n \"statement\": resolve_with_no_returns,\n \"if_statement\": resolve_if_statement,\n}\n\n#\n# LLVM code gen\n#\n\n\ndef print_module_body(module):\n print(\"\\n\".join(module._get_body_lines()))\n\n\ndef generate_llvm_ir(ast):\n resolve_ast_object(ast)\n # with open(\"output.ll\", \"w\") as f:\n # f.write(str(module))\n print_module_body(module)\n return module\n","repo_name":"ignaciodelmont/nachlang","sub_path":"nachlang/codegen.py","file_name":"codegen.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"4271810029","text":"# 演化算法得到粗略解后,将演化算法作为先验知识做进一步优化\r\n\r\nimport numpy as np\r\nfrom sklearn import preprocessing\r\n\r\n\r\nfrom typing import *\r\nimport operator\r\nimport time\r\nimport copy\r\n\r\nimport pkg_resources\r\n\r\nimport sys\r\nsys.path.append('./')\r\n\r\nfrom pymoo.factory import get_reference_directions, get_sampling, get_crossover, get_mutation\r\nfrom pymoo.model.individual import Individual\r\nfrom pymoo.model.population import Population\r\n\r\n\r\nfrom pymoo.model.result import Result\r\nfrom pymoo.optimize import minimize\r\nfrom pymoo.problems.securitygame.MOSG import SGs1\r\nfrom MOSGs.ORIGAMIM import ORIGAMIM\r\nfrom pymoo.MOSGsGeneticSolver.performance import Performance\r\n\r\n\r\nfrom securitygame_core.MO_security_game import MOSG\r\nfrom pymoo.MOSGsGeneticSolver.truing_genetic_problem import TruingGP\r\nfrom pymoo.MOSGsGeneticSolver.genetic_turing import GeneticTruing\r\n\r\n\r\nimport tool.algorithm\r\n\r\n\r\n\r\nclass Truing():\r\n\r\n\r\n def __init__(self, res:Result=None, para_dir=None):\r\n\r\n self.para_dir = para_dir\r\n\r\n # 读入数据\r\n self.res:Result = res\r\n self.problem:SGs1 = res.problem\r\n\r\n # 来自种群,规模远大于opt\r\n self.x:np.ndarray = res.pop.get('X')\r\n self.fit:np.ndarray = res.pop.get('F') * -1 # maximize fit\r\n feasible_bool:np.ndarray = res.pop.get('feasible')\r\n self.feasible = np.array(list(map(lambda x: int(x),feasible_bool)))\r\n self.ct:np.ndarray = res.pop.get('CT')\r\n\r\n # 来自opt,复杂度较高的方法推荐opt,规模小\r\n self.opt = res.opt\r\n self.opt_x = res.opt.get('X')\r\n self.opt_fit = res.opt.get('F') * -1\r\n feasible_bool:np.ndarray = res.opt.get('feasible')\r\n self.opt_feasible = np.array(list(map(lambda x: int(x),feasible_bool)))\r\n # self.opt_ct:np.ndarray = res.opt.get('CT')\r\n\r\n # 最终保存的pf信息\r\n self.fit_pf:Union[None,np.ndarray] = None # minimize Fitness\r\n self.ct_pf:List[np.ndarray] = [] # 一般算法算完就返回,不需要存ct;只有分阶段的算法需要保存\r\n\r\n\r\n def check(self):\r\n a = self.res.pop.get('F')\r\n for best_fit in self.res.F:\r\n for idx in range(a.shape[0]):\r\n if operator.eq(best_fit, a[idx]).all():\r\n break\r\n if idx == a.shape[0]-1:\r\n print('opt_fit dont exist in pop_fit, error!!!')\r\n\r\n\r\n # NOTE: 提供的pf_total必须是minimize task\r\n def mulResCompare(self, pf_total:List[np.ndarray], name_total:List[str]):\r\n pf:np.ndarray = np.vstack(pf_total)\r\n len_total = [len(pf) for pf in pf_total]\r\n print(Performance(pf, len_total, name_total, para_dir=self.para_dir))\r\n\r\n\r\n def update_by_idx(self, idx:Union[List[int], np.ndarray]):\r\n self.ct = self.ct[idx]\r\n self.fit = self.fit[idx]\r\n self.feasible = self.feasible[idx]\r\n self.x = self.x[idx]\r\n\r\n\r\n # 将编码X转化为ct\r\n def x2CtGamma(self, x:np.ndarray, fit_true:np.ndarray=None, model:SGs1=None)\\\r\n ->Tuple[Union[np.ndarray, None], Dict[int,List[int]], Dict[int,List[float]], Dict[int, int]]:\r\n if model is None:\r\n model = SGs1(player_num=self.problem.player, target_num=self.problem.target)\r\n # decode DNA into strategy\r\n strategy = model.GetQuery(x)\r\n return model.Strategy2Ct(strategy)\r\n # DEBUG\r\n # if ct is not None: # feasible\r\n # model.cal_payoff(ct)\r\n # fit = model.cal_payoff_defender()\r\n # if not operator.eq(fit, fit_true).all():\r\n # print('error1')\r\n # else: # not feasible # 一般情况下不应该出现该情况\r\n # return None\r\n\r\n # NOTE: truing_by_mincov是在SG框架中的程序,所以处理的是maximise task\r\n # 该函数并非不需要ct,而是提供idx下标,访问ct;相反不需要fit\r\n def truing_by_mincov(self, ct_i:np.ndarray, b:np.ndarray, pf_total=None, ct_star_total:np.ndarray=None)\\\r\n ->Tuple[np.ndarray, np.ndarray]:\r\n K = 3\r\n count = 0 # 记录精修的次数\r\n # 每次搜索到新方案ct后,结合game table算fitness\r\n problem_mosg = MOSG(player_num=self.problem.player, target_num=self.problem.target)\r\n model = ORIGAMIM(MOSG=problem_mosg)\r\n\r\n for gameidx in range(self.fit.shape[1]): # 第二层for遍历obj\r\n # 利用ct尝试精修,用到MINCOV\r\n model.c = ct_i\r\n model.updateC()\r\n model.updateU(i=gameidx)\r\n # 需要注意的是,由于gmosg编码的破��性,next和idx对应不一定是相同的,但是影响并不是很大只要next>1\r\n idx = np.argsort(-model.U_ia)\r\n # NOTE: 由于不好确定next的具体取值,将next设为T一定没错,只是时间会增长\r\n # next = model.getNextLen(gap)\r\n next = min(model.getNextLen(epsilon=0.1)*K, self.problem.target)\r\n ct_star = model.MINCOV(gameIdx=gameidx, b=b, next=next, idx=idx)\r\n if ct_star is None:\r\n continue\r\n if ct_star_total is not None and ct_star in ct_star_total:\r\n continue\r\n if ct_star_total is not None:\r\n ct_star_total = np.vstack([ct_star, ct_star_total])\r\n else:\r\n ct_star_total = ct_star\r\n model.c = ct_star\r\n model.updateC()\r\n model.updateU(i=gameidx)\r\n # self.problem.cal_payoff(ct_star)\r\n # fit_star = self.problem.cal_payoff_defender()\r\n for obj_idx in range(self.fit.shape[1]):\r\n model.leftAllocation(b=b, obj_idx=obj_idx)\r\n ct_final = model.c\r\n self.problem.cal_payoff(ct_final)\r\n fit_final = self.problem.cal_payoff_defender()\r\n if pf_total is None:\r\n pf_total = fit_final\r\n else:\r\n pf_total = np.vstack([pf_total, fit_final])\r\n # ct_total = np.vstack([ct_total, ct_final])\r\n count += 1\r\n # print('找到更优解{}处'.format(count))\r\n return pf_total, ct_star_total\r\n\r\n # 下面mosgSearch_pop和mosgSearch_opt分别代表从全体种群中开始搜索还是从最优解中开始搜索\r\n # 注:两者复杂度相差不大,因此直接使用mosgSearch_pop,因为它效果优于_opt\r\n # _opt与_pop的区别:种群数量远大于最优解,最优解是种群的子集\r\n\r\n '''# 遍历求解\r\n # 重新算当前Ct的Fit,作为b,传给Direct Search解\r\n # 每个目标依次单独优化,优化目标为单目标上提升最大化并且所需资源最小化,留一个目标,吧剩余资源分给他。'''\r\n def mosgSearch_pop(self): # 在整个种群中找精修的方法\r\n\r\n # 先从res把整数编码转成实数编码ct\r\n pf_total:Union[None,np.ndarray] = None\r\n # ct_total:Union[None,np.ndarray] = None\r\n ct_star_total = None\r\n for idx in range(self.x.shape[0]):\r\n ct, _, _, _ = self.x2CtGamma(x=self.x[idx], model=self.problem, fit_true=self.fit[idx])\r\n if ct is not None:\r\n self.ct[idx] = ct\r\n self.feasible[idx] = 1\r\n else:\r\n self.feasible[idx] = 0\r\n self.update_by_idx(idx=self.feasible == 1)\r\n\r\n timer_start = time.perf_counter()\r\n for i in range(self.ct.shape[0]): # 第一层for遍历pop\r\n # 想法是每个ct用MINCOV算一次ctPrime,然后循环check是否违反b\r\n # 若死锁型违反则无视(TODO),或者返回一个相对好的\r\n # 得到cPrime后调用leftAllocation循环N次\r\n b = self.fit[i]\r\n # 把已知的可行解放入pf集,保证解不退化\r\n if pf_total is None:\r\n pf_total = b\r\n # ct_total\r\n else:\r\n pf_total = np.vstack([pf_total, b])\r\n # ct_total\r\n pf_total, ct_star_total = self.truing_by_mincov(self.ct[i], b, pf_total, ct_star_total)\r\n timer_end = time.perf_counter()\r\n\r\n print('mosgSearch_pop:{}'.format(timer_end - timer_start))\r\n # 暂时忽略ct_pf\r\n # self.ct_pf = ct_star_total\r\n self.fit_pf = -pf_total\r\n\r\n def initialization(self, ub:np.ndarray, lb:np.ndarray, pop_size:int, sample_real:np.ndarray) ->np.ndarray:\r\n # 分别计算distance from sample to up-bound+1 and to low-bound,\r\n # 然后取axis_normalised*dis2lb if axis_normalised<0 otherwise axis_normalised*dis2ub\r\n # 最后加上best_sample\r\n sample_len = len(sample_real)\r\n conv = np.eye(N=sample_len)\r\n axis = np.random.multivariate_normal(mean=sample_real, cov=conv, size=pop_size)\r\n axis[0] = 0 # 第一条数据保存为best_sample,不发生偏移\r\n axis_normalised = preprocessing.MaxAbsScaler().fit_transform(axis) # [-1, 1]\r\n dis2lb = sample_real - lb\r\n dis2ub = ub-0.01 - sample_real\r\n sampling = np.repeat(a=sample_real[np.newaxis,:], repeats=pop_size, axis=0)\r\n loc_neg = axis_normalised < 0\r\n loc_pos = axis_normalised > 0\r\n sampling_neg = sampling + dis2lb * axis_normalised\r\n sampling_pos = sampling + dis2ub * axis_normalised\r\n sampling[loc_pos] = sampling_pos[loc_pos]\r\n sampling[loc_neg] = sampling_neg[loc_neg]\r\n return np.floor(sampling).astype(int)\r\n\r\n def real2binary(self, real:np.ndarray, problem:TruingGP) ->np.ndarray:\r\n part_start = [sum(problem.part_len[:i]) for i in range(len(problem.part_len))]\r\n binary_len = sum(problem.part_len)\r\n binary = np.empty(shape=[binary_len,])\r\n for idx, target in enumerate(problem.conflict_target):\r\n r = real[idx]\r\n b = bin(r)[2:]\r\n b = '0' * (problem.part_len[idx] - len(b)) + b\r\n for i, b_i in enumerate(b):\r\n binary[part_start[idx] + i] = int(b_i)\r\n return binary\r\n\r\n # def calGamma(self):\r\n # self.Gamma:List[Dict[int, List[int]]] = []\r\n # for idx in range(self.x.shape[0]): # 第一个循环pop\r\n # x =\r\n\r\n # TODO LIST\r\n # TODO 1: 初始化\r\n # TODO 2: 把mincov加到每轮迭代中\r\n\r\n # 让函数直接返回发生冲突的ct集,然后对着ct集编码\r\n def geneticSearch(self, pop_size:int=100, gen_n:int=100) ->np.ndarray:\r\n # 由于Gamma数据结构复杂持久化,因此根据读入数据重新计算Gamma\r\n ref_dirs = get_reference_directions(\"das-dennis\", self.problem.n_obj, n_partitions=12)\r\n ct_star_total = None\r\n for i in range(self.opt_fit.shape[0]): # for用于遍历pop\r\n # NOTE: 这里求idx=i时的self.opt_x的ct,讲道理应该要存到self.opt_ct,没存,以后万一要用可能照成一定麻烦\r\n ct, _, conflict_ct, ct_idx = self.x2CtGamma(x=self.opt_x[i], model=self.problem)\r\n if ct is None: # not feasible\r\n continue\r\n problem = TruingGP(conflict=conflict_ct, ct=ct, problem=self.problem, ct_star_total=ct_star_total)\r\n ub = np.array(problem.part_max)\r\n lb = np.zeros(ub.shape)\r\n # ct_idx_binary = self.real2binary(ct_idx_real, problem)\r\n ct_idx_real:np.ndarray = np.array([ct_idx[target] for target in problem.conflict_target])\r\n sampling_real = self.initialization(ub=ub, lb=lb, pop_size=pop_size, sample_real=ct_idx_real)\r\n sampling_binary = np.ndarray(shape=[pop_size, problem.n_var])\r\n for j in range(pop_size):\r\n sampling_binary[j] = self.real2binary(sampling_real[j], problem)\r\n algorithm = GeneticTruing(pop_size=pop_size,\r\n ref_dirs=ref_dirs, display=False, save_history=False, verbose=False,\r\n # sampling=get_sampling('bin_random'),\r\n sampling=sampling_binary,\r\n crossover=get_crossover('bin_hux'),\r\n mutation=get_mutation('bin_bitflip'),\r\n eliminate_duplicates=True)\r\n # NOTE: res: minimize task\r\n res = minimize(problem=problem,\r\n algorithm=algorithm,\r\n seed=1,\r\n termination=('n_gen', gen_n))\r\n ct_star_total = problem.ct_star_total\r\n # print('gen_n={}, pop_size={}, 参数下,程序运行时间:{}秒'\r\n # .format(gen_n, pop_size, res.exec_time))\r\n if self.fit_pf is None: # NOTE: minimise task\r\n self.fit_pf = res.opt.get('F')\r\n self.ct_pf = res.opt.get('CT')\r\n else:\r\n self.fit_pf = np.vstack([self.fit_pf, res.opt.get('F')])\r\n self.ct_pf = np.vstack([self.ct_pf, res.opt.get('CT')])\r\n pf_total_temp = self.fit_pf\r\n\r\n # mincov 精修\r\n # NOTE: maximise task\r\n self.fit_pf = -self.fit_pf\r\n ct_star_total = None\r\n pf_total = None\r\n for idx, b in enumerate(self.fit_pf):\r\n if np.isnan(self.ct_pf[idx]).any():\r\n continue\r\n if pf_total is None:\r\n pf_total = b\r\n else:\r\n pf_total = np.vstack([pf_total, b])\r\n pf_total, ct_star_total = self.truing_by_mincov(self.ct_pf[idx], b, pf_total, ct_star_total)\r\n self.fit_pf = -pf_total\r\n return pf_total_temp\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"1589864500/SDES","sub_path":"pymoo/MOSGsGeneticSolver/truing.py","file_name":"truing.py","file_ext":"py","file_size_in_byte":13629,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"50"}
+{"seq_id":"2667988912","text":"\nfrom random import shuffle\nimport click\n\n\n@click.command()\n@click.option('--startnumber', '-s', default=1, required=True, help='begin range number. default: 1')\n@click.option('--endnumber', '-e', default=10, required=True, help='end range number. default: 10')\n\n\ndef main(startnumber,endnumber):\n\t\"\"\"\n\tFunction will print random number list from given range\n\t\"\"\"\n\tordered_list = list(range(startnumber,endnumber+1))\n\tshuffle(ordered_list)\n\tfor item in ordered_list:\n\t\tprint(item)\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"sohel2020/challenge-adjust","sub_path":"challenge-1/random_number.py","file_name":"random_number.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"8162940798","text":"# Name: domains_to_codon_opt_oligos.py\r\n# Author: Connor Ludwig\r\n# Organization: Bintu Lab, Stanford University\r\n# Updated: 10/03/2020\r\n\r\nimport os\r\nimport sys\r\nimport pandas as pd\r\nimport math\r\nfrom dnachisel import *\r\n\r\n# define optimizeOligo function:\r\n# |_ failed = list of oligos that fail codon optimization (input and output - updates)\r\n# |_ ID = tile ID (input)\r\n# |_ dna_sequence = starting DNA sequence to optimize (input; may be output if codon optimization fails)\r\n# |_ GCglobMax = upper limit for enforcement of GC content (input)\r\n# |_ optimizedDNA = codon-opimized DNA sequence (output)\r\n\r\ndef optimizeOligo(failed, ID, dna_sequence, GCglobMax):\r\n\tproblem = DnaOptimizationProblem(\r\n\t\tsequence=dna_sequence,\r\n\t\tconstraints=[\r\n\t\t\tAvoidPattern('BsmBI_site'),\r\n\t\t\tAvoidPattern('7xC'),\r\n\t\t\tAvoidRareCodons(species='h_sapiens', min_frequency=0.1),\r\n\t\t EnforceGCContent(mini=0.25, maxi=GCglobMax),\r\n\t\t EnforceGCContent(mini=0.20, maxi=0.70, window=50),\r\n\t\t EnforceTranslation(),\r\n\t\t AvoidStopCodons()],\r\n\t\tobjectives=[CodonOptimize(species='h_sapiens', method='match_codon_usage')]\r\n\t\t)\r\n\ttry:\r\n\t\tproblem.resolve_constraints()\r\n\texcept:\r\n\t\tif ID not in failed:\r\n\t\t\tfailed.append(ID)\r\n\t\tGCglobMax += 0.01\r\n\t\tprint('++++++++++ GOING UP TO %s ++++++++++' % str(GCglobMax))\r\n\t\toptimizedDNA, failed = optimizeOligo(failed, ID, dna_sequence, GCglobMax)\r\n\t\treturn optimizedDNA, failed\r\n\tproblem.optimize()\r\n\toptimizedDNA = str(problem.sequence)\r\n\treturn optimizedDNA, failed\r\n\r\n\r\n# sys.argv[1] = input csv with unique tiles\r\n# sys.argv[2] = library name\r\n\r\ndf = pd.read_csv(sys.argv[1])\r\nlibName = sys.argv[2]\r\n\r\n# store tile ID and protein sequence column values as lists\r\ntileID = df['Tile ID'].values.tolist()\r\ntileAAseq = df['Tile Sequence'].values.tolist()\r\n\r\n# libName = [sys.argv[2]] * len(tileID)\r\n\r\n# initialize arrays to store information from codon optimization\r\ntileDNAseq = []\r\nfailedList = []\r\n\r\n# for each tile protein sequence, reverse-translate and attempt to codon-optimize with a default max global GC content of 65%\r\n# return the IDs of tiles that only pass codon optimization with relaxed global GC content constraints\r\nfor i in range(len(tileID)):\r\n\tinitialDNAseq = reverse_translate(tileAAseq[i])\r\n\tcoDNAseq, failedList = optimizeOligo(failedList, tileID[i], initialDNAseq, GCglobMax=0.65)\r\n\ttileDNAseq.append(coDNAseq)\r\n\r\n# if any oligos required relaxed global GC content constraints for optimization, report these IDs and save a text file with them\r\nif len(failedList) != 0:\r\n\tprint('Oligos with global GC content > 65%: ', failedList)\r\n\tfailedFile = sys.argv[1][:-4] + '_oligos-globalGC-gt65-IDs.txt'\r\n\twith open(failedFile, 'w') as f:\r\n\t\tfor failedID in failedList:\r\n\t\t\tf.write(\"%s\\n\" % failedID)\r\nelse:\r\n\tprint('All oligos passed codon optimization with specified constraints')\r\n\r\n# add codon-optimized DNA sequence for each oligo and library tag to the dataframe and save\r\ndf['DNA Sequence'] = tileDNAseq\r\ndf['Library'] = libName\r\nsavename = sys.argv[1][:-4] + '_codon-opt-oligos.csv'\r\n\r\ndf.to_csv(savename, index=False)\r\n\r\n","repo_name":"bintulab/Viral_Ludwig_2022","sub_path":"final_April-2023/Library Generation - Command Line Scripts/domains_to_codon_opt_oligos_v2.py","file_name":"domains_to_codon_opt_oligos_v2.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"19177979581","text":"import json\nfrom Data import Data\n\n\ndef output():\n for team in Data.teams:\n with open(f'TeamOutput\\\\{team}.json') as json_file:\n data_team = json.load(json_file)\n json_file.close()\n\n wins = 0\n loses = 0\n ties = 0\n\n for w in range(Data.weeks):\n week = f\"WEEK{w+1}\"\n\n for t in Data.teams:\n if t != team:\n with open(f'TeamOutput\\\\{t}.json') as opp_file:\n opp_data = json.load(opp_file)[week]\n opp_file.close()\n\n for cat in Data.pos_cats:\n if data_team[week][cat] > opp_data[cat]:\n wins = wins + 1\n elif data_team[week][cat] < opp_data[cat]:\n loses = loses + 1\n else:\n ties = ties + 1\n\n for cat in Data.neg_cats:\n if data_team[week][cat] < opp_data[cat]:\n wins = wins + 1\n elif data_team[week][cat] > opp_data[cat]:\n loses = loses + 1\n else:\n ties = ties + 1\n\n record = float('{:.3f}'.format(wins / (wins + loses + ties)))\n print(f\"{team}\\t{wins}\\t{loses}\\t{ties}\\t{record}\")\n","repo_name":"DexRobinson/RepublicBaseball2021","sub_path":"OverallRecord.py","file_name":"OverallRecord.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"39921696770","text":"import tensorflow as tf\r\nfrom tensorflow.keras import models, optimizers, regularizers\r\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, BatchNormalization\r\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\r\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import load_model, clone_model\r\nimport matplotlib.pyplot as plt \r\n\r\n\r\ndef generate_model():\r\n model = tf.keras.Sequential()\r\n model.add(Conv2D(filters=16,kernel_size=3,padding='same', activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4), input_shape=(256,180,3)))\r\n model.add(BatchNormalization())\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Conv2D(filters=32,kernel_size=3,padding='same', activation='relu', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4)))\r\n model.add(BatchNormalization())\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Conv2D(filters=64,kernel_size=3,padding='same', kernel_regularizer=regularizers.l1_l2(l1=1e-5, l2=1e-4), activation='relu'))\r\n model.add(MaxPooling2D(pool_size=2))\r\n model.add(BatchNormalization())\r\n model.add(Dropout(0.35))\r\n\r\n model.add(Flatten())\r\n model.add(Dense(256))\r\n model.add(BatchNormalization())\r\n model.add(Dense(1, activation='sigmoid'))\r\n model.summary()\r\n \r\n return model\r\n\r\n\r\ndef generate_imagedatagen():\r\n train_datagen = ImageDataGenerator(\r\n rescale = 1./255,\r\n rotation_range = 20,\r\n width_shift_range = 0.2,\r\n height_shift_range = 0.2,\r\n shear_range = 0.2,\r\n zoom_range = 0.3,\r\n horizontal_flip = False\r\n )\r\n \r\n test_datagen = ImageDataGenerator(rescale = 1./255)\r\n \r\n return train_datagen, test_datagen\r\n\r\n\r\ndef generate_datagen(train_datagen, test_datagen):\r\n train_generator1 = train_datagen.flow_from_directory('../input/tarros-dataset-final-for-real/DATASET_improved/1_front/train',\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator1 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/1_front/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n train_generator2 = train_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/2_back/train\",\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator2 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/2_back/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n train_generator3 = train_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/3_up/train\",\r\n target_size = (256,180),\r\n batch_size = 4,\r\n class_mode = \"binary\")\r\n\r\n validation_generator3 = test_datagen.flow_from_directory(\"../input/tarros-dataset-final-for-real/DATASET_improved/3_up/validation\",\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n return train_generator1, validation_generator1, train_generator2, validation_generator2, train_generator3, validation_generator3\r\n\r\n\r\ndef generate_checkpoints():\r\n checkpoint1 = ModelCheckpoint('tarros_1.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n checkpoint2 = ModelCheckpoint('tarros_2.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n checkpoint3 = ModelCheckpoint('tarros_3.hdf5', monitor = \"val_accuracy\", verbose = 1, save_best_only = True)\r\n \r\n return checkpoint1, checkpoint2, checkpoint3\r\n\r\n\r\ndef train_model(model, train_generator, validation_generator, checkpoint, epochs):\r\n model.compile(loss = \"binary_crossentropy\",\r\n optimizer = 'rmsprop',\r\n metrics = [\"accuracy\"])\r\n \r\n hist = model.fit(train_generator,\r\n steps_per_epoch = 448//4,\r\n epochs = epochs,\r\n validation_data = validation_generator,\r\n validation_steps = 56//1,\r\n callbacks = [checkpoint])\r\n \r\n return hist\r\n\r\n\r\ndef plot_performance(hist, title):\r\n plt.plot(hist.history[\"accuracy\"], label = \"Train\")\r\n plt.plot(hist.history[\"val_accuracy\"], label = \"Validation\")\r\n plt.title(title)\r\n plt.legend()\r\n plt.show()\r\n plt.savefig(title)\r\n\r\n\r\ndef train_network():\r\n model1 = generate_model()\r\n model2 = clone_model(model1)\r\n model3 = clone_model(model1)\r\n \r\n train_datagen, test_datagen = generate_imagedatagen()\r\n \r\n train_generator1, validation_generator1, train_generator2, validation_generator2, train_generator3, validation_generator3 = generate_datagen(train_datagen, test_datagen)\r\n \r\n checkpoint1, checkpoint2, checkpoint3 = generate_checkpoints()\r\n \r\n hist1 = train_model(model = model1, \r\n train_generator = train_generator1, \r\n validation_generator = validation_generator1, \r\n checkpoint = checkpoint1, \r\n epochs = 70)\r\n \r\n hist2 = train_model(model = model2, \r\n train_generator = train_generator2, \r\n validation_generator = validation_generator2, \r\n checkpoint = checkpoint2, \r\n epochs = 70)\r\n \r\n hist3 = train_model(model = model3, \r\n train_generator = train_generator3, \r\n validation_generator = validation_generator3, \r\n checkpoint = checkpoint3, \r\n epochs = 70)\r\n \r\n plot_performance(hist1, 'front-side performance')\r\n \r\n plot_performance(hist2, 'back-side performance')\r\n \r\n plot_performance(hist3, 'up-side performance')\r\n\r\n\r\ndef test_model(model_name, directory):\r\n test_model = load_model(model_name)\r\n test_datagen = ImageDataGenerator(rescale = 1./255)\r\n test_generator = test_datagen.flow_from_directory(directory,\r\n target_size = (256,180),\r\n batch_size = 1,\r\n class_mode = \"binary\")\r\n \r\n test_model.evaluate(test_generator)\r\n\r\n\r\nif __name__ == '__main__':\r\n train_network()\r\n test_model(model_name = './tarros_1.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/1_front/test')\r\n test_model(model_name = './tarros_2.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/2_back/test')\r\n test_model(model_name = './tarros_3.hdf5', \r\n directory = '../input/tarros-dataset-final-for-real/DATASET_improved/3_up/test')","repo_name":"TheFrancho/Plastic-Containers-CNN-Model","sub_path":"training/network_training.py","file_name":"network_training.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"50"}
+{"seq_id":"41739978174","text":"import numpy as np\nimport astropy.units as u\nimport astropy.constants as c\nfrom kick_amuse import *\n\nP = 1. *u.yr # years\ntperi = 0. *u.yr\na = 1. *u.AU #linear distance\ne = 0.5\ninc = 0. *np.pi *u.rad\nomega = 0. *np.pi *u.rad\nanode = 0. *np.pi *u.rad\n\nnum_particles = 1\n\nnum_steps = 600\n\nt_max = (P * 1)\nt_orbit = np.linspace(0,0+t_max.value,num_steps) *u.yr\n\ndelta_v_arr = np.ones(num_particles)*(.01)*u.m/u.s\ntheta_arr = np.ones(num_particles)*(0.5)*np.pi*u.rad\nphi_arr = np.ones(num_particles)*(0.)*np.pi*u.rad\n\nstellar_mass = c.M_sun\nm = c.M_earth\npart_masses = np.ones(num_particles)*(m/1000)\n\nkick_orbit_elements(t_orbit, stellar_mass, part_masses, P, a, e, tperi, inc, anode, omega, delta_v_arr, theta_arr, phi_arr)\n\n#original particle\n# X, Y, Xs, Ys, Zs, Xv, Yv, Zv = kep3d(t_orbit,P,tperi,a,e,inc,omega,anode)\n# save_kep3d(X, Y, Xs, Ys, Zs, Xv, Yv, Zv, filename = 'earthsun_prekick.csv', overwrite=True)\n# \n# # X_0 = Xs.copy()\n# # Y_0 = Ys.copy()\n# # Z_0 = Zs.copy()\n# \n# #kicked particle\n# X, Y, Xs, Ys, Zs, Xv, Yv, Zv = kep3d(t_orbit,P_prime,tperi_prime,a_prime,e_prime,inc_prime, omega_prime, anode_prime)\n# save_kep3d(X, Y, Xs, Ys, Zs, Xv, Yv, Zv, filename = 'earthsun_postkick.csv', overwrite=True)\n# \n# # dist = np.sqrt((X_0[0] - Xs[0])**2 + (Y_0[0] - Ys[0])**2 + (Z_0[0] - Zs[0])**2)\n# # \n# # print(dist)\n# \n# \n# # \n# animate_3d('./earthsuntest/')","repo_name":"catieslaughts/MRP_2022","sub_path":"code/old_code/amusetest/amusetest/amuse_testcoll.py","file_name":"amuse_testcoll.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"11443481955","text":"class Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n check = []\n suspect = {}\n if n == 1:\n return 1\n elif n == 2 and len(trust) ==1:\n return trust[0][1]\n for i in trust:\n check.append(i[0])\n if i[1] in suspect:\n suspect[i[1]].append(i[0])\n else:\n suspect[i[1]] = [i[0]]\n\n for i in suspect:\n if i not in check and len(suspect[i]) == n-1: \n return i\n return -1","repo_name":"kwilliam777/CodingTestStudy","sub_path":"weekly assingment/week1/k_997.py","file_name":"k_997.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"36125383101","text":"#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n new_matrix = []\n _list = []\n for list in matrix:\n for element in list:\n _list.append(element**2)\n new_matrix.append(_list)\n _list = []\n return new_matrix\n","repo_name":"Letsoken/alx-higher_level_programming","sub_path":"0x04-python-more_data_structures/0-square_matrix_simple.py","file_name":"0-square_matrix_simple.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"24736133006","text":"'''\nPROBLEM You are given a string that contains left and right parenthesis char-\nacters. Write code to determine whether the parentheses are correctly nested. For\nexample, the strings \"(())\" and \"()()\" are correctly nested but \"(()()\" and \")\n(\" are not.\n'''\ndef has_nested(s):\n my_stack = []\n list_s = list(s)\n for i in range(len(list_s)):\n if list_s[i] == \"(\":\n my_stack.append(list_s[i])\n elif list_s[i] == \")\" and len(my_stack) > 0:\n my_stack.pop()\n else: return False\n\n return len(my_stack) == 0\n\nresult = has_nested(\"(())()\")\nprint(result)\n\n'''\nTime complexity = O(n)\nSpace complexity = O(n)\n'''","repo_name":"kadimasum/BridgePy","sub_path":"stack/nested_parenthesis.py","file_name":"nested_parenthesis.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"10724060197","text":"import random\nimport pyglet\nimport logging\nimport os\nimport glob\nimport math\nfrom functions import *\nfrom actor import Actor, Hand\nfrom stats import StatSystem\nfrom animations import HandAnimAttack, HeadBobbing, Pulse\nfrom load_config import ConfigSectionMap as load_cfg\nimport abilities\nROOT = os.path.dirname(__file__)\nCLASSES_PATH = os.path.join(ROOT, \"classes/\")\n\n\nclass Player(Actor):\n\n def __init__(\n self, game, window=None, x=0, y=0,\n modifiers={'str': 5, 'int': 5, 'cha': 5, 'agi': 5}, mainstat=\"agi\"\n ):\n super().__init__()\n self.game = game\n self.child_objects = []\n self.cast_object = None\n self.x, self.y = x, y\n # self.movement = Movement(self)\n self.lhand_offset = (0, 0)\n self.rhand_offset = (0, 0)\n self.body_offset = (0, 0)\n self.child_objects.append(HeadBobbing(self, duration=0.5, amount=3))\n if window:\n self.windowpos = (window.width // 2, window.height // 2)\n logging.debug(\"Adding sprite to player.\")\n self.window = window\n sprite_x, sprite_y = window.get_windowpos(x, y, precise=True)\n self.sprite = pyglet.sprite.Sprite(\n window.textures[\"player_body\"],\n x=window.width // 2, y=window.height // 2,\n batch=window.batches[\"creatures\"], group=window.fg_group\n )\n self.glow = pyglet.sprite.Sprite(\n window.textures[\"player_body_glow\"],\n x=window.width // 2, y=window.height // 2,\n batch=window.batches[\"creatures\"], group=window.mid_group\n )\n self.glow.color = (255, 255, 255)\n self.glow.opacity = 0\n else:\n logging.info(\"No window specified, not adding sprite to player.\")\n\n self.limbs = dict(\n left=Hand(\n self, (-10, 8), window.textures[\"player_hand\"],\n glow_texture=window.textures[\"player_hand_glow\"],\n glow_color=(20, 160, 120)\n ),\n right=Hand(\n self, (10, 8), window.textures[\"player_hand\"],\n glow_texture=window.textures[\"player_hand_glow\"],\n glow_color=(175, 50, 110)\n )\n )\n self.child_objects.append(Pulse(self.limbs[\"right\"].glow))\n self.child_objects.append(\n Pulse(self.limbs[\"left\"].glow, frequency=0.3)\n )\n self.child_objects.append(\n Pulse(\n self.glow, frequency=2.5,\n max_opacity=0.3, min_scale=0.8, max_scale=1.3\n )\n )\n\n self.action = None\n self.actions = dict(\n sprint=False,\n movement=False,\n targeting=False,\n )\n self.auto_attack_target = None\n self.target = None\n self.modifiers = modifiers\n self.modifiers_items = modifiers\n self.mainstat = mainstat\n self.move_dir = dict(\n left=False,\n right=False,\n up=False,\n down=False\n )\n self.last_dir = \"down\"\n self.head_dir = (1, 0)\n\n self.base_stats = load_cfg(\"PlayerBaseStats\")\n self.base_stats_items = self.base_stats.copy()\n\n self.equipped_items = dict(\n head=None,\n torso=None,\n hands=None,\n feet=None,\n acc_1=None,\n acc_2=None,\n weapon_l=None,\n weapon_r=None,\n weapon_2h=None\n )\n\n self.attack_effects = dict(\n dmg=30,\n dmg_type=\"physical\",\n stun=0,\n slow=0,\n aoe=0,\n aoe_dmg=0,\n dot=None,\n dot_dmg=None,\n penetration=0,\n crit=10\n )\n\n self.stats = StatSystem(self)\n self.stats.set_base_attack(self.attack_effects)\n self.stats.set_base_stats(self.base_stats)\n self.stats.recalculate_items()\n\n self.abilities = dict(\n slot1=abilities.FireBall(self),\n slot2=abilities.SpreadBalls(self),\n slot3=abilities.Blink(self),\n slot4=abilities.Spark(self),\n )\n\n self.hp = self.max_hp = self.base_stats[\"hp\"]\n self.mp = self.max_mp = self.base_stats[\"mp\"]\n self.sta = self.max_sta = self.base_stats[\"sta\"]\n self.xp = 0\n self.attack_cd = 0\n\n self.update_stats()\n self.restore_stats()\n\n def get_windowpos(self):\n return self.windowpos\n\n def award_kill(self, xp=0, gold=0):\n if xp:\n self.xp += xp\n print(self.xp)\n if gold:\n pass\n\n def levelup(self, attribute=None):\n if not attribute: # If no attribute given, assign random upgrade\n attribute = random.choice([\"str\", \"int\", \"agi\"])\n\n # Increases the chosen attribute by 1\n self.stats.increase_stat(attribute)\n logging.info(\n \"Level up, increased attribute \\\"{0}\\\" by 1 to {1}\".format(\n attribute, self.stats.get(attribute)\n )\n )\n self.update_stats()\n self.restore_stats()\n\n def restore_stats(self):\n logging.debug(\"Player hp, mana and stamina restored to full status.\")\n self.hp = self.max_hp\n self.mp = self.max_mp\n self.sta = self.max_sta\n\n def equip_item(self, item):\n if not self.equipped_items[item.slot]:\n self.equipped_items[item.slot] = item\n logging.debug(\n \"Player equipped item {0} in slot {1}.\".format(\n item.get_name(), item.slot\n )\n )\n\n self.stats.recalculate_items()\n\n def unequip_item(self, slot):\n if self.equipped_items[slot]:\n logging.info(\n \"Removed item {0} in slot {1} from player\".format(\n self.equipped_items[slot], slot\n )\n )\n self.equipped_items[slot] = None\n else:\n logging.error(\"No item in slot \\\"{0}\\\"\".format(slot))\n\n self.stats.recalculate_items()\n\n def use_ability(self, ability, target=None):\n a = None\n if ability == 1:\n a = self.abilities[\"slot1\"]\n elif ability == 2:\n a = self.abilities[\"slot2\"]\n elif ability == 3:\n a = self.abilities[\"slot3\"]\n elif ability == 4:\n a = self.abilities[\"slot4\"]\n\n if a:\n logging.debug(\"Player uses ability {}.\".format(a.get_name()))\n if isinstance(a, abilities.ProjectileAbility):\n self.window.set_reticule(\"projectile\")\n self.actions[\"targeting\"] = a\n else:\n self.clear_ability_target()\n a.use(target=target)\n else:\n logging.debug(\"No ability in slot {0}.\".format(ability))\n\n def clear_ability_target(self):\n self.actions[\"targeting\"] = False\n self.window.set_reticule(\"default\")\n\n def set_target(self, target):\n self.target = target\n\n def clear_target(self):\n self.auto_attack_target = None\n self.target = None\n\n def halt_movement(self):\n for key, value in self.move_dir.items():\n self.move_dir[key] = False\n\n def set_move_sprite(self):\n anim = self.window.player_anim_grid\n static = self.window.player_static_img\n d = self.move_dir\n spd = 0.2 * 80 / self.stats.get(\"ms\")\n if d[\"left\"] and d[\"down\"]:\n self.last_dir = \"leftdown\"\n if not self.sprite.image == anim[\"leftdown\"]:\n self.sprite.image = anim[\"leftdown\"]\n elif d[\"right\"] and d[\"down\"]:\n self.last_dir = \"rightdown\"\n if not self.sprite.image == anim[\"rightdown\"]:\n self.sprite.image = anim[\"rightdown\"]\n elif d[\"left\"] and d[\"up\"]:\n self.last_dir = \"leftup\"\n if not self.sprite.image == anim[\"leftup\"]:\n self.sprite.image = anim[\"leftup\"]\n elif d[\"right\"] and d[\"up\"]:\n self.last_dir = \"rightup\"\n if not self.sprite.image == anim[\"rightup\"]:\n self.sprite.image = anim[\"rightup\"]\n elif d[\"up\"] and not d[\"down\"]:\n self.last_dir = \"up\"\n if not self.sprite.image == anim[\"up\"]:\n self.sprite.image = anim[\"up\"]\n elif d[\"down\"] and not d[\"up\"]:\n self.last_dir = \"down\"\n if not self.sprite.image == anim[\"down\"]:\n self.sprite.image = anim[\"down\"]\n elif d[\"left\"] and not d[\"right\"]:\n self.last_dir = \"left\"\n if not self.sprite.image == anim[\"left\"]:\n self.sprite.image = anim[\"left\"]\n elif d[\"right\"] and not d[\"left\"]:\n self.last_dir = \"right\"\n if not self.sprite.image == anim[\"right\"]:\n self.sprite.image = anim[\"right\"]\n else:\n if not self.sprite.image == static[self.last_dir]:\n self.sprite.image = static[self.last_dir]\n\n if isinstance(self.sprite.image, pyglet.image.Animation):\n set_duration(self.sprite.image, spd)\n\n def auto_attack(self, dt):\n t = self.auto_attack_target\n if t not in self.game.enemies: # To prevent having a zombie of target\n t = self.auto_attack_target = None\n if not self.cast_object and self.attack_cd <= 0:\n if t:\n dist = get_dist(self.x, self.y, t.x, t.y)\n attack_range = self.stats.get(\"arng\")\n if dist <= attack_range:\n angle = math.degrees(\n get_angle(self.x, self.y, t.x, t.y)\n )\n anglediff = (\n (self.angle - angle + 180) % 360 - 180\n )\n if anglediff <= 45 and anglediff >= -45:\n self.attack(t)\n self.attack_cd = self.stats.get(\"aspd\")\n else:\n self.attack_cd -= dt\n\n def attack(self, t):\n attack_effects = self.attack_effects.copy()\n attack_effects[\"dmg\"] = self.stats.get(\"dmg\")\n attack_effects[\"crit\"] = self.stats.get(\"crit\")\n result = t.do_effect(attack_effects, origin=self)\n self.attack_fx(t)\n if result[\"crit\"]:\n force = 100\n else:\n force = 50\n vec = ((t.x - self.x), (t.y - self.y))\n force_x = force_y = force\n force_x -= abs(vec[0])\n force_y -= abs(vec[1])\n force_vec = (vec[0] * force_x), (vec[1] * force_y)\n t.body.apply_impulse(force_vec)\n if result[\"crit\"]:\n self.child_objects.append(\n HandAnimAttack(\n self, \"left\", duration=self.stats.get(\"aspd\") / 3\n )\n )\n self.child_objects.append(\n HandAnimAttack(\n self, \"right\", duration=self.stats.get(\"aspd\") / 3\n )\n )\n else:\n hand = random.choice([\"right\", \"left\"])\n self.child_objects.append(\n HandAnimAttack(self, hand, duration=self.stats.get(\"aspd\") / 3)\n )\n\n def critical_strike(self, critchance):\n if random.randrange(1, 100) <= critchance:\n return True\n else:\n return False\n\n def attack_fx(self, t):\n midpoint = get_midpoint((self.x, self.y), (t.x, t.y))\n fx_point = get_midpoint(midpoint, (t.x, t.y))\n apos = self.game.window.get_windowpos(\n *fx_point\n )\n effect = random.choice([\"Melee 1\", \"Melee 2\", \"Melee 5\"])\n self.game.window.animator.spawn_anim(\n effect, apos, scale=0.25,\n rotation=self.angle - 45\n )\n\n def update_stats(self):\n self.stats.update_owner_stats()\n\n def update_regen(self, dt):\n if self.hp < self.max_hp:\n self.hp += self.stats.get(\"hp_regen\") * dt\n if self.mp < self.max_mp:\n self.mp += self.stats.get(\"mp_regen\") * dt\n if self.sta < self.max_sta and not self.actions[\"sprint\"]:\n self.sta += self.stats.get(\"sta_regen\") * dt\n\n def update_degen(self, dt):\n if self.actions[\"sprint\"]:\n if self.sta > 0:\n for d, val in self.move_dir.items():\n if val:\n self.sta -= 15 * dt\n break\n else:\n self.actions[\"sprint\"] = False\n\n def update_body(self):\n angle = get_angle(self.sprite.x, self.sprite.y, *self.window.mouse_pos)\n self.angle = math.degrees(angle)\n for key, limb in self.limbs.items():\n limb.update_pos()\n\n self.sprite.x, self.sprite.y = rotate2d(\n math.radians(self.angle + 90), (\n self.windowpos[0] + self.body_offset[0],\n self.windowpos[1] + self.body_offset[1]\n ),\n self.windowpos\n )\n self.sprite.rotation = self.angle + 90\n self.glow.x, self.glow.y = self.sprite.x, self.sprite.y\n self.glow.rotation = self.sprite.rotation\n\n def die(self):\n pos = self.window.get_windowpos(self.x, self.y, precise=True)\n self.window.animator.spawn_anim(\"Blood Splash\", pos, scale=0.8)\n # self.active_effects = []\n self.limbs = {}\n self.child_objects = []\n self.sprite.delete()\n self.glow.delete()\n self.remove_body()\n self.clear_target()\n self.clear_ability_target()\n self.game.player = None\n # self.sprite.visible = False\n logging.info(\"Player died!\")\n\n def update(self, dt):\n if self.hp <= 0:\n self.die()\n else:\n if self.xp >= 30:\n self.levelup()\n self.xp = 0\n self.movement.speed = self.stats.get(\"ms\")\n old_x, old_y = self.x, self.y\n self.movement.update(dt)\n self.window.update_offset(dx=old_x - self.x, dy=old_y - self.y)\n if self.actions[\"movement\"] and self.cast_object:\n self.cast_object = None\n logging.info(\"Cast interrupted by movement.\")\n self.auto_attack(dt)\n self.update_regen(dt)\n self.update_degen(dt)\n self.update_stats()\n for o in self.child_objects:\n try:\n o.update(dt)\n except Exception as e:\n logging.error(e)\n if self.cast_object:\n self.cast_object.update(dt)\n\n self.update_body()\n\n\nclass Damage:\n\n def __init__(self, owner, target, dmg=0, dmg_type=\"normal\"):\n self.owner, self.target = owner, target\n\n if self.owner.critical_strike(self.stats.get(\"crit\")):\n dmg = int(dmg * 1.5)\n logging.info(\"Critical strike!\")\n\n self.target.hp -= dmg\n if self.target.hp < 0:\n self.target.hp = 0\n logging.debug(\"Target takes {0} damage.\".format(dmg))\n\n def update(self, dt):\n pass\n\n# Reads all python files in the classes directory and executes them,\n# adding the classes to the game\nfor class_file in glob.glob(CLASSES_PATH + '*.py'):\n exec(open(class_file).read(), globals())\n","repo_name":"NiclasEriksen/rpg_procgen","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":15324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"8740163771","text":"# Problem 25\n# 1000-digit Fibonacci number\n\nfibs = [1,1]\ndigits = 1000\nfor num in range(100000):\n fibs.append(fibs[num]+fibs[num+1])\n if len(str(fibs[num+2])) == digits:\n break\nprint(f'The {len(fibs)} fib has {digits} digits')","repo_name":"cavandervoort/Project-Euler-001-to-100","sub_path":"Euler_025.py","file_name":"Euler_025.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"6458454479","text":"soma = 0 \r\nlista = \"\"\r\nlista2 = \"\"\r\nwhile True: \r\n m, n = map(int, input().split())\r\n if m <= 0 or n <= 0: break\r\n if m<=n:\r\n a = m\r\n b = n\r\n else:\r\n a = n\r\n b = m\r\n for i in range(a,b+1):\r\n lista += str(i)\r\n soma += i\r\n lista = \" \".join(lista)+\" Sum=\"+str(soma)\r\n lista2 += lista+\"\\n\"\r\n lista = \"\"\r\n soma = 0\r\nprint(lista2.rstrip())","repo_name":"Gefft3/ProblemasBeecrowd","sub_path":"beecrowd/1101.py","file_name":"1101.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"40557211986","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nfrom lu import *\nfrom choleski import *\nfrom matplotlib import animation\nfrom scipy.sparse import csr_matrix, csc_matrix, diags, linalg as sla\n\nR, tmax = 0.065, 60. # en mètres, en secondes\nD = 98.8e-6 # Diffusivité thermique de l'aluminium\nTmax = 80. # °C\nTamb = 20. # °C\nNx_lst = np.array([10_000])\nNt_lst = np.array([2_811_768])\n\nfor Nx in Nx_lst:\n for Nt in Nt_lst:\n dx = R / (Nx + 1)\n dt = tmax / (Nt + 1)\n beta = D * dt / dx ** 2\n\n print(\"beta={}, Nx={}, Nt={}\".format(beta, Nx, Nt))\n\n X = np.array([0. for _ in range(Nx + 2)])\n\n # Matrice Euler implicite\n diag = [1 + 2. * beta for _ in range(Nx + 2)]\n diag[0], diag[Nx + 1] = 1, 1 # Condition aux bornes\n\n upper_band = [-beta for _ in range(Nx + 1)]\n upper_band[0] = 0\n\n lower_band = [-beta for _ in range(Nx + 1)]\n lower_band[Nx] = 0\n\n diagonals = [diag, lower_band, upper_band]\n M = csc_matrix(diags(diagonals, [0, -1, 1]))\n\n # Vecteur initial\n B = np.transpose(np.array([Tamb for _ in range(Nx + 2)]))\n B[0] = Tmax\n\n # superLU\n LU = sla.splu(M)\n # print(\"L done\")\n # print(L)\n\n x_i = [i * dx * 100 for i in range(Nx + 2)] # Positions des points à l'intérieur de l'intervalle\n fig = plt.figure()\n line, = plt.plot([], [])\n plt.xlim(0, R * 100)\n plt.ylim(Tamb, Tmax)\n plt.xlabel('Position (cm)')\n plt.ylabel('Temperature (°C)')\n\n for i in range(Nt):\n X = LU.solve(B)\n if i % 50_000 == 0:\n print(i)\n plt.plot(x_i, X, 'b')\n B = X.copy()\n plt.show()\n '''\n def animate(i):\n global LU, B, X\n X = LU.solve(B)\n\n if i % 1_000 == 0:\n print(i)\n plt.plot(x_i, X, 'b')\n #line.set_data(x_i, X)\n # print(x_i)\n #print(X)\n B = X.copy()\n\n # filename = folder+'/{:0>9}.png'.format(i)\n\n # save frame\n # plt.savefig(filename)\n\n return line,\n '''\n\n # ani = animation.FuncAnimation(fig, animate, frames=Nt, blit=True, repeat=False)#interval=.5, repeat=False)\n\n # time.sleep(5)\n # plt.show()\n","repo_name":"UnderscorePoY/L3_Python","sub_path":"AlgebreLineaireNumerique/Projet_ALN/main_anim_superLU.py","file_name":"main_anim_superLU.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"39881997686","text":"import anki_vector\nimport time\nfrom PIL import Image\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nwith anki_vector.Robot(enable_camera_feed=True) as robot:\n robot.motors.set_head_motor(-5.0) # move head to look at ground\n robot.motors.set_wheel_motors(10, 10) # set initial driving direction\n for count in range(25):\n while not robot.camera.latest_image:\n time.sleep(1.0)\n\n imageFromVector = robot.camera.latest_image\n image = cv2.cvtColor(np.array(imageFromVector),cv2.COLOR_RGB2GRAY) #convert image to gray\n\n maskArea = np.array([[(125, 200),(175,100), (450, 100), (500, 225)]], dtype=np.int32)\n\n blank = np.zeros_like(image)\n\n mask = cv2.fillPoly(blank, maskArea, 255)\n\n maskedImage = cv2.bitwise_and(image, mask)\n\n image_canny = cv2.Canny(maskedImage,50,200,apertureSize=3)\n\n rho = 2\n theta = np.pi/180\n threshold = 50\n minLine = 50\n maxLine = 8\n lines = cv2.HoughLinesP(image_canny, rho, theta, threshold, np.array([]), minLineLength=minLine, maxLineGap=maxLine)\n #lines = cv2.HoughLines(image_canny,1,np.pi/180,200) # for regular Hough Transform\n\n\n\n try:\n if lines[0,0,0] < 150: # turn left slightly\n robot.motors.set_wheel_motors(10, 15)\n\n elif lines[1,0,0] > 450: # turn right slightly\n robot.motors.set_wheel_motors(15, 10)\n\n else: # go straight\n robot.motors.set_wheel_motors(10, 10)\n except:\n print(\"didnt find any\")\n\n # the code below is for testing purposes\n # plt.imshow(image_canny)\n # #plt.imshow(image,cmap=\"gray\")\n # plt.show()\n # cv2.waitKey(3)\n # print(lines)\n","repo_name":"cggonzal/Self-Driving-Anki-Vector","sub_path":"lineFollowingVector.py","file_name":"lineFollowingVector.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"52"}
+{"seq_id":"75225266404","text":"import os\nimport boto3\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nfrom racial_covenants_processor.storage_backends import PrivateMediaStorage\nfrom apps.deed.models import DeedPage\nfrom apps.zoon.models import ZooniverseSubject\nfrom apps.zoon.utils.zooniverse_config import get_workflow_obj\n\n\nclass Command(BaseCommand):\n\n session = boto3.Session(\n aws_access_key_id=settings.AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)\n\n def add_arguments(self, parser):\n parser.add_argument('-w', '--workflow', type=str,\n help='Name of Zooniverse workflow to process, e.g. \"Ramsey County\"')\n\n def build_hit_lookup(self, workflow):\n '''\n First step of join_to_subjects. Expands the list of image ids from the ZooniverseSubject instance to create a lookup table from each image id to the ZooniverseSubject primary key\n\n Arguments:\n workflow: Django ZooniverseWorkflow object\n '''\n\n subject_hit_set = ZooniverseSubject.objects.filter(\n workflow=workflow\n ).exclude(\n deedpage_s3_lookup__isnull=True\n ).values('id', 'deedpage_s3_lookup')\n\n subject_hit_lookup = {}\n for subject in subject_hit_set:\n subject_hit_lookup[subject['deedpage_s3_lookup']] = subject['id']\n\n return subject_hit_lookup\n\n def join_subjects_to_hits(self, deed_pages, subject_hit_lookup):\n '''\n Second step of join_to_subjects. Does the Django work to actually update the database\n\n Arguments:\n deed_pages: Django queryset of DeedPage objects from previously selected workflow\n subject_hit_lookup: A dictionary where each key is an s3_lookup from the Zooniverse subject data, and the value is the pk value for the correct ZooniverseSubject instance\n '''\n\n # Build a lookup dict for the DeedImage objects for comparison to subject_image_lookup so we only loop through necessary DeedPage objects\n deed_pages_lookup = {\n page['s3_lookup']: page['id'] for page in deed_pages.values('id', 's3_lookup')\n }\n\n common_keys = [key for key in deed_pages_lookup.keys()\n & subject_hit_lookup.keys()]\n # common_keys = list(set(deed_pages_lookup.keys()).intersection(set(subject_hit_lookup.keys())))\n\n deed_pages_lookup_filtered = {\n key: deed_pages_lookup[key] for key in common_keys}\n\n pages_to_update = []\n for dp in deed_pages.filter(id__in=deed_pages_lookup_filtered.values()):\n dp.zooniverse_subject_id = subject_hit_lookup[dp.s3_lookup]\n pages_to_update.append(dp)\n\n print(f'Linking images for {len(pages_to_update)} hits ...')\n DeedPage.objects.bulk_update(\n pages_to_update, [f'zooniverse_subject'])\n\n def build_image_lookup(self, workflow, position):\n '''\n Third step of join_to_subjects. Expands the list of image ids from the ZooniverseSubject instance to create a lookup table from each image id to the ZooniverseSubject primary key\n\n Arguments:\n workflow: Django ZooniverseWorkflow object\n '''\n\n subject_image_set = ZooniverseSubject.objects.filter(\n workflow=workflow\n ).exclude(\n image_links__isnull=True\n ).values('id', 'image_links')\n\n expanded_subject_image_set = {}\n for subject in subject_image_set:\n image = subject['image_links'][position]\n # for image in subject['image_links']:\n if image not in ['', None]:\n expanded_subject_image_set[os.path.basename(image.replace(\n '.png', '.jpg'))] = subject['id']\n\n return expanded_subject_image_set\n\n def add_image_links(self, deed_pages, subject_image_lookup, page):\n '''\n Fourth step of join_to_subjects. Does the Django work to actually update the database\n\n Arguments:\n deed_pages: Django queryset of DeedPage objects from previously selected workflow\n subject_image_lookup: A dictionary where each key is an image id from the Zooniverse subject data, and the value is the pk value for the correct ZooniverseSubject instance\n page: What position is this image in relative to the individual subject (1st, 2nd, or 3rd)\n '''\n\n # Build a lookup dict for the DeedImage objects for comparison to subject_image_lookup so we only loop through necessary DeedPage objects\n deed_pages_lookup = {os.path.basename(\n page['page_image_web']): page['id'] for page in deed_pages.values('id', 'page_image_web')}\n\n common_keys = [key for key in deed_pages_lookup.keys()\n & subject_image_lookup.keys()]\n\n deed_pages_lookup_filtered = {\n key: deed_pages_lookup[key] for key in common_keys}\n\n pages_to_update = []\n for dp in deed_pages.filter(id__in=deed_pages_lookup_filtered.values()):\n setattr(\n dp,\n f'zooniverse_subject_{page}_page_id',\n subject_image_lookup[os.path.basename(str(dp.page_image_web))]\n )\n pages_to_update.append(dp)\n\n print(f'{page} page: Linking {len(pages_to_update)} images ...')\n DeedPage.objects.bulk_update(\n pages_to_update, [f'zooniverse_subject_{page}_page'])\n\n def handle(self, *args, **kwargs):\n workflow_name = kwargs['workflow']\n if not workflow_name:\n print('Missing workflow name. Please specify with --workflow.')\n else:\n workflow = get_workflow_obj(workflow_name)\n\n deed_pages = DeedPage.objects.filter(\n workflow=workflow\n ).only('id', 'page_image_web', 's3_lookup')\n\n # Join to deed page of hit via deedpage_s3_lookup\n subject_hit_lookup = self.build_hit_lookup(workflow)\n self.join_subjects_to_hits(deed_pages, subject_hit_lookup)\n\n\n # Join all related DeedPage images based on image position\n subject_images_1st = self.build_image_lookup(workflow, 0)\n subject_images_2nd = self.build_image_lookup(workflow, 1)\n subject_images_3rd = self.build_image_lookup(workflow, 2)\n\n self.add_image_links(deed_pages, subject_images_1st, '1st')\n self.add_image_links(deed_pages, subject_images_2nd, '2nd')\n self.add_image_links(deed_pages, subject_images_3rd, '3rd')\n","repo_name":"UMNLibraries/racial_covenants_processor","sub_path":"apps/deed/management/commands/join_deeds_to_subjects.py","file_name":"join_deeds_to_subjects.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"13901065954","text":"# _*_ coding:utf-8 _*_\n__author__ = 'Tanz'\n__date__ = '2019/6/4 14:26'\nimport time\nfrom app.start.start import get_driver\ndef login_by_phone(driver):\n # driver = get_driver()\n time.sleep(10)\n driver.find_element_by_android_uiautomator('new UiSelector().text(\"personal center-outline 个人中心\")').click()\n time.sleep(2)\n driver.find_element_by_xpath('//android.view.View[contains(@index,4)]').click()\n phone_input = driver.find_elements_by_class_name('android.widget.EditText')\n phone_input[0].send_keys('18852923055')\n phone_input[1].send_keys('123456')\n driver.find_element_by_android_uiautomator('new UiSelector().className(\"android.widget.Button\").text(\"登录\")').click()\n","repo_name":"PhoeNixTanZ/Moxa-Aromatherapy-Machine-Test","sub_path":"AF_autotest/app/login/phone_login.py","file_name":"phone_login.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73076294886","text":"# glow.py\n# This program uses PWM output to change the brightness of\n# each of the R, G and B color of the RGB LED.\n# Colour is chosen randomly and the PWM is modified over a series of steps\n# to change from the current colour to the new colour\n\n# Import Python library\nimport RPi.GPIO as GPIO\nimport time\nimport random\nimport math\n\nDUTY_CYCLE = 100\nBLACK = [0.0, 0.0, 0.0]\n\n# Pin Setup:\nGPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme\n\nPWMS = []\n# Pin Definitions, R=GPIO023, G=GPIO024, B=GPIO025:\nfor pin in [23, 24, 25]:\n GPIO.setup(pin, GPIO.OUT) # LED pin set as output\n\n # Initialize PWM on all pins at 100Hz frequency\n pwm = GPIO.PWM(pin, DUTY_CYCLE)\n pwm.start(0)\n PWMS.append(pwm)\n\nprint(\"Press CTRL+C to terminate program\")\ntry:\n last_colour = BLACK\n\n while 1:\n # Create a new colour (need 3 channels - R, G and B)\n new_colour = [float(random.randint(0, DUTY_CYCLE) * random.randint(0, 1)) for _ in range(3)]\n\n scale = max(new_colour)\n if not scale:\n # We ignore black - it's boring\n continue\n\n # Make it maximally bright by scaling to the max duty cycle\n target_colour = [DUTY_CYCLE * channel / scale for channel in new_colour]\n\n # Find the distance between this colour and the previous to make the\n # shade change appear event no matter what colours we move between\n sum_squares = 0.0\n for a, b in zip(last_colour, target_colour):\n sum_squares += math.pow(a - b, 2)\n steps = int(math.sqrt(sum_squares))\n\n if not steps:\n # There is no meaningful difference in colour, so pick a new one\n continue\n\n # Create a list containing how big each step in for each colour channel is\n # We also include the PWM itself to make the call easier later\n interpolate = [(pwm, base, (target - base) / steps)\n for pwm, base, target in zip(PWMS, last_colour, target_colour)]\n\n for i in range(steps):\n for pwm, base, gradient in interpolate:\n pwm.ChangeDutyCycle(int(base + i * gradient))\n time.sleep(0.1) #delay 0.1 second\n time.sleep(0.2) # slight pause at the peak colour\n last_colour = target_colour\n\nexcept KeyboardInterrupt: # Exit program if CTRL+C is pressed\n for pwm in PWMS:\n pwm.stop()\n GPIO.cleanup() # cleanup all GPIO and set all to input","repo_name":"aalcock/watering","sub_path":"glow.py","file_name":"glow.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"73033689445","text":"import torch\nfrom torch import nn\n\n\n# x=torch.rand(1,17)\n# print(x)\n#\n# print(x.view(1,1,-1))\n#\n# print(x.size())\n# print(x.size(0))\n# print(x.size(1))\n# print(x.data)\n# topv,topi=x.data.topk(1)#返回最大的两个数及对应的坐标\n# print(topv,topi,topi.item())\n\n\n\n# input=torch.randn(1,17)\n# print(input)\n# print(input.size())\n# m=nn.LayerNorm(17)\n# output=m(input)\n# print(output)\n\n\n\n#RNN\nrnn=nn.RNN(10,20,2) #(each_input_size, hidden_state, num_layers)\ninput=torch.randn(5,3,10) # (seq_len, batch, input_size)\nh0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\noutput,hn=rnn(input,h0)\nprint(output.size(),hn.size())\n\n\n#LSTM\nrnn=nn.LSTM(10,20,2) #(each_input_size, hidden_state, num_layers)\ninput=torch.randn(5,3,10) # (seq_len, batch, input_size)\nh0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\nc0=torch.randn(2,3,20) #(num_layers * num_directions, batch, hidden_size)\noutput,(hn,cn)=rnn(input,(h0,c0))\nprint(output.size(),hn.size(),cn.size())\n\n\n#GRU\nrnn=nn.GRU(10,20,2)\ninput=torch.randn(5,3,10)\nh0=torch.randn(2,3,20)\noutput,hn=rnn(input,h0)\nprint(output.size(),hn.size())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"zhanxlin/translate","sub_path":"RNN_pytorch_ex.py","file_name":"RNN_pytorch_ex.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"298623482","text":"from airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\nfrom airflow.providers.postgres.hooks.postgres import PostgresHook\n\n\nclass QueryPostgres(BaseOperator):\n @apply_defaults\n def __init__(\n self,\n table=None,\n last_extraction_timestamp=None,\n attributes=None,\n *args,\n **kwargs,\n ):\n super(QueryPostgres, self).__init__(*args, **kwargs)\n self.table = table\n self.last_extraction_timestamp = last_extraction_timestamp\n self.attributes = attributes\n\n def execute(self, context):\n postgres_hook = PostgresHook(postgres_conn_id=\"postgres_homero\")\n\n sql_query = f\"\"\"\n SELECT {self.attributes}\n FROM {self.table}\n WHERE updatedAt > '{self.last_extraction_timestamp}'\n \"\"\"\n\n conn = postgres_hook.get_conn()\n cursor = conn.cursor()\n cursor.execute(sql_query)\n result = cursor.fetchall()\n\n data_list = []\n\n for data in result:\n record = dict(zip(self.attributes.split(\", \"), data))\n record[\"_id\"] = record.pop(\"id\")\n data_list.append(record)\n\n cursor.close()\n conn.close()\n\n return data_list\n","repo_name":"supervipe/ETL-Airflow","sub_path":"dags/operators/postegresql_operator/extract_data_operator.py","file_name":"extract_data_operator.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"14732213997","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 17 17:31:57 2021\n\n@author: AMK\n\"\"\"\n\n\n\"\"\"\nCreated on Wed Mar 10 18:21:33 2021\n\n@author: AMK\n\"\"\"\nimport os\nimport pandas as pd\nfrom tensorflow.keras.preprocessing import image\nimport numpy as np\n\nimport keras.backend as k\nimport keras\nfrom keras.models import Sequential,Input,Model\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.models import model_from_json\nfrom sklearn.model_selection import train_test_split\nfrom keras import regularizers\n\nBase=os.path.abspath('Data/train')\nBT=os.listdir(Base)\nnclasses=len(BT)\n\ndef train_data():\n x=[]\n y=[]\n for i in BT:\n t=os.path.join(Base,i)\n for j in os.listdir(t):\n img=os.path.join(t,j)\n img = image.load_img(img, target_size=(48,48),color_mode=\"grayscale\")\n img_array = image.img_to_array(img)\n y.append(BT.index(i))\n x.append(img_array)\n \n x=np.array(x).reshape(-1,48,48,1)\n x /=255\n y = keras.utils.to_categorical(y,nclasses)\n return x,y\n\n\n\ndef test_data():\n Base=os.path.abspath('Data/test')\n BT=os.listdir(Base)\n nclasses=len(BT)\n xt=[]\n yt=[]\n for i in BT:\n t=os.path.join(Base,i)\n for j in os.listdir(t):\n img=os.path.join(t,j)\n img = image.load_img(img, target_size=(48,48),color_mode=\"grayscale\")\n img_array = image.img_to_array(img)\n img_array.shape\n yt.append(BT.index(i))\n xt.append(img_array)\n xt=np.array(xt).reshape(-1,48,48,1) \n xt /=255 \n yt = keras.utils.to_categorical(yt,nclasses)\n return xt,yt\n\n\nx,y=train_data()\nxt,yt=test_data()\n\nxtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.20,shuffle=True)\nimport autokeras as ak\nclf=ak.ImageClassifier()\nclf.fit(xtrain,ytrain)\nr=clf.predict(xtest)\n","repo_name":"Muthukumar1303/DS-Projects","sub_path":"Emoji Create/clftry.py","file_name":"clftry.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"12300271165","text":"import logging\nimport optparse\nimport os\nimport sys\nimport time\n\n_SRC_PATH = os.path.abspath(os.path.join(\n os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))\n\nsys.path.append(os.path.join(_SRC_PATH, 'third_party', 'catapult', 'devil'))\nfrom devil.android import device_utils\nfrom devil.android import flag_changer\nfrom devil.android.constants import chrome\nfrom devil.android.perf import cache_control\nfrom devil.android.sdk import intent\n\nsys.path.append(os.path.join(_SRC_PATH, 'build', 'android'))\nimport devil_chromium\n\nimport chrome_setup\nimport device_setup\n\n\ndef RunChrome(device, cold, chrome_args, package_info):\n \"\"\"Runs Chrome on the device.\n\n Args:\n device: (DeviceUtils) device to run the tests on.\n cold: (bool) Whether caches should be dropped.\n chrome_args: ([str]) List of arguments to pass to Chrome.\n package_info: (PackageInfo) Chrome package info.\n \"\"\"\n if not device.HasRoot():\n device.EnableRoot()\n\n cmdline_file = package_info.cmdline_file\n package = package_info.package\n with flag_changer.CustomCommandLineFlags(device, cmdline_file, chrome_args):\n device.ForceStop(package)\n\n if cold:\n chrome_setup.ResetChromeLocalState(device, package)\n cache_control.CacheControl(device).DropRamCaches()\n\n start_intent = intent.Intent(package=package, data='about:blank',\n activity=package_info.activity)\n try:\n device.StartActivity(start_intent, blocking=True)\n print (\n '\\n\\n'\n ' +---------------------------------------------+\\n'\n ' | Chrome launched, press Ctrl-C to interrupt. |\\n'\n ' +---------------------------------------------+')\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n pass\n finally:\n device.ForceStop(package)\n\n\ndef _CreateOptionParser():\n description = 'Launches Chrome on a device, connected to a WebPageReplay ' \\\n 'instance running on the host. The WPR archive must be ' \\\n 'passed as parameter.'\n parser = optparse.OptionParser(description=description,\n usage='Usage: %prog [options] wpr_archive')\n\n # Device-related options.\n d = optparse.OptionGroup(parser, 'Device options')\n d.add_option('--device', help='Device ID')\n d.add_option('--cold', help='Purge all caches before running Chrome.',\n default=False, action='store_true')\n d.add_option('--chrome_package_name',\n help='Chrome package name (e.g. \"chrome\" or \"chromium\") '\n '[default: %default].', default='chrome')\n parser.add_option_group(d)\n\n # WebPageReplay-related options.\n w = optparse.OptionGroup(parser, 'WebPageReplay options')\n w.add_option('--record',\n help='Enable this to record a new WPR archive.',\n action='store_true', default=False)\n w.add_option('--wpr_log', help='WPR log path.')\n w.add_option('--network_condition', help='Network condition for emulation.')\n parser.add_option_group(w)\n\n return parser\n\n\ndef main():\n parser = _CreateOptionParser()\n options, args = parser.parse_args()\n if len(args) != 1:\n parser.error(\"Incorrect number of arguments.\")\n devil_chromium.Initialize()\n devices = device_utils.DeviceUtils.HealthyDevices()\n device = devices[0]\n if len(devices) != 1 and options.device is None:\n logging.error('Several devices attached, must specify one with --device.')\n sys.exit(0)\n if options.device is not None:\n matching_devices = [d for d in devices if str(d) == options.device]\n if not matching_devices:\n logging.error('Device not found.')\n sys.exit(0)\n device = matching_devices[0]\n\n with device_setup.RemoteWprHost(device, args[0], options.record,\n options.network_condition,\n out_log_path=options.wpr_log) as wpr_attr:\n RunChrome(device, options.cold,\n chrome_setup.CHROME_ARGS + wpr_attr.chrome_args,\n chrome.PACKAGE_INFO[options.chrome_package_name])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kiwibrowser/src","sub_path":"tools/android/loading/wpr_helper.py","file_name":"wpr_helper.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":2475,"dataset":"github-code","pt":"52"}
+{"seq_id":"43145917348","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport time\n\ndriver = webdriver.Chrome(ChromeDriverManager().install())\ndriver.implicitly_wait(10)\n\ndriver.get('https://mail.rediff.com/cgi-bin/login.cgi')\n\ndriver.find_element(By.NAME, 'proceed').click()\ntime.sleep(3)\n#js pop windows\nalert = driver.switch_to.alert\nprint(alert.text)\nalert.accept()\n#alert.dismiss()\nalert.send_keys('h1')\n#main window again select\ndriver.swith_to.default_content()\n\n\ntime.sleep(3)\ndriver.quit()\n\ndriver.get('http://www.londonfreelance.org/courses/frames/index.html')\ndriver.switch_to.frame('main')\n\n#main ( also we can count 123 (2)\n#another method frame_element = driver.find_element(By.NAME, 'main')\n#driver.switch_to.frame(frame_element)\n\nheaderValue = driver.find_element(By.CSS_SELECTOR, 'body > h2').text\n\nprint(headerValue)\n\ndriver.switch_to.default_content()\n#default method alternative parent method\n#driver.switch_to.parent_frame()\n\n","repo_name":"padalasurendramac/python","sub_path":"selenium/fileupload.py","file_name":"fileupload.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"27546483696","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File : jknet.py\n@Time : 2022/4/10 11:16 上午\n@Author : Jia Yiming\n\"\"\"\n\nimport tensorlayerx as tlx\nfrom gammagl.layers.conv import SAGEConv, GCNConv, JumpingKnowledge\n\n\nclass JKNet(tlx.nn.Module):\n def __init__(self, dataset, mode='max', num_layers=6, hidden=16, drop=0.5):\n super(JKNet, self).__init__()\n self.num_layers = num_layers\n self.mode = mode\n self.drop = drop\n\n self.conv0 = GCNConv(in_channels=dataset.num_node_features, out_channels=hidden)\n self.dropout0 = tlx.nn.Dropout(p=drop)\n for i in range(1, self.num_layers):\n setattr(self, 'conv{}'.format(i), GCNConv(hidden, hidden))\n setattr(self, 'dropout{}'.format(i), tlx.nn.Dropout(p=drop))\n self.jk = JumpingKnowledge(mode=mode, channels=hidden, num_layers=num_layers)\n if mode == 'max':\n self.fc = tlx.nn.Linear(in_features=hidden, out_features=dataset.num_classes)\n elif mode == 'cat':\n self.fc = tlx.nn.Linear(in_features=num_layers * hidden, out_features=dataset.num_classes)\n elif mode == 'lstm':\n self.fc = tlx.nn.Linear(in_features=hidden, out_features=dataset.num_classes)\n\n\n def forward(self, x, edge_index, edge_weight, num_nodes):\n layer_out = []\n for i in range(self.num_layers):\n conv = getattr(self, 'conv{}'.format(i))\n dropout = getattr(self, 'dropout{}'.format(i))\n x = dropout(tlx.relu(conv(x, edge_index, edge_weight=edge_weight)))\n layer_out.append(x)\n h = self.jk(layer_out)\n h = self.fc(h)\n h = tlx.softmax(h, axis=1)\n return h","repo_name":"BUPT-GAMMA/GammaGL","sub_path":"gammagl/models/jknet.py","file_name":"jknet.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"52"}
+{"seq_id":"7588276092","text":"from pyrogram.enums import ParseMode\n\nfrom spotipy import SpotifyOAuth, Spotify\n\nfrom alemibot import alemiBot\nfrom alemibot.util import is_allowed, edit_or_reply, filterCommand, report_error, HelpCategory\nfrom alemibot.util.command import _Message as Message\n\nfrom ..common import format_track, progress_bar\nfrom ..session import sess\n\nimport logging\nlogger = logging.getLogger(__name__)\n\nHELP = HelpCategory(\"SPOTIFY\")\n\nSPOTIFY : Spotify\n\n@alemiBot.on_ready()\nasync def setup_spotify_oauth_api_cb(client:alemiBot):\n\tglobal SPOTIFY\n\tauth = SpotifyOAuth(\n\t\tusername=client.config.get(\"spotify\", \"username\", fallback=None),\n\t\tscope=\"user-modify-playback-state user-read-currently-playing\",\n\t\tclient_id=client.config.get(\"spotify\", \"clientId\", fallback=None),\n\t\tclient_secret=client.config.get(\"spotify\", \"clientSecret\", fallback=None),\n\t\tredirect_uri='https://alemi.dev/spotify.html',\n\t\topen_browser=False\n\t)\n\tSPOTIFY = Spotify(auth_manager=auth)\n\tlogger.debug(str(SPOTIFY.current_user()))\n\n@HELP.add(cmd=\"\", sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"queue\", flags=[\"-preview\"]))\n@report_error(logger)\nasync def add_to_queue_cmd(client:alemiBot, message:Message):\n\t\"\"\"add song to queue\n\n\tAdd a track to spotify queue.\n\tAccepts both a search query or a spotify URI.\n\tUse `search` command to first lookup songs if you are unsure of your query.\n\tAdd `-preview` flag to include spotify track url and embedded preview.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tif len(message.command) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No input\")\n\tpreview = message.command[\"-preview\"]\n\tq = message.command.text\n\tif q.startswith(\"spotify:\") or q.startswith(\"http://open.spotify.com\"):\n\t\tSPOTIFY.add_to_queue(q)\n\t\tawait edit_or_reply(message, \"` → ` Added to queue\")\n\telse:\n\t\tres = SPOTIFY.search(q, limit=1)\n\t\tif len(res) < 1:\n\t\t\treturn await edit_or_reply(message, \"`[!] → ` No results\")\n\t\tSPOTIFY.add_to_queue(res[\"tracks\"][\"items\"][0][\"uri\"])\n\t\ttext = format_track(res[\"tracks\"][\"items\"][0], preview=preview)\n\t\tawait edit_or_reply(message, f\"` → ` Added to queue : {text}\", disable_web_page_preview=True)\n\n@HELP.add(sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"playing\", flags=[\"-preview\"]))\n@report_error(logger)\nasync def show_current_song_cmd(client:alemiBot, message:Message):\n\t\"\"\"show track currently played\n\n\tShows track currently being played, with a progress bar.\n\tAdd flag `-preview` to include spotify track url and embedded preview.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tpreview = message.command[\"-preview\"]\n\tres = SPOTIFY.current_user_playing_track()\n\tif not res:\n\t\treturn await edit_or_reply(message, \"`[!] → ` Not playing anything\")\n\ttext = format_track(res[\"item\"], preview=preview) + '\\n' + progress_bar(res[\"progress_ms\"], res['item']['duration_ms'])\n\tawait edit_or_reply(message, f\"` → ` {text}\")\n\n@HELP.add(sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"skip\"))\n@report_error(logger)\nasync def skip_track_cmd(client:alemiBot, message:Message):\n\t\"\"\"skip current track\n\n\tSkip current track. Since playout is buffered (for resampling), skip may take up to 5s.\n\t\"\"\"\n\tif not sess.group_call or not sess.group_call.is_connected:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No active call\")\n\tSPOTIFY.next_track()\n\tawait edit_or_reply(message, \"` → ` Skipped\")\n\n@HELP.add(cmd=\"\", sudo=False)\n@alemiBot.on_message(is_allowed & filterCommand(\"search\", options={\n\t\"limit\" : [\"-l\", \"--limit\"],\n}, flags=[\"-preview\"]))\n@report_error(logger)\nasync def search_track_cmd(client:alemiBot, message:Message):\n\t\"\"\"search a song on spotify\n\n\tSearch tracks on spotify. Will return first 5 results (change with `-l`).\n\tSong URIs will be returned, use this before queuing uncommon songs\n\t\"\"\"\n\tif len(message.command) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No input\")\n\tlimit = int(message.command[\"limit\"] or 5)\n\tpreview = message.command[\"-preview\"]\n\tq = message.command.text\n\tres = SPOTIFY.search(q, limit=limit)[\"tracks\"][\"items\"]\n\tif len(res) < 1:\n\t\treturn await edit_or_reply(message, \"`[!] → ` No results\")\n\ttext = f\"→ Results for \\\"{q}\\\"\\n\"\n\tfor track in res:\n\t\ttext += f\" → {format_track(track, html=True, preview=preview)}\\n\\t\\t\\t\\t{track['uri']}\\n\"\n\tawait edit_or_reply(message, text, parse_mode=ParseMode.HTML, disable_web_page_preview=(len(res) > 1))","repo_name":"alemidev/spotyrobot","sub_path":"commands/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"52"}
+{"seq_id":"72038157926","text":"from dependencies import *\nfrom qcircuit import *\nfrom train import save_model\nimport time\n# tem que estar normalizado\n\ndef get_activation(w,train_set_x,num_shots = 8192):\n m = len(train_set_x[0])\n n = ceil(log2(m))\n A = np.array([])\n w_sent = phase_normalize(w, np.min(w), np.max(w))\n train_set_x_sent = phase_normalize(train_set_x, 0, 255)\n for pos,train_input in enumerate(train_set_x_sent):\n model = PerceptronCircuit(train_input, w_sent, n)\n qobj = assemble(model) \n counts = sim.run(qobj,shots = num_shots).result().get_counts()\n \n if \"1\" in counts:\n A = np.append(A,counts[\"1\"]/ num_shots)\n else:\n A = np.append(A,0.)\n return A\n\ndef get_dJ(w):\n phi = phase_normalize(w, np.min(w), np.max(w))\n theta = phase_normalize(train_set_x, 0, 255)\n set_size = train_set_x.shape[0]\n u = theta - phi # theta - phi\n c = np.cos(u) # cos(theta - phi)\n C = c.sum(axis = 1).reshape(1,set_size).T\n s = np.sin(u)\n S = s.sum(axis = 1).reshape(1,set_size).T\n A = (C * C + S * S) / 2**(2 * n)\n return (2 * (s*C - c*S) / 2**(2 * n)) * A/set_size\n\n\n\ndef get_A(w,train_set_x,n):## Função exata de A\n phi = phase_normalize(w, np.min(w), np.max(w))\n theta = phase_normalize(train_set_x, 0, 255)\n set_size = train_set_x.shape[0]\n u = theta - phi \n c = np.cos(u) \n C = c.sum(axis = 1).reshape(1,set_size).T\n s = np.sin(u)\n S = s.sum(axis = 1).reshape(1,set_size).T\n return (C * C + S * S) / 2**(2 * n)\n\n\ndef loss_func(w):\n A = get_activation(w,train_set_x_gb,8192)\n diff = A.reshape(set_size,1) - train_set_y_gb.reshape(set_size,1)\n cost = np.sum(diff ** 2) / set_size\n print(\"Custo: {}\\n\".format(cost))\n save_model(w, -1)\n return cost\n \ndef powerseries_f(eta=0.01, power=2, offset=0):\n k = 1\n while True:\n yield eta / ((k + offset) ** power)\n k += 1\n\ndef learning_rate_f():\n return powerseries_f(50.860244892404292, 0.602, 0)\n\ndef perturbation_f():\n return powerseries_f(0.1, 0.101)\n\ndef optimize(w,train_x,train_y, Hyperparameters):\n global train_set_x_gb\n global train_set_y_gb\n global set_size\n train_set_x_gb = train_x\n train_set_y_gb = train_y\n\n set_size = len(train_set_y_gb)\n\n\n spsa = SPSA(maxiter=Hyperparameters[\"iterations\"],learning_rate = learning_rate_f, perturbation = perturbation_f)\n result = spsa.optimize(num_vars=1,objective_function=loss_func,gradient_function=get_dJ, initial_point = w)\n return result[0],result[1]","repo_name":"daviyan5/QuantumPerceptron","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"30904894900","text":"#Author: Andrew Otto B\n#If you're looking for a skilled Python, C++, Java, C#, or JavaScript developer\n#Contact me: twitter.com/@ARPPoisoning\n\n#Guide for Debian/Ubuntu-based distributions. If you're using a Arch-based distribution, replace apt-get with pacman -S.\n#Prequisites:\n#sudo apt-get install ffmpeg\n#sudo apt-get install python-tk\n#sudo apt-get install python-pil\n#sudo apt install python-pip\n#pip install pyscreenshot\n\n\nfrom Tkinter import *\nfrom threading import Thread\nfrom os.path import expanduser\nimport os\nimport time\nimport tkFont\nimport pyscreenshot\n\ndef recThread():\n os.system(\"ffmpeg -video_size 1366x768 -framerate 30 -f x11grab -i :0.0 -f pulse -ac 2 -i 0 $(date +%d%b_%Hh%Mm).mkv\")\ndef rec():\n b.config(state=DISABLED)\n b1.config(state=ACTIVE)\n t = Thread(target=recThread)\n t.start()\n global count_flag, secs, mins\n count_flag = True\n secs=0\n mins=0\n while True:\n if count_flag == False:\n break\n label['text'] = str(\"%02dm:%02ds\" % (mins,secs))\n if secs == 0:\n time.sleep(0)\n else:\n time.sleep(1)\n if(mins==0 and secs==1):\n b1.config(bg=\"red\")\n b.config(fg=\"red\")\n b.config(bg=\"red\")\n if secs==60:\n secs=0\n mins+=1\n label['text'] = str(\"%02dm:%02ds\" % (mins,secs))\n root.update()\n secs = secs+1\ndef stop():\n\n b.config(state=ACTIVE)\n b1.config(state=DISABLED)\n b1.config(fg=\"green\")\n b1.config(bg=\"green\")\n b.config(fg=\"green\")\n b.config(bg=\"green\")\n global count_flag\n count_flag = False\n os.system(\"pkill -n ffmpeg\")\n try:\n t.stop()\n except:\n print(\"\")\n\ndef screenshot():\n im = pyscreenshot.grab()\n im.save('screenshot.png')\n\n \n\nroot = Tk()\nfontTime = tkFont.Font(family=\"Franklin Gothic\", size=12)\nfontButton = tkFont.Font(family=\"Times New Roman\", size=11,weight=\"bold\")\nlabel = Label(root, text=\"00m:00s\",fg=\"blue\",font=\"fontTime\")\nb = Button(root,text=\"Record\",command=rec,state=ACTIVE,bg=\"green\",font=\"fontButton\")\nb1 = Button(root,text=\"Stop\",command=stop,state=DISABLED,bg=\"red\",font=\"fontButton\")\nb2 = Button(root, text = \"Screenshot\",command=screenshot,bg=\"orange\",font=\"fontButton\")\nl = Label(root, text=\"\")\nl1 = Label(root, text=\"\")\nlabel.grid(row=0, column=0, columnspan=2)\nb.grid(row=1, column=0, padx=1, pady=5)\nb1.grid(row=1, column=1, padx=1)\nb2.grid(row=1, column=2, padx=1)\nl.grid(row=2, column=0,columnspan=2)\nl1.grid(row=3, column=0,columnspan=2)\nroot.minsize(280,105)\nroot.maxsize(280,105)\nroot.title(\"Linux Screen Recorder\")\nroot.attributes(\"-topmost\", 1)\nroot.mainloop()\n","repo_name":"Exploitability/Linux-Screen-Recorder","sub_path":"LinuxScreenRecorder/linuxscreenrecorder.py","file_name":"linuxscreenrecorder.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"38466963718","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 24 16:20:56 2018\n\n@author: manucastilla\n\"\"\"\n\nimport tkinter as tk\n\ndef diz_oi():\n print (\"boa\")\n\nwindow = tk.Tk()\n\nbotao = tk.Button(window)\nbotao.configure(text=\"aperta aqui!\")\nbotao.configure(command=diz_oi)\nbotao.grid()\n\nwindow.mainloop()","repo_name":"AmandaRM/EP--design-de-software","sub_path":"aulatk.py","file_name":"aulatk.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"71650364964","text":"import os\nimport cv2\nimport time\nimport pickle\nimport random\nimport os.path as osp\nfrom tqdm import tqdm\n\nimport torch\nimport numpy as np\n\nfrom Camera.BaseCamera import BaseCamera, fmeasure\n\n\n# #######################################################################\ndef get_sequence_list(img_list, label_list):\n seq_list = []\n _seq_list = []\n for l in label_list:\n imglist = sorted(img_list[l])\n idx = 0\n while idx < 54:\n num = np.random.randint(int(0.5 * len(imglist)), len(imglist))\n start = np.random.randint(0, len(imglist) - num)\n seq = imglist[start:start + num]\n m = np.abs(np.array([x[3] for x in seq])).min()\n if m > 0.01:\n continue\n _seq = '{}{}{}'.format(seq[0][0].split('_')[0], start, num)\n if _seq not in _seq_list:\n seq_list.append(seq)\n _seq_list.append(_seq)\n idx += 1\n np.random.shuffle(seq_list)\n return seq_list\n\n\ndef rand(size=1, range=1):\n assert (isinstance(size, int)\n or isinstance(size, tuple)), 'size must be int or tuple'\n if isinstance(size, int):\n size = (size, )\n return (np.random.rand(*size) - 0.5) * 2 * range\n\n\ndef img_lrud_move(img, x=0, y=0):\n '''\n left-right-up-down movement\n '''\n h, w = img.shape\n\n if x > 0:\n img = np.pad(img, ((0, 0), (0, x)), 'edge')\n img = img[:, x:w + x]\n elif x < 0:\n img = np.pad(img, ((0, 0), (np.abs(x), 0)), 'edge')\n img = img[:, :w]\n if y > 0:\n img = np.pad(img, ((0, y), (0, 0)), 'edge')\n img = img[y:h + y, :]\n elif y < 0:\n img = np.pad(img, ((np.abs(y), 0), (0, 0)), 'edge')\n img = img[:h, :]\n return img\n\n\ndef init_move(fb_move,\n lrud_move,\n max_fb_move=0.25,\n max_lrud_move=0.15,\n max_frame=50):\n lrud_move = str(lrud_move)\n fb_move = str(fb_move)\n if lrud_move.lower() == 'random':\n lrud_move = random.choice(\n ['linear', 'cos', 'rlinear', 'rcos', 'random', 'none'])\n if fb_move.lower() == 'random':\n fb_move = random.choice(\n ['linear', 'cos', 'rlinear', 'rcos', 'random', 'none'])\n\n if fb_move.lower() == 'linear':\n start, end = np.sort(rand(2))\n fb_move = np.linspace(start, end, max_frame) * max_fb_move\n elif fb_move.lower() == 'cos':\n start, end = np.sort(rand(2, 4 * np.pi))\n fb_move = np.cos(np.linspace(start, end, max_frame)) * max_fb_move\n elif fb_move.lower() == 'rlinear':\n start, end = np.sort(rand(2))\n fb_move = (np.sort(np.random.uniform(start, end, max_frame)) +\n np.random.normal(0, 0.5, max_frame) * 0.2) * max_fb_move\n elif fb_move.lower() == 'rcos':\n start, end = np.sort(rand(2, 4 * np.pi))\n fb_move = (np.cos(np.sort(np.random.uniform(start, end, max_frame))) +\n np.random.normal(0, 0.5, max_frame) * 0.2) * max_fb_move\n elif fb_move.lower() == 'random':\n fb_move = np.random.normal(0, 0.5, max_frame) * max_fb_move\n else:\n fb_move = None\n\n if lrud_move.lower() == 'linear':\n start, end = np.sort(rand((2, 2)), axis=0)\n lrud_move = np.stack(\n (np.linspace(start[0], end[0],\n max_frame), np.linspace(start[1], end[1], max_frame)),\n axis=1) * max_lrud_move\n elif lrud_move.lower() == 'cos':\n start, end = np.sort(rand((2, 2), 4 * np.pi), axis=0)\n lrud_move = np.cos(\n np.stack((np.linspace(start[0], end[0], max_frame),\n np.linspace(start[1], end[1], max_frame)),\n axis=1)) * max_lrud_move\n elif lrud_move.lower() == 'rlinear':\n start, end = np.sort(rand((2, 2)), axis=0)\n lrud_move = (np.stack(\n (np.sort(np.random.uniform(start[0], end[0], max_frame)),\n np.sort(np.random.uniform(start[1], end[1], max_frame))),\n axis=1) + np.random.normal(0, 0.5,\n (max_frame, 2)) * 0.2) * max_lrud_move\n elif lrud_move.lower() == 'rcos':\n start, end = np.sort(rand((2, 2), 4 * np.pi), axis=0)\n lrud_move = (np.cos(\n np.stack((np.sort(np.random.uniform(start[0], end[0], max_frame)),\n np.sort(np.random.uniform(start[1], end[1], max_frame))),\n axis=1)) +\n np.random.normal(0, 0.5,\n (max_frame, 2)) * 0.2) * max_lrud_move\n elif lrud_move.lower() == 'random':\n lrud_move = np.random.normal(0, 0.5, (max_frame, 2)) * max_lrud_move\n else:\n lrud_move = None\n if lrud_move is not None:\n lrud_move = lrud_move\n return fb_move, lrud_move\n\n\n# #######################################################################\nclass VirtualCamera(BaseCamera):\n def __init__(self,\n seq,\n mode='norm',\n max_frame=30,\n min_ele=0,\n max_ele=530,\n move_type=(None, None),\n is_save_result=True,\n is_save_img=True,\n is_display=False,\n is_display_info=True) -> None:\n super().__init__(min_ele, max_ele, is_save_result, is_save_img,\n is_display, is_display_info)\n self.seq = seq\n self.mode = mode\n self.dis_mode = mode\n self.max_frame = max_frame\n\n self.basepath = 'dataset/HutIris-Blur/png'\n self.len_range = np.array([int(x[0].split('_')[2]) for x in seq])\n self.min_ele = self.len_range.min()\n self.max_ele = self.len_range.max()\n\n self.seq = {int(x[0].split('_')[2]): x for x in seq}\n\n self.move_type = move_type\n self.fb_move, self.lrud_move = init_move(move_type[0],\n move_type[1],\n max_frame=max_frame)\n\n self._config()\n\n def _find_side(self, target):\n idx = np.abs(self.len_range - int(target)).argmin()\n p1 = self.len_range[idx]\n if p1 > target and idx - 1 > 0:\n p2 = self.len_range[idx - 1]\n elif p1 < target and idx + 1 < len(self.len_range):\n p2 = self.len_range[idx + 1]\n else:\n p2 = p1\n return p1, p2\n\n def _getimg(self, pos=None, loc=True):\n # fb move\n if self.fb_move is not None:\n offset_z = self.fb_move[self.frame_num % self.max_frame]\n offset_z = int(offset_z * (self.max_ele - self.min_ele))\n pos += offset_z\n\n if pos in self.len_range:\n img, roi = self._load_img(self.seq[pos])\n else:\n pos1, pos2 = self._find_side(pos)\n if np.abs(pos1 - pos2) < 1:\n img, roi = self._load_img(self.seq[pos1])\n else:\n img1, roi1 = self._load_img(self.seq[pos1])\n img2, roi2 = self._load_img(self.seq[pos2])\n alpha1 = np.abs(pos1 - pos) / np.abs(pos1 - pos2)\n alpha2 = np.abs(pos2 - pos) / np.abs(pos1 - pos2)\n img = alpha1 * img1.astype(np.double) + alpha2 * img2.astype(\n np.double)\n img = np.clip(np.round(img), 0, 255).astype(np.uint8)\n roi = np.round(alpha1 * np.array(roi1) +\n alpha2 * np.array(roi2)).astype(np.int)\n assert np.all(roi > 0)\n\n # lrud move\n if self.lrud_move is not None:\n offset_x, offset_y = self.lrud_move[self.frame_num %\n self.max_frame]\n offset_x = int(offset_x * img.shape[1])\n offset_y = int(offset_y * img.shape[0])\n img = img_lrud_move(img, offset_x, offset_y)\n roi = roi - np.array([offset_x, offset_y, 0])\n\n return img, roi.tolist()\n\n def _load_img(self, info, resize=True):\n _path = osp.join(self.basepath, info[0] + '.png')\n img = cv2.imread(_path, cv2.IMREAD_GRAYSCALE)\n roi = np.array([\n [\n int((info[-1][0])),\n int((info[-1][1])),\n int((info[-1][2])),\n ],\n [\n int((info[-1][3])),\n int((info[-1][4])),\n int((info[-1][5])),\n ],\n ])\n if resize:\n img = cv2.resize(img, None, fx=0.125, fy=0.125)\n roi = np.round(roi * 0.125).astype(np.int)\n return img, roi\n\n def _loop(self):\n if self.mode == 'fib':\n self.fibonacci_search()\n while self.frame_num < self.max_frame:\n self.get_img()\n if self.key == ord('q'):\n break\n elif self.mode == 'fast':\n self.fast_tracking(self.max_frame)\n else:\n if self.is_display:\n if self.move_type[0] is not None or self.move_type[\n 1] is not None:\n while self.frame_num < self.max_frame:\n self.get_img()\n if self.key == ord('q'):\n break\n else:\n while self.cur_ele < self.max_ele:\n self.get_img(self.cur_ele)\n self.cur_ele += 1\n if self.key == ord('q'):\n break\n if self.is_display:\n cv2.destroyAllWindows()\n return 0\n\n def _final(self):\n if self.is_save_result:\n img_num = len(self.saved_result['img'])\n ele = np.array(self.saved_result['ele'])\n ele = (ele - ele.min()) / (ele.max() - ele.min())\n self.saved_result['ele_norm'] = ele\n\n if len(self.saved_result['gt_roi']) > 0:\n roi = self.saved_result['gt_roi']\n elif len(self.saved_result['roi']) > 0:\n roi = self.saved_result['roi']\n else:\n roi = [None for _ in range(img_num)]\n fm = [\n fmeasure(self.saved_result['img'][idx], roi[idx])\n for idx in range(img_num)\n ]\n self.saved_result['focus'] = np.array(fm)\n self.saved_result['seq'] = self.seq\n self.saved_result['move'] = (self.fb_move, self.lrud_move)\n if not self.is_save_img:\n del self.saved_result['img']\n\n\n# #######################################################################\ndef debug():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n\n cam = VirtualCamera(seq_list[5],\n max_frame=30,\n mode='fast',\n move_type=(None, None),\n is_save_img=False,\n is_save_result=True)\n cam.run()\n\n\ndef test():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n\n print('1/4 fib stay')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fib',\n # move_type=(None, None),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=(None, None),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fibstay.pth')\n\n print('2/4 fib move')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fib',\n # move_type=('cos', 'cos'),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=('cos', 'cos'),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fibmove.pth')\n\n print('3/4 fast stay')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fast',\n # move_type=(None, None),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fast',\n move_type=(None, None),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/faststay.pth')\n\n print('4/4 fast move')\n result = []\n # for seq in tqdm(seq_list[:-5]):\n # cam = VirtualCamera(\n # seq,\n # max_frame=30,\n # mode='fast',\n # move_type=('cos', 'cos'),\n # is_save_img=False,\n # is_save_result=True,\n # is_display=False,\n # )\n # cam.run()\n # result.append(cam.saved_result)\n for seq in tqdm(seq_list[-5:]):\n cam = VirtualCamera(\n seq,\n max_frame=30,\n mode='fib',\n move_type=('cos', 'cos'),\n is_save_img=True,\n is_save_result=True,\n is_display=False,\n )\n cam.run()\n result.append(cam.saved_result)\n torch.save(result, 'Camera/result/fastmove.pth')\n\n\ndef show():\n with open('dataset/HutIris-Blur/meta_info.pkl', \"rb\") as f:\n meta_info = pickle.load(f)\n img_list = meta_info['label2']\n label_list = meta_info['split'][2]\n seq_list = get_sequence_list(img_list, label_list)\n seq_list = np.random.choice(seq_list, 5)\n\n for seq in tqdm(seq_list):\n cam = VirtualCamera(\n seq,\n max_frame=np.random.randint(45, 75),\n mode='fast',\n move_type=('none', 'none'),\n is_save_img=True,\n is_save_result=True,\n is_display=True,\n )\n cam.run()\n result = cam.saved_result\n dst = 'D:/Code/FocusTracker/Camera/result/fast_stay_{}'.format(\n int(time.time()))\n os.makedirs(dst)\n for idx in range(len(result['ele'])):\n frame = result['img'][idx]\n text = 'frame:{} fm:{} ele:{}'.format(idx,\n int(result['focus'][idx]),\n int(result['ele'][idx]))\n cv2.putText(frame, text, (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5,\n (255, 255, 255), 1, cv2.LINE_AA)\n cv2.imwrite('{}/{:0>2d}.png'.format(dst, idx), frame)\n\n\n# #######################################################################\n\nif __name__ == \"__main__\":\n show()","repo_name":"Debatrix/AquulaCam","sub_path":"Camera/autoFocus_test.py","file_name":"autoFocus_test.py","file_ext":"py","file_size_in_byte":15798,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"31778892039","text":"#!/usr/bin/env python\n'''\n@FileName : partition.py\n@Description : DAG could be partitioned into two independent subsets.\n@Date : 2022/12/14 17:42:53\n@Author : Wiger\n@version : 1.0\n'''\ndef divide_into_independent_subsets(graph):\n # Create a reversed copy of the graph\n reversed_graph = {vertex: set() for vertex in graph}\n for vertex, edges in graph.items():\n for neighbor in edges:\n reversed_graph[neighbor].add(vertex)\n\n # Initialize the stack and visited set\n stack = []\n visited = set()\n\n # Depth-first search on the reversed graph to get the finish times of the vertices\n def dfs(vertex):\n visited.add(vertex)\n for neighbor in reversed_graph[vertex]:\n if neighbor not in visited:\n dfs(neighbor)\n stack.append(vertex)\n\n for vertex in reversed_graph:\n if vertex not in visited:\n dfs(vertex)\n\n # Initialize the strongly connected components\n sccs = []\n\n # Clear the visited set\n visited.clear()\n\n # Depth-first search on the original graph to find the strongly connected components\n def dfs(vertex, scc):\n visited.add(vertex)\n scc.add(vertex)\n for neighbor in graph[vertex]:\n if neighbor not in visited:\n dfs(neighbor, scc)\n\n while stack:\n vertex = stack.pop()\n if vertex not in visited:\n scc = set()\n dfs(vertex, scc)\n sccs.append(scc)\n\n # Return the strongly connected components\n return sccs\n\ngraph = {\n '1': {'2', '3'},\n '2': {'4'},\n '3': {'4'},\n '4': {'5'},\n '5': {'6'},\n '6': {'1'},\n '7': {'7'},\n '8': {'9'},\n '9': {'8'}\n}\n\nsccs = divide_into_independent_subsets(graph)\nprint(sccs)\n","repo_name":"wigerwei/state-verification-machine","sub_path":"dag/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"14736423849","text":"class Solution:\n def intToRoman(self,num):\n romanSymbol = [\"I\",\"IV\",\"V\",\"IX\",\"X\",\"XL\",\"L\",\"XC\",\"C\",\"CD\",\"D\",\"CM\",\"M\"]\n romanVal = [1,4,5,9,10,40,50,90,100,400,500,900,1000]\n\n # romanSymbol = [\"I\",\"V\",\"X\",\"L\",\"C\",\"D\",\"M\"]\n # romanVal = [1,5,10,50,100,500,1000]\n\n n = num\n tuples = [(key, value) for i, (key, value) in enumerate(zip(romanVal, romanSymbol))]\n romanNum = dict(tuples)\n\n\n preSolution = []\n solution = \"\"\n i = 0 \n while n > 0: #Big O = 7n --> n --> linear \n while i < len(romanVal):\n print(\"note: \",n,\"compare\",romanVal[i],\"iteration\",i)\n if n <= 0:\n break\n if n == romanVal[i]:\n print(f\"Exact Case: {n}-{romanVal[i]} = {n-romanVal[i]}\")\n #print(romanVal[i])\n n -= romanVal[i]\n preSolution.append(romanVal[i])\n i = 0 \n \n #append answer to preSolution\n \n elif n < romanVal[i]: #main case where n is not exact so we find the nearest value\n # print(romanVal[i-1])\n print(f\"Nearest Val case: {n}-{romanVal[i-1]} = {n-romanVal[i-1]}\")\n n-= romanVal[i-1]\n preSolution.append(romanVal[i-1])\n i = 0 \n \n elif (n > 1000) :\n print(f\"Special Case: {n}-{1000} = {n-1000}\")\n n -= 1000 #1000 is the max value available for the roman number notation\n preSolution.append(1000)\n i = 0\n i += 1\n \n \n\n print(preSolution)\n\n for i in preSolution:\n solution += romanNum[i]\n \n return solution","repo_name":"prompto416/leetcode-competitive-programming-questions","sub_path":"medium/integerToRoman/integerToRoman.py","file_name":"integerToRoman.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"72429268005","text":"__author__ = \"kdhht5022@gmail.com\"\nfrom keras.regularizers import l2\nfrom sklearn.cross_validation import train_test_split\nfrom six.moves import xrange\nfrom keras.layers import LSTM, Dense, Dropout, Activation, Flatten, Lambda\nfrom keras.layers import MaxPooling1D, MaxPooling2D, AveragePooling2D, MaxPooling3D\nfrom keras.layers import Conv1D, Conv2D, Conv3D, GlobalAveragePooling2D, GlobalMaxPooling2D\nfrom keras.layers.convolutional_recurrent import ConvLSTM2D, ConvRecurrent2D\nfrom keras.engine import Input, Model\n\nfrom keras.callbacks import Callback, LearningRateScheduler, ModelCheckpoint, EarlyStopping\nfrom keras.preprocessing.image import ImageDataGenerator\nimport json\nimport keras\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import SGD, Adam\nfrom keras import backend as K\n\nfrom keras.models import Sequential\nfrom keras.layers.embeddings import Embedding\nfrom keras.utils.data_utils import get_file\n\nfrom keras.layers.wrappers import TimeDistributed, Bidirectional\nimport numpy as np\n\nfrom keras.layers.wrappers import TimeDistributed, Bidirectional\nfrom keras.layers.recurrent import SimpleRNN, GRU\n\nimport warnings\nfrom keras.utils import layer_utils\n\n\n\nif __name__ == \"__main__\":\n\n from util import Util as util\n X_data_name_1 = '/your/path/train/x_train.npz'\n y_data_name_1 = '/your/path/train/y_train.npz'\n X_data_name_2 = '/your/path/test/x_test.npz'\n y_data_name_2 = '/your/path/test/y_test.npz'\n X_train, y_train = util.load_from_npz(X_data_name_1), util.load_from_npz(y_data_name_1)\n X_test, y_test = util.load_from_npz(X_data_name_2), util.load_from_npz(y_data_name_2)\n\n def normalize(X_train, X_test):\n mean = np.mean(X_train,axis=0)\n std = np.std(X_train, axis=0)\n X_train = (X_train-mean)/(std+1e-7)\n X_test = (X_test-mean)/(std+1e-7)\n return X_train, X_test\n \n # data normalize\n X_train, X_test = normalize(X_train, X_test)\n \n X_train = X_train.reshape(1464,1,577)\n X_test = X_test.reshape(383,1,577)\n\n \n # one-hot\n from keras.utils import np_utils\n nb_classes = 7\n y_train = np_utils.to_categorical(y_train, nb_classes).astype(np.float32)\n y_test = np_utils.to_categorical(y_test, nb_classes).astype(np.float32)\n\n from keras.layers.merge import concatenate, add\n def audio_clstm(inputs):\n x = GRU(577, return_sequences=True)(inputs)\n x = Dropout(0.8)(x)\n # x = concatenate( [x1, x2] )\n x = GRU(577, return_sequences=True)(x)\n x = Dropout(0.8)(x)\n x = GRU(577, return_sequences=True)(x)\n x = Dropout(0.8)(x)\n x = GRU(577)(x)\n x = Dropout(0.8)(x)\n x = Dense(7, activation='softmax')(x)\n \n return x\n \n # Case 1: CLSTM\n # from keras.layers.merge import concatenate, add\n inputs = Input(shape=(1,577))\n\n out = audio_clstm(inputs)\n model_clstm = Model(inputs=[inputs], outputs=[out])\n model_clstm.summary()\n\n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_clstm.compile(optimizer='adam', \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-clstm/model_clstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=False, save_weights_only=True, mode='auto', period=1)\n model_clstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n \n # Save model information in yaml and weight\n open('/your/path/checkpoint-clstm/model_audio_clstm.yaml', 'w').write(model_clstm.to_yaml())\n proba_clstm = model_clstm.predict_on_batch(X_test)\n \n # Case 2: Bidirectional LSTM model\n model_Bilstm = Sequential()\n model_Bilstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Bidirectional(LSTM(577, return_sequences=True)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Bidirectional(LSTM(577)))\n model_Bilstm.add(Dropout(0.8))\n model_Bilstm.add(Dense(7, activation='softmax'))\n model_Bilstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_Bilstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-Bilstm/model_Bilstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True, mode='auto', period=1)\n model_Bilstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n \n # Case 3: LSTM model\n model_lstm = Sequential()\n model_lstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577, return_sequences=True))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(Dense(7, activation='softmax'))\n model_lstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_lstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-lstm/model_lstm_weights.{epoch:02d}-{loss:.2f}-{val_acc:.2f}.h5', monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True, mode='auto', period=1)\n model_lstm.fit(X_train, y_train, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=200, callbacks=[mc])\n\n \n # Case 3: LSTM\n model_lstm = Sequential()\n model_lstm.add(LSTM(577, return_sequences=True,\n input_shape=(1,577)))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577, return_sequences=True))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(LSTM(577))\n model_lstm.add(Dropout(0.8))\n model_lstm.add(Dense(7, activation='softmax'))\n model_lstm.summary()\n \n sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True)\n model_lstm.compile(optimizer=sgd, \n loss='categorical_crossentropy', \n metrics=['accuracy'])\n \n mc = keras.callbacks.ModelCheckpoint('/your/path/checkpoint-lstm/model_lstm_weights.{epoch:02d}-{loss:.2f}.h5', monitor='val_loss', verbose=1, save_best_only=False, save_weights_only=True, mode='auto', period=1)\n model_lstm.fit(X_train_2nd, y_train_2nd, batch_size=4, validation_data=(X_test, y_test), \n shuffle=True, epochs=50, callbacks=[mc])\n","repo_name":"InhaDeeplearningGroup/EmotiW_2017","sub_path":"audio_based/audio_lstm.py","file_name":"audio_lstm.py","file_ext":"py","file_size_in_byte":6869,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"52"}
+{"seq_id":"28974741802","text":"#!/usr/bin/python -tt\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport random as rd\nimport sys\nimport itertools as it\n\ndef ER(n, z, s):\n\tG=nx.Graph()\n\tG.add_nodes_from(range(n))\n\tedges=it.combinations(range(n),2) #builds tuples of (0,1) (0,2) to (n,n-1)\n\tp=float(z)/float(n)\n\trd.seed(s)\n\n\tfor e in edges:\n\t\tif rd.random() int:\n g = defaultdict(list)\n vis = set()\n res = n * (n-1) // 2\n def dfs(node):\n cnt = 1\n vis.add(node)\n for child in g[node]:\n if child not in vis:\n cnt += dfs(child) \n return cnt\n for u,v in edges:\n g[u].append(v)\n g[v].append(u)\n \n for i in range(n):\n if i in vis:\n continue\n cur = dfs(i)\n res -= cur * (cur - 1) // 2\n return res\n","repo_name":"samyogita/LeetCode-problems","sub_path":"count_unreachable_pairs_of_nodes_in_an_undirected_graph.py","file_name":"count_unreachable_pairs_of_nodes_in_an_undirected_graph.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"}
+{"seq_id":"73848391204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 17 15:06:32 2015\n\n@author: niyuli\n\"\"\"\n\nimport Bio\nimport Bio.Seq\nimport Bio.Alphabet.IUPAC\nimport Bio.SeqIO\nimport Bio.AlignIO\nimport Bio.Entrez\nimport random\n\nprint (Bio.__version__)\n\nmyseq = Bio.Seq.Seq(\"CAT CAT CAT UTC UUG UCG UUG CCU CTU GUG UUG TTC UTG\")\n\nmyseq = Bio.Seq.Seq(str(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n\nmyseq = str(myseq).replace(\" \", '')\nmyseq = Bio.Seq.Seq(str(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n\nprint (myseq.translate() )\nprint ('whole sequnce', myseq)\nprint (\"Every fourth necleotide: \", myseq[::4])\n\n\nproteinseq = myseq.translate()\nreversecomplement = myseq.reverse_complement()\nrevcomp_protein = reversecomplement.translate()\n\nprint(\"rev complement\", reversecomplement)\nprint (\"revcomp_protien\", reversecomplement.translate())\n\nrevcomp_protein = revcomp_protein[: -3]\nprint (\"revcomp --> protein minus 3\", revcomp_protein)\n\n\n\nmyseqrecord = Bio.SeqRecord.SeqRecord(id=\"MyFirstSeq\", description = \"This is my first seq record\",\n seq=myseq)\nprint(myseqrecord)\n\nmyseqrecord.format(\"fasta\")\nprint(myseqrecord.format(\"fasta\"))\nprint(myseqrecord.format(\"genbank\")) \nprint(myseqrecord.format(\"seqxml\"))\n\n\nmyseq = [\"A\",\"T\",\"C\",\"G\"]*25\nseq_record_list = []\nfor i in range(100):\n random.shuffle(myseq)\n \n myseq_object = Bio.Seq.Seq(\"\".join(myseq), Bio.Alphabet.IUPAC.IUPACUnambiguousDNA())\n \n seq_record = Bio.SeqRecord.SeqRecord(id = str(i), description = '', seq = myseq_object)\n seq_record_list.append(seq_record)\n \ncount = Bio.SeqIO.write(seq_record_list, \"l31_random_seqs.fna\", \"fasta\") \n\n\ninput_file = Bio.SeqIO.parse(\"l31_random_seqs.fna\", \"fasta\")\n\nfor record in input_file:\n print(record.format(\"fasta\"), end='')\n\n\nmy_alignment = Bio.AlignIO.read(\"l31_random_seqs.fna\", \"fasta\")\nprint(my_alignment)\n\nBio.AlignIO.write(my_alignment, \"l31_random_seqs.stk\", \"stockholm\")\n\n\n\n\n","repo_name":"danielnee2/Bootcamptest","sub_path":"biopython.py","file_name":"biopython.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"10598216528","text":"from django.conf.urls import include\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.reference_list, name='reference_list'),\n path('reference//', views.reference_detail, name='reference_detail'),\n path('reference/new/', views.reference_new, name='reference_new'),\n path('reference//edit', views.reference_edit, name='reference_edit'),\n path('fav//', views.favourite_add, name='favourite_add'),\n]","repo_name":"BlaNaoZ/jjbioenergy","sub_path":"app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23694018935","text":"import agb.types\n\npokedex_order_type = agb.types.FixedSizeArrayType(\n 'u16',\n lambda project, context: len(project.constants['species']) - 1\n)\n\npokedex_entry_string_type = agb.types.StringType(box_size=(35, 255))\n\npokdex_entry_string_pointer_type = agb.types.PointerType(\n 'pokedex.entry_string',\n lambda project, context, parents: (f'pokedex_entry_{context[-2]}', 0, False)\n)\n\npokedex_genus_string_type = agb.types.StringType(fixed_size=12)\n\npokdex_entry_type = agb.types.Structure([\n ('genus', 'pokedex.genus_string', 0),\n ('height', 'u16', 0),\n ('weight', 'u16', 0),\n ('entry_string_0', 'pokedex.entry_string_pointer', 0),\n ('entry_string_1', 'pokedex.entry_string_pointer', 0),\n ('field_14', 'u16', 0),\n ('pokemon_scale', 'u16', 0),\n ('pokemon_displace', 'u16', 0),\n ('trainer_scale', 'u16', 0),\n ('trainer_displace', 'u16', 0),\n ('field_1E', 'u16', 0)\n])\n\npokedex_entries_type = agb.types.FixedSizeArrayType(\n 'pokedex.entry',\n lambda project, context: 386 + 1\n)\n\nmodels_to_export = {\n 'pokedex_order' : pokedex_order_type,\n 'pokedex.entry_string' : pokedex_entry_string_type,\n 'pokedex.entry_string_pointer' : pokdex_entry_string_pointer_type,\n 'pokedex.genus_string' : pokedex_genus_string_type,\n 'pokedex.entry' : pokdex_entry_type,\n 'pokedex_entries' : pokedex_entries_type,\n}","repo_name":"dfuchsgruber/Violet","sub_path":"Violet/models/pokedex.py","file_name":"pokedex.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"52"}
+{"seq_id":"38507413071","text":"import argparse\nimport datetime\nimport os\nimport shutil\nimport tempfile\n\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport toolz as t\n\nfrom .. import io as rio\nfrom .. import utils as rutils\nfrom ..io import DEFAULT_CHANNELS\n\nTFRECORD_COMPRESSION = tf.python_io.TFRecordCompressionType.GZIP\nTFRECORD_OPTIONS = tf.python_io.TFRecordOptions(TFRECORD_COMPRESSION)\nVALID_DATASETS = {'train', 'test'}\nVALID_STRATEGIES = {'random', 'by_exp_plate_site'}\n\n### TensorFlow Helpers\n\n\ndef bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef string_feature(value):\n return bytes_feature(value.encode('utf-8'))\n\n\ndef int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(\n value=rutils.wrap(value)))\n\n\ndef float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(\n value=ruitls.wrap(value)))\n\n\n### Conversion to TFExample and TFRecord logic\n\n\ndef dict_to_tfexample(site):\n \"\"\"\n Takes a dictionary of a site with all the metadata and the `image` data.\n\n Returns a TFExample\n \"\"\"\n\n features = {\n 'image': bytes_feature(site['image'].tostring()),\n 'well': string_feature(site['well']),\n 'well_type': string_feature(site['well_type']),\n 'experiment': string_feature(site['experiment']),\n 'plate': int64_feature(site['plate']),\n 'site': int64_feature(site['site']),\n 'cell_type': string_feature(site['cell_type'])\n }\n\n # Handle case where sirna is not known (test)\n if site[\"sirna\"] is not None:\n features[\"sirna\"] = int64_feature(site[\"sirna\"])\n\n return tf.train.Example(features=tf.train.Features(feature=features))\n\n\ndef _pack_tfrecord(base_path,\n sites,\n dest_path,\n channels=DEFAULT_CHANNELS):\n if not dest_path.startswith('gs://'):\n os.makedirs(os.path.dirname(dest_path), exist_ok=True)\n with tf.python_io.TFRecordWriter(\n dest_path, options=TFRECORD_OPTIONS) as writer:\n for site in sites:\n data = rio.load_site(\n base_path=base_path,\n channels=channels,\n **rutils.select_keys(site, ('dataset', 'experiment', 'plate',\n 'well', 'site')))\n example = dict_to_tfexample(t.assoc(site, 'image', data))\n writer.write(example.SerializeToString())\n\n\n### Strategies to pack the TFRecords differently and some helper functions\n#\n# Each strategy takes the metadata DataFrame and returns a list of\n# dictionaries containing `dest_path` and `sites` where\n# `dest_path` - the full path of the destination TFRecord file\n# `sites` - a list of all of the sites that should be packed into the\n# destination path. Each `site` is a row, in dictionary form,\n# from the metadata dataframe.\n#\n\n\ndef _dataset_rs_dict(seed):\n \"\"\"Returns a dictionary of random states keyed by dataset.\n A seed for every dataset is created regardless of if it will be\n processed. This is done to guarantee determinism of the\n randomization invariant of what datasets are being processed.\n \"\"\"\n rs = np.random.RandomState(seed)\n high = 2**32 - 1\n return {\n ds: np.random.RandomState(rs.randint(high))\n for ds in sorted(VALID_DATASETS)\n }\n\n\ndef _correct_sirna_dtype(row):\n if np.isnan(row['sirna']):\n row['sirna'] = None\n else:\n row['sirna'] = int(row['sirna'])\n return row\n\n\ndef _random_partition(metadata_df,\n dest_path,\n sites_per_tfrecord=308,\n random_seed=42):\n \"\"\"\n Randomly partitions each dataset into multiple TFRecords.\n \"\"\"\n # make groupby's determinisic\n metadata_df = metadata_df.sort_values(\n ['dataset', 'experiment', 'plate', 'well', 'site'])\n # get random states to make randomizations determinisic\n rs_dict = _dataset_rs_dict(random_seed)\n\n to_pack = []\n for dataset, df in metadata_df.groupby('dataset'):\n df = (df.sort_values(['experiment', 'plate', 'well', 'site'])\n .sample(frac=1.0, random_state=rs_dict[dataset]))\n rows = [_correct_sirna_dtype(row) for row in df.to_dict(orient='row')]\n sites_for_files = t.partition_all(sites_per_tfrecord, rows)\n dataset_path = os.path.join(dest_path, 'random-{}'.format(random_seed), dataset)\n for file_num, sites in enumerate(sites_for_files, 1):\n dest_file = os.path.join(dataset_path, \"{:03d}.tfrecord\".format(file_num))\n to_pack.append({'dest_path': dest_file, 'sites': sites})\n return to_pack\n\n\ndef _by_exp_plate_site(metadata_df, dest_path, random_seed=42):\n \"\"\"\n Groups by experiment, plate, and packs each site into individual TFRecords.\n \"\"\"\n # make groupby's determinisic\n metadata_df = metadata_df.sort_values(\n ['dataset', 'experiment', 'plate', 'well', 'site'])\n # get random states to make randomizations determinisic\n rs_dict = _dataset_rs_dict(random_seed)\n\n to_pack = []\n for (dataset, exp, plate, site), df in metadata_df.groupby(\n ['dataset', 'experiment', 'plate', 'site']):\n df = (df.sort_values(['experiment', 'plate', 'well', 'site'])\n .sample(frac=1.0, random_state=rs_dict[dataset]))\n rows = [_correct_sirna_dtype(row) for row in df.to_dict(orient='row')]\n\n dest_file = os.path.join(dest_path, 'by_exp_plate_site-{}'.format(random_seed),\n \"{}_p{}_s{}.tfrecord\".format(exp, plate, site))\n to_pack.append({'dest_path': dest_file, 'sites': rows})\n return to_pack\n\n\ndef _sites_df(i, ix):\n return pd.DataFrame([i] * len(ix), index=ix, columns=['site'])\n\n\n### Main entry point and CLI logic\n\n\ndef pack_tfrecords(images_path,\n metadata_df,\n num_workers,\n dest_path,\n strategies=['random', 'by_exp_plate_site'],\n channels=DEFAULT_CHANNELS,\n sites_per_tfrecord=308,\n random_seeds=[42],\n runner='dask',\n project=None,\n datasets=None):\n if datasets is None:\n datasets = [\n ds.strip('/') for ds in tf.gfile.ListDirectory(images_path)\n if ds.strip('/') in VALID_DATASETS\n ]\n\n # Only consider metadata for the datasets we care about\n metadata_df = metadata_df[metadata_df.dataset.isin(datasets)]\n # only pack images for the treatment wells, not the controls!\n metadata_df = metadata_df[metadata_df.well_type == \"treatment\"]\n\n strategies = set(strategies)\n\n if len(strategies - VALID_STRATEGIES) > 0:\n raise ValueError(\n 'invalid strategies: {}. You may only provide a subset of {}'.format(strategies, VALID_STRATEGIES)\n )\n\n to_pack = []\n for random_seed in random_seeds:\n if 'random' in strategies:\n to_pack += _random_partition(\n metadata_df,\n dest_path,\n random_seed=random_seed,\n sites_per_tfrecord=sites_per_tfrecord)\n\n if 'by_exp_plate_site' in strategies:\n to_pack += _by_exp_plate_site(\n metadata_df, dest_path, random_seed=random_seed)\n\n if runner == 'dask':\n import dask\n import dask.bag\n\n print('Distributing {} on dask'.format(len(to_pack)))\n to_pack_bag = dask.bag.from_sequence(to_pack, npartitions=len(to_pack))\n (to_pack_bag\n .map(lambda kw: _pack_tfrecord(base_path=images_path,\n channels=channels,\n **kw))\n .compute(num_workers=num_workers))\n return [p['dest_path'] for p in to_pack]\n else:\n print('Distributing {} on {}'.format(len(to_pack), runner))\n run_on_dataflow(to_pack, dest_path, images_path, channels, runner, project)\n return None\n\n\ndef run_on_dataflow(to_pack, dest_path, images_path, channels, runner, project):\n\n import apache_beam as beam\n\n options = {\n 'staging_location':\n os.path.join(dest_path, 'tmp', 'staging'),\n 'temp_location':\n os.path.join(dest_path, 'tmp'),\n 'job_name': ('rxrx1-' + os.getlogin().replace('.', '-') + '-' +\n datetime.datetime.now().strftime('%y%m%d-%H%M%S')),\n 'max_num_workers':\n 600, # CHANGE AS NEEDED\n 'machine_type':\n 'n1-standard-4',\n 'save_main_session':\n True,\n 'setup_file': (os.path.join(\n os.path.dirname(os.path.abspath(__file__)), '../../setup.py')),\n 'runner':\n runner,\n 'project':\n project\n }\n opts = beam.pipeline.PipelineOptions(flags=[], **options)\n with beam.Pipeline(runner, options=opts) as p:\n (p\n | 'find_images' >> beam.Create(to_pack)\n | 'pack' >> beam.FlatMap(\n lambda kw: _pack_tfrecord(base_path=images_path,\n channels=channels,\n **kw))\n )\n if runner == 'dataflow':\n print(\n 'Submitting job ... Please monitor at https://console.cloud.google.com/dataflow'\n )\n\n\ndef cli():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawTextHelpFormatter,\n description=\"Packs the raw PNG images into TFRecords.\")\n parser.add_argument(\"--raw-images\", type=str, help=\"Path of the raw images\",\n default=rio.DEFAULT_IMAGES_BASE_PATH)\n parser.add_argument(\n \"--metadata\", type=str, help=\"Path to the metadata directory\",\n default=rio.DEFAULT_METADATA_BASE_PATH)\n parser.add_argument(\n \"--num-workers\",\n type=int,\n default=None,\n help=\"Number of workers to be writing TFRecords. Defaults to number of cores.\"\n )\n parser.add_argument(\n \"--random-seeds\",\n type=int,\n nargs='+',\n default=[42],\n help=\"The seed used to make the sorting determistic. Embedded in the dir name to allow multiple folds to be created.\"\n )\n parser.add_argument(\n \"--sites-per-tfrecord\",\n type=int,\n default=1500,\n help=\"Only used with the random strategy, indicates how many site images you want in a single TFRecord\"\n )\n parser.add_argument(\n \"--strategies\",\n nargs='+',\n choices=VALID_STRATEGIES,\n default=['random', 'by_exp_plate_site'],\n help=\"\"\"What strategies to use to pack up the records:\n\\t`random` - Randomly partitions each dataset into multiple TFRecords.\n\\t`by_exp_plate_site` - Groups by experiment, plate, and packs each site into individual TFRecords.\n \"\"\")\n parser.add_argument(\n \"--dest-path\",\n type=str,\n default=\"./tfrecords\",\n help=\"Destination directory of where to write the tfrecords\")\n parser.add_argument(\n \"--runner\",\n type=str,\n default=\"dask\",\n choices={'dask', 'dataflow'},\n help=\"Specify one of DirectRunner, dataflow, or dask\")\n parser.add_argument(\n \"--project\",\n type=str,\n default=None,\n help=\"If using dataflow, the project to bill\")\n args = parser.parse_args()\n if args.runner == 'dataflow':\n if not args.project:\n raise ValueError('When using dataflow, you need to specify project')\n\n metadata_df = rio.combine_metadata(args.metadata)\n if args.runner == 'dask':\n from dask.diagnostics import ProgressBar\n ProgressBar().register()\n\n pack_tfrecords(\n images_path=args.raw_images,\n metadata_df=metadata_df,\n dest_path=args.dest_path,\n strategies=args.strategies,\n sites_per_tfrecord=args.sites_per_tfrecord,\n random_seeds=args.random_seeds,\n num_workers=args.num_workers,\n runner=args.runner,\n project=args.project)\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"recursionpharma/rxrx1-utils","sub_path":"rxrx/preprocess/images2tfrecords.py","file_name":"images2tfrecords.py","file_ext":"py","file_size_in_byte":12094,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"52"}
+{"seq_id":"18538556015","text":"# 입력 예시\n# https://lagooni.tistory.com/entry/Python-%EB%B0%B1%EC%A4%80-%ED%8A%B8%EB%A6%AC-%EC%88%9C%ED%9A%8C-%EC%A0%84%EC%9C%84-%EC%88%9C%ED%9A%8C-%EC%A4%91%EC%9C%84-%EC%88%9C%ED%9A%8C-%ED%9B%84%EC%9C%84-%EC%88%9C%ED%9A%8C\nclass Node:\n def __init__(self, data, left_node, right_node):\n self.data = data\n self.left_node = left_node\n self.right_node = right_node\n\n\n# 전위 순회: 현재 노드 -> 왼쪽 서브트리 -> 오른쪽 서브트리\ndef preorder(node):\n print(node.data, end=\" \")\n if node.left_node is not None:\n preorder(tree[node.left_node])\n if node.right_node is not None:\n preorder(tree[node.right_node])\n\n\n# 중위 순회: 왼쪽 서브트리 -> 현재 노드 -> 오른쪽 서브트리\ndef inorder(node):\n if node.left_node is not None:\n inorder(tree[node.left_node])\n print(node.data, end=\" \")\n if node.right_node is not None:\n inorder(tree[node.right_node])\n\n\n# 후위 순회: 왼쪽 서브트리 -> 오른쪽 서브트리 -> 현재 노드\ndef postorder(node):\n if node.left_node is not None:\n postorder(tree[node.left_node])\n if node.right_node is not None:\n postorder(tree[node.right_node])\n print(node.data, end=\" \")\n\n\nn = int(input())\ntree = {}\n# tree의 인덱스는 KEY로, 저장되�� 값은 VALUE로 dictionary에 저장\n# {\"A\" : (\"B\",\"C\")}\n# 👉 의미 : A가 부모인 노드가 B, C / A의 자식이 B, C\nfor i in range(n):\n data, left_node, right_node = input().split()\n if left_node == '.':\n left_node = None\n if right_node == '.':\n right_node = None\n tree[data] = Node(data, left_node, right_node)\n\npreorder(tree['A'])\nprint()\ninorder(tree['A'])\nprint()\npostorder(tree['A'])\n","repo_name":"kkm0406/AlgorithmBOJ","sub_path":"트리/Tree Traversal.py","file_name":"Tree Traversal.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"22672889473","text":"import random\n\nclass NumberGuessingGame:\n def __init__(self):\n self.secret_number = random.randint(1, 100)\n self.attempts = 0\n self.max_attempts = 10\n\n def get_user_guess(self):\n while True:\n try:\n guess = int(input(\"Enter your guess (1-100): \"))\n if 1 <= guess <= 100:\n return guess\n else:\n print(\"Please enter a number between 1 and 100.\")\n except ValueError:\n print(\"Please enter a valid number.\")\n\n def play(self):\n print(\"Welcome to the Number Guessing Game!\")\n print(\"Try to guess the secret number between 1 and 100.\")\n\n while self.attempts < self.max_attempts:\n guess = self.get_user_guess()\n self.attempts += 1\n\n if guess < self.secret_number:\n print(\"Too low! Try again.\")\n elif guess > self.secret_number:\n print(\"Too high! Try again.\")\n else:\n print(f\"Congratulations! You guessed the number {self.secret_number} in {self.attempts} attempts.\")\n break\n\n if self.attempts == self.max_attempts:\n print(f\"Sorry, you've run out of attempts. The secret number was {self.secret_number}.\")\n\nif __name__ == \"__main__\":\n game = NumberGuessingGame()\n game.play()\n","repo_name":"ljonesdesign/python-games","sub_path":"guess_number.py","file_name":"guess_number.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"43845804239","text":"from time import sleep\r\nsaldo = 1500\r\nlimite_diario = 500\r\nextrato = ''\r\nsaques_diarios = 0\r\nmenu = '''Qual operação deseja fazer?\r\n\r\n1 - Depósito\r\n2 - Saque\r\n3 - Extrato\r\n9 - Sair\r\n'''\r\n\r\nwhile True:\r\n print(menu)\r\n opção = int(input('Digite uma operação: '))\r\n if opção == 1:\r\n valor = float(input('\\nInforme o valor que deseja depositar: R$'))\r\n if valor > 0:\r\n saldo += valor\r\n extrato += f'Depósito: R${valor:.2f}\\n'\r\n sleep(1)\r\n print(f'\\nDepósito realizado com sucesso.\\n')\r\n else:\r\n print('\\nOperação inválida. Informe um valor MAIOR que zero.\\n')\r\n elif opção == 2:\r\n if saques_diarios >= 3:\r\n print('\\nFALHOU... Você já usou os 3 saques que tem direito no dia.\\n')\r\n else:\r\n valor = float(input('\\nInforme o valor que deseja sacar: R$'))\r\n if valor > saldo:\r\n print('\\nFALHOU... Saldo insuficiente.\\n')\r\n elif valor > limite_diario:\r\n print('\\nFALHOU... O valor que deseja sacar excede o limite de R$500.\\n')\r\n elif valor <= 500 and saques_diarios <= 3:\r\n sleep(1)\r\n print('\\nCONTANDO...')\r\n sleep(1)\r\n print('\\nSaque realizado com sucesso.\\n')\r\n sleep(1)\r\n saldo -= valor\r\n saques_diarios += 1\r\n extrato += f'Saque: R${valor:.2f}\\n'\r\n elif opção == 3:\r\n print('\\nIMPRIMINDO...')\r\n sleep(2)\r\n print('\\n************ EXTRATO BANCÁRIO ************')\r\n print('Não houve nenhuma movimentação até o momento' if not extrato else extrato)\r\n print(f'\\nSaldo: R${saldo:.2f}\\n')\r\n elif opção == 9:\r\n print('VOLTE SEMPRE!!!')\r\n break\r\n else:\r\n print('\\nOperação inválida... Selecione uma das opções abaixo.\\n')\r\n\r\n","repo_name":"Virardi78/Desafio_Banco","sub_path":"sistema_bancario.py","file_name":"sistema_bancario.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"19784308376","text":"import tkinter\nimport tkinter.filedialog as fd\nfrom sys import argv, exit\nimport os\nfrom platform import system\nfrom math import floor\nfrom time import sleep\n\ncolorWheel = []\ncolorWheel2 = []\n\n# Logging functions\ndef log(n):\n print(\"[#]\", n)\ndef warn(n):\n print(\"[!]\", n)\ndef die(n):\n print(\"[XX]\", n)\n sleep(5)\n exit(1)\n\n\n# define config file path\nif system() == \"Windows\":\n configPath = \"C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\skeditConf.txt\"\nelse: # Assuming other operating systems are UNIX-like\n configPath = \"/usr/share/skeditFiles/skeditConf.txt\"\n\n# Checks if the config file exists\ntry:\n configFile = open(configPath)\nexcept FileNotFoundError:\n die(\"skedit configuration missing.\")\n\nconfig = configFile.readlines()\nconfigFile.close()\n\n# get info from config file\ntry:\n fontSize = config[config.index(\"fontSize:\\n\") + 1] \nexcept:\n fontSize = 15\ntry:\n defSize = config[config.index(\"defaultSize:\\n\") + 1]\n defSize = defSize[:-1]\nexcept:\n defSize = \"500x500\"\ntry:\n useDefSize = config[config.index(\"applyDefaultSizeAtStartup:\\n\") + 1]\nexcept:\n useDefSize = \"true\"\ntry:\n # get resources preference from config file\n ignoreRes = config[config.index(\"ignoreResources:\\n\") + 1]\nexcept:\n ignoreRes = \"false\"\nif ignoreRes != \"true\":\n # windows users - this reads the skedit resources file.\n # the formatting for this file mimics the formatting of a *nix .Xresources file.\n if system() == \"Windows\":\n try:\n Xresources = open(\"C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\skeditResources.txt\")\n colors = Xresources.readlines()\n Xresources.close()\n except FileNotFoundError:\n pass\n # linux users - this reads .Xresources file from your $HOME directory.\n # this means your colors will restore to default if you run skedit as root.\n # to fix this, copy your .Xresources to /root/\n else:\n home = os.environ[\"HOME\"]\n # or, change 'home+\"/.Xresources\"' to '\"yourusername/.Xresources\"' in the follwing line\n try:\n Xresources = open(home+\"/.Xresources\")\n colors = Xresources.readlines()\n Xresources.close()\n except FileNotFoundError:\n pass\n try:\n for i in range(16):\n colorWheel.append([x for x in colors if (\"*.color\" + str(i) + \":\") in x])\n # the worst line of code ever written\n colorWheel2.append((str(colorWheel[i]).replace(\"*.color\" + str(i) + \":\", \"\")).replace(\" \", \"\").replace(\"\\\\n\", \"\").replace(\"['\", \"\").replace(\"']\", \"\"))\n foreground = str([a for a in colors if (\"*.foreground:\") in a]).replace(\" \", \"\")\n foreground = foreground.replace(\"['*.foreground:\", \"\").replace(\"\\\\n']\", \"\")\n background = str([a for a in colors if (\"*.background:\") in a]).replace(\" \", \"\")\n background = background.replace(\"['*.background:\", \"\").replace(\"\\\\n']\", \"\")\n cursor = str([a for a in colors if (\"*.cursorColor:\") in a])\n cursor = cursor.replace(\"['*.cursorColor:\", \"\").replace(\"\\\\n']\", \"\").replace(\" \", \"\")\n except:\n background = '#1c1c1c'\n foreground='#d6d6d6'\n cursor='#d6d6d6'\n pass\nelse:\n print(\"ignoring resources file\")\n\nfilename = \"scratch document\"\n\n# main functions for using editor\n\ndef get_text():\n t = text.get(0.0, tkinter.END).rstrip()\n return t\n\ndef newFile(self):\n global filename\n filename = \"scratch document\"\n text.delete(0.0, tkinter.END)\n root.title(filename+\" - skedit\")\n\ndef save(self):\n global t\n t = get_text()\n with open(filename, 'w') as f:\n f.write(t)\n\ndef saveAs(self):\n global filename\n fn = fd.asksaveasfilename(initialdir=\"~\", title=\"save as\", defaultextension='.txt')\n with open(fn, 'w') as f:\n root.title(fn+\" - skedit\")\n t = get_text()\n try:\n f.write(t)\n except:\n warn(\"unable to save file.\")\n else:\n filename = fn\n\ndef openFile(self):\n global filename\n fn = fd.askopenfilename(title=\"open file\")\n \n try:\n t = open(fn, 'r').read()\n except:\n return\n else:\n filename = fn\n root.title(filename+\" - skedit\")\n text.delete(0.0, tkinter.END)\n text.insert(0.0, t)\n\ndef gotoTop(self):\n text.mark_set(\"insert\", \"%d.%d\" % (0, 0))\n\ndef removeLine(self):\n curLine = float(floor(float(text.index(tkinter.INSERT))))\n text.delete(curLine, curLine+1)\n\ndef helpMenu(self):\n global t\n if root.title() != \"scratch document\":\n save(None)\n t = get_text()\n root.title(\"help - skedit\")\n text.delete(0.0, tkinter.END)\n helpText = \"\"\"Welcome to skedit, the cross-platform, dark-mode by default, simple text editor.\n\nskedit is built with python, and tkinter. source code is available at https://github.com/smhsketch/skedit.\n\nbindings:\n ctrl-o: open a new file\n ctrl-s: save current file\n ctrl-d: save current buffer as\n ctrl-n: new blank buffer\n ctrl-t: go to top of buffer\n ctrl-r: remove current line of buffer\n ctrl-e: exit this help menu and return to your document\"\"\"\n text.insert(0.0, helpText)\n\ndef exitHelp(self):\n if root.title() == \"help - skedit\":\n text.delete(0.0, tkinter.END)\n text.insert(0.0, t)\n root.title(filename+\" - skedit\")\n\n#Tk\nroot = tkinter.Tk()\nroot.title(\"scratch document - skedit\")\n\n#bindings\nroot.bind('', save)\nroot.bind('', newFile)\nroot.bind('', saveAs)\nroot.bind('', openFile)\nroot.bind('', gotoTop)\nroot.bind('', removeLine)\nroot.bind('', helpMenu)\nroot.bind('', exitHelp)\n\ntext = tkinter.Text(root)\nroot.update()\ntext.configure(background=background, fg=foreground, insertbackground=cursor, height=root.winfo_height(), width=root.winfo_width(), bd=0, font=(\"monospace\", fontSize))\nif useDefSize == \"true\\n\":\n root.geometry(defSize)\nroot.maxsize(1500, 1000)\nroot.update()\ntext.focus_set()\n\ntext.pack()\ntry:\n if system() == \"Windows\":\n root.iconphoto(False, tkinter.PhotoImage(file='C:\\\\Program Files\\\\skedit\\\\skeditFiles\\\\icon.png'))\n else:\n root.iconphoto(False, tkinter.PhotoImage(file='/usr/share/skeditFiles/icon.png'))\nexcept:\n pass\n\nroot.mainloop()","repo_name":"smhsketch/skedit","sub_path":"skeditFiles/skedit.py","file_name":"skedit.py","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"5080152455","text":"import pandas as pd\nimport numpy as np\nimport os\nimport glob\nimport sys\nfrom tqdm import tqdm\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom tensorflow.keras.models import Sequential,Model ,load_model\nfrom tensorflow.keras.layers import Dense, LSTM, Dropout,Lambda,MaxPooling2D, Conv2D, Flatten, Reshape, Conv1D, MaxPooling1D, Input,LeakyReLU\nfrom sklearn.metrics import mean_squared_error,r2_score\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\nfrom tensorflow.keras.losses import Huber\nfrom tensorflow.keras.optimizers import Adam\n\ndef preprocess_data (data, is_train=True) :\n temp = data.copy()\n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n if is_train == True : \n temp['Target1'] = temp['TARGET'].shift(-48).fillna(method='ffill') # 다음날 TARGET을 붙인다.\n temp['Target2'] = temp['TARGET'].shift(-48*2).fillna(method='ffill') # 다다음날 TARGET을 붙인다.\n temp = temp.dropna() # 결측값 제거\n return temp.iloc[:-96] # 이틀치 데이터만 빼고 전체\n elif is_train == False : \n # Day, Minute 컬럼 제거\n temp = temp[['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T']]\n return temp.iloc[-48:, :] # 마지막 하루치 데이터\n\ndef split_xy(dataset, time_steps, y_column):\n x, y = list(), list()\n for i in range(len(dataset)):\n x_end_number = i + time_steps\n y_end_number = x_end_number + y_column\n\n if y_end_number > len(dataset):\n break\n tmp_x = dataset[i:x_end_number]\n tmp_y = dataset[x_end_number:y_end_number,:,-2:] \n x.append(tmp_x)\n y.append(tmp_y)\n return np.array(x), np.array(y)\n\n\n'''\ndef split_xy(dataset, time_steps, y_column):\n x, y1,y2 = list(), list(),list()\n for i in range(len(dataset)):\n x_end_number = i + time_steps\n y_end_number = x_end_number + y_column\n\n if y_end_number > len(dataset):\n break\n tmp_x = dataset[i:x_end_number]\n tmp_y1 = dataset[x_end_number:y_end_number,:,-2] \n tmp_y2 = dataset[x_end_number:y_end_number,:,-1] \n x.append(tmp_x)\n y1.append(tmp_y1)\n y2.append(tmp_y2)\n\n return np.array(x), np.array(y1) ,np.array(y2) \n'''\ndef tilted_loss(q,y,f):\n e = (y-f)\n return K.mean(K.maximum(q*e, (q-1)*e), axis=-1)\n\n#data 준비\ntrain_df = pd.read_csv('C:/data/csv/solar/train/train.csv')\nprint(train_df .shape) #(52560, 9)\nprint(train_df .tail())\nsample = pd.read_csv('C:/data/csv/solar/sample_submission.csv')\n\ntrain_data = preprocess_data(train_df)\nprint(train_data.columns)\n#Index(['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T', 'Target1', 'Target2'], dtype='object')\n\ntrain = train_data.to_numpy()\nprint(train.shape) #(52464, 9)\n\ntrain = train.reshape(-1,48,9)\nprint(train.shape) #(1093, 48, 9)\n\ntime_steps =7\ny_column = 2 \nx,y = split_xy(train,time_steps,y_column)\n# x,y1,y2 = split_xy(train,time_steps,y_column)\n\nx= x[:,:,:,3:]\n#y1 = y1\n#y2 = y2\nprint(x.shape) #(1085, 7, 48, 6)\n#print(y1.shape) #(1085, 2, 48)\n#print(y2.shape) #(1085, 2, 48)\n\ny = y.reshape(-1,96)\n#y1 = y1.reshape(-1,96)\n#y2 = y2.reshape(-1,96)\n\nquantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\ndef Conv2dmodel():\n drop = 0.2\n input1 = Input(shape=(7,48,6))\n dense1 = Conv2D(256, 2, padding='same')(input1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Conv2D(128, 2, padding='same')(dense1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Conv2D(64, 2, padding='same')(dense1)\n dense1=(LeakyReLU(alpha = 0.05))(dense1)\n dense1 = Flatten()(dense1)\n dense1 = Dense(128)(dense1)\n dense1 = Dense(96)(dense1)\n outputs = Dense(96)(dense1)\n\n model = Model(inputs=input1, outputs=outputs)\n\n return model\n\n# model 학습 \n# for i in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:\n\n# print(\"##### {} model fit start! #####\".format(i))\n\n# q = i\n \n# model = Conv2dmodel()\n# early_stopping = EarlyStopping(monitor = 'val_loss', patience = 30, mode = 'min')\n# cp = ModelCheckpoint('C:/data/modelcheckpoint/solar_0120model1_{}.h5'.format(i), monitor='val_loss', mode='auto', save_best_only=True)\n# lr = ReduceLROnPlateau(monitor='val_loss', patience=10, factor=0.5, verbose=1)\n\n# model.compile(loss=lambda y,f: tilted_loss(q,y,f), optimizer='adam')\n# model.fit(x, y, epochs=1, batch_size=128, validation_split=0.2, callbacks=[early_stopping, cp,lr], verbose=1)\n\n\n#x_test = pd.concat(test_data)\n#print(x_test.shape) #(3888, 7) # 81day 48 hour 8 columns\n#print(x_test.columns) #Index(['Hour', 'TARGET', 'DHI', 'DNI', 'WS', 'RH', 'T'], dtype='object')\n# 모델 trainning\n\"\"\"\nfor q in ([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]):\n print(\"##### {} model fit start! #####\".format(q))\n model = Conv2dmodel()\n early_stopping = EarlyStopping(monitor = 'val_loss', patience = 30, mode = 'min')\n cp = ModelCheckpoint('C:/data/modelcheckpoint/solar_0120model2_{}.h5'.format(q), monitor='val_loss', mode='auto', save_best_only=True)\n lr = ReduceLROnPlateau(monitor='val_loss', patience=10, factor=0.5, verbose=1)\n\n model.compile(loss=lambda y,f: tilted_loss(q,y,f), optimizer='adam')\n model.fit(x, y, epochs=100, batch_size=128, validation_split=0.2, callbacks=[early_stopping, cp,lr], verbose=1)\n # model_1_path = 'C:/data/modelcheckpoint/solar_0120model1_{}.h5'.format(q)\n # #print(model_1_path.shape)\n # print(model_1_path) \n \n test_data = []\n for i in range(81):\n file_path = pd.read_csv('C:/data/csv/solar/test/%d.csv'%i) \n file_path.drop(['Hour','Minute','Day'], axis =1, inplace = True)\n test = file_path.to_numpy() \n test = test.reshape(1,7,48,6)\n y_pred = model.predict(test)\n #print(y_pred.shape)\n y_pred = y_pred.reshape(2,48)\n print(y_pred.shape)\n a = []\n for j in range(2):\n b = []\n for k in range(48):\n b.append(y_pred[j,k])\n a.append(b)\n test_data.append(a)\n test_data = np.array(test_data)\n test_data = test_data.reshape(81*2*48,)\n sample.loc[:, \"q_%d\"%q] = test_data\n test_data = pd.DataFrame(test_data)\n test_data.to_csv('C:/data/csv/predict1/0121predict3_{}.csv'.format(q))\n\n#sample= sample.iloc[:,:-1]\n#sample.to_csv('C:/data/csv/solar/sample_submission5.csv', index=False)\n # model_1 = load_model(model_1_path, compile=False)\n # predict_1 = model_1.predict(test)\n # print(predict_1.shape)\n # predict_1 = predict_1.reshape(-1, 1)\n # print(predict_1.shape)\n # predict_1 = pd.DataFrame(predict_1)\n # predict_1.to_csv('C:/data/csv/predict1/0120predict1_{}.csv'.format(i))\n\n\n# print(predict_1)\n# print(predict_1.shape) #(96, 1)\n\npred1 = np.zeros((81*48*2,9))\nfor i , num in enumerate([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]):\n temp = pd.read_csv('C:/data/csv/predict1/0121predict3_'+str(num)+'.csv',index_col=None, header=0)\n #temp = pd.read_csv(file_path)\n temp.drop('Unnamed: 0', axis=1)\n temp = np.array(temp)\n print(temp.shape)\n temp = temp[:,0]\n print(temp.shape)\n #print(temp.tail())\n #temp = temp.reshape(-1)\n print(temp.shape) #(15552,)\n pred1[:,i] = temp\npred1 = pd.DataFrame(pred1)\nprint(pred1.shape)\nprint(pred1)\n\"\"\"\nresult = pd.read_csv('C:/data/csv/predict1/result3.csv')\nsample.iloc[1:, 1:] = result.to_numpy()\n# #sample to numpy\n# submission = pd.concat([pred1])\n# submission[submission.values<0] = 0\n# sample.iloc[:, 1:] = submission.to_numpy()\nsample.to_csv('C:/data/csv/solar/sample/sample_submission3.csv',header=True, index=False)\n\n\n","repo_name":"jsja22/study","sub_path":".vscode/solar_system/solar_0120_1.py","file_name":"solar_0120_1.py","file_ext":"py","file_size_in_byte":7805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"}
+{"seq_id":"23373588825","text":"# 배열 원소의 최대값을 구해서 출력하기(원소값을 입력받음)\n\nfrom max import max_of\n\nprint('배열의 최대값을 구합니다.')\nprint('주의: \"end\"를 입력하면 종료합니다.')\n\nnumber = 0\nx = [] # 빈 리스트\n\nwhile True:\n s = input(f'x[{number}]값을 입력하세요: ')\n if s == 'end':\n break\n x.append(int(s)) # 배열의 맨 끝에 추가\n number += 1\n\nprint(f'{number}개를 입력했습니다.')\nprint(f'최대값은 {max_of(x)}입니다.')\n","repo_name":"anifilm/study","sub_path":"learn_data_structures/doit_algorithm_py/chap02/section2/max_of_test_input.py","file_name":"max_of_test_input.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"}
+{"seq_id":"18316512571","text":"f=open(\"cali.cal\",\"r\")\n\nv_prev=-1\ni=0\nfor l in f:\n v=float(l)\n if v